| 1 |
The crate is part of the [`linktime`](https://crates.io/crates/linktime) project. |
| 2 |
|
| 3 |
[](https://github.com/mmastrac/linktime) [](https://crates.io/crates/link-section) [](https://github.com/mmastrac/linktime/actions/workflows/rust.yml) |
| 4 |
|
| 5 |
|
| 6 |
| crate | | |
| 7 |
| --- | --- | |
| 8 |
| `linktime`<br>[](https://docs.rs/linktime) [](https://crates.io/crates/linktime) | Convenience crate for `ctor`, `dtor` and `link-section` | |
| 9 |
| `ctor`<br>[](https://docs.rs/ctor) [](https://crates.io/crates/ctor) | Module initialization functions before main | |
| 10 |
| `dtor`<br>[](https://docs.rs/dtor) [](https://crates.io/crates/dtor) | Module shutdown functions before main | |
| 11 |
| `link-section`<br>[](https://docs.rs/link-section) [](https://crates.io/crates/link-section) | Linker-managed typed (slices) and untyped sections | |
| 12 |
| `scattered-collect`<br>[](https://docs.rs/scattered-collect) [](https://crates.io/crates/scattered-collect) | Linker-managed collections: slices, sorted slices, maps | |
| 13 |
# ctor |
| 14 |
Module initialization functions for Rust (like `__attribute__((constructor))` in |
| 15 |
C/C++) for Linux, macOS, Windows, WASM, BSD-likes, and many others. |
| 16 |
|
| 17 |
```rust |
| 18 |
use ctor::ctor; |
| 19 |
use libc_print::*; |
| 20 |
|
| 21 |
#[ctor(unsafe)] |
| 22 |
fn foo() { |
| 23 |
libc_println!("Life before main!"); |
| 24 |
} |
| 25 |
``` |
| 26 |
|
| 27 |
## MSRV |
| 28 |
|
| 29 |
For most platforms, this library currently has a MSRV of **Rust >= 1.60**. |
| 30 |
|
| 31 |
The priority feature requires a MSRV of **Rust >= 1.85** on macOS targets. |
| 32 |
|
| 33 |
MSRV for WASM targets is **Rust >= 1.85**. |
| 34 |
|
| 35 |
## Lightweight |
| 36 |
|
| 37 |
`ctor` has no dependencies other than the `linktime-proc-macro` and |
| 38 |
`link-section` crates. The proc-macro is only used to delegate to the |
| 39 |
declarative macro and should have minimal effect on compilation time. |
| 40 |
|
| 41 |
## Support |
| 42 |
|
| 43 |
This library works and is regularly tested on Linux, macOS, Windows, and |
| 44 |
FreeBSD, with both `+crt-static` and `-crt-static` and `bin`/`cdylib` outputs. |
| 45 |
|
| 46 |
Contributions to support other platforms or improve testing are welcome. |
| 47 |
|
| 48 |
| OS | Supported | CI Tested | |
| 49 |
| ------------ | --------- | --------- | |
| 50 |
| Linux | β
| π
| |
| 51 |
| macOS | β
| π
| |
| 52 |
| Windows | β
| π
| |
| 53 |
| WASM πΈοΈ | β
| π
| |
| 54 |
| FreeBSD | β
| π¨ | |
| 55 |
| NetBSD | β
| π¨ | |
| 56 |
| OpenBSD | β
| π¨ | |
| 57 |
| DragonFlyBSD | β
| π¨ | |
| 58 |
| Illumos | β
| - | |
| 59 |
| Android | β
| - | |
| 60 |
| iOS | β
| - | |
| 61 |
| AIX | β
| - | |
| 62 |
| Haiku | β
| - | |
| 63 |
| VxWorks | β
| - | |
| 64 |
| Xtensa | β
| - | |
| 65 |
| NTO | β
| - | |
| 66 |
| UEFI | β οΈ | - | |
| 67 |
|
| 68 |
- π
Full CI (miri, address sanitizer, etc.) |
| 69 |
- π¨ Smoke tests (varying levels) |
| 70 |
- β οΈ Needs more feedback |
| 71 |
- πΈοΈ WASM `wasm-unknown-unknown`, `wasm-wasip1`, `wasm-wasip2` are supported. |
| 72 |
|
| 73 |
- `wasm-unknown-unknown` requires host environment support for `atexit` if used |
| 74 |
with `dtor`. |
| 75 |
- `wasm-wasip2` may require you to manually call `__wasm_call_ctors` and |
| 76 |
`__wasm_call_dtors` at the appropriate times. |
| 77 |
|
| 78 |
## Warnings |
| 79 |
|
| 80 |
Rust's philosophy is that nothing happens before or after main and this library |
| 81 |
explicitly subverts that. The code that runs in the `ctor` and `dtor` functions |
| 82 |
should be careful to limit itself to `libc` functions and code that does not |
| 83 |
rely on Rust's stdlib services. |
| 84 |
|
| 85 |
See [`::life_before_main`](crate::life_before_main) for more information. |
| 86 |
|
| 87 |
## Usage |
| 88 |
|
| 89 |
`#[ctor]` decorates a function item to be called as a module constructor. Both |
| 90 |
free (a global `fn()`) and impl functions (`Self::method()`) are supported. |
| 91 |
|
| 92 |
The example below marks the function `foo` as a module constructor, called when |
| 93 |
a static library is loaded or an executable is started: |
| 94 |
|
| 95 |
```rust |
| 96 |
use std::sync::atomic::{AtomicBool, Ordering}; |
| 97 |
use ctor::ctor; |
| 98 |
|
| 99 |
static INITED: AtomicBool = AtomicBool::new(false); |
| 100 |
|
| 101 |
#[ctor(unsafe)] |
| 102 |
fn foo() { |
| 103 |
// ... (do something) |
| 104 |
INITED.store(true, Ordering::SeqCst); |
| 105 |
} |
| 106 |
``` |
| 107 |
|
| 108 |
Implementation methods can also be decorated with `#[ctor]`, as long as they |
| 109 |
have no `self` parameter: |
| 110 |
|
| 111 |
```rust |
| 112 |
use ctor::ctor; |
| 113 |
|
| 114 |
struct MyStruct { |
| 115 |
// ... |
| 116 |
} |
| 117 |
|
| 118 |
impl MyStruct { |
| 119 |
/// Ensure the required C library is loaded at startup time. |
| 120 |
#[ctor(unsafe)] |
| 121 |
fn load_required_c_library() { |
| 122 |
// ... (do something) |
| 123 |
} |
| 124 |
} |
| 125 |
``` |
| 126 |
|
| 127 |
### `static` items |
| 128 |
|
| 129 |
The `#[ctor]` macro also supports decorating `static` items, which are |
| 130 |
initialized at startup time. `static` items declared in this way must not be |
| 131 |
accessed from other threads before the module constructors have run (if this is |
| 132 |
done without caution, the initializer may panic). |
| 133 |
|
| 134 |
The below example creates a `HashMap` populated with strings, which would |
| 135 |
normally not be possible with `const` items: |
| 136 |
|
| 137 |
```rust |
| 138 |
use std::collections::HashMap; |
| 139 |
use ctor::ctor; |
| 140 |
|
| 141 |
#[ctor(unsafe)] |
| 142 |
/// This is an immutable static, evaluated at init time |
| 143 |
static STATIC_CTOR: HashMap<u32, &'static str> = { |
| 144 |
let mut m = HashMap::new(); |
| 145 |
m.insert(0, "foo"); |
| 146 |
m.insert(1, "bar"); |
| 147 |
m.insert(2, "baz"); |
| 148 |
m |
| 149 |
}; |
| 150 |
``` |
| 151 |
|
| 152 |
### As a building block |
| 153 |
|
| 154 |
The `#[ctor]` macro can be used as a building block for more complex |
| 155 |
initialization logic. Use the [`declarative::ctor`](crate::declarative::ctor) to |
| 156 |
easily export macros that re-use `ctor` functionality. |
| 157 |
|
| 158 |
```rust |
| 159 |
use ctor::ctor; |
| 160 |
|
| 161 |
trait Driver: 'static + Send + Sync { |
| 162 |
// ... |
| 163 |
} |
| 164 |
|
| 165 |
static DRIVERS: ::std::sync::Mutex<Vec<Box<dyn Driver>>> = ::std::sync::Mutex::new(Vec::new()); |
| 166 |
|
| 167 |
fn register_driver(name: &'static str, driver: impl Driver) { |
| 168 |
DRIVERS.lock().unwrap().push(Box::new(driver)); |
| 169 |
} |
| 170 |
|
| 171 |
#[ctor(unsafe, priority = late)] |
| 172 |
fn walk_drivers() { |
| 173 |
for driver in DRIVERS.lock().unwrap().iter() { |
| 174 |
// ... |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
macro_rules! register_driver { |
| 179 |
($name:expr, $driver:expr) => { |
| 180 |
$crate::ctor::declarative::ctor!( |
| 181 |
#[ctor(unsafe, anonymous, priority = 1)] |
| 182 |
fn register() { |
| 183 |
register_driver($name, $driver); |
| 184 |
} |
| 185 |
); |
| 186 |
}; |
| 187 |
} |
| 188 |
|
| 189 |
struct MyDriver { |
| 190 |
// ... |
| 191 |
} |
| 192 |
|
| 193 |
impl Driver for MyDriver { |
| 194 |
// ... |
| 195 |
} |
| 196 |
|
| 197 |
register_driver!("my_driver", MyDriver {}); |
| 198 |
``` |
| 199 |
|
| 200 |
## Under the Hood |
| 201 |
|
| 202 |
The `#[ctor]` macro makes use of linker sections to ensure that a function is |
| 203 |
run at startup time. |
| 204 |
|
| 205 |
The above example translates into the following Rust code (approximately): |
| 206 |
|
| 207 |
```rust |
| 208 |
#[used] |
| 209 |
#[cfg_attr(target_os = "linux", link_section = ".init_array")] |
| 210 |
#[cfg_attr(target_vendor = "apple", link_section = "__DATA,__mod_init_func,mod_init_funcs")] |
| 211 |
#[cfg_attr(target_os = "windows", link_section = ".CRT$XCU")] |
| 212 |
/* ... other platforms elided ... */ |
| 213 |
static FOO: extern fn() = { |
| 214 |
extern fn foo() { /* ... */ }; |
| 215 |
foo |
| 216 |
}; |
| 217 |
``` |
| 218 |
|
| 219 |
## Inspiration |
| 220 |
|
| 221 |
The idea for `ctor` was originally inspired by the Neon project. |
| 222 |
# Re-exporting from another crate |
| 223 |
|
| 224 |
The macros assume this crate is available as a direct dependency, resolving their |
| 225 |
support paths through the crate's own name. If you re-export this crate's items as |
| 226 |
part of your own crate (so that downstream users don't need to depend on it |
| 227 |
directly), you have two options: |
| 228 |
|
| 229 |
- (preferred) use the declarative macro form. It resolves its support paths |
| 230 |
relative to your re-export, so no extra configuration is required. |
| 231 |
- Alternatively, pass the `crate_path` attribute to redirect the macro's |
| 232 |
generated output to the path where this crate has been re-exported. |
| 233 |
|
| 234 |
See the `crate_path` entry in the *Macro Attributes* section below for the exact |
| 235 |
syntax for this crate. |
| 236 |
# Crate Features |
| 237 |
|
| 238 |
| Cargo feature | Description | |
| 239 |
| --- | --- | |
| 240 |
| `priority` | Enable support for the priority parameter. | |
| 241 |
| `proc_macro` | Enable support for the proc-macro `#[ctor]` attribute. The declarative form (`ctor!(...)`) is always available. It is recommended that crates re-exporting the `ctor` macro disable this feature and only use the declarative form. | |
| 242 |
| `std` | Enable support for the standard library. | |
| 243 |
|
| 244 |
# Macro Attributes |
| 245 |
|
| 246 |
<table><tr><th>Attribute</th><th>Description</th></tr> |
| 247 |
<tr><td><code>anonymous</code></td><td> |
| 248 |
|
| 249 |
Do not give the constructor a name in the generated code (allows for |
| 250 |
multiple constructors with the same name). Equivalent to wrapping the |
| 251 |
constructor in an anonymous const (i.e.: `const _ = { ... };`). |
| 252 |
|
| 253 |
|
| 254 |
</td></tr> |
| 255 |
<tr><td><code>body(link_section = ".text.startup")</code></td><td> |
| 256 |
|
| 257 |
Place the constructor body in a custom link section. By default, this |
| 258 |
uses the appropriate platform-specific link section. |
| 259 |
|
| 260 |
Co-locating startup functions may improve performance by allowing the binary |
| 261 |
to page them in and out of memory together. |
| 262 |
|
| 263 |
|
| 264 |
</td></tr> |
| 265 |
<tr><td><code>crate_path = ::path::to::ctor::crate</code></td><td> |
| 266 |
|
| 267 |
The path to the `ctor` crate containing the support macros. If you |
| 268 |
re-export `ctor` items as part of your crate, you can use this to |
| 269 |
redirect the macroβs output to the correct crate. |
| 270 |
|
| 271 |
Using the declarative [`ctor!`][c] form is |
| 272 |
preferred over this parameter. |
| 273 |
|
| 274 |
[c]: crate::declarative::ctor! |
| 275 |
|
| 276 |
|
| 277 |
</td></tr> |
| 278 |
<tr><td><code>export_name_prefix = "ctor_"</code></td><td> |
| 279 |
|
| 280 |
Specify a custom export name prefix for the constructor function. |
| 281 |
|
| 282 |
If specified, an export with the given prefix will be generated in the form: |
| 283 |
|
| 284 |
`<prefix><priority>_<unique_id>` |
| 285 |
|
| 286 |
|
| 287 |
</td></tr> |
| 288 |
<tr><td><code>link_section = ".ctors"</code></td><td> |
| 289 |
|
| 290 |
Place the constructor function pointer in a custom link section. By |
| 291 |
default, this uses the appropriate platform-specific link section. |
| 292 |
|
| 293 |
|
| 294 |
</td></tr> |
| 295 |
<tr><td><code>naked</code></td><td> |
| 296 |
|
| 297 |
Use the least-possibly mangled version of the linker invocation for this |
| 298 |
constructor. This is not recommended for general use as it may prevent |
| 299 |
authors of binary crates from having low-level control over the order of |
| 300 |
initialization. |
| 301 |
|
| 302 |
There are no guarantees about the order of execution of constructors |
| 303 |
with this attribute, just that it will be called at some point before |
| 304 |
`main`. |
| 305 |
|
| 306 |
`naked` constructors are always executed directly by the underlying C |
| 307 |
library and/or dynamic loader. |
| 308 |
|
| 309 |
`naked` cannot be used with the `priority` attribute. |
| 310 |
|
| 311 |
|
| 312 |
</td></tr> |
| 313 |
<tr><td><code>priority = N | early | late</code></td><td> |
| 314 |
|
| 315 |
The priority of the constructor. Higher-`N`-priority constructors are |
| 316 |
run last. `N` must be between 0 and 999 inclusive for ordering |
| 317 |
guarantees (`N` >= 1000 ordering is platform-defined). |
| 318 |
|
| 319 |
Priority is specified as numeric value, string literal, or the |
| 320 |
identifiers `early`, `default`, or `late`. The integer value will be |
| 321 |
clamped to a platform-defined range (typically 0-65535), while string |
| 322 |
priorities are passed through unprocessed. |
| 323 |
|
| 324 |
Most platforms reserve the numeric values range of 0..100 for their own |
| 325 |
internal use and it may not be safe to access platform services (`libc` |
| 326 |
or other) in constructors with those priorities. |
| 327 |
|
| 328 |
Priority is applied as follows: |
| 329 |
|
| 330 |
- `N` is run in increasing order, from `0 <= N <= 999`. |
| 331 |
- `early` is run at a priority level where it is safe to access the C |
| 332 |
runtime. This is equivalent to a priority of 101 on most platforms. |
| 333 |
- `default` is the default, and is run after `early`. This is |
| 334 |
equivalent to a priority of 500. |
| 335 |
- `late` is run last, and will be positioned to run after most |
| 336 |
constructors, even outside the range `0 <= N <= 999`. The equivalent |
| 337 |
priority is platform-defined. |
| 338 |
- `main` is run, for binary targets. |
| 339 |
|
| 340 |
Ordering with explicit priority values outside of `0 <= N <= 999` is |
| 341 |
platform-defined with respect to the list above, however platforms will |
| 342 |
order constructors within a given priority range in ascending order |
| 343 |
(i.e.: 10000 will run before 20000). |
| 344 |
|
| 345 |
|
| 346 |
</td></tr> |
| 347 |
<tr><td><code>unsafe</code></td><td> |
| 348 |
|
| 349 |
|
| 350 |
Marks a ctor as unsafe. Required. |
| 351 |
|
| 352 |
The `ctor` crate rejects `#[ctor]` without marking the item unsafe; |
| 353 |
that error can be suppressed by passing |
| 354 |
`RUSTFLAGS="--cfg linktime_no_fail_on_missing_unsafe"` to Cargo. |
| 355 |
|
| 356 |
|
| 357 |
</td></tr> |
| 358 |
<tr><td><code>used(linker)</code></td><td> |
| 359 |
|
| 360 |
|
| 361 |
Mark generated function pointers `used(linker)`. Requires nightly |
| 362 |
for the nightly-only feature `feature(used_with_arg)` (see |
| 363 |
<https://github.com/rust-lang/rust/issues/93798>). |
| 364 |
|
| 365 |
This can be made the default by using the `cfg` flag |
| 366 |
`linktime_used_linker` (`RUSTFLAGS="--cfg linktime_used_linker"`). |
| 367 |
|
| 368 |
For a crate using this macro to function correctly with and without |
| 369 |
this flag, it is recommended to add the following line to the top of |
| 370 |
lib.rs in the crate root: |
| 371 |
|
| 372 |
`#![cfg_attr(linktime_used_linker, feature(used_with_arg))]` |
| 373 |
|
| 374 |
|
| 375 |
</td></tr> |
| 376 |
</table> |
| 377 |
|
| 378 |
# Defaults |
| 379 |
|
| 380 |
## `body_link_section` |
| 381 |
|
| 382 |
```rust |
| 383 |
#[cfg(target_os = "linux")] |
| 384 |
body_link_section = ".text.startup" |
| 385 |
|
| 386 |
#[cfg(target_os = "android")] |
| 387 |
body_link_section = ".text.startup" |
| 388 |
|
| 389 |
#[cfg(target_os = "freebsd")] |
| 390 |
body_link_section = ".text.startup" |
| 391 |
|
| 392 |
#[cfg(all(target_os = "windows", any(target_env = "gnu", target_env = "msvc")))] |
| 393 |
body_link_section = ".text$A" |
| 394 |
|
| 395 |
#[cfg(all(target_os = "windows", not(any(target_env = "gnu", target_env = "msvc"))))] |
| 396 |
body_link_section = ".text.startup" |
| 397 |
|
| 398 |
#[cfg(target_vendor = "apple")] |
| 399 |
body_link_section = "__TEXT,__text_startup,regular,pure_instructions" |
| 400 |
|
| 401 |
// default |
| 402 |
body_link_section = () |
| 403 |
``` |
| 404 |
|
| 405 |
## `export_name_prefix` |
| 406 |
|
| 407 |
```rust |
| 408 |
#[cfg(target_os = "aix")] |
| 409 |
export_name_prefix = "__sinit" |
| 410 |
|
| 411 |
// default |
| 412 |
export_name_prefix = () |
| 413 |
``` |
| 414 |
|
| 415 |
## `link_section` |
| 416 |
|
| 417 |
```rust |
| 418 |
#[cfg(target_vendor = "apple")] |
| 419 |
link_section = "__DATA,__mod_init_func,mod_init_funcs" |
| 420 |
|
| 421 |
#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd", |
| 422 |
target_os = "netbsd", target_os = "openbsd", target_os = "dragonfly", |
| 423 |
target_os = "illumos", target_os = "haiku", target_os = "vxworks", target_os = |
| 424 |
"nto", target_family = "wasm"))] |
| 425 |
link_section = ".init_array" |
| 426 |
|
| 427 |
#[cfg(target_os = "none")] |
| 428 |
link_section = ".init_array" |
| 429 |
|
| 430 |
#[cfg(target_arch = "xtensa")] |
| 431 |
link_section = ".ctors" |
| 432 |
|
| 433 |
#[cfg(all(target_os = "windows", any(target_env = "gnu", target_env = "msvc")))] |
| 434 |
link_section = ".CRT$XCU" |
| 435 |
|
| 436 |
#[cfg(all(target_os = "windows", not(any(target_env = "gnu", target_env = "msvc"))))] |
| 437 |
link_section = ".ctors" |
| 438 |
|
| 439 |
#[cfg(target_os = "uefi")] |
| 440 |
link_section = ".init_array" |
| 441 |
|
| 442 |
#[cfg(target_os = "aix")] |
| 443 |
link_section = () |
| 444 |
|
| 445 |
// default |
| 446 |
link_section = ".init_array" |
| 447 |
``` |
| 448 |
|
| 449 |
## `priority` |
| 450 |
|
| 451 |
```rust |
| 452 |
#[cfg(feature = "priority")] |
| 453 |
priority = default |
| 454 |
|
| 455 |
// default |
| 456 |
priority = () |
| 457 |
``` |
| 458 |
|
| 459 |
## `r#unsafe` |
| 460 |
|
| 461 |
```rust |
| 462 |
#[cfg(linktime_no_fail_on_missing_unsafe)] |
| 463 |
r#unsafe = (no_fail_on_missing_unsafe) |
| 464 |
|
| 465 |
// default |
| 466 |
r#unsafe = () |
| 467 |
``` |
| 468 |
|
| 469 |
## `used_linker` |
| 470 |
|
| 471 |
```rust |
| 472 |
#[cfg(linktime_used_linker)] |
| 473 |
used_linker = used_linker |
| 474 |
|
| 475 |
// default |
| 476 |
used_linker = () |
| 477 |
``` |