Skip to content
Tcl Source Code View Ticket
Login

View Ticket

segfault compiling deeply nested [catch]

Closed / Fixedfec0c17d39db02faffa101ebb605d0958dbf3466Created 9 years agoUpdated 7 years ago
Descriptionplain2017-11-28 13:21:09
Reported in the chat by Rolf Ade:

http://paste.tclers.tk/4602

Following script segfaults:

proc gencode {nr} {
    set code ""
    for {set i 0} {$i < $nr} {incr i} {
        append code "catch \{"
    }
    append code "set a foo"
    for {set i 0} {$i < $nr} {incr i} {
        append code "\}"
    }
    return $code
}
puts [eval [gencode 100000]]

`fossil bisect` blames https://core.tcl.tk/tcl/info/bf171b6b51
Referenced by10
  • f096ae5e60amend to [fec0c17d39] - reduce max count of nested compiles to 1500 check-in2019-09-26 16:21:25
  • 6147a8c8b0partially cherrypick of [ecf524bce0], bug-fec0c17d39-8.6-limit: ultimate fix for [fec0c17d39] - avoid SO on deeply recursive call stack by restriction of nested compilations using same limit (interp recursionlimit) like the evaluation, this must protect against unexpected stack exhaustion; conflicts resolved, tests fixed (no command `try` in 8.5) check-in2019-09-11 19:10:05
  • ecf524bce0merge bug-fec0c17d39-8.6-limit: ultimate fix for [fec0c17d39] - avoid SO on deeply recursive call stack by restriction of nested compilations using same limit (interp recursionlimit) like the evaluation, this must protect against unexpected stack exhaustion check-in2019-09-11 18:24:48
  • d9ccf1ab84extends [fec0c17d39]: restrict nested compilations using same limit (interp recursionlimit) like the evaluation, this must protect against unexpected stack exhaustion (avoid SO by deeply recursive call stack) check-in2019-08-30 19:48:04
  • 2ff3869960merge 8.5 - compile.test: reduce count of nested scripts to 1000 in debug case (seems to be to heavy on some platforms within debug-build); (small amend to the fix of [fec0c17d39]) check-in2019-08-30 16:35:38
  • ae6806e6a9compile.test: reduce count of nested scripts to 1000 in debug case (seems to be to heavy on some platforms within debug-build); (small amend to the fix of [fec0c17d39]) check-in2019-08-30 16:33:33
  • f2eecef0a3fixes bug [fec0c17d39] (regression firstly introduced in [bf171b6b51]): stack overflow (followed by segfault) by compilation of too many nested scripts (don't use system stack anymore) check-in2019-08-29 20:55:43
  • 5ece79492ccloses [fec0c17d39]: fixed stack overflow (followed by SF) by compilation of too many nested bodies (don't use system stack, size of Tcl_Parse is ca. 400 bytes and compiler proc's of commands are reserving stack too) check-in2019-08-29 20:50:31
  • 4695da0056bug [fec0c17d39]: add test cases covering nested compilation (8.6th compile generates a stack overflow with following segfault by 2000 nested bodies) check-in2019-08-29 20:33:30
  • 2f4d19ea81add test cases covering nested compilation bug [fec0c17d39] (8.5 is not affected at the moment by nested count under 2500) check-in2019-08-29 20:28:47
dgpplain2017-11-28 13:30:41
Script results in a deeply recursive call stack compiling the script.  Here's one round of it:

#35003 0x00000000004bfebe in TclCompileScript (interp=0x828378, 
    script=0x7ffff7e0319f "catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catc"..., 
    numBytes=0, envPtr=0x7fffffffbef0)
    at /home/dgp/fossil/tcl8.6/generic/tclCompile.c:2198
#35004 0x00000000004c1d44 in TclCompileCmdWord (interp=0x828378, 
    tokenPtr=0x7ffffffeb1d8, count=1, envPtr=0x7fffffffbef0)
    at /home/dgp/fossil/tcl8.6/generic/tclCompile.c:2563
#35005 0x0000000000444868 in TclCompileCatchCmd (interp=0x828378, 
    parsePtr=0x7ffffffeb130, cmdPtr=0x830838, envPtr=0x7fffffffbef0)
    at /home/dgp/fossil/tcl8.6/generic/tclCompCmds.c:647
