Closed Bug 1960192 Opened 1 year ago Closed 6 months ago

GC-JS data race TSAN errors found by local xpcshell-test of TSAN DEBUG version of C-C TB

Categories

(Core :: JavaScript: GC, defect, P3)

defect

Tracking

()

RESOLVED WONTFIX

People

(Reporter: ishikawa, Assigned: ishikawa)

References

(Blocks 1 open bug)

Details

Attachments

(6 files, 1 external file)

Hi, I am testing local C-C TB patches under linux.

I found TSAN errors some genuine and some only triggered in DEBUG build when I ran sanitized DEBUG version of C-C TB.
I am attaching the locally patched errors, and places marked with the word "race" to be fixed in the future.
Come to think if, though, this is inside M-C tree.

Maybe the category may need change.

The background and some difficulty in getting TSAN version created locally is explained in
https://bugzilla.mozilla.org/show_bug.cgi?id=1816588#c13

I am going to attach a few TSAN run-time error to show the currently remaining issues.
(I am aborting the run when an issue is encountered. So once I fixe these, newer ones will be encountered.)
The line numbers are likely different from pristine source file's because the patches are already applied.

One thing I don't understand is that TSAN test on treeherder does not report these errors I noticed.
Is it because the TSAN runtime may be different ?
(I notice mine prints V3 locally)
Or is there a clever whitelisting / suppression of known issues with the tree herder TSAN run?

See Also: → 1816588
Component: Untriaged → General

I have been debugging data race issues in C-C TB's IMAP module.
Logically, all the TSAN issues that occur during my testing on local PC and treeherder have been identified and fixed.

But during the testing it became obvious that DEBUG-enabled version of binary trigger GC-JS data races and this hampered
testing.
DEBUG-binary is useful because it prints various internal issues / warnings to give context to real errors.
However, GC-JS data race triggers in a few test cases very randomly in about 170+ test runs using the test programs in
comm/mailnews/imap/test/unit.
Many tests there are run twice, one using mbox message file and one using maildir (one message per file).

Since I don't see the race not as often on treeherder, I realize that treeherder TSAN binary is created without DEBUG flag.
So I created a non-DEBUG version locally and have been running tests.
Without DEBUG flaga, generated TSAN-binary does not seem to experience this GC-JS data race. I can get clean test results.

It would be great this GC-JS data race is removed in DEBUG build.
TSAN introduces enough timing variations and can uncover issues like missed notification and other timing issues. In such cases, the messags from macros that are enabled only during DEBUG build is very useful.

Anyway, I upload a few TSAN runtime reports I have experienced in the last few weeks for those interested in tightening up
the code.

TSAN runtime report. Case 1

Attached file 2.trace —

TSAN runtime report. Case 2

TSAN runtime report. Case 3.

SpiderMonkey GC TSAN Race: NurserySweepTask vs Major GC Marker (BitSet<1024>)

Summary

Again, this is about the DEBUG version of C-C TB.

ThreadSanitizer reports a data race in SpiderMonkey's GC: a concurrent read of
BitSet<1024>::test() on the main thread during major GC marking races with a
write to the same BitSet word by a NurserySweepTask helper thread performing
minor GC buffer sweep.

Component: Core → JavaScript Engine: GC


Race Location

mozilla/dist/include/mozilla/BitSet.h:117
mozilla::BitSet<1024ul, unsigned long>::test(unsigned long) const

Specifically within:

js::gc::AllocSpace<js::gc::SmallBufferRegion, 16384ul, 16ul>::isAllocated()
js::gc::AllocSpace<js::gc::SmallBufferRegion, 16384ul, 16ul>::isNurseryOwned()

(BufferAllocatorInternals.h:241, 258)

Racy address: 0x7f77b596c098 — one 8-byte unsigned long word of the BitSet<1024>.


Thread 1 — Main Thread (Reader)

The main thread is executing a major GC cycle triggered explicitly by JS_GC()
(called from the GC builtin in XPCShellImpl.cpp:411).

Call chain:

JS_GC()
  → GCRuntime::gc()
  → GCRuntime::collect()
  → GCRuntime::gcCycle()
  → GCRuntime::incrementalSlice()
  → GCRuntime::markPhase()
  → GCRuntime::markSynchronously()
  → GCMarker::markUntilBudgetExhausted()
  → GCMarker::doMarking()
  → GCMarker::markOneColor()
  → GCMarker::processMarkStackTop()
  → BaseScript::traceChildren()
  → TraceBufferEdge<PrivateScriptData*>()
  → TraceBufferEdgeInternal()
  → BufferAllocator::traceEdge()
  → BufferAllocator::isNurseryOwned()
  → AllocSpace::isNurseryOwned()
  → AllocSpace::isAllocated()         ← READ of BitSet word
  → BitSet<1024>::test()              ← TSAN REPORTS READ HERE

The major GC marker is tracing a BaseScript's children, specifically a
PrivateScriptData* buffer edge. To determine whether this buffer is
nursery-owned, it calls BufferAllocator::isNurseryOwned(), which reads the
isAllocated bitmap — a BitSet<1024> — without any lock or atomic operation.


Thread 2 — Helper Thread T24 TaskCon~ller #0 (Writer)

Concurrently, a mozilla::TaskController pool thread is running
NurserySweepTask — the background minor GC sweep — dispatched during a
preceding minor GC triggered by a JS string allocation from JSON.parse.

Trigger chain for minor GC:

JSON.parse → NewStringCopyN → nursery alloc
  → RetryNurseryAlloc → minorGC
  → startBackgroundFreeAfterMinorGC
  → dispatches NurserySweepTask to helper thread pool

NurserySweepTask call chain:

ThreadFuncPoolThread()
  → TaskController::RunPoolThread()
  → TaskController::RunTask()
  → HelperThreadTaskHandler::Run()
  → JS::RunHelperThreadTask()
  → GCParallelTask::runHelperThreadTask()
  → GCParallelTask::runTask()
  → NurserySweepTask::run()
  → BufferAllocator::sweepForMinorCollection()
  → BufferAllocator::sweepChunk()
  → BufferAllocator::sweepSmallBufferRegion()
  → AllocSpace::setDeallocated()
  → AllocSpace::setAllocated(ptr, idx, false)  ← WRITE to BitSet word
  → BitSet<1024>::Reference::operator=(bool)   ← TSAN REPORTS WRITE HERE

