• Stars
    star
    714
  • Rank 63,413 (Top 2 %)
  • Language
    Rust
  • License
    Apache License 2.0
  • Created almost 6 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Module initialization/global constructor functions for Rust

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);
    }

More Repositories

1

webfont-dl

Webfont Downloader
JavaScript
332
star
2

stylus

Lightweight status page for home infrastructure
Rust
122
star
3

nanojson

A tiny, compliant JSON parser and writer for Java
Java
101
star
4

longshot

API and CLI for ECAM-based Delonghi machines
Rust
90
star
5

automedia

A set of tools for automatically managing bitrot and format in large quantities of media
Python
90
star
6

rust-libc-print

#[no_std] print equivalent for Rust
Rust
57
star
7

bootstrap

Bootstrapping VM for bare metal to trusted C compilation
Assembly
45
star
8

jquery-noclickdelay

Removes the 300ms click delay from iOS webviews
JavaScript
32
star
9

keepcalm

Simple shared types for multi-threaded Rust programs
Rust
23
star
10

progscrape

progscrape.com source
Rust
21
star
11

brew-a-coffee-demo

Demo repo for a Github Action that brews coffee (simulator only)
20
star
12

dress-simulator

Opinionated Dress Color Simulator
HTML
18
star
13

oblivious-cpu

A re-implementation of ShapeCPU
Java
18
star
14

adventure

Port of the 550 point adventure game to the web
Java
16
star
15

kalos

Kalos embeddable scripting language
C
12
star
16

progscrape-android

Android app for progscrape.com
Java
10
star
17

Charbase

The source for charbase.com
Python
6
star
18

Stencil

Rich templating system for Java webapps
Java
6
star
19

gibbet-hill

Gibbet Hill - Bram Stoker
6
star
20

javausb

Java USB interface, build on JNA/libusb
Java
5
star
21

reedsolomon-ecc

Reed-solomon ECC generator in Java
Java
5
star
22

unifi-rpi-docker

UniFi Docker Raspberry Pi
Dockerfile
4
star
23

snippets

Random snippets
Rascal
3
star
24

ffmpeg-omx-rpi-docker

FFMPEG configured for OMX on Raspberry Pi
Dockerfile
2
star
25

gst-omx-rpi-docker

Dockerfile for working GStreamer w/OMX
Dockerfile
2
star
26

replies-and-more

Replies and More for Google+
JavaScript
2
star
27

video4all

Automatically exported from code.google.com/p/video4all
JavaScript
2
star
28

android-docker-slim

Slimmed down version of https://hub.docker.com/r/bitriseio/android-ndk/
1
star
29

unsync_channel

Rust
1
star
30

deno-op2-presentation

Jupyter Notebook
1
star
31

gwt-rpc-plus

Automatically exported from code.google.com/p/gwt-rpc-plus
Java
1
star
32

requirejs-ember-handlebars

Require.js plugin to pre-compile Ember.js handlebar templates
JavaScript
1
star
33

Stencil-Web

Website for Stencil
1
star
34

no-mans-sky-recipes

Recipes for No Man's Sky
JavaScript
1
star
35

gpsclock

GPS Clock
KiCad Layout
1
star