-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathWasm.zig
4767 lines (4151 loc) · 178 KB
/
Wasm.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 overall strategy here is to load all the object file data into memory
//! as inputs are parsed. During `prelink`, as much linking as possible is
//! performed without any knowledge of functions and globals provided by the
//! Zcu. If there is no Zcu, effectively all linking is done in `prelink`.
//!
//! `updateFunc`, `updateNav`, `updateExports`, and `deleteExport` are handled
//! by merely tracking references to the relevant functions and globals. All
//! the linking logic between objects and Zcu happens in `flush`. Many
//! components of the final output are computed on-the-fly at this time rather
//! than being precomputed and stored separately.
const Wasm = @This();
const Archive = @import("Wasm/Archive.zig");
const Object = @import("Wasm/Object.zig");
pub const Flush = @import("Wasm/Flush.zig");
const builtin = @import("builtin");
const native_endian = builtin.cpu.arch.endian();
const build_options = @import("build_options");
const std = @import("std");
const Allocator = std.mem.Allocator;
const Cache = std.Build.Cache;
const Path = Cache.Path;
const assert = std.debug.assert;
const fs = std.fs;
const leb = std.leb;
const log = std.log.scoped(.link);
const mem = std.mem;
const Air = @import("../Air.zig");
const Mir = @import("../arch/wasm/Mir.zig");
const CodeGen = @import("../arch/wasm/CodeGen.zig");
const abi = @import("../arch/wasm/abi.zig");
const Compilation = @import("../Compilation.zig");
const Dwarf = @import("Dwarf.zig");
const InternPool = @import("../InternPool.zig");
const Liveness = @import("../Liveness.zig");
const LlvmObject = @import("../codegen/llvm.zig").Object;
const Zcu = @import("../Zcu.zig");
const codegen = @import("../codegen.zig");
const dev = @import("../dev.zig");
const link = @import("../link.zig");
const lldMain = @import("../main.zig").lldMain;
const trace = @import("../tracy.zig").trace;
const wasi_libc = @import("../wasi_libc.zig");
const Value = @import("../Value.zig");
base: link.File,
/// Null-terminated strings, indexes have type String and string_table provides
/// lookup.
///
/// There are a couple of sites that add things here without adding
/// corresponding string_table entries. For such cases, when implementing
/// serialization/deserialization, they should be adjusted to prefix that data
/// with a null byte so that deserialization does not attempt to create
/// string_table entries for them. Alternately those sites could be moved to
/// use a different byte array for this purpose.
string_bytes: std.ArrayListUnmanaged(u8),
/// Sometimes we have logic that wants to borrow string bytes to store
/// arbitrary things in there. In this case it is not allowed to intern new
/// strings during this time. This safety lock is used to detect misuses.
string_bytes_lock: std.debug.SafetyLock = .{},
/// Omitted when serializing linker state.
string_table: String.Table,
/// Symbol name of the entry function to export
entry_name: OptionalString,
/// When true, will allow undefined symbols
import_symbols: bool,
/// Set of *global* symbol names to export to the host environment.
export_symbol_names: []const []const u8,
/// When defined, sets the start of the data section.
global_base: ?u64,
/// When defined, sets the initial memory size of the memory.
initial_memory: ?u64,
/// When defined, sets the maximum memory size of the memory.
max_memory: ?u64,
/// When true, will import the function table from the host environment.
import_table: bool,
/// When true, will export the function table to the host environment.
export_table: bool,
/// 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.Ptr = null,
/// List of relocatable files to be linked into the final binary.
objects: std.ArrayListUnmanaged(Object) = .{},
func_types: std.AutoArrayHashMapUnmanaged(FunctionType, void) = .empty,
/// Provides a mapping of both imports and provided functions to symbol name.
/// Local functions may be unnamed.
/// Key is symbol name, however the `FunctionImport` may have an name override for the import name.
object_function_imports: std.AutoArrayHashMapUnmanaged(String, FunctionImport) = .empty,
/// All functions for all objects.
object_functions: std.ArrayListUnmanaged(ObjectFunction) = .empty,
/// Provides a mapping of both imports and provided globals to symbol name.
/// Local globals may be unnamed.
object_global_imports: std.AutoArrayHashMapUnmanaged(String, GlobalImport) = .empty,
/// All globals for all objects.
object_globals: std.ArrayListUnmanaged(ObjectGlobal) = .empty,
/// All table imports for all objects.
object_table_imports: std.AutoArrayHashMapUnmanaged(String, TableImport) = .empty,
/// All parsed table sections for all objects.
object_tables: std.ArrayListUnmanaged(Table) = .empty,
/// All memory imports for all objects.
object_memory_imports: std.AutoArrayHashMapUnmanaged(String, MemoryImport) = .empty,
/// All parsed memory sections for all objects.
object_memories: std.ArrayListUnmanaged(ObjectMemory) = .empty,
/// All relocations from all objects concatenated. `relocs_start` marks the end
/// point of object relocations and start point of Zcu relocations.
object_relocations: std.MultiArrayList(ObjectRelocation) = .empty,
/// List of initialization functions. These must be called in order of priority
/// by the (synthetic) `__wasm_call_ctors` function.
object_init_funcs: std.ArrayListUnmanaged(InitFunc) = .empty,
/// The data section of an object has many segments. Each segment corresponds
/// logically to an object file's .data section, or .rodata section. In
/// the case of `-fdata-sections` there will be one segment per data symbol.
object_data_segments: std.ArrayListUnmanaged(ObjectDataSegment) = .empty,
/// Each segment has many data symbols, which correspond logically to global
/// constants.
object_datas: std.ArrayListUnmanaged(ObjectData) = .empty,
object_data_imports: std.AutoArrayHashMapUnmanaged(String, ObjectDataImport) = .empty,
/// Non-synthetic section that can essentially be mem-cpy'd into place after performing relocations.
object_custom_segments: std.AutoArrayHashMapUnmanaged(ObjectSectionIndex, CustomSegment) = .empty,
/// All comdat information for all objects.
object_comdats: std.ArrayListUnmanaged(Comdat) = .empty,
/// A table that maps the relocations to be performed where the key represents
/// the section (across all objects) that the slice of relocations applies to.
object_relocations_table: std.AutoArrayHashMapUnmanaged(ObjectSectionIndex, ObjectRelocation.Slice) = .empty,
/// Incremented across all objects in order to enable calculation of `ObjectSectionIndex` values.
object_total_sections: u32 = 0,
/// All comdat symbols from all objects concatenated.
object_comdat_symbols: std.MultiArrayList(Comdat.Symbol) = .empty,
/// Relocations to be emitted into an object file. Remains empty when not
/// emitting an object file.
out_relocs: std.MultiArrayList(OutReloc) = .empty,
/// List of locations within `string_bytes` that must be patched with the virtual
/// memory address of a Uav during `flush`.
/// When emitting an object file, `out_relocs` is used instead.
uav_fixups: std.ArrayListUnmanaged(UavFixup) = .empty,
/// List of locations within `string_bytes` that must be patched with the virtual
/// memory address of a Nav during `flush`.
/// When emitting an object file, `out_relocs` is used instead.
/// No functions here only global variables.
nav_fixups: std.ArrayListUnmanaged(NavFixup) = .empty,
/// When a nav reference is a function pointer, this tracks the required function
/// table entry index that needs to overwrite the code in the final output.
func_table_fixups: std.ArrayListUnmanaged(FuncTableFixup) = .empty,
/// Symbols to be emitted into an object file. Remains empty when not emitting
/// an object file.
symbol_table: std.AutoArrayHashMapUnmanaged(String, void) = .empty,
/// When importing objects from the host environment, a name must be supplied.
/// LLVM uses "env" by default when none is given.
/// This value is passed to object files since wasm tooling conventions provides
/// no way to specify the module name in the symbol table.
object_host_name: OptionalString,
/// Memory section
memories: std.wasm.Memory = .{ .limits = .{
.min = 0,
.max = 0,
.flags = .{ .has_max = false, .is_shared = false },
} },
/// `--verbose-link` output.
/// Initialized on creation, appended to as inputs are added, printed during `flush`.
/// String data is allocated into Compilation arena.
dump_argv_list: std.ArrayListUnmanaged([]const u8),
preloaded_strings: PreloadedStrings,
/// This field is used when emitting an object; `navs_exe` used otherwise.
/// Does not include externs since that data lives elsewhere.
navs_obj: std.AutoArrayHashMapUnmanaged(InternPool.Nav.Index, ZcuDataObj) = .empty,
/// This field is unused when emitting an object; `navs_obj` used otherwise.
/// Does not include externs since that data lives elsewhere.
navs_exe: std.AutoArrayHashMapUnmanaged(InternPool.Nav.Index, ZcuDataExe) = .empty,
/// Tracks all InternPool values referenced by codegen. Needed for outputting
/// the data segment. This one does not track ref count because object files
/// require using max LEB encoding for these references anyway.
uavs_obj: std.AutoArrayHashMapUnmanaged(InternPool.Index, ZcuDataObj) = .empty,
/// Tracks ref count to optimize LEB encodings for UAV references.
uavs_exe: std.AutoArrayHashMapUnmanaged(InternPool.Index, ZcuDataExe) = .empty,
/// Sparse table of uavs that need to be emitted with greater alignment than
/// the default for the type.
overaligned_uavs: std.AutoArrayHashMapUnmanaged(InternPool.Index, Alignment) = .empty,
/// When the key is an enum type, this represents a `@tagName` function.
zcu_funcs: std.AutoArrayHashMapUnmanaged(InternPool.Index, ZcuFunc) = .empty,
nav_exports: std.AutoArrayHashMapUnmanaged(NavExport, Zcu.Export.Index) = .empty,
uav_exports: std.AutoArrayHashMapUnmanaged(UavExport, Zcu.Export.Index) = .empty,
imports: std.AutoArrayHashMapUnmanaged(InternPool.Nav.Index, void) = .empty,
dwarf: ?Dwarf = null,
flush_buffer: Flush = .{},
/// Empty until `prelink`. There it is populated based on object files.
/// Next, it is copied into `Flush.missing_exports` just before `flush`
/// and that data is used during `flush`.
missing_exports: std.AutoArrayHashMapUnmanaged(String, void) = .empty,
entry_resolution: FunctionImport.Resolution = .unresolved,
/// Empty when outputting an object.
function_exports: std.AutoArrayHashMapUnmanaged(String, FunctionIndex) = .empty,
hidden_function_exports: std.AutoArrayHashMapUnmanaged(String, FunctionIndex) = .empty,
global_exports: std.ArrayListUnmanaged(GlobalExport) = .empty,
/// Tracks the value at the end of prelink.
global_exports_len: u32 = 0,
/// Ordered list of non-import functions that will appear in the final binary.
/// Empty until prelink.
functions: std.AutoArrayHashMapUnmanaged(FunctionImport.Resolution, void) = .empty,
/// Tracks the value at the end of prelink, at which point `functions`
/// contains only object file functions, and nothing from the Zcu yet.
functions_end_prelink: u32 = 0,
function_imports_len_prelink: u32 = 0,
data_imports_len_prelink: u32 = 0,
/// At the end of prelink, this is populated with needed functions from
/// objects.
///
/// During the Zcu phase, entries are not deleted from this table
/// because doing so would be irreversible when a `deleteExport` call is
/// handled. However, entries are added during the Zcu phase when extern
/// functions are passed to `updateNav`.
///
/// `flush` gets a copy of this table, and then Zcu exports are applied to
/// remove elements from the table, and the remainder are either undefined
/// symbol errors, or import section entries depending on the output mode.
function_imports: std.AutoArrayHashMapUnmanaged(String, FunctionImportId) = .empty,
/// At the end of prelink, this is populated with data symbols needed by
/// objects.
///
/// During the Zcu phase, entries are not deleted from this table
/// because doing so would be irreversible when a `deleteExport` call is
/// handled. However, entries are added during the Zcu phase when extern
/// functions are passed to `updateNav`.
///
/// `flush` gets a copy of this table, and then Zcu exports are applied to
/// remove elements from the table, and the remainder are either undefined
/// symbol errors, or symbol table entries depending on the output mode.
data_imports: std.AutoArrayHashMapUnmanaged(String, DataImportId) = .empty,
/// Set of data symbols that will appear in the final binary. Used to populate
/// `Flush.data_segments` before sorting.
data_segments: std.AutoArrayHashMapUnmanaged(DataSegmentId, void) = .empty,
/// Ordered list of non-import globals that will appear in the final binary.
/// Empty until prelink.
globals: std.AutoArrayHashMapUnmanaged(GlobalImport.Resolution, void) = .empty,
/// Tracks the value at the end of prelink, at which point `globals`
/// contains only object file globals, and nothing from the Zcu yet.
globals_end_prelink: u32 = 0,
global_imports: std.AutoArrayHashMapUnmanaged(String, GlobalImportId) = .empty,
/// Ordered list of non-import tables that will appear in the final binary.
/// Empty until prelink.
tables: std.AutoArrayHashMapUnmanaged(TableImport.Resolution, void) = .empty,
table_imports: std.AutoArrayHashMapUnmanaged(String, TableImport.Index) = .empty,
/// All functions that have had their address taken and therefore might be
/// called via a `call_indirect` function.
zcu_indirect_function_set: std.AutoArrayHashMapUnmanaged(InternPool.Nav.Index, void) = .empty,
object_indirect_function_import_set: std.AutoArrayHashMapUnmanaged(String, void) = .empty,
object_indirect_function_set: std.AutoArrayHashMapUnmanaged(ObjectFunctionIndex, void) = .empty,
error_name_table_ref_count: u32 = 0,
tag_name_table_ref_count: u32 = 0,
/// Set to true if any `GLOBAL_INDEX` relocation is encountered with
/// `SymbolFlags.tls` set to true. This is for objects only; final
/// value must be this OR'd with the same logic for zig functions
/// (set to true if any threadlocal global is used).
any_tls_relocs: bool = false,
any_passive_inits: bool = false,
/// All MIR instructions for all Zcu functions.
mir_instructions: std.MultiArrayList(Mir.Inst) = .{},
/// Corresponds to `mir_instructions`.
mir_extra: std.ArrayListUnmanaged(u32) = .empty,
/// All local types for all Zcu functions.
all_zcu_locals: std.ArrayListUnmanaged(std.wasm.Valtype) = .empty,
params_scratch: std.ArrayListUnmanaged(std.wasm.Valtype) = .empty,
returns_scratch: std.ArrayListUnmanaged(std.wasm.Valtype) = .empty,
/// All Zcu error names in order, null-terminated, concatenated. No need to
/// serialize; trivially reconstructed.
error_name_bytes: std.ArrayListUnmanaged(u8) = .empty,
/// For each Zcu error, in order, offset into `error_name_bytes` where the name
/// is stored. No need to serialize; trivially reconstructed.
error_name_offs: std.ArrayListUnmanaged(u32) = .empty,
tag_name_bytes: std.ArrayListUnmanaged(u8) = .empty,
tag_name_offs: std.ArrayListUnmanaged(u32) = .empty,
pub const TagNameOff = extern struct {
off: u32,
len: u32,
};
/// Index into `Wasm.zcu_indirect_function_set`.
pub const ZcuIndirectFunctionSetIndex = enum(u32) {
_,
};
pub const UavFixup = extern struct {
uavs_exe_index: UavsExeIndex,
/// Index into `string_bytes`.
offset: u32,
addend: u32,
};
pub const NavFixup = extern struct {
navs_exe_index: NavsExeIndex,
/// Index into `string_bytes`.
offset: u32,
addend: u32,
};
pub const FuncTableFixup = extern struct {
table_index: ZcuIndirectFunctionSetIndex,
/// Index into `string_bytes`.
offset: u32,
};
/// Index into `objects`.
pub const ObjectIndex = enum(u32) {
_,
pub fn ptr(index: ObjectIndex, wasm: *const Wasm) *Object {
return &wasm.objects.items[@intFromEnum(index)];
}
};
/// Index into `Wasm.functions`.
pub const FunctionIndex = enum(u32) {
_,
pub fn ptr(index: FunctionIndex, wasm: *const Wasm) *FunctionImport.Resolution {
return &wasm.functions.keys()[@intFromEnum(index)];
}
pub fn fromIpNav(wasm: *const Wasm, nav_index: InternPool.Nav.Index) ?FunctionIndex {
return fromResolution(wasm, .fromIpNav(wasm, nav_index));
}
pub fn fromTagNameType(wasm: *const Wasm, tag_type: InternPool.Index) ?FunctionIndex {
const zcu_func: ZcuFunc.Index = @enumFromInt(wasm.zcu_funcs.getIndex(tag_type) orelse return null);
return fromResolution(wasm, .pack(wasm, .{ .zcu_func = zcu_func }));
}
pub fn fromSymbolName(wasm: *const Wasm, name: String) ?FunctionIndex {
if (wasm.object_function_imports.getPtr(name)) |import| {
return fromResolution(wasm, import.resolution);
}
if (wasm.function_exports.get(name)) |index| return index;
if (wasm.hidden_function_exports.get(name)) |index| return index;
return null;
}
pub fn fromResolution(wasm: *const Wasm, resolution: FunctionImport.Resolution) ?FunctionIndex {
const i = wasm.functions.getIndex(resolution) orelse return null;
return @enumFromInt(i);
}
};
pub const GlobalExport = extern struct {
name: String,
global_index: GlobalIndex,
};
/// 0. Index into `Flush.function_imports`
/// 1. Index into `functions`.
///
/// Note that function_imports indexes are subject to swap removals during
/// `flush`.
pub const OutputFunctionIndex = enum(u32) {
_,
pub fn fromResolution(wasm: *const Wasm, resolution: FunctionImport.Resolution) ?OutputFunctionIndex {
return fromFunctionIndex(wasm, FunctionIndex.fromResolution(wasm, resolution) orelse return null);
}
pub fn fromFunctionIndex(wasm: *const Wasm, index: FunctionIndex) OutputFunctionIndex {
return @enumFromInt(wasm.flush_buffer.function_imports.entries.len + @intFromEnum(index));
}
pub fn fromObjectFunction(wasm: *const Wasm, index: ObjectFunctionIndex) OutputFunctionIndex {
return fromResolution(wasm, .fromObjectFunction(wasm, index)).?;
}
pub fn fromObjectFunctionHandlingWeak(wasm: *const Wasm, index: ObjectFunctionIndex) OutputFunctionIndex {
const ptr = index.ptr(wasm);
if (ptr.flags.binding == .weak) {
const name = ptr.name.unwrap().?;
const import = wasm.object_function_imports.getPtr(name).?;
assert(import.resolution != .unresolved);
return fromResolution(wasm, import.resolution).?;
}
return fromResolution(wasm, .fromObjectFunction(wasm, index)).?;
}
pub fn fromIpIndex(wasm: *const Wasm, ip_index: InternPool.Index) OutputFunctionIndex {
const zcu = wasm.base.comp.zcu.?;
const ip = &zcu.intern_pool;
return switch (ip.indexToKey(ip_index)) {
.@"extern" => |ext| {
const name = wasm.getExistingString(ext.name.toSlice(ip)).?;
return fromSymbolName(wasm, name);
},
else => fromResolution(wasm, .fromIpIndex(wasm, ip_index)).?,
};
}
pub fn fromIpNav(wasm: *const Wasm, nav_index: InternPool.Nav.Index) OutputFunctionIndex {
const zcu = wasm.base.comp.zcu.?;
const ip = &zcu.intern_pool;
const nav = ip.getNav(nav_index);
return fromIpIndex(wasm, nav.status.fully_resolved.val);
}
pub fn fromTagNameType(wasm: *const Wasm, tag_type: InternPool.Index) OutputFunctionIndex {
return fromFunctionIndex(wasm, FunctionIndex.fromTagNameType(wasm, tag_type).?);
}
pub fn fromSymbolName(wasm: *const Wasm, name: String) OutputFunctionIndex {
if (wasm.flush_buffer.function_imports.getIndex(name)) |i| return @enumFromInt(i);
return fromFunctionIndex(wasm, FunctionIndex.fromSymbolName(wasm, name).?);
}
};
/// Index into `Wasm.globals`.
pub const GlobalIndex = enum(u32) {
_,
/// This is only accurate when not emitting an object and there is a Zcu.
pub const stack_pointer: GlobalIndex = @enumFromInt(0);
/// Same as `stack_pointer` but with a safety assertion.
pub fn stackPointer(wasm: *const Wasm) ObjectGlobal.Index {
const comp = wasm.base.comp;
assert(comp.config.output_mode != .Obj);
assert(comp.zcu != null);
return .stack_pointer;
}
pub fn ptr(index: GlobalIndex, f: *const Flush) *Wasm.GlobalImport.Resolution {
return &f.globals.items[@intFromEnum(index)];
}
pub fn fromIpNav(wasm: *const Wasm, nav_index: InternPool.Nav.Index) ?GlobalIndex {
const i = wasm.globals.getIndex(.fromIpNav(wasm, nav_index)) orelse return null;
return @enumFromInt(i);
}
pub fn fromObjectGlobal(wasm: *const Wasm, i: ObjectGlobalIndex) GlobalIndex {
return @enumFromInt(wasm.globals.getIndex(.fromObjectGlobal(wasm, i)).?);
}
pub fn fromObjectGlobalHandlingWeak(wasm: *const Wasm, index: ObjectGlobalIndex) GlobalIndex {
const global = index.ptr(wasm);
return if (global.flags.binding == .weak)
fromSymbolName(wasm, global.name.unwrap().?)
else
fromObjectGlobal(wasm, index);
}
pub fn fromSymbolName(wasm: *const Wasm, name: String) GlobalIndex {
const import = wasm.object_global_imports.getPtr(name).?;
return @enumFromInt(wasm.globals.getIndex(import.resolution).?);
}
};
/// Index into `tables`.
pub const TableIndex = enum(u32) {
_,
pub fn ptr(index: TableIndex, f: *const Flush) *Wasm.TableImport.Resolution {
return &f.tables.items[@intFromEnum(index)];
}
pub fn fromObjectTable(wasm: *const Wasm, i: ObjectTableIndex) TableIndex {
return @enumFromInt(wasm.tables.getIndex(.fromObjectTable(i)).?);
}
pub fn fromSymbolName(wasm: *const Wasm, name: String) TableIndex {
const import = wasm.object_table_imports.getPtr(name).?;
return @enumFromInt(wasm.tables.getIndex(import.resolution).?);
}
};
/// The first N indexes correspond to input objects (`objects`) array.
/// After that, the indexes correspond to the `source_locations` array,
/// representing a location in a Zig source file that can be pinpointed
/// precisely via AST node and token.
pub const SourceLocation = enum(u32) {
/// From the Zig compilation unit but no precise source location.
zig_object_nofile = std.math.maxInt(u32) - 1,
none = std.math.maxInt(u32),
_,
/// Index into `source_locations`.
pub const Index = enum(u32) {
_,
};
pub const Unpacked = union(enum) {
none,
zig_object_nofile,
object_index: ObjectIndex,
source_location_index: Index,
};
pub fn pack(unpacked: Unpacked, wasm: *const Wasm) SourceLocation {
_ = wasm;
return switch (unpacked) {
.zig_object_nofile => .zig_object_nofile,
.none => .none,
.object_index => |object_index| @enumFromInt(@intFromEnum(object_index)),
.source_location_index => @panic("TODO"),
};
}
pub fn unpack(sl: SourceLocation, wasm: *const Wasm) Unpacked {
return switch (sl) {
.zig_object_nofile => .zig_object_nofile,
.none => .none,
_ => {
const i = @intFromEnum(sl);
if (i < wasm.objects.items.len) return .{ .object_index = @enumFromInt(i) };
const sl_index = i - wasm.objects.items.len;
_ = sl_index;
@panic("TODO");
},
};
}
pub fn fromObject(object_index: ObjectIndex, wasm: *const Wasm) SourceLocation {
return pack(.{ .object_index = object_index }, wasm);
}
pub fn addError(sl: SourceLocation, wasm: *Wasm, comptime f: []const u8, args: anytype) void {
const diags = &wasm.base.comp.link_diags;
switch (sl.unpack(wasm)) {
.none => unreachable,
.zig_object_nofile => diags.addError("zig compilation unit: " ++ f, args),
.object_index => |i| diags.addError("{}: " ++ f, .{i.ptr(wasm).path} ++ args),
.source_location_index => @panic("TODO"),
}
}
pub fn addNote(
sl: SourceLocation,
err: *link.Diags.ErrorWithNotes,
comptime f: []const u8,
args: anytype,
) void {
err.addNote(f, args);
const err_msg = &err.diags.msgs.items[err.index];
err_msg.notes[err.note_slot - 1].source_location = .{ .wasm = sl };
}
pub fn fail(sl: SourceLocation, diags: *link.Diags, comptime format: []const u8, args: anytype) error{LinkFailure} {
return diags.failSourceLocation(.{ .wasm = sl }, format, args);
}
pub fn string(
sl: SourceLocation,
msg: []const u8,
bundle: *std.zig.ErrorBundle.Wip,
wasm: *const Wasm,
) Allocator.Error!std.zig.ErrorBundle.String {
return switch (sl.unpack(wasm)) {
.none => try bundle.addString(msg),
.zig_object_nofile => try bundle.printString("zig compilation unit: {s}", .{msg}),
.object_index => |i| {
const obj = i.ptr(wasm);
return if (obj.archive_member_name.slice(wasm)) |obj_name|
try bundle.printString("{} ({s}): {s}", .{ obj.path, std.fs.path.basename(obj_name), msg })
else
try bundle.printString("{}: {s}", .{ obj.path, msg });
},
.source_location_index => @panic("TODO"),
};
}
};
/// The lower bits of this ABI-match the flags here:
/// https://github.com/WebAssembly/tool-conventions/blob/df8d737539eb8a8f446ba5eab9dc670c40dfb81e/Linking.md#symbol-table-subsection
/// The upper bits are used for nefarious purposes.
pub const SymbolFlags = packed struct(u32) {
binding: Binding = .strong,
/// Indicating that this is a hidden symbol. Hidden symbols are not to be
/// exported when performing the final link, but may be linked to other
/// modules.
visibility_hidden: bool = false,
padding0: u1 = 0,
/// For non-data symbols, this must match whether the symbol is an import
/// or is defined; for data symbols, determines whether a segment is
/// specified.
undefined: bool = false,
/// The symbol is intended to be exported from the wasm module to the host
/// environment. This differs from the visibility flags in that it affects
/// static linking.
exported: bool = false,
/// The symbol uses an explicit symbol name, rather than reusing the name
/// from a wasm import. This allows it to remap imports from foreign
/// WebAssembly modules into local symbols with different names.
explicit_name: bool = false,
/// The symbol is intended to be included in the linker output, regardless
/// of whether it is used by the program. Same meaning as `retain`.
no_strip: bool = false,
/// The symbol resides in thread local storage.
tls: bool = false,
/// The symbol represents an absolute address. This means its offset is
/// relative to the start of the wasm memory as opposed to being relative
/// to a data segment.
absolute: bool = false,
// Above here matches the tooling conventions ABI.
padding1: u13 = 0,
/// Zig-specific. Dead things are allowed to be garbage collected.
alive: bool = false,
/// Zig-specific. This symbol comes from an object that must be included in
/// the final link.
must_link: bool = false,
/// Zig-specific.
global_type: GlobalType4 = .zero,
/// Zig-specific.
limits_has_max: bool = false,
/// Zig-specific.
limits_is_shared: bool = false,
/// Zig-specific.
ref_type: RefType1 = .funcref,
pub const Binding = enum(u2) {
strong = 0,
/// Indicating that this is a weak symbol. When linking multiple modules
/// defining the same symbol, all weak definitions are discarded if any
/// strong definitions exist; then if multiple weak definitions exist all
/// but one (unspecified) are discarded; and finally it is an error if more
/// than one definition remains.
weak = 1,
/// Indicating that this is a local symbol. Local symbols are not to be
/// exported, or linked to other modules/sections. The names of all
/// non-local symbols must be unique, but the names of local symbols
/// are not considered for uniqueness. A local function or global
/// symbol cannot reference an import.
local = 2,
};
pub fn initZigSpecific(flags: *SymbolFlags, must_link: bool, no_strip: bool) void {
flags.no_strip = no_strip;
flags.alive = false;
flags.must_link = must_link;
flags.global_type = .zero;
flags.limits_has_max = false;
flags.limits_is_shared = false;
flags.ref_type = .funcref;
}
pub fn isIncluded(flags: SymbolFlags, is_dynamic: bool) bool {
return flags.exported or
(is_dynamic and !flags.visibility_hidden) or
(flags.no_strip and flags.must_link);
}
pub fn isExported(flags: SymbolFlags, is_dynamic: bool) bool {
if (flags.undefined or flags.binding == .local) return false;
if (is_dynamic and !flags.visibility_hidden) return true;
return flags.exported;
}
/// Returns the name as how it will be output into the final object
/// file or binary. When `merge` is true, this will return the
/// short name. i.e. ".rodata". When false, it returns the entire name instead.
pub fn outputName(flags: SymbolFlags, name: []const u8, merge: bool) []const u8 {
if (flags.tls) return ".tdata";
if (!merge) return name;
if (mem.startsWith(u8, name, ".rodata.")) return ".rodata";
if (mem.startsWith(u8, name, ".text.")) return ".text";
if (mem.startsWith(u8, name, ".data.")) return ".data";
if (mem.startsWith(u8, name, ".bss.")) return ".bss";
return name;
}
/// Masks off the Zig-specific stuff.
pub fn toAbiInteger(flags: SymbolFlags) u32 {
var copy = flags;
copy.initZigSpecific(false, false);
return @bitCast(copy);
}
};
pub const GlobalType4 = packed struct(u4) {
valtype: Valtype3,
mutable: bool,
pub const zero: GlobalType4 = @bitCast(@as(u4, 0));
pub fn to(gt: GlobalType4) ObjectGlobal.Type {
return .{
.valtype = gt.valtype.to(),
.mutable = gt.mutable,
};
}
};
pub const Valtype3 = enum(u3) {
i32,
i64,
f32,
f64,
v128,
pub fn from(v: std.wasm.Valtype) Valtype3 {
return switch (v) {
.i32 => .i32,
.i64 => .i64,
.f32 => .f32,
.f64 => .f64,
.v128 => .v128,
};
}
pub fn to(v: Valtype3) std.wasm.Valtype {
return switch (v) {
.i32 => .i32,
.i64 => .i64,
.f32 => .f32,
.f64 => .f64,
.v128 => .v128,
};
}
};
/// Index into `Wasm.navs_obj`.
pub const NavsObjIndex = enum(u32) {
_,
pub fn key(i: @This(), wasm: *const Wasm) *InternPool.Nav.Index {
return &wasm.navs_obj.keys()[@intFromEnum(i)];
}
pub fn value(i: @This(), wasm: *const Wasm) *ZcuDataObj {
return &wasm.navs_obj.values()[@intFromEnum(i)];
}
pub fn name(i: @This(), wasm: *const Wasm) [:0]const u8 {
const zcu = wasm.base.comp.zcu.?;
const ip = &zcu.intern_pool;
const nav = ip.getNav(i.key(wasm).*);
return nav.fqn.toSlice(ip);
}
};
/// Index into `Wasm.navs_exe`.
pub const NavsExeIndex = enum(u32) {
_,
pub fn key(i: @This(), wasm: *const Wasm) *InternPool.Nav.Index {
return &wasm.navs_exe.keys()[@intFromEnum(i)];
}
pub fn value(i: @This(), wasm: *const Wasm) *ZcuDataExe {
return &wasm.navs_exe.values()[@intFromEnum(i)];
}
pub fn name(i: @This(), wasm: *const Wasm) [:0]const u8 {
const zcu = wasm.base.comp.zcu.?;
const ip = &zcu.intern_pool;
const nav = ip.getNav(i.key(wasm).*);
return nav.fqn.toSlice(ip);
}
};
/// Index into `Wasm.uavs_obj`.
pub const UavsObjIndex = enum(u32) {
_,
pub fn key(i: @This(), wasm: *const Wasm) *InternPool.Index {
return &wasm.uavs_obj.keys()[@intFromEnum(i)];
}
pub fn value(i: @This(), wasm: *const Wasm) *ZcuDataObj {
return &wasm.uavs_obj.values()[@intFromEnum(i)];
}
};
/// Index into `Wasm.uavs_exe`.
pub const UavsExeIndex = enum(u32) {
_,
pub fn key(i: @This(), wasm: *const Wasm) *InternPool.Index {
return &wasm.uavs_exe.keys()[@intFromEnum(i)];
}
pub fn value(i: @This(), wasm: *const Wasm) *ZcuDataExe {
return &wasm.uavs_exe.values()[@intFromEnum(i)];
}
};
/// Used when emitting a relocatable object.
pub const ZcuDataObj = extern struct {
code: DataPayload,
relocs: OutReloc.Slice,
};
/// Used when not emitting a relocatable object.
pub const ZcuDataExe = extern struct {
code: DataPayload,
/// Tracks how many references there are for the purposes of sorting data segments.
count: u32,
};
/// An abstraction for calling `lowerZcuData` repeatedly until all data entries
/// are populated.
const ZcuDataStarts = struct {
uavs_i: u32,
fn init(wasm: *const Wasm) ZcuDataStarts {
const comp = wasm.base.comp;
const is_obj = comp.config.output_mode == .Obj;
return if (is_obj) initObj(wasm) else initExe(wasm);
}
fn initObj(wasm: *const Wasm) ZcuDataStarts {
return .{
.uavs_i = @intCast(wasm.uavs_obj.entries.len),
};
}
fn initExe(wasm: *const Wasm) ZcuDataStarts {
return .{
.uavs_i = @intCast(wasm.uavs_exe.entries.len),
};
}
fn finish(zds: ZcuDataStarts, wasm: *Wasm, pt: Zcu.PerThread) !void {
const comp = wasm.base.comp;
const is_obj = comp.config.output_mode == .Obj;
return if (is_obj) finishObj(zds, wasm, pt) else finishExe(zds, wasm, pt);
}
fn finishObj(zds: ZcuDataStarts, wasm: *Wasm, pt: Zcu.PerThread) !void {
var uavs_i = zds.uavs_i;
while (uavs_i < wasm.uavs_obj.entries.len) : (uavs_i += 1) {
// Call to `lowerZcuData` here possibly creates more entries in these tables.
wasm.uavs_obj.values()[uavs_i] = try lowerZcuData(wasm, pt, wasm.uavs_obj.keys()[uavs_i]);
}
}
fn finishExe(zds: ZcuDataStarts, wasm: *Wasm, pt: Zcu.PerThread) !void {
var uavs_i = zds.uavs_i;
while (uavs_i < wasm.uavs_exe.entries.len) : (uavs_i += 1) {
// Call to `lowerZcuData` here possibly creates more entries in these tables.
const zcu_data = try lowerZcuData(wasm, pt, wasm.uavs_exe.keys()[uavs_i]);
wasm.uavs_exe.values()[uavs_i].code = zcu_data.code;
}
}
};
pub const ZcuFunc = union {
function: CodeGen.Function,
tag_name: TagName,
pub const TagName = extern struct {
symbol_name: String,
type_index: FunctionType.Index,
/// Index into `Wasm.tag_name_offs`.
table_index: u32,
};
/// Index into `Wasm.zcu_funcs`.
/// Note that swapRemove is sometimes performed on `zcu_funcs`.
pub const Index = enum(u32) {
_,
pub fn key(i: @This(), wasm: *const Wasm) *InternPool.Index {
return &wasm.zcu_funcs.keys()[@intFromEnum(i)];
}
pub fn value(i: @This(), wasm: *const Wasm) *ZcuFunc {
return &wasm.zcu_funcs.values()[@intFromEnum(i)];
}
pub fn name(i: @This(), wasm: *const Wasm) [:0]const u8 {
const zcu = wasm.base.comp.zcu.?;
const ip = &zcu.intern_pool;
const ip_index = i.key(wasm).*;
switch (ip.indexToKey(ip_index)) {
.func => |func| {
const nav = ip.getNav(func.owner_nav);
return nav.fqn.toSlice(ip);
},
.enum_type => {
return i.value(wasm).tag_name.symbol_name.slice(wasm);
},
else => unreachable,
}
}
pub fn typeIndex(i: @This(), wasm: *Wasm) FunctionType.Index {
const comp = wasm.base.comp;
const zcu = comp.zcu.?;
const target = &comp.root_mod.resolved_target.result;
const ip = &zcu.intern_pool;
switch (ip.indexToKey(i.key(wasm).*)) {
.func => |func| {
const fn_ty = zcu.navValue(func.owner_nav).typeOf(zcu);
const fn_info = zcu.typeToFunc(fn_ty).?;
return wasm.getExistingFunctionType(fn_info.cc, fn_info.param_types.get(ip), .fromInterned(fn_info.return_type), target).?;
},
.enum_type => {
return i.value(wasm).tag_name.type_index;
},
else => unreachable,
}
}
};
};
pub const NavExport = extern struct {
name: String,
nav_index: InternPool.Nav.Index,
};
pub const UavExport = extern struct {
name: String,
uav_index: InternPool.Index,
};
pub const FunctionImport = extern struct {
flags: SymbolFlags,
module_name: OptionalString,
/// May be different than the key which is a symbol name.
name: String,
source_location: SourceLocation,
resolution: Resolution,
type: FunctionType.Index,
/// Represents a synthetic function, a function from an object, or a
/// function from the Zcu.
pub const Resolution = enum(u32) {
unresolved,
__wasm_apply_global_tls_relocs,
__wasm_call_ctors,
__wasm_init_memory,
__wasm_init_tls,
// Next, index into `object_functions`.
// Next, index into `zcu_funcs`.
_,
const first_object_function = @intFromEnum(Resolution.__wasm_init_tls) + 1;
pub const Unpacked = union(enum) {
unresolved,
__wasm_apply_global_tls_relocs,
__wasm_call_ctors,
__wasm_init_memory,
__wasm_init_tls,
object_function: ObjectFunctionIndex,
zcu_func: ZcuFunc.Index,
};
pub fn unpack(r: Resolution, wasm: *const Wasm) Unpacked {
return switch (r) {
.unresolved => .unresolved,
.__wasm_apply_global_tls_relocs => .__wasm_apply_global_tls_relocs,
.__wasm_call_ctors => .__wasm_call_ctors,
.__wasm_init_memory => .__wasm_init_memory,
.__wasm_init_tls => .__wasm_init_tls,
_ => {
const object_function_index = @intFromEnum(r) - first_object_function;
const zcu_func_index = if (object_function_index < wasm.object_functions.items.len)
return .{ .object_function = @enumFromInt(object_function_index) }
else
object_function_index - wasm.object_functions.items.len;
return .{ .zcu_func = @enumFromInt(zcu_func_index) };
},
};
}
pub fn pack(wasm: *const Wasm, unpacked: Unpacked) Resolution {
return switch (unpacked) {
.unresolved => .unresolved,