sclang: use-after-free of Frames — returnFromBlock() frees a frame still referenced by a live frame's `caller` (GC heap corruption, random crashes)

Author: marcelastrapiCreated Sep 15, 2026Updated Sep 15, 2026
Labelsbugcomp: sclangcrash

Environment

  • SuperCollider version: 3.14.1 (Arch Linux package supercollider 3.14.1-6; PyrMessage.cpp and GC.cpp are identical to tag Version-3.14.1). The code involved is unchanged on develop (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:

supercollider
(
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

  1. returnFromBlock() frees the frame of a function that does not need a heap context (PyrMessage.cpp#L567-L571, same code on develop):
    cpp
    if (!methraw->needsHeapContext) {
        g->gc->Free(curframe);
    } else {
        SetInt(&curframe->caller, 0);
    }
  2. returnFromMethod() clears caller on the frames it leaves, except the home frame of a method that needs a heap context (PyrMessage.cpp#L676-L681, same code on develop):
    cpp
    if (!methraw->needsHeapContext) {
        SetInt(&tempFrame->caller, 0);
    } else {
        if (tempFrame != homeContext)
            SetInt(&tempFrame->caller, 0);
    }
  3. Put together: a function F that creates no closure calls a method M whose frame is captured by a closure that outlives the call (a GUI action, a callback, a returned function…). M returns and keeps caller = F's frame. Then F returns and its frame is Free()d. M's frame is still reachable through the closure, so its caller slot 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 UserView drawFunc: PyrGC::ScanSlots ← ScanOneObj ← Collect ← New ← prObjectCopySeries. It segfaulted while relinking an "object" whose prev/next were float slot data. mWhiteColor was 0 at that moment, so zeroed memory looked white.
  • Crash 2, SystemClock thread: PyrGC::Allocate with mFree == nullptr for size class 2, ← newPyrString ← prObjectString.
What the heaps in the two core files show

I walked the GC object lists in both cores and checked every object slot.

  • Crash 1: the object being scanned is a finished magResponse2 frame (a drawFunc helper method). Its only referrer is an IdentityDictionary whose array slot points to that frame. That dictionary is only referenced by an already-returned Dictionary:keysValuesDo frame (caller == 0). That frame's only referrer is the caller slot of my buildBody method frame, which the view-action closures keep alive; buildBody was called from the deferred function shown above. So the chain is: dangling caller → memory reused by an unrelated frame → its dictionary's array (freed, then reused by another frame) → that frame's freqs argument (pointing inside a freed and reused Array) → segfault.
  • Frames whose caller slot 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:doSend frame whose caller is an Array;
    • crash 2: 4 of 3,586 frames, again including SynthDef:doSend, and one frame whose caller is a freed Frame.
  • 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't Free() a frame that has been used as caller by a frame whose method needs a heap context. For example, mark the calling frame in createFrameForExecuteMethod() (PyrMessage.cpp#L496-L514), and for a marked frame only clear its caller, leaving the frame to the GC.
  • Or don't leave a raw pointer in the caller of 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 on develop after #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 !

crash1-backtrace.txt

crash2-backtrace.txt

Source: supercollider/supercollider