#35006 0x00000000004de2fb in TclAttemptCompileProc (interp=0x828378, 
    parsePtr=0x7ffffffeb130, depth=1, cmdPtr=0x830838, envPtr=0x7fffffffbef0)
    at /home/dgp/fossil/tcl8.6/generic/tclEnsemble.c:3212
#35007 0x00000000004bf36a in CompileCmdCompileProc (interp=0x828378, 
    parsePtr=0x7ffffffeb130, cmdPtr=0x830838, envPtr=0x7fffffffbef0)
    at /home/dgp/fossil/tcl8.6/generic/tclCompile.c:1952
#35008 0x00000000004bf963 in CompileCommandTokens (interp=0x828378, 
    parsePtr=0x7ffffffeb130, envPtr=0x7fffffffbef0)
    at /home/dgp/fossil/tcl8.6/generic/tclCompile.c:2067
#35009 0x00000000004bfebe in TclCompileScript (interp=0x828378, 
    script=0x7ffff7e03198 "catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catc"..., 
    numBytes=0, envPtr=0x7fffffffbef0)
dgpplain2017-11-28 13:32:46
Sitting on top of that stack:

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff715d244 in _int_malloc () from /lib64/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.17-196.el7.x86_64 zlib-1.2.7-17.el7.x86_64
(gdb) bt
#0  0x00007ffff715d244 in _int_malloc () from /lib64/libc.so.6
#1  0x00007ffff716010c in malloc () from /lib64/libc.so.6
#2  0x00000000005cb246 in TclpAlloc (numBytes=83)
    at /home/dgp/fossil/tcl8.6/generic/tclAlloc.c:699
#3  0x000000000042220a in Tcl_AttemptDbCkalloc (size=11, 
    file=0x5e87f0 "/home/dgp/fossil/tcl8.6/generic/tclStringObj.c", line=154)
    at /home/dgp/fossil/tcl8.6/generic/tclCkalloc.c:499
#4  0x0000000000422793 in Tcl_AttemptDbCkrealloc (ptr=0x0, size=11, 
    file=0x5e87f0 "/home/dgp/fossil/tcl8.6/generic/tclStringObj.c", line=154)
    at /home/dgp/fossil/tcl8.6/generic/tclCkalloc.c:713
#5  0x0000000000568ef7 in GrowStringBuffer (objPtr=0xeb4678, needed=5, flag=0)
    at /home/dgp/fossil/tcl8.6/generic/tclStringObj.c:154
#6  0x000000000056a75e in AppendUtfToUtfRep (objPtr=0xeb4678, 
    bytes=0x7ffff7e0d117 "catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catc"..., 
    numBytes=5) at /home/dgp/fossil/tcl8.6/generic/tclStringObj.c:1562
#7  0x000000000056a004 in Tcl_AppendLimitedToObj (objPtr=0xeb4678, 
    bytes=0x7ffff7e0d117 "catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catc"..., 
    length=5, limit=2147483647, ellipsis=0x0)
    at /home/dgp/fossil/tcl8.6/generic/tclStringObj.c:1089
#8  0x000000000056a0ab in Tcl_AppendToObj (objPtr=0xeb4678, 
    bytes=0x7ffff7e0d117 "catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catc"..., 
    length=5) at /home/dgp/fossil/tcl8.6/generic/tclStringObj.c:1130
#9  0x00000000004be27a in TclWordKnownAtCompileTime (tokenPtr=0x7fffff7ff380, 
    valuePtr=0xeb4678) at /home/dgp/fossil/tcl8.6/generic/tclCompile.c:1704
#10 0x00000000004bf88a in CompileCommandTokens (interp=0x828378, 
    parsePtr=0x7fffff7ff320, envPtr=0x7fffffffbef0)
    at /home/dgp/fossil/tcl8.6/generic/tclCompile.c:2040
#11 0x00000000004bfebe in TclCompileScript (interp=0x828378, 
    script=0x7ffff7e0d117 "catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catc"..., 
    numBytes=0, envPtr=0x7fffffffbef0)
dgpplain2017-11-28 14:04:42
It appears this is conceptually a simple case of call stack exhaustion.

The `fossil bisect` points to a checkin that expanded use of automatic variables to hold Tcl_Parse structs.  That made the pressure on the call stack greater and made this problem easier to demonstrate with less deeply nested scripts.  It seems it was not the difference between the existence and absence of the problem, though.
dgpplain2017-11-28 14:11:38
I'll be damned but the thing runs in Tcl 8.3.5.
dgpplain2017-11-28 14:17:35
No. Broken there too. Just needs even more nesting levels to demo.
sebreswiki2017-11-28 16:47:08

It appears this is conceptually a simple case of call stack exhaustion.

I don't think so... Just note that we've here an factorial by lengths of each body objects (which compiled separately)... Simply we cannot allocate all this objects...

I'll try to explain it here:


proc gencode_lengths {nr} {
    # initial length:
    set codelen [string length "set a foo"]
    # unfold "recursion" to count each body length:
    for {set i 0} {$i < $nr} {incr i} {
        # length of body self (from prev. recursion level):
        incr codelen $codelen
        # length of addition in this body:
        incr codelen [string length "catch \{\}"]
    }
    # lengths of all body objects (will be compiled)
    return $codelen
}

% puts [set len [gencode_lengths 100000]] 16983035581244536635048556993610571046667295363921088760115997655...........very-very-long.

% puts [string index $len 0].[string index $len 1]e[expr {[string length $len]-1}] 1.6e30104

The only "real" solution is to dispense the NTS in string representations and use the same (offset-ed) as shared string representation pointer with offset/length. This expects completely rewriting of Tcl_Obj primitives.

dgpplain2017-11-28 16:49:41
I would expect a memory allocation failure to show up as a panic from Tcl_Alloc().  That's not what I see.
dgpplain2017-11-28 16:51:59
I could easily believe the script demonstrates both problems, but it just happens to reach a failure level of the stack space before it exhausts memory.
sebreswiki2017-11-28 17:32:32

I was a bit too fast with my explaining example (I made dual counting there), below the correct example:


proc gencode_lengths {nr} {
    # initial length:
    set codelen 0
    set initlen [string length "set a foo"]
    set levincr [string length "catch \{\}"]
    set codelen2 0
    # unfold "recursion" to count each body length:
    for {set i 0} {$i < $nr} {incr i} {
        # length of this level body (new catch + from prev. recursion level):
        set levlen [expr {$initlen + $levincr * $i}]
        # + length of addition in current body:
        incr codelen $levlen
        # to debug each level:
        # puts "**$i** $codelen (+ $levlen) - [gencode $i]"
    }
    # lengths of all body objects (that will be compiled)
    return $codelen
}

% puts [set len [gencode_lengths 100000]] 40000500000

But the conclusion still the same: no memory, at least in 32-bit env I can pretty see allocation panic... Possibly by x64 (and enough memory) somewhere in interim structures we've signed int (instead of long), that overflows into negative...

sebres Ticket [fec0c17d39]: 3 changes [History diff]2019-06-12 07:37:44
sebreswiki2019-08-29 21:00:04

Fixed in bug-fec0c17d39-8.6, merged in 8.6 (and also test covered in 8.5 now).

sebreswiki2019-08-30 19:59:56

New branch bug-fec0c17d39-8.6-limit provide a mechanism to really avoid SO in case of deeply nested calls of TclCompileScript.

Although at the moment it uses same level variable as the execution depth (iPtr->numLevels), I selected a factor (5/4 = 1.25) for comparison with max depth (interp recursionlimit), which is used to avoid mistaken level excess by "mixed" compile/eval process (if eval/invoke calls compile which calls eval/invoke etc).
This way it protects against stack exhaustion (don't confuses eval level check, which always wins) and is good enough for default recursionlimit (1000), so stop compile process at least after 1250 recursion steps.

Additional test case compile-13.3 (similar to compile-13.2) covers in the test interpreter the stop by compilation of same commands (having body) like in bug-fix, just exceeding limit of 100.

jan.nijtmanswiki2019-09-02 12:19:13

Branches bug-fec0c17d39-8.6-limit and core-8-6-branch are still failing in Travis. Could you have a look at that, please? See: https://travis-ci.org/tcltk/tcl/jobs/579106602

sebreswiki2019-09-02 13:27:27

Hmm... you are right, Jan.

Just the reason seems to be the wrong recognition of debug, because variable ::tcl_platform(debug) does not exist.
I'll try to find why (option --enable-symbols alone is not enough?) and fix it for all versions.

Thanks!

sebreswiki2019-09-02 13:58:56

Fixed now (replaced #ifdef _DEBUG with #ifndef NDEBUG), 8.5 was not affected (has already checked NDEBUG definition).

Possibly to be more compatible (or rather for consistency reasons), should we append to default debug flags (-g at the moment) still -D_DEBUG?

Anyway now compile.test works for both branches (core-8-6-branch and bug-fec0c17d39-8.6-limit) without any issue (and also variable ::tcl_platform(debug) is found) if debug build used.

jan.nijtmansplain2019-09-02 14:15:53
Solution looks good to me. Thanks!

However, since tcl_platform(debug) flag is only set on Windows, let's change it such that the same switch is made on UNIX too. As a little addendum ...

Done that on core-8-6-branch now.
dgpplain2019-09-03 18:25:20
Branch crashes in test event-11.8
jan.nijtmansplain2019-09-03 18:48:12
I suspect that's because of my change in tcEvent.c which came in from core-8-6-branch. Although I cannot explain yet what's wrong in that commit.
dgpplain2019-09-03 19:27:15
It's incorrect to add TCL_GLOBAL_ONLY to VwaitVarProc.

The [vwait] command resolves its variable name argument globally.

That does not imply that every write trace callback should reroute the local name of the variable getting written to a global name that might name another variable entirely.
sebreswiki2019-09-04 11:12:17

Back to the issue: I have still one idea to improve the recursion protection against SO:

At the moment we hold the level counter and max depth per interpreter. A thread (which stack we are trying to protect) can own more as one interpreter (and compile resp. execute the code across them), so the stack exhaustion could occur if common stack depth is reached (but the limits in each interpreter are still not reached).

I think we could need additionally a "global" (per process or per thread) recursion limit as well as the counter in the thread storage that would hold real nested depth across all interpreter.

dgpplain2019-09-11 17:29:27
The original demo script still segfaults all the active branches.
dgpplain2019-09-11 17:43:25
So the original report is a segfault both before and after the fix, while the new test compile-13.2 passes both before and after the fix.
sebreswiki2019-09-11 18:38:58

Branch bug-fec0c17d39-8.6-limit gets merged, so it is ultimately fixed now for 8.6 in [ecf524bce0]. The body of catch is compiled in core on demand, so the original script falls in the category of mixed eval+compile and now it stops to compile after ca. 1250 nested compilations (mentioned factor 5/4).

Although the script returned successfully with 0 now (due to top catch's around of catch-ed error), but the error is pretty visible using $errorInfo:

% puts [eval [gencode 100000]]
0
% puts $::errorInfo
too many nested compilations (infinite loop?)
    invoked from within
"catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch {catch ...

Thus close now.
Thanks for reminder, Don!

dgpplain2019-09-11 19:17:40
Ok, this isn't right yet:

% catch [gencode 100000] m o
0
% set o
-code 0 -level 0
% set errorInfo
too many nested compilations (infinite loop?)
...

Not as bad as a segfault, but more to do.
dgpplain2019-09-11 19:19:37
Spoke too hastily
dgpplain2019-09-11 19:19:58
% catch {catch {catch {error foo}}} m o
0
% set o
-code 0 -level 0
% set errorInfo
foo
    while executing
"error foo"
jan.nijtmanswiki2019-09-22 20:53:49

@sebres. Are you aware that Travis builds for core-8-5-branch are still failing in compile.test? See for example: https://travis-ci.org/tcltk/tcl/jobs/587771946

So, what should we do about it? It only happens with gcc builds on Windows. core-8-6-branch doesn't suffer, only 8.5

sebreswiki2019-09-23 09:47:36

> Are you aware that Travis builds for core-8-5-branch are still failing in compile.test? So, what should we do about it?

Hmmm... Did not see this on my side (neither release nor debug build of 8.5). No matter how I start it (from make using make test TESTFLAGS="-file compile.test") or using tcltest-helper (tcltest.cmd -file compile.test) it succeeds compiled with mingw 7.3 and 8.3 (x64 and x86).

Anyway your branch "travis-win32-with-make" (with reduced repetition count to 1500/750) may be a good candidate (if tests running and not affected).

> It only happens with gcc builds on Windows. core-8-6-branch doesn't suffer, only 8.5

Sure, due to several NRE's inside 8.6 it is fewer stack hungry, so 8.6 seems to be "safer" as 8.5 by larger nested compile/eval's. Just strange I don't see it testing direct (outside of Travis).

sebresplain2019-09-26 16:24:20
done (reduce of nested count to 1500 seems to fix this in Travis).
Log in (anonymous is fine) to add a comment.