36 releases

0.2.8 Apr 16, 2024
0.2.7 Feb 26, 2024
0.2.6 Dec 12, 2023
0.2.5 Sep 26, 2023
0.1.6 Dec 30, 2018

#16 in Procedural macros

Download history 384137/week @ 2024-01-03 367579/week @ 2024-01-10 366505/week @ 2024-01-17 342603/week @ 2024-01-24 343240/week @ 2024-01-31 316784/week @ 2024-02-07 308855/week @ 2024-02-14 309900/week @ 2024-02-21 321543/week @ 2024-02-28 316097/week @ 2024-03-06 342942/week @ 2024-03-13 337556/week @ 2024-03-20 299388/week @ 2024-03-27 306617/week @ 2024-04-03 302902/week @ 2024-04-10 252374/week @ 2024-04-17

1,218,597 downloads per month
Used in 1,332 crates (280 directly)

Apache-2.0 OR MIT

22KB
263 lines

rust-ctor

Build Status docs.rs crates.io

Module initialization/teardown functions for Rust (like __attribute__((constructor)) in C/C++) for Linux, OSX, FreeBSD, NetBSD, Illumos, OpenBSD, DragonFlyBSD, Android, iOS, and Windows.

This library currently requires Rust > 1.31.0 at a minimum for the procedural macro support.

Idea inspired by this code in the Neon project.

Support

This library works and is regularly tested on Linux, OSX and Windows, with both +crt-static and -crt-static. Other platforms are supported but not tested as part of the automatic builds. This library will also work as expected in both bin and cdylib outputs, ie: the ctor and dtor will run at executable or library startup/shutdown respectively.

Warnings

Rust's philosophy is that nothing happens before or after main and this library explicitly subverts that. The code that runs in the ctor and dtor functions should be careful to limit itself to libc functions and code that does not rely on Rust's stdlib services.

For example, using stdout in a dtor function is a guaranteed panic. Consider using the libc-print crate for output to stderr/stdout during #[ctor] and #[dtor] methods. Other issues may involve signal processing or panic handling in that early code.

In most cases, sys_common::at_exit is a better choice than #[dtor]. Caveat emptor!

On some platforms, unloading of shared libraries may not actually happen until process exit, even if explicitly unloaded. The rules for this are arcane and difficult to understand. For example, thread-local storage on OSX will affect this (see this comment).

Examples

Marks the function foo as a module constructor, called when a static library is loaded or an executable is started:

    static INITED: AtomicBool = AtomicBool::new(false);

    #[ctor]
    fn foo() {
        INITED.store(true, Ordering::SeqCst);
    }

Creates a HashMap populated with strings when a static library is loaded or an executable is started (new in 0.1.7):

    #[ctor]
    /// This is an immutable static, evaluated at init time
    static STATIC_CTOR: HashMap<u32, &'static str> = {
        let mut m = HashMap::new();
        m.insert(0, "foo");
        m.insert(1, "bar");
        m.insert(2, "baz");
        m
    };

Print a message at shutdown time. Note that Rust may have shut down some stdlib services at this time.

    #[dtor]
    unsafe fn shutdown() {
        // Using println or eprintln here will panic as Rust has shut down
        libc::printf("Shutting down!\n\0".as_ptr() as *const i8);
    }

Under the Hood

The #[ctor] macro makes use of linker sections to ensure that a function is run at startup time.

The above example translates into the following Rust code (approximately):

    #[used]
    #[cfg_attr(any(target_os = "linux", target_os = "android"), link_section = ".init_array")]
    #[cfg_attr(target_os = "freebsd", link_section = ".init_array")]
    #[cfg_attr(target_os = "netbsd", link_section = ".init_array")]
    #[cfg_attr(target_os = "openbsd", link_section = ".init_array")]
    #[cfg_attr(target_os = "macos", link_section = "__DATA,__mod_init_func")]
    #[cfg_attr(target_os = "windows", link_section = ".CRT$XCU")]
    static FOO: extern fn() = {
        #[cfg_attr(any(target_os = "linux", target_os = "android"), link_section = ".text.startup")]
        extern fn foo() { /* ... */ };
        foo
    };

The #[dtor] macro effectively creates a constructor that calls libc::atexit with the provided function, ie roughly equivalent to:

    #[ctor]
    fn dtor_atexit() {
        libc::atexit(dtor);
    }

Dependencies

~325–780KB
~19K SLoC