Library onload Initialization


#1

Is there a way to specify a function that is executed as soon as my library – written in Rust – gets loaded? Basically, I am looking for something like GCC’s __attribute__((constructor)) (or DllMain on Windows, though I would be content with a Linux-specific solution).

I need something like this because I am trying to implement a method of function hooking that is based on library injection. The injected library has to hook the functions as soon as it gets loaded. Is this possible with (nightly) Rust?


#2

No and it probably never will be. https://doc.rust-lang.org/complement-design-faq.html#there-is-no-life-before-or-after-main-(no-static-ctors/dtors)


#3

As @stebalien mentioned we don’t currently have a way to do so, but I wouldn’t say we’ll never have this kind of support, it seems like there’s possible to have legitimate use cases! I’m not sure what’d need to happen on the LLVM side here (e.g. how we express this to LLVM), but at least having a nightly-only unstable ability to do this (perhaps unsafe) doesn’t seem totally unreasonable!


#4

Hello,

My situation might be similar to this. However, my situation is that I have to link a 3rd party C library, which relies on __attribute__((constructor)) to perform certain setup. I’m wondering, after 3 years of development in Rust, is there any proper way to achieve this?

Thanks!


#5

I’ve writen similar code this based on https://github.com/geofft/redhook

fn main() {
    println!("Hello, world!");
}

#[link_section = ".init_array"]
pub static INITIALIZE: extern "C" fn() = ::rust_ctor;

#[no_mangle]
pub extern "C" fn rust_ctor() {
    println!("Before the world!");
}

It works on my machine, but I do not know when it is valid :<


#6

Hello, thanks for the reply. I’m not sure whether this is what I want. I’m new to the __attribute__((constructor)) usage. The situation in my case is that the 3rd party C library is offered as static libraries. Internally, they rely on __attribute__((constructor)) to perform setup. If I write a C program linked with their libraries, I need to use --whole-archive to make sure those __attribute__((constructor)) functions are not dropped during the linkage. However, I don’t need to use __attribute__((constructor)) functions in my Rust program. Again, those __attribute__((constructor)) are for the internal of 3rd party C library.

Now, I did the similar thing --whole-archive when I tried to compile and link my Rust program with those C static libraries. However, certain functionalities are missing from the C library and I’m suspecting rustc has some issue handling __attribute__((constructor)).