cargo-zigbuild 0.24.0

Compile Cargo project with zig as linker
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
use std::path::Path;

use super::target_info::TargetInfo;

pub(crate) enum FilteredArg {
    Keep(Vec<String>),
    /// Keep this option and its following operand without filtering the operand.
    KeepWithNext,
    Skip,
    SkipWithNext,
}

/// Keep option/operand handling consistent across command-line and response-file args.
#[derive(Default)]
pub(crate) struct LinkerArgFilter {
    next: NextArg,
}

#[derive(Default)]
enum NextArg {
    #[default]
    Filter,
    Keep,
    Skip,
}

impl LinkerArgFilter {
    pub(crate) fn filter_arg(
        &mut self,
        arg: &str,
        rustc_ver: &rustc_version::Version,
        zig_version: &semver::Version,
        target_info: &TargetInfo,
    ) -> Vec<String> {
        match std::mem::take(&mut self.next) {
            NextArg::Keep => return vec![arg.to_owned()],
            NextArg::Skip => return vec![],
            NextArg::Filter => {}
        }
        match filter_linker_arg(arg, rustc_ver, zig_version, target_info) {
            FilteredArg::Keep(filtered) => filtered,
            FilteredArg::KeepWithNext => {
                self.next = NextArg::Keep;
                vec![arg.to_owned()]
            }
            FilteredArg::Skip => vec![],
            FilteredArg::SkipWithNext => {
                self.next = NextArg::Skip;
                vec![]
            }
        }
    }

    pub(crate) fn filter_args(
        &mut self,
        args: impl IntoIterator<Item = String>,
        rustc_ver: &rustc_version::Version,
        zig_version: &semver::Version,
        target_info: &TargetInfo,
    ) -> Vec<String> {
        let result = args
            .into_iter()
            .flat_map(|arg| self.filter_arg(&arg, rustc_ver, zig_version, target_info))
            .collect();
        if target_info.is_apple_platform() {
            dedup_apple_link_libs(result)
        } else {
            result
        }
    }
}

/// Deduplicate `-l` arguments for Apple targets, keeping the first occurrence.
///
/// ld64 ignores duplicate libraries, but Zig's Mach-O linker (since 0.14) emits
/// one `LC_LOAD_DYLIB` load command per `-l` flag, and newer macOS dyld refuses
/// to load binaries with duplicate linked dylibs.
/// See https://github.com/rust-cross/cargo-zigbuild/issues/457
pub(crate) fn dedup_apple_link_libs(args: Vec<String>) -> Vec<String> {
    let mut seen = std::collections::HashSet::new();
    args.into_iter()
        .filter(|arg| {
            if arg.starts_with("-l") && arg.len() > 2 {
                seen.insert(arg.clone())
            } else {
                true
            }
        })
        .collect()
}

