TclOO + coroutine + event loop = coredump
# behavior observed with Tcl 8.6.11, 8.6.12 on various Linuxes
#
# the following program coredumps when looking after the frame information
#
# at least 2 instances needed for coredump
set nworkers 2
set nrounds 1
proc main {} {
global nworkers
for {set n 1} {$n <= $nworkers} {incr n} {A create a$n; a$n schedule}
after 5000 {puts STOPPING;variable forever false}
variable forever true
vwait forever
return 0
}
oo::class create A {
method schedule {} {
set coro ::coro-[string trim [self] :]
if {[llength [info commands $coro]] == 0} {
coroutine $coro my Work
}
}
method Work {} {
after 0 [info coroutine]; yield
global nrounds
while {[incr rounds] <= $nrounds} {
after 1000 [info coroutine]; yield
}
my dump-frames
# with "after 0 [self] dump-frames" there is no coredump
}
method dump-frames {} {
puts "[self] INFO FRAME=[info frame]"
for {set i 1} {$i < [info frame]} {incr i} {
puts [format "\t%2d: %s" $i [info frame $i]]
}
}
}
exit [main]
# a backtrace with gdb
#
#0 0x00007fd15d493553 in TclInfoFrame () from /usr/lib/libtcl8.6.so
#1 0x00007fd15d493e04 in InfoFrameCmd () from /usr/lib/libtcl8.6.so
#2 0x00007fd15d481d37 in TclNRRunCallbacks () from /usr/lib/libtcl8.6.so
#3 0x00007fd15d563ed0 in AfterProc () from /usr/lib/libtcl8.6.so
#4 0x00007fd15d5641cd in TimerHandlerEventProc () from /usr/lib/libtcl8.6.so
#5 0x00007fd15d544417 in Tcl_ServiceEvent () from /usr/lib/libtcl8.6.so
#6 0x00007fd15d544719 in Tcl_DoOneEvent () from /usr/lib/libtcl8.6.so
#7 0x00007fd15d5085d6 in Tcl_VwaitObjCmd () from /usr/lib/libtcl8.6.so
#8 0x00007fd15d481d37 in TclNRRunCallbacks () from /usr/lib/libtcl8.6.so
#9 0x00007fd15d483eb0 in TclEvalEx () from /usr/lib/libtcl8.6.so
#10 0x00007fd15d54ac12 in TclSubstTokens () from /usr/lib/libtcl8.6.so
#11 0x00007fd15d483882 in TclEvalEx () from /usr/lib/libtcl8.6.so
#12 0x00007fd15d53790f in Tcl_FSEvalFileEx () from /usr/lib/libtcl8.6.so
#13 0x00007fd15d53ee9f in Tcl_MainEx () from /usr/lib/libtcl8.6.so
#14 0x00000000004007a4 in main ()
# with a Tcl compiled with --enable-symbol, gdb tells me
#
#0 0x00007fe82e55c4a5 in TclInfoFrame (interp=0x1ac85b0, framePtr=0x24193f8) at /home/an/build/tcl8.6.12/generic/tclCmdIL.c:1392
1392 Tcl_HashEntry *namePtr = procPtr->cmdPtr->hPtr;
#
# here, the procPtr->cmdPtr happens to be NULL
d66179d380Merge [db8bfb98f1810b15]: Proper fix for [87271f7cd6]. Structures relating to [info frame] in a method now have the correct lifetime. check-in2024-08-28 16:44:1956673bfe22Merge [ee33b4b9230bd4de]: Apply emergency workaround for [87271f7cd6]; not fixed yet, but no longer crashes. check-in2024-08-28 16:43:398fb7f1d640Closed ticket [624786283e]: [info frame] crash plus 7 other changes ticket2024-05-23 10:56:35db8bfb98f1Proper fix for [87271f7cd6]. Structures relating to [info frame] in a method now have the correct lifetime. check-in2024-05-17 13:48:15612af6e7d6Proper fix for [87271f7cd6]. Structures relating to [info frame] in a method now have the correct lifetime. check-in2024-05-17 13:45:50371e968debProper fix for [87271f7cd6]. Structures relating to [info frame] in a method now have the correct lifetime. check-in2024-05-17 13:43:40ee33b4b923Apply emergency workaround for [87271f7cd6]; not fixed yet, but no longer crashes check-in2024-05-16 15:55:519208e56d48Apply emergency workaround for [87271f7cd6]; not fixed yet, but no longer crashes check-in2024-05-16 15:55:2803f0a26c4fApply emergency workaround for [87271f7cd6]; not fixed yet, but no longer crashes check-in2024-05-16 15:53:29bc5bf9b73eTest that hits [87271f7cd6] reasonably precisely check-in2024-05-16 15:38:08
Can confirm that the problem was also there in 8.6.4 (which is what I happen to have on this machine).
Output from the program is this:
::a1 INFO FRAME=5
1: type eval line 1 cmd main level 2
2: type proc line 6 cmd {vwait forever} proc ::main
3: type eval line 1 cmd ::coro-a1 proc ::main
4: type proc line 7 cmd {my dump-frames} method Work class ::A level 1
::a2 INFO FRAME=5
1: type eval line 1 cmd main level 2
2: type proc line 6 cmd {vwait forever} proc ::main
3: type eval line 1 cmd ::coro-a2 proc ::main
Note the missing frame 4 for the second trace.
Turning dump-frames into an ordinary procedure (and doing the obvious adjustment to the call site) also crashes with an almost identical trace of printed messages:
proc dump-frames {} {
puts "[uplevel self] INFO FRAME=[info frame]"
for {set i 1} {$i < [info frame]} {incr i} {
puts [format "\t%2d: %s" $i [info frame $i]]
}
}
I conclude that the crash is not dependent on the current stack frame being a method stack frame.
The immediate crash appears to be caused by a Proc without a reference to a Command. That should only be possible if the command has been deleted.
I think there will be two parts to this fix:
- Making the code not crash by only running that code stanza below there if both
procPtrandprocPtr->cmdPtrare valid. (This is needed because it is possible for code to be running while a procedure is being deleted; the information extractable will be of mixed quality, but that's better than a crash.) - Working out why the
procPtr->cmdPtris NULL there; it shouldn't be because it is running at a stage when nothing on the stack is actually dead!
I've just found a bug that I can reproduce on 8.6.2 (Win32) with the code below. It involves yielding a coroutine in a method, then doing an info frame that introspects the method. I came across this ticket while looking for known issues, and I think there's a chance it is another symptom of the same problem.
oo::class create LogDies {
method process {args} {
puts "[info coroutine] Starting"
set randMs [expr { 1050 + int([tcl::mathfunc::rand] * 1000) }]
after $randMs [info coroutine] ; yield
puts "[info coroutine] Back from yield $randMs ms"
info frame 0
#or: apply {{} { info frame -1 }}
}
}
set obj [LogDies new]
time { coroutine c[incr ctr] $obj process a1 a2 } 100
- I can confirm that the code to reproduce this ticket causes an Access Violation (0xc0000005) fault on 8.6.2 (Win32).
- My code above reproduces a bug probabilistically, not deterministically. I suspect there is a more concise deterministic reproduction (working on it, and on testing with a more recent build).
- Wildly guessing based on dfk's comment (2022-06-28 12:04), doesn't a coroutine delete its Command while it is running?
- Re how a method stack frame is involved: in my case it is the attempt to introspect the method stack frame that causes the process to die. I don't get a fault if I use
apply {{} { apply {{} { info frame -1}} }}orinfo frame -1within the method.
This bug exists in 9.0 as well. Below is the diagnosis. This is my first look at the tcloo implementation so caveat emptor! Apologies for the length. It is to keep things straight in my own head as to what is going on.
When a oo method is created, a ProcedureMethod structure is allocated and
initialized (pmPtr in the analysis below). A Proc structure containing the arg
definitions, byte code etc. hangs off the procPtr field in the structure.
Crucially, the procPtr->cmdPtr is (by design) set to NULL and is populated
when the method is actually called. Note this datum is part of the per-method
"static" data (not on stack) and that is an obvious problem as recursive
calls will overwrite the value. More on this below.
When the method is called (InvokeProcedureMethod), a PMFrameData struct is
allocated on the Tcl stack. There are two fields relevant to this bug. The first
is the cmd field which is a Command struct. On a method call, this struct
is filled out, as the comment in the code
states, with mostly bogus values, the valid ones being the ones
(afaict) that are needed to describe the frame. The procPtr->cmdPtr field
above (part of the per-method data) is then set to point to this field.
The issue with the procPtr field being part of the method data and not on any
stack resulted in the crash on recursive calls as reported in bug [3001438].
Fixing this introduced the second relevant field in PMFrameData - oldCmdPtr.
On a method call, the current value stored in the method data
pmPtr->procPtr->cmdPtr field is stored in the oldCmdPtr field and
pmPtr->procPtr->cmdPtr is updated to point to the "dummy" PMFrameData.cmd
field before the actual method evaluation. After the method evaluation,
the reverse happens with pmPtr->procPtr->cmdPtr being restored from
oldCmdPtr to its original value at the time of the method invocation.
Essentially a linked stack.
This solved the [3001438] recursive call crash resulting from nested
calls. However, in the current bug report, the calls are not nested, but
interleaved via coroutines resulting in interference between two
concurrently executing method calls. The restoration of cmdPtr during
the return from the first coroutine call overwrites the cmdPtr placed in the
ProcedureMethod structure at the start of invocation of the second coroutine.
(Remember the second coroutine is still in execution state)
Since the original cmdPtr at method definition time is NULL, the invocation
from the second coroutine results in a NULL pointer access.
The sequence is illustrated after the test code below. The code is slightly simplified from the original with unnecessary fragments removed.
# at least 2 instances needed for coredump
set nworkers 2
set nrounds 1
proc main {} {
global nworkers
for {set n 1} {$n <= $nworkers} {incr n} {
A create a$n
puts "a$n namespace [info object namespace a$n]"
a$n schedule
}
after 5000 {puts STOPPING;variable forever false}
variable forever true
puts vwaiting
vwait forever
return 0
}
oo::class create A {
method schedule {} {
puts "[self] schedule Enter"
set coro ::coro-[string trim [self] :]
if {[llength [info commands $coro]] == 0} {
coroutine $coro my Work
}
puts "[self] schedule Exit"
}
method Work {} {
puts "[self] Work Enter"
after 0 [info coroutine]
puts "[self] Work yielding"
yield
puts "[self] Work back from yield"
global nrounds
puts "[self] calling dump"
dump
# with "after 0 [self] dump-frames" there is no coredump
puts "[self] Work Exit"
}
}
proc dump {} {
puts "INFO FRAME=[info frame]"
for {set i 1} {$i < [info frame]} {incr i} {
puts [format "\t%2d: %s" $i [info frame $i]]
}
}
main
This results in the following sequence resulting in the cmdPtr being NULL
(a1 and a2 are the two objects created)
a1 is created. At this time the pmPtr->procPtr->cmdPtr corresponding to a1.Work is initialized to NULL.
a1.Work is called (from a1.schedule). The current value of pmPtr->procPtr->cmdPtr (which is NULL from the method definition time) is saved to fdPtr->oldCmdPtr and a new value &fdPtr->cmd is assigned to it (the "bogus" or "dummy" Command struct).
a1.Work arranges for itself to be called back through the event loop and then yields back to a1.schedule which returns.
a2 is created.
Steps 2 and 3 are repeated but for a2. Note however that pmPtr->procPtr->cmdPtr is not NULL here, it holds the value from the a1.Work call! This is not consistent but will ignore for the moment because it is not the cause of the crash.
Calls unwind to the main thread which enters a vwait loop. Now the fun begins.
a1.Work returns from the yield (via the coroutine call from the event loop). It dumps the trace information. Then during method exit, it restores what it saved in its fdPtr->oldCmdPtr back into pmPtr->procPtr->cmdPtr! Note the latter is method data and shared with the invocation of a2.Word. Moreover, the value of
oldCmdPtr(from step 2) is NULL. Control is now returned back to the event loop.a2.Work now returns from its yield (again via from the event loop). It too calls dump. But now, the pmPtr->procPtr->cmdPtr value it set up in its call initialization has been overwritten by NULL as part of a1.Work exit in step 7.
Crash in TclInfoFrame on attempt to access pmPtr->procPtr->cmdPtr.
Above is easily corroborated with a few puts in the test case.
Fixing the specific crash as dkf mentioned in an earlier post, could be
Just check for the NULL pointer in TclInfoFrame and ignore the frame or do some default. Aside from very much being a band aid and not palatable, I do not know the repercussions on users of info frame.
Fix the core issue. DKF or someone with better knowledge of the oo implementation than me (everything I know is up above!) will have to do (2). I'm likely to introduce more bugs than I fix.
Although info frame itself may or may not be important, I'm more worried about
possibly more serious implications of interleaved oo method calls from different
coroutines getting tangled up.
TL;DR for my previous long post. Calls to a oo method that yields from two coroutines results in interleaved execution leading to a crash.
Assigned to dkf as I think I've diagnosed the issue but am too unfamiliar with the implementation to provide a fix.
Sorry, forgot to include the output ``` make -s valgrind TESTFLAGS="-f ioCmd.test -match iocmd-32.3" ... ==52905== 6,728 (264 direct, 6,464 indirect) bytes in 1 blocks are definitely lost in loss record 115 of 115 ==52905== at 0x484280F: malloc (vg_replace_malloc.c:442) ==52905== by 0x4894FA5: TclpAlloc (tclAlloc.c:699) ==52905== by 0x48AE1C9: Tcl_Alloc (tclCkalloc.c:1059) ==52905== by 0x49A2745: Tcl_CreateChannel (tclIO.c:1630) ==52905== by 0x49B332E: TclChanCreateObjCmd (tclIORChan.c:665) ==52905== by 0x48A0C55: Dispatch (tclBasic.c:4503) ==52905== by 0x48A0CDB: TclNRRunCallbacks (tclBasic.c:4539) ==52905== by 0x48A0594: Tcl_EvalObjv (tclBasic.c:4262) ==52905== by 0x48A2A7D: TclEvalEx (tclBasic.c:5408) ==52905== by 0x49BE690: Tcl_FSEvalFileEx (tclIOUtil.c:1821) ==52905== by 0x49C99AB: Tcl_MainEx (tclMain.c:403) ==52905== by 0x4012F4: main (tclAppInit.c:91) ==52905== ==52905== LEAK SUMMARY: ==52905== definitely lost: 264 bytes in 1 blocks ==52905== indirectly lost: 6,464 bytes in 131 blocks ==52905== possibly lost: 0 bytes in 0 blocks ==52905== still reachable: 0 bytes in 0 blocks ==52905== suppressed: 0 bytes in 0 blocks ==52905== ```
Oops posted a stack for the wrong ticket. Please ignore previous post :-(
The band-aid fix:
Index: generic/tclCmdIL.c
==================================================================
--- generic/tclCmdIL.c
+++ generic/tclCmdIL.c
@@ -1380,11 +1380,11 @@
/*
* 'proc'. Common to all frame types. Conditional on having an associated
* Procedure CallFrame.
*/
- if (procPtr != NULL) {
+ if (procPtr != NULL && procPtr->cmdPtr != NULL) {
Tcl_HashEntry *namePtr = procPtr->cmdPtr->hPtr;
if (namePtr) {
Tcl_Obj *procNameObj;
The problem is I'm not sure how to fix this properly. (You can also detect whether framePtr->framePtr->isProcCallFrame & FRAME_IS_METHOD is true, but that activates in more cases; the test suite picks that up.) In particular, should the info frame call report the declaration object/class or the call object/class? That's a critical difference when dealing with subclassing...
See bug-87271f7cd6 for work on fixing this. So far, got things boiled down to a test.
Good news everybody!
It now just gives the wrong answers from info frame in the problem case. That's definitely better than reading off a NULL, but will need better fixing. The problem is we need to have the nsPtr of the cmdPtr point to the instance namespace while we build the bytecode (and possibly later) so it doesn't fit with exactly the same lifetime as the method itself.
I knew there was a reason I did things this complicated way. There's a bunch of awful assumptions that are all tangled together...
There are other cases were info frame falls down similarly. I already had a branch apn-info-frame to avoid the crash in this ticket and the others (via invokehidden and when an extension directly calls via the Tcl_CmdInfo.objProc field) My opinion is that irrespective of whether the bugs can be individually fixed, the info frame code should protect itself when the calling context has not set up a proper frame (of course only possible to detect when the frame pointer is NULL). I will try to propose something on tcl-core this weekend.
It turns out that all the stuff relating to the Command and the ExtraFrameInfo can be held in the ProcedureMethod; the lifespan is right and we don't use that Command to communicate the compilation context namespace to the bytecode compiler (procedures do use that, but we pass that as a direct argument). Doing that means that we don't need to initialise things so often (provided we take care when we clone a class or object) and allows us to avoid entirely keeping a linked stack of PMFrameDatas that need to be put back correctly, and that lets us avoid a bunch of bugs and crashes (including this one!).
There's one down-side: the ProcedureMethod structure size changes. I believe that nobody but TclOO itself should ever know the size of that structure (let alone allocate one!) so it's not a problem, but I don't know if Itcl is playing tricks.
The other cases with info frame and invokehidden and so on are out of scope of this bug. We're now setting the record data correctly using structures that have the correct lifetime so whatever the problems now are, they're outside of TclOO.
BTW,
THANK YOU!
for the test case, it was tremendously helpful.
> There's one down-side: the `ProcedureMethod` structure size changes. I believe that nobody but TclOO itself should ever know the size of that structure (let alone allocate one!) so it's not a problem, but I don't know if Itcl is playing tricks.
https://core.tcl-lang.org/itcl/file?ln=205-207&ci=aa224f01ddc2f3bf&name=generic%2Fitcl2TclOO.c
:-(
Possible solution: increment TCLOO_PROCEDURE_METHOD_VERSION from 0 to 1. Then - in Tcl - if the version is 0, don't use the additional fields
Looking further, Itcl uses this structure to pass some info to its (internal) Tcl_InvokeClassProcedureMethod, which only uses the fields it knowns off. It never passes the structure back to Tcl. So I don't think it's a problem.
Phew....
We can bump TCLOO_PROCEDURE_METHOD_VERSION, but we need all the fields; they contain structures that have to be there for the bytecode compiler to work and that have to have a lifespan the same as the method. The fix to this bug was (at its heart) to put those fields in the ProcedureMethod structure rather than trying to hang them off the side with a different lifespan.
All the mess that was in there was originally there because I was trying to figure out how to graft TclOO onto the back-end of procedures, which was complicated because TclOO needs to control the current namespace in a different way. I then later bit the bullet and split the guts of the procedure bytecode compiler so that I could pass the things I needed to directly; the Command structure then just became a way for communicating with [info frame]... but never had that complicated management for handling varying namespaces removed. It didn't matter except when [info frame] was mixed with coroutines to mess up the unstacking of contexts.
Sounds like Itcl will need to recompile. And we might need to bump the TclOO version number to let them detect. There really isn't a way around the fact that we had to grow the structure.
> Sounds like Itcl will need to recompile
(Did you read my "Looking further ..."?)
I don't think Itcl will need to be recompiled. Yes, it will allocate a partial structure, but it won't address any of the extended fields. So, no problem. (Phew...., again)
Fixed by dkf in [371e968deb8f119e].