forked from ziglang/zig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBuild.zig
2893 lines (2620 loc) · 107 KB
/
Build.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.zig");
const builtin = @import("builtin");
const io = std.io;
const fs = std.fs;
const mem = std.mem;
const debug = std.debug;
const panic = std.debug.panic;
const assert = debug.assert;
const log = std.log;
const ArrayList = std.ArrayList;
const StringHashMap = std.StringHashMap;
const Allocator = mem.Allocator;
const Target = std.Target;
const process = std.process;
const EnvMap = std.process.EnvMap;
const File = fs.File;
const Sha256 = std.crypto.hash.sha2.Sha256;
const Build = @This();
pub const Cache = @import("Build/Cache.zig");
pub const Step = @import("Build/Step.zig");
pub const Module = @import("Build/Module.zig");
pub const Watch = @import("Build/Watch.zig");
pub const Fuzz = @import("Build/Fuzz.zig");
const ThreadLocalData = struct {
running_step: ?*Step = null,
};
pub threadlocal var thread_local: ThreadLocalData = .{};
/// Shared state among all Build instances.
graph: *Graph,
install_tls: TopLevelStep,
uninstall_tls: TopLevelStep,
allocator: Allocator,
user_input_options: UserInputOptionsMap,
available_options_map: AvailableOptionsMap,
available_options_list: ArrayList(AvailableOption),
verbose: bool,
verbose_link: bool,
verbose_cc: bool,
verbose_air: bool,
verbose_llvm_ir: ?[]const u8,
verbose_llvm_bc: ?[]const u8,
verbose_cimport: bool,
verbose_llvm_cpu_features: bool,
reference_trace: ?u32 = null,
invalid_user_input: bool,
default_step: *Step,
top_level_steps: std.StringArrayHashMapUnmanaged(*TopLevelStep),
install_prefix: []const u8,
dest_dir: ?[]const u8,
lib_dir: []const u8,
exe_dir: []const u8,
h_dir: []const u8,
install_path: []const u8,
sysroot: ?[]const u8 = null,
search_prefixes: std.ArrayListUnmanaged([]const u8),
libc_file: ?[]const u8 = null,
/// Path to the directory containing build.zig.
build_root: Cache.Directory,
cache_root: Cache.Directory,
pkg_config_pkg_list: ?(PkgConfigError![]const PkgConfigPkg) = null,
args: ?[]const []const u8 = null,
debug_log_scopes: []const []const u8 = &.{},
debug_compile_errors: bool = false,
debug_pkg_config: bool = false,
/// Number of stack frames captured when a `StackTrace` is recorded for debug purposes,
/// in particular at `Step` creation.
/// Set to 0 to disable stack collection.
debug_stack_frames_count: u8 = 8,
/// Experimental. Use system Darling installation to run cross compiled macOS build artifacts.
enable_darling: bool = false,
/// Use system QEMU installation to run cross compiled foreign architecture build artifacts.
enable_qemu: bool = false,
/// Darwin. Use Rosetta to run x86_64 macOS build artifacts on arm64 macOS.
enable_rosetta: bool = false,
/// Use system Wasmtime installation to run cross compiled wasm/wasi build artifacts.
enable_wasmtime: bool = false,
/// Use system Wine installation to run cross compiled Windows build artifacts.
enable_wine: bool = false,
/// After following the steps in https://github.com/ziglang/zig/wiki/Updating-libc#glibc,
/// this will be the directory $glibc-build-dir/install/glibcs
/// Given the example of the aarch64 target, this is the directory
/// that contains the path `aarch64-linux-gnu/lib/ld-linux-aarch64.so.1`.
glibc_runtimes_dir: ?[]const u8 = null,
dep_prefix: []const u8 = "",
modules: std.StringArrayHashMap(*Module),
named_writefiles: std.StringArrayHashMap(*Step.WriteFile),
named_lazy_paths: std.StringArrayHashMap(LazyPath),
/// The hash of this instance's package. `""` means that this is the root package.
pkg_hash: []const u8,
/// A mapping from dependency names to package hashes.
available_deps: AvailableDeps,
release_mode: ReleaseMode,
pub const ReleaseMode = enum {
off,
any,
fast,
safe,
small,
};
/// Shared state among all Build instances.
/// Settings that are here rather than in Build are not configurable per-package.
pub const Graph = struct {
arena: Allocator,
system_library_options: std.StringArrayHashMapUnmanaged(SystemLibraryMode) = .empty,
system_package_mode: bool = false,
debug_compiler_runtime_libs: bool = false,
cache: Cache,
zig_exe: [:0]const u8,
env_map: EnvMap,
global_cache_root: Cache.Directory,
zig_lib_directory: Cache.Directory,
needed_lazy_dependencies: std.StringArrayHashMapUnmanaged(void) = .empty,
/// Information about the native target. Computed before build() is invoked.
host: ResolvedTarget,
incremental: ?bool = null,
random_seed: u32 = 0,
dependency_cache: InitializedDepMap = .empty,
allow_so_scripts: ?bool = null,
};
const AvailableDeps = []const struct { []const u8, []const u8 };
const SystemLibraryMode = enum {
/// User asked for the library to be disabled.
/// The build runner has not confirmed whether the setting is recognized yet.
user_disabled,
/// User asked for the library to be enabled.
/// The build runner has not confirmed whether the setting is recognized yet.
user_enabled,
/// The build runner has confirmed that this setting is recognized.
/// System integration with this library has been resolved to off.
declared_disabled,
/// The build runner has confirmed that this setting is recognized.
/// System integration with this library has been resolved to on.
declared_enabled,
};
const InitializedDepMap = std.HashMapUnmanaged(InitializedDepKey, *Dependency, InitializedDepContext, std.hash_map.default_max_load_percentage);
const InitializedDepKey = struct {
build_root_string: []const u8,
user_input_options: UserInputOptionsMap,
};
const InitializedDepContext = struct {
allocator: Allocator,
pub fn hash(ctx: @This(), k: InitializedDepKey) u64 {
var hasher = std.hash.Wyhash.init(0);
hasher.update(k.build_root_string);
hashUserInputOptionsMap(ctx.allocator, k.user_input_options, &hasher);
return hasher.final();
}
pub fn eql(_: @This(), lhs: InitializedDepKey, rhs: InitializedDepKey) bool {
if (!std.mem.eql(u8, lhs.build_root_string, rhs.build_root_string))
return false;
if (lhs.user_input_options.count() != rhs.user_input_options.count())
return false;
var it = lhs.user_input_options.iterator();
while (it.next()) |lhs_entry| {
const rhs_value = rhs.user_input_options.get(lhs_entry.key_ptr.*) orelse return false;
if (!userValuesAreSame(lhs_entry.value_ptr.*.value, rhs_value.value))
return false;
}
return true;
}
};
pub const RunError = error{
ReadFailure,
ExitCodeFailure,
ProcessTerminated,
ExecNotSupported,
} || std.process.Child.SpawnError;
pub const PkgConfigError = error{
PkgConfigCrashed,
PkgConfigFailed,
PkgConfigNotInstalled,
PkgConfigInvalidOutput,
};
pub const PkgConfigPkg = struct {
name: []const u8,
desc: []const u8,
};
const UserInputOptionsMap = StringHashMap(UserInputOption);
const AvailableOptionsMap = StringHashMap(AvailableOption);
const AvailableOption = struct {
name: []const u8,
type_id: TypeId,
description: []const u8,
/// If the `type_id` is `enum` or `enum_list` this provides the list of enum options
enum_options: ?[]const []const u8,
};
const UserInputOption = struct {
name: []const u8,
value: UserValue,
used: bool,
};
const UserValue = union(enum) {
flag: void,
scalar: []const u8,
list: ArrayList([]const u8),
map: StringHashMap(*const UserValue),
lazy_path: LazyPath,
lazy_path_list: ArrayList(LazyPath),
};
const TypeId = enum {
bool,
int,
float,
@"enum",
enum_list,
string,
list,
build_id,
lazy_path,
lazy_path_list,
};
const TopLevelStep = struct {
pub const base_id: Step.Id = .top_level;
step: Step,
description: []const u8,
};
pub const DirList = struct {
lib_dir: ?[]const u8 = null,
exe_dir: ?[]const u8 = null,
include_dir: ?[]const u8 = null,
};
pub fn create(
graph: *Graph,
build_root: Cache.Directory,
cache_root: Cache.Directory,
available_deps: AvailableDeps,
) error{OutOfMemory}!*Build {
const arena = graph.arena;
const b = try arena.create(Build);
b.* = .{
.graph = graph,
.build_root = build_root,
.cache_root = cache_root,
.verbose = false,
.verbose_link = false,
.verbose_cc = false,
.verbose_air = false,
.verbose_llvm_ir = null,
.verbose_llvm_bc = null,
.verbose_cimport = false,
.verbose_llvm_cpu_features = false,
.invalid_user_input = false,
.allocator = arena,
.user_input_options = UserInputOptionsMap.init(arena),
.available_options_map = AvailableOptionsMap.init(arena),
.available_options_list = ArrayList(AvailableOption).init(arena),
.top_level_steps = .{},
.default_step = undefined,
.search_prefixes = .{},
.install_prefix = undefined,
.lib_dir = undefined,
.exe_dir = undefined,
.h_dir = undefined,
.dest_dir = graph.env_map.get("DESTDIR"),
.install_tls = .{
.step = Step.init(.{
.id = TopLevelStep.base_id,
.name = "install",
.owner = b,
}),
.description = "Copy build artifacts to prefix path",
},
.uninstall_tls = .{
.step = Step.init(.{
.id = TopLevelStep.base_id,
.name = "uninstall",
.owner = b,
.makeFn = makeUninstall,
}),
.description = "Remove build artifacts from prefix path",
},
.install_path = undefined,
.args = null,
.modules = .init(arena),
.named_writefiles = .init(arena),
.named_lazy_paths = .init(arena),
.pkg_hash = "",
.available_deps = available_deps,
.release_mode = .off,
};
try b.top_level_steps.put(arena, b.install_tls.step.name, &b.install_tls);
try b.top_level_steps.put(arena, b.uninstall_tls.step.name, &b.uninstall_tls);
b.default_step = &b.install_tls.step;
return b;
}
fn createChild(
parent: *Build,
dep_name: []const u8,
build_root: Cache.Directory,
pkg_hash: []const u8,
pkg_deps: AvailableDeps,
user_input_options: UserInputOptionsMap,
) error{OutOfMemory}!*Build {
const child = try createChildOnly(parent, dep_name, build_root, pkg_hash, pkg_deps, user_input_options);
try determineAndApplyInstallPrefix(child);
return child;
}
fn createChildOnly(
parent: *Build,
dep_name: []const u8,
build_root: Cache.Directory,
pkg_hash: []const u8,
pkg_deps: AvailableDeps,
user_input_options: UserInputOptionsMap,
) error{OutOfMemory}!*Build {
const allocator = parent.allocator;
const child = try allocator.create(Build);
child.* = .{
.graph = parent.graph,
.allocator = allocator,
.install_tls = .{
.step = Step.init(.{
.id = TopLevelStep.base_id,
.name = "install",
.owner = child,
}),
.description = "Copy build artifacts to prefix path",
},
.uninstall_tls = .{
.step = Step.init(.{
.id = TopLevelStep.base_id,
.name = "uninstall",
.owner = child,
.makeFn = makeUninstall,
}),
.description = "Remove build artifacts from prefix path",
},
.user_input_options = user_input_options,
.available_options_map = AvailableOptionsMap.init(allocator),
.available_options_list = ArrayList(AvailableOption).init(allocator),
.verbose = parent.verbose,
.verbose_link = parent.verbose_link,
.verbose_cc = parent.verbose_cc,
.verbose_air = parent.verbose_air,
.verbose_llvm_ir = parent.verbose_llvm_ir,
.verbose_llvm_bc = parent.verbose_llvm_bc,
.verbose_cimport = parent.verbose_cimport,
.verbose_llvm_cpu_features = parent.verbose_llvm_cpu_features,
.reference_trace = parent.reference_trace,
.invalid_user_input = false,
.default_step = undefined,
.top_level_steps = .{},
.install_prefix = undefined,
.dest_dir = parent.dest_dir,
.lib_dir = parent.lib_dir,
.exe_dir = parent.exe_dir,
.h_dir = parent.h_dir,
.install_path = parent.install_path,
.sysroot = parent.sysroot,
.search_prefixes = parent.search_prefixes,
.libc_file = parent.libc_file,
.build_root = build_root,
.cache_root = parent.cache_root,
.debug_log_scopes = parent.debug_log_scopes,
.debug_compile_errors = parent.debug_compile_errors,
.debug_pkg_config = parent.debug_pkg_config,
.enable_darling = parent.enable_darling,
.enable_qemu = parent.enable_qemu,
.enable_rosetta = parent.enable_rosetta,
.enable_wasmtime = parent.enable_wasmtime,
.enable_wine = parent.enable_wine,
.glibc_runtimes_dir = parent.glibc_runtimes_dir,
.dep_prefix = parent.fmt("{s}{s}.", .{ parent.dep_prefix, dep_name }),
.modules = .init(allocator),
.named_writefiles = .init(allocator),
.named_lazy_paths = .init(allocator),
.pkg_hash = pkg_hash,
.available_deps = pkg_deps,
.release_mode = parent.release_mode,
};
try child.top_level_steps.put(allocator, child.install_tls.step.name, &child.install_tls);
try child.top_level_steps.put(allocator, child.uninstall_tls.step.name, &child.uninstall_tls);
child.default_step = &child.install_tls.step;
return child;
}
fn userInputOptionsFromArgs(allocator: Allocator, args: anytype) UserInputOptionsMap {
var user_input_options = UserInputOptionsMap.init(allocator);
inline for (@typeInfo(@TypeOf(args)).@"struct".fields) |field| {
const v = @field(args, field.name);
const T = @TypeOf(v);
switch (T) {
Target.Query => {
user_input_options.put(field.name, .{
.name = field.name,
.value = .{ .scalar = v.zigTriple(allocator) catch @panic("OOM") },
.used = false,
}) catch @panic("OOM");
user_input_options.put("cpu", .{
.name = "cpu",
.value = .{ .scalar = v.serializeCpuAlloc(allocator) catch @panic("OOM") },
.used = false,
}) catch @panic("OOM");
},
ResolvedTarget => {
user_input_options.put(field.name, .{
.name = field.name,
.value = .{ .scalar = v.query.zigTriple(allocator) catch @panic("OOM") },
.used = false,
}) catch @panic("OOM");
user_input_options.put("cpu", .{
.name = "cpu",
.value = .{ .scalar = v.query.serializeCpuAlloc(allocator) catch @panic("OOM") },
.used = false,
}) catch @panic("OOM");
},
LazyPath => {
user_input_options.put(field.name, .{
.name = field.name,
.value = .{ .lazy_path = v.dupeInner(allocator) },
.used = false,
}) catch @panic("OOM");
},
[]const LazyPath => {
var list = ArrayList(LazyPath).initCapacity(allocator, v.len) catch @panic("OOM");
for (v) |lp| list.appendAssumeCapacity(lp.dupeInner(allocator));
user_input_options.put(field.name, .{
.name = field.name,
.value = .{ .lazy_path_list = list },
.used = false,
}) catch @panic("OOM");
},
[]const u8 => {
user_input_options.put(field.name, .{
.name = field.name,
.value = .{ .scalar = v },
.used = false,
}) catch @panic("OOM");
},
[]const []const u8 => {
var list = ArrayList([]const u8).initCapacity(allocator, v.len) catch @panic("OOM");
list.appendSliceAssumeCapacity(v);
user_input_options.put(field.name, .{
.name = field.name,
.value = .{ .list = list },
.used = false,
}) catch @panic("OOM");
},
else => switch (@typeInfo(T)) {
.bool => {
user_input_options.put(field.name, .{
.name = field.name,
.value = .{ .scalar = if (v) "true" else "false" },
.used = false,
}) catch @panic("OOM");
},
.@"enum", .enum_literal => {
user_input_options.put(field.name, .{
.name = field.name,
.value = .{ .scalar = @tagName(v) },
.used = false,
}) catch @panic("OOM");
},
.comptime_int, .int => {
user_input_options.put(field.name, .{
.name = field.name,
.value = .{ .scalar = std.fmt.allocPrint(allocator, "{d}", .{v}) catch @panic("OOM") },
.used = false,
}) catch @panic("OOM");
},
.comptime_float, .float => {
user_input_options.put(field.name, .{
.name = field.name,
.value = .{ .scalar = std.fmt.allocPrint(allocator, "{e}", .{v}) catch @panic("OOM") },
.used = false,
}) catch @panic("OOM");
},
else => @compileError("option '" ++ field.name ++ "' has unsupported type: " ++ @typeName(T)),
},
}
}
return user_input_options;
}
const OrderedUserValue = union(enum) {
flag: void,
scalar: []const u8,
list: ArrayList([]const u8),
map: ArrayList(Pair),
lazy_path: LazyPath,
lazy_path_list: ArrayList(LazyPath),
const Pair = struct {
name: []const u8,
value: OrderedUserValue,
fn lessThan(_: void, lhs: Pair, rhs: Pair) bool {
return std.ascii.lessThanIgnoreCase(lhs.name, rhs.name);
}
};
fn hash(val: OrderedUserValue, hasher: *std.hash.Wyhash) void {
hasher.update(&std.mem.toBytes(std.meta.activeTag(val)));
switch (val) {
.flag => {},
.scalar => |scalar| hasher.update(scalar),
// lists are already ordered
.list => |list| for (list.items) |list_entry|
hasher.update(list_entry),
.map => |map| for (map.items) |map_entry| {
hasher.update(map_entry.name);
map_entry.value.hash(hasher);
},
.lazy_path => |lp| hashLazyPath(lp, hasher),
.lazy_path_list => |lp_list| for (lp_list.items) |lp| {
hashLazyPath(lp, hasher);
},
}
}
fn hashLazyPath(lp: LazyPath, hasher: *std.hash.Wyhash) void {
switch (lp) {
.src_path => |sp| {
hasher.update(sp.owner.pkg_hash);
hasher.update(sp.sub_path);
},
.generated => |gen| {
hasher.update(gen.file.step.owner.pkg_hash);
hasher.update(std.mem.asBytes(&gen.up));
hasher.update(gen.sub_path);
},
.cwd_relative => |rel_path| {
hasher.update(rel_path);
},
.dependency => |dep| {
hasher.update(dep.dependency.builder.pkg_hash);
hasher.update(dep.sub_path);
},
}
}
fn mapFromUnordered(allocator: Allocator, unordered: std.StringHashMap(*const UserValue)) ArrayList(Pair) {
var ordered = ArrayList(Pair).init(allocator);
var it = unordered.iterator();
while (it.next()) |entry| {
ordered.append(.{
.name = entry.key_ptr.*,
.value = OrderedUserValue.fromUnordered(allocator, entry.value_ptr.*.*),
}) catch @panic("OOM");
}
std.mem.sortUnstable(Pair, ordered.items, {}, Pair.lessThan);
return ordered;
}
fn fromUnordered(allocator: Allocator, unordered: UserValue) OrderedUserValue {
return switch (unordered) {
.flag => .{ .flag = {} },
.scalar => |scalar| .{ .scalar = scalar },
.list => |list| .{ .list = list },
.map => |map| .{ .map = OrderedUserValue.mapFromUnordered(allocator, map) },
.lazy_path => |lp| .{ .lazy_path = lp },
.lazy_path_list => |list| .{ .lazy_path_list = list },
};
}
};
const OrderedUserInputOption = struct {
name: []const u8,
value: OrderedUserValue,
used: bool,
fn hash(opt: OrderedUserInputOption, hasher: *std.hash.Wyhash) void {
hasher.update(opt.name);
opt.value.hash(hasher);
}
fn fromUnordered(allocator: Allocator, user_input_option: UserInputOption) OrderedUserInputOption {
return OrderedUserInputOption{
.name = user_input_option.name,
.used = user_input_option.used,
.value = OrderedUserValue.fromUnordered(allocator, user_input_option.value),
};
}
fn lessThan(_: void, lhs: OrderedUserInputOption, rhs: OrderedUserInputOption) bool {
return std.ascii.lessThanIgnoreCase(lhs.name, rhs.name);
}
};
// The hash should be consistent with the same values given a different order.
// This function takes a user input map, orders it, then hashes the contents.
fn hashUserInputOptionsMap(allocator: Allocator, user_input_options: UserInputOptionsMap, hasher: *std.hash.Wyhash) void {
var ordered = ArrayList(OrderedUserInputOption).init(allocator);
var it = user_input_options.iterator();
while (it.next()) |entry|
ordered.append(OrderedUserInputOption.fromUnordered(allocator, entry.value_ptr.*)) catch @panic("OOM");
std.mem.sortUnstable(OrderedUserInputOption, ordered.items, {}, OrderedUserInputOption.lessThan);
// juice it
for (ordered.items) |user_option|
user_option.hash(hasher);
}
fn determineAndApplyInstallPrefix(b: *Build) error{OutOfMemory}!void {
// Create an installation directory local to this package. This will be used when
// dependant packages require a standard prefix, such as include directories for C headers.
var hash = b.graph.cache.hash;
// Random bytes to make unique. Refresh this with new random bytes when
// implementation is modified in a non-backwards-compatible way.
hash.add(@as(u32, 0xd8cb0055));
hash.addBytes(b.dep_prefix);
var wyhash = std.hash.Wyhash.init(0);
hashUserInputOptionsMap(b.allocator, b.user_input_options, &wyhash);
hash.add(wyhash.final());
const digest = hash.final();
const install_prefix = try b.cache_root.join(b.allocator, &.{ "i", &digest });
b.resolveInstallPrefix(install_prefix, .{});
}
/// This function is intended to be called by lib/build_runner.zig, not a build.zig file.
pub fn resolveInstallPrefix(b: *Build, install_prefix: ?[]const u8, dir_list: DirList) void {
if (b.dest_dir) |dest_dir| {
b.install_prefix = install_prefix orelse "/usr";
b.install_path = b.pathJoin(&.{ dest_dir, b.install_prefix });
} else {
b.install_prefix = install_prefix orelse
(b.build_root.join(b.allocator, &.{"zig-out"}) catch @panic("unhandled error"));
b.install_path = b.install_prefix;
}
var lib_list = [_][]const u8{ b.install_path, "lib" };
var exe_list = [_][]const u8{ b.install_path, "bin" };
var h_list = [_][]const u8{ b.install_path, "include" };
if (dir_list.lib_dir) |dir| {
if (fs.path.isAbsolute(dir)) lib_list[0] = b.dest_dir orelse "";
lib_list[1] = dir;
}
if (dir_list.exe_dir) |dir| {
if (fs.path.isAbsolute(dir)) exe_list[0] = b.dest_dir orelse "";
exe_list[1] = dir;
}
if (dir_list.include_dir) |dir| {
if (fs.path.isAbsolute(dir)) h_list[0] = b.dest_dir orelse "";
h_list[1] = dir;
}
b.lib_dir = b.pathJoin(&lib_list);
b.exe_dir = b.pathJoin(&exe_list);
b.h_dir = b.pathJoin(&h_list);
}
/// Create a set of key-value pairs that can be converted into a Zig source
/// file and then inserted into a Zig compilation's module table for importing.
/// In other words, this provides a way to expose build.zig values to Zig
/// source code with `@import`.
/// Related: `Module.addOptions`.
pub fn addOptions(b: *Build) *Step.Options {
return Step.Options.create(b);
}
pub const ExecutableOptions = struct {
name: []const u8,
version: ?std.SemanticVersion = null,
linkage: ?std.builtin.LinkMode = null,
max_rss: usize = 0,
use_llvm: ?bool = null,
use_lld: ?bool = null,
zig_lib_dir: ?LazyPath = null,
/// Embed a `.manifest` file in the compilation if the object format supports it.
/// https://learn.microsoft.com/en-us/windows/win32/sbscs/manifest-files-reference
/// Manifest files must have the extension `.manifest`.
/// Can be set regardless of target. The `.manifest` file will be ignored
/// if the target object format does not support embedded manifests.
win32_manifest: ?LazyPath = null,
/// Prefer populating this field (using e.g. `createModule`) instead of populating
/// the following fields (`root_source_file` etc). In a future release, those fields
/// will be removed, and this field will become non-optional.
root_module: ?*Module = null,
/// Deprecated; prefer populating `root_module`.
root_source_file: ?LazyPath = null,
/// Deprecated; prefer populating `root_module`.
target: ?ResolvedTarget = null,
/// Deprecated; prefer populating `root_module`.
optimize: std.builtin.OptimizeMode = .Debug,
/// Deprecated; prefer populating `root_module`.
code_model: std.builtin.CodeModel = .default,
/// Deprecated; prefer populating `root_module`.
link_libc: ?bool = null,
/// Deprecated; prefer populating `root_module`.
single_threaded: ?bool = null,
/// Deprecated; prefer populating `root_module`.
pic: ?bool = null,
/// Deprecated; prefer populating `root_module`.
strip: ?bool = null,
/// Deprecated; prefer populating `root_module`.
unwind_tables: ?std.builtin.UnwindTables = null,
/// Deprecated; prefer populating `root_module`.
omit_frame_pointer: ?bool = null,
/// Deprecated; prefer populating `root_module`.
sanitize_thread: ?bool = null,
/// Deprecated; prefer populating `root_module`.
error_tracing: ?bool = null,
};
pub fn addExecutable(b: *Build, options: ExecutableOptions) *Step.Compile {
if (options.root_module != null and options.target != null) {
@panic("`root_module` and `target` cannot both be populated");
}
return .create(b, .{
.name = options.name,
.root_module = options.root_module orelse b.createModule(.{
.root_source_file = options.root_source_file,
.target = options.target orelse @panic("`root_module` and `target` cannot both be null"),
.optimize = options.optimize,
.link_libc = options.link_libc,
.single_threaded = options.single_threaded,
.pic = options.pic,
.strip = options.strip,
.unwind_tables = options.unwind_tables,
.omit_frame_pointer = options.omit_frame_pointer,
.sanitize_thread = options.sanitize_thread,
.error_tracing = options.error_tracing,
.code_model = options.code_model,
}),
.version = options.version,
.kind = .exe,
.linkage = options.linkage,
.max_rss = options.max_rss,
.use_llvm = options.use_llvm,
.use_lld = options.use_lld,
.zig_lib_dir = options.zig_lib_dir,
.win32_manifest = options.win32_manifest,
});
}
pub const ObjectOptions = struct {
name: []const u8,
max_rss: usize = 0,
use_llvm: ?bool = null,
use_lld: ?bool = null,
zig_lib_dir: ?LazyPath = null,
/// Prefer populating this field (using e.g. `createModule`) instead of populating
/// the following fields (`root_source_file` etc). In a future release, those fields
/// will be removed, and this field will become non-optional.
root_module: ?*Module = null,
/// Deprecated; prefer populating `root_module`.
root_source_file: ?LazyPath = null,
/// Deprecated; prefer populating `root_module`.
target: ?ResolvedTarget = null,
/// Deprecated; prefer populating `root_module`.
optimize: std.builtin.OptimizeMode = .Debug,
/// Deprecated; prefer populating `root_module`.
code_model: std.builtin.CodeModel = .default,
/// Deprecated; prefer populating `root_module`.
link_libc: ?bool = null,
/// Deprecated; prefer populating `root_module`.
single_threaded: ?bool = null,
/// Deprecated; prefer populating `root_module`.
pic: ?bool = null,
/// Deprecated; prefer populating `root_module`.
strip: ?bool = null,
/// Deprecated; prefer populating `root_module`.
unwind_tables: ?std.builtin.UnwindTables = null,
/// Deprecated; prefer populating `root_module`.
omit_frame_pointer: ?bool = null,
/// Deprecated; prefer populating `root_module`.
sanitize_thread: ?bool = null,
/// Deprecated; prefer populating `root_module`.
error_tracing: ?bool = null,
};
pub fn addObject(b: *Build, options: ObjectOptions) *Step.Compile {
if (options.root_module != null and options.target != null) {
@panic("`root_module` and `target` cannot both be populated");
}
return .create(b, .{
.name = options.name,
.root_module = options.root_module orelse b.createModule(.{
.root_source_file = options.root_source_file,
.target = options.target orelse @panic("`root_module` and `target` cannot both be null"),
.optimize = options.optimize,
.link_libc = options.link_libc,
.single_threaded = options.single_threaded,
.pic = options.pic,
.strip = options.strip,
.unwind_tables = options.unwind_tables,
.omit_frame_pointer = options.omit_frame_pointer,
.sanitize_thread = options.sanitize_thread,
.error_tracing = options.error_tracing,
.code_model = options.code_model,
}),
.kind = .obj,
.max_rss = options.max_rss,
.use_llvm = options.use_llvm,
.use_lld = options.use_lld,
.zig_lib_dir = options.zig_lib_dir,
});
}
pub const SharedLibraryOptions = struct {
name: []const u8,
version: ?std.SemanticVersion = null,
max_rss: usize = 0,
use_llvm: ?bool = null,
use_lld: ?bool = null,
zig_lib_dir: ?LazyPath = null,
/// Embed a `.manifest` file in the compilation if the object format supports it.
/// https://learn.microsoft.com/en-us/windows/win32/sbscs/manifest-files-reference
/// Manifest files must have the extension `.manifest`.
/// Can be set regardless of target. The `.manifest` file will be ignored
/// if the target object format does not support embedded manifests.
win32_manifest: ?LazyPath = null,
/// Prefer populating this field (using e.g. `createModule`) instead of populating
/// the following fields (`root_source_file` etc). In a future release, those fields
/// will be removed, and this field will become non-optional.
root_module: ?*Module = null,
/// Deprecated; prefer populating `root_module`.
root_source_file: ?LazyPath = null,
/// Deprecated; prefer populating `root_module`.
target: ?ResolvedTarget = null,
/// Deprecated; prefer populating `root_module`.
optimize: std.builtin.OptimizeMode = .Debug,
/// Deprecated; prefer populating `root_module`.
code_model: std.builtin.CodeModel = .default,
/// Deprecated; prefer populating `root_module`.
link_libc: ?bool = null,
/// Deprecated; prefer populating `root_module`.
single_threaded: ?bool = null,
/// Deprecated; prefer populating `root_module`.
pic: ?bool = null,
/// Deprecated; prefer populating `root_module`.
strip: ?bool = null,
/// Deprecated; prefer populating `root_module`.
unwind_tables: ?std.builtin.UnwindTables = null,
/// Deprecated; prefer populating `root_module`.
omit_frame_pointer: ?bool = null,
/// Deprecated; prefer populating `root_module`.
sanitize_thread: ?bool = null,
/// Deprecated; prefer populating `root_module`.
error_tracing: ?bool = null,
};
/// Deprecated: use `b.addLibrary(.{ ..., .linkage = .dynamic })` instead.
pub fn addSharedLibrary(b: *Build, options: SharedLibraryOptions) *Step.Compile {
if (options.root_module != null and options.target != null) {
@panic("`root_module` and `target` cannot both be populated");
}
return .create(b, .{
.name = options.name,
.root_module = options.root_module orelse b.createModule(.{
.target = options.target orelse @panic("`root_module` and `target` cannot both be null"),
.optimize = options.optimize,
.root_source_file = options.root_source_file,
.link_libc = options.link_libc,
.single_threaded = options.single_threaded,
.pic = options.pic,
.strip = options.strip,
.unwind_tables = options.unwind_tables,
.omit_frame_pointer = options.omit_frame_pointer,
.sanitize_thread = options.sanitize_thread,
.error_tracing = options.error_tracing,
.code_model = options.code_model,
}),
.kind = .lib,
.linkage = .dynamic,
.version = options.version,
.max_rss = options.max_rss,
.use_llvm = options.use_llvm,
.use_lld = options.use_lld,
.zig_lib_dir = options.zig_lib_dir,
.win32_manifest = options.win32_manifest,
});
}
pub const StaticLibraryOptions = struct {
name: []const u8,
version: ?std.SemanticVersion = null,
max_rss: usize = 0,
use_llvm: ?bool = null,
use_lld: ?bool = null,
zig_lib_dir: ?LazyPath = null,
/// Prefer populating this field (using e.g. `createModule`) instead of populating
/// the following fields (`root_source_file` etc). In a future release, those fields
/// will be removed, and this field will become non-optional.
root_module: ?*Module = null,
/// Deprecated; prefer populating `root_module`.
root_source_file: ?LazyPath = null,
/// Deprecated; prefer populating `root_module`.
target: ?ResolvedTarget = null,
/// Deprecated; prefer populating `root_module`.
optimize: std.builtin.OptimizeMode = .Debug,
/// Deprecated; prefer populating `root_module`.
code_model: std.builtin.CodeModel = .default,
/// Deprecated; prefer populating `root_module`.
link_libc: ?bool = null,
/// Deprecated; prefer populating `root_module`.
single_threaded: ?bool = null,
/// Deprecated; prefer populating `root_module`.
pic: ?bool = null,
/// Deprecated; prefer populating `root_module`.
strip: ?bool = null,
/// Deprecated; prefer populating `root_module`.
unwind_tables: ?std.builtin.UnwindTables = null,
/// Deprecated; prefer populating `root_module`.
omit_frame_pointer: ?bool = null,
/// Deprecated; prefer populating `root_module`.
sanitize_thread: ?bool = null,
/// Deprecated; prefer populating `root_module`.
error_tracing: ?bool = null,
};
/// Deprecated: use `b.addLibrary(.{ ..., .linkage = .static })` instead.
pub fn addStaticLibrary(b: *Build, options: StaticLibraryOptions) *Step.Compile {
if (options.root_module != null and options.target != null) {
@panic("`root_module` and `target` cannot both be populated");
}
return .create(b, .{
.name = options.name,
.root_module = options.root_module orelse b.createModule(.{
.target = options.target orelse @panic("`root_module` and `target` cannot both be null"),
.optimize = options.optimize,
.root_source_file = options.root_source_file,
.link_libc = options.link_libc,
.single_threaded = options.single_threaded,
.pic = options.pic,
.strip = options.strip,
.unwind_tables = options.unwind_tables,
.omit_frame_pointer = options.omit_frame_pointer,
.sanitize_thread = options.sanitize_thread,
.error_tracing = options.error_tracing,
.code_model = options.code_model,
}),
.kind = .lib,
.linkage = .static,
.version = options.version,
.max_rss = options.max_rss,
.use_llvm = options.use_llvm,
.use_lld = options.use_lld,
.zig_lib_dir = options.zig_lib_dir,
});
}
pub const LibraryOptions = struct {
linkage: std.builtin.LinkMode = .static,
name: []const u8,
root_module: *Module,
version: ?std.SemanticVersion = null,
max_rss: usize = 0,
use_llvm: ?bool = null,
use_lld: ?bool = null,
zig_lib_dir: ?LazyPath = null,
/// Embed a `.manifest` file in the compilation if the object format supports it.
/// https://learn.microsoft.com/en-us/windows/win32/sbscs/manifest-files-reference
/// Manifest files must have the extension `.manifest`.
/// Can be set regardless of target. The `.manifest` file will be ignored
/// if the target object format does not support embedded manifests.
win32_manifest: ?LazyPath = null,
};
pub fn addLibrary(b: *Build, options: LibraryOptions) *Step.Compile {