/
main.zig
3388 lines (3147 loc) · 142 KB
/
main.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
const std = @import("std");
const assert = std.debug.assert;
const io = std.io;
const fs = std.fs;
const mem = std.mem;
const process = std.process;
const Allocator = mem.Allocator;
const ArrayList = std.ArrayList;
const ast = std.zig.ast;
const warn = std.log.warn;
const Compilation = @import("Compilation.zig");
const link = @import("link.zig");
const Package = @import("Package.zig");
const zir = @import("zir.zig");
const build_options = @import("build_options");
const introspect = @import("introspect.zig");
const LibCInstallation = @import("libc_installation.zig").LibCInstallation;
const translate_c = @import("translate_c.zig");
const Cache = @import("Cache.zig");
const target_util = @import("target.zig");
const ThreadPool = @import("ThreadPool.zig");
pub fn fatal(comptime format: []const u8, args: anytype) noreturn {
std.log.emerg(format, args);
process.exit(1);
}
pub const max_src_size = 2 * 1024 * 1024 * 1024; // 2 GiB
pub const Color = enum {
auto,
off,
on,
};
const usage =
\\Usage: zig [command] [options]
\\
\\Commands:
\\
\\ build Build project from build.zig
\\ build-exe Create executable from source or object files
\\ build-lib Create library from source or object files
\\ build-obj Create object from source or object files
\\ cc Use Zig as a drop-in C compiler
\\ c++ Use Zig as a drop-in C++ compiler
\\ env Print lib path, std path, cache directory, and version
\\ fmt Reformat Zig source into canonical form
\\ help Print this help and exit
\\ init-exe Initialize a `zig build` application in the cwd
\\ init-lib Initialize a `zig build` library in the cwd
\\ libc Display native libc paths file or validate one
\\ run Create executable and run immediately
\\ translate-c Convert C code to Zig code
\\ targets List available compilation targets
\\ test Create and run a test build
\\ version Print version number and exit
\\ zen Print Zen of Zig and exit
\\
\\General Options:
\\
\\ -h, --help Print command-specific usage
\\
;
pub const log_level: std.log.Level = switch (std.builtin.mode) {
.Debug => .debug,
.ReleaseSafe, .ReleaseFast => .info,
.ReleaseSmall => .crit,
};
var log_scopes: std.ArrayListUnmanaged([]const u8) = .{};
pub fn log(
comptime level: std.log.Level,
comptime scope: @TypeOf(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
// Hide debug messages unless:
// * logging enabled with `-Dlog`.
// * the --debug-log arg for the scope has been provided
if (@enumToInt(level) > @enumToInt(std.log.level) or
@enumToInt(level) > @enumToInt(std.log.Level.info))
{
if (!build_options.enable_logging) return;
const scope_name = @tagName(scope);
for (log_scopes.items) |log_scope| {
if (mem.eql(u8, log_scope, scope_name))
break;
} else return;
}
// We only recognize 4 log levels in this application.
const level_txt = switch (level) {
.emerg, .alert, .crit, .err => "error",
.warn => "warning",
.notice, .info => "info",
.debug => "debug",
};
const prefix1 = level_txt;
const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
// Print the message to stderr, silently ignoring any errors
std.debug.print(prefix1 ++ prefix2 ++ format ++ "\n", args);
}
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
pub fn main() anyerror!void {
const gpa = if (std.builtin.link_libc)
std.heap.raw_c_allocator
else
&general_purpose_allocator.allocator;
defer if (!std.builtin.link_libc) {
_ = general_purpose_allocator.deinit();
};
var arena_instance = std.heap.ArenaAllocator.init(gpa);
defer arena_instance.deinit();
const arena = &arena_instance.allocator;
const args = try process.argsAlloc(arena);
return mainArgs(gpa, arena, args);
}
pub fn mainArgs(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !void {
if (args.len <= 1) {
std.log.info("{s}", .{usage});
fatal("expected command argument", .{});
}
if (std.process.can_execv and std.os.getenvZ("ZIG_IS_DETECTING_LIBC_PATHS") != null) {
// In this case we have accidentally invoked ourselves as "the system C compiler"
// to figure out where libc is installed. This is essentially infinite recursion
// via child process execution due to the CC environment variable pointing to Zig.
// Here we ignore the CC environment variable and exec `cc` as a child process.
// However it's possible Zig is installed as *that* C compiler as well, which is
// why we have this additional environment variable here to check.
var env_map = try std.process.getEnvMap(arena);
const inf_loop_env_key = "ZIG_IS_TRYING_TO_NOT_CALL_ITSELF";
if (env_map.get(inf_loop_env_key) != null) {
fatal("The compilation links against libc, but Zig is unable to provide a libc " ++
"for this operating system, and no --libc " ++
"parameter was provided, so Zig attempted to invoke the system C compiler " ++
"in order to determine where libc is installed. However the system C " ++
"compiler is `zig cc`, so no libc installation was found.", .{});
}
try env_map.set(inf_loop_env_key, "1");
// Some programs such as CMake will strip the `cc` and subsequent args from the
// CC environment variable. We detect and support this scenario here because of
// the ZIG_IS_DETECTING_LIBC_PATHS environment variable.
if (mem.eql(u8, args[1], "cc")) {
return std.process.execve(arena, args[1..], &env_map);
} else {
const modified_args = try arena.dupe([]const u8, args);
modified_args[0] = "cc";
return std.process.execve(arena, modified_args, &env_map);
}
}
defer log_scopes.deinit(gpa);
const cmd = args[1];
const cmd_args = args[2..];
if (mem.eql(u8, cmd, "build-exe")) {
return buildOutputType(gpa, arena, args, .{ .build = .Exe });
} else if (mem.eql(u8, cmd, "build-lib")) {
return buildOutputType(gpa, arena, args, .{ .build = .Lib });
} else if (mem.eql(u8, cmd, "build-obj")) {
return buildOutputType(gpa, arena, args, .{ .build = .Obj });
} else if (mem.eql(u8, cmd, "test")) {
return buildOutputType(gpa, arena, args, .zig_test);
} else if (mem.eql(u8, cmd, "run")) {
return buildOutputType(gpa, arena, args, .run);
} else if (mem.eql(u8, cmd, "cc")) {
return buildOutputType(gpa, arena, args, .cc);
} else if (mem.eql(u8, cmd, "c++")) {
return buildOutputType(gpa, arena, args, .cpp);
} else if (mem.eql(u8, cmd, "translate-c")) {
return buildOutputType(gpa, arena, args, .translate_c);
} else if (mem.eql(u8, cmd, "clang") or
mem.eql(u8, cmd, "-cc1") or mem.eql(u8, cmd, "-cc1as"))
{
return punt_to_clang(arena, args);
} else if (mem.eql(u8, cmd, "ld.lld") or
mem.eql(u8, cmd, "ld64.lld") or
mem.eql(u8, cmd, "lld-link") or
mem.eql(u8, cmd, "wasm-ld"))
{
return punt_to_lld(arena, args);
} else if (mem.eql(u8, cmd, "build")) {
return cmdBuild(gpa, arena, cmd_args);
} else if (mem.eql(u8, cmd, "fmt")) {
return cmdFmt(gpa, cmd_args);
} else if (mem.eql(u8, cmd, "libc")) {
return cmdLibC(gpa, cmd_args);
} else if (mem.eql(u8, cmd, "init-exe")) {
return cmdInit(gpa, arena, cmd_args, .Exe);
} else if (mem.eql(u8, cmd, "init-lib")) {
return cmdInit(gpa, arena, cmd_args, .Lib);
} else if (mem.eql(u8, cmd, "targets")) {
const info = try detectNativeTargetInfo(arena, .{});
const stdout = io.getStdOut().writer();
return @import("print_targets.zig").cmdTargets(arena, cmd_args, stdout, info.target);
} else if (mem.eql(u8, cmd, "version")) {
try std.io.getStdOut().writeAll(build_options.version ++ "\n");
} else if (mem.eql(u8, cmd, "env")) {
try @import("print_env.zig").cmdEnv(arena, cmd_args, io.getStdOut().writer());
} else if (mem.eql(u8, cmd, "zen")) {
try io.getStdOut().writeAll(info_zen);
} else if (mem.eql(u8, cmd, "help") or mem.eql(u8, cmd, "-h") or mem.eql(u8, cmd, "--help")) {
try io.getStdOut().writeAll(usage);
} else {
std.log.info("{s}", .{usage});
fatal("unknown command: {s}", .{args[1]});
}
}
const usage_build_generic =
\\Usage: zig build-exe <options> [files]
\\ zig build-lib <options> [files]
\\ zig build-obj <options> [files]
\\ zig test <options> [files]
\\ zig run <options> [file] [-- [args]]
\\
\\Supported file types:
\\ .zig Zig source code
\\ .o ELF object file
\\ .o MACH-O (macOS) object file
\\ .obj COFF (Windows) object file
\\ .lib COFF (Windows) static library
\\ .a ELF static library
\\ .so ELF shared object (dynamic link)
\\ .dll Windows Dynamic Link Library
\\ .dylib MACH-O (macOS) dynamic library
\\ .tbd (macOS) text-based dylib definition
\\ .s Target-specific assembly source code
\\ .S Assembly with C preprocessor (requires LLVM extensions)
\\ .c C source code (requires LLVM extensions)
\\ .cpp C++ source code (requires LLVM extensions)
\\ Other C++ extensions: .C .cc .cxx
\\
\\General Options:
\\ -h, --help Print this help and exit
\\ --watch Enable compiler REPL
\\ --color [auto|off|on] Enable or disable colored error messages
\\ -femit-bin[=path] (default) Output machine code
\\ -fno-emit-bin Do not output machine code
\\ -femit-asm[=path] Output .s (assembly code)
\\ -fno-emit-asm (default) Do not output .s (assembly code)
\\ -femit-llvm-ir[=path] Produce a .ll file with LLVM IR (requires LLVM extensions)
\\ -fno-emit-llvm-ir (default) Do not produce a .ll file with LLVM IR
\\ -femit-h[=path] Generate a C header file (.h)
\\ -fno-emit-h (default) Do not generate a C header file (.h)
\\ -femit-docs[=path] Create a docs/ dir with html documentation
\\ -fno-emit-docs (default) Do not produce docs/ dir with html documentation
\\ -femit-analysis[=path] Write analysis JSON file with type information
\\ -fno-emit-analysis (default) Do not write analysis JSON file with type information
\\ --show-builtin Output the source of @import("builtin") then exit
\\ --cache-dir [path] Override the local cache directory
\\ --global-cache-dir [path] Override the global cache directory
\\ --override-lib-dir [path] Override path to Zig installation lib directory
\\ --enable-cache Output to cache directory; print path to stdout
\\
\\Compile Options:
\\ -target [name] <arch><sub>-<os>-<abi> see the targets command
\\ -mcpu [cpu] Specify target CPU and feature set
\\ -mcmodel=[default|tiny| Limit range of code and data virtual addresses
\\ small|kernel|
\\ medium|large]
\\ -mred-zone Force-enable the "red-zone"
\\ -mno-red-zone Force-disable the "red-zone"
\\ --name [name] Override root name (not a file path)
\\ -O [mode] Choose what to optimize for
\\ Debug (default) Optimizations off, safety on
\\ ReleaseFast Optimizations on, safety off
\\ ReleaseSafe Optimizations on, safety on
\\ ReleaseSmall Optimize for small binary, safety off
\\ --pkg-begin [name] [path] Make pkg available to import and push current pkg
\\ --pkg-end Pop current pkg
\\ --main-pkg-path Set the directory of the root package
\\ -fPIC Force-enable Position Independent Code
\\ -fno-PIC Force-disable Position Independent Code
\\ -fPIE Force-enable Position Independent Executable
\\ -fno-PIE Force-disable Position Independent Executable
\\ -flto Force-enable Link Time Optimization (requires LLVM extensions)
\\ -fno-lto Force-disable Link Time Optimization
\\ -fstack-check Enable stack probing in unsafe builds
\\ -fno-stack-check Disable stack probing in safe builds
\\ -fsanitize-c Enable C undefined behavior detection in unsafe builds
\\ -fno-sanitize-c Disable C undefined behavior detection in safe builds
\\ -fvalgrind Include valgrind client requests in release builds
\\ -fno-valgrind Omit valgrind client requests in debug builds
\\ -fsanitize-thread Enable Thread Sanitizer
\\ -fno-sanitize-thread Disable Thread Sanitizer
\\ -fdll-export-fns Mark exported functions as DLL exports (Windows)
\\ -fno-dll-export-fns Force-disable marking exported functions as DLL exports
\\ -fLLVM Force using LLVM as the codegen backend
\\ -fno-LLVM Prevent using LLVM as a codegen backend
\\ -fClang Force using Clang as the C/C++ compilation backend
\\ -fno-Clang Prevent using Clang as the C/C++ compilation backend
\\ --strip Omit debug symbols
\\ --single-threaded Code assumes it is only used single-threaded
\\ -ofmt=[mode] Override target object format
\\ elf Executable and Linking Format
\\ c Compile to C source code
\\ wasm WebAssembly
\\ pe Portable Executable (Windows)
\\ coff Common Object File Format (Windows)
\\ macho macOS relocatables
\\ hex (planned) Intel IHEX
\\ raw (planned) Dump machine code directly
\\ -dirafter [dir] Add directory to AFTER include search path
\\ -isystem [dir] Add directory to SYSTEM include search path
\\ -I[dir] Add directory to include search path
\\ -D[macro]=[value] Define C [macro] to [value] (1 if [value] omitted)
\\ --libc [file] Provide a file which specifies libc paths
\\ -cflags [flags] -- Set extra flags for the next positional C source files
\\ -ffunction-sections Places each function in a separate section
\\
\\Link Options:
\\ -l[lib], --library [lib] Link against system library
\\ -L[d], --library-directory [d] Add a directory to the library search path
\\ -T[script], --script [script] Use a custom linker script
\\ --version-script [path] Provide a version .map file
\\ --dynamic-linker [path] Set the dynamic interpreter path (usually ld.so)
\\ --version [ver] Dynamic library semver
\\ -fsoname[=name] (Linux) Override the default SONAME value
\\ -fno-soname (Linux) Disable emitting a SONAME
\\ -fLLD Force using LLD as the linker
\\ -fno-LLD Prevent using LLD as the linker
\\ -fcompiler-rt Always include compiler-rt symbols in output
\\ -fno-compiler-rt Prevent including compiler-rt symbols in output
\\ -rdynamic Add all symbols to the dynamic symbol table
\\ -rpath [path] Add directory to the runtime library search path
\\ -feach-lib-rpath Ensure adding rpath for each used dynamic library
\\ -fno-each-lib-rpath Prevent adding rpath for each used dynamic library
\\ --eh-frame-hdr Enable C++ exception handling by passing --eh-frame-hdr to linker
\\ --emit-relocs Enable output of relocation sections for post build tools
\\ -dynamic Force output to be dynamically linked
\\ -static Force output to be statically linked
\\ -Bsymbolic Bind global references locally
\\ --subsystem [subsystem] (Windows) /SUBSYSTEM:<subsystem> to the linker
\\ --stack [size] Override default stack size
\\ --image-base [addr] Set base address for executable image
\\ -framework [name] (Darwin) link against framework
\\ -F[dir] (Darwin) add search path for frameworks
\\
\\Test Options:
\\ --test-filter [text] Skip tests that do not match filter
\\ --test-name-prefix [text] Add prefix to all tests
\\ --test-cmd [arg] Specify test execution command one arg at a time
\\ --test-cmd-bin Appends test binary path to test cmd args
\\ --test-evented-io Runs the test in evented I/O mode
\\
\\Debug Options (Zig Compiler Development):
\\ -ftime-report Print timing diagnostics
\\ -fstack-report Print stack size diagnostics
\\ --verbose-link Display linker invocations
\\ --verbose-cc Display C compiler invocations
\\ --verbose-tokenize Enable compiler debug output for tokenization
\\ --verbose-ast Enable compiler debug output for AST parsing
\\ --verbose-ir Enable compiler debug output for Zig IR
\\ --verbose-llvm-ir Enable compiler debug output for LLVM IR
\\ --verbose-cimport Enable compiler debug output for C imports
\\ --verbose-llvm-cpu-features Enable compiler debug output for LLVM CPU features
\\ --debug-log [scope] Enable printing debug/info log messages for scope
\\
;
const repl_help =
\\Commands:
\\ update Detect changes to source files and update output files.
\\ help Print this text
\\ exit Quit this repl
\\
;
const SOName = union(enum) {
no,
yes_default_value,
yes: []const u8,
};
const EmitBin = union(enum) {
no,
yes_default_path,
yes: []const u8,
yes_a_out,
};
const Emit = union(enum) {
no,
yes_default_path,
yes: []const u8,
const Resolved = struct {
data: ?Compilation.EmitLoc,
dir: ?fs.Dir,
fn deinit(self: *Resolved) void {
if (self.dir) |*dir| {
dir.close();
}
}
};
fn resolve(emit: Emit, default_basename: []const u8) !Resolved {
var resolved: Resolved = .{ .data = null, .dir = null };
errdefer resolved.deinit();
switch (emit) {
.no => {},
.yes_default_path => {
resolved.data = Compilation.EmitLoc{
.directory = .{ .path = null, .handle = fs.cwd() },
.basename = default_basename,
};
},
.yes => |full_path| {
const basename = fs.path.basename(full_path);
if (fs.path.dirname(full_path)) |dirname| {
const handle = try fs.cwd().openDir(dirname, .{});
resolved = .{
.dir = handle,
.data = Compilation.EmitLoc{
.basename = basename,
.directory = .{
.path = dirname,
.handle = handle,
},
},
};
} else {
resolved.data = Compilation.EmitLoc{
.basename = basename,
.directory = .{ .path = null, .handle = fs.cwd() },
};
}
},
}
return resolved;
}
};
fn optionalStringEnvVar(arena: *Allocator, name: []const u8) !?[]const u8 {
if (std.process.getEnvVarOwned(arena, name)) |value| {
return value;
} else |err| switch (err) {
error.EnvironmentVariableNotFound => return null,
else => |e| return e,
}
}
fn buildOutputType(
gpa: *Allocator,
arena: *Allocator,
all_args: []const []const u8,
arg_mode: union(enum) {
build: std.builtin.OutputMode,
cc,
cpp,
translate_c,
zig_test,
run,
},
) !void {
var color: Color = .auto;
var optimize_mode: std.builtin.Mode = .Debug;
var provided_name: ?[]const u8 = null;
var link_mode: ?std.builtin.LinkMode = null;
var dll_export_fns: ?bool = null;
var root_src_file: ?[]const u8 = null;
var version: std.builtin.Version = .{ .major = 0, .minor = 0, .patch = 0 };
var have_version = false;
var strip = false;
var single_threaded = false;
var function_sections = false;
var watch = false;
var verbose_link = false;
var verbose_cc = false;
var verbose_tokenize = false;
var verbose_ast = false;
var verbose_ir = false;
var verbose_llvm_ir = false;
var verbose_cimport = false;
var verbose_llvm_cpu_features = false;
var time_report = false;
var stack_report = false;
var show_builtin = false;
var emit_bin: EmitBin = .yes_default_path;
var emit_asm: Emit = .no;
var emit_llvm_ir: Emit = .no;
var emit_zir: Emit = .no;
var emit_docs: Emit = .no;
var emit_analysis: Emit = .no;
var target_arch_os_abi: []const u8 = "native";
var target_mcpu: ?[]const u8 = null;
var target_dynamic_linker: ?[]const u8 = null;
var target_ofmt: ?[]const u8 = null;
var output_mode: std.builtin.OutputMode = undefined;
var emit_h: Emit = .no;
var soname: SOName = undefined;
var ensure_libc_on_non_freestanding = false;
var ensure_libcpp_on_non_freestanding = false;
var link_libc = false;
var link_libcpp = false;
var want_native_include_dirs = false;
var enable_cache: ?bool = null;
var want_pic: ?bool = null;
var want_pie: ?bool = null;
var want_lto: ?bool = null;
var want_sanitize_c: ?bool = null;
var want_stack_check: ?bool = null;
var want_red_zone: ?bool = null;
var want_valgrind: ?bool = null;
var want_tsan: ?bool = null;
var want_compiler_rt: ?bool = null;
var rdynamic: bool = false;
var linker_script: ?[]const u8 = null;
var version_script: ?[]const u8 = null;
var disable_c_depfile = false;
var linker_gc_sections: ?bool = null;
var linker_allow_shlib_undefined: ?bool = null;
var linker_bind_global_refs_locally: ?bool = null;
var linker_z_nodelete = false;
var linker_z_defs = false;
var linker_tsaware = false;
var linker_nxcompat = false;
var linker_dynamicbase = false;
var test_evented_io = false;
var stack_size_override: ?u64 = null;
var image_base_override: ?u64 = null;
var use_llvm: ?bool = null;
var use_lld: ?bool = null;
var use_clang: ?bool = null;
var link_eh_frame_hdr = false;
var link_emit_relocs = false;
var each_lib_rpath: ?bool = null;
var libc_paths_file: ?[]const u8 = try optionalStringEnvVar(arena, "ZIG_LIBC");
var machine_code_model: std.builtin.CodeModel = .default;
var runtime_args_start: ?usize = null;
var test_filter: ?[]const u8 = null;
var test_name_prefix: ?[]const u8 = null;
var override_local_cache_dir: ?[]const u8 = try optionalStringEnvVar(arena, "ZIG_LOCAL_CACHE_DIR");
var override_global_cache_dir: ?[]const u8 = try optionalStringEnvVar(arena, "ZIG_GLOBAL_CACHE_DIR");
var override_lib_dir: ?[]const u8 = try optionalStringEnvVar(arena, "ZIG_LIB_DIR");
var main_pkg_path: ?[]const u8 = null;
var clang_preprocessor_mode: Compilation.ClangPreprocessorMode = .no;
var subsystem: ?std.Target.SubSystem = null;
var major_subsystem_version: ?u32 = null;
var minor_subsystem_version: ?u32 = null;
var system_libs = std.ArrayList([]const u8).init(gpa);
defer system_libs.deinit();
var clang_argv = std.ArrayList([]const u8).init(gpa);
defer clang_argv.deinit();
var extra_cflags = std.ArrayList([]const u8).init(gpa);
defer extra_cflags.deinit();
var lld_argv = std.ArrayList([]const u8).init(gpa);
defer lld_argv.deinit();
var lib_dirs = std.ArrayList([]const u8).init(gpa);
defer lib_dirs.deinit();
var rpath_list = std.ArrayList([]const u8).init(gpa);
defer rpath_list.deinit();
var c_source_files = std.ArrayList(Compilation.CSourceFile).init(gpa);
defer c_source_files.deinit();
var link_objects = std.ArrayList([]const u8).init(gpa);
defer link_objects.deinit();
var framework_dirs = std.ArrayList([]const u8).init(gpa);
defer framework_dirs.deinit();
var frameworks = std.ArrayList([]const u8).init(gpa);
defer frameworks.deinit();
// null means replace with the test executable binary
var test_exec_args = std.ArrayList(?[]const u8).init(gpa);
defer test_exec_args.deinit();
const pkg_tree_root = try gpa.create(Package);
// This package only exists to clean up the code parsing --pkg-begin and
// --pkg-end flags. Use dummy values that are safe for the destroy call.
pkg_tree_root.* = .{
.root_src_directory = .{ .path = null, .handle = fs.cwd() },
.root_src_path = &[0]u8{},
};
defer pkg_tree_root.destroy(gpa);
var cur_pkg: *Package = pkg_tree_root;
switch (arg_mode) {
.build, .translate_c, .zig_test, .run => {
var optimize_mode_string: ?[]const u8 = null;
switch (arg_mode) {
.build => |m| {
output_mode = m;
},
.translate_c => {
emit_bin = .no;
output_mode = .Obj;
},
.zig_test, .run => {
output_mode = .Exe;
},
else => unreachable,
}
soname = .yes_default_value;
const args = all_args[2..];
var i: usize = 0;
args_loop: while (i < args.len) : (i += 1) {
const arg = args[i];
if (mem.startsWith(u8, arg, "-")) {
if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
try io.getStdOut().writeAll(usage_build_generic);
return cleanExit();
} else if (mem.eql(u8, arg, "--")) {
if (arg_mode == .run) {
// The index refers to all_args so skip `zig` `run`
// and `--`
runtime_args_start = i + 3;
break :args_loop;
} else {
fatal("unexpected end-of-parameter mark: --", .{});
}
} else if (mem.eql(u8, arg, "--pkg-begin")) {
if (i + 2 >= args.len) fatal("Expected 2 arguments after {s}", .{arg});
i += 1;
const pkg_name = args[i];
i += 1;
const pkg_path = args[i];
const new_cur_pkg = Package.create(
gpa,
fs.path.dirname(pkg_path),
fs.path.basename(pkg_path),
) catch |err| {
fatal("Failed to add package at path {s}: {s}", .{ pkg_path, @errorName(err) });
};
new_cur_pkg.parent = cur_pkg;
try cur_pkg.add(gpa, pkg_name, new_cur_pkg);
cur_pkg = new_cur_pkg;
} else if (mem.eql(u8, arg, "--pkg-end")) {
cur_pkg = cur_pkg.parent orelse
fatal("encountered --pkg-end with no matching --pkg-begin", .{});
} else if (mem.eql(u8, arg, "--main-pkg-path")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
main_pkg_path = args[i];
} else if (mem.eql(u8, arg, "-cflags")) {
extra_cflags.shrinkRetainingCapacity(0);
while (true) {
i += 1;
if (i + 1 >= args.len) fatal("expected -- after -cflags", .{});
if (mem.eql(u8, args[i], "--")) break;
try extra_cflags.append(args[i]);
}
} else if (mem.eql(u8, arg, "--color")) {
if (i + 1 >= args.len) {
fatal("expected [auto|on|off] after --color", .{});
}
i += 1;
const next_arg = args[i];
color = std.meta.stringToEnum(Color, next_arg) orelse {
fatal("expected [auto|on|off] after --color, found '{s}'", .{next_arg});
};
} else if (mem.eql(u8, arg, "--subsystem")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
if (mem.eql(u8, args[i], "console")) {
subsystem = .Console;
} else if (mem.eql(u8, args[i], "windows")) {
subsystem = .Windows;
} else if (mem.eql(u8, args[i], "posix")) {
subsystem = .Posix;
} else if (mem.eql(u8, args[i], "native")) {
subsystem = .Native;
} else if (mem.eql(u8, args[i], "efi_application")) {
subsystem = .EfiApplication;
} else if (mem.eql(u8, args[i], "efi_boot_service_driver")) {
subsystem = .EfiBootServiceDriver;
} else if (mem.eql(u8, args[i], "efi_rom")) {
subsystem = .EfiRom;
} else if (mem.eql(u8, args[i], "efi_runtime_driver")) {
subsystem = .EfiRuntimeDriver;
} else {
fatal("invalid: --subsystem: '{s}'. Options are:\n{s}", .{
args[i],
\\ console
\\ windows
\\ posix
\\ native
\\ efi_application
\\ efi_boot_service_driver
\\ efi_rom
\\ efi_runtime_driver
\\
});
}
} else if (mem.eql(u8, arg, "-O")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
optimize_mode_string = args[i];
} else if (mem.eql(u8, arg, "--stack")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
stack_size_override = std.fmt.parseUnsigned(u64, args[i], 0) catch |err| {
fatal("unable to parse '{s}': {s}", .{ arg, @errorName(err) });
};
} else if (mem.eql(u8, arg, "--image-base")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
image_base_override = std.fmt.parseUnsigned(u64, args[i], 0) catch |err| {
fatal("unable to parse '{s}': {s}", .{ arg, @errorName(err) });
};
} else if (mem.eql(u8, arg, "--name")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
provided_name = args[i];
} else if (mem.eql(u8, arg, "-rpath")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
try rpath_list.append(args[i]);
} else if (mem.eql(u8, arg, "--library-directory") or mem.eql(u8, arg, "-L")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
try lib_dirs.append(args[i]);
} else if (mem.eql(u8, arg, "-F")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
try framework_dirs.append(args[i]);
} else if (mem.eql(u8, arg, "-framework")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
try frameworks.append(args[i]);
} else if (mem.eql(u8, arg, "-T") or mem.eql(u8, arg, "--script")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
linker_script = args[i];
} else if (mem.eql(u8, arg, "--version-script")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
version_script = args[i];
} else if (mem.eql(u8, arg, "--library") or mem.eql(u8, arg, "-l")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
// We don't know whether this library is part of libc or libc++ until we resolve the target.
// So we simply append to the list for now.
i += 1;
try system_libs.append(args[i]);
} else if (mem.eql(u8, arg, "-D") or
mem.eql(u8, arg, "-isystem") or
mem.eql(u8, arg, "-I") or
mem.eql(u8, arg, "-dirafter"))
{
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
try clang_argv.append(arg);
try clang_argv.append(args[i]);
} else if (mem.eql(u8, arg, "--version")) {
if (i + 1 >= args.len) {
fatal("expected parameter after --version", .{});
}
i += 1;
version = std.builtin.Version.parse(args[i]) catch |err| {
fatal("unable to parse --version '{s}': {s}", .{ args[i], @errorName(err) });
};
have_version = true;
} else if (mem.eql(u8, arg, "-target")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
target_arch_os_abi = args[i];
} else if (mem.eql(u8, arg, "-mcpu")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
target_mcpu = args[i];
} else if (mem.eql(u8, arg, "-mcmodel")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
machine_code_model = parseCodeModel(args[i]);
} else if (mem.startsWith(u8, arg, "-ofmt=")) {
target_ofmt = arg["-ofmt=".len..];
} else if (mem.startsWith(u8, arg, "-mcpu=")) {
target_mcpu = arg["-mcpu=".len..];
} else if (mem.startsWith(u8, arg, "-mcmodel=")) {
machine_code_model = parseCodeModel(arg["-mcmodel=".len..]);
} else if (mem.startsWith(u8, arg, "-O")) {
optimize_mode_string = arg["-O".len..];
} else if (mem.eql(u8, arg, "--dynamic-linker")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
target_dynamic_linker = args[i];
} else if (mem.eql(u8, arg, "--libc")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
libc_paths_file = args[i];
} else if (mem.eql(u8, arg, "--test-filter")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
test_filter = args[i];
} else if (mem.eql(u8, arg, "--test-name-prefix")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
test_name_prefix = args[i];
} else if (mem.eql(u8, arg, "--test-cmd")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
try test_exec_args.append(args[i]);
} else if (mem.eql(u8, arg, "--cache-dir")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
override_local_cache_dir = args[i];
} else if (mem.eql(u8, arg, "--global-cache-dir")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
override_global_cache_dir = args[i];
} else if (mem.eql(u8, arg, "--override-lib-dir")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
override_lib_dir = args[i];
} else if (mem.eql(u8, arg, "--debug-log")) {
if (i + 1 >= args.len) fatal("expected parameter after {s}", .{arg});
i += 1;
try log_scopes.append(gpa, args[i]);
} else if (mem.eql(u8, arg, "-fcompiler-rt")) {
want_compiler_rt = true;
} else if (mem.eql(u8, arg, "-fno-compiler-rt")) {
want_compiler_rt = false;
} else if (mem.eql(u8, arg, "-feach-lib-rpath")) {
each_lib_rpath = true;
} else if (mem.eql(u8, arg, "-fno-each-lib-rpath")) {
each_lib_rpath = false;
} else if (mem.eql(u8, arg, "--enable-cache")) {
enable_cache = true;
} else if (mem.eql(u8, arg, "--test-cmd-bin")) {
try test_exec_args.append(null);
} else if (mem.eql(u8, arg, "--test-evented-io")) {
test_evented_io = true;
} else if (mem.eql(u8, arg, "--watch")) {
watch = true;
} else if (mem.eql(u8, arg, "-ftime-report")) {
time_report = true;
} else if (mem.eql(u8, arg, "-fstack-report")) {
stack_report = true;
} else if (mem.eql(u8, arg, "-fPIC")) {
want_pic = true;
} else if (mem.eql(u8, arg, "-fno-PIC")) {
want_pic = false;
} else if (mem.eql(u8, arg, "-fPIE")) {
want_pie = true;
} else if (mem.eql(u8, arg, "-fno-PIE")) {
want_pie = false;
} else if (mem.eql(u8, arg, "-flto")) {
want_lto = true;
} else if (mem.eql(u8, arg, "-fno-lto")) {
want_lto = false;
} else if (mem.eql(u8, arg, "-fstack-check")) {
want_stack_check = true;
} else if (mem.eql(u8, arg, "-fno-stack-check")) {
want_stack_check = false;
} else if (mem.eql(u8, arg, "-mred-zone")) {
want_red_zone = true;
} else if (mem.eql(u8, arg, "-mno-red-zone")) {
want_red_zone = false;
} else if (mem.eql(u8, arg, "-fsanitize-c")) {
want_sanitize_c = true;
} else if (mem.eql(u8, arg, "-fno-sanitize-c")) {
want_sanitize_c = false;
} else if (mem.eql(u8, arg, "-fvalgrind")) {
want_valgrind = true;
} else if (mem.eql(u8, arg, "-fno-valgrind")) {
want_valgrind = false;
} else if (mem.eql(u8, arg, "-fsanitize-thread")) {
want_tsan = true;
} else if (mem.eql(u8, arg, "-fno-sanitize-thread")) {
want_tsan = false;
} else if (mem.eql(u8, arg, "-fLLVM")) {
use_llvm = true;
} else if (mem.eql(u8, arg, "-fno-LLVM")) {
use_llvm = false;
} else if (mem.eql(u8, arg, "-fLLD")) {
use_lld = true;
} else if (mem.eql(u8, arg, "-fno-LLD")) {
use_lld = false;
} else if (mem.eql(u8, arg, "-fClang")) {
use_clang = true;
} else if (mem.eql(u8, arg, "-fno-Clang")) {
use_clang = false;
} else if (mem.eql(u8, arg, "-rdynamic")) {
rdynamic = true;
} else if (mem.eql(u8, arg, "-fsoname")) {
soname = .yes_default_value;
} else if (mem.startsWith(u8, arg, "-fsoname=")) {
soname = .{ .yes = arg["-fsoname=".len..] };
} else if (mem.eql(u8, arg, "-fno-soname")) {
soname = .no;
} else if (mem.eql(u8, arg, "-femit-bin")) {
emit_bin = .yes_default_path;
} else if (mem.startsWith(u8, arg, "-femit-bin=")) {
emit_bin = .{ .yes = arg["-femit-bin=".len..] };
} else if (mem.eql(u8, arg, "-fno-emit-bin")) {
emit_bin = .no;
} else if (mem.eql(u8, arg, "-femit-zir")) {
emit_zir = .yes_default_path;
} else if (mem.startsWith(u8, arg, "-femit-zir=")) {
emit_zir = .{ .yes = arg["-femit-zir=".len..] };
} else if (mem.eql(u8, arg, "-fno-emit-zir")) {
emit_zir = .no;
} else if (mem.eql(u8, arg, "-femit-h")) {
emit_h = .yes_default_path;
} else if (mem.startsWith(u8, arg, "-femit-h=")) {
emit_h = .{ .yes = arg["-femit-h=".len..] };
} else if (mem.eql(u8, arg, "-fno-emit-h")) {
emit_h = .no;
} else if (mem.eql(u8, arg, "-femit-asm")) {
emit_asm = .yes_default_path;
} else if (mem.startsWith(u8, arg, "-femit-asm=")) {
emit_asm = .{ .yes = arg["-femit-asm=".len..] };
} else if (mem.eql(u8, arg, "-fno-emit-asm")) {
emit_asm = .no;
} else if (mem.eql(u8, arg, "-femit-llvm-ir")) {
emit_llvm_ir = .yes_default_path;
} else if (mem.startsWith(u8, arg, "-femit-llvm-ir=")) {
emit_llvm_ir = .{ .yes = arg["-femit-llvm-ir=".len..] };
} else if (mem.eql(u8, arg, "-fno-emit-llvm-ir")) {
emit_llvm_ir = .no;
} else if (mem.eql(u8, arg, "-femit-docs")) {
emit_docs = .yes_default_path;
} else if (mem.startsWith(u8, arg, "-femit-docs=")) {
emit_docs = .{ .yes = arg["-femit-docs=".len..] };
} else if (mem.eql(u8, arg, "-fno-emit-docs")) {
emit_docs = .no;
} else if (mem.eql(u8, arg, "-femit-analysis")) {
emit_analysis = .yes_default_path;
} else if (mem.startsWith(u8, arg, "-femit-analysis=")) {
emit_analysis = .{ .yes = arg["-femit-analysis=".len..] };
} else if (mem.eql(u8, arg, "-fno-emit-analysis")) {
emit_analysis = .no;
} else if (mem.eql(u8, arg, "-dynamic")) {
link_mode = .Dynamic;
} else if (mem.eql(u8, arg, "-static")) {
link_mode = .Static;
} else if (mem.eql(u8, arg, "-fdll-export-fns")) {
dll_export_fns = true;
} else if (mem.eql(u8, arg, "-fno-dll-export-fns")) {
dll_export_fns = false;
} else if (mem.eql(u8, arg, "--show-builtin")) {
show_builtin = true;
emit_bin = .no;
} else if (mem.eql(u8, arg, "--strip")) {
strip = true;
} else if (mem.eql(u8, arg, "--single-threaded")) {
single_threaded = true;
} else if (mem.eql(u8, arg, "-ffunction-sections")) {
function_sections = true;
} else if (mem.eql(u8, arg, "--eh-frame-hdr")) {
link_eh_frame_hdr = true;
} else if (mem.eql(u8, arg, "--emit-relocs")) {
link_emit_relocs = true;
} else if (mem.eql(u8, arg, "-Bsymbolic")) {
linker_bind_global_refs_locally = true;
} else if (mem.eql(u8, arg, "--verbose-link")) {
verbose_link = true;
} else if (mem.eql(u8, arg, "--verbose-cc")) {
verbose_cc = true;
} else if (mem.eql(u8, arg, "--verbose-tokenize")) {
verbose_tokenize = true;
} else if (mem.eql(u8, arg, "--verbose-ast")) {
verbose_ast = true;
} else if (mem.eql(u8, arg, "--verbose-ir")) {
verbose_ir = true;
} else if (mem.eql(u8, arg, "--verbose-llvm-ir")) {
verbose_llvm_ir = true;
} else if (mem.eql(u8, arg, "--verbose-cimport")) {
verbose_cimport = true;
} else if (mem.eql(u8, arg, "--verbose-llvm-cpu-features")) {
verbose_llvm_cpu_features = true;
} else if (mem.startsWith(u8, arg, "-T")) {
linker_script = arg[2..];
} else if (mem.startsWith(u8, arg, "-L")) {
try lib_dirs.append(arg[2..]);
} else if (mem.startsWith(u8, arg, "-F")) {
try framework_dirs.append(arg[2..]);
} else if (mem.startsWith(u8, arg, "-l")) {
// We don't know whether this library is part of libc or libc++ until we resolve the target.
// So we simply append to the list for now.
try system_libs.append(arg[2..]);
} else if (mem.startsWith(u8, arg, "-D") or
mem.startsWith(u8, arg, "-I"))
{