Commit baa45caa

baa45caa6e94Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · ~1 modified

Description

fix(parse): emit_node_array uses growable buffer (#744)

emit_node_array used a fixed 65536-byte stack buffer for the comma-separated node-id list. snprintf returns the bytes it WOULD have written (not what it actually wrote when truncated), so pos advanced past the buffer end on long lists; subsequent writes corrupted the surrounding stack. Trivial repro: a literal with ~10k+ Integer elements.

Switch to a malloc'd buffer that doubles when within 16 bytes of the current capacity (worst case per integer: ", -2147483648\0" = 14 bytes). free()'d before return.

Regression test deferred: large-array repros also hit a separate spinel_analyze stack-overflow during recursive type inference, so a working end-to-end test would need that fix too. The parser-side fix is correct and tested manually (a 10k-element array now reaches spinel_analyze instead of aborting with "buffer overflow detected").

471 tests pass; optcarrot checksum 59662.

Closes #744

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
baa45caa6e94
Parent
4406c16d87b9

spinel_parse.cmodifiedView file

@@ -129,15 +129,26 @@
129129 int *ids = malloc(sizeof(int) * list->size);
130130 for (size_t i = 0; i < list->size; i++)
131131 ids[i] = flatten(list->nodes[i]);
132- /* Build comma-separated string */
133- char buf[65536];
134- int pos = 0;
132+ /* Issue #744: build comma-separated string into a growable buffer.
133+ Previously a fixed 65536-byte stack buffer overflowed on
134+ 20k+-element arrays -- snprintf returns the bytes it WOULD have
135+ written, advancing pos past the end and corrupting the stack. */
136+ size_t cap = 1024;
137+ char *buf = malloc(cap);
138+ size_t pos = 0;
135139 for (size_t i = 0; i < list->size; i++) {
140+ /* worst case per iter: ", -2147483648\0" -> 14 bytes; reserve 16 to be safe */
141+ if (pos + 16 >= cap) {
142+ cap = cap * 2 + 16;
143+ buf = realloc(buf, cap);
144+ }
136145 if (i > 0) buf[pos++] = ',';
137- pos += snprintf(buf + pos, sizeof(buf) - pos, "%d", ids[i]);
146+ int n = snprintf(buf + pos, cap - pos, "%d", ids[i]);
147+ if (n > 0) pos += (size_t)n;
138148 }
139149 buf[pos] = '\0';
140150 out_add("A %d %s %s", id, field, buf);
151+ free(buf);
141152 free(ids);
142153 }
143154