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!