pub(crate) fn filter_linker_arg(
    arg: &str,
    rustc_ver: &rustc_version::Version,
    zig_version: &semver::Version,
    target_info: &TargetInfo,
) -> FilteredArg {
    // Zig 0.12 and newer ignore rustc's linker optimization flag and warn about it.
    // Preserve it for older versions in case the linker honors the setting.
    if arg == "-Wl,-O1" && ((0, 12)..).contains(&(zig_version.major, zig_version.minor)) {
        return FilteredArg::Skip;
    }
    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)]);
    } else if let Some(sym) = arg.strip_prefix("-Wl,--undefined=") {
        // zig cc rejects `--undefined=SYM` as an unsupported linker arg, but
        // accepts the synonymous `-u SYM`; used e.g. by cargo-auditable
        // https://github.com/rust-cross/cargo-zigbuild/issues/162
        return FilteredArg::Keep(vec![format!("-Wl,-u,{sym}")]);
    }
    if 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 == "-lsynchronization" {
            // Zig doesn't ship a `synchronization.def` import library for
            // MinGW, but it does ship the API set that actually exports these
            // symbols (WaitOnAddress, WakeByAddress*, ...). Link against that
            // instead so we don't have to write into Zig's lib directory.
            // https://github.com/rust-cross/cargo-zigbuild/issues/484
            return FilteredArg::Keep(vec!["-lapi-ms-win-core-synch-l1-2-0".to_string()]);
        }
    } 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"
        // See https://github.com/rust-lang/rust/pull/162546
        || arg == "-Wl,--no-rosegment"
        || arg.starts_with("-Wl,-plugin-opt")
    {
        return FilteredArg::Skip;
    }

    // An input file that reached us through `-Wl,`.
    //
    // rustc passes a native static library bundled in an rlib as
    // `-Wl,--whole-archive -Wl,<path> -Wl,--no-whole-archive`, which is what a build
    // script asking for `link_lib_modifier("+whole-archive")` produces. cc and clang
    // forward a `-Wl,` value that is not an option to the linker as a positional
    // input; zig cc matches every `-Wl,` value against a list of linker flags it
    // knows and fails with `unsupported linker arg: <path>` instead. Passing it
    // positionally is the same thing the other drivers do, and leaves the
    // `--whole-archive` pair around it untouched.
    if let Some(path) = arg
        .strip_prefix("-Wl,")
        .filter(|path| !path.starts_with('-') && Path::new(path).is_file())
    {
        return FilteredArg::Keep(vec![path.to_owned()]);
    }
    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 base_cpu = if target_info.is_apple_platform() {
                target_info.apple_cpu()
            } else {
                "generic"
            };
            let (features, has_crypto) = map_aarch64_features(march_value);
            let mut result = vec![format!("-mcpu={base_cpu}{features}")];
            if has_crypto {
                result.append(&mut vec!["-Xassembler".to_owned(), arg.to_string()]);
            }
            return FilteredArg::Keep(result);
        } else {
            // -march values on the remaining architectures are CPU names,
            // e.g. -march=x86-64-v3
            let value = arg.strip_prefix("-march=").unwrap();
            return FilteredArg::Keep(vec![format!("-march={}", map_cpu_name(value, target_info))]);
        }
    }
    if let Some((flag @ ("-mcpu" | "-mtune"), value)) = arg.split_once('=') {
        if target_info.is_aarch64() || target_info.is_aarch64_be() {
            let cpu = value.split('+').next().unwrap();
            let (features, _) = map_aarch64_features(value);
            return FilteredArg::Keep(vec![format!(
                "{flag}={}{features}",
                map_cpu_name(cpu, target_info)
            )]);
        }
        return FilteredArg::Keep(vec![format!("{flag}={}", map_cpu_name(value, target_info))]);
    }
    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;
        }
    } else if arg == "-Wl,-exported_symbols_list" || arg == "-Wl,--dynamic-list" {
        // These files are operands, not positional linker inputs. In particular,
        // do not apply the `-Wl,<path>` rewrite to an existing symbols list (#479).
        return FilteredArg::KeepWithNext;
    }
    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()])
}

/// Unescape one line of a rustc linker response file.
///
/// rustc writes linker response files for non-MSVC linkers one argument per
/// line, escaping each `\` and each space with a backslash (the GNU ld
/// convention, see `Escape` in rustc_codegen_ssa's `back/link.rs`). A backslash
/// followed by any character yields that character; a trailing one stays
/// literal.
pub(crate) fn unescape_linker_response_line(line: &str) -> String {
    let mut unescaped = String::with_capacity(line.len());
    let mut chars = line.chars();
    while let Some(c) = chars.next() {
        if c == '\\'
            && let Some(next) = chars.next()
        {
            unescaped.push(next);
        } else {
            unescaped.push(c);
        }
    }
    unescaped
}

/// Quote one linker argument for a single line of a response file as zig reads
/// it.
///
/// zig parses response files with the Windows command line rules
/// (`std.process.Args.ArgIteratorGeneral` in zig's std), so arguments are
/// written Windows style, as in Rust std's `make_command_line`: bare if they
/// have no whitespace and no `"` or `'`, and do not start with `#` (the
/// iterator splits on whitespace, groups by quotes, and with response file
/// comments enabled skips a token starting with `#`); otherwise inside double
/// quotes with `\"` escaped and backslashes doubled right before a quote.
///
/// A `'` cannot be preserved whatever is written: zig reads response files with
/// `single_quotes` enabled, so it is always consumed as a quote (and `\'`
/// decodes to `"`). Arguments containing one are written best effort.
pub(crate) fn quote_linker_response_arg(arg: &str) -> String {
    let needs_quoting = arg.is_empty()
        || arg.starts_with('#')
        || arg
            .chars()
            .any(|c| c.is_whitespace() || c == '"' || c == '\'');
    if !needs_quoting {
        return arg.to_string();
    }
    let mut quoted = String::with_capacity(arg.len() + 2);
    quoted.push('"');
    let mut backslashes = 0;
    for c in arg.chars() {
        match c {
            '\\' => backslashes += 1,
            '"' => {
                // n backslashes before a quote are written as 2n+1 so the
                // reader emits n of them plus the quote itself
                for _ in 0..2 * backslashes + 1 {
                    quoted.push('\\');
                }
                backslashes = 0;
                quoted.push('"');
            }
            _ => {
                for _ in 0..backslashes {
                    quoted.push('\\');
                }
                backslashes = 0;
                quoted.push(c);
            }
        }
    }
    // the closing quote also doubles the backslashes before it
    for _ in 0..2 * backslashes {
        quoted.push('\\');
    }
    quoted.push('"');
    quoted
}

