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::{Context, Result, anyhow, bail};
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") || x.contains("maccatalyst"))
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                    || x.contains("maccatalyst")
171            })
172            .unwrap_or_default()
173    }
174
175    fn is_ios(&self) -> bool {
176        self.target
177            .as_ref()
178            .map(|x| x.contains("ios") && !x.contains("visionos"))
179            .unwrap_or_default()
180    }
181
182    fn is_tvos(&self) -> bool {
183        self.target
184            .as_ref()
185            .map(|x| x.contains("tvos"))
186            .unwrap_or_default()
187    }
188
189    fn is_watchos(&self) -> bool {
190        self.target
191            .as_ref()
192            .map(|x| x.contains("watchos"))
193            .unwrap_or_default()
194    }
195
196    fn is_visionos(&self) -> bool {
197        self.target
198            .as_ref()
199            .map(|x| x.contains("visionos"))
200            .unwrap_or_default()
201    }
202
203    /// Returns the appropriate Apple CPU for the platform
204    fn apple_cpu(&self) -> &'static str {
205        if self.is_macos() || self.is_darwin() {
206            "apple_m1" // M-series for macOS
207        } else if self.is_visionos() {
208            "apple_m2" // M2 for Apple Vision Pro
209        } else if self.is_watchos() {
210            "apple_s5" // S-series for Apple Watch
211        } else if self.is_ios() || self.is_tvos() {
212            "apple_a14" // A-series for iOS/tvOS (iPhone 12 era - good baseline)
213        } else {
214            "generic"
215        }
216    }
217
218    fn is_freebsd(&self) -> bool {
219        self.target
220            .as_ref()
221            .map(|x| x.contains("freebsd"))
222            .unwrap_or_default()
223    }
224
225    fn is_windows_gnu(&self) -> bool {
226        self.target
227            .as_ref()
228            .map(|x| x.contains("windows-gnu"))
229            .unwrap_or_default()
230    }
231
232    fn is_windows_msvc(&self) -> bool {
233        self.target
234            .as_ref()
235            .map(|x| x.contains("windows-msvc"))
236            .unwrap_or_default()
237    }
238
239    fn is_ohos(&self) -> bool {
240        self.target
241            .as_ref()
242            .map(|x| x.contains("ohos"))
243            .unwrap_or_default()
244    }
245}
246
247impl Zig {
248    /// Execute the underlying zig command
249    pub fn execute(&self) -> Result<()> {
250        match self {
251            Zig::Cc { args } => self.execute_compiler("cc", args),
252            Zig::Cxx { args } => self.execute_compiler("c++", args),
253            Zig::Ar { args } => self.execute_tool("ar", args),
254            Zig::Ranlib { args } => self.execute_compiler("ranlib", args),
255            Zig::Lib { args } => self.execute_compiler("lib", args),
256            Zig::Dlltool { args } => self.execute_dlltool(args),
257        }
258    }
259
260    /// Execute zig dlltool command
261    /// Filter out unsupported options for older zig versions (< 0.12)
262    pub fn execute_dlltool(&self, cmd_args: &[String]) -> Result<()> {
263        let zig_version = Zig::zig_version()?;
264        let needs_filtering = zig_version.major == 0 && zig_version.minor < 12;
265
266        if !needs_filtering {
267            return self.execute_tool("dlltool", cmd_args);
268        }
269
270        // Filter out --no-leading-underscore, --temp-prefix, and -t (short form)
271        // These options are not supported by zig dlltool in versions < 0.12
272        let mut filtered_args = Vec::with_capacity(cmd_args.len());
273        let mut skip_next = false;
274        for arg in cmd_args {
275            if skip_next {
276                skip_next = false;
277                continue;
278            }
279            if arg == "--no-leading-underscore" {
280                continue;
281            }
282            if arg == "--temp-prefix" || arg == "-t" {
283                // Skip this arg and the next one (the value)
284                skip_next = true;
285                continue;
286            }
287            // Handle --temp-prefix=value and -t=value forms
288            if arg.starts_with("--temp-prefix=") || arg.starts_with("-t=") {
289                continue;
290            }
291            filtered_args.push(arg.clone());
292        }
293
294        self.execute_tool("dlltool", &filtered_args)
295    }
296
297    /// Execute zig cc/c++ command
298    pub fn execute_compiler(&self, cmd: &str, cmd_args: &[String]) -> Result<()> {
299        let target = cmd_args
300            .iter()
301            .position(|x| x == "-target")
302            .and_then(|index| cmd_args.get(index + 1));
303        let target_info = TargetInfo::new(target);
304
305        let rustc_ver = match env::var("CARGO_ZIGBUILD_RUSTC_VERSION") {
306            Ok(version) => version.parse()?,
307            Err(_) => rustc_version::version()?,
308        };
309        let zig_version = Zig::zig_version()?;
310
311        let mut new_cmd_args = Vec::with_capacity(cmd_args.len());
312        let mut skip_next_arg = false;
313        let mut seen_target = false;
314        for arg in cmd_args {
315            if skip_next_arg {
316                skip_next_arg = false;
317                continue;
318            }
319            // Our wrapper script already passes the correct -target;
320            // skip any duplicate -target from rustc to avoid conflicts
321            // (e.g. rustc passes arm64 which zig doesn't recognize for some targets)
322            if arg == "-target" {
323                if seen_target {
324                    skip_next_arg = true;
325                    continue;
326                }
327                seen_target = true;
328            }
329            let args = if arg.starts_with('@') && arg.ends_with("linker-arguments") {
330                vec![self.process_linker_response_file(
331                    arg,
332                    &rustc_ver,
333                    &zig_version,
334                    &target_info,
335                )?]
336            } else {
337                match self.filter_linker_arg(arg, &rustc_ver, &zig_version, &target_info) {
338                    FilteredArg::Keep(filtered) => filtered,
339                    FilteredArg::Skip => continue,
340                    FilteredArg::SkipWithNext => {
341                        skip_next_arg = true;
342                        continue;
343                    }
344                }
345            };
346            new_cmd_args.extend(args);
347        }
348
349        if target_info.is_mips32() {
350            // See https://github.com/ziglang/zig/issues/4925#issuecomment-1499823425
351            new_cmd_args.push("-Wl,-z,notext".to_string());
352        }
353
354        if target_info.is_windows_gnu() && (zig_version.major, zig_version.minor) >= (0, 16) {
355            new_cmd_args.push("-lcompiler_rt".to_string());
356        }
357
358        if self.has_undefined_dynamic_lookup(cmd_args) {
359            new_cmd_args.push("-Wl,-undefined=dynamic_lookup".to_string());
360        }
361        if target_info.is_macos() {
362            if self.should_add_libcharset(cmd_args, &zig_version) {
363                new_cmd_args.push("-lcharset".to_string());
364            }
365            self.add_macos_specific_args(&mut new_cmd_args, &zig_version)?;
366        }
367
368        // For Zig >= 0.15 with macOS, set SDKROOT environment variable
369        // if it exists, instead of passing --sysroot
370        let mut command = Self::command()?;
371        if (zig_version.major, zig_version.minor) >= (0, 15)
372            && let Some(sdkroot) = Self::macos_sdk_root()
373        {
374            command.env("SDKROOT", sdkroot);
375        }
376
377        let mut child = command
378            .arg(cmd)
379            .args(new_cmd_args)
380            .spawn()
381            .with_context(|| format!("Failed to run `zig {cmd}`"))?;
382        let status = child.wait().expect("Failed to wait on zig child process");
383        if !status.success() {
384            process::exit(status.code().unwrap_or(1));
385        }
386        Ok(())
387    }
388
389    fn process_linker_response_file(
390        &self,
391        arg: &str,
392        rustc_ver: &rustc_version::Version,
393        zig_version: &semver::Version,
394        target_info: &TargetInfo,
395    ) -> Result<String> {
396        // rustc passes arguments to linker via an @-file when arguments are too long
397        // See https://github.com/rust-lang/rust/issues/41190
398        // and https://github.com/rust-lang/rust/blob/87937d3b6c302dfedfa5c4b94d0a30985d46298d/compiler/rustc_codegen_ssa/src/back/link.rs#L1373-L1382
399        let content_bytes = fs::read(arg.trim_start_matches('@'))?;
400        let content = if target_info.is_windows_msvc() {
401            if content_bytes[0..2] != [255, 254] {
402                bail!(
403                    "linker response file `{}` didn't start with a utf16 BOM",
404                    &arg
405                );
406            }
407            let content_utf16: Vec<u16> = content_bytes[2..]
408                .chunks_exact(2)
409                .map(|a| u16::from_ne_bytes([a[0], a[1]]))
410                .collect();
411            String::from_utf16(&content_utf16).with_context(|| {
412                format!(
413                    "linker response file `{}` didn't contain valid utf16 content",
414                    &arg
415                )
416            })?
417        } else {
418            String::from_utf8(content_bytes).with_context(|| {
419                format!(
420                    "linker response file `{}` didn't contain valid utf8 content",
421                    &arg
422                )
423            })?
424        };
425        let mut link_args: Vec<_> = filter_linker_args(
426            content.split('\n').map(|s| s.to_string()),
427            rustc_ver,
428            zig_version,
429            target_info,
430        );
431        if self.has_undefined_dynamic_lookup(&link_args) {
432            link_args.push("-Wl,-undefined=dynamic_lookup".to_string());
433        }
434        if target_info.is_macos() && self.should_add_libcharset(&link_args, zig_version) {
435            link_args.push("-lcharset".to_string());
436        }
437        if target_info.is_windows_msvc() {
438            let new_content = link_args.join("\n");
439            let mut out = Vec::with_capacity((1 + new_content.len()) * 2);
440            // start the stream with a UTF-16 BOM
441            for c in std::iter::once(0xFEFF).chain(new_content.encode_utf16()) {
442                // encode in little endian
443                out.push(c as u8);
444                out.push((c >> 8) as u8);
445            }
446            fs::write(arg.trim_start_matches('@'), out)?;
447        } else {
448            fs::write(arg.trim_start_matches('@'), link_args.join("\n").as_bytes())?;
449        }
450        Ok(arg.to_string())
451    }
452
453    fn filter_linker_arg(
454        &self,
455        arg: &str,
456        rustc_ver: &rustc_version::Version,
457        zig_version: &semver::Version,
458        target_info: &TargetInfo,
459    ) -> FilteredArg {
460        filter_linker_arg(arg, rustc_ver, zig_version, target_info)
461    }
462}
463
464enum FilteredArg {
465    Keep(Vec<String>),
466    Skip,
467    SkipWithNext,
468}
469
470fn filter_linker_args(
471    args: impl IntoIterator<Item = String>,
472    rustc_ver: &rustc_version::Version,
473    zig_version: &semver::Version,
474    target_info: &TargetInfo,
475) -> Vec<String> {
476    let mut result = Vec::new();
477    let mut skip_next = false;
478    for arg in args {
479        if skip_next {
480            skip_next = false;
481            continue;
482        }
483        match filter_linker_arg(&arg, rustc_ver, zig_version, target_info) {
484            FilteredArg::Keep(filtered) => result.extend(filtered),
485            FilteredArg::Skip => {}
486            FilteredArg::SkipWithNext => {
487                skip_next = true;
488            }
489        }
490    }
491    result
492}
493
494fn filter_linker_arg(
495    arg: &str,
496    rustc_ver: &rustc_version::Version,
497    zig_version: &semver::Version,
498    target_info: &TargetInfo,
499) -> FilteredArg {
500    if arg == "-lgcc_s" {
501        return FilteredArg::Keep(vec!["-lunwind".to_string()]);
502    } else if arg.starts_with("--target=") {
503        return FilteredArg::Skip;
504    } else if arg.starts_with("-e") && arg.len() > 2 && !arg.starts_with("-export") {
505        let entry = &arg[2..];
506        return FilteredArg::Keep(vec![format!("-Wl,--entry={}", entry)]);
507    }
508    if (target_info.is_arm() || target_info.is_windows_gnu())
509        && arg.ends_with(".rlib")
510        && arg.contains("libcompiler_builtins-")
511    {
512        return FilteredArg::Skip;
513    }
514    if target_info.is_windows_gnu() {
515        #[allow(clippy::if_same_then_else)]
516        if arg == "-lgcc_eh"
517            && ((zig_version.major, zig_version.minor) < (0, 14) || target_info.is_i686())
518        {
519            return FilteredArg::Keep(vec!["-lc++".to_string()]);
520        } else if arg.ends_with("rsbegin.o") || arg.ends_with("rsend.o") {
521            if target_info.is_i686() {
522                return FilteredArg::Skip;
523            }
524        } else if arg == "-Wl,-Bdynamic" && (zig_version.major, zig_version.minor) >= (0, 11) {
525            return FilteredArg::Keep(vec!["-Wl,-search_paths_first".to_owned()]);
526        } else if arg == "-lwindows" || arg == "-l:libpthread.a" || arg == "-lgcc" {
527            return FilteredArg::Skip;
528        } else if arg == "-Wl,--disable-auto-image-base"
529            || arg == "-Wl,--dynamicbase"
530            || arg == "-Wl,--large-address-aware"
531            || (arg.starts_with("-Wl,")
532                && (arg.ends_with("/list.def") || arg.ends_with("\\list.def")))
533        {
534            return FilteredArg::Skip;
535        } else if arg == "-lmsvcrt" {
536            return FilteredArg::Skip;
537        }
538    } else if arg == "-Wl,--no-undefined-version"
539        || arg == "-Wl,-znostart-stop-gc"
540        || arg.starts_with("-Wl,-plugin-opt")
541    {
542        return FilteredArg::Skip;
543    }
544    if target_info.is_musl() || target_info.is_ohos() {
545        if (arg.ends_with(".o") && arg.contains("self-contained") && arg.contains("crt"))
546            || arg == "-Wl,-melf_i386"
547        {
548            return FilteredArg::Skip;
549        }
550        if rustc_ver.major == 1
551            && rustc_ver.minor < 59
552            && arg.ends_with(".rlib")
553            && arg.contains("liblibc-")
554        {
555            return FilteredArg::Skip;
556        }
557        if arg == "-lc" {
558            return FilteredArg::Skip;
559        }
560    }
561    // zig cc only supports -Wp,-MD, -Wp,-MMD, and -Wp,-MT;
562    // strip all other -Wp, args (e.g. -Wp,-U_FORTIFY_SOURCE from CMake)
563    // https://github.com/ziglang/zig/blob/0.15.2/src/main.zig#L2798
564    if arg.starts_with("-Wp,")
565        && !arg.starts_with("-Wp,-MD")
566        && !arg.starts_with("-Wp,-MMD")
567        && !arg.starts_with("-Wp,-MT")
568    {
569        return FilteredArg::Skip;
570    }
571    if arg.starts_with("-march=") {
572        if target_info.is_arm() || target_info.is_i386() {
573            return FilteredArg::Skip;
574        } else if target_info.is_riscv64() {
575            return FilteredArg::Keep(vec!["-march=generic_rv64".to_string()]);
576        } else if target_info.is_riscv32() {
577            return FilteredArg::Keep(vec!["-march=generic_rv32".to_string()]);
578        } else if arg.starts_with("-march=armv")
579            && (target_info.is_aarch64() || target_info.is_aarch64_be())
580        {
581            let march_value = arg.strip_prefix("-march=").unwrap();
582            let features = if let Some(pos) = march_value.find('+') {
583                &march_value[pos..]
584            } else {
585                ""
586            };
587            let base_cpu = if target_info.is_apple_platform() {
588                target_info.apple_cpu()
589            } else {
590                "generic"
591            };
592            let mut result = vec![format!("-mcpu={}{}", base_cpu, features)];
593            if features.contains("+crypto") {
594                result.append(&mut vec!["-Xassembler".to_owned(), arg.to_string()]);
595            }
596            return FilteredArg::Keep(result);
597        }
598    }
599    if target_info.is_apple_platform() {
600        if (zig_version.major, zig_version.minor) < (0, 16) {
601            if arg.starts_with("-Wl,-exported_symbols_list,") {
602                return FilteredArg::Skip;
603            }
604            if arg == "-Wl,-exported_symbols_list" {
605                return FilteredArg::SkipWithNext;
606            }
607        }
608        if arg == "-Wl,-dylib" {
609            return FilteredArg::Skip;
610        }
611    }
612    // Handle two-arg form on all platforms (cross-compilation from non-Apple hosts)
613    if (zig_version.major, zig_version.minor) < (0, 16) {
614        if arg == "-Wl,-exported_symbols_list" || arg == "-Wl,--dynamic-list" {
615            return FilteredArg::SkipWithNext;
616        }
617        if arg.starts_with("-Wl,-exported_symbols_list,") || arg.starts_with("-Wl,--dynamic-list,")
618        {
619            return FilteredArg::Skip;
620        }
621    }
622    if target_info.is_freebsd() {
623        let ignored_libs = ["-lkvm", "-lmemstat", "-lprocstat", "-ldevstat"];
624        if ignored_libs.contains(&arg) {
625            return FilteredArg::Skip;
626        }
627    }
628    FilteredArg::Keep(vec![arg.to_string()])
629}
630
631impl Zig {
632    fn has_undefined_dynamic_lookup(&self, args: &[String]) -> bool {
633        let undefined = args
634            .iter()
635            .position(|x| x == "-undefined")
636            .and_then(|i| args.get(i + 1));
637        matches!(undefined, Some(x) if x == "dynamic_lookup")
638    }
639
640    fn should_add_libcharset(&self, args: &[String], zig_version: &semver::Version) -> bool {
641        // See https://github.com/apple-oss-distributions/libiconv/blob/a167071feb7a83a01b27ec8d238590c14eb6faff/xcodeconfig/libiconv.xcconfig
642        if (zig_version.major, zig_version.minor) >= (0, 12) {
643            args.iter().any(|x| x == "-liconv") && !args.iter().any(|x| x == "-lcharset")
644        } else {
645            false
646        }
647    }
648
649    fn add_macos_specific_args(
650        &self,
651        new_cmd_args: &mut Vec<String>,
652        zig_version: &semver::Version,
653    ) -> Result<()> {
654        let sdkroot = Self::macos_sdk_root();
655        if (zig_version.major, zig_version.minor) >= (0, 12) {
656            // Zig 0.12.0+ requires passing `--sysroot`
657            // However, for Zig 0.15+, we should use SDKROOT environment variable instead
658            // to avoid issues with library paths being interpreted relative to sysroot
659            if let Some(ref sdkroot) = sdkroot
660                && (zig_version.major, zig_version.minor) < (0, 15)
661            {
662                new_cmd_args.push(format!("--sysroot={}", sdkroot.display()));
663            }
664            // For Zig >= 0.15, SDKROOT will be set as environment variable
665        }
666        if let Some(ref sdkroot) = sdkroot {
667            if (zig_version.major, zig_version.minor) < (0, 15) {
668                // For zig < 0.15, we need to explicitly add SDK paths with --sysroot
669                new_cmd_args.extend_from_slice(&[
670                    "-isystem".to_string(),
671                    format!("{}", sdkroot.join("usr").join("include").display()),
672                    format!("-L{}", sdkroot.join("usr").join("lib").display()),
673                    format!(
674                        "-F{}",
675                        sdkroot
676                            .join("System")
677                            .join("Library")
678                            .join("Frameworks")
679                            .display()
680                    ),
681                    "-DTARGET_OS_IPHONE=0".to_string(),
682                ]);
683            } else {
684                // For zig >= 0.15 with SDKROOT, we still need to add framework paths
685                // Use -iframework for framework header search
686                new_cmd_args.extend_from_slice(&[
687                    "-isystem".to_string(),
688                    format!("{}", sdkroot.join("usr").join("include").display()),
689                    format!("-L{}", sdkroot.join("usr").join("lib").display()),
690                    format!(
691                        "-F{}",
692                        sdkroot
693                            .join("System")
694                            .join("Library")
695                            .join("Frameworks")
696                            .display()
697                    ),
698                    // Also add the SYSTEM framework search path
699                    "-iframework".to_string(),
700                    format!(
701                        "{}",
702                        sdkroot
703                            .join("System")
704                            .join("Library")
705                            .join("Frameworks")
706                            .display()
707                    ),
708                    "-DTARGET_OS_IPHONE=0".to_string(),
709                ]);
710            }
711        }
712
713        // Add the deps directory that contains `.tbd` files to the library search path
714        let cache_dir = cache_dir();
715        let deps_dir = cache_dir.join("deps");
716        fs::create_dir_all(&deps_dir)?;
717        write_tbd_files(&deps_dir)?;
718        new_cmd_args.push("-L".to_string());
719        new_cmd_args.push(format!("{}", deps_dir.display()));
720        Ok(())
721    }
722
723    /// Execute zig ar/ranlib command
724    pub fn execute_tool(&self, cmd: &str, cmd_args: &[String]) -> Result<()> {
725        let mut child = Self::command()?
726            .arg(cmd)
727            .args(cmd_args)
728            .spawn()
729            .with_context(|| format!("Failed to run `zig {cmd}`"))?;
730        let status = child.wait().expect("Failed to wait on zig child process");
731        if !status.success() {
732            process::exit(status.code().unwrap_or(1));
733        }
734        Ok(())
735    }
736
737    /// Build the zig command line
738    pub fn command() -> Result<Command> {
739        let (zig, zig_args) = Self::find_zig()?;
740        let mut cmd = Command::new(zig);
741        cmd.args(zig_args);
742        Ok(cmd)
743    }
744
745    fn zig_version() -> Result<semver::Version> {
746        static ZIG_VERSION: OnceLock<semver::Version> = OnceLock::new();
747
748        if let Some(version) = ZIG_VERSION.get() {
749            return Ok(version.clone());
750        }
751        // Check for cached version from environment variable first
752        if let Ok(version_str) = env::var("CARGO_ZIGBUILD_ZIG_VERSION")
753            && let Ok(version) = semver::Version::parse(&version_str)
754        {
755            return Ok(ZIG_VERSION.get_or_init(|| version).clone());
756        }
757        let output = Self::command()?.arg("version").output()?;
758        let version_str =
759            str::from_utf8(&output.stdout).context("`zig version` didn't return utf8 output")?;
760        let version = semver::Version::parse(version_str.trim())?;
761        Ok(ZIG_VERSION.get_or_init(|| version).clone())
762    }
763
764    /// Search for `python -m ziglang` first and for `zig` second.
765    pub fn find_zig() -> Result<(PathBuf, Vec<String>)> {
766        static ZIG_PATH: OnceLock<(PathBuf, Vec<String>)> = OnceLock::new();
767
768        if let Some(cached) = ZIG_PATH.get() {
769            return Ok(cached.clone());
770        }
771        let result = Self::find_zig_python()
772            .or_else(|_| Self::find_zig_bin())
773            .context("Failed to find zig")?;
774        Ok(ZIG_PATH.get_or_init(|| result).clone())
775    }
776
777    /// Detect the plain zig binary
778    fn find_zig_bin() -> Result<(PathBuf, Vec<String>)> {
779        let zig_path = zig_path()?;
780        let output = Command::new(&zig_path).arg("version").output()?;
781
782        let version_str = str::from_utf8(&output.stdout).with_context(|| {
783            format!("`{} version` didn't return utf8 output", zig_path.display())
784        })?;
785        Self::validate_zig_version(version_str)?;
786        Ok((zig_path, Vec::new()))
787    }
788
789    /// Detect the Python ziglang package
790    fn find_zig_python() -> Result<(PathBuf, Vec<String>)> {
791        let python_path = python_path()?;
792        let output = Command::new(&python_path)
793            .args(["-m", "ziglang", "version"])
794            .output()?;
795
796        let version_str = str::from_utf8(&output.stdout).with_context(|| {
797            format!(
798                "`{} -m ziglang version` didn't return utf8 output",
799                python_path.display()
800            )
801        })?;
802        Self::validate_zig_version(version_str)?;
803        Ok((python_path, vec!["-m".to_string(), "ziglang".to_string()]))
804    }
805
806    fn validate_zig_version(version: &str) -> Result<()> {
807        let min_ver = semver::Version::new(0, 9, 0);
808        let version = semver::Version::parse(version.trim())?;
809        if version >= min_ver {
810            Ok(())
811        } else {
812            bail!(
813                "zig version {} is too old, need at least {}",
814                version,
815                min_ver
816            )
817        }
818    }
819
820    /// Find zig lib directory
821    pub fn lib_dir() -> Result<PathBuf> {
822        static LIB_DIR: OnceLock<PathBuf> = OnceLock::new();
823
824        if let Some(cached) = LIB_DIR.get() {
825            return Ok(cached.clone());
826        }
827        let (zig, zig_args) = Self::find_zig()?;
828        let zig_version = Self::zig_version()?;
829        let output = Command::new(zig).args(zig_args).arg("env").output()?;
830        let parse_zon_lib_dir = || -> Result<PathBuf> {
831            let output_str =
832                str::from_utf8(&output.stdout).context("`zig env` didn't return utf8 output")?;
833            let lib_dir = output_str
834                .find(".lib_dir")
835                .and_then(|idx| {
836                    let bytes = output_str.as_bytes();
837                    let mut start = idx;
838                    while start < bytes.len() && bytes[start] != b'"' {
839                        start += 1;
840                    }
841                    if start >= bytes.len() {
842                        return None;
843                    }
844                    let mut end = start + 1;
845                    while end < bytes.len() && bytes[end] != b'"' {
846                        end += 1;
847                    }
848                    if end >= bytes.len() {
849                        return None;
850                    }
851                    Some(&output_str[start + 1..end])
852                })
853                .context("Failed to parse lib_dir from `zig env` ZON output")?;
854            Ok(PathBuf::from(lib_dir))
855        };
856        let lib_dir = if zig_version >= semver::Version::new(0, 15, 0) {
857            parse_zon_lib_dir()?
858        } else {
859            serde_json::from_slice::<ZigEnv>(&output.stdout)
860                .map(|zig_env| PathBuf::from(zig_env.lib_dir))
861                .or_else(|_| parse_zon_lib_dir())?
862        };
863        Ok(LIB_DIR.get_or_init(|| lib_dir).clone())
864    }
865
866    fn add_env_if_missing<K, V>(command: &mut Command, name: K, value: V)
867    where
868        K: AsRef<OsStr>,
869        V: AsRef<OsStr>,
870    {
871        let command_env_contains_no_key =
872            |name: &K| !command.get_envs().any(|(key, _)| name.as_ref() == key);
873
874        if command_env_contains_no_key(&name) && env::var_os(&name).is_none() {
875            command.env(name, value);
876        }
877    }
878
879    pub(crate) fn apply_command_env(
880        manifest_path: Option<&Path>,
881        release: bool,
882        cargo: &cargo_options::CommonOptions,
883        cmd: &mut Command,
884        enable_zig_ar: bool,
885    ) -> Result<()> {
886        // setup zig as linker
887        let cargo_config = cargo_config2::Config::load()?;
888        // Use targets from CLI args, or fall back to cargo config's build.target
889        let config_targets;
890        let raw_targets: &[String] = if cargo.target.is_empty() {
891            if let Some(targets) = &cargo_config.build.target {
892                config_targets = targets
893                    .iter()
894                    .map(|t| t.triple().to_string())
895                    .collect::<Vec<_>>();
896                &config_targets
897            } else {
898                &cargo.target
899            }
900        } else {
901            &cargo.target
902        };
903        let rust_targets = raw_targets
904            .iter()
905            .map(|target| target.split_once('.').map(|(t, _)| t).unwrap_or(target))
906            .collect::<Vec<&str>>();
907        let rustc_meta = rustc_version::version_meta()?;
908        Self::add_env_if_missing(
909            cmd,
910            "CARGO_ZIGBUILD_RUSTC_VERSION",
911            rustc_meta.semver.to_string(),
912        );
913        let host_target = &rustc_meta.host;
914        for (parsed_target, raw_target) in rust_targets.iter().zip(raw_targets) {
915            let env_target = parsed_target.replace('-', "_");
916            let zig_wrapper = prepare_zig_linker(raw_target, &cargo_config)?;
917
918            if is_mingw_shell() {
919                let zig_cc = zig_wrapper.cc.to_slash_lossy();
920                let zig_cxx = zig_wrapper.cxx.to_slash_lossy();
921                Self::add_env_if_missing(cmd, format!("CC_{env_target}"), &*zig_cc);
922                Self::add_env_if_missing(cmd, format!("CXX_{env_target}"), &*zig_cxx);
923                if !parsed_target.contains("wasm") {
924                    Self::add_env_if_missing(
925                        cmd,
926                        format!("CARGO_TARGET_{}_LINKER", env_target.to_uppercase()),
927                        &*zig_cc,
928                    );
929                }
930            } else {
931                Self::add_env_if_missing(cmd, format!("CC_{env_target}"), &zig_wrapper.cc);
932                Self::add_env_if_missing(cmd, format!("CXX_{env_target}"), &zig_wrapper.cxx);
933                if !parsed_target.contains("wasm") {
934                    Self::add_env_if_missing(
935                        cmd,
936                        format!("CARGO_TARGET_{}_LINKER", env_target.to_uppercase()),
937                        &zig_wrapper.cc,
938                    );
939                }
940            }
941
942            Self::add_env_if_missing(cmd, format!("RANLIB_{env_target}"), &zig_wrapper.ranlib);
943            // Only setup AR when explicitly asked to
944            // because it need special executable name handling, see src/bin/cargo-zigbuild.rs
945            if enable_zig_ar {
946                if parsed_target.contains("msvc") {
947                    Self::add_env_if_missing(cmd, format!("AR_{env_target}"), &zig_wrapper.lib);
948                } else {
949                    Self::add_env_if_missing(cmd, format!("AR_{env_target}"), &zig_wrapper.ar);
950                }
951            }
952
953            Self::setup_os_deps(manifest_path, release, cargo)?;
954
955            let cmake_toolchain_file_env = format!("CMAKE_TOOLCHAIN_FILE_{env_target}");
956            if env::var_os(&cmake_toolchain_file_env).is_none()
957                && env::var_os(format!("CMAKE_TOOLCHAIN_FILE_{parsed_target}")).is_none()
958                && env::var_os("TARGET_CMAKE_TOOLCHAIN_FILE").is_none()
959                && env::var_os("CMAKE_TOOLCHAIN_FILE").is_none()
960                && let Ok(cmake_toolchain_file) =
961                    Self::setup_cmake_toolchain(parsed_target, &zig_wrapper, enable_zig_ar)
962            {
963                cmd.env(cmake_toolchain_file_env, cmake_toolchain_file);
964            }
965
966            // On Windows, cmake defaults to the Visual Studio generator which ignores
967            // CMAKE_C_COMPILER from the toolchain file. Force Ninja to ensure zig cc
968            // is used for cross-compilation.
969            // See https://github.com/rust-cross/cargo-zigbuild/issues/174
970            if cfg!(target_os = "windows")
971                && env::var_os("CMAKE_GENERATOR").is_none()
972                && which::which("ninja").is_ok()
973            {
974                cmd.env("CMAKE_GENERATOR", "Ninja");
975            }
976
977            if raw_target.contains("windows-gnu") {
978                cmd.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
979                // Add the cache directory to PATH so rustc can find architecture-specific dlltool
980                // (e.g., x86_64-w64-mingw32-dlltool), but only if no system dlltool exists
981                // If system mingw-w64 dlltool exists, prefer it over zig's dlltool
982                let triple: Triple = parsed_target.parse().unwrap_or_else(|_| Triple::unknown());
983                if !has_system_dlltool(&triple.architecture) {
984                    // zig_wrapper.ar lives in the per-exe wrapper dir
985                    let wrapper_dir = zig_wrapper.ar.parent().unwrap();
986                    let existing_path = env::var_os("PATH").unwrap_or_default();
987                    let paths = std::iter::once(wrapper_dir.to_path_buf())
988                        .chain(env::split_paths(&existing_path));
989                    if let Ok(new_path) = env::join_paths(paths) {
990                        cmd.env("PATH", new_path);
991                    }
992                }
993            }
994
995            if raw_target.contains("apple-darwin")
996                && let Some(sdkroot) = Self::macos_sdk_root()
997                && env::var_os("PKG_CONFIG_SYSROOT_DIR").is_none()
998            {
999                // Set PKG_CONFIG_SYSROOT_DIR for pkg-config crate
1000                cmd.env("PKG_CONFIG_SYSROOT_DIR", sdkroot);
1001            }
1002
1003            // Enable unstable `target-applies-to-host` option automatically
1004            // when target is the same as host but may have specified glibc version
1005            if host_target == parsed_target {
1006                if !matches!(rustc_meta.channel, rustc_version::Channel::Nightly) {
1007                    // Hack to use the unstable feature on stable Rust
1008                    // https://github.com/rust-lang/cargo/pull/9753#issuecomment-1022919343
1009                    cmd.env("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS", "nightly");
1010                }
1011                cmd.env("CARGO_UNSTABLE_TARGET_APPLIES_TO_HOST", "true");
1012                cmd.env("CARGO_TARGET_APPLIES_TO_HOST", "false");
1013            }
1014
1015            // Pass options used by zig cc down to bindgen, if possible
1016            let mut options = Self::collect_zig_cc_options(&zig_wrapper, raw_target)
1017                .context("Failed to collect `zig cc` options")?;
1018            if raw_target.contains("apple-darwin") {
1019                // everyone seems to miss `#import <TargetConditionals.h>`...
1020                options.push("-DTARGET_OS_IPHONE=0".to_string());
1021            }
1022            let escaped_options = shell_words::join(options.iter().map(|s| &s[..]));
1023            let bindgen_env = "BINDGEN_EXTRA_CLANG_ARGS";
1024            let fallback_value = env::var(bindgen_env);
1025            for target in [&env_target[..], parsed_target] {
1026                let name = format!("{bindgen_env}_{target}");
1027                if let Ok(mut value) = env::var(&name).or(fallback_value.clone()) {
1028                    if shell_words::split(&value).is_err() {
1029                        // bindgen treats the whole string as a single argument if split fails
1030                        value = shell_words::quote(&value).into_owned();
1031                    }
1032                    if !value.is_empty() {
1033                        value.push(' ');
1034                    }
1035                    value.push_str(&escaped_options);
1036                    unsafe { env::set_var(name, value) };
1037                } else {
1038                    unsafe { env::set_var(name, escaped_options.clone()) };
1039                }
1040            }
1041        }
1042        Ok(())
1043    }
1044
1045    /// Collects compiler options used by `zig cc` for given target.
1046    /// Used for the case where `zig cc` cannot be used but underlying options should be retained,
1047    /// for example, as in bindgen (which requires libclang.so and thus is independent from zig).
1048    fn collect_zig_cc_options(zig_wrapper: &ZigWrapper, raw_target: &str) -> Result<Vec<String>> {
1049        #[derive(Debug, PartialEq, Eq)]
1050        enum Kind {
1051            Normal,
1052            Framework,
1053        }
1054
1055        #[derive(Debug)]
1056        struct PerLanguageOptions {
1057            glibc_minor_ver: Option<u32>,
1058            include_paths: Vec<(Kind, String)>,
1059        }
1060
1061        fn collect_per_language_options(
1062            program: &Path,
1063            ext: &str,
1064            raw_target: &str,
1065        ) -> Result<PerLanguageOptions> {
1066            // We can't use `-x c` or `-x c++` because pre-0.11 Zig doesn't handle them
1067            let empty_file_path = cache_dir().join(format!(".intentionally-empty-file.{ext}"));
1068            if !empty_file_path.exists() {
1069                fs::write(&empty_file_path, "")?;
1070            }
1071
1072            let output = Command::new(program)
1073                .arg("-E")
1074                .arg(&empty_file_path)
1075                .arg("-v")
1076                .output()?;
1077            // Clang always generates UTF-8 regardless of locale, so this is okay.
1078            let stderr = String::from_utf8(output.stderr)?;
1079            if !output.status.success() {
1080                bail!(
1081                    "Failed to run `zig cc -v` with status {}: {}",
1082                    output.status,
1083                    stderr.trim(),
1084                );
1085            }
1086
1087            // Collect some macro definitions from cc1 options. We can't directly use
1088            // them though, as we can't distinguish options added by zig from options
1089            // added by clang driver (e.g. `__GCC_HAVE_DWARF2_CFI_ASM`).
1090            let glibc_minor_ver = if let Some(start) = stderr.find("__GLIBC_MINOR__=") {
1091                let stderr = &stderr[start + 16..];
1092                let end = stderr
1093                    .find(|c: char| !c.is_ascii_digit())
1094                    .unwrap_or(stderr.len());
1095                stderr[..end].parse().ok()
1096            } else {
1097                None
1098            };
1099
1100            let start = stderr
1101                .find("#include <...> search starts here:")
1102                .ok_or_else(|| anyhow!("Failed to parse `zig cc -v` output"))?
1103                + 34;
1104            let end = stderr
1105                .find("End of search list.")
1106                .ok_or_else(|| anyhow!("Failed to parse `zig cc -v` output"))?;
1107
1108            let mut include_paths = Vec::new();
1109            for mut line in stderr[start..end].lines() {
1110                line = line.trim();
1111                let mut kind = Kind::Normal;
1112                if line.ends_with(" (framework directory)") {
1113                    line = line[..line.len() - 22].trim();
1114                    kind = Kind::Framework;
1115                } else if line.ends_with(" (headermap)") {
1116                    bail!("C/C++ search path includes header maps, which are not supported");
1117                }
1118                if !line.is_empty() {
1119                    include_paths.push((kind, line.to_owned()));
1120                }
1121            }
1122
1123            // In openharmony, we should add search header path by default which is useful for bindgen.
1124            if raw_target.contains("ohos") {
1125                let ndk = env::var("OHOS_NDK_HOME").expect("Can't get NDK path");
1126                include_paths.push((Kind::Normal, format!("{}/native/sysroot/usr/include", ndk)));
1127            }
1128
1129            Ok(PerLanguageOptions {
1130                include_paths,
1131                glibc_minor_ver,
1132            })
1133        }
1134
1135        let c_opts = collect_per_language_options(&zig_wrapper.cc, "c", raw_target)?;
1136        let cpp_opts = collect_per_language_options(&zig_wrapper.cxx, "cpp", raw_target)?;
1137
1138        // Ensure that `c_opts` and `cpp_opts` are almost identical in the way we expect.
1139        if c_opts.glibc_minor_ver != cpp_opts.glibc_minor_ver {
1140            bail!(
1141                "`zig cc` gives a different glibc minor version for C ({:?}) and C++ ({:?})",
1142                c_opts.glibc_minor_ver,
1143                cpp_opts.glibc_minor_ver,
1144            );
1145        }
1146        let c_paths = c_opts.include_paths;
1147        let mut cpp_paths = cpp_opts.include_paths;
1148        let cpp_pre_len = cpp_paths
1149            .iter()
1150            .position(|p| {
1151                p == c_paths
1152                    .iter()
1153                    .find(|(kind, _)| *kind == Kind::Normal)
1154                    .unwrap()
1155            })
1156            .unwrap_or_default();
1157        let cpp_post_len = cpp_paths.len()
1158            - cpp_paths
1159                .iter()
1160                .position(|p| p == c_paths.last().unwrap())
1161                .unwrap_or_default()
1162            - 1;
1163
1164        // <digression>
1165        //
1166        // So, why we do need all of these?
1167        //
1168        // Bindgen wouldn't look at our `zig cc` (which doesn't contain `libclang.so` anyway),
1169        // but it does collect include paths from the local clang and feed them to `libclang.so`.
1170        // We want those include paths to come from our `zig cc` instead of the local clang.
1171        // There are three main mechanisms possible:
1172        //
1173        // 1. Replace the local clang with our version.
1174        //
1175        //    Bindgen, internally via clang-sys, recognizes `CLANG_PATH` and `PATH`.
1176        //    They are unfortunately a global namespace and simply setting them may break
1177        //    existing build scripts, so we can't confidently override them.
1178        //
1179        //    Clang-sys can also look at target-prefixed clang if arguments contain `-target`.
1180        //    Unfortunately clang-sys can only recognize `-target xxx`, which very slightly
1181        //    differs from what bindgen would pass (`-target=xxx`), so this is not yet possible.
1182        //
1183        //    It should be also noted that we need to collect not only include paths
1184        //    but macro definitions added by Zig, for example `-D__GLIBC_MINOR__`.
1185        //    Clang-sys can't do this yet, so this option seems less robust than we want.
1186        //
1187        // 2. Set the environment variable `BINDGEN_EXTRA_CLANG_ARGS` and let bindgen to
1188        //    append them to arguments passed to `libclang.so`.
1189        //
1190        //    This unfortunately means that we have the same set of arguments for C and C++.
1191        //    Also we have to support older versions of clang, as old as clang 5 (2017).
1192        //    We do have options like `-c-isystem` (cc1 only) and `-cxx-isystem`,
1193        //    but we need to be aware of other options may affect our added options
1194        //    and this requires a nitty gritty of clang driver and cc1---really annoying.
1195        //
1196        // 3. Fix either bindgen or clang-sys or Zig to ease our jobs.
1197        //
1198        //    This is not the option for now because, even after fixes, we have to support
1199        //    older versions of bindgen or Zig which won't have those fixes anyway.
1200        //    But it seems that minor changes to bindgen can indeed fix lots of issues
1201        //    we face, so we are looking for them in the future.
1202        //
1203        // For this reason, we chose the option 2 and overrode `BINDGEN_EXTRA_CLANG_ARGS`.
1204        // The following therefore assumes some understanding about clang option handling,
1205        // including what the heck is cc1 (see the clang FAQ) and how driver options get
1206        // translated to cc1 options (no documentation at all, as it's supposedly unstable).
1207        // Fortunately for us, most (but not all) `-i...` options are passed through cc1.
1208        //
1209        // If you do experience weird compilation errors during bindgen, there's a chance
1210        // that this code has overlooked some edge cases. You can put `.clang_arg("-###")`
1211        // to print the final cc1 options, which would give a lot of information about
1212        // how it got screwed up and help a lot when we fix the issue.
1213        //
1214        // </digression>
1215
1216        let mut args = Vec::new();
1217
1218        // Never include default include directories,
1219        // otherwise `__has_include` will be totally confused.
1220        args.push("-nostdinc".to_owned());
1221
1222        // Add various options for libc++ and glibc.
1223        // Should match what `Compilation.zig` internally does:
1224        //
1225        // https://github.com/ziglang/zig/blob/0.9.0/src/Compilation.zig#L3390-L3427
1226        // https://github.com/ziglang/zig/blob/0.9.1/src/Compilation.zig#L3408-L3445
1227        // https://github.com/ziglang/zig/blob/0.10.0/src/Compilation.zig#L4163-L4211
1228        // https://github.com/ziglang/zig/blob/0.10.1/src/Compilation.zig#L4240-L4288
1229        if raw_target.contains("musl") || raw_target.contains("ohos") {
1230            args.push("-D_LIBCPP_HAS_MUSL_LIBC".to_owned());
1231            // for musl or openharmony
1232            // https://github.com/ziglang/zig/pull/16098
1233            args.push("-D_LARGEFILE64_SOURCE".to_owned());
1234        }
1235        args.extend(
1236            [
1237                "-D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS",
1238                "-D_LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS",
1239                "-D_LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS",
1240                "-D_LIBCPP_PSTL_CPU_BACKEND_SERIAL",
1241                "-D_LIBCPP_ABI_VERSION=1",
1242                "-D_LIBCPP_ABI_NAMESPACE=__1",
1243                "-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST",
1244                // Required by zig 0.15+ libc++ for streambuf and other I/O headers
1245                "-D_LIBCPP_HAS_LOCALIZATION=1",
1246                "-D_LIBCPP_HAS_WIDE_CHARACTERS=1",
1247                "-D_LIBCPP_HAS_UNICODE=1",
1248                "-D_LIBCPP_HAS_THREADS=1",
1249                "-D_LIBCPP_HAS_MONOTONIC_CLOCK",
1250            ]
1251            .into_iter()
1252            .map(ToString::to_string),
1253        );
1254        if let Some(ver) = c_opts.glibc_minor_ver {
1255            // Handled separately because we have no way to infer this without Zig
1256            args.push(format!("-D__GLIBC_MINOR__={ver}"));
1257        }
1258
1259        for (kind, path) in cpp_paths.drain(..cpp_pre_len) {
1260            if kind != Kind::Normal {
1261                // may also be Kind::Framework on macOS
1262                continue;
1263            }
1264            // Ideally this should be `-stdlib++-isystem`, which can be disabled by
1265            // passing `-nostdinc++`, but it is fairly new: https://reviews.llvm.org/D64089
1266            //
1267            // (Also note that `-stdlib++-isystem` is a driver-only option,
1268            // so it will be moved relative to other `-isystem` options against our will.)
1269            args.push("-cxx-isystem".to_owned());
1270            args.push(path);
1271        }
1272
1273        for (kind, path) in c_paths {
1274            match kind {
1275                Kind::Normal => {
1276                    // A normal `-isystem` is preferred over `-cxx-isystem` by cc1...
1277                    args.push("-Xclang".to_owned());
1278                    args.push("-c-isystem".to_owned());
1279                    args.push("-Xclang".to_owned());
1280                    args.push(path.clone());
1281                    args.push("-cxx-isystem".to_owned());
1282                    args.push(path);
1283                }
1284                Kind::Framework => {
1285                    args.push("-iframework".to_owned());
1286                    args.push(path);
1287                }
1288            }
1289        }
1290
1291        for (kind, path) in cpp_paths.drain(cpp_paths.len() - cpp_post_len..) {
1292            assert!(kind == Kind::Normal);
1293            args.push("-cxx-isystem".to_owned());
1294            args.push(path);
1295        }
1296
1297        Ok(args)
1298    }
1299
1300    fn setup_os_deps(
1301        manifest_path: Option<&Path>,
1302        release: bool,
1303        cargo: &cargo_options::CommonOptions,
1304    ) -> Result<()> {
1305        for target in &cargo.target {
1306            if target.contains("apple") {
1307                let target_dir = if let Some(target_dir) = cargo.target_dir.clone() {
1308                    target_dir.join(target)
1309                } else {
1310                    let manifest_path = manifest_path.unwrap_or_else(|| Path::new("Cargo.toml"));
1311                    if !manifest_path.exists() {
1312                        // cargo install doesn't pass a manifest path so `Cargo.toml` in cwd may not exist
1313                        continue;
1314                    }
1315                    let metadata = cargo_metadata::MetadataCommand::new()
1316                        .manifest_path(manifest_path)
1317                        .no_deps()
1318                        .exec()?;
1319                    metadata.target_directory.into_std_path_buf().join(target)
1320                };
1321                let profile = match cargo.profile.as_deref() {
1322                    Some("dev" | "test") => "debug",
1323                    Some("release" | "bench") => "release",
1324                    Some(profile) => profile,
1325                    None => {
1326                        if release {
1327                            "release"
1328                        } else {
1329                            "debug"
1330                        }
1331                    }
1332                };
1333                let deps_dir = target_dir.join(profile).join("deps");
1334                fs::create_dir_all(&deps_dir)?;
1335                if !target_dir.join("CACHEDIR.TAG").is_file() {
1336                    // Create a CACHEDIR.TAG file to exclude target directory from backup
1337                    let _ = write_file(
1338                        &target_dir.join("CACHEDIR.TAG"),
1339                        "Signature: 8a477f597d28d172789f06886806bc55
1340# This file is a cache directory tag created by cargo.
1341# For information about cache directory tags see https://bford.info/cachedir/
1342",
1343                    );
1344                }
1345                write_tbd_files(&deps_dir)?;
1346            } else if target.contains("arm") && target.contains("linux") {
1347                // See https://github.com/ziglang/zig/issues/3287
1348                if let Ok(lib_dir) = Zig::lib_dir() {
1349                    let arm_features_h = lib_dir
1350                        .join("libc")
1351                        .join("glibc")
1352                        .join("sysdeps")
1353                        .join("arm")
1354                        .join("arm-features.h");
1355                    if !arm_features_h.is_file() {
1356                        fs::write(arm_features_h, ARM_FEATURES_H)?;
1357                    }
1358                }
1359            } else if target.contains("windows-gnu")
1360                && let Ok(lib_dir) = Zig::lib_dir()
1361            {
1362                let lib_common = lib_dir.join("libc").join("mingw").join("lib-common");
1363                let synchronization_def = lib_common.join("synchronization.def");
1364                if !synchronization_def.is_file() {
1365                    let api_ms_win_core_synch_l1_2_0_def =
1366                        lib_common.join("api-ms-win-core-synch-l1-2-0.def");
1367                    // Ignore error
1368                    fs::copy(api_ms_win_core_synch_l1_2_0_def, synchronization_def).ok();
1369                }
1370            }
1371        }
1372        Ok(())
1373    }
1374
1375    fn setup_cmake_toolchain(
1376        target: &str,
1377        zig_wrapper: &ZigWrapper,
1378        enable_zig_ar: bool,
1379    ) -> Result<PathBuf> {
1380        // Place cmake toolchain files alongside the other wrappers in the
1381        // per-exe directory to avoid races between parallel builds.
1382        let wrapper_dir = zig_wrapper.cc.parent().unwrap();
1383        let cmake = wrapper_dir.join("cmake");
1384        fs::create_dir_all(&cmake)?;
1385
1386        let toolchain_file = cmake.join(format!("{target}-toolchain.cmake"));
1387        let triple: Triple = target.parse()?;
1388        let os = triple.operating_system.to_string();
1389        let arch = triple.architecture.to_string();
1390        let (system_name, system_processor) = match (os.as_str(), arch.as_str()) {
1391            ("darwin", "x86_64") => ("Darwin", "x86_64"),
1392            ("darwin", "aarch64") => ("Darwin", "arm64"),
1393            ("linux", arch) => {
1394                let cmake_arch = match arch {
1395                    "powerpc" => "ppc",
1396                    "powerpc64" => "ppc64",
1397                    "powerpc64le" => "ppc64le",
1398                    _ => arch,
1399                };
1400                ("Linux", cmake_arch)
1401            }
1402            ("windows", "x86_64") => ("Windows", "AMD64"),
1403            ("windows", "i686") => ("Windows", "X86"),
1404            ("windows", "aarch64") => ("Windows", "ARM64"),
1405            (os, arch) => (os, arch),
1406        };
1407        let mut content = format!(
1408            r#"
1409set(CMAKE_SYSTEM_NAME {system_name})
1410set(CMAKE_SYSTEM_PROCESSOR {system_processor})
1411set(CMAKE_C_COMPILER {cc})
1412set(CMAKE_CXX_COMPILER {cxx})
1413set(CMAKE_RANLIB {ranlib})
1414set(CMAKE_C_LINKER_DEPFILE_SUPPORTED FALSE)
1415set(CMAKE_CXX_LINKER_DEPFILE_SUPPORTED FALSE)"#,
1416            system_name = system_name,
1417            system_processor = system_processor,
1418            cc = zig_wrapper.cc.to_slash_lossy(),
1419            cxx = zig_wrapper.cxx.to_slash_lossy(),
1420            ranlib = zig_wrapper.ranlib.to_slash_lossy(),
1421        );
1422        if enable_zig_ar {
1423            content.push_str(&format!(
1424                "\nset(CMAKE_AR {})\n",
1425                zig_wrapper.ar.to_slash_lossy()
1426            ));
1427        }
1428        // When cross-compiling to Darwin from a non-macOS host, CMake requires
1429        // install_name_tool and otool which don't exist on Linux/Windows.
1430        // Provide our own install_name_tool implementation via symlink wrapper,
1431        // and a no-op script for otool (not needed for builds) if no system otool exists.
1432        if system_name == "Darwin" && !cfg!(target_os = "macos") {
1433            let exe_ext = if cfg!(windows) { ".exe" } else { "" };
1434            let install_name_tool = wrapper_dir.join(format!("install_name_tool{exe_ext}"));
1435            symlink_wrapper(&install_name_tool)?;
1436            content.push_str(&format!(
1437                "\nset(CMAKE_INSTALL_NAME_TOOL {})",
1438                install_name_tool.to_slash_lossy()
1439            ));
1440
1441            if which::which("otool").is_err() {
1442                let script_ext = if cfg!(windows) { "bat" } else { "sh" };
1443                let otool = cmake.join(format!("otool.{script_ext}"));
1444                write_noop_script(&otool)?;
1445                content.push_str(&format!("\nset(CMAKE_OTOOL {})", otool.to_slash_lossy()));
1446            }
1447        }
1448        // Prevent cmake from searching the host system's include and library paths,
1449        // which can conflict with zig's bundled headers (e.g. __COLD in sys/cdefs.h).
1450        // See https://github.com/rust-cross/cargo-zigbuild/issues/268
1451        content.push_str(
1452            r#"
1453set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
1454set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
1455set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
1456set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)"#,
1457        );
1458        write_file(&toolchain_file, &content)?;
1459        Ok(toolchain_file)
1460    }
1461
1462    #[cfg(target_os = "macos")]
1463    fn macos_sdk_root() -> Option<PathBuf> {
1464        static SDK_ROOT: OnceLock<Option<PathBuf>> = OnceLock::new();
1465
1466        SDK_ROOT
1467            .get_or_init(|| match env::var_os("SDKROOT") {
1468                Some(sdkroot) if !sdkroot.is_empty() => Some(sdkroot.into()),
1469                _ => {
1470                    let output = Command::new("xcrun")
1471                        .args(["--sdk", "macosx", "--show-sdk-path"])
1472                        .output()
1473                        .ok()?;
1474                    if output.status.success() {
1475                        let stdout = String::from_utf8(output.stdout).ok()?;
1476                        let stdout = stdout.trim();
1477                        if !stdout.is_empty() {
1478                            return Some(stdout.into());
1479                        }
1480                    }
1481                    None
1482                }
1483            })
1484            .clone()
1485    }
1486
1487    #[cfg(not(target_os = "macos"))]
1488    fn macos_sdk_root() -> Option<PathBuf> {
1489        match env::var_os("SDKROOT") {
1490            Some(sdkroot) if !sdkroot.is_empty() => Some(sdkroot.into()),
1491            _ => None,
1492        }
1493    }
1494}
1495
1496fn write_file(path: &Path, content: &str) -> Result<(), anyhow::Error> {
1497    let existing_content = fs::read_to_string(path).unwrap_or_default();
1498    if existing_content != content {
1499        fs::write(path, content)?;
1500    }
1501    Ok(())
1502}
1503
1504/// Write a no-op shell/batch script for use as a placeholder tool.
1505/// Used for macOS-specific tools (install_name_tool, otool) when cross-compiling
1506/// to Darwin from non-macOS hosts.
1507#[cfg(target_family = "unix")]
1508fn write_noop_script(path: &Path) -> Result<()> {
1509    let content = "#!/bin/sh\nexit 0\n";
1510    let existing = fs::read_to_string(path).unwrap_or_default();
1511    if existing != content {
1512        OpenOptions::new()
1513            .create(true)
1514            .write(true)
1515            .truncate(true)
1516            .mode(0o700)
1517            .open(path)?
1518            .write_all(content.as_bytes())?;
1519    }
1520    Ok(())
1521}
1522
1523#[cfg(not(target_family = "unix"))]
1524fn write_noop_script(path: &Path) -> Result<()> {
1525    let content = "@echo off\r\nexit /b 0\r\n";
1526    let existing = fs::read_to_string(path).unwrap_or_default();
1527    if existing != content {
1528        fs::write(path, content)?;
1529    }
1530    Ok(())
1531}
1532
1533fn write_tbd_files(deps_dir: &Path) -> Result<(), anyhow::Error> {
1534    write_file(&deps_dir.join("libiconv.tbd"), LIBICONV_TBD)?;
1535    write_file(&deps_dir.join("libcharset.1.tbd"), LIBCHARSET_TBD)?;
1536    write_file(&deps_dir.join("libcharset.tbd"), LIBCHARSET_TBD)?;
1537    Ok(())
1538}
1539
1540fn cache_dir() -> PathBuf {
1541    env::var("CARGO_ZIGBUILD_CACHE_DIR")
1542        .ok()
1543        .map(|s| s.into())
1544        .or_else(dirs::cache_dir)
1545        // If the really is no cache dir, cwd will also do
1546        .unwrap_or_else(|| env::current_dir().expect("Failed to get current dir"))
1547        .join(env!("CARGO_PKG_NAME"))
1548        .join(env!("CARGO_PKG_VERSION"))
1549}
1550
1551#[derive(Debug, Deserialize)]
1552struct ZigEnv {
1553    lib_dir: String,
1554}
1555
1556/// zig wrapper paths
1557#[derive(Debug, Clone)]
1558pub struct ZigWrapper {
1559    pub cc: PathBuf,
1560    pub cxx: PathBuf,
1561    pub ar: PathBuf,
1562    pub ranlib: PathBuf,
1563    pub lib: PathBuf,
1564}
1565
1566#[derive(Debug, Clone, Default, PartialEq)]
1567struct TargetFlags {
1568    pub target_cpu: String,
1569    pub target_feature: String,
1570}
1571
1572impl TargetFlags {
1573    pub fn parse_from_encoded(encoded: &OsStr) -> Result<Self> {
1574        let mut parsed = Self::default();
1575
1576        let f = rustflags::from_encoded(encoded);
1577        for flag in f {
1578            if let rustflags::Flag::Codegen { opt, value } = flag {
1579                let key = opt.replace('-', "_");
1580                match key.as_str() {
1581                    "target_cpu" => {
1582                        if let Some(value) = value {
1583                            parsed.target_cpu = value;
1584                        }
1585                    }
1586                    "target_feature" => {
1587                        // See https://github.com/rust-lang/rust/blob/7e3ba5b8b7556073ab69822cc36b93d6e74cd8c9/compiler/rustc_session/src/options.rs#L1233
1588                        if let Some(value) = value {
1589                            if !parsed.target_feature.is_empty() {
1590                                parsed.target_feature.push(',');
1591                            }
1592                            parsed.target_feature.push_str(&value);
1593                        }
1594                    }
1595                    _ => {}
1596                }
1597            }
1598        }
1599        Ok(parsed)
1600    }
1601}
1602
1603/// Prepare wrapper scripts for `zig cc` and `zig c++` and returns their paths
1604///
1605/// We want to use `zig cc` as linker and c compiler. We want to call `python -m ziglang cc`, but
1606/// cargo only accepts a path to an executable as linker, so we add a wrapper script. We then also
1607/// use the wrapper script to pass arguments and substitute an unsupported argument.
1608///
1609/// We create different files for different args because otherwise cargo might skip recompiling even
1610/// if the linker target changed
1611#[allow(clippy::blocks_in_conditions)]
1612pub fn prepare_zig_linker(
1613    target: &str,
1614    cargo_config: &cargo_config2::Config,
1615) -> Result<ZigWrapper> {
1616    let (rust_target, abi_suffix) = target.split_once('.').unwrap_or((target, ""));
1617    let abi_suffix = if abi_suffix.is_empty() {
1618        String::new()
1619    } else {
1620        if abi_suffix
1621            .split_once('.')
1622            .filter(|(x, y)| {
1623                !x.is_empty()
1624                    && x.chars().all(|c| c.is_ascii_digit())
1625                    && !y.is_empty()
1626                    && y.chars().all(|c| c.is_ascii_digit())
1627            })
1628            .is_none()
1629        {
1630            bail!("Malformed zig target abi suffix.")
1631        }
1632        format!(".{abi_suffix}")
1633    };
1634    let triple: Triple = rust_target
1635        .parse()
1636        .with_context(|| format!("Unsupported Rust target '{rust_target}'"))?;
1637    let arch = triple.architecture.to_string();
1638    let target_env = match (triple.architecture, triple.environment) {
1639        (Architecture::Mips32(..), Environment::Gnu) => Environment::Gnueabihf,
1640        (Architecture::Powerpc, Environment::Gnu) => Environment::Gnueabihf,
1641        (_, Environment::GnuLlvm) => Environment::Gnu,
1642        (_, environment) => environment,
1643    };
1644    let file_ext = if cfg!(windows) { "bat" } else { "sh" };
1645    let file_target = target.trim_end_matches('.');
1646
1647    let mut cc_args = vec![
1648        // prevent stripping
1649        "-g".to_owned(),
1650        // disable sanitizers
1651        "-fno-sanitize=all".to_owned(),
1652    ];
1653
1654    // TODO: Maybe better to assign mcpu according to:
1655    // rustc --target <target> -Z unstable-options --print target-spec-json
1656    let zig_mcpu_default = match triple.operating_system {
1657        OperatingSystem::Linux => {
1658            match arch.as_str() {
1659                // zig uses _ instead of - in cpu features
1660                "arm" => match target_env {
1661                    Environment::Gnueabi | Environment::Musleabi => "generic+v6+strict_align",
1662                    Environment::Gnueabihf | Environment::Musleabihf => {
1663                        "generic+v6+strict_align+vfp2-d32"
1664                    }
1665                    _ => "",
1666                },
1667                "armv5te" => "generic+soft_float+strict_align",
1668                "armv7" => "generic+v7a+vfp3-d32+thumb2-neon",
1669                arch_str @ ("i586" | "i686") => {
1670                    if arch_str == "i586" {
1671                        "pentium"
1672                    } else {
1673                        "pentium4"
1674                    }
1675                }
1676                "riscv64gc" => "generic_rv64+m+a+f+d+c",
1677                "s390x" => "z10-vector",
1678                _ => "",
1679            }
1680        }
1681        _ => "",
1682    };
1683
1684    // Override mcpu from RUSTFLAGS if provided. The override happens when
1685    // commands like `cargo-zigbuild build` are invoked.
1686    // Currently we only override according to target_cpu.
1687    let zig_mcpu_override = {
1688        let rust_flags = cargo_config.rustflags(rust_target)?.unwrap_or_default();
1689        let encoded_rust_flags = rust_flags.encode()?;
1690        let target_flags = TargetFlags::parse_from_encoded(OsStr::new(&encoded_rust_flags))?;
1691        // Note: zig uses _ instead of - for target_cpu and target_feature
1692        // target_cpu may be empty string, which means target_cpu is not specified.
1693        target_flags.target_cpu.replace('-', "_")
1694    };
1695
1696    if !zig_mcpu_override.is_empty() {
1697        cc_args.push(format!("-mcpu={zig_mcpu_override}"));
1698    } else if !zig_mcpu_default.is_empty() {
1699        cc_args.push(format!("-mcpu={zig_mcpu_default}"));
1700    }
1701
1702    match triple.operating_system {
1703        OperatingSystem::Linux => {
1704            let zig_arch = match arch.as_str() {
1705                // zig uses _ instead of - in cpu features
1706                "arm" => "arm",
1707                "armv5te" => "arm",
1708                "armv7" => "arm",
1709                "i586" | "i686" => {
1710                    let zig_version = Zig::zig_version()?;
1711                    if zig_version.major == 0 && zig_version.minor >= 11 {
1712                        "x86"
1713                    } else {
1714                        "i386"
1715                    }
1716                }
1717                "riscv64gc" => "riscv64",
1718                "s390x" => "s390x",
1719                _ => arch.as_str(),
1720            };
1721            let mut zig_target_env = target_env.to_string();
1722
1723            let zig_version = Zig::zig_version()?;
1724
1725            // Since Zig 0.15.0, arm-linux-ohos changed to arm-linux-ohoseabi
1726            // We need to follow the change but target_lexicon follow the LLVM target(https://github.com/bytecodealliance/target-lexicon/pull/123).
1727            // So we use string directly.
1728            if zig_version >= semver::Version::new(0, 15, 0)
1729                && arch.as_str() == "armv7"
1730                && target_env == Environment::Ohos
1731            {
1732                zig_target_env = "ohoseabi".to_string();
1733            }
1734
1735            cc_args.push("-target".to_string());
1736            cc_args.push(format!("{zig_arch}-linux-{zig_target_env}{abi_suffix}"));
1737        }
1738        OperatingSystem::MacOSX { .. } | OperatingSystem::Darwin(_) => {
1739            let zig_version = Zig::zig_version()?;
1740            // Zig 0.10.0 switched macOS ABI to none
1741            // see https://github.com/ziglang/zig/pull/11684
1742            if zig_version > semver::Version::new(0, 9, 1) {
1743                cc_args.push("-target".to_string());
1744                cc_args.push(format!("{arch}-macos-none{abi_suffix}"));
1745            } else {
1746                cc_args.push("-target".to_string());
1747                cc_args.push(format!("{arch}-macos-gnu{abi_suffix}"));
1748            }
1749        }
1750        OperatingSystem::Windows => {
1751            let zig_arch = match arch.as_str() {
1752                "i686" => {
1753                    let zig_version = Zig::zig_version()?;
1754                    if zig_version.major == 0 && zig_version.minor >= 11 {
1755                        "x86"
1756                    } else {
1757                        "i386"
1758                    }
1759                }
1760                arch => arch,
1761            };
1762            cc_args.push("-target".to_string());
1763            cc_args.push(format!("{zig_arch}-windows-{target_env}{abi_suffix}"));
1764        }
1765        OperatingSystem::Emscripten => {
1766            cc_args.push("-target".to_string());
1767            cc_args.push(format!("{arch}-emscripten{abi_suffix}"));
1768        }
1769        OperatingSystem::Wasi => {
1770            cc_args.push("-target".to_string());
1771            cc_args.push(format!("{arch}-wasi{abi_suffix}"));
1772        }
1773        OperatingSystem::WasiP1 => {
1774            cc_args.push("-target".to_string());
1775            cc_args.push(format!("{arch}-wasi.0.1.0{abi_suffix}"));
1776        }
1777        OperatingSystem::IOS(_) if triple.environment == Environment::Macabi => {
1778            // Mac Catalyst (aarch64-apple-ios-macabi / x86_64-apple-ios-macabi)
1779            // maps to zig's maccatalyst target
1780            cc_args.push("-target".to_string());
1781            cc_args.push(format!("{arch}-maccatalyst-none{abi_suffix}"));
1782        }
1783        OperatingSystem::Freebsd => {
1784            let zig_arch = match arch.as_str() {
1785                "i686" => {
1786                    let zig_version = Zig::zig_version()?;
1787                    if zig_version.major == 0 && zig_version.minor >= 11 {
1788                        "x86"
1789                    } else {
1790                        "i386"
1791                    }
1792                }
1793                arch => arch,
1794            };
1795            cc_args.push("-target".to_string());
1796            cc_args.push(format!("{zig_arch}-freebsd"));
1797        }
1798        OperatingSystem::Openbsd => {
1799            cc_args.push("-target".to_string());
1800            cc_args.push(format!("{arch}-openbsd"));
1801        }
1802        OperatingSystem::Unknown => {
1803            if triple.architecture == Architecture::Wasm32
1804                || triple.architecture == Architecture::Wasm64
1805            {
1806                cc_args.push("-target".to_string());
1807                cc_args.push(format!("{arch}-freestanding{abi_suffix}"));
1808            } else {
1809                bail!("unsupported target '{rust_target}'")
1810            }
1811        }
1812        _ => bail!(format!("unsupported target '{rust_target}'")),
1813    };
1814
1815    let zig_linker_dir = cache_dir();
1816    fs::create_dir_all(&zig_linker_dir)?;
1817
1818    if triple.operating_system == OperatingSystem::Linux {
1819        if matches!(
1820            triple.environment,
1821            Environment::Gnu
1822                | Environment::Gnuspe
1823                | Environment::Gnux32
1824                | Environment::Gnueabi
1825                | Environment::Gnuabi64
1826                | Environment::GnuIlp32
1827                | Environment::Gnueabihf
1828        ) {
1829            let glibc_version = if abi_suffix.is_empty() {
1830                (2, 17)
1831            } else {
1832                let mut parts = abi_suffix[1..].split('.');
1833                let major: usize = parts.next().unwrap().parse()?;
1834                let minor: usize = parts.next().unwrap().parse()?;
1835                (major, minor)
1836            };
1837            // See https://github.com/ziglang/zig/issues/9485
1838            if glibc_version < (2, 28) {
1839                use crate::linux::{FCNTL_H, FCNTL_MAP};
1840
1841                let zig_version = Zig::zig_version()?;
1842                if zig_version.major == 0 && zig_version.minor < 11 {
1843                    let fcntl_map = zig_linker_dir.join("fcntl.map");
1844                    let existing_content = fs::read_to_string(&fcntl_map).unwrap_or_default();
1845                    if existing_content != FCNTL_MAP {
1846                        fs::write(&fcntl_map, FCNTL_MAP)?;
1847                    }
1848                    let fcntl_h = zig_linker_dir.join("fcntl.h");
1849                    let existing_content = fs::read_to_string(&fcntl_h).unwrap_or_default();
1850                    if existing_content != FCNTL_H {
1851                        fs::write(&fcntl_h, FCNTL_H)?;
1852                    }
1853
1854                    cc_args.push(format!("-Wl,--version-script={}", fcntl_map.display()));
1855                    cc_args.push("-include".to_string());
1856                    cc_args.push(fcntl_h.display().to_string());
1857                }
1858            }
1859        } else if matches!(
1860            triple.environment,
1861            Environment::Musl
1862                | Environment::Muslabi64
1863                | Environment::Musleabi
1864                | Environment::Musleabihf
1865        ) {
1866            use crate::linux::MUSL_WEAK_SYMBOLS_MAPPING_SCRIPT;
1867
1868            let zig_version = Zig::zig_version()?;
1869            let rustc_version = rustc_version::version_meta()?.semver;
1870
1871            // as zig 0.11.0 is released, its musl has been upgraded to 1.2.4 with break changes
1872            // but rust is still with musl 1.2.3
1873            // we need this workaround before rust 1.72
1874            // https://github.com/ziglang/zig/pull/16098
1875            if (zig_version.major, zig_version.minor) >= (0, 11)
1876                && (rustc_version.major, rustc_version.minor) < (1, 72)
1877            {
1878                let weak_symbols_map = zig_linker_dir.join("musl_weak_symbols_map.ld");
1879                fs::write(&weak_symbols_map, MUSL_WEAK_SYMBOLS_MAPPING_SCRIPT)?;
1880
1881                cc_args.push(format!("-Wl,-T,{}", weak_symbols_map.display()));
1882            }
1883        }
1884    }
1885
1886    // Use platform-specific quoting: shell_words for Unix (single quotes),
1887    // custom quoting for Windows batch files (double quotes)
1888    let cc_args_str = join_args_for_script(&cc_args);
1889
1890    // Put all generated wrappers and symlinks in a per-exe subdirectory so
1891    // that parallel builds driven by different binaries (e.g. multiple maturin
1892    // instances in separate temp venvs) never clobber each other.
1893    // See https://github.com/rust-cross/cargo-zigbuild/issues/318
1894    let current_exe = resolve_current_exe()?;
1895    let exe_hash = crc::Crc::<u16>::new(&crc::CRC_16_IBM_SDLC)
1896        .checksum(current_exe.as_os_str().as_encoded_bytes());
1897    let wrapper_dir = zig_linker_dir
1898        .join("wrappers")
1899        .join(format!("{:x}", exe_hash));
1900    fs::create_dir_all(&wrapper_dir)?;
1901
1902    let hash = crc::Crc::<u16>::new(&crc::CRC_16_IBM_SDLC).checksum(cc_args_str.as_bytes());
1903    let zig_cc = wrapper_dir.join(format!("zigcc-{file_target}-{:x}.{file_ext}", hash));
1904    let zig_cxx = wrapper_dir.join(format!("zigcxx-{file_target}-{:x}.{file_ext}", hash));
1905    let zig_ranlib = wrapper_dir.join(format!("zigranlib.{file_ext}"));
1906    let zig_version = Zig::zig_version()?;
1907    write_linker_wrapper(&zig_cc, "cc", &cc_args_str, &zig_version)?;
1908    write_linker_wrapper(&zig_cxx, "c++", &cc_args_str, &zig_version)?;
1909    write_linker_wrapper(&zig_ranlib, "ranlib", "", &zig_version)?;
1910
1911    let exe_ext = if cfg!(windows) { ".exe" } else { "" };
1912    let zig_ar = wrapper_dir.join(format!("ar{exe_ext}"));
1913    symlink_wrapper(&zig_ar)?;
1914    let zig_lib = wrapper_dir.join(format!("lib{exe_ext}"));
1915    symlink_wrapper(&zig_lib)?;
1916
1917    // Create dlltool symlinks for Windows GNU targets, but only if no system dlltool exists
1918    // On Windows hosts, rustc looks for "dlltool.exe"
1919    // On non-Windows hosts, rustc looks for architecture-specific names
1920    //
1921    // See https://github.com/rust-lang/rust/blob/a18e6d9d1473d9b25581dd04bef6c7577999631c/compiler/rustc_codegen_ssa/src/back/archive.rs#L275-L309
1922    if matches!(triple.operating_system, OperatingSystem::Windows)
1923        && matches!(triple.environment, Environment::Gnu)
1924    {
1925        // Only create zig dlltool wrapper if no system dlltool is found
1926        // System dlltool (from mingw-w64) handles raw-dylib better than zig's dlltool
1927        if !has_system_dlltool(&triple.architecture) {
1928            let dlltool_name = get_dlltool_name(&triple.architecture);
1929            let zig_dlltool = wrapper_dir.join(format!("{dlltool_name}{exe_ext}"));
1930            symlink_wrapper(&zig_dlltool)?;
1931        }
1932    }
1933
1934    Ok(ZigWrapper {
1935        cc: zig_cc,
1936        cxx: zig_cxx,
1937        ar: zig_ar,
1938        ranlib: zig_ranlib,
1939        lib: zig_lib,
1940    })
1941}
1942
1943/// Resolve the current executable path, preferring the test override env var.
1944fn resolve_current_exe() -> Result<PathBuf> {
1945    if let Ok(exe) = env::var("CARGO_BIN_EXE_cargo-zigbuild") {
1946        Ok(PathBuf::from(exe))
1947    } else {
1948        Ok(env::current_exe()?)
1949    }
1950}
1951
1952fn symlink_wrapper(target: &Path) -> Result<()> {
1953    let current_exe = resolve_current_exe()?;
1954    #[cfg(windows)]
1955    {
1956        if !target.exists() {
1957            // symlink on Windows requires admin privileges so we use hardlink instead
1958            if std::fs::hard_link(&current_exe, target).is_err() {
1959                // hard_link doesn't support cross-device links so we fallback to copy
1960                std::fs::copy(&current_exe, target)?;
1961            }
1962        }
1963    }
1964
1965    #[cfg(unix)]
1966    {
1967        if !target.exists() {
1968            if fs::read_link(target).is_ok() {
1969                // remove broken symlink
1970                fs::remove_file(target)?;
1971            }
1972            std::os::unix::fs::symlink(current_exe, target)?;
1973        }
1974    }
1975    Ok(())
1976}
1977
1978/// Join arguments for Unix shell script using shell_words (single quotes)
1979#[cfg(target_family = "unix")]
1980fn join_args_for_script<I, S>(args: I) -> String
1981where
1982    I: IntoIterator<Item = S>,
1983    S: AsRef<str>,
1984{
1985    shell_words::join(args)
1986}
1987
1988/// Quote a string for Windows batch file (cmd.exe)
1989///
1990/// - `%` expands even inside quotes, so we escape it as `%%`.
1991/// - We disable delayed expansion in the wrapper script, so `!` should not expand.
1992/// - Internal `"` are escaped by doubling them (`""`).
1993#[cfg(not(target_family = "unix"))]
1994fn quote_for_batch(s: &str) -> String {
1995    let needs_quoting_or_escaping = s.is_empty()
1996        || s.contains(|c: char| {
1997            matches!(
1998                c,
1999                ' ' | '\t' | '"' | '&' | '|' | '<' | '>' | '^' | '%' | '(' | ')' | '!'
2000            )
2001        });
2002
2003    if !needs_quoting_or_escaping {
2004        return s.to_string();
2005    }
2006
2007    let mut out = String::with_capacity(s.len() + 8);
2008    out.push('"');
2009    for c in s.chars() {
2010        match c {
2011            '"' => out.push_str("\"\""),
2012            '%' => out.push_str("%%"),
2013            _ => out.push(c),
2014        }
2015    }
2016    out.push('"');
2017    out
2018}
2019
2020/// Join arguments for Windows batch file using double quotes
2021#[cfg(not(target_family = "unix"))]
2022fn join_args_for_script<I, S>(args: I) -> String
2023where
2024    I: IntoIterator<Item = S>,
2025    S: AsRef<str>,
2026{
2027    args.into_iter()
2028        .map(|s| quote_for_batch(s.as_ref()))
2029        .collect::<Vec<_>>()
2030        .join(" ")
2031}
2032
2033/// Write a zig cc wrapper batch script for unix
2034#[cfg(target_family = "unix")]
2035fn write_linker_wrapper(
2036    path: &Path,
2037    command: &str,
2038    args: &str,
2039    zig_version: &semver::Version,
2040) -> Result<()> {
2041    let mut buf = Vec::<u8>::new();
2042    let current_exe = resolve_current_exe()?;
2043    writeln!(&mut buf, "#!/bin/sh")?;
2044
2045    // Export zig version to avoid spawning `zig version` subprocess
2046    writeln!(
2047        &mut buf,
2048        "export CARGO_ZIGBUILD_ZIG_VERSION={}",
2049        zig_version
2050    )?;
2051
2052    // Pass through SDKROOT if it exists at runtime
2053    writeln!(&mut buf, "if [ -n \"$SDKROOT\" ]; then export SDKROOT; fi")?;
2054
2055    writeln!(
2056        &mut buf,
2057        "exec \"{}\" zig {} -- {} \"$@\"",
2058        current_exe.display(),
2059        command,
2060        args
2061    )?;
2062
2063    // Try not to write the file again if it's already the same.
2064    // This is more friendly for cache systems like ccache, which by default
2065    // uses mtime to determine if a recompilation is needed.
2066    let existing_content = fs::read(path).unwrap_or_default();
2067    if existing_content != buf {
2068        OpenOptions::new()
2069            .create(true)
2070            .write(true)
2071            .truncate(true)
2072            .mode(0o700)
2073            .open(path)?
2074            .write_all(&buf)?;
2075    }
2076    Ok(())
2077}
2078
2079/// Write a zig cc wrapper batch script for windows
2080#[cfg(not(target_family = "unix"))]
2081fn write_linker_wrapper(
2082    path: &Path,
2083    command: &str,
2084    args: &str,
2085    zig_version: &semver::Version,
2086) -> Result<()> {
2087    let mut buf = Vec::<u8>::new();
2088    let current_exe = resolve_current_exe()?;
2089    let current_exe = if is_mingw_shell() {
2090        current_exe.to_slash_lossy().to_string()
2091    } else {
2092        current_exe.display().to_string()
2093    };
2094    writeln!(&mut buf, "@echo off")?;
2095    // Prevent `!VAR!` expansion surprises (delayed expansion) in user-controlled args.
2096    writeln!(&mut buf, "setlocal DisableDelayedExpansion")?;
2097    // Set zig version to avoid spawning `zig version` subprocess
2098    writeln!(&mut buf, "set CARGO_ZIGBUILD_ZIG_VERSION={}", zig_version)?;
2099    writeln!(
2100        &mut buf,
2101        "\"{}\" zig {} -- {} %*",
2102        adjust_canonicalization(current_exe),
2103        command,
2104        args
2105    )?;
2106
2107    let existing_content = fs::read(path).unwrap_or_default();
2108    if existing_content != buf {
2109        fs::write(path, buf)?;
2110    }
2111    Ok(())
2112}
2113
2114pub(crate) fn is_mingw_shell() -> bool {
2115    env::var_os("MSYSTEM").is_some() && env::var_os("SHELL").is_some()
2116}
2117
2118// https://stackoverflow.com/a/50323079/3549270
2119#[cfg(target_os = "windows")]
2120pub fn adjust_canonicalization(p: String) -> String {
2121    const VERBATIM_PREFIX: &str = r#"\\?\"#;
2122    if p.starts_with(VERBATIM_PREFIX) {
2123        p[VERBATIM_PREFIX.len()..].to_string()
2124    } else {
2125        p
2126    }
2127}
2128
2129fn python_path() -> Result<PathBuf> {
2130    let python = env::var("CARGO_ZIGBUILD_PYTHON_PATH").unwrap_or_else(|_| "python3".to_string());
2131    Ok(which::which(python)?)
2132}
2133
2134fn zig_path() -> Result<PathBuf> {
2135    let zig = env::var("CARGO_ZIGBUILD_ZIG_PATH").unwrap_or_else(|_| "zig".to_string());
2136    Ok(which::which(zig)?)
2137}
2138
2139/// Get the dlltool executable name for the given architecture
2140/// On Windows, rustc looks for "dlltool.exe"
2141/// On non-Windows hosts, rustc looks for architecture-specific names
2142fn get_dlltool_name(arch: &Architecture) -> &'static str {
2143    if cfg!(windows) {
2144        "dlltool"
2145    } else {
2146        match arch {
2147            Architecture::X86_64 => "x86_64-w64-mingw32-dlltool",
2148            Architecture::X86_32(_) => "i686-w64-mingw32-dlltool",
2149            Architecture::Aarch64(_) => "aarch64-w64-mingw32-dlltool",
2150            _ => "dlltool",
2151        }
2152    }
2153}
2154
2155/// Check if a dlltool for the given architecture exists in PATH
2156/// Returns true if found, false otherwise
2157fn has_system_dlltool(arch: &Architecture) -> bool {
2158    which::which(get_dlltool_name(arch)).is_ok()
2159}
2160
2161#[cfg(test)]
2162mod tests {
2163    use super::*;
2164
2165    #[test]
2166    fn test_target_flags() {
2167        let cases = [
2168            // Input, TargetCPU, TargetFeature
2169            ("-C target-feature=-crt-static", "", "-crt-static"),
2170            ("-C target-cpu=native", "native", ""),
2171            (
2172                "--deny warnings --codegen target-feature=+crt-static",
2173                "",
2174                "+crt-static",
2175            ),
2176            ("-C target_cpu=skylake-avx512", "skylake-avx512", ""),
2177            ("-Ctarget_cpu=x86-64-v3", "x86-64-v3", ""),
2178            (
2179                "-C target-cpu=native --cfg foo -C target-feature=-avx512bf16,-avx512bitalg",
2180                "native",
2181                "-avx512bf16,-avx512bitalg",
2182            ),
2183            (
2184                "--target x86_64-unknown-linux-gnu --codegen=target-cpu=x --codegen=target-cpu=x86-64",
2185                "x86-64",
2186                "",
2187            ),
2188            (
2189                "-Ctarget-feature=+crt-static -Ctarget-feature=+avx",
2190                "",
2191                "+crt-static,+avx",
2192            ),
2193        ];
2194
2195        for (input, expected_target_cpu, expected_target_feature) in cases.iter() {
2196            let args = cargo_config2::Flags::from_space_separated(input);
2197            let encoded_rust_flags = args.encode().unwrap();
2198            let flags = TargetFlags::parse_from_encoded(OsStr::new(&encoded_rust_flags)).unwrap();
2199            assert_eq!(flags.target_cpu, *expected_target_cpu, "{}", input);
2200            assert_eq!(flags.target_feature, *expected_target_feature, "{}", input);
2201        }
2202    }
2203
2204    #[test]
2205    fn test_join_args_for_script() {
2206        // Test basic arguments without special characters
2207        let args = vec!["-target", "x86_64-linux-gnu"];
2208        let result = join_args_for_script(&args);
2209        assert!(result.contains("-target"));
2210        assert!(result.contains("x86_64-linux-gnu"));
2211    }
2212
2213    #[test]
2214    #[cfg(not(target_family = "unix"))]
2215    fn test_quote_for_batch() {
2216        // Simple argument without special characters - no quoting needed
2217        assert_eq!(quote_for_batch("-target"), "-target");
2218        assert_eq!(quote_for_batch("x86_64-linux-gnu"), "x86_64-linux-gnu");
2219
2220        // Arguments with spaces need quoting
2221        assert_eq!(
2222            quote_for_batch("C:\\Users\\John Doe\\path"),
2223            "\"C:\\Users\\John Doe\\path\""
2224        );
2225
2226        // Empty string needs quoting
2227        assert_eq!(quote_for_batch(""), "\"\"");
2228
2229        // Arguments with special batch characters need quoting
2230        assert_eq!(quote_for_batch("foo&bar"), "\"foo&bar\"");
2231        assert_eq!(quote_for_batch("foo|bar"), "\"foo|bar\"");
2232        assert_eq!(quote_for_batch("foo<bar"), "\"foo<bar\"");
2233        assert_eq!(quote_for_batch("foo>bar"), "\"foo>bar\"");
2234        assert_eq!(quote_for_batch("foo^bar"), "\"foo^bar\"");
2235        assert_eq!(quote_for_batch("foo%bar"), "\"foo%bar\"");
2236
2237        // Internal double quotes are escaped by doubling
2238        assert_eq!(quote_for_batch("foo\"bar"), "\"foo\"\"bar\"");
2239    }
2240
2241    #[test]
2242    #[cfg(not(target_family = "unix"))]
2243    fn test_join_args_for_script_windows() {
2244        // Test with path containing spaces
2245        let args = vec![
2246            "-target",
2247            "x86_64-linux-gnu",
2248            "-L",
2249            "C:\\Users\\John Doe\\path",
2250        ];
2251        let result = join_args_for_script(&args);
2252        // The path with space should be quoted
2253        assert!(result.contains("\"C:\\Users\\John Doe\\path\""));
2254        // Simple args should not be quoted
2255        assert!(result.contains("-target"));
2256        assert!(!result.contains("\"-target\""));
2257    }
2258
2259    fn make_rustc_ver(major: u64, minor: u64, patch: u64) -> rustc_version::Version {
2260        rustc_version::Version::new(major, minor, patch)
2261    }
2262
2263    fn make_zig_ver(major: u64, minor: u64, patch: u64) -> semver::Version {
2264        semver::Version::new(major, minor, patch)
2265    }
2266
2267    fn run_filter(args: &[&str], target: Option<&str>, zig_ver: (u64, u64)) -> Vec<String> {
2268        let rustc_ver = make_rustc_ver(1, 80, 0);
2269        let zig_version = make_zig_ver(0, zig_ver.0, zig_ver.1);
2270        let target_info = TargetInfo::new(target.map(|s| s.to_string()).as_ref());
2271        filter_linker_args(
2272            args.iter().map(|s| s.to_string()),
2273            &rustc_ver,
2274            &zig_version,
2275            &target_info,
2276        )
2277    }
2278
2279    fn run_filter_one(arg: &str, target: Option<&str>, zig_ver: (u64, u64)) -> Vec<String> {
2280        run_filter(&[arg], target, zig_ver)
2281    }
2282
2283    fn run_filter_one_rustc(
2284        arg: &str,
2285        target: Option<&str>,
2286        zig_ver: (u64, u64),
2287        rustc_minor: u64,
2288    ) -> Vec<String> {
2289        let rustc_ver = make_rustc_ver(1, rustc_minor, 0);
2290        let zig_version = make_zig_ver(0, zig_ver.0, zig_ver.1);
2291        let target_info = TargetInfo::new(target.map(|s| s.to_string()).as_ref());
2292        filter_linker_args(
2293            std::iter::once(arg.to_string()),
2294            &rustc_ver,
2295            &zig_version,
2296            &target_info,
2297        )
2298    }
2299
2300    #[test]
2301    fn test_filter_common_replacements() {
2302        let linux = Some("x86_64-unknown-linux-gnu");
2303        // -lgcc_s -> -lunwind
2304        assert_eq!(run_filter_one("-lgcc_s", linux, (13, 0)), vec!["-lunwind"]);
2305        // --target= stripped (already passed via -target)
2306        assert!(run_filter_one("--target=x86_64-unknown-linux-gnu", linux, (13, 0)).is_empty());
2307        // -e<entry> transformed to -Wl,--entry=<entry>
2308        assert_eq!(
2309            run_filter_one("-emain", linux, (13, 0)),
2310            vec!["-Wl,--entry=main"]
2311        );
2312        // -export-* should NOT be transformed
2313        assert_eq!(
2314            run_filter_one("-export-dynamic", linux, (13, 0)),
2315            vec!["-export-dynamic"]
2316        );
2317    }
2318
2319    #[test]
2320    fn test_filter_compiler_builtins_removed() {
2321        for target in &["armv7-unknown-linux-gnueabihf", "x86_64-pc-windows-gnu"] {
2322            let result = run_filter_one(
2323                "/path/to/libcompiler_builtins-abc123.rlib",
2324                Some(target),
2325                (13, 0),
2326            );
2327            assert!(
2328                result.is_empty(),
2329                "compiler_builtins should be removed for {target}"
2330            );
2331        }
2332    }
2333
2334    #[test]
2335    fn test_filter_windows_gnu_args() {
2336        let gnu = Some("x86_64-pc-windows-gnu");
2337        // Args that should be removed entirely
2338        let removed: &[&str] = &[
2339            "-lwindows",
2340            "-l:libpthread.a",
2341            "-lgcc",
2342            "-Wl,--disable-auto-image-base",
2343            "-Wl,--dynamicbase",
2344            "-Wl,--large-address-aware",
2345            "-Wl,/path/to/list.def",
2346            "-Wl,C:\\path\\to\\list.def",
2347            "-lmsvcrt",
2348        ];
2349        for arg in removed {
2350            let result = run_filter_one(arg, gnu, (13, 0));
2351            assert!(result.is_empty(), "{arg} should be removed for windows-gnu");
2352        }
2353        // Args that get replaced
2354        let replaced: &[(&str, (u64, u64), &str)] = &[
2355            ("-lgcc_eh", (13, 0), "-lc++"),
2356            ("-Wl,-Bdynamic", (13, 0), "-Wl,-search_paths_first"),
2357        ];
2358        for (arg, zig_ver, expected) in replaced {
2359            let result = run_filter_one(arg, gnu, *zig_ver);
2360            assert_eq!(result, vec![*expected], "filter({arg})");
2361        }
2362        // -lgcc_eh kept on zig >= 0.14 for x86_64
2363        let result = run_filter_one("-lgcc_eh", gnu, (14, 0));
2364        assert_eq!(result, vec!["-lgcc_eh"]);
2365    }
2366
2367    #[test]
2368    fn test_filter_windows_gnu_rsbegin() {
2369        // i686: rsbegin.o filtered out
2370        let result = run_filter_one("/path/to/rsbegin.o", Some("i686-pc-windows-gnu"), (13, 0));
2371        assert!(result.is_empty());
2372        // x86_64: rsbegin.o kept
2373        let result = run_filter_one("/path/to/rsbegin.o", Some("x86_64-pc-windows-gnu"), (13, 0));
2374        assert_eq!(result, vec!["/path/to/rsbegin.o"]);
2375    }
2376
2377    #[test]
2378    fn test_filter_unsupported_linker_args() {
2379        let linux = Some("x86_64-unknown-linux-gnu");
2380        let removed: &[&str] = &[
2381            "-Wl,--no-undefined-version",
2382            "-Wl,-znostart-stop-gc",
2383            "-Wl,-plugin-opt=O2",
2384        ];
2385        for arg in removed {
2386            let result = run_filter_one(arg, linux, (13, 0));
2387            assert!(result.is_empty(), "{arg} should be removed");
2388        }
2389    }
2390
2391    #[test]
2392    fn test_filter_wp_args() {
2393        let linux = Some("x86_64-unknown-linux-gnu");
2394        // Unsupported -Wp, args should be removed
2395        for arg in &[
2396            "-Wp,-U_FORTIFY_SOURCE",
2397            "-Wp,-DFOO=1",
2398            "-Wp,-MF,/tmp/t.d",
2399            "-Wp,-MQ,foo",
2400            "-Wp,-MP",
2401        ] {
2402            let result = run_filter_one(arg, linux, (13, 0));
2403            assert!(result.is_empty(), "{arg} should be removed");
2404        }
2405        // Supported -Wp, args should be kept (-MD, -MMD, -MT)
2406        for arg in &["-Wp,-MD,/tmp/test.d", "-Wp,-MMD,/tmp/test.d", "-Wp,-MT,foo"] {
2407            let result = run_filter_one(arg, linux, (13, 0));
2408            assert_eq!(result, vec![*arg], "{arg} should be kept");
2409        }
2410        // bare -U and -D should be kept (zig cc supports them directly)
2411        let result = run_filter_one("-U_FORTIFY_SOURCE", linux, (13, 0));
2412        assert_eq!(result, vec!["-U_FORTIFY_SOURCE"]);
2413        let result = run_filter_one("-DFOO=1", linux, (13, 0));
2414        assert_eq!(result, vec!["-DFOO=1"]);
2415    }
2416
2417    #[test]
2418    fn test_filter_musl_args() {
2419        let musl = Some("x86_64-unknown-linux-musl");
2420        let removed: &[&str] = &["/path/self-contained/crt1.o", "-lc"];
2421        for arg in removed {
2422            let result = run_filter_one(arg, musl, (13, 0));
2423            assert!(result.is_empty(), "{arg} should be removed for musl");
2424        }
2425        // -Wl,-melf_i386 for i686 musl
2426        let result = run_filter_one("-Wl,-melf_i386", Some("i686-unknown-linux-musl"), (13, 0));
2427        assert!(result.is_empty());
2428        // liblibc removed for old rustc (<1.59), kept for new
2429        let result = run_filter_one_rustc("/path/to/liblibc-abc123.rlib", musl, (13, 0), 58);
2430        assert!(result.is_empty());
2431        let result = run_filter_one_rustc("/path/to/liblibc-abc123.rlib", musl, (13, 0), 59);
2432        assert_eq!(result, vec!["/path/to/liblibc-abc123.rlib"]);
2433    }
2434
2435    #[test]
2436    fn test_filter_march_args() {
2437        // (input, target, expected)
2438        let cases: &[(&str, &str, &[&str])] = &[
2439            // arm: removed
2440            ("-march=armv7-a", "armv7-unknown-linux-gnueabihf", &[]),
2441            // riscv64: replaced
2442            (
2443                "-march=rv64gc",
2444                "riscv64gc-unknown-linux-gnu",
2445                &["-march=generic_rv64"],
2446            ),
2447            // riscv32: replaced
2448            (
2449                "-march=rv32imac",
2450                "riscv32imac-unknown-none-elf",
2451                &["-march=generic_rv32"],
2452            ),
2453            // aarch64 armv: converted to -mcpu=generic
2454            (
2455                "-march=armv8.4-a",
2456                "aarch64-unknown-linux-gnu",
2457                &["-mcpu=generic"],
2458            ),
2459            // aarch64 armv with crypto: adds -Xassembler
2460            (
2461                "-march=armv8.4-a+crypto",
2462                "aarch64-unknown-linux-gnu",
2463                &[
2464                    "-mcpu=generic+crypto",
2465                    "-Xassembler",
2466                    "-march=armv8.4-a+crypto",
2467                ],
2468            ),
2469            // apple aarch64: uses apple cpu name
2470            (
2471                "-march=armv8.4-a",
2472                "aarch64-apple-darwin",
2473                &["-mcpu=apple_m1"],
2474            ),
2475        ];
2476        for (input, target, expected) in cases {
2477            let result = run_filter_one(input, Some(target), (13, 0));
2478            assert_eq!(&result, expected, "filter({input}, {target})");
2479        }
2480    }
2481
2482    #[test]
2483    fn test_filter_apple_args() {
2484        let darwin = Some("aarch64-apple-darwin");
2485        let result = run_filter_one("-Wl,-dylib", darwin, (13, 0));
2486        assert!(result.is_empty());
2487    }
2488
2489    #[test]
2490    fn test_filter_freebsd_libs_removed() {
2491        for lib in &["-lkvm", "-lmemstat", "-lprocstat", "-ldevstat"] {
2492            let result = run_filter_one(lib, Some("x86_64-unknown-freebsd"), (13, 0));
2493            assert!(result.is_empty(), "{lib} should be removed for freebsd");
2494        }
2495    }
2496
2497    #[test]
2498    fn test_filter_exported_symbols_list_two_arg_apple() {
2499        let result = run_filter(
2500            &[
2501                "-arch",
2502                "arm64",
2503                "-Wl,-exported_symbols_list",
2504                "-Wl,/tmp/rustcXXX/list",
2505                "-o",
2506                "output.dylib",
2507            ],
2508            Some("aarch64-apple-darwin"),
2509            (13, 0),
2510        );
2511        assert_eq!(result, vec!["-arch", "arm64", "-o", "output.dylib"]);
2512    }
2513
2514    #[test]
2515    fn test_filter_exported_symbols_list_two_arg_cross_platform() {
2516        let result = run_filter(
2517            &[
2518                "-arch",
2519                "arm64",
2520                "-Wl,-exported_symbols_list",
2521                "-Wl,C:\\Users\\RUNNER~1\\AppData\\Local\\Temp\\rustcXXX\\list",
2522                "-o",
2523                "output.dylib",
2524            ],
2525            None,
2526            (13, 0),
2527        );
2528        assert_eq!(result, vec!["-arch", "arm64", "-o", "output.dylib"]);
2529    }
2530
2531    #[test]
2532    fn test_filter_exported_symbols_list_single_arg_comma() {
2533        let result = run_filter(
2534            &[
2535                "-Wl,-exported_symbols_list,/tmp/rustcXXX/list",
2536                "-o",
2537                "output.dylib",
2538            ],
2539            Some("aarch64-apple-darwin"),
2540            (13, 0),
2541        );
2542        assert_eq!(result, vec!["-o", "output.dylib"]);
2543    }
2544
2545    #[test]
2546    fn test_filter_exported_symbols_list_not_filtered_zig_016() {
2547        let result = run_filter(
2548            &[
2549                "-Wl,-exported_symbols_list",
2550                "-Wl,/tmp/rustcXXX/list",
2551                "-o",
2552                "output.dylib",
2553            ],
2554            Some("aarch64-apple-darwin"),
2555            (16, 0),
2556        );
2557        assert_eq!(
2558            result,
2559            vec![
2560                "-Wl,-exported_symbols_list",
2561                "-Wl,/tmp/rustcXXX/list",
2562                "-o",
2563                "output.dylib"
2564            ]
2565        );
2566    }
2567
2568    #[test]
2569    fn test_filter_dynamic_list_two_arg() {
2570        let result = run_filter(
2571            &[
2572                "-Wl,--dynamic-list",
2573                "-Wl,/tmp/rustcXXX/list",
2574                "-o",
2575                "output.so",
2576            ],
2577            Some("x86_64-unknown-linux-gnu"),
2578            (13, 0),
2579        );
2580        assert_eq!(result, vec!["-o", "output.so"]);
2581    }
2582
2583    #[test]
2584    fn test_filter_dynamic_list_single_arg_comma() {
2585        let result = run_filter(
2586            &["-Wl,--dynamic-list,/tmp/rustcXXX/list", "-o", "output.so"],
2587            Some("x86_64-unknown-linux-gnu"),
2588            (13, 0),
2589        );
2590        assert_eq!(result, vec!["-o", "output.so"]);
2591    }
2592
2593    #[test]
2594    fn test_filter_preserves_normal_args() {
2595        let result = run_filter(
2596            &["-arch", "arm64", "-lSystem", "-lc", "-o", "output"],
2597            Some("aarch64-apple-darwin"),
2598            (13, 0),
2599        );
2600        assert_eq!(
2601            result,
2602            vec!["-arch", "arm64", "-lSystem", "-lc", "-o", "output"]
2603        );
2604    }
2605
2606    #[test]
2607    fn test_filter_skip_next_at_end_of_args() {
2608        let result = run_filter(
2609            &["-o", "output", "-Wl,-exported_symbols_list"],
2610            Some("aarch64-apple-darwin"),
2611            (13, 0),
2612        );
2613        assert_eq!(result, vec!["-o", "output"]);
2614    }
2615}