SegFault when linking against shared libraries on Alpine

Hi!

Recently I've encountered a problem of rustc on Alpine: linking against any share libraries works fine but results in a binary which generate SegFault errors all the time? Could I get some help here?

Below is a simple and reproducible example, tested on Alpine 3.18:

main.rs:

use std::os::raw::c_int;
#[link(name = "test")]
extern "C" {
    fn testtt() -> c_int;
}
fn main() {
    unsafe { testtt() };
}

test.c:

int testtt() {
  return 32;
}

Generate libtest shared library:

gcc test.c -shared -o libtest.so -fPIC

Compile:

LIBRARY_PATH=.  rustc  -g main.rs

Check and run:

$ LD_LIBRARY_PATH=. ldd ./main
	/lib/ld-musl-x86_64.so.1 (0x7fe41d1f4000)
	libtest.so => ./libtest.so (0x7fe41d186000)

$ LD_LIBRARY_PATH=.  ./main
Segmentation fault

did you run the program under gdb? the debugger should be able to catch the signal and show the actual offending instruction location and the call stack.

Yes, the instruction causing SegFault is the one loading/calling dynamic symbol testtt, and backtrace has little useful information:

(gdb) backtrace
#0  0x0000000000000000 in ?? ()
#1  0x00007ffff7f9d657 in main::main () at main.rs:17

Works fine.

LD_LIBRARY_PATH=. ldd ./main
        /lib/ld-musl-x86_64.so.1 (0x7f4d49615000)
        libtest.so => ./libtest.so (0x7f4d495bf000)
        libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0x7f4d495a1000)
        libc.musl-x86_64.so.1 => /lib/ld-musl-x86_64.so.1 (0x7f4d49615000)

Did you install rust (& gcc) using apk?

Can you try

use std::os::raw::c_int;
extern "C" {
    fn testtt() -> c_int;
}
fn main() {
    unsafe { testtt() };
}

and

LIBRARY_PATH=.  rustc  -g main.rs -ltest

Interesting difference between your ldd output and that of OP is that you link musl libc dynamically. Maybe that makes a difference?

Did you install rust (& gcc) using apk?

No, apk doesn't offer rust or cargo. AFAIK installing rust on apline by rustup is the only way to use it.

Works fine.

May I have your configuration: the stable or nightly channel? and the compiler options? and OS version?

Problem solved, by adding -C target-feature=-crt-static flag to rustc.

ref: Tracking issue for musl host toolchain · Issue #59302 · rust-lang/rust · GitHub

the alpine community repository does have rust available. there's only stable rust though, nightly is unavailable.

oh, that explains why @jonh and I didn't encounter the crash. the crt-static feature is turned off by default by the apk community package maintainer. see this patch:

https://git.alpinelinux.org/aports/tree/community/rust/musl-fix-linux_musl_base.patch?h=3.18-stable#n23

It is helpful information, thanks for pointing out that!