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