-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathBuild.zig
More file actions
2713 lines (2451 loc) · 98.9 KB
/
Copy pathBuild.zig
File metadata and controls
2713 lines (2451 loc) · 98.9 KB
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 builtin = @import("builtin");
const std = @import("std.zig");
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 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();
const ArrayList = std.ArrayList;
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");
pub const WebServer = @import("Build/WebServer.zig");
pub const abi = @import("Build/abi.zig");
/// 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: std.array_list.Managed(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: ArrayList([]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_incremental: 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`.
/// Also works for dynamic musl.
libc_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,
build_id: ?std.zig.BuildId = null,
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 {
io: Io,
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,
time_report: bool,
};
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: std.array_list.Managed([]const u8),
map: StringHashMap(*const UserValue),
lazy_path: LazyPath,
lazy_path_list: std.array_list.Managed(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 = std.array_list.Managed(AvailableOption).init(arena),
.top_level_steps = .{},
.default_step = undefined,
.search_prefixes = .empty,
.install_prefix = undefined,
.lib_dir = undefined,
.exe_dir = undefined,
.h_dir = undefined,
.dest_dir = graph.env_map.get("DESTDIR"),
.install_tls = .{
.step = .init(.{
.id = TopLevelStep.base_id,
.name = "install",
.owner = b,
}),
.description = "Copy build artifacts to prefix path",
},
.uninstall_tls = .{
.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 = .init(.{
.id = TopLevelStep.base_id,
.name = "install",
.owner = child,
}),
.description = "Copy build artifacts to prefix path",
},
.uninstall_tls = .{
.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 = std.array_list.Managed(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_incremental = parent.debug_incremental,
.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,
.libc_runtimes_dir = parent.libc_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(arena: Allocator, args: anytype) UserInputOptionsMap {
var map = UserInputOptionsMap.init(arena);
inline for (@typeInfo(@TypeOf(args)).@"struct".fields) |field| {
if (field.type == @TypeOf(null)) continue;
addUserInputOptionFromArg(arena, &map, field, field.type, @field(args, field.name));
}
return map;
}
fn addUserInputOptionFromArg(
arena: Allocator,
map: *UserInputOptionsMap,
field: std.builtin.Type.StructField,
comptime T: type,
/// If null, the value won't be added, but `T` will still be type-checked.
maybe_value: ?T,
) void {
switch (T) {
Target.Query => return if (maybe_value) |v| {
map.put(field.name, .{
.name = field.name,
.value = .{ .scalar = v.zigTriple(arena) catch @panic("OOM") },
.used = false,
}) catch @panic("OOM");
map.put("cpu", .{
.name = "cpu",
.value = .{ .scalar = v.serializeCpuAlloc(arena) catch @panic("OOM") },
.used = false,
}) catch @panic("OOM");
},
ResolvedTarget => return if (maybe_value) |v| {
map.put(field.name, .{
.name = field.name,
.value = .{ .scalar = v.query.zigTriple(arena) catch @panic("OOM") },
.used = false,
}) catch @panic("OOM");
map.put("cpu", .{
.name = "cpu",
.value = .{ .scalar = v.query.serializeCpuAlloc(arena) catch @panic("OOM") },
.used = false,
}) catch @panic("OOM");
},
std.zig.BuildId => return if (maybe_value) |v| {
map.put(field.name, .{
.name = field.name,
.value = .{ .scalar = std.fmt.allocPrint(arena, "{f}", .{v}) catch @panic("OOM") },
.used = false,
}) catch @panic("OOM");
},
LazyPath => return if (maybe_value) |v| {
map.put(field.name, .{
.name = field.name,
.value = .{ .lazy_path = v.dupeInner(arena) },
.used = false,
}) catch @panic("OOM");
},
[]const LazyPath => return if (maybe_value) |v| {
var list = std.array_list.Managed(LazyPath).initCapacity(arena, v.len) catch @panic("OOM");
for (v) |lp| list.appendAssumeCapacity(lp.dupeInner(arena));
map.put(field.name, .{
.name = field.name,
.value = .{ .lazy_path_list = list },
.used = false,
}) catch @panic("OOM");
},
[]const u8 => return if (maybe_value) |v| {
map.put(field.name, .{
.name = field.name,
.value = .{ .scalar = arena.dupe(u8, v) catch @panic("OOM") },
.used = false,
}) catch @panic("OOM");
},
[]const []const u8 => return if (maybe_value) |v| {
var list = std.array_list.Managed([]const u8).initCapacity(arena, v.len) catch @panic("OOM");
for (v) |s| list.appendAssumeCapacity(arena.dupe(u8, s) catch @panic("OOM"));
map.put(field.name, .{
.name = field.name,
.value = .{ .list = list },
.used = false,
}) catch @panic("OOM");
},
else => switch (@typeInfo(T)) {
.bool => return if (maybe_value) |v| {
map.put(field.name, .{
.name = field.name,
.value = .{ .scalar = if (v) "true" else "false" },
.used = false,
}) catch @panic("OOM");
},
.@"enum", .enum_literal => return if (maybe_value) |v| {
map.put(field.name, .{
.name = field.name,
.value = .{ .scalar = @tagName(v) },
.used = false,
}) catch @panic("OOM");
},
.comptime_int, .int => return if (maybe_value) |v| {
map.put(field.name, .{
.name = field.name,
.value = .{ .scalar = std.fmt.allocPrint(arena, "{d}", .{v}) catch @panic("OOM") },
.used = false,
}) catch @panic("OOM");
},
.comptime_float, .float => return if (maybe_value) |v| {
map.put(field.name, .{
.name = field.name,
.value = .{ .scalar = std.fmt.allocPrint(arena, "{x}", .{v}) catch @panic("OOM") },
.used = false,
}) catch @panic("OOM");
},
.pointer => |ptr_info| switch (ptr_info.size) {
.one => switch (@typeInfo(ptr_info.child)) {
.array => |array_info| {
addUserInputOptionFromArg(
arena,
map,
field,
@Pointer(.slice, .{ .@"const" = true }, array_info.child, null),
maybe_value orelse null,
);
return;
},
else => {},
},
.slice => switch (@typeInfo(ptr_info.child)) {
.@"enum" => return if (maybe_value) |v| {
var list = std.array_list.Managed([]const u8).initCapacity(arena, v.len) catch @panic("OOM");
for (v) |tag| list.appendAssumeCapacity(@tagName(tag));
map.put(field.name, .{
.name = field.name,
.value = .{ .list = list },
.used = false,
}) catch @panic("OOM");
},
else => {
addUserInputOptionFromArg(
arena,
map,
field,
@Pointer(ptr_info.size, .{ .@"const" = true }, ptr_info.child, null),
maybe_value orelse null,
);
return;
},
},
else => {},
},
.null => unreachable,
.optional => |info| switch (@typeInfo(info.child)) {
.optional => {},
else => {
addUserInputOptionFromArg(
arena,
map,
field,
info.child,
maybe_value orelse null,
);
return;
},
},
else => {},
},
}
@compileError("option '" ++ field.name ++ "' has unsupported type: " ++ @typeName(field.type));
}
const OrderedUserValue = union(enum) {
flag: void,
scalar: []const u8,
list: std.array_list.Managed([]const u8),
map: std.array_list.Managed(Pair),
lazy_path: LazyPath,
lazy_path_list: std.array_list.Managed(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)) std.array_list.Managed(Pair) {
var ordered = std.array_list.Managed(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 = std.array_list.Managed(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,
root_module: *Module,
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,
};
pub fn addExecutable(b: *Build, options: ExecutableOptions) *Step.Compile {
return .create(b, .{
.name = options.name,
.root_module = options.root_module,
.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,
root_module: *Module,
max_rss: usize = 0,
use_llvm: ?bool = null,
use_lld: ?bool = null,
zig_lib_dir: ?LazyPath = null,
};
pub fn addObject(b: *Build, options: ObjectOptions) *Step.Compile {
return .create(b, .{
.name = options.name,
.root_module = options.root_module,
.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 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 {
return .create(b, .{
.name = options.name,
.root_module = options.root_module,
.kind = .lib,
.linkage = options.linkage,
.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 TestOptions = struct {
name: []const u8 = "test",
root_module: *Module,
max_rss: usize = 0,
filters: []const []const u8 = &.{},
test_runner: ?Step.Compile.TestRunner = null,
use_llvm: ?bool = null,
use_lld: ?bool = null,
zig_lib_dir: ?LazyPath = null,
/// Emits an object file instead of a test binary.
/// The object must be linked separately.
/// Usually used in conjunction with a custom `test_runner`.
emit_object: bool = false,
};
/// Creates an executable containing unit tests.
///
/// Equivalent to running the command `zig test --test-no-exec ...`.
///
/// **This step does not run the unit tests**. Typically, the result of this
/// function will be passed to `addRunArtifact`, creating a `Step.Run`. These
/// two steps are separated because they are independently configured and
/// cached.
pub fn addTest(b: *Build, options: TestOptions) *Step.Compile {
return .create(b, .{
.name = options.name,
.kind = if (options.emit_object) .test_obj else .@"test",
.root_module = options.root_module,
.max_rss = options.max_rss,
.filters = b.dupeStrings(options.filters),
.test_runner = options.test_runner,
.use_llvm = options.use_llvm,
.use_lld = options.use_lld,
.zig_lib_dir = options.zig_lib_dir,
});
}
pub const AssemblyOptions = struct {
name: []const u8,
source_file: LazyPath,
/// To choose the same computer as the one building the package, pass the
/// `host` field of the package's `Build` instance.
target: ResolvedTarget,
optimize: std.builtin.OptimizeMode,
max_rss: usize = 0,
zig_lib_dir: ?LazyPath = null,
};
/// This function creates a module and adds it to the package's module set, making
/// it available to other packages which depend on this one.
/// `createModule` can be used instead to create a private module.
pub fn addModule(b: *Build, name: []const u8, options: Module.CreateOptions) *Module {
const module = Module.create(b, options);
b.modules.put(b.dupe(name), module) catch @panic("OOM");
return module;
}
/// This function creates a private module, to be used by the current package,
/// but not exposed to other packages depending on this one.
/// `addModule` can be used instead to create a public module.
pub fn createModule(b: *Build, options: Module.CreateOptions) *Module {
return Module.create(b, options);
}
/// Initializes a `Step.Run` with argv, which must at least have the path to the
/// executable. More command line arguments can be added with `addArg`,
/// `addArgs`, and `addArtifactArg`.
/// Be careful using this function, as it introduces a system dependency.
/// To run an executable built with zig build, see `Step.Compile.run`.
pub fn addSystemCommand(b: *Build, argv: []const []const u8) *Step.Run {
assert(argv.len >= 1);
const run_step = Step.Run.create(b, b.fmt("run {s}", .{argv[0]}));
run_step.addArgs(argv);
return run_step;
}
/// Creates a `Step.Run` with an executable built with `addExecutable`.
/// Add command line arguments with methods of `Step.Run`.
pub fn addRunArtifact(b: *Build, exe: *Step.Compile) *Step.Run {
// It doesn't have to be native. We catch that if you actually try to run it.
// Consider that this is declarative; the run step may not be run unless a user
// option is supplied.
// Avoid the common case of the step name looking like "run test test".
const step_name = if (exe.kind.isTest() and mem.eql(u8, exe.name, "test"))
b.fmt("run {s}", .{@tagName(exe.kind)})
else
b.fmt("run {s} {s}", .{ @tagName(exe.kind), exe.name });
const run_step = Step.Run.create(b, step_name);
run_step.producer = exe;
if (exe.kind == .@"test") {
if (exe.exec_cmd_args) |exec_cmd_args| {
for (exec_cmd_args) |cmd_arg| {
if (cmd_arg) |arg| {
run_step.addArg(arg);
} else {
run_step.addArtifactArg(exe);
}
}
} else {
run_step.addArtifactArg(exe);
}
const test_server_mode: bool = s: {
if (exe.test_runner) |r| break :s r.mode == .server;
if (exe.use_llvm == false) {
// The default test runner does not use the server protocol if the selected backend
// is too immature to support it. Keep this logic in sync with `need_simple` in the
// default test runner implementation.
switch (exe.rootModuleTarget().cpu.arch) {
// stage2_aarch64
.aarch64,
.aarch64_be,
// stage2_powerpc
.powerpc,
.powerpcle,
.powerpc64,
.powerpc64le,
// stage2_riscv64
.riscv64,
=> break :s false,
else => {},
}
}
break :s true;
};
if (test_server_mode) {
run_step.enableTestRunnerMode();
} else if (exe.test_runner == null) {
// If a test runner does not use the `std.zig.Server` protocol, it can instead
// communicate failure via its exit code.
run_step.expectExitCode(0);
}
} else {
run_step.addArtifactArg(exe);
}
return run_step;
}
/// Using the `values` provided, produces a C header file, possibly based on a
/// template input file (e.g. config.h.in).
/// When an input template file is provided, this function will fail the build
/// when an option not found in the input file is provided in `values`, and
/// when an option found in the input file is missing from `values`.
pub fn addConfigHeader(
b: *Build,
options: Step.ConfigHeader.Options,
values: anytype,