Commit b7d6e234
b7d6e2341b30Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified
Description
Fix block-form String#gsub / #sub returning NUL-padded garbage
The block form built its result in a buffer from sp_str_alloc_raw(cap),
filled olen bytes, then returned that buffer directly. sp_str_alloc_raw
records the allocation size (cap-1) as the string's byte length, so the
result carried the unused tail as trailing NULs:
"abc".gsub(/[ac]/) { |m| m.upcase } # => "AbC\0\0\0..." (was)
The working buffer was also an sp_str_alloc'd pointer, so the grow-path realloc() ran on a non-malloc base (UB, latent until a match made the output exceed the initial capacity).
Use a plain malloc working buffer (realloc now valid), and copy the
olen content bytes into a right-sized sp_str_alloc(olen) result before
returning, freeing the scratch buffer -- matching sp_StrArray_join.
"abc".gsub(/[ac]/) { |m| m.upcase } # => "AbC" ("a"*100).gsub(/a/) { |m| "XYZ" } # => "XYZ"*100 (exercises grow)
Fixes #1083
Co-Authored-By: Claude Opus 4.8 [email protected]
Details
- Commit
- b7d6e2341b30
- Parent
- a0a69b34ea63
spinel_codegen.rbmodifiedView file
did_gb = new_temp rest_gb = new_temp emit(" size_t " + cap_gb + " = strlen(" + rc + ") * 2 + 64;") emit(" char *" + out_gb + " = sp_str_alloc_raw(" + cap_gb + ");") # Plain malloc working buffer: it gets realloc'd as matches accrue # (invalid on an sp_str_alloc'd pointer), and the final result is # copied into a right-sized heap string below so its recorded byte # length is the content length, not the allocation size (the old # sp_str_alloc_raw return leaked trailing NULs -- issue #1083). emit(" char *" + out_gb + " = (char *)malloc(" + cap_gb + ");") emit(" size_t " + olen_gb + " = 0;") emit(" int64_t " + pos_gb + " = 0;") emit(" int64_t " + slen_gb + " = (int64_t)strlen(" + rc + ");") emit(" if (" + olen_gb + " + " + rest_gb + " + 1 >= " + cap_gb + ") { " + cap_gb + " = " + olen_gb + " + " + rest_gb + " + 64; " + out_gb + " = (char*)realloc(" + out_gb + ", " + cap_gb + "); }") emit(" memcpy(" + out_gb + " + " + olen_gb + ", " + rc + " + " + pos_gb + ", " + rest_gb + "); " + olen_gb + " += " + rest_gb + ";") emit(" " + out_gb + "[" + olen_gb + "] = 0; }") return out_gb # Copy into a right-sized heap string (length == content length) and # free the working buffer. fin_gb = new_temp emit(" char *" + fin_gb + " = sp_str_alloc(" + olen_gb + ");") emit(" memcpy(" + fin_gb + ", " + out_gb + ", " + olen_gb + ");") emit(" free(" + out_gb + ");") return fin_gb end end endtest/gsub_sub_block.rbaddedView file
Loading diff…
test/gsub_sub_block.rb.expectedaddedView file
Loading diff…