Lint for str::as_ptr arguments?

Is there a way to easily check if str::as_ptr is being used to construct an argument to a foreign function? I recently encountered a bug due to this (where a C function expected a null-terminated string). Arguably the right thing is to wrap the foreign function to accept a &CStr; it would be helpful to get a list of potential problems.

CStr::as_ptr returns signed (*const i8) while str::as_ptr returns unsigned (*const u8).

Is the foreign function declared to accept what CStr::as_ptr returns?

If no then why not?

If yes then is the compiler not producing an error?

CStr::as_ptr returns *const std::ffi::c_char and in C signedness of its char type is implementation defined. Here's how the Rust libstd detects it, for example in linux it's signed on x86 but unsigned on ARM.

3 Likes

I don't have the code in front of me but it might have had a cast as well.

...which unfortunately is not reflected in the documentation.

That would be the goal. Create a situation in which the only way to get it correct is to have no cast. Rust is strongly typed and has support for new types.

Maybe something like this...

use std::ffi::CString;
use std::os::raw::c_char;

#[repr(C)]
struct MyChar(c_char);

#[repr(C)]
struct MyCharWrapper(*const MyChar);

impl From<&CString> for MyCharWrapper {
    fn from(value: &CString) -> MyCharWrapper {
        MyCharWrapper(value.as_ptr() as *const MyChar)
    }
}

extern "C" { fn puts(s: MyCharWrapper); }

fn main() {
    let print_me = CString::new("Hello, world!").unwrap();
    unsafe { puts((&print_me).into()); }
}
1 Like

There is an issue in Clippy for this: Lint to warn about str::as_ptr() usage in ffi call · Issue #1236 · rust-lang/rust-clippy · GitHub.

The problem however is that it's not always incorrect to pass a pointer from str::as_ptr to an external function. If a function accepts a pair of pointer and length (like memcpy) or a pair of two pointers to start and end of an array (like STL containers do) then it's not a problem to do so, and determining cases like this isn't easy with how Clippy works.

2 Likes

I agree, it's not always a problem. I'm okay with false positives since I just want to use this to review code. I would be happy with just a way to find every str reference being converted to a pointer.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.