/// Map the CPU-name part of a GCC/clang `-mcpu`/`-mtune`/`-march` value to
/// zig's spelling: zig uses underscores where GCC/clang use dashes
/// (e.g. cortex-a53 -> cortex_a53, x86-64-v3 -> x86_64_v3), and powerpc
/// CPUs use the LLVM names (e.g. power9 -> pwr9). Any `+ext` suffixes are
/// preserved as-is; zig-spelled values pass through unchanged.
fn map_cpu_name(value: &str, target_info: &TargetInfo) -> String {
    if target_info.is_s390x() {
        // zig s390x CPU specs like z10-vector use `-` for feature
        // subtraction, and GCC/clang s390x CPU names contain no dashes
        return value.to_string();
    }
    let (cpu, features) = match value.find('+') {
        Some(pos) => value.split_at(pos),
        None => (value, ""),
    };
    if target_info.is_powerpc() {
        let cpu = match cpu {
            "powerpc" => "ppc".to_string(),
            "powerpc64" => "ppc64".to_string(),
            "powerpc64le" => "ppc64le".to_string(),
            _ => match cpu.strip_prefix("power") {
                Some(n) if n.starts_with(|c: char| c.is_ascii_digit()) => format!("pwr{n}"),
                _ => cpu.to_string(),
            },
        };
        return format!("{cpu}{features}");
    }
    format!("{}{features}", cpu.replace('-', "_"))
}

/// Convert the `+ext` suffixes of a GCC/clang aarch64 `-march`/`-mcpu` value
/// (e.g. `armv8.2-a+sve+nofp16`) into zig's feature syntax (`+sve-fullfp16`).
/// Returns the feature string and whether `+crypto` was requested.
fn map_aarch64_features(value: &str) -> (String, bool) {
    let mut extensions = value.split('+');
    let _cpu_or_arch = extensions.next();
    let mut features = String::new();
    let mut has_crypto = false;
    for ext in extensions.filter(|e| !e.is_empty() && *e != "none") {
        has_crypto |= ext == "crypto";
        // GCC/clang spell disabling an extension `+no<ext>`,
        // zig's -mcpu spells it `-<feature>`
        let (sign, name) = match ext.strip_prefix("no") {
            Some(name) if !name.is_empty() => ('-', name),
            _ => ('+', ext),
        };
        features.push(sign);
        // zig spells multi-word feature names with underscores
        // (e.g. sve2_aes) and parses `-` as feature subtraction
        for c in map_aarch64_arch_extension(name).chars() {
            features.push(if c == '-' { '_' } else { c });
        }
    }
    (features, has_crypto)
}