The nursery sweep task is marking buffer regions as deallocated by clearing bits
in the same BitSet<1024> that the main thread is simultaneously reading.


Nature of the Race

The BitSet<1024> uses unsigned long words as its underlying storage. Both:

  • the read (test(), BitSet.h:117) on the main thread, and
  • the write (Reference::operator=, BitSet.h:82) on the helper thread

operate on the same 8-byte word at address 0x7f77b596c098 without any
synchronization. This is an unsynchronized concurrent read/write on a
non-atomic type — undefined behaviour and a real data race under the C++ memory
model.

The root cause is that BufferAllocator's isAllocated bitmap is shared
between:

  • the major GC marker running on the main thread (reads via isNurseryOwned())
  • the nursery sweep background task running on a helper thread (writes via setDeallocated())

with no lock or atomic protecting the shared BitSet word.


Trigger Conditions

The race requires two GC activities to overlap:

  1. A minor GC that dispatches NurserySweepTask as a background task
  2. A major GC that begins incremental marking on the main thread before the
    background nursery sweep completes

In xpcshell tests, it seems this overlap is reliably triggered by JSON.parse or
JSON.stringify on large objects (e.g. a 1 MiB Uint8Array), which generates
heavy string allocation pressure, fills the nursery, triggers minor GC, and
dispatches the sweep task. If a subsequent major GC slice begins before the
sweep task finishes, the race window opens.

Case 2 summary

SpiderMonkey GC TSAN Race: NurserySweepTask (BufferChunk) vs Major GC Marker (BitSet<256>)

Summary

Again, this is with DEBUG build of C-C TB.

ThreadSanitizer reports a data race in SpiderMonkey's GC: a concurrent read of
BitSet<256>::test() on the main thread during major GC marking races with a
write to the same BitSet word by a NurserySweepTask helper thread sweeping
large buffer chunks during minor GC cleanup.

Component: Core → JavaScript Engine: GC


Relationship to Previously Filed Race (BitSet<1024>)

This race is closely related to, but distinct from, the previously filed
NurserySweepTask vs major GC marker race involving BitSet<1024ul> and
SmallBufferRegion. Both races share the same root cause structure:

  • Same two thread roles: major GC marker (main thread) vs NurserySweepTask (helper thread)
  • Same BufferAllocator::isNurseryOwned() → isAllocated() → BitSet::test() read path
  • Same sweepForMinorCollection() → sweepChunk() → setDeallocated() → BitSet::operator= write path

The key differences are:

Property This report Previous report
BitSet size BitSet<256> BitSet<1024>
AllocSpace template AllocSpace<BufferChunk, 1048576ul, 4096ul> AllocSpace<SmallBufferRegion, 16384ul, 16ul>
Reader entry point BufferAllocator::markTenuredAlloc() BufferAllocator::traceEdge()
Reader source line BufferAllocator.cpp:808 (→ BufferAllocator.cpp:1044) BufferAllocator.cpp:809 (→ BufferAllocator.cpp:967)
Writer sweep path sweepChunk() directly (no sweepSmallBufferRegion) sweepChunk() → sweepSmallBufferRegion()

The large-chunk allocator (BufferChunk, 1 MiB regions, 4096-byte granule)
uses BitSet<256> (256 bits = 1 MiB / 4096). The small-buffer allocator
(SmallBufferRegion, 16 KiB regions, 16-byte granule) uses BitSet<1024>
(1024 bits = 16 KiB / 16). Both bitmaps are accessed without synchronization
between the major GC marker and the concurrent nursery sweep task.


Race Location

mozilla/dist/include/mozilla/BitSet.h:117
mozilla::BitSet<256ul, unsigned long>::test(unsigned long) const

Specifically within:

js::gc::AllocSpace<js::gc::BufferChunk, 1048576ul, 4096ul>::isAllocated(void const*) const
js::gc::SmallBufferRegion::from(void*)

(BufferAllocatorInternals.h:241, 414)

Racy address: 0x7f32f6b00050 — one 8-byte unsigned long word of the BitSet<256>.


Thread 1 — Main Thread (Reader)

The main thread is executing a major GC cycle triggered by JS_GC()
(called from the GC builtin in XPCShellImpl.cpp:411).

Call chain:

JS_GC()
  → GCRuntime::gc()
  → GCRuntime::collect()
  → GCRuntime::gcCycle()
  → GCRuntime::incrementalSlice()
  → GCRuntime::markPhase()
  → GCRuntime::markSynchronously()
  → GCMarker::markUntilBudgetExhausted()
  → GCMarker::doMarking()
  → GCMarker::markOneColor()
  → GCMarker::processMarkStackTop()      ← Marking.cpp:1783
  → MarkTenuredBuffer()                  ← BufferAllocator-inl.h:138
  → BufferAllocator::markTenuredAlloc()  ← BufferAllocator.cpp:1044
  → BufferAllocator::isNurseryOwned()    ← BufferAllocator.cpp:808, 801
  → AllocSpace<BufferChunk,...>::isAllocated()   ← BufferAllocatorInternals.h:241
  → SmallBufferRegion::from()            ← BufferAllocatorInternals.h:414
  → BitSet<256>::test()                  ← TSAN REPORTS READ HERE (BitSet.h:117)

Note the different reader entry point compared to the previous report:
here the major GC marker calls MarkTenuredBuffer() → markTenuredAlloc()
rather than TraceBufferEdge() → traceEdge(). Both ultimately reach
isNurseryOwned() → isAllocated() → BitSet::test() without a lock.


Thread 2 — Helper Thread T24 TaskCon~ller #0 (Writer)

A mozilla::TaskController pool thread runs NurserySweepTask, dispatched
during a preceding minor GC triggered by a JS string allocation from JSON.parse.

Trigger chain for minor GC (identical to previous report):

JSON.parse → NewStringCopyN → nursery alloc
  → RetryNurseryAlloc → minorGC
  → startBackgroundFreeAfterMinorGC
  → dispatches NurserySweepTask to helper thread pool

NurserySweepTask call chain:

