Lily Mara
Lily Mara

Reputation: 4128

Segmentation fault doing dynamic loading in OSX

I'm trying to do some dynamic library loading in Rust. I'm getting a segmentation fault when passing a large Vec from a dynamically loaded library function. It's a basic function that creates a Vec<i32> of a specified size. If the Vec gets much bigger than 8MB, the program hits a segfault on OSX. I haven't had the same problem when running on linux, can anyone look at this and tell me if I'm doing something wrong here? I'm running this with:

$ cargo build --release
$ ./target/release/linkfoo
8281
[1]    84253 segmentation fault  ./target/release/linkfoo

Cargo.toml

[package]
name = "linkfoo"
version = "0.1.0"
authors = ["Nate Mara <[email protected]>"]

[dependencies]
libloading = "0.3.0"

[lib]
name = "foo"
crate-type = ["dylib"]

main.rs

extern crate libloading as lib;

fn main() {
    let dylib = lib::Library::new("./target/release/libfoo.dylib").expect("Failed to load library");
    let func = unsafe {
        let wrapped_func: lib::Symbol<fn(&[i32]) -> Vec<i32>> = dylib.get(b"alloc")
            .expect("Failed to load function");

        wrapped_func.into_raw()
    };

    let args = vec![8182];
    println!("{}", func(&args).len());
}

lib.rs

#[no_mangle]
pub fn alloc(args: &[i32]) -> Vec<i32> {
    let size = args[0] as usize;
    let mut mat = Vec::with_capacity(size);

    for _ in 0..size {
        mat.push(0);
    }

    mat
}

Upvotes: 4

Views: 384

Answers (1)

Lily Mara
Lily Mara

Reputation: 4128

Rust uses the system allocator for dynamic libraries, and jemalloc for all other code. This difference in loaders was causing the segfault, and I was able to fix it by adding this to the top of main.rs:

#![feature(alloc_system)]
extern crate alloc_system;

Upvotes: 1

Related Questions