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
int *ids = malloc(sizeof(int) * list->size); for (size_t i = 0; i < list->size; i++) ids[i] = flatten(list->nodes[i]); /* Build comma-separated string */ char buf[65536]; int pos = 0; /* Issue #744: build comma-separated string into a growable buffer. Previously a fixed 65536-byte stack buffer overflowed on 20k+-element arrays -- snprintf returns the bytes it WOULD have written, advancing pos past the end and corrupting the stack. */ size_t cap = 1024; char *buf = malloc(cap); size_t pos = 0; for (size_t i = 0; i < list->size; i++) { /* worst case per iter: ", -2147483648\0" -> 14 bytes; reserve 16 to be safe */ if (pos + 16 >= cap) { cap = cap * 2 + 16; buf = realloc(buf, cap); } if (i > 0) buf[pos++] = ','; pos += snprintf(buf + pos, sizeof(buf) - pos, "%d", ids[i]); int n = snprintf(buf + pos, cap - pos, "%d", ids[i]); if (n > 0) pos += (size_t)n; } buf[pos] = '\0'; out_add("A %d %s %s", id, field, buf); free(buf); free(ids);}