ThreadFuncPoolThread()
  → TaskController::RunPoolThread()
  → TaskController::RunTask()
  → HelperThreadTaskHandler::Run()
  → JS::RunHelperThreadTask()
  → GCParallelTask::runHelperThreadTask()
  → GCParallelTask::runTask()
  → NurserySweepTask::run()                       ← Nursery.cpp:204
  → BufferAllocator::sweepForMinorCollection()    ← BufferAllocator.cpp:1232
  → BufferAllocator::sweepChunk()                 ← BufferAllocator.cpp:2578
  → AllocSpace<BufferChunk,...>::setDeallocated()  ← BufferAllocator.cpp:311
  → AllocSpace<BufferChunk,...>::setAllocated(ptr, idx, false)  ← BufferAllocator.cpp:301
  → BitSet<256>::Reference::operator=(bool)        ← TSAN REPORTS WRITE HERE (BitSet.h:82)

Note: compared to the previous report, there is no sweepSmallBufferRegion()
intermediate call — sweepChunk() calls setDeallocated() directly for the
large BufferChunk allocator.


Nature of the Race

The BitSet<256> uses unsigned long words as its underlying storage. Both:

  • the read (test(), BitSet.h:117) on the main thread, and
  • the write (Reference::operator=, BitSet.h:82) on the helper thread

operate on the same 8-byte word at address 0x7f32f6b00050 without any
synchronization. This is an unsynchronized concurrent read/write on a
non-atomic type — undefined behaviour and a real data race.

The root cause is that the large-buffer BufferAllocator isAllocated bitmap
(BitSet<256>, covering 1 MiB BufferChunk regions at 4096-byte granularity)
is shared between:

  • the major GC marker (reads during markTenuredAlloc() to determine
    nursery ownership before marking a tenured allocation)
  • the nursery sweep background task (writes during sweepChunk() to
    mark buffer regions as deallocated)

with no lock or atomic protecting the shared BitSet word.


Trigger Conditions

Identical to the previously filed race: the race requires a minor GC that
dispatches NurserySweepTask as a background task to overlap with a
subsequent major GC incremental marking slice on the main thread.

In xpcshell tests this is reliably triggered by JSON.parse or JSON.stringify
on large objects generating heavy string allocation pressure that fills the
nursery. The subsequent major GC slice races with the still-running sweep.


Impact

Observed in: xpcshell DEBUG-enabled TSAN builds of comm-central, triggered by tests that
perform heavy JS string allocation (test_repairMbox.js,
test_imapAttachmentSaves.js, test_copyThenMove.js, test_offlineCopy.js).

case 3 summary

SpiderMonkey GC TSAN Race: Parallel Compaction Pointer Update vs DOM Worker GC (HeaderWord)

Summary

This is again about a DEBUG version of C-C TB.

ThreadSanitizer reports a data race in SpiderMonkey's GC compaction phase: a
non-atomic read of HeaderWord::get() on a DOM Worker thread running its
own GC cycle races with an atomic write of HeaderWord::setAtomic() by a
ParallelWorker helper thread performing parallel cell pointer updates during
compaction.

Component: Core → JavaScript Engine: GC

This race is fundamentally different from the two previously filed
NurserySweepTask / BufferAllocator / BitSet races.
It involves a
completely different GC phase (compaction, not minor GC sweep), different
thread roles (DOM Worker thread vs GC parallel worker, not main thread vs
nursery sweep task), and a different data structure (HeaderWord in
Cell.h:110, not BitSet in BitSet.h:117).


Race Location

mozilla/js/src/gc/Cell.h:110
js::gc::HeaderWord::get() const

Specifically, the non-atomic read of the JSObject header word during GC
marking (JSObject::shape() → JSObject::zoneFromAnyThread()) on a DOM Worker
thread races with an atomic write of the same header word
(HeaderWord::setAtomic()) by a parallel compaction worker updating relocated
cell pointers.

Racy address: 0x7f53c4b95040 — the HeaderWord of a JSObject.


Thread 1 — DOM Worker Thread T31 (Reader — non-atomic)

A DOM Worker thread ('DOM Worker', tid=417183) is running its own
independent GC cycle via WorkerPrivate::GarbageCollectInternal(). This is
a non-incremental full GC (JS::NonIncrementalGC) triggered during the
worker's run loop. The worker's GC reaches the compaction phase and calls
updateCellPointers(), which traces JSObject children. During tracing,
JSObject::zoneFromAnyThread() reads the object's shape(), which calls
HeaderWord::get() — a plain non-atomic read — to retrieve the current
header word value.

Call chain:

WorkerPrivate::DoRunLoop()
  → WorkerPrivate::GarbageCollectInternal()
  → JS::NonIncrementalGC()
  → GCRuntime::gc()
  → GCRuntime::collect()
  → GCRuntime::gcCycle()
  → GCRuntime::incrementalSlice()          ← GC.cpp:4485
  → GCRuntime::compactPhase()              ← Compacting.cpp:89
  → GCRuntime::updateZonePointersToRelocatedCells()   ← Compacting.cpp:805
  → GCRuntime::updateAllCellPointers()     ← Compacting.cpp:770
  → GCRuntime::updateCellPointers()        ← Compacting.cpp:696
  → UpdateArenaListSegmentPointers()       ← Compacting.cpp:565
  → UpdateArenaPointers()                  ← Compacting.cpp:540
  → UpdateArenaPointersTyped<JSObject>()   ← Compacting.cpp:510
  → UpdateCellPointers<JSObject>()         ← Compacting.cpp:504
  → JSObject::traceChildren()              ← JSObject.cpp:3326
  → TraceRange<JS::Value>()
  → TraceRangeInternal<JS::Value>()
  → TraceEdgeInternal(JSTracer*, JS::Value*, ...)
  → TraceTaggedPtrEdge<JS::Value>()
  → TraceEdgeInternal(JSTracer*, JSObject**, ...)
  → CheckTracedThing<JSObject>()           ← Marking.cpp:156
  → JSObject::zoneFromAnyThread()          ← JSObject.h:318
  → JSObject::shape()                      ← JSObject.h:92
  → CellWithTenuredGCPointer::headerPtr()  ← Cell.h:843
  → HeaderWord::get()                      ← TSAN REPORTS READ HERE (Cell.h:110)

