Skip to main content

cargo_zigbuild/
zig.rs

1use std::env;
2use std::ffi::OsStr;
3#[cfg(target_family = "unix")]
4use std::fs::OpenOptions;
5use std::io::Write;
6#[cfg(target_family = "unix")]
7use std::os::unix::fs::OpenOptionsExt;
8use std::path::{Path, PathBuf};
9use std::process::{self, Command};
10use std::str;
11use std::sync::OnceLock;
12
13use anyhow::{anyhow, bail, Context, Result};
14use fs_err as fs;
15use path_slash::PathBufExt;
16use serde::Deserialize;
17use target_lexicon::{Architecture, Environment, OperatingSystem, Triple};
18
19use crate::linux::ARM_FEATURES_H;
20use crate::macos::{LIBCHARSET_TBD, LIBICONV_TBD};
21
22/// Zig linker wrapper
23#[derive(Clone, Debug, clap::Subcommand)]
24pub enum Zig {
25    /// `zig cc` wrapper
26    #[command(name = "cc")]
27    Cc {
28        /// `zig cc` arguments
29        #[arg(num_args = 1.., trailing_var_arg = true)]
30        args: Vec<String>,
31    },
32    /// `zig c++` wrapper
33    #[command(name = "c++")]
34    Cxx {
35        /// `zig c++` arguments
36        #[arg(num_args = 1.., trailing_var_arg = true)]
37        args: Vec<String>,
38    },
39    /// `zig ar` wrapper
40    #[command(name = "ar")]
41    Ar {
42        /// `zig ar` arguments
43        #[arg(num_args = 1.., trailing_var_arg = true)]
44        args: Vec<String>,
45    },
46    /// `zig ranlib` wrapper
47    #[command(name = "ranlib")]
48    Ranlib {
49        /// `zig ranlib` arguments
50        #[arg(num_args = 1.., trailing_var_arg = true)]
51        args: Vec<String>,
52    },
53    /// `zig lib` wrapper
54    #[command(name = "lib")]
55    Lib {
56        /// `zig lib` arguments
57        #[arg(num_args = 1.., trailing_var_arg = true)]
58        args: Vec<String>,
59    },
60    /// `zig dlltool` wrapper
61    #[command(name = "dlltool")]
62    Dlltool {
63        /// `zig dlltool` arguments
64        #[arg(num_args = 1.., trailing_var_arg = true)]
65        args: Vec<String>,
66    },
67}
68
69struct TargetInfo {
70    target: Option<String>,
71}
72
73impl TargetInfo {
74    fn new(target: Option<&String>) -> Self {
75        Self {
76            target: target.cloned(),
77        }
78    }
79
80    // Architecture helpers
81    fn is_arm(&self) -> bool {
82        self.target
83            .as_ref()
84            .map(|x| x.starts_with("arm"))
85            .unwrap_or_default()
86    }
87
88    fn is_aarch64(&self) -> bool {
89        self.target
90            .as_ref()
91            .map(|x| x.starts_with("aarch64"))
92            .unwrap_or_default()
93    }
94
95    fn is_aarch64_be(&self) -> bool {
96        self.target
97            .as_ref()
98            .map(|x| x.starts_with("aarch64_be"))
99            .unwrap_or_default()
100    }
101
102    fn is_i386(&self) -> bool {
103        self.target
104            .as_ref()
105            .map(|x| x.starts_with("i386"))
106            .unwrap_or_default()
107    }
108
109    fn is_i686(&self) -> bool {
110        self.target
111            .as_ref()
112            .map(|x| x.starts_with("i686") || x.starts_with("x86-"))
113            .unwrap_or_default()
114    }
115
116    fn is_riscv64(&self) -> bool {
117        self.target
118            .as_ref()
119            .map(|x| x.starts_with("riscv64"))
120            .unwrap_or_default()
121    }
122
123    fn is_riscv32(&self) -> bool {
124        self.target
125            .as_ref()
126            .map(|x| x.starts_with("riscv32"))
127            .unwrap_or_default()
128    }
129
130    fn is_mips32(&self) -> bool {
131        self.target
132            .as_ref()
133            .map(|x| x.starts_with("mips") && !x.starts_with("mips64"))
134            .unwrap_or_default()
135    }
136
137    // libc helpers
138    fn is_musl(&self) -> bool {
139        self.target
140            .as_ref()
141            .map(|x| x.contains("musl"))
142            .unwrap_or_default()
143    }
144
145    // Platform helpers
146    fn is_macos(&self) -> bool {
147        self.target
148            .as_ref()
149            .map(|x| x.contains("macos"))
150            .unwrap_or_default()
151    }
152
153    fn is_darwin(&self) -> bool {
154        self.target
155            .as_ref()
156            .map(|x| x.contains("darwin"))
157            .unwrap_or_default()
158    }
159
160    fn is_apple_platform(&self) -> bool {
161        self.target
162            .as_ref()
163            .map(|x| {
164                x.contains("macos")
165                    || x.contains("darwin")
166                    || x.contains("ios")
167                    || x.contains("tvos")
168                    || x.contains("watchos")
169                    || x.contains("visionos")
170            })
171            .unwrap_or_default()
172    }
173
174    fn is_ios(&self) -> bool {
175        self.target
176            .as_ref()
177            .map(|x| x.contains("ios") && !x.contains("visionos"))
178            .unwrap_or_default()
179    }
180
181    fn is_tvos(&self) -> bool {
182        self.target
183            .as_ref()
184            .map(|x| x.contains("tvos"))
185            .unwrap_or_default()
186    }
187
188    fn is_watchos(&self) -> bool {
189        self.target
190            .as_ref()
191            .map(|x| x.contains("watchos"))
192            .unwrap_or_default()
193    }
194
195    fn is_visionos(&self) -> bool {
196        self.target
197            .as_ref()
198            .map(|x| x.contains("visionos"))
199            .unwrap_or_default()
200    }
201
202    /// Returns the appropriate Apple CPU for the platform
203    fn apple_cpu(&self) -> &'static str {
204        if self.is_macos() || self.is_darwin() {
205            "apple_m1" // M-series for macOS
206        } else if self.is_visionos() {
207            "apple_m2" // M2 for Apple Vision Pro
208        } else if self.is_watchos() {
209            "apple_s5" // S-series for Apple Watch
210        } else if self.is_ios() || self.is_tvos() {
211            "apple_a14" // A-series for iOS/tvOS (iPhone 12 era - good baseline)
212        } else {
213            "generic"
214        }
215    }
216
217    fn is_freebsd(&self) -> bool {
218        self.target
219            .as_ref()
220            .map(|x| x.contains("freebsd"))
221            .unwrap_or_default()
222    }
223
224    fn is_windows_gnu(&self) -> bool {
225        self.target
226            .as_ref()
227            .map(|x| x.contains("windows-gnu"))
228            .unwrap_or_default()
229    }
230
231    fn is_windows_msvc(&self) -> bool {
232        self.target
233            .as_ref()
234            .map(|x| x.contains("windows-msvc"))
235            .unwrap_or_default()
236    }
237
238    fn is_ohos(&self) -> bool {
239        self.target
240            .as_ref()
241            .map(|x| x.contains("ohos"))
242            .unwrap_or_default()
243    }
244}
245
246impl Zig {
247    /// Execute the underlying zig command
248    pub fn execute(&self) -> Result<()> {
249        match self {
250            Zig::Cc { args } => self.execute_compiler("cc", args),
251            Zig::Cxx { args } => self.execute_compiler("c++", args),
252            Zig::Ar { args } => self.execute_tool("ar", args),
253            Zig::Ranlib { args } => self.execute_compiler("ranlib", args),
254            Zig::Lib { args } => self.execute_compiler("lib", args),
255            Zig::Dlltool { args } => self.execute_dlltool(args),
256        }
257    }
258
259    /// Execute zig dlltool command
260    /// Filter out unsupported options for older zig versions (< 0.12)
261    pub fn execute_dlltool(&self, cmd_args: &[String]) -> Result<()> {
262        let zig_version = Zig::zig_version()?;
263        let needs_filtering = zig_version.major == 0 && zig_version.minor < 12;
264
265        if !needs_filtering {
266            return self.execute_tool("dlltool", cmd_args);
267        }
268
269        // Filter out --no-leading-underscore, --temp-prefix, and -t (short form)
270        // These options are not supported by zig dlltool in versions < 0.12
271        let mut filtered_args = Vec::with_capacity(cmd_args.len());
272        let mut skip_next = false;
273        for arg in cmd_args {
274            if skip_next {
275                skip_next = false;
276                continue;
277            }
278            if arg == "--no-leading-underscore" {
279                continue;
280            }
281            if arg == "--temp-prefix" || arg == "-t" {
282                // Skip this arg and the next one (the value)
283                skip_next = true;
284                continue;
285            }
286            // Handle --temp-prefix=value and -t=value forms
287            if arg.starts_with("--temp-prefix=") || arg.starts_with("-t=") {
288                continue;
289            }
290            filtered_args.push(arg.clone());
291        }
292
293        self.execute_tool("dlltool", &filtered_args)
294    }
295
296    /// Execute zig cc/c++ command
297    pub fn execute_compiler(&self, cmd: &str, cmd_args: &[String]) -> Result<()> {
298        let target = cmd_args
299            .iter()
300            .position(|x| x == "-target")
301            .and_then(|index| cmd_args.get(index + 1));
302        let target_info = TargetInfo::new(target);
303
304        let rustc_ver = match env::var("CARGO_ZIGBUILD_RUSTC_VERSION") {
305            Ok(version) => version.parse()?,
306            Err(_) => rustc_version::version()?,
307        };
308        let zig_version = Zig::zig_version()?;
309
310        let mut new_cmd_args = Vec::with_capacity(cmd_args.len());
311        let mut skip_next_arg = false;
312        for arg in cmd_args {
313            if skip_next_arg {
314                skip_next_arg = false;
315                continue;
316            }
317            let args = if arg.starts_with('@') && arg.ends_with("linker-arguments") {
318                vec![self.process_linker_response_file(
319                    arg,
320                    &rustc_ver,
321                    &zig_version,
322                    &target_info,
323                )?]
324            } else {
325                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            if let Some(sdkroot) = Self::macos_sdk_root() {
357                command.env("SDKROOT", sdkroot);
358            }
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                if (zig_version.major, zig_version.minor) < (0, 15) {
635                    new_cmd_args.push(format!("--sysroot={}", sdkroot.display()));
636                }
637                // For Zig >= 0.15, SDKROOT will be set as environment variable
638            }
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            if let Ok(version) = semver::Version::parse(&version_str) {
728                return Ok(ZIG_VERSION.get_or_init(|| version).clone());
729            }
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 rust_targets = cargo
862            .target
863            .iter()
864            .map(|target| target.split_once('.').map(|(t, _)| t).unwrap_or(target))
865            .collect::<Vec<&str>>();
866        let rustc_meta = rustc_version::version_meta()?;
867        Self::add_env_if_missing(
868            cmd,
869            "CARGO_ZIGBUILD_RUSTC_VERSION",
870            rustc_meta.semver.to_string(),
871        );
872        let host_target = &rustc_meta.host;
873        for (parsed_target, raw_target) in rust_targets.iter().zip(&cargo.target) {
874            let env_target = parsed_target.replace('-', "_");
875            let zig_wrapper = prepare_zig_linker(raw_target)?;
876
877            if is_mingw_shell() {
878                let zig_cc = zig_wrapper.cc.to_slash_lossy();
879                let zig_cxx = zig_wrapper.cxx.to_slash_lossy();
880                Self::add_env_if_missing(cmd, format!("CC_{env_target}"), &*zig_cc);
881                Self::add_env_if_missing(cmd, format!("CXX_{env_target}"), &*zig_cxx);
882                if !parsed_target.contains("wasm") {
883                    Self::add_env_if_missing(
884                        cmd,
885                        format!("CARGO_TARGET_{}_LINKER", env_target.to_uppercase()),
886                        &*zig_cc,
887                    );
888                }
889            } else {
890                Self::add_env_if_missing(cmd, format!("CC_{env_target}"), &zig_wrapper.cc);
891                Self::add_env_if_missing(cmd, format!("CXX_{env_target}"), &zig_wrapper.cxx);
892                if !parsed_target.contains("wasm") {
893                    Self::add_env_if_missing(
894                        cmd,
895                        format!("CARGO_TARGET_{}_LINKER", env_target.to_uppercase()),
896                        &zig_wrapper.cc,
897                    );
898                }
899            }
900
901            Self::add_env_if_missing(cmd, format!("RANLIB_{env_target}"), &zig_wrapper.ranlib);
902            // Only setup AR when explicitly asked to
903            // because it need special executable name handling, see src/bin/cargo-zigbuild.rs
904            if enable_zig_ar {
905                if parsed_target.contains("msvc") {
906                    Self::add_env_if_missing(cmd, format!("AR_{env_target}"), &zig_wrapper.lib);
907                } else {
908                    Self::add_env_if_missing(cmd, format!("AR_{env_target}"), &zig_wrapper.ar);
909                }
910            }
911
912            Self::setup_os_deps(manifest_path, release, cargo)?;
913
914            let cmake_toolchain_file_env = format!("CMAKE_TOOLCHAIN_FILE_{env_target}");
915            if env::var_os(&cmake_toolchain_file_env).is_none()
916                && env::var_os(format!("CMAKE_TOOLCHAIN_FILE_{parsed_target}")).is_none()
917                && env::var_os("TARGET_CMAKE_TOOLCHAIN_FILE").is_none()
918                && env::var_os("CMAKE_TOOLCHAIN_FILE").is_none()
919            {
920                if let Ok(cmake_toolchain_file) =
921                    Self::setup_cmake_toolchain(parsed_target, &zig_wrapper, enable_zig_ar)
922                {
923                    cmd.env(cmake_toolchain_file_env, cmake_toolchain_file);
924                }
925            }
926
927            if raw_target.contains("windows-gnu") {
928                cmd.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
929                // Add the cache directory to PATH so rustc can find architecture-specific dlltool
930                // (e.g., x86_64-w64-mingw32-dlltool), but only if no system dlltool exists
931                // If system mingw-w64 dlltool exists, prefer it over zig's dlltool
932                let triple: Triple = parsed_target.parse().unwrap_or_else(|_| Triple::unknown());
933                if !has_system_dlltool(&triple.architecture) {
934                    let cache_dir = cache_dir();
935                    let existing_path = env::var_os("PATH").unwrap_or_default();
936                    let paths = std::iter::once(cache_dir).chain(env::split_paths(&existing_path));
937                    if let Ok(new_path) = env::join_paths(paths) {
938                        cmd.env("PATH", new_path);
939                    }
940                }
941            }
942
943            if raw_target.contains("apple-darwin") {
944                if let Some(sdkroot) = Self::macos_sdk_root() {
945                    if env::var_os("PKG_CONFIG_SYSROOT_DIR").is_none() {
946                        // Set PKG_CONFIG_SYSROOT_DIR for pkg-config crate
947                        cmd.env("PKG_CONFIG_SYSROOT_DIR", sdkroot);
948                    }
949                }
950            }
951
952            // Enable unstable `target-applies-to-host` option automatically
953            // when target is the same as host but may have specified glibc version
954            if host_target == parsed_target {
955                if !matches!(rustc_meta.channel, rustc_version::Channel::Nightly) {
956                    // Hack to use the unstable feature on stable Rust
957                    // https://github.com/rust-lang/cargo/pull/9753#issuecomment-1022919343
958                    cmd.env("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS", "nightly");
959                }
960                cmd.env("CARGO_UNSTABLE_TARGET_APPLIES_TO_HOST", "true");
961                cmd.env("CARGO_TARGET_APPLIES_TO_HOST", "false");
962            }
963
964            // Pass options used by zig cc down to bindgen, if possible
965            let mut options = Self::collect_zig_cc_options(&zig_wrapper, raw_target)
966                .context("Failed to collect `zig cc` options")?;
967            if raw_target.contains("apple-darwin") {
968                // everyone seems to miss `#import <TargetConditionals.h>`...
969                options.push("-DTARGET_OS_IPHONE=0".to_string());
970            }
971            let escaped_options = shell_words::join(options.iter().map(|s| &s[..]));
972            let bindgen_env = "BINDGEN_EXTRA_CLANG_ARGS";
973            let fallback_value = env::var(bindgen_env);
974            for target in [&env_target[..], parsed_target] {
975                let name = format!("{bindgen_env}_{target}");
976                if let Ok(mut value) = env::var(&name).or(fallback_value.clone()) {
977                    if shell_words::split(&value).is_err() {
978                        // bindgen treats the whole string as a single argument if split fails
979                        value = shell_words::quote(&value).into_owned();
980                    }
981                    if !value.is_empty() {
982                        value.push(' ');
983                    }
984                    value.push_str(&escaped_options);
985                    unsafe { env::set_var(name, value) };
986                } else {
987                    unsafe { env::set_var(name, escaped_options.clone()) };
988                }
989            }
990        }
991        Ok(())
992    }
993
994    /// Collects compiler options used by `zig cc` for given target.
995    /// Used for the case where `zig cc` cannot be used but underlying options should be retained,
996    /// for example, as in bindgen (which requires libclang.so and thus is independent from zig).
997    fn collect_zig_cc_options(zig_wrapper: &ZigWrapper, raw_target: &str) -> Result<Vec<String>> {
998        #[derive(Debug, PartialEq, Eq)]
999        enum Kind {
1000            Normal,
1001            Framework,
1002        }
1003
1004        #[derive(Debug)]
1005        struct PerLanguageOptions {
1006            glibc_minor_ver: Option<u32>,
1007            include_paths: Vec<(Kind, String)>,
1008        }
1009
1010        fn collect_per_language_options(
1011            program: &Path,
1012            ext: &str,
1013            raw_target: &str,
1014        ) -> Result<PerLanguageOptions> {
1015            // We can't use `-x c` or `-x c++` because pre-0.11 Zig doesn't handle them
1016            let empty_file_path = cache_dir().join(format!(".intentionally-empty-file.{ext}"));
1017            if !empty_file_path.exists() {
1018                fs::write(&empty_file_path, "")?;
1019            }
1020
1021            let output = Command::new(program)
1022                .arg("-E")
1023                .arg(&empty_file_path)
1024                .arg("-v")
1025                .output()?;
1026            // Clang always generates UTF-8 regardless of locale, so this is okay.
1027            let stderr = String::from_utf8(output.stderr)?;
1028            if !output.status.success() {
1029                bail!(
1030                    "Failed to run `zig cc -v` with status {}: {}",
1031                    output.status,
1032                    stderr.trim(),
1033                );
1034            }
1035
1036            // Collect some macro definitions from cc1 options. We can't directly use
1037            // them though, as we can't distinguish options added by zig from options
1038            // added by clang driver (e.g. `__GCC_HAVE_DWARF2_CFI_ASM`).
1039            let glibc_minor_ver = if let Some(start) = stderr.find("__GLIBC_MINOR__=") {
1040                let stderr = &stderr[start + 16..];
1041                let end = stderr
1042                    .find(|c: char| !c.is_ascii_digit())
1043                    .unwrap_or(stderr.len());
1044                stderr[..end].parse().ok()
1045            } else {
1046                None
1047            };
1048
1049            let start = stderr
1050                .find("#include <...> search starts here:")
1051                .ok_or_else(|| anyhow!("Failed to parse `zig cc -v` output"))?
1052                + 34;
1053            let end = stderr
1054                .find("End of search list.")
1055                .ok_or_else(|| anyhow!("Failed to parse `zig cc -v` output"))?;
1056
1057            let mut include_paths = Vec::new();
1058            for mut line in stderr[start..end].lines() {
1059                line = line.trim();
1060                let mut kind = Kind::Normal;
1061                if line.ends_with(" (framework directory)") {
1062                    line = line[..line.len() - 22].trim();
1063                    kind = Kind::Framework;
1064                } else if line.ends_with(" (headermap)") {
1065                    bail!("C/C++ search path includes header maps, which are not supported");
1066                }
1067                if !line.is_empty() {
1068                    include_paths.push((kind, line.to_owned()));
1069                }
1070            }
1071
1072            // In openharmony, we should add search header path by default which is useful for bindgen.
1073            if raw_target.contains("ohos") {
1074                let ndk = env::var("OHOS_NDK_HOME").expect("Can't get NDK path");
1075                include_paths.push((Kind::Normal, format!("{}/native/sysroot/usr/include", ndk)));
1076            }
1077
1078            Ok(PerLanguageOptions {
1079                include_paths,
1080                glibc_minor_ver,
1081            })
1082        }
1083
1084        let c_opts = collect_per_language_options(&zig_wrapper.cc, "c", raw_target)?;
1085        let cpp_opts = collect_per_language_options(&zig_wrapper.cxx, "cpp", raw_target)?;
1086
1087        // Ensure that `c_opts` and `cpp_opts` are almost identical in the way we expect.
1088        if c_opts.glibc_minor_ver != cpp_opts.glibc_minor_ver {
1089            bail!(
1090                "`zig cc` gives a different glibc minor version for C ({:?}) and C++ ({:?})",
1091                c_opts.glibc_minor_ver,
1092                cpp_opts.glibc_minor_ver,
1093            );
1094        }
1095        let c_paths = c_opts.include_paths;
1096        let mut cpp_paths = cpp_opts.include_paths;
1097        let cpp_pre_len = cpp_paths
1098            .iter()
1099            .position(|p| {
1100                p == c_paths
1101                    .iter()
1102                    .find(|(kind, _)| *kind == Kind::Normal)
1103                    .unwrap()
1104            })
1105            .unwrap_or_default();
1106        let cpp_post_len = cpp_paths.len()
1107            - cpp_paths
1108                .iter()
1109                .position(|p| p == c_paths.last().unwrap())
1110                .unwrap_or_default()
1111            - 1;
1112
1113        // <digression>
1114        //
1115        // So, why we do need all of these?
1116        //
1117        // Bindgen wouldn't look at our `zig cc` (which doesn't contain `libclang.so` anyway),
1118        // but it does collect include paths from the local clang and feed them to `libclang.so`.
1119        // We want those include paths to come from our `zig cc` instead of the local clang.
1120        // There are three main mechanisms possible:
1121        //
1122        // 1. Replace the local clang with our version.
1123        //
1124        //    Bindgen, internally via clang-sys, recognizes `CLANG_PATH` and `PATH`.
1125        //    They are unfortunately a global namespace and simply setting them may break
1126        //    existing build scripts, so we can't confidently override them.
1127        //
1128        //    Clang-sys can also look at target-prefixed clang if arguments contain `-target`.
1129        //    Unfortunately clang-sys can only recognize `-target xxx`, which very slightly
1130        //    differs from what bindgen would pass (`-target=xxx`), so this is not yet possible.
1131        //
1132        //    It should be also noted that we need to collect not only include paths
1133        //    but macro definitions added by Zig, for example `-D__GLIBC_MINOR__`.
1134        //    Clang-sys can't do this yet, so this option seems less robust than we want.
1135        //
1136        // 2. Set the environment variable `BINDGEN_EXTRA_CLANG_ARGS` and let bindgen to
1137        //    append them to arguments passed to `libclang.so`.
1138        //
1139        //    This unfortunately means that we have the same set of arguments for C and C++.
1140        //    Also we have to support older versions of clang, as old as clang 5 (2017).
1141        //    We do have options like `-c-isystem` (cc1 only) and `-cxx-isystem`,
1142        //    but we need to be aware of other options may affect our added options
1143        //    and this requires a nitty gritty of clang driver and cc1---really annoying.
1144        //
1145        // 3. Fix either bindgen or clang-sys or Zig to ease our jobs.
1146        //
1147        //    This is not the option for now because, even after fixes, we have to support
1148        //    older versions of bindgen or Zig which won't have those fixes anyway.
1149        //    But it seems that minor changes to bindgen can indeed fix lots of issues
1150        //    we face, so we are looking for them in the future.
1151        //
1152        // For this reason, we chose the option 2 and overrode `BINDGEN_EXTRA_CLANG_ARGS`.
1153        // The following therefore assumes some understanding about clang option handling,
1154        // including what the heck is cc1 (see the clang FAQ) and how driver options get
1155        // translated to cc1 options (no documentation at all, as it's supposedly unstable).
1156        // Fortunately for us, most (but not all) `-i...` options are passed through cc1.
1157        //
1158        // If you do experience weird compilation errors during bindgen, there's a chance
1159        // that this code has overlooked some edge cases. You can put `.clang_arg("-###")`
1160        // to print the final cc1 options, which would give a lot of information about
1161        // how it got screwed up and help a lot when we fix the issue.
1162        //
1163        // </digression>
1164
1165        let mut args = Vec::new();
1166
1167        // Never include default include directories,
1168        // otherwise `__has_include` will be totally confused.
1169        args.push("-nostdinc".to_owned());
1170
1171        // Add various options for libc++ and glibc.
1172        // Should match what `Compilation.zig` internally does:
1173        //
1174        // https://github.com/ziglang/zig/blob/0.9.0/src/Compilation.zig#L3390-L3427
1175        // https://github.com/ziglang/zig/blob/0.9.1/src/Compilation.zig#L3408-L3445
1176        // https://github.com/ziglang/zig/blob/0.10.0/src/Compilation.zig#L4163-L4211
1177        // https://github.com/ziglang/zig/blob/0.10.1/src/Compilation.zig#L4240-L4288
1178        if raw_target.contains("musl") || raw_target.contains("ohos") {
1179            args.push("-D_LIBCPP_HAS_MUSL_LIBC".to_owned());
1180            // for musl or openharmony
1181            // https://github.com/ziglang/zig/pull/16098
1182            args.push("-D_LARGEFILE64_SOURCE".to_owned());
1183        }
1184        args.extend(
1185            [
1186                "-D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS",
1187                "-D_LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS",
1188                "-D_LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS",
1189                "-D_LIBCPP_PSTL_CPU_BACKEND_SERIAL",
1190                "-D_LIBCPP_ABI_VERSION=1",
1191                "-D_LIBCPP_ABI_NAMESPACE=__1",
1192                "-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST",
1193                // Required by zig 0.15+ libc++ for streambuf and other I/O headers
1194                "-D_LIBCPP_HAS_LOCALIZATION=1",
1195                "-D_LIBCPP_HAS_WIDE_CHARACTERS=1",
1196                "-D_LIBCPP_HAS_UNICODE=1",
1197                "-D_LIBCPP_HAS_THREADS=1",
1198                "-D_LIBCPP_HAS_MONOTONIC_CLOCK",
1199            ]
1200            .into_iter()
1201            .map(ToString::to_string),
1202        );
1203        if let Some(ver) = c_opts.glibc_minor_ver {
1204            // Handled separately because we have no way to infer this without Zig
1205            args.push(format!("-D__GLIBC_MINOR__={ver}"));
1206        }
1207
1208        for (kind, path) in cpp_paths.drain(..cpp_pre_len) {
1209            if kind != Kind::Normal {
1210                // may also be Kind::Framework on macOS
1211                continue;
1212            }
1213            // Ideally this should be `-stdlib++-isystem`, which can be disabled by
1214            // passing `-nostdinc++`, but it is fairly new: https://reviews.llvm.org/D64089
1215            //
1216            // (Also note that `-stdlib++-isystem` is a driver-only option,
1217            // so it will be moved relative to other `-isystem` options against our will.)
1218            args.push("-cxx-isystem".to_owned());
1219            args.push(path);
1220        }
1221
1222        for (kind, path) in c_paths {
1223            match kind {
1224                Kind::Normal => {
1225                    // A normal `-isystem` is preferred over `-cxx-isystem` by cc1...
1226                    args.push("-Xclang".to_owned());
1227                    args.push("-c-isystem".to_owned());
1228                    args.push("-Xclang".to_owned());
1229                    args.push(path.clone());
1230                    args.push("-cxx-isystem".to_owned());
1231                    args.push(path);
1232                }
1233                Kind::Framework => {
1234                    args.push("-iframework".to_owned());
1235                    args.push(path);
1236                }
1237            }
1238        }
1239
1240        for (kind, path) in cpp_paths.drain(cpp_paths.len() - cpp_post_len..) {
1241            assert!(kind == Kind::Normal);
1242            args.push("-cxx-isystem".to_owned());
1243            args.push(path);
1244        }
1245
1246        Ok(args)
1247    }
1248
1249    fn setup_os_deps(
1250        manifest_path: Option<&Path>,
1251        release: bool,
1252        cargo: &cargo_options::CommonOptions,
1253    ) -> Result<()> {
1254        for target in &cargo.target {
1255            if target.contains("apple") {
1256                let target_dir = if let Some(target_dir) = cargo.target_dir.clone() {
1257                    target_dir.join(target)
1258                } else {
1259                    let manifest_path = manifest_path.unwrap_or_else(|| Path::new("Cargo.toml"));
1260                    if !manifest_path.exists() {
1261                        // cargo install doesn't pass a manifest path so `Cargo.toml` in cwd may not exist
1262                        continue;
1263                    }
1264                    let metadata = cargo_metadata::MetadataCommand::new()
1265                        .manifest_path(manifest_path)
1266                        .no_deps()
1267                        .exec()?;
1268                    metadata.target_directory.into_std_path_buf().join(target)
1269                };
1270                let profile = match cargo.profile.as_deref() {
1271                    Some("dev" | "test") => "debug",
1272                    Some("release" | "bench") => "release",
1273                    Some(profile) => profile,
1274                    None => {
1275                        if release {
1276                            "release"
1277                        } else {
1278                            "debug"
1279                        }
1280                    }
1281                };
1282                let deps_dir = target_dir.join(profile).join("deps");
1283                fs::create_dir_all(&deps_dir)?;
1284                if !target_dir.join("CACHEDIR.TAG").is_file() {
1285                    // Create a CACHEDIR.TAG file to exclude target directory from backup
1286                    let _ = write_file(
1287                        &target_dir.join("CACHEDIR.TAG"),
1288                        "Signature: 8a477f597d28d172789f06886806bc55
1289# This file is a cache directory tag created by cargo.
1290# For information about cache directory tags see https://bford.info/cachedir/
1291",
1292                    );
1293                }
1294                write_tbd_files(&deps_dir)?;
1295            } else if target.contains("arm") && target.contains("linux") {
1296                // See https://github.com/ziglang/zig/issues/3287
1297                if let Ok(lib_dir) = Zig::lib_dir() {
1298                    let arm_features_h = lib_dir
1299                        .join("libc")
1300                        .join("glibc")
1301                        .join("sysdeps")
1302                        .join("arm")
1303                        .join("arm-features.h");
1304                    if !arm_features_h.is_file() {
1305                        fs::write(arm_features_h, ARM_FEATURES_H)?;
1306                    }
1307                }
1308            } else if target.contains("windows-gnu") {
1309                if let Ok(lib_dir) = Zig::lib_dir() {
1310                    let lib_common = lib_dir.join("libc").join("mingw").join("lib-common");
1311                    let synchronization_def = lib_common.join("synchronization.def");
1312                    if !synchronization_def.is_file() {
1313                        let api_ms_win_core_synch_l1_2_0_def =
1314                            lib_common.join("api-ms-win-core-synch-l1-2-0.def");
1315                        // Ignore error
1316                        fs::copy(api_ms_win_core_synch_l1_2_0_def, synchronization_def).ok();
1317                    }
1318                }
1319            }
1320        }
1321        Ok(())
1322    }
1323
1324    fn setup_cmake_toolchain(
1325        target: &str,
1326        zig_wrapper: &ZigWrapper,
1327        enable_zig_ar: bool,
1328    ) -> Result<PathBuf> {
1329        let cmake = cache_dir().join("cmake");
1330        fs::create_dir_all(&cmake)?;
1331
1332        let toolchain_file = cmake.join(format!("{target}-toolchain.cmake"));
1333        let triple: Triple = target.parse()?;
1334        let os = triple.operating_system.to_string();
1335        let arch = triple.architecture.to_string();
1336        let (system_name, system_processor) = match (os.as_str(), arch.as_str()) {
1337            ("darwin", "x86_64") => ("Darwin", "x86_64"),
1338            ("darwin", "aarch64") => ("Darwin", "arm64"),
1339            ("linux", arch) => {
1340                let cmake_arch = match arch {
1341                    "powerpc" => "ppc",
1342                    "powerpc64" => "ppc64",
1343                    "powerpc64le" => "ppc64le",
1344                    _ => arch,
1345                };
1346                ("Linux", cmake_arch)
1347            }
1348            ("windows", "x86_64") => ("Windows", "AMD64"),
1349            ("windows", "i686") => ("Windows", "X86"),
1350            ("windows", "aarch64") => ("Windows", "ARM64"),
1351            (os, arch) => (os, arch),
1352        };
1353        let mut content = format!(
1354            r#"
1355set(CMAKE_SYSTEM_NAME {system_name})
1356set(CMAKE_SYSTEM_PROCESSOR {system_processor})
1357set(CMAKE_C_COMPILER {cc})
1358set(CMAKE_CXX_COMPILER {cxx})
1359set(CMAKE_RANLIB {ranlib})
1360set(CMAKE_C_LINKER_DEPFILE_SUPPORTED FALSE)
1361set(CMAKE_CXX_LINKER_DEPFILE_SUPPORTED FALSE)"#,
1362            system_name = system_name,
1363            system_processor = system_processor,
1364            cc = zig_wrapper.cc.to_slash_lossy(),
1365            cxx = zig_wrapper.cxx.to_slash_lossy(),
1366            ranlib = zig_wrapper.ranlib.to_slash_lossy(),
1367        );
1368        if enable_zig_ar {
1369            content.push_str(&format!(
1370                "\nset(CMAKE_AR {})\n",
1371                zig_wrapper.ar.to_slash_lossy()
1372            ));
1373        }
1374        write_file(&toolchain_file, &content)?;
1375        Ok(toolchain_file)
1376    }
1377
1378    #[cfg(target_os = "macos")]
1379    fn macos_sdk_root() -> Option<PathBuf> {
1380        static SDK_ROOT: OnceLock<Option<PathBuf>> = OnceLock::new();
1381
1382        SDK_ROOT
1383            .get_or_init(|| match env::var_os("SDKROOT") {
1384                Some(sdkroot) if !sdkroot.is_empty() => Some(sdkroot.into()),
1385                _ => {
1386                    let output = Command::new("xcrun")
1387                        .args(["--sdk", "macosx", "--show-sdk-path"])
1388                        .output()
1389                        .ok()?;
1390                    if output.status.success() {
1391                        let stdout = String::from_utf8(output.stdout).ok()?;
1392                        let stdout = stdout.trim();
1393                        if !stdout.is_empty() {
1394                            return Some(stdout.into());
1395                        }
1396                    }
1397                    None
1398                }
1399            })
1400            .clone()
1401    }
1402
1403    #[cfg(not(target_os = "macos"))]
1404    fn macos_sdk_root() -> Option<PathBuf> {
1405        match env::var_os("SDKROOT") {
1406            Some(sdkroot) if !sdkroot.is_empty() => Some(sdkroot.into()),
1407            _ => None,
1408        }
1409    }
1410}
1411
1412fn write_file(path: &Path, content: &str) -> Result<(), anyhow::Error> {
1413    let existing_content = fs::read_to_string(path).unwrap_or_default();
1414    if existing_content != content {
1415        fs::write(path, content)?;
1416    }
1417    Ok(())
1418}
1419
1420fn write_tbd_files(deps_dir: &Path) -> Result<(), anyhow::Error> {
1421    write_file(&deps_dir.join("libiconv.tbd"), LIBICONV_TBD)?;
1422    write_file(&deps_dir.join("libcharset.1.tbd"), LIBCHARSET_TBD)?;
1423    write_file(&deps_dir.join("libcharset.tbd"), LIBCHARSET_TBD)?;
1424    Ok(())
1425}
1426
1427fn cache_dir() -> PathBuf {
1428    env::var("CARGO_ZIGBUILD_CACHE_DIR")
1429        .ok()
1430        .map(|s| s.into())
1431        .or_else(dirs::cache_dir)
1432        // If the really is no cache dir, cwd will also do
1433        .unwrap_or_else(|| env::current_dir().expect("Failed to get current dir"))
1434        .join(env!("CARGO_PKG_NAME"))
1435        .join(env!("CARGO_PKG_VERSION"))
1436}
1437
1438#[derive(Debug, Deserialize)]
1439struct ZigEnv {
1440    lib_dir: String,
1441}
1442
1443/// zig wrapper paths
1444#[derive(Debug, Clone)]
1445pub struct ZigWrapper {
1446    pub cc: PathBuf,
1447    pub cxx: PathBuf,
1448    pub ar: PathBuf,
1449    pub ranlib: PathBuf,
1450    pub lib: PathBuf,
1451}
1452
1453#[derive(Debug, Clone, Default, PartialEq)]
1454struct TargetFlags {
1455    pub target_cpu: String,
1456    pub target_feature: String,
1457}
1458
1459impl TargetFlags {
1460    pub fn parse_from_encoded(encoded: &OsStr) -> Result<Self> {
1461        let mut parsed = Self::default();
1462
1463        let f = rustflags::from_encoded(encoded);
1464        for flag in f {
1465            if let rustflags::Flag::Codegen { opt, value } = flag {
1466                let key = opt.replace('-', "_");
1467                match key.as_str() {
1468                    "target_cpu" => {
1469                        if let Some(value) = value {
1470                            parsed.target_cpu = value;
1471                        }
1472                    }
1473                    "target_feature" => {
1474                        // See https://github.com/rust-lang/rust/blob/7e3ba5b8b7556073ab69822cc36b93d6e74cd8c9/compiler/rustc_session/src/options.rs#L1233
1475                        if let Some(value) = value {
1476                            if !parsed.target_feature.is_empty() {
1477                                parsed.target_feature.push(',');
1478                            }
1479                            parsed.target_feature.push_str(&value);
1480                        }
1481                    }
1482                    _ => {}
1483                }
1484            }
1485        }
1486        Ok(parsed)
1487    }
1488}
1489
1490/// Prepare wrapper scripts for `zig cc` and `zig c++` and returns their paths
1491///
1492/// We want to use `zig cc` as linker and c compiler. We want to call `python -m ziglang cc`, but
1493/// cargo only accepts a path to an executable as linker, so we add a wrapper script. We then also
1494/// use the wrapper script to pass arguments and substitute an unsupported argument.
1495///
1496/// We create different files for different args because otherwise cargo might skip recompiling even
1497/// if the linker target changed
1498#[allow(clippy::blocks_in_conditions)]
1499pub fn prepare_zig_linker(target: &str) -> Result<ZigWrapper> {
1500    let (rust_target, abi_suffix) = target.split_once('.').unwrap_or((target, ""));
1501    let abi_suffix = if abi_suffix.is_empty() {
1502        String::new()
1503    } else {
1504        if abi_suffix
1505            .split_once('.')
1506            .filter(|(x, y)| {
1507                !x.is_empty()
1508                    && x.chars().all(|c| c.is_ascii_digit())
1509                    && !y.is_empty()
1510                    && y.chars().all(|c| c.is_ascii_digit())
1511            })
1512            .is_none()
1513        {
1514            bail!("Malformed zig target abi suffix.")
1515        }
1516        format!(".{abi_suffix}")
1517    };
1518    let triple: Triple = rust_target
1519        .parse()
1520        .with_context(|| format!("Unsupported Rust target '{rust_target}'"))?;
1521    let arch = triple.architecture.to_string();
1522    let target_env = match (triple.architecture, triple.environment) {
1523        (Architecture::Mips32(..), Environment::Gnu) => Environment::Gnueabihf,
1524        (Architecture::Powerpc, Environment::Gnu) => Environment::Gnueabihf,
1525        (_, Environment::GnuLlvm) => Environment::Gnu,
1526        (_, environment) => environment,
1527    };
1528    let file_ext = if cfg!(windows) { "bat" } else { "sh" };
1529    let file_target = target.trim_end_matches('.');
1530
1531    let mut cc_args = vec![
1532        // prevent stripping
1533        "-g".to_owned(),
1534        // disable sanitizers
1535        "-fno-sanitize=all".to_owned(),
1536    ];
1537
1538    // TODO: Maybe better to assign mcpu according to:
1539    // rustc --target <target> -Z unstable-options --print target-spec-json
1540    let zig_mcpu_default = match triple.operating_system {
1541        OperatingSystem::Linux => {
1542            match arch.as_str() {
1543                // zig uses _ instead of - in cpu features
1544                "arm" => match target_env {
1545                    Environment::Gnueabi | Environment::Musleabi => "generic+v6+strict_align",
1546                    Environment::Gnueabihf | Environment::Musleabihf => {
1547                        "generic+v6+strict_align+vfp2-d32"
1548                    }
1549                    _ => "",
1550                },
1551                "armv5te" => "generic+soft_float+strict_align",
1552                "armv7" => "generic+v7a+vfp3-d32+thumb2-neon",
1553                arch_str @ ("i586" | "i686") => {
1554                    if arch_str == "i586" {
1555                        "pentium"
1556                    } else {
1557                        "pentium4"
1558                    }
1559                }
1560                "riscv64gc" => "generic_rv64+m+a+f+d+c",
1561                "s390x" => "z10-vector",
1562                _ => "",
1563            }
1564        }
1565        _ => "",
1566    };
1567
1568    // Override mcpu from RUSTFLAGS if provided. The override happens when
1569    // commands like `cargo-zigbuild build` are invoked.
1570    // Currently we only override according to target_cpu.
1571    let zig_mcpu_override = {
1572        let cargo_config = cargo_config2::Config::load()?;
1573        let rust_flags = cargo_config.rustflags(rust_target)?.unwrap_or_default();
1574        let encoded_rust_flags = rust_flags.encode()?;
1575        let target_flags = TargetFlags::parse_from_encoded(OsStr::new(&encoded_rust_flags))?;
1576        // Note: zig uses _ instead of - for target_cpu and target_feature
1577        // target_cpu may be empty string, which means target_cpu is not specified.
1578        target_flags.target_cpu.replace('-', "_")
1579    };
1580
1581    if !zig_mcpu_override.is_empty() {
1582        cc_args.push(format!("-mcpu={zig_mcpu_override}"));
1583    } else if !zig_mcpu_default.is_empty() {
1584        cc_args.push(format!("-mcpu={zig_mcpu_default}"));
1585    }
1586
1587    match triple.operating_system {
1588        OperatingSystem::Linux => {
1589            let zig_arch = match arch.as_str() {
1590                // zig uses _ instead of - in cpu features
1591                "arm" => "arm",
1592                "armv5te" => "arm",
1593                "armv7" => "arm",
1594                "i586" | "i686" => {
1595                    let zig_version = Zig::zig_version()?;
1596                    if zig_version.major == 0 && zig_version.minor >= 11 {
1597                        "x86"
1598                    } else {
1599                        "i386"
1600                    }
1601                }
1602                "riscv64gc" => "riscv64",
1603                "s390x" => "s390x",
1604                _ => arch.as_str(),
1605            };
1606            let mut zig_target_env = target_env.to_string();
1607
1608            let zig_version = Zig::zig_version()?;
1609
1610            // Since Zig 0.15.0, arm-linux-ohos changed to arm-linux-ohoseabi
1611            // We need to follow the change but target_lexicon follow the LLVM target(https://github.com/bytecodealliance/target-lexicon/pull/123).
1612            // So we use string directly.
1613            if zig_version >= semver::Version::new(0, 15, 0)
1614                && arch.as_str() == "armv7"
1615                && target_env == Environment::Ohos
1616            {
1617                zig_target_env = "ohoseabi".to_string();
1618            }
1619
1620            cc_args.push("-target".to_string());
1621            cc_args.push(format!("{zig_arch}-linux-{zig_target_env}{abi_suffix}"));
1622        }
1623        OperatingSystem::MacOSX { .. } | OperatingSystem::Darwin(_) => {
1624            let zig_version = Zig::zig_version()?;
1625            // Zig 0.10.0 switched macOS ABI to none
1626            // see https://github.com/ziglang/zig/pull/11684
1627            if zig_version > semver::Version::new(0, 9, 1) {
1628                cc_args.push("-target".to_string());
1629                cc_args.push(format!("{arch}-macos-none{abi_suffix}"));
1630            } else {
1631                cc_args.push("-target".to_string());
1632                cc_args.push(format!("{arch}-macos-gnu{abi_suffix}"));
1633            }
1634        }
1635        OperatingSystem::Windows => {
1636            let zig_arch = match arch.as_str() {
1637                "i686" => {
1638                    let zig_version = Zig::zig_version()?;
1639                    if zig_version.major == 0 && zig_version.minor >= 11 {
1640                        "x86"
1641                    } else {
1642                        "i386"
1643                    }
1644                }
1645                arch => arch,
1646            };
1647            cc_args.push("-target".to_string());
1648            cc_args.push(format!("{zig_arch}-windows-{target_env}{abi_suffix}"));
1649        }
1650        OperatingSystem::Emscripten => {
1651            cc_args.push("-target".to_string());
1652            cc_args.push(format!("{arch}-emscripten{abi_suffix}"));
1653        }
1654        OperatingSystem::Wasi => {
1655            cc_args.push("-target".to_string());
1656            cc_args.push(format!("{arch}-wasi{abi_suffix}"));
1657        }
1658        OperatingSystem::WasiP1 => {
1659            cc_args.push("-target".to_string());
1660            cc_args.push(format!("{arch}-wasi.0.1.0{abi_suffix}"));
1661        }
1662        OperatingSystem::Freebsd => {
1663            let zig_arch = match arch.as_str() {
1664                "i686" => {
1665                    let zig_version = Zig::zig_version()?;
1666                    if zig_version.major == 0 && zig_version.minor >= 11 {
1667                        "x86"
1668                    } else {
1669                        "i386"
1670                    }
1671                }
1672                arch => arch,
1673            };
1674            cc_args.push("-target".to_string());
1675            cc_args.push(format!("{zig_arch}-freebsd"));
1676        }
1677        OperatingSystem::Unknown => {
1678            if triple.architecture == Architecture::Wasm32
1679                || triple.architecture == Architecture::Wasm64
1680            {
1681                cc_args.push("-target".to_string());
1682                cc_args.push(format!("{arch}-freestanding{abi_suffix}"));
1683            } else {
1684                bail!("unsupported target '{rust_target}'")
1685            }
1686        }
1687        _ => bail!(format!("unsupported target '{rust_target}'")),
1688    };
1689
1690    let zig_linker_dir = cache_dir();
1691    fs::create_dir_all(&zig_linker_dir)?;
1692
1693    if triple.operating_system == OperatingSystem::Linux {
1694        if matches!(
1695            triple.environment,
1696            Environment::Gnu
1697                | Environment::Gnuspe
1698                | Environment::Gnux32
1699                | Environment::Gnueabi
1700                | Environment::Gnuabi64
1701                | Environment::GnuIlp32
1702                | Environment::Gnueabihf
1703        ) {
1704            let glibc_version = if abi_suffix.is_empty() {
1705                (2, 17)
1706            } else {
1707                let mut parts = abi_suffix[1..].split('.');
1708                let major: usize = parts.next().unwrap().parse()?;
1709                let minor: usize = parts.next().unwrap().parse()?;
1710                (major, minor)
1711            };
1712            // See https://github.com/ziglang/zig/issues/9485
1713            if glibc_version < (2, 28) {
1714                use crate::linux::{FCNTL_H, FCNTL_MAP};
1715
1716                let zig_version = Zig::zig_version()?;
1717                if zig_version.major == 0 && zig_version.minor < 11 {
1718                    let fcntl_map = zig_linker_dir.join("fcntl.map");
1719                    let existing_content = fs::read_to_string(&fcntl_map).unwrap_or_default();
1720                    if existing_content != FCNTL_MAP {
1721                        fs::write(&fcntl_map, FCNTL_MAP)?;
1722                    }
1723                    let fcntl_h = zig_linker_dir.join("fcntl.h");
1724                    let existing_content = fs::read_to_string(&fcntl_h).unwrap_or_default();
1725                    if existing_content != FCNTL_H {
1726                        fs::write(&fcntl_h, FCNTL_H)?;
1727                    }
1728
1729                    cc_args.push(format!("-Wl,--version-script={}", fcntl_map.display()));
1730                    cc_args.push("-include".to_string());
1731                    cc_args.push(fcntl_h.display().to_string());
1732                }
1733            }
1734        } else if matches!(
1735            triple.environment,
1736            Environment::Musl
1737                | Environment::Muslabi64
1738                | Environment::Musleabi
1739                | Environment::Musleabihf
1740        ) {
1741            use crate::linux::MUSL_WEAK_SYMBOLS_MAPPING_SCRIPT;
1742
1743            let zig_version = Zig::zig_version()?;
1744            let rustc_version = rustc_version::version_meta()?.semver;
1745
1746            // as zig 0.11.0 is released, its musl has been upgraded to 1.2.4 with break changes
1747            // but rust is still with musl 1.2.3
1748            // we need this workaround before rust 1.72
1749            // https://github.com/ziglang/zig/pull/16098
1750            if (zig_version.major, zig_version.minor) >= (0, 11)
1751                && (rustc_version.major, rustc_version.minor) < (1, 72)
1752            {
1753                let weak_symbols_map = zig_linker_dir.join("musl_weak_symbols_map.ld");
1754                fs::write(&weak_symbols_map, MUSL_WEAK_SYMBOLS_MAPPING_SCRIPT)?;
1755
1756                cc_args.push(format!("-Wl,-T,{}", weak_symbols_map.display()));
1757            }
1758        }
1759    }
1760
1761    // Use platform-specific quoting: shell_words for Unix (single quotes),
1762    // custom quoting for Windows batch files (double quotes)
1763    let cc_args_str = join_args_for_script(&cc_args);
1764    let hash = crc::Crc::<u16>::new(&crc::CRC_16_IBM_SDLC).checksum(cc_args_str.as_bytes());
1765    let zig_cc = zig_linker_dir.join(format!("zigcc-{file_target}-{:x}.{file_ext}", hash));
1766    let zig_cxx = zig_linker_dir.join(format!("zigcxx-{file_target}-{:x}.{file_ext}", hash));
1767    let zig_ranlib = zig_linker_dir.join(format!("zigranlib.{file_ext}"));
1768    let zig_version = Zig::zig_version()?;
1769    write_linker_wrapper(&zig_cc, "cc", &cc_args_str, &zig_version)?;
1770    write_linker_wrapper(&zig_cxx, "c++", &cc_args_str, &zig_version)?;
1771    write_linker_wrapper(&zig_ranlib, "ranlib", "", &zig_version)?;
1772
1773    let exe_ext = if cfg!(windows) { ".exe" } else { "" };
1774    let zig_ar = zig_linker_dir.join(format!("ar{exe_ext}"));
1775    symlink_wrapper(&zig_ar)?;
1776    let zig_lib = zig_linker_dir.join(format!("lib{exe_ext}"));
1777    symlink_wrapper(&zig_lib)?;
1778
1779    // Create dlltool symlinks for Windows GNU targets, but only if no system dlltool exists
1780    // On Windows hosts, rustc looks for "dlltool.exe"
1781    // On non-Windows hosts, rustc looks for architecture-specific names
1782    //
1783    // See https://github.com/rust-lang/rust/blob/a18e6d9d1473d9b25581dd04bef6c7577999631c/compiler/rustc_codegen_ssa/src/back/archive.rs#L275-L309
1784    if matches!(triple.operating_system, OperatingSystem::Windows)
1785        && matches!(triple.environment, Environment::Gnu)
1786    {
1787        // Only create zig dlltool wrapper if no system dlltool is found
1788        // System dlltool (from mingw-w64) handles raw-dylib better than zig's dlltool
1789        if !has_system_dlltool(&triple.architecture) {
1790            let dlltool_name = get_dlltool_name(&triple.architecture);
1791            let zig_dlltool = zig_linker_dir.join(format!("{dlltool_name}{exe_ext}"));
1792            symlink_wrapper(&zig_dlltool)?;
1793        }
1794    }
1795
1796    Ok(ZigWrapper {
1797        cc: zig_cc,
1798        cxx: zig_cxx,
1799        ar: zig_ar,
1800        ranlib: zig_ranlib,
1801        lib: zig_lib,
1802    })
1803}
1804
1805fn symlink_wrapper(target: &Path) -> Result<()> {
1806    let current_exe = if let Ok(exe) = env::var("CARGO_BIN_EXE_cargo-zigbuild") {
1807        PathBuf::from(exe)
1808    } else {
1809        env::current_exe()?
1810    };
1811    #[cfg(windows)]
1812    {
1813        if !target.exists() {
1814            // symlink on Windows requires admin privileges so we use hardlink instead
1815            if std::fs::hard_link(&current_exe, target).is_err() {
1816                // hard_link doesn't support cross-device links so we fallback to copy
1817                std::fs::copy(&current_exe, target)?;
1818            }
1819        }
1820    }
1821
1822    #[cfg(unix)]
1823    {
1824        if !target.exists() {
1825            if fs::read_link(target).is_ok() {
1826                // remove broken symlink
1827                fs::remove_file(target)?;
1828            }
1829            std::os::unix::fs::symlink(current_exe, target)?;
1830        }
1831    }
1832    Ok(())
1833}
1834
1835/// Join arguments for Unix shell script using shell_words (single quotes)
1836#[cfg(target_family = "unix")]
1837fn join_args_for_script<I, S>(args: I) -> String
1838where
1839    I: IntoIterator<Item = S>,
1840    S: AsRef<str>,
1841{
1842    shell_words::join(args)
1843}
1844
1845/// Quote a string for Windows batch file (cmd.exe)
1846///
1847/// - `%` expands even inside quotes, so we escape it as `%%`.
1848/// - We disable delayed expansion in the wrapper script, so `!` should not expand.
1849/// - Internal `"` are escaped by doubling them (`""`).
1850#[cfg(not(target_family = "unix"))]
1851fn quote_for_batch(s: &str) -> String {
1852    let needs_quoting_or_escaping = s.is_empty()
1853        || s.contains(|c: char| {
1854            matches!(
1855                c,
1856                ' ' | '\t' | '"' | '&' | '|' | '<' | '>' | '^' | '%' | '(' | ')' | '!'
1857            )
1858        });
1859
1860    if !needs_quoting_or_escaping {
1861        return s.to_string();
1862    }
1863
1864    let mut out = String::with_capacity(s.len() + 8);
1865    out.push('"');
1866    for c in s.chars() {
1867        match c {
1868            '"' => out.push_str("\"\""),
1869            '%' => out.push_str("%%"),
1870            _ => out.push(c),
1871        }
1872    }
1873    out.push('"');
1874    out
1875}
1876
1877/// Join arguments for Windows batch file using double quotes
1878#[cfg(not(target_family = "unix"))]
1879fn join_args_for_script<I, S>(args: I) -> String
1880where
1881    I: IntoIterator<Item = S>,
1882    S: AsRef<str>,
1883{
1884    args.into_iter()
1885        .map(|s| quote_for_batch(s.as_ref()))
1886        .collect::<Vec<_>>()
1887        .join(" ")
1888}
1889
1890/// Write a zig cc wrapper batch script for unix
1891#[cfg(target_family = "unix")]
1892fn write_linker_wrapper(
1893    path: &Path,
1894    command: &str,
1895    args: &str,
1896    zig_version: &semver::Version,
1897) -> Result<()> {
1898    let mut buf = Vec::<u8>::new();
1899    let current_exe = if let Ok(exe) = env::var("CARGO_BIN_EXE_cargo-zigbuild") {
1900        PathBuf::from(exe)
1901    } else {
1902        env::current_exe()?
1903    };
1904    writeln!(&mut buf, "#!/bin/sh")?;
1905
1906    // Export zig version to avoid spawning `zig version` subprocess
1907    writeln!(
1908        &mut buf,
1909        "export CARGO_ZIGBUILD_ZIG_VERSION={}",
1910        zig_version
1911    )?;
1912
1913    // Pass through SDKROOT if it exists at runtime
1914    writeln!(&mut buf, "if [ -n \"$SDKROOT\" ]; then export SDKROOT; fi")?;
1915
1916    writeln!(
1917        &mut buf,
1918        "exec \"{}\" zig {} -- {} \"$@\"",
1919        current_exe.display(),
1920        command,
1921        args
1922    )?;
1923
1924    // Try not to write the file again if it's already the same.
1925    // This is more friendly for cache systems like ccache, which by default
1926    // uses mtime to determine if a recompilation is needed.
1927    let existing_content = fs::read(path).unwrap_or_default();
1928    if existing_content != buf {
1929        OpenOptions::new()
1930            .create(true)
1931            .write(true)
1932            .truncate(true)
1933            .mode(0o700)
1934            .open(path)?
1935            .write_all(&buf)?;
1936    }
1937    Ok(())
1938}
1939
1940/// Write a zig cc wrapper batch script for windows
1941#[cfg(not(target_family = "unix"))]
1942fn write_linker_wrapper(
1943    path: &Path,
1944    command: &str,
1945    args: &str,
1946    zig_version: &semver::Version,
1947) -> Result<()> {
1948    let mut buf = Vec::<u8>::new();
1949    let current_exe = if let Ok(exe) = env::var("CARGO_BIN_EXE_cargo-zigbuild") {
1950        PathBuf::from(exe)
1951    } else {
1952        env::current_exe()?
1953    };
1954    let current_exe = if is_mingw_shell() {
1955        current_exe.to_slash_lossy().to_string()
1956    } else {
1957        current_exe.display().to_string()
1958    };
1959    writeln!(&mut buf, "@echo off")?;
1960    // Prevent `!VAR!` expansion surprises (delayed expansion) in user-controlled args.
1961    writeln!(&mut buf, "setlocal DisableDelayedExpansion")?;
1962    // Set zig version to avoid spawning `zig version` subprocess
1963    writeln!(&mut buf, "set CARGO_ZIGBUILD_ZIG_VERSION={}", zig_version)?;
1964    writeln!(
1965        &mut buf,
1966        "\"{}\" zig {} -- {} %*",
1967        adjust_canonicalization(current_exe),
1968        command,
1969        args
1970    )?;
1971
1972    let existing_content = fs::read(path).unwrap_or_default();
1973    if existing_content != buf {
1974        fs::write(path, buf)?;
1975    }
1976    Ok(())
1977}
1978
1979pub(crate) fn is_mingw_shell() -> bool {
1980    env::var_os("MSYSTEM").is_some() && env::var_os("SHELL").is_some()
1981}
1982
1983// https://stackoverflow.com/a/50323079/3549270
1984#[cfg(target_os = "windows")]
1985pub fn adjust_canonicalization(p: String) -> String {
1986    const VERBATIM_PREFIX: &str = r#"\\?\"#;
1987    if p.starts_with(VERBATIM_PREFIX) {
1988        p[VERBATIM_PREFIX.len()..].to_string()
1989    } else {
1990        p
1991    }
1992}
1993
1994fn python_path() -> Result<PathBuf> {
1995    let python = env::var("CARGO_ZIGBUILD_PYTHON_PATH").unwrap_or_else(|_| "python3".to_string());
1996    Ok(which::which(python)?)
1997}
1998
1999fn zig_path() -> Result<PathBuf> {
2000    let zig = env::var("CARGO_ZIGBUILD_ZIG_PATH").unwrap_or_else(|_| "zig".to_string());
2001    Ok(which::which(zig)?)
2002}
2003
2004/// Get the dlltool executable name for the given architecture
2005/// On Windows, rustc looks for "dlltool.exe"
2006/// On non-Windows hosts, rustc looks for architecture-specific names
2007fn get_dlltool_name(arch: &Architecture) -> &'static str {
2008    if cfg!(windows) {
2009        "dlltool"
2010    } else {
2011        match arch {
2012            Architecture::X86_64 => "x86_64-w64-mingw32-dlltool",
2013            Architecture::X86_32(_) => "i686-w64-mingw32-dlltool",
2014            Architecture::Aarch64(_) => "aarch64-w64-mingw32-dlltool",
2015            _ => "dlltool",
2016        }
2017    }
2018}
2019
2020/// Check if a dlltool for the given architecture exists in PATH
2021/// Returns true if found, false otherwise
2022fn has_system_dlltool(arch: &Architecture) -> bool {
2023    which::which(get_dlltool_name(arch)).is_ok()
2024}
2025
2026#[cfg(test)]
2027mod tests {
2028    use super::*;
2029
2030    #[test]
2031    fn test_target_flags() {
2032        let cases = [
2033            // Input, TargetCPU, TargetFeature
2034            ("-C target-feature=-crt-static", "", "-crt-static"),
2035            ("-C target-cpu=native", "native", ""),
2036            (
2037                "--deny warnings --codegen target-feature=+crt-static",
2038                "",
2039                "+crt-static",
2040            ),
2041            ("-C target_cpu=skylake-avx512", "skylake-avx512", ""),
2042            ("-Ctarget_cpu=x86-64-v3", "x86-64-v3", ""),
2043            (
2044                "-C target-cpu=native --cfg foo -C target-feature=-avx512bf16,-avx512bitalg",
2045                "native",
2046                "-avx512bf16,-avx512bitalg",
2047            ),
2048            (
2049                "--target x86_64-unknown-linux-gnu --codegen=target-cpu=x --codegen=target-cpu=x86-64",
2050                "x86-64",
2051                "",
2052            ),
2053            (
2054                "-Ctarget-feature=+crt-static -Ctarget-feature=+avx",
2055                "",
2056                "+crt-static,+avx",
2057            ),
2058        ];
2059
2060        for (input, expected_target_cpu, expected_target_feature) in cases.iter() {
2061            let args = cargo_config2::Flags::from_space_separated(input);
2062            let encoded_rust_flags = args.encode().unwrap();
2063            let flags = TargetFlags::parse_from_encoded(OsStr::new(&encoded_rust_flags)).unwrap();
2064            assert_eq!(flags.target_cpu, *expected_target_cpu, "{}", input);
2065            assert_eq!(flags.target_feature, *expected_target_feature, "{}", input);
2066        }
2067    }
2068
2069    #[test]
2070    fn test_join_args_for_script() {
2071        // Test basic arguments without special characters
2072        let args = vec!["-target", "x86_64-linux-gnu"];
2073        let result = join_args_for_script(&args);
2074        assert!(result.contains("-target"));
2075        assert!(result.contains("x86_64-linux-gnu"));
2076    }
2077
2078    #[test]
2079    #[cfg(not(target_family = "unix"))]
2080    fn test_quote_for_batch() {
2081        // Simple argument without special characters - no quoting needed
2082        assert_eq!(quote_for_batch("-target"), "-target");
2083        assert_eq!(quote_for_batch("x86_64-linux-gnu"), "x86_64-linux-gnu");
2084
2085        // Arguments with spaces need quoting
2086        assert_eq!(
2087            quote_for_batch("C:\\Users\\John Doe\\path"),
2088            "\"C:\\Users\\John Doe\\path\""
2089        );
2090
2091        // Empty string needs quoting
2092        assert_eq!(quote_for_batch(""), "\"\"");
2093
2094        // Arguments with special batch characters need quoting
2095        assert_eq!(quote_for_batch("foo&bar"), "\"foo&bar\"");
2096        assert_eq!(quote_for_batch("foo|bar"), "\"foo|bar\"");
2097        assert_eq!(quote_for_batch("foo<bar"), "\"foo<bar\"");
2098        assert_eq!(quote_for_batch("foo>bar"), "\"foo>bar\"");
2099        assert_eq!(quote_for_batch("foo^bar"), "\"foo^bar\"");
2100        assert_eq!(quote_for_batch("foo%bar"), "\"foo%bar\"");
2101
2102        // Internal double quotes are escaped by doubling
2103        assert_eq!(quote_for_batch("foo\"bar"), "\"foo\"\"bar\"");
2104    }
2105
2106    #[test]
2107    #[cfg(not(target_family = "unix"))]
2108    fn test_join_args_for_script_windows() {
2109        // Test with path containing spaces
2110        let args = vec![
2111            "-target",
2112            "x86_64-linux-gnu",
2113            "-L",
2114            "C:\\Users\\John Doe\\path",
2115        ];
2116        let result = join_args_for_script(&args);
2117        // The path with space should be quoted
2118        assert!(result.contains("\"C:\\Users\\John Doe\\path\""));
2119        // Simple args should not be quoted
2120        assert!(result.contains("-target"));
2121        assert!(!result.contains("\"-target\""));
2122    }
2123
2124    fn make_rustc_ver(major: u64, minor: u64, patch: u64) -> rustc_version::Version {
2125        rustc_version::Version::new(major, minor, patch)
2126    }
2127
2128    fn make_zig_ver(major: u64, minor: u64, patch: u64) -> semver::Version {
2129        semver::Version::new(major, minor, patch)
2130    }
2131
2132    fn run_filter(args: &[&str], target: Option<&str>, zig_ver: (u64, u64)) -> Vec<String> {
2133        let rustc_ver = make_rustc_ver(1, 80, 0);
2134        let zig_version = make_zig_ver(0, zig_ver.0, zig_ver.1);
2135        let target_info = TargetInfo::new(target.map(|s| s.to_string()).as_ref());
2136        filter_linker_args(
2137            args.iter().map(|s| s.to_string()),
2138            &rustc_ver,
2139            &zig_version,
2140            &target_info,
2141        )
2142    }
2143
2144    fn run_filter_one(arg: &str, target: Option<&str>, zig_ver: (u64, u64)) -> Vec<String> {
2145        run_filter(&[arg], target, zig_ver)
2146    }
2147
2148    fn run_filter_one_rustc(
2149        arg: &str,
2150        target: Option<&str>,
2151        zig_ver: (u64, u64),
2152        rustc_minor: u64,
2153    ) -> Vec<String> {
2154        let rustc_ver = make_rustc_ver(1, rustc_minor, 0);
2155        let zig_version = make_zig_ver(0, zig_ver.0, zig_ver.1);
2156        let target_info = TargetInfo::new(target.map(|s| s.to_string()).as_ref());
2157        filter_linker_args(
2158            std::iter::once(arg.to_string()),
2159            &rustc_ver,
2160            &zig_version,
2161            &target_info,
2162        )
2163    }
2164
2165    #[test]
2166    fn test_filter_common_replacements() {
2167        let linux = Some("x86_64-unknown-linux-gnu");
2168        // -lgcc_s -> -lunwind
2169        assert_eq!(run_filter_one("-lgcc_s", linux, (13, 0)), vec!["-lunwind"]);
2170        // --target= stripped (already passed via -target)
2171        assert!(run_filter_one("--target=x86_64-unknown-linux-gnu", linux, (13, 0)).is_empty());
2172        // -e<entry> transformed to -Wl,--entry=<entry>
2173        assert_eq!(
2174            run_filter_one("-emain", linux, (13, 0)),
2175            vec!["-Wl,--entry=main"]
2176        );
2177        // -export-* should NOT be transformed
2178        assert_eq!(
2179            run_filter_one("-export-dynamic", linux, (13, 0)),
2180            vec!["-export-dynamic"]
2181        );
2182    }
2183
2184    #[test]
2185    fn test_filter_compiler_builtins_removed() {
2186        for target in &["armv7-unknown-linux-gnueabihf", "x86_64-pc-windows-gnu"] {
2187            let result = run_filter_one(
2188                "/path/to/libcompiler_builtins-abc123.rlib",
2189                Some(target),
2190                (13, 0),
2191            );
2192            assert!(
2193                result.is_empty(),
2194                "compiler_builtins should be removed for {target}"
2195            );
2196        }
2197    }
2198
2199    #[test]
2200    fn test_filter_windows_gnu_args() {
2201        let gnu = Some("x86_64-pc-windows-gnu");
2202        // Args that should be removed entirely
2203        let removed: &[&str] = &[
2204            "-lwindows",
2205            "-l:libpthread.a",
2206            "-lgcc",
2207            "-Wl,--disable-auto-image-base",
2208            "-Wl,--dynamicbase",
2209            "-Wl,--large-address-aware",
2210            "-Wl,/path/to/list.def",
2211            "-Wl,C:\\path\\to\\list.def",
2212            "-lmsvcrt",
2213        ];
2214        for arg in removed {
2215            let result = run_filter_one(arg, gnu, (13, 0));
2216            assert!(result.is_empty(), "{arg} should be removed for windows-gnu");
2217        }
2218        // Args that get replaced
2219        let replaced: &[(&str, (u64, u64), &str)] = &[
2220            ("-lgcc_eh", (13, 0), "-lc++"),
2221            ("-Wl,-Bdynamic", (13, 0), "-Wl,-search_paths_first"),
2222        ];
2223        for (arg, zig_ver, expected) in replaced {
2224            let result = run_filter_one(arg, gnu, *zig_ver);
2225            assert_eq!(result, vec![*expected], "filter({arg})");
2226        }
2227        // -lgcc_eh kept on zig >= 0.14 for x86_64
2228        let result = run_filter_one("-lgcc_eh", gnu, (14, 0));
2229        assert_eq!(result, vec!["-lgcc_eh"]);
2230    }
2231
2232    #[test]
2233    fn test_filter_windows_gnu_rsbegin() {
2234        // i686: rsbegin.o filtered out
2235        let result = run_filter_one("/path/to/rsbegin.o", Some("i686-pc-windows-gnu"), (13, 0));
2236        assert!(result.is_empty());
2237        // x86_64: rsbegin.o kept
2238        let result = run_filter_one("/path/to/rsbegin.o", Some("x86_64-pc-windows-gnu"), (13, 0));
2239        assert_eq!(result, vec!["/path/to/rsbegin.o"]);
2240    }
2241
2242    #[test]
2243    fn test_filter_unsupported_linker_args() {
2244        let linux = Some("x86_64-unknown-linux-gnu");
2245        let removed: &[&str] = &[
2246            "-Wl,--no-undefined-version",
2247            "-Wl,-znostart-stop-gc",
2248            "-Wl,-plugin-opt=O2",
2249        ];
2250        for arg in removed {
2251            let result = run_filter_one(arg, linux, (13, 0));
2252            assert!(result.is_empty(), "{arg} should be removed");
2253        }
2254    }
2255
2256    #[test]
2257    fn test_filter_musl_args() {
2258        let musl = Some("x86_64-unknown-linux-musl");
2259        let removed: &[&str] = &["/path/self-contained/crt1.o", "-lc"];
2260        for arg in removed {
2261            let result = run_filter_one(arg, musl, (13, 0));
2262            assert!(result.is_empty(), "{arg} should be removed for musl");
2263        }
2264        // -Wl,-melf_i386 for i686 musl
2265        let result = run_filter_one("-Wl,-melf_i386", Some("i686-unknown-linux-musl"), (13, 0));
2266        assert!(result.is_empty());
2267        // liblibc removed for old rustc (<1.59), kept for new
2268        let result = run_filter_one_rustc("/path/to/liblibc-abc123.rlib", musl, (13, 0), 58);
2269        assert!(result.is_empty());
2270        let result = run_filter_one_rustc("/path/to/liblibc-abc123.rlib", musl, (13, 0), 59);
2271        assert_eq!(result, vec!["/path/to/liblibc-abc123.rlib"]);
2272    }
2273
2274    #[test]
2275    fn test_filter_march_args() {
2276        // (input, target, expected)
2277        let cases: &[(&str, &str, &[&str])] = &[
2278            // arm: removed
2279            ("-march=armv7-a", "armv7-unknown-linux-gnueabihf", &[]),
2280            // riscv64: replaced
2281            (
2282                "-march=rv64gc",
2283                "riscv64gc-unknown-linux-gnu",
2284                &["-march=generic_rv64"],
2285            ),
2286            // riscv32: replaced
2287            (
2288                "-march=rv32imac",
2289                "riscv32imac-unknown-none-elf",
2290                &["-march=generic_rv32"],
2291            ),
2292            // aarch64 armv: converted to -mcpu=generic
2293            (
2294                "-march=armv8.4-a",
2295                "aarch64-unknown-linux-gnu",
2296                &["-mcpu=generic"],
2297            ),
2298            // aarch64 armv with crypto: adds -Xassembler
2299            (
2300                "-march=armv8.4-a+crypto",
2301                "aarch64-unknown-linux-gnu",
2302                &[
2303                    "-mcpu=generic+crypto",
2304                    "-Xassembler",
2305                    "-march=armv8.4-a+crypto",
2306                ],
2307            ),
2308            // apple aarch64: uses apple cpu name
2309            (
2310                "-march=armv8.4-a",
2311                "aarch64-apple-darwin",
2312                &["-mcpu=apple_m1"],
2313            ),
2314        ];
2315        for (input, target, expected) in cases {
2316            let result = run_filter_one(input, Some(target), (13, 0));
2317            assert_eq!(&result, expected, "filter({input}, {target})");
2318        }
2319    }
2320
2321    #[test]
2322    fn test_filter_apple_args() {
2323        let darwin = Some("aarch64-apple-darwin");
2324        let result = run_filter_one("-Wl,-dylib", darwin, (13, 0));
2325        assert!(result.is_empty());
2326    }
2327
2328    #[test]
2329    fn test_filter_freebsd_libs_removed() {
2330        for lib in &["-lkvm", "-lmemstat", "-lprocstat", "-ldevstat"] {
2331            let result = run_filter_one(lib, Some("x86_64-unknown-freebsd"), (13, 0));
2332            assert!(result.is_empty(), "{lib} should be removed for freebsd");
2333        }
2334    }
2335
2336    #[test]
2337    fn test_filter_exported_symbols_list_two_arg_apple() {
2338        let result = run_filter(
2339            &[
2340                "-arch",
2341                "arm64",
2342                "-Wl,-exported_symbols_list",
2343                "-Wl,/tmp/rustcXXX/list",
2344                "-o",
2345                "output.dylib",
2346            ],
2347            Some("aarch64-apple-darwin"),
2348            (13, 0),
2349        );
2350        assert_eq!(result, vec!["-arch", "arm64", "-o", "output.dylib"]);
2351    }
2352
2353    #[test]
2354    fn test_filter_exported_symbols_list_two_arg_cross_platform() {
2355        let result = run_filter(
2356            &[
2357                "-arch",
2358                "arm64",
2359                "-Wl,-exported_symbols_list",
2360                "-Wl,C:\\Users\\RUNNER~1\\AppData\\Local\\Temp\\rustcXXX\\list",
2361                "-o",
2362                "output.dylib",
2363            ],
2364            None,
2365            (13, 0),
2366        );
2367        assert_eq!(result, vec!["-arch", "arm64", "-o", "output.dylib"]);
2368    }
2369
2370    #[test]
2371    fn test_filter_exported_symbols_list_single_arg_comma() {
2372        let result = run_filter(
2373            &[
2374                "-Wl,-exported_symbols_list,/tmp/rustcXXX/list",
2375                "-o",
2376                "output.dylib",
2377            ],
2378            Some("aarch64-apple-darwin"),
2379            (13, 0),
2380        );
2381        assert_eq!(result, vec!["-o", "output.dylib"]);
2382    }
2383
2384    #[test]
2385    fn test_filter_exported_symbols_list_not_filtered_zig_016() {
2386        let result = run_filter(
2387            &[
2388                "-Wl,-exported_symbols_list",
2389                "-Wl,/tmp/rustcXXX/list",
2390                "-o",
2391                "output.dylib",
2392            ],
2393            Some("aarch64-apple-darwin"),
2394            (16, 0),
2395        );
2396        assert_eq!(
2397            result,
2398            vec![
2399                "-Wl,-exported_symbols_list",
2400                "-Wl,/tmp/rustcXXX/list",
2401                "-o",
2402                "output.dylib"
2403            ]
2404        );
2405    }
2406
2407    #[test]
2408    fn test_filter_dynamic_list_two_arg() {
2409        let result = run_filter(
2410            &[
2411                "-Wl,--dynamic-list",
2412                "-Wl,/tmp/rustcXXX/list",
2413                "-o",
2414                "output.so",
2415            ],
2416            Some("x86_64-unknown-linux-gnu"),
2417            (13, 0),
2418        );
2419        assert_eq!(result, vec!["-o", "output.so"]);
2420    }
2421
2422    #[test]
2423    fn test_filter_dynamic_list_single_arg_comma() {
2424        let result = run_filter(
2425            &["-Wl,--dynamic-list,/tmp/rustcXXX/list", "-o", "output.so"],
2426            Some("x86_64-unknown-linux-gnu"),
2427            (13, 0),
2428        );
2429        assert_eq!(result, vec!["-o", "output.so"]);
2430    }
2431
2432    #[test]
2433    fn test_filter_preserves_normal_args() {
2434        let result = run_filter(
2435            &["-arch", "arm64", "-lSystem", "-lc", "-o", "output"],
2436            Some("aarch64-apple-darwin"),
2437            (13, 0),
2438        );
2439        assert_eq!(
2440            result,
2441            vec!["-arch", "arm64", "-lSystem", "-lc", "-o", "output"]
2442        );
2443    }
2444
2445    #[test]
2446    fn test_filter_skip_next_at_end_of_args() {
2447        let result = run_filter(
2448            &["-o", "output", "-Wl,-exported_symbols_list"],
2449            Some("aarch64-apple-darwin"),
2450            (13, 0),
2451        );
2452        assert_eq!(result, vec!["-o", "output"]);
2453    }
2454}