Should this lint trigger even if the access is checked e.g with ptr.as_ref/as_mut? The lint describes that it is to ensure unchecked access is not done ever, but does using as_ref/as_mut on pointers not count as checked access?
This arises a lot when implementing COM classes using the windows crate which is annoying.
the lint is about checking the validity of raw pointers, as_ref() only checks for null, which is not enough to be safe to dereference a raw pointer. the pointer must be valid. quoting the documentation for pointer types:
Working with raw pointers in Rust is uncommon, typically limited to a few patterns. Raw pointers can be out-of-bounds, unaligned, or null. However, when loading from or storing to a raw pointer, it must be valid for the given access and aligned.
if you use raw pointer as parameter types in public APIs, and the pointer is dereferenced in this API, it will be unsound to NOT mark the function unsafe, otherwise, the caller in safe code can cause UB by simply passing an invalid pointer as argument, e.g.
fn main() {
let p = std::ptr::dangling();
totally_safe_api_I_promise(p); //<--- UB if the function derefereces the raw pointer
}
if you don't want to mark many public APIs as unsafe, and you have a way to check for pointer validity at runtime, maybe create a wrapper type that checks the validity of the pointer eagerly, then use the wrapper type instead of raw pointers with your public API. this way, you only need to make the constructor of the wrapper unsafe, not every API.
I see. The problem is that I do not own the API, Microsoft does. As such @rylev or @kennykerr may be the persons to answer what would be best way to proceed.
that trait method definition is indeed problematic, it cannot be meaningfully implemented in a sound way, using a raw pointer as parameter. IMO, for this kind of functions, the parameter can just use a regular reference instead of raw pointers.
however, since they are mechanically generated from C++ API, I don't how feasible to make the change, because there may not be enough type information or metadata about memory safety properties of the parameters.