-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Elf.zig
6266 lines (5515 loc) · 226 KB
/
Elf.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
base: link.File,
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,
/// TODO make this non optional and resolve the default in open()
z_common_page_size: ?u64,
/// TODO make this non optional and resolve the default in open()
z_max_page_size: ?u64,
lib_dirs: []const []const u8,
hash_style: HashStyle,
compress_debug_sections: CompressDebugSections,
symbol_wrap_set: std.StringArrayHashMapUnmanaged(void),
sort_section: ?SortSection,
soname: ?[]const u8,
bind_global_refs_locally: bool,
linker_script: ?[]const u8,
version_script: ?[]const u8,
allow_undefined_version: bool,
enable_new_dtags: ?bool,
print_icf_sections: bool,
print_map: bool,
entry_name: ?[]const u8,
ptr_width: PtrWidth,
/// If this is not null, an object file is created by LLVM and emitted to zcu_object_sub_path.
llvm_object: ?*LlvmObject = null,
/// A list of all input files.
/// Index of each input file also encodes the priority or precedence of one input file
/// over another.
files: std.MultiArrayList(File.Entry) = .{},
/// Long-lived list of all file descriptors.
/// We store them globally rather than per actual File so that we can re-use
/// one file handle per every object file within an archive.
file_handles: std.ArrayListUnmanaged(File.Handle) = .{},
zig_object_index: ?File.Index = null,
linker_defined_index: ?File.Index = null,
objects: std.ArrayListUnmanaged(File.Index) = .{},
shared_objects: std.ArrayListUnmanaged(File.Index) = .{},
/// Stored in native-endian format, depending on target endianness needs to be bswapped on read/write.
/// Same order as in the file.
shdrs: std.ArrayListUnmanaged(elf.Elf64_Shdr) = .{},
/// Given index to a section, pulls index of containing phdr if any.
phdr_to_shdr_table: std.AutoHashMapUnmanaged(u32, u32) = .{},
/// File offset into the shdr table.
shdr_table_offset: ?u64 = null,
/// Table of lists of atoms per output section.
/// This table is not used to track incrementally generated atoms.
output_sections: std.AutoArrayHashMapUnmanaged(u32, std.ArrayListUnmanaged(Atom.Index)) = .{},
output_rela_sections: std.AutoArrayHashMapUnmanaged(u32, RelaSection) = .{},
/// Stored in native-endian format, depending on target endianness needs to be bswapped on read/write.
/// Same order as in the file.
phdrs: std.ArrayListUnmanaged(elf.Elf64_Phdr) = .{},
/// Tracked loadable segments during incremental linking.
/// The index into the program headers of a PT_LOAD program header with Read and Execute flags
phdr_zig_load_re_index: ?u16 = null,
/// The index into the program headers of the global offset table.
/// It needs PT_LOAD and Read flags.
phdr_zig_got_index: ?u16 = null,
/// The index into the program headers of a PT_LOAD program header with Read flag
phdr_zig_load_ro_index: ?u16 = null,
/// The index into the program headers of a PT_LOAD program header with Write flag
phdr_zig_load_rw_index: ?u16 = null,
/// The index into the program headers of a PT_LOAD program header with zerofill data.
phdr_zig_load_zerofill_index: ?u16 = null,
/// Special program headers
/// PT_PHDR
phdr_table_index: ?u16 = null,
/// PT_LOAD for PHDR table
/// We add this special load segment to ensure the EHDR and PHDR table are always
/// loaded into memory.
phdr_table_load_index: ?u16 = null,
/// PT_INTERP
phdr_interp_index: ?u16 = null,
/// PT_DYNAMIC
phdr_dynamic_index: ?u16 = null,
/// PT_GNU_EH_FRAME
phdr_gnu_eh_frame_index: ?u16 = null,
/// PT_GNU_STACK
phdr_gnu_stack_index: ?u16 = null,
/// PT_TLS
/// TODO I think ELF permits multiple TLS segments but for now, assume one per file.
phdr_tls_index: ?u16 = null,
entry_index: ?Symbol.Index = null,
page_size: u32,
default_sym_version: elf.Elf64_Versym,
/// .shstrtab buffer
shstrtab: std.ArrayListUnmanaged(u8) = .{},
/// .symtab buffer
symtab: std.ArrayListUnmanaged(elf.Elf64_Sym) = .{},
/// .strtab buffer
strtab: std.ArrayListUnmanaged(u8) = .{},
/// Dynamic symbol table. Only populated and emitted when linking dynamically.
dynsym: DynsymSection = .{},
/// .dynstrtab buffer
dynstrtab: std.ArrayListUnmanaged(u8) = .{},
/// Version symbol table. Only populated and emitted when linking dynamically.
versym: std.ArrayListUnmanaged(elf.Elf64_Versym) = .{},
/// .verneed section
verneed: VerneedSection = .{},
/// .got section
got: GotSection = .{},
/// .rela.dyn section
rela_dyn: std.ArrayListUnmanaged(elf.Elf64_Rela) = .{},
/// .dynamic section
dynamic: DynamicSection = .{},
/// .hash section
hash: HashSection = .{},
/// .gnu.hash section
gnu_hash: GnuHashSection = .{},
/// .plt section
plt: PltSection = .{},
/// .got.plt section
got_plt: GotPltSection = .{},
/// .plt.got section
plt_got: PltGotSection = .{},
/// .copyrel section
copy_rel: CopyRelSection = .{},
/// .rela.plt section
rela_plt: std.ArrayListUnmanaged(elf.Elf64_Rela) = .{},
/// .got.zig section
zig_got: ZigGotSection = .{},
/// SHT_GROUP sections
/// Applies only to a relocatable.
comdat_group_sections: std.ArrayListUnmanaged(ComdatGroupSection) = .{},
/// Tracked section headers with incremental updates to Zig object.
/// .rela.* sections are only used when emitting a relocatable object file.
zig_text_section_index: ?u32 = null,
zig_data_rel_ro_section_index: ?u32 = null,
zig_data_section_index: ?u32 = null,
zig_bss_section_index: ?u32 = null,
zig_got_section_index: ?u32 = null,
debug_info_section_index: ?u32 = null,
debug_abbrev_section_index: ?u32 = null,
debug_str_section_index: ?u32 = null,
debug_aranges_section_index: ?u32 = null,
debug_line_section_index: ?u32 = null,
copy_rel_section_index: ?u32 = null,
dynamic_section_index: ?u32 = null,
dynstrtab_section_index: ?u32 = null,
dynsymtab_section_index: ?u32 = null,
eh_frame_section_index: ?u32 = null,
eh_frame_rela_section_index: ?u32 = null,
eh_frame_hdr_section_index: ?u32 = null,
hash_section_index: ?u32 = null,
gnu_hash_section_index: ?u32 = null,
got_section_index: ?u32 = null,
got_plt_section_index: ?u32 = null,
interp_section_index: ?u32 = null,
plt_section_index: ?u32 = null,
plt_got_section_index: ?u32 = null,
rela_dyn_section_index: ?u32 = null,
rela_plt_section_index: ?u32 = null,
versym_section_index: ?u32 = null,
verneed_section_index: ?u32 = null,
shstrtab_section_index: ?u32 = null,
strtab_section_index: ?u32 = null,
symtab_section_index: ?u32 = null,
// Linker-defined symbols
dynamic_index: ?Symbol.Index = null,
ehdr_start_index: ?Symbol.Index = null,
init_array_start_index: ?Symbol.Index = null,
init_array_end_index: ?Symbol.Index = null,
fini_array_start_index: ?Symbol.Index = null,
fini_array_end_index: ?Symbol.Index = null,
preinit_array_start_index: ?Symbol.Index = null,
preinit_array_end_index: ?Symbol.Index = null,
got_index: ?Symbol.Index = null,
plt_index: ?Symbol.Index = null,
end_index: ?Symbol.Index = null,
gnu_eh_frame_hdr_index: ?Symbol.Index = null,
dso_handle_index: ?Symbol.Index = null,
rela_iplt_start_index: ?Symbol.Index = null,
rela_iplt_end_index: ?Symbol.Index = null,
global_pointer_index: ?Symbol.Index = null,
start_stop_indexes: std.ArrayListUnmanaged(u32) = .{},
/// An array of symbols parsed across all input files.
symbols: std.ArrayListUnmanaged(Symbol) = .{},
symbols_extra: std.ArrayListUnmanaged(u32) = .{},
symbols_free_list: std.ArrayListUnmanaged(Symbol.Index) = .{},
resolver: std.AutoArrayHashMapUnmanaged(u32, Symbol.Index) = .{},
has_text_reloc: bool = false,
num_ifunc_dynrelocs: usize = 0,
/// List of atoms that are owned directly by the linker.
atoms: std.ArrayListUnmanaged(Atom) = .{},
/// List of range extension thunks.
thunks: std.ArrayListUnmanaged(Thunk) = .{},
/// Table of last atom index in a section and matching atom free list if any.
last_atom_and_free_list_table: LastAtomAndFreeListTable = .{},
comdat_groups: std.ArrayListUnmanaged(ComdatGroup) = .{},
comdat_groups_owners: std.ArrayListUnmanaged(ComdatGroupOwner) = .{},
comdat_groups_table: std.AutoHashMapUnmanaged(u32, ComdatGroupOwner.Index) = .{},
/// Global string table used to provide quick access to global symbol resolvers
/// such as `resolver` and `comdat_groups_table`.
strings: StringTable = .{},
/// When allocating, the ideal_capacity is calculated by
/// actual_capacity + (actual_capacity / ideal_factor)
const ideal_factor = 3;
/// In order for a slice of bytes to be considered eligible to keep metadata pointing at
/// it as a possible place to put new symbols, it must have enough room for this many bytes
/// (plus extra for reserved capacity).
const minimum_atom_size = 64;
pub const min_text_capacity = padToIdeal(minimum_atom_size);
pub const PtrWidth = enum { p32, p64 };
pub const HashStyle = enum { sysv, gnu, both };
pub const CompressDebugSections = enum { none, zlib, zstd };
pub const SortSection = enum { name, alignment };
pub fn createEmpty(
arena: Allocator,
comp: *Compilation,
emit: Compilation.Emit,
options: link.File.OpenOptions,
) !*Elf {
const target = comp.root_mod.resolved_target.result;
assert(target.ofmt == .elf);
const use_lld = build_options.have_llvm and comp.config.use_lld;
const use_llvm = comp.config.use_llvm;
const opt_zcu = comp.module;
const output_mode = comp.config.output_mode;
const link_mode = comp.config.link_mode;
const optimize_mode = comp.root_mod.optimize_mode;
const is_native_os = comp.root_mod.resolved_target.is_native_os;
const ptr_width: PtrWidth = switch (target.ptrBitWidth()) {
0...32 => .p32,
33...64 => .p64,
else => return error.UnsupportedELFArchitecture,
};
const page_size: u32 = switch (target.cpu.arch) {
.aarch64, .powerpc64le => 0x10000,
.sparc64 => 0x2000,
else => 0x1000,
};
const is_dyn_lib = output_mode == .Lib and link_mode == .dynamic;
const default_sym_version: elf.Elf64_Versym = if (is_dyn_lib or comp.config.rdynamic)
elf.VER_NDX_GLOBAL
else
elf.VER_NDX_LOCAL;
// If using LLD to link, this code should produce an object file so that it
// can be passed to LLD.
// If using LLVM to generate the object file for the zig compilation unit,
// we need a place to put the object file so that it can be subsequently
// handled.
const zcu_object_sub_path = if (!use_lld and !use_llvm)
null
else
try std.fmt.allocPrint(arena, "{s}.o", .{emit.sub_path});
const self = try arena.create(Elf);
self.* = .{
.base = .{
.tag = .elf,
.comp = comp,
.emit = emit,
.zcu_object_sub_path = zcu_object_sub_path,
.gc_sections = options.gc_sections orelse (optimize_mode != .Debug and output_mode != .Obj),
.print_gc_sections = options.print_gc_sections,
.stack_size = options.stack_size orelse 16777216,
.allow_shlib_undefined = options.allow_shlib_undefined orelse !is_native_os,
.file = null,
.disable_lld_caching = options.disable_lld_caching,
.build_id = options.build_id,
.rpath_list = options.rpath_list,
},
.ptr_width = ptr_width,
.page_size = page_size,
.default_sym_version = default_sym_version,
.entry_name = switch (options.entry) {
.disabled => null,
.default => if (output_mode != .Exe) null else defaultEntrySymbolName(target.cpu.arch),
.enabled => defaultEntrySymbolName(target.cpu.arch),
.named => |name| name,
},
.image_base = b: {
if (is_dyn_lib) break :b 0;
if (output_mode == .Exe and comp.config.pie) break :b 0;
break :b options.image_base orelse switch (ptr_width) {
.p32 => 0x10000,
.p64 => 0x1000000,
};
},
.emit_relocs = options.emit_relocs,
.z_nodelete = options.z_nodelete,
.z_notext = options.z_notext,
.z_defs = options.z_defs,
.z_origin = options.z_origin,
.z_nocopyreloc = options.z_nocopyreloc,
.z_now = options.z_now,
.z_relro = options.z_relro,
.z_common_page_size = options.z_common_page_size,
.z_max_page_size = options.z_max_page_size,
.lib_dirs = options.lib_dirs,
.hash_style = options.hash_style,
.compress_debug_sections = options.compress_debug_sections,
.symbol_wrap_set = options.symbol_wrap_set,
.sort_section = options.sort_section,
.soname = options.soname,
.bind_global_refs_locally = options.bind_global_refs_locally,
.linker_script = options.linker_script,
.version_script = options.version_script,
.allow_undefined_version = options.allow_undefined_version,
.enable_new_dtags = options.enable_new_dtags,
.print_icf_sections = options.print_icf_sections,
.print_map = options.print_map,
};
if (use_llvm and comp.config.have_zcu) {
self.llvm_object = try LlvmObject.create(arena, comp);
}
errdefer self.base.destroy();
if (use_lld and (use_llvm or !comp.config.have_zcu)) {
// LLVM emits the object file (if any); LLD links it into the final product.
return self;
}
const is_obj = output_mode == .Obj;
const is_obj_or_ar = is_obj or (output_mode == .Lib and link_mode == .static);
// What path should this ELF linker code output to?
// If using LLD to link, this code should produce an object file so that it
// can be passed to LLD.
const sub_path = if (use_lld) zcu_object_sub_path.? else emit.sub_path;
self.base.file = try emit.directory.handle.createFile(sub_path, .{
.truncate = true,
.read = true,
.mode = link.File.determineMode(use_lld, output_mode, link_mode),
});
const gpa = comp.gpa;
// Index 0 is always a null symbol.
try self.symbols.append(gpa, .{});
// Index 0 is always a null symbol.
try self.symbols_extra.append(gpa, 0);
// Allocate atom index 0 to null atom
try self.atoms.append(gpa, .{});
// Append null file at index 0
try self.files.append(gpa, .null);
// Append null byte to string tables
try self.shstrtab.append(gpa, 0);
try self.strtab.append(gpa, 0);
// There must always be a null shdr in index 0
_ = try self.addSection(.{ .name = "" });
// Append null symbol in output symtab
try self.symtab.append(gpa, null_sym);
if (!is_obj_or_ar) {
try self.dynstrtab.append(gpa, 0);
// Initialize PT_PHDR program header
const p_align: u16 = switch (self.ptr_width) {
.p32 => @alignOf(elf.Elf32_Phdr),
.p64 => @alignOf(elf.Elf64_Phdr),
};
const ehsize: u64 = switch (self.ptr_width) {
.p32 => @sizeOf(elf.Elf32_Ehdr),
.p64 => @sizeOf(elf.Elf64_Ehdr),
};
const phsize: u64 = switch (self.ptr_width) {
.p32 => @sizeOf(elf.Elf32_Phdr),
.p64 => @sizeOf(elf.Elf64_Phdr),
};
const max_nphdrs = comptime getMaxNumberOfPhdrs();
const reserved: u64 = mem.alignForward(u64, padToIdeal(max_nphdrs * phsize), self.page_size);
self.phdr_table_index = try self.addPhdr(.{
.type = elf.PT_PHDR,
.flags = elf.PF_R,
.@"align" = p_align,
.addr = self.image_base + ehsize,
.offset = ehsize,
.filesz = reserved,
.memsz = reserved,
});
self.phdr_table_load_index = try self.addPhdr(.{
.type = elf.PT_LOAD,
.flags = elf.PF_R,
.@"align" = self.page_size,
.addr = self.image_base,
.offset = 0,
.filesz = reserved + ehsize,
.memsz = reserved + ehsize,
});
}
if (opt_zcu) |zcu| {
if (!use_llvm) {
const index: File.Index = @intCast(try self.files.addOne(gpa));
self.files.set(index, .{ .zig_object = .{
.index = index,
.path = try std.fmt.allocPrint(arena, "{s}.o", .{std.fs.path.stem(
zcu.main_mod.root_src_path,
)}),
} });
self.zig_object_index = index;
try self.zigObjectPtr().?.init(self);
try self.initMetadata(.{
.symbol_count_hint = options.symbol_count_hint,
.program_code_size_hint = options.program_code_size_hint,
});
}
}
return self;
}
pub fn open(
arena: Allocator,
comp: *Compilation,
emit: Compilation.Emit,
options: link.File.OpenOptions,
) !*Elf {
// TODO: restore saved linker state, don't truncate the file, and
// participate in incremental compilation.
return createEmpty(arena, comp, emit, options);
}
pub fn deinit(self: *Elf) void {
const gpa = self.base.comp.gpa;
if (self.llvm_object) |llvm_object| llvm_object.deinit();
for (self.file_handles.items) |fh| {
fh.close();
}
self.file_handles.deinit(gpa);
for (self.files.items(.tags), self.files.items(.data)) |tag, *data| switch (tag) {
.null => {},
.zig_object => data.zig_object.deinit(gpa),
.linker_defined => data.linker_defined.deinit(gpa),
.object => data.object.deinit(gpa),
.shared_object => data.shared_object.deinit(gpa),
};
self.files.deinit(gpa);
self.objects.deinit(gpa);
self.shared_objects.deinit(gpa);
self.shdrs.deinit(gpa);
self.phdr_to_shdr_table.deinit(gpa);
self.phdrs.deinit(gpa);
for (self.output_sections.values()) |*list| {
list.deinit(gpa);
}
self.output_sections.deinit(gpa);
for (self.output_rela_sections.values()) |*sec| {
sec.atom_list.deinit(gpa);
}
self.output_rela_sections.deinit(gpa);
self.shstrtab.deinit(gpa);
self.symtab.deinit(gpa);
self.strtab.deinit(gpa);
self.symbols.deinit(gpa);
self.symbols_extra.deinit(gpa);
self.symbols_free_list.deinit(gpa);
self.resolver.deinit(gpa);
self.start_stop_indexes.deinit(gpa);
self.atoms.deinit(gpa);
self.thunks.deinit(gpa);
for (self.last_atom_and_free_list_table.values()) |*value| {
value.free_list.deinit(gpa);
}
self.last_atom_and_free_list_table.deinit(gpa);
self.comdat_groups.deinit(gpa);
self.comdat_groups_owners.deinit(gpa);
self.comdat_groups_table.deinit(gpa);
self.strings.deinit(gpa);
self.got.deinit(gpa);
self.plt.deinit(gpa);
self.plt_got.deinit(gpa);
self.dynsym.deinit(gpa);
self.dynstrtab.deinit(gpa);
self.dynamic.deinit(gpa);
self.hash.deinit(gpa);
self.versym.deinit(gpa);
self.verneed.deinit(gpa);
self.copy_rel.deinit(gpa);
self.rela_dyn.deinit(gpa);
self.rela_plt.deinit(gpa);
self.zig_got.deinit(gpa);
self.comdat_group_sections.deinit(gpa);
}
pub fn getDeclVAddr(self: *Elf, decl_index: InternPool.DeclIndex, reloc_info: link.File.RelocInfo) !u64 {
assert(self.llvm_object == null);
return self.zigObjectPtr().?.getDeclVAddr(self, decl_index, reloc_info);
}
pub fn lowerAnonDecl(
self: *Elf,
decl_val: InternPool.Index,
explicit_alignment: InternPool.Alignment,
src_loc: Module.SrcLoc,
) !codegen.Result {
return self.zigObjectPtr().?.lowerAnonDecl(self, decl_val, explicit_alignment, src_loc);
}
pub fn getAnonDeclVAddr(self: *Elf, decl_val: InternPool.Index, reloc_info: link.File.RelocInfo) !u64 {
assert(self.llvm_object == null);
return self.zigObjectPtr().?.getAnonDeclVAddr(self, decl_val, reloc_info);
}
/// Returns end pos of collision, if any.
fn detectAllocCollision(self: *Elf, start: u64, size: u64) ?u64 {
const small_ptr = self.ptr_width == .p32;
const ehdr_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Ehdr) else @sizeOf(elf.Elf64_Ehdr);
if (start < ehdr_size)
return ehdr_size;
const end = start + padToIdeal(size);
if (self.shdr_table_offset) |off| {
const shdr_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Shdr) else @sizeOf(elf.Elf64_Shdr);
const tight_size = self.shdrs.items.len * shdr_size;
const increased_size = padToIdeal(tight_size);
const test_end = off +| increased_size;
if (end > off and start < test_end) {
return test_end;
}
}
for (self.shdrs.items) |shdr| {
if (shdr.sh_type == elf.SHT_NOBITS) continue;
const increased_size = padToIdeal(shdr.sh_size);
const test_end = shdr.sh_offset +| increased_size;
if (end > shdr.sh_offset and start < test_end) {
return test_end;
}
}
for (self.phdrs.items) |phdr| {
if (phdr.p_type != elf.PT_LOAD) continue;
const increased_size = padToIdeal(phdr.p_filesz);
const test_end = phdr.p_offset +| increased_size;
if (end > phdr.p_offset and start < test_end) {
return test_end;
}
}
return null;
}
pub fn allocatedSize(self: *Elf, start: u64) u64 {
if (start == 0) return 0;
var min_pos: u64 = std.math.maxInt(u64);
if (self.shdr_table_offset) |off| {
if (off > start and off < min_pos) min_pos = off;
}
for (self.shdrs.items) |section| {
if (section.sh_offset <= start) continue;
if (section.sh_offset < min_pos) min_pos = section.sh_offset;
}
for (self.phdrs.items) |phdr| {
if (phdr.p_offset <= start) continue;
if (phdr.p_offset < min_pos) min_pos = phdr.p_offset;
}
return min_pos - start;
}
fn allocatedVirtualSize(self: *Elf, start: u64) u64 {
if (start == 0) return 0;
var min_pos: u64 = std.math.maxInt(u64);
for (self.phdrs.items) |phdr| {
if (phdr.p_vaddr <= start) continue;
if (phdr.p_vaddr < min_pos) min_pos = phdr.p_vaddr;
}
return min_pos - start;
}
pub fn findFreeSpace(self: *Elf, object_size: u64, min_alignment: u64) u64 {
var start: u64 = 0;
while (self.detectAllocCollision(start, object_size)) |item_end| {
start = mem.alignForward(u64, item_end, min_alignment);
}
return start;
}
pub const InitMetadataOptions = struct {
symbol_count_hint: u64,
program_code_size_hint: u64,
};
/// TODO move to ZigObject
pub fn initMetadata(self: *Elf, options: InitMetadataOptions) !void {
const gpa = self.base.comp.gpa;
const ptr_size = self.ptrWidthBytes();
const target = self.base.comp.root_mod.resolved_target.result;
const ptr_bit_width = target.ptrBitWidth();
const is_linux = target.os.tag == .linux;
const zig_object = self.zigObjectPtr().?;
const fillSection = struct {
fn fillSection(elf_file: *Elf, shdr: *elf.Elf64_Shdr, size: u64, phndx: ?u16) void {
if (elf_file.base.isRelocatable()) {
const off = elf_file.findFreeSpace(size, shdr.sh_addralign);
shdr.sh_offset = off;
shdr.sh_size = size;
} else {
const phdr = elf_file.phdrs.items[phndx.?];
shdr.sh_addr = phdr.p_vaddr;
shdr.sh_offset = phdr.p_offset;
shdr.sh_size = phdr.p_memsz;
}
}
}.fillSection;
comptime assert(number_of_zig_segments == 5);
if (!self.base.isRelocatable()) {
if (self.phdr_zig_load_re_index == null) {
const filesz = options.program_code_size_hint;
const off = self.findFreeSpace(filesz, self.page_size);
self.phdr_zig_load_re_index = try self.addPhdr(.{
.type = elf.PT_LOAD,
.offset = off,
.filesz = filesz,
.addr = if (ptr_bit_width >= 32) 0x8000000 else 0x8000,
.memsz = filesz,
.@"align" = self.page_size,
.flags = elf.PF_X | elf.PF_R | elf.PF_W,
});
}
if (self.phdr_zig_got_index == null) {
// We really only need ptr alignment but since we are using PROGBITS, linux requires
// page align.
const alignment = if (is_linux) self.page_size else @as(u16, ptr_size);
const filesz = @as(u64, ptr_size) * options.symbol_count_hint;
const off = self.findFreeSpace(filesz, alignment);
self.phdr_zig_got_index = try self.addPhdr(.{
.type = elf.PT_LOAD,
.offset = off,
.filesz = filesz,
.addr = if (ptr_bit_width >= 32) 0x4000000 else 0x4000,
.memsz = filesz,
.@"align" = alignment,
.flags = elf.PF_R | elf.PF_W,
});
}
if (self.phdr_zig_load_ro_index == null) {
const alignment = if (is_linux) self.page_size else @as(u16, ptr_size);
const filesz: u64 = 1024;
const off = self.findFreeSpace(filesz, alignment);
self.phdr_zig_load_ro_index = try self.addPhdr(.{
.type = elf.PT_LOAD,
.offset = off,
.filesz = filesz,
.addr = if (ptr_bit_width >= 32) 0xc000000 else 0xa000,
.memsz = filesz,
.@"align" = alignment,
.flags = elf.PF_R | elf.PF_W,
});
}
if (self.phdr_zig_load_rw_index == null) {
const alignment = if (is_linux) self.page_size else @as(u16, ptr_size);
const filesz: u64 = 1024;
const off = self.findFreeSpace(filesz, alignment);
self.phdr_zig_load_rw_index = try self.addPhdr(.{
.type = elf.PT_LOAD,
.offset = off,
.filesz = filesz,
.addr = if (ptr_bit_width >= 32) 0x10000000 else 0xc000,
.memsz = filesz,
.@"align" = alignment,
.flags = elf.PF_R | elf.PF_W,
});
}
if (self.phdr_zig_load_zerofill_index == null) {
const alignment = if (is_linux) self.page_size else @as(u16, ptr_size);
self.phdr_zig_load_zerofill_index = try self.addPhdr(.{
.type = elf.PT_LOAD,
.addr = if (ptr_bit_width >= 32) 0x14000000 else 0xf000,
.memsz = 1024,
.@"align" = alignment,
.flags = elf.PF_R | elf.PF_W,
});
}
}
if (self.zig_text_section_index == null) {
self.zig_text_section_index = try self.addSection(.{
.name = ".text.zig",
.type = elf.SHT_PROGBITS,
.flags = elf.SHF_ALLOC | elf.SHF_EXECINSTR,
.addralign = 1,
.offset = std.math.maxInt(u64),
});
const shdr = &self.shdrs.items[self.zig_text_section_index.?];
fillSection(self, shdr, options.program_code_size_hint, self.phdr_zig_load_re_index);
if (self.base.isRelocatable()) {
const rela_shndx = try self.addRelaShdr(".rela.text.zig", self.zig_text_section_index.?);
try self.output_rela_sections.putNoClobber(gpa, self.zig_text_section_index.?, .{
.shndx = rela_shndx,
});
} else {
try self.phdr_to_shdr_table.putNoClobber(
gpa,
self.zig_text_section_index.?,
self.phdr_zig_load_re_index.?,
);
}
try self.output_sections.putNoClobber(gpa, self.zig_text_section_index.?, .{});
try self.last_atom_and_free_list_table.putNoClobber(gpa, self.zig_text_section_index.?, .{});
}
if (self.zig_got_section_index == null and !self.base.isRelocatable()) {
self.zig_got_section_index = try self.addSection(.{
.name = ".got.zig",
.type = elf.SHT_PROGBITS,
.addralign = ptr_size,
.flags = elf.SHF_ALLOC | elf.SHF_WRITE,
.offset = std.math.maxInt(u64),
});
const shdr = &self.shdrs.items[self.zig_got_section_index.?];
const phndx = self.phdr_zig_got_index.?;
const phdr = self.phdrs.items[phndx];
shdr.sh_addr = phdr.p_vaddr;
shdr.sh_offset = phdr.p_offset;
shdr.sh_size = phdr.p_memsz;
try self.phdr_to_shdr_table.putNoClobber(
gpa,
self.zig_got_section_index.?,
self.phdr_zig_got_index.?,
);
}
if (self.zig_data_rel_ro_section_index == null) {
self.zig_data_rel_ro_section_index = try self.addSection(.{
.name = ".data.rel.ro.zig",
.type = elf.SHT_PROGBITS,
.addralign = 1,
.flags = elf.SHF_ALLOC | elf.SHF_WRITE,
.offset = std.math.maxInt(u64),
});
const shdr = &self.shdrs.items[self.zig_data_rel_ro_section_index.?];
fillSection(self, shdr, 1024, self.phdr_zig_load_ro_index);
if (self.base.isRelocatable()) {
const rela_shndx = try self.addRelaShdr(
".rela.data.rel.ro.zig",
self.zig_data_rel_ro_section_index.?,
);
try self.output_rela_sections.putNoClobber(gpa, self.zig_data_rel_ro_section_index.?, .{
.shndx = rela_shndx,
});
} else {
try self.phdr_to_shdr_table.putNoClobber(
gpa,
self.zig_data_rel_ro_section_index.?,
self.phdr_zig_load_ro_index.?,
);
}
try self.output_sections.putNoClobber(gpa, self.zig_data_rel_ro_section_index.?, .{});
try self.last_atom_and_free_list_table.putNoClobber(gpa, self.zig_data_rel_ro_section_index.?, .{});
}
if (self.zig_data_section_index == null) {
self.zig_data_section_index = try self.addSection(.{
.name = ".data.zig",
.type = elf.SHT_PROGBITS,
.addralign = ptr_size,
.flags = elf.SHF_ALLOC | elf.SHF_WRITE,
.offset = std.math.maxInt(u64),
});
const shdr = &self.shdrs.items[self.zig_data_section_index.?];
fillSection(self, shdr, 1024, self.phdr_zig_load_rw_index);
if (self.base.isRelocatable()) {
const rela_shndx = try self.addRelaShdr(
".rela.data.zig",
self.zig_data_section_index.?,
);
try self.output_rela_sections.putNoClobber(gpa, self.zig_data_section_index.?, .{
.shndx = rela_shndx,
});
} else {
try self.phdr_to_shdr_table.putNoClobber(
gpa,
self.zig_data_section_index.?,
self.phdr_zig_load_rw_index.?,
);
}
try self.output_sections.putNoClobber(gpa, self.zig_data_section_index.?, .{});
try self.last_atom_and_free_list_table.putNoClobber(gpa, self.zig_data_section_index.?, .{});
}
if (self.zig_bss_section_index == null) {
self.zig_bss_section_index = try self.addSection(.{
.name = ".bss.zig",
.type = elf.SHT_NOBITS,
.addralign = ptr_size,
.flags = elf.SHF_ALLOC | elf.SHF_WRITE,
.offset = 0,
});
const shdr = &self.shdrs.items[self.zig_bss_section_index.?];
if (self.phdr_zig_load_zerofill_index) |phndx| {
const phdr = self.phdrs.items[phndx];
shdr.sh_addr = phdr.p_vaddr;
shdr.sh_size = phdr.p_memsz;
try self.phdr_to_shdr_table.putNoClobber(gpa, self.zig_bss_section_index.?, phndx);
} else {
shdr.sh_size = 1024;
}
try self.output_sections.putNoClobber(gpa, self.zig_bss_section_index.?, .{});
try self.last_atom_and_free_list_table.putNoClobber(gpa, self.zig_bss_section_index.?, .{});
}
if (zig_object.dwarf) |*dw| {
if (self.debug_str_section_index == null) {
assert(dw.strtab.buffer.items.len == 0);
try dw.strtab.buffer.append(gpa, 0);
self.debug_str_section_index = try self.addSection(.{
.name = ".debug_str",
.flags = elf.SHF_MERGE | elf.SHF_STRINGS,
.entsize = 1,
.type = elf.SHT_PROGBITS,
.addralign = 1,
.offset = std.math.maxInt(u64),
});
const shdr = &self.shdrs.items[self.debug_str_section_index.?];
const size = @as(u64, @intCast(dw.strtab.buffer.items.len));
const off = self.findFreeSpace(size, 1);
shdr.sh_offset = off;
shdr.sh_size = size;
zig_object.debug_strtab_dirty = true;
try self.output_sections.putNoClobber(gpa, self.debug_str_section_index.?, .{});
}
if (self.debug_info_section_index == null) {
self.debug_info_section_index = try self.addSection(.{
.name = ".debug_info",
.type = elf.SHT_PROGBITS,
.addralign = 1,
.offset = std.math.maxInt(u64),
});
const shdr = &self.shdrs.items[self.debug_info_section_index.?];
const size: u64 = 200;
const off = self.findFreeSpace(size, 1);
shdr.sh_offset = off;
shdr.sh_size = size;
zig_object.debug_info_header_dirty = true;
try self.output_sections.putNoClobber(gpa, self.debug_info_section_index.?, .{});
}
if (self.debug_abbrev_section_index == null) {
self.debug_abbrev_section_index = try self.addSection(.{
.name = ".debug_abbrev",
.type = elf.SHT_PROGBITS,
.addralign = 1,
.offset = std.math.maxInt(u64),
});
const shdr = &self.shdrs.items[self.debug_abbrev_section_index.?];
const size: u64 = 128;
const off = self.findFreeSpace(size, 1);
shdr.sh_offset = off;
shdr.sh_size = size;
zig_object.debug_abbrev_section_dirty = true;
try self.output_sections.putNoClobber(gpa, self.debug_abbrev_section_index.?, .{});
}
if (self.debug_aranges_section_index == null) {
self.debug_aranges_section_index = try self.addSection(.{
.name = ".debug_aranges",
.type = elf.SHT_PROGBITS,
.addralign = 16,
.offset = std.math.maxInt(u64),
});
const shdr = &self.shdrs.items[self.debug_aranges_section_index.?];
const size: u64 = 160;
const off = self.findFreeSpace(size, 16);
shdr.sh_offset = off;
shdr.sh_size = size;
zig_object.debug_aranges_section_dirty = true;
try self.output_sections.putNoClobber(gpa, self.debug_aranges_section_index.?, .{});
}
if (self.debug_line_section_index == null) {
self.debug_line_section_index = try self.addSection(.{
.name = ".debug_line",
.type = elf.SHT_PROGBITS,
.addralign = 1,
.offset = std.math.maxInt(u64),
});
const shdr = &self.shdrs.items[self.debug_line_section_index.?];
const size: u64 = 250;
const off = self.findFreeSpace(size, 1);
shdr.sh_offset = off;
shdr.sh_size = size;
zig_object.debug_line_header_dirty = true;
try self.output_sections.putNoClobber(gpa, self.debug_line_section_index.?, .{});
}
}
// We need to find current max assumed file offset, and actually write to file to make it a reality.
var end_pos: u64 = 0;
for (self.shdrs.items) |shdr| {
if (shdr.sh_offset == std.math.maxInt(u64)) continue;
end_pos = @max(end_pos, shdr.sh_offset + shdr.sh_size);
}
try self.base.file.?.pwriteAll(&[1]u8{0}, end_pos);
}
pub fn growAllocSection(self: *Elf, shdr_index: u32, needed_size: u64) !void {
const shdr = &self.shdrs.items[shdr_index];
const maybe_phdr = if (self.phdr_to_shdr_table.get(shdr_index)) |phndx| &self.phdrs.items[phndx] else null;
const is_zerofill = shdr.sh_type == elf.SHT_NOBITS;
if (needed_size > self.allocatedSize(shdr.sh_offset) and !is_zerofill) {
const existing_size = shdr.sh_size;
shdr.sh_size = 0;
// Must move the entire section.
const alignment = if (maybe_phdr) |phdr| phdr.p_align else shdr.sh_addralign;
const new_offset = self.findFreeSpace(needed_size, alignment);
log.debug("new '{s}' file offset 0x{x} to 0x{x}", .{
self.getShString(shdr.sh_name),
new_offset,
new_offset + existing_size,
});
const amt = try self.base.file.?.copyRangeAll(shdr.sh_offset, self.base.file.?, new_offset, existing_size);
// TODO figure out what to about this error condition - how to communicate it up.
if (amt != existing_size) return error.InputOutput;
shdr.sh_offset = new_offset;
if (maybe_phdr) |phdr| phdr.p_offset = new_offset;
}
shdr.sh_size = needed_size;
if (!is_zerofill) {
if (maybe_phdr) |phdr| phdr.p_filesz = needed_size;
}
if (maybe_phdr) |phdr| {
const mem_capacity = self.allocatedVirtualSize(phdr.p_vaddr);
if (needed_size > mem_capacity) {
var err = try self.addErrorWithNotes(2);
try err.addMsg(self, "fatal linker error: cannot expand load segment phdr({d}) in virtual memory", .{
self.phdr_to_shdr_table.get(shdr_index).?,
});
try err.addNote(self, "TODO: emit relocations to memory locations in self-hosted backends", .{});
try err.addNote(self, "as a workaround, try increasing pre-allocated virtual memory of each segment", .{});
}
phdr.p_memsz = needed_size;
}
self.markDirty(shdr_index);
}
pub fn growNonAllocSection(
self: *Elf,
shdr_index: u32,
needed_size: u64,
min_alignment: u32,
requires_file_copy: bool,
) !void {
const shdr = &self.shdrs.items[shdr_index];
if (needed_size > self.allocatedSize(shdr.sh_offset)) {
const existing_size = shdr.sh_size;
shdr.sh_size = 0;