You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The usage of CString by recursion/gnark-ffi seems incorrect when compared to what the Rust documentation says about ownership. Specifically:
As far as I can tell, these strings are allocated by the Go code here
The CString documentation explicitly says "Other usage (e.g., trying to take ownership of a string that was allocated by foreign code) is likely to lead to undefined behavior or allocator corruption."
This means the string is allocated by Go, but being freed by Rust. This seems possibly unsafe.
The documentation also says: "Note: If you need to borrow a string that was allocated by foreign code, use CStr. If you need to take ownership of a string that was allocated by foreign code, you will need to make your own provisions for freeing it appropriately, likely with the foreign code’s API to do that."
The correct solution would be to return these pointers and have the Go side free them from Go
// Go string to C string
// The C string is allocated in the C heap using malloc.
// It is the caller's responsibility to arrange for it to be
// freed, such as by calling C.free (be sure to include stdlib.h
// if C.free is needed).
func C.CString(string) *C.char
CString in Rust is actually allocated from the Rust global allocator and not C's malloc/free functions. So this code is freeing something allocated by malloc with Rust's allocator, which is just incorrect in terms of safety
Since this code does seem to work, in some cases where Rust and Go are using the same libc on the same system, this is likely to be incidentally fine
Further, in some cases, such as when binaries are distributed in pre-compiled formats, it is possible for there to be a version mismatch between libcs used, leading to further issues even if the Rust global allocator ends up using malloc/free
This same mishandling is present when parsing the error strings returned by Go
The text was updated successfully, but these errors were encountered:
From https://github.com/wormhole-foundation/wp1/pull/222#discussion_r1613607167:
The usage of
CString
byrecursion/gnark-ffi
seems incorrect when compared to what the Rust documentation says about ownership. Specifically:CString
documentation explicitly says "Other usage (e.g., trying to take ownership of a string that was allocated by foreign code) is likely to lead to undefined behavior or allocator corruption."CString
in Rust is actually allocated from the Rust global allocator and not C's malloc/free functions. So this code is freeing something allocated by malloc with Rust's allocator, which is just incorrect in terms of safetyThe text was updated successfully, but these errors were encountered: