Skip to main content

ax_ctor_bare/
lib.rs

1#![no_std]
2#![doc = include_str!("../README.md")]
3
4pub use ax_ctor_bare_macros::register_ctor;
5
6/// Placeholder for the `.init_array` section, so that
7/// the `__init_array_start` and `__init_array_end` symbols can be generated.
8#[unsafe(link_section = ".init_array")]
9#[used]
10static _SECTION_PLACE_HOLDER: [u8; 0] = [];
11
12unsafe extern "C" {
13    fn __init_array_start();
14    fn __init_array_end();
15}
16
17/// Invoke all constructor functions registered by the `register_ctor` attribute.
18///
19/// # Notes
20/// Caller should ensure that the `.init_array` section will not be disturbed by other sections.
21pub fn call_ctors() {
22    for ctor_ptr in (__init_array_start as *const () as usize
23        ..__init_array_end as *const () as usize)
24        .step_by(core::mem::size_of::<*const core::ffi::c_void>())
25    {
26        unsafe {
27            core::mem::transmute::<*const core::ffi::c_void, fn()>(
28                *(ctor_ptr as *const *const core::ffi::c_void),
29            )();
30        }
31    }
32}