Repository navigation
Expand file tree
/
Copy pathWasm.zig
More file actions
2773 lines (2464 loc) · 109 KB
/
Copy pathWasm.zig
File metadata and controls
2773 lines (2464 loc) · 109 KB
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 Wasm = @This();
const std = @import("std");
const builtin = @import("builtin");
const mem = std.mem;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const fs = std.fs;
const leb = std.leb;
const log = std.log.scoped(.link);
const wasm = std.wasm;
const Atom = @import("Wasm/Atom.zig");
const Module = @import("../Module.zig");
const Compilation = @import("../Compilation.zig");
const CodeGen = @import("../arch/wasm/CodeGen.zig");
const codegen = @import("../codegen.zig");
const link = @import("../link.zig");
const lldMain = @import("../main.zig").lldMain;
const trace = @import("../tracy.zig").trace;
const build_options = @import("build_options");
const wasi_libc = @import("../wasi_libc.zig");
const Cache = @import("../Cache.zig");
const Type = @import("../type.zig").Type;
const TypedValue = @import("../TypedValue.zig");
const LlvmObject = @import("../codegen/llvm.zig").Object;
const Air = @import("../Air.zig");
const Liveness = @import("../Liveness.zig");
const Symbol = @import("Wasm/Symbol.zig");
const Object = @import("Wasm/Object.zig");
const types = @import("Wasm/types.zig");
pub const base_tag = link.File.Tag.wasm;
/// deprecated: Use `@import("Wasm/Atom.zig");`
pub const DeclBlock = Atom;
base: link.File,
/// Output name of the file
name: []const u8,
/// If this is not null, an object file is created by LLVM and linked with LLD afterwards.
llvm_object: ?*LlvmObject = null,
/// When importing objects from the host environment, a name must be supplied.
/// LLVM uses "env" by default when none is given. This would be a good default for Zig
/// to support existing code.
/// TODO: Allow setting this through a flag?
host_name: []const u8 = "env",
/// List of all `Decl` that are currently alive.
/// This is ment for bookkeeping so we can safely cleanup all codegen memory
/// when calling `deinit`
decls: std.AutoHashMapUnmanaged(Module.Decl.Index, void) = .{},
/// List of all symbols generated by Zig code.
symbols: std.ArrayListUnmanaged(Symbol) = .{},
/// List of symbol indexes which are free to be used.
symbols_free_list: std.ArrayListUnmanaged(u32) = .{},
/// Maps atoms to their segment index
atoms: std.AutoHashMapUnmanaged(u32, *Atom) = .{},
/// Atoms managed and created by the linker. This contains atoms
/// from object files, and not Atoms generated by a Decl.
managed_atoms: std.ArrayListUnmanaged(*Atom) = .{},
/// Represents the index into `segments` where the 'code' section
/// lives.
code_section_index: ?u32 = null,
/// The count of imported functions. This number will be appended
/// to the function indexes as their index starts at the lowest non-extern function.
imported_functions_count: u32 = 0,
/// The count of imported wasm globals. This number will be appended
/// to the global indexes when sections are merged.
imported_globals_count: u32 = 0,
/// The count of imported tables. This number will be appended
/// to the table indexes when sections are merged.
imported_tables_count: u32 = 0,
/// Map of symbol locations, represented by its `types.Import`
imports: std.AutoHashMapUnmanaged(SymbolLoc, types.Import) = .{},
/// Represents non-synthetic section entries.
/// Used for code, data and custom sections.
segments: std.ArrayListUnmanaged(Segment) = .{},
/// Maps a data segment key (such as .rodata) to the index into `segments`.
data_segments: std.StringArrayHashMapUnmanaged(u32) = .{},
/// A list of `types.Segment` which provide meta data
/// about a data symbol such as its name
segment_info: std.ArrayListUnmanaged(types.Segment) = .{},
/// Deduplicated string table for strings used by symbols, imports and exports.
string_table: StringTable = .{},
// Output sections
/// Output type section
func_types: std.ArrayListUnmanaged(wasm.Type) = .{},
/// Output function section
functions: std.ArrayListUnmanaged(wasm.Func) = .{},
/// Output global section
wasm_globals: std.ArrayListUnmanaged(wasm.Global) = .{},
/// Memory section
memories: wasm.Memory = .{ .limits = .{ .min = 0, .max = null } },
/// Output table section
tables: std.ArrayListUnmanaged(wasm.Table) = .{},
/// Output export section
exports: std.ArrayListUnmanaged(types.Export) = .{},
/// Indirect function table, used to call function pointers
/// When this is non-zero, we must emit a table entry,
/// as well as an 'elements' section.
///
/// Note: Key is symbol location, value represents the index into the table
function_table: std.AutoHashMapUnmanaged(SymbolLoc, u32) = .{},
/// All object files and their data which are linked into the final binary
objects: std.ArrayListUnmanaged(Object) = .{},
/// A map of global names (read: offset into string table) to their symbol location
globals: std.AutoHashMapUnmanaged(u32, SymbolLoc) = .{},
/// Maps discarded symbols and their positions to the location of the symbol
/// it was resolved to
discarded: std.AutoHashMapUnmanaged(SymbolLoc, SymbolLoc) = .{},
/// List of all symbol locations which have been resolved by the linker and will be emit
/// into the final binary.
resolved_symbols: std.AutoArrayHashMapUnmanaged(SymbolLoc, void) = .{},
/// Maps a symbol's location to an atom. This can be used to find meta
/// data of a symbol, such as its size, or its offset to perform a relocation.
/// Undefined (and synthetic) symbols do not have an Atom and therefore cannot be mapped.
symbol_atom: std.AutoHashMapUnmanaged(SymbolLoc, *Atom) = .{},
/// Maps a symbol's location to its export name, which may differ from the decl's name
/// which does the exporting.
/// Note: The value represents the offset into the string table, rather than the actual string.
export_names: std.AutoHashMapUnmanaged(SymbolLoc, u32) = .{},
/// Represents the symbol index of the error name table
/// When this is `null`, no code references an error using runtime `@errorName`.
/// During initializion, a symbol with corresponding atom will be created that is
/// used to perform relocations to the pointer of this table.
/// The actual table is populated during `flush`.
error_table_symbol: ?u32 = null,
pub const Segment = struct {
alignment: u32,
size: u32,
offset: u32,
};
pub const FnData = struct {
type_index: u32,
pub const empty: FnData = .{
.type_index = undefined,
};
};
pub const Export = struct {
sym_index: ?u32 = null,
};
pub const SymbolLoc = struct {
/// The index of the symbol within the specified file
index: u32,
/// The index of the object file where the symbol resides.
/// When this is `null` the symbol comes from a non-object file.
file: ?u16,
/// From a given location, returns the corresponding symbol in the wasm binary
pub fn getSymbol(self: SymbolLoc, wasm_bin: *const Wasm) *Symbol {
if (wasm_bin.discarded.get(self)) |new_loc| {
return new_loc.getSymbol(wasm_bin);
}
if (self.file) |object_index| {
const object = wasm_bin.objects.items[object_index];
return &object.symtable[self.index];
}
return &wasm_bin.symbols.items[self.index];
}
/// From a given location, returns the name of the symbol.
pub fn getName(self: SymbolLoc, wasm_bin: *const Wasm) []const u8 {
if (wasm_bin.discarded.get(self)) |new_loc| {
return new_loc.getName(wasm_bin);
}
if (self.file) |object_index| {
const object = wasm_bin.objects.items[object_index];
return object.string_table.get(object.symtable[self.index].name);
}
return wasm_bin.string_table.get(wasm_bin.symbols.items[self.index].name);
}
};
/// Generic string table that duplicates strings
/// and converts them into offsets instead.
pub const StringTable = struct {
/// Table that maps string offsets, which is used to de-duplicate strings.
/// Rather than having the offset map to the data, the `StringContext` holds all bytes of the string.
/// The strings are stored as a contigious array where each string is zero-terminated.
string_table: std.HashMapUnmanaged(
u32,
void,
std.hash_map.StringIndexContext,
std.hash_map.default_max_load_percentage,
) = .{},
/// Holds the actual data of the string table.
string_data: std.ArrayListUnmanaged(u8) = .{},
/// Accepts a string and searches for a corresponding string.
/// When found, de-duplicates the string and returns the existing offset instead.
/// When the string is not found in the `string_table`, a new entry will be inserted
/// and the new offset to its data will be returned.
pub fn put(self: *StringTable, allocator: Allocator, string: []const u8) !u32 {
const gop = try self.string_table.getOrPutContextAdapted(
allocator,
string,
std.hash_map.StringIndexAdapter{ .bytes = &self.string_data },
.{ .bytes = &self.string_data },
);
if (gop.found_existing) {
const off = gop.key_ptr.*;
log.debug("reusing string '{s}' at offset 0x{x}", .{ string, off });
return off;
}
try self.string_data.ensureUnusedCapacity(allocator, string.len + 1);
const offset = @intCast(u32, self.string_data.items.len);
log.debug("writing new string '{s}' at offset 0x{x}", .{ string, offset });
self.string_data.appendSliceAssumeCapacity(string);
self.string_data.appendAssumeCapacity(0);
gop.key_ptr.* = offset;
return offset;
}
/// From a given offset, returns its corresponding string value.
/// Asserts offset does not exceed bounds.
pub fn get(self: StringTable, off: u32) []const u8 {
assert(off < self.string_data.items.len);
return mem.sliceTo(@ptrCast([*:0]const u8, self.string_data.items.ptr + off), 0);
}
/// Returns the offset of a given string when it exists.
/// Will return null if the given string does not yet exist within the string table.
pub fn getOffset(self: *StringTable, string: []const u8) ?u32 {
return self.string_table.getKeyAdapted(
string,
std.hash_map.StringIndexAdapter{ .bytes = &self.string_data },
);
}
/// Frees all resources of the string table. Any references pointing
/// to the strings will be invalid.
pub fn deinit(self: *StringTable, allocator: Allocator) void {
self.string_data.deinit(allocator);
self.string_table.deinit(allocator);
self.* = undefined;
}
};
pub fn openPath(allocator: Allocator, sub_path: []const u8, options: link.Options) !*Wasm {
assert(options.object_format == .wasm);
if (build_options.have_llvm and options.use_llvm) {
return createEmpty(allocator, options);
}
const wasm_bin = try createEmpty(allocator, options);
errdefer wasm_bin.base.destroy();
// TODO: read the file and keep valid parts instead of truncating
const file = try options.emit.?.directory.handle.createFile(sub_path, .{ .truncate = true, .read = true });
wasm_bin.base.file = file;
wasm_bin.name = sub_path;
try file.writeAll(&(wasm.magic ++ wasm.version));
// As sym_index '0' is reserved, we use it for our stack pointer symbol
const sym_name = try wasm_bin.string_table.put(allocator, "__stack_pointer");
const symbol = try wasm_bin.symbols.addOne(allocator);
symbol.* = .{
.name = sym_name,
.tag = .global,
.flags = 0,
.index = 0,
};
const loc: SymbolLoc = .{ .file = null, .index = 0 };
try wasm_bin.resolved_symbols.putNoClobber(allocator, loc, {});
try wasm_bin.globals.putNoClobber(allocator, sym_name, loc);
// For object files we will import the stack pointer symbol
if (options.output_mode == .Obj) {
symbol.setUndefined(true);
try wasm_bin.imports.putNoClobber(
allocator,
.{ .file = null, .index = 0 },
.{
.module_name = try wasm_bin.string_table.put(allocator, wasm_bin.host_name),
.name = sym_name,
.kind = .{ .global = .{ .valtype = .i32, .mutable = true } },
},
);
} else {
symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN);
const global = try wasm_bin.wasm_globals.addOne(allocator);
global.* = .{
.global_type = .{
.valtype = .i32,
.mutable = true,
},
.init = .{ .i32_const = 0 },
};
}
return wasm_bin;
}
pub fn createEmpty(gpa: Allocator, options: link.Options) !*Wasm {
const self = try gpa.create(Wasm);
errdefer gpa.destroy(self);
self.* = .{
.base = .{
.tag = .wasm,
.options = options,
.file = null,
.allocator = gpa,
},
.name = undefined,
};
const use_llvm = build_options.have_llvm and options.use_llvm;
const use_stage1 = build_options.is_stage1 and options.use_stage1;
if (use_llvm and !use_stage1) {
self.llvm_object = try LlvmObject.create(gpa, options);
}
return self;
}
fn parseInputFiles(self: *Wasm, files: []const []const u8) !void {
for (files) |path| {
if (try self.parseObjectFile(path)) continue;
log.warn("Unexpected file format at path: '{s}'", .{path});
}
}
/// Parses the object file from given path. Returns true when the given file was an object
/// file and parsed successfully. Returns false when file is not an object file.
/// May return an error instead when parsing failed.
fn parseObjectFile(self: *Wasm, path: []const u8) !bool {
const file = try fs.cwd().openFile(path, .{});
errdefer file.close();
var object = Object.create(self.base.allocator, file, path) catch |err| switch (err) {
error.InvalidMagicByte, error.NotObjectFile => {
log.warn("Self hosted linker does not support non-object file parsing: {s}", .{@errorName(err)});
return false;
},
else => |e| return e,
};
errdefer object.deinit(self.base.allocator);
try self.objects.append(self.base.allocator, object);
return true;
}
fn resolveSymbolsInObject(self: *Wasm, object_index: u16) !void {
const object: Object = self.objects.items[object_index];
log.debug("Resolving symbols in object: '{s}'", .{object.name});
for (object.symtable) |symbol, i| {
const sym_index = @intCast(u32, i);
const location: SymbolLoc = .{
.file = object_index,
.index = sym_index,
};
const sym_name = object.string_table.get(symbol.name);
if (mem.eql(u8, sym_name, "__indirect_function_table")) {
continue;
}
const sym_name_index = try self.string_table.put(self.base.allocator, sym_name);
if (symbol.isLocal()) {
if (symbol.isUndefined()) {
log.err("Local symbols are not allowed to reference imports", .{});
log.err(" symbol '{s}' defined in '{s}'", .{ sym_name, object.name });
return error.undefinedLocal;
}
try self.resolved_symbols.putNoClobber(self.base.allocator, location, {});
continue;
}
// TODO: locals are allowed to have duplicate symbol names
// TODO: Store undefined symbols so we can verify at the end if they've all been found
// if not, emit an error (unless --allow-undefined is enabled).
const maybe_existing = try self.globals.getOrPut(self.base.allocator, sym_name_index);
if (!maybe_existing.found_existing) {
maybe_existing.value_ptr.* = location;
try self.resolved_symbols.putNoClobber(self.base.allocator, location, {});
continue;
}
const existing_loc = maybe_existing.value_ptr.*;
const existing_sym: *Symbol = existing_loc.getSymbol(self);
const existing_file_path = if (existing_loc.file) |file| blk: {
break :blk self.objects.items[file].name;
} else self.name;
if (!existing_sym.isUndefined()) {
if (!symbol.isUndefined()) {
log.err("symbol '{s}' defined multiple times", .{sym_name});
log.err(" first definition in '{s}'", .{existing_file_path});
log.err(" next definition in '{s}'", .{object.name});
return error.SymbolCollision;
}
continue; // Do not overwrite defined symbols with undefined symbols
}
// when both symbols are weak, we skip overwriting
if (existing_sym.isWeak() and symbol.isWeak()) {
continue;
}
// simply overwrite with the new symbol
log.debug("Overwriting symbol '{s}'", .{sym_name});
log.debug(" old definition in '{s}'", .{existing_file_path});
log.debug(" new definition in '{s}'", .{object.name});
try self.discarded.putNoClobber(self.base.allocator, maybe_existing.value_ptr.*, location);
maybe_existing.value_ptr.* = location;
try self.globals.put(self.base.allocator, sym_name_index, location);
try self.resolved_symbols.put(self.base.allocator, location, {});
assert(self.resolved_symbols.swapRemove(existing_loc));
}
}
pub fn deinit(self: *Wasm) void {
const gpa = self.base.allocator;
if (build_options.have_llvm) {
if (self.llvm_object) |llvm_object| llvm_object.destroy(gpa);
}
if (self.base.options.module) |mod| {
var decl_it = self.decls.keyIterator();
while (decl_it.next()) |decl_index_ptr| {
const decl = mod.declPtr(decl_index_ptr.*);
decl.link.wasm.deinit(gpa);
}
} else {
assert(self.decls.count() == 0);
}
for (self.func_types.items) |*func_type| {
func_type.deinit(gpa);
}
for (self.segment_info.items) |segment_info| {
gpa.free(segment_info.name);
}
for (self.objects.items) |*object| {
object.file.?.close();
object.deinit(gpa);
}
self.decls.deinit(gpa);
self.symbols.deinit(gpa);
self.symbols_free_list.deinit(gpa);
self.globals.deinit(gpa);
self.resolved_symbols.deinit(gpa);
self.discarded.deinit(gpa);
self.symbol_atom.deinit(gpa);
self.export_names.deinit(gpa);
self.atoms.deinit(gpa);
for (self.managed_atoms.items) |managed_atom| {
managed_atom.deinit(gpa);
gpa.destroy(managed_atom);
}
self.managed_atoms.deinit(gpa);
self.segments.deinit(gpa);
self.data_segments.deinit(gpa);
self.segment_info.deinit(gpa);
self.objects.deinit(gpa);
// free output sections
self.imports.deinit(gpa);
self.func_types.deinit(gpa);
self.functions.deinit(gpa);
self.wasm_globals.deinit(gpa);
self.function_table.deinit(gpa);
self.tables.deinit(gpa);
self.exports.deinit(gpa);
self.string_table.deinit(gpa);
}
pub fn allocateDeclIndexes(self: *Wasm, decl_index: Module.Decl.Index) !void {
if (self.llvm_object) |_| return;
const decl = self.base.options.module.?.declPtr(decl_index);
if (decl.link.wasm.sym_index != 0) return;
try self.symbols.ensureUnusedCapacity(self.base.allocator, 1);
try self.decls.putNoClobber(self.base.allocator, decl_index, {});
const atom = &decl.link.wasm;
var symbol: Symbol = .{
.name = undefined, // will be set after updateDecl
.flags = @enumToInt(Symbol.Flag.WASM_SYM_BINDING_LOCAL),
.tag = undefined, // will be set after updateDecl
.index = undefined, // will be set after updateDecl
};
if (self.symbols_free_list.popOrNull()) |index| {
atom.sym_index = index;
self.symbols.items[index] = symbol;
} else {
atom.sym_index = @intCast(u32, self.symbols.items.len);
self.symbols.appendAssumeCapacity(symbol);
}
try self.symbol_atom.putNoClobber(self.base.allocator, atom.symbolLoc(), atom);
}
pub fn updateFunc(self: *Wasm, mod: *Module, func: *Module.Fn, air: Air, liveness: Liveness) !void {
if (build_options.skip_non_native and builtin.object_format != .wasm) {
@panic("Attempted to compile for object format that was disabled by build configuration");
}
if (build_options.have_llvm) {
if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(mod, func, air, liveness);
}
const decl_index = func.owner_decl;
const decl = mod.declPtr(decl_index);
assert(decl.link.wasm.sym_index != 0); // Must call allocateDeclIndexes()
decl.link.wasm.clear();
var code_writer = std.ArrayList(u8).init(self.base.allocator);
defer code_writer.deinit();
const result = try codegen.generateFunction(
&self.base,
decl.srcLoc(),
func,
air,
liveness,
&code_writer,
.none,
);
const code = switch (result) {
.appended => code_writer.items,
.fail => |em| {
decl.analysis = .codegen_failure;
try mod.failed_decls.put(mod.gpa, decl_index, em);
return;
},
};
return self.finishUpdateDecl(decl, code);
}
// Generate code for the Decl, storing it in memory to be later written to
// the file on flush().
pub fn updateDecl(self: *Wasm, mod: *Module, decl_index: Module.Decl.Index) !void {
if (build_options.skip_non_native and builtin.object_format != .wasm) {
@panic("Attempted to compile for object format that was disabled by build configuration");
}
if (build_options.have_llvm) {
if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(mod, decl_index);
}
const decl = mod.declPtr(decl_index);
assert(decl.link.wasm.sym_index != 0); // Must call allocateDeclIndexes()
decl.link.wasm.clear();
if (decl.isExtern()) {
return;
}
if (decl.val.castTag(.function)) |_| {
return;
} else if (decl.val.castTag(.extern_fn)) |_| {
return;
}
const val = if (decl.val.castTag(.variable)) |payload| payload.data.init else decl.val;
var code_writer = std.ArrayList(u8).init(self.base.allocator);
defer code_writer.deinit();
const res = try codegen.generateSymbol(
&self.base,
decl.srcLoc(),
.{ .ty = decl.ty, .val = val },
&code_writer,
.none,
.{ .parent_atom_index = decl.link.wasm.sym_index },
);
const code = switch (res) {
.externally_managed => |x| x,
.appended => code_writer.items,
.fail => |em| {
decl.analysis = .codegen_failure;
try mod.failed_decls.put(mod.gpa, decl_index, em);
return;
},
};
return self.finishUpdateDecl(decl, code);
}
fn finishUpdateDecl(self: *Wasm, decl: *Module.Decl, code: []const u8) !void {
if (code.len == 0) return;
const mod = self.base.options.module.?;
const atom: *Atom = &decl.link.wasm;
atom.size = @intCast(u32, code.len);
atom.alignment = decl.ty.abiAlignment(self.base.options.target);
const symbol = &self.symbols.items[atom.sym_index];
const full_name = try decl.getFullyQualifiedName(mod);
defer self.base.allocator.free(full_name);
symbol.name = try self.string_table.put(self.base.allocator, full_name);
try atom.code.appendSlice(self.base.allocator, code);
try self.resolved_symbols.put(self.base.allocator, atom.symbolLoc(), {});
}
/// Lowers a constant typed value to a local symbol and atom.
/// Returns the symbol index of the local
/// The given `decl` is the parent decl whom owns the constant.
pub fn lowerUnnamedConst(self: *Wasm, tv: TypedValue, decl_index: Module.Decl.Index) !u32 {
assert(tv.ty.zigTypeTag() != .Fn); // cannot create local symbols for functions
const mod = self.base.options.module.?;
const decl = mod.declPtr(decl_index);
// Create and initialize a new local symbol and atom
const local_index = decl.link.wasm.locals.items.len;
const fqdn = try decl.getFullyQualifiedName(mod);
defer self.base.allocator.free(fqdn);
const name = try std.fmt.allocPrintZ(self.base.allocator, "__unnamed_{s}_{d}", .{ fqdn, local_index });
defer self.base.allocator.free(name);
var symbol: Symbol = .{
.name = try self.string_table.put(self.base.allocator, name),
.flags = 0,
.tag = .data,
.index = undefined,
};
symbol.setFlag(.WASM_SYM_BINDING_LOCAL);
const atom = try decl.link.wasm.locals.addOne(self.base.allocator);
atom.* = Atom.empty;
atom.alignment = tv.ty.abiAlignment(self.base.options.target);
try self.symbols.ensureUnusedCapacity(self.base.allocator, 1);
if (self.symbols_free_list.popOrNull()) |index| {
atom.sym_index = index;
self.symbols.items[index] = symbol;
} else {
atom.sym_index = @intCast(u32, self.symbols.items.len);
self.symbols.appendAssumeCapacity(symbol);
}
try self.resolved_symbols.putNoClobber(self.base.allocator, atom.symbolLoc(), {});
try self.symbol_atom.putNoClobber(self.base.allocator, atom.symbolLoc(), atom);
var value_bytes = std.ArrayList(u8).init(self.base.allocator);
defer value_bytes.deinit();
const result = try codegen.generateSymbol(
&self.base,
decl.srcLoc(),
tv,
&value_bytes,
.none,
.{
.parent_atom_index = atom.sym_index,
.addend = null,
},
);
const code = switch (result) {
.externally_managed => |x| x,
.appended => value_bytes.items,
.fail => |em| {
decl.analysis = .codegen_failure;
try mod.failed_decls.put(mod.gpa, decl_index, em);
return error.AnalysisFail;
},
};
atom.size = @intCast(u32, code.len);
try atom.code.appendSlice(self.base.allocator, code);
return atom.sym_index;
}
/// For a given decl, find the given symbol index's atom, and create a relocation for the type.
/// Returns the given pointer address
pub fn getDeclVAddr(
self: *Wasm,
decl_index: Module.Decl.Index,
reloc_info: link.File.RelocInfo,
) !u64 {
const mod = self.base.options.module.?;
const decl = mod.declPtr(decl_index);
const target_symbol_index = decl.link.wasm.sym_index;
assert(target_symbol_index != 0);
assert(reloc_info.parent_atom_index != 0);
const atom = self.symbol_atom.get(.{ .file = null, .index = reloc_info.parent_atom_index }).?;
const is_wasm32 = self.base.options.target.cpu.arch == .wasm32;
if (decl.ty.zigTypeTag() == .Fn) {
assert(reloc_info.addend == 0); // addend not allowed for function relocations
// We found a function pointer, so add it to our table,
// as function pointers are not allowed to be stored inside the data section.
// They are instead stored in a function table which are called by index.
try self.addTableFunction(target_symbol_index);
try atom.relocs.append(self.base.allocator, .{
.index = target_symbol_index,
.offset = @intCast(u32, reloc_info.offset),
.relocation_type = if (is_wasm32) .R_WASM_TABLE_INDEX_I32 else .R_WASM_TABLE_INDEX_I64,
});
} else {
try atom.relocs.append(self.base.allocator, .{
.index = target_symbol_index,
.offset = @intCast(u32, reloc_info.offset),
.relocation_type = if (is_wasm32) .R_WASM_MEMORY_ADDR_I32 else .R_WASM_MEMORY_ADDR_I64,
.addend = reloc_info.addend,
});
}
// we do not know the final address at this point,
// as atom allocation will determine the address and relocations
// will calculate and rewrite this. Therefore, we simply return the symbol index
// that was targeted.
return target_symbol_index;
}
pub fn deleteExport(self: *Wasm, exp: Export) void {
if (self.llvm_object) |_| return;
const sym_index = exp.sym_index orelse return;
const loc: SymbolLoc = .{ .file = null, .index = sym_index };
const symbol = loc.getSymbol(self);
const symbol_name = self.string_table.get(symbol.name);
log.debug("Deleting export for decl '{s}'", .{symbol_name});
if (self.export_names.fetchRemove(loc)) |kv| {
assert(self.globals.remove(kv.value));
} else {
assert(self.globals.remove(symbol.name));
}
}
pub fn updateDeclExports(
self: *Wasm,
mod: *Module,
decl_index: Module.Decl.Index,
exports: []const *Module.Export,
) !void {
if (build_options.skip_non_native and builtin.object_format != .wasm) {
@panic("Attempted to compile for object format that was disabled by build configuration");
}
if (build_options.have_llvm) {
if (self.llvm_object) |llvm_object| return llvm_object.updateDeclExports(mod, decl_index, exports);
}
const decl = mod.declPtr(decl_index);
for (exports) |exp| {
if (exp.options.section) |section| {
try mod.failed_exports.putNoClobber(mod.gpa, exp, try Module.ErrorMsg.create(
mod.gpa,
decl.srcLoc(),
"Unimplemented: ExportOptions.section '{s}'",
.{section},
));
continue;
}
const export_name = try self.string_table.put(self.base.allocator, exp.options.name);
if (self.globals.getPtr(export_name)) |existing_loc| {
if (existing_loc.index == decl.link.wasm.sym_index) continue;
const existing_sym: Symbol = existing_loc.getSymbol(self).*;
const exp_is_weak = exp.options.linkage == .Internal or exp.options.linkage == .Weak;
// When both the to-bo-exported symbol and the already existing symbol
// are strong symbols, we have a linker error.
// In the other case we replace one with the other.
if (!exp_is_weak and !existing_sym.isWeak()) {
try mod.failed_exports.put(mod.gpa, exp, try Module.ErrorMsg.create(
mod.gpa,
decl.srcLoc(),
\\LinkError: symbol '{s}' defined multiple times
\\ first definition in '{s}'
\\ next definition in '{s}'
,
.{ exp.options.name, self.name, self.name },
));
continue;
} else if (exp_is_weak) {
continue; // to-be-exported symbol is weak, so we keep the existing symbol
} else {
existing_loc.index = decl.link.wasm.sym_index;
existing_loc.file = null;
exp.link.wasm.sym_index = existing_loc.index;
}
}
const exported_decl = mod.declPtr(exp.exported_decl);
const sym_index = exported_decl.link.wasm.sym_index;
const sym_loc = exported_decl.link.wasm.symbolLoc();
const symbol = sym_loc.getSymbol(self);
switch (exp.options.linkage) {
.Internal => {
symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN);
symbol.setFlag(.WASM_SYM_BINDING_WEAK);
},
.Weak => {
symbol.setFlag(.WASM_SYM_BINDING_WEAK);
},
.Strong => {}, // symbols are strong by default
.LinkOnce => {
try mod.failed_exports.putNoClobber(mod.gpa, exp, try Module.ErrorMsg.create(
mod.gpa,
decl.srcLoc(),
"Unimplemented: LinkOnce",
.{},
));
continue;
},
}
// Ensure the symbol will be exported using the given name
if (!mem.eql(u8, exp.options.name, sym_loc.getName(self))) {
try self.export_names.put(self.base.allocator, sym_loc, export_name);
}
symbol.setGlobal(true);
try self.globals.put(
self.base.allocator,
export_name,
sym_loc,
);
// if the symbol was previously undefined, remove it as an import
_ = self.imports.remove(sym_loc);
exp.link.wasm.sym_index = sym_index;
}
}
pub fn freeDecl(self: *Wasm, decl_index: Module.Decl.Index) void {
if (build_options.have_llvm) {
if (self.llvm_object) |llvm_object| return llvm_object.freeDecl(decl_index);
}
const mod = self.base.options.module.?;
const decl = mod.declPtr(decl_index);
const atom = &decl.link.wasm;
self.symbols_free_list.append(self.base.allocator, atom.sym_index) catch {};
_ = self.decls.remove(decl_index);
self.symbols.items[atom.sym_index].tag = .dead;
for (atom.locals.items) |local_atom| {
const local_symbol = &self.symbols.items[local_atom.sym_index];
local_symbol.tag = .dead; // also for any local symbol
self.symbols_free_list.append(self.base.allocator, local_atom.sym_index) catch {};
assert(self.resolved_symbols.swapRemove(local_atom.symbolLoc()));
assert(self.symbol_atom.remove(local_atom.symbolLoc()));
}
if (decl.isExtern()) {
_ = self.imports.remove(atom.symbolLoc());
}
_ = self.resolved_symbols.swapRemove(atom.symbolLoc());
_ = self.symbol_atom.remove(atom.symbolLoc());
atom.deinit(self.base.allocator);
}
/// Appends a new entry to the indirect function table
pub fn addTableFunction(self: *Wasm, symbol_index: u32) !void {
const index = @intCast(u32, self.function_table.count());
try self.function_table.put(self.base.allocator, .{ .file = null, .index = symbol_index }, index);
}
/// Assigns indexes to all indirect functions.
/// Starts at offset 1, where the value `0` represents an unresolved function pointer
/// or null-pointer
fn mapFunctionTable(self: *Wasm) void {
var it = self.function_table.valueIterator();
var index: u32 = 1;
while (it.next()) |value_ptr| : (index += 1) {
value_ptr.* = index;
}
}
pub fn addOrUpdateImport(self: *Wasm, decl: *Module.Decl) !void {
// For the import name itself, we use the decl's name, rather than the fully qualified name
const decl_name_index = try self.string_table.put(self.base.allocator, mem.sliceTo(decl.name, 0));
const symbol_index = decl.link.wasm.sym_index;
const symbol: *Symbol = &self.symbols.items[symbol_index];
symbol.setUndefined(true);
symbol.setGlobal(true);
const global_gop = try self.globals.getOrPut(self.base.allocator, decl_name_index);
if (!global_gop.found_existing) {
const loc: SymbolLoc = .{ .file = null, .index = symbol_index };
global_gop.value_ptr.* = loc;
try self.resolved_symbols.put(self.base.allocator, loc, {});
}
switch (decl.ty.zigTypeTag()) {
.Fn => {
const gop = try self.imports.getOrPut(self.base.allocator, .{ .index = symbol_index, .file = null });
const module_name = if (decl.getExternFn().?.lib_name) |lib_name| blk: {
break :blk mem.sliceTo(lib_name, 0);
} else self.host_name;
if (!gop.found_existing) {
gop.value_ptr.* = .{
.module_name = try self.string_table.put(self.base.allocator, module_name),
.name = decl_name_index,
.kind = .{ .function = decl.fn_link.wasm.type_index },
};
}
},
else => @panic("TODO: Implement undefined symbols for non-function declarations"),
}
}
const Kind = union(enum) {
data: void,
function: FnData,
};
/// Parses an Atom and inserts its metadata into the corresponding sections.
fn parseAtom(self: *Wasm, atom: *Atom, kind: Kind) !void {
const symbol = (SymbolLoc{ .file = null, .index = atom.sym_index }).getSymbol(self);
const final_index: u32 = switch (kind) {
.function => |fn_data| result: {
const index = @intCast(u32, self.functions.items.len + self.imported_functions_count);
try self.functions.append(self.base.allocator, .{ .type_index = fn_data.type_index });
symbol.tag = .function;
symbol.index = index;
if (self.code_section_index == null) {
self.code_section_index = @intCast(u32, self.segments.items.len);
try self.segments.append(self.base.allocator, .{
.alignment = atom.alignment,
.size = atom.size,
.offset = 0,
});
}
break :result self.code_section_index.?;
},
.data => result: {
// TODO: Add mutables global decls to .bss section instead
const segment_name = try std.mem.concat(self.base.allocator, u8, &.{
".rodata.",
self.string_table.get(symbol.name),
});
errdefer self.base.allocator.free(segment_name);
const segment_info: types.Segment = .{
.name = segment_name,
.alignment = atom.alignment,
.flags = 0,
};
symbol.tag = .data;
const should_merge = self.base.options.output_mode != .Obj;
const gop = try self.data_segments.getOrPut(self.base.allocator, segment_info.outputName(should_merge));
if (gop.found_existing) {
const index = gop.value_ptr.*;
self.segments.items[index].size += atom.size;
// segment indexes can be off by 1 due to also containing a segment
// for the code section, so we must check if the existing segment
// is larger than that of the code section, and substract the index by 1 in such case.
const info_add = if (self.code_section_index) |idx| blk: {
if (idx < index) break :blk @as(u32, 1);
break :blk 0;
} else @as(u32, 0);
symbol.index = index - info_add;
// segment info already exists, so free its memory
self.base.allocator.free(segment_name);
break :result index;
} else {
const index = @intCast(u32, self.segments.items.len);
try self.segments.append(self.base.allocator, .{
.alignment = atom.alignment,
.size = 0,
.offset = 0,
});
gop.value_ptr.* = index;
const info_index = @intCast(u32, self.segment_info.items.len);
try self.segment_info.append(self.base.allocator, segment_info);
symbol.index = info_index;
break :result index;
}
},
};
const segment: *Segment = &self.segments.items[final_index];
segment.alignment = std.math.max(segment.alignment, atom.alignment);
if (self.atoms.getPtr(final_index)) |last| {
last.*.next = atom;
atom.prev = last.*;
last.* = atom;
} else {
try self.atoms.putNoClobber(self.base.allocator, final_index, atom);
}
}
fn allocateAtoms(self: *Wasm) !void {
var it = self.atoms.iterator();
while (it.next()) |entry| {
const segment = &self.segments.items[entry.key_ptr.*];
var atom: *Atom = entry.value_ptr.*.getFirst();
var offset: u32 = 0;
while (true) {
offset = std.mem.alignForwardGeneric(u32, offset, atom.alignment);