ctor-0.1.26/.cargo_vcs_info.json0000644000000001420000000000100120660ustar { "git": { "sha1": "2bb37a7906534dabc3e2edcccdd0617dd329787d" }, "path_in_vcs": "ctor" }ctor-0.1.26/Cargo.lock0000644000000027610000000000100100520ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "ctor" version = "0.1.26" dependencies = [ "libc-print", "quote", "syn", ] [[package]] name = "libc" version = "0.2.135" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68783febc7782c6c5cb401fbda4de5a9898be1762314da0bb2c10ced61f18b0c" [[package]] name = "libc-print" version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a574491aebd99996f31b32469bbd3b50e580c35f6305663d68f6d6b28eaced09" dependencies = [ "libc", ] [[package]] name = "proc-macro2" version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" dependencies = [ "proc-macro2", ] [[package]] name = "syn" version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fcd952facd492f9be3ef0d0b7032a6e442ee9b361d4acc2b1d0c4aaa5f613a1" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "unicode-ident" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" ctor-0.1.26/Cargo.toml0000644000000021560000000000100100730ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "ctor" version = "0.1.26" authors = ["Matt Mastracci "] description = "__attribute__((constructor)) for Rust" readme = "README.md" license = "Apache-2.0 OR MIT" repository = "https://github.com/mmastrac/rust-ctor" [lib] name = "ctor" proc-macro = true [[example]] name = "example" path = "src/example.rs" [dependencies.quote] version = "1.0.20" [dependencies.syn] version = "1.0.98" features = [ "full", "parsing", "printing", "proc-macro", ] default-features = false [dev-dependencies.libc-print] version = "0.1.20" [badges.travis-ci] branch = "master" repository = "mmastrac/rust-ctor" ctor-0.1.26/Cargo.toml.orig000064400000000000000000000012020072674642500135730ustar 00000000000000[package] name = "ctor" version = "0.1.26" authors = ["Matt Mastracci "] edition = "2018" description = "__attribute__((constructor)) for Rust" license = "Apache-2.0 OR MIT" repository = "https://github.com/mmastrac/rust-ctor" readme = "../README.md" [badges] travis-ci = { repository = "mmastrac/rust-ctor", branch = "master" } [dependencies] quote = "1.0.20" [dependencies.syn] version = "1.0.98" features = ["full", "parsing", "printing", "proc-macro"] default-features = false [dev-dependencies] libc-print = "0.1.20" [lib] name = "ctor" proc-macro = true [[example]] name = "example" path = "src/example.rs" ctor-0.1.26/LICENSE-APACHE000064400000000000000000000260740072674642500126460ustar 00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ctor-0.1.26/LICENSE-MIT000064400000000000000000000017760072674642500123600ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.ctor-0.1.26/README.md000064400000000000000000000101600072674642500121660ustar 00000000000000# rust-ctor [![Build Status](https://api.travis-ci.com/mmastrac/rust-ctor.svg?branch=master)](https://travis-ci.com/mmastrac/rust-ctor) [![docs.rs](https://docs.rs/ctor/badge.svg)](https://docs.rs/ctor) [![crates.io](https://img.shields.io/crates/v/ctor.svg)](https://crates.io/crates/ctor) 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](https://github.com/neon-bindings/neon/blob/2277e943a619579c144c1da543874f4a7ec39879/src/lib.rs#L42) in the Neon project. ## Support This library works and [is regularly tested](https://travis-ci.org/mmastrac/rust-ctor) 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](https://crates.io/crates/libc-print) 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](https://github.com/rust-lang/rust/issues/28794#issuecomment-368693049)). ## Examples Marks the function `foo` as a module constructor, called when a static library is loaded or an executable is started: ```rust 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`): ```rust #[ctor] /// This is an immutable static, evaluated at init time static STATIC_CTOR: HashMap = { 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. ```rust #[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): ```rust #[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: ```rust #[ctor] fn dtor_atexit() { libc::atexit(dtor); } ``` ctor-0.1.26/src/example.rs000064400000000000000000000017030072674642500135020ustar 00000000000000extern crate ctor; extern crate libc_print; use ctor::*; use libc_print::*; use std::collections::HashMap; #[ctor] /// This is an immutable static, evaluated at init time static STATIC_CTOR: HashMap = { let mut m = HashMap::new(); m.insert(0, "foo"); m.insert(1, "bar"); m.insert(2, "baz"); libc_eprintln!("STATIC_CTOR"); m }; #[ctor] fn ctor() { libc_eprintln!("ctor"); } #[ctor] unsafe fn ctor_unsafe() { libc_eprintln!("ctor_unsafe"); } #[dtor] fn dtor() { libc_eprintln!("dtor"); } #[dtor] unsafe fn dtor_unsafe() { libc_eprintln!("dtor_unsafe"); } mod module { use ctor::*; use libc_print::*; #[ctor] pub static STATIC_CTOR: u8 = { libc_eprintln!("module::STATIC_CTOR"); 42 }; } pub fn main() { libc_eprintln!("main!"); libc_eprintln!("STATIC_CTOR = {:?}", *STATIC_CTOR); libc_eprintln!("module::STATIC_CTOR = {:?}", *module::STATIC_CTOR); } ctor-0.1.26/src/lib.rs000064400000000000000000000322560072674642500126240ustar 00000000000000#![recursion_limit = "256"] //! Procedural macro for defining global constructor/destructor functions. //! //! This provides module initialization/teardown functions for Rust (like //! `__attribute__((constructor))` in C/C++) for Linux, OSX, and Windows via //! the `#[ctor]` and `#[dtor]` macros. //! //! 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. //! //! This library currently requires Rust > `1.31.0` at a minimum for the //! procedural macro support. // Code note: // You might wonder why we don't use `__attribute__((destructor))`/etc for // dtor. Unfortunately mingw doesn't appear to properly support section-based // hooks for shutdown, ie: // https://github.com/Alexpux/mingw-w64/blob/d0d7f784833bbb0b2d279310ddc6afb52fe47a46/mingw-w64-crt/crt/crtdll.c // In addition, OSX has removed support for section-based shutdown hooks after // warning about it for a number of years: // https://reviews.llvm.org/D45578 extern crate proc_macro; extern crate syn; #[macro_use] extern crate quote; use proc_macro::{TokenStream}; /// Attributes required to mark a function as a constructor. This may be exposed in the future if we determine /// it to be stable. #[doc(hidden)] macro_rules! ctor_attributes { () => { quote!( #[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 = "dragonfly", link_section = ".init_array")] #[cfg_attr(target_os = "illumos", link_section = ".init_array")] #[cfg_attr(target_os = "haiku", link_section = ".init_array")] #[cfg_attr(any(target_os = "macos", target_os = "ios"), link_section = "__DATA,__mod_init_func")] #[cfg_attr(windows, link_section = ".CRT$XCU")] ) }; } /// Marks a function or static variable as a library/executable constructor. /// This uses OS-specific linker sections to call a specific function at /// load time. /// /// Multiple startup functions/statics are supported, but the invocation order is not /// guaranteed. /// /// # Examples /// /// Print a startup message (using `libc_print` for safety): /// /// ```rust /// # extern crate ctor; /// # use ctor::*; /// use libc_print::std_name::println; /// /// #[ctor] /// fn foo() { /// println!("Hello, world!"); /// } /// /// # fn main() { /// println!("main()"); /// # } /// ``` /// /// Make changes to `static` variables: /// /// ```rust /// # extern crate ctor; /// # use ctor::*; /// # use std::sync::atomic::{AtomicBool, Ordering}; /// static INITED: AtomicBool = AtomicBool::new(false); /// /// #[ctor] /// fn foo() { /// INITED.store(true, Ordering::SeqCst); /// } /// ``` /// /// Initialize a `HashMap` at startup time: /// /// ```rust /// # extern crate ctor; /// # use std::collections::HashMap; /// # use ctor::*; /// #[ctor] /// static STATIC_CTOR: HashMap = { /// let mut m = HashMap::new(); /// for i in 0..100 { /// m.insert(i, format!("x*100={}", i*100)); /// } /// m /// }; /// /// # pub fn main() { /// # assert_eq!(STATIC_CTOR.len(), 100); /// # assert_eq!(STATIC_CTOR[&20], "x*100=2000"); /// # } /// ``` /// /// # Details /// /// 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): /// ///```rust /// #[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 = "illumos", link_section = ".init_array")] /// #[cfg_attr(any(target_os = "macos", target_os = "ios"), 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 /// }; /// ``` #[proc_macro_attribute] pub fn ctor(_attribute: TokenStream, function: TokenStream) -> TokenStream { let item: syn::Item = syn::parse_macro_input!(function); if let syn::Item::Fn(function) = item { validate_item("ctor", &function); let syn::ItemFn { attrs, block, vis, sig: syn::Signature { ident, unsafety, constness, abi, .. }, .. } = function; // Linux/ELF: https://www.exploit-db.com/papers/13234 // Mac details: https://blog.timac.org/2016/0716-constructor-and-destructor-attributes/ // Why .CRT$XCU on Windows? https://www.cnblogs.com/sunkang/archive/2011/05/24/2055635.html // 'I'=C init, 'C'=C++ init, 'P'=Pre-terminators and 'T'=Terminators let ctor_ident = syn::parse_str::(format!("{}___rust_ctor___ctor", ident).as_ref()) .expect("Unable to create identifier"); let tokens = ctor_attributes!(); let output = quote!( #[cfg(not(any(target_os = "linux", target_os = "android", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", target_os = "dragonfly", target_os = "illumos", target_os = "haiku", target_os = "macos", target_os = "ios", windows)))] compile_error!("#[ctor] is not supported on the current target"); #(#attrs)* #vis #unsafety extern #abi #constness fn #ident() #block #[used] #[allow(non_upper_case_globals)] #[doc(hidden)] #tokens static #ctor_ident : unsafe extern "C" fn() = { #[cfg_attr(any(target_os = "linux", target_os = "android"), link_section = ".text.startup")] unsafe extern "C" fn #ctor_ident() { #ident() }; #ctor_ident } ; ); // eprintln!("{}", output); output.into() } else if let syn::Item::Static(var) = item { let syn::ItemStatic { ident, mutability, expr, attrs, ty, vis, .. } = var; if mutability.is_some() { panic!("#[ctor]-annotated static objects must not be mutable"); } if attrs.iter().any(|attr| { attr.path .segments .iter() .any(|segment| segment.ident == "no_mangle") }) { panic!("#[ctor]-annotated static objects do not support #[no_mangle]"); } let ctor_ident = syn::parse_str::(format!("{}___rust_ctor___ctor", ident).as_ref()) .expect("Unable to create identifier"); let storage_ident = syn::parse_str::(format!("{}___rust_ctor___storage", ident).as_ref()) .expect("Unable to create identifier"); let tokens = ctor_attributes!(); let output = quote!( #[cfg(not(any(target_os = "linux", target_os = "android", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", target_os = "dragonfly", target_os = "illumos", target_os = "haiku", target_os = "macos", target_os = "ios", windows)))] compile_error!("#[ctor] is not supported on the current target"); // This is mutable, but only by this macro code! static mut #storage_ident: Option<#ty> = None; #[doc(hidden)] #[allow(non_camel_case_types)] #vis struct #ident { _data: core::marker::PhantomData } #(#attrs)* #vis static #ident: #ident<#ty> = #ident { _data: core::marker::PhantomData::<#ty> }; impl core::ops::Deref for #ident<#ty> { type Target = #ty; fn deref(&self) -> &'static #ty { unsafe { #storage_ident.as_ref().unwrap() } } } #[used] #[allow(non_upper_case_globals)] #tokens static #ctor_ident : unsafe extern "C" fn() = { #[cfg_attr(any(target_os = "linux", target_os = "android"), link_section = ".text.startup")] unsafe extern "C" fn initer() { #storage_ident = Some(#expr); }; initer } ; ); // eprintln!("{}", output); output.into() } else { panic!("#[ctor] items must be functions or static globals"); } } /// Marks a function as a library/executable destructor. This uses OS-specific /// linker sections to call a specific function at termination time. /// /// Multiple shutdown functions are supported, but the invocation order is not /// guaranteed. /// /// `sys_common::at_exit` is usually a better solution for shutdown handling, as /// it allows you to use `stdout` in your handlers. /// /// ```rust /// # extern crate ctor; /// # use ctor::*; /// # fn main() {} /// /// #[dtor] /// fn shutdown() { /// /* ... */ /// } /// ``` #[proc_macro_attribute] pub fn dtor(_attribute: TokenStream, function: TokenStream) -> TokenStream { let function: syn::ItemFn = syn::parse_macro_input!(function); validate_item("dtor", &function); let syn::ItemFn { attrs, block, vis, sig: syn::Signature { ident, unsafety, constness, abi, .. }, .. } = function; let mod_ident = syn::parse_str::(format!("{}___rust_dtor___mod", ident).as_ref()) .expect("Unable to create identifier"); let dtor_ident = syn::parse_str::(format!("{}___rust_dtor___dtor", ident).as_ref()) .expect("Unable to create identifier"); let tokens = ctor_attributes!(); let output = quote!( #[cfg(not(any(target_os = "linux", target_os = "android", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", target_os = "dragonfly", target_os = "illumos", target_os = "haiku", target_os = "macos", target_os = "ios", windows)))] compile_error!("#[dtor] is not supported on the current target"); #(#attrs)* #vis #unsafety extern #abi #constness fn #ident() #block mod #mod_ident { use super::#ident; // Note that we avoid a dep on the libc crate by linking directly to atexit functions #[cfg(not(any(target_os = "macos", target_os = "ios")))] #[inline(always)] unsafe fn do_atexit(cb: unsafe extern fn()) { extern "C" { fn atexit(cb: unsafe extern fn()); } atexit(cb); } // For platforms that have __cxa_atexit, we register the dtor as scoped to dso_handle #[cfg(any(target_os = "macos", target_os = "ios"))] #[inline(always)] unsafe fn do_atexit(cb: unsafe extern fn()) { extern "C" { static __dso_handle: *const u8; fn __cxa_atexit(cb: unsafe extern fn(), arg: *const u8, dso_handle: *const u8); } __cxa_atexit(cb, std::ptr::null(), __dso_handle); } #[used] #[allow(non_upper_case_globals)] #tokens static __dtor_export : unsafe extern "C" fn() = { #[cfg_attr(any(target_os = "linux", target_os = "android"), link_section = ".text.exit")] unsafe extern "C" fn #dtor_ident() { #ident() }; #[cfg_attr(any(target_os = "linux", target_os = "android"), link_section = ".text.startup")] unsafe extern fn __dtor_atexit() { do_atexit(#dtor_ident); }; __dtor_atexit }; } ); // eprintln!("{}", output); output.into() } fn validate_item(typ: &str, item: &syn::ItemFn) { let syn::ItemFn { vis, sig, .. } = item; // Ensure that visibility modifier is not present match vis { syn::Visibility::Inherited => {} _ => panic!("#[{}] methods must not have visibility modifiers", typ), } // No parameters allowed if !sig.inputs.is_empty() { panic!("#[{}] methods may not have parameters", typ); } // No return type allowed match sig.output { syn::ReturnType::Default => {} _ => panic!("#[{}] methods must not have return types", typ), } }