SIGSEGV on shutdown with TclOO, coroutines, namespaces, and -DPURIFY
A complex interaction between TclOO, coroutines, namespaces, and -DPURIFY can cause SIGSEGV on shutdown, not completely deterministically. The case presented below died 17 out of the last 20 runs.
Create ~/crash.tcl with contents as follows:
oo::class create class
oo::define class method yield {} {yield}
namespace eval ns {coroutine coro [class new] yield}
Build and test like so:
cd $HOME/tcl/unix
fossil clean -verily
CPPFLAGS=-DPURIFY ./configure --enable-symbols --prefix=$HOME/tcl/install
make -j`nproc` install
../install/bin/tclsh* $HOME/crash.tcl
I couldn't figure out how to reproduce this crash without -DPURIFY. Adding namespace delete ns and/or class destroy did not SIGSEGV, nor any other namespace shenanigans I could dream up. The crash happens with or without --enable-symbols, but it's great for debugging.
In addition to 8.6.15, I confirmed this fails in the latest trunk version at time of writing. I was unable to find any unaffected versions.
Using commit b688a485b2, the backtrace looks like this:
#0 0x00007ffff7f384e7 in TclOOObjectName (interp=0x40f030, oPtr=0x497) at /root/tcl/generic/tclOO.c:3118
#1 0x00007ffff7f4c831 in MethodErrorHandler (interp=0x40f030, dummy1213=0x4956b0) at /root/tcl/generic/tclOOMethod.c:1235
#2 0x00007ffff7edb740 in InterpProcNR2 (data=0x481088, interp=0x40f030, result=1) at /root/tcl/generic/tclProc.c:1876
#3 0x00007ffff7d82ead in TclNRRunCallbacks (interp=0x40f030, result=1, rootPtr=0x4a9fa0) at /root/tcl/generic/tclBasic.c:4656
#4 0x00007ffff7d8a361 in DeleteCoroutine (clientData=0x40eae0) at /root/tcl/generic/tclBasic.c:9106
#5 0x00007ffff7d81c3f in Tcl_DeleteCommandFromToken (interp=0x40f030, cmd=0x4963c0) at /root/tcl/generic/tclBasic.c:3767
#6 0x00007ffff7ebb44f in Tcl_DeleteNamespace (namespacePtr=0x4d73c0) at /root/tcl/generic/tclNamesp.c:1063
#7 0x00007ffff7ebb81d in TclDeleteNamespaceChildren (nsPtr=0x40f660) at /root/tcl/generic/tclNamesp.c:1227
#8 0x00007ffff7ebbb47 in TclTeardownNamespace (nsPtr=0x40f660) at /root/tcl/generic/tclNamesp.c:1340
#9 0x00007ffff7d7f282 in DeleteInterpProc (blockPtr=0x40f030) at /root/tcl/generic/tclBasic.c:1949
#10 0x00007ffff7ed8465 in Tcl_Release (clientData=0x40f030) at /root/tcl/generic/tclPreserve.c:229
#11 0x00007ffff7eba500 in FreeMainInterp (clientData=0x40f030) at /root/tcl/generic/tclMain.c:930
#12 0x00007ffff7e54ee1 in InvokeExitHandlers () at /root/tcl/generic/tclEvent.c:917
#13 0x00007ffff7e55048 in Tcl_Finalize () at /root/tcl/generic/tclEvent.c:1198
#14 0x00007ffff7e54f91 in Tcl_Exit (status=0) at /root/tcl/generic/tclEvent.c:973
#15 0x00007ffff7da55f8 in Tcl_ExitObjCmd (dummy981=0x0, interp=0x40f030, objc=2, objv=0x484c00) at /root/tcl/generic/tclCmdAH.c:998
#16 0x00007ffff7d82e49 in Dispatch (data=0x496108, interp=0x40f030, dummy4602=0) at /root/tcl/generic/tclBasic.c:4640
#17 0x00007ffff7d82ead in TclNRRunCallbacks (interp=0x40f030, result=0, rootPtr=0x0) at /root/tcl/generic/tclBasic.c:4656
#18 0x00007ffff7d85af7 in TclEvalObjEx (interp=0x40f030, objPtr=0x4d8560, flags=131072, invoker=0x0, word=0)
at /root/tcl/generic/tclBasic.c:6115
#19 0x00007ffff7d85a8b in Tcl_EvalObjEx (interp=0x40f030, objPtr=0x4d8560, flags=131072) at /root/tcl/generic/tclBasic.c:6096
#20 0x00007ffff7eb9dde in Tcl_MainEx (argc=-1, argv=0x7fffffffe2d8, appInitProc=0x4011c5 <Tcl_AppInit>, interp=0x40f030)
at /root/tcl/generic/tclMain.c:610
#21 0x00000000004011c5 in main (argc=2, argv=0x7fffffffe2d8) at /root/tcl/unix/tclAppInit.c:94
The SIGSEGV arises in oPtr->cachedNameObj because oPtr is garbage (0x497 in the above trace), yet MethodErrorHandler is trying to generate a nice error message. The result code (1, shown above) is due to the following in TEBCresume, which doesn't set an interpreter result (thus it is tclEmptyString):
if (iPtr->execEnvPtr->rewind) {
result = TCL_ERROR;
goto abnormalReturn;
}
This code is invoked due to DeleteCoroutine having called RewindCoroutine immediately before launching into TclNRRunCallbacks, on account of the coroutine being suspended.
I investigated further. -DPURIFY is not itself the problem, rather it causes the program to immediately crash upon use-after-free. Omitting -DPURIFY only succeeds in masking the problem. It might be possible to crash even without -DPURIFY by somehow causing allocation between the free and the use-after-free.
Curious if the problem could be triggered by child interpreters without using -DPURIFY (the answer is no), I amended the test script, while sticking with commit b688a485b2:
interp create child
child eval {
oo::class create class
oo::define class method yield {} {yield}
namespace eval ns {coroutine coro [class new] yield}
}
interp delete child
The oPtr passed to TclOOObjectName comes from mPtr->declaringClassPtr->thisPtr. Given this exact test script and Tcl version, this field is set by the 21st crossing of tclOO.c:1686 (TclOOAllocClass). When using -DPURIFY, it later gets trashed by Tcl_Free called by the 2nd crossing of tclOO.c:1384 (TclOODecrRefCount). When not using -DPURIFY, the class struct pointer is still passed to Tcl_Free, but said function does not wipe the class struct, thus its fields can be read without complaint. At least until the next allocation happens, I would imagine.
The trouble arises because the class is deallocated before the coroutine which yielded inside a class method, but the suspended coroutine cleanup then wants to include the class name in the error report. I'm not quite sure where the error report is expected to go, but it's being made because TEBCresume was instructed to resume execution of a rewound coroutine.
To see the problem, get the above-mentioned crash script and Tcl commit tree, build with --enable-symbols and either with or without -DPURIFY, then do:
cd
gdb --args tcl/install/bin/tclsh9.0 crash.tcl
start
tb tclOO.c:1686
ignore 2 20
tb tclOO.c:1384
ignore 3 1
c
p clsPtr
c
p oPtr->classPtr
n
rwatch -l oPtr->classPtr->thisPtr
c
Running the above sequence shows that oPtr->classPtr->thisPtr gets read by MethodErrorHandler despite having called TclFree(oPtr->classPtr).
Repeating, this time showing selected gdb output:
$ cd
$ gdb --args tcl/install/bin/tclsh9.0 crash.tcl
(gdb) start
Temporary breakpoint 1 at 0x401185: file /root/tcl/unix/tclAppInit.c, line 91.
(gdb) tb tclOO.c:1686
Temporary breakpoint 2 at 0x7ffff7f326d3: file /root/tcl/generic/tclOO.c, line 1686.
(gdb) ignore 2 20
Will ignore next 20 crossings of breakpoint 2.
(gdb) tb tclOO.c:1384
Temporary breakpoint 3 at 0x7ffff7f31fe1: file /root/tcl/generic/tclOO.c, line 1384.
(gdb) ignore 3 1
Will ignore next crossing of breakpoint 3.
(gdb) c
Continuing.
Temporary breakpoint 2, TclOOAllocClass (interp=0x4ac250, useThisObj=0x5880a0) at /root/tcl/generic/tclOO.c:1686
1686 clsPtr->thisPtr = useThisObj;
(gdb) p clsPtr
$1 = (Class *) 0x587ca0
(gdb) p useThisObj
$2 = (Object *) 0x5880a0
(gdb) c
Continuing.
Temporary breakpoint 3, TclOODecrRefCount (oPtr=0x5880a0) at /root/tcl/generic/tclOO.c:1384
1384 Tcl_Free(oPtr->classPtr);
(gdb) p oPtr->classPtr
$3 = (Class *) 0x587ca0
(gdb) n
(gdb) rwatch -l oPtr->classPtr->thisPtr
Hardware read watchpoint 4: -location oPtr->classPtr->thisPtr
(gdb) c
Continuing.
Hardware read watchpoint 4: -location oPtr->classPtr->thisPtr
Value = (Object *) 0x5880a0
0x00007ffff7f49da4 in MethodErrorHandler (interp=0x4ac250, dummy1213=0x54b0a0) at /root/tcl/generic/tclOOMethod.c:1231
1231 declarerPtr = mPtr->declaringClassPtr->thisPtr;
For the record, I did this test using Slackware64 15.0 plus gcc-14.2.0-x86_64-2.txz, binutils-2.43.1-x86_64-1.txz, and glibc-2.40-x86_64-5.txz from Slackware64-current.
When using -DPURIFY, here's what Valgrind 3.24.0 has to say:
$ valgrind tcl/install/bin/tclsh9.0 crash.tcl
[...]
==31924== Invalid read of size 8
==31924== at 0x4A7A80C: MethodErrorHandler (tclOOMethod.c:1231)
==31924== by 0x4A0973F: InterpProcNR2 (tclProc.c:1876)
==31924== by 0x48B0EAC: TclNRRunCallbacks (tclBasic.c:4656)
==31924== by 0x48B8360: DeleteCoroutine (tclBasic.c:9106)
==31924== by 0x48AFC3E: Tcl_DeleteCommandFromToken (tclBasic.c:3767)
==31924== by 0x49E944E: Tcl_DeleteNamespace (tclNamesp.c:1063)
==31924== by 0x49E981C: TclDeleteNamespaceChildren (tclNamesp.c:1227)
==31924== by 0x49E9B46: TclTeardownNamespace (tclNamesp.c:1340)
==31924== by 0x48AD281: DeleteInterpProc (tclBasic.c:1949) ==31924== by 0x4A06587: Tcl_EventuallyFree (tclPreserve.c:296)
==31924== by 0x48AD06F: Tcl_DeleteInterp (tclBasic.c:1837)
==31924== by 0x49B2D55: ChildObjCmdDeleteProc (tclInterp.c:2744)
==31924== Address 0x624e1a0 is 0 bytes inside a block of size 392 free'd
==31924== at 0x484B78B: free (vg_replace_malloc.c:989)
==31924== by 0x48A20DA: TclpFree (tclAlloc.c:724) ==31924== by 0x4A62E0F: TclOODecrRefCount (tclOO.c:1384) ==31924== by 0x4A61894: ObjectRenamedTrace (tclOO.c:896)
==31924== by 0x48AFEC9: CallCommandTraces (tclBasic.c:3898)
==31924== by 0x48AFAD9: Tcl_DeleteCommandFromToken (tclBasic.c:3698)
==31924== by 0x49E99A1: TclTeardownNamespace (tclNamesp.c:1299)
==31924== by 0x48AD281: DeleteInterpProc (tclBasic.c:1949)
==31924== by 0x4A06587: Tcl_EventuallyFree (tclPreserve.c:296)
==31924== by 0x48AD06F: Tcl_DeleteInterp (tclBasic.c:1837)
==31924== by 0x49B2D55: ChildObjCmdDeleteProc (tclInterp.c:2744)
==31924== by 0x48AFC3E: Tcl_DeleteCommandFromToken (tclBasic.c:3767)
==31924== Block was alloc'd at ==31924== at 0x48487C4: malloc (vg_replace_malloc.c:446) ==31924== by 0x48A20C0: TclpAlloc (tclAlloc.c:700)
==31924== by 0x48C05DF: Tcl_Alloc (tclCkalloc.c:1035)
==31924== by 0x4A634D7: TclOOAllocClass (tclOO.c:1683)
==31924== by 0x4A63ADA: TclNewObjectInstanceCommon (tclOO.c:1917)
==31924== by 0x4A63733: TclNRNewObjectInstance (tclOO.c:1818) ==31924== by 0x4A67188: TclOO_Class_Create (tclOOBasic.c:235)
==31924== by 0x4A6A261: TclOOInvokeContext (tclOOCall.c:384)
==31924== by 0x4A65E94: TclOOObjectCmdCore (tclOO.c:2837)
==31924== by 0x4A65615: PublicNRObjectCmd (tclOO.c:2594)
==31924== by 0x48B0E48: Dispatch (tclBasic.c:4640)
==31924== by 0x48B0EAC: TclNRRunCallbacks (tclBasic.c:4656)
[...]
Without -DPURIFY, Valgrind does not notice the issue and thinks all is well.
I came up with a script that crashes Tcl without using namespaces, interpreters, or -DPURIFY, making this a more serious issue:
oo::class create class
oo::define class method yield {} {yield}
coroutine coro [class new] yield
trace add command coro delete {apply {{args} {lrepeat 0}}}
class destroy
rename coro {}
Despite the class being destroyed, the coroutine remains suspended within the method, until the coroutine itself is forcibly destroyed, at which point the bogus error message is generated. However, the trace on coroutine command destruction forces an allocation to occur between the free and the use-after-free, stomping on the freed class struct, thereby causing the error message generation to crash.
This crash can happen within a safe interpreter:
interp create -safe child
child eval {
... the above script ...
}
By the way, I apologize for the formatting error in the prior comment, no way to edit it now. If the Valgrind listing is messed up, just narrow your browser window until it wraps nicely.
I can reproduce it with 8.6+ without any trace...
Thread 1 received signal SIGSEGV, Segmentation fault.
0x00007ffd56430aa6 in TclOOObjectName (interp=0xda8270, oPtr=0xfeeefeeefeeefeee) at ./generic/tclOO.c:2937
2937 if (oPtr->cachedNameObj) {
(gdb) where
#0 0x00007ffd56430aa6 in TclOOObjectName (interp=0xda8270, oPtr=0xfeeefeeefeeefeee) at ./generic/tclOO.c:2937
#1 0x00007ffd56440e78 in MethodErrorHandler (interp=0xda8270, methodNameObj=0x25dd990) at ./generic/tclOOMethod.c:1162
#2 0x00007ffd564592c9 in InterpProcNR2 (data=0x2633168, interp=0xda8270, result=1) at ./generic/tclProc.c:1874
#3 0x00007ffd562ffb65 in TclNRRunCallbacks (interp=0xda8270, result=1, rootPtr=0x2648e40) at ./generic/tclBasic.c:4541
#4 0x00007ffd56306494 in DeleteCoroutine (clientData=0x2646b20) at ./generic/tclBasic.c:8743
mPtr->declaringClassPtr shows indeed deleted object... The reason for that is, there is no cross reference between methods and instances (probably to avoid cyclic refs), and the instance doesn't get reset if class or object gets deleted in case of the method remains due to its ref-counter, neither in TclOODelMethodRef (nor in its caller).
I've already fixed it, it's coming soon.
The last finding should be fixed in [66717314ae3c81c4] (branch bug-0b809cd3fc8b6e5e-sf-by-del-oo-in-coro), see also new test "oo-1.25"...
Reviews are welcome. Please test the rest of the ticket got fixed likewise (I think so, since the call-stack is the same).
First I reproduced the crash with all four of my test scripts, as well as oo-1.25. Next I built your branch, both with and without -DPURIFY, and confirmed my test scripts and oo-1.25 no longer crash. Looks good, thank you. I eagerly await a release with this fix included, in fact am considering immediately applying it as a patch on top of my enterprise deployment.
As for you being able to crash without using trace, your compiler environment must be different than mine, to automatically overwrite freed memory with 0xfeee. That's quite helpful to find use-after-free.
Probably a topic for another day, but I'm still curious about the need to generate an error message when rewinding a coroutine, given that the error message is at risk of accessing partially dismantled data and has nowhere to go anyway.
Thanks for the test and confirmation.
I eagerly await a release with this fix included
Don is preparing the release 8.6.16 right now, but I'm unsure whether this fix is not too raw for the merge to it (however I would have included it, since it fixes a memory overwriting with a potential for BO, or even RCE-attack due to predictable matter).
@dgp, @dkf, @TCT any thoughts?
your compiler environment must be different than mine, to automatically overwrite freed memory with
0xfeee.
It is not the env, it was build with --enable-symbols=mem (tcl uses it's own memory manager and without that config-option a use-after-free is hard to reproduce.
the need to generate an error message when rewinding a coroutine ...
It has basically nothing to do with the coro, it was just an after effect of binding the method (without the object/class) to NRE-data or the callFrame, what were also affected by different approaches in the same way, even without NRE or coros (e. g. if the method would be referenced within an event or some callback or other callFrames, like lambda or proc args etc).
Anyway the patch made minimal invasive, without to touch regular cases producing errors via MethodErrorHandler, see for instance test oo-7.7.
No real brainpower to apply to this today (I'll comment more once I've slept!) but --enable-symbols=mem helps a lot with finding dodgy accesses (at quite a speed penalty, though not as severe as a full purify/efence run).
The proposed fix looks likely to be correct (it looks like it is addressing the right sort of things and the fields it is blanking are indeed non-owning pointers so it's a relevant way forward), though the test could do with a bit more work. In particular, I'd love to see the error message actually demonstrated and caught so that we can know for sure that we're getting the right behaviour.
Thx for review...
I'd love to see the error message actually demonstrated
You cannot get the error message using exactly this approach, because it was never intended in tcl to handle an error by jumping back to the callee-coro after yield (what basically happens) and therefore the error is simply swallowed somewhere around NRE-trampoline.
To reproduce the raising of error with some different approach, one has to bound the method somewhere (without object or class) and cause a class destroy inside of the chain without immediate epoch increment (caused a recompile/reresolve), otherwise one'd get another errors either like "method without declarer", "invalid command name", etc by resolving of the method or object command.
I'm not so familiar with the tclOO to construct such test (without to create some C-command in test-suite), but may be you were able to do this.
Anyway, I merged the fix for now as it is, better tests can be added later.
Note there is a small amend [dfba47d117ed3e67], otherwise the fix instead of segfault could cause panic "method not declared" in constructor/destructor in case the instance get abrupt deleted there...
Now all 3 handlers use common generic logic (with a code deduplication).