rust-lang / rust-lang/rust

`fn_addr_eq` docs suggest incorrect reasoning

Open
#160,202 20 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-docs C-bug I-lang-radar T-lang-docs T-libs T-opsem
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

View all comments

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 gptr points to g, and use that to inline the call to g.
  • Optimize the then branch to std::hint::assert_unchecked(false), and then replace it by arbitrary code (e.g. a trap).
  • Later during compilation, merge f and g into 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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.