napi_build/lib.rs
1use std::env;
2
3mod android;
4mod wasi;
5mod windows;
6
7/// The build-script lines that give the calling crate `cfg(napi_wasi_threads)`.
8///
9/// The `rustc-check-cfg` line is unconditional, so the cfg is a *known* cfg on
10/// every target and `#[cfg(napi_wasi_threads)]` never trips the
11/// `unexpected_cfgs` lint. The `rustc-cfg` line is emitted only for the
12/// threaded WASI target, matched as an exact triple — the same gate
13/// `crates/napi/build.rs` and `crates/async-runtime/build.rs` use, because the
14/// addon and `napi` have to agree on what the cfg means.
15///
16/// `cargo::` rather than the legacy `cargo:` form: the double-colon syntax
17/// needs Cargo 1.77 and this crate's `rust-version` is 1.88, so a toolchain
18/// old enough to misread it cannot compile `napi-build` in the first place.
19/// Both napi build scripts already emit their cfgs this way.
20///
21/// `napi_wasi_no_heap_sync` is only declared, never set: an addon turns it on
22/// with `--cfg napi_wasi_no_heap_sync` in its target rustflags to opt out of the
23/// allocator wrap (see `wasi.rs`), and the declaration lets its own code test
24/// the cfg without tripping `unexpected_cfgs`.
25fn wasi_threads_cfg_lines(target: &str) -> Vec<&'static str> {
26 let mut lines = vec![
27 "cargo::rustc-check-cfg=cfg(napi_wasi_threads)",
28 "cargo::rustc-check-cfg=cfg(napi_wasi_no_heap_sync)",
29 ];
30 if target == "wasm32-wasip1-threads" {
31 lines.push("cargo::rustc-cfg=napi_wasi_threads");
32 }
33 lines
34}
35
36/// Configuration options for [`setup_with`].
37#[derive(Debug, Default, Clone, PartialEq, Eq)]
38pub struct SetupOptions {
39 wasi_stack_size: Option<u32>,
40}
41
42impl SetupOptions {
43 /// Creates a new `SetupOptions` with all options set to their defaults.
44 pub fn new() -> Self {
45 Self::default()
46 }
47
48 /// Sets the WASI `-zstack-size` linker argument in bytes.
49 ///
50 /// The value must be a non-zero 16-byte multiple (as required by `wasm-ld`).
51 /// `-zstack-size` sizes only the main thread's linear-memory shadow stack.
52 ///
53 /// Effective precedence (highest to lowest):
54 /// 1. `NAPI_WASI_STACK_SIZE` environment variable (non-empty; an empty string `""` is
55 /// treated as unset)
56 /// 2. `napi.wasm.stackSizeBytes` in `package.json` (forwarded by `@napi-rs/cli` as
57 /// `NAPI_WASI_STACK_SIZE` when the environment variable is unset or empty)
58 /// 3. `SetupOptions::wasi_stack_size(...)` in `build.rs`
59 /// 4. Default: `64_000_000` bytes (~61.04 MiB)
60 pub fn wasi_stack_size(mut self, bytes: u32) -> Self {
61 self.wasi_stack_size = Some(bytes);
62 self
63 }
64}
65
66/// Configure the build of a `napi-rs` addon crate.
67///
68/// Call it from the addon's `build.rs`. Besides the per-platform link
69/// arguments, it hands the crate a first-party `cfg(napi_wasi_threads)`, set
70/// exactly when the crate is compiled for `wasm32-wasip1-threads`:
71///
72/// ```ignore
73/// // build.rs
74/// fn main() {
75/// napi_build::setup();
76/// }
77///
78/// // src/lib.rs
79/// #[cfg(napi_wasi_threads)]
80/// const SHARED_MEMORY: bool = true;
81/// #[cfg(not(napi_wasi_threads))]
82/// const SHARED_MEMORY: bool = false;
83/// ```
84///
85/// rustc has no built-in cfg that tells the two WASI targets apart: it prints
86/// an *identical* cfg set for `wasm32-wasip1` and `wasm32-wasip1-threads`
87/// (same `target_env = "p1"`), and the wasm `atomics` target feature is
88/// unstable, so the stable channel never puts `target_feature = "atomics"` in
89/// the cfg set of either one (rust-lang/rust#77839). Only the exact cargo
90/// `TARGET` answers the question, and only a build script can read it.
91///
92/// A build-script cfg is crate-local: it reaches the crate whose `build.rs`
93/// called this function and nothing else. Every other crate in the graph that
94/// needs the distinction needs its own build script. Absence must therefore be
95/// the conservative branch — a plain `cargo build` compiles the
96/// `not(napi_wasi_threads)` side, and that side has to stay correct.
97///
98/// To customize build options such as the WASI stack size, use [`setup_with`].
99pub fn setup() {
100 setup_with(SetupOptions::default());
101}
102
103/// Configure the build of a `napi-rs` addon crate with explicit [`SetupOptions`].
104///
105/// See [`setup`] for details on the build-script directives emitted.
106///
107/// For WASI builds, `-zstack-size` is resolved in the following priority order
108/// (highest to lowest):
109/// 1. `NAPI_WASI_STACK_SIZE` environment variable (non-empty; an empty string `""` is
110/// treated as unset)
111/// 2. `napi.wasm.stackSizeBytes` in `package.json` (forwarded by `@napi-rs/cli` as
112/// `NAPI_WASI_STACK_SIZE` when the environment variable is unset or empty)
113/// 3. `SetupOptions::wasi_stack_size(...)` in `build.rs`
114/// 4. Default: `64_000_000` bytes (~61.04 MiB)
115pub fn setup_with(options: SetupOptions) {
116 if let Some(bytes) = options.wasi_stack_size {
117 wasi::validate_stack_size(bytes, "SetupOptions::wasi_stack_size")
118 .unwrap_or_else(|error| panic!("{error}"));
119 }
120
121 for line in wasi_threads_cfg_lines(&env::var("TARGET").unwrap_or_default()) {
122 println!("{line}");
123 }
124
125 // compatible with the v2 versions, will remove in the future
126 {
127 println!("cargo:rerun-if-env-changed=DEBUG_GENERATED_CODE");
128 println!("cargo:rerun-if-env-changed=TYPE_DEF_TMP_PATH");
129 println!("cargo:rerun-if-env-changed=CARGO_CFG_NAPI_RS_CLI_VERSION");
130 }
131
132 println!("cargo::rerun-if-env-changed=NAPI_DEBUG_GENERATED_CODE");
133 println!("cargo::rerun-if-env-changed=NAPI_TYPE_DEF_TMP_FOLDER");
134 println!(
135 "cargo::rerun-if-env-changed=NAPI_FORCE_BUILD_{}",
136 env::var("CARGO_PKG_NAME")
137 .expect("CARGO_PKG_NAME is not set")
138 .to_uppercase()
139 .replace("-", "_")
140 );
141
142 let target_env = env::var("CARGO_CFG_TARGET_ENV").expect("CARGO_CFG_TARGET_ENV is not set");
143 let target_os = env::var("CARGO_CFG_TARGET_OS").expect("CARGO_CFG_TARGET_OS is not set");
144
145 match target_os.as_str() {
146 "android" => if android::setup().is_ok() {},
147 "wasi" => {
148 wasi::setup(options.wasi_stack_size);
149 }
150 "macos" => {
151 // Keep the dynamic lookup behavior on macOS to avoid breaking changes.
152 println!("cargo:rustc-cdylib-link-arg=-Wl");
153 println!("cargo:rustc-cdylib-link-arg=-undefined");
154 println!("cargo:rustc-cdylib-link-arg=dynamic_lookup");
155 }
156 "windows" => {
157 if let Ok("gnu") = env::var("CARGO_CFG_TARGET_ENV").as_deref() {
158 windows::setup_gnu();
159 }
160 }
161 _ => {}
162 }
163
164 if (target_env == "gnu" && target_os != "windows")
165 || target_os == "freebsd"
166 || target_os == "openbsd"
167 {
168 // https://sourceware.org/bugzilla/show_bug.cgi?id=21032
169 // https://sourceware.org/bugzilla/show_bug.cgi?id=21031
170 // https://github.com/rust-lang/rust/issues/134820
171 // pthread_key_create() destructors and segfault after a DSO unloading
172 println!("cargo:rustc-link-arg=-Wl,-z,nodelete");
173 }
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179
180 #[test]
181 fn emits_the_cfg_for_the_threaded_wasi_target() {
182 assert_eq!(
183 wasi_threads_cfg_lines("wasm32-wasip1-threads"),
184 vec![
185 "cargo::rustc-check-cfg=cfg(napi_wasi_threads)",
186 "cargo::rustc-check-cfg=cfg(napi_wasi_no_heap_sync)",
187 "cargo::rustc-cfg=napi_wasi_threads",
188 ]
189 );
190 }
191
192 #[test]
193 fn keeps_the_cfg_off_the_threadless_wasi_target() {
194 assert_eq!(
195 wasi_threads_cfg_lines("wasm32-wasip1"),
196 vec![
197 "cargo::rustc-check-cfg=cfg(napi_wasi_threads)",
198 "cargo::rustc-check-cfg=cfg(napi_wasi_no_heap_sync)",
199 ]
200 );
201 }
202
203 #[test]
204 fn still_declares_the_cfg_on_a_native_target() {
205 assert_eq!(
206 wasi_threads_cfg_lines("x86_64-unknown-linux-gnu"),
207 vec![
208 "cargo::rustc-check-cfg=cfg(napi_wasi_threads)",
209 "cargo::rustc-check-cfg=cfg(napi_wasi_no_heap_sync)",
210 ]
211 );
212 }
213
214 #[test]
215 fn setup_options_defaults_and_builder() {
216 let default_options = SetupOptions::default();
217 assert_eq!(SetupOptions::new(), default_options);
218 assert_eq!(default_options.wasi_stack_size, None);
219
220 let configured = SetupOptions::new().wasi_stack_size(8_388_608);
221 assert_eq!(configured.wasi_stack_size, Some(8_388_608));
222 assert_eq!(configured.clone(), configured);
223 }
224
225 #[test]
226 #[should_panic(expected = "SetupOptions::wasi_stack_size must be greater than 0 bytes")]
227 fn setup_with_rejects_zero_wasi_stack_size_before_target_dispatch() {
228 setup_with(SetupOptions::new().wasi_stack_size(0));
229 }
230
231 #[test]
232 #[should_panic(expected = "SetupOptions::wasi_stack_size must be a 16-byte multiple")]
233 fn setup_with_rejects_unaligned_wasi_stack_size_before_target_dispatch() {
234 setup_with(SetupOptions::new().wasi_stack_size(17));
235 }
236}