Skip to content

fix: naive use of cstring pointer as a typed array buffer pointer resulting in a crash on gc in #739 - expose stringToBuffer#740

Merged
saghul merged 10 commits intosaghul:masterfrom
ldeninski:feat/expose-stringToBuffer
Jan 21, 2026
Merged

fix: naive use of cstring pointer as a typed array buffer pointer resulting in a crash on gc in #739 - expose stringToBuffer#740
saghul merged 10 commits intosaghul:masterfrom
ldeninski:feat/expose-stringToBuffer

Conversation

@ldeninski
Copy link
Copy Markdown
Contributor

This is a fix for #739 . My assumption was that JS_ToCString was returning c managed memory buffer - so handing it over to the js runtime by using it as a backing buffer for a typed array would be fine.. but as it turns out JS_ToCString do actually return a memory buffer to a cstring, BUT this buffer is actually already a backing buffer of a JSString allocated in this function.. so GCing the JSString and the TypedArray resulted in double free and a crash. So the updated code now

  • uses JS_NewUint8ArrayCopy that copies the buffer from the JSString
  • frees the CString (JSString)
  • hands over the Uint8Array to the calling code

This time I did my homework (hopefully) - I tested the code both for stability and if it is leaking memory with the help of JS_SetDumpFlags(rt, JS_DUMP_LEAKS); JS_SetDumpFlags(rt, JS_DUMP_MEM); and ENABLE_DUMPS - no difference in memory usage at the end of a test after no calls vs 10.. 100.. and 1000 calls to ffi.bufferToString(ffi.stringToBuffer(longString) and no leaked objects and strings reported.

@saghul saghul merged commit de1226e into saghul:master Jan 21, 2026
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants