-
-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathlink.zig
2445 lines (2215 loc) · 94.5 KB
/
link.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 build_options = @import("build_options");
const builtin = @import("builtin");
const assert = std.debug.assert;
const fs = std.fs;
const mem = std.mem;
const log = std.log.scoped(.link);
const trace = @import("tracy.zig").trace;
const wasi_libc = @import("wasi_libc.zig");
const Air = @import("Air.zig");
const Allocator = std.mem.Allocator;
const Cache = std.Build.Cache;
const Path = std.Build.Cache.Path;
const Directory = std.Build.Cache.Directory;
const Compilation = @import("Compilation.zig");
const LibCInstallation = std.zig.LibCInstallation;
const Liveness = @import("Liveness.zig");
const Zcu = @import("Zcu.zig");
const InternPool = @import("InternPool.zig");
const Type = @import("Type.zig");
const Value = @import("Value.zig");
const LlvmObject = @import("codegen/llvm.zig").Object;
const lldMain = @import("main.zig").lldMain;
const Package = @import("Package.zig");
const dev = @import("dev.zig");
const ThreadSafeQueue = @import("ThreadSafeQueue.zig").ThreadSafeQueue;
const target_util = @import("target.zig");
const codegen = @import("codegen.zig");
pub const LdScript = @import("link/LdScript.zig");
pub const Diags = struct {
/// Stored here so that function definitions can distinguish between
/// needing an allocator for things besides error reporting.
gpa: Allocator,
mutex: std.Thread.Mutex,
msgs: std.ArrayListUnmanaged(Msg),
flags: Flags,
lld: std.ArrayListUnmanaged(Lld),
pub const SourceLocation = union(enum) {
none,
wasm: File.Wasm.SourceLocation,
};
pub const Flags = packed struct {
no_entry_point_found: bool = false,
missing_libc: bool = false,
alloc_failure_occurred: bool = false,
const Int = blk: {
const bits = @typeInfo(@This()).@"struct".fields.len;
break :blk @Type(.{ .int = .{
.signedness = .unsigned,
.bits = bits,
} });
};
pub fn anySet(ef: Flags) bool {
return @as(Int, @bitCast(ef)) > 0;
}
};
pub const Lld = struct {
/// Allocated with gpa.
msg: []const u8,
context_lines: []const []const u8 = &.{},
pub fn deinit(self: *Lld, gpa: Allocator) void {
for (self.context_lines) |line| gpa.free(line);
gpa.free(self.context_lines);
gpa.free(self.msg);
self.* = undefined;
}
};
pub const Msg = struct {
source_location: SourceLocation = .none,
msg: []const u8,
notes: []Msg = &.{},
fn string(
msg: *const Msg,
bundle: *std.zig.ErrorBundle.Wip,
base: ?*File,
) Allocator.Error!std.zig.ErrorBundle.String {
return switch (msg.source_location) {
.none => try bundle.addString(msg.msg),
.wasm => |sl| {
dev.check(.wasm_linker);
const wasm = base.?.cast(.wasm).?;
return sl.string(msg.msg, bundle, wasm);
},
};
}
pub fn deinit(self: *Msg, gpa: Allocator) void {
for (self.notes) |*note| note.deinit(gpa);
gpa.free(self.notes);
gpa.free(self.msg);
}
};
pub const ErrorWithNotes = struct {
diags: *Diags,
/// Allocated index in diags.msgs array.
index: usize,
/// Next available note slot.
note_slot: usize = 0,
pub fn addMsg(
err: ErrorWithNotes,
comptime format: []const u8,
args: anytype,
) error{OutOfMemory}!void {
const gpa = err.diags.gpa;
const err_msg = &err.diags.msgs.items[err.index];
err_msg.msg = try std.fmt.allocPrint(gpa, format, args);
}
pub fn addNote(err: *ErrorWithNotes, comptime format: []const u8, args: anytype) void {
const gpa = err.diags.gpa;
const msg = std.fmt.allocPrint(gpa, format, args) catch return err.diags.setAllocFailure();
const err_msg = &err.diags.msgs.items[err.index];
assert(err.note_slot < err_msg.notes.len);
err_msg.notes[err.note_slot] = .{ .msg = msg };
err.note_slot += 1;
}
};
pub fn init(gpa: Allocator) Diags {
return .{
.gpa = gpa,
.mutex = .{},
.msgs = .empty,
.flags = .{},
.lld = .empty,
};
}
pub fn deinit(diags: *Diags) void {
const gpa = diags.gpa;
for (diags.msgs.items) |*item| item.deinit(gpa);
diags.msgs.deinit(gpa);
for (diags.lld.items) |*item| item.deinit(gpa);
diags.lld.deinit(gpa);
diags.* = undefined;
}
pub fn hasErrors(diags: *Diags) bool {
return diags.msgs.items.len > 0 or diags.flags.anySet();
}
pub fn lockAndParseLldStderr(diags: *Diags, prefix: []const u8, stderr: []const u8) void {
diags.mutex.lock();
defer diags.mutex.unlock();
diags.parseLldStderr(prefix, stderr) catch diags.setAllocFailure();
}
fn parseLldStderr(
diags: *Diags,
prefix: []const u8,
stderr: []const u8,
) Allocator.Error!void {
const gpa = diags.gpa;
var context_lines = std.ArrayList([]const u8).init(gpa);
defer context_lines.deinit();
var current_err: ?*Lld = null;
var lines = mem.splitSequence(u8, stderr, if (builtin.os.tag == .windows) "\r\n" else "\n");
while (lines.next()) |line| {
if (line.len > prefix.len + ":".len and
mem.eql(u8, line[0..prefix.len], prefix) and line[prefix.len] == ':')
{
if (current_err) |err| {
err.context_lines = try context_lines.toOwnedSlice();
}
var split = mem.splitSequence(u8, line, "error: ");
_ = split.first();
const duped_msg = try std.fmt.allocPrint(gpa, "{s}: {s}", .{ prefix, split.rest() });
errdefer gpa.free(duped_msg);
current_err = try diags.lld.addOne(gpa);
current_err.?.* = .{ .msg = duped_msg };
} else if (current_err != null) {
const context_prefix = ">>> ";
var trimmed = mem.trimRight(u8, line, &std.ascii.whitespace);
if (mem.startsWith(u8, trimmed, context_prefix)) {
trimmed = trimmed[context_prefix.len..];
}
if (trimmed.len > 0) {
const duped_line = try gpa.dupe(u8, trimmed);
try context_lines.append(duped_line);
}
}
}
if (current_err) |err| {
err.context_lines = try context_lines.toOwnedSlice();
}
}
pub fn fail(diags: *Diags, comptime format: []const u8, args: anytype) error{LinkFailure} {
@branchHint(.cold);
addError(diags, format, args);
return error.LinkFailure;
}
pub fn failSourceLocation(diags: *Diags, sl: SourceLocation, comptime format: []const u8, args: anytype) error{LinkFailure} {
@branchHint(.cold);
addErrorSourceLocation(diags, sl, format, args);
return error.LinkFailure;
}
pub fn addError(diags: *Diags, comptime format: []const u8, args: anytype) void {
return addErrorSourceLocation(diags, .none, format, args);
}
pub fn addErrorSourceLocation(diags: *Diags, sl: SourceLocation, comptime format: []const u8, args: anytype) void {
@branchHint(.cold);
const gpa = diags.gpa;
const eu_main_msg = std.fmt.allocPrint(gpa, format, args);
diags.mutex.lock();
defer diags.mutex.unlock();
addErrorLockedFallible(diags, sl, eu_main_msg) catch |err| switch (err) {
error.OutOfMemory => diags.setAllocFailureLocked(),
};
}
fn addErrorLockedFallible(diags: *Diags, sl: SourceLocation, eu_main_msg: Allocator.Error![]u8) Allocator.Error!void {
const gpa = diags.gpa;
const main_msg = try eu_main_msg;
errdefer gpa.free(main_msg);
try diags.msgs.append(gpa, .{
.msg = main_msg,
.source_location = sl,
});
}
pub fn addErrorWithNotes(diags: *Diags, note_count: usize) error{OutOfMemory}!ErrorWithNotes {
@branchHint(.cold);
const gpa = diags.gpa;
diags.mutex.lock();
defer diags.mutex.unlock();
try diags.msgs.ensureUnusedCapacity(gpa, 1);
return addErrorWithNotesAssumeCapacity(diags, note_count);
}
pub fn addErrorWithNotesAssumeCapacity(diags: *Diags, note_count: usize) error{OutOfMemory}!ErrorWithNotes {
@branchHint(.cold);
const gpa = diags.gpa;
const index = diags.msgs.items.len;
const err = diags.msgs.addOneAssumeCapacity();
err.* = .{
.msg = undefined,
.notes = try gpa.alloc(Msg, note_count),
};
return .{
.diags = diags,
.index = index,
};
}
pub fn addMissingLibraryError(
diags: *Diags,
checked_paths: []const []const u8,
comptime format: []const u8,
args: anytype,
) void {
@branchHint(.cold);
const gpa = diags.gpa;
const eu_main_msg = std.fmt.allocPrint(gpa, format, args);
diags.mutex.lock();
defer diags.mutex.unlock();
addMissingLibraryErrorLockedFallible(diags, checked_paths, eu_main_msg) catch |err| switch (err) {
error.OutOfMemory => diags.setAllocFailureLocked(),
};
}
fn addMissingLibraryErrorLockedFallible(
diags: *Diags,
checked_paths: []const []const u8,
eu_main_msg: Allocator.Error![]u8,
) Allocator.Error!void {
const gpa = diags.gpa;
const main_msg = try eu_main_msg;
errdefer gpa.free(main_msg);
try diags.msgs.ensureUnusedCapacity(gpa, 1);
const notes = try gpa.alloc(Msg, checked_paths.len);
errdefer gpa.free(notes);
for (checked_paths, notes) |path, *note| {
note.* = .{ .msg = try std.fmt.allocPrint(gpa, "tried {s}", .{path}) };
}
diags.msgs.appendAssumeCapacity(.{
.msg = main_msg,
.notes = notes,
});
}
pub fn addParseError(
diags: *Diags,
path: Path,
comptime format: []const u8,
args: anytype,
) void {
@branchHint(.cold);
const gpa = diags.gpa;
const eu_main_msg = std.fmt.allocPrint(gpa, format, args);
diags.mutex.lock();
defer diags.mutex.unlock();
addParseErrorLockedFallible(diags, path, eu_main_msg) catch |err| switch (err) {
error.OutOfMemory => diags.setAllocFailureLocked(),
};
}
fn addParseErrorLockedFallible(diags: *Diags, path: Path, m: Allocator.Error![]u8) Allocator.Error!void {
const gpa = diags.gpa;
const main_msg = try m;
errdefer gpa.free(main_msg);
try diags.msgs.ensureUnusedCapacity(gpa, 1);
const note = try std.fmt.allocPrint(gpa, "while parsing {}", .{path});
errdefer gpa.free(note);
const notes = try gpa.create([1]Msg);
errdefer gpa.destroy(notes);
notes.* = .{.{ .msg = note }};
diags.msgs.appendAssumeCapacity(.{
.msg = main_msg,
.notes = notes,
});
}
pub fn failParse(
diags: *Diags,
path: Path,
comptime format: []const u8,
args: anytype,
) error{LinkFailure} {
@branchHint(.cold);
addParseError(diags, path, format, args);
return error.LinkFailure;
}
pub fn setAllocFailure(diags: *Diags) void {
@branchHint(.cold);
diags.mutex.lock();
defer diags.mutex.unlock();
setAllocFailureLocked(diags);
}
fn setAllocFailureLocked(diags: *Diags) void {
log.debug("memory allocation failure", .{});
diags.flags.alloc_failure_occurred = true;
}
pub fn addMessagesToBundle(diags: *const Diags, bundle: *std.zig.ErrorBundle.Wip, base: ?*File) Allocator.Error!void {
for (diags.msgs.items) |link_err| {
try bundle.addRootErrorMessage(.{
.msg = try link_err.string(bundle, base),
.notes_len = @intCast(link_err.notes.len),
});
const notes_start = try bundle.reserveNotes(@intCast(link_err.notes.len));
for (link_err.notes, 0..) |note, i| {
bundle.extra.items[notes_start + i] = @intFromEnum(try bundle.addErrorMessage(.{
.msg = try note.string(bundle, base),
}));
}
}
}
};
pub const producer_string = if (builtin.is_test) "zig test" else "zig " ++ build_options.version;
pub const File = struct {
tag: Tag,
/// The owner of this output File.
comp: *Compilation,
emit: Path,
file: ?fs.File,
/// When linking with LLD, this linker code will output an object file only at
/// this location, and then this path can be placed on the LLD linker line.
zcu_object_sub_path: ?[]const u8 = null,
disable_lld_caching: bool,
gc_sections: bool,
print_gc_sections: bool,
build_id: std.zig.BuildId,
allow_shlib_undefined: bool,
stack_size: u64,
post_prelink: bool = false,
/// Prevents other processes from clobbering files in the output directory
/// of this linking operation.
lock: ?Cache.Lock = null,
child_pid: ?std.process.Child.Id = null,
pub const OpenOptions = struct {
symbol_count_hint: u64 = 32,
program_code_size_hint: u64 = 256 * 1024,
/// This may depend on what symbols are found during the linking process.
entry: Entry,
/// Virtual address of the entry point procedure relative to image base.
entry_addr: ?u64,
stack_size: ?u64,
image_base: ?u64,
emit_relocs: bool,
z_nodelete: bool,
z_notext: bool,
z_defs: bool,
z_origin: bool,
z_nocopyreloc: bool,
z_now: bool,
z_relro: bool,
z_common_page_size: ?u64,
z_max_page_size: ?u64,
tsaware: bool,
nxcompat: bool,
dynamicbase: bool,
compress_debug_sections: Elf.CompressDebugSections,
bind_global_refs_locally: bool,
import_symbols: bool,
import_table: bool,
export_table: bool,
initial_memory: ?u64,
max_memory: ?u64,
object_host_name: ?[]const u8,
export_symbol_names: []const []const u8,
global_base: ?u64,
build_id: std.zig.BuildId,
disable_lld_caching: bool,
hash_style: Elf.HashStyle,
sort_section: ?Elf.SortSection,
major_subsystem_version: ?u16,
minor_subsystem_version: ?u16,
gc_sections: ?bool,
repro: bool,
allow_shlib_undefined: ?bool,
allow_undefined_version: bool,
enable_new_dtags: ?bool,
subsystem: ?std.Target.SubSystem,
linker_script: ?[]const u8,
version_script: ?[]const u8,
soname: ?[]const u8,
print_gc_sections: bool,
print_icf_sections: bool,
print_map: bool,
/// Use a wrapper function for symbol. Any undefined reference to symbol
/// will be resolved to __wrap_symbol. Any undefined reference to
/// __real_symbol will be resolved to symbol. This can be used to provide a
/// wrapper for a system function. The wrapper function should be called
/// __wrap_symbol. If it wishes to call the system function, it should call
/// __real_symbol.
symbol_wrap_set: std.StringArrayHashMapUnmanaged(void),
compatibility_version: ?std.SemanticVersion,
// TODO: remove this. libraries are resolved by the frontend.
lib_directories: []const Directory,
framework_dirs: []const []const u8,
rpath_list: []const []const u8,
/// Zig compiler development linker flags.
/// Enable dumping of linker's state as JSON.
enable_link_snapshots: bool,
/// Darwin-specific linker flags:
/// Install name for the dylib
install_name: ?[]const u8,
/// Path to entitlements file
entitlements: ?[]const u8,
/// size of the __PAGEZERO segment
pagezero_size: ?u64,
/// Set minimum space for future expansion of the load commands
headerpad_size: ?u32,
/// Set enough space as if all paths were MATPATHLEN
headerpad_max_install_names: bool,
/// Remove dylibs that are unreachable by the entry point or exported symbols
dead_strip_dylibs: bool,
frameworks: []const MachO.Framework,
darwin_sdk_layout: ?MachO.SdkLayout,
/// Force load all members of static archives that implement an
/// Objective-C class or category
force_load_objc: bool,
/// Whether local symbols should be discarded from the symbol table.
discard_local_symbols: bool,
/// Windows-specific linker flags:
/// PDB source path prefix to instruct the linker how to resolve relative
/// paths when consolidating CodeView streams into a single PDB file.
pdb_source_path: ?[]const u8,
/// PDB output path
pdb_out_path: ?[]const u8,
/// .def file to specify when linking
module_definition_file: ?[]const u8,
pub const Entry = union(enum) {
default,
disabled,
enabled,
named: []const u8,
};
};
/// Attempts incremental linking, if the file already exists. If
/// incremental linking fails, falls back to truncating the file and
/// rewriting it. A malicious file is detected as incremental link failure
/// and does not cause Illegal Behavior. This operation is not atomic.
/// `arena` is used for allocations with the same lifetime as the created File.
pub fn open(
arena: Allocator,
comp: *Compilation,
emit: Path,
options: OpenOptions,
) !*File {
switch (Tag.fromObjectFormat(comp.root_mod.resolved_target.result.ofmt)) {
inline else => |tag| {
dev.check(tag.devFeature());
const ptr = try tag.Type().open(arena, comp, emit, options);
return &ptr.base;
},
}
}
pub fn createEmpty(
arena: Allocator,
comp: *Compilation,
emit: Path,
options: OpenOptions,
) !*File {
switch (Tag.fromObjectFormat(comp.root_mod.resolved_target.result.ofmt)) {
inline else => |tag| {
dev.check(tag.devFeature());
const ptr = try tag.Type().createEmpty(arena, comp, emit, options);
return &ptr.base;
},
}
}
pub fn cast(base: *File, comptime tag: Tag) if (dev.env.supports(tag.devFeature())) ?*tag.Type() else ?noreturn {
return if (dev.env.supports(tag.devFeature()) and base.tag == tag) @fieldParentPtr("base", base) else null;
}
pub fn makeWritable(base: *File) !void {
dev.check(.make_writable);
const comp = base.comp;
const gpa = comp.gpa;
switch (base.tag) {
.coff, .elf, .macho, .plan9, .wasm => {
if (base.file != null) return;
dev.checkAny(&.{ .coff_linker, .elf_linker, .macho_linker, .plan9_linker, .wasm_linker });
const emit = base.emit;
if (base.child_pid) |pid| {
if (builtin.os.tag == .windows) {
base.cast(.coff).?.ptraceAttach(pid) catch |err| {
log.warn("attaching failed with error: {s}", .{@errorName(err)});
};
} else {
// If we try to open the output file in write mode while it is running,
// it will return ETXTBSY. So instead, we copy the file, atomically rename it
// over top of the exe path, and then proceed normally. This changes the inode,
// avoiding the error.
const tmp_sub_path = try std.fmt.allocPrint(gpa, "{s}-{x}", .{
emit.sub_path, std.crypto.random.int(u32),
});
defer gpa.free(tmp_sub_path);
try emit.root_dir.handle.copyFile(emit.sub_path, emit.root_dir.handle, tmp_sub_path, .{});
try emit.root_dir.handle.rename(tmp_sub_path, emit.sub_path);
switch (builtin.os.tag) {
.linux => std.posix.ptrace(std.os.linux.PTRACE.ATTACH, pid, 0, 0) catch |err| {
log.warn("ptrace failure: {s}", .{@errorName(err)});
},
.macos => base.cast(.macho).?.ptraceAttach(pid) catch |err| {
log.warn("attaching failed with error: {s}", .{@errorName(err)});
},
.windows => unreachable,
else => return error.HotSwapUnavailableOnHostOperatingSystem,
}
}
}
const use_lld = build_options.have_llvm and comp.config.use_lld;
const output_mode = comp.config.output_mode;
const link_mode = comp.config.link_mode;
base.file = try emit.root_dir.handle.createFile(emit.sub_path, .{
.truncate = false,
.read = true,
.mode = determineMode(use_lld, output_mode, link_mode),
});
},
.c, .spirv, .nvptx => dev.checkAny(&.{ .c_linker, .spirv_linker, .nvptx_linker }),
}
}
/// Some linkers create a separate file for debug info, which we might need to temporarily close
/// when moving the compilation result directory due to the host OS not allowing moving a
/// file/directory while a handle remains open.
/// Returns `true` if a debug info file was closed. In that case, `reopenDebugInfo` may be called.
pub fn closeDebugInfo(base: *File) bool {
const macho = base.cast(.macho) orelse return false;
return macho.closeDebugInfo();
}
pub fn reopenDebugInfo(base: *File) !void {
const macho = base.cast(.macho).?;
return macho.reopenDebugInfo();
}
pub fn makeExecutable(base: *File) !void {
dev.check(.make_executable);
const comp = base.comp;
const output_mode = comp.config.output_mode;
const link_mode = comp.config.link_mode;
const use_lld = build_options.have_llvm and comp.config.use_lld;
switch (output_mode) {
.Obj => return,
.Lib => switch (link_mode) {
.static => return,
.dynamic => {},
},
.Exe => {},
}
switch (base.tag) {
.elf => if (base.file) |f| {
dev.check(.elf_linker);
if (base.zcu_object_sub_path != null and use_lld) {
// The file we have open is not the final file that we want to
// make executable, so we don't have to close it.
return;
}
f.close();
base.file = null;
if (base.child_pid) |pid| {
switch (builtin.os.tag) {
.linux => std.posix.ptrace(std.os.linux.PTRACE.DETACH, pid, 0, 0) catch |err| {
log.warn("ptrace failure: {s}", .{@errorName(err)});
},
else => return error.HotSwapUnavailableOnHostOperatingSystem,
}
}
},
.coff, .macho, .plan9, .wasm => if (base.file) |f| {
dev.checkAny(&.{ .coff_linker, .macho_linker, .plan9_linker, .wasm_linker });
if (base.zcu_object_sub_path != null) {
// The file we have open is not the final file that we want to
// make executable, so we don't have to close it.
return;
}
f.close();
base.file = null;
if (base.child_pid) |pid| {
switch (builtin.os.tag) {
.macos => base.cast(.macho).?.ptraceDetach(pid) catch |err| {
log.warn("detaching failed with error: {s}", .{@errorName(err)});
},
.windows => base.cast(.coff).?.ptraceDetach(pid),
else => return error.HotSwapUnavailableOnHostOperatingSystem,
}
}
},
.c, .spirv, .nvptx => dev.checkAny(&.{ .c_linker, .spirv_linker, .nvptx_linker }),
}
}
pub const DebugInfoOutput = union(enum) {
dwarf: *Dwarf.WipNav,
plan9: *Plan9.DebugInfoOutput,
none,
};
pub const UpdateDebugInfoError = Dwarf.UpdateError;
pub const FlushDebugInfoError = Dwarf.FlushError;
/// Note that `LinkFailure` is not a member of this error set because the error message
/// must be attached to `Zcu.failed_codegen` rather than `Compilation.link_diags`.
pub const UpdateNavError = codegen.CodeGenError;
/// Called from within CodeGen to retrieve the symbol index of a global symbol.
/// If no symbol exists yet with this name, a new undefined global symbol will
/// be created. This symbol may get resolved once all relocatables are (re-)linked.
/// Optionally, it is possible to specify where to expect the symbol defined if it
/// is an import.
pub fn getGlobalSymbol(base: *File, name: []const u8, lib_name: ?[]const u8) UpdateNavError!u32 {
log.debug("getGlobalSymbol '{s}' (expected in '{?s}')", .{ name, lib_name });
switch (base.tag) {
.plan9 => unreachable,
.spirv => unreachable,
.c => unreachable,
.nvptx => unreachable,
inline else => |tag| {
dev.check(tag.devFeature());
return @as(*tag.Type(), @fieldParentPtr("base", base)).getGlobalSymbol(name, lib_name);
},
}
}
/// May be called before or after updateExports for any given Nav.
pub fn updateNav(base: *File, pt: Zcu.PerThread, nav_index: InternPool.Nav.Index) UpdateNavError!void {
const nav = pt.zcu.intern_pool.getNav(nav_index);
assert(nav.status == .fully_resolved);
switch (base.tag) {
inline else => |tag| {
dev.check(tag.devFeature());
return @as(*tag.Type(), @fieldParentPtr("base", base)).updateNav(pt, nav_index);
},
}
}
pub const UpdateContainerTypeError = error{
OutOfMemory,
/// `Zcu.failed_types` is already populated with the error message.
TypeFailureReported,
};
pub fn updateContainerType(base: *File, pt: Zcu.PerThread, ty: InternPool.Index) UpdateContainerTypeError!void {
switch (base.tag) {
else => {},
inline .elf => |tag| {
dev.check(tag.devFeature());
return @as(*tag.Type(), @fieldParentPtr("base", base)).updateContainerType(pt, ty);
},
}
}
/// May be called before or after updateExports for any given Decl.
pub fn updateFunc(
base: *File,
pt: Zcu.PerThread,
func_index: InternPool.Index,
air: Air,
liveness: Liveness,
) UpdateNavError!void {
switch (base.tag) {
inline else => |tag| {
dev.check(tag.devFeature());
return @as(*tag.Type(), @fieldParentPtr("base", base)).updateFunc(pt, func_index, air, liveness);
},
}
}
pub const UpdateLineNumberError = error{
OutOfMemory,
Overflow,
LinkFailure,
};
/// On an incremental update, fixup the line number of all `Nav`s at the given `TrackedInst`, because
/// its line number has changed. The ZIR instruction `ti_id` has tag `.declaration`.
pub fn updateLineNumber(base: *File, pt: Zcu.PerThread, ti_id: InternPool.TrackedInst.Index) UpdateLineNumberError!void {
{
const ti = ti_id.resolveFull(&pt.zcu.intern_pool).?;
const file = pt.zcu.fileByIndex(ti.file);
const inst = file.zir.?.instructions.get(@intFromEnum(ti.inst));
assert(inst.tag == .declaration);
}
switch (base.tag) {
.spirv, .nvptx => {},
inline else => |tag| {
dev.check(tag.devFeature());
return @as(*tag.Type(), @fieldParentPtr("base", base)).updateLineNumber(pt, ti_id);
},
}
}
pub fn releaseLock(self: *File) void {
if (self.lock) |*lock| {
lock.release();
self.lock = null;
}
}
pub fn toOwnedLock(self: *File) Cache.Lock {
const lock = self.lock.?;
self.lock = null;
return lock;
}
pub fn destroy(base: *File) void {
base.releaseLock();
if (base.file) |f| f.close();
switch (base.tag) {
inline else => |tag| {
dev.check(tag.devFeature());
@as(*tag.Type(), @fieldParentPtr("base", base)).deinit();
},
}
}
pub const FlushError = error{
/// Indicates an error will be present in `Compilation.link_diags`.
LinkFailure,
OutOfMemory,
};
/// Commit pending changes and write headers. Takes into account final output mode
/// and `use_lld`, not only `effectiveOutputMode`.
/// `arena` has the lifetime of the call to `Compilation.update`.
pub fn flush(base: *File, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) FlushError!void {
const comp = base.comp;
if (comp.clang_preprocessor_mode == .yes or comp.clang_preprocessor_mode == .pch) {
dev.check(.clang_command);
const emit = base.emit;
// TODO: avoid extra link step when it's just 1 object file (the `zig cc -c` case)
// Until then, we do `lld -r -o output.o input.o` even though the output is the same
// as the input. For the preprocessing case (`zig cc -E -o foo`) we copy the file
// to the final location. See also the corresponding TODO in Coff linking.
assert(comp.c_object_table.count() == 1);
const the_key = comp.c_object_table.keys()[0];
const cached_pp_file_path = the_key.status.success.object_path;
cached_pp_file_path.root_dir.handle.copyFile(cached_pp_file_path.sub_path, emit.root_dir.handle, emit.sub_path, .{}) catch |err| {
const diags = &base.comp.link_diags;
return diags.fail("failed to copy '{'}' to '{'}': {s}", .{
@as(Path, cached_pp_file_path), @as(Path, emit), @errorName(err),
});
};
return;
}
assert(base.post_prelink);
const use_lld = build_options.have_llvm and comp.config.use_lld;
const output_mode = comp.config.output_mode;
const link_mode = comp.config.link_mode;
if (use_lld and output_mode == .Lib and link_mode == .static) {
return base.linkAsArchive(arena, tid, prog_node);
}
switch (base.tag) {
inline else => |tag| {
dev.check(tag.devFeature());
return @as(*tag.Type(), @fieldParentPtr("base", base)).flush(arena, tid, prog_node);
},
}
}
/// Commit pending changes and write headers. Works based on `effectiveOutputMode`
/// rather than final output mode.
pub fn flushModule(base: *File, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) FlushError!void {
switch (base.tag) {
inline else => |tag| {
dev.check(tag.devFeature());
return @as(*tag.Type(), @fieldParentPtr("base", base)).flushModule(arena, tid, prog_node);
},
}
}
pub const UpdateExportsError = error{
OutOfMemory,
AnalysisFail,
};
/// This is called for every exported thing. `exports` is almost always
/// a list of size 1, meaning that `exported` is exported once. However, it is possible
/// to export the same thing with multiple different symbol names (aliases).
/// May be called before or after updateDecl for any given Decl.
pub fn updateExports(
base: *File,
pt: Zcu.PerThread,
exported: Zcu.Exported,
export_indices: []const Zcu.Export.Index,
) UpdateExportsError!void {
switch (base.tag) {
inline else => |tag| {
dev.check(tag.devFeature());
return @as(*tag.Type(), @fieldParentPtr("base", base)).updateExports(pt, exported, export_indices);
},
}
}
pub const RelocInfo = struct {
parent: Parent,
offset: u64,
addend: u32,
pub const Parent = union(enum) {
none,
atom_index: u32,
debug_output: DebugInfoOutput,
};
};
/// Get allocated `Nav`'s address in virtual memory.
/// The linker is passed information about the containing atom, `parent_atom_index`, and offset within it's
/// memory buffer, `offset`, so that it can make a note of potential relocation sites, should the
/// `Nav`'s address was not yet resolved, or the containing atom gets moved in virtual memory.
/// May be called before or after updateFunc/updateNav therefore it is up to the linker to allocate
/// the block/atom.
pub fn getNavVAddr(base: *File, pt: Zcu.PerThread, nav_index: InternPool.Nav.Index, reloc_info: RelocInfo) !u64 {
switch (base.tag) {
.c => unreachable,
.spirv => unreachable,
.nvptx => unreachable,
.wasm => unreachable,
inline else => |tag| {
dev.check(tag.devFeature());
return @as(*tag.Type(), @fieldParentPtr("base", base)).getNavVAddr(pt, nav_index, reloc_info);
},
}
}
pub fn lowerUav(
base: *File,
pt: Zcu.PerThread,
decl_val: InternPool.Index,
decl_align: InternPool.Alignment,
src_loc: Zcu.LazySrcLoc,
) !codegen.GenResult {
switch (base.tag) {
.c => unreachable,
.spirv => unreachable,
.nvptx => unreachable,
.wasm => unreachable,
inline else => |tag| {
dev.check(tag.devFeature());
return @as(*tag.Type(), @fieldParentPtr("base", base)).lowerUav(pt, decl_val, decl_align, src_loc);
},
}
}
pub fn getUavVAddr(base: *File, decl_val: InternPool.Index, reloc_info: RelocInfo) !u64 {
switch (base.tag) {
.c => unreachable,
.spirv => unreachable,
.nvptx => unreachable,
.wasm => unreachable,
inline else => |tag| {
dev.check(tag.devFeature());
return @as(*tag.Type(), @fieldParentPtr("base", base)).getUavVAddr(decl_val, reloc_info);
},
}
}
pub fn deleteExport(
base: *File,
exported: Zcu.Exported,
name: InternPool.NullTerminatedString,
) void {
switch (base.tag) {
.plan9,
.spirv,
.nvptx,
=> {},
inline else => |tag| {
dev.check(tag.devFeature());
return @as(*tag.Type(), @fieldParentPtr("base", base)).deleteExport(exported, name);
},
}
}
/// Opens a path as an object file and parses it into the linker.
fn openLoadObject(base: *File, path: Path) anyerror!void {
const diags = &base.comp.link_diags;
const input = try openObjectInput(diags, path);
errdefer input.object.file.close();
try loadInput(base, input);
}
/// Opens a path as a static library and parses it into the linker.
/// If `query` is non-null, allows GNU ld scripts.
fn openLoadArchive(base: *File, path: Path, opt_query: ?UnresolvedInput.Query) anyerror!void {
if (opt_query) |query| {
const archive = try openObject(path, query.must_link, query.hidden);
errdefer archive.file.close();
loadInput(base, .{ .archive = archive }) catch |err| switch (err) {
error.BadMagic, error.UnexpectedEndOfFile => {
if (base.tag != .elf) return err;
try loadGnuLdScript(base, path, query, archive.file);
archive.file.close();
return;
},
else => return err,
};
} else {
const archive = try openObject(path, false, false);
errdefer archive.file.close();
try loadInput(base, .{ .archive = archive });
}
}
/// Opens a path as a shared library and parses it into the linker.
/// Handles GNU ld scripts.
fn openLoadDso(base: *File, path: Path, query: UnresolvedInput.Query) anyerror!void {
const dso = try openDso(path, query.needed, query.weak, query.reexport);
errdefer dso.file.close();
loadInput(base, .{ .dso = dso }) catch |err| switch (err) {
error.BadMagic, error.UnexpectedEndOfFile => {
if (base.tag != .elf) return err;
try loadGnuLdScript(base, path, query, dso.file);