sclang: use-after-free of Frames — returnFromBlock() frees a frame still referenced by a live frame's `caller` (GC heap corruption, random crashes)
Environment
- SuperCollider version: 3.14.1 (Arch Linux package
supercollider 3.14.1-6;PyrMessage.cppandGC.cppare identical to tagVersion-3.14.1). The code involved is unchanged ondevelop(a332bbb). - Operating system: Arch Linux, x86_64 (kernel 6.18-rt)
- Other details (Qt version, audio driver, etc.): Qt 6.11.2. The reproducer below needs no server, no GUI and no extensions (also tested with an empty user config and extensions directory).
Steps to reproduce
Run this in a freshly started interpreter:
(
var f = { 42 }, escaped, check;
// Calls a class-library method whose frame outlives the call: Function:inEnvir returns a
// closure over its own frame. This function creates no closure itself, so its FunctionDef
// has needsHeapContext == false and returnFromBlock() frees its frame when it returns.
var noClosure = { escaped = f.inEnvir; nil };
// Identical, plus an unused inner closure over a local variable: needsHeapContext == true,
// so returnFromBlock() leaves this frame to the garbage collector.
var withClosure = { var x; escaped = f.inEnvir; { x }; nil };
check = { |label, callingFunction|
var frame, caller, arrays = Array.new(64), i = 0;
callingFunction.value;
frame = escaped.instVarAt(1); // Function.context = the Function:inEnvir frame, kept alive by the closure
// allocate small Arrays (same GC size class as the freed frame) without calling any function
while { i < 64 } { arrays.add(Array.new(6)); i = i + 1 };
caller = frame.instVarAt(1); // slot 1 of a Frame = caller
"% -> caller slot of the live Function:inEnvir frame holds: % %".format(label, caller.class,
if(caller.isKindOf(Frame) and: { caller.instVarAt(0) === callingFunction.def }) {
"(the calling function's frame: OK)"
} {
"(NOT the calling function's frame: dangling pointer)"
}
).postln;
};
check.("withClosure", withClosure);
check.("noClosure ", noClosure);
)Output (the same in 3 runs out of 3):
withClosure -> caller slot of the live Function:inEnvir frame holds: Frame (the calling function's frame: OK)
noClosure -> caller slot of the live Function:inEnvir frame holds: Array (NOT the calling function's frame: dangling pointer)instVarAt is only used to observe the slot. The bug does not depend on it: the garbage collector scans that slot on its own (see below).
Expected vs. actual behavior
Expected: a frame that is still reachable (here kept alive by the closure returned by Function:inEnvir) never points to freed memory. Its caller slot is either a valid frame or cleared.
Actual: when the calling function's FunctionDef has needsHeapContext == false, its frame is freed on return while the surviving frame still points to it through caller. The memory is reused right away (here by one of the Arrays), so a live frame ends up pointing to an unrelated object.
Cause
returnFromBlock()frees the frame of a function that does not need a heap context (PyrMessage.cpp#L567-L571, same code on develop):if (!methraw->needsHeapContext) { g->gc->Free(curframe); } else { SetInt(&curframe->caller, 0); }returnFromMethod()clearscalleron the frames it leaves, except the home frame of a method that needs a heap context (PyrMessage.cpp#L676-L681, same code on develop):if (!methraw->needsHeapContext) { SetInt(&tempFrame->caller, 0); } else { if (tempFrame != homeContext) SetInt(&tempFrame->caller, 0); }- Put together: a function
Fthat creates no closure calls a methodMwhose frame is captured by a closure that outlives the call (a GUI action, a callback, a returned function…).Mreturns and keepscaller=F's frame. ThenFreturns and its frame isFree()d.M's frame is still reachable through the closure, so itscallerslot is now a dangling pointer, and the GC keeps scanning it.
Kernel.sc already acknowledges part of this (Kernel.sc#L612-L614): "since some Frames are deleted instead of garbage collected, it is too dangerous to allow access to them. Dangling pointers could result." sclang hides Frames for that reason, but PyrGC itself still follows caller.
Consequences: random crashes
Once the address is reused, the GC traces whatever object lives there now. It keeps dead objects alive and follows their stale slots. When a stale object's gc_color happens to equal the current white color, ScanSlots() relinks it into the grey list (GC.cpp#L164-L187). From then on the treadmill is corrupted, and sclang crashes later in unrelated code, which makes the crashes look random.
I got two SIGSEGVs ten minutes apart during a GUI-heavy session. In my own classes, a step-sequencer view rebuilds itself with { ...; this.buildBody; ... }.defer, where buildBody creates the view actions. Backtraces (gdb + eu-stack, all threads) are attached: crash1-backtrace.txt, crash2-backtrace.txt.
- Crash 1, main thread, inside a
UserViewdrawFunc:PyrGC::ScanSlots←ScanOneObj←Collect←New←prObjectCopySeries. It segfaulted while relinking an "object" whoseprev/nextwere float slot data.mWhiteColorwas0at that moment, so zeroed memory looked white. - Crash 2, SystemClock thread:
PyrGC::AllocatewithmFree == nullptrfor size class 2, ←newPyrString←prObjectString.
I walked the GC object lists in both cores and checked every object slot.
- Crash 1: the object being scanned is a finished
magResponse2frame (adrawFunchelper method). Its only referrer is anIdentityDictionarywhosearrayslot points to that frame. That dictionary is only referenced by an already-returnedDictionary:keysValuesDoframe (caller == 0). That frame's only referrer is thecallerslot of mybuildBodymethod frame, which the view-action closures keep alive;buildBodywas called from the deferred function shown above. So the chain is: danglingcaller→ memory reused by an unrelated frame → its dictionary'sarray(freed, then reused by another frame) → that frame'sfreqsargument (pointing inside a freed and reusedArray) → segfault. - Frames whose
callerslot is not a live frame (this check cannot detect callers recycled as other frames, so these are lower bounds):- crash 1: 2 of 5,966 frames, including a
SynthDef:doSendframe whosecalleris anArray; - crash 2: 4 of 3,586 frames, again including
SynthDef:doSend, and one frame whosecalleris a freedFrame.
- crash 1: 2 of 5,966 frames, including a
- Crash 1 is fully explained by this bug. Crash 2 has the same dangling callers, but the routine running in that thread also had 977 values left on its 2048-slot stack with only 13 active frames, which looks like #7448. So I cannot attribute crash 2 to this bug alone.
- I could not write a short script that crashes plain sclang. In a 110 s stress loop the freed frames were reused within milliseconds, so the stale pointers kept aliasing valid objects. The real crashes needed long-lived closures and many GC cycles.
Possible directions
I don't know the interpreter well, so these are only suggestions:
- In
returnFromBlock(), don'tFree()a frame that has been used ascallerby a frame whose method needs a heap context. For example, mark the calling frame increateFrameForExecuteMethod()(PyrMessage.cpp#L496-L514), and for a marked frame only clear itscaller, leaving the frame to the GC. - Or don't leave a raw pointer in the
callerof a home frame that has already returned. It seems to be kept for the out-of-context^check; a marker that is not a pointer could replace it.
Simply never freeing these frames would probably also require allocating them with inAccount = true (NewFrame). Otherwise a tight loop could pile up frames without ever triggering a collection.
Related
- #7448 / #7449: non-local returns leave values on the stack. That is a different mechanism in the same function (
returnFromMethod); the lines quoted above are unchanged ondevelopafter #7449. - #6261, #7133: other GC fixes (scan counter overflow, collecting inside primitives).
Before posting, I searched open and closed issues and PRs for returnFromBlock, needsHeapContext, outOfContextReturn, freed or dangling frames, and use-after-free, and found nothing about this.
This analysis (core dump inspection, reading the interpreter source) was done with the help of an AI assistant (Claude). I don't undersand what it did, but I suppose you will...
I just want to add a big thanks for creating a such fun project, supercollider is so awsome !
Source: supercollider/supercollider