coerceValue returns a slice of buf: [24]u8 instead of the static candidate cSeverity: MEDIUM
Status: ✅ FIXED
Files: src/options.zig:170-176, src/options.zig:98-102
Bug #516 made numeric choice options settable (e.g. set-option -g status 2)
by coercing .number values to .choice when matching def.choices:
.number => |n| {
var buf: [24]u8 = undefined;
const s = std.fmt.bufPrint(&buf, "{d}", .{n}) catch return value;
if (def.choices) |choices| {
for (choices) |c| {
if (std.mem.eql(u8, s, c)) return OptionValue{ .choice = s };
}
}
return value;
},
Notice return OptionValue{ .choice = s };. s is a slice pointing directly
into buf, which is a stack-local array of coerceValue. When coerceValue
returns to its caller Options.set:
const coerced = try coerceValue(def, value);
try validateType(def, coerced);
const cloned = try cloneValue(self.allocator, coerced);
The stack frame of coerceValue is popped before validateType and cloneValue
run. Both access coerced.choice, reading from deallocated stack memory
(stack-use-after-return).
While the memory happened not to be trampled immediately in tests, escaping a stack buffer slice into a returned value is a latent memory hazard and undefined behaviour.
Return c (which is the matched candidate slice from def.choices, backed by
static comptime strings in option definition tables) rather than s:
if (std.mem.eql(u8, s, c)) return OptionValue{ .choice = c };
Regression test numeric choice coercion returns static string from def.choices — bug #531
in src/options.zig asserts that the coerced slice pointer equals the static
choice literal pointer (def.choices.?[2].ptr), confirming it no longer aliases
stack memory.
Full suite verified on Zig 0.16.0 and 0.17.0 with isolated caches.
#516 introduced numeric choice coercion.