Commit d17bf68f
d17bf68f7f81Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · ~1 modified
Description
fix(codegen): FFI :str return copies into spinel-owned storage
A FFI function declared with :str return type forwarded the
C-side const char * directly into the Ruby side. The pointer
aliases the FFI library's storage, so:
- The Ruby string survives only while the library keeps the
source alive. Calling the library's
free(or any function that releases the context) makes every previously-returned string dangle, and the next GC scan walks alien memory. - The header marker the spinel string heap relies on
(
\xffbyte before the string body, set by sp_str_alloc) is absent, so the GC scanner can't follow the alias safely. A large array of FFI strings amplifies this: each scanned entry tries to read the marker, often hits unmapped or misaligned memory, and the process segfaults.
Wrap :str returns in sp_str_dup_external (the existing helper
that copies into the spinel string heap with the right marker).
sp_str_dup_external handles NULL inputs, so optional-string
returns continue to work; cost is one strlen + one allocation
per FFI call. Callers that need zero-copy access can keep using
:ptr and read characters explicitly.
Refs #626 (third sub-issue: large FFI :str arrays segv). The cross-class type widening (issue 1) and RBS-strict-mode (issue 2) sub-issues are unrelated and stay open under #626.
Co-Authored-By: Claude Opus 4.7 [email protected]
Details
- Commit
- d17bf68f7f81
- Parent
- be7145336cfc
spinel_codegen.rbmodifiedView file
if ret_spec == "void" return "(" + result + ", (mrb_int)0)" end # `:str` returns alias the FFI library's `const char *` storage. # Without a copy, the Ruby side holds a pointer that may be freed # / overwritten when the C library releases its context (or, with # large arrays of FFI strings pinned at once, the GC scan walks # alien memory and trips on alignment). sp_str_dup_external copies # into the spinel string heap with the marker byte the GC scanner # expects, severing the alias. Issue #626 (issue 3). NULL passes # through (sp_str_dup_external returns NULL on NULL input). if ret_spec == "str" return "sp_str_dup_external(" + result + ")" end result end