Closed ChunMinChang closed 4 years ago
Thanks for filing! CString's API is easy to misuse, I've run into similar issues before too. I'll make a note to set clippy up in CI when I get a chance to catch this type of issue quicker.
Interestingly, in this particular case I believe clippy's warning is incorrect. The lifetime of the CString extends over the duration of the function call (see https://doc.rust-lang.org/reference/expressions.html#temporary-lifetimes), so there is no UAF in this instance. See this playground, where running MIRI from the Tools menu indicates the issue exists for baz()
but not for bar()
. It's also visible by selecting MIR from the Build menu and examining the lifetimes of the various local variables in the IR.
The
std::ffi::CString::new(id).unwrap()
will create a temporary variable.std::ffi::CString::new(id).unwrap().as_ptr()
is a pointer pointing to a temporary variable. Using this pointer directly is unsafe since we cannot make sure the variable is alive when the pointer is referred. It's better to save the variable returned fromCString::new()
and use its pointer (in the same scope of the variable) when we need.Run
cargo clippy
withCString::new(text).unwrap().as_ptr()
will lead to atemporary_cstring_as_ptr
error. Here is a playground test.r? @kinetiknz