Zig 0.17.0-dev (Split by item)

Shortcut keys
?
Show these tips
S
Focus search field
Esc
Clear focus & close tips
U
Jump to source code
↑
Move up in search results
↓
Move down in search results
↵
Go to active search result
This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig standard library. Public Struct

LibCInstallation

Public Struct

See the render function implementation for documentation of the fields.

Fields

include_dir: ?[]const u8 = null
sys_include_dir: ?[]const u8 = null
crt_dir: ?[]const u8 = null
msvc_lib_dir: ?[]const u8 = null
kernel32_lib_dir: ?[]const u8 = null
gcc_dir: ?[]const u8 = null

Namespaces

Structs

Values

Functions

pub fn parse(allocator: Allocator, io: Io, libc_file: []const u8, target: *const std.Target) !LibCInstallation
pub fn render(self: LibCInstallation, out: *std.Io.Writer) !void
pub fn findNative(gpa: Allocator, io: Io, args: FindNativeOptions) FindError!LibCInstallation

Finds the default, native libc.

pub fn deinit(self: *LibCInstallation, allocator: Allocator) void

Must be the same allocator passed to parse or findNative.

fn findNativeIncludeDirPosix(self: *LibCInstallation, gpa: Allocator, io: Io, args: FindNativeOptions) FindError!void
fn findNativeIncludeDirWindows(self: *LibCInstallation, gpa: Allocator, io: Io, sdk: std.zig.WindowsSdk) FindError!void
fn findNativeCrtDirWindows(self: *LibCInstallation, gpa: Allocator, io: Io, target: *const std.Target, sdk: std.zig.WindowsSdk) FindError!void
fn findNativeCrtDirPosix(self: *LibCInstallation, gpa: Allocator, io: Io, args: FindNativeOptions) FindError!void
fn findNativeGccDirPosix(self: *LibCInstallation, gpa: Allocator, io: Io, args: FindNativeOptions) FindError!void
fn findNativeKernel32LibDir(self: *LibCInstallation, gpa: Allocator, io: Io, args: FindNativeOptions, sdk: std.zig.WindowsSdk) FindError!void
fn findNativeMsvcIncludeDir(self: *LibCInstallation, gpa: Allocator, io: Io, sdk: std.zig.WindowsSdk) FindError!void
fn findNativeMsvcLibDir(self: *LibCInstallation, gpa: Allocator, sdk: std.zig.WindowsSdk) FindError!void
fn ccPrintFileName(gpa: Allocator, io: Io, args: CCPrintFileNameOptions) ![]u8

caller owns returned memory

fn printVerboseInvocation(argv: []const []const u8, search_basename: ?[]const u8, verbose: bool, stderr: ?[]const u8) void
fn fillInstallations(installs: *[2]std.zig.WindowsSdk.Installation, sdk: std.zig.WindowsSdk) []std.zig.WindowsSdk.Installation
fn appendCcExe(args: *std.array_list.Managed([]const u8), skip_cc_env_var: bool, environ_map: *const Environ.Map) !void
pub fn resolveCrtPaths(lci: LibCInstallation, arena: Allocator, crt_basenames: CrtBasenames, target: *const std.Target) error
pub fn addToHash(opt_lci: ?*const LibCInstallation, hh: *Cache.HashHelper, abi: std.Target.Abi) void

File

zig/LibCInstallation.zig
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
//! See the render function implementation for documentation of the fields.
const LibCInstallation = @This();

const builtin = @import("builtin");
const is_darwin = builtin.target.os.tag.isDarwin();
const is_windows = builtin.target.os.tag == .windows;
const is_haiku = builtin.target.os.tag == .haiku;
const is_serenity = builtin.target.os.tag == .serenity;

const std = @import("std");
const Io = std.Io;
const Target = std.Target;
const fs = std.fs;
const Allocator = std.mem.Allocator;
const Path = std.Build.Cache.Path;
const Cache = std.Build.Cache;
const log = std.log.scoped(.libc_installation);
const Environ = std.process.Environ;

include_dir: ?[]const u8 = null,
sys_include_dir: ?[]const u8 = null,
crt_dir: ?[]const u8 = null,
msvc_lib_dir: ?[]const u8 = null,
kernel32_lib_dir: ?[]const u8 = null,
gcc_dir: ?[]const u8 = null,

pub const FindError = error{
    OutOfMemory,
    FileSystem,
    UnableToSpawnCCompiler,
    CCompilerExitCode,
    CCompilerCrashed,
    CCompilerCannotFindHeaders,
    LibCRuntimeNotFound,
    LibCStdLibHeaderNotFound,
    LibCKernel32LibNotFound,
    UnsupportedArchitecture,
    WindowsSdkNotFound,
    DarwinSdkNotFound,
    ZigIsTheCCompiler,
};

pub fn parse(allocator: Allocator, io: Io, libc_file: []const u8, target: *const std.Target) !LibCInstallation {
    var self: LibCInstallation = .{};

    const field_names = @typeInfo(LibCInstallation).@"struct".field_names;
    const FoundKey = struct {
        found: bool,
        allocated: ?[]u8,
    };

    var found_keys: [field_names.len]FoundKey = @splat(.{ .found = false, .allocated = null });
    errdefer {
        self = .{};
        for (found_keys) |found_key| {
            if (found_key.allocated) |s| allocator.free(s);
        }
    }

    const contents = try Io.Dir.cwd().readFileAlloc(io, libc_file, allocator, .limited(std.math.maxInt(usize)));
    defer allocator.free(contents);

    var it = std.mem.tokenizeAny(u8, contents, "\n\r");
    while (it.next()) |line| {
        if (line.len == 0 or line[0] == '#') continue;
        var line_it = std.mem.splitScalar(u8, line, '=');
        const name = line_it.first();
        const value = line_it.rest();
        inline for (field_names, 0..) |field_name, i| {
            if (std.mem.eql(u8, name, field_name)) {
                found_keys[i].found = true;
                if (value.len == 0) {
                    @field(self, field_name) = null;
                } else {
                    found_keys[i].allocated = try allocator.dupe(u8, value);
                    @field(self, field_name) = found_keys[i].allocated;
                }
                break;
            }
        }
    }
    inline for (field_names, 0..) |field_name, i| {
        if (!found_keys[i].found) {
            log.err("missing field: {s}", .{field_name});
            return error.ParseError;
        }
    }
    if (self.include_dir == null) {
        log.err("include_dir may not be empty", .{});
        return error.ParseError;
    }
    if (self.sys_include_dir == null) {
        log.err("sys_include_dir may not be empty", .{});
        return error.ParseError;
    }

    const os_tag = target.os.tag;
    if (self.crt_dir == null and !target.os.tag.isDarwin()) {
        log.err("crt_dir may not be empty for {s}", .{@tagName(os_tag)});
        return error.ParseError;
    }

    if (self.msvc_lib_dir == null and os_tag == .windows and (target.abi == .msvc or target.abi == .itanium)) {
        log.err("msvc_lib_dir may not be empty for {s}-{s}", .{
            @tagName(os_tag),
            @tagName(target.abi),
        });
        return error.ParseError;
    }
    if (self.kernel32_lib_dir == null and os_tag == .windows and (target.abi == .msvc or target.abi == .itanium)) {
        log.err("kernel32_lib_dir may not be empty for {s}-{s}", .{
            @tagName(os_tag),
            @tagName(target.abi),
        });
        return error.ParseError;
    }

    if (self.gcc_dir == null and (os_tag == .haiku or os_tag == .serenity)) {
        log.err("gcc_dir may not be empty for {s}", .{@tagName(os_tag)});
        return error.ParseError;
    }

    return self;
}

pub fn render(self: LibCInstallation, out: *std.Io.Writer) !void {
    @setEvalBranchQuota(4000);
    const include_dir = self.include_dir orelse "";
    const sys_include_dir = self.sys_include_dir orelse "";
    const crt_dir = self.crt_dir orelse "";
    const msvc_lib_dir = self.msvc_lib_dir orelse "";
    const kernel32_lib_dir = self.kernel32_lib_dir orelse "";
    const gcc_dir = self.gcc_dir orelse "";

    try out.print(
        \\# The directory that contains `stdlib.h`.
        \\# On POSIX-like systems, include directories be found with: `cc -E -Wp,-v -xc /dev/null`
        \\include_dir={s}
        \\
        \\# The system-specific include directory. May be the same as `include_dir`.
        \\# On Windows it's the directory that includes `vcruntime.h`.
        \\# On POSIX it's the directory that includes `sys/errno.h`.
        \\sys_include_dir={s}
        \\
        \\# The directory that contains `crt1.o` or `crt2.o`.
        \\# On POSIX, can be found with `cc -print-file-name=crt1.o`.
        \\# Not needed when targeting MacOS.
        \\crt_dir={s}
        \\
        \\# The directory that contains `vcruntime.lib`.
        \\# Only needed when targeting MSVC on Windows.
        \\msvc_lib_dir={s}
        \\
        \\# The directory that contains `kernel32.lib`.
        \\# Only needed when targeting MSVC on Windows.
        \\kernel32_lib_dir={s}
        \\
        \\# The directory that contains `crtbeginS.o` and `crtendS.o`
        \\# Only needed when targeting Haiku.
        \\gcc_dir={s}
        \\
    , .{
        include_dir,
        sys_include_dir,
        crt_dir,
        msvc_lib_dir,
        kernel32_lib_dir,
        gcc_dir,
    });
}

pub const FindNativeOptions = struct {
    target: *const std.Target,
    environ_map: *const Environ.Map,

    /// If enabled, will print human-friendly errors to stderr.
    verbose: bool = false,
};

/// Finds the default, native libc.
pub fn findNative(gpa: Allocator, io: Io, args: FindNativeOptions) FindError!LibCInstallation {
    var self: LibCInstallation = .{};

    if (is_darwin and args.target.os.tag.isDarwin()) {
        if (!std.zig.system.darwin.isSdkInstalled(gpa, io))
            return error.DarwinSdkNotFound;
        const sdk = std.zig.system.darwin.getSdk(gpa, io, args.target) orelse
            return error.DarwinSdkNotFound;
        defer gpa.free(sdk);

        self.include_dir = try fs.path.join(gpa, &.{
            sdk, "usr/include",
        });
        self.sys_include_dir = try fs.path.join(gpa, &.{
            sdk, "usr/include",
        });
        return self;
    } else if (is_windows) {
        const sdk = std.zig.WindowsSdk.find(gpa, io, args.target.cpu.arch, args.environ_map) catch |err| switch (err) {
            error.NotFound => return error.WindowsSdkNotFound,
            error.PathTooLong => return error.WindowsSdkNotFound,
            error.OutOfMemory => |e| return e,
        };
        defer sdk.free(gpa);

        try self.findNativeMsvcIncludeDir(gpa, io, sdk);
        try self.findNativeMsvcLibDir(gpa, sdk);
        try self.findNativeKernel32LibDir(gpa, io, args, sdk);
        try self.findNativeIncludeDirWindows(gpa, io, sdk);
        try self.findNativeCrtDirWindows(gpa, io, args.target, sdk);
    } else if (is_haiku) {
        try self.findNativeIncludeDirPosix(gpa, io, args);
        try self.findNativeGccDirPosix(gpa, io, args);
        self.crt_dir = try gpa.dupe(u8, "/system/develop/lib");
    } else if (is_serenity) {
        try self.findNativeIncludeDirPosix(gpa, io, args);
        try self.findNativeGccDirPosix(gpa, io, args);
        self.crt_dir = try gpa.dupe(u8, "/usr/lib");
    } else if (builtin.target.os.tag == .illumos) {
        // There is only one libc, and its headers/libraries are always in the same spot.
        self.include_dir = try gpa.dupe(u8, "/usr/include");
        self.sys_include_dir = try gpa.dupe(u8, "/usr/include");
        self.crt_dir = try gpa.dupe(u8, "/usr/lib/64");
    } else if (std.process.can_spawn) {
        try self.findNativeIncludeDirPosix(gpa, io, args);
        switch (builtin.target.os.tag) {
            .freebsd, .netbsd, .openbsd, .dragonfly => self.crt_dir = try gpa.dupe(u8, "/usr/lib"),
            .linux => {
                try self.findNativeCrtDirPosix(gpa, io, args);
                try self.findNativeGccDirPosix(gpa, io, args);
            },
            else => {},
        }
    } else {
        return error.LibCRuntimeNotFound;
    }
    return self;
}

/// Must be the same allocator passed to `parse` or `findNative`.
pub fn deinit(self: *LibCInstallation, allocator: Allocator) void {
    inline for (@typeInfo(LibCInstallation).@"struct".field_names) |field_name| {
        if (@field(self, field_name)) |payload| {
            allocator.free(payload);
        }
    }
    self.* = undefined;
}

fn findNativeIncludeDirPosix(self: *LibCInstallation, gpa: Allocator, io: Io, args: FindNativeOptions) FindError!void {
    // Detect infinite loops.
    var environ_map = try args.environ_map.clone(gpa);
    defer environ_map.deinit();
    const skip_cc_env_var = if (environ_map.get(inf_loop_env_key)) |phase| blk: {
        if (std.mem.eql(u8, phase, "1")) {
            try environ_map.put(inf_loop_env_key, "2");
            break :blk true;
        } else {
            return error.ZigIsTheCCompiler;
        }
    } else blk: {
        try environ_map.put(inf_loop_env_key, "1");
        break :blk false;
    };

    const dev_null = if (is_windows) "nul" else "/dev/null";

    var argv = std.array_list.Managed([]const u8).init(gpa);
    defer argv.deinit();

    try appendCcExe(&argv, skip_cc_env_var, &environ_map);
    try argv.appendSlice(&.{
        "-E",
        "-Wp,-v",
        "-xc",
        dev_null,
    });

    const run_res = std.process.run(gpa, io, .{
        .stdout_limit = .limited(1024 * 1024),
        .stderr_limit = .limited(1024 * 1024),
        .argv = argv.items,
        .environ_map = &environ_map,
        // Some C compilers, such as Clang, are known to rely on argv[0] to find the path
        // to their own executable, without even bothering to resolve PATH. This results in the message:
        // error: unable to execute command: Executable "" doesn't exist!
        // So we use the expandArg0 variant of ChildProcess to give them a helping hand.
        .expand_arg0 = .expand,
    }) catch |err| switch (err) {
        error.OutOfMemory => |e| return e,
        else => {
            printVerboseInvocation(argv.items, null, args.verbose, null);
            return error.UnableToSpawnCCompiler;
        },
    };
    defer {
        gpa.free(run_res.stdout);
        gpa.free(run_res.stderr);
    }
    switch (run_res.term) {
        .exited => |code| if (code != 0) {
            printVerboseInvocation(argv.items, null, args.verbose, run_res.stderr);
            return error.CCompilerExitCode;
        },
        else => {
            printVerboseInvocation(argv.items, null, args.verbose, run_res.stderr);
            return error.CCompilerCrashed;
        },
    }

    var it = std.mem.tokenizeAny(u8, run_res.stderr, "\n\r");
    var search_paths = std.array_list.Managed([]const u8).init(gpa);
    defer search_paths.deinit();
    while (it.next()) |line| {
        if (line.len != 0 and line[0] == ' ') {
            try search_paths.append(line);
        }
    }
    if (search_paths.items.len == 0) {
        return error.CCompilerCannotFindHeaders;
    }

    const include_dir_example_file = if (is_haiku) "posix/stdlib.h" else "stdlib.h";
    const sys_include_dir_example_file = if (is_windows)
        "sys\\types.h"
    else if (is_haiku or is_serenity)
        "errno.h"
    else
        "sys/errno.h";

    var path_i: usize = 0;
    while (path_i < search_paths.items.len) : (path_i += 1) {
        // search in reverse order
        const search_path_untrimmed = search_paths.items[search_paths.items.len - path_i - 1];
        const search_path = std.mem.trimStart(u8, search_path_untrimmed, " ");
        var search_dir = Io.Dir.cwd().openDir(io, search_path, .{}) catch |err| switch (err) {
            error.FileNotFound,
            error.NotDir,
            error.NoDevice,
            => continue,

            else => return error.FileSystem,
        };
        defer search_dir.close(io);

        if (self.include_dir == null) {
            if (search_dir.access(io, include_dir_example_file, .{})) |_| {
                self.include_dir = try gpa.dupe(u8, search_path);
            } else |err| switch (err) {
                error.FileNotFound => {},
                else => return error.FileSystem,
            }
        }

        if (self.sys_include_dir == null) {
            if (search_dir.access(io, sys_include_dir_example_file, .{})) |_| {
                self.sys_include_dir = try gpa.dupe(u8, search_path);
            } else |err| switch (err) {
                error.FileNotFound => {},
                else => return error.FileSystem,
            }
        }

        if (self.include_dir != null and self.sys_include_dir != null) {
            // Success.
            return;
        }
    }

    return error.LibCStdLibHeaderNotFound;
}

fn findNativeIncludeDirWindows(
    self: *LibCInstallation,
    gpa: Allocator,
    io: Io,
    sdk: std.zig.WindowsSdk,
) FindError!void {
    var install_buf: [2]std.zig.WindowsSdk.Installation = undefined;
    const installs = fillInstallations(&install_buf, sdk);

    var result_buf = std.array_list.Managed(u8).init(gpa);
    defer result_buf.deinit();

    for (installs) |install| {
        result_buf.shrinkAndFree(0);
        try result_buf.print("{s}\\Include\\{s}\\ucrt", .{ install.path, install.version });

        var dir = Io.Dir.cwd().openDir(io, result_buf.items, .{}) catch |err| switch (err) {
            error.FileNotFound,
            error.NotDir,
            error.NoDevice,
            => continue,

            else => return error.FileSystem,
        };
        defer dir.close(io);

        dir.access(io, "stdlib.h", .{}) catch |err| switch (err) {
            error.FileNotFound => continue,
            else => return error.FileSystem,
        };

        self.include_dir = try result_buf.toOwnedSlice();
        return;
    }

    return error.LibCStdLibHeaderNotFound;
}

fn findNativeCrtDirWindows(
    self: *LibCInstallation,
    gpa: Allocator,
    io: Io,
    target: *const std.Target,
    sdk: std.zig.WindowsSdk,
) FindError!void {
    var install_buf: [2]std.zig.WindowsSdk.Installation = undefined;
    const installs = fillInstallations(&install_buf, sdk);

    var result_buf = std.array_list.Managed(u8).init(gpa);
    defer result_buf.deinit();

    const arch_sub_dir = switch (target.cpu.arch) {
        .x86 => "x86",
        .x86_64 => "x64",
        .thumb => "arm",
        .aarch64 => "arm64",
        else => return error.UnsupportedArchitecture,
    };

    for (installs) |install| {
        result_buf.shrinkAndFree(0);
        try result_buf.print("{s}\\Lib\\{s}\\ucrt\\{s}", .{ install.path, install.version, arch_sub_dir });

        var dir = Io.Dir.cwd().openDir(io, result_buf.items, .{}) catch |err| switch (err) {
            error.FileNotFound,
            error.NotDir,
            error.NoDevice,
            => continue,

            else => return error.FileSystem,
        };
        defer dir.close(io);

        dir.access(io, "ucrt.lib", .{}) catch |err| switch (err) {
            error.FileNotFound => continue,
            else => return error.FileSystem,
        };

        self.crt_dir = try result_buf.toOwnedSlice();
        return;
    }
    return error.LibCRuntimeNotFound;
}

fn findNativeCrtDirPosix(self: *LibCInstallation, gpa: Allocator, io: Io, args: FindNativeOptions) FindError!void {
    self.crt_dir = try ccPrintFileName(gpa, io, .{
        .environ_map = args.environ_map,
        .search_basename = switch (args.target.os.tag) {
            .linux => if (args.target.abi.isAndroid()) "crtbegin_dynamic.o" else "crt1.o",
            else => "crt1.o",
        },
        .want_dirname = .only_dir,
        .verbose = args.verbose,
    });
}

fn findNativeGccDirPosix(self: *LibCInstallation, gpa: Allocator, io: Io, args: FindNativeOptions) FindError!void {
    self.gcc_dir = try ccPrintFileName(gpa, io, .{
        .environ_map = args.environ_map,
        .search_basename = "crtbeginS.o",
        .want_dirname = .only_dir,
        .verbose = args.verbose,
    });
}

fn findNativeKernel32LibDir(
    self: *LibCInstallation,
    gpa: Allocator,
    io: Io,
    args: FindNativeOptions,
    sdk: std.zig.WindowsSdk,
) FindError!void {
    var install_buf: [2]std.zig.WindowsSdk.Installation = undefined;
    const installs = fillInstallations(&install_buf, sdk);

    var result_buf = std.array_list.Managed(u8).init(gpa);
    defer result_buf.deinit();

    const arch_sub_dir = switch (args.target.cpu.arch) {
        .x86 => "x86",
        .x86_64 => "x64",
        .thumb => "arm",
        .aarch64 => "arm64",
        else => return error.UnsupportedArchitecture,
    };

    for (installs) |install| {
        result_buf.shrinkAndFree(0);
        try result_buf.print("{s}\\Lib\\{s}\\um\\{s}", .{ install.path, install.version, arch_sub_dir });

        var dir = Io.Dir.cwd().openDir(io, result_buf.items, .{}) catch |err| switch (err) {
            error.FileNotFound,
            error.NotDir,
            error.NoDevice,
            => continue,

            else => return error.FileSystem,
        };
        defer dir.close(io);

        dir.access(io, "kernel32.lib", .{}) catch |err| switch (err) {
            error.FileNotFound => continue,
            else => return error.FileSystem,
        };

        self.kernel32_lib_dir = try result_buf.toOwnedSlice();
        return;
    }
    return error.LibCKernel32LibNotFound;
}

fn findNativeMsvcIncludeDir(
    self: *LibCInstallation,
    gpa: Allocator,
    io: Io,
    sdk: std.zig.WindowsSdk,
) FindError!void {
    const msvc_lib_dir = sdk.msvc_lib_dir orelse return error.LibCStdLibHeaderNotFound;
    const up1 = fs.path.dirname(msvc_lib_dir) orelse return error.LibCStdLibHeaderNotFound;
    const up2 = fs.path.dirname(up1) orelse return error.LibCStdLibHeaderNotFound;

    const dir_path = try fs.path.join(gpa, &[_][]const u8{ up2, "include" });
    errdefer gpa.free(dir_path);

    var dir = Io.Dir.cwd().openDir(io, dir_path, .{}) catch |err| switch (err) {
        error.FileNotFound,
        error.NotDir,
        error.NoDevice,
        => return error.LibCStdLibHeaderNotFound,

        else => return error.FileSystem,
    };
    defer dir.close(io);

    dir.access(io, "vcruntime.h", .{}) catch |err| switch (err) {
        error.FileNotFound => return error.LibCStdLibHeaderNotFound,
        else => return error.FileSystem,
    };

    self.sys_include_dir = dir_path;
}

fn findNativeMsvcLibDir(
    self: *LibCInstallation,
    gpa: Allocator,
    sdk: std.zig.WindowsSdk,
) FindError!void {
    const msvc_lib_dir = sdk.msvc_lib_dir orelse return error.LibCRuntimeNotFound;
    self.msvc_lib_dir = try gpa.dupe(u8, msvc_lib_dir);
}

pub const CCPrintFileNameOptions = struct {
    environ_map: *const Environ.Map,
    search_basename: []const u8,
    want_dirname: enum { full_path, only_dir },
    verbose: bool = false,
};

/// caller owns returned memory
fn ccPrintFileName(gpa: Allocator, io: Io, args: CCPrintFileNameOptions) ![]u8 {
    // Detect infinite loops.
    var environ_map = try args.environ_map.clone(gpa);
    defer environ_map.deinit();
    const skip_cc_env_var = if (environ_map.get(inf_loop_env_key)) |phase| blk: {
        if (std.mem.eql(u8, phase, "1")) {
            try environ_map.put(inf_loop_env_key, "2");
            break :blk true;
        } else {
            return error.ZigIsTheCCompiler;
        }
    } else blk: {
        try environ_map.put(inf_loop_env_key, "1");
        break :blk false;
    };

    var argv = std.array_list.Managed([]const u8).init(gpa);
    defer argv.deinit();

    const arg1 = try std.fmt.allocPrint(gpa, "-print-file-name={s}", .{args.search_basename});
    defer gpa.free(arg1);

    try appendCcExe(&argv, skip_cc_env_var, &environ_map);
    try argv.append(arg1);

    const run_res = std.process.run(gpa, io, .{
        .stdout_limit = .limited(1024 * 1024),
        .stderr_limit = .limited(1024 * 1024),
        .argv = argv.items,
        .environ_map = &environ_map,
        // Some C compilers, such as Clang, are known to rely on argv[0] to find the path
        // to their own executable, without even bothering to resolve PATH. This results in the message:
        // error: unable to execute command: Executable "" doesn't exist!
        // So we use the expandArg0 variant of ChildProcess to give them a helping hand.
        .expand_arg0 = .expand,
    }) catch |err| switch (err) {
        error.OutOfMemory => |e| return e,
        else => return error.UnableToSpawnCCompiler,
    };
    defer {
        gpa.free(run_res.stdout);
        gpa.free(run_res.stderr);
    }
    switch (run_res.term) {
        .exited => |code| if (code != 0) {
            printVerboseInvocation(argv.items, args.search_basename, args.verbose, run_res.stderr);
            return error.CCompilerExitCode;
        },
        else => {
            printVerboseInvocation(argv.items, args.search_basename, args.verbose, run_res.stderr);
            return error.CCompilerCrashed;
        },
    }

    var it = std.mem.tokenizeAny(u8, run_res.stdout, "\n\r");
    const line = it.next() orelse return error.LibCRuntimeNotFound;
    // When this command fails, it returns exit code 0 and duplicates the input file name.
    // So we detect failure by checking if the output matches exactly the input.
    if (std.mem.eql(u8, line, args.search_basename)) return error.LibCRuntimeNotFound;
    switch (args.want_dirname) {
        .full_path => return gpa.dupe(u8, line),
        .only_dir => {
            const dirname = fs.path.dirname(line) orelse return error.LibCRuntimeNotFound;
            return gpa.dupe(u8, dirname);
        },
    }
}

fn printVerboseInvocation(
    argv: []const []const u8,
    search_basename: ?[]const u8,
    verbose: bool,
    stderr: ?[]const u8,
) void {
    if (!verbose) return;

    if (search_basename) |s| {
        std.debug.print("Zig attempted to find the file '{s}' by executing this command:\n", .{s});
    } else {
        std.debug.print("Zig attempted to find the path to native system libc headers by executing this command:\n", .{});
    }
    for (argv, 0..) |arg, i| {
        if (i != 0) std.debug.print(" ", .{});
        std.debug.print("{s}", .{arg});
    }
    std.debug.print("\n", .{});
    if (stderr) |s| {
        std.debug.print("Output:\n==========\n{s}\n==========\n", .{s});
    }
}

fn fillInstallations(
    installs: *[2]std.zig.WindowsSdk.Installation,
    sdk: std.zig.WindowsSdk,
) []std.zig.WindowsSdk.Installation {
    var installs_len: usize = 0;
    if (sdk.windows10sdk) |windows10sdk| {
        installs[installs_len] = windows10sdk;
        installs_len += 1;
    }
    if (sdk.windows81sdk) |windows81sdk| {
        installs[installs_len] = windows81sdk;
        installs_len += 1;
    }
    return installs[0..installs_len];
}

const inf_loop_env_key = "ZIG_IS_DETECTING_LIBC_PATHS";

fn appendCcExe(
    args: *std.array_list.Managed([]const u8),
    skip_cc_env_var: bool,
    environ_map: *const Environ.Map,
) !void {
    const default_cc_exe = if (is_windows) "cc.exe" else "cc";
    try args.ensureUnusedCapacity(1);
    if (skip_cc_env_var) {
        args.appendAssumeCapacity(default_cc_exe);
        return;
    }
    const cc_env_var = std.zig.EnvVar.CC.get(environ_map) orelse {
        args.appendAssumeCapacity(default_cc_exe);
        return;
    };
    // Respect space-separated flags to the C compiler.
    var it = std.mem.tokenizeScalar(u8, cc_env_var, ' ');
    while (it.next()) |arg| {
        try args.append(arg);
    }
}

