-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Compile.zig
2295 lines (1990 loc) · 81.8 KB
/
Compile.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 builtin = @import("builtin");
const std = @import("std");
const mem = std.mem;
const fs = std.fs;
const assert = std.debug.assert;
const panic = std.debug.panic;
const ArrayList = std.ArrayList;
const StringHashMap = std.StringHashMap;
const Sha256 = std.crypto.hash.sha2.Sha256;
const Allocator = mem.Allocator;
const Step = std.Build.Step;
const CrossTarget = std.zig.CrossTarget;
const NativeTargetInfo = std.zig.system.NativeTargetInfo;
const LazyPath = std.Build.LazyPath;
const PkgConfigPkg = std.Build.PkgConfigPkg;
const PkgConfigError = std.Build.PkgConfigError;
const ExecError = std.Build.ExecError;
const Module = std.Build.Module;
const VcpkgRoot = std.Build.VcpkgRoot;
const InstallDir = std.Build.InstallDir;
const GeneratedFile = std.Build.GeneratedFile;
const Compile = @This();
pub const base_id: Step.Id = .compile;
step: Step,
name: []const u8,
target: CrossTarget,
target_info: NativeTargetInfo,
optimize: std.builtin.OptimizeMode,
linker_script: ?LazyPath = null,
version_script: ?[]const u8 = null,
out_filename: []const u8,
linkage: ?Linkage = null,
version: ?std.SemanticVersion,
kind: Kind,
major_only_filename: ?[]const u8,
name_only_filename: ?[]const u8,
strip: ?bool,
unwind_tables: ?bool,
// keep in sync with src/link.zig:CompressDebugSections
compress_debug_sections: enum { none, zlib } = .none,
lib_paths: ArrayList(LazyPath),
rpaths: ArrayList(LazyPath),
frameworks: StringHashMap(FrameworkLinkInfo),
verbose_link: bool,
verbose_cc: bool,
bundle_compiler_rt: ?bool = null,
single_threaded: ?bool,
stack_protector: ?bool = null,
disable_stack_probing: bool,
disable_sanitize_c: bool,
sanitize_thread: bool,
rdynamic: bool,
dwarf_format: ?std.dwarf.Format = null,
import_memory: bool = false,
export_memory: bool = false,
/// For WebAssembly targets, this will allow for undefined symbols to
/// be imported from the host environment.
import_symbols: bool = false,
import_table: bool = false,
export_table: bool = false,
initial_memory: ?u64 = null,
max_memory: ?u64 = null,
shared_memory: bool = false,
global_base: ?u64 = null,
c_std: std.Build.CStd,
/// Set via options; intended to be read-only after that.
zig_lib_dir: ?LazyPath,
/// Set via options; intended to be read-only after that.
main_pkg_path: ?LazyPath,
exec_cmd_args: ?[]const ?[]const u8,
filter: ?[]const u8,
test_evented_io: bool = false,
test_runner: ?[]const u8,
code_model: std.builtin.CodeModel = .default,
wasi_exec_model: ?std.builtin.WasiExecModel = null,
/// Symbols to be exported when compiling to wasm
export_symbol_names: []const []const u8 = &.{},
root_src: ?LazyPath,
out_lib_filename: []const u8,
modules: std.StringArrayHashMap(*Module),
link_objects: ArrayList(LinkObject),
include_dirs: ArrayList(IncludeDir),
c_macros: ArrayList([]const u8),
installed_headers: ArrayList(*Step),
is_linking_libc: bool,
is_linking_libcpp: bool,
vcpkg_bin_path: ?[]const u8 = null,
installed_path: ?[]const u8,
/// Base address for an executable image.
image_base: ?u64 = null,
libc_file: ?LazyPath = null,
valgrind_support: ?bool = null,
each_lib_rpath: ?bool = null,
/// On ELF targets, this will emit a link section called ".note.gnu.build-id"
/// which can be used to coordinate a stripped binary with its debug symbols.
/// As an example, the bloaty project refuses to work unless its inputs have
/// build ids, in order to prevent accidental mismatches.
/// The default is to not include this section because it slows down linking.
build_id: ?BuildId = null,
/// Create a .eh_frame_hdr section and a PT_GNU_EH_FRAME segment in the ELF
/// file.
link_eh_frame_hdr: bool = false,
link_emit_relocs: bool = false,
/// Place every function in its own section so that unused ones may be
/// safely garbage-collected during the linking phase.
link_function_sections: bool = false,
/// Remove functions and data that are unreachable by the entry point or
/// exported symbols.
link_gc_sections: ?bool = null,
/// (Windows) Whether or not to enable ASLR. Maps to the /DYNAMICBASE[:NO] linker argument.
linker_dynamicbase: bool = true,
linker_allow_shlib_undefined: ?bool = null,
/// Permit read-only relocations in read-only segments. Disallowed by default.
link_z_notext: bool = false,
/// Force all relocations to be read-only after processing.
link_z_relro: bool = true,
/// Allow relocations to be lazily processed after load.
link_z_lazy: bool = false,
/// Common page size
link_z_common_page_size: ?u64 = null,
/// Maximum page size
link_z_max_page_size: ?u64 = null,
/// (Darwin) Install name for the dylib
install_name: ?[]const u8 = null,
/// (Darwin) Path to entitlements file
entitlements: ?[]const u8 = null,
/// (Darwin) Size of the pagezero segment.
pagezero_size: ?u64 = null,
/// (Darwin) Set size of the padding between the end of load commands
/// and start of `__TEXT,__text` section.
headerpad_size: ?u32 = null,
/// (Darwin) Automatically Set size of the padding between the end of load commands
/// and start of `__TEXT,__text` section to a value fitting all paths expanded to MAXPATHLEN.
headerpad_max_install_names: bool = false,
/// (Darwin) Remove dylibs that are unreachable by the entry point or exported symbols.
dead_strip_dylibs: bool = false,
/// Position Independent Code
force_pic: ?bool = null,
/// Position Independent Executable
pie: ?bool = null,
red_zone: ?bool = null,
omit_frame_pointer: ?bool = null,
dll_export_fns: ?bool = null,
subsystem: ?std.Target.SubSystem = null,
entry_symbol_name: ?[]const u8 = null,
/// List of symbols forced as undefined in the symbol table
/// thus forcing their resolution by the linker.
/// Corresponds to `-u <symbol>` for ELF/MachO and `/include:<symbol>` for COFF/PE.
force_undefined_symbols: std.StringHashMap(void),
/// Overrides the default stack size
stack_size: ?u64 = null,
want_lto: ?bool = null,
use_llvm: ?bool,
use_lld: ?bool,
/// This is an advanced setting that can change the intent of this Compile step.
/// If this slice has nonzero length, it means that this Compile step exists to
/// check for compile errors and return *success* if they match, and failure
/// otherwise.
expect_errors: []const []const u8 = &.{},
emit_directory: ?*GeneratedFile,
generated_docs: ?*GeneratedFile,
generated_asm: ?*GeneratedFile,
generated_bin: ?*GeneratedFile,
generated_pdb: ?*GeneratedFile,
generated_implib: ?*GeneratedFile,
generated_llvm_bc: ?*GeneratedFile,
generated_llvm_ir: ?*GeneratedFile,
generated_h: ?*GeneratedFile,
pub const CSourceFiles = struct {
/// Relative to the build root.
files: []const []const u8,
flags: []const []const u8,
};
pub const CSourceFile = struct {
file: LazyPath,
flags: []const []const u8,
pub fn dupe(self: CSourceFile, b: *std.Build) CSourceFile {
return .{
.file = self.file.dupe(b),
.flags = b.dupeStrings(self.flags),
};
}
};
pub const LinkObject = union(enum) {
static_path: LazyPath,
other_step: *Compile,
system_lib: SystemLib,
assembly_file: LazyPath,
c_source_file: *CSourceFile,
c_source_files: *CSourceFiles,
};
pub const SystemLib = struct {
name: []const u8,
needed: bool,
weak: bool,
use_pkg_config: UsePkgConfig,
preferred_link_mode: std.builtin.LinkMode,
search_strategy: SystemLib.SearchStrategy,
pub const UsePkgConfig = enum {
/// Don't use pkg-config, just pass -lfoo where foo is name.
no,
/// Try to get information on how to link the library from pkg-config.
/// If that fails, fall back to passing -lfoo where foo is name.
yes,
/// Try to get information on how to link the library from pkg-config.
/// If that fails, error out.
force,
};
pub const SearchStrategy = enum { paths_first, mode_first, no_fallback };
};
const FrameworkLinkInfo = struct {
needed: bool = false,
weak: bool = false,
};
pub const IncludeDir = union(enum) {
path: LazyPath,
path_system: LazyPath,
framework_path: LazyPath,
framework_path_system: LazyPath,
other_step: *Compile,
config_header_step: *Step.ConfigHeader,
};
pub const Options = struct {
name: []const u8,
root_source_file: ?LazyPath = null,
target: CrossTarget,
optimize: std.builtin.OptimizeMode,
kind: Kind,
linkage: ?Linkage = null,
version: ?std.SemanticVersion = null,
max_rss: usize = 0,
filter: ?[]const u8 = null,
test_runner: ?[]const u8 = null,
link_libc: ?bool = null,
single_threaded: ?bool = null,
use_llvm: ?bool = null,
use_lld: ?bool = null,
zig_lib_dir: ?LazyPath = null,
main_pkg_path: ?LazyPath = null,
};
pub const BuildId = union(enum) {
none,
fast,
uuid,
sha1,
md5,
hexstring: HexString,
pub fn eql(a: BuildId, b: BuildId) bool {
const a_tag = std.meta.activeTag(a);
const b_tag = std.meta.activeTag(b);
if (a_tag != b_tag) return false;
return switch (a) {
.none, .fast, .uuid, .sha1, .md5 => true,
.hexstring => |a_hexstring| mem.eql(u8, a_hexstring.toSlice(), b.hexstring.toSlice()),
};
}
pub const HexString = struct {
bytes: [32]u8,
len: u8,
/// Result is byte values, *not* hex-encoded.
pub fn toSlice(hs: *const HexString) []const u8 {
return hs.bytes[0..hs.len];
}
};
/// Input is byte values, *not* hex-encoded.
/// Asserts `bytes` fits inside `HexString`
pub fn initHexString(bytes: []const u8) BuildId {
var result: BuildId = .{ .hexstring = .{
.bytes = undefined,
.len = @as(u8, @intCast(bytes.len)),
} };
@memcpy(result.hexstring.bytes[0..bytes.len], bytes);
return result;
}
/// Converts UTF-8 text to a `BuildId`.
pub fn parse(text: []const u8) !BuildId {
if (mem.eql(u8, text, "none")) {
return .none;
} else if (mem.eql(u8, text, "fast")) {
return .fast;
} else if (mem.eql(u8, text, "uuid")) {
return .uuid;
} else if (mem.eql(u8, text, "sha1") or mem.eql(u8, text, "tree")) {
return .sha1;
} else if (mem.eql(u8, text, "md5")) {
return .md5;
} else if (mem.startsWith(u8, text, "0x")) {
var result: BuildId = .{ .hexstring = undefined };
const slice = try std.fmt.hexToBytes(&result.hexstring.bytes, text[2..]);
result.hexstring.len = @as(u8, @intCast(slice.len));
return result;
}
return error.InvalidBuildIdStyle;
}
test parse {
try std.testing.expectEqual(BuildId.md5, try parse("md5"));
try std.testing.expectEqual(BuildId.none, try parse("none"));
try std.testing.expectEqual(BuildId.fast, try parse("fast"));
try std.testing.expectEqual(BuildId.uuid, try parse("uuid"));
try std.testing.expectEqual(BuildId.sha1, try parse("sha1"));
try std.testing.expectEqual(BuildId.sha1, try parse("tree"));
try std.testing.expect(BuildId.initHexString("").eql(try parse("0x")));
try std.testing.expect(BuildId.initHexString("\x12\x34\x56").eql(try parse("0x123456")));
try std.testing.expectError(error.InvalidLength, parse("0x12-34"));
try std.testing.expectError(error.InvalidCharacter, parse("0xfoobbb"));
try std.testing.expectError(error.InvalidBuildIdStyle, parse("yaddaxxx"));
}
};
pub const Kind = enum {
exe,
lib,
obj,
@"test",
};
pub const Linkage = enum { dynamic, static };
pub fn create(owner: *std.Build, options: Options) *Compile {
const name = owner.dupe(options.name);
const root_src: ?LazyPath = if (options.root_source_file) |rsrc| rsrc.dupe(owner) else null;
if (mem.indexOf(u8, name, "/") != null or mem.indexOf(u8, name, "\\") != null) {
panic("invalid name: '{s}'. It looks like a file path, but it is supposed to be the library or application name.", .{name});
}
// Avoid the common case of the step name looking like "zig test test".
const name_adjusted = if (options.kind == .@"test" and mem.eql(u8, name, "test"))
""
else
owner.fmt("{s} ", .{name});
const step_name = owner.fmt("{s} {s}{s} {s}", .{
switch (options.kind) {
.exe => "zig build-exe",
.lib => "zig build-lib",
.obj => "zig build-obj",
.@"test" => "zig test",
},
name_adjusted,
@tagName(options.optimize),
options.target.zigTriple(owner.allocator) catch @panic("OOM"),
});
const target_info = NativeTargetInfo.detect(options.target) catch @panic("unhandled error");
const out_filename = std.zig.binNameAlloc(owner.allocator, .{
.root_name = name,
.target = target_info.target,
.output_mode = switch (options.kind) {
.lib => .Lib,
.obj => .Obj,
.exe, .@"test" => .Exe,
},
.link_mode = if (options.linkage) |some| @as(std.builtin.LinkMode, switch (some) {
.dynamic => .Dynamic,
.static => .Static,
}) else null,
.version = options.version,
}) catch @panic("OOM");
const self = owner.allocator.create(Compile) catch @panic("OOM");
self.* = .{
.strip = null,
.unwind_tables = null,
.verbose_link = false,
.verbose_cc = false,
.optimize = options.optimize,
.target = options.target,
.linkage = options.linkage,
.kind = options.kind,
.root_src = root_src,
.name = name,
.frameworks = StringHashMap(FrameworkLinkInfo).init(owner.allocator),
.step = Step.init(.{
.id = base_id,
.name = step_name,
.owner = owner,
.makeFn = make,
.max_rss = options.max_rss,
}),
.version = options.version,
.out_filename = out_filename,
.out_lib_filename = undefined,
.major_only_filename = null,
.name_only_filename = null,
.modules = std.StringArrayHashMap(*Module).init(owner.allocator),
.include_dirs = ArrayList(IncludeDir).init(owner.allocator),
.link_objects = ArrayList(LinkObject).init(owner.allocator),
.c_macros = ArrayList([]const u8).init(owner.allocator),
.lib_paths = ArrayList(LazyPath).init(owner.allocator),
.rpaths = ArrayList(LazyPath).init(owner.allocator),
.installed_headers = ArrayList(*Step).init(owner.allocator),
.c_std = std.Build.CStd.C99,
.zig_lib_dir = null,
.main_pkg_path = null,
.exec_cmd_args = null,
.filter = options.filter,
.test_runner = options.test_runner,
.disable_stack_probing = false,
.disable_sanitize_c = false,
.sanitize_thread = false,
.rdynamic = false,
.installed_path = null,
.force_undefined_symbols = StringHashMap(void).init(owner.allocator),
.emit_directory = null,
.generated_docs = null,
.generated_asm = null,
.generated_bin = null,
.generated_pdb = null,
.generated_implib = null,
.generated_llvm_bc = null,
.generated_llvm_ir = null,
.generated_h = null,
.target_info = target_info,
.is_linking_libc = options.link_libc orelse false,
.is_linking_libcpp = false,
.single_threaded = options.single_threaded,
.use_llvm = options.use_llvm,
.use_lld = options.use_lld,
};
if (options.zig_lib_dir) |lp| {
self.zig_lib_dir = lp.dupe(self.step.owner);
lp.addStepDependencies(&self.step);
}
if (options.main_pkg_path) |lp| {
self.main_pkg_path = lp.dupe(self.step.owner);
lp.addStepDependencies(&self.step);
}
if (self.kind == .lib) {
if (self.linkage != null and self.linkage.? == .static) {
self.out_lib_filename = self.out_filename;
} else if (self.version) |version| {
if (target_info.target.isDarwin()) {
self.major_only_filename = owner.fmt("lib{s}.{d}.dylib", .{
self.name,
version.major,
});
self.name_only_filename = owner.fmt("lib{s}.dylib", .{self.name});
self.out_lib_filename = self.out_filename;
} else if (target_info.target.os.tag == .windows) {
self.out_lib_filename = owner.fmt("{s}.lib", .{self.name});
} else {
self.major_only_filename = owner.fmt("lib{s}.so.{d}", .{ self.name, version.major });
self.name_only_filename = owner.fmt("lib{s}.so", .{self.name});
self.out_lib_filename = self.out_filename;
}
} else {
if (target_info.target.isDarwin()) {
self.out_lib_filename = self.out_filename;
} else if (target_info.target.os.tag == .windows) {
self.out_lib_filename = owner.fmt("{s}.lib", .{self.name});
} else {
self.out_lib_filename = self.out_filename;
}
}
}
if (root_src) |rs| rs.addStepDependencies(&self.step);
return self;
}
pub fn installHeader(cs: *Compile, src_path: []const u8, dest_rel_path: []const u8) void {
const b = cs.step.owner;
const install_file = b.addInstallHeaderFile(src_path, dest_rel_path);
b.getInstallStep().dependOn(&install_file.step);
cs.installed_headers.append(&install_file.step) catch @panic("OOM");
}
pub const InstallConfigHeaderOptions = struct {
install_dir: InstallDir = .header,
dest_rel_path: ?[]const u8 = null,
};
pub fn installConfigHeader(
cs: *Compile,
config_header: *Step.ConfigHeader,
options: InstallConfigHeaderOptions,
) void {
const dest_rel_path = options.dest_rel_path orelse config_header.include_path;
const b = cs.step.owner;
const install_file = b.addInstallFileWithDir(
.{ .generated = &config_header.output_file },
options.install_dir,
dest_rel_path,
);
install_file.step.dependOn(&config_header.step);
b.getInstallStep().dependOn(&install_file.step);
cs.installed_headers.append(&install_file.step) catch @panic("OOM");
}
pub fn installHeadersDirectory(
a: *Compile,
src_dir_path: []const u8,
dest_rel_path: []const u8,
) void {
return installHeadersDirectoryOptions(a, .{
.source_dir = .{ .path = src_dir_path },
.install_dir = .header,
.install_subdir = dest_rel_path,
});
}
pub fn installHeadersDirectoryOptions(
cs: *Compile,
options: std.Build.Step.InstallDir.Options,
) void {
const b = cs.step.owner;
const install_dir = b.addInstallDirectory(options);
b.getInstallStep().dependOn(&install_dir.step);
cs.installed_headers.append(&install_dir.step) catch @panic("OOM");
}
pub fn installLibraryHeaders(cs: *Compile, l: *Compile) void {
assert(l.kind == .lib);
const b = cs.step.owner;
const install_step = b.getInstallStep();
// Copy each element from installed_headers, modifying the builder
// to be the new parent's builder.
for (l.installed_headers.items) |step| {
const step_copy = switch (step.id) {
inline .install_file, .install_dir => |id| blk: {
const T = id.Type();
const ptr = b.allocator.create(T) catch @panic("OOM");
ptr.* = step.cast(T).?.*;
ptr.dest_builder = b;
break :blk &ptr.step;
},
else => unreachable,
};
cs.installed_headers.append(step_copy) catch @panic("OOM");
install_step.dependOn(step_copy);
}
cs.installed_headers.appendSlice(l.installed_headers.items) catch @panic("OOM");
}
pub fn addObjCopy(cs: *Compile, options: Step.ObjCopy.Options) *Step.ObjCopy {
const b = cs.step.owner;
var copy = options;
if (copy.basename == null) {
if (options.format) |f| {
copy.basename = b.fmt("{s}.{s}", .{ cs.name, @tagName(f) });
} else {
copy.basename = cs.name;
}
}
return b.addObjCopy(cs.getEmittedBin(), copy);
}
/// This function would run in the context of the package that created the executable,
/// which is undesirable when running an executable provided by a dependency package.
pub const run = @compileError("deprecated; use std.Build.addRunArtifact");
/// This function would install in the context of the package that created the artifact,
/// which is undesirable when installing an artifact provided by a dependency package.
pub const install = @compileError("deprecated; use std.Build.installArtifact");
pub fn checkObject(self: *Compile) *Step.CheckObject {
return Step.CheckObject.create(self.step.owner, self.getEmittedBin(), self.target_info.target.ofmt);
}
/// deprecated: use `setLinkerScript`
pub const setLinkerScriptPath = setLinkerScript;
pub fn setLinkerScript(self: *Compile, source: LazyPath) void {
const b = self.step.owner;
self.linker_script = source.dupe(b);
source.addStepDependencies(&self.step);
}
pub fn forceUndefinedSymbol(self: *Compile, symbol_name: []const u8) void {
const b = self.step.owner;
self.force_undefined_symbols.put(b.dupe(symbol_name), {}) catch @panic("OOM");
}
pub fn linkFramework(self: *Compile, framework_name: []const u8) void {
const b = self.step.owner;
self.frameworks.put(b.dupe(framework_name), .{}) catch @panic("OOM");
}
pub fn linkFrameworkNeeded(self: *Compile, framework_name: []const u8) void {
const b = self.step.owner;
self.frameworks.put(b.dupe(framework_name), .{
.needed = true,
}) catch @panic("OOM");
}
pub fn linkFrameworkWeak(self: *Compile, framework_name: []const u8) void {
const b = self.step.owner;
self.frameworks.put(b.dupe(framework_name), .{
.weak = true,
}) catch @panic("OOM");
}
/// Returns whether the library, executable, or object depends on a particular system library.
pub fn dependsOnSystemLibrary(self: Compile, name: []const u8) bool {
if (isLibCLibrary(name)) {
return self.is_linking_libc;
}
if (isLibCppLibrary(name)) {
return self.is_linking_libcpp;
}
for (self.link_objects.items) |link_object| {
switch (link_object) {
.system_lib => |lib| if (mem.eql(u8, lib.name, name)) return true,
else => continue,
}
}
return false;
}
pub fn linkLibrary(self: *Compile, lib: *Compile) void {
assert(lib.kind == .lib);
self.linkLibraryOrObject(lib);
}
pub fn isDynamicLibrary(self: *Compile) bool {
return self.kind == .lib and self.linkage == Linkage.dynamic;
}
pub fn isStaticLibrary(self: *Compile) bool {
return self.kind == .lib and self.linkage != Linkage.dynamic;
}
pub fn producesPdbFile(self: *Compile) bool {
// TODO: Is this right? Isn't PDB for *any* PE/COFF file?
// TODO: just share this logic with the compiler, silly!
if (!self.target.isWindows() and !self.target.isUefi()) return false;
if (self.target.getObjectFormat() == .c) return false;
if (self.strip == true or (self.strip == null and self.optimize == .ReleaseSmall)) return false;
return self.isDynamicLibrary() or self.kind == .exe or self.kind == .@"test";
}
pub fn producesImplib(self: *Compile) bool {
return self.isDynamicLibrary() and self.target.isWindows();
}
pub fn linkLibC(self: *Compile) void {
self.is_linking_libc = true;
}
pub fn linkLibCpp(self: *Compile) void {
self.is_linking_libcpp = true;
}
/// If the value is omitted, it is set to 1.
/// `name` and `value` need not live longer than the function call.
pub fn defineCMacro(self: *Compile, name: []const u8, value: ?[]const u8) void {
const b = self.step.owner;
const macro = std.Build.constructCMacro(b.allocator, name, value);
self.c_macros.append(macro) catch @panic("OOM");
}
/// name_and_value looks like [name]=[value]. If the value is omitted, it is set to 1.
pub fn defineCMacroRaw(self: *Compile, name_and_value: []const u8) void {
const b = self.step.owner;
self.c_macros.append(b.dupe(name_and_value)) catch @panic("OOM");
}
/// deprecated: use linkSystemLibrary2
pub fn linkSystemLibraryName(self: *Compile, name: []const u8) void {
return linkSystemLibrary2(self, name, .{ .use_pkg_config = .no });
}
/// deprecated: use linkSystemLibrary2
pub fn linkSystemLibraryNeededName(self: *Compile, name: []const u8) void {
return linkSystemLibrary2(self, name, .{ .needed = true, .use_pkg_config = .no });
}
/// deprecated: use linkSystemLibrary2
pub fn linkSystemLibraryWeakName(self: *Compile, name: []const u8) void {
return linkSystemLibrary2(self, name, .{ .weak = true, .use_pkg_config = .no });
}
/// deprecated: use linkSystemLibrary2
pub fn linkSystemLibraryPkgConfigOnly(self: *Compile, lib_name: []const u8) void {
return linkSystemLibrary2(self, lib_name, .{ .use_pkg_config = .force });
}
/// deprecated: use linkSystemLibrary2
pub fn linkSystemLibraryNeededPkgConfigOnly(self: *Compile, lib_name: []const u8) void {
return linkSystemLibrary2(self, lib_name, .{ .needed = true, .use_pkg_config = .force });
}
/// Run pkg-config for the given library name and parse the output, returning the arguments
/// that should be passed to zig to link the given library.
fn runPkgConfig(self: *Compile, lib_name: []const u8) ![]const []const u8 {
const b = self.step.owner;
const pkg_name = match: {
// First we have to map the library name to pkg config name. Unfortunately,
// there are several examples where this is not straightforward:
// -lSDL2 -> pkg-config sdl2
// -lgdk-3 -> pkg-config gdk-3.0
// -latk-1.0 -> pkg-config atk
const pkgs = try getPkgConfigList(b);
// Exact match means instant winner.
for (pkgs) |pkg| {
if (mem.eql(u8, pkg.name, lib_name)) {
break :match pkg.name;
}
}
// Next we'll try ignoring case.
for (pkgs) |pkg| {
if (std.ascii.eqlIgnoreCase(pkg.name, lib_name)) {
break :match pkg.name;
}
}
// Now try appending ".0".
for (pkgs) |pkg| {
if (std.ascii.indexOfIgnoreCase(pkg.name, lib_name)) |pos| {
if (pos != 0) continue;
if (mem.eql(u8, pkg.name[lib_name.len..], ".0")) {
break :match pkg.name;
}
}
}
// Trimming "-1.0".
if (mem.endsWith(u8, lib_name, "-1.0")) {
const trimmed_lib_name = lib_name[0 .. lib_name.len - "-1.0".len];
for (pkgs) |pkg| {
if (std.ascii.eqlIgnoreCase(pkg.name, trimmed_lib_name)) {
break :match pkg.name;
}
}
}
return error.PackageNotFound;
};
var code: u8 = undefined;
const stdout = if (b.execAllowFail(&[_][]const u8{
"pkg-config",
pkg_name,
"--cflags",
"--libs",
}, &code, .Ignore)) |stdout| stdout else |err| switch (err) {
error.ProcessTerminated => return error.PkgConfigCrashed,
error.ExecNotSupported => return error.PkgConfigFailed,
error.ExitCodeFailure => return error.PkgConfigFailed,
error.FileNotFound => return error.PkgConfigNotInstalled,
else => return err,
};
var zig_args = ArrayList([]const u8).init(b.allocator);
defer zig_args.deinit();
var it = mem.tokenizeAny(u8, stdout, " \r\n\t");
while (it.next()) |tok| {
if (mem.eql(u8, tok, "-I")) {
const dir = it.next() orelse return error.PkgConfigInvalidOutput;
try zig_args.appendSlice(&[_][]const u8{ "-I", dir });
} else if (mem.startsWith(u8, tok, "-I")) {
try zig_args.append(tok);
} else if (mem.eql(u8, tok, "-L")) {
const dir = it.next() orelse return error.PkgConfigInvalidOutput;
try zig_args.appendSlice(&[_][]const u8{ "-L", dir });
} else if (mem.startsWith(u8, tok, "-L")) {
try zig_args.append(tok);
} else if (mem.eql(u8, tok, "-l")) {
const lib = it.next() orelse return error.PkgConfigInvalidOutput;
try zig_args.appendSlice(&[_][]const u8{ "-l", lib });
} else if (mem.startsWith(u8, tok, "-l")) {
try zig_args.append(tok);
} else if (mem.eql(u8, tok, "-D")) {
const macro = it.next() orelse return error.PkgConfigInvalidOutput;
try zig_args.appendSlice(&[_][]const u8{ "-D", macro });
} else if (mem.startsWith(u8, tok, "-D")) {
try zig_args.append(tok);
} else if (b.debug_pkg_config) {
return self.step.fail("unknown pkg-config flag '{s}'", .{tok});
}
}
return zig_args.toOwnedSlice();
}
pub fn linkSystemLibrary(self: *Compile, name: []const u8) void {
self.linkSystemLibrary2(name, .{});
}
/// deprecated: use linkSystemLibrary2
pub fn linkSystemLibraryNeeded(self: *Compile, name: []const u8) void {
return linkSystemLibrary2(self, name, .{ .needed = true });
}
/// deprecated: use linkSystemLibrary2
pub fn linkSystemLibraryWeak(self: *Compile, name: []const u8) void {
return linkSystemLibrary2(self, name, .{ .weak = true });
}
pub const LinkSystemLibraryOptions = struct {
needed: bool = false,
weak: bool = false,
use_pkg_config: SystemLib.UsePkgConfig = .yes,
preferred_link_mode: std.builtin.LinkMode = .Dynamic,
search_strategy: SystemLib.SearchStrategy = .paths_first,
};
pub fn linkSystemLibrary2(
self: *Compile,
name: []const u8,
options: LinkSystemLibraryOptions,
) void {
const b = self.step.owner;
if (isLibCLibrary(name)) {
self.linkLibC();
return;
}
if (isLibCppLibrary(name)) {
self.linkLibCpp();
return;
}
self.link_objects.append(.{
.system_lib = .{
.name = b.dupe(name),
.needed = options.needed,
.weak = options.weak,
.use_pkg_config = options.use_pkg_config,
.preferred_link_mode = options.preferred_link_mode,
.search_strategy = options.search_strategy,
},
}) catch @panic("OOM");
}
/// Handy when you have many C/C++ source files and want them all to have the same flags.
pub fn addCSourceFiles(self: *Compile, files: []const []const u8, flags: []const []const u8) void {
const b = self.step.owner;
const c_source_files = b.allocator.create(CSourceFiles) catch @panic("OOM");
const files_copy = b.dupeStrings(files);
const flags_copy = b.dupeStrings(flags);
c_source_files.* = .{
.files = files_copy,
.flags = flags_copy,
};
self.link_objects.append(.{ .c_source_files = c_source_files }) catch @panic("OOM");
}
pub fn addCSourceFile(self: *Compile, source: CSourceFile) void {
const b = self.step.owner;
const c_source_file = b.allocator.create(CSourceFile) catch @panic("OOM");
c_source_file.* = source.dupe(b);
self.link_objects.append(.{ .c_source_file = c_source_file }) catch @panic("OOM");
source.file.addStepDependencies(&self.step);
}
pub fn setVerboseLink(self: *Compile, value: bool) void {
self.verbose_link = value;
}
pub fn setVerboseCC(self: *Compile, value: bool) void {
self.verbose_cc = value;
}
pub fn setLibCFile(self: *Compile, libc_file: ?LazyPath) void {
const b = self.step.owner;
self.libc_file = if (libc_file) |f| f.dupe(b) else null;
}
fn getEmittedFileGeneric(self: *Compile, output_file: *?*GeneratedFile) LazyPath {
if (output_file.*) |g| {
return .{ .generated = g };
}
const arena = self.step.owner.allocator;
const generated_file = arena.create(GeneratedFile) catch @panic("OOM");
generated_file.* = .{ .step = &self.step };
output_file.* = generated_file;
return .{ .generated = generated_file };
}
/// deprecated: use `getEmittedBinDirectory`
pub const getOutputDirectorySource = getEmittedBinDirectory;
/// Returns the path to the directory that contains the emitted binary file.
pub fn getEmittedBinDirectory(self: *Compile) LazyPath {
_ = self.getEmittedBin();
return self.getEmittedFileGeneric(&self.emit_directory);
}
/// deprecated: use `getEmittedBin`
pub const getOutputSource = getEmittedBin;
/// Returns the path to the generated executable, library or object file.
/// To run an executable built with zig build, use `run`, or create an install step and invoke it.
pub fn getEmittedBin(self: *Compile) LazyPath {
return self.getEmittedFileGeneric(&self.generated_bin);
}
/// deprecated: use `getEmittedImplib`
pub const getOutputLibSource = getEmittedImplib;
/// Returns the path to the generated import library.
/// This function can only be called for libraries.
pub fn getEmittedImplib(self: *Compile) LazyPath {
assert(self.kind == .lib);
return self.getEmittedFileGeneric(&self.generated_implib);
}
/// deprecated: use `getEmittedH`
pub const getOutputHSource = getEmittedH;
/// Returns the path to the generated header file.
/// This function can only be called for libraries or objects.
pub fn getEmittedH(self: *Compile) LazyPath {
assert(self.kind != .exe and self.kind != .@"test");
return self.getEmittedFileGeneric(&self.generated_h);
}
/// deprecated: use `getEmittedPdb`.
pub const getOutputPdbSource = getEmittedPdb;
/// Returns the generated PDB file.
/// If the compilation does not produce a PDB file, this causes a FileNotFound error
/// at build time.
pub fn getEmittedPdb(self: *Compile) LazyPath {
_ = self.getEmittedBin();
return self.getEmittedFileGeneric(&self.generated_pdb);
}
/// Returns the path to the generated documentation directory.
pub fn getEmittedDocs(self: *Compile) LazyPath {
return self.getEmittedFileGeneric(&self.generated_docs);
}
/// Returns the path to the generated assembly code.
pub fn getEmittedAsm(self: *Compile) LazyPath {
return self.getEmittedFileGeneric(&self.generated_asm);
}
/// Returns the path to the generated LLVM IR.
pub fn getEmittedLlvmIr(self: *Compile) LazyPath {
return self.getEmittedFileGeneric(&self.generated_llvm_ir);
}