szn

Bug 450 — display_clients |*dc| loops hold pointers into a value ArrayList backing buffer

450. In-flight *dc pointers dangle if registerDisplayClient or removeClient runs mid-loop

Severity: LOW Status: Fixed

Symptoms

None observable today. Every loop that holds a *dc into self.display_clients.items either calls only functions that never mutate display_clients (flushDisplayClient, appendClientOut*), or breaks immediately after the call. registerDisplayClient (append) is only reached from handleClient’s .identify_term case and removeClient (swapRemove) only from detach/error paths — none of which are reachable from inside the loops. The hazard is latent: any future code that appends or removes a display client while a *dc is held re-opens the bug.


Root Cause Analysis

self.display_clients is std.ArrayList(DisplayClient) (values, not pointers). An append (registerDisplayClient, server.zig:2430) can reallocate the backing buffer, moving every element; a swapRemove (removeClient, server.zig:2612) moves the last element into the hole and shrinks the length. Consequently:

// src/server/server.zig:3035 — renderToDisplayClient
for (self.display_clients.items) |*dc| {
    ...
    _ = self.flushDisplayClient(dc);   // safe: never mutates display_clients
    ...
}

is a pointer into the array buffer held across the body. This is the same shape as holding reader = client_readers.get(fd) across the dispatch loop in #428/#443 (sub-form (b): pointer into a reallocatable container held across a call that can resize it). The difference is that the mutators are currently unreachable from the hold sites, so it is a defensive gap rather than a live use-after-free.

Note also that DisplayClient contains ArrayList fields (out_buf, last_cells, bounds_buf) and a Screen — copying the struct by value when the array grows is safe because those are heap buffers whose pointers are copied, but any code holding &dc.field across an append would see stale fields.


Solution

  1. Convert display_clients to an ArrayList(*DisplayClient) of heap-allocated structs (destroyed in removeClient/deinit), so element pointers survive append/swapRemove — matching how sessions, windows, and panes already store pointers.
  2. Alternatively, keep values but re-fetch *dc after any call that could mutate the array, and never hold a *dc across such a call.
  3. Add a regression test that registers a display client (append → forced reallocation) while a caller holds a *dc, asserting the held pointer is not used afterwards.

Fixed: