A numeric value shall not be transmuted to a function pointer

Guideline: A numeric value shall not be transmuted to a function pointer gui_gghCZVhoRV8Z
status: draft
tags: subset, undefined-behavior
category: required
decidability: decidable
scope: module
release: <TODO>

std::mem::transmute shall not be used with any numeric type (including floating point types) as the argument to the Src parameter, and any function pointer type as the argument to the Dst parameter.

Rationale: rat_71j2Ud06kthz
status: draft
parent needs: gui_gghCZVhoRV8Z

An all-zero numeric representation can produce a null function pointer and violate the function-pointer validity invariant at construction [FLS-FUNCTION-POINTER-TYPES]. A nonzero representation does not violate that invariant merely because it came from a numeric value, but non-nullness alone does not establish that it designates a function callable through the destination function pointer type.

In particular, the FLS defines calling a function with an ABI other than the ABI with which it was defined as undefined behavior [FLS-CALL-EXPRESSIONS]. A numeric value cannot establish that the address designates a function callable through the destination function pointer type. This guideline therefore imposes a conservative subset restriction on direct numeric-to-function-pointer transmutation.

The as operator cannot directly convert a numeric value to a function pointer. Direct numeric-to-raw-pointer as casts and numeric-to-pointer std::mem::transmute operations are prohibited by the guideline A numeric value shall not be converted to a pointer.

Non-Compliant Example: non_compl_ex_jg56Jyx1KbkE
status: draft
parent needs: gui_gghCZVhoRV8Z

Directly transmuting a numeric value to a function pointer is noncompliant, even if the resulting pointer is never called:

miri
#[allow(dead_code)]
fn f1(address: usize) {
  unsafe {
    let _function = std::mem::transmute::<usize, fn()>(address); // non-compliant
  }
}
Compliant Example: compl_ex_8S7Xw4sUk6kP
status: draft
parent needs: gui_gghCZVhoRV8Z

Obtain a function pointer from a function item instead of fabricating one from a numeric value:

fn target() {}

fn main() {
  let _handler: fn() = target;
}
Bibliography: bib_gghCZVhoRV8Z
status: draft
parent needs: gui_gghCZVhoRV8Z

[FLS-FUNCTION-POINTER-TYPES]

The Rust FLS. “Types and Traits - Indirection Types - Function Pointer Types.” https://rust-lang.github.io/fls/types-and-traits.html#fls_52thmi9hnoks

[FLS-CALL-EXPRESSIONS]

The Rust FLS. “Expressions - Call Expressions.” https://rust-lang.github.io/fls/expressions.html#fls_5yeq4oah58dl