`UnwindException` is aligned to 8: LLVM libunwind faults on it when a throw reaches the system unwinder (Rust host on musl)

Aperta Adatta ai principianti
#14,789 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
73/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
linux, rust

Direzione di ricerca

Inizia con UnwindException e la definizione di EXC_OBJECT in crates/perry-runtime/src/eh.rs; il report indica che l’allineamento a 16 byte è un requisito e suggerisce #[repr(C, align(16))]. Riproduci il caso host con offset usando PERRY_EH_WALKER=off e un throw non intercettato, quindi verifica che termini con il messaggio di errore invece che con SIGSEGV. L’issue non indica alcun file di test.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

area:runtime-gc effort:S impact:low platform:linux type:bug

What happened

UnwindException in crates/perry-runtime/src/eh.rs is #[repr(C)] with u64 and pointer-sized fields, so the per-thread EXC_OBJECT is aligned to 8. The unwinding ABI asks for 16, and LLVM's libunwind relies on it: _Unwind_RaiseException clears two words of the object with movaps. When the object lands on an address that is 8 modulo 16 and a throw reaches the system unwinder, the process dies with SIGSEGV and prints nothing.

I hit this in a Rust host built for x86_64-unknown-linux-musl that links --output-type staticlib output. Rust's std brings LLVM's libunwind on that target. I have not seen it in anything Perry links itself (details at the end), so this is low priority for most users, but the fix looks like one line.

What you expected

An uncaught throw prints the error and exits 1, wherever the linker happens to put the object.

Minimal reproduction

app.ts

export function thrower(n: number): number {
  if (n > 2) { throw new Error("thrown " + n); }
  return n;
}

host/Cargo.toml

[package]
name = "host"
version = "0.0.0"
edition = "2021"
publish = false

[profile.release]
opt-level = 2

[features]
shift = []

host/build.rs

fn main() {
    println!("cargo:rerun-if-env-changed=APP_OBJECT");
    let path = std::env::var("APP_OBJECT").expect("set APP_OBJECT to the pre-linked object");
    println!("cargo:rerun-if-changed={path}");
    println!("cargo:rustc-link-arg={path}");
    // The object comes after rustc's own libraries on the link line, so name these again.
    println!("cargo:rustc-link-arg=-lc");
    println!("cargo:rustc-link-arg=-lgcc");
}

host/src/main.rs

//! Owns `main`, calls one exported function of a module compiled by Perry to a static library.
//! `main` is a plain C entry point: Rust's own start-up wraps `main` in a frame that aborts on
//! a foreign exception, which would hide what happens to an uncaught throw.
//!
//! usage: host            three throws, each caught by js_trap_call
//!        host uncaught   one throw with nothing on the stack to catch it
#![no_main]
use std::ffi::{c_char, c_int, c_void, CStr};

type Body = unsafe extern "C-unwind" fn(*mut c_void);

extern "C-unwind" {
    fn perry_module_init();
    fn perry_fn_app_ts__thrower(n: f64) -> f64;
}
extern "C" {
    fn js_trap_call(body: Body, ctx: *mut c_void) -> i32;
    fn js_clear_exception();
}

unsafe extern "C-unwind" fn init(_: *mut c_void) { perry_module_init(); }
unsafe extern "C-unwind" fn call(ctx: *mut c_void) { perry_fn_app_ts__thrower(*(ctx as *const f64)); }

// One 8-byte thread-local of the host's own. It changes nothing but the layout of the
// thread-local block, and so whether Perry's EXC_OBJECT lands on a multiple of 16.
#[cfg(feature = "shift")]
thread_local! {
    static PAD: std::cell::Cell<u64> = const { std::cell::Cell::new(1) };
}

/// # Safety
/// Called once by the C start-up code.
#[no_mangle]
pub unsafe extern "C-unwind" fn main(argc: c_int, argv: *const *const c_char) -> c_int {
    #[cfg(feature = "shift")]
    PAD.with(|p| p.set(p.get() + argc as u64));
    let uncaught = argc > 1 && CStr::from_ptr(*argv.offset(1)).to_str() == Ok("uncaught");
    println!("module init: trap returned {}", js_trap_call(init, std::ptr::null_mut()));
    if uncaught {
        perry_fn_app_ts__thrower(3.0);
        println!("it returned");
        return 0;
    }
    for n in 0..6 {
        let mut value = n as f64;
        let threw = js_trap_call(call, (&raw mut value).cast());
        println!("thrower({n}): trap returned {threw}");
        if threw != 0 { js_clear_exception(); }
    }
    println!("done");
    0
}

Command you ran (needs the linux-x86_64-musl build of perry as perry, jq, binutils, and a Rust toolchain with the x86_64-unknown-linux-musl target):

perry compile app.ts --no-cache --output-type staticlib -o libapp.a
RUNTIME=$(jq -r '.link_archives[] | select(.role == "runtime") | .path' libapp.linkdeps.json)

