【问题标题】:How to specify which ELF section to use in a Rust dylib如何指定在 Rust dylib 中使用哪个 ELF 部分
【发布时间】:2016-02-17 06:05:50
【问题描述】:

我可以使用 Rust dylib crate 类型创建共享对象,但不知道如何指定 ELF .init 部分。我有一个 C 程序,它使用dlopen() 加载共享对象,并且共享对象将在.init 注册类似于回调函数的东西。如果我写,编译会失败:

#[no_mangle]
pub extern fn _init() {
    ...

那么,

test.0.rs:(.text._init+0x0): multiple definition of `_init'

如何指定 ELF 部分(如 GCC 的 constructor 属性)或者是否有另一种方法来指定将在 .so 加载后立即调用的函数?

【问题讨论】:

    标签: rust elf


    【解决方案1】:

    直接的答案是使用#[link_section = "foo"] 属性。

    我试图对 GCC 在 OS X 上创建的内容进行逆向工程以复制它:

    pub extern fn do_a_thing() {
        println!("I was called by .init");
        cool_code();
    }
    
    #[link_section = "__DATA,__mod_init_func"]
    pub static CONSTRUCTOR: extern fn() = do_a_thing;
    
    fn cool_code() {
        println!("I'm just some code");
    }
    

    这确实在加载dlopen 时打印了两行,但随后整个程序出现了分段错误。我对这个早期初始化的细节了解得不够多,无法完全缩小范围。

    实际上可能是this bug,这表明问题可能只是因为println!中使用的内部数据结构。

    【讨论】:

    • 在我的情况下,[link_section = ".ctors"] 可以正常工作,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多