authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-11-27 12:17:32-08:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2021-11-27 12:17:32-08:00
logaa61e03f244a72ea01f05c3ceea7c5fb5aadf1ff
treea66e20f7e6478f0f196551bec38063f1f230fb1c
parentc46a91da13a21da22f1c6b9cbdc2cf516adb53c5
parent6e88df44a29e0c30c341f113cf4771e08fc1f0fe
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #10229 from Luukdegram/wasm-linker

stage2: Upstream zwld (partly) into wasm backend

8 files changed, 1270 insertions(+), 365 deletions(-)

lib/std/wasm.zig+139-3
......@@ -1,4 +1,8 @@
1const testing = @import("std.zig").testing;
1///! Contains all constants and types representing the wasm
2///! binary format, as specified by:
3///! https://webassembly.github.io/spec/core/
4const std = @import("std.zig");
5const testing = std.testing;
26
37// TODO: Add support for multi-byte ops (e.g. table operations)
48
......@@ -222,6 +226,18 @@ pub fn valtype(value: Valtype) u8 {
222226 return @enumToInt(value);
223227}
224228
229/// Reference types, where the funcref references to a function regardless of its type
230/// and ref references an object from the embedder.
231pub const RefType = enum(u8) {
232 funcref = 0x70,
233 externref = 0x6F,
234};
235
236/// Returns the integer value of a `Reftype`
237pub fn reftype(value: RefType) u8 {
238 return @enumToInt(value);
239}
240
225241test "Wasm - valtypes" {
226242 const _i32 = valtype(.i32);
227243 const _i64 = valtype(.i64);
......@@ -234,6 +250,124 @@ test "Wasm - valtypes" {
234250 try testing.expectEqual(@as(u8, 0x7C), _f64);
235251}
236252
253/// Limits classify the size range of resizeable storage associated with memory types and table types.
254pub const Limits = struct {
255 min: u32,
256 max: ?u32,
257};
258
259/// Initialization expressions are used to set the initial value on an object
260/// when a wasm module is being loaded.
261pub const InitExpression = union(enum) {
262 i32_const: i32,
263 i64_const: i64,
264 f32_const: f32,
265 f64_const: f64,
266 global_get: u32,
267};
268
269///
270pub const Func = struct {
271 type_index: u32,
272};
273
274/// Tables are used to hold pointers to opaque objects.
275/// This can either by any function, or an object from the host.
276pub const Table = struct {
277 limits: Limits,
278 reftype: RefType,
279};
280
281/// Describes the layout of the memory where `min` represents
282/// the minimal amount of pages, and the optional `max` represents
283/// the max pages. When `null` will allow the host to determine the
284/// amount of pages.
285pub const Memory = struct {
286 limits: Limits,
287};
288
289/// Represents the type of a `Global` or an imported global.
290pub const GlobalType = struct {
291 valtype: Valtype,
292 mutable: bool,
293};
294
295pub const Global = struct {
296 global_type: GlobalType,
297 init: InitExpression,
298};
299
300/// Notates an object to be exported from wasm
301/// to the host.
302pub const Export = struct {
303 name: []const u8,
304 kind: ExternalKind,
305 index: u32,
306};
307
308/// Element describes the layout of the table that can
309/// be found at `table_index`
310pub const Element = struct {
311 table_index: u32,
312 offset: InitExpression,
313 func_indexes: []const u32,
314};
315
316/// Imports are used to import objects from the host
317pub const Import = struct {
318 module_name: []const u8,
319 name: []const u8,
320 kind: Kind,
321
322 pub const Kind = union(ExternalKind) {
323 function: u32,
324 table: Table,
325 memory: Limits,
326 global: GlobalType,
327 };
328};
329
330/// `Type` represents a function signature type containing both
331/// a slice of parameters as well as a slice of return values.
332pub const Type = struct {
333 params: []const Valtype,
334 returns: []const Valtype,
335
336 pub fn format(self: Type, comptime fmt: []const u8, opt: std.fmt.FormatOptions, writer: anytype) !void {
337 _ = fmt;
338 _ = opt;
339 try writer.writeByte('(');
340 for (self.params) |param, i| {
341 try writer.print("{s}", .{@tagName(param)});
342 if (i + 1 != self.params.len) {
343 try writer.writeAll(", ");
344 }
345 }
346 try writer.writeAll(") -> ");
347 if (self.returns.len == 0) {
348 try writer.writeAll("nil");
349 } else {
350 for (self.returns) |return_ty, i| {
351 try writer.print("{s}", .{@tagName(return_ty)});
352 if (i + 1 != self.returns.len) {
353 try writer.writeAll(", ");
354 }
355 }
356 }
357 }
358
359 pub fn eql(self: Type, other: Type) bool {
360 return std.mem.eql(Valtype, self.params, other.params) and
361 std.mem.eql(Valtype, self.returns, other.returns);
362 }
363
364 pub fn deinit(self: *Type, gpa: *std.mem.Allocator) void {
365 gpa.free(self.params);
366 gpa.free(self.returns);
367 self.* = undefined;
368 }
369};
370
237371/// Wasm module sections as per spec:
238372/// https://webassembly.github.io/spec/core/binary/modules.html
239373pub const Section = enum(u8) {
......@@ -249,6 +383,8 @@ pub const Section = enum(u8) {
249383 element,
250384 code,
251385 data,
386 data_count,
387 _,
252388};
253389
254390/// Returns the integer value of a given `Section`
......@@ -270,7 +406,7 @@ pub fn externalKind(val: ExternalKind) u8 {
270406 return @enumToInt(val);
271407}
272408
273// types
409// type constants
274410pub const element_type: u8 = 0x70;
275411pub const function_type: u8 = 0x60;
276412pub const result_type: u8 = 0x40;
......@@ -280,7 +416,7 @@ pub const block_empty: u8 = 0x40;
280416
281417// binary constants
282418pub const magic = [_]u8{ 0x00, 0x61, 0x73, 0x6D }; // \0asm
283pub const version = [_]u8{ 0x01, 0x00, 0x00, 0x00 }; // version 1
419pub const version = [_]u8{ 0x01, 0x00, 0x00, 0x00 }; // version 1 (MVP)
284420
285421// Each wasm page size is 64kB
286422pub const page_size = 64 * 1024;
src/arch/wasm/CodeGen.zig+33-40
......@@ -518,9 +518,6 @@ blocks: std.AutoArrayHashMapUnmanaged(Air.Inst.Index, struct {
518518}) = .{},
519519/// `bytes` contains the wasm bytecode belonging to the 'code' section.
520520code: ArrayList(u8),
521/// Contains the generated function type bytecode for the current function
522/// found in `decl`
523func_type_data: ArrayList(u8),
524521/// The index the next local generated will have
525522/// NOTE: arguments share the index with locals therefore the first variable
526523/// will have the index that comes after the last argument's index
......@@ -539,7 +536,7 @@ locals: std.ArrayListUnmanaged(u8),
539536/// The Target we're emitting (used to call intInfo)
540537target: std.Target,
541538/// Represents the wasm binary file that is being linked.
542bin_file: *link.File,
539bin_file: *link.File.Wasm,
543540/// Table with the global error set. Consists of every error found in
544541/// the compiled code. Each error name maps to a `Module.ErrorInt` which is emitted
545542/// during codegen to determine the error value.
......@@ -577,6 +574,7 @@ pub fn deinit(self: *Self) void {
577574 self.locals.deinit(self.gpa);
578575 self.mir_instructions.deinit(self.gpa);
579576 self.mir_extra.deinit(self.gpa);
577 self.code.deinit();
580578 self.* = undefined;
581579}
582580
......@@ -734,43 +732,44 @@ fn allocLocal(self: *Self, ty: Type) InnerError!WValue {
734732 return WValue{ .local = initial_index };
735733}
736734
737fn genFunctype(self: *Self) InnerError!void {
738 assert(self.decl.has_tv);
739 const ty = self.decl.ty;
740 const writer = self.func_type_data.writer();
741
742 try writer.writeByte(wasm.function_type);
735/// Generates a `wasm.Type` from a given function type.
736/// Memory is owned by the caller.
737fn genFunctype(self: *Self, fn_ty: Type) !wasm.Type {
738 var params = std.ArrayList(wasm.Valtype).init(self.gpa);
739 defer params.deinit();
740 var returns = std.ArrayList(wasm.Valtype).init(self.gpa);
741 defer returns.deinit();
743742
744743 // param types
745 try leb.writeULEB128(writer, @intCast(u32, ty.fnParamLen()));
746 if (ty.fnParamLen() != 0) {
747 const params = try self.gpa.alloc(Type, ty.fnParamLen());
748 defer self.gpa.free(params);
749 ty.fnParamTypes(params);
750 for (params) |param_type| {
751 // Can we maybe get the source index of each param?
752 const val_type = try self.genValtype(param_type);
753 try writer.writeByte(val_type);
744 if (fn_ty.fnParamLen() != 0) {
745 const fn_params = try self.gpa.alloc(Type, fn_ty.fnParamLen());
746 defer self.gpa.free(fn_params);
747 fn_ty.fnParamTypes(fn_params);
748 for (fn_params) |param_type| {
749 if (!param_type.hasCodeGenBits()) continue;
750 try params.append(try self.typeToValtype(param_type));
754751 }
755752 }
756753
757754 // return type
758 const return_type = ty.fnReturnType();
755 const return_type = fn_ty.fnReturnType();
759756 switch (return_type.zigTypeTag()) {
760 .Void, .NoReturn => try leb.writeULEB128(writer, @as(u32, 0)),
757 .Void, .NoReturn => {},
761758 .Struct => return self.fail("TODO: Implement struct as return type for wasm", .{}),
762759 .Optional => return self.fail("TODO: Implement optionals as return type for wasm", .{}),
763 else => {
764 try leb.writeULEB128(writer, @as(u32, 1));
765 const val_type = try self.genValtype(return_type);
766 try writer.writeByte(val_type);
767 },
760 else => try returns.append(try self.typeToValtype(return_type)),
768761 }
762
763 return wasm.Type{
764 .params = params.toOwnedSlice(),
765 .returns = returns.toOwnedSlice(),
766 };
769767}
770768
771769pub fn genFunc(self: *Self) InnerError!Result {
772 try self.genFunctype();
773 // TODO: check for and handle death of instructions
770 var func_type = try self.genFunctype(self.decl.ty);
771 defer func_type.deinit(self.gpa);
772 self.decl.fn_link.wasm.type_index = try self.bin_file.putOrGetFuncType(func_type);
774773
775774 var cc_result = try self.resolveCallingConventionValues(self.decl.ty);
776775 defer cc_result.deinit(self.gpa);
......@@ -791,7 +790,7 @@ pub fn genFunc(self: *Self) InnerError!Result {
791790
792791 var emit: Emit = .{
793792 .mir = mir,
794 .bin_file = self.bin_file,
793 .bin_file = &self.bin_file.base,
795794 .code = &self.code,
796795 .locals = self.locals.items,
797796 .decl = self.decl,
......@@ -813,8 +812,10 @@ pub fn genFunc(self: *Self) InnerError!Result {
813812pub fn gen(self: *Self, ty: Type, val: Value) InnerError!Result {
814813 switch (ty.zigTypeTag()) {
815814 .Fn => {
816 try self.genFunctype();
817815 if (val.tag() == .extern_fn) {
816 var func_type = try self.genFunctype(self.decl.ty);
817 defer func_type.deinit(self.gpa);
818 self.decl.fn_link.wasm.type_index = try self.bin_file.putOrGetFuncType(func_type);
818819 return Result.appended; // don't need code body for extern functions
819820 }
820821 return self.fail("TODO implement wasm codegen for function pointers", .{});
......@@ -1079,7 +1080,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index) InnerError!WValue {
10791080 try self.emitWValue(arg_val);
10801081 }
10811082
1082 try self.addLabel(.call, target.link.wasm.symbol_index);
1083 try self.addLabel(.call, target.link.wasm.sym_index);
10831084
10841085 const ret_ty = target.ty.fnReturnType();
10851086 switch (ret_ty.zigTypeTag()) {
......@@ -1362,15 +1363,7 @@ fn emitConstant(self: *Self, val: Value, ty: Type) InnerError!void {
13621363 if (val.castTag(.decl_ref)) |payload| {
13631364 const decl = payload.data;
13641365 decl.alive = true;
1365
1366 // offset into the offset table within the 'data' section
1367 const ptr_width = self.target.cpu.arch.ptrBitWidth() / 8;
1368 try self.addImm32(@bitCast(i32, decl.link.wasm.offset_index * ptr_width));
1369
1370 // memory instruction followed by their memarg immediate
1371 // memarg ::== x:u32, y:u32 => {align x, offset y}
1372 const extra_index = try self.addExtra(Mir.MemArg{ .offset = 0, .alignment = 4 });
1373 try self.addInst(.{ .tag = .i32_load, .data = .{ .payload = extra_index } });
1366 try self.addLabel(.memory_address, decl.link.wasm.sym_index);
13741367 } else return self.fail("Wasm TODO: emitConstant for other const pointer tag {s}", .{val.tag()});
13751368 },
13761369 .Void => {},
src/arch/wasm/Emit.zig+30-14
......@@ -29,8 +29,6 @@ const InnerError = error{
2929
3030pub fn emitMir(emit: *Emit) InnerError!void {
3131 const mir_tags = emit.mir.instructions.items(.tag);
32 // Reserve space to write the size after generating the code.
33 try emit.code.resize(5);
3432 // write the locals in the prologue of the function body
3533 // before we emit the function body when lowering MIR
3634 try emit.emitLocals();
......@@ -51,6 +49,7 @@ pub fn emitMir(emit: *Emit) InnerError!void {
5149 .call => try emit.emitCall(inst),
5250 .global_get => try emit.emitGlobal(tag, inst),
5351 .global_set => try emit.emitGlobal(tag, inst),
52 .memory_address => try emit.emitMemAddress(inst),
5453
5554 // immediates
5655 .f32_const => try emit.emitFloat32(inst),
......@@ -157,11 +156,10 @@ pub fn emitMir(emit: *Emit) InnerError!void {
157156 .i64_extend32_s => try emit.emitTag(tag),
158157 }
159158 }
159}
160160
161 // Fill in the size of the generated code to the reserved space at the
162 // beginning of the buffer.
163 const size = emit.code.items.len - 5;
164 leb128.writeUnsignedFixed(5, emit.code.items[0..5], @intCast(u32, size));
161fn offset(self: Emit) u32 {
162 return @intCast(u32, self.code.items.len);
165163}
166164
167165fn fail(emit: *Emit, comptime format: []const u8, args: anytype) InnerError {
......@@ -216,9 +214,14 @@ fn emitGlobal(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) !void {
216214 try emit.code.append(@enumToInt(tag));
217215 var buf: [5]u8 = undefined;
218216 leb128.writeUnsignedFixed(5, &buf, label);
217 const global_offset = emit.offset();
219218 try emit.code.appendSlice(&buf);
220219
221 // TODO: Append label to the relocation list of this function
220 try emit.decl.link.wasm.relocs.append(emit.bin_file.allocator, .{
221 .index = label,
222 .offset = global_offset,
223 .relocation_type = .R_WASM_GLOBAL_INDEX_LEB,
224 });
222225}
223226
224227fn emitImm32(emit: *Emit, inst: Mir.Inst.Index) !void {
......@@ -261,16 +264,29 @@ fn emitMemArg(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) !void {
261264fn emitCall(emit: *Emit, inst: Mir.Inst.Index) !void {
262265 const label = emit.mir.instructions.items(.data)[inst].label;
263266 try emit.code.append(std.wasm.opcode(.call));
264 const offset = @intCast(u32, emit.code.items.len);
267 const call_offset = emit.offset();
265268 var buf: [5]u8 = undefined;
266269 leb128.writeUnsignedFixed(5, &buf, label);
267270 try emit.code.appendSlice(&buf);
268271
269 // The function index immediate argument will be filled in using this data
270 // in link.Wasm.flush().
271 // TODO: Replace this with proper relocations saved in the Atom.
272 try emit.decl.fn_link.wasm.idx_refs.append(emit.bin_file.allocator, .{
273 .offset = offset,
274 .decl = label,
272 try emit.decl.link.wasm.relocs.append(emit.bin_file.allocator, .{
273 .offset = call_offset,
274 .index = label,
275 .relocation_type = .R_WASM_FUNCTION_INDEX_LEB,
276 });
277}
278
279fn emitMemAddress(emit: *Emit, inst: Mir.Inst.Index) !void {
280 const symbol_index = emit.mir.instructions.items(.data)[inst].label;
281 try emit.code.append(std.wasm.opcode(.i32_const));
282 const mem_offset = emit.offset();
283 var buf: [5]u8 = undefined;
284 leb128.writeUnsignedFixed(5, &buf, symbol_index);
285 try emit.code.appendSlice(&buf);
286
287 try emit.decl.link.wasm.relocs.append(emit.bin_file.allocator, .{
288 .offset = mem_offset,
289 .index = symbol_index,
290 .relocation_type = .R_WASM_MEMORY_ADDR_LEB,
275291 });
276292}
src/arch/wasm/Mir.zig+6
......@@ -358,6 +358,12 @@ pub const Inst = struct {
358358 i64_extend16_s = 0xC3,
359359 /// Uses `tag`
360360 i64_extend32_s = 0xC4,
361 /// Contains a symbol to a memory address
362 /// Uses `label`
363 ///
364 /// Note: This uses `0xFF` as value as it is unused and not-reserved
365 /// by the wasm specification, making it safe to use
366 memory_address = 0xFF,
361367
362368 /// From a given wasm opcode, returns a MIR tag.
363369 pub fn fromOpcode(opcode: std.wasm.Opcode) Tag {
src/link/Wasm.zig+542-308
......@@ -10,6 +10,7 @@ const leb = std.leb;
1010const log = std.log.scoped(.link);
1111const wasm = std.wasm;
1212
13const Atom = @import("Wasm/Atom.zig");
1314const Module = @import("../Module.zig");
1415const Compilation = @import("../Compilation.zig");
1516const CodeGen = @import("../arch/wasm/CodeGen.zig");
......@@ -22,101 +23,78 @@ const TypedValue = @import("../TypedValue.zig");
2223const LlvmObject = @import("../codegen/llvm.zig").Object;
2324const Air = @import("../Air.zig");
2425const Liveness = @import("../Liveness.zig");
26const Symbol = @import("Wasm/Symbol.zig");
27const types = @import("Wasm/types.zig");
2528
2629pub const base_tag = link.File.Tag.wasm;
2730
31/// deprecated: Use `@import("Wasm/Atom.zig");`
32pub const DeclBlock = Atom;
33
2834base: link.File,
2935/// If this is not null, an object file is created by LLVM and linked with LLD afterwards.
3036llvm_object: ?*LlvmObject = null,
31/// List of all function Decls to be written to the output file. The index of
32/// each Decl in this list at the time of writing the binary is used as the
33/// function index. In the event where ext_funcs' size is not 0, the index of
34/// each function is added on top of the ext_funcs' length.
35/// TODO: can/should we access some data structure in Module directly?
36funcs: std.ArrayListUnmanaged(*Module.Decl) = .{},
37/// List of all extern function Decls to be written to the `import` section of the
38/// wasm binary. The position in the list defines the function index
39ext_funcs: std.ArrayListUnmanaged(*Module.Decl) = .{},
4037/// When importing objects from the host environment, a name must be supplied.
4138/// LLVM uses "env" by default when none is given. This would be a good default for Zig
4239/// to support existing code.
4340/// TODO: Allow setting this through a flag?
4441host_name: []const u8 = "env",
45/// The last `DeclBlock` that was initialized will be saved here.
46last_block: ?*DeclBlock = null,
47/// Table with offsets, each element represents an offset with the value being
48/// the offset into the 'data' section where the data lives
49offset_table: std.ArrayListUnmanaged(u32) = .{},
50/// List of offset indexes which are free to be used for new decl's.
51/// Each element's value points to an index into the offset_table.
52offset_table_free_list: std.ArrayListUnmanaged(u32) = .{},
5342/// List of all `Decl` that are currently alive.
5443/// This is ment for bookkeeping so we can safely cleanup all codegen memory
5544/// when calling `deinit`
56symbols: std.ArrayListUnmanaged(*Module.Decl) = .{},
45decls: std.AutoHashMapUnmanaged(*Module.Decl, void) = .{},
46/// List of all symbols.
47symbols: std.ArrayListUnmanaged(Symbol) = .{},
5748/// List of symbol indexes which are free to be used.
5849symbols_free_list: std.ArrayListUnmanaged(u32) = .{},
50/// Maps atoms to their segment index
51atoms: std.AutoHashMapUnmanaged(u32, *Atom) = .{},
52/// Represents the index into `segments` where the 'code' section
53/// lives.
54code_section_index: ?u32 = null,
55/// The count of imported functions. This number will be appended
56/// to the function indexes as their index starts at the lowest non-extern function.
57imported_functions_count: u32 = 0,
58/// Map of symbol indexes, represented by its `wasm.Import`
59imports: std.AutoHashMapUnmanaged(u32, wasm.Import) = .{},
60/// Represents non-synthetic section entries.
61/// Used for code, data and custom sections.
62segments: std.ArrayListUnmanaged(Segment) = .{},
63/// Maps a data segment key (such as .rodata) to the index into `segments`.
64data_segments: std.StringArrayHashMapUnmanaged(u32) = .{},
65/// A list of `types.Segment` which provide meta data
66/// about a data symbol such as its name
67segment_info: std.ArrayListUnmanaged(types.Segment) = .{},
68
69// Output sections
70/// Output type section
71func_types: std.ArrayListUnmanaged(wasm.Type) = .{},
72/// Output function section
73functions: std.ArrayListUnmanaged(wasm.Func) = .{},
74/// Output global section
75globals: std.ArrayListUnmanaged(wasm.Global) = .{},
76/// Memory section
77memories: wasm.Memory = .{ .limits = .{ .min = 0, .max = null } },
78
79/// Indirect function table, used to call function pointers
80/// When this is non-zero, we must emit a table entry,
81/// as well as an 'elements' section.
82function_table: std.ArrayListUnmanaged(Symbol) = .{},
83
84pub const Segment = struct {
85 alignment: u32,
86 size: u32,
87 offset: u32,
88};
5989
6090pub const FnData = struct {
61 /// Generated code for the type of the function
62 functype: std.ArrayListUnmanaged(u8),
63 /// Generated code for the body of the function
64 code: std.ArrayListUnmanaged(u8),
65 /// Locations in the generated code where function indexes must be filled in.
66 /// This must be kept ordered by offset.
67 /// `decl` is the symbol_index of the target.
68 idx_refs: std.ArrayListUnmanaged(struct { offset: u32, decl: u32 }),
91 type_index: u32,
6992
7093 pub const empty: FnData = .{
71 .functype = .{},
72 .code = .{},
73 .idx_refs = .{},
94 .type_index = undefined,
7495 };
7596};
7697
77pub const DeclBlock = struct {
78 /// Determines whether the `DeclBlock` has been initialized for codegen.
79 init: bool,
80 /// Index into the `symbols` list.
81 symbol_index: u32,
82 /// Index into the offset table
83 offset_index: u32,
84 /// The size of the block and how large part of the data section it occupies.
85 /// Will be 0 when the Decl will not live inside the data section and `data` will be undefined.
86 size: u32,
87 /// Points to the previous and next blocks.
88 /// Can be used to find the total size, and used to calculate the `offset` based on the previous block.
89 prev: ?*DeclBlock,
90 next: ?*DeclBlock,
91 /// Pointer to data that will be written to the 'data' section.
92 /// This data either lives in `FnData.code` or is externally managed.
93 /// For data that does not live inside the 'data' section, this field will be undefined. (size == 0).
94 data: [*]const u8,
95
96 pub const empty: DeclBlock = .{
97 .init = false,
98 .symbol_index = 0,
99 .offset_index = 0,
100 .size = 0,
101 .prev = null,
102 .next = null,
103 .data = undefined,
104 };
105
106 /// Unplugs the `DeclBlock` from the chain
107 fn unplug(self: *DeclBlock) void {
108 if (self.prev) |prev| {
109 prev.next = self.next;
110 }
111
112 if (self.next) |next| {
113 next.prev = self.prev;
114 }
115 self.next = null;
116 self.prev = null;
117 }
118};
119
12098pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Options) !*Wasm {
12199 assert(options.object_format == .wasm);
122100
......@@ -139,6 +117,22 @@ pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Optio
139117
140118 try file.writeAll(&(wasm.magic ++ wasm.version));
141119
120 // As sym_index '0' is reserved, we use it for our stack pointer symbol
121 const global = try wasm_bin.globals.addOne(allocator);
122 global.* = .{
123 .global_type = .{
124 .valtype = .i32,
125 .mutable = true,
126 },
127 .init = .{ .i32_const = 0 },
128 };
129 const symbol = try wasm_bin.symbols.addOne(allocator);
130 symbol.* = .{
131 .name = "__stack_pointer",
132 .tag = .global,
133 .flags = 0,
134 .index = 0,
135 };
142136 return wasm_bin;
143137}
144138
......@@ -160,63 +154,57 @@ pub fn deinit(self: *Wasm) void {
160154 if (self.llvm_object) |llvm_object| llvm_object.destroy(self.base.allocator);
161155 }
162156
163 for (self.symbols.items) |decl, symbol_index| {
164 // Check if we already freed all memory for the symbol
165 // TODO: Audit this when we refactor the linker.
166 var already_freed = false;
167 for (self.symbols_free_list.items) |index| {
168 if (symbol_index == index) {
169 already_freed = true;
170 break;
171 }
172 }
173 if (already_freed) continue;
174 decl.fn_link.wasm.functype.deinit(self.base.allocator);
175 decl.fn_link.wasm.code.deinit(self.base.allocator);
176 decl.fn_link.wasm.idx_refs.deinit(self.base.allocator);
157 var decl_it = self.decls.keyIterator();
158 while (decl_it.next()) |decl_ptr| {
159 const decl = decl_ptr.*;
160 decl.link.wasm.deinit(self.base.allocator);
177161 }
178162
179 self.funcs.deinit(self.base.allocator);
180 self.ext_funcs.deinit(self.base.allocator);
181 self.offset_table.deinit(self.base.allocator);
182 self.offset_table_free_list.deinit(self.base.allocator);
163 for (self.func_types.items) |func_type| {
164 self.base.allocator.free(func_type.params);
165 self.base.allocator.free(func_type.returns);
166 }
167 for (self.segment_info.items) |segment_info| {
168 self.base.allocator.free(segment_info.name);
169 }
170
171 self.decls.deinit(self.base.allocator);
183172 self.symbols.deinit(self.base.allocator);
184173 self.symbols_free_list.deinit(self.base.allocator);
174 self.atoms.deinit(self.base.allocator);
175 self.segments.deinit(self.base.allocator);
176 self.data_segments.deinit(self.base.allocator);
177 self.segment_info.deinit(self.base.allocator);
178
179 // free output sections
180 self.imports.deinit(self.base.allocator);
181 self.func_types.deinit(self.base.allocator);
182 self.functions.deinit(self.base.allocator);
183 self.globals.deinit(self.base.allocator);
184 self.function_table.deinit(self.base.allocator);
185185}
186186
187187pub fn allocateDeclIndexes(self: *Wasm, decl: *Module.Decl) !void {
188 if (decl.link.wasm.init) return;
188 if (decl.link.wasm.sym_index != 0) return;
189189
190 try self.offset_table.ensureUnusedCapacity(self.base.allocator, 1);
191190 try self.symbols.ensureUnusedCapacity(self.base.allocator, 1);
191 try self.decls.putNoClobber(self.base.allocator, decl, {});
192192
193 const block = &decl.link.wasm;
194 block.init = true;
193 const atom = &decl.link.wasm;
195194
196 if (self.offset_table_free_list.popOrNull()) |index| {
197 block.offset_index = index;
198 } else {
199 block.offset_index = @intCast(u32, self.offset_table.items.len);
200 _ = self.offset_table.addOneAssumeCapacity();
201 }
195 var symbol: Symbol = .{
196 .name = undefined, // will be set after updateDecl
197 .flags = 0,
198 .tag = undefined, // will be set after updateDecl
199 .index = undefined, // will be set after updateDecl
200 };
202201
203202 if (self.symbols_free_list.popOrNull()) |index| {
204 block.symbol_index = index;
205 self.symbols.items[block.symbol_index] = decl;
203 atom.sym_index = index;
204 self.symbols.items[index] = symbol;
206205 } else {
207 block.symbol_index = @intCast(u32, self.symbols.items.len);
208 self.symbols.appendAssumeCapacity(decl);
209 }
210
211 self.offset_table.items[block.offset_index] = 0;
212
213 if (decl.ty.zigTypeTag() == .Fn) {
214 switch (decl.val.tag()) {
215 // dependent on function type, appends it to the correct list
216 .function => try self.funcs.append(self.base.allocator, decl),
217 .extern_fn => try self.ext_funcs.append(self.base.allocator, decl),
218 else => unreachable,
219 }
206 atom.sym_index = @intCast(u32, self.symbols.items.len);
207 self.symbols.appendAssumeCapacity(symbol);
220208 }
221209}
222210
......@@ -228,25 +216,21 @@ pub fn updateFunc(self: *Wasm, module: *Module, func: *Module.Fn, air: Air, live
228216 if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(module, func, air, liveness);
229217 }
230218 const decl = func.owner_decl;
231 assert(decl.link.wasm.init); // Must call allocateDeclIndexes()
219 assert(decl.link.wasm.sym_index != 0); // Must call allocateDeclIndexes()
232220
233 const fn_data = &decl.fn_link.wasm;
234 fn_data.functype.items.len = 0;
235 fn_data.code.items.len = 0;
236 fn_data.idx_refs.items.len = 0;
221 decl.link.wasm.clear();
237222
238223 var codegen: CodeGen = .{
239224 .gpa = self.base.allocator,
240225 .air = air,
241226 .liveness = liveness,
242227 .values = .{},
243 .code = fn_data.code.toManaged(self.base.allocator),
244 .func_type_data = fn_data.functype.toManaged(self.base.allocator),
228 .code = std.ArrayList(u8).init(self.base.allocator),
245229 .decl = decl,
246230 .err_msg = undefined,
247231 .locals = .{},
248232 .target = self.base.options.target,
249 .bin_file = &self.base,
233 .bin_file = self,
250234 .global_error_set = self.base.options.module.?.global_error_set,
251235 };
252236 defer codegen.deinit();
......@@ -272,26 +256,21 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void {
272256 if (build_options.have_llvm) {
273257 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(module, decl);
274258 }
275 assert(decl.link.wasm.init); // Must call allocateDeclIndexes()
259 assert(decl.link.wasm.sym_index != 0); // Must call allocateDeclIndexes()
276260
277 // TODO don't use this for non-functions
278 const fn_data = &decl.fn_link.wasm;
279 fn_data.functype.items.len = 0;
280 fn_data.code.items.len = 0;
281 fn_data.idx_refs.items.len = 0;
261 decl.link.wasm.clear();
282262
283263 var codegen: CodeGen = .{
284264 .gpa = self.base.allocator,
285265 .air = undefined,
286266 .liveness = undefined,
287267 .values = .{},
288 .code = fn_data.code.toManaged(self.base.allocator),
289 .func_type_data = fn_data.functype.toManaged(self.base.allocator),
268 .code = std.ArrayList(u8).init(self.base.allocator),
290269 .decl = decl,
291270 .err_msg = undefined,
292271 .locals = .{},
293272 .target = self.base.options.target,
294 .bin_file = &self.base,
273 .bin_file = self,
295274 .global_error_set = self.base.options.module.?.global_error_set,
296275 };
297276 defer codegen.deinit();
......@@ -310,33 +289,19 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void {
310289}
311290
312291fn finishUpdateDecl(self: *Wasm, decl: *Module.Decl, result: CodeGen.Result, codegen: *CodeGen) !void {
313 const fn_data: *FnData = &decl.fn_link.wasm;
314
315 fn_data.code = codegen.code.toUnmanaged();
316 fn_data.functype = codegen.func_type_data.toUnmanaged();
317
318292 const code: []const u8 = switch (result) {
319 .appended => @as([]const u8, fn_data.code.items),
293 .appended => @as([]const u8, codegen.code.items),
320294 .externally_managed => |payload| payload,
321295 };
322296
323 const block = &decl.link.wasm;
324 if (decl.ty.zigTypeTag() != .Fn) {
325 block.size = @intCast(u32, code.len);
326 block.data = code.ptr;
297 if (decl.isExtern()) {
298 try self.addOrUpdateImport(decl);
327299 }
328300
329 // If we're updating an existing decl, unplug it first
330 // to avoid infinite loops due to earlier links
331 block.unplug();
332
333 if (self.last_block) |last| {
334 if (last != block) {
335 last.next = block;
336 block.prev = last;
337 }
338 }
339 self.last_block = block;
301 if (code.len == 0) return;
302 const atom: *Atom = &decl.link.wasm;
303 atom.size = @intCast(u32, code.len);
304 try atom.code.appendSlice(self.base.allocator, code);
340305}
341306
342307pub fn updateDeclExports(
......@@ -357,30 +322,240 @@ pub fn freeDecl(self: *Wasm, decl: *Module.Decl) void {
357322 if (build_options.have_llvm) {
358323 if (self.llvm_object) |llvm_object| return llvm_object.freeDecl(decl);
359324 }
325 const atom = &decl.link.wasm;
326 self.symbols_free_list.append(self.base.allocator, atom.sym_index) catch {};
327 atom.deinit(self.base.allocator);
328 _ = self.decls.remove(decl);
329
330 if (decl.isExtern()) {
331 const import = self.imports.fetchRemove(decl.link.wasm.sym_index).?.value;
332 switch (import.kind) {
333 .function => self.imported_functions_count -= 1,
334 else => unreachable,
335 }
336 }
337}
338
339fn addOrUpdateImport(self: *Wasm, decl: *Module.Decl) !void {
340 const symbol_index = decl.link.wasm.sym_index;
341 const symbol: *Symbol = &self.symbols.items[symbol_index];
342 symbol.name = decl.name;
343 symbol.setUndefined(true);
344 switch (decl.ty.zigTypeTag()) {
345 .Fn => {
346 const gop = try self.imports.getOrPut(self.base.allocator, symbol_index);
347 if (!gop.found_existing) {
348 self.imported_functions_count += 1;
349 gop.value_ptr.* = .{
350 .module_name = self.host_name,
351 .name = std.mem.span(symbol.name),
352 .kind = .{ .function = decl.fn_link.wasm.type_index },
353 };
354 }
355 },
356 else => @panic("TODO: Implement undefined symbols for non-function declarations"),
357 }
358}
359
360fn parseDeclIntoAtom(self: *Wasm, decl: *Module.Decl) !void {
361 const atom: *Atom = &decl.link.wasm;
362 const symbol: *Symbol = &self.symbols.items[atom.sym_index];
363 symbol.name = decl.name;
364 atom.alignment = decl.ty.abiAlignment(self.base.options.target);
365 const final_index: u32 = switch (decl.ty.zigTypeTag()) {
366 .Fn => result: {
367 const fn_data = decl.fn_link.wasm;
368 const type_index = fn_data.type_index;
369 const index = @intCast(u32, self.functions.items.len + self.imported_functions_count);
370 try self.functions.append(self.base.allocator, .{ .type_index = type_index });
371 symbol.tag = .function;
372 symbol.index = index;
373
374 if (self.code_section_index == null) {
375 self.code_section_index = @intCast(u32, self.segments.items.len);
376 try self.segments.append(self.base.allocator, .{
377 .alignment = atom.alignment,
378 .size = atom.size,
379 .offset = 0,
380 });
381 }
382
383 break :result self.code_section_index.?;
384 },
385 else => result: {
386 const gop = try self.data_segments.getOrPut(self.base.allocator, ".rodata");
387 const atom_index = if (gop.found_existing) blk: {
388 self.segments.items[gop.value_ptr.*].size += atom.size;
389 break :blk gop.value_ptr.*;
390 } else blk: {
391 const index = @intCast(u32, self.segments.items.len);
392 try self.segments.append(self.base.allocator, .{
393 .alignment = atom.alignment,
394 .size = 0,
395 .offset = 0,
396 });
397 gop.value_ptr.* = index;
398 break :blk index;
399 };
400 const info_index = @intCast(u32, self.segment_info.items.len);
401 const segment_name = try std.mem.concat(self.base.allocator, u8, &.{
402 ".rodata.",
403 std.mem.span(symbol.name),
404 });
405 errdefer self.base.allocator.free(segment_name);
406 try self.segment_info.append(self.base.allocator, .{
407 .name = segment_name,
408 .alignment = atom.alignment,
409 .flags = 0,
410 });
411 symbol.tag = .data;
412 symbol.index = info_index;
413 atom.alignment = decl.ty.abiAlignment(self.base.options.target);
414
415 break :result atom_index;
416 },
417 };
418
419 const segment: *Segment = &self.segments.items[final_index];
420 segment.alignment = std.math.max(segment.alignment, atom.alignment);
421 segment.size = std.mem.alignForwardGeneric(
422 u32,
423 std.mem.alignForwardGeneric(u32, segment.size, atom.alignment) + atom.size,
424 segment.alignment,
425 );
426
427 if (self.atoms.getPtr(final_index)) |last| {
428 last.*.next = atom;
429 atom.prev = last.*;
430 last.* = atom;
431 } else {
432 try self.atoms.putNoClobber(self.base.allocator, final_index, atom);
433 }
434}
360435
361 if (self.getFuncidx(decl)) |func_idx| {
362 switch (decl.val.tag()) {
363 .function => _ = self.funcs.swapRemove(func_idx),
364 .extern_fn => _ = self.ext_funcs.swapRemove(func_idx),
436fn allocateAtoms(self: *Wasm) !void {
437 var it = self.atoms.iterator();
438 while (it.next()) |entry| {
439 var atom: *Atom = entry.value_ptr.*.getFirst();
440 var offset: u32 = 0;
441 while (true) {
442 offset = std.mem.alignForwardGeneric(u32, offset, atom.alignment);
443 atom.offset = offset;
444 log.debug("Atom '{s}' allocated from 0x{x:0>8} to 0x{x:0>8} size={d}", .{
445 self.symbols.items[atom.sym_index].name,
446 offset,
447 offset + atom.size,
448 atom.size,
449 });
450 offset += atom.size;
451 atom = atom.next orelse break;
452 }
453 }
454}
455
456fn setupImports(self: *Wasm) void {
457 var function_index: u32 = 0;
458 var it = self.imports.iterator();
459 while (it.next()) |entry| {
460 const symbol = &self.symbols.items[entry.key_ptr.*];
461 const import: wasm.Import = entry.value_ptr.*;
462 switch (import.kind) {
463 .function => {
464 symbol.index = function_index;
465 function_index += 1;
466 },
365467 else => unreachable,
366468 }
367469 }
368 const block = &decl.link.wasm;
470}
369471
370 if (self.last_block == block) {
371 self.last_block = block.prev;
472/// Sets up the memory section of the wasm module, as well as the stack.
473fn setupMemory(self: *Wasm) !void {
474 log.debug("Setting up memory layout", .{});
475 const page_size = 64 * 1024;
476 const stack_size = self.base.options.stack_size_override orelse page_size * 1;
477 const stack_alignment = 16;
478 var memory_ptr: u64 = self.base.options.global_base orelse 1024;
479 memory_ptr = std.mem.alignForwardGeneric(u64, memory_ptr, stack_alignment);
480
481 var offset: u32 = @intCast(u32, memory_ptr);
482 for (self.segments.items) |*segment, i| {
483 // skip 'code' segments
484 if (self.code_section_index) |index| {
485 if (index == i) continue;
486 }
487 memory_ptr = std.mem.alignForwardGeneric(u64, memory_ptr, segment.alignment);
488 memory_ptr += segment.size;
489 segment.offset = offset;
490 offset += segment.size;
372491 }
373492
374 block.unplug();
493 memory_ptr = std.mem.alignForwardGeneric(u64, memory_ptr, stack_alignment);
494 memory_ptr += stack_size;
495
496 // Setup the max amount of pages
497 // For now we only support wasm32 by setting the maximum allowed memory size 2^32-1
498 const max_memory_allowed: u64 = (1 << 32) - 1;
375499
376 self.offset_table_free_list.append(self.base.allocator, decl.link.wasm.offset_index) catch {};
377 self.symbols_free_list.append(self.base.allocator, block.symbol_index) catch {};
500 if (self.base.options.initial_memory) |initial_memory| {
501 if (!std.mem.isAlignedGeneric(u64, initial_memory, page_size)) {
502 log.err("Initial memory must be {d}-byte aligned", .{page_size});
503 return error.MissAlignment;
504 }
505 if (memory_ptr > initial_memory) {
506 log.err("Initial memory too small, must be at least {d} bytes", .{memory_ptr});
507 return error.MemoryTooSmall;
508 }
509 if (initial_memory > max_memory_allowed) {
510 log.err("Initial memory exceeds maximum memory {d}", .{max_memory_allowed});
511 return error.MemoryTooBig;
512 }
513 memory_ptr = initial_memory;
514 }
378515
379 block.init = false;
516 // In case we do not import memory, but define it ourselves,
517 // set the minimum amount of pages on the memory section.
518 self.memories.limits.min = @intCast(u32, std.mem.alignForwardGeneric(u64, memory_ptr, page_size) / page_size);
519 log.debug("Total memory pages: {d}", .{self.memories.limits.min});
380520
381 decl.fn_link.wasm.functype.deinit(self.base.allocator);
382 decl.fn_link.wasm.code.deinit(self.base.allocator);
383 decl.fn_link.wasm.idx_refs.deinit(self.base.allocator);
521 if (self.base.options.max_memory) |max_memory| {
522 if (!std.mem.isAlignedGeneric(u64, max_memory, page_size)) {
523 log.err("Maximum memory must be {d}-byte aligned", .{page_size});
524 return error.MissAlignment;
525 }
526 if (memory_ptr > max_memory) {
527 log.err("Maxmimum memory too small, must be at least {d} bytes", .{memory_ptr});
528 return error.MemoryTooSmall;
529 }
530 if (max_memory > max_memory_allowed) {
531 log.err("Maximum memory exceeds maxmium amount {d}", .{max_memory_allowed});
532 return error.MemoryTooBig;
533 }
534 self.memories.limits.max = @intCast(u32, max_memory / page_size);
535 log.debug("Maximum memory pages: {d}", .{self.memories.limits.max});
536 }
537
538 // We always put the stack pointer global at index 0
539 self.globals.items[0].init.i32_const = @bitCast(i32, @intCast(u32, memory_ptr));
540}
541
542fn resetState(self: *Wasm) void {
543 for (self.segment_info.items) |*segment_info| {
544 self.base.allocator.free(segment_info.name);
545 }
546 var decl_it = self.decls.keyIterator();
547 while (decl_it.next()) |decl| {
548 const atom = &decl.*.link.wasm;
549 atom.next = null;
550 atom.prev = null;
551 }
552 self.functions.clearRetainingCapacity();
553 self.segments.clearRetainingCapacity();
554 self.segment_info.clearRetainingCapacity();
555 self.data_segments.clearRetainingCapacity();
556 self.function_table.clearRetainingCapacity();
557 self.atoms.clearRetainingCapacity();
558 self.code_section_index = null;
384559}
385560
386561pub fn flush(self: *Wasm, comp: *Compilation) !void {
......@@ -396,29 +571,21 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void {
396571 const tracy = trace(@src());
397572 defer tracy.end();
398573
574 // When we finish/error we reset the state of the linker
575 // So we can rebuild the binary file on each incremental update
576 defer self.resetState();
577 self.setupImports();
578 var decl_it = self.decls.keyIterator();
579 while (decl_it.next()) |decl| {
580 if (decl.*.isExtern()) continue;
581 try self.parseDeclIntoAtom(decl.*);
582 }
583
584 try self.setupMemory();
585 try self.allocateAtoms();
586
399587 const file = self.base.file.?;
400588 const header_size = 5 + 1;
401 // ptr_width in bytes
402 const ptr_width = self.base.options.target.cpu.arch.ptrBitWidth() / 8;
403 // The size of the offset table in bytes
404 // The table contains all decl's with its corresponding offset into
405 // the 'data' section
406 const offset_table_size = @intCast(u32, self.offset_table.items.len * ptr_width);
407 // The size of the emulated stack
408 const stack_size = @intCast(u32, self.base.options.stack_size_override orelse std.wasm.page_size);
409
410 // The size of the data, this together with `offset_table_size` amounts to the
411 // total size of the 'data' section
412 var first_decl: ?*DeclBlock = null;
413 const data_size: u32 = if (self.last_block) |last| blk: {
414 var size = last.size;
415 var cur = last;
416 while (cur.prev) |prev| : (cur = prev) {
417 size += prev.size;
418 }
419 first_decl = cur;
420 break :blk size;
421 } else 0;
422589
423590 // No need to rewrite the magic/version header
424591 try file.setEndPos(@sizeOf(@TypeOf(wasm.magic ++ wasm.version)));
......@@ -427,38 +594,46 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void {
427594 // Type section
428595 {
429596 const header_offset = try reserveVecSectionHeader(file);
597 const writer = file.writer();
430598
431 // extern functions are defined in the wasm binary first through the `import`
432 // section, so define their func types first
433 for (self.ext_funcs.items) |decl| try file.writeAll(decl.fn_link.wasm.functype.items);
434 for (self.funcs.items) |decl| try file.writeAll(decl.fn_link.wasm.functype.items);
599 for (self.func_types.items) |func_type| {
600 try leb.writeULEB128(writer, wasm.function_type);
601 try leb.writeULEB128(writer, @intCast(u32, func_type.params.len));
602 for (func_type.params) |param_ty| try leb.writeULEB128(writer, wasm.valtype(param_ty));
603 try leb.writeULEB128(writer, @intCast(u32, func_type.returns.len));
604 for (func_type.returns) |ret_ty| try leb.writeULEB128(writer, wasm.valtype(ret_ty));
605 }
435606
436607 try writeVecSectionHeader(
437608 file,
438609 header_offset,
439610 .type,
440611 @intCast(u32, (try file.getPos()) - header_offset - header_size),
441 @intCast(u32, self.ext_funcs.items.len + self.funcs.items.len),
612 @intCast(u32, self.func_types.items.len),
442613 );
443614 }
444615
445616 // Import section
446 {
447 // TODO: implement non-functions imports
617 const import_mem = self.base.options.import_memory;
618 if (self.imports.count() != 0 or import_mem) {
448619 const header_offset = try reserveVecSectionHeader(file);
449620 const writer = file.writer();
450 for (self.ext_funcs.items) |decl, typeidx| {
451 try leb.writeULEB128(writer, @intCast(u32, self.host_name.len));
452 try writer.writeAll(self.host_name);
453621
454 // wasm requires the length of the import name with no null-termination
455 const decl_len = mem.len(decl.name);
456 try leb.writeULEB128(writer, @intCast(u32, decl_len));
457 try writer.writeAll(decl.name[0..decl_len]);
622 var it = self.imports.iterator();
623 while (it.next()) |entry| {
624 const import_symbol = self.symbols.items[entry.key_ptr.*];
625 std.debug.assert(import_symbol.isUndefined());
626 const import = entry.value_ptr.*;
627 try emitImport(writer, import);
628 }
458629
459 // emit kind and the function type
460 try writer.writeByte(wasm.externalKind(.function));
461 try leb.writeULEB128(writer, @intCast(u32, typeidx));
630 if (import_mem) {
631 const mem_imp: wasm.Import = .{
632 .module_name = self.host_name,
633 .name = "memory",
634 .kind = .{ .memory = self.memories.limits },
635 };
636 try emitImport(writer, mem_imp);
462637 }
463638
464639 try writeVecSectionHeader(
......@@ -466,7 +641,7 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void {
466641 header_offset,
467642 .import,
468643 @intCast(u32, (try file.getPos()) - header_offset - header_size),
469 @intCast(u32, self.ext_funcs.items.len),
644 @intCast(u32, self.imports.count() + @boolToInt(import_mem)),
470645 );
471646 }
472647
......@@ -474,9 +649,8 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void {
474649 {
475650 const header_offset = try reserveVecSectionHeader(file);
476651 const writer = file.writer();
477 for (self.funcs.items) |_, typeidx| {
478 const func_idx = @intCast(u32, self.getFuncIdxOffset() + typeidx);
479 try leb.writeULEB128(writer, func_idx);
652 for (self.functions.items) |function| {
653 try leb.writeULEB128(writer, function.type_index);
480654 }
481655
482656 try writeVecSectionHeader(
......@@ -484,26 +658,16 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void {
484658 header_offset,
485659 .function,
486660 @intCast(u32, (try file.getPos()) - header_offset - header_size),
487 @intCast(u32, self.funcs.items.len),
661 @intCast(u32, self.functions.items.len),
488662 );
489663 }
490664
491665 // Memory section
492 {
666 if (!self.base.options.import_memory) {
493667 const header_offset = try reserveVecSectionHeader(file);
494668 const writer = file.writer();
495669
496 try leb.writeULEB128(writer, @as(u32, 0));
497 // Calculate the amount of memory pages are required and write them.
498 // Wasm uses 64kB page sizes. Round up to ensure the data segments fit into the memory
499 try leb.writeULEB128(
500 writer,
501 try std.math.divCeil(
502 u32,
503 offset_table_size + data_size + stack_size,
504 std.wasm.page_size,
505 ),
506 );
670 try emitLimits(writer, self.memories.limits);
507671 try writeVecSectionHeader(
508672 file,
509673 header_offset,
......@@ -515,29 +679,21 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void {
515679
516680 // Global section (used to emit stack pointer)
517681 {
518 // We emit the emulated stack at the end of the data section,
519 // 'growing' downwards towards the program memory.
520 // TODO: Have linker resolve the offset table, so we can emit the stack
521 // at the start so we can't overwrite program memory with the stack.
522 const sp_value = offset_table_size + data_size + std.wasm.page_size;
523 const mutable = true; // stack pointer MUST be mutable
524682 const header_offset = try reserveVecSectionHeader(file);
525683 const writer = file.writer();
526684
527 try writer.writeByte(wasm.valtype(.i32));
528 try writer.writeByte(@boolToInt(mutable));
529
530 // set the initial value of the stack pointer to the data size + stack size
531 try writer.writeByte(wasm.opcode(.i32_const));
532 try leb.writeILEB128(writer, @bitCast(i32, sp_value));
533 try writer.writeByte(wasm.opcode(.end));
685 for (self.globals.items) |global| {
686 try writer.writeByte(wasm.valtype(global.global_type.valtype));
687 try writer.writeByte(@boolToInt(global.global_type.mutable));
688 try emitInit(writer, global.init);
689 }
534690
535691 try writeVecSectionHeader(
536692 file,
537693 header_offset,
538694 .global,
539695 @intCast(u32, (try file.getPos()) - header_offset - header_size),
540 @as(u32, 1),
696 @intCast(u32, self.globals.items.len),
541697 );
542698 }
543699
......@@ -554,10 +710,13 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void {
554710
555711 switch (exprt.exported_decl.ty.zigTypeTag()) {
556712 .Fn => {
713 const target = exprt.exported_decl.link.wasm.sym_index;
714 const target_symbol = self.symbols.items[target];
715 std.debug.assert(target_symbol.tag == .function);
557716 // Type of the export
558717 try writer.writeByte(wasm.externalKind(.function));
559718 // Exported function index
560 try leb.writeULEB128(writer, self.getFuncidx(exprt.exported_decl).?);
719 try leb.writeULEB128(writer, target_symbol.index);
561720 },
562721 else => return error.TODOImplementNonFnDeclsForWasm,
563722 }
......@@ -567,7 +726,7 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void {
567726 }
568727
569728 // export memory if size is not 0
570 if (data_size != 0) {
729 if (!self.base.options.import_memory) {
571730 try leb.writeULEB128(writer, @intCast(u32, "memory".len));
572731 try writer.writeAll("memory");
573732 try writer.writeByte(wasm.externalKind(.memory));
......@@ -585,75 +744,143 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void {
585744 }
586745
587746 // Code section
588 {
747 if (self.code_section_index) |code_index| {
589748 const header_offset = try reserveVecSectionHeader(file);
590749 const writer = file.writer();
591 for (self.funcs.items) |decl| {
592 const fn_data = &decl.fn_link.wasm;
593
594 // Write the already generated code to the file, inserting
595 // function indexes where required.
596 for (fn_data.idx_refs.items) |idx_ref| {
597 const relocatable_decl = self.symbols.items[idx_ref.decl];
598 const index = self.getFuncidx(relocatable_decl).?;
599 leb.writeUnsignedFixed(5, fn_data.code.items[idx_ref.offset..][0..5], index);
600 }
601 try writer.writeAll(fn_data.code.items);
750 var atom: *Atom = self.atoms.get(code_index).?.getFirst();
751 while (true) {
752 try atom.resolveRelocs(self);
753 try leb.writeULEB128(writer, atom.size);
754 try writer.writeAll(atom.code.items);
755 atom = atom.next orelse break;
602756 }
603757 try writeVecSectionHeader(
604758 file,
605759 header_offset,
606760 .code,
607761 @intCast(u32, (try file.getPos()) - header_offset - header_size),
608 @intCast(u32, self.funcs.items.len),
762 @intCast(u32, self.functions.items.len),
609763 );
610764 }
611765
612766 // Data section
613 if (data_size != 0) {
767 if (self.data_segments.count() != 0) {
614768 const header_offset = try reserveVecSectionHeader(file);
615769 const writer = file.writer();
616 // index to memory section (currently, there can only be 1 memory section in wasm)
617 try leb.writeULEB128(writer, @as(u32, 0));
618
619 // offset into data section
620 try writer.writeByte(wasm.opcode(.i32_const));
621 try leb.writeILEB128(writer, @as(i32, 0));
622 try writer.writeByte(wasm.opcode(.end));
623
624 const total_size = offset_table_size + data_size;
625
626 // offset table + data size
627 try leb.writeULEB128(writer, total_size);
628770
629 // fill in the offset table and the data segments
630 const file_offset = try file.getPos();
631 var cur = first_decl;
632 var data_offset = offset_table_size;
633 while (cur) |cur_block| : (cur = cur_block.next) {
634 if (cur_block.size == 0) continue;
635 assert(cur_block.init);
636
637 const offset = (cur_block.offset_index) * ptr_width;
638 var buf: [4]u8 = undefined;
639 std.mem.writeIntLittle(u32, &buf, data_offset);
640
641 try file.pwriteAll(&buf, file_offset + offset);
642 try file.pwriteAll(cur_block.data[0..cur_block.size], file_offset + data_offset);
643 data_offset += cur_block.size;
771 var it = self.data_segments.iterator();
772 var segment_count: u32 = 0;
773 while (it.next()) |entry| {
774 // do not output 'bss' section
775 if (std.mem.eql(u8, entry.key_ptr.*, ".bss")) continue;
776 segment_count += 1;
777 const atom_index = entry.value_ptr.*;
778 var atom: *Atom = self.atoms.getPtr(atom_index).?.*.getFirst();
779 var segment = self.segments.items[atom_index];
780
781 // flag and index to memory section (currently, there can only be 1 memory section in wasm)
782 try leb.writeULEB128(writer, @as(u32, 0));
783 // offset into data section
784 try emitInit(writer, .{ .i32_const = @bitCast(i32, segment.offset) });
785 try leb.writeULEB128(writer, segment.size);
786
787 // fill in the offset table and the data segments
788 var current_offset: u32 = 0;
789 while (true) {
790 try atom.resolveRelocs(self);
791
792 // Pad with zeroes to ensure all segments are aligned
793 if (current_offset != atom.offset) {
794 const diff = atom.offset - current_offset;
795 try writer.writeByteNTimes(0, diff);
796 current_offset += diff;
797 }
798 std.debug.assert(current_offset == atom.offset);
799 std.debug.assert(atom.code.items.len == atom.size);
800 try writer.writeAll(atom.code.items);
801
802 current_offset += atom.size;
803 if (atom.next) |next| {
804 atom = next;
805 } else {
806 // also pad with zeroes when last atom to ensure
807 // segments are aligned.
808 if (current_offset != segment.size) {
809 try writer.writeByteNTimes(0, segment.size - current_offset);
810 }
811 break;
812 }
813 }
644814 }
645815
646 try file.seekTo(file_offset + data_offset);
647816 try writeVecSectionHeader(
648817 file,
649818 header_offset,
650819 .data,
651 @intCast(u32, (file_offset + data_offset) - header_offset - header_size),
652 @intCast(u32, 1), // only 1 data section
820 @intCast(u32, (try file.getPos()) - header_offset - header_size),
821 @intCast(u32, segment_count),
653822 );
654823 }
655824}
656825
826fn emitLimits(writer: anytype, limits: wasm.Limits) !void {
827 try leb.writeULEB128(writer, @boolToInt(limits.max != null));
828 try leb.writeULEB128(writer, limits.min);
829 if (limits.max) |max| {
830 try leb.writeULEB128(writer, max);
831 }
832}
833
834fn emitInit(writer: anytype, init_expr: wasm.InitExpression) !void {
835 switch (init_expr) {
836 .i32_const => |val| {
837 try writer.writeByte(wasm.opcode(.i32_const));
838 try leb.writeILEB128(writer, val);
839 },
840 .i64_const => |val| {
841 try writer.writeByte(wasm.opcode(.i64_const));
842 try leb.writeILEB128(writer, val);
843 },
844 .f32_const => |val| {
845 try writer.writeByte(wasm.opcode(.f32_const));
846 try writer.writeIntLittle(u32, @bitCast(u32, val));
847 },
848 .f64_const => |val| {
849 try writer.writeByte(wasm.opcode(.f64_const));
850 try writer.writeIntLittle(u64, @bitCast(u64, val));
851 },
852 .global_get => |val| {
853 try writer.writeByte(wasm.opcode(.global_get));
854 try leb.writeULEB128(writer, val);
855 },
856 }
857 try writer.writeByte(wasm.opcode(.end));
858}
859
860fn emitImport(writer: anytype, import: wasm.Import) !void {
861 try leb.writeULEB128(writer, @intCast(u32, import.module_name.len));
862 try writer.writeAll(import.module_name);
863
864 try leb.writeULEB128(writer, @intCast(u32, import.name.len));
865 try writer.writeAll(import.name);
866
867 try writer.writeByte(@enumToInt(import.kind));
868 switch (import.kind) {
869 .function => |type_index| try leb.writeULEB128(writer, type_index),
870 .global => |global_type| {
871 try leb.writeULEB128(writer, wasm.valtype(global_type.valtype));
872 try writer.writeByte(@boolToInt(global_type.mutable));
873 },
874 .table => |table| {
875 try leb.writeULEB128(writer, wasm.reftype(table.reftype));
876 try emitLimits(writer, table.limits);
877 },
878 .memory => |limits| {
879 try emitLimits(writer, limits);
880 },
881 }
882}
883
657884fn linkWithLLD(self: *Wasm, comp: *Compilation) !void {
658885 const tracy = trace(@src());
659886 defer tracy.end();
......@@ -970,32 +1197,6 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void {
9701197 }
9711198}
9721199
973/// Get the current index of a given Decl in the function list
974/// This will correctly provide the index, regardless whether the function is extern or not
975/// TODO: we could maintain a hash map to potentially make this simpler
976fn getFuncidx(self: Wasm, decl: *Module.Decl) ?u32 {
977 var offset: u32 = 0;
978 const slice = switch (decl.val.tag()) {
979 .function => blk: {
980 // when the target is a regular function, we have to calculate
981 // the offset of where the index starts
982 offset += self.getFuncIdxOffset();
983 break :blk self.funcs.items;
984 },
985 .extern_fn => self.ext_funcs.items,
986 else => return null,
987 };
988 return for (slice) |func, idx| {
989 if (func == decl) break @intCast(u32, offset + idx);
990 } else null;
991}
992
993/// Based on the size of `ext_funcs` returns the
994/// offset of the function indices
995fn getFuncIdxOffset(self: Wasm) u32 {
996 return @intCast(u32, self.ext_funcs.items.len);
997}
998
9991200fn reserveVecSectionHeader(file: fs.File) !u64 {
10001201 // section id + fixed leb contents size + fixed leb vector length
10011202 const header_size = 1 + 5 + 5;
......@@ -1012,3 +1213,36 @@ fn writeVecSectionHeader(file: fs.File, offset: u64, section: wasm.Section, size
10121213 leb.writeUnsignedFixed(5, buf[6..], items);
10131214 try file.pwriteAll(&buf, offset);
10141215}
1216
1217/// Searches for an a matching function signature, when not found
1218/// a new entry will be made. The index of the existing/new signature will be returned.
1219pub fn putOrGetFuncType(self: *Wasm, func_type: wasm.Type) !u32 {
1220 var index: u32 = 0;
1221 while (index < self.func_types.items.len) : (index += 1) {
1222 if (self.func_types.items[index].eql(func_type)) return index;
1223 }
1224
1225 // functype does not exist.
1226 const params = try self.base.allocator.dupe(wasm.Valtype, func_type.params);
1227 errdefer self.base.allocator.free(params);
1228 const returns = try self.base.allocator.dupe(wasm.Valtype, func_type.returns);
1229 errdefer self.base.allocator.free(returns);
1230 try self.func_types.append(self.base.allocator, .{
1231 .params = params,
1232 .returns = returns,
1233 });
1234 return index;
1235}
1236
1237/// From a given index and an `ExternalKind`, finds the corresponding Import.
1238/// This is due to indexes for imports being unique per type, rather than across all imports.
1239fn findImport(self: Wasm, index: u32, external_type: wasm.ExternalKind) ?*wasm.Import {
1240 var current_index: u32 = 0;
1241 for (self.imports.items) |*import| {
1242 if (import.kind == external_type) {
1243 if (current_index == index) return import;
1244 current_index += 1;
1245 }
1246 }
1247 return null;
1248}
src/link/Wasm/Atom.zig created+164
......@@ -0,0 +1,164 @@
1const Atom = @This();
2
3const std = @import("std");
4const types = @import("types.zig");
5const Wasm = @import("../Wasm.zig");
6const Symbol = @import("Symbol.zig");
7
8const leb = std.leb;
9const log = std.log.scoped(.link);
10const mem = std.mem;
11const Allocator = mem.Allocator;
12
13/// symbol index of the symbol representing this atom
14sym_index: u32,
15/// Size of the atom, used to calculate section sizes in the final binary
16size: u32,
17/// List of relocations belonging to this atom
18relocs: std.ArrayListUnmanaged(types.Relocation) = .{},
19/// Contains the binary data of an atom, which can be non-relocated
20code: std.ArrayListUnmanaged(u8) = .{},
21/// For code this is 1, for data this is set to the highest value of all segments
22alignment: u32,
23/// Offset into the section where the atom lives, this already accounts
24/// for alignment.
25offset: u32,
26
27/// Next atom in relation to this atom.
28/// When null, this atom is the last atom
29next: ?*Atom,
30/// Previous atom in relation to this atom.
31/// is null when this atom is the first in its order
32prev: ?*Atom,
33
34/// Represents a default empty wasm `Atom`
35pub const empty: Atom = .{
36 .alignment = 0,
37 .next = null,
38 .offset = 0,
39 .prev = null,
40 .size = 0,
41 .sym_index = 0,
42};
43
44/// Frees all resources owned by this `Atom`.
45pub fn deinit(self: *Atom, gpa: *Allocator) void {
46 self.relocs.deinit(gpa);
47 self.code.deinit(gpa);
48}
49
50/// Sets the length of relocations and code to '0',
51/// effectively resetting them and allowing them to be re-populated.
52pub fn clear(self: *Atom) void {
53 self.relocs.clearRetainingCapacity();
54 self.code.clearRetainingCapacity();
55}
56
57pub fn format(self: Atom, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
58 _ = fmt;
59 _ = options;
60 writer.print("Atom{{ .sym_index = {d}, .alignment = {d}, .size = {d}, .offset = 0x{x:0>8} }}", .{
61 self.sym_index,
62 self.alignment,
63 self.size,
64 self.offset,
65 });
66}
67
68/// Returns the first `Atom` from a given atom
69pub fn getFirst(self: *Atom) *Atom {
70 var tmp = self;
71 while (tmp.prev) |prev| tmp = prev;
72 return tmp;
73}
74
75/// Resolves the relocations within the atom, writing the new value
76/// at the calculated offset.
77pub fn resolveRelocs(self: *Atom, wasm_bin: *const Wasm) !void {
78 const symbol: Symbol = wasm_bin.symbols.items[self.sym_index];
79 log.debug("Resolving relocs in atom '{s}' count({d})", .{
80 symbol.name,
81 self.relocs.items.len,
82 });
83
84 for (self.relocs.items) |reloc| {
85 const value = try relocationValue(reloc, wasm_bin);
86 log.debug("Relocating '{s}' referenced in '{s}' offset=0x{x:0>8} value={d}\n", .{
87 wasm_bin.symbols.items[reloc.index].name,
88 symbol.name,
89 reloc.offset,
90 value,
91 });
92
93 switch (reloc.relocation_type) {
94 .R_WASM_TABLE_INDEX_I32,
95 .R_WASM_FUNCTION_OFFSET_I32,
96 .R_WASM_GLOBAL_INDEX_I32,
97 .R_WASM_MEMORY_ADDR_I32,
98 .R_WASM_SECTION_OFFSET_I32,
99 => std.mem.writeIntLittle(u32, self.code.items[reloc.offset..][0..4], @intCast(u32, value)),
100 .R_WASM_TABLE_INDEX_I64,
101 .R_WASM_MEMORY_ADDR_I64,
102 => std.mem.writeIntLittle(u64, self.code.items[reloc.offset..][0..8], value),
103 .R_WASM_GLOBAL_INDEX_LEB,
104 .R_WASM_EVENT_INDEX_LEB,
105 .R_WASM_FUNCTION_INDEX_LEB,
106 .R_WASM_MEMORY_ADDR_LEB,
107 .R_WASM_MEMORY_ADDR_SLEB,
108 .R_WASM_TABLE_INDEX_SLEB,
109 .R_WASM_TABLE_NUMBER_LEB,
110 .R_WASM_TYPE_INDEX_LEB,
111 => leb.writeUnsignedFixed(5, self.code.items[reloc.offset..][0..5], @intCast(u32, value)),
112 .R_WASM_MEMORY_ADDR_LEB64,
113 .R_WASM_MEMORY_ADDR_SLEB64,
114 .R_WASM_TABLE_INDEX_SLEB64,
115 => leb.writeUnsignedFixed(10, self.code.items[reloc.offset..][0..10], value),
116 }
117 }
118}
119
120/// From a given `relocation` will return the new value to be written.
121/// All values will be represented as a `u64` as all values can fit within it.
122/// The final value must be casted to the correct size.
123fn relocationValue(relocation: types.Relocation, wasm_bin: *const Wasm) !u64 {
124 const symbol: Symbol = wasm_bin.symbols.items[relocation.index];
125 return switch (relocation.relocation_type) {
126 .R_WASM_FUNCTION_INDEX_LEB => symbol.index,
127 .R_WASM_TABLE_NUMBER_LEB => symbol.index,
128 .R_WASM_TABLE_INDEX_I32,
129 .R_WASM_TABLE_INDEX_I64,
130 .R_WASM_TABLE_INDEX_SLEB,
131 .R_WASM_TABLE_INDEX_SLEB64,
132 => return error.TodoImplementTableIndex, // find table index from a function symbol
133 .R_WASM_TYPE_INDEX_LEB => wasm_bin.functions.items[symbol.index].type_index,
134 .R_WASM_GLOBAL_INDEX_I32,
135 .R_WASM_GLOBAL_INDEX_LEB,
136 => symbol.index,
137 .R_WASM_MEMORY_ADDR_I32,
138 .R_WASM_MEMORY_ADDR_I64,
139 .R_WASM_MEMORY_ADDR_LEB,
140 .R_WASM_MEMORY_ADDR_LEB64,
141 .R_WASM_MEMORY_ADDR_SLEB,
142 .R_WASM_MEMORY_ADDR_SLEB64,
143 => blk: {
144 if (symbol.isUndefined() and (symbol.tag == .data or symbol.isWeak())) {
145 return 0;
146 }
147 const segment_name = wasm_bin.segment_info.items[symbol.index].outputName();
148 const atom_index = wasm_bin.data_segments.get(segment_name).?;
149 var target_atom = wasm_bin.atoms.getPtr(atom_index).?.*.getFirst();
150 while (true) {
151 if (target_atom.sym_index == relocation.index) break;
152 target_atom = target_atom.next orelse break;
153 }
154 const segment = wasm_bin.segments.items[atom_index];
155 const base = wasm_bin.base.options.global_base orelse 1024;
156 const offset = target_atom.offset + segment.offset;
157 break :blk offset + base + (relocation.addend orelse 0);
158 },
159 .R_WASM_EVENT_INDEX_LEB => symbol.index,
160 .R_WASM_SECTION_OFFSET_I32,
161 .R_WASM_FUNCTION_OFFSET_I32,
162 => relocation.offset,
163 };
164}
src/link/Wasm/Symbol.zig created+157
......@@ -0,0 +1,157 @@
1//! Wasm symbols describing its kind,
2//! name and its properties.
3const Symbol = @This();
4
5const std = @import("std");
6const types = @import("types.zig");
7
8/// Bitfield containings flags for a symbol
9/// Can contain any of the flags defined in `Flag`
10flags: u32,
11/// Symbol name, when undefined this will be taken from the import.
12name: [*:0]const u8,
13/// An union that represents both the type of symbol
14/// as well as the data it holds.
15tag: Tag,
16/// Index into the list of objects based on set `tag`
17/// NOTE: This will be set to `undefined` when `tag` is `data`
18/// and the symbol is undefined.
19index: u32,
20
21pub const Tag = enum {
22 function,
23 data,
24 global,
25 section,
26 event,
27 table,
28
29 /// From a given symbol tag, returns the `ExternalType`
30 /// Asserts the given tag can be represented as an external type.
31 pub fn externalType(self: Tag) std.wasm.ExternalKind {
32 return switch (self) {
33 .function => .function,
34 .global => .global,
35 .data => .memory,
36 .section => unreachable, // Not an external type
37 .event => unreachable, // Not an external type
38 .table => .table,
39 };
40 }
41};
42
43pub const Flag = enum(u32) {
44 /// Indicates a weak symbol.
45 /// When linking multiple modules defining the same symbol, all weak definitions are discarded
46 /// in favourite of the strong definition. When no strong definition exists, all weak but one definiton is discarded.
47 /// If multiple definitions remain, we get an error: symbol collision.
48 WASM_SYM_BINDING_WEAK = 0x1,
49 /// Indicates a local, non-exported, non-module-linked symbol.
50 /// The names of local symbols are not required to be unique, unlike non-local symbols.
51 WASM_SYM_BINDING_LOCAL = 0x2,
52 /// Represents the binding of a symbol, indicating if it's local or not, and weak or not.
53 WASM_SYM_BINDING_MASK = 0x3,
54 /// Indicates a hidden symbol. Hidden symbols will not be exported to the link result, but may
55 /// link to other modules.
56 WASM_SYM_VISIBILITY_HIDDEN = 0x4,
57 /// Indicates an undefined symbol. For non-data symbols, this must match whether the symbol is
58 /// an import or is defined. For data symbols however, determines whether a segment is specified.
59 WASM_SYM_UNDEFINED = 0x10,
60 /// Indicates a symbol of which its intention is to be exported from the wasm module to the host environment.
61 /// This differs from the visibility flag as this flag affects the static linker.
62 WASM_SYM_EXPORTED = 0x20,
63 /// Indicates the symbol uses an explicit symbol name, rather than reusing the name from a wasm import.
64 /// Allows remapping imports from foreign WASM modules into local symbols with a different name.
65 WASM_SYM_EXPLICIT_NAME = 0x40,
66 /// Indicates the symbol is to be included in the linker output, regardless of whether it is used or has any references to it.
67 WASM_SYM_NO_STRIP = 0x80,
68 /// Indicates a symbol is TLS
69 WASM_SYM_TLS = 0x100,
70};
71
72/// Verifies if the given symbol should be imported from the
73/// host environment or not
74pub fn requiresImport(self: Symbol) bool {
75 if (!self.isUndefined()) return false;
76 if (self.isWeak()) return false;
77 if (self.kind == .data) return false;
78 // if (self.isDefined() and self.isWeak()) return true; //TODO: Only when building shared lib
79
80 return true;
81}
82
83pub fn hasFlag(self: Symbol, flag: Flag) bool {
84 return self.flags & @enumToInt(flag) != 0;
85}
86
87pub fn setFlag(self: *Symbol, flag: Flag) void {
88 self.flags |= @enumToInt(flag);
89}
90
91pub fn isUndefined(self: Symbol) bool {
92 return self.flags & @enumToInt(Flag.WASM_SYM_UNDEFINED) != 0;
93}
94
95pub fn setUndefined(self: *Symbol, is_undefined: bool) void {
96 if (is_undefined) {
97 self.setFlag(.WASM_SYM_UNDEFINED);
98 } else {
99 self.flags &= ~@enumToInt(Flag.WASM_SYM_UNDEFINED);
100 }
101}
102
103pub fn isDefined(self: Symbol) bool {
104 return !self.isUndefined();
105}
106
107pub fn isVisible(self: Symbol) bool {
108 return self.flags & @enumToInt(Flag.WASM_SYM_VISIBILITY_HIDDEN) == 0;
109}
110
111pub fn isLocal(self: Symbol) bool {
112 return self.flags & @enumToInt(Flag.WASM_SYM_BINDING_LOCAL) != 0;
113}
114
115pub fn isGlobal(self: Symbol) bool {
116 return self.flags & @enumToInt(Flag.WASM_SYM_BINDING_LOCAL) == 0;
117}
118
119pub fn isHidden(self: Symbol) bool {
120 return self.flags & @enumToInt(Flag.WASM_SYM_VISIBILITY_HIDDEN) != 0;
121}
122
123pub fn isNoStrip(self: Symbol) bool {
124 return self.flags & @enumToInt(Flag.WASM_SYM_NO_STRIP) != 0;
125}
126
127pub fn isExported(self: Symbol) bool {
128 if (self.isUndefined() or self.isLocal()) return false;
129 if (self.isHidden()) return false;
130 return true;
131}
132
133pub fn isWeak(self: Symbol) bool {
134 return self.flags & @enumToInt(Flag.WASM_SYM_BINDING_WEAK) != 0;
135}
136
137/// Formats the symbol into human-readable text
138pub fn format(self: Symbol, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
139 _ = fmt;
140 _ = options;
141
142 const kind_fmt: u8 = switch (self.kind) {
143 .function => 'F',
144 .data => 'D',
145 .global => 'G',
146 .section => 'S',
147 .event => 'E',
148 .table => 'T',
149 };
150 const visible: []const u8 = if (self.isVisible()) "yes" else "no";
151 const binding: []const u8 = if (self.isLocal()) "local" else "global";
152
153 try writer.print(
154 "{c} binding={s} visible={s} id={d} name={s}",
155 .{ kind_fmt, binding, visible, self.index(), self.name },
156 );
157}
src/link/Wasm/types.zig created+199
......@@ -0,0 +1,199 @@
1//! This file contains all constants and related to wasm's object format.
2
3const std = @import("std");
4
5pub const Relocation = struct {
6 /// Represents the type of the `Relocation`
7 relocation_type: RelocationType,
8 /// Offset of the value to rewrite relative to the relevant section's contents.
9 /// When `offset` is zero, its position is immediately after the id and size of the section.
10 offset: u32,
11 /// The index of the symbol used.
12 /// When the type is `R_WASM_TYPE_INDEX_LEB`, it represents the index of the type.
13 index: u32,
14 /// Addend to add to the address.
15 /// This field is only non-null for `R_WASM_MEMORY_ADDR_*`, `R_WASM_FUNCTION_OFFSET_I32` and `R_WASM_SECTION_OFFSET_I32`.
16 addend: ?u32 = null,
17
18 /// All possible relocation types currently existing.
19 /// This enum is exhaustive as the spec is WIP and new types
20 /// can be added which means that a generated binary will be invalid,
21 /// so instead we will show an error in such cases.
22 pub const RelocationType = enum(u8) {
23 R_WASM_FUNCTION_INDEX_LEB = 0,
24 R_WASM_TABLE_INDEX_SLEB = 1,
25 R_WASM_TABLE_INDEX_I32 = 2,
26 R_WASM_MEMORY_ADDR_LEB = 3,
27 R_WASM_MEMORY_ADDR_SLEB = 4,
28 R_WASM_MEMORY_ADDR_I32 = 5,
29 R_WASM_TYPE_INDEX_LEB = 6,
30 R_WASM_GLOBAL_INDEX_LEB = 7,
31 R_WASM_FUNCTION_OFFSET_I32 = 8,
32 R_WASM_SECTION_OFFSET_I32 = 9,
33 R_WASM_EVENT_INDEX_LEB = 10,
34 R_WASM_GLOBAL_INDEX_I32 = 13,
35 R_WASM_MEMORY_ADDR_LEB64 = 14,
36 R_WASM_MEMORY_ADDR_SLEB64 = 15,
37 R_WASM_MEMORY_ADDR_I64 = 16,
38 R_WASM_TABLE_INDEX_SLEB64 = 18,
39 R_WASM_TABLE_INDEX_I64 = 19,
40 R_WASM_TABLE_NUMBER_LEB = 20,
41
42 /// Returns true for relocation types where the `addend` field is present.
43 pub fn addendIsPresent(self: RelocationType) bool {
44 return switch (self) {
45 .R_WASM_MEMORY_ADDR_LEB,
46 .R_WASM_MEMORY_ADDR_SLEB,
47 .R_WASM_MEMORY_ADDR_I32,
48 .R_WASM_MEMORY_ADDR_LEB64,
49 .R_WASM_MEMORY_ADDR_SLEB64,
50 .R_WASM_MEMORY_ADDR_I64,
51 .R_WASM_FUNCTION_OFFSET_I32,
52 .R_WASM_SECTION_OFFSET_I32,
53 => true,
54 else => false,
55 };
56 }
57 };
58
59 /// Verifies the relocation type of a given `Relocation` and returns
60 /// true when the relocation references a function call or address to a function.
61 pub fn isFunction(self: Relocation) bool {
62 return switch (self.relocation_type) {
63 .R_WASM_FUNCTION_INDEX_LEB,
64 .R_WASM_TABLE_INDEX_SLEB,
65 => true,
66 else => false,
67 };
68 }
69
70 pub fn format(self: Relocation, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
71 _ = fmt;
72 _ = options;
73 try writer.print("{s} offset=0x{x:0>6} symbol={d}", .{
74 @tagName(self.relocation_type),
75 self.offset,
76 self.index,
77 });
78 }
79};
80
81pub const SubsectionType = enum(u8) {
82 WASM_SEGMENT_INFO = 5,
83 WASM_INIT_FUNCS = 6,
84 WASM_COMDAT_INFO = 7,
85 WASM_SYMBOL_TABLE = 8,
86};
87
88pub const Segment = struct {
89 /// Segment's name, encoded as UTF-8 bytes.
90 name: []const u8,
91 /// The required alignment of the segment, encoded as a power of 2
92 alignment: u32,
93 /// Bitfield containing flags for a segment
94 flags: u32,
95
96 pub fn outputName(self: Segment) []const u8 {
97 if (std.mem.startsWith(u8, self.name, ".rodata.")) {
98 return ".rodata";
99 } else if (std.mem.startsWith(u8, self.name, ".text.")) {
100 return ".text";
101 } else if (std.mem.startsWith(u8, self.name, ".rodata.")) {
102 return ".rodata";
103 } else if (std.mem.startsWith(u8, self.name, ".data.")) {
104 return ".data";
105 } else if (std.mem.startsWith(u8, self.name, ".bss.")) {
106 return ".bss";
107 }
108 return self.name;
109 }
110};
111
112pub const InitFunc = struct {
113 /// Priority of the init function
114 priority: u32,
115 /// The symbol index of init function (not the function index).
116 symbol_index: u32,
117};
118
119pub const Comdat = struct {
120 name: []const u8,
121 /// Must be zero, no flags are currently defined by the tool-convention.
122 flags: u32,
123 symbols: []const ComdatSym,
124};
125
126pub const ComdatSym = struct {
127 kind: Type,
128 /// Index of the data segment/function/global/event/table within a WASM module.
129 /// The object must not be an import.
130 index: u32,
131
132 pub const Type = enum(u8) {
133 WASM_COMDAT_DATA = 0,
134 WASM_COMDAT_FUNCTION = 1,
135 WASM_COMDAT_GLOBAL = 2,
136 WASM_COMDAT_EVENT = 3,
137 WASM_COMDAT_TABLE = 4,
138 WASM_COMDAT_SECTION = 5,
139 };
140};
141
142pub const Feature = struct {
143 /// Provides information about the usage of the feature.
144 /// - '0x2b' (+): Object uses this feature, and the link fails if feature is not in the allowed set.
145 /// - '0x2d' (-): Object does not use this feature, and the link fails if this feature is in the allowed set.
146 /// - '0x3d' (=): Object uses this feature, and the link fails if this feature is not in the allowed set,
147 /// or if any object does not use this feature.
148 prefix: Prefix,
149 /// Type of the feature, must be unique in the sequence of features.
150 tag: Tag,
151
152 pub const Tag = enum {
153 atomics,
154 bulk_memory,
155 exception_handling,
156 multivalue,
157 mutable_globals,
158 nontrapping_fptoint,
159 sign_ext,
160 simd128,
161 tail_call,
162 };
163
164 pub const Prefix = enum(u8) {
165 used = '+',
166 disallowed = '-',
167 required = '=',
168 };
169
170 pub fn toString(self: Feature) []const u8 {
171 return switch (self.tag) {
172 .bulk_memory => "bulk-memory",
173 .exception_handling => "exception-handling",
174 .mutable_globals => "mutable-globals",
175 .nontrapping_fptoint => "nontrapping-fptoint",
176 .sign_ext => "sign-ext",
177 .tail_call => "tail-call",
178 else => @tagName(self),
179 };
180 }
181
182 pub fn format(self: Feature, comptime fmt: []const u8, opt: std.fmt.FormatOptions, writer: anytype) !void {
183 _ = opt;
184 _ = fmt;
185 try writer.print("{c} {s}", .{ self.prefix, self.toString() });
186 }
187};
188
189pub const known_features = std.ComptimeStringMap(Feature.Tag, .{
190 .{ "atomics", .atomics },
191 .{ "bulk-memory", .bulk_memory },
192 .{ "exception-handling", .exception_handling },
193 .{ "multivalue", .multivalue },
194 .{ "mutable-globals", .mutable_globals },
195 .{ "nontrapping-fptoint", .nontrapping_fptoint },
196 .{ "sign-ext", .sign_ext },
197 .{ "simd128", .simd128 },
198 .{ "tail-call", .tail_call },
199});