Casting `extern fn` to usize or fn pointer has changing address
Author: zjp-CNCreated Sep 10, 2026Updated Sep 10, 2026
The following code panics because __einit_array as *const () as usize is accessed earlier than __sinit_array as *const () as usize:
fn main() {
unsafe extern "C" {
fn __sinit_array();
fn __einit_array();
}
let n = __einit_array as *const () as usize - __sinit_array as *const () as usize;
dbg!(n);
}thread 'main' (15) panicked at src/main.rs:6:13:
attempt to subtract with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
note: in Miri, you may have to set `MIRIFLAGS=-Zmiri-env-forward=RUST_BACKTRACE` for the environment variable to have an effectAnd it's interesting to see the different cast may have different adreesses: playground
fn main() {
unsafe extern "C" {
fn __sinit_array();
fn __einit_array();
}
println!(
"__einit_array={:p} __sinit_array={:p}",
__einit_array as unsafe extern "C" fn(),
__sinit_array as unsafe extern "C" fn()
);
println!(
"__einit_array={:#x} __sinit_array={:#x}",
__einit_array as *const () as usize,
__sinit_array as *const () as usize
);
let _ = dbg!(__einit_array as *const ()) as usize - dbg!(__sinit_array as *const ()) as usize;
}Standard Error:
[src/main.rs:16:13] __einit_array as *const () = 0x000000000002ad0b
[src/main.rs:16:57] __sinit_array as *const () = 0x0000000000036939
thread 'main' (13) panicked at src/main.rs:16:13:
attempt to subtract with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
note: in Miri, you may have to set `MIRIFLAGS=-Zmiri-env-forward=RUST_BACKTRACE` for the environment variable to have an effect
Standard Output:
__einit_array=0x21467 __sinit_array=0x2148b
__einit_array=0x2ad0b __sinit_array=0x2ad2cDoes it make sense for miri to allow extern fn casting to an adreess?
extern static is not recognized by miri (playground), unless it's defined in Rust ( https://github.com/rust-lang/miri/pull/5230 ).
fn extern_fn() {
unsafe extern "C" {
fn __sinit_array();
}
dbg!(__sinit_array as unsafe extern "C" fn());
dbg!(__sinit_array as *const ());
}
fn extern_static() {
unsafe extern "C" {
static __sinit_array: usize;
}
dbg!(&raw const __sinit_array as *const ());
}
fn main() {
extern_fn();
extern_static();
}[src/main.rs:5:5] __sinit_array as unsafe extern "C" fn() = 0x000000000002144b
[src/main.rs:6:5] __sinit_array as *const () = 0x0000000000024f6a
error: unsupported operation: extern static `__sinit_array` is not supported by Miri
--> src/main.rs:13:21
|
13 | dbg!(&raw const __sinit_array as *const ());
| ^^^^^^^^^^^^^ unsupported operation occurred here
|
= help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support
= note: stack backtrace:
0: extern_static
at src/main.rs:13:21: 13:34
1: main
at src/main.rs:18:5: 18:20Source: rust-lang/miri