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

@@ -21407,7 +21407,12 @@
2140721407 did_gb = new_temp
2140821408 rest_gb = new_temp
2140921409 emit(" size_t " + cap_gb + " = strlen(" + rc + ") * 2 + 64;")
21410- emit(" char *" + out_gb + " = sp_str_alloc_raw(" + cap_gb + ");")
21410+ # Plain malloc working buffer: it gets realloc'd as matches accrue
21411+ # (invalid on an sp_str_alloc'd pointer), and the final result is
21412+ # copied into a right-sized heap string below so its recorded byte
21413+ # length is the content length, not the allocation size (the old
21414+ # sp_str_alloc_raw return leaked trailing NULs -- issue #1083).
21415+ emit(" char *" + out_gb + " = (char *)malloc(" + cap_gb + ");")
2141121416 emit(" size_t " + olen_gb + " = 0;")
2141221417 emit(" int64_t " + pos_gb + " = 0;")
2141321418 emit(" int64_t " + slen_gb + " = (int64_t)strlen(" + rc + ");")
@@ -21460,7 +21465,13 @@
2146021465 emit(" if (" + olen_gb + " + " + rest_gb + " + 1 >= " + cap_gb + ") { " + cap_gb + " = " + olen_gb + " + " + rest_gb + " + 64; " + out_gb + " = (char*)realloc(" + out_gb + ", " + cap_gb + "); }")
2146121466 emit(" memcpy(" + out_gb + " + " + olen_gb + ", " + rc + " + " + pos_gb + ", " + rest_gb + "); " + olen_gb + " += " + rest_gb + ";")
2146221467 emit(" " + out_gb + "[" + olen_gb + "] = 0; }")
21463- return out_gb
21468+ # Copy into a right-sized heap string (length == content length) and
21469+ # free the working buffer.
21470+ fin_gb = new_temp
21471+ emit(" char *" + fin_gb + " = sp_str_alloc(" + olen_gb + ");")
21472+ emit(" memcpy(" + fin_gb + ", " + out_gb + ", " + olen_gb + ");")
21473+ emit(" free(" + out_gb + ");")
21474+ return fin_gb
2146421475 end
2146521476 end
2146621477 end