Tk Source Code

View Ticket
Login
Ticket UUID: b964b98d1b1fa9bc1abf08a09bcaef20c4ed0ba
Title: ttk manager relayout use-after-free during teardown (Aqua)
Type: Bug Version: 9.0.3/9.0.4
Submitter: anonymous Created on: 2026-07-04 08:19:00
Subsystem: (unused) Assigned To: nobody
Priority: 5 Medium Severity: Minor
Status: Open Last Modified: 2026-10-07 02:02:29
Resolution: None Closed By: nobody
    Closed on:
Description:

On macOS/Aqua, destroying a nested ttk::panedwindow structure (and, to a lesser degree, a ttk::notebook) intermittently crashes with EXC_BAD_ACCESS in Tk_MapWindow, called from the ttk geometry manager's deferred relayout (ttkManager.c ManagerIdleProc → RecomputeLayout → PlaceContent → Ttk_PlaceContent → Tk_MapWindow). The container window is still alive; one of its content windows has already been freed but is being mapped. It is a use-after-free caused by the manager's relayout running re-entrantly during window teardown, which on Aqua happens because Tk_DestroyWindow pumps the Cocoa run loop (window-close handling / NSAnimation) and services a pending idle mid-destroy.

Affected

  • Tk 9.0.3 and 9.0.4 (the ttk manager + panedwindow code is unchanged between them here).
  • macOS (observed on macOS 26.5.2 / arm64, Aqua backend). Not reproduced on X11/Linux — the crash needs the Aqua teardown's re-entrant run-loop pumping to fire the idle mid-destroy.
  • Widgets: nested ttk::panedwindow (primary); ttk::notebook shows the same signature under churn. Both use generic/ttk/ttkManager.c.

Symptom / backtrace (lldb, unstripped build)

thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=2, address=0x10083c4a8)
  frame #0: Tk_MapWindow + 68
      -> str  w8, [x0, #0x118]        ; winPtr->flags |= TK_MAPPED
  lr = PanedPlaceContent + 176        ; the caller
  x0 = 0x10083c390                    ; the "window" arg — a WILD pointer (lands in __TEXT),
                                      ; not a heap TkWindow  => content->window is freed/garbage

code=2 is a write fault; x0 (the Tk_Window passed to Tk_MapWindow) is not a valid TkWindow — it points into the text segment — so winPtr->flags |= TK_MAPPED writes into read-only memory. mgr itself is valid (its flags/content/window all dereference cleanly before the fault); only the content entry's window is stale.

Mechanism

ttkManager.c:

  • ScheduleUpdate() defers relayout via Tcl_DoWhenIdle(ManagerIdleProc, mgr).
  • RemoveContent() (called from a content window's DestroyNotify via ContentLostEventHandler) removes the content and re-schedules the idle (ScheduleUpdate(mgr, MGR_RESIZE_REQUIRED)).
  • Ttk_PlaceContent() maps content only while the container is mapped (if (Tk_IsMapped(mgr->window)) Tk_MapWindow(content->window);).

Teardown of a nested panedwindow destroys children (content) before the container. On Aqua, Tk_DestroyWindow pumps the run loop while closing NSWindows/animating, so a pending ManagerIdleProc for a still-alive container fires in the middle of the child-destroy cascade — at a point where a content window's TkWindow has been freed but the manager's PlaceContent still iterates it (or iterates it before its RemoveContent has run). Ttk_PlaceContent then calls Tk_MapWindow on the freed window. On X11 the idle is serviced only at the next top-level event-loop turn, after teardown has fully settled, so the window is never observed.

Ruled out

  • Not the container being destroyed: a guard that bails RecomputeLayout when ((TkWindow*)mgr->window)->flags & TK_ALREADY_DEAD was bypassed (container alive) and did not fix it.
  • Not the Player's bindings: reproduces with raw Tcl creating/destroying nested ttk::panedwindows (no app widget objects involved).
  • Timing-sensitive (Heisenbug): does not reproduce under lldb, and the rate tracks how hard the run loop is pumped during teardown.

Possible fix direction

The manager relayout must not run on content that is being torn down. Candidates:

  1. In ManagerIdleProc / RecomputeLayout, skip any content window flagged TK_ALREADY_DEAD before placing/mapping it (guarding the content, not the container) — but note the observed pointer is already freed, so this needs the dead content to still be in the list and a valid (if dead) TkWindow, i.e. it depends on ordering vs. RemoveContent.
  2. Cancel/suppress the manager's pending relayout idle for the duration of a re-entrant teardown (e.g. a "manager is tearing down" guard, or servicing the idle non-re-entrantly).
  3. On Aqua specifically, avoid servicing arbitrary Tcl idles while pumping the run loop inside Tk_DestroyWindow.

Full disclosure: The report above was AI generated after a debug session.

User Comments: marc_culler (claiming to be Marc Culler) added on 2026-10-07 02:02:29:
Thanks!  I will take a look.

anonymous added on 2026-10-04 13:25:19:
Yes, sorry for the long silence. (I should register somewhere so I get notigication, I suppose.) The attached b964b98d-repro.tcl is a
standalone script for plain wish:

    wish9.1 b964b98d-repro.tcl ?iterations?

It is not Aqua-only; the description's "not reproduced on X11" was wrong for
this reduced form. A ttk::panedwindow has four panes, and a <Configure>
binding on one pane destroys that pane. Tk_MoveResizeWindow delivers
<Configure> synchronously (TkDoConfigureNotify), so the binding runs while
Ttk_PlaceContent is placing that very pane from the manager's idle relayout
(ManagerIdleProc -> RecomputeLayout -> PanedPlaceContent -> PlacePanes). The
destroy frees the window and its manager records, and the placement then
reads them.

A release build usually survives the script, because Tcl's allocator keeps
the freed block. With Tcl and Tk 9.1.0 built from the release tarballs with
-DPURIFY and run under valgrind on Linux/X11, 10 iterations give 60 errors
from 5 contexts, for example:

    Invalid read of size 1
       at Tk_MapWindow (tkWindow.c:1791)
       by Tk_MaintainGeometry (tkGeometry.c:446)
       by Ttk_PlaceContent (ttkManager.c:372)
       by PlacePanes (ttkPanedwindow.c:391)
       by PanedPlaceContent (ttkPanedwindow.c:411)
       by RecomputeLayout (ttkManager.c:109)
       by ManagerIdleProc (ttkManager.c:129)
       by TclServiceIdle (tclTimer.c:991)
     Address ... is 280 bytes inside a block of size 440 free'd
       at free
       by TclpFree (tclAlloc.c:724)
       by Tcl_EventuallyFree (tclPreserve.c:294)
       by Tk_DestroyWindow (tkWindow.c:1764)
       by Tk_DestroyObjCmd (tkCmds.c:508)
       ...
       by Tk_BindEvent (tkBind.c:2582)
       by TkBindEventProc (tkCmds.c:327)
       by Tk_HandleEvent (tkEvent.c:1284)
       by TkDoConfigureNotify (tkWindow.c:2374)

On macOS/Aqua with 9.0.4, in July, the same script crashed unpatched wish
with SIGBUS in Tk_MapWindow on every run, and an ASan build reported the
same free and use sites.

The attached b964b98d-9.1.0.patch is the patch already attached here,
brought to 9.1.0 (patch -p1 from the Tk source root):

- ttkManager.c: the manager counts changes to its content list (an epoch),
  and code that calls into Tk while holding a content record checks the
  count afterwards and stops if the list changed. Stopping is safe because
  every change schedules a new relayout. It also skips content and
  containers that are being destroyed (TK_ALREADY_DEAD).
- tkGeometry.c: Tk_MaintainGeometry preserves both windows around
  Tk_MoveResizeWindow and does not map a window that is being destroyed.
- ttkPanedwindow.c: PlacePanes reads the pane's sash position before
  placing, since placing can free the pane.

With the patch, valgrind reports 0 errors for the same run. Tk's test suite
under Xvfb gives the same result with and without it: 9733 tests, the same
15 failures (send, unixWm and wm tests that need a window manager) on both,
and the ttk tests 2042 run, 0 failed.

marc_culler (claiming to be Marc Culler) added on 2026-07-18 21:31:12:
Do you have a Tcl script that causes this crash?

Attachments: