Skip to content

[sanitizers] Optimize locking StackDepotBase for fork #76280

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
Show file tree
Hide file tree
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
4 changes: 4 additions & 0 deletions compiler-rt/lib/sanitizer_common/sanitizer_flat_map.h
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ class TwoLevelMap {
return *AddressSpaceView::LoadWritable(&map2[idx % kSize2]);
}

void Lock() SANITIZER_NO_THREAD_SAFETY_ANALYSIS { mu_.Lock(); }

void Unlock() SANITIZER_NO_THREAD_SAFETY_ANALYSIS { mu_.Unlock(); }

private:
constexpr uptr MmapSize() const {
return RoundUpTo(kSize2 * sizeof(T), GetPageSizeCached());
Expand Down
22 changes: 18 additions & 4 deletions compiler-rt/lib/sanitizer_common/sanitizer_stackdepotbase.h
Original file line number Diff line number Diff line change
Expand Up @@ -161,18 +161,32 @@ StackDepotBase<Node, kReservedBits, kTabSizeLog>::Get(u32 id) {

template <class Node, int kReservedBits, int kTabSizeLog>
void StackDepotBase<Node, kReservedBits, kTabSizeLog>::LockBeforeFork() {
for (int i = 0; i < kTabSize; ++i) {
lock(&tab[i]);
}
// Do not lock hash table. It's very expensive, but it's not rely needed. The
// parent process will neither lock nor unlock. Child process risks to be
// deadlocked on already locked buckets. To avoid deadlock we will unlock
// every locked buckets in `UnlockAfterFork`. This may affect consistency of
// the hash table, but the only issue is a few items inserted by parent
// process will be not found by child, and the child may insert them again,
// wasting some space in `stackStore`.

// We still need to lock nodes.
nodes.Lock();
}

template <class Node, int kReservedBits, int kTabSizeLog>
void StackDepotBase<Node, kReservedBits, kTabSizeLog>::UnlockAfterFork(
bool fork_child) {
nodes.Unlock();

// Only unlock in child process to avoid deadlock. See `LockBeforeFork`.
if (!fork_child)
return;

for (int i = 0; i < kTabSize; ++i) {
atomic_uint32_t *p = &tab[i];
uptr s = atomic_load(p, memory_order_relaxed);
unlock(p, s & kUnlockMask);
if (s & kLockMask)
unlock(p, s & kUnlockMask);
}
}

Expand Down