Skip to main content

cargo_zigbuild/
zig.rs

1use std::env;
2use std::ffi::OsStr;
3#[cfg(target_family = "unix")]
4use std::fs::OpenOptions;
5use std::io::Write;
6#[cfg(target_family = "unix")]
7use std::os::unix::fs::OpenOptionsExt;
8use std::path::{Path, PathBuf};
9use std::process::{self, Command};
10use std::str;
11use std::sync::OnceLock;
12
13use anyhow::{anyhow, bail, Context, Result};
14use fs_err as fs;
15use path_slash::PathBufExt;
16use serde::Deserialize;
17use target_lexicon::{Architecture, Environment, OperatingSystem, Triple};
18
19use crate::linux::ARM_FEATURES_H;
20use crate::macos::{LIBCHARSET_TBD, LIBICONV_TBD};
21
22/// Zig linker wrapper
23#[derive(Clone, Debug, clap::Subcommand)]
24pub enum Zig {
25    /// `zig cc` wrapper
26    #[command(name = "cc")]
27    Cc {
28        /// `zig cc` arguments
29        #[arg(num_args = 1.., trailing_var_arg = true)]
30        args: Vec<String>,
31    },
32    /// `zig c++` wrapper
33    #[command(name = "c++")]
34    Cxx {
35        /// `zig c++` arguments
36        #[arg(num_args = 1.., trailing_var_arg = true)]
37        args: Vec<String>,
38    },
39    /// `zig ar` wrapper
40    #[command(name = "ar")]
41    Ar {
42        /// `zig ar` arguments
43        #[arg(num_args = 1.., trailing_var_arg = true)]
44        args: Vec<String>,
45    },
46    /// `zig ranlib` wrapper
47    #[command(name = "ranlib")]
48    Ranlib {
49        /// `zig ranlib` arguments
50        #[arg(num_args = 1.., trailing_var_arg = true)]
51        args: Vec<String>,
52    },
53    /// `zig lib` wrapper
54    #[command(name = "lib")]
55    Lib {
56        /// `zig lib` arguments
57        #[arg(num_args = 1.., trailing_var_arg = true)]
58        args: Vec<String>,
59    },
60    /// `zig dlltool` wrapper
61    #[command(name = "dlltool")]
62    Dlltool {
63        /// `zig dlltool` arguments
64        #[arg(num_args = 1.., trailing_var_arg = true)]
65        args: Vec<String>,
66    },
67}
68
69struct TargetInfo {
70    target: Option<String>,
71}
72
73impl TargetInfo {
74    fn new(target: Option<&String>) -> Self {
75        Self {
76            target: target.cloned(),
77        }
78    }
79
80    // Architecture helpers
81    fn is_arm(&self) -> bool {
82        self.target
83            .as_ref()
84            .map(|x| x.starts_with("arm"))
85            .unwrap_or_default()
86    }
87
88    fn is_aarch64(&self) -> bool {
89        self.target
90            .as_ref()
91            .map(|x| x.starts_with("aarch64"))
92            .unwrap_or_default()
93    }
94
95    fn is_aarch64_be(&self) -> bool {
96        self.target
97            .as_ref()
98            .map(|x| x.starts_with("aarch64_be"))
99            .unwrap_or_default()
100    }
101
102    fn is_i386(&self) -> bool {
103        self.target
104            .as_ref()
105            .map(|x| x.starts_with("i386"))
106            .unwrap_or_default()
107    }
108
109    fn is_i686(&self) -> bool {
110        self.target
111            .as_ref()
112            .map(|x| x.starts_with("i686") || x.starts_with("x86-"))
113            .unwrap_or_default()
114    }
115
116    fn is_riscv64(&self) -> bool {
117        self.target
118            .as_ref()
119            .map(|x| x.starts_with("riscv64"))
120            .unwrap_or_default()
121    }
122
123    fn is_riscv32(&self) -> bool {
124        self.target
125            .as_ref()
126            .map(|x| x.starts_with("riscv32"))
127            .unwrap_or_default()
128    }
129
130    fn is_mips32(&self) -> bool {
131        self.target
132            .as_ref()
133            .map(|x| x.starts_with("mips") && !x.starts_with("mips64"))
134            .unwrap_or_default()
135    }
136
137    // libc helpers
138    fn is_musl(&self) -> bool {
139        self.target
140            .as_ref()
141            .map(|x| x.contains("musl"))
142            .unwrap_or_default()
143    }
144
145    // Platform helpers
146    fn is_macos(&self) -> bool {
147        self.target
148            .as_ref()
149            .map(|x| x.contains("macos"))
150            .unwrap_or_default()
151    }
152
153    fn is_darwin(&self) -> bool {
154        self.target
155            .as_ref()
156            .map(|x| x.contains("darwin"))
157            .unwrap_or_default()
158    }
159
160    fn is_apple_platform(&self) -> bool {
161        self.target
162            .as_ref()
163            .map(|x| {
164                x.contains("macos")
165                    || x.contains("darwin")
166                    || x.contains("ios")
167                    || x.contains("tvos")
168                    || x.contains("watchos")
169                    || x.contains("visionos")
170            })
171            .unwrap_or_default()
172    }
173
174    fn is_ios(&self) -> bool {
175        self.target
176            .as_ref()
177            .map(|x| x.contains("ios") && !x.contains("visionos"))
178            .unwrap_or_default()
179    }
180
181    fn is_tvos(&self) -> bool {
182        self.target
183            .as_ref()
184            .map(|x| x.contains("tvos"))
185            .unwrap_or_default()
186    }
187
188    fn is_watchos(&self) -> bool {
189        self.target
190            .as_ref()
191            .map(|x| x.contains("watchos"))
192            .unwrap_or_default()
193    }
194
195    fn is_visionos(&self) -> bool {
196        self.target
197            .as_ref()
198            .map(|x| x.contains("visionos"))
199            .unwrap_or_default()
200    }
201
202    /// Returns the appropriate Apple CPU for the platform
203    fn apple_cpu(&self) -> &'static str {
204        if self.is_macos() || self.is_darwin() {
205            "apple_m1" // M-series for macOS
206        } else if self.is_visionos() {
207            "apple_m2" // M2 for Apple Vision Pro
208        } else if self.is_watchos() {
209            "apple_s5" // S-series for Apple Watch
210        } else if self.is_ios() || self.is_tvos() {
211            "apple_a14" // A-series for iOS/tvOS (iPhone 12 era - good baseline)
212        } else {
213            "generic"
214        }
215    }
216
217    fn is_freebsd(&self) -> bool {
218        self.target
219            .as_ref()
220            .map(|x| x.contains("freebsd"))
221            .unwrap_or_default()
222    }
223
224    fn is_windows_gnu(&self) -> bool {
225        self.target
226            .as_ref()
227            .map(|x| x.contains("windows-gnu"))
228            .unwrap_or_default()
229    }
230
231    fn is_windows_msvc(&self) -> bool {
232        self.target
233            .as_ref()
234            .map(|x| x.contains("windows-msvc"))
235            .unwrap_or_default()
236    }
237
238    fn is_ohos(&self) -> bool {
239        self.target
240            .as_ref()
241            .map(|x| x.contains("ohos"))
242            .unwrap_or_default()
243    }
244}
245
246impl Zig {
247    /// Execute the underlying zig command
248    pub fn execute(&self) -> Result<()> {
249        match self {
250            Zig::Cc { args } => self.execute_compiler("cc", args),
251            Zig::Cxx { args } => self.execute_compiler("c++", args),
252            Zig::Ar { args } => self.execute_tool("ar", args),
253            Zig::Ranlib { args } => self.execute_compiler("ranlib", args),
254            Zig::Lib { args } => self.execute_compiler("lib", args),
255            Zig::Dlltool { args } => self.execute_dlltool(args),
256        }
257    }
258
259    /// Execute zig dlltool command
260    /// Filter out unsupported options for older zig versions (< 0.12)
261    pub fn execute_dlltool(&self, cmd_args: &[String]) -> Result<()> {
262        let zig_version = Zig::zig_version()?;
263        let needs_filtering = zig_version.major == 0 && zig_version.minor < 12;
264
265        if !needs_filtering {
266            return self.execute_tool("dlltool", cmd_args);
267        }
268
269        // Filter out --no-leading-underscore, --temp-prefix, and -t (short form)
270        // These options are not supported by zig dlltool in versions < 0.12
271        let mut filtered_args = Vec::with_capacity(cmd_args.len());
272        let mut skip_next = false;
273        for arg in cmd_args {
274            if skip_next {
275                skip_next = false;
276                continue;
277            }
278            if arg == "--no-leading-underscore" {
279                continue;
280            }
281            if arg == "--temp-prefix" || arg == "-t" {
282                // Skip this arg and the next one (the value)
283                skip_next = true;
284                continue;
285            }
286            // Handle --temp-prefix=value and -t=value forms
287            if arg.starts_with("--temp-prefix=") || arg.starts_with("-t=") {
288                continue;
289            }
290            filtered_args.push(arg.clone());
291        }
292
293        self.execute_tool("dlltool", &filtered_args)
294    }
295
296    /// Execute zig cc/c++ command
297    pub fn execute_compiler(&self, cmd: &str, cmd_args: &[String]) -> Result<()> {
298        let target = cmd_args
299            .iter()
300            .position(|x| x == "-target")
301            .and_then(|index| cmd_args.get(index + 1));
302        let target_info = TargetInfo::new(target);
303
304        let rustc_ver = match env::var("CARGO_ZIGBUILD_RUSTC_VERSION") {
305            Ok(version) => version.parse()?,
306            Err(_) => rustc_version::version()?,
307        };
308        let zig_version = Zig::zig_version()?;
309
310        let mut new_cmd_args = Vec::with_capacity(cmd_args.len());
311        let mut skip_next_arg = false;
312        for arg in cmd_args {
313            if skip_next_arg {
314                skip_next_arg = false;
315                continue;
316            }
317            let args = if arg.starts_with('@') && arg.ends_with("linker-arguments") {
318                vec![self.process_linker_response_file(
319                    arg,
320                    &rustc_ver,
321                    &zig_version,
322                    &target_info,
323                )?]
324            } else {
325                self.filter_linker_arg(arg, &rustc_ver, &zig_version, &target_info)
326            };
327            for arg in args {
328                if arg == "-Wl,-exported_symbols_list" || arg == "-Wl,--dynamic-list" {
329                    // Filter out this and the next argument
330                    // zig cc doesn't pass these through to lld even though lld supports them
331                    // See https://github.com/rust-cross/cargo-zigbuild/issues/355
332                    skip_next_arg = true;
333                } else {
334                    new_cmd_args.push(arg);
335                }
336            }
337        }
338
339        if target_info.is_mips32() {
340            // See https://github.com/ziglang/zig/issues/4925#issuecomment-1499823425
341            new_cmd_args.push("-Wl,-z,notext".to_string());
342        }
343
344        if self.has_undefined_dynamic_lookup(cmd_args) {
345            new_cmd_args.push("-Wl,-undefined=dynamic_lookup".to_string());
346        }
347        if target_info.is_macos() {
348            if self.should_add_libcharset(cmd_args, &zig_version) {
349                new_cmd_args.push("-lcharset".to_string());
350            }
351            self.add_macos_specific_args(&mut new_cmd_args, &zig_version)?;
352        }
353
354        // For Zig >= 0.15 with macOS, set SDKROOT environment variable
355        // if it exists, instead of passing --sysroot
356        let mut command = Self::command()?;
357        if (zig_version.major, zig_version.minor) >= (0, 15) {
358            if let Some(sdkroot) = Self::macos_sdk_root() {
359                command.env("SDKROOT", sdkroot);
360            }
361        }
362
363        let mut child = command
364            .arg(cmd)
365            .args(new_cmd_args)
366            .spawn()
367            .with_context(|| format!("Failed to run `zig {cmd}`"))?;
368        let status = child.wait().expect("Failed to wait on zig child process");
369        if !status.success() {
370            process::exit(status.code().unwrap_or(1));
371        }
372        Ok(())
373    }
374
375    fn process_linker_response_file(
376        &self,
377        arg: &str,
378        rustc_ver: &rustc_version::Version,
379        zig_version: &semver::Version,
380        target_info: &TargetInfo,
381    ) -> Result<String> {
382        // rustc passes arguments to linker via an @-file when arguments are too long
383        // See https://github.com/rust-lang/rust/issues/41190
384        // and https://github.com/rust-lang/rust/blob/87937d3b6c302dfedfa5c4b94d0a30985d46298d/compiler/rustc_codegen_ssa/src/back/link.rs#L1373-L1382
385        let content_bytes = fs::read(arg.trim_start_matches('@'))?;
386        let content = if target_info.is_windows_msvc() {
387            if content_bytes[0..2] != [255, 254] {
388                bail!(
389                    "linker response file `{}` didn't start with a utf16 BOM",
390                    &arg
391                );
392            }
393            let content_utf16: Vec<u16> = content_bytes[2..]
394                .chunks_exact(2)
395                .map(|a| u16::from_ne_bytes([a[0], a[1]]))
396                .collect();
397            String::from_utf16(&content_utf16).with_context(|| {
398                format!(
399                    "linker response file `{}` didn't contain valid utf16 content",
400                    &arg
401                )
402            })?
403        } else {
404            String::from_utf8(content_bytes).with_context(|| {
405                format!(
406                    "linker response file `{}` didn't contain valid utf8 content",
407                    &arg
408                )
409            })?
410        };
411        let mut link_args: Vec<_> = content
412            .split('\n')
413            .flat_map(|arg| self.filter_linker_arg(arg, rustc_ver, zig_version, target_info))
414            .collect();
415        if self.has_undefined_dynamic_lookup(&link_args) {
416            link_args.push("-Wl,-undefined=dynamic_lookup".to_string());
417        }
418        if target_info.is_macos() && self.should_add_libcharset(&link_args, zig_version) {
419            link_args.push("-lcharset".to_string());
420        }
421        if target_info.is_windows_msvc() {
422            let new_content = link_args.join("\n");
423            let mut out = Vec::with_capacity((1 + new_content.len()) * 2);
424            // start the stream with a UTF-16 BOM
425            for c in std::iter::once(0xFEFF).chain(new_content.encode_utf16()) {
426                // encode in little endian
427                out.push(c as u8);
428                out.push((c >> 8) as u8);
429            }
430            fs::write(arg.trim_start_matches('@'), out)?;
431        } else {
432            fs::write(arg.trim_start_matches('@'), link_args.join("\n").as_bytes())?;
433        }
434        Ok(arg.to_string())
435    }
436
437    fn filter_linker_arg(
438        &self,
439        arg: &str,
440        rustc_ver: &rustc_version::Version,
441        zig_version: &semver::Version,
442        target_info: &TargetInfo,
443    ) -> Vec<String> {
444        if arg == "-lgcc_s" {
445            // Replace libgcc_s with libunwind
446            return vec!["-lunwind".to_string()];
447        } else if arg.starts_with("--target=") {
448            // We have already passed target via `-target`
449            return vec![];
450        } else if arg.starts_with("-e") && arg.len() > 2 && !arg.starts_with("-export") {
451            // GCC accepts -e<entry> (no space) but zig/clang requires -e <entry> (with space)
452            // Transform to -Wl,--entry=<entry> to pass directly to the linker
453            // See https://github.com/rust-cross/cargo-zigbuild/issues/378
454            let entry = &arg[2..];
455            return vec![format!("-Wl,--entry={}", entry)];
456        }
457        if (target_info.is_arm() || target_info.is_windows_gnu())
458            && arg.ends_with(".rlib")
459            && arg.contains("libcompiler_builtins-")
460        {
461            // compiler-builtins is duplicated with zig's compiler-rt
462            return vec![];
463        }
464        if target_info.is_windows_gnu() {
465            #[allow(clippy::if_same_then_else)]
466            if arg == "-lgcc_eh"
467                && ((zig_version.major, zig_version.minor) < (0, 14) || target_info.is_i686())
468            {
469                // zig<0.14 doesn't provide gcc_eh alternative
470                // For i686-pc-windows-gnu, zig's libgcc_eh doesn't provide __register_frame_info
471                // and __deregister_frame_info symbols required by Rust's rsbegin.o
472                // We use libc++ to replace it on windows gnu targets
473                return vec!["-lc++".to_string()];
474            } else if arg.ends_with("rsbegin.o") || arg.ends_with("rsend.o") {
475                // i686-pc-windows-gnu rsbegin.o/rsend.o require __register_frame_info and
476                // __deregister_frame_info symbols which are GCC-specific. Zig uses LLVM's
477                // libunwind which provides __register_frame (without _info) instead.
478                // Filtering these out allows compilation but breaks panic unwinding.
479                // Users requiring panic unwinding should use a real MinGW toolchain.
480                if target_info.is_i686() {
481                    return vec![];
482                }
483            } else if arg == "-Wl,-Bdynamic" && (zig_version.major, zig_version.minor) >= (0, 11) {
484                // https://github.com/ziglang/zig/pull/16058
485                // zig changes the linker behavior, -Bdynamic won't search *.a for mingw, but this may be fixed in the later version
486                // here is a workaround to replace the linker switch with -search_paths_first, which will search for *.dll,*lib first,
487                // then fallback to *.a
488                return vec!["-Wl,-search_paths_first".to_owned()];
489            } else if arg == "-lwindows" || arg == "-l:libpthread.a" || arg == "-lgcc" {
490                return vec![];
491            } else if arg == "-Wl,--disable-auto-image-base"
492                || arg == "-Wl,--dynamicbase"
493                || arg == "-Wl,--large-address-aware"
494                || (arg.starts_with("-Wl,")
495                    && (arg.ends_with("/list.def") || arg.ends_with("\\list.def")))
496            {
497                // https://github.com/rust-lang/rust/blob/f0bc76ac41a0a832c9ee621e31aaf1f515d3d6a5/compiler/rustc_target/src/spec/windows_gnu_base.rs#L23
498                // https://github.com/rust-lang/rust/blob/2fb0e8d162a021f8a795fb603f5d8c0017855160/compiler/rustc_target/src/spec/windows_gnu_base.rs#L22
499                // https://github.com/rust-lang/rust/blob/f0bc76ac41a0a832c9ee621e31aaf1f515d3d6a5/compiler/rustc_target/src/spec/i686_pc_windows_gnu.rs#L16
500                // zig doesn't support --disable-auto-image-base, --dynamicbase and --large-address-aware
501                return vec![];
502            } else if arg == "-lmsvcrt" {
503                return vec![];
504            }
505        } else if arg == "-Wl,--no-undefined-version" {
506            // https://github.com/rust-lang/rust/blob/542ed2bf72b232b245ece058fc11aebb1ca507d7/compiler/rustc_codegen_ssa/src/back/linker.rs#L723
507            // zig doesn't support --no-undefined-version
508            return vec![];
509        } else if arg == "-Wl,-znostart-stop-gc" {
510            // https://github.com/rust-lang/rust/blob/c580c498a1fe144d7c5b2dfc7faab1a229aa288b/compiler/rustc_codegen_ssa/src/back/link.rs#L3371
511            // zig doesn't support -znostart-stop-gc
512            return vec![];
513        } else if arg.starts_with("-Wl,-plugin-opt") {
514            // https://github.com/rust-cross/cargo-zigbuild/issues/369
515            // zig doesn't support -plugin-opt (used for cross-lang LTO with LLVM gold plugin)
516            // Since zig cc is already LLVM-based, ignoring this is fine
517            return vec![];
518        }
519        if target_info.is_musl() || target_info.is_ohos() {
520            // Avoids duplicated symbols with both zig musl libc and the libc crate
521            if arg.ends_with(".o") && arg.contains("self-contained") && arg.contains("crt") {
522                return vec![];
523            } else if arg == "-Wl,-melf_i386" {
524                // unsupported linker arg: -melf_i386
525                return vec![];
526            }
527            if rustc_ver.major == 1
528                && rustc_ver.minor < 59
529                && arg.ends_with(".rlib")
530                && arg.contains("liblibc-")
531            {
532                // Rust distributes standalone libc.a in self-contained for musl since 1.59.0
533                // See https://github.com/rust-lang/rust/pull/90527
534                return vec![];
535            }
536            if arg == "-lc" {
537                return vec![];
538            }
539        }
540        if arg.starts_with("-march=") {
541            // Ignore `-march` option for arm* targets, we use `generic` + cpu features instead
542            if target_info.is_arm() || target_info.is_i386() {
543                return vec![];
544            } else if target_info.is_riscv64() {
545                return vec!["-march=generic_rv64".to_string()];
546            } else if target_info.is_riscv32() {
547                return vec!["-march=generic_rv32".to_string()];
548            } else if arg.starts_with("-march=armv") {
549                // zig doesn't support GCC-style -march=armvX.Y-a+feature syntax
550                // Convert to -mcpu with features preserved
551                if target_info.is_aarch64() || target_info.is_aarch64_be() {
552                    // Extract features after the base arch (e.g., +sha3+crypto from armv8.4-a+sha3+crypto)
553                    let march_value = arg.strip_prefix("-march=").unwrap();
554                    // Find the first '+' which marks the start of features
555                    let features = if let Some(pos) = march_value.find('+') {
556                        &march_value[pos..]
557                    } else {
558                        ""
559                    };
560                    let base_cpu = if target_info.is_apple_platform() {
561                        target_info.apple_cpu()
562                    } else {
563                        "generic"
564                    };
565                    let mut result = vec![format!("-mcpu={}{}", base_cpu, features)];
566                    if features.contains("+crypto") {
567                        // Workaround for building sha1-asm on aarch64
568                        // See:
569                        // https://github.com/rust-cross/cargo-zigbuild/issues/149
570                        // https://github.com/RustCrypto/asm-hashes/blob/master/sha1/build.rs#L17-L19
571                        // https://github.com/ziglang/zig/issues/10411
572                        result.append(&mut vec!["-Xassembler".to_owned(), arg.to_string()]);
573                    }
574                    return result;
575                }
576            }
577        }
578        if target_info.is_macos() {
579            if arg.starts_with("-Wl,-exported_symbols_list,") {
580                // zig doesn't support -exported_symbols_list arg
581                // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-exported_symbols_list
582                return vec![];
583            }
584            if arg == "-Wl,-dylib" {
585                // zig doesn't support -dylib
586                return vec![];
587            }
588        }
589        if target_info.is_freebsd() {
590            let ignored_libs = ["-lkvm", "-lmemstat", "-lprocstat", "-ldevstat"];
591            if ignored_libs.contains(&arg) {
592                return vec![];
593            }
594        }
595        vec![arg.to_string()]
596    }
597
598    fn has_undefined_dynamic_lookup(&self, args: &[String]) -> bool {
599        let undefined = args
600            .iter()
601            .position(|x| x == "-undefined")
602            .and_then(|i| args.get(i + 1));
603        matches!(undefined, Some(x) if x == "dynamic_lookup")
604    }
605
606    fn should_add_libcharset(&self, args: &[String], zig_version: &semver::Version) -> bool {
607        // See https://github.com/apple-oss-distributions/libiconv/blob/a167071feb7a83a01b27ec8d238590c14eb6faff/xcodeconfig/libiconv.xcconfig
608        if (zig_version.major, zig_version.minor) >= (0, 12) {
609            args.iter().any(|x| x == "-liconv") && !args.iter().any(|x| x == "-lcharset")
610        } else {
611            false
612        }
613    }
614
615    fn add_macos_specific_args(
616        &self,
617        new_cmd_args: &mut Vec<String>,
618        zig_version: &semver::Version,
619    ) -> Result<()> {
620        let sdkroot = Self::macos_sdk_root();
621        if (zig_version.major, zig_version.minor) >= (0, 12) {
622            // Zig 0.12.0+ requires passing `--sysroot`
623            // However, for Zig 0.15+, we should use SDKROOT environment variable instead
624            // to avoid issues with library paths being interpreted relative to sysroot
625            if let Some(ref sdkroot) = sdkroot {
626                if (zig_version.major, zig_version.minor) < (0, 15) {
627                    new_cmd_args.push(format!("--sysroot={}", sdkroot.display()));
628                }
629                // For Zig >= 0.15, SDKROOT will be set as environment variable
630            }
631        }
632        if let Some(ref sdkroot) = sdkroot {
633            if (zig_version.major, zig_version.minor) < (0, 15) {
634                // For zig < 0.15, we need to explicitly add SDK paths with --sysroot
635                new_cmd_args.extend_from_slice(&[
636                    "-isystem".to_string(),
637                    format!("{}", sdkroot.join("usr").join("include").display()),
638                    format!("-L{}", sdkroot.join("usr").join("lib").display()),
639                    format!(
640                        "-F{}",
641                        sdkroot
642                            .join("System")
643                            .join("Library")
644                            .join("Frameworks")
645                            .display()
646                    ),
647                    "-DTARGET_OS_IPHONE=0".to_string(),
648                ]);
649            } else {
650                // For zig >= 0.15 with SDKROOT, we still need to add framework paths
651                // Use -iframework for framework header search
652                new_cmd_args.extend_from_slice(&[
653                    "-isystem".to_string(),
654                    format!("{}", sdkroot.join("usr").join("include").display()),
655                    format!("-L{}", sdkroot.join("usr").join("lib").display()),
656                    "-iframework".to_string(),
657                    format!(
658                        "{}",
659                        sdkroot
660                            .join("System")
661                            .join("Library")
662                            .join("Frameworks")
663                            .display()
664                    ),
665                    "-DTARGET_OS_IPHONE=0".to_string(),
666                ]);
667            }
668        }
669
670        // Add the deps directory that contains `.tbd` files to the library search path
671        let cache_dir = cache_dir();
672        let deps_dir = cache_dir.join("deps");
673        fs::create_dir_all(&deps_dir)?;
674        write_tbd_files(&deps_dir)?;
675        new_cmd_args.push("-L".to_string());
676        new_cmd_args.push(format!("{}", deps_dir.display()));
677        Ok(())
678    }
679
680    /// Execute zig ar/ranlib command
681    pub fn execute_tool(&self, cmd: &str, cmd_args: &[String]) -> Result<()> {
682        let mut child = Self::command()?
683            .arg(cmd)
684            .args(cmd_args)
685            .spawn()
686            .with_context(|| format!("Failed to run `zig {cmd}`"))?;
687        let status = child.wait().expect("Failed to wait on zig child process");
688        if !status.success() {
689            process::exit(status.code().unwrap_or(1));
690        }
691        Ok(())
692    }
693
694    /// Build the zig command line
695    pub fn command() -> Result<Command> {
696        let (zig, zig_args) = Self::find_zig()?;
697        let mut cmd = Command::new(zig);
698        cmd.args(zig_args);
699        Ok(cmd)
700    }
701
702    fn zig_version() -> Result<semver::Version> {
703        static ZIG_VERSION: OnceLock<semver::Version> = OnceLock::new();
704
705        if let Some(version) = ZIG_VERSION.get() {
706            return Ok(version.clone());
707        }
708        // Check for cached version from environment variable first
709        if let Ok(version_str) = env::var("CARGO_ZIGBUILD_ZIG_VERSION") {
710            if let Ok(version) = semver::Version::parse(&version_str) {
711                return Ok(ZIG_VERSION.get_or_init(|| version).clone());
712            }
713        }
714        let output = Self::command()?.arg("version").output()?;
715        let version_str =
716            str::from_utf8(&output.stdout).context("`zig version` didn't return utf8 output")?;
717        let version = semver::Version::parse(version_str.trim())?;
718        Ok(ZIG_VERSION.get_or_init(|| version).clone())
719    }
720
721    /// Search for `python -m ziglang` first and for `zig` second.
722    pub fn find_zig() -> Result<(PathBuf, Vec<String>)> {
723        static ZIG_PATH: OnceLock<(PathBuf, Vec<String>)> = OnceLock::new();
724
725        if let Some(cached) = ZIG_PATH.get() {
726            return Ok(cached.clone());
727        }
728        let result = Self::find_zig_python()
729            .or_else(|_| Self::find_zig_bin())
730            .context("Failed to find zig")?;
731        Ok(ZIG_PATH.get_or_init(|| result).clone())
732    }
733
734    /// Detect the plain zig binary
735    fn find_zig_bin() -> Result<(PathBuf, Vec<String>)> {
736        let zig_path = zig_path()?;
737        let output = Command::new(&zig_path).arg("version").output()?;
738
739        let version_str = str::from_utf8(&output.stdout).with_context(|| {
740            format!("`{} version` didn't return utf8 output", zig_path.display())
741        })?;
742        Self::validate_zig_version(version_str)?;
743        Ok((zig_path, Vec::new()))
744    }
745
746    /// Detect the Python ziglang package
747    fn find_zig_python() -> Result<(PathBuf, Vec<String>)> {
748        let python_path = python_path()?;
749        let output = Command::new(&python_path)
750            .args(["-m", "ziglang", "version"])
751            .output()?;
752
753        let version_str = str::from_utf8(&output.stdout).with_context(|| {
754            format!(
755                "`{} -m ziglang version` didn't return utf8 output",
756                python_path.display()
757            )
758        })?;
759        Self::validate_zig_version(version_str)?;
760        Ok((python_path, vec!["-m".to_string(), "ziglang".to_string()]))
761    }
762
763    fn validate_zig_version(version: &str) -> Result<()> {
764        let min_ver = semver::Version::new(0, 9, 0);
765        let version = semver::Version::parse(version.trim())?;
766        if version >= min_ver {
767            Ok(())
768        } else {
769            bail!(
770                "zig version {} is too old, need at least {}",
771                version,
772                min_ver
773            )
774        }
775    }
776
777    /// Find zig lib directory
778    pub fn lib_dir() -> Result<PathBuf> {
779        static LIB_DIR: OnceLock<PathBuf> = OnceLock::new();
780
781        if let Some(cached) = LIB_DIR.get() {
782            return Ok(cached.clone());
783        }
784        let (zig, zig_args) = Self::find_zig()?;
785        let zig_version = Self::zig_version()?;
786        let output = Command::new(zig).args(zig_args).arg("env").output()?;
787        let parse_zon_lib_dir = || -> Result<PathBuf> {
788            let output_str =
789                str::from_utf8(&output.stdout).context("`zig env` didn't return utf8 output")?;
790            let lib_dir = output_str
791                .find(".lib_dir")
792                .and_then(|idx| {
793                    let bytes = output_str.as_bytes();
794                    let mut start = idx;
795                    while start < bytes.len() && bytes[start] != b'"' {
796                        start += 1;
797                    }
798                    if start >= bytes.len() {
799                        return None;
800                    }
801                    let mut end = start + 1;
802                    while end < bytes.len() && bytes[end] != b'"' {
803                        end += 1;
804                    }
805                    if end >= bytes.len() {
806                        return None;
807                    }
808                    Some(&output_str[start + 1..end])
809                })
810                .context("Failed to parse lib_dir from `zig env` ZON output")?;
811            Ok(PathBuf::from(lib_dir))
812        };
813        let lib_dir = if zig_version >= semver::Version::new(0, 15, 0) {
814            parse_zon_lib_dir()?
815        } else {
816            serde_json::from_slice::<ZigEnv>(&output.stdout)
817                .map(|zig_env| PathBuf::from(zig_env.lib_dir))
818                .or_else(|_| parse_zon_lib_dir())?
819        };
820        Ok(LIB_DIR.get_or_init(|| lib_dir).clone())
821    }
822
823    fn add_env_if_missing<K, V>(command: &mut Command, name: K, value: V)
824    where
825        K: AsRef<OsStr>,
826        V: AsRef<OsStr>,
827    {
828        let command_env_contains_no_key =
829            |name: &K| !command.get_envs().any(|(key, _)| name.as_ref() == key);
830
831        if command_env_contains_no_key(&name) && env::var_os(&name).is_none() {
832            command.env(name, value);
833        }
834    }
835
836    pub(crate) fn apply_command_env(
837        manifest_path: Option<&Path>,
838        release: bool,
839        cargo: &cargo_options::CommonOptions,
840        cmd: &mut Command,
841        enable_zig_ar: bool,
842    ) -> Result<()> {
843        // setup zig as linker
844        let rust_targets = cargo
845            .target
846            .iter()
847            .map(|target| target.split_once('.').map(|(t, _)| t).unwrap_or(target))
848            .collect::<Vec<&str>>();
849        let rustc_meta = rustc_version::version_meta()?;
850        Self::add_env_if_missing(
851            cmd,
852            "CARGO_ZIGBUILD_RUSTC_VERSION",
853            rustc_meta.semver.to_string(),
854        );
855        let host_target = &rustc_meta.host;
856        for (parsed_target, raw_target) in rust_targets.iter().zip(&cargo.target) {
857            let env_target = parsed_target.replace('-', "_");
858            let zig_wrapper = prepare_zig_linker(raw_target)?;
859
860            if is_mingw_shell() {
861                let zig_cc = zig_wrapper.cc.to_slash_lossy();
862                let zig_cxx = zig_wrapper.cxx.to_slash_lossy();
863                Self::add_env_if_missing(cmd, format!("CC_{env_target}"), &*zig_cc);
864                Self::add_env_if_missing(cmd, format!("CXX_{env_target}"), &*zig_cxx);
865                if !parsed_target.contains("wasm") {
866                    Self::add_env_if_missing(
867                        cmd,
868                        format!("CARGO_TARGET_{}_LINKER", env_target.to_uppercase()),
869                        &*zig_cc,
870                    );
871                }
872            } else {
873                Self::add_env_if_missing(cmd, format!("CC_{env_target}"), &zig_wrapper.cc);
874                Self::add_env_if_missing(cmd, format!("CXX_{env_target}"), &zig_wrapper.cxx);
875                if !parsed_target.contains("wasm") {
876                    Self::add_env_if_missing(
877                        cmd,
878                        format!("CARGO_TARGET_{}_LINKER", env_target.to_uppercase()),
879                        &zig_wrapper.cc,
880                    );
881                }
882            }
883
884            Self::add_env_if_missing(cmd, format!("RANLIB_{env_target}"), &zig_wrapper.ranlib);
885            // Only setup AR when explicitly asked to
886            // because it need special executable name handling, see src/bin/cargo-zigbuild.rs
887            if enable_zig_ar {
888                if parsed_target.contains("msvc") {
889                    Self::add_env_if_missing(cmd, format!("AR_{env_target}"), &zig_wrapper.lib);
890                } else {
891                    Self::add_env_if_missing(cmd, format!("AR_{env_target}"), &zig_wrapper.ar);
892                }
893            }
894
895            Self::setup_os_deps(manifest_path, release, cargo)?;
896
897            let cmake_toolchain_file_env = format!("CMAKE_TOOLCHAIN_FILE_{env_target}");
898            if env::var_os(&cmake_toolchain_file_env).is_none()
899                && env::var_os(format!("CMAKE_TOOLCHAIN_FILE_{parsed_target}")).is_none()
900                && env::var_os("TARGET_CMAKE_TOOLCHAIN_FILE").is_none()
901                && env::var_os("CMAKE_TOOLCHAIN_FILE").is_none()
902            {
903                if let Ok(cmake_toolchain_file) =
904                    Self::setup_cmake_toolchain(parsed_target, &zig_wrapper, enable_zig_ar)
905                {
906                    cmd.env(cmake_toolchain_file_env, cmake_toolchain_file);
907                }
908            }
909
910            if raw_target.contains("windows-gnu") {
911                cmd.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
912                // Add the cache directory to PATH so rustc can find architecture-specific dlltool
913                // (e.g., x86_64-w64-mingw32-dlltool), but only if no system dlltool exists
914                // If system mingw-w64 dlltool exists, prefer it over zig's dlltool
915                let triple: Triple = parsed_target.parse().unwrap_or_else(|_| Triple::unknown());
916                if !has_system_dlltool(&triple.architecture) {
917                    let cache_dir = cache_dir();
918                    let existing_path = env::var_os("PATH").unwrap_or_default();
919                    let paths = std::iter::once(cache_dir).chain(env::split_paths(&existing_path));
920                    if let Ok(new_path) = env::join_paths(paths) {
921                        cmd.env("PATH", new_path);
922                    }
923                }
924            }
925
926            if raw_target.contains("apple-darwin") {
927                if let Some(sdkroot) = Self::macos_sdk_root() {
928                    if env::var_os("PKG_CONFIG_SYSROOT_DIR").is_none() {
929                        // Set PKG_CONFIG_SYSROOT_DIR for pkg-config crate
930                        cmd.env("PKG_CONFIG_SYSROOT_DIR", sdkroot);
931                    }
932                }
933            }
934
935            // Enable unstable `target-applies-to-host` option automatically
936            // when target is the same as host but may have specified glibc version
937            if host_target == parsed_target {
938                if !matches!(rustc_meta.channel, rustc_version::Channel::Nightly) {
939                    // Hack to use the unstable feature on stable Rust
940                    // https://github.com/rust-lang/cargo/pull/9753#issuecomment-1022919343
941                    cmd.env("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS", "nightly");
942                }
943                cmd.env("CARGO_UNSTABLE_TARGET_APPLIES_TO_HOST", "true");
944                cmd.env("CARGO_TARGET_APPLIES_TO_HOST", "false");
945            }
946
947            // Pass options used by zig cc down to bindgen, if possible
948            let mut options = Self::collect_zig_cc_options(&zig_wrapper, raw_target)
949                .context("Failed to collect `zig cc` options")?;
950            if raw_target.contains("apple-darwin") {
951                // everyone seems to miss `#import <TargetConditionals.h>`...
952                options.push("-DTARGET_OS_IPHONE=0".to_string());
953            }
954            let escaped_options = shell_words::join(options.iter().map(|s| &s[..]));
955            let bindgen_env = "BINDGEN_EXTRA_CLANG_ARGS";
956            let fallback_value = env::var(bindgen_env);
957            for target in [&env_target[..], parsed_target] {
958                let name = format!("{bindgen_env}_{target}");
959                if let Ok(mut value) = env::var(&name).or(fallback_value.clone()) {
960                    if shell_words::split(&value).is_err() {
961                        // bindgen treats the whole string as a single argument if split fails
962                        value = shell_words::quote(&value).into_owned();
963                    }
964                    if !value.is_empty() {
965                        value.push(' ');
966                    }
967                    value.push_str(&escaped_options);
968                    unsafe { env::set_var(name, value) };
969                } else {
970                    unsafe { env::set_var(name, escaped_options.clone()) };
971                }
972            }
973        }
974        Ok(())
975    }
976
977    /// Collects compiler options used by `zig cc` for given target.
978    /// Used for the case where `zig cc` cannot be used but underlying options should be retained,
979    /// for example, as in bindgen (which requires libclang.so and thus is independent from zig).
980    fn collect_zig_cc_options(zig_wrapper: &ZigWrapper, raw_target: &str) -> Result<Vec<String>> {
981        #[derive(Debug, PartialEq, Eq)]
982        enum Kind {
983            Normal,
984            Framework,
985        }
986
987        #[derive(Debug)]
988        struct PerLanguageOptions {
989            glibc_minor_ver: Option<u32>,
990            include_paths: Vec<(Kind, String)>,
991        }
992
993        fn collect_per_language_options(
994            program: &Path,
995            ext: &str,
996            raw_target: &str,
997        ) -> Result<PerLanguageOptions> {
998            // We can't use `-x c` or `-x c++` because pre-0.11 Zig doesn't handle them
999            let empty_file_path = cache_dir().join(format!(".intentionally-empty-file.{ext}"));
1000            if !empty_file_path.exists() {
1001                fs::write(&empty_file_path, "")?;
1002            }
1003
1004            let output = Command::new(program)
1005                .arg("-E")
1006                .arg(&empty_file_path)
1007                .arg("-v")
1008                .output()?;
1009            // Clang always generates UTF-8 regardless of locale, so this is okay.
1010            let stderr = String::from_utf8(output.stderr)?;
1011            if !output.status.success() {
1012                bail!(
1013                    "Failed to run `zig cc -v` with status {}: {}",
1014                    output.status,
1015                    stderr.trim(),
1016                );
1017            }
1018
1019            // Collect some macro definitions from cc1 options. We can't directly use
1020            // them though, as we can't distinguish options added by zig from options
1021            // added by clang driver (e.g. `__GCC_HAVE_DWARF2_CFI_ASM`).
1022            let glibc_minor_ver = if let Some(start) = stderr.find("__GLIBC_MINOR__=") {
1023                let stderr = &stderr[start + 16..];
1024                let end = stderr
1025                    .find(|c: char| !c.is_ascii_digit())
1026                    .unwrap_or(stderr.len());
1027                stderr[..end].parse().ok()
1028            } else {
1029                None
1030            };
1031
1032            let start = stderr
1033                .find("#include <...> search starts here:")
1034                .ok_or_else(|| anyhow!("Failed to parse `zig cc -v` output"))?
1035                + 34;
1036            let end = stderr
1037                .find("End of search list.")
1038                .ok_or_else(|| anyhow!("Failed to parse `zig cc -v` output"))?;
1039
1040            let mut include_paths = Vec::new();
1041            for mut line in stderr[start..end].lines() {
1042                line = line.trim();
1043                let mut kind = Kind::Normal;
1044                if line.ends_with(" (framework directory)") {
1045                    line = line[..line.len() - 22].trim();
1046                    kind = Kind::Framework;
1047                } else if line.ends_with(" (headermap)") {
1048                    bail!("C/C++ search path includes header maps, which are not supported");
1049                }
1050                if !line.is_empty() {
1051                    include_paths.push((kind, line.to_owned()));
1052                }
1053            }
1054
1055            // In openharmony, we should add search header path by default which is useful for bindgen.
1056            if raw_target.contains("ohos") {
1057                let ndk = env::var("OHOS_NDK_HOME").expect("Can't get NDK path");
1058                include_paths.push((Kind::Normal, format!("{}/native/sysroot/usr/include", ndk)));
1059            }
1060
1061            Ok(PerLanguageOptions {
1062                include_paths,
1063                glibc_minor_ver,
1064            })
1065        }
1066
1067        let c_opts = collect_per_language_options(&zig_wrapper.cc, "c", raw_target)?;
1068        let cpp_opts = collect_per_language_options(&zig_wrapper.cxx, "cpp", raw_target)?;
1069
1070        // Ensure that `c_opts` and `cpp_opts` are almost identical in the way we expect.
1071        if c_opts.glibc_minor_ver != cpp_opts.glibc_minor_ver {
1072            bail!(
1073                "`zig cc` gives a different glibc minor version for C ({:?}) and C++ ({:?})",
1074                c_opts.glibc_minor_ver,
1075                cpp_opts.glibc_minor_ver,
1076            );
1077        }
1078        let c_paths = c_opts.include_paths;
1079        let mut cpp_paths = cpp_opts.include_paths;
1080        let cpp_pre_len = cpp_paths
1081            .iter()
1082            .position(|p| {
1083                p == c_paths
1084                    .iter()
1085                    .find(|(kind, _)| *kind == Kind::Normal)
1086                    .unwrap()
1087            })
1088            .unwrap_or_default();
1089        let cpp_post_len = cpp_paths.len()
1090            - cpp_paths
1091                .iter()
1092                .position(|p| p == c_paths.last().unwrap())
1093                .unwrap_or_default()
1094            - 1;
1095
1096        // <digression>
1097        //
1098        // So, why we do need all of these?
1099        //
1100        // Bindgen wouldn't look at our `zig cc` (which doesn't contain `libclang.so` anyway),
1101        // but it does collect include paths from the local clang and feed them to `libclang.so`.
1102        // We want those include paths to come from our `zig cc` instead of the local clang.
1103        // There are three main mechanisms possible:
1104        //
1105        // 1. Replace the local clang with our version.
1106        //
1107        //    Bindgen, internally via clang-sys, recognizes `CLANG_PATH` and `PATH`.
1108        //    They are unfortunately a global namespace and simply setting them may break
1109        //    existing build scripts, so we can't confidently override them.
1110        //
1111        //    Clang-sys can also look at target-prefixed clang if arguments contain `-target`.
1112        //    Unfortunately clang-sys can only recognize `-target xxx`, which very slightly
1113        //    differs from what bindgen would pass (`-target=xxx`), so this is not yet possible.
1114        //
1115        //    It should be also noted that we need to collect not only include paths
1116        //    but macro definitions added by Zig, for example `-D__GLIBC_MINOR__`.
1117        //    Clang-sys can't do this yet, so this option seems less robust than we want.
1118        //
1119        // 2. Set the environment variable `BINDGEN_EXTRA_CLANG_ARGS` and let bindgen to
1120        //    append them to arguments passed to `libclang.so`.
1121        //
1122        //    This unfortunately means that we have the same set of arguments for C and C++.
1123        //    Also we have to support older versions of clang, as old as clang 5 (2017).
1124        //    We do have options like `-c-isystem` (cc1 only) and `-cxx-isystem`,
1125        //    but we need to be aware of other options may affect our added options
1126        //    and this requires a nitty gritty of clang driver and cc1---really annoying.
1127        //
1128        // 3. Fix either bindgen or clang-sys or Zig to ease our jobs.
1129        //
1130        //    This is not the option for now because, even after fixes, we have to support
1131        //    older versions of bindgen or Zig which won't have those fixes anyway.
1132        //    But it seems that minor changes to bindgen can indeed fix lots of issues
1133        //    we face, so we are looking for them in the future.
1134        //
1135        // For this reason, we chose the option 2 and overrode `BINDGEN_EXTRA_CLANG_ARGS`.
1136        // The following therefore assumes some understanding about clang option handling,
1137        // including what the heck is cc1 (see the clang FAQ) and how driver options get
1138        // translated to cc1 options (no documentation at all, as it's supposedly unstable).
1139        // Fortunately for us, most (but not all) `-i...` options are passed through cc1.
1140        //
1141        // If you do experience weird compilation errors during bindgen, there's a chance
1142        // that this code has overlooked some edge cases. You can put `.clang_arg("-###")`
1143        // to print the final cc1 options, which would give a lot of information about
1144        // how it got screwed up and help a lot when we fix the issue.
1145        //
1146        // </digression>
1147
1148        let mut args = Vec::new();
1149
1150        // Never include default include directories,
1151        // otherwise `__has_include` will be totally confused.
1152        args.push("-nostdinc".to_owned());
1153
1154        // Add various options for libc++ and glibc.
1155        // Should match what `Compilation.zig` internally does:
1156        //
1157        // https://github.com/ziglang/zig/blob/0.9.0/src/Compilation.zig#L3390-L3427
1158        // https://github.com/ziglang/zig/blob/0.9.1/src/Compilation.zig#L3408-L3445
1159        // https://github.com/ziglang/zig/blob/0.10.0/src/Compilation.zig#L4163-L4211
1160        // https://github.com/ziglang/zig/blob/0.10.1/src/Compilation.zig#L4240-L4288
1161        if raw_target.contains("musl") || raw_target.contains("ohos") {
1162            args.push("-D_LIBCPP_HAS_MUSL_LIBC".to_owned());
1163            // for musl or openharmony
1164            // https://github.com/ziglang/zig/pull/16098
1165            args.push("-D_LARGEFILE64_SOURCE".to_owned());
1166        }
1167        args.extend(
1168            [
1169                "-D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS",
1170                "-D_LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS",
1171                "-D_LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS",
1172                "-D_LIBCPP_PSTL_CPU_BACKEND_SERIAL",
1173                "-D_LIBCPP_ABI_VERSION=1",
1174                "-D_LIBCPP_ABI_NAMESPACE=__1",
1175                "-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST",
1176                // Required by zig 0.15+ libc++ for streambuf and other I/O headers
1177                "-D_LIBCPP_HAS_LOCALIZATION=1",
1178                "-D_LIBCPP_HAS_WIDE_CHARACTERS=1",
1179                "-D_LIBCPP_HAS_UNICODE=1",
1180                "-D_LIBCPP_HAS_THREADS=1",
1181                "-D_LIBCPP_HAS_MONOTONIC_CLOCK",
1182            ]
1183            .into_iter()
1184            .map(ToString::to_string),
1185        );
1186        if let Some(ver) = c_opts.glibc_minor_ver {
1187            // Handled separately because we have no way to infer this without Zig
1188            args.push(format!("-D__GLIBC_MINOR__={ver}"));
1189        }
1190
1191        for (kind, path) in cpp_paths.drain(..cpp_pre_len) {
1192            if kind != Kind::Normal {
1193                // may also be Kind::Framework on macOS
1194                continue;
1195            }
1196            // Ideally this should be `-stdlib++-isystem`, which can be disabled by
1197            // passing `-nostdinc++`, but it is fairly new: https://reviews.llvm.org/D64089
1198            //
1199            // (Also note that `-stdlib++-isystem` is a driver-only option,
1200            // so it will be moved relative to other `-isystem` options against our will.)
1201            args.push("-cxx-isystem".to_owned());
1202            args.push(path);
1203        }
1204
1205        for (kind, path) in c_paths {
1206            match kind {
1207                Kind::Normal => {
1208                    // A normal `-isystem` is preferred over `-cxx-isystem` by cc1...
1209                    args.push("-Xclang".to_owned());
1210                    args.push("-c-isystem".to_owned());
1211                    args.push("-Xclang".to_owned());
1212                    args.push(path.clone());
1213                    args.push("-cxx-isystem".to_owned());
1214                    args.push(path);
1215                }
1216                Kind::Framework => {
1217                    args.push("-iframework".to_owned());
1218                    args.push(path);
1219                }
1220            }
1221        }
1222
1223        for (kind, path) in cpp_paths.drain(cpp_paths.len() - cpp_post_len..) {
1224            assert!(kind == Kind::Normal);
1225            args.push("-cxx-isystem".to_owned());
1226            args.push(path);
1227        }
1228
1229        Ok(args)
1230    }
1231
1232    fn setup_os_deps(
1233        manifest_path: Option<&Path>,
1234        release: bool,
1235        cargo: &cargo_options::CommonOptions,
1236    ) -> Result<()> {
1237        for target in &cargo.target {
1238            if target.contains("apple") {
1239                let target_dir = if let Some(target_dir) = cargo.target_dir.clone() {
1240                    target_dir.join(target)
1241                } else {
1242                    let manifest_path = manifest_path.unwrap_or_else(|| Path::new("Cargo.toml"));
1243                    if !manifest_path.exists() {
1244                        // cargo install doesn't pass a manifest path so `Cargo.toml` in cwd may not exist
1245                        continue;
1246                    }
1247                    let metadata = cargo_metadata::MetadataCommand::new()
1248                        .manifest_path(manifest_path)
1249                        .no_deps()
1250                        .exec()?;
1251                    metadata.target_directory.into_std_path_buf().join(target)
1252                };
1253                let profile = match cargo.profile.as_deref() {
1254                    Some("dev" | "test") => "debug",
1255                    Some("release" | "bench") => "release",
1256                    Some(profile) => profile,
1257                    None => {
1258                        if release {
1259                            "release"
1260                        } else {
1261                            "debug"
1262                        }
1263                    }
1264                };
1265                let deps_dir = target_dir.join(profile).join("deps");
1266                fs::create_dir_all(&deps_dir)?;
1267                if !target_dir.join("CACHEDIR.TAG").is_file() {
1268                    // Create a CACHEDIR.TAG file to exclude target directory from backup
1269                    let _ = write_file(
1270                        &target_dir.join("CACHEDIR.TAG"),
1271                        "Signature: 8a477f597d28d172789f06886806bc55
1272# This file is a cache directory tag created by cargo.
1273# For information about cache directory tags see https://bford.info/cachedir/
1274",
1275                    );
1276                }
1277                write_tbd_files(&deps_dir)?;
1278            } else if target.contains("arm") && target.contains("linux") {
1279                // See https://github.com/ziglang/zig/issues/3287
1280                if let Ok(lib_dir) = Zig::lib_dir() {
1281                    let arm_features_h = lib_dir
1282                        .join("libc")
1283                        .join("glibc")
1284                        .join("sysdeps")
1285                        .join("arm")
1286                        .join("arm-features.h");
1287                    if !arm_features_h.is_file() {
1288                        fs::write(arm_features_h, ARM_FEATURES_H)?;
1289                    }
1290                }
1291            } else if target.contains("windows-gnu") {
1292                if let Ok(lib_dir) = Zig::lib_dir() {
1293                    let lib_common = lib_dir.join("libc").join("mingw").join("lib-common");
1294                    let synchronization_def = lib_common.join("synchronization.def");
1295                    if !synchronization_def.is_file() {
1296                        let api_ms_win_core_synch_l1_2_0_def =
1297                            lib_common.join("api-ms-win-core-synch-l1-2-0.def");
1298                        // Ignore error
1299                        fs::copy(api_ms_win_core_synch_l1_2_0_def, synchronization_def).ok();
1300                    }
1301                }
1302            }
1303        }
1304        Ok(())
1305    }
1306
1307    fn setup_cmake_toolchain(
1308        target: &str,
1309        zig_wrapper: &ZigWrapper,
1310        enable_zig_ar: bool,
1311    ) -> Result<PathBuf> {
1312        let cmake = cache_dir().join("cmake");
1313        fs::create_dir_all(&cmake)?;
1314
1315        let toolchain_file = cmake.join(format!("{target}-toolchain.cmake"));
1316        let triple: Triple = target.parse()?;
1317        let os = triple.operating_system.to_string();
1318        let arch = triple.architecture.to_string();
1319        let (system_name, system_processor) = match (os.as_str(), arch.as_str()) {
1320            ("darwin", "x86_64") => ("Darwin", "x86_64"),
1321            ("darwin", "aarch64") => ("Darwin", "arm64"),
1322            ("linux", arch) => {
1323                let cmake_arch = match arch {
1324                    "powerpc" => "ppc",
1325                    "powerpc64" => "ppc64",
1326                    "powerpc64le" => "ppc64le",
1327                    _ => arch,
1328                };
1329                ("Linux", cmake_arch)
1330            }
1331            ("windows", "x86_64") => ("Windows", "AMD64"),
1332            ("windows", "i686") => ("Windows", "X86"),
1333            ("windows", "aarch64") => ("Windows", "ARM64"),
1334            (os, arch) => (os, arch),
1335        };
1336        let mut content = format!(
1337            r#"
1338set(CMAKE_SYSTEM_NAME {system_name})
1339set(CMAKE_SYSTEM_PROCESSOR {system_processor})
1340set(CMAKE_C_COMPILER {cc})
1341set(CMAKE_CXX_COMPILER {cxx})
1342set(CMAKE_RANLIB {ranlib})
1343set(CMAKE_C_LINKER_DEPFILE_SUPPORTED FALSE)
1344set(CMAKE_CXX_LINKER_DEPFILE_SUPPORTED FALSE)"#,
1345            system_name = system_name,
1346            system_processor = system_processor,
1347            cc = zig_wrapper.cc.to_slash_lossy(),
1348            cxx = zig_wrapper.cxx.to_slash_lossy(),
1349            ranlib = zig_wrapper.ranlib.to_slash_lossy(),
1350        );
1351        if enable_zig_ar {
1352            content.push_str(&format!(
1353                "\nset(CMAKE_AR {})\n",
1354                zig_wrapper.ar.to_slash_lossy()
1355            ));
1356        }
1357        write_file(&toolchain_file, &content)?;
1358        Ok(toolchain_file)
1359    }
1360
1361    #[cfg(target_os = "macos")]
1362    fn macos_sdk_root() -> Option<PathBuf> {
1363        static SDK_ROOT: OnceLock<Option<PathBuf>> = OnceLock::new();
1364
1365        SDK_ROOT
1366            .get_or_init(|| match env::var_os("SDKROOT") {
1367                Some(sdkroot) if !sdkroot.is_empty() => Some(sdkroot.into()),
1368                _ => {
1369                    let output = Command::new("xcrun")
1370                        .args(["--sdk", "macosx", "--show-sdk-path"])
1371                        .output()
1372                        .ok()?;
1373                    if output.status.success() {
1374                        let stdout = String::from_utf8(output.stdout).ok()?;
1375                        let stdout = stdout.trim();
1376                        if !stdout.is_empty() {
1377                            return Some(stdout.into());
1378                        }
1379                    }
1380                    None
1381                }
1382            })
1383            .clone()
1384    }
1385
1386    #[cfg(not(target_os = "macos"))]
1387    fn macos_sdk_root() -> Option<PathBuf> {
1388        match env::var_os("SDKROOT") {
1389            Some(sdkroot) if !sdkroot.is_empty() => Some(sdkroot.into()),
1390            _ => None,
1391        }
1392    }
1393}
1394
1395fn write_file(path: &Path, content: &str) -> Result<(), anyhow::Error> {
1396    let existing_content = fs::read_to_string(path).unwrap_or_default();
1397    if existing_content != content {
1398        fs::write(path, content)?;
1399    }
1400    Ok(())
1401}
1402
1403fn write_tbd_files(deps_dir: &Path) -> Result<(), anyhow::Error> {
1404    write_file(&deps_dir.join("libiconv.tbd"), LIBICONV_TBD)?;
1405    write_file(&deps_dir.join("libcharset.1.tbd"), LIBCHARSET_TBD)?;
1406    write_file(&deps_dir.join("libcharset.tbd"), LIBCHARSET_TBD)?;
1407    Ok(())
1408}
1409
1410fn cache_dir() -> PathBuf {
1411    env::var("CARGO_ZIGBUILD_CACHE_DIR")
1412        .ok()
1413        .map(|s| s.into())
1414        .or_else(dirs::cache_dir)
1415        // If the really is no cache dir, cwd will also do
1416        .unwrap_or_else(|| env::current_dir().expect("Failed to get current dir"))
1417        .join(env!("CARGO_PKG_NAME"))
1418        .join(env!("CARGO_PKG_VERSION"))
1419}
1420
1421#[derive(Debug, Deserialize)]
1422struct ZigEnv {
1423    lib_dir: String,
1424}
1425
1426/// zig wrapper paths
1427#[derive(Debug, Clone)]
1428pub struct ZigWrapper {
1429    pub cc: PathBuf,
1430    pub cxx: PathBuf,
1431    pub ar: PathBuf,
1432    pub ranlib: PathBuf,
1433    pub lib: PathBuf,
1434}
1435
1436#[derive(Debug, Clone, Default, PartialEq)]
1437struct TargetFlags {
1438    pub target_cpu: String,
1439    pub target_feature: String,
1440}
1441
1442impl TargetFlags {
1443    pub fn parse_from_encoded(encoded: &OsStr) -> Result<Self> {
1444        let mut parsed = Self::default();
1445
1446        let f = rustflags::from_encoded(encoded);
1447        for flag in f {
1448            if let rustflags::Flag::Codegen { opt, value } = flag {
1449                let key = opt.replace('-', "_");
1450                match key.as_str() {
1451                    "target_cpu" => {
1452                        if let Some(value) = value {
1453                            parsed.target_cpu = value;
1454                        }
1455                    }
1456                    "target_feature" => {
1457                        // See https://github.com/rust-lang/rust/blob/7e3ba5b8b7556073ab69822cc36b93d6e74cd8c9/compiler/rustc_session/src/options.rs#L1233
1458                        if let Some(value) = value {
1459                            if !parsed.target_feature.is_empty() {
1460                                parsed.target_feature.push(',');
1461                            }
1462                            parsed.target_feature.push_str(&value);
1463                        }
1464                    }
1465                    _ => {}
1466                }
1467            }
1468        }
1469        Ok(parsed)
1470    }
1471}
1472
1473/// Prepare wrapper scripts for `zig cc` and `zig c++` and returns their paths
1474///
1475/// We want to use `zig cc` as linker and c compiler. We want to call `python -m ziglang cc`, but
1476/// cargo only accepts a path to an executable as linker, so we add a wrapper script. We then also
1477/// use the wrapper script to pass arguments and substitute an unsupported argument.
1478///
1479/// We create different files for different args because otherwise cargo might skip recompiling even
1480/// if the linker target changed
1481#[allow(clippy::blocks_in_conditions)]
1482pub fn prepare_zig_linker(target: &str) -> Result<ZigWrapper> {
1483    let (rust_target, abi_suffix) = target.split_once('.').unwrap_or((target, ""));
1484    let abi_suffix = if abi_suffix.is_empty() {
1485        String::new()
1486    } else {
1487        if abi_suffix
1488            .split_once('.')
1489            .filter(|(x, y)| {
1490                !x.is_empty()
1491                    && x.chars().all(|c| c.is_ascii_digit())
1492                    && !y.is_empty()
1493                    && y.chars().all(|c| c.is_ascii_digit())
1494            })
1495            .is_none()
1496        {
1497            bail!("Malformed zig target abi suffix.")
1498        }
1499        format!(".{abi_suffix}")
1500    };
1501    let triple: Triple = rust_target
1502        .parse()
1503        .with_context(|| format!("Unsupported Rust target '{rust_target}'"))?;
1504    let arch = triple.architecture.to_string();
1505    let target_env = match (triple.architecture, triple.environment) {
1506        (Architecture::Mips32(..), Environment::Gnu) => Environment::Gnueabihf,
1507        (Architecture::Powerpc, Environment::Gnu) => Environment::Gnueabihf,
1508        (_, Environment::GnuLlvm) => Environment::Gnu,
1509        (_, environment) => environment,
1510    };
1511    let file_ext = if cfg!(windows) { "bat" } else { "sh" };
1512    let file_target = target.trim_end_matches('.');
1513
1514    let mut cc_args = vec![
1515        // prevent stripping
1516        "-g".to_owned(),
1517        // disable sanitizers
1518        "-fno-sanitize=all".to_owned(),
1519    ];
1520
1521    // TODO: Maybe better to assign mcpu according to:
1522    // rustc --target <target> -Z unstable-options --print target-spec-json
1523    let zig_mcpu_default = match triple.operating_system {
1524        OperatingSystem::Linux => {
1525            match arch.as_str() {
1526                // zig uses _ instead of - in cpu features
1527                "arm" => match target_env {
1528                    Environment::Gnueabi | Environment::Musleabi => "generic+v6+strict_align",
1529                    Environment::Gnueabihf | Environment::Musleabihf => {
1530                        "generic+v6+strict_align+vfp2-d32"
1531                    }
1532                    _ => "",
1533                },
1534                "armv5te" => "generic+soft_float+strict_align",
1535                "armv7" => "generic+v7a+vfp3-d32+thumb2-neon",
1536                arch_str @ ("i586" | "i686") => {
1537                    if arch_str == "i586" {
1538                        "pentium"
1539                    } else {
1540                        "pentium4"
1541                    }
1542                }
1543                "riscv64gc" => "generic_rv64+m+a+f+d+c",
1544                "s390x" => "z10-vector",
1545                _ => "",
1546            }
1547        }
1548        _ => "",
1549    };
1550
1551    // Override mcpu from RUSTFLAGS if provided. The override happens when
1552    // commands like `cargo-zigbuild build` are invoked.
1553    // Currently we only override according to target_cpu.
1554    let zig_mcpu_override = {
1555        let cargo_config = cargo_config2::Config::load()?;
1556        let rust_flags = cargo_config.rustflags(rust_target)?.unwrap_or_default();
1557        let encoded_rust_flags = rust_flags.encode()?;
1558        let target_flags = TargetFlags::parse_from_encoded(OsStr::new(&encoded_rust_flags))?;
1559        // Note: zig uses _ instead of - for target_cpu and target_feature
1560        // target_cpu may be empty string, which means target_cpu is not specified.
1561        target_flags.target_cpu.replace('-', "_")
1562    };
1563
1564    if !zig_mcpu_override.is_empty() {
1565        cc_args.push(format!("-mcpu={zig_mcpu_override}"));
1566    } else if !zig_mcpu_default.is_empty() {
1567        cc_args.push(format!("-mcpu={zig_mcpu_default}"));
1568    }
1569
1570    match triple.operating_system {
1571        OperatingSystem::Linux => {
1572            let zig_arch = match arch.as_str() {
1573                // zig uses _ instead of - in cpu features
1574                "arm" => "arm",
1575                "armv5te" => "arm",
1576                "armv7" => "arm",
1577                "i586" | "i686" => {
1578                    let zig_version = Zig::zig_version()?;
1579                    if zig_version.major == 0 && zig_version.minor >= 11 {
1580                        "x86"
1581                    } else {
1582                        "i386"
1583                    }
1584                }
1585                "riscv64gc" => "riscv64",
1586                "s390x" => "s390x",
1587                _ => arch.as_str(),
1588            };
1589            let mut zig_target_env = target_env.to_string();
1590
1591            let zig_version = Zig::zig_version()?;
1592
1593            // Since Zig 0.15.0, arm-linux-ohos changed to arm-linux-ohoseabi
1594            // We need to follow the change but target_lexicon follow the LLVM target(https://github.com/bytecodealliance/target-lexicon/pull/123).
1595            // So we use string directly.
1596            if zig_version >= semver::Version::new(0, 15, 0)
1597                && arch.as_str() == "armv7"
1598                && target_env == Environment::Ohos
1599            {
1600                zig_target_env = "ohoseabi".to_string();
1601            }
1602
1603            cc_args.push("-target".to_string());
1604            cc_args.push(format!("{zig_arch}-linux-{zig_target_env}{abi_suffix}"));
1605        }
1606        OperatingSystem::MacOSX { .. } | OperatingSystem::Darwin(_) => {
1607            let zig_version = Zig::zig_version()?;
1608            // Zig 0.10.0 switched macOS ABI to none
1609            // see https://github.com/ziglang/zig/pull/11684
1610            if zig_version > semver::Version::new(0, 9, 1) {
1611                cc_args.push("-target".to_string());
1612                cc_args.push(format!("{arch}-macos-none{abi_suffix}"));
1613            } else {
1614                cc_args.push("-target".to_string());
1615                cc_args.push(format!("{arch}-macos-gnu{abi_suffix}"));
1616            }
1617        }
1618        OperatingSystem::Windows => {
1619            let zig_arch = match arch.as_str() {
1620                "i686" => {
1621                    let zig_version = Zig::zig_version()?;
1622                    if zig_version.major == 0 && zig_version.minor >= 11 {
1623                        "x86"
1624                    } else {
1625                        "i386"
1626                    }
1627                }
1628                arch => arch,
1629            };
1630            cc_args.push("-target".to_string());
1631            cc_args.push(format!("{zig_arch}-windows-{target_env}{abi_suffix}"));
1632        }
1633        OperatingSystem::Emscripten => {
1634            cc_args.push("-target".to_string());
1635            cc_args.push(format!("{arch}-emscripten{abi_suffix}"));
1636        }
1637        OperatingSystem::Wasi => {
1638            cc_args.push("-target".to_string());
1639            cc_args.push(format!("{arch}-wasi{abi_suffix}"));
1640        }
1641        OperatingSystem::WasiP1 => {
1642            cc_args.push("-target".to_string());
1643            cc_args.push(format!("{arch}-wasi.0.1.0{abi_suffix}"));
1644        }
1645        OperatingSystem::Freebsd => {
1646            let zig_arch = match arch.as_str() {
1647                "i686" => {
1648                    let zig_version = Zig::zig_version()?;
1649                    if zig_version.major == 0 && zig_version.minor >= 11 {
1650                        "x86"
1651                    } else {
1652                        "i386"
1653                    }
1654                }
1655                arch => arch,
1656            };
1657            cc_args.push("-target".to_string());
1658            cc_args.push(format!("{zig_arch}-freebsd"));
1659        }
1660        OperatingSystem::Unknown => {
1661            if triple.architecture == Architecture::Wasm32
1662                || triple.architecture == Architecture::Wasm64
1663            {
1664                cc_args.push("-target".to_string());
1665                cc_args.push(format!("{arch}-freestanding{abi_suffix}"));
1666            } else {
1667                bail!("unsupported target '{rust_target}'")
1668            }
1669        }
1670        _ => bail!(format!("unsupported target '{rust_target}'")),
1671    };
1672
1673    let zig_linker_dir = cache_dir();
1674    fs::create_dir_all(&zig_linker_dir)?;
1675
1676    if triple.operating_system == OperatingSystem::Linux {
1677        if matches!(
1678            triple.environment,
1679            Environment::Gnu
1680                | Environment::Gnuspe
1681                | Environment::Gnux32
1682                | Environment::Gnueabi
1683                | Environment::Gnuabi64
1684                | Environment::GnuIlp32
1685                | Environment::Gnueabihf
1686        ) {
1687            let glibc_version = if abi_suffix.is_empty() {
1688                (2, 17)
1689            } else {
1690                let mut parts = abi_suffix[1..].split('.');
1691                let major: usize = parts.next().unwrap().parse()?;
1692                let minor: usize = parts.next().unwrap().parse()?;
1693                (major, minor)
1694            };
1695            // See https://github.com/ziglang/zig/issues/9485
1696            if glibc_version < (2, 28) {
1697                use crate::linux::{FCNTL_H, FCNTL_MAP};
1698
1699                let zig_version = Zig::zig_version()?;
1700                if zig_version.major == 0 && zig_version.minor < 11 {
1701                    let fcntl_map = zig_linker_dir.join("fcntl.map");
1702                    let existing_content = fs::read_to_string(&fcntl_map).unwrap_or_default();
1703                    if existing_content != FCNTL_MAP {
1704                        fs::write(&fcntl_map, FCNTL_MAP)?;
1705                    }
1706                    let fcntl_h = zig_linker_dir.join("fcntl.h");
1707                    let existing_content = fs::read_to_string(&fcntl_h).unwrap_or_default();
1708                    if existing_content != FCNTL_H {
1709                        fs::write(&fcntl_h, FCNTL_H)?;
1710                    }
1711
1712                    cc_args.push(format!("-Wl,--version-script={}", fcntl_map.display()));
1713                    cc_args.push("-include".to_string());
1714                    cc_args.push(fcntl_h.display().to_string());
1715                }
1716            }
1717        } else if matches!(
1718            triple.environment,
1719            Environment::Musl
1720                | Environment::Muslabi64
1721                | Environment::Musleabi
1722                | Environment::Musleabihf
1723        ) {
1724            use crate::linux::MUSL_WEAK_SYMBOLS_MAPPING_SCRIPT;
1725
1726            let zig_version = Zig::zig_version()?;
1727            let rustc_version = rustc_version::version_meta()?.semver;
1728
1729            // as zig 0.11.0 is released, its musl has been upgraded to 1.2.4 with break changes
1730            // but rust is still with musl 1.2.3
1731            // we need this workaround before rust 1.72
1732            // https://github.com/ziglang/zig/pull/16098
1733            if (zig_version.major, zig_version.minor) >= (0, 11)
1734                && (rustc_version.major, rustc_version.minor) < (1, 72)
1735            {
1736                let weak_symbols_map = zig_linker_dir.join("musl_weak_symbols_map.ld");
1737                fs::write(&weak_symbols_map, MUSL_WEAK_SYMBOLS_MAPPING_SCRIPT)?;
1738
1739                cc_args.push(format!("-Wl,-T,{}", weak_symbols_map.display()));
1740            }
1741        }
1742    }
1743
1744    // Use platform-specific quoting: shell_words for Unix (single quotes),
1745    // custom quoting for Windows batch files (double quotes)
1746    let cc_args_str = join_args_for_script(&cc_args);
1747    let hash = crc::Crc::<u16>::new(&crc::CRC_16_IBM_SDLC).checksum(cc_args_str.as_bytes());
1748    let zig_cc = zig_linker_dir.join(format!("zigcc-{file_target}-{:x}.{file_ext}", hash));
1749    let zig_cxx = zig_linker_dir.join(format!("zigcxx-{file_target}-{:x}.{file_ext}", hash));
1750    let zig_ranlib = zig_linker_dir.join(format!("zigranlib.{file_ext}"));
1751    let zig_version = Zig::zig_version()?;
1752    write_linker_wrapper(&zig_cc, "cc", &cc_args_str, &zig_version)?;
1753    write_linker_wrapper(&zig_cxx, "c++", &cc_args_str, &zig_version)?;
1754    write_linker_wrapper(&zig_ranlib, "ranlib", "", &zig_version)?;
1755
1756    let exe_ext = if cfg!(windows) { ".exe" } else { "" };
1757    let zig_ar = zig_linker_dir.join(format!("ar{exe_ext}"));
1758    symlink_wrapper(&zig_ar)?;
1759    let zig_lib = zig_linker_dir.join(format!("lib{exe_ext}"));
1760    symlink_wrapper(&zig_lib)?;
1761
1762    // Create dlltool symlinks for Windows GNU targets, but only if no system dlltool exists
1763    // On Windows hosts, rustc looks for "dlltool.exe"
1764    // On non-Windows hosts, rustc looks for architecture-specific names
1765    //
1766    // See https://github.com/rust-lang/rust/blob/a18e6d9d1473d9b25581dd04bef6c7577999631c/compiler/rustc_codegen_ssa/src/back/archive.rs#L275-L309
1767    if matches!(triple.operating_system, OperatingSystem::Windows)
1768        && matches!(triple.environment, Environment::Gnu)
1769    {
1770        // Only create zig dlltool wrapper if no system dlltool is found
1771        // System dlltool (from mingw-w64) handles raw-dylib better than zig's dlltool
1772        if !has_system_dlltool(&triple.architecture) {
1773            let dlltool_name = get_dlltool_name(&triple.architecture);
1774            let zig_dlltool = zig_linker_dir.join(format!("{dlltool_name}{exe_ext}"));
1775            symlink_wrapper(&zig_dlltool)?;
1776        }
1777    }
1778
1779    Ok(ZigWrapper {
1780        cc: zig_cc,
1781        cxx: zig_cxx,
1782        ar: zig_ar,
1783        ranlib: zig_ranlib,
1784        lib: zig_lib,
1785    })
1786}
1787
1788fn symlink_wrapper(target: &Path) -> Result<()> {
1789    let current_exe = if let Ok(exe) = env::var("CARGO_BIN_EXE_cargo-zigbuild") {
1790        PathBuf::from(exe)
1791    } else {
1792        env::current_exe()?
1793    };
1794    #[cfg(windows)]
1795    {
1796        if !target.exists() {
1797            // symlink on Windows requires admin privileges so we use hardlink instead
1798            if std::fs::hard_link(&current_exe, target).is_err() {
1799                // hard_link doesn't support cross-device links so we fallback to copy
1800                std::fs::copy(&current_exe, target)?;
1801            }
1802        }
1803    }
1804
1805    #[cfg(unix)]
1806    {
1807        if !target.exists() {
1808            if fs::read_link(target).is_ok() {
1809                // remove broken symlink
1810                fs::remove_file(target)?;
1811            }
1812            std::os::unix::fs::symlink(current_exe, target)?;
1813        }
1814    }
1815    Ok(())
1816}
1817
1818/// Join arguments for Unix shell script using shell_words (single quotes)
1819#[cfg(target_family = "unix")]
1820fn join_args_for_script<I, S>(args: I) -> String
1821where
1822    I: IntoIterator<Item = S>,
1823    S: AsRef<str>,
1824{
1825    shell_words::join(args)
1826}
1827
1828/// Quote a string for Windows batch file (cmd.exe)
1829///
1830/// - `%` expands even inside quotes, so we escape it as `%%`.
1831/// - We disable delayed expansion in the wrapper script, so `!` should not expand.
1832/// - Internal `"` are escaped by doubling them (`""`).
1833#[cfg(not(target_family = "unix"))]
1834fn quote_for_batch(s: &str) -> String {
1835    let needs_quoting_or_escaping = s.is_empty()
1836        || s.contains(|c: char| {
1837            matches!(
1838                c,
1839                ' ' | '\t' | '"' | '&' | '|' | '<' | '>' | '^' | '%' | '(' | ')' | '!'
1840            )
1841        });
1842
1843    if !needs_quoting_or_escaping {
1844        return s.to_string();
1845    }
1846
1847    let mut out = String::with_capacity(s.len() + 8);
1848    out.push('"');
1849    for c in s.chars() {
1850        match c {
1851            '"' => out.push_str("\"\""),
1852            '%' => out.push_str("%%"),
1853            _ => out.push(c),
1854        }
1855    }
1856    out.push('"');
1857    out
1858}
1859
1860/// Join arguments for Windows batch file using double quotes
1861#[cfg(not(target_family = "unix"))]
1862fn join_args_for_script<I, S>(args: I) -> String
1863where
1864    I: IntoIterator<Item = S>,
1865    S: AsRef<str>,
1866{
1867    args.into_iter()
1868        .map(|s| quote_for_batch(s.as_ref()))
1869        .collect::<Vec<_>>()
1870        .join(" ")
1871}
1872
1873/// Write a zig cc wrapper batch script for unix
1874#[cfg(target_family = "unix")]
1875fn write_linker_wrapper(
1876    path: &Path,
1877    command: &str,
1878    args: &str,
1879    zig_version: &semver::Version,
1880) -> Result<()> {
1881    let mut buf = Vec::<u8>::new();
1882    let current_exe = if let Ok(exe) = env::var("CARGO_BIN_EXE_cargo-zigbuild") {
1883        PathBuf::from(exe)
1884    } else {
1885        env::current_exe()?
1886    };
1887    writeln!(&mut buf, "#!/bin/sh")?;
1888
1889    // Export zig version to avoid spawning `zig version` subprocess
1890    writeln!(
1891        &mut buf,
1892        "export CARGO_ZIGBUILD_ZIG_VERSION={}",
1893        zig_version
1894    )?;
1895
1896    // Pass through SDKROOT if it exists at runtime
1897    writeln!(&mut buf, "if [ -n \"$SDKROOT\" ]; then export SDKROOT; fi")?;
1898
1899    writeln!(
1900        &mut buf,
1901        "exec \"{}\" zig {} -- {} \"$@\"",
1902        current_exe.display(),
1903        command,
1904        args
1905    )?;
1906
1907    // Try not to write the file again if it's already the same.
1908    // This is more friendly for cache systems like ccache, which by default
1909    // uses mtime to determine if a recompilation is needed.
1910    let existing_content = fs::read(path).unwrap_or_default();
1911    if existing_content != buf {
1912        OpenOptions::new()
1913            .create(true)
1914            .write(true)
1915            .truncate(true)
1916            .mode(0o700)
1917            .open(path)?
1918            .write_all(&buf)?;
1919    }
1920    Ok(())
1921}
1922
1923/// Write a zig cc wrapper batch script for windows
1924#[cfg(not(target_family = "unix"))]
1925fn write_linker_wrapper(
1926    path: &Path,
1927    command: &str,
1928    args: &str,
1929    zig_version: &semver::Version,
1930) -> Result<()> {
1931    let mut buf = Vec::<u8>::new();
1932    let current_exe = if let Ok(exe) = env::var("CARGO_BIN_EXE_cargo-zigbuild") {
1933        PathBuf::from(exe)
1934    } else {
1935        env::current_exe()?
1936    };
1937    let current_exe = if is_mingw_shell() {
1938        current_exe.to_slash_lossy().to_string()
1939    } else {
1940        current_exe.display().to_string()
1941    };
1942    writeln!(&mut buf, "@echo off")?;
1943    // Prevent `!VAR!` expansion surprises (delayed expansion) in user-controlled args.
1944    writeln!(&mut buf, "setlocal DisableDelayedExpansion")?;
1945    // Set zig version to avoid spawning `zig version` subprocess
1946    writeln!(&mut buf, "set CARGO_ZIGBUILD_ZIG_VERSION={}", zig_version)?;
1947    writeln!(
1948        &mut buf,
1949        "\"{}\" zig {} -- {} %*",
1950        adjust_canonicalization(current_exe),
1951        command,
1952        args
1953    )?;
1954
1955    let existing_content = fs::read(path).unwrap_or_default();
1956    if existing_content != buf {
1957        fs::write(path, buf)?;
1958    }
1959    Ok(())
1960}
1961
1962pub(crate) fn is_mingw_shell() -> bool {
1963    env::var_os("MSYSTEM").is_some() && env::var_os("SHELL").is_some()
1964}
1965
1966// https://stackoverflow.com/a/50323079/3549270
1967#[cfg(target_os = "windows")]
1968pub fn adjust_canonicalization(p: String) -> String {
1969    const VERBATIM_PREFIX: &str = r#"\\?\"#;
1970    if p.starts_with(VERBATIM_PREFIX) {
1971        p[VERBATIM_PREFIX.len()..].to_string()
1972    } else {
1973        p
1974    }
1975}
1976
1977fn python_path() -> Result<PathBuf> {
1978    let python = env::var("CARGO_ZIGBUILD_PYTHON_PATH").unwrap_or_else(|_| "python3".to_string());
1979    Ok(which::which(python)?)
1980}
1981
1982fn zig_path() -> Result<PathBuf> {
1983    let zig = env::var("CARGO_ZIGBUILD_ZIG_PATH").unwrap_or_else(|_| "zig".to_string());
1984    Ok(which::which(zig)?)
1985}
1986
1987/// Get the dlltool executable name for the given architecture
1988/// On Windows, rustc looks for "dlltool.exe"
1989/// On non-Windows hosts, rustc looks for architecture-specific names
1990fn get_dlltool_name(arch: &Architecture) -> &'static str {
1991    if cfg!(windows) {
1992        "dlltool"
1993    } else {
1994        match arch {
1995            Architecture::X86_64 => "x86_64-w64-mingw32-dlltool",
1996            Architecture::X86_32(_) => "i686-w64-mingw32-dlltool",
1997            Architecture::Aarch64(_) => "aarch64-w64-mingw32-dlltool",
1998            _ => "dlltool",
1999        }
2000    }
2001}
2002
2003/// Check if a dlltool for the given architecture exists in PATH
2004/// Returns true if found, false otherwise
2005fn has_system_dlltool(arch: &Architecture) -> bool {
2006    which::which(get_dlltool_name(arch)).is_ok()
2007}
2008
2009#[cfg(test)]
2010mod tests {
2011    use super::*;
2012
2013    #[test]
2014    fn test_target_flags() {
2015        let cases = [
2016            // Input, TargetCPU, TargetFeature
2017            ("-C target-feature=-crt-static", "", "-crt-static"),
2018            ("-C target-cpu=native", "native", ""),
2019            (
2020                "--deny warnings --codegen target-feature=+crt-static",
2021                "",
2022                "+crt-static",
2023            ),
2024            ("-C target_cpu=skylake-avx512", "skylake-avx512", ""),
2025            ("-Ctarget_cpu=x86-64-v3", "x86-64-v3", ""),
2026            (
2027                "-C target-cpu=native --cfg foo -C target-feature=-avx512bf16,-avx512bitalg",
2028                "native",
2029                "-avx512bf16,-avx512bitalg",
2030            ),
2031            (
2032                "--target x86_64-unknown-linux-gnu --codegen=target-cpu=x --codegen=target-cpu=x86-64",
2033                "x86-64",
2034                "",
2035            ),
2036            (
2037                "-Ctarget-feature=+crt-static -Ctarget-feature=+avx",
2038                "",
2039                "+crt-static,+avx",
2040            ),
2041        ];
2042
2043        for (input, expected_target_cpu, expected_target_feature) in cases.iter() {
2044            let args = cargo_config2::Flags::from_space_separated(input);
2045            let encoded_rust_flags = args.encode().unwrap();
2046            let flags = TargetFlags::parse_from_encoded(OsStr::new(&encoded_rust_flags)).unwrap();
2047            assert_eq!(flags.target_cpu, *expected_target_cpu, "{}", input);
2048            assert_eq!(flags.target_feature, *expected_target_feature, "{}", input);
2049        }
2050    }
2051
2052    #[test]
2053    fn test_join_args_for_script() {
2054        // Test basic arguments without special characters
2055        let args = vec!["-target", "x86_64-linux-gnu"];
2056        let result = join_args_for_script(&args);
2057        assert!(result.contains("-target"));
2058        assert!(result.contains("x86_64-linux-gnu"));
2059    }
2060
2061    #[test]
2062    #[cfg(not(target_family = "unix"))]
2063    fn test_quote_for_batch() {
2064        // Simple argument without special characters - no quoting needed
2065        assert_eq!(quote_for_batch("-target"), "-target");
2066        assert_eq!(quote_for_batch("x86_64-linux-gnu"), "x86_64-linux-gnu");
2067
2068        // Arguments with spaces need quoting
2069        assert_eq!(
2070            quote_for_batch("C:\\Users\\John Doe\\path"),
2071            "\"C:\\Users\\John Doe\\path\""
2072        );
2073
2074        // Empty string needs quoting
2075        assert_eq!(quote_for_batch(""), "\"\"");
2076
2077        // Arguments with special batch characters need quoting
2078        assert_eq!(quote_for_batch("foo&bar"), "\"foo&bar\"");
2079        assert_eq!(quote_for_batch("foo|bar"), "\"foo|bar\"");
2080        assert_eq!(quote_for_batch("foo<bar"), "\"foo<bar\"");
2081        assert_eq!(quote_for_batch("foo>bar"), "\"foo>bar\"");
2082        assert_eq!(quote_for_batch("foo^bar"), "\"foo^bar\"");
2083        assert_eq!(quote_for_batch("foo%bar"), "\"foo%bar\"");
2084
2085        // Internal double quotes are escaped by doubling
2086        assert_eq!(quote_for_batch("foo\"bar"), "\"foo\"\"bar\"");
2087    }
2088
2089    #[test]
2090    #[cfg(not(target_family = "unix"))]
2091    fn test_join_args_for_script_windows() {
2092        // Test with path containing spaces
2093        let args = vec![
2094            "-target",
2095            "x86_64-linux-gnu",
2096            "-L",
2097            "C:\\Users\\John Doe\\path",
2098        ];
2099        let result = join_args_for_script(&args);
2100        // The path with space should be quoted
2101        assert!(result.contains("\"C:\\Users\\John Doe\\path\""));
2102        // Simple args should not be quoted
2103        assert!(result.contains("-target"));
2104        assert!(!result.contains("\"-target\""));
2105    }
2106}