Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Safety issue with RString::as_interned_str #142

Open
ianks opened this issue Mar 13, 2025 · 1 comment
Open

Safety issue with RString::as_interned_str #142

ianks opened this issue Mar 13, 2025 · 1 comment

Comments

@ianks
Copy link
Contributor

ianks commented Mar 13, 2025

Currently, FString assumes the underlying memory address is fixed. This assumption is used to safely expose the Ruby string’s backing bytes as a &str. In practice, this guarantee does not extend to dynamic strings. Only a static C string literal (or equivalent, as created by r_string!("literal")) is truly non-GC-managed and fixed in memory.

It's currently possible to get an FString from an RString using RString::as_interned_str, which only checks that RSTRING_FSTR is set - which only guarantees that there's no two strings that both have RSTRING_FSTR and have the same contents and does not guarantee the underlying memory address is fixed.

I think it should only be possible to get an FString with the r_string! macro so all safety guarantees can be met.

@erickguan
Copy link
Contributor

It's currently possible to get an FString from an RString using RString::as_interned_str, which only checks that RSTRING_FSTR is set - which only guarantees that there's no two strings that both have RSTRING_FSTR and have the same contents and does not guarantee the underlying memory address is fixed.

Good eyes!

Can we get an unsound FString from an RString? If in a normal function call, this looks unlikely to me.

But if I am getting the GC code correctly, r_string! and rb_str_lit API hands over the C pointer to the GC. MRI then keeps track of the pointer. Then I am not certain if the underlying memory address will be the same if the GC compact happens. In other words, I don't know if keeping a FString in the (Rust) heap is safe or not.

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

No branches or pull requests

2 participants