The key point: HeaderWord::get() performs a plain non-atomic load of the
header word. This is intentional for performance in the normal single-GC case,
but becomes a race when two GC instances run concurrently on different threads
touching the same object.


Thread 2 — Helper Thread T25 TaskCon~ller #1 (Writer — atomic)

A mozilla::TaskController pool thread (T25, 'TaskCon~ller #1', tid=417176)
is running a ParallelWorker<ArenaListSegment, ArenasToUpdate> task —
SpiderMonkey's parallel cell pointer update worker, used during the
compaction phase to update stale pointers to relocated cells across arenas in
parallel. This worker calls JSObject::traceChildren(), which traces the
object's header (shape pointer) via TraceCellHeaderEdge(). The tracer writes
the updated (relocated) shape pointer back via unbarrieredSetHeaderPtr() →
HeaderWord::set() → HeaderWord::setAtomic() — an atomic store.

Call chain:

ThreadFuncPoolThread()
  → TaskController::RunPoolThread()
  → TaskController::RunTask()
  → HelperThreadTaskHandler::Run()
  → JS::RunHelperThreadTask()
  → GCParallelTask::runHelperThreadTask()
  → GCParallelTask::runTask()
  → ParallelWorker<ArenaListSegment, ArenasToUpdate>::run()  ← ParallelWork.h:54
  → UpdateArenaListSegmentPointers()       ← Compacting.cpp:565
  → UpdateArenaPointers()                  ← Compacting.cpp:540
  → UpdateArenaPointersTyped<JSObject>()   ← Compacting.cpp:510
  → UpdateCellPointers<JSObject>()         ← Compacting.cpp:504
  → JSObject::traceChildren()              ← JSObject.cpp:3295
  → TraceCellHeaderEdge<Cell, Shape>()     ← Tracer.h:167
  → CellWithTenuredGCPointer::unbarrieredSetHeaderPtr()  ← Cell.h:854
  → HeaderWord::set()                      ← Cell.h:116
  → HeaderWord::setAtomic()                ← TSAN REPORTS WRITE HERE (Cell.h:94)

Nature of the Race

The HeaderWord of a JSObject is being accessed simultaneously by two
independent GC instances running on different threads:

  • The DOM Worker thread reads it non-atomically via HeaderWord::get()
    (Cell.h:110) during its own compaction phase's CheckTracedThing() call
  • The GC parallel worker writes it atomically via HeaderWord::setAtomic()
    (Cell.h:94) during the parallel pointer update pass of a separate GC
    instance

TSAN flags this as a data race because one access is non-atomic (get()) and
the other is atomic (setAtomic()). Under the C++ memory model, mixing atomic
and non-atomic accesses to the same memory location is undefined behaviour,
regardless of which side is atomic.

The root cause is that two independent JS runtimes/GC instances are
compacting the heap concurrently
— one on a DOM Worker thread and one using
the main thread's GC helper thread pool — and they happen to be operating on
overlapping memory (the same JSObject's header word). The DOM Worker's GC
compaction reads the header non-atomically while the main GC's parallel
compaction worker writes it atomically.

This is architecturally distinct from the nursery sweep races: those involved a
single GC instance with one phase (marking) racing against a background task
from the same GC (nursery sweep). This race involves two independent GC
instances
from two different JS contexts (main thread and DOM Worker)
competing on the same object's header, with neither aware of the other.


Trigger Conditions

The race requires:

  1. A DOM Worker to be active and running its own GC cycle in its compaction
    phase (here triggered by MboxRepair.worker.mjs creating a ChromeWorker
    for the mbox repair operation)
  2. The main thread's GC to simultaneously be running its parallel
    compaction pointer update phase via helper threads
  3. Both to operate on the same JSObject — possible if the object is in a
    shared zone or is reachable from both contexts

The worker creation chain confirms this: the DOM Worker was created by
ChromeWorker::Constructor() → WorkerPrivate::Constructor() →
RuntimeService::ScheduleWorker() — this is the MboxRepair.worker.mjs
ChromeWorker spawned by repairMbox().
(Submitter's note: This is from xpcshell test run of comm/mailnews/imap/test/unit/test_repairMbox.js.
Very strangely, this particular test program triggers this TSAN error
in DEBUG build very often.)


Key Differences from Previously Filed Races

Property This report Previous reports (BitSet races)
Data structure HeaderWord (Cell.h:110) BitSet<256/1024> (BitSet.h:117)
Reader thread DOM Worker thread (T31) Main thread
Writer thread GC ParallelWorker (T25) NurserySweepTask helper
GC phase Compaction — pointer update Minor GC — nursery sweep
Access type Non-atomic read vs atomic write Non-atomic read vs non-atomic write
Root cause Two independent GC instances on different threads touching same object Single GC instance: marking phase vs background sweep task
Context DOM Worker GC + main GC helper threads Main thread GC + nursery sweep task
Trigger ChromeWorker (MboxRepair) running own GC during main thread compaction JSON.parse string allocation pressure filling nursery

Impact

The test reports FAIL due to TSAN aborting the process (return code -6). All
subtests pass before the abort — the race does not cause incorrect results.
The race is a real concurrency bug in SpiderMonkey's GC, not in
Thunderbird/comm-central code.

Observed in: xpcshell TSAN builds of comm-central running
test_repairMbox.js, which spawns a ChromeWorker (MboxRepair.worker.mjs)
that independently runs GC on its worker thread.


case 4 summary

SpiderMonkey GC TSAN Race: NurserySweepTask (BufferChunk) vs Major GC Marker via traceEdge (BitSet<256>, Main Thread)

Summary

Again, I observed this in DEBUG-enabled C-C TB, but now I am not sure
if this particular path is DEBUG-binary specific after the analysis here.

ThreadSanitizer reports a data race in SpiderMonkey's GC: a concurrent read of
BitSet<256>::test() on the main thread during major GC marking races with
a write to the same BitSet word by a NurserySweepTask helper thread sweeping
large buffer chunks during minor GC cleanup.

Component: Core → JavaScript Engine: GC


Relationship to Previously Filed Races

This is the fourth in a series of related BufferAllocator / BitSet /
NurserySweepTask races. A comparison table of all four:

# BitSet size AllocSpace Reader thread Reader entry point BuildId
1 BitSet<1024> SmallBufferRegion (16KiB/16B) Main thread traceEdge() → BufferAllocator.cpp:967 4f57c358...
2 BitSet<256> BufferChunk (1MiB/4KiB) Main thread markTenuredAlloc() → BufferAllocator.cpp:1044 4f57c358...
3 HeaderWord N/A DOM Worker thread CheckTracedThing() / parallel compaction 4f57c358...
4 (this) BitSet<256> BufferChunk (1MiB/4KiB) Main thread traceEdge() → BufferAllocator.cpp:967 f76c4df0...

This report (BuildId f76c4df0...) is from a different build than reports 1–3
(BuildId 4f57c358...).
It demonstrates the same class of race persists across
builds. The reader entry point here (traceEdge()) matches Report 1 but uses
BitSet<256> / BufferChunk (like Report 2) rather than BitSet<1024> /
SmallBufferRegion. This indicates that both allocator tiers are reachable via
both reader entry points — the race is not limited to specific combinations of
allocator tier and entry path.

The writer side is identical across reports 1, 2, and 4:
NurserySweepTask → sweepForMinorCollection() → sweepChunk() →
setDeallocated() → BitSet::operator=.


Race Location

mozilla/dist/include/mozilla/BitSet.h:117
mozilla::BitSet<256ul, unsigned long>::test(unsigned long) const

Within:

js::gc::AllocSpace<js::gc::BufferChunk, 1048576ul, 4096ul>::isAllocated(void const*) const
js::gc::SmallBufferRegion::from(void*)

(BufferAllocatorInternals.h:241, 414)

Racy address: 0x7fdc4cb00060 — one 8-byte unsigned long word of the BitSet<256>.


Thread 1 — Main Thread (Reader)

The main thread is executing a major GC cycle triggered explicitly by JS_GC()
(called from the GC builtin in XPCShellImpl.cpp:411). The main thread GC
reaches the mark phase and traces a BaseScript's PrivateScriptData* buffer
edge via traceEdge(), which calls isNurseryOwned() → isAllocated() →
BitSet<256>::test() without any lock.

Call chain:

JS_GC()
  → GCRuntime::gc()
  → GCRuntime::collect()
  → GCRuntime::gcCycle()
  → GCRuntime::incrementalSlice()
  → GCRuntime::markPhase()
  → GCRuntime::markSynchronously()
  → GCMarker::markUntilBudgetExhausted()
  → GCMarker::doMarking()
  → GCMarker::markOneColor()
  → GCMarker::processMarkStackTop()        ← Marking.cpp:1679
  → BaseScript::traceChildren()            ← TraceMethods-inl.h:42
  → TraceBufferEdge<PrivateScriptData*>()  ← Tracer.h:364
  → TraceBufferEdgeInternal()              ← BufferAllocator-inl.h:134
  → BufferAllocator::traceEdge()           ← BufferAllocator.cpp:967
  → BufferAllocator::isNurseryOwned()      ← BufferAllocator.cpp:808, 801
  → AllocSpace<BufferChunk,...>::isAllocated()     ← BufferAllocatorInternals.h:241
  → SmallBufferRegion::from()              ← BufferAllocatorInternals.h:414
  → BitSet<256>::test()                    ← TSAN REPORTS READ HERE (BitSet.h:117)

Note: this reader path is via traceEdge() (same as Report 1), not
markTenuredAlloc() (as in Report 2), confirming the BufferChunk-tier
BitSet<256> is reachable from both entry points.

The GC was triggered during a microtask checkpoint (BeforeProcessTask →
PerformMicroTaskCheckPoint) after an async JSON.parse resumed via JIT
(jit::InterpretResume). The JIT path is visible at frames #45–#48 of the
reader stack, distinguishing this report from the interpreter-only path in
Reports 1 and 2.


Thread 2 — Helper Thread T24 TaskCon~ller #0 (Writer)

Identical writer path to Reports 1 and 2. A mozilla::TaskController pool
thread runs NurserySweepTask, dispatched during a minor GC triggered by
JSON.parse string allocation pressure.

Call chain:

ThreadFuncPoolThread()
  → TaskController::RunPoolThread()
  → TaskController::RunTask()
  → HelperThreadTaskHandler::Run()
  → JS::RunHelperThreadTask()
  → GCParallelTask::runHelperThreadTask()
  → GCParallelTask::runTask()
  → NurserySweepTask::run()                       ← Nursery.cpp:204
  → BufferAllocator::sweepForMinorCollection()    ← BufferAllocator.cpp:1232
  → BufferAllocator::sweepChunk()                 ← BufferAllocator.cpp:2578
  → AllocSpace<BufferChunk,...>::setDeallocated()  ← BufferAllocator.cpp:311
  → AllocSpace<BufferChunk,...>::setAllocated(ptr, idx, false)  ← BufferAllocator.cpp:301
  → BitSet<256>::Reference::operator=(bool)        ← TSAN REPORTS WRITE HERE (BitSet.h:82)

Nature of the Race

Identical to Reports 1 and 2: the BufferAllocator's isAllocated bitmap
(BitSet<256> covering 1 MiB BufferChunk regions at 4096-byte granularity)
is accessed without synchronization between:

  • the major GC marker on the main thread (reads via traceEdge() →
    isNurseryOwned() → isAllocated())
  • the nursery sweep background task on a helper thread (writes via
    sweepChunk() → setDeallocated() → setAllocated())

Both accesses are non-atomic reads/writes to the same unsigned long word,
which is undefined behaviour under the C++ memory model.


Additional Observation: JIT Path

Unlike Reports 1 and 2 where the GC was triggered from the interpreter, here
the main thread GC is triggered from the JIT path:

js::jit::InterpretResume()          ← VMFunctions.cpp:1197
  → [JIT code frame]
  → js::jit::MaybeEnterJit()       ← Jit.cpp:253

This confirms the race is not specific to interpreter execution — it occurs
regardless of whether JS code is running interpreted or JIT-compiled. Any
major GC marking slice that reaches traceEdge() or markTenuredAlloc()
while a NurserySweepTask is active can trigger the race.


Trigger Conditions

Same as Reports 1 and 2: JSON.parse string allocation fills the nursery,
triggering a minor GC that dispatches NurserySweepTask as a background task.
A subsequent major GC marking slice on the main thread then races with the
still-running sweep task.

The JIT compilation of the JSON.parse-heavy async function appears to have
made the race window slightly more likely — JIT code runs faster and can reach
the GC trigger point sooner, leaving less time for the nursery sweep to
complete before the major GC marking slice begins.


Impact

All subtests pass (7/7). TSAN aborts the process with return code -6, causing
the xpcshell test harness to report FAIL. The race is a real concurrency bug in
SpiderMonkey's GC.


Raw TSAN Report (abbreviated)

WARNING: ThreadSanitizer: data race (pid=321082)
  Read of size 8 at 0x7fdc4cb00060 by main thread:
    #0 mozilla::BitSet<256ul, unsigned long>::test(unsigned long) const
       BitSet.h:117
    #2 js::gc::AllocSpace<js::gc::BufferChunk,...>::isAllocated(void const*) const
       BufferAllocatorInternals.h:241
    #3 js::gc::SmallBufferRegion::from(void*)
       BufferAllocatorInternals.h:414
    #4 js::gc::BufferAllocator::isNurseryOwned(void*)
       BufferAllocator.cpp:808
    #6 js::gc::BufferAllocator::traceEdge(...)
       BufferAllocator.cpp:967
    #8 void js::TraceBufferEdge<js::PrivateScriptData*>(...)
       Tracer.h:364
    #9 js::BaseScript::traceChildren(JSTracer*)
       TraceMethods-inl.h:42
    #10 js::GCMarker::processMarkStackTop<0u>(...)
       Marking.cpp:1679
    #20 JS_GC(JSContext*, JS::GCReason)

  Previous write of size 8 at 0x7fdc4cb00060 by thread T24 'TaskCon~ller #0':
    #0 mozilla::BitSet<256ul, unsigned long>::Reference::operator=(bool)
       BitSet.h:82
    #1 js::gc::AllocSpace<js::gc::BufferChunk,...>::setAllocated(void*, unsigned long, bool)
       BufferAllocator.cpp:301
    #2 js::gc::AllocSpace<js::gc::BufferChunk,...>::setDeallocated(void*, unsigned long)
       BufferAllocator.cpp:311
    #3 js::gc::BufferAllocator::sweepChunk(...)
       BufferAllocator.cpp:2578
    #4 js::gc::BufferAllocator::sweepForMinorCollection()
       BufferAllocator.cpp:1232
    #5 js::NurserySweepTask::run(js::AutoLockHelperThreadState&)
       Nursery.cpp:204

SUMMARY: ThreadSanitizer: data race BitSet.h:117
  in mozilla::BitSet<256ul, unsigned long>::test(unsigned long) const

I hope the case summaries would help.

Now I created a local non-DEBUG TSAN build of C-C TB.
After running the whole IMAP xcpshell test twice (individual 350+ test runs), I got no GC-JS data race.
This suggests that the GC-JS data race is only in DEBUG build. With DEBUG build, I would have observed a few data races to be sure.
I notice there are internal checks of data structures done in DEBUG build.
I suspect some of them are not paying attention to data race issues.

I know people who use DEBUG build AND TSAN together are very small in numbers.
So fixing this issue may be a low priority.
Yet, for those people, this bug is very obnoxious and fixing this would go a long way.
I am afraid that suppressing the TSAN issue at this low-level might mask real issues.

In any case, I would see how far I can find and fix issues with non-DEBUG version.

Assignee: nobody → ishikawa
Status: NEW → ASSIGNED

Oh, regarding the atomic variable, etc., I did try to solve the GC data race issue in DEBUG build by
introducing atomic increment and decrement, etc. That is the why the atomic access is mentioned above unless there are other atomic variable access in the GC code.
See the phabricator patch. I also removed a couple of MOZ_ASSERT() that seem to reference data structure for
checking consistency, but the removal did not help.

In any case, the clean GC-JS interaction in DEBUG build will be good for debugging TSAN races in mozilla code.

EDIT: typo fixed, and atomic variable access is clarified.

Summary Case 5

I am afraid I forgot to add case 5 summary.

SpiderMonkey GC TSAN Race: Parallel Compaction Pointer Update vs DOM Worker GC (HeaderWord) — Second Instance, Different Build and Nursery Sweep Path

Summary

This is observed with DEBUG build of C-C TB.

ThreadSanitizer reports a second instance of the HeaderWord compaction data
race: a non-atomic read of HeaderWord::get() on a DOM Worker thread
running its own GC compaction phase races with an atomic write of
HeaderWord::setAtomic() by a ParallelWorker helper thread performing
parallel cell pointer updates. This is structurally identical to Report 3 but
occurs in a different build (b1cb05a7... vs 4f57c358.... I was
forced to rebuild when I needed to add a few minor tweaks and rust
package update forced me to rebuild completely) and has a
different nursery sweep dispatch path on the writer side.

Component: Core → JavaScript Engine: GC


Relationship to Report 3

Property Report 3 This report (5)
BuildId 4f57c358... b1cb05a7...
Reader thread DOM Worker T31 DOM Worker T31
Writer thread TaskCon~ller #1 T25 TaskCon~ller #1 T25
Reader path CheckTracedThing → compactPhase identical
Writer path startBackgroundFreeAfterMinorGC Nursery::sweepBuffers() → Nursery::sweep() → Nursery::doCollection()
Racy data HeaderWord at Cell.h:110 identical
Access types Non-atomic read vs atomic write identical
DOM Worker trigger ChromeWorker::Constructor → MboxRepair.worker.mjs identical

The key new information in this report is the writer's nursery dispatch path.
In Report 3 the NurserySweepTask was dispatched via
startBackgroundFreeAfterMinorGC(). Here it is dispatched via
Nursery::sweepBuffers() → Nursery::sweep() → Nursery::doCollection() →
Nursery::collect() → GCRuntime::collectNursery(), confirming that the
ParallelWorker compaction task can race with HeaderWord::get() regardless
of which nursery sweep dispatch path triggered the helper thread.


Race Location

mozilla/js/src/gc/Cell.h:110
js::gc::HeaderWord::get() const

Racy address: 0x7fba94095040 — the HeaderWord of a JSObject.


Thread 1 — DOM Worker Thread T31 (Reader — non-atomic)

A DOM Worker thread ('DOM Worker', tid=611005) is running
WorkerPrivate::GarbageCollectInternal() → JS::NonIncrementalGC(). The
worker's GC reaches the compaction phase and during updateCellPointers()
calls JSObject::traceChildren() → TraceRange<JS::Value> →
CheckTracedThing<JSObject> → JSObject::zoneFromAnyThread() →
JSObject::shape() → HeaderWord::get() — a plain non-atomic read.

Call chain (abbreviated):

WorkerPrivate::DoRunLoop()
  → WorkerPrivate::GarbageCollectInternal()   ← WorkerPrivate.cpp:6160
  → JS::NonIncrementalGC()
  → GCRuntime::gc() → collect() → gcCycle()
  → GCRuntime::incrementalSlice()             ← GC.cpp:4485
  → GCRuntime::compactPhase()                 ← Compacting.cpp:89
  → GCRuntime::updateZonePointersToRelocatedCells()
  → GCRuntime::updateAllCellPointers()
  → GCRuntime::updateCellPointers()           ← Compacting.cpp:696
  → UpdateArenaListSegmentPointers()
  → UpdateArenaPointers()
  → UpdateArenaPointersTyped<JSObject>()
  → UpdateCellPointers<JSObject>()            ← Compacting.cpp:504
  → JSObject::traceChildren()                 ← JSObject.cpp:3326
  → TraceRange<JS::Value>()
  → TraceRangeInternal<JS::Value>()
  → TraceEdgeInternal(JSTracer*, JS::Value*, ...)
  → TraceTaggedPtrEdge<JS::Value>()
  → TraceEdgeInternal(JSTracer*, JSObject**, ...)
  → CheckTracedThing<JSObject>()              ← Marking.cpp:156
  → JSObject::zoneFromAnyThread()
  → JSObject::shape()
  → CellWithTenuredGCPointer::headerPtr()
  → HeaderWord::get()                         ← TSAN REPORTS READ HERE (Cell.h:110)

The DOM Worker was created by ChromeWorker::Constructor() →
WorkerPrivate::Constructor() → RuntimeService::ScheduleWorker() —
the MboxRepair.worker.mjs ChromeWorker spawned by repairMbox(),
identical to Report 3.


Thread 2 — Helper Thread T25 TaskCon~ller #1 (Writer — atomic)

A mozilla::TaskController pool thread (T25, 'TaskCon~ller #1', tid=610992)
runs a ParallelWorker<ArenaListSegment, ArenasToUpdate> task performing
parallel cell pointer updates during GC compaction. The writer atomically
updates the JSObject's shape pointer via HeaderWord::setAtomic().

Call chain (abbreviated):

ThreadFuncPoolThread()
  → TaskController::RunPoolThread()
  → TaskController::RunTask()
  → HelperThreadTaskHandler::Run()
  → JS::RunHelperThreadTask()
  → GCParallelTask::runHelperThreadTask()
  → GCParallelTask::runTask()
  → ParallelWorker<ArenaListSegment, ArenasToUpdate>::run()  ← ParallelWork.h:54
  → UpdateArenaListSegmentPointers()
  → UpdateArenaPointers()
  → UpdateArenaPointersTyped<JSObject>()
  → UpdateCellPointers<JSObject>()            ← Compacting.cpp:504
  → JSObject::traceChildren()                 ← JSObject.cpp:3295
  → TraceCellHeaderEdge<Cell, Shape>()        ← Tracer.h:167
  → CellWithTenuredGCPointer::unbarrieredSetHeaderPtr()
  → HeaderWord::set()
  → HeaderWord::setAtomic()                   ← TSAN REPORTS WRITE HERE (Cell.h:94)

Key Difference from Report 3: Nursery Sweep Dispatch Path

In Report 3 the helper thread pool task was dispatched via:

startBackgroundFreeAfterMinorGC()
  → AutoLockHelperThreadState::~()
  → AutoHelperTaskQueue::~()
  → dispatchQueuedTasks()

In this report it is dispatched via:

Nursery::sweepBuffers()              ← Nursery.cpp:1886
  → AutoLockHelperThreadState::~()
  → AutoHelperTaskQueue::~()
  → dispatchQueuedTasks()

called from:

Nursery::sweep()                     ← Nursery.cpp:2028
  → Nursery::doCollection()          ← Nursery.cpp:1579
  → Nursery::collect()               ← Nursery.cpp:1409
  → GCRuntime::collectNursery()      ← GC.cpp:5408
  → GCRuntime::minorGC()
  → CellAllocator::RetryNurseryAlloc()

The string allocation trigger is also slightly different: here it is a
JSLinearString property name allocation during JSON.parse key parsing
(advancePropertyName() → readString() → stringToken()) rather than a
boolean value allocation, but the effect is identical — nursery fills, minor
GC fires, helper thread dispatched.

This confirms the ParallelWorker compaction race fires regardless of
which internal nursery sweep entry point dispatches the helper thread.


Nature of the Race

Identical to Report 3: two independent GC instances from two different JS
contexts (main thread and DOM Worker) operate concurrently on the same
JSObject's HeaderWord. The DOM Worker's compaction phase reads it
non-atomically (HeaderWord::get(), Cell.h:110) while the main GC's
parallel compaction worker writes it atomically (HeaderWord::setAtomic(),
Cell.h:94). Mixing atomic and non-atomic accesses to the same memory location
is undefined behaviour under the C++ memory model.


Trigger Conditions

Identical to Report 3: a ChromeWorker (MboxRepair.worker.mjs) is active
and running its own GC compaction cycle on its worker thread, while the main
thread's GC simultaneously runs its parallel compaction pointer update phase
via helper threads, and both happen to operate on the same JSObject.


Impact

TSAN aborts the process with return code -6. All subtests pass before the
abort. The race is a real concurrency bug in DEBUG-built SpiderMonkey's GC.


Raw TSAN Report (abbreviated)

WARNING: ThreadSanitizer: data race (pid=610964)
  Read of size 8 at 0x7fba94095040 by thread T31 'DOM Worker':
    #0 js::gc::HeaderWord::get() const
       Cell.h:110
    #2 JSObject::shape() const
       JSObject.h:92
    #3 JSObject::zoneFromAnyThread() const
       JSObject.h:318
    #4 void js::CheckTracedThing<JSObject>(JSTracer*, JSObject*)
       Marking.cpp:156
    #12 JSObject::traceChildren(JSTracer*)
       JSObject.cpp:3326
    #13 UpdateCellPointers<JSObject>
       Compacting.cpp:504
    #20 js::gc::GCRuntime::compactPhase(...)
       Compacting.cpp:89
    #25 JS::NonIncrementalGC(...)
    #26 mozilla::dom::WorkerPrivate::GarbageCollectInternal(...)
       WorkerPrivate.cpp:6160
    #27 mozilla::dom::WorkerPrivate::DoRunLoop(...)
       WorkerPrivate.cpp:3821

  Previous atomic write of size 8 at 0x7fba94095040 by thread T25:
    #0 js::gc::HeaderWord::setAtomic(unsigned long)
       Cell.h:94
    #3 void js::TraceCellHeaderEdge<js::gc::Cell, js::Shape>(...)
       Tracer.h:167
    #4 JSObject::traceChildren(JSTracer*)
       JSObject.cpp:3295
    #5 UpdateCellPointers<JSObject>
       Compacting.cpp:504
    #9 js::gc::ParallelWorker<ArenaListSegment, ArenasToUpdate>::run(...)
       ParallelWork.h:54

  Thread T25 created at:
    #9 js::Nursery::sweepBuffers()              ← NEW vs Report 3
       Nursery.cpp:1886
    #10 js::Nursery::sweep()
       Nursery.cpp:2028
    #11 js::Nursery::doCollection(...)
       Nursery.cpp:1579
    #12 js::Nursery::collect(...)
       Nursery.cpp:1409
    #13 js::gc::GCRuntime::collectNursery(...)
       GC.cpp:5408
    [vs Report 3: js::gc::GCRuntime::startBackgroundFreeAfterMinorGC()]

SUMMARY: ThreadSanitizer: data race Cell.h:110
  in js::gc::HeaderWord::get() const
Summary: TSAN errors found by local xpcshell-test of TSAN DEBUG version of C-C TB → GC-JS data race TSAN errors found by local xpcshell-test of TSAN DEBUG version of C-C TB
Component: General → JavaScript: GC
Product: Thunderbird → Core

We don't generally test debug builds with TSAN, only opt builds. These races are most likely caused by debug-only code reading something as part of an assertion.

(In reply to Jon Coppeard (:jonco) from comment #17)

We don't generally test debug builds with TSAN, only opt builds. These races are most likely caused by debug-only code reading something as part of an assertion.

Right. I think that is the case.

For my local debugging, where DEBUG version of C-C TB running under TSAN was indispensable to investigate TB's IMAP module data races / deadlock / missed notification due to changed timing with proper locking, I think I am going to comment out such assertion usage with #if DEBUG_gc , #endif. Then I can enjoy the merit of TSAN and DEBUG.
I needed DEBUG output from various embedded macros to compensate for the lack of documentation of IMAP cpde/
It's ironic that the assertions that would be activated during DEBUG build contribute to the TSAN data races. And I am afraid that whitelisting these may mask real issues since GC runs at such low-level. So commenting out the assertions is the only way to make TSAN useful for DEBG build.

If someone can come up with any other ideas, I will be all ears.

TIA

Blocks: GC.stability
Severity: -- → S3
Priority: -- → P3

(In reply to Jon Coppeard (:jonco) from comment #17)

We don't generally test debug builds with TSAN, only opt builds. These races are most likely caused by debug-only code reading something as part of an assertion.

Hi, the original reporter again.

I tried to rewrite the DEBUG only assertion code, but could not remove the data races after a few failed attemps.
So for the easiest often encountered data race, I inserted the following entries to
the TSAN whitelist of my addition.

race:js::gc::HeaderWord::get
race:js::gc::HeaderWord::setAtomic
race:UpdateCellPointers
race:js::SparseBitmap::readonlyThreadsafeGetBit

Note that you CANNOT add your own tsan white list file and add it to the test run right now.
I found it the hard way. |mach| ignores our locally crafted white list that we define using TSAN_OPTIONS environmental variable. See Bug Bug 2031796. |mach| basically overwrites the TSAN_OPTIONS discarding user's environmental variable setting. I showed a patch to enable user-supplied data to survive.

Anyway, I thought I could get away with the most often seen GC-JS race this way.
I was wrong.

In the last few days, I found a recurrent strange TSAN race report about WeakMap handling in GC. (I think this was masked by other GC data race.)

I carefully analyzed and, to my surprise, it seemed to be genuine.
So I instrumented what GC was doing (which thread, which action, etc.) and found
the following two bugs. They occur irrespective DEBUG-build or not.

Bug 1: JS_DISABLE_HELPER_THREADS=1 does not prevent ParallelMarkTask dispatch via XPCOM TaskController

This bug causes to run mutiple GC threads even if wanted a strict single task GC for easy debugging.

Bug 2: Data race on SlimLinkedList<WeakMapBase> node linkage during parallel marking

When a node from a WeakMap's linked list is removed, a lock is held.
However, in a linked list, when a node is removed, the predecessor's next pointer and the successor's prev pointer need to be updated. Those updates are NOT protected under a lock. (This is my understanding of reading the TSAN data race.)

Since the two bugs I mention is very focused, and the above from a latest TSAN log with very focused analysis,
I am creating a separate bugzilla for the clearly found two bugs.

If I encounter another GC data race AFTER that bug is fixed, I will come back to this bugzilla and explain any new discovery.

The GC data race issue is found during TSAN test of the thunderbird. Obviously x5 ~x20 slowdown opens the window of data race very wide and my test runs hit the issue often enough.

T

Thanks for your reports. We are not planning to fix races in debug builds because it would be too much work work and doesn't affect the product. Therefore I'm closing this bug.

Status: ASSIGNED → RESOLVED
Closed: 6 months ago
Resolution: --- → WONTFIX
You need to log in before you can comment on or make changes to this bug.

Attachment

General

Created:
Updated:
Size: