`fn_addr_eq` docs suggest incorrect reasoning
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
The docs for fn_addr_eq say
Despite these false positives and false negatives, this comparison can still be useful. Specifically, if
- T is the same type as U, T is a subtype of U, or U is a subtype of T, and
- ptr::fn_addr_eq(f, g) returns true,
then calling f and calling g will be equivalent.
This is not correct, I think.
Consider this example:
unsafe fn f(x: i32) -> i32 { x }
unsafe fn g(x: i32) -> i32 { std::hint::assert_unchecked(x != 0); x }
fn main() {
let fptr = f as unsafe fn(i32) -> i32;
let gptr = g as unsafe fn(i32) -> i32;
if std::ptr::fn_addr_eq(fptr, gptr) {
// SAFETY: Calling `fptr(0)` here would be allowed, and according to the `fn_addr_eq`
// docs, inside this `if` calling `gptr` is equivalent to calling `fptr`.
unsafe { gptr(0) };
}
}
The compiler may now do the following:
- Realize that
gptrpoints tog, and use that to inline the call tog. - Optimize the
thenbranch tostd::hint::assert_unchecked(false), and then replace it by arbitrary code (e.g. a trap). - Later during compilation, merge
fandginto one function since they compile to the same assembly.
Now if we run this program we hit the trap, i.e., we have exhibited UB.
(See https://github.com/rust-lang/unsafe-code-guidelines/issues/589 for a wider discussion of the problem. When discussing this we were not aware that our libs docs actually make any claims in this regard.)
Cc @rust-lang/opsem @rust-lang/libs-api
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the fn_addr_eq documentation linked in the issue, then read the example and the discussion in unsafe-code-guidelines issue 589. Determine which claim about equivalent calls is invalid and revise the documentation accordingly, with wording that reflects the agreed Rust semantics. Done means the docs no longer make the disputed guarantee and the relevant reviewers agree with the explanation.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100