-
-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathzig.rs
More file actions
2619 lines (2434 loc) · 96.4 KB
/
Copy pathzig.rs
File metadata and controls
2619 lines (2434 loc) · 96.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::env;
use std::ffi::OsStr;
#[cfg(target_family = "unix")]
use std::fs::OpenOptions;
use std::io::Write;
#[cfg(target_family = "unix")]
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::process::{self, Command};
use std::str;
use std::sync::OnceLock;
use anyhow::{Context, Result, anyhow, bail};
use fs_err as fs;
use path_slash::PathBufExt;
use serde::Deserialize;
use target_lexicon::{Architecture, Environment, OperatingSystem, Triple};
use crate::linux::ARM_FEATURES_H;
use crate::macos::{LIBCHARSET_TBD, LIBICONV_TBD};
/// Zig linker wrapper
#[derive(Clone, Debug, clap::Subcommand)]
pub enum Zig {
/// `zig cc` wrapper
#[command(name = "cc")]
Cc {
/// `zig cc` arguments
#[arg(num_args = 1.., trailing_var_arg = true)]
args: Vec<String>,
},
/// `zig c++` wrapper
#[command(name = "c++")]
Cxx {
/// `zig c++` arguments
#[arg(num_args = 1.., trailing_var_arg = true)]
args: Vec<String>,
},
/// `zig ar` wrapper
#[command(name = "ar")]
Ar {
/// `zig ar` arguments
#[arg(num_args = 1.., trailing_var_arg = true)]
args: Vec<String>,
},
/// `zig ranlib` wrapper
#[command(name = "ranlib")]
Ranlib {
/// `zig ranlib` arguments
#[arg(num_args = 1.., trailing_var_arg = true)]
args: Vec<String>,
},
/// `zig lib` wrapper
#[command(name = "lib")]
Lib {
/// `zig lib` arguments
#[arg(num_args = 1.., trailing_var_arg = true)]
args: Vec<String>,
},
/// `zig dlltool` wrapper
#[command(name = "dlltool")]
Dlltool {
/// `zig dlltool` arguments
#[arg(num_args = 1.., trailing_var_arg = true)]
args: Vec<String>,
},
}
struct TargetInfo {
target: Option<String>,
}
impl TargetInfo {
fn new(target: Option<&String>) -> Self {
Self {
target: target.cloned(),
}
}
// Architecture helpers
fn is_arm(&self) -> bool {
self.target
.as_ref()
.map(|x| x.starts_with("arm"))
.unwrap_or_default()
}
fn is_aarch64(&self) -> bool {
self.target
.as_ref()
.map(|x| x.starts_with("aarch64"))
.unwrap_or_default()
}
fn is_aarch64_be(&self) -> bool {
self.target
.as_ref()
.map(|x| x.starts_with("aarch64_be"))
.unwrap_or_default()
}
fn is_i386(&self) -> bool {
self.target
.as_ref()
.map(|x| x.starts_with("i386"))
.unwrap_or_default()
}
fn is_i686(&self) -> bool {
self.target
.as_ref()
.map(|x| x.starts_with("i686") || x.starts_with("x86-"))
.unwrap_or_default()
}
fn is_riscv64(&self) -> bool {
self.target
.as_ref()
.map(|x| x.starts_with("riscv64"))
.unwrap_or_default()
}
fn is_riscv32(&self) -> bool {
self.target
.as_ref()
.map(|x| x.starts_with("riscv32"))
.unwrap_or_default()
}
fn is_mips32(&self) -> bool {
self.target
.as_ref()
.map(|x| x.starts_with("mips") && !x.starts_with("mips64"))
.unwrap_or_default()
}
// libc helpers
fn is_musl(&self) -> bool {
self.target
.as_ref()
.map(|x| x.contains("musl"))
.unwrap_or_default()
}
// Platform helpers
fn is_macos(&self) -> bool {
self.target
.as_ref()
.map(|x| x.contains("macos") || x.contains("maccatalyst"))
.unwrap_or_default()
}
fn is_darwin(&self) -> bool {
self.target
.as_ref()
.map(|x| x.contains("darwin"))
.unwrap_or_default()
}
fn is_apple_platform(&self) -> bool {
self.target
.as_ref()
.map(|x| {
x.contains("macos")
|| x.contains("darwin")
|| x.contains("ios")
|| x.contains("tvos")
|| x.contains("watchos")
|| x.contains("visionos")
|| x.contains("maccatalyst")
})
.unwrap_or_default()
}
fn is_ios(&self) -> bool {
self.target
.as_ref()
.map(|x| x.contains("ios") && !x.contains("visionos"))
.unwrap_or_default()
}
fn is_tvos(&self) -> bool {
self.target
.as_ref()
.map(|x| x.contains("tvos"))
.unwrap_or_default()
}
fn is_watchos(&self) -> bool {
self.target
.as_ref()
.map(|x| x.contains("watchos"))
.unwrap_or_default()
}
fn is_visionos(&self) -> bool {
self.target
.as_ref()
.map(|x| x.contains("visionos"))
.unwrap_or_default()
}
/// Returns the appropriate Apple CPU for the platform
fn apple_cpu(&self) -> &'static str {
if self.is_macos() || self.is_darwin() {
"apple_m1" // M-series for macOS
} else if self.is_visionos() {
"apple_m2" // M2 for Apple Vision Pro
} else if self.is_watchos() {
"apple_s5" // S-series for Apple Watch
} else if self.is_ios() || self.is_tvos() {
"apple_a14" // A-series for iOS/tvOS (iPhone 12 era - good baseline)
} else {
"generic"
}
}
fn is_freebsd(&self) -> bool {
self.target
.as_ref()
.map(|x| x.contains("freebsd"))
.unwrap_or_default()
}
fn is_windows_gnu(&self) -> bool {
self.target
.as_ref()
.map(|x| x.contains("windows-gnu"))
.unwrap_or_default()
}
fn is_windows_msvc(&self) -> bool {
self.target
.as_ref()
.map(|x| x.contains("windows-msvc"))
.unwrap_or_default()
}
fn is_ohos(&self) -> bool {
self.target
.as_ref()
.map(|x| x.contains("ohos"))
.unwrap_or_default()
}
}
impl Zig {
/// Execute the underlying zig command
pub fn execute(&self) -> Result<()> {
match self {
Zig::Cc { args } => self.execute_compiler("cc", args),
Zig::Cxx { args } => self.execute_compiler("c++", args),
Zig::Ar { args } => self.execute_tool("ar", args),
Zig::Ranlib { args } => self.execute_compiler("ranlib", args),
Zig::Lib { args } => self.execute_compiler("lib", args),
Zig::Dlltool { args } => self.execute_dlltool(args),
}
}
/// Execute zig dlltool command
/// Filter out unsupported options for older zig versions (< 0.12)
pub fn execute_dlltool(&self, cmd_args: &[String]) -> Result<()> {
let zig_version = Zig::zig_version()?;
let needs_filtering = zig_version.major == 0 && zig_version.minor < 12;
if !needs_filtering {
return self.execute_tool("dlltool", cmd_args);
}
// Filter out --no-leading-underscore, --temp-prefix, and -t (short form)
// These options are not supported by zig dlltool in versions < 0.12
let mut filtered_args = Vec::with_capacity(cmd_args.len());
let mut skip_next = false;
for arg in cmd_args {
if skip_next {
skip_next = false;
continue;
}
if arg == "--no-leading-underscore" {
continue;
}
if arg == "--temp-prefix" || arg == "-t" {
// Skip this arg and the next one (the value)
skip_next = true;
continue;
}
// Handle --temp-prefix=value and -t=value forms
if arg.starts_with("--temp-prefix=") || arg.starts_with("-t=") {
continue;
}
filtered_args.push(arg.clone());
}
self.execute_tool("dlltool", &filtered_args)
}
/// Execute zig cc/c++ command
pub fn execute_compiler(&self, cmd: &str, cmd_args: &[String]) -> Result<()> {
let target = cmd_args
.iter()
.position(|x| x == "-target")
.and_then(|index| cmd_args.get(index + 1));
let target_info = TargetInfo::new(target);
let rustc_ver = match env::var("CARGO_ZIGBUILD_RUSTC_VERSION") {
Ok(version) => version.parse()?,
Err(_) => rustc_version::version()?,
};
let zig_version = Zig::zig_version()?;
let mut new_cmd_args = Vec::with_capacity(cmd_args.len());
let mut skip_next_arg = false;
let mut seen_target = false;
for arg in cmd_args {
if skip_next_arg {
skip_next_arg = false;
continue;
}
// Our wrapper script already passes the correct -target;
// skip any duplicate -target from rustc to avoid conflicts
// (e.g. rustc passes arm64 which zig doesn't recognize for some targets)
if arg == "-target" {
if seen_target {
skip_next_arg = true;
continue;
}
seen_target = true;
}
let args = if arg.starts_with('@') && arg.ends_with("linker-arguments") {
vec![self.process_linker_response_file(
arg,
&rustc_ver,
&zig_version,
&target_info,
)?]
} else {
match self.filter_linker_arg(arg, &rustc_ver, &zig_version, &target_info) {
FilteredArg::Keep(filtered) => filtered,
FilteredArg::Skip => continue,
FilteredArg::SkipWithNext => {
skip_next_arg = true;
continue;
}
}
};
new_cmd_args.extend(args);
}
if target_info.is_mips32() {
// See https://github.com/ziglang/zig/issues/4925#issuecomment-1499823425
new_cmd_args.push("-Wl,-z,notext".to_string());
}
if target_info.is_windows_gnu() && (zig_version.major, zig_version.minor) >= (0, 16) {
new_cmd_args.push("-lcompiler_rt".to_string());
}
if self.has_undefined_dynamic_lookup(cmd_args) {
new_cmd_args.push("-Wl,-undefined=dynamic_lookup".to_string());
}
if target_info.is_macos() {
if self.should_add_libcharset(cmd_args, &zig_version) {
new_cmd_args.push("-lcharset".to_string());
}
self.add_macos_specific_args(&mut new_cmd_args, &zig_version)?;
}
// For Zig >= 0.15 with macOS, set SDKROOT environment variable
// if it exists, instead of passing --sysroot
let mut command = Self::command()?;
if (zig_version.major, zig_version.minor) >= (0, 15)
&& let Some(sdkroot) = Self::macos_sdk_root()
{
command.env("SDKROOT", sdkroot);
}
let mut child = command
.arg(cmd)
.args(new_cmd_args)
.spawn()
.with_context(|| format!("Failed to run `zig {cmd}`"))?;
let status = child.wait().expect("Failed to wait on zig child process");
if !status.success() {
process::exit(status.code().unwrap_or(1));
}
Ok(())
}
fn process_linker_response_file(
&self,
arg: &str,
rustc_ver: &rustc_version::Version,
zig_version: &semver::Version,
target_info: &TargetInfo,
) -> Result<String> {
// rustc passes arguments to linker via an @-file when arguments are too long
// See https://github.com/rust-lang/rust/issues/41190
// and https://github.com/rust-lang/rust/blob/87937d3b6c302dfedfa5c4b94d0a30985d46298d/compiler/rustc_codegen_ssa/src/back/link.rs#L1373-L1382
let content_bytes = fs::read(arg.trim_start_matches('@'))?;
let content = if target_info.is_windows_msvc() {
if content_bytes[0..2] != [255, 254] {
bail!(
"linker response file `{}` didn't start with a utf16 BOM",
&arg
);
}
let content_utf16: Vec<u16> = content_bytes[2..]
.chunks_exact(2)
.map(|a| u16::from_ne_bytes([a[0], a[1]]))
.collect();
String::from_utf16(&content_utf16).with_context(|| {
format!(
"linker response file `{}` didn't contain valid utf16 content",
&arg
)
})?
} else {
String::from_utf8(content_bytes).with_context(|| {
format!(
"linker response file `{}` didn't contain valid utf8 content",
&arg
)
})?
};
let mut link_args: Vec<_> = filter_linker_args(
content.split('\n').map(|s| s.to_string()),
rustc_ver,
zig_version,
target_info,
);
if self.has_undefined_dynamic_lookup(&link_args) {
link_args.push("-Wl,-undefined=dynamic_lookup".to_string());
}
if target_info.is_macos() && self.should_add_libcharset(&link_args, zig_version) {
link_args.push("-lcharset".to_string());
}
if target_info.is_windows_msvc() {
let new_content = link_args.join("\n");
let mut out = Vec::with_capacity((1 + new_content.len()) * 2);
// start the stream with a UTF-16 BOM
for c in std::iter::once(0xFEFF).chain(new_content.encode_utf16()) {
// encode in little endian
out.push(c as u8);
out.push((c >> 8) as u8);
}
fs::write(arg.trim_start_matches('@'), out)?;
} else {
fs::write(arg.trim_start_matches('@'), link_args.join("\n").as_bytes())?;
}
Ok(arg.to_string())
}
fn filter_linker_arg(
&self,
arg: &str,
rustc_ver: &rustc_version::Version,
zig_version: &semver::Version,
target_info: &TargetInfo,
) -> FilteredArg {
filter_linker_arg(arg, rustc_ver, zig_version, target_info)
}
}
enum FilteredArg {
Keep(Vec<String>),
Skip,
SkipWithNext,
}
fn filter_linker_args(
args: impl IntoIterator<Item = String>,
rustc_ver: &rustc_version::Version,
zig_version: &semver::Version,
target_info: &TargetInfo,
) -> Vec<String> {
let mut result = Vec::new();
let mut skip_next = false;
for arg in args {
if skip_next {
skip_next = false;
continue;
}
match filter_linker_arg(&arg, rustc_ver, zig_version, target_info) {
FilteredArg::Keep(filtered) => result.extend(filtered),
FilteredArg::Skip => {}
FilteredArg::SkipWithNext => {
skip_next = true;
}
}
}
result
}
fn filter_linker_arg(
arg: &str,
rustc_ver: &rustc_version::Version,
zig_version: &semver::Version,
target_info: &TargetInfo,
) -> FilteredArg {
if arg == "-lgcc_s" {
return FilteredArg::Keep(vec!["-lunwind".to_string()]);
} else if arg.starts_with("--target=") {
return FilteredArg::Skip;
} else if arg.starts_with("-e") && arg.len() > 2 && !arg.starts_with("-export") {
let entry = &arg[2..];
return FilteredArg::Keep(vec![format!("-Wl,--entry={}", entry)]);
}
if (target_info.is_arm() || target_info.is_windows_gnu())
&& arg.ends_with(".rlib")
&& arg.contains("libcompiler_builtins-")
{
return FilteredArg::Skip;
}
if target_info.is_windows_gnu() {
#[allow(clippy::if_same_then_else)]
if arg == "-lgcc_eh"
&& ((zig_version.major, zig_version.minor) < (0, 14) || target_info.is_i686())
{
return FilteredArg::Keep(vec!["-lc++".to_string()]);
} else if arg.ends_with("rsbegin.o") || arg.ends_with("rsend.o") {
if target_info.is_i686() {
return FilteredArg::Skip;
}
} else if arg == "-Wl,-Bdynamic" && (zig_version.major, zig_version.minor) >= (0, 11) {
return FilteredArg::Keep(vec!["-Wl,-search_paths_first".to_owned()]);
} else if arg == "-lwindows" || arg == "-l:libpthread.a" || arg == "-lgcc" {
return FilteredArg::Skip;
} else if arg == "-Wl,--disable-auto-image-base"
|| arg == "-Wl,--dynamicbase"
|| arg == "-Wl,--large-address-aware"
|| (arg.starts_with("-Wl,")
&& (arg.ends_with("/list.def") || arg.ends_with("\\list.def")))
{
return FilteredArg::Skip;
} else if arg == "-lmsvcrt" {
return FilteredArg::Skip;
}
} else if arg == "-Wl,--no-undefined-version"
|| arg == "-Wl,-znostart-stop-gc"
// See https://github.com/rust-lang/rust/pull/155453
|| arg == "-Wl,--fix-cortex-a53-843419"
|| arg.starts_with("-Wl,-plugin-opt")
{
return FilteredArg::Skip;
}
if target_info.is_musl() || target_info.is_ohos() {
if (arg.ends_with(".o") && arg.contains("self-contained") && arg.contains("crt"))
|| arg == "-Wl,-melf_i386"
{
return FilteredArg::Skip;
}
if rustc_ver.major == 1
&& rustc_ver.minor < 59
&& arg.ends_with(".rlib")
&& arg.contains("liblibc-")
{
return FilteredArg::Skip;
}
if arg == "-lc" {
return FilteredArg::Skip;
}
}
// zig cc only supports -Wp,-MD, -Wp,-MMD, and -Wp,-MT;
// strip all other -Wp, args (e.g. -Wp,-U_FORTIFY_SOURCE from CMake)
// https://github.com/ziglang/zig/blob/0.15.2/src/main.zig#L2798
if arg.starts_with("-Wp,")
&& !arg.starts_with("-Wp,-MD")
&& !arg.starts_with("-Wp,-MMD")
&& !arg.starts_with("-Wp,-MT")
{
return FilteredArg::Skip;
}
if arg.starts_with("-march=") {
if target_info.is_arm() || target_info.is_i386() {
return FilteredArg::Skip;
} else if target_info.is_riscv64() {
return FilteredArg::Keep(vec!["-march=generic_rv64".to_string()]);
} else if target_info.is_riscv32() {
return FilteredArg::Keep(vec!["-march=generic_rv32".to_string()]);
} else if arg.starts_with("-march=armv")
&& (target_info.is_aarch64() || target_info.is_aarch64_be())
{
let march_value = arg.strip_prefix("-march=").unwrap();
let features = if let Some(pos) = march_value.find('+') {
&march_value[pos..]
} else {
""
};
let base_cpu = if target_info.is_apple_platform() {
target_info.apple_cpu()
} else {
"generic"
};
let mut result = vec![format!("-mcpu={}{}", base_cpu, features)];
if features.contains("+crypto") {
result.append(&mut vec!["-Xassembler".to_owned(), arg.to_string()]);
}
return FilteredArg::Keep(result);
}
}
if target_info.is_apple_platform() {
if (zig_version.major, zig_version.minor) < (0, 16) {
if arg.starts_with("-Wl,-exported_symbols_list,") {
return FilteredArg::Skip;
}
if arg == "-Wl,-exported_symbols_list" {
return FilteredArg::SkipWithNext;
}
}
if arg == "-Wl,-dylib" {
return FilteredArg::Skip;
}
}
// Handle two-arg form on all platforms (cross-compilation from non-Apple hosts)
if (zig_version.major, zig_version.minor) < (0, 16) {
if arg == "-Wl,-exported_symbols_list" || arg == "-Wl,--dynamic-list" {
return FilteredArg::SkipWithNext;
}
if arg.starts_with("-Wl,-exported_symbols_list,") || arg.starts_with("-Wl,--dynamic-list,")
{
return FilteredArg::Skip;
}
}
if target_info.is_freebsd() {
let ignored_libs = ["-lkvm", "-lmemstat", "-lprocstat", "-ldevstat"];
if ignored_libs.contains(&arg) {
return FilteredArg::Skip;
}
}
FilteredArg::Keep(vec![arg.to_string()])
}
impl Zig {
fn has_undefined_dynamic_lookup(&self, args: &[String]) -> bool {
let undefined = args
.iter()
.position(|x| x == "-undefined")
.and_then(|i| args.get(i + 1));
matches!(undefined, Some(x) if x == "dynamic_lookup")
}
fn should_add_libcharset(&self, args: &[String], zig_version: &semver::Version) -> bool {
// See https://github.com/apple-oss-distributions/libiconv/blob/a167071feb7a83a01b27ec8d238590c14eb6faff/xcodeconfig/libiconv.xcconfig
if (zig_version.major, zig_version.minor) >= (0, 12) {
args.iter().any(|x| x == "-liconv") && !args.iter().any(|x| x == "-lcharset")
} else {
false
}
}
fn add_macos_specific_args(
&self,
new_cmd_args: &mut Vec<String>,
zig_version: &semver::Version,
) -> Result<()> {
let sdkroot = Self::macos_sdk_root();
if (zig_version.major, zig_version.minor) >= (0, 12) {
// Zig 0.12.0+ requires passing `--sysroot`
// However, for Zig 0.15+, we should use SDKROOT environment variable instead
// to avoid issues with library paths being interpreted relative to sysroot
if let Some(ref sdkroot) = sdkroot
&& (zig_version.major, zig_version.minor) < (0, 15)
{
new_cmd_args.push(format!("--sysroot={}", sdkroot.display()));
}
// For Zig >= 0.15, SDKROOT will be set as environment variable
}
if let Some(ref sdkroot) = sdkroot {
if (zig_version.major, zig_version.minor) < (0, 15) {
// For zig < 0.15, we need to explicitly add SDK paths with --sysroot
new_cmd_args.extend_from_slice(&[
"-isystem".to_string(),
format!("{}", sdkroot.join("usr").join("include").display()),
format!("-L{}", sdkroot.join("usr").join("lib").display()),
format!(
"-F{}",
sdkroot
.join("System")
.join("Library")
.join("Frameworks")
.display()
),
"-DTARGET_OS_IPHONE=0".to_string(),
]);
} else {
// For zig >= 0.15 with SDKROOT, we still need to add framework paths
// Use -iframework for framework header search
new_cmd_args.extend_from_slice(&[
"-isystem".to_string(),
format!("{}", sdkroot.join("usr").join("include").display()),
format!("-L{}", sdkroot.join("usr").join("lib").display()),
format!(
"-F{}",
sdkroot
.join("System")
.join("Library")
.join("Frameworks")
.display()
),
// Also add the SYSTEM framework search path
"-iframework".to_string(),
format!(
"{}",
sdkroot
.join("System")
.join("Library")
.join("Frameworks")
.display()
),
"-DTARGET_OS_IPHONE=0".to_string(),
]);
}
}
// Add the deps directory that contains `.tbd` files to the library search path
let cache_dir = cache_dir();
let deps_dir = cache_dir.join("deps");
fs::create_dir_all(&deps_dir)?;
write_tbd_files(&deps_dir)?;
new_cmd_args.push("-L".to_string());
new_cmd_args.push(format!("{}", deps_dir.display()));
Ok(())
}
/// Execute zig ar/ranlib command
pub fn execute_tool(&self, cmd: &str, cmd_args: &[String]) -> Result<()> {
let mut child = Self::command()?
.arg(cmd)
.args(cmd_args)
.spawn()
.with_context(|| format!("Failed to run `zig {cmd}`"))?;
let status = child.wait().expect("Failed to wait on zig child process");
if !status.success() {
process::exit(status.code().unwrap_or(1));
}
Ok(())
}
/// Build the zig command line
pub fn command() -> Result<Command> {
let (zig, zig_args) = Self::find_zig()?;
let mut cmd = Command::new(zig);
cmd.args(zig_args);
Ok(cmd)
}
fn zig_version() -> Result<semver::Version> {
static ZIG_VERSION: OnceLock<semver::Version> = OnceLock::new();
if let Some(version) = ZIG_VERSION.get() {
return Ok(version.clone());
}
// Check for cached version from environment variable first
if let Ok(version_str) = env::var("CARGO_ZIGBUILD_ZIG_VERSION")
&& let Ok(version) = semver::Version::parse(&version_str)
{
return Ok(ZIG_VERSION.get_or_init(|| version).clone());
}
let output = Self::command()?.arg("version").output()?;
let version_str =
str::from_utf8(&output.stdout).context("`zig version` didn't return utf8 output")?;
let version = semver::Version::parse(version_str.trim())?;
Ok(ZIG_VERSION.get_or_init(|| version).clone())
}
/// Search for `python -m ziglang` first and for `zig` second.
pub fn find_zig() -> Result<(PathBuf, Vec<String>)> {
static ZIG_PATH: OnceLock<(PathBuf, Vec<String>)> = OnceLock::new();
if let Some(cached) = ZIG_PATH.get() {
return Ok(cached.clone());
}
let result = Self::find_zig_python()
.or_else(|_| Self::find_zig_bin())
.context("Failed to find zig")?;
Ok(ZIG_PATH.get_or_init(|| result).clone())
}
/// Detect the plain zig binary
fn find_zig_bin() -> Result<(PathBuf, Vec<String>)> {
let zig_path = zig_path()?;
let output = Command::new(&zig_path).arg("version").output()?;
let version_str = str::from_utf8(&output.stdout).with_context(|| {
format!("`{} version` didn't return utf8 output", zig_path.display())
})?;
Self::validate_zig_version(version_str)?;
Ok((zig_path, Vec::new()))
}
/// Detect the Python ziglang package
fn find_zig_python() -> Result<(PathBuf, Vec<String>)> {
let python_path = python_path()?;
let output = Command::new(&python_path)
.args(["-m", "ziglang", "version"])
.output()?;
let version_str = str::from_utf8(&output.stdout).with_context(|| {
format!(
"`{} -m ziglang version` didn't return utf8 output",
python_path.display()
)
})?;
Self::validate_zig_version(version_str)?;
Ok((python_path, vec!["-m".to_string(), "ziglang".to_string()]))
}
fn validate_zig_version(version: &str) -> Result<()> {
let min_ver = semver::Version::new(0, 9, 0);
let version = semver::Version::parse(version.trim())?;
if version >= min_ver {
Ok(())
} else {
bail!(
"zig version {} is too old, need at least {}",
version,
min_ver
)
}
}
/// Find zig lib directory
pub fn lib_dir() -> Result<PathBuf> {
static LIB_DIR: OnceLock<PathBuf> = OnceLock::new();
if let Some(cached) = LIB_DIR.get() {
return Ok(cached.clone());
}
let (zig, zig_args) = Self::find_zig()?;
let zig_version = Self::zig_version()?;
let output = Command::new(zig).args(zig_args).arg("env").output()?;
let parse_zon_lib_dir = || -> Result<PathBuf> {
let output_str =
str::from_utf8(&output.stdout).context("`zig env` didn't return utf8 output")?;
let lib_dir = output_str
.find(".lib_dir")
.and_then(|idx| {
let bytes = output_str.as_bytes();
let mut start = idx;
while start < bytes.len() && bytes[start] != b'"' {
start += 1;
}
if start >= bytes.len() {
return None;
}
let mut end = start + 1;
while end < bytes.len() && bytes[end] != b'"' {
end += 1;
}
if end >= bytes.len() {
return None;
}
Some(&output_str[start + 1..end])
})
.context("Failed to parse lib_dir from `zig env` ZON output")?;
Ok(PathBuf::from(lib_dir))
};
let lib_dir = if zig_version >= semver::Version::new(0, 15, 0) {
parse_zon_lib_dir()?
} else {
serde_json::from_slice::<ZigEnv>(&output.stdout)
.map(|zig_env| PathBuf::from(zig_env.lib_dir))
.or_else(|_| parse_zon_lib_dir())?
};
Ok(LIB_DIR.get_or_init(|| lib_dir).clone())
}
fn add_env_if_missing<K, V>(command: &mut Command, name: K, value: V)
where
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
let command_env_contains_no_key =
|name: &K| !command.get_envs().any(|(key, _)| name.as_ref() == key);
if command_env_contains_no_key(&name) && env::var_os(&name).is_none() {
command.env(name, value);
}
}
pub(crate) fn apply_command_env(
manifest_path: Option<&Path>,
release: bool,
cargo: &cargo_options::CommonOptions,
cmd: &mut Command,
enable_zig_ar: bool,
) -> Result<()> {
// setup zig as linker
let cargo_config = cargo_config2::Config::load()?;
// Use targets from CLI args, or fall back to cargo config's build.target
let config_targets;
let raw_targets: &[String] = if cargo.target.is_empty() {
if let Some(targets) = &cargo_config.build.target {
config_targets = targets
.iter()
.map(|t| t.triple().to_string())
.collect::<Vec<_>>();
&config_targets
} else {
&cargo.target
}
} else {
&cargo.target
};
let rust_targets = raw_targets
.iter()
.map(|target| target.split_once('.').map(|(t, _)| t).unwrap_or(target))
.collect::<Vec<&str>>();
let rustc_meta = rustc_version::version_meta()?;
Self::add_env_if_missing(
cmd,
"CARGO_ZIGBUILD_RUSTC_VERSION",
rustc_meta.semver.to_string(),
);
let host_target = &rustc_meta.host;
for (parsed_target, raw_target) in rust_targets.iter().zip(raw_targets) {
let env_target = parsed_target.replace('-', "_");
let zig_wrapper = prepare_zig_linker(raw_target, &cargo_config)?;
if is_mingw_shell() {
let zig_cc = zig_wrapper.cc.to_slash_lossy();
let zig_cxx = zig_wrapper.cxx.to_slash_lossy();
Self::add_env_if_missing(cmd, format!("CC_{env_target}"), &*zig_cc);
Self::add_env_if_missing(cmd, format!("CXX_{env_target}"), &*zig_cxx);
if !parsed_target.contains("wasm") {
Self::add_env_if_missing(
cmd,
format!("CARGO_TARGET_{}_LINKER", env_target.to_uppercase()),
&*zig_cc,
);
}
} else {
Self::add_env_if_missing(cmd, format!("CC_{env_target}"), &zig_wrapper.cc);
Self::add_env_if_missing(cmd, format!("CXX_{env_target}"), &zig_wrapper.cxx);
if !parsed_target.contains("wasm") {
Self::add_env_if_missing(
cmd,
format!("CARGO_TARGET_{}_LINKER", env_target.to_uppercase()),
&zig_wrapper.cc,
);
}
}
Self::add_env_if_missing(cmd, format!("RANLIB_{env_target}"), &zig_wrapper.ranlib);
// Only setup AR when explicitly asked to
// because it need special executable name handling, see src/bin/cargo-zigbuild.rs
if enable_zig_ar {
if parsed_target.contains("msvc") {
Self::add_env_if_missing(cmd, format!("AR_{env_target}"), &zig_wrapper.lib);
} else {
Self::add_env_if_missing(cmd, format!("AR_{env_target}"), &zig_wrapper.ar);
}
}
Self::setup_os_deps(manifest_path, release, cargo)?;
let cmake_toolchain_file_env = format!("CMAKE_TOOLCHAIN_FILE_{env_target}");
if env::var_os(&cmake_toolchain_file_env).is_none()
&& env::var_os(format!("CMAKE_TOOLCHAIN_FILE_{parsed_target}")).is_none()
&& env::var_os("TARGET_CMAKE_TOOLCHAIN_FILE").is_none()
&& env::var_os("CMAKE_TOOLCHAIN_FILE").is_none()
&& let Ok(cmake_toolchain_file) =
Self::setup_cmake_toolchain(parsed_target, &zig_wrapper, enable_zig_ar)
{
cmd.env(cmake_toolchain_file_env, cmake_toolchain_file);
}
// On Windows, cmake defaults to the Visual Studio generator which ignores
// CMAKE_C_COMPILER from the toolchain file. Force Ninja to ensure zig cc
// is used for cross-compilation.
// See https://github.com/rust-cross/cargo-zigbuild/issues/174
if cfg!(target_os = "windows")
&& env::var_os("CMAKE_GENERATOR").is_none()
&& which::which("ninja").is_ok()
{
cmd.env("CMAKE_GENERATOR", "Ninja");
}
if raw_target.contains("windows-gnu") {
cmd.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
// Add the cache directory to PATH so rustc can find architecture-specific dlltool
// (e.g., x86_64-w64-mingw32-dlltool), but only if no system dlltool exists
// If system mingw-w64 dlltool exists, prefer it over zig's dlltool
let triple: Triple = parsed_target.parse().unwrap_or_else(|_| Triple::unknown());
if !has_system_dlltool(&triple.architecture) {
// zig_wrapper.ar lives in the per-exe wrapper dir
let wrapper_dir = zig_wrapper.ar.parent().unwrap();
let existing_path = env::var_os("PATH").unwrap_or_default();
let paths = std::iter::once(wrapper_dir.to_path_buf())
.chain(env::split_paths(&existing_path));
if let Ok(new_path) = env::join_paths(paths) {
cmd.env("PATH", new_path);
}
}
}
if raw_target.contains("apple-darwin")
&& let Some(sdkroot) = Self::macos_sdk_root()
&& env::var_os("PKG_CONFIG_SYSROOT_DIR").is_none()
{