Skip to main content

dtor/
lib.rs

1#![recursion_limit = "256"]
2#![no_std]
3#![doc = include_str!("../docs/BUILD.md")]
4//! # dtor
5#![doc = include_str!("../docs/PREAMBLE.md")]
6#![doc = include_str!("../docs/REEXPORT.md")]
7#![doc = include_str!("../docs/GENERATED.md")]
8// UEFI compiles the destructor-collection section into this crate.
9#![cfg_attr(all(target_os = "uefi", linktime_used_linker), feature(used_with_arg))]
10#![cfg_attr(all(target_os = "uefi", linktime_asan), feature(sanitize))]
11
12#[cfg(feature = "std")]
13extern crate std;
14
15mod macros;
16mod native;
17mod parse;
18
19#[doc = include_str!("../docs/LIFE_BEFORE_MAIN.md")]
20pub mod life_before_main {}
21
22pub use native::*;
23
24/// Runs every registered destructor once, in unspecified order.
25///
26/// UEFI never runs `.fini_array` and has no `atexit`, so a UEFI binary must call
27/// this at shutdown. A repeat call is a no-op. A concurrent or re-entrant call
28/// panics.
29///
30/// # Safety
31///
32/// Runs arbitrary user code with the usual life-after-main caveats.
33#[cfg(target_os = "uefi")]
34#[allow(unsafe_code)]
35pub unsafe fn run_destructors() {
36    use core::sync::atomic::{AtomicU8, Ordering};
37    // 0 = not started, 1 = running, 2 = finished.
38    static STATE: AtomicU8 = AtomicU8::new(0);
39    match STATE.compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire) {
40        Ok(_) => {
41            for f in crate::collect::DESTRUCTORS.iter() {
42                f();
43            }
44            STATE.store(2, Ordering::Release);
45        }
46        Err(2) => {}
47        Err(_) => panic!("run_destructors called while already running"),
48    }
49}
50
51/// Destructors collected for manual invocation on UEFI.
52#[cfg(target_os = "uefi")]
53#[doc(hidden)]
54pub mod collect {
55    link_section::declarative::section!(
56        #[section(unsafe, type = typed, name = _DTOR0_FN)]
57        pub static DESTRUCTORS: link_section::TypedSection<extern "C" fn()>;
58    );
59
60    /// Registers a destructor function pointer in the collection section.
61    #[macro_export]
62    #[doc(hidden)]
63    macro_rules! __register_dtor {
64        ($fn:ident) => {
65            $crate::__support::in_section!(
66                #[in_section(unsafe, type = typed, name = _DTOR0_FN)]
67                const _: extern "C" fn() = $fn;
68            );
69        };
70    }
71}
72
73/// Marks a function as a library/executable destructor. This uses OS-specific
74/// linker sections to call a specific function at termination time.
75///
76/// Multiple shutdown functions are supported, but the invocation order is not
77/// guaranteed.
78///
79/// The `dtor` crate assumes it is available as a direct dependency. If you
80/// re-export `dtor` items as part of your crate, you can use the `crate_path`
81/// parameter to redirect the macro's output to the correct crate, or use the
82/// [`declarative::dtor`] form.
83///
84/// ```rust,ignore
85/// # use dtor::dtor;
86/// # fn main() {}
87///
88/// #[dtor(unsafe)]
89/// fn shutdown() {
90///   /* ... */
91/// }
92/// ```
93#[doc(inline)]
94#[cfg(feature = "proc_macro")]
95pub use linktime_proc_macro::dtor;
96
97/// Declarative forms of the `#[dtor]` macro.
98///
99/// The declarative forms wrap and parse a proc_macro-like syntax like so, and
100/// are identical in expansion to the undecorated procedural macros. The
101/// declarative forms support the same attribute parameters as the procedural
102/// macros.
103///
104/// ```rust
105/// # #[cfg(any())] mod test { use dtor::*; use libc_print::*;
106/// dtor::declarative::dtor! {
107///   #[dtor(unsafe)]
108///   fn foo() {
109///     libc_println!("Goodbye, world!");
110///   }
111/// }
112/// # }
113///
114/// // ... the above is identical to:
115///
116/// # #[cfg(any())] mod test_2 { use dtor::*; use libc_print::*;
117/// #[dtor(unsafe)]
118/// fn foo() {
119///   libc_println!("Goodbye, world!");
120/// }
121/// # }
122/// ```
123pub mod declarative {
124    #[doc(inline)]
125    pub use crate::__dtor_parse as dtor;
126}
127
128#[doc(hidden)]
129#[allow(unused)]
130pub mod __support {
131    use crate::macros::*;
132
133    // Required for proc_macro.
134    pub use crate::__dtor_parse as dtor_parse;
135
136    pub use crate::native::*;
137
138    // Used by `__register_dtor` to place destructors in the collection section.
139    #[cfg(target_os = "uefi")]
140    pub use link_section::declarative::in_section;
141}
142
143__declare_features!(
144    dtor: __dtor_features;
145
146    /// Do not give the destructor's registration entry a name in the generated
147    /// code (allows for multiple items with the same name). Equivalent to
148    /// wrapping the registration in an anonymous const (i.e.: `const _ = { ... };`).
149    anonymous {
150        attr: [(anonymous) => (anonymous)];
151    };
152    /// The path to the `dtor` crate containing the support macros. If you
153    /// re-export `dtor` items as part of your crate, you can use this to
154    /// redirect the macro's output to the correct crate.
155    ///
156    /// Using the declarative [`dtor!`][d] form is
157    /// preferred over this parameter.
158    ///
159    /// [d]: crate::declarative::dtor!
160    crate_path {
161        attr: [(crate_path = $path:pat) => (($path))];
162        example: "crate_path = ::path::to::dtor::crate";
163    };
164    /// Specify a custom export name prefix for the generated constructor
165    /// function.
166    ///
167    /// If specified, an export with the given prefix will be generated in the
168    /// form:
169    ///
170    /// `<prefix>_<unique_id>`
171    ctor_export_name_prefix {
172        attr: [(ctor(export_name_prefix = $ctor_export_name_prefix_str:literal)) => ($ctor_export_name_prefix_str)];
173        example: "ctor(export_name_prefix = \"ctor_\")";
174        default {
175            (target_os = "aix") => "__sinit80000000",
176            _ => (),
177        }
178    };
179    /// Place the generated registration constructor's function pointer in a
180    /// custom link section.
181    ctor_link_section {
182        attr: [(ctor(link_section = $ctor_link_section_name:literal)) => ($ctor_link_section_name)];
183        example: "ctor(link_section = \".ctors\")";
184        // Historical note: GCC 4.7 stopped providing .ctors/.dtors compatible
185        // crt files. Modern compilers, with the exception of Apple, MSVC, and
186        // AIX, will use `.init_array`.
187        default {
188            (target_vendor = "apple") => "__DATA,__mod_init_func,mod_init_funcs",
189            // Most LLVM/GCC targets can use .init_array
190            (any(
191                target_os = "linux",
192                target_os = "android",
193                target_os = "freebsd",
194                target_os = "netbsd",
195                target_os = "openbsd",
196                target_os = "dragonfly",
197                target_os = "illumos",
198                target_os = "haiku",
199                target_os = "vxworks",
200                target_os = "nto",
201                target_family = "wasm"
202            )) => ".init_array",
203            // No OS
204            (target_os = "none") => ".init_array",
205            // xtensa targets: .ctors
206            (target_arch = "xtensa") => ".ctors",
207            // Windows targets: .CRT$XCU
208            (all(target_os = "windows", any(target_env = "gnu", target_env = "msvc"))) => ".CRT$XCU",
209            // ... except mingw32 (https://llvm.googlesource.com/clang/+/1a209b667f83588866326a0384fa943ea2287b6c)
210            (all(target_os = "windows", not(any(target_env = "gnu", target_env = "msvc")))) => ".ctors",
211            // Research suggests that MSVC will use .CRT$XCU for UEFI targets, but won't actually
212            // run them. The gnu-efi project _does_ at least document .init_array support:
213            // https://github.com/vathpela/gnu-efi/blob/master/gnuefi/elf_x86_64_efi.lds
214            (target_os = "uefi") => ".init_array",
215            (target_os = "aix") => (), // AIX uses export_name_prefix
216            // Fall back to .init_array which is effectively the gold standard
217            // for LLVM/GCC targets moving forward
218            #[warn("Falling back to .init_array for unsupported target. If this \
219            works for you, please file an issue to add support for your target \
220            at https://github.com/mmastrac/linktime/issues")]
221            _ => ".init_array",
222        }
223    };
224    /// The default method used for running a `dtor` on termination. This is
225    /// generally not recommended as code may be unloaded before the dtor is
226    /// called.
227    ///
228    /// This is only used if the specified `dtor` method is `term`.
229    ///
230    /// All platforms use `at_binary_exit` except Windows, which uses
231    /// `at_module_exit`.
232    default_term_method {
233        default {
234            (target_os = "windows") => at_module_exit,
235            _ => at_binary_exit,
236        }
237    };
238    /// The default method used for running a `dtor` on module unload.
239    ///
240    /// This is only used if the `method` attribute is not specified, or if the
241    /// method is `unload`.
242    default_unload_method {
243        default {
244            _ => at_module_exit,
245        }
246    };
247    /// Specify a custom export name prefix for the destructor function.
248    ///
249    /// If specified, an export with the given prefix will be generated in the form:
250    ///
251    /// `<prefix>_<unique_id>`
252    export_name_prefix {
253        attr: [(export_name_prefix = $export_name_prefix_str:literal) => ($export_name_prefix_str)];
254        example: "export_name_prefix = \"ctor_\"";
255        default {
256            (target_os = "aix") => "__sterm80000000",
257            _ => (),
258        }
259    };
260    /// Place the destructor function pointer in a custom link section.
261    link_section {
262        attr: [(link_section = $section:literal) => ($section)];
263        example: "link_section = \".dtors\"";
264        default {
265            // This is no longer supported by Apple
266            (target_vendor = "apple") => "__DATA,__mod_term_func,mod_term_funcs",
267            // Most LLVM/GCC targets can use .fini_array
268            (any(
269                target_os = "linux",
270                target_os = "android",
271                target_os = "freebsd",
272                target_os = "netbsd",
273                target_os = "dragonfly",
274                target_os = "illumos",
275                target_os = "haiku",
276                target_os = "vxworks",
277                target_os = "nto",
278                target_family = "wasm"
279            )) => ".fini_array",
280            // OpenBSD only seems to support .fini_array for binaries
281            (target_os = "openbsd") => ".dtors",
282            // No OS
283            (target_os = "none") => ".fini_array",
284            // xtensa targets: .dtors
285            (target_arch = "xtensa") => ".dtors",
286            // Windows targets: .CRT$XPU (requires static CRT)
287            (all(target_os = "windows", any(target_env = "gnu", target_env = "msvc"))) => ".CRT$XPU",
288            // ... except GNU
289            (all(target_os = "windows", not(any(target_env = "gnu", target_env = "msvc")))) => ".dtors",
290            // The gnu-efi project documents .fini_array support:
291            // https://github.com/vathpela/gnu-efi/blob/master/gnuefi/elf_x86_64_efi.lds
292            (target_os = "uefi") => ".fini_array",
293            (target_os = "aix") => (), // AIX uses export_name_prefix
294            // Fall back to .fini_array which is effectively the gold standard
295            // for LLVM/GCC targets moving forward
296            #[warn("Falling back to .fini_array for unsupported target. If this \
297            works for you, please file an issue to add support for your target \
298            at https://github.com/mmastrac/linktime/issues")]
299            _ => ".fini_array",
300        }
301    };
302    /// Specify the dtor method.
303    ///
304    ///  - `term`: Run the dtor on binary termination using the platform's
305    ///    [default_term_method](#default_term_method). Not recommended as code
306    ///    may be unloaded before the dtor is called.
307    ///  - `unload`: Run the dtor on module unload (library or binary) using the
308    ///    platform's [default_unload_method](#default_unload_method).
309    ///  - `at_module_exit`: Run the dtor using the platform's
310    ///    [`at_module_exit`][at_module_exit] (`__cxa_atexit` on all platforms
311    ///    other than Windows, `atexit` on Windows).
312    ///  - `at_binary_exit`: Run the dtor using the platform's
313    ///    [`at_binary_exit`][at_binary_exit] (unsupported on Windows
314    ///    platforms).
315    ///  - `linker`: Register the dtor using the platform's
316    ///    [link_section](#link_section) or
317    ///    [export_name_prefix](#export_name_prefix) (unsupported on Apple
318    ///    platforms).
319    ///
320    /// [at_module_exit]: crate::native::at_module_exit
321    /// [at_binary_exit]: crate::native::at_binary_exit
322    method {
323        attr: [(method = $method_id:ident) => ($method_id)];
324        example: "method = term|unload|at_module_exit|at_binary_exit|linker";
325        validate: [(term), (unload), (at_module_exit), (at_binary_exit), (linker)];
326        default {
327            (target_vendor = "apple") => at_module_exit,
328            (target_os = "windows") => at_module_exit,
329            // WASI/Emscripten support atexit only
330            // For wasm-unknown-unknown, you'll need to provide one
331            (target_family = "wasm") => at_binary_exit,
332            // OpenBSD's linker support is inconsistent
333            (target_os = "openbsd") => at_module_exit,
334            _ => linker,
335        }
336    };
337    /// Enable support for the proc-macro `#[dtor]` attribute. The declarative
338    /// form (`dtor!(...)`) is always available. It is recommended that crates
339    /// re-exporting the `dtor` macro disable this feature and only use the
340    /// declarative form.
341    proc_macro {
342        feature: "proc_macro";
343    };
344    /// Enable support for the standard library.
345    std {
346        feature: "std";
347    };
348    r#unsafe {
349        /// attr
350        ///
351        /// Marks a dtor as unsafe. Required.
352        ///
353        /// The `dtor` crate rejects `#[dtor]` without marking the item unsafe;
354        /// that error can be suppressed by passing
355        /// `RUSTFLAGS="--cfg linktime_no_fail_on_missing_unsafe"` to Cargo.
356        attr: [(unsafe) => (no_fail_on_missing_unsafe)];
357        default {
358            (linktime_no_fail_on_missing_unsafe) => (no_fail_on_missing_unsafe),
359            _ => (),
360        }
361    };
362    used_linker {
363        /// attr
364        ///
365        /// Mark generated function pointers `used(linker)`. Requires nightly
366        /// for the nightly-only feature `feature(used_with_arg)` (see
367        /// <https://github.com/rust-lang/rust/issues/93798>).
368        ///
369        /// This can be made the default by using the `cfg` flag
370        /// `linktime_used_linker` (`RUSTFLAGS="--cfg linktime_used_linker"`).
371        ///
372        /// For a crate using this macro to function correctly with and without
373        /// this flag, it is recommended to add the following line to the top of
374        /// lib.rs in the crate root:
375        ///
376        /// `#![cfg_attr(linktime_used_linker, feature(used_with_arg))]`
377        ///
378        attr: [(used(linker)) => (used_linker)];
379        default {
380            (linktime_used_linker) => used_linker,
381            _ => (),
382        }
383    };
384);
385
386#[cfg(doc)]
387__generate_docs!(__dtor_features);