-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Coff.zig
2757 lines (2386 loc) · 102 KB
/
Coff.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
//! The main driver of the COFF linker.
//! Currently uses our own implementation for the incremental linker, and falls back to
//! LLD for traditional linking (linking relocatable object files).
//! LLD is also the default linker for LLVM.
/// If this is not null, an object file is created by LLVM and emitted to zcu_object_sub_path.
llvm_object: ?*LlvmObject = null,
base: link.File,
image_base: u64,
subsystem: ?std.Target.SubSystem,
tsaware: bool,
nxcompat: bool,
dynamicbase: bool,
/// TODO this and minor_subsystem_version should be combined into one property and left as
/// default or populated together. They should not be separate fields.
major_subsystem_version: u16,
minor_subsystem_version: u16,
lib_dirs: []const []const u8,
entry: link.File.OpenOptions.Entry,
entry_addr: ?u32,
module_definition_file: ?[]const u8,
pdb_out_path: ?[]const u8,
ptr_width: PtrWidth,
page_size: u32,
objects: std.ArrayListUnmanaged(Object) = .{},
sections: std.MultiArrayList(Section) = .{},
data_directories: [coff.IMAGE_NUMBEROF_DIRECTORY_ENTRIES]coff.ImageDataDirectory,
text_section_index: ?u16 = null,
got_section_index: ?u16 = null,
rdata_section_index: ?u16 = null,
data_section_index: ?u16 = null,
reloc_section_index: ?u16 = null,
idata_section_index: ?u16 = null,
locals: std.ArrayListUnmanaged(coff.Symbol) = .{},
globals: std.ArrayListUnmanaged(SymbolWithLoc) = .{},
resolver: std.StringHashMapUnmanaged(u32) = .{},
unresolved: std.AutoArrayHashMapUnmanaged(u32, bool) = .{},
need_got_table: std.AutoHashMapUnmanaged(u32, void) = .{},
locals_free_list: std.ArrayListUnmanaged(u32) = .{},
globals_free_list: std.ArrayListUnmanaged(u32) = .{},
strtab: StringTable = .{},
strtab_offset: ?u32 = null,
temp_strtab: StringTable = .{},
got_table: TableSection(SymbolWithLoc) = .{},
/// A table of ImportTables partitioned by the library name.
/// Key is an offset into the interning string table `temp_strtab`.
import_tables: std.AutoArrayHashMapUnmanaged(u32, ImportTable) = .{},
got_table_count_dirty: bool = true,
got_table_contents_dirty: bool = true,
imports_count_dirty: bool = true,
/// Table of tracked LazySymbols.
lazy_syms: LazySymbolTable = .{},
/// Table of tracked Decls.
decls: DeclTable = .{},
/// List of atoms that are either synthetic or map directly to the Zig source program.
atoms: std.ArrayListUnmanaged(Atom) = .{},
/// Table of atoms indexed by the symbol index.
atom_by_index_table: std.AutoHashMapUnmanaged(u32, Atom.Index) = .{},
/// Table of unnamed constants associated with a parent `Decl`.
/// We store them here so that we can free the constants whenever the `Decl`
/// needs updating or is freed.
///
/// For example,
///
/// ```zig
/// const Foo = struct{
/// a: u8,
/// };
///
/// pub fn main() void {
/// var foo = Foo{ .a = 1 };
/// _ = foo;
/// }
/// ```
///
/// value assigned to label `foo` is an unnamed constant belonging/associated
/// with `Decl` `main`, and lives as long as that `Decl`.
unnamed_const_atoms: UnnamedConstTable = .{},
anon_decls: AnonDeclTable = .{},
/// A table of relocations indexed by the owning them `Atom`.
/// Note that once we refactor `Atom`'s lifetime and ownership rules,
/// this will be a table indexed by index into the list of Atoms.
relocs: RelocTable = .{},
/// A table of base relocations indexed by the owning them `Atom`.
/// Note that once we refactor `Atom`'s lifetime and ownership rules,
/// this will be a table indexed by index into the list of Atoms.
base_relocs: BaseRelocationTable = .{},
/// Hot-code swapping state.
hot_state: if (is_hot_update_compatible) HotUpdateState else struct {} = .{},
const is_hot_update_compatible = switch (builtin.target.os.tag) {
.windows => true,
else => false,
};
const HotUpdateState = struct {
/// Base address at which the process (image) got loaded.
/// We need this info to correctly slide pointers when relocating.
loaded_base_address: ?std.os.windows.HMODULE = null,
};
const DeclTable = std.AutoArrayHashMapUnmanaged(InternPool.DeclIndex, DeclMetadata);
const AnonDeclTable = std.AutoHashMapUnmanaged(InternPool.Index, DeclMetadata);
const RelocTable = std.AutoArrayHashMapUnmanaged(Atom.Index, std.ArrayListUnmanaged(Relocation));
const BaseRelocationTable = std.AutoArrayHashMapUnmanaged(Atom.Index, std.ArrayListUnmanaged(u32));
const UnnamedConstTable = std.AutoArrayHashMapUnmanaged(InternPool.DeclIndex, std.ArrayListUnmanaged(Atom.Index));
const default_file_alignment: u16 = 0x200;
const default_size_of_stack_reserve: u32 = 0x1000000;
const default_size_of_stack_commit: u32 = 0x1000;
const default_size_of_heap_reserve: u32 = 0x100000;
const default_size_of_heap_commit: u32 = 0x1000;
const Section = struct {
header: coff.SectionHeader,
last_atom_index: ?Atom.Index = null,
/// A list of atoms that have surplus capacity. This list can have false
/// positives, as functions grow and shrink over time, only sometimes being added
/// or removed from the freelist.
///
/// An atom has surplus capacity when its overcapacity value is greater than
/// padToIdeal(minimum_atom_size). That is, when it has so
/// much extra capacity, that we could fit a small new symbol in it, itself with
/// ideal_capacity or more.
///
/// Ideal capacity is defined by size + (size / ideal_factor).
///
/// Overcapacity is measured by actual_capacity - ideal_capacity. Note that
/// overcapacity can be negative. A simple way to have negative overcapacity is to
/// allocate a fresh atom, which will have ideal capacity, and then grow it
/// by 1 byte. It will then have -1 overcapacity.
free_list: std.ArrayListUnmanaged(Atom.Index) = .{},
};
const LazySymbolTable = std.AutoArrayHashMapUnmanaged(InternPool.OptionalDeclIndex, LazySymbolMetadata);
const LazySymbolMetadata = struct {
const State = enum { unused, pending_flush, flushed };
text_atom: Atom.Index = undefined,
rdata_atom: Atom.Index = undefined,
text_state: State = .unused,
rdata_state: State = .unused,
};
const DeclMetadata = struct {
atom: Atom.Index,
section: u16,
/// A list of all exports aliases of this Decl.
exports: std.ArrayListUnmanaged(u32) = .{},
fn deinit(m: *DeclMetadata, allocator: Allocator) void {
m.exports.deinit(allocator);
}
fn getExport(m: DeclMetadata, coff_file: *const Coff, name: []const u8) ?u32 {
for (m.exports.items) |exp| {
if (mem.eql(u8, name, coff_file.getSymbolName(.{
.sym_index = exp,
.file = null,
}))) return exp;
}
return null;
}
fn getExportPtr(m: *DeclMetadata, coff_file: *Coff, name: []const u8) ?*u32 {
for (m.exports.items) |*exp| {
if (mem.eql(u8, name, coff_file.getSymbolName(.{
.sym_index = exp.*,
.file = null,
}))) return exp;
}
return null;
}
};
pub const PtrWidth = enum {
p32,
p64,
/// Size in bytes.
pub fn size(pw: PtrWidth) u4 {
return switch (pw) {
.p32 => 4,
.p64 => 8,
};
}
};
pub const SymbolWithLoc = struct {
// Index into the respective symbol table.
sym_index: u32,
// null means it's a synthetic global or Zig source.
file: ?u32 = null,
pub fn eql(this: SymbolWithLoc, other: SymbolWithLoc) bool {
if (this.file == null and other.file == null) {
return this.sym_index == other.sym_index;
}
if (this.file != null and other.file != null) {
return this.sym_index == other.sym_index and this.file.? == other.file.?;
}
return false;
}
};
/// 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_text_block_size = 64;
pub const min_text_capacity = padToIdeal(minimum_text_block_size);
pub fn createEmpty(
arena: Allocator,
comp: *Compilation,
emit: Compilation.Emit,
options: link.File.OpenOptions,
) !*Coff {
const target = comp.root_mod.resolved_target.result;
assert(target.ofmt == .coff);
const optimize_mode = comp.root_mod.optimize_mode;
const output_mode = comp.config.output_mode;
const link_mode = comp.config.link_mode;
const use_llvm = comp.config.use_llvm;
const use_lld = build_options.have_llvm and comp.config.use_lld;
const ptr_width: PtrWidth = switch (target.ptrBitWidth()) {
0...32 => .p32,
33...64 => .p64,
else => return error.UnsupportedCOFFArchitecture,
};
const page_size: u32 = switch (target.cpu.arch) {
else => 0x1000,
};
// 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}.obj", .{emit.sub_path});
const self = try arena.create(Coff);
self.* = .{
.base = .{
.tag = .coff,
.comp = comp,
.emit = emit,
.zcu_object_sub_path = zcu_object_sub_path,
.stack_size = options.stack_size orelse 16777216,
.gc_sections = options.gc_sections orelse (optimize_mode != .Debug),
.print_gc_sections = options.print_gc_sections,
.allow_shlib_undefined = options.allow_shlib_undefined orelse false,
.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,
.data_directories = [1]coff.ImageDataDirectory{.{
.virtual_address = 0,
.size = 0,
}} ** coff.IMAGE_NUMBEROF_DIRECTORY_ENTRIES,
.image_base = options.image_base orelse switch (output_mode) {
.Exe => switch (target.cpu.arch) {
.aarch64 => 0x140000000,
.x86_64, .x86 => 0x400000,
else => unreachable,
},
.Lib => 0x10000000,
.Obj => 0,
},
// Subsystem depends on the set of public symbol names from linked objects.
// See LinkerDriver::inferSubsystem from the LLD project for the flow chart.
.subsystem = options.subsystem,
.entry = options.entry,
.tsaware = options.tsaware,
.nxcompat = options.nxcompat,
.dynamicbase = options.dynamicbase,
.major_subsystem_version = options.major_subsystem_version orelse 6,
.minor_subsystem_version = options.minor_subsystem_version orelse 0,
.lib_dirs = options.lib_dirs,
.entry_addr = math.cast(u32, options.entry_addr orelse 0) orelse
return error.EntryAddressTooBig,
.module_definition_file = options.module_definition_file,
.pdb_out_path = options.pdb_out_path,
};
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;
}
// What path should this COFF 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),
});
assert(self.llvm_object == null);
const gpa = comp.gpa;
try self.strtab.buffer.ensureUnusedCapacity(gpa, @sizeOf(u32));
self.strtab.buffer.appendNTimesAssumeCapacity(0, @sizeOf(u32));
try self.temp_strtab.buffer.append(gpa, 0);
// Index 0 is always a null symbol.
try self.locals.append(gpa, .{
.name = [_]u8{0} ** 8,
.value = 0,
.section_number = .UNDEFINED,
.type = .{ .base_type = .NULL, .complex_type = .NULL },
.storage_class = .NULL,
.number_of_aux_symbols = 0,
});
if (self.text_section_index == null) {
const file_size: u32 = @intCast(options.program_code_size_hint);
self.text_section_index = try self.allocateSection(".text", file_size, .{
.CNT_CODE = 1,
.MEM_EXECUTE = 1,
.MEM_READ = 1,
});
}
if (self.got_section_index == null) {
const file_size = @as(u32, @intCast(options.symbol_count_hint)) * self.ptr_width.size();
self.got_section_index = try self.allocateSection(".got", file_size, .{
.CNT_INITIALIZED_DATA = 1,
.MEM_READ = 1,
});
}
if (self.rdata_section_index == null) {
const file_size: u32 = self.page_size;
self.rdata_section_index = try self.allocateSection(".rdata", file_size, .{
.CNT_INITIALIZED_DATA = 1,
.MEM_READ = 1,
});
}
if (self.data_section_index == null) {
const file_size: u32 = self.page_size;
self.data_section_index = try self.allocateSection(".data", file_size, .{
.CNT_INITIALIZED_DATA = 1,
.MEM_READ = 1,
.MEM_WRITE = 1,
});
}
if (self.idata_section_index == null) {
const file_size = @as(u32, @intCast(options.symbol_count_hint)) * self.ptr_width.size();
self.idata_section_index = try self.allocateSection(".idata", file_size, .{
.CNT_INITIALIZED_DATA = 1,
.MEM_READ = 1,
});
}
if (self.reloc_section_index == null) {
const file_size = @as(u32, @intCast(options.symbol_count_hint)) * @sizeOf(coff.BaseRelocation);
self.reloc_section_index = try self.allocateSection(".reloc", file_size, .{
.CNT_INITIALIZED_DATA = 1,
.MEM_DISCARDABLE = 1,
.MEM_READ = 1,
});
}
if (self.strtab_offset == null) {
const file_size = @as(u32, @intCast(self.strtab.buffer.items.len));
self.strtab_offset = self.findFreeSpace(file_size, @alignOf(u32)); // 4bytes aligned seems like a good idea here
log.debug("found strtab free space 0x{x} to 0x{x}", .{ self.strtab_offset.?, self.strtab_offset.? + file_size });
}
{
// We need to find out what the max file offset is according to section headers.
// Otherwise, we may end up with an COFF binary with file size not matching the final section's
// offset + it's filesize.
// TODO I don't like this here one bit
var max_file_offset: u64 = 0;
for (self.sections.items(.header)) |header| {
if (header.pointer_to_raw_data + header.size_of_raw_data > max_file_offset) {
max_file_offset = header.pointer_to_raw_data + header.size_of_raw_data;
}
}
try self.base.file.?.pwriteAll(&[_]u8{0}, max_file_offset);
}
return self;
}
pub fn open(
arena: Allocator,
comp: *Compilation,
emit: Compilation.Emit,
options: link.File.OpenOptions,
) !*Coff {
// 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: *Coff) void {
const gpa = self.base.comp.gpa;
if (self.llvm_object) |llvm_object| llvm_object.deinit();
for (self.objects.items) |*object| {
object.deinit(gpa);
}
self.objects.deinit(gpa);
for (self.sections.items(.free_list)) |*free_list| {
free_list.deinit(gpa);
}
self.sections.deinit(gpa);
self.atoms.deinit(gpa);
self.locals.deinit(gpa);
self.globals.deinit(gpa);
{
var it = self.resolver.keyIterator();
while (it.next()) |key_ptr| {
gpa.free(key_ptr.*);
}
self.resolver.deinit(gpa);
}
self.unresolved.deinit(gpa);
self.locals_free_list.deinit(gpa);
self.globals_free_list.deinit(gpa);
self.strtab.deinit(gpa);
self.temp_strtab.deinit(gpa);
self.got_table.deinit(gpa);
for (self.import_tables.values()) |*itab| {
itab.deinit(gpa);
}
self.import_tables.deinit(gpa);
self.lazy_syms.deinit(gpa);
for (self.decls.values()) |*metadata| {
metadata.deinit(gpa);
}
self.decls.deinit(gpa);
self.atom_by_index_table.deinit(gpa);
for (self.unnamed_const_atoms.values()) |*atoms| {
atoms.deinit(gpa);
}
self.unnamed_const_atoms.deinit(gpa);
{
var it = self.anon_decls.iterator();
while (it.next()) |entry| {
entry.value_ptr.exports.deinit(gpa);
}
self.anon_decls.deinit(gpa);
}
for (self.relocs.values()) |*relocs| {
relocs.deinit(gpa);
}
self.relocs.deinit(gpa);
for (self.base_relocs.values()) |*relocs| {
relocs.deinit(gpa);
}
self.base_relocs.deinit(gpa);
}
fn allocateSection(self: *Coff, name: []const u8, size: u32, flags: coff.SectionHeaderFlags) !u16 {
const index = @as(u16, @intCast(self.sections.slice().len));
const off = self.findFreeSpace(size, default_file_alignment);
// Memory is always allocated in sequence
// TODO: investigate if we can allocate .text last; this way it would never need to grow in memory!
const vaddr = blk: {
if (index == 0) break :blk self.page_size;
const prev_header = self.sections.items(.header)[index - 1];
break :blk mem.alignForward(u32, prev_header.virtual_address + prev_header.virtual_size, self.page_size);
};
// We commit more memory than needed upfront so that we don't have to reallocate too soon.
const memsz = mem.alignForward(u32, size, self.page_size) * 100;
log.debug("found {s} free space 0x{x} to 0x{x} (0x{x} - 0x{x})", .{
name,
off,
off + size,
vaddr,
vaddr + size,
});
var header = coff.SectionHeader{
.name = undefined,
.virtual_size = memsz,
.virtual_address = vaddr,
.size_of_raw_data = size,
.pointer_to_raw_data = off,
.pointer_to_relocations = 0,
.pointer_to_linenumbers = 0,
.number_of_relocations = 0,
.number_of_linenumbers = 0,
.flags = flags,
};
const gpa = self.base.comp.gpa;
try self.setSectionName(&header, name);
try self.sections.append(gpa, .{ .header = header });
return index;
}
fn growSection(self: *Coff, sect_id: u32, needed_size: u32) !void {
const header = &self.sections.items(.header)[sect_id];
const maybe_last_atom_index = self.sections.items(.last_atom_index)[sect_id];
const sect_capacity = self.allocatedSize(header.pointer_to_raw_data);
if (needed_size > sect_capacity) {
const new_offset = self.findFreeSpace(needed_size, default_file_alignment);
const current_size = if (maybe_last_atom_index) |last_atom_index| blk: {
const last_atom = self.getAtom(last_atom_index);
const sym = last_atom.getSymbol(self);
break :blk (sym.value + last_atom.size) - header.virtual_address;
} else 0;
log.debug("moving {s} from 0x{x} to 0x{x}", .{
self.getSectionName(header),
header.pointer_to_raw_data,
new_offset,
});
const amt = try self.base.file.?.copyRangeAll(
header.pointer_to_raw_data,
self.base.file.?,
new_offset,
current_size,
);
if (amt != current_size) return error.InputOutput;
header.pointer_to_raw_data = new_offset;
}
const sect_vm_capacity = self.allocatedVirtualSize(header.virtual_address);
if (needed_size > sect_vm_capacity) {
self.markRelocsDirtyByAddress(header.virtual_address + header.virtual_size);
try self.growSectionVirtualMemory(sect_id, needed_size);
}
header.virtual_size = @max(header.virtual_size, needed_size);
header.size_of_raw_data = needed_size;
}
fn growSectionVirtualMemory(self: *Coff, sect_id: u32, needed_size: u32) !void {
const header = &self.sections.items(.header)[sect_id];
const increased_size = padToIdeal(needed_size);
const old_aligned_end = header.virtual_address + mem.alignForward(u32, header.virtual_size, self.page_size);
const new_aligned_end = header.virtual_address + mem.alignForward(u32, increased_size, self.page_size);
const diff = new_aligned_end - old_aligned_end;
log.debug("growing {s} in virtual memory by {x}", .{ self.getSectionName(header), diff });
// TODO: enforce order by increasing VM addresses in self.sections container.
// This is required by the loader anyhow as far as I can tell.
for (self.sections.items(.header)[sect_id + 1 ..], 0..) |*next_header, next_sect_id| {
const maybe_last_atom_index = self.sections.items(.last_atom_index)[sect_id + 1 + next_sect_id];
next_header.virtual_address += diff;
if (maybe_last_atom_index) |last_atom_index| {
var atom_index = last_atom_index;
while (true) {
const atom = self.getAtom(atom_index);
const sym = atom.getSymbolPtr(self);
sym.value += diff;
if (atom.prev_index) |prev_index| {
atom_index = prev_index;
} else break;
}
}
}
header.virtual_size = increased_size;
}
fn allocateAtom(self: *Coff, atom_index: Atom.Index, new_atom_size: u32, alignment: u32) !u32 {
const tracy = trace(@src());
defer tracy.end();
const atom = self.getAtom(atom_index);
const sect_id = @intFromEnum(atom.getSymbol(self).section_number) - 1;
const header = &self.sections.items(.header)[sect_id];
const free_list = &self.sections.items(.free_list)[sect_id];
const maybe_last_atom_index = &self.sections.items(.last_atom_index)[sect_id];
const new_atom_ideal_capacity = if (header.isCode()) padToIdeal(new_atom_size) else new_atom_size;
// We use these to indicate our intention to update metadata, placing the new atom,
// and possibly removing a free list node.
// It would be simpler to do it inside the for loop below, but that would cause a
// problem if an error was returned later in the function. So this action
// is actually carried out at the end of the function, when errors are no longer possible.
var atom_placement: ?Atom.Index = null;
var free_list_removal: ?usize = null;
// First we look for an appropriately sized free list node.
// The list is unordered. We'll just take the first thing that works.
const vaddr = blk: {
var i: usize = 0;
while (i < free_list.items.len) {
const big_atom_index = free_list.items[i];
const big_atom = self.getAtom(big_atom_index);
// We now have a pointer to a live atom that has too much capacity.
// Is it enough that we could fit this new atom?
const sym = big_atom.getSymbol(self);
const capacity = big_atom.capacity(self);
const ideal_capacity = if (header.isCode()) padToIdeal(capacity) else capacity;
const ideal_capacity_end_vaddr = math.add(u32, sym.value, ideal_capacity) catch ideal_capacity;
const capacity_end_vaddr = sym.value + capacity;
const new_start_vaddr_unaligned = capacity_end_vaddr - new_atom_ideal_capacity;
const new_start_vaddr = mem.alignBackward(u32, new_start_vaddr_unaligned, alignment);
if (new_start_vaddr < ideal_capacity_end_vaddr) {
// Additional bookkeeping here to notice if this free list node
// should be deleted because the atom that it points to has grown to take up
// more of the extra capacity.
if (!big_atom.freeListEligible(self)) {
_ = free_list.swapRemove(i);
} else {
i += 1;
}
continue;
}
// At this point we know that we will place the new atom here. But the
// remaining question is whether there is still yet enough capacity left
// over for there to still be a free list node.
const remaining_capacity = new_start_vaddr - ideal_capacity_end_vaddr;
const keep_free_list_node = remaining_capacity >= min_text_capacity;
// Set up the metadata to be updated, after errors are no longer possible.
atom_placement = big_atom_index;
if (!keep_free_list_node) {
free_list_removal = i;
}
break :blk new_start_vaddr;
} else if (maybe_last_atom_index.*) |last_index| {
const last = self.getAtom(last_index);
const last_symbol = last.getSymbol(self);
const ideal_capacity = if (header.isCode()) padToIdeal(last.size) else last.size;
const ideal_capacity_end_vaddr = last_symbol.value + ideal_capacity;
const new_start_vaddr = mem.alignForward(u32, ideal_capacity_end_vaddr, alignment);
atom_placement = last_index;
break :blk new_start_vaddr;
} else {
break :blk mem.alignForward(u32, header.virtual_address, alignment);
}
};
const expand_section = if (atom_placement) |placement_index|
self.getAtom(placement_index).next_index == null
else
true;
if (expand_section) {
const needed_size: u32 = (vaddr + new_atom_size) - header.virtual_address;
try self.growSection(sect_id, needed_size);
maybe_last_atom_index.* = atom_index;
}
self.getAtomPtr(atom_index).size = new_atom_size;
if (atom.prev_index) |prev_index| {
const prev = self.getAtomPtr(prev_index);
prev.next_index = atom.next_index;
}
if (atom.next_index) |next_index| {
const next = self.getAtomPtr(next_index);
next.prev_index = atom.prev_index;
}
if (atom_placement) |big_atom_index| {
const big_atom = self.getAtomPtr(big_atom_index);
const atom_ptr = self.getAtomPtr(atom_index);
atom_ptr.prev_index = big_atom_index;
atom_ptr.next_index = big_atom.next_index;
big_atom.next_index = atom_index;
} else {
const atom_ptr = self.getAtomPtr(atom_index);
atom_ptr.prev_index = null;
atom_ptr.next_index = null;
}
if (free_list_removal) |i| {
_ = free_list.swapRemove(i);
}
return vaddr;
}
pub fn allocateSymbol(self: *Coff) !u32 {
const gpa = self.base.comp.gpa;
try self.locals.ensureUnusedCapacity(gpa, 1);
const index = blk: {
if (self.locals_free_list.popOrNull()) |index| {
log.debug(" (reusing symbol index {d})", .{index});
break :blk index;
} else {
log.debug(" (allocating symbol index {d})", .{self.locals.items.len});
const index = @as(u32, @intCast(self.locals.items.len));
_ = self.locals.addOneAssumeCapacity();
break :blk index;
}
};
self.locals.items[index] = .{
.name = [_]u8{0} ** 8,
.value = 0,
.section_number = .UNDEFINED,
.type = .{ .base_type = .NULL, .complex_type = .NULL },
.storage_class = .NULL,
.number_of_aux_symbols = 0,
};
return index;
}
fn allocateGlobal(self: *Coff) !u32 {
const gpa = self.base.comp.gpa;
try self.globals.ensureUnusedCapacity(gpa, 1);
const index = blk: {
if (self.globals_free_list.popOrNull()) |index| {
log.debug(" (reusing global index {d})", .{index});
break :blk index;
} else {
log.debug(" (allocating global index {d})", .{self.globals.items.len});
const index = @as(u32, @intCast(self.globals.items.len));
_ = self.globals.addOneAssumeCapacity();
break :blk index;
}
};
self.globals.items[index] = .{
.sym_index = 0,
.file = null,
};
return index;
}
fn addGotEntry(self: *Coff, target: SymbolWithLoc) !void {
const gpa = self.base.comp.gpa;
if (self.got_table.lookup.contains(target)) return;
const got_index = try self.got_table.allocateEntry(gpa, target);
try self.writeOffsetTableEntry(got_index);
self.got_table_count_dirty = true;
self.markRelocsDirtyByTarget(target);
}
pub fn createAtom(self: *Coff) !Atom.Index {
const gpa = self.base.comp.gpa;
const atom_index = @as(Atom.Index, @intCast(self.atoms.items.len));
const atom = try self.atoms.addOne(gpa);
const sym_index = try self.allocateSymbol();
try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom_index);
atom.* = .{
.sym_index = sym_index,
.file = null,
.size = 0,
.prev_index = null,
.next_index = null,
};
log.debug("creating ATOM(%{d}) at index {d}", .{ sym_index, atom_index });
return atom_index;
}
fn growAtom(self: *Coff, atom_index: Atom.Index, new_atom_size: u32, alignment: u32) !u32 {
const atom = self.getAtom(atom_index);
const sym = atom.getSymbol(self);
const align_ok = mem.alignBackward(u32, sym.value, alignment) == sym.value;
const need_realloc = !align_ok or new_atom_size > atom.capacity(self);
if (!need_realloc) return sym.value;
return self.allocateAtom(atom_index, new_atom_size, alignment);
}
fn shrinkAtom(self: *Coff, atom_index: Atom.Index, new_block_size: u32) void {
_ = self;
_ = atom_index;
_ = new_block_size;
// TODO check the new capacity, and if it crosses the size threshold into a big enough
// capacity, insert a free list node for it.
}
fn writeAtom(self: *Coff, atom_index: Atom.Index, code: []u8) !void {
const atom = self.getAtom(atom_index);
const sym = atom.getSymbol(self);
const section = self.sections.get(@intFromEnum(sym.section_number) - 1);
const file_offset = section.header.pointer_to_raw_data + sym.value - section.header.virtual_address;
log.debug("writing atom for symbol {s} at file offset 0x{x} to 0x{x}", .{
atom.getName(self),
file_offset,
file_offset + code.len,
});
const gpa = self.base.comp.gpa;
// Gather relocs which can be resolved.
// We need to do this as we will be applying different slide values depending
// if we are running in hot-code swapping mode or not.
// TODO: how crazy would it be to try and apply the actual image base of the loaded
// process for the in-file values rather than the Windows defaults?
var relocs = std.ArrayList(*Relocation).init(gpa);
defer relocs.deinit();
if (self.relocs.getPtr(atom_index)) |rels| {
try relocs.ensureTotalCapacityPrecise(rels.items.len);
for (rels.items) |*reloc| {
if (reloc.isResolvable(self) and reloc.dirty) {
relocs.appendAssumeCapacity(reloc);
}
}
}
if (is_hot_update_compatible) {
if (self.base.child_pid) |handle| {
const slide = @intFromPtr(self.hot_state.loaded_base_address.?);
const mem_code = try gpa.dupe(u8, code);
defer gpa.free(mem_code);
self.resolveRelocs(atom_index, relocs.items, mem_code, slide);
const vaddr = sym.value + slide;
const pvaddr = @as(*anyopaque, @ptrFromInt(vaddr));
log.debug("writing to memory at address {x}", .{vaddr});
if (build_options.enable_logging) {
try debugMem(gpa, handle, pvaddr, mem_code);
}
if (section.header.flags.MEM_WRITE == 0) {
writeMemProtected(handle, pvaddr, mem_code) catch |err| {
log.warn("writing to protected memory failed with error: {s}", .{@errorName(err)});
};
} else {
writeMem(handle, pvaddr, mem_code) catch |err| {
log.warn("writing to protected memory failed with error: {s}", .{@errorName(err)});
};
}
}
}
self.resolveRelocs(atom_index, relocs.items, code, self.image_base);
try self.base.file.?.pwriteAll(code, file_offset);
// Now we can mark the relocs as resolved.
while (relocs.popOrNull()) |reloc| {
reloc.dirty = false;
}
}
fn debugMem(allocator: Allocator, handle: std.ChildProcess.Id, pvaddr: std.os.windows.LPVOID, code: []const u8) !void {
const buffer = try allocator.alloc(u8, code.len);
defer allocator.free(buffer);
const memread = try std.os.windows.ReadProcessMemory(handle, pvaddr, buffer);
log.debug("to write: {x}", .{std.fmt.fmtSliceHexLower(code)});
log.debug("in memory: {x}", .{std.fmt.fmtSliceHexLower(memread)});
}
fn writeMemProtected(handle: std.ChildProcess.Id, pvaddr: std.os.windows.LPVOID, code: []const u8) !void {
const old_prot = try std.os.windows.VirtualProtectEx(handle, pvaddr, code.len, std.os.windows.PAGE_EXECUTE_WRITECOPY);
try writeMem(handle, pvaddr, code);
// TODO: We can probably just set the pages writeable and leave it at that without having to restore the attributes.
// For that though, we want to track which page has already been modified.
_ = try std.os.windows.VirtualProtectEx(handle, pvaddr, code.len, old_prot);
}
fn writeMem(handle: std.ChildProcess.Id, pvaddr: std.os.windows.LPVOID, code: []const u8) !void {
const amt = try std.os.windows.WriteProcessMemory(handle, pvaddr, code);
if (amt != code.len) return error.InputOutput;
}
fn writeOffsetTableEntry(self: *Coff, index: usize) !void {
const sect_id = self.got_section_index.?;
if (self.got_table_count_dirty) {
const needed_size = @as(u32, @intCast(self.got_table.entries.items.len * self.ptr_width.size()));
try self.growSection(sect_id, needed_size);
self.got_table_count_dirty = false;
}
const header = &self.sections.items(.header)[sect_id];
const entry = self.got_table.entries.items[index];
const entry_value = self.getSymbol(entry).value;
const entry_offset = index * self.ptr_width.size();
const file_offset = header.pointer_to_raw_data + entry_offset;
const vmaddr = header.virtual_address + entry_offset;
log.debug("writing GOT entry {d}: @{x} => {x}", .{ index, vmaddr, entry_value + self.image_base });
switch (self.ptr_width) {
.p32 => {
var buf: [4]u8 = undefined;
mem.writeInt(u32, &buf, @as(u32, @intCast(entry_value + self.image_base)), .little);
try self.base.file.?.pwriteAll(&buf, file_offset);
},
.p64 => {
var buf: [8]u8 = undefined;
mem.writeInt(u64, &buf, entry_value + self.image_base, .little);
try self.base.file.?.pwriteAll(&buf, file_offset);
},
}
if (is_hot_update_compatible) {
if (self.base.child_pid) |handle| {
const gpa = self.base.comp.gpa;
const slide = @intFromPtr(self.hot_state.loaded_base_address.?);
const actual_vmaddr = vmaddr + slide;
const pvaddr = @as(*anyopaque, @ptrFromInt(actual_vmaddr));
log.debug("writing GOT entry to memory at address {x}", .{actual_vmaddr});
if (build_options.enable_logging) {
switch (self.ptr_width) {
.p32 => {
var buf: [4]u8 = undefined;
try debugMem(gpa, handle, pvaddr, &buf);
},
.p64 => {
var buf: [8]u8 = undefined;
try debugMem(gpa, handle, pvaddr, &buf);
},
}
}
switch (self.ptr_width) {
.p32 => {
var buf: [4]u8 = undefined;
mem.writeInt(u32, &buf, @as(u32, @intCast(entry_value + slide)), .little);
writeMem(handle, pvaddr, &buf) catch |err| {
log.warn("writing to protected memory failed with error: {s}", .{@errorName(err)});
};
},
.p64 => {
var buf: [8]u8 = undefined;
mem.writeInt(u64, &buf, entry_value + slide, .little);
writeMem(handle, pvaddr, &buf) catch |err| {
log.warn("writing to protected memory failed with error: {s}", .{@errorName(err)});
};
},
}
}
}
}
fn markRelocsDirtyByTarget(self: *Coff, target: SymbolWithLoc) void {
// TODO: reverse-lookup might come in handy here
for (self.relocs.values()) |*relocs| {
for (relocs.items) |*reloc| {
if (!reloc.target.eql(target)) continue;
reloc.dirty = true;
}
}
}
fn markRelocsDirtyByAddress(self: *Coff, addr: u32) void {
const got_moved = blk: {
const sect_id = self.got_section_index orelse break :blk false;