-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathbuild.zig
1734 lines (1547 loc) · 69.5 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");
const log = std.log.scoped(.mach_gpu_dawn);
pub fn build(b: *std.Build) !void {
const optimize = b.standardOptimizeOption(.{});
const target = b.standardTargetOptions(.{});
const options = Options{
.install_libs = true,
.from_source = false,
};
// Just to demonstrate/test linking. This is not a functional example, see the mach/gpu examples
// or Dawn C++ examples for functional example code.
const example = b.addExecutable(.{
.name = "empty",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
link(b, example, &example.root_module, options);
const example_step = b.step("dawn", "Build dawn from source");
example_step.dependOn(&b.addRunArtifact(example).step);
}
pub const DownloadBinaryStep = struct {
target: *std.Build.Step.Compile,
options: Options,
step: std.Build.Step,
b: *std.Build,
pub fn init(b: *std.Build, target: *std.Build.Step.Compile, options: Options) *DownloadBinaryStep {
const download_step = b.allocator.create(DownloadBinaryStep) catch unreachable;
download_step.* = .{
.target = target,
.options = options,
.step = std.Build.Step.init(.{
.id = .custom,
.name = "download",
.owner = b,
.makeFn = &make,
}),
.b = b,
};
return download_step;
}
fn make(step: *std.Build.Step, prog_node: std.Progress.Node) anyerror!void {
_ = prog_node;
const download_step: *DownloadBinaryStep = @fieldParentPtr("step", step);
try downloadFromBinary(download_step.b, download_step.target, download_step.options);
}
};
pub const Options = struct {
/// Defaults to true on Windows
d3d12: ?bool = null,
/// Defaults to true on Darwin
metal: ?bool = null,
/// Defaults to true on Linux, Fuchsia
// TODO(build-system): enable on Windows if we can cross compile Vulkan
vulkan: ?bool = null,
/// Defaults to true on Linux
desktop_gl: ?bool = null,
/// Defaults to true on Android, Linux, Windows, Emscripten
// TODO(build-system): not respected at all currently
opengl_es: ?bool = null,
/// Whether or not minimal debug symbols should be emitted. This is -g1 in most cases, enough to
/// produce stack traces but omitting debug symbols for locals. For spirv-tools and tint in
/// specific, -g0 will be used (no debug symbols at all) to save an additional ~39M.
debug: bool = false,
/// Whether or not to produce separate static libraries for each component of Dawn (reduces
/// iteration times when building from source / testing changes to Dawn source code.)
separate_libs: bool = false,
/// Whether or not to produce shared libraries instead of static ones
shared_libs: bool = false,
/// Whether to build Dawn from source or not.
from_source: bool = false,
/// Produce static libraries at zig-out/lib
install_libs: bool = false,
/// The binary release version to use from https://github.com/hexops/mach-gpu-dawn/releases
binary_version: []const u8 = "release-9c05275",
/// Detects the default options to use for the given target.
pub fn detectDefaults(self: Options, target: std.Target) Options {
const tag = target.os.tag;
var options = self;
if (options.d3d12 == null) options.d3d12 = tag == .windows;
if (options.metal == null) options.metal = tag.isDarwin();
if (options.vulkan == null) options.vulkan = tag == .fuchsia or isLinuxDesktopLike(tag);
// TODO(build-system): technically Dawn itself defaults desktop_gl to true on Windows.
if (options.desktop_gl == null) options.desktop_gl = isLinuxDesktopLike(tag);
// TODO(build-system): OpenGL ES
options.opengl_es = false;
// if (options.opengl_es == null) options.opengl_es = tag == .windows or tag == .emscripten or target.isAndroid() or linux_desktop_like;
return options;
}
};
pub fn link(b: *std.Build, step: *std.Build.Step.Compile, mod: *std.Build.Module, options: Options) void {
const target = step.rootModuleTarget();
const opt = options.detectDefaults(target);
if (target.os.tag == .windows) @import("direct3d_headers").addLibraryPath(step);
if (target.os.tag == .macos) @import("xcode_frameworks").addPaths(mod);
if (options.from_source or isEnvVarTruthy(b.allocator, "DAWN_FROM_SOURCE")) {
linkFromSource(b, step, mod, opt) catch unreachable;
} else {
// Add a build step to download Dawn binaries. This ensures it only downloads if needed,
// and that e.g. if you are running a different `zig build <step>` it doesn't always just
// download the binaries.
var download_step = DownloadBinaryStep.init(b, step, options);
step.step.dependOn(&download_step.step);
// Declare how to link against the binaries.
linkFromBinary(b, step, mod, opt) catch unreachable;
}
}
fn linkFromSource(b: *std.Build, step: *std.Build.Step.Compile, mod: *std.Build.Module, options: Options) !void {
_ = mod;
// Source scanning requires that these files actually exist on disk, so we must download them
// here right now if we are building from source.
try ensureGitRepoCloned(b.allocator, "https://github.com/hexops/dawn", "generated-2023-08-10.1691685418", sdkPath("/libs/dawn"));
// branch: mach
try ensureGitRepoCloned(b.allocator, "https://github.com/hexops/DirectXShaderCompiler", "bb5211aa247978e2ab75bea9f5c985ba3fabd269", sdkPath("/libs/DirectXShaderCompiler"));
step.addIncludePath(.{ .cwd_relative = sdkPath("/libs/dawn/out/Debug/gen/include") });
step.addIncludePath(.{ .cwd_relative = sdkPath("/libs/dawn/include") });
step.addIncludePath(.{ .cwd_relative = sdkPath("/src/dawn") });
if (options.separate_libs) {
const lib_dawn_common = try buildLibDawnCommon(b, step, options);
const lib_dawn_platform = try buildLibDawnPlatform(b, step, options);
const lib_abseil_cpp = try buildLibAbseilCpp(b, step, options);
const lib_dawn_native = try buildLibDawnNative(b, step, options);
const lib_dawn_wire = try buildLibDawnWire(b, step, options);
const lib_spirv_tools = try buildLibSPIRVTools(b, step, options);
const lib_tint = try buildLibTint(b, step, options);
step.linkLibrary(lib_dawn_common);
step.linkLibrary(lib_dawn_platform);
step.linkLibrary(lib_abseil_cpp);
step.linkLibrary(lib_dawn_native);
step.linkLibrary(lib_dawn_wire);
step.linkLibrary(lib_spirv_tools);
step.linkLibrary(lib_tint);
if (options.d3d12.?) {
const lib_dxcompiler = try buildLibDxcompiler(b, step, options);
step.linkLibrary(lib_dxcompiler);
}
return;
}
const lib_dawn = if (options.shared_libs) b.addSharedLibrary(.{
.name = "dawn",
.target = step.root_module.resolved_target.?,
.optimize = if (options.debug) .Debug else .ReleaseFast,
}) else b.addStaticLibrary(.{
.name = "dawn",
.target = step.root_module.resolved_target.?,
.optimize = if (options.debug) .Debug else .ReleaseFast,
});
step.linkLibrary(lib_dawn);
_ = try buildLibDawnCommon(b, lib_dawn, options);
_ = try buildLibDawnPlatform(b, lib_dawn, options);
_ = try buildLibAbseilCpp(b, lib_dawn, options);
_ = try buildLibDawnNative(b, lib_dawn, options);
_ = try buildLibDawnWire(b, lib_dawn, options);
_ = try buildLibSPIRVTools(b, lib_dawn, options);
_ = try buildLibTint(b, lib_dawn, options);
if (options.d3d12.?) _ = try buildLibDxcompiler(b, lib_dawn, options);
}
fn ensureGitRepoCloned(allocator: std.mem.Allocator, clone_url: []const u8, revision: []const u8, dir: []const u8) !void {
if (isEnvVarTruthy(allocator, "NO_ENSURE_SUBMODULES") or isEnvVarTruthy(allocator, "NO_ENSURE_GIT")) {
return;
}
ensureGit(allocator);
if (std.fs.openDirAbsolute(dir, .{})) |_| {
const current_revision = try getCurrentGitRevision(allocator, dir);
if (!std.mem.eql(u8, current_revision, revision)) {
// Reset to the desired revision
exec(allocator, &[_][]const u8{ "git", "fetch" }, dir) catch |err| std.debug.print("warning: failed to 'git fetch' in {s}: {s}\n", .{ dir, @errorName(err) });
try exec(allocator, &[_][]const u8{ "git", "checkout", "--quiet", "--force", revision }, dir);
try exec(allocator, &[_][]const u8{ "git", "submodule", "update", "--init", "--recursive" }, dir);
}
return;
} else |err| return switch (err) {
error.FileNotFound => {
std.log.info("cloning required dependency..\ngit clone {s} {s}..\n", .{ clone_url, dir });
try exec(allocator, &[_][]const u8{ "git", "clone", "-c", "core.longpaths=true", clone_url, dir }, sdkPath("/"));
try exec(allocator, &[_][]const u8{ "git", "checkout", "--quiet", "--force", revision }, dir);
try exec(allocator, &[_][]const u8{ "git", "submodule", "update", "--init", "--recursive" }, dir);
return;
},
else => err,
};
}
fn exec(allocator: std.mem.Allocator, argv: []const []const u8, cwd: []const u8) !void {
var child = std.process.Child.init(argv, allocator);
child.cwd = cwd;
_ = try child.spawnAndWait();
}
fn getCurrentGitRevision(allocator: std.mem.Allocator, cwd: []const u8) ![]const u8 {
const result = try std.process.Child.run(.{ .allocator = allocator, .argv = &.{ "git", "rev-parse", "HEAD" }, .cwd = cwd });
allocator.free(result.stderr);
if (result.stdout.len > 0) return result.stdout[0 .. result.stdout.len - 1]; // trim newline
return result.stdout;
}
fn ensureGit(allocator: std.mem.Allocator) void {
const argv = &[_][]const u8{ "git", "--version" };
const result = std.process.Child.run(.{
.allocator = allocator,
.argv = argv,
.cwd = ".",
}) catch { // e.g. FileNotFound
std.log.err("mach: error: 'git --version' failed. Is git not installed?", .{});
std.process.exit(1);
};
defer {
allocator.free(result.stderr);
allocator.free(result.stdout);
}
if (result.term.Exited != 0) {
std.log.err("mach: error: 'git --version' failed. Is git not installed?", .{});
std.process.exit(1);
}
}
fn isEnvVarTruthy(allocator: std.mem.Allocator, name: []const u8) bool {
if (std.process.getEnvVarOwned(allocator, name)) |truthy| {
defer allocator.free(truthy);
if (std.mem.eql(u8, truthy, "true")) return true;
return false;
} else |_| {
return false;
}
}
fn getGitHubBaseURLOwned(allocator: std.mem.Allocator) ![]const u8 {
if (std.process.getEnvVarOwned(allocator, "MACH_GITHUB_BASE_URL")) |base_url| {
std.log.info("mach: respecting MACH_GITHUB_BASE_URL: {s}\n", .{base_url});
return base_url;
} else |_| {
return allocator.dupe(u8, "https://github.com");
}
}
var download_mutex = std.Thread.Mutex{};
pub fn downloadFromBinary(b: *std.Build, step: *std.Build.Step.Compile, options: Options) !void {
// Zig will run build steps in parallel if possible, so if there were two invocations of
// link() then this function would be called in parallel. We're manipulating the FS here
// and so need to prevent that.
download_mutex.lock();
defer download_mutex.unlock();
const target = step.rootModuleTarget();
const binaries_available = switch (target.os.tag) {
.windows => target.abi.isGnu(),
.linux => (target.cpu.arch.isX86() or target.cpu.arch.isAARCH64()) and (target.abi.isGnu() or target.abi.isMusl()),
.macos => blk: {
if (!target.cpu.arch.isX86() and !target.cpu.arch.isAARCH64()) break :blk false;
// The minimum macOS version with which our binaries can be used.
const min_available = std.SemanticVersion{ .major = 11, .minor = 0, .patch = 0 };
// If the target version is >= the available version, then it's OK.
const order = target.os.version_range.semver.min.order(min_available);
break :blk (order == .gt or order == .eq);
},
else => false,
};
if (!binaries_available) {
const zig_triple = try target.zigTriple(b.allocator);
std.log.err("gpu-dawn binaries for {s} not available.", .{zig_triple});
std.log.err("-> open an issue: https://github.com/hexops/mach/issues", .{});
std.log.err("-> build from source (takes 5-15 minutes):", .{});
std.log.err(" set `DAWN_FROM_SOURCE` environment variable or `Options.from_source` to `true`\n", .{});
if (target.os.tag == .macos) {
std.log.err("", .{});
if (target.cpu.arch.isX86()) std.log.err("-> Did you mean to use -Dtarget=x86_64-macos.12.0...13.1-none ?", .{});
if (target.cpu.arch.isAARCH64()) std.log.err("-> Did you mean to use -Dtarget=aarch64-macos.12.0...13.1-none ?", .{});
}
std.process.exit(1);
}
// Remove OS version range / glibc version from triple (we do not include that in our download
// URLs.)
var binary_target = std.zig.CrossTarget.fromTarget(target);
binary_target.os_version_min = .{ .none = undefined };
binary_target.os_version_max = .{ .none = undefined };
binary_target.glibc_version = null;
const zig_triple = try binary_target.zigTriple(b.allocator);
try ensureBinaryDownloaded(
b.allocator,
b.cache_root.path,
zig_triple,
options.debug,
target.os.tag == .windows,
options.binary_version,
);
}
pub fn linkFromBinary(b: *std.Build, step: *std.Build.Step.Compile, mod: *std.Build.Module, options: Options) !void {
const target = step.rootModuleTarget();
// Remove OS version range / glibc version from triple (we do not include that in our download
// URLs.)
var binary_target = std.zig.CrossTarget.fromTarget(target);
binary_target.os_version_min = .{ .none = undefined };
binary_target.os_version_max = .{ .none = undefined };
binary_target.glibc_version = null;
const zig_triple = try binary_target.zigTriple(b.allocator);
const base_cache_dir_rel = try std.fs.path.join(b.allocator, &.{
b.cache_root.path orelse "zig-cache",
"mach",
"gpu-dawn",
});
try std.fs.cwd().makePath(base_cache_dir_rel);
const base_cache_dir = try std.fs.cwd().realpathAlloc(b.allocator, base_cache_dir_rel);
const commit_cache_dir = try std.fs.path.join(b.allocator, &.{ base_cache_dir, options.binary_version });
const release_tag = if (options.debug) "debug" else "release-fast";
const target_cache_dir = try std.fs.path.join(b.allocator, &.{ commit_cache_dir, zig_triple, release_tag });
const include_dir = try std.fs.path.join(b.allocator, &.{ commit_cache_dir, "include" });
step.addLibraryPath(.{ .cwd_relative = target_cache_dir });
step.linkSystemLibrary("dawn");
step.linkLibCpp();
step.addIncludePath(.{ .cwd_relative = include_dir });
step.addIncludePath(.{ .cwd_relative = sdkPath("/src/dawn") });
linkLibDawnCommonDependencies(b, step, mod, options);
linkLibDawnPlatformDependencies(b, step, mod, options);
linkLibDawnNativeDependencies(b, step, mod, options);
linkLibTintDependencies(b, step, mod, options);
linkLibSPIRVToolsDependencies(b, step, mod, options);
linkLibAbseilCppDependencies(b, step, mod, options);
linkLibDawnWireDependencies(b, step, mod, options);
linkLibDxcompilerDependencies(b, step, mod, options);
// Transitive dependencies, explicit linkage of these works around
// ziglang/zig#17130
if (target.os.tag == .macos) {
step.linkFramework("CoreImage");
step.linkFramework("CoreVideo");
}
}
pub fn addPathsToModule(b: *std.Build, module: *std.Build.Module, options: Options) void {
const target = (module.resolved_target orelse b.host).result;
const opt = options.detectDefaults(target);
if (options.from_source or isEnvVarTruthy(b.allocator, "DAWN_FROM_SOURCE")) {
addPathsToModuleFromSource(b, module, opt) catch unreachable;
} else {
addPathsToModuleFromBinary(b, module, opt) catch unreachable;
}
}
pub fn addPathsToModuleFromSource(b: *std.Build, module: *std.Build.Module, options: Options) !void {
_ = b;
_ = options;
module.addIncludePath(.{ .cwd_relative = sdkPath("/libs/dawn/out/Debug/gen/include") });
module.addIncludePath(.{ .cwd_relative = sdkPath("/libs/dawn/include") });
module.addIncludePath(.{ .cwd_relative = sdkPath("/src/dawn") });
}
pub fn addPathsToModuleFromBinary(b: *std.Build, module: *std.Build.Module, options: Options) !void {
const target = (module.resolved_target orelse b.host).result;
// Remove OS version range / glibc version from triple (we do not include that in our download
// URLs.)
var binary_target = std.zig.CrossTarget.fromTarget(target);
binary_target.os_version_min = .{ .none = undefined };
binary_target.os_version_max = .{ .none = undefined };
binary_target.glibc_version = null;
const zig_triple = try binary_target.zigTriple(b.allocator);
const base_cache_dir_rel = try std.fs.path.join(b.allocator, &.{
b.cache_root.path orelse "zig-cache",
"mach",
"gpu-dawn",
});
try std.fs.cwd().makePath(base_cache_dir_rel);
const base_cache_dir = try std.fs.cwd().realpathAlloc(b.allocator, base_cache_dir_rel);
const commit_cache_dir = try std.fs.path.join(b.allocator, &.{ base_cache_dir, options.binary_version });
const release_tag = if (options.debug) "debug" else "release-fast";
const target_cache_dir = try std.fs.path.join(b.allocator, &.{ commit_cache_dir, zig_triple, release_tag });
_ = target_cache_dir;
const include_dir = try std.fs.path.join(b.allocator, &.{ commit_cache_dir, "include" });
module.addIncludePath(.{ .cwd_relative = include_dir });
module.addIncludePath(.{ .cwd_relative = sdkPath("/src/dawn") });
}
pub fn ensureBinaryDownloaded(
allocator: std.mem.Allocator,
cache_root: ?[]const u8,
zig_triple: []const u8,
is_debug: bool,
is_windows: bool,
version: []const u8,
) !void {
// If zig-cache/mach/gpu-dawn/<git revision> does not exist:
// If on a commit in the main branch => rm -r zig-cache/mach/gpu-dawn/
// else => noop
// If zig-cache/mach/gpu-dawn/<git revision>/<target> exists:
// noop
// else:
// Download archive to zig-cache/mach/gpu-dawn/download/macos-aarch64
// Extract to zig-cache/mach/gpu-dawn/<git revision>/macos-aarch64/libgpu.a
// Remove zig-cache/mach/gpu-dawn/download
const base_cache_dir_rel = try std.fs.path.join(allocator, &.{ cache_root orelse "zig-cache", "mach", "gpu-dawn" });
try std.fs.cwd().makePath(base_cache_dir_rel);
const base_cache_dir = try std.fs.cwd().realpathAlloc(allocator, base_cache_dir_rel);
const commit_cache_dir = try std.fs.path.join(allocator, &.{ base_cache_dir, version });
defer {
allocator.free(base_cache_dir_rel);
allocator.free(base_cache_dir);
allocator.free(commit_cache_dir);
}
if (!dirExists(commit_cache_dir)) {
// Commit cache dir does not exist. If the commit we're on is in the main branch, we're
// probably moving to a newer commit and so we should cleanup older cached binaries.
const current_git_commit = try getCurrentGitCommit(allocator);
if (gitBranchContainsCommit(allocator, "main", current_git_commit) catch false) {
std.fs.deleteTreeAbsolute(base_cache_dir) catch {};
}
}
const release_tag = if (is_debug) "debug" else "release-fast";
const target_cache_dir = try std.fs.path.join(allocator, &.{ commit_cache_dir, zig_triple, release_tag });
defer allocator.free(target_cache_dir);
if (dirExists(target_cache_dir)) {
return; // nothing to do, already have the binary
}
downloadBinary(allocator, commit_cache_dir, release_tag, target_cache_dir, zig_triple, is_windows, version) catch |err| {
// A download failed, or extraction failed, so wipe out the directory to ensure we correctly
// try again next time.
std.fs.deleteTreeAbsolute(base_cache_dir) catch {};
std.log.err("mach/gpu-dawn: prebuilt binary download failed: {s}", .{@errorName(err)});
std.process.exit(1);
};
}
fn downloadBinary(
allocator: std.mem.Allocator,
commit_cache_dir: []const u8,
release_tag: []const u8,
target_cache_dir: []const u8,
zig_triple: []const u8,
is_windows: bool,
version: []const u8,
) !void {
const download_dir = try std.fs.path.join(allocator, &.{ target_cache_dir, "download" });
defer allocator.free(download_dir);
std.fs.cwd().makePath(download_dir) catch @panic(download_dir);
std.debug.print("download_dir: {s}\n", .{download_dir});
// Replace "..." with "---" because GitHub releases has very weird restrictions on file names.
// https://twitter.com/slimsag/status/1498025997987315713
const github_triple = try std.mem.replaceOwned(u8, allocator, zig_triple, "...", "---");
defer allocator.free(github_triple);
// Compose the download URL, e.g.:
// https://github.com/hexops/mach-gpu-dawn/releases/download/release-6b59025/libdawn_x86_64-macos-none_debug.a.gz
const github_base_url = try getGitHubBaseURLOwned(allocator);
defer allocator.free(github_base_url);
const lib_prefix = if (is_windows) "dawn_" else "libdawn_";
const lib_ext = if (is_windows) ".lib" else ".a";
const lib_file_name = if (is_windows) "dawn.lib" else "libdawn.a";
const download_url = try std.mem.concat(allocator, u8, &.{
github_base_url,
"/hexops/mach-gpu-dawn/releases/download/",
version,
"/",
lib_prefix,
github_triple,
"_",
release_tag,
lib_ext,
".gz",
});
defer allocator.free(download_url);
// Download and decompress libdawn
const gz_target_file = try std.fs.path.join(allocator, &.{ download_dir, "compressed.gz" });
defer allocator.free(gz_target_file);
downloadFile(allocator, gz_target_file, download_url) catch @panic(gz_target_file);
const target_file = try std.fs.path.join(allocator, &.{ target_cache_dir, lib_file_name });
defer allocator.free(target_file);
log.info("extracting {s}\n", .{gz_target_file});
try gzipDecompress(allocator, gz_target_file, target_file);
log.info("finished\n", .{});
// If we don't yet have the headers (these are shared across architectures), download them.
const include_dir = try std.fs.path.join(allocator, &.{ commit_cache_dir, "include" });
defer allocator.free(include_dir);
if (!dirExists(include_dir)) {
// Compose the headers download URL, e.g.:
// https://github.com/hexops/mach-gpu-dawn/releases/download/release-6b59025/headers.json.gz
const headers_download_url = try std.mem.concat(allocator, u8, &.{
github_base_url,
"/hexops/mach-gpu-dawn/releases/download/",
version,
"/headers.json.gz",
});
defer allocator.free(headers_download_url);
// Download and decompress headers.json.gz
const headers_gz_target_file = try std.fs.path.join(allocator, &.{ download_dir, "headers.json.gz" });
defer allocator.free(headers_gz_target_file);
downloadFile(allocator, headers_gz_target_file, headers_download_url) catch @panic(headers_gz_target_file);
const headers_target_file = try std.fs.path.join(allocator, &.{ target_cache_dir, "headers.json" });
defer allocator.free(headers_target_file);
gzipDecompress(allocator, headers_gz_target_file, headers_target_file) catch @panic(headers_target_file);
// Extract headers JSON archive.
extractHeaders(allocator, headers_target_file, commit_cache_dir) catch @panic(commit_cache_dir);
}
try std.fs.deleteTreeAbsolute(download_dir);
}
fn extractHeaders(allocator: std.mem.Allocator, json_file: []const u8, out_dir: []const u8) !void {
const contents = try std.fs.cwd().readFileAlloc(allocator, json_file, std.math.maxInt(usize));
defer allocator.free(contents);
var tree = try std.json.parseFromSlice(std.json.Value, allocator, contents, .{});
defer tree.deinit();
var iter = tree.value.object.iterator();
while (iter.next()) |f| {
const out_path = try std.fs.path.join(allocator, &.{ out_dir, f.key_ptr.* });
defer allocator.free(out_path);
try std.fs.cwd().makePath(std.fs.path.dirname(out_path).?);
var new_file = try std.fs.createFileAbsolute(out_path, .{});
defer new_file.close();
try new_file.writeAll(f.value_ptr.*.string);
}
}
fn dirExists(path: []const u8) bool {
var dir = std.fs.openDirAbsolute(path, .{}) catch return false;
dir.close();
return true;
}
fn gzipDecompress(allocator: std.mem.Allocator, src_absolute_path: []const u8, dst_absolute_path: []const u8) !void {
var file = try std.fs.openFileAbsolute(src_absolute_path, .{ .mode = .read_only });
defer file.close();
var buf_stream = std.io.bufferedReader(file.reader());
var decompressor = std.compress.gzip.decompressor(buf_stream.reader());
// Read and decompress the whole file
const buf = try decompressor.reader().readAllAlloc(allocator, std.math.maxInt(usize));
defer allocator.free(buf);
var new_file = try std.fs.createFileAbsolute(dst_absolute_path, .{});
defer new_file.close();
try new_file.writeAll(buf);
}
fn gitBranchContainsCommit(allocator: std.mem.Allocator, branch: []const u8, commit: []const u8) !bool {
const result = try std.process.Child.run(.{
.allocator = allocator,
.argv = &.{ "git", "branch", branch, "--contains", commit },
.cwd = sdkPath("/"),
});
defer {
allocator.free(result.stdout);
allocator.free(result.stderr);
}
return result.term.Exited == 0;
}
fn getCurrentGitCommit(allocator: std.mem.Allocator) ![]const u8 {
const result = try std.process.Child.run(.{
.allocator = allocator,
.argv = &.{ "git", "rev-parse", "HEAD" },
.cwd = sdkPath("/"),
});
defer allocator.free(result.stderr);
if (result.stdout.len > 0) return result.stdout[0 .. result.stdout.len - 1]; // trim newline
return result.stdout;
}
fn gitClone(allocator: std.mem.Allocator, repository: []const u8, dir: []const u8) !bool {
const result = try std.process.Child.run(.{
.allocator = allocator,
.argv = &.{ "git", "clone", repository, dir },
.cwd = sdkPath("/"),
});
defer {
allocator.free(result.stdout);
allocator.free(result.stderr);
}
return result.term.Exited == 0;
}
fn downloadFile(allocator: std.mem.Allocator, target_file_path: []const u8, url: []const u8) !void {
log.info("downloading {s}\n", .{url});
var client: std.http.Client = .{ .allocator = allocator };
defer client.deinit();
var resp = std.ArrayList(u8).init(allocator);
defer resp.deinit();
var fetch_res = try client.fetch(.{
.location = .{ .url = url },
.response_storage = .{ .dynamic = &resp },
.max_append_size = 50 * 1024 * 1024,
});
if (fetch_res.status.class() != .success) {
log.err("unable to fetch: HTTP {}", .{fetch_res.status});
return error.FetchFailed;
}
log.info("finished\n", .{});
const target_file = try std.fs.cwd().createFile(target_file_path, .{});
try target_file.writeAll(resp.items);
}
fn isLinuxDesktopLike(tag: std.Target.Os.Tag) bool {
return switch (tag) {
.linux,
.freebsd,
.kfreebsd,
.openbsd,
.dragonfly,
=> true,
else => false,
};
}
pub fn appendFlags(step: *std.Build.Step.Compile, flags: *std.ArrayList([]const u8), debug_symbols: bool, is_cpp: bool) !void {
if (debug_symbols) try flags.append("-g1") else try flags.append("-g0");
if (is_cpp) try flags.append("-std=c++17");
if (isLinuxDesktopLike(step.rootModuleTarget().os.tag)) {
step.defineCMacro("DAWN_USE_X11", "1");
step.defineCMacro("DAWN_USE_WAYLAND", "1");
}
}
fn linkLibDawnCommonDependencies(b: *std.Build, step: *std.Build.Step.Compile, mod: *std.Build.Module, options: Options) void {
_ = b;
_ = options;
step.linkLibCpp();
if (step.rootModuleTarget().os.tag == .macos) {
@import("xcode_frameworks").addPaths(mod);
step.linkSystemLibrary("objc");
step.linkFramework("Foundation");
}
}
// Builds common sources; derived from src/common/BUILD.gn
fn buildLibDawnCommon(b: *std.Build, step: *std.Build.Step.Compile, options: Options) !*std.Build.Step.Compile {
const target = step.rootModuleTarget();
const lib = if (!options.separate_libs) step else if (options.shared_libs) b.addSharedLibrary(.{
.name = "dawn-common",
.target = step.root_module.resolved_target.?,
.optimize = if (options.debug) .Debug else .ReleaseFast,
}) else b.addStaticLibrary(.{
.name = "dawn-common",
.target = step.root_module.resolved_target.?,
.optimize = if (options.debug) .Debug else .ReleaseFast,
});
if (options.install_libs) b.installArtifact(lib);
linkLibDawnCommonDependencies(b, lib, &lib.root_module, options);
if (target.os.tag == .linux) lib.linkLibrary(b.dependency("x11_headers", .{
.target = step.root_module.resolved_target.?,
.optimize = lib.root_module.optimize.?,
}).artifact("x11-headers"));
defineDawnEnableBackend(lib, options);
var flags = std.ArrayList([]const u8).init(b.allocator);
try flags.appendSlice(&.{
include("libs/dawn/src"),
include("libs/dawn/out/Debug/gen/include"),
include("libs/dawn/out/Debug/gen/src"),
});
try appendLangScannedSources(b, lib, .{
.rel_dirs = &.{
"libs/dawn/src/dawn/common/",
"libs/dawn/out/Debug/gen/src/dawn/common/",
},
.flags = flags.items,
.excluding_contains = &.{
"test",
"benchmark",
"mock",
"WindowsUtils.cpp",
},
});
var cpp_sources = std.ArrayList([]const u8).init(b.allocator);
if (target.os.tag == .macos) {
// TODO(build-system): pass system SDK options through
const abs_path = "libs/dawn/src/dawn/common/SystemUtils_mac.mm";
try cpp_sources.append(abs_path);
}
if (target.os.tag == .windows) {
const abs_path = "libs/dawn/src/dawn/common/WindowsUtils.cpp";
try cpp_sources.append(abs_path);
}
var cpp_flags = std.ArrayList([]const u8).init(b.allocator);
try cpp_flags.appendSlice(flags.items);
try appendFlags(lib, &cpp_flags, options.debug, true);
lib.addCSourceFiles(.{ .files = cpp_sources.items, .flags = cpp_flags.items });
return lib;
}
fn linkLibDawnPlatformDependencies(b: *std.Build, step: *std.Build.Step.Compile, mod: *std.Build.Module, options: Options) void {
_ = mod;
_ = b;
_ = options;
step.linkLibCpp();
}
// Build dawn platform sources; derived from src/dawn/platform/BUILD.gn
fn buildLibDawnPlatform(b: *std.Build, step: *std.Build.Step.Compile, options: Options) !*std.Build.Step.Compile {
const lib = if (!options.separate_libs) step else if (options.shared_libs) b.addSharedLibrary(.{
.name = "dawn-platform",
.target = step.root_module.resolved_target.?,
.optimize = if (options.debug) .Debug else .ReleaseFast,
}) else b.addStaticLibrary(.{
.name = "dawn-platform",
.target = step.root_module.resolved_target.?,
.optimize = if (options.debug) .Debug else .ReleaseFast,
});
if (options.install_libs) b.installArtifact(lib);
linkLibDawnPlatformDependencies(b, lib, &lib.root_module, options);
var cpp_flags = std.ArrayList([]const u8).init(b.allocator);
try appendFlags(lib, &cpp_flags, options.debug, true);
try cpp_flags.appendSlice(&.{
include("libs/dawn/src"),
include("libs/dawn/include"),
include("libs/dawn/out/Debug/gen/include"),
});
var cpp_sources = std.ArrayList([]const u8).init(b.allocator);
inline for ([_][]const u8{
"src/dawn/platform/metrics/HistogramMacros.cpp",
"src/dawn/platform/tracing/EventTracer.cpp",
"src/dawn/platform/WorkerThread.cpp",
"src/dawn/platform/DawnPlatform.cpp",
}) |path| {
const abs_path = "libs/dawn/" ++ path;
try cpp_sources.append(abs_path);
}
lib.addCSourceFiles(.{ .files = cpp_sources.items, .flags = cpp_flags.items });
return lib;
}
fn defineDawnEnableBackend(step: *std.Build.Step.Compile, options: Options) void {
step.defineCMacro("DAWN_ENABLE_BACKEND_NULL", "1");
// TODO: support the Direct3D 11 backend
// if (options.d3d11.?) step.defineCMacro("DAWN_ENABLE_BACKEND_D3D11", "1");
if (options.d3d12.?) step.defineCMacro("DAWN_ENABLE_BACKEND_D3D12", "1");
if (options.metal.?) step.defineCMacro("DAWN_ENABLE_BACKEND_METAL", "1");
if (options.vulkan.?) step.defineCMacro("DAWN_ENABLE_BACKEND_VULKAN", "1");
if (options.desktop_gl.?) {
step.defineCMacro("DAWN_ENABLE_BACKEND_OPENGL", "1");
step.defineCMacro("DAWN_ENABLE_BACKEND_DESKTOP_GL", "1");
}
if (options.opengl_es.?) {
step.defineCMacro("DAWN_ENABLE_BACKEND_OPENGL", "1");
step.defineCMacro("DAWN_ENABLE_BACKEND_OPENGLES", "1");
}
}
fn linkLibDawnNativeDependencies(b: *std.Build, step: *std.Build.Step.Compile, mod: *std.Build.Module, options: Options) void {
step.linkLibCpp();
if (options.d3d12.?) {
step.linkLibrary(b.dependency("direct3d_headers", .{
.target = step.root_module.resolved_target.?,
.optimize = step.root_module.optimize.?,
}).artifact("direct3d-headers"));
@import("direct3d_headers").addLibraryPath(step);
}
if (options.metal.?) {
@import("xcode_frameworks").addPaths(mod);
step.linkSystemLibrary("objc");
step.linkFramework("Metal");
step.linkFramework("CoreGraphics");
step.linkFramework("Foundation");
step.linkFramework("IOKit");
step.linkFramework("IOSurface");
step.linkFramework("QuartzCore");
}
}
// Builds dawn native sources; derived from src/dawn/native/BUILD.gn
fn buildLibDawnNative(b: *std.Build, step: *std.Build.Step.Compile, options: Options) !*std.Build.Step.Compile {
const target = step.rootModuleTarget();
const lib = if (!options.separate_libs) step else if (options.shared_libs) b.addSharedLibrary(.{
.name = "dawn-native",
.target = step.root_module.resolved_target.?,
.optimize = if (options.debug) .Debug else .ReleaseFast,
}) else b.addStaticLibrary(.{
.name = "dawn-native",
.target = step.root_module.resolved_target.?,
.optimize = if (options.debug) .Debug else .ReleaseFast,
});
if (options.install_libs) b.installArtifact(lib);
linkLibDawnNativeDependencies(b, lib, &lib.root_module, options);
if (options.vulkan.?) lib.linkLibrary(b.dependency("vulkan_headers", .{
.target = step.root_module.resolved_target.?,
.optimize = lib.root_module.optimize.?,
}).artifact("vulkan-headers"));
if (target.os.tag == .linux) lib.linkLibrary(b.dependency("x11_headers", .{
.target = step.root_module.resolved_target.?,
.optimize = lib.root_module.optimize.?,
}).artifact("x11-headers"));
// MacOS: this must be defined for macOS 13.3 and older.
// Critically, this MUST NOT be included as a -D__kernel_ptr_semantics flag. If it is,
// then this macro will not be defined even if `defineCMacro` was also called!
lib.defineCMacro("__kernel_ptr_semantics", "");
lib.defineCMacro("_HRESULT_DEFINED", "");
lib.defineCMacro("HRESULT", "long");
defineDawnEnableBackend(lib, options);
// TODO(build-system): make these optional
lib.defineCMacro("TINT_BUILD_SPV_READER", "1");
lib.defineCMacro("TINT_BUILD_SPV_WRITER", "1");
lib.defineCMacro("TINT_BUILD_WGSL_READER", "1");
lib.defineCMacro("TINT_BUILD_WGSL_WRITER", "1");
lib.defineCMacro("TINT_BUILD_MSL_WRITER", "1");
lib.defineCMacro("TINT_BUILD_HLSL_WRITER", "1");
lib.defineCMacro("TINT_BUILD_GLSL_WRITER", "1");
lib.defineCMacro("DAWN_NO_WINDOWS_UI", "1");
var flags = std.ArrayList([]const u8).init(b.allocator);
try flags.appendSlice(&.{
include("libs/dawn"),
include("libs/dawn/src"),
include("libs/dawn/include"),
include("libs/dawn/third_party/vulkan-deps/spirv-tools/src/include"),
include("libs/dawn/third_party/khronos"),
"-Wno-deprecated-declarations",
"-Wno-deprecated-builtins",
include("libs/dawn/third_party/abseil-cpp"),
include("libs/dawn/"),
include("libs/dawn/include/tint"),
include("libs/dawn/third_party/vulkan-deps/vulkan-tools/src/"),
include("libs/dawn/out/Debug/gen/include"),
include("libs/dawn/out/Debug/gen/src"),
});
if (options.d3d12.?) {
lib.defineCMacro("DAWN_NO_WINDOWS_UI", "");
lib.defineCMacro("__EMULATE_UUID", "");
lib.defineCMacro("_CRT_SECURE_NO_WARNINGS", "");
lib.defineCMacro("WIN32_LEAN_AND_MEAN", "");
lib.defineCMacro("D3D10_ARBITRARY_HEADER_ORDERING", "");
lib.defineCMacro("NOMINMAX", "");
try flags.appendSlice(&.{
"-Wno-nonportable-include-path",
"-Wno-extern-c-compat",
"-Wno-invalid-noreturn",
"-Wno-pragma-pack",
"-Wno-microsoft-template-shadow",
"-Wno-unused-command-line-argument",
"-Wno-microsoft-exception-spec",
"-Wno-implicit-exception-spec-mismatch",
"-Wno-unknown-attributes",
"-Wno-c++20-extensions",
});
}
try appendLangScannedSources(b, lib, .{
.rel_dirs = &.{
"libs/dawn/out/Debug/gen/src/dawn/",
"libs/dawn/src/dawn/native/",
"libs/dawn/src/dawn/native/utils/",
"libs/dawn/src/dawn/native/stream/",
},
.flags = flags.items,
.excluding_contains = if (options.shared_libs) &.{
"test",
"benchmark",
"mock",
"SpirvValidation.cpp",
"X11Functions.cpp",
"dawn_proc.c",
} else &.{
"test",
"benchmark",
"mock",
"SpirvValidation.cpp",
"X11Functions.cpp",
"dawn_proc.c",
},
});
// dawn_native_gen
try appendLangScannedSources(b, lib, .{
.rel_dirs = &.{
"libs/dawn/out/Debug/gen/src/dawn/native/",
},
.flags = flags.items,
.excluding_contains = &.{ "test", "benchmark", "mock", "webgpu_dawn_native_proc.cpp" },
});
// TODO(build-system): could allow enable_vulkan_validation_layers here. See src/dawn/native/BUILD.gn
// TODO(build-system): allow use_angle here. See src/dawn/native/BUILD.gn
// TODO(build-system): could allow use_swiftshader here. See src/dawn/native/BUILD.gn
var cpp_sources = std.ArrayList([]const u8).init(b.allocator);
if (options.d3d12.?) {
inline for ([_][]const u8{
"src/dawn/mingw_helpers.cpp",
}) |path| {
try cpp_sources.append(path);
}
try appendLangScannedSources(b, lib, .{
.rel_dirs = &.{
"libs/dawn/src/dawn/native/d3d/",
"libs/dawn/src/dawn/native/d3d12/",
},
.flags = flags.items,
.excluding_contains = &.{ "test", "benchmark", "mock" },
});
}
if (options.metal.?) {
try appendLangScannedSources(b, lib, .{
.objc = true,
.rel_dirs = &.{
"libs/dawn/src/dawn/native/metal/",
"libs/dawn/src/dawn/native/",
},
.flags = flags.items,
.excluding_contains = &.{ "test", "benchmark", "mock" },
});
}
if (isLinuxDesktopLike(target.os.tag)) {
inline for ([_][]const u8{
"src/dawn/native/X11Functions.cpp",
}) |path| {
const abs_path = "libs/dawn/" ++ path;
try cpp_sources.append(abs_path);
}
}
inline for ([_][]const u8{
"src/dawn/native/null/DeviceNull.cpp",
}) |path| {
const abs_path = "libs/dawn/" ++ path;
try cpp_sources.append(abs_path);
}
if (options.desktop_gl.? or options.vulkan.?) {
inline for ([_][]const u8{