# One object with private symbols. Linked directly, the runtime archive's copy of Rust's std
# collides with the host's (duplicate symbol: rust_eh_personality).
# --whole-archive on libapp.a: see #14787.
KEEP="perry_module_init perry_fn_app_ts__thrower js_trap_call js_clear_exception"
U=""; K=""; for s in $KEEP; do U="$U -u $s"; K="$K --keep-global-symbol=$s"; done
ld -r --force-group-allocation $U -o all.o --whole-archive libapp.a --no-whole-archive "$RUNTIME"
# The two --remove-section options drop GCC 15 LTO data that GCC 16 refuses to read.
objcopy $K --remove-section='.gnu.lto_*' --remove-section='.gnu.debuglto_*' all.o app.o

run() {   # <label> <command...>
  label=$1; shift
  "$@" > out.txt 2>&1; code=$?
  echo "$label: exit $code: $(grep -v -e '^ *at ' -e '^Segmentation fault' out.txt | tail -n 1)"
}
for variant in plain shifted; do
  FEATURES=""; [ "$variant" = shifted ] && FEATURES="--features shift"
  (cd host && APP_OBJECT="$PWD/../app.o" CARGO_TARGET_DIR="../target-$variant" \
    cargo build -q --release --target x86_64-unknown-linux-musl $FEATURES) || exit 1
  BIN=target-$variant/x86_64-unknown-linux-musl/release/host
  echo "$variant: EXC_OBJECT at offset 0x$(readelf -sW "$BIN" | awk '$4 == "TLS" && $3 == 64 && /2eh10EXC_OBJECT/ {print $2}' | sed 's/^0*//') of the thread-local block"
  run "$variant, throws caught by js_trap_call" "$BIN"
  run "$variant, the same with PERRY_EH_WALKER=off" env PERRY_EH_WALKER=off "$BIN"
  run "$variant, a throw nothing catches" "$BIN" uncaught
done

Environment

  • Perry version: 0.5.1665
  • Host OS: Debian testing (forky), x86_64, kernel 7.2.15, GCC 16.2.0, GNU ld 2.47.50
  • Target: --output-type staticlib from the linux-x86_64-musl build, linked into a Rust host for x86_64-unknown-linux-musl
  • Rust toolchain (for the host only): rustc 1.99.0-nightly (b6839f4d0 2026-07-17)
  • Installed via: perry-linux-x86_64-musl.tar.gz from the v0.5.1665 release

The compiler ran inside a bubblewrap sandbox with no network and PERRY_NO_AUTO_FETCH=1. Rust's musl std came from an unpacked rust-std component passed with RUSTFLAGS=--sysroot, not from rustup target add. Nothing else differs from the commands above.

Diagnostic output

Output of the script, with the compiler's progress lines removed:

plain: EXC_OBJECT at offset 0x130 of the thread-local block
plain, throws caught by js_trap_call: exit 0: done
plain, the same with PERRY_EH_WALKER=off: exit 0: done
plain, a throw nothing catches: exit 1: Error: thrown 3
shifted: EXC_OBJECT at offset 0x138 of the thread-local block
shifted, throws caught by js_trap_call: exit 0: done
shifted, the same with PERRY_EH_WALKER=off: exit 139: thrower(2): trap returned 0
shifted, a throw nothing catches: exit 139: module init: trap returned 0

In the two lines with exit 139 the text after the code is the last thing the host printed before it died.

From a core dump of shifted, host uncaught:

_Unwind_RaiseException+0x47:   movaps %xmm0,0x10(%r12)      r12 = 0x7fa4e0a43178

r12 is the exception object, 8 modulo 16. strace shows SIGSEGV {si_code=SI_KERNEL, si_addr=NULL}, which is what a misaligned SSE store gives. _Unwind_RaiseException in this binary calls unw_getcontext, unw_init_local and unw_step, so it is LLVM's.

Anything else

The one extra 8-byte thread-local in the shifted build changes nothing but the layout. It stands in for whatever a real host adds.

With Perry's own stack walker carrying the throw nothing goes wrong, so the fault needs the walker to decline: nothing on the stack handles the throw, or PERRY_EH_WALKER=off.

The Itanium C++ ABI, exception handling, Level I, section 1.2: "An _Unwind_Exception object must be double-word aligned." GCC's unwind.h declares the struct with __attribute__((__aligned__)).

Suggested fix, not tried, since I have not built Perry from source: #[repr(C, align(16))] on UnwindException. main at 883909c3 still has plain #[repr(C)].

Where I did not see it:

  • Six small programs that Perry linked itself as glibc executables. EXC_OBJECT sat at 8 modulo 16 in five of them. Caught throws, caught throws with PERRY_EH_WALKER=off and an uncaught throw all behaved correctly, 18 of 18 runs. They use libgcc_s.so.1, whose _Unwind_RaiseException on this machine has no aligned SSE store through the object.
  • I could not test an executable from Perry's own --libc musl target, because linking one failed here on the LTO data mentioned in the script. Which unwinder such an executable gets decides whether it is affected.

This report was prepared with the help of an AI coding assistant. Every command and output above was run on the machine described.

Lingua principale
Rust
Stelle
4.9k
Fork
166
Merge medio
4h 54m
PR unite (30g)
909

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di PerryTS/perry

Tutte le issue di PerryTS/perry

Issue simili

Altre issue su Rust

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.