Skip to content

[SourceKit] Resolve a nondeterministic deadlock in SourceKit while cancelling #42258

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 19, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 21 additions & 17 deletions tools/SourceKit/lib/SwiftLang/SwiftASTManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1137,38 +1137,42 @@ void ASTBuildOperation::schedule(WorkQueue Queue) {
std::string Error;
assert(!Result && "We should only be producing a result once");
ASTUnitRef AST = buildASTUnit(Error);
SmallVector<SwiftASTConsumerRef, 4> LocalConsumers;
{
llvm::sys::ScopedLock L(ConsumersAndResultMtx);
bool WasCancelled = CancellationFlag->load(std::memory_order_relaxed);
Result.emplace(AST, Error, WasCancelled);
for (auto &Consumer : Consumers) {
informConsumer(Consumer);
}
LocalConsumers = Consumers;
Consumers = {};
}
for (auto &Consumer : LocalConsumers) {
informConsumer(Consumer);
}
DidFinishCallback();
},
/*isStackDeep=*/true);
}

bool ASTBuildOperation::addConsumer(SwiftASTConsumerRef Consumer) {
llvm::sys::ScopedLock L(ConsumersAndResultMtx);
if (isCancelled()) {
return false;
}
if (Result) {
informConsumer(Consumer);
} else {
{
llvm::sys::ScopedLock L(ConsumersAndResultMtx);
if (isCancelled()) {
return false;
}
if (Result) {
informConsumer(Consumer);
return true;
}
Comment on lines +1162 to +1165
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally this would be outside the lock as well - maybe check !Result here and then the same check outside the lock to either inform/add cancellation?

assert(OperationState != State::Finished);
auto WeakThis = std::weak_ptr<ASTBuildOperation>(shared_from_this());
Consumers.push_back(Consumer);
Consumer->setCancellationRequestCallback(
[WeakThis](SwiftASTConsumerRef Consumer) {
if (auto This = WeakThis.lock()) {
This->requestConsumerCancellation(Consumer);
}
});
}
auto WeakThis = std::weak_ptr<ASTBuildOperation>(shared_from_this());
Consumer->setCancellationRequestCallback(
[WeakThis](SwiftASTConsumerRef Consumer) {
if (auto This = WeakThis.lock()) {
This->requestConsumerCancellation(Consumer);
}
});
return true;
}

Expand Down