/// These are basenames. This data is produced with a pure function. See also
/// `CsuPaths`.
pub const CrtBasenames = struct {
    crt0: ?[]const u8 = null,
    crti: ?[]const u8 = null,
    crtbegin: ?[]const u8 = null,
    crtend: ?[]const u8 = null,
    crtn: ?[]const u8 = null,

    pub const GetArgs = struct {
        target: *const std.Target,
        link_libc: bool,
        output_mode: std.lang.OutputMode,
        link_mode: std.lang.LinkMode,
        pie: bool,
    };

    /// Determine file system path names of C runtime startup objects for supported
    /// link modes.
    pub fn get(args: GetArgs) CrtBasenames {
        // crt objects are only required for libc.
        if (!args.link_libc) return .{};

        // Flatten crt cases.
        const mode: enum {
            dynamic_lib,
            dynamic_exe,
            dynamic_pie,
            static_exe,
            static_pie,
        } = switch (args.output_mode) {
            .Obj => return .{},
            .Lib => switch (args.link_mode) {
                .dynamic => .dynamic_lib,
                .static => return .{},
            },
            .Exe => switch (args.link_mode) {
                .dynamic => if (args.pie) .dynamic_pie else .dynamic_exe,
                .static => if (args.pie) .static_pie else .static_exe,
            },
        };

        const target = args.target;

        if (target.abi.isAndroid()) return switch (mode) {
            .dynamic_lib => .{
                .crtbegin = "crtbegin_so.o",
                .crtend = "crtend_so.o",
            },
            .dynamic_exe, .dynamic_pie => .{
                .crtbegin = "crtbegin_dynamic.o",
                .crtend = "crtend_android.o",
            },
            .static_exe, .static_pie => .{
                .crtbegin = "crtbegin_static.o",
                .crtend = "crtend_android.o",
            },
        };

        return switch (target.os.tag) {
            .linux => switch (mode) {
                .dynamic_lib => .{
                    .crti = "crti.o",
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                    .crtn = "crtn.o",
                },
                .dynamic_exe => .{
                    .crt0 = "crt1.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbegin.o",
                    .crtend = "crtend.o",
                    .crtn = "crtn.o",
                },
                .dynamic_pie => .{
                    .crt0 = "Scrt1.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                    .crtn = "crtn.o",
                },
                .static_exe => .{
                    .crt0 = "crt1.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbegin.o",
                    .crtend = "crtend.o",
                    .crtn = "crtn.o",
                },
                .static_pie => .{
                    .crt0 = "rcrt1.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                    .crtn = "crtn.o",
                },
            },
            .dragonfly => switch (mode) {
                .dynamic_lib => .{
                    .crti = "crti.o",
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                    .crtn = "crtn.o",
                },
                .dynamic_exe => .{
                    .crt0 = "crt1.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbegin.o",
                    .crtend = "crtend.o",
                    .crtn = "crtn.o",
                },
                .dynamic_pie => .{
                    .crt0 = "Scrt1.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                    .crtn = "crtn.o",
                },
                .static_exe => .{
                    .crt0 = "crt1.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbegin.o",
                    .crtend = "crtend.o",
                    .crtn = "crtn.o",
                },
                .static_pie => .{
                    .crt0 = "Scrt1.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                    .crtn = "crtn.o",
                },
            },
            .freebsd => switch (mode) {
                .dynamic_lib => .{
                    .crti = "crti.o",
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                    .crtn = "crtn.o",
                },
                .dynamic_exe => .{
                    .crt0 = "crt1.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbegin.o",
                    .crtend = "crtend.o",
                    .crtn = "crtn.o",
                },
                .dynamic_pie => .{
                    .crt0 = "Scrt1.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                    .crtn = "crtn.o",
                },
                .static_exe => .{
                    .crt0 = "crt1.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbeginT.o",
                    .crtend = "crtend.o",
                    .crtn = "crtn.o",
                },
                .static_pie => .{
                    .crt0 = "Scrt1.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                    .crtn = "crtn.o",
                },
            },
            .netbsd => switch (mode) {
                .dynamic_lib => .{
                    .crti = "crti.o",
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                    .crtn = "crtn.o",
                },
                .dynamic_exe => .{
                    .crt0 = "crt0.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbegin.o",
                    .crtend = "crtend.o",
                    .crtn = "crtn.o",
                },
                .dynamic_pie => .{
                    .crt0 = "crt0.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                    .crtn = "crtn.o",
                },
                .static_exe => .{
                    .crt0 = "crt0.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbeginT.o",
                    .crtend = "crtend.o",
                    .crtn = "crtn.o",
                },
                .static_pie => .{
                    .crt0 = "crt0.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbeginT.o",
                    .crtend = "crtendS.o",
                    .crtn = "crtn.o",
                },
            },
            .openbsd => switch (mode) {
                .dynamic_lib => .{
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                },
                .dynamic_exe, .dynamic_pie => .{
                    .crt0 = "crt0.o",
                    .crtbegin = "crtbegin.o",
                    .crtend = "crtend.o",
                },
                .static_exe, .static_pie => .{
                    .crt0 = "rcrt0.o",
                    .crtbegin = "crtbegin.o",
                    .crtend = "crtend.o",
                },
            },
            .haiku => switch (mode) {
                .dynamic_lib => .{
                    .crti = "crti.o",
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                    .crtn = "crtn.o",
                },
                .dynamic_exe => .{
                    .crt0 = "start_dyn.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbegin.o",
                    .crtend = "crtend.o",
                    .crtn = "crtn.o",
                },
                .dynamic_pie => .{
                    .crt0 = "start_dyn.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                    .crtn = "crtn.o",
                },
                .static_exe => .{
                    .crt0 = "start_dyn.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbegin.o",
                    .crtend = "crtend.o",
                    .crtn = "crtn.o",
                },
                .static_pie => .{
                    .crt0 = "start_dyn.o",
                    .crti = "crti.o",
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                    .crtn = "crtn.o",
                },
            },
            .illumos => switch (mode) {
                .dynamic_lib => .{
                    .crti = "crti.o",
                    .crtn = "crtn.o",
                },
                .dynamic_exe, .dynamic_pie => .{
                    .crt0 = "crt1.o",
                    .crti = "crti.o",
                    .crtn = "crtn.o",
                },
                .static_exe, .static_pie => .{},
            },
            .serenity => switch (mode) {
                .dynamic_lib => .{
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                },
                .dynamic_exe, .static_exe => .{
                    .crt0 = "crt0.o",
                    .crtbegin = "crtbegin.o",
                    .crtend = "crtend.o",
                },
                .dynamic_pie, .static_pie => .{
                    .crt0 = "crt0.o",
                    .crtbegin = "crtbeginS.o",
                    .crtend = "crtendS.o",
                },
            },
            else => .{},
        };
    }
};

pub const CrtPaths = struct {
    crt0: ?Path = null,
    crti: ?Path = null,
    crtbegin: ?Path = null,
    crtend: ?Path = null,
    crtn: ?Path = null,
};

pub fn resolveCrtPaths(
    lci: LibCInstallation,
    arena: Allocator,
    crt_basenames: CrtBasenames,
    target: *const std.Target,
) error{ OutOfMemory, LibCInstallationMissingCrtDir }!CrtPaths {
    const crt_dir_path: Path = .{
        .root_dir = Cache.Directory.cwd(),
        .sub_path = lci.crt_dir orelse return error.LibCInstallationMissingCrtDir,
    };

    switch (target.os.tag) {
        .dragonfly => {
            const gccv: []const u8 = if (target.os.version_range.semver.isAtLeast(.{
                .major = 5,
                .minor = 4,
                .patch = 0,
            }) orelse true) "gcc80" else "gcc54";
            return .{
                .crt0 = if (crt_basenames.crt0) |basename| try crt_dir_path.join(arena, basename) else null,
                .crti = if (crt_basenames.crti) |basename| try crt_dir_path.join(arena, basename) else null,
                .crtbegin = if (crt_basenames.crtbegin) |basename| .{
                    .root_dir = crt_dir_path.root_dir,
                    .sub_path = try fs.path.join(arena, &.{ crt_dir_path.sub_path, gccv, basename }),
                } else null,
                .crtend = if (crt_basenames.crtend) |basename| .{
                    .root_dir = crt_dir_path.root_dir,
                    .sub_path = try fs.path.join(arena, &.{ crt_dir_path.sub_path, gccv, basename }),
                } else null,
                .crtn = if (crt_basenames.crtn) |basename| try crt_dir_path.join(arena, basename) else null,
            };
        },
        .haiku, .serenity, .linux => {
            const gcc_dir_path: Path = .{
                .root_dir = Cache.Directory.cwd(),
                .sub_path = lci.gcc_dir orelse return error.LibCInstallationMissingCrtDir,
            };
            return .{
                .crt0 = if (crt_basenames.crt0) |basename| try crt_dir_path.join(arena, basename) else null,
                .crti = if (crt_basenames.crti) |basename| try crt_dir_path.join(arena, basename) else null,
                .crtbegin = if (crt_basenames.crtbegin) |basename| try gcc_dir_path.join(arena, basename) else null,
                .crtend = if (crt_basenames.crtend) |basename| try gcc_dir_path.join(arena, basename) else null,
                .crtn = if (crt_basenames.crtn) |basename| try crt_dir_path.join(arena, basename) else null,
            };
        },
        else => {
            return .{
                .crt0 = if (crt_basenames.crt0) |basename| try crt_dir_path.join(arena, basename) else null,
                .crti = if (crt_basenames.crti) |basename| try crt_dir_path.join(arena, basename) else null,
                .crtbegin = if (crt_basenames.crtbegin) |basename| try crt_dir_path.join(arena, basename) else null,
                .crtend = if (crt_basenames.crtend) |basename| try crt_dir_path.join(arena, basename) else null,
                .crtn = if (crt_basenames.crtn) |basename| try crt_dir_path.join(arena, basename) else null,
            };
        },
    }
}

pub fn addToHash(opt_lci: ?*const LibCInstallation, hh: *Cache.HashHelper, abi: std.Target.Abi) void {
    const lci = opt_lci orelse return hh.add(false);
    hh.add(true);
    hh.addOptionalBytes(lci.crt_dir);
    switch (abi) {
        .msvc, .itanium => {
            hh.addOptionalBytes(lci.msvc_lib_dir);
            hh.addOptionalBytes(lci.kernel32_lib_dir);
        },
        else => {},
    }
}