/// Map GCC/clang aarch64 `-march` arch-extension names to the LLVM feature
/// names understood by zig's `-mcpu` parser, e.g. `fp16` -> `fullfp16`
///
/// The mapping comes from the `ExtensionWithMArch` definitions in
/// https://github.com/llvm/llvm-project/blob/main/llvm/lib/Target/AArch64/AArch64Features.td
fn map_aarch64_arch_extension(ext: &str) -> &str {
    match ext {
        "fp" => "fp-armv8",
        "fp16" => "fullfp16",
        "simd" => "neon",
        "profile" => "spe",
        "rng" => "rand",
        "memtag" => "mte",
        "pmuv3" => "perfmon",
        "jscvt" => "jsconv",
        "fcma" => "complxnum",
        "predres2" => "specres2",
        _ => ext,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_rustc_ver(major: u64, minor: u64, patch: u64) -> rustc_version::Version {
        rustc_version::Version::new(major, minor, patch)
    }

    fn make_zig_ver(major: u64, minor: u64, patch: u64) -> semver::Version {
        semver::Version::new(major, minor, patch)
    }

    fn run_filter(args: &[&str], target: Option<&str>, zig_ver: (u64, u64)) -> Vec<String> {
        let rustc_ver = make_rustc_ver(1, 80, 0);
        let zig_version = make_zig_ver(0, zig_ver.0, zig_ver.1);
        let target_info = TargetInfo::new(target.map(|s| s.to_string()).as_ref());
        LinkerArgFilter::default().filter_args(
            args.iter().map(|s| s.to_string()),
            &rustc_ver,
            &zig_version,
            &target_info,
        )
    }

    fn run_filter_one(arg: &str, target: Option<&str>, zig_ver: (u64, u64)) -> Vec<String> {
        run_filter(&[arg], target, zig_ver)
    }

    fn run_filter_one_rustc(
        arg: &str,
        target: Option<&str>,
        zig_ver: (u64, u64),
        rustc_minor: u64,
    ) -> Vec<String> {
        let rustc_ver = make_rustc_ver(1, rustc_minor, 0);
        let zig_version = make_zig_ver(0, zig_ver.0, zig_ver.1);
        let target_info = TargetInfo::new(target.map(|s| s.to_string()).as_ref());
        LinkerArgFilter::default().filter_args(
            std::iter::once(arg.to_string()),
            &rustc_ver,
            &zig_version,
            &target_info,
        )
    }

    #[test]
    fn test_filter_deprecated_linker_optimization() {
        for target in ["x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu"] {
            for version in [(12, 0), (13, 0), (14, 1), (15, 2), (16, 0), (17, 0)] {
                assert_eq!(
                    run_filter(
                        &[
                            "-O3",
                            "-Wl,-O1",
                            "-Wl,-O2",
                            "-Wl,--gc-sections",
                            "-o",
                            "output"
                        ],
                        Some(target),
                        version,
                    ),
                    vec!["-O3", "-Wl,-O2", "-Wl,--gc-sections", "-o", "output"]
                );
            }
            for version in [(10, 0), (11, 0)] {
                assert_eq!(
                    run_filter_one("-Wl,-O1", Some(target), version),
                    vec!["-Wl,-O1"]
                );
            }
        }
    }

    #[test]
    fn test_filter_common_replacements() {
        let linux = Some("x86_64-unknown-linux-gnu");
        // -lgcc_s -> -lunwind
        assert_eq!(run_filter_one("-lgcc_s", linux, (13, 0)), vec!["-lunwind"]);
        // --target= stripped (already passed via -target)
        assert!(run_filter_one("--target=x86_64-unknown-linux-gnu", linux, (13, 0)).is_empty());
        // -e<entry> transformed to -Wl,--entry=<entry>
        assert_eq!(
            run_filter_one("-emain", linux, (13, 0)),
            vec!["-Wl,--entry=main"]
        );
        // -export-* should NOT be transformed
        assert_eq!(
            run_filter_one("-export-dynamic", linux, (13, 0)),
            vec!["-export-dynamic"]
        );
    }

    #[test]
    fn test_filter_compiler_builtins_removed() {
        for target in &["i686-pc-windows-gnu", "x86_64-pc-windows-gnu"] {
            let result = run_filter_one(
                "/path/to/libcompiler_builtins-abc123.rlib",
                Some(target),
                (13, 0),
            );
            assert!(
                result.is_empty(),
                "compiler_builtins should be removed for {target}"
            );
        }
    }

    #[test]
    fn test_filter_arm_compiler_builtins_preserved() {
        let arg = "/path/to/libcompiler_builtins-abc123.rlib";
        for target in &[
            "arm-unknown-linux-gnueabihf",
            "armv7-unknown-linux-gnueabihf",
            "armv7-unknown-linux-musleabi",
        ] {
            assert_eq!(
                run_filter_one(arg, Some(target), (17, 0)),
                vec![arg],
                "compiler_builtins should be preserved for {target}"
            );
        }
    }

    #[test]
    fn test_filter_windows_gnu_args() {
        let gnu = Some("x86_64-pc-windows-gnu");
        // Args that should be removed entirely
        let removed: &[&str] = &[
            "-lwindows",
            "-l:libpthread.a",
            "-lgcc",
            "-Wl,--disable-auto-image-base",
            "-Wl,--dynamicbase",
            "-Wl,--large-address-aware",
            "-Wl,/path/to/list.def",
            "-Wl,C:\\path\\to\\list.def",
            "-lmsvcrt",
        ];
        for arg in removed {
            let result = run_filter_one(arg, gnu, (13, 0));
            assert!(result.is_empty(), "{arg} should be removed for windows-gnu");
        }
        // Args that get replaced
        let replaced: &[(&str, (u64, u64), &str)] = &[
            ("-lgcc_eh", (13, 0), "-lc++"),
            ("-Wl,-Bdynamic", (13, 0), "-Wl,-search_paths_first"),
            (
                "-lsynchronization",
                (13, 0),
                "-lapi-ms-win-core-synch-l1-2-0",
            ),
        ];
        for (arg, zig_ver, expected) in replaced {
            let result = run_filter_one(arg, gnu, *zig_ver);
            assert_eq!(result, vec![*expected], "filter({arg})");
        }
        // -lgcc_eh kept on zig >= 0.14 for x86_64
        let result = run_filter_one("-lgcc_eh", gnu, (14, 0));
        assert_eq!(result, vec!["-lgcc_eh"]);
    }

    #[test]
    fn test_filter_windows_gnu_rsbegin() {
        // i686: rsbegin.o filtered out
        let result = run_filter_one("/path/to/rsbegin.o", Some("i686-pc-windows-gnu"), (13, 0));
        assert!(result.is_empty());
        // x86_64: rsbegin.o kept
        let result = run_filter_one("/path/to/rsbegin.o", Some("x86_64-pc-windows-gnu"), (13, 0));
        assert_eq!(result, vec!["/path/to/rsbegin.o"]);
    }

    #[test]
    fn test_filter_unsupported_linker_args() {
        let linux = Some("x86_64-unknown-linux-gnu");
        let removed: &[&str] = &[
            "-Wl,--no-undefined-version",
            "-Wl,-znostart-stop-gc",
            "-Wl,--fix-cortex-a53-843419",
            "-Wl,--no-rosegment",
            "-Wl,-plugin-opt=O2",
        ];
        for arg in removed {
            let result = run_filter_one(arg, linux, (13, 0));
            assert!(result.is_empty(), "{arg} should be removed");
        }
    }

    #[test]
    fn test_filter_undefined_arg() {
        let linux = Some("x86_64-unknown-linux-gnu");
        // `--undefined=SYM` is rewritten to the `-u SYM` synonym zig supports
        let result = run_filter_one("-Wl,--undefined=AUDITABLE_VERSION_INFO", linux, (13, 0));
        assert_eq!(result, vec!["-Wl,-u,AUDITABLE_VERSION_INFO"]);
        // macOS `-undefined dynamic_lookup` (single dash) must not match
        let result = run_filter_one(
            "-Wl,-undefined=dynamic_lookup",
            Some("aarch64-apple-darwin"),
            (13, 0),
        );
        assert_eq!(result, vec!["-Wl,-undefined=dynamic_lookup"]);
    }

    #[test]
    fn test_filter_wp_args() {
        let linux = Some("x86_64-unknown-linux-gnu");
        // Unsupported -Wp, args should be removed
        for arg in &[
            "-Wp,-U_FORTIFY_SOURCE",
            "-Wp,-DFOO=1",
            "-Wp,-MF,/tmp/t.d",
            "-Wp,-MQ,foo",
            "-Wp,-MP",
        ] {
            let result = run_filter_one(arg, linux, (13, 0));
            assert!(result.is_empty(), "{arg} should be removed");
        }
        // Supported -Wp, args should be kept (-MD, -MMD, -MT)
        for arg in &["-Wp,-MD,/tmp/test.d", "-Wp,-MMD,/tmp/test.d", "-Wp,-MT,foo"] {
            let result = run_filter_one(arg, linux, (13, 0));
            assert_eq!(result, vec![*arg], "{arg} should be kept");
        }
        // bare -U and -D should be kept (zig cc supports them directly)
        let result = run_filter_one("-U_FORTIFY_SOURCE", linux, (13, 0));
        assert_eq!(result, vec!["-U_FORTIFY_SOURCE"]);
        let result = run_filter_one("-DFOO=1", linux, (13, 0));
        assert_eq!(result, vec!["-DFOO=1"]);
    }

    #[test]
    fn test_filter_musl_args() {
        let musl = Some("x86_64-unknown-linux-musl");
        let removed: &[&str] = &["/path/self-contained/crt1.o", "-lc"];
        for arg in removed {
            let result = run_filter_one(arg, musl, (13, 0));
            assert!(result.is_empty(), "{arg} should be removed for musl");
        }
        // -Wl,-melf_i386 for i686 musl
        let result = run_filter_one("-Wl,-melf_i386", Some("i686-unknown-linux-musl"), (13, 0));
        assert!(result.is_empty());
        // liblibc removed for old rustc (<1.59), kept for new
        let result = run_filter_one_rustc("/path/to/liblibc-abc123.rlib", musl, (13, 0), 58);
        assert!(result.is_empty());
        let result = run_filter_one_rustc("/path/to/liblibc-abc123.rlib", musl, (13, 0), 59);
        assert_eq!(result, vec!["/path/to/liblibc-abc123.rlib"]);
    }

    #[test]
    fn test_filter_march_args() {
        // (input, target, expected)
        let cases: &[(&str, &str, &[&str])] = &[
            // arm: removed
            ("-march=armv7-a", "armv7-unknown-linux-gnueabihf", &[]),
            // riscv64: replaced
            (
                "-march=rv64gc",
                "riscv64gc-unknown-linux-gnu",
                &["-march=generic_rv64"],
            ),
            // riscv32: replaced
            (
                "-march=rv32imac",
                "riscv32imac-unknown-none-elf",
                &["-march=generic_rv32"],
            ),
            // aarch64 armv: converted to -mcpu=generic
            (
                "-march=armv8.4-a",
                "aarch64-unknown-linux-gnu",
                &["-mcpu=generic"],
            ),
            // aarch64 armv with crypto: adds -Xassembler
            (
                "-march=armv8.4-a+crypto",
                "aarch64-unknown-linux-gnu",
                &[
                    "-mcpu=generic+crypto",
                    "-Xassembler",
                    "-march=armv8.4-a+crypto",
                ],
            ),
            // apple aarch64: uses apple cpu name
            (
                "-march=armv8.4-a",
                "aarch64-apple-darwin",
                &["-mcpu=apple_m1"],
            ),
            // aarch64: GCC/clang extension names mapped to LLVM feature names
            // https://github.com/rust-cross/cargo-zigbuild/issues/456
            (
                "-march=armv8.2-a+sve+fp16",
                "aarch64-unknown-linux-musl",
                &["-mcpu=generic+sve+fullfp16"],
            ),
            (
                "-march=armv8.2-a+simd+profile+rng+memtag",
                "aarch64-unknown-linux-gnu",
                &["-mcpu=generic+neon+spe+rand+mte"],
            ),
            // aarch64: dashed feature names use underscores in zig,
            // where `-` would mean feature subtraction
            (
                "-march=armv9-a+sve2-aes+fp",
                "aarch64-unknown-linux-gnu",
                &["-mcpu=generic+sve2_aes+fp_armv8"],
            ),
            // aarch64: `+no<ext>` disables a feature
            (
                "-march=armv8.2-a+nofp16+nosimd",
                "aarch64-unknown-linux-gnu",
                &["-mcpu=generic-fullfp16-neon"],
            ),
            // x86-64: -march values are CPU names, spelled with underscores in zig
            (
                "-march=x86-64-v3",
                "x86_64-unknown-linux-gnu",
                &["-march=x86_64_v3"],
            ),
            (
                "-march=haswell",
                "x86_64-unknown-linux-gnu",
                &["-march=haswell"],
            ),
        ];
        for (input, target, expected) in cases {
            let result = run_filter_one(input, Some(target), (13, 0));
            assert_eq!(&result, expected, "filter({input}, {target})");
        }
    }

    #[test]
    fn test_filter_mcpu_mtune_args() {
        // (input, target, expected)
        let cases: &[(&str, &str, &[&str])] = &[
            // zig spells CPU names with underscores
            (
                "-mcpu=cortex-a53",
                "aarch64-unknown-linux-gnu",
                &["-mcpu=cortex_a53"],
            ),
            (
                "-mcpu=cortex-a7",
                "arm-unknown-linux-gnueabihf",
                &["-mcpu=cortex_a7"],
            ),
            (
                "-mtune=x86-64-v3",
                "x86_64-unknown-linux-gnu",
                &["-mtune=x86_64_v3"],
            ),
            // aarch64 -mcpu arch extensions are mapped like -march ones
            (
                "-mcpu=cortex-a53+crypto+nofp16",
                "aarch64-unknown-linux-gnu",
                &["-mcpu=cortex_a53+crypto-fullfp16"],
            ),
            // powerpc CPU names use the LLVM spellings
            (
                "-mcpu=power9",
                "powerpc64le-unknown-linux-gnu",
                &["-mcpu=pwr9"],
            ),
            (
                "-mcpu=powerpc64le",
                "powerpc64le-unknown-linux-gnu",
                &["-mcpu=ppc64le"],
            ),
            // zig-spelled values pass through unchanged: `-` after a `+` is
            // zig's feature subtraction, and s390x specs like z10-vector are
            // never rewritten
            (
                "-mcpu=generic+v6+strict_align+vfp2-d32",
                "arm-unknown-linux-gnueabihf",
                &["-mcpu=generic+v6+strict_align+vfp2-d32"],
            ),
            (
                "-mcpu=z10-vector",
                "s390x-unknown-linux-gnu",
                &["-mcpu=z10-vector"],
            ),
        ];
        for (input, target, expected) in cases {
            let result = run_filter_one(input, Some(target), (13, 0));
            assert_eq!(&result, expected, "filter({input}, {target})");
        }
    }

    #[test]
    fn test_filter_apple_args() {
        let darwin = Some("aarch64-apple-darwin");
        let result = run_filter_one("-Wl,-dylib", darwin, (13, 0));
        assert!(result.is_empty());
    }

    #[test]
    fn test_dedup_apple_duplicate_libs() {
        // See https://github.com/rust-cross/cargo-zigbuild/issues/457
        let darwin = Some("aarch64-apple-darwin");
        let result = run_filter(
            &[
                "-lobjc",
                "-framework",
                "AppKit",
                "-lobjc",
                "-liconv",
                "-lobjc",
                "main.o",
            ],
            darwin,
            (16, 0),
        );
        assert_eq!(
            result,
            vec!["-lobjc", "-framework", "AppKit", "-liconv", "main.o"]
        );
        // duplicates are kept on non-Apple targets where link order can matter
        let result = run_filter(
            &["-lfoo", "-lfoo"],
            Some("x86_64-unknown-linux-gnu"),
            (16, 0),
        );
        assert_eq!(result, vec!["-lfoo", "-lfoo"]);
    }

    #[test]
    fn test_filter_freebsd_libs_removed() {
        for lib in &["-lkvm", "-lmemstat", "-lprocstat", "-ldevstat"] {
            let result = run_filter_one(lib, Some("x86_64-unknown-freebsd"), (13, 0));
            assert!(result.is_empty(), "{lib} should be removed for freebsd");
        }
    }

    #[test]
    fn test_filter_exported_symbols_list_two_arg_apple() {
        let result = run_filter(
            &[
                "-arch",
                "arm64",
                "-Wl,-exported_symbols_list",
                "-Wl,/tmp/rustcXXX/list",
                "-o",
                "output.dylib",
            ],
            Some("aarch64-apple-darwin"),
            (13, 0),
        );
        assert_eq!(result, vec!["-arch", "arm64", "-o", "output.dylib"]);
    }

    #[test]
    fn test_filter_exported_symbols_list_two_arg_cross_platform() {
        let result = run_filter(
            &[
                "-arch",
                "arm64",
                "-Wl,-exported_symbols_list",
                "-Wl,C:\\Users\\RUNNER~1\\AppData\\Local\\Temp\\rustcXXX\\list",
                "-o",
                "output.dylib",
            ],
            None,
            (13, 0),
        );
        assert_eq!(result, vec!["-arch", "arm64", "-o", "output.dylib"]);
    }

    #[test]
    fn test_filter_exported_symbols_list_single_arg_comma() {
        let result = run_filter(
            &[
                "-Wl,-exported_symbols_list,/tmp/rustcXXX/list",
                "-o",
                "output.dylib",
            ],
            Some("aarch64-apple-darwin"),
            (13, 0),
        );
        assert_eq!(result, vec!["-o", "output.dylib"]);
    }

    #[test]
    fn test_filter_exported_symbols_list_not_filtered_zig_016() {
        let dir = tempfile::tempdir().unwrap();
        let list = dir.path().join("list");
        std::fs::write(&list, "_hello\n").unwrap();
        let list_arg = format!("-Wl,{}", list.display());
        let result = run_filter(
            &[
                "-Wl,-exported_symbols_list",
                &list_arg,
                "-o",
                "output.dylib",
            ],
            Some("aarch64-apple-darwin"),
            (16, 0),
        );
        assert_eq!(
            result,
            vec![
                "-Wl,-exported_symbols_list",
                &list_arg,
                "-o",
                "output.dylib"
            ]
        );
    }

    #[test]
    fn test_filter_dynamic_list_two_arg() {
        let result = run_filter(
            &[
                "-Wl,--dynamic-list",
                "-Wl,/tmp/rustcXXX/list",
                "-o",
                "output.so",
            ],
            Some("x86_64-unknown-linux-gnu"),
            (13, 0),
        );
        assert_eq!(result, vec!["-o", "output.so"]);
    }

    #[test]
    fn test_filter_dynamic_list_single_arg_comma() {
        let result = run_filter(
            &["-Wl,--dynamic-list,/tmp/rustcXXX/list", "-o", "output.so"],
            Some("x86_64-unknown-linux-gnu"),
            (13, 0),
        );
        assert_eq!(result, vec!["-o", "output.so"]);
    }

    #[test]
    fn test_filter_preserves_normal_args() {
        let result = run_filter(
            &["-arch", "arm64", "-lSystem", "-lc", "-o", "output"],
            Some("aarch64-apple-darwin"),
            (13, 0),
        );
        assert_eq!(
            result,
            vec!["-arch", "arm64", "-lSystem", "-lc", "-o", "output"]
        );
    }

    #[test]
    fn test_filter_skip_next_at_end_of_args() {
        let result = run_filter(
            &["-o", "output", "-Wl,-exported_symbols_list"],
            Some("aarch64-apple-darwin"),
            (13, 0),
        );
        assert_eq!(result, vec!["-o", "output"]);
    }

    #[test]
    fn test_filter_wl_path_becomes_positional() {
        let dir = tempfile::tempdir().unwrap();
        let archive = dir.path().join("libtree-sitter-bash.a");
        std::fs::write(&archive, b"").unwrap();
        let archive = archive.to_str().unwrap();

        // How rustc passes a static library bundled in an rlib with `+whole-archive`.
        let result = run_filter(
            &[
                "-Wl,--whole-archive",
                &format!("-Wl,{archive}"),
                "-Wl,--no-whole-archive",
            ],
            Some("x86_64-unknown-linux-musl"),
            (13, 0),
        );
        assert_eq!(
            result,
            vec!["-Wl,--whole-archive", archive, "-Wl,--no-whole-archive"]
        );
    }

    #[test]
    fn test_filter_leaves_other_wl_args_alone() {
        let linux = Some("x86_64-unknown-linux-gnu");
        // An option, not an input file.
        assert_eq!(
            run_filter_one("-Wl,-rpath,/usr/lib", linux, (13, 0)),
            vec!["-Wl,-rpath,/usr/lib"]
        );
        // A path that is not there is not an input file either.
        assert_eq!(
            run_filter_one("-Wl,/no/such/libfoo.a", linux, (13, 0)),
            vec!["-Wl,/no/such/libfoo.a"]
        );
    }

    #[test]
    fn test_unescape_linker_response_line() {
        // rustc escapes each `\` and space with a backslash; a path with a
        // space is split by zig without the unescaping
        assert_eq!(
            unescape_linker_response_line(r#"C:\\Users\\John\ Doe\\libfoo.rlib"#),
            r#"C:\Users\John Doe\libfoo.rlib"#
        );
        // a trailing backslash has nothing following it to unescape
        assert_eq!(
            unescape_linker_response_line(r#"C:\\path\\"#),
            r#"C:\path\"#
        );
        // an embedded quote is not escaped by rustc on this path
        assert_eq!(unescape_linker_response_line(r#"C:\\fo"o"#), r#"C:\fo"o"#);
        assert_eq!(unescape_linker_response_line("-lfoo"), "-lfoo");
        assert_eq!(unescape_linker_response_line(""), "");
    }

    #[test]
    fn test_quote_linker_response_arg() {
        // an argument with no whitespace, quotes, or leading `#` stays bare
        assert_eq!(quote_linker_response_arg("-lfoo"), "-lfoo");
        // a space and a tab would split the token for zig
        assert_eq!(
            quote_linker_response_arg(r#"C:\Users\John Doe\libfoo.rlib"#),
            r#""C:\Users\John Doe\libfoo.rlib""#
        );
        assert_eq!(quote_linker_response_arg("foo\tbar"), "\"foo\tbar\"");
        // a leading `#` would start a comment line
        assert_eq!(quote_linker_response_arg("#foo"), "\"#foo\"");
        // a trailing backslash stays bare; zig reads it literally before the
        // newline
        assert_eq!(quote_linker_response_arg(r#"C:\path\"#), r#"C:\path\"#);
        // an embedded quote is escaped, and backslashes right before a quote
        // or the closing quote are doubled
        assert_eq!(quote_linker_response_arg(r#"C:\fo"o"#), r#""C:\fo\"o""#);
        assert_eq!(quote_linker_response_arg(r#"C:\a"b\"#), r#""C:\a\"b\\""#);
        // an empty argument still becomes one token
        assert_eq!(quote_linker_response_arg(""), "\"\"");
    }

    #[test]
    fn test_rustc_escaped_line_to_quoted_arg() {
        // rustc writes the escaped line on the left into the response file;
        // zig reads back the quoted argument on the right
        assert_eq!(
            quote_linker_response_arg(&unescape_linker_response_line(
                r#"C:\\Users\\John\ Doe\\libfoo.rlib"#
            )),
            r#""C:\Users\John Doe\libfoo.rlib""#
        );
    }
}