Debian Codegraph @

debian/rust-vendor/ctor/docs/PREAMBLE.md

raw
1 Module initialization functions for Rust (like `__attribute__((constructor))` in
2 C/C++) for Linux, macOS, Windows, WASM, BSD-likes, and many others.
3
4 ```rust
5 use ctor::ctor;
6 use libc_print::*;
7
8 #[ctor(unsafe)]
9 fn foo() {
10 libc_println!("Life before main!");
11 }
12 ```
13
14 ## MSRV
15
16 For most platforms, this library currently has a MSRV of **Rust >= 1.60**.
17
18 The priority feature requires a MSRV of **Rust >= 1.85** on macOS targets.
19
20 MSRV for WASM targets is **Rust >= 1.85**.
21
22 ## Lightweight
23
24 `ctor` has no dependencies other than the `linktime-proc-macro` and
25 `link-section` crates. The proc-macro is only used to delegate to the
26 declarative macro and should have minimal effect on compilation time.
27
28 ## Support
29
30 This library works and is regularly tested on Linux, macOS, Windows, and
31 FreeBSD, with both `+crt-static` and `-crt-static` and `bin`/`cdylib` outputs.
32
33 Contributions to support other platforms or improve testing are welcome.
34
35 | OS | Supported | CI Tested |
36 | ------------ | --------- | --------- |
37 | Linux | βœ… | πŸ… |
38 | macOS | βœ… | πŸ… |
39 | Windows | βœ… | πŸ… |
40 | WASM πŸ•ΈοΈ | βœ… | πŸ… |
41 | FreeBSD | βœ… | πŸ’¨ |
42 | NetBSD | βœ… | πŸ’¨ |
43 | OpenBSD | βœ… | πŸ’¨ |
44 | DragonFlyBSD | βœ… | πŸ’¨ |
45 | Illumos | βœ… | - |
46 | Android | βœ… | - |
47 | iOS | βœ… | - |
48 | AIX | βœ… | - |
49 | Haiku | βœ… | - |
50 | VxWorks | βœ… | - |
51 | Xtensa | βœ… | - |
52 | NTO | βœ… | - |
53 | UEFI | ⚠️ | - |
54
55 - πŸ… Full CI (miri, address sanitizer, etc.)
56 - πŸ’¨ Smoke tests (varying levels)
57 - ⚠️ Needs more feedback
58 - πŸ•ΈοΈ WASM `wasm-unknown-unknown`, `wasm-wasip1`, `wasm-wasip2` are supported.
59
60 - `wasm-unknown-unknown` requires host environment support for `atexit` if used
61 with `dtor`.
62 - `wasm-wasip2` may require you to manually call `__wasm_call_ctors` and
63 `__wasm_call_dtors` at the appropriate times.
64
65 ## Warnings
66
67 Rust's philosophy is that nothing happens before or after main and this library
68 explicitly subverts that. The code that runs in the `ctor` and `dtor` functions
69 should be careful to limit itself to `libc` functions and code that does not
70 rely on Rust's stdlib services.
71
72 See [`::life_before_main`](crate::life_before_main) for more information.
73
74 ## Usage
75
76 `#[ctor]` decorates a function item to be called as a module constructor. Both
77 free (a global `fn()`) and impl functions (`Self::method()`) are supported.
78
79 The example below marks the function `foo` as a module constructor, called when
80 a static library is loaded or an executable is started:
81
82 ```rust
83 use std::sync::atomic::{AtomicBool, Ordering};
84 use ctor::ctor;
85
86 static INITED: AtomicBool = AtomicBool::new(false);
87
88 #[ctor(unsafe)]
89 fn foo() {
90 // ... (do something)
91 INITED.store(true, Ordering::SeqCst);
92 }
93 ```
94
95 Implementation methods can also be decorated with `#[ctor]`, as long as they
96 have no `self` parameter:
97
98 ```rust
99 use ctor::ctor;
100
101 struct MyStruct {
102 // ...
103 }
104
105 impl MyStruct {
106 /// Ensure the required C library is loaded at startup time.
107 #[ctor(unsafe)]
108 fn load_required_c_library() {
109 // ... (do something)
110 }
111 }
112 ```
113
114 ### `static` items
115
116 The `#[ctor]` macro also supports decorating `static` items, which are
117 initialized at startup time. `static` items declared in this way must not be
118 accessed from other threads before the module constructors have run (if this is
119 done without caution, the initializer may panic).
120
121 The below example creates a `HashMap` populated with strings, which would
122 normally not be possible with `const` items:
123
124 ```rust
125 use std::collections::HashMap;
126 use ctor::ctor;
127
128 #[ctor(unsafe)]
129 /// This is an immutable static, evaluated at init time
130 static STATIC_CTOR: HashMap<u32, &'static str> = {
131 let mut m = HashMap::new();
132 m.insert(0, "foo");
133 m.insert(1, "bar");
134 m.insert(2, "baz");
135 m
136 };
137 ```
138
139 ### As a building block
140
141 The `#[ctor]` macro can be used as a building block for more complex
142 initialization logic. Use the [`declarative::ctor`](crate::declarative::ctor) to
143 easily export macros that re-use `ctor` functionality.
144
145 ```rust
146 use ctor::ctor;
147
148 trait Driver: 'static + Send + Sync {
149 // ...
150 }
151
152 static DRIVERS: ::std::sync::Mutex<Vec<Box<dyn Driver>>> = ::std::sync::Mutex::new(Vec::new());
153
154 fn register_driver(name: &'static str, driver: impl Driver) {
155 DRIVERS.lock().unwrap().push(Box::new(driver));
156 }
157
158 #[ctor(unsafe, priority = late)]
159 fn walk_drivers() {
160 for driver in DRIVERS.lock().unwrap().iter() {
161 // ...
162 }
163 }
164
165 macro_rules! register_driver {
166 ($name:expr, $driver:expr) => {
167 $crate::ctor::declarative::ctor!(
168 #[ctor(unsafe, anonymous, priority = 1)]
169 fn register() {
170 register_driver($name, $driver);
171 }
172 );
173 };
174 }
175
176 struct MyDriver {
177 // ...
178 }
179
180 impl Driver for MyDriver {
181 // ...
182 }
183
184 register_driver!("my_driver", MyDriver {});
185 ```
186
187 ## Under the Hood
188
189 The `#[ctor]` macro makes use of linker sections to ensure that a function is
190 run at startup time.
191
192 The above example translates into the following Rust code (approximately):
193
194 ```rust
195 #[used]
196 #[cfg_attr(target_os = "linux", link_section = ".init_array")]
197 #[cfg_attr(target_vendor = "apple", link_section = "__DATA,__mod_init_func,mod_init_funcs")]
198 #[cfg_attr(target_os = "windows", link_section = ".CRT$XCU")]
199 /* ... other platforms elided ... */
200 static FOO: extern fn() = {
201 extern fn foo() { /* ... */ };
202 foo
203 };
204 ```
205
206 ## Inspiration
207
208 The idea for `ctor` was originally inspired by the Neon project.