Skip to content

Commit 7eef019

Browse files
authored
Merge pull request #73813 from ktoso/pick-concurrency-isCurrent-more-fixes
2 parents 67e9df0 + 347864b commit 7eef019

16 files changed

+456
-116
lines changed

stdlib/public/Concurrency/Actor.cpp

Lines changed: 106 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ bool _task_serialExecutor_isSameExclusiveExecutionContext(
323323
enum IsCurrentExecutorCheckMode: unsigned {
324324
/// The default mode when an app was compiled against "new" enough SDK.
325325
/// It allows crashing in isCurrentExecutor, and calls into `checkIsolated`.
326-
Default_UseCheckIsolated_AllowCrash,
326+
Swift6_UseCheckIsolated_AllowCrash,
327327
/// Legacy mode; Primarily to support old applications which used data race
328328
/// detector with "warning" mode, which is no longer supported. When such app
329329
/// is re-compiled against a new SDK, it will see crashes in what was
@@ -332,39 +332,45 @@ enum IsCurrentExecutorCheckMode: unsigned {
332332
Legacy_NoCheckIsolated_NonCrashing,
333333
};
334334
static IsCurrentExecutorCheckMode isCurrentExecutorMode =
335-
Default_UseCheckIsolated_AllowCrash;
336-
335+
Swift6_UseCheckIsolated_AllowCrash;
337336

338337
// Shimming call to Swift runtime because Swift Embedded does not have
339-
// these symbols defined
340-
bool swift_bincompat_useLegacyNonCrashingExecutorChecks() {
338+
// these symbols defined.
339+
bool __swift_bincompat_useLegacyNonCrashingExecutorChecks() {
341340
#if !SWIFT_CONCURRENCY_EMBEDDED
342-
swift::runtime::bincompat::
341+
return swift::runtime::bincompat::
343342
swift_bincompat_useLegacyNonCrashingExecutorChecks();
344-
#endif
343+
#else
345344
return false;
345+
#endif
346346
}
347347

348-
// Check override of executor checking mode.
349-
static void checkIsCurrentExecutorMode(void *context) {
350-
auto useLegacyMode =
351-
swift_bincompat_useLegacyNonCrashingExecutorChecks();
348+
// Done this way because of the interaction with the initial value of
349+
// 'unexpectedExecutorLogLevel'
350+
bool swift_bincompat_useLegacyNonCrashingExecutorChecks() {
351+
bool legacyMode = __swift_bincompat_useLegacyNonCrashingExecutorChecks();
352352

353353
// Potentially, override the platform detected mode, primarily used in tests.
354354
#if SWIFT_STDLIB_HAS_ENVIRON
355-
if (const char *modeStr =
356-
runtime::environment::concurrencyIsCurrentExecutorLegacyModeOverride()) {
357-
if (modeStr) {
358-
if (strcmp(modeStr, "nocrash") == 0) {
359-
useLegacyMode = true;
360-
} else if (strcmp(modeStr, "crash") == 0) {
361-
useLegacyMode = false;
362-
} // else, just use the platform detected mode
363-
}
364-
}
355+
if (const char *modeStr = runtime::environment::
356+
concurrencyIsCurrentExecutorLegacyModeOverride()) {
357+
if (strcmp(modeStr, "nocrash") == 0 || strcmp(modeStr, "legacy") == 0) {
358+
return true;
359+
} else if (strcmp(modeStr, "crash") == 0 || strcmp(modeStr, "swift6") == 0) {
360+
return false; // don't use the legacy mode
361+
} // else, just use the platform detected mode
362+
} // no override, use the default mode
365363
#endif // SWIFT_STDLIB_HAS_ENVIRON
364+
365+
return legacyMode;
366+
}
367+
368+
// Check override of executor checking mode.
369+
static void checkIsCurrentExecutorMode(void *context) {
370+
bool useLegacyMode =
371+
swift_bincompat_useLegacyNonCrashingExecutorChecks();
366372
isCurrentExecutorMode = useLegacyMode ? Legacy_NoCheckIsolated_NonCrashing
367-
: Default_UseCheckIsolated_AllowCrash;
373+
: Swift6_UseCheckIsolated_AllowCrash;
368374
}
369375

370376
SWIFT_CC(swift)
@@ -373,6 +379,12 @@ static bool swift_task_isCurrentExecutorImpl(SerialExecutorRef expectedExecutor)
373379

374380
// To support old applications on apple platforms which assumed this call
375381
// does not crash, try to use a more compatible mode for those apps.
382+
//
383+
// We only allow returning `false` directly from this function when operating
384+
// in 'Legacy_NoCheckIsolated_NonCrashing' mode. If allowing crashes, we
385+
// instead must call into 'checkIsolated' or crash directly.
386+
//
387+
// Whenever we confirm an executor equality, we can return true, in any mode.
376388
static swift::once_t checkModeToken;
377389
swift::once(checkModeToken, checkIsCurrentExecutorMode, nullptr);
378390

@@ -382,20 +394,19 @@ static bool swift_task_isCurrentExecutorImpl(SerialExecutorRef expectedExecutor)
382394
// the expected executor however, so we need to try a bit harder before
383395
// we fail.
384396

385-
// Are we expecting the main executor and are using the main thread?
397+
// Special handling the main executor by detecting the main thread.
386398
if (expectedExecutor.isMainExecutor() && isExecutingOnMainThread()) {
387-
// Due to compatibility with pre-checkIsolated code, we cannot remove
388-
// this special handling. CheckIsolated can handle this if the expected
389-
// executor is the main queue / main executor, however, if we cannot call
390-
// checkIsolated we cannot rely on it to handle this.
391-
// TODO: consider removing this branch when `useCrashingCheckIsolated=true`
392399
return true;
393400
}
394401

402+
// We cannot use 'complexEquality' as it requires two executor instances,
403+
// and we do not have a 'current' executor here.
404+
395405
// Otherwise, as last resort, let the expected executor check using
396406
// external means, as it may "know" this thread is managed by it etc.
397-
if (isCurrentExecutorMode == Default_UseCheckIsolated_AllowCrash) {
398-
swift_task_checkIsolated(expectedExecutor);
407+
if (isCurrentExecutorMode == Swift6_UseCheckIsolated_AllowCrash) {
408+
swift_task_checkIsolated(expectedExecutor); // will crash if not same context
409+
399410
// checkIsolated did not crash, so we are on the right executor, after all!
400411
return true;
401412
}
@@ -418,46 +429,50 @@ static bool swift_task_isCurrentExecutorImpl(SerialExecutorRef expectedExecutor)
418429
return true;
419430
}
420431

421-
// If the expected executor is "default" then we should have matched
422-
// by pointer equality already with the current executor.
423-
if (expectedExecutor.isDefaultActor()) {
424-
// If the expected executor is a default actor, it makes no sense to try
425-
// the 'checkIsolated' call, it must be equal to the other actor, or it is
426-
// not the same isolation domain.
427-
swift_Concurrency_fatalError(0, "Incorrect actor executor assumption");
428-
return false;
429-
}
430-
431-
if (expectedExecutor.isMainExecutor() && !currentExecutor.isMainExecutor()) {
432-
// TODO: Invoke checkIsolated() on "main" SerialQueue once it implements `checkIsolated`, otherwise messages will be sub-par and hard to address
433-
swift_Concurrency_fatalError(0, "Incorrect actor executor assumption; Expected MainActor executor");
434-
return false;
435-
} else if (!expectedExecutor.isMainExecutor() && currentExecutor.isMainExecutor()) {
436-
// TODO: Invoke checkIsolated() on "main" SerialQueue once it implements `checkIsolated`, otherwise messages will be sub-par and hard to address
437-
swift_Concurrency_fatalError(0, "Incorrect actor executor assumption; Expected not-MainActor executor");
438-
return false;
439-
}
440-
441-
if (expectedExecutor.isComplexEquality()) {
442-
if (!swift_compareWitnessTables(
443-
reinterpret_cast<const WitnessTable*>(currentExecutor.getSerialExecutorWitnessTable()),
444-
reinterpret_cast<const WitnessTable*>(expectedExecutor.getSerialExecutorWitnessTable()))) {
445-
// different witness table, we cannot invoke complex equality call
432+
// Only in legacy mode:
433+
// We check if the current xor expected executor are the main executor.
434+
// If so only one of them is, we know that WITHOUT 'checkIsolated' or invoking
435+
// 'dispatch_assert_queue' we cannot be truly sure the expected/current truly
436+
// are "on the same queue". There exists no non-crashing API to check this,
437+
// so we PESSIMISTICALLY return false here.
438+
//
439+
// In Swift6 mode:
440+
// We don't do this naive check, because we'll fall back to
441+
// `expected.checkIsolated()` which, if it is the main executor, will invoke
442+
// the crashing 'dispatch_assert_queue(main queue)' which will either crash
443+
// or confirm we actually are on the main queue; or the custom expected
444+
// executor has a chance to implement a similar queue check.
445+
if (isCurrentExecutorMode == Legacy_NoCheckIsolated_NonCrashing) {
446+
if ((expectedExecutor.isMainExecutor() && !currentExecutor.isMainExecutor()) ||
447+
(!expectedExecutor.isMainExecutor() && currentExecutor.isMainExecutor())) {
446448
return false;
447449
}
450+
}
448451

449-
// Avoid passing nulls to Swift for the isSame check:
450-
if (!currentExecutor.getIdentity() || !expectedExecutor.getIdentity()) {
451-
return false;
452+
// Complex equality means that if two executors of the same type have some
453+
// special logic to check if they are "actually the same".
454+
if (expectedExecutor.isComplexEquality()) {
455+
if (currentExecutor.getIdentity() &&
456+
expectedExecutor.getIdentity() &&
457+
swift_compareWitnessTables(
458+
reinterpret_cast<const WitnessTable *>(
459+
currentExecutor.getSerialExecutorWitnessTable()),
460+
reinterpret_cast<const WitnessTable *>(
461+
expectedExecutor.getSerialExecutorWitnessTable()))) {
462+
463+
auto isSameExclusiveExecutionContextResult =
464+
_task_serialExecutor_isSameExclusiveExecutionContext(
465+
currentExecutor.getIdentity(), expectedExecutor.getIdentity(),
466+
swift_getObjectType(currentExecutor.getIdentity()),
467+
expectedExecutor.getSerialExecutorWitnessTable());
468+
469+
// if the 'isSameExclusiveExecutionContext' returned true we trust
470+
// it and return; if it was false, we need to give checkIsolated another
471+
// chance to check.
472+
if (isSameExclusiveExecutionContextResult) {
473+
return true;
474+
} // else, we must give 'checkIsolated' a last chance to verify isolation
452475
}
453-
454-
auto result = _task_serialExecutor_isSameExclusiveExecutionContext(
455-
currentExecutor.getIdentity(),
456-
expectedExecutor.getIdentity(),
457-
swift_getObjectType(currentExecutor.getIdentity()),
458-
expectedExecutor.getSerialExecutorWitnessTable());
459-
460-
return result;
461476
}
462477

463478
// This provides a last-resort check by giving the expected SerialExecutor the
@@ -480,21 +495,22 @@ static bool swift_task_isCurrentExecutorImpl(SerialExecutorRef expectedExecutor)
480495
// Note that this only works because the closure in assumeIsolated is
481496
// synchronous, and will not cause suspensions, as that would require the
482497
// presence of a Task.
483-
// compat_invoke_swift_task_checkIsolated(expectedExecutor);
484-
if (isCurrentExecutorMode == Default_UseCheckIsolated_AllowCrash) {
485-
swift_task_checkIsolated(expectedExecutor);
498+
if (isCurrentExecutorMode == Swift6_UseCheckIsolated_AllowCrash) {
499+
swift_task_checkIsolated(expectedExecutor); // will crash if not same context
500+
486501
// The checkIsolated call did not crash, so we are on the right executor.
487502
return true;
488503
}
489504

490-
// Using legacy mode, if no explicit executor match worked, we assume `false`
505+
// In the end, since 'checkIsolated' could not be used, so we must assume
506+
// that the executors are not the same context.
491507
assert(isCurrentExecutorMode == Legacy_NoCheckIsolated_NonCrashing);
492508
return false;
493509
}
494510

495511
/// Logging level for unexpected executors:
496-
/// 0 - no logging
497-
/// 1 - warn on each instance
512+
/// 0 - no logging -- will be IGNORED when Swift6 mode of isCurrentExecutor is used
513+
/// 1 - warn on each instance -- will be IGNORED when Swift6 mode of isCurrentExecutor is used
498514
/// 2 - fatal error
499515
///
500516
/// NOTE: The default behavior on Apple platforms depends on the SDK version
@@ -512,8 +528,24 @@ static void checkUnexpectedExecutorLogLevel(void *context) {
512528
return;
513529

514530
long level = strtol(levelStr, nullptr, 0);
515-
if (level >= 0 && level < 3)
516-
unexpectedExecutorLogLevel = level;
531+
if (level >= 0 && level < 3) {
532+
if (swift_bincompat_useLegacyNonCrashingExecutorChecks()) {
533+
// legacy mode permits doing nothing or just logging, since the method
534+
// used to perform the check itself is not going to crash:
535+
unexpectedExecutorLogLevel = level;
536+
} else {
537+
// We are in swift6/crash mode of isCurrentExecutor which means that
538+
// rather than returning false, that method will always CRASH when an
539+
// executor mismatch is discovered.
540+
//
541+
// Thus, for clarity, we set this mode also to crashing, as runtime should
542+
// not expect to be able to get any logging or ignoring done. In practice,
543+
// the crash would happen before logging or "ignoring", but this should
544+
// help avoid confusing situations like "I thought it should log" when
545+
// debugging the runtime.
546+
unexpectedExecutorLogLevel = 2;
547+
}
548+
}
517549
#endif // SWIFT_STDLIB_HAS_ENVIRON
518550
}
519551

stdlib/public/runtime/Bincompat.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,19 @@ bool useLegacySwiftObjCHashing() {
255255
#endif
256256
}
257257

258+
// Controls legacy mode for the 'swift_task_isCurrentExecutorImpl' runtime function.
259+
//
260+
// In "legacy" / "no crash" mode:
261+
// * The `swift_task_isCurrentExecutorImpl` cannot crash
262+
// * This means cases where no "current" executor is present cannot be diagnosed correctly
263+
// * The runtime can NOT use 'SerialExecutor/checkIsolated'
264+
// * The runtime can NOT use 'dispatch_precondition' which is able ot handle some dispatch and main actor edge cases
265+
//
266+
// New behavior in "swift6" "crash" mode:
267+
// * The 'swift_task_isCurrentExecutorImpl' will CRASH rather than return 'false'
268+
// * This allows the method to invoke 'SerialExecutor/checkIsolated'
269+
// * Which is allowed to call 'dispatch_precondition' and handle "on dispatch queue but not on Swift executor" cases
270+
//
258271
// FIXME(concurrency): Once the release is announced, adjust the logic detecting the SDKs
259272
bool swift_bincompat_useLegacyNonCrashingExecutorChecks() {
260273
#if BINARY_COMPATIBILITY_APPLE

stdlib/public/runtime/EnvironmentVariables.def

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ VARIABLE(SWIFT_IS_CURRENT_EXECUTOR_LEGACY_MODE_OVERRIDE, string, "",
121121
"non-crashing behavior. This flag enables temporarily restoring the "
122122
"legacy 'nocrash' behavior until adopting code has been adjusted. "
123123
"Legal values are: "
124-
" 'nocrash' (Legacy behavior), "
125-
" 'crash' (Swift 6.0+ behavior)")
124+
" 'legacy' (Legacy behavior), "
125+
" 'swift6' (Swift 6.0+ behavior)")
126126

127127
#undef VARIABLE

test/Concurrency/Runtime/actor_assert_precondition_executor.swift

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,21 @@
11
// RUN: %empty-directory(%t)
22
// RUN: %target-build-swift -Xfrontend -disable-availability-checking -parse-as-library %s -o %t/a.out
33
// RUN: %target-codesign %t/a.out
4-
// RUN: %target-run %t/a.out
4+
// RUN: %env-SWIFT_IS_CURRENT_EXECUTOR_LEGACY_MODE_OVERRIDE=legacy %target-run %t/a.out
55

66
// REQUIRES: executable_test
77
// REQUIRES: concurrency
88
// REQUIRES: concurrency_runtime
99

10+
// TODO: The actual reason is that we do these %env- tricks, which e.g. Windows is confused about
11+
// REQUIRES: libdispatch
12+
1013
// UNSUPPORTED: back_deployment_runtime
1114
// UNSUPPORTED: back_deploy_concurrency
1215
// UNSUPPORTED: use_os_stdlib
1316
// UNSUPPORTED: freestanding
1417

15-
// rdar://119743909 fails in optimze tests.
18+
// rdar://119743909 fails in optimize tests.
1619
// UNSUPPORTED: swift_test_mode_optimize
1720
// UNSUPPORTED: swift_test_mode_optimize_size
1821

test/Concurrency/Runtime/actor_assert_precondition_executor_checkIsolated_bincompat.swift renamed to test/Concurrency/Runtime/actor_assert_precondition_executor_checkIsolated_bincompat_crash_swift_6_mode.swift

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
// RUN: %target-run-simple-swift(-parse-as-library -Xfrontend -disable-availability-checking) | %FileCheck %s
1+
// RUN: %empty-directory(%t)
2+
// RUN: %target-build-swift -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library %s -o %t/a.out
3+
// RUN: %target-codesign %t/a.out
4+
// RUN: %env-SWIFT_IS_CURRENT_EXECUTOR_LEGACY_MODE_OVERRIDE=swift6 %target-run %t/a.out
25

36
// REQUIRES: executable_test
47
// REQUIRES: concurrency
@@ -11,6 +14,8 @@
1114
// UNSUPPORTED: use_os_stdlib
1215
// UNSUPPORTED: freestanding
1316

17+
import StdlibUnittest
18+
1419
final class NaiveQueueExecutor: SerialExecutor {
1520
init() {}
1621

@@ -38,32 +43,26 @@ actor ActorOnNaiveQueueExecutor {
3843
self.executor.asUnownedSerialExecutor()
3944
}
4045

46+
// Executes on global pool, but our `checkIsolated` impl pretends
47+
// that it is the same executor by never crashing.
4148
nonisolated func checkPreconditionIsolated() async {
4249
print("Before preconditionIsolated")
4350
self.preconditionIsolated()
4451
print("After preconditionIsolated")
45-
46-
print("Before assumeIsolated")
47-
self.assumeIsolated { iso in
48-
print("Inside assumeIsolated")
49-
}
50-
print("After assumeIsolated")
5152
}
5253
}
5354

5455
@main struct Main {
5556
static func main() async {
56-
if #available(SwiftStdlib 6.0, *) {
57-
let actor = ActorOnNaiveQueueExecutor()
58-
await actor.checkPreconditionIsolated()
59-
// CHECK: Before preconditionIsolated
60-
// CHECK-NEXT: checkIsolated: pretend it is ok!
61-
// CHECK-NEXT: After preconditionIsolated
57+
let tests = TestSuite("AssertPreconditionIsolationTests")
6258

63-
// CHECK-NEXT: Before assumeIsolated
64-
// CHECK-NEXT: checkIsolated: pretend it is ok!
65-
// CHECK-NEXT: Inside assumeIsolated
66-
// CHECK-NEXT: After assumeIsolated
59+
if #available(SwiftStdlib 6.0, *) {
60+
tests.test("[swift6+checkIsolated] Isolation assured by invoking 'checkIsolated'") {
61+
let actor = ActorOnNaiveQueueExecutor()
62+
await actor.checkPreconditionIsolated()
63+
}
6764
}
65+
66+
await runAllTestsAsync()
6867
}
6968
}

0 commit comments

Comments
 (0)