-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
main.cpp
1706 lines (1596 loc) · 75.7 KB
/
main.cpp
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
/*
* Copyright (c) 2015 Andrew Kelley
*
* This file is part of zig, which is MIT licensed.
* See http://opensource.org/licenses/MIT
*/
#include "ast_render.hpp"
#include "buffer.hpp"
#include "codegen.hpp"
#include "compiler.hpp"
#include "config.h"
#include "error.hpp"
#include "heap.hpp"
#include "os.hpp"
#include "target.hpp"
#include "stage2.h"
#include "glibc.hpp"
#include "dump_analysis.hpp"
#include "mem_profile.hpp"
#include <stdio.h>
static int print_error_usage(const char *arg0) {
fprintf(stderr, "See `%s --help` for detailed usage information\n", arg0);
return EXIT_FAILURE;
}
static int print_full_usage(const char *arg0, FILE *file, int return_code) {
fprintf(file,
"Usage: %s [command] [options]\n"
"\n"
"Commands:\n"
" build build project from build.zig\n"
" build-exe [source] create executable from source or object files\n"
" build-lib [source] create library from source or object files\n"
" build-obj [source] create object from source or assembly\n"
" builtin show the source code of @import(\"builtin\")\n"
" cc use Zig as a drop-in C compiler\n"
" fmt parse files and render in canonical zig format\n"
" id print the base64-encoded compiler id\n"
" init-exe initialize a `zig build` application in the cwd\n"
" init-lib initialize a `zig build` library in the cwd\n"
" libc [paths_file] Display native libc paths file or validate one\n"
" run [source] [-- [args]] create executable and run immediately\n"
" translate-c [source] convert c code to zig code\n"
" targets list available compilation targets\n"
" test [source] create and run a test build\n"
" version print version number and exit\n"
" zen print zen of zig and exit\n"
"\n"
"Compile Options:\n"
" --c-source [options] [file] compile C source code\n"
" --cache-dir [path] override the local cache directory\n"
" --cache [auto|off|on] build in cache, print output path to stdout\n"
" --color [auto|off|on] enable or disable colored error messages\n"
" --disable-valgrind omit valgrind client requests in debug builds\n"
" --eh-frame-hdr enable C++ exception handling by passing --eh-frame-hdr to linker\n"
" --enable-valgrind include valgrind client requests release builds\n"
" -fstack-check enable stack probing in unsafe builds\n"
" -fno-stack-check disable stack probing in safe builds\n"
" -fsanitize-c enable C undefined behavior detection in unsafe builds\n"
" -fno-sanitize-c disable C undefined behavior detection in safe builds\n"
" --emit [asm|bin|llvm-ir] (deprecated) emit a specific file format as compilation output\n"
" -fPIC enable Position Independent Code\n"
" -fno-PIC disable Position Independent Code\n"
" -ftime-report print timing diagnostics\n"
" -fstack-report print stack size diagnostics\n"
" -fmem-report print memory usage diagnostics\n"
" -fdump-analysis write analysis.json file with type information\n"
" -femit-docs create a docs/ dir with html documentation\n"
" -fno-emit-docs do not produce docs/ dir with html documentation\n"
" -femit-bin (default) output machine code\n"
" -fno-emit-bin do not output machine code\n"
" -femit-asm output .s (assembly code)\n"
" -fno-emit-asm (default) do not output .s (assembly code)\n"
" -femit-llvm-ir produce a .ll file with LLVM IR\n"
" -fno-emit-llvm-ir (default) do not produce a .ll file with LLVM IR\n"
" -femit-h generate a C header file (.h)\n"
" -fno-emit-h (default) do not generate a C header file (.h)\n"
" --libc [file] Provide a file which specifies libc paths\n"
" --name [name] override output name\n"
" --output-dir [dir] override output directory (defaults to cwd)\n"
" --pkg-begin [name] [path] make pkg available to import and push current pkg\n"
" --pkg-end pop current pkg\n"
" --main-pkg-path set the directory of the root package\n"
" --release-fast build with optimizations on and safety off\n"
" --release-safe build with optimizations on and safety on\n"
" --release-small build with size optimizations on and safety off\n"
" --single-threaded source may assume it is only used single-threaded\n"
" -dynamic create a shared library (.so; .dll; .dylib)\n"
" --strip exclude debug symbols\n"
" -target [name] <arch>-<os>-<abi> see the targets command\n"
" --verbose-tokenize enable compiler debug output for tokenization\n"
" --verbose-ast enable compiler debug output for AST parsing\n"
" --verbose-link enable compiler debug output for linking\n"
" --verbose-ir enable compiler debug output for Zig IR\n"
" --verbose-llvm-ir enable compiler debug output for LLVM IR\n"
" --verbose-cimport enable compiler debug output for C imports\n"
" --verbose-cc enable compiler debug output for C compilation\n"
" --verbose-llvm-cpu-features enable compiler debug output for LLVM CPU features\n"
" -dirafter [dir] add directory to AFTER include search path\n"
" -isystem [dir] add directory to SYSTEM include search path\n"
" -I[dir] add directory to include search path\n"
" -mllvm [arg] (unsupported) forward an arg to LLVM's option processing\n"
" --override-lib-dir [arg] override path to Zig lib directory\n"
" -ffunction-sections places each function in a separate section\n"
" -D[macro]=[value] define C [macro] to [value] (1 if [value] omitted)\n"
" -mcpu [cpu] specify target CPU and feature set\n"
" -code-model [default|tiny| set target code model\n"
" small|kernel|\n"
" medium|large]\n"
"\n"
"Link Options:\n"
" --bundle-compiler-rt for static libraries, include compiler-rt symbols\n"
" --dynamic-linker [path] set the path to ld.so\n"
" --each-lib-rpath add rpath for each used dynamic library\n"
" --library [lib] link against lib\n"
" --forbid-library [lib] make it an error to link against lib\n"
" --library-path [dir] add a directory to the library search path\n"
" --linker-script [path] use a custom linker script\n"
" --version-script [path] provide a version .map file\n"
" --object [obj] add object file to build\n"
" -L[dir] alias for --library-path\n"
" -l[lib] alias for --library\n"
" -rdynamic add all symbols to the dynamic symbol table\n"
" -rpath [path] add directory to the runtime library search path\n"
" --subsystem [subsystem] (windows) /SUBSYSTEM:<subsystem> to the linker\n"
" -F[dir] (darwin) add search path for frameworks\n"
" -framework [name] (darwin) link against framework\n"
" --ver-major [ver] dynamic library semver major version\n"
" --ver-minor [ver] dynamic library semver minor version\n"
" --ver-patch [ver] dynamic library semver patch version\n"
"\n"
"Test Options:\n"
" --test-filter [text] skip tests that do not match filter\n"
" --test-name-prefix [text] add prefix to all tests\n"
" --test-cmd [arg] specify test execution command one arg at a time\n"
" --test-cmd-bin appends test binary path to test cmd args\n"
" --test-evented-io runs the test in evented I/O mode\n"
, arg0);
return return_code;
}
static int print_libc_usage(const char *arg0, FILE *file, int return_code) {
fprintf(file,
"Usage: %s libc\n"
"\n"
"Detect the native libc installation and print the resulting paths to stdout.\n"
"You can save this into a file and then edit the paths to create a cross\n"
"compilation libc kit. Then you can pass `--libc [file]` for Zig to use it.\n"
"\n"
"When compiling natively and no `--libc` argument provided, Zig will create\n"
"`%s/native_libc.txt`\n"
"so that it does not have to detect libc on every invocation. You can remove\n"
"this file to have Zig re-detect the native libc.\n"
"\n\n"
"Usage: %s libc [file]\n"
"\n"
"Parse a libc installation text file and validate it.\n"
, arg0, buf_ptr(get_global_cache_dir()), arg0);
return return_code;
}
enum Cmd {
CmdNone,
CmdBuild,
CmdBuiltin,
CmdRun,
CmdTargets,
CmdTest,
CmdTranslateC,
CmdVersion,
CmdZen,
CmdLibC,
};
static const char *default_zig_cache_name = "zig-cache";
struct CliPkg {
const char *name;
const char *path;
ZigList<CliPkg *> children;
CliPkg *parent;
};
static void add_package(CodeGen *g, CliPkg *cli_pkg, ZigPackage *pkg) {
for (size_t i = 0; i < cli_pkg->children.length; i += 1) {
CliPkg *child_cli_pkg = cli_pkg->children.at(i);
Buf *dirname = buf_alloc();
Buf *basename = buf_alloc();
os_path_split(buf_create_from_str(child_cli_pkg->path), dirname, basename);
ZigPackage *child_pkg = codegen_create_package(g, buf_ptr(dirname), buf_ptr(basename),
buf_ptr(buf_sprintf("%s.%s", buf_ptr(&pkg->pkg_path), child_cli_pkg->name)));
auto entry = pkg->package_table.put_unique(buf_create_from_str(child_cli_pkg->name), child_pkg);
if (entry) {
ZigPackage *existing_pkg = entry->value;
Buf *full_path = buf_alloc();
os_path_join(&existing_pkg->root_src_dir, &existing_pkg->root_src_path, full_path);
fprintf(stderr, "Unable to add package '%s'->'%s': already exists as '%s'\n",
child_cli_pkg->name, child_cli_pkg->path, buf_ptr(full_path));
exit(EXIT_FAILURE);
}
add_package(g, child_cli_pkg, child_pkg);
}
}
enum CacheOpt {
CacheOptAuto,
CacheOptOn,
CacheOptOff,
};
static bool get_cache_opt(CacheOpt opt, bool default_value) {
switch (opt) {
case CacheOptAuto:
return default_value;
case CacheOptOn:
return true;
case CacheOptOff:
return false;
}
zig_unreachable();
}
static int zig_error_no_build_file(void) {
fprintf(stderr,
"No 'build.zig' file found, in the current directory or any parent directories.\n"
"Initialize a 'build.zig' template file with `zig init-lib` or `zig init-exe`,\n"
"or see `zig --help` for more options.\n"
);
return EXIT_FAILURE;
}
static bool str_starts_with(const char *s1, const char *s2) {
size_t s2_len = strlen(s2);
if (strlen(s1) < s2_len) {
return false;
}
return memcmp(s1, s2, s2_len) == 0;
}
extern "C" int ZigClang_main(int argc, char **argv);
#ifdef ZIG_ENABLE_MEM_PROFILE
bool mem_report = false;
#endif
int main_exit(Stage2ProgressNode *root_progress_node, int exit_code) {
if (root_progress_node != nullptr) {
stage2_progress_end(root_progress_node);
}
return exit_code;
}
static int main0(int argc, char **argv) {
char *arg0 = argv[0];
Error err;
if (argc == 2 && strcmp(argv[1], "BUILD_INFO") == 0) {
printf("%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
ZIG_CMAKE_BINARY_DIR,
ZIG_CXX_COMPILER,
ZIG_LLVM_CONFIG_EXE,
ZIG_LLD_INCLUDE_PATH,
ZIG_LLD_LIBRARIES,
ZIG_CLANG_LIBRARIES,
ZIG_DIA_GUIDS_LIB);
return 0;
}
if (argc >= 2 && (strcmp(argv[1], "clang") == 0 ||
strcmp(argv[1], "-cc1") == 0 || strcmp(argv[1], "-cc1as") == 0))
{
return ZigClang_main(argc, argv);
}
if (argc == 2 && strcmp(argv[1], "id") == 0) {
Buf *compiler_id;
if ((err = get_compiler_id(&compiler_id))) {
fprintf(stderr, "Unable to determine compiler id: %s\n", err_str(err));
return EXIT_FAILURE;
}
printf("%s\n", buf_ptr(compiler_id));
return EXIT_SUCCESS;
}
enum InitKind {
InitKindNone,
InitKindExe,
InitKindLib,
};
InitKind init_kind = InitKindNone;
if (argc >= 2) {
const char *init_cmd = argv[1];
if (strcmp(init_cmd, "init-exe") == 0) {
init_kind = InitKindExe;
} else if (strcmp(init_cmd, "init-lib") == 0) {
init_kind = InitKindLib;
}
if (init_kind != InitKindNone) {
if (argc >= 3) {
fprintf(stderr, "Unexpected extra argument: %s\n", argv[2]);
return print_error_usage(arg0);
}
Buf *cmd_template_path = buf_alloc();
os_path_join(get_zig_special_dir(get_zig_lib_dir()), buf_create_from_str(init_cmd), cmd_template_path);
Buf *build_zig_path = buf_alloc();
os_path_join(cmd_template_path, buf_create_from_str("build.zig"), build_zig_path);
Buf *src_dir_path = buf_alloc();
os_path_join(cmd_template_path, buf_create_from_str("src"), src_dir_path);
Buf *main_zig_path = buf_alloc();
os_path_join(src_dir_path, buf_create_from_str("main.zig"), main_zig_path);
Buf *cwd = buf_alloc();
if ((err = os_get_cwd(cwd))) {
fprintf(stderr, "Unable to get cwd: %s\n", err_str(err));
return EXIT_FAILURE;
}
Buf *cwd_basename = buf_alloc();
os_path_split(cwd, nullptr, cwd_basename);
Buf *build_zig_contents = buf_alloc();
if ((err = os_fetch_file_path(build_zig_path, build_zig_contents))) {
fprintf(stderr, "Unable to read %s: %s\n", buf_ptr(build_zig_path), err_str(err));
return EXIT_FAILURE;
}
Buf *modified_build_zig_contents = buf_alloc();
for (size_t i = 0; i < buf_len(build_zig_contents); i += 1) {
char c = buf_ptr(build_zig_contents)[i];
if (c == '$') {
buf_append_buf(modified_build_zig_contents, cwd_basename);
} else {
buf_append_char(modified_build_zig_contents, c);
}
}
Buf *main_zig_contents = buf_alloc();
if ((err = os_fetch_file_path(main_zig_path, main_zig_contents))) {
fprintf(stderr, "Unable to read %s: %s\n", buf_ptr(main_zig_path), err_str(err));
return EXIT_FAILURE;
}
Buf *out_build_zig_path = buf_create_from_str("build.zig");
Buf *out_src_dir_path = buf_create_from_str("src");
Buf *out_main_zig_path = buf_alloc();
os_path_join(out_src_dir_path, buf_create_from_str("main.zig"), out_main_zig_path);
bool already_exists;
if ((err = os_file_exists(out_build_zig_path, &already_exists))) {
fprintf(stderr, "Unable test existence of %s: %s\n", buf_ptr(out_build_zig_path), err_str(err));
return EXIT_FAILURE;
}
if (already_exists) {
fprintf(stderr, "This file would be overwritten: %s\n", buf_ptr(out_build_zig_path));
return EXIT_FAILURE;
}
if ((err = os_make_dir(out_src_dir_path))) {
fprintf(stderr, "Unable to make directory: %s: %s\n", buf_ptr(out_src_dir_path), err_str(err));
return EXIT_FAILURE;
}
if ((err = os_write_file(out_build_zig_path, modified_build_zig_contents))) {
fprintf(stderr, "Unable to write file: %s: %s\n", buf_ptr(out_build_zig_path), err_str(err));
return EXIT_FAILURE;
}
if ((err = os_write_file(out_main_zig_path, main_zig_contents))) {
fprintf(stderr, "Unable to write file: %s: %s\n", buf_ptr(out_main_zig_path), err_str(err));
return EXIT_FAILURE;
}
fprintf(stderr, "Created %s\n", buf_ptr(out_build_zig_path));
fprintf(stderr, "Created %s\n", buf_ptr(out_main_zig_path));
if (init_kind == InitKindExe) {
fprintf(stderr, "\nNext, try `zig build --help` or `zig build run`\n");
} else if (init_kind == InitKindLib) {
fprintf(stderr, "\nNext, try `zig build --help` or `zig build test`\n");
} else {
zig_unreachable();
}
return EXIT_SUCCESS;
}
}
Cmd cmd = CmdNone;
const char *in_file = nullptr;
Buf *output_dir = nullptr;
bool strip = false;
bool is_dynamic = false;
OutType out_type = OutTypeUnknown;
const char *out_name = nullptr;
bool verbose_tokenize = false;
bool verbose_ast = false;
bool verbose_link = false;
bool verbose_ir = false;
bool verbose_llvm_ir = false;
bool verbose_cimport = false;
bool verbose_cc = false;
bool verbose_llvm_cpu_features = false;
bool link_eh_frame_hdr = false;
ErrColor color = ErrColorAuto;
CacheOpt enable_cache = CacheOptAuto;
const char *dynamic_linker = nullptr;
const char *libc_txt = nullptr;
ZigList<const char *> clang_argv = {0};
ZigList<const char *> lib_dirs = {0};
ZigList<const char *> link_libs = {0};
ZigList<const char *> forbidden_link_libs = {0};
ZigList<const char *> framework_dirs = {0};
ZigList<const char *> frameworks = {0};
bool have_libc = false;
const char *target_string = nullptr;
bool rdynamic = false;
const char *linker_script = nullptr;
Buf *version_script = nullptr;
ZigList<const char *> rpath_list = {0};
bool each_lib_rpath = false;
ZigList<const char *> objects = {0};
ZigList<CFile *> c_source_files = {0};
const char *test_filter = nullptr;
const char *test_name_prefix = nullptr;
bool test_evented_io = false;
size_t ver_major = 0;
size_t ver_minor = 0;
size_t ver_patch = 0;
bool timing_info = false;
bool stack_report = false;
bool enable_dump_analysis = false;
bool enable_doc_generation = false;
bool emit_bin = true;
const char *emit_bin_override_path = nullptr;
bool emit_asm = false;
bool emit_llvm_ir = false;
bool emit_h = false;
const char *cache_dir = nullptr;
CliPkg *cur_pkg = heap::c_allocator.create<CliPkg>();
BuildMode build_mode = BuildModeDebug;
ZigList<const char *> test_exec_args = {0};
int runtime_args_start = -1;
bool system_linker_hack = false;
TargetSubsystem subsystem = TargetSubsystemAuto;
bool want_single_threaded = false;
bool bundle_compiler_rt = false;
Buf *override_lib_dir = nullptr;
Buf *main_pkg_path = nullptr;
ValgrindSupport valgrind_support = ValgrindSupportAuto;
WantPIC want_pic = WantPICAuto;
WantStackCheck want_stack_check = WantStackCheckAuto;
WantCSanitize want_sanitize_c = WantCSanitizeAuto;
bool function_sections = false;
const char *mcpu = nullptr;
CodeModel code_model = CodeModelDefault;
const char *override_soname = nullptr;
bool only_preprocess = false;
ZigList<const char *> llvm_argv = {0};
llvm_argv.append("zig (LLVM option parsing)");
if (argc >= 2 && strcmp(argv[1], "build") == 0) {
Buf zig_exe_path_buf = BUF_INIT;
if ((err = os_self_exe_path(&zig_exe_path_buf))) {
fprintf(stderr, "Unable to determine path to zig's own executable\n");
return EXIT_FAILURE;
}
const char *zig_exe_path = buf_ptr(&zig_exe_path_buf);
const char *build_file = nullptr;
init_all_targets();
ZigList<const char *> args = {0};
args.append(NULL); // placeholder
args.append(zig_exe_path);
args.append(NULL); // placeholder
args.append(NULL); // placeholder
for (int i = 2; i < argc; i += 1) {
if (strcmp(argv[i], "--help") == 0) {
args.append(argv[i]);
} else if (i + 1 < argc && strcmp(argv[i], "--build-file") == 0) {
build_file = argv[i + 1];
i += 1;
} else if (i + 1 < argc && strcmp(argv[i], "--cache-dir") == 0) {
cache_dir = argv[i + 1];
i += 1;
} else if (i + 1 < argc && strcmp(argv[i], "--override-lib-dir") == 0) {
override_lib_dir = buf_create_from_str(argv[i + 1]);
i += 1;
args.append("--override-lib-dir");
args.append(buf_ptr(override_lib_dir));
} else {
args.append(argv[i]);
}
}
Buf *zig_lib_dir = (override_lib_dir == nullptr) ? get_zig_lib_dir() : override_lib_dir;
Buf *build_runner_path = buf_alloc();
os_path_join(get_zig_special_dir(zig_lib_dir), buf_create_from_str("build_runner.zig"), build_runner_path);
ZigTarget target;
if ((err = target_parse_triple(&target, "native", nullptr, nullptr))) {
fprintf(stderr, "Unable to get native target: %s\n", err_str(err));
return EXIT_FAILURE;
}
Buf *build_file_buf = buf_create_from_str((build_file != nullptr) ? build_file : "build.zig");
Buf build_file_abs = os_path_resolve(&build_file_buf, 1);
Buf build_file_basename = BUF_INIT;
Buf build_file_dirname = BUF_INIT;
os_path_split(&build_file_abs, &build_file_dirname, &build_file_basename);
for (;;) {
bool build_file_exists;
if ((err = os_file_exists(&build_file_abs, &build_file_exists))) {
fprintf(stderr, "unable to check existence of '%s': %s\n", buf_ptr(&build_file_abs), err_str(err));
return 1;
}
if (build_file_exists)
break;
if (build_file != nullptr) {
// they asked for a specific build file path. only look for that one
return zig_error_no_build_file();
}
Buf *next_dir = buf_alloc();
os_path_dirname(&build_file_dirname, next_dir);
if (buf_eql_buf(&build_file_dirname, next_dir)) {
// no more parent directories to search, give up
return zig_error_no_build_file();
}
os_path_join(next_dir, &build_file_basename, &build_file_abs);
buf_init_from_buf(&build_file_dirname, next_dir);
}
Buf full_cache_dir = BUF_INIT;
if (cache_dir == nullptr) {
os_path_join(&build_file_dirname, buf_create_from_str(default_zig_cache_name), &full_cache_dir);
} else {
Buf *cache_dir_buf = buf_create_from_str(cache_dir);
full_cache_dir = os_path_resolve(&cache_dir_buf, 1);
}
Stage2ProgressNode *root_progress_node = stage2_progress_start_root(stage2_progress_create(), "", 0, 0);
CodeGen *g = codegen_create(main_pkg_path, build_runner_path, &target, OutTypeExe,
BuildModeDebug, override_lib_dir, nullptr, &full_cache_dir, false, root_progress_node);
g->valgrind_support = valgrind_support;
g->enable_time_report = timing_info;
codegen_set_out_name(g, buf_create_from_str("build"));
args.items[2] = buf_ptr(&build_file_dirname);
args.items[3] = buf_ptr(&full_cache_dir);
ZigPackage *build_pkg = codegen_create_package(g, buf_ptr(&build_file_dirname),
buf_ptr(&build_file_basename), "std.special");
g->main_pkg->package_table.put(buf_create_from_str("@build"), build_pkg);
g->enable_cache = get_cache_opt(enable_cache, true);
codegen_build_and_link(g);
if (root_progress_node != nullptr) {
stage2_progress_end(root_progress_node);
root_progress_node = nullptr;
}
Termination term;
args.items[0] = buf_ptr(&g->bin_file_output_path);
os_spawn_process(args, &term);
if (term.how != TerminationIdClean || term.code != 0) {
fprintf(stderr, "\nBuild failed. The following command failed:\n");
const char *prefix = "";
for (size_t i = 0; i < args.length; i += 1) {
fprintf(stderr, "%s%s", prefix, args.at(i));
prefix = " ";
}
fprintf(stderr, "\n");
}
return (term.how == TerminationIdClean) ? term.code : -1;
} else if (argc >= 2 && strcmp(argv[1], "fmt") == 0) {
return stage2_fmt(argc, argv);
} else if (argc >= 2 && strcmp(argv[1], "cc") == 0) {
emit_h = false;
strip = true;
bool c_arg = false;
Stage2ClangArgIterator it;
stage2_clang_arg_iterator(&it, argc, argv);
bool nostdlib = false;
bool is_shared_lib = false;
ZigList<Buf *> linker_args = {};
while (it.has_next) {
if ((err = stage2_clang_arg_next(&it))) {
fprintf(stderr, "unable to parse command line parameters: %s\n", err_str(err));
return EXIT_FAILURE;
}
switch (it.kind) {
case Stage2ClangArgTarget: // example: -target riscv64-linux-unknown
target_string = it.only_arg;
break;
case Stage2ClangArgO: // -o
emit_bin_override_path = it.only_arg;
enable_cache = CacheOptOn;
break;
case Stage2ClangArgC: // -c
c_arg = true;
break;
case Stage2ClangArgOther:
for (size_t i = 0; i < it.other_args_len; i += 1) {
clang_argv.append(it.other_args_ptr[i]);
}
break;
case Stage2ClangArgPositional: {
Buf *arg_buf = buf_create_from_str(it.only_arg);
if (buf_ends_with_str(arg_buf, ".c") ||
buf_ends_with_str(arg_buf, ".C") ||
buf_ends_with_str(arg_buf, ".cc") ||
buf_ends_with_str(arg_buf, ".cpp") ||
buf_ends_with_str(arg_buf, ".cxx") ||
buf_ends_with_str(arg_buf, ".s") ||
buf_ends_with_str(arg_buf, ".S"))
{
CFile *c_file = heap::c_allocator.create<CFile>();
c_file->source_path = it.only_arg;
c_source_files.append(c_file);
} else {
objects.append(it.only_arg);
}
break;
}
case Stage2ClangArgL: // -l
if (strcmp(it.only_arg, "c") == 0)
have_libc = true;
link_libs.append(it.only_arg);
break;
case Stage2ClangArgIgnore:
break;
case Stage2ClangArgDriverPunt:
// Never mind what we're doing, just pass the args directly. For example --help.
return ZigClang_main(argc, argv);
case Stage2ClangArgPIC:
want_pic = WantPICEnabled;
break;
case Stage2ClangArgNoPIC:
want_pic = WantPICDisabled;
break;
case Stage2ClangArgNoStdLib:
nostdlib = true;
break;
case Stage2ClangArgShared:
is_dynamic = true;
is_shared_lib = true;
break;
case Stage2ClangArgRDynamic:
rdynamic = true;
break;
case Stage2ClangArgWL: {
const char *arg = it.only_arg;
for (;;) {
size_t pos = 0;
while (arg[pos] != ',' && arg[pos] != 0) pos += 1;
linker_args.append(buf_create_from_mem(arg, pos));
if (arg[pos] == 0) break;
arg += pos + 1;
}
break;
}
case Stage2ClangArgPreprocess:
only_preprocess = true;
break;
case Stage2ClangArgOptimize:
// alright what release mode do they want?
if (strcmp(it.only_arg, "Os") == 0) {
build_mode = BuildModeSmallRelease;
} else if (strcmp(it.only_arg, "O2") == 0 ||
strcmp(it.only_arg, "O3") == 0 ||
strcmp(it.only_arg, "O4") == 0)
{
build_mode = BuildModeFastRelease;
} else if (strcmp(it.only_arg, "Og") == 0) {
build_mode = BuildModeDebug;
} else {
for (size_t i = 0; i < it.other_args_len; i += 1) {
clang_argv.append(it.other_args_ptr[i]);
}
}
break;
case Stage2ClangArgDebug:
strip = false;
if (strcmp(it.only_arg, "-g") == 0) {
// we handled with strip = false above
} else {
for (size_t i = 0; i < it.other_args_len; i += 1) {
clang_argv.append(it.other_args_ptr[i]);
}
}
break;
case Stage2ClangArgSanitize:
if (strcmp(it.only_arg, "undefined") == 0) {
want_sanitize_c = WantCSanitizeEnabled;
} else {
for (size_t i = 0; i < it.other_args_len; i += 1) {
clang_argv.append(it.other_args_ptr[i]);
}
}
break;
}
}
// Parse linker args
for (size_t i = 0; i < linker_args.length; i += 1) {
Buf *arg = linker_args.at(i);
if (buf_eql_str(arg, "-soname")) {
i += 1;
if (i >= linker_args.length) {
fprintf(stderr, "expected linker arg after '%s'\n", buf_ptr(arg));
return EXIT_FAILURE;
}
Buf *soname_buf = linker_args.at(i);
override_soname = buf_ptr(soname_buf);
// use it as --name
// example: libsoundio.so.2
size_t prefix = 0;
if (buf_starts_with_str(soname_buf, "lib")) {
prefix = 3;
}
size_t end = buf_len(soname_buf);
if (buf_ends_with_str(soname_buf, ".so")) {
end -= 3;
} else {
bool found_digit = false;
while (end > 0 && isdigit(buf_ptr(soname_buf)[end - 1])) {
found_digit = true;
end -= 1;
}
if (found_digit && end > 0 && buf_ptr(soname_buf)[end - 1] == '.') {
end -= 1;
} else {
end = buf_len(soname_buf);
}
if (buf_ends_with_str(buf_slice(soname_buf, prefix, end), ".so")) {
end -= 3;
}
}
out_name = buf_ptr(buf_slice(soname_buf, prefix, end));
} else if (buf_eql_str(arg, "-rpath")) {
i += 1;
if (i >= linker_args.length) {
fprintf(stderr, "expected linker arg after '%s'\n", buf_ptr(arg));
return EXIT_FAILURE;
}
Buf *rpath = linker_args.at(i);
rpath_list.append(buf_ptr(rpath));
} else if (buf_eql_str(arg, "-I") ||
buf_eql_str(arg, "--dynamic-linker") ||
buf_eql_str(arg, "-dynamic-linker"))
{
i += 1;
if (i >= linker_args.length) {
fprintf(stderr, "expected linker arg after '%s'\n", buf_ptr(arg));
return EXIT_FAILURE;
}
dynamic_linker = buf_ptr(linker_args.at(i));
} else {
fprintf(stderr, "warning: unsupported linker arg: %s\n", buf_ptr(arg));
}
}
if (want_sanitize_c == WantCSanitizeEnabled && build_mode == BuildModeFastRelease) {
build_mode = BuildModeSafeRelease;
}
if (!nostdlib && !have_libc) {
have_libc = true;
link_libs.append("c");
}
if (only_preprocess) {
cmd = CmdBuild;
out_type = OutTypeObj;
emit_bin = false;
// Transfer "objects" into c_source_files
for (size_t i = 0; i < objects.length; i += 1) {
CFile *c_file = heap::c_allocator.create<CFile>();
c_file->source_path = objects.at(i);
c_source_files.append(c_file);
}
for (size_t i = 0; i < c_source_files.length; i += 1) {
Buf *src_path;
if (emit_bin_override_path != nullptr) {
src_path = buf_create_from_str(emit_bin_override_path);
} else {
src_path = buf_create_from_str(c_source_files.at(i)->source_path);
}
Buf basename = BUF_INIT;
os_path_split(src_path, nullptr, &basename);
c_source_files.at(i)->preprocessor_only_basename = buf_ptr(&basename);
}
} else if (!c_arg) {
cmd = CmdBuild;
if (is_shared_lib) {
out_type = OutTypeLib;
} else {
out_type = OutTypeExe;
}
if (emit_bin_override_path == nullptr) {
emit_bin_override_path = "a.out";
}
} else {
cmd = CmdBuild;
out_type = OutTypeObj;
}
if (c_source_files.length == 0 && objects.length == 0) {
// For example `zig cc` and no args should print the "no input files" message.
return ZigClang_main(argc, argv);
}
} else for (int i = 1; i < argc; i += 1) {
char *arg = argv[i];
if (arg[0] == '-') {
if (strcmp(arg, "--") == 0) {
if (cmd == CmdRun) {
runtime_args_start = i + 1;
break; // rest of the args are for the program
} else {
fprintf(stderr, "Unexpected end-of-parameter mark: %s\n", arg);
}
} else if (strcmp(arg, "--release-fast") == 0) {
build_mode = BuildModeFastRelease;
} else if (strcmp(arg, "--release-safe") == 0) {
build_mode = BuildModeSafeRelease;
} else if (strcmp(arg, "--release-small") == 0) {
build_mode = BuildModeSmallRelease;
} else if (strcmp(arg, "--help") == 0) {
if (cmd == CmdLibC) {
return print_libc_usage(arg0, stdout, EXIT_SUCCESS);
} else {
return print_full_usage(arg0, stdout, EXIT_SUCCESS);
}
} else if (strcmp(arg, "--strip") == 0) {
strip = true;
} else if (strcmp(arg, "-dynamic") == 0) {
is_dynamic = true;
} else if (strcmp(arg, "--verbose-tokenize") == 0) {
verbose_tokenize = true;
} else if (strcmp(arg, "--verbose-ast") == 0) {
verbose_ast = true;
} else if (strcmp(arg, "--verbose-link") == 0) {
verbose_link = true;
} else if (strcmp(arg, "--verbose-ir") == 0) {
verbose_ir = true;
} else if (strcmp(arg, "--verbose-llvm-ir") == 0) {
verbose_llvm_ir = true;
} else if (strcmp(arg, "--verbose-cimport") == 0) {
verbose_cimport = true;
} else if (strcmp(arg, "--verbose-cc") == 0) {
verbose_cc = true;
} else if (strcmp(arg, "--verbose-llvm-cpu-features") == 0) {
verbose_llvm_cpu_features = true;
} else if (strcmp(arg, "-rdynamic") == 0) {
rdynamic = true;
} else if (strcmp(arg, "--each-lib-rpath") == 0) {
each_lib_rpath = true;
} else if (strcmp(arg, "-ftime-report") == 0) {
timing_info = true;
} else if (strcmp(arg, "-fstack-report") == 0) {
stack_report = true;
} else if (strcmp(arg, "-fmem-report") == 0) {
#ifdef ZIG_ENABLE_MEM_PROFILE
mem_report = true;
mem::report_print = true;
#else
fprintf(stderr, "-fmem-report requires configuring with -DZIG_ENABLE_MEM_PROFILE=ON\n");
return print_error_usage(arg0);
#endif
} else if (strcmp(arg, "-fdump-analysis") == 0) {
enable_dump_analysis = true;
} else if (strcmp(arg, "-femit-docs") == 0) {
enable_doc_generation = true;
} else if (strcmp(arg, "--enable-valgrind") == 0) {
valgrind_support = ValgrindSupportEnabled;
} else if (strcmp(arg, "--disable-valgrind") == 0) {
valgrind_support = ValgrindSupportDisabled;
} else if (strcmp(arg, "--eh-frame-hdr") == 0) {
link_eh_frame_hdr = true;
} else if (strcmp(arg, "-fPIC") == 0) {
want_pic = WantPICEnabled;
} else if (strcmp(arg, "-fno-PIC") == 0) {
want_pic = WantPICDisabled;
} else if (strcmp(arg, "-fstack-check") == 0) {
want_stack_check = WantStackCheckEnabled;
} else if (strcmp(arg, "-fno-stack-check") == 0) {
want_stack_check = WantStackCheckDisabled;
} else if (strcmp(arg, "-fsanitize-c") == 0) {
want_sanitize_c = WantCSanitizeEnabled;
} else if (strcmp(arg, "-fno-sanitize-c") == 0) {
want_sanitize_c = WantCSanitizeDisabled;
} else if (strcmp(arg, "--system-linker-hack") == 0) {
system_linker_hack = true;
} else if (strcmp(arg, "--single-threaded") == 0) {
want_single_threaded = true;;
} else if (strcmp(arg, "--bundle-compiler-rt") == 0) {
bundle_compiler_rt = true;
} else if (strcmp(arg, "--test-cmd-bin") == 0) {
test_exec_args.append(nullptr);
} else if (arg[1] == 'D' && arg[2] != 0) {
clang_argv.append("-D");
clang_argv.append(&arg[2]);
} else if (arg[1] == 'L' && arg[2] != 0) {
// alias for --library-path
lib_dirs.append(&arg[2]);
} else if (arg[1] == 'l' && arg[2] != 0) {
// alias for --library
const char *l = &arg[2];
if (strcmp(l, "c") == 0)
have_libc = true;
link_libs.append(l);
} else if (arg[1] == 'I' && arg[2] != 0) {
clang_argv.append("-I");
clang_argv.append(&arg[2]);
} else if (arg[1] == 'F' && arg[2] != 0) {
framework_dirs.append(&arg[2]);
} else if (strcmp(arg, "--pkg-begin") == 0) {
if (i + 2 >= argc) {
fprintf(stderr, "Expected 2 arguments after --pkg-begin\n");
return print_error_usage(arg0);
}
CliPkg *new_cur_pkg = heap::c_allocator.create<CliPkg>();
i += 1;
new_cur_pkg->name = argv[i];
i += 1;
new_cur_pkg->path = argv[i];
new_cur_pkg->parent = cur_pkg;
cur_pkg->children.append(new_cur_pkg);
cur_pkg = new_cur_pkg;
} else if (strcmp(arg, "--pkg-end") == 0) {
if (cur_pkg->parent == nullptr) {
fprintf(stderr, "Encountered --pkg-end with no matching --pkg-begin\n");
return EXIT_FAILURE;
}
cur_pkg = cur_pkg->parent;
} else if (strcmp(arg, "-ffunction-sections") == 0) {
function_sections = true;
} else if (strcmp(arg, "--test-evented-io") == 0) {
test_evented_io = true;
} else if (strcmp(arg, "-femit-bin") == 0) {
emit_bin = true;
} else if (strcmp(arg, "-fno-emit-bin") == 0) {
emit_bin = false;
} else if (strcmp(arg, "-femit-asm") == 0) {
emit_asm = true;
} else if (strcmp(arg, "-fno-emit-asm") == 0) {
emit_asm = false;
} else if (strcmp(arg, "-femit-llvm-ir") == 0) {
emit_llvm_ir = true;
} else if (strcmp(arg, "-fno-emit-llvm-ir") == 0) {
emit_llvm_ir = false;
} else if (strcmp(arg, "-femit-h") == 0) {
emit_h = true;
} else if (strcmp(arg, "-fno-emit-h") == 0 || strcmp(arg, "--disable-gen-h") == 0) {
// the --disable-gen-h is there to support godbolt. once they upgrade to -fno-emit-h then we can remove this
emit_h = false;
} else if (str_starts_with(arg, "-mcpu=")) {
mcpu = arg + strlen("-mcpu=");
} else if (i + 1 >= argc) {
fprintf(stderr, "Expected another argument after %s\n", arg);
return print_error_usage(arg0);
} else {
i += 1;
if (strcmp(arg, "--output-dir") == 0) {
output_dir = buf_create_from_str(argv[i]);
} else if (strcmp(arg, "--color") == 0) {
if (strcmp(argv[i], "auto") == 0) {
color = ErrColorAuto;
} else if (strcmp(argv[i], "on") == 0) {
color = ErrColorOn;
} else if (strcmp(argv[i], "off") == 0) {
color = ErrColorOff;
} else {
fprintf(stderr, "--color options are 'auto', 'on', or 'off'\n");
return print_error_usage(arg0);
}
} else if (strcmp(arg, "--cache") == 0) {
if (strcmp(argv[i], "auto") == 0) {
enable_cache = CacheOptAuto;
} else if (strcmp(argv[i], "on") == 0) {
enable_cache = CacheOptOn;
} else if (strcmp(argv[i], "off") == 0) {
enable_cache = CacheOptOff;
} else {
fprintf(stderr, "--cache options are 'auto', 'on', or 'off'\n");
return print_error_usage(arg0);
}
} else if (strcmp(arg, "--emit") == 0) {
if (strcmp(argv[i], "asm") == 0) {
emit_asm = true;
emit_bin = false;
} else if (strcmp(argv[i], "bin") == 0) {
emit_bin = true;
} else if (strcmp(argv[i], "llvm-ir") == 0) {
emit_llvm_ir = true;
emit_bin = false;