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 (\xff byte 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

@@ -5324,6 +5324,17 @@
53245324 if ret_spec == "void"
53255325 return "(" + result + ", (mrb_int)0)"
53265326 end
5327+ # `:str` returns alias the FFI library's `const char *` storage.
5328+ # Without a copy, the Ruby side holds a pointer that may be freed
5329+ # / overwritten when the C library releases its context (or, with
5330+ # large arrays of FFI strings pinned at once, the GC scan walks
5331+ # alien memory and trips on alignment). sp_str_dup_external copies
5332+ # into the spinel string heap with the marker byte the GC scanner
5333+ # expects, severing the alias. Issue #626 (issue 3). NULL passes
5334+ # through (sp_str_dup_external returns NULL on NULL input).
5335+ if ret_spec == "str"
5336+ return "sp_str_dup_external(" + result + ")"
5337+ end
53275338 result
53285339 end
53295340