| ... | @@ -10,6 +10,7 @@ const leb = std.leb; | ... | @@ -10,6 +10,7 @@ const leb = std.leb; |
| 10 | const log = std.log.scoped(.link); | 10 | const log = std.log.scoped(.link); |
| 11 | const wasm = std.wasm; | 11 | const wasm = std.wasm; |
| 12 | | 12 | |
| | 13 | const Atom = @import("Wasm/Atom.zig"); |
| 13 | const Module = @import("../Module.zig"); | 14 | const Module = @import("../Module.zig"); |
| 14 | const Compilation = @import("../Compilation.zig"); | 15 | const Compilation = @import("../Compilation.zig"); |
| 15 | const CodeGen = @import("../arch/wasm/CodeGen.zig"); | 16 | const CodeGen = @import("../arch/wasm/CodeGen.zig"); |
| ... | @@ -22,101 +23,80 @@ const TypedValue = @import("../TypedValue.zig"); | ... | @@ -22,101 +23,80 @@ const TypedValue = @import("../TypedValue.zig"); |
| 22 | const LlvmObject = @import("../codegen/llvm.zig").Object; | 23 | const LlvmObject = @import("../codegen/llvm.zig").Object; |
| 23 | const Air = @import("../Air.zig"); | 24 | const Air = @import("../Air.zig"); |
| 24 | const Liveness = @import("../Liveness.zig"); | 25 | const Liveness = @import("../Liveness.zig"); |
| | 26 | const Symbol = @import("Wasm/Symbol.zig"); |
| | 27 | const types = @import("Wasm/types.zig"); |
| 25 | | 28 | |
| 26 | pub const base_tag = link.File.Tag.wasm; | 29 | pub const base_tag = link.File.Tag.wasm; |
| 27 | | 30 | |
| | 31 | /// deprecated: Use `@import("Wasm/Atom.zig");` |
| | 32 | pub const DeclBlock = Atom; |
| | 33 | |
| 28 | base: link.File, | 34 | base: link.File, |
| 29 | /// If this is not null, an object file is created by LLVM and linked with LLD afterwards. | 35 | /// If this is not null, an object file is created by LLVM and linked with LLD afterwards. |
| 30 | llvm_object: ?*LlvmObject = null, | 36 | llvm_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? | | |
| 36 | funcs: 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 | | |
| 39 | ext_funcs: std.ArrayListUnmanaged(*Module.Decl) = .{}, | | |
| 40 | /// When importing objects from the host environment, a name must be supplied. | 37 | /// When importing objects from the host environment, a name must be supplied. |
| 41 | /// LLVM uses "env" by default when none is given. This would be a good default for Zig | 38 | /// LLVM uses "env" by default when none is given. This would be a good default for Zig |
| 42 | /// to support existing code. | 39 | /// to support existing code. |
| 43 | /// TODO: Allow setting this through a flag? | 40 | /// TODO: Allow setting this through a flag? |
| 44 | host_name: []const u8 = "env", | 41 | host_name: []const u8 = "env", |
| 45 | /// The last `DeclBlock` that was initialized will be saved here. | 42 | /// The last `DeclBlock` that was initialized will be saved here. |
| 46 | last_block: ?*DeclBlock = null, | 43 | last_atom: ?*Atom = 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 | | |
| 49 | offset_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. | | |
| 52 | offset_table_free_list: std.ArrayListUnmanaged(u32) = .{}, | | |
| 53 | /// List of all `Decl` that are currently alive. | 44 | /// List of all `Decl` that are currently alive. |
| 54 | /// This is ment for bookkeeping so we can safely cleanup all codegen memory | 45 | /// This is ment for bookkeeping so we can safely cleanup all codegen memory |
| 55 | /// when calling `deinit` | 46 | /// when calling `deinit` |
| 56 | symbols: std.ArrayListUnmanaged(*Module.Decl) = .{}, | 47 | decls: std.AutoHashMapUnmanaged(*Module.Decl, void) = .{}, |
| | 48 | /// List of all symbols. |
| | 49 | symbols: std.ArrayListUnmanaged(Symbol) = .{}, |
| 57 | /// List of symbol indexes which are free to be used. | 50 | /// List of symbol indexes which are free to be used. |
| 58 | symbols_free_list: std.ArrayListUnmanaged(u32) = .{}, | 51 | symbols_free_list: std.ArrayListUnmanaged(u32) = .{}, |
| | 52 | /// Maps atoms to their segment index |
| | 53 | atoms: std.AutoHashMapUnmanaged(u32, *Atom) = .{}, |
| | 54 | /// Represents the index into `segments` where the 'code' section |
| | 55 | /// lives. |
| | 56 | code_section_index: ?u32 = null, |
| | 57 | /// The count of imported functions. This number will be appended |
| | 58 | /// to the function indexes as their index starts at the lowest non-extern function. |
| | 59 | imported_functions_count: u32 = 0, |
| | 60 | /// List of all 'extern' declarations |
| | 61 | imports: std.ArrayListUnmanaged(wasm.Import) = .{}, |
| | 62 | /// List of indexes of symbols representing extern declarations. |
| | 63 | import_symbols: std.ArrayListUnmanaged(u32) = .{}, |
| | 64 | /// Represents non-synthetic section entries. |
| | 65 | /// Used for code, data and custom sections. |
| | 66 | segments: std.ArrayListUnmanaged(Segment) = .{}, |
| | 67 | /// Maps a data segment key (such as .rodata) to the index into `segments`. |
| | 68 | data_segments: std.StringArrayHashMapUnmanaged(u32) = .{}, |
| | 69 | /// A list of `types.Segment` which provide meta data |
| | 70 | /// about a data symbol such as its name |
| | 71 | segment_info: std.ArrayListUnmanaged(types.Segment) = .{}, |
| | 72 | |
| | 73 | // Output sections |
| | 74 | /// Output type section |
| | 75 | func_types: std.ArrayListUnmanaged(wasm.Type) = .{}, |
| | 76 | /// Output function section |
| | 77 | functions: std.ArrayListUnmanaged(wasm.Func) = .{}, |
| | 78 | /// Output global section |
| | 79 | globals: std.ArrayListUnmanaged(wasm.Global) = .{}, |
| | 80 | |
| | 81 | /// Indirect function table, used to call function pointers |
| | 82 | /// When this is non-zero, we must emit a table entry, |
| | 83 | /// as well as an 'elements' section. |
| | 84 | function_table: std.ArrayListUnmanaged(Symbol) = .{}, |
| | 85 | |
| | 86 | pub const Segment = struct { |
| | 87 | alignment: u32, |
| | 88 | size: u32, |
| | 89 | offset: u32, |
| | 90 | }; |
| 59 | | 91 | |
| 60 | pub const FnData = struct { | 92 | pub const FnData = struct { |
| 61 | /// Generated code for the type of the function | 93 | type_index: u32, |
| 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 }), | | |
| 69 | | 94 | |
| 70 | pub const empty: FnData = .{ | 95 | pub const empty: FnData = .{ |
| 71 | .functype = .{}, | 96 | .type_index = undefined, |
| 72 | .code = .{}, | | |
| 73 | .idx_refs = .{}, | | |
| 74 | }; | 97 | }; |
| 75 | }; | 98 | }; |
| 76 | | 99 | |
| 77 | pub 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 | | | |
| 120 | pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Options) !*Wasm { | 100 | pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Options) !*Wasm { |
| 121 | assert(options.object_format == .wasm); | 101 | assert(options.object_format == .wasm); |
| 122 | | 102 | |
| ... | @@ -139,6 +119,22 @@ pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Optio | ... | @@ -139,6 +119,22 @@ pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Optio |
| 139 | | 119 | |
| 140 | try file.writeAll(&(wasm.magic ++ wasm.version)); | 120 | try file.writeAll(&(wasm.magic ++ wasm.version)); |
| 141 | | 121 | |
| | 122 | // As sym_index '0' is reserved, we use it for our stack pointer symbol |
| | 123 | const global = try wasm_bin.globals.addOne(allocator); |
| | 124 | global.* = .{ |
| | 125 | .global_type = .{ |
| | 126 | .valtype = .i32, |
| | 127 | .mutable = true, |
| | 128 | }, |
| | 129 | .init = .{ .i32_const = 0 }, |
| | 130 | }; |
| | 131 | const symbol = try wasm_bin.symbols.addOne(allocator); |
| | 132 | symbol.* = .{ |
| | 133 | .name = "__stack_pointer", |
| | 134 | .tag = .global, |
| | 135 | .flags = 0, |
| | 136 | .index = 0, |
| | 137 | }; |
| 142 | return wasm_bin; | 138 | return wasm_bin; |
| 143 | } | 139 | } |
| 144 | | 140 | |
| ... | @@ -160,63 +156,58 @@ pub fn deinit(self: *Wasm) void { | ... | @@ -160,63 +156,58 @@ pub fn deinit(self: *Wasm) void { |
| 160 | if (self.llvm_object) |llvm_object| llvm_object.destroy(self.base.allocator); | 156 | if (self.llvm_object) |llvm_object| llvm_object.destroy(self.base.allocator); |
| 161 | } | 157 | } |
| 162 | | 158 | |
| 163 | for (self.symbols.items) |decl, symbol_index| { | 159 | var decl_it = self.decls.keyIterator(); |
| 164 | // Check if we already freed all memory for the symbol | 160 | while (decl_it.next()) |decl_ptr| { |
| 165 | // TODO: Audit this when we refactor the linker. | 161 | const decl = decl_ptr.*; |
| 166 | var already_freed = false; | 162 | decl.link.wasm.deinit(self.base.allocator); |
| 167 | for (self.symbols_free_list.items) |index| { | 163 | } |
| 168 | if (symbol_index == index) { | 164 | |
| 169 | already_freed = true; | 165 | for (self.func_types.items) |func_type| { |
| 170 | break; | 166 | self.base.allocator.free(func_type.params); |
| 171 | } | 167 | self.base.allocator.free(func_type.returns); |
| 172 | } | 168 | } |
| 173 | if (already_freed) continue; | 169 | for (self.segment_info.items) |segment_info| { |
| 174 | decl.fn_link.wasm.functype.deinit(self.base.allocator); | 170 | self.base.allocator.free(segment_info.name); |
| 175 | decl.fn_link.wasm.code.deinit(self.base.allocator); | | |
| 176 | decl.fn_link.wasm.idx_refs.deinit(self.base.allocator); | | |
| 177 | } | 171 | } |
| 178 | | 172 | |
| 179 | self.funcs.deinit(self.base.allocator); | 173 | self.decls.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); | | |
| 183 | self.symbols.deinit(self.base.allocator); | 174 | self.symbols.deinit(self.base.allocator); |
| 184 | self.symbols_free_list.deinit(self.base.allocator); | 175 | self.symbols_free_list.deinit(self.base.allocator); |
| | 176 | self.atoms.deinit(self.base.allocator); |
| | 177 | self.segments.deinit(self.base.allocator); |
| | 178 | self.data_segments.deinit(self.base.allocator); |
| | 179 | self.segment_info.deinit(self.base.allocator); |
| | 180 | |
| | 181 | // free output sections |
| | 182 | self.imports.deinit(self.base.allocator); |
| | 183 | self.import_symbols.deinit(self.base.allocator); |
| | 184 | self.func_types.deinit(self.base.allocator); |
| | 185 | self.functions.deinit(self.base.allocator); |
| | 186 | self.globals.deinit(self.base.allocator); |
| | 187 | self.function_table.deinit(self.base.allocator); |
| 185 | } | 188 | } |
| 186 | | 189 | |
| 187 | pub fn allocateDeclIndexes(self: *Wasm, decl: *Module.Decl) !void { | 190 | pub fn allocateDeclIndexes(self: *Wasm, decl: *Module.Decl) !void { |
| 188 | if (decl.link.wasm.init) return; | 191 | if (decl.link.wasm.sym_index != 0) return; |
| 189 | | 192 | |
| 190 | try self.offset_table.ensureUnusedCapacity(self.base.allocator, 1); | | |
| 191 | try self.symbols.ensureUnusedCapacity(self.base.allocator, 1); | 193 | try self.symbols.ensureUnusedCapacity(self.base.allocator, 1); |
| | 194 | try self.decls.putNoClobber(self.base.allocator, decl, {}); |
| 192 | | 195 | |
| 193 | const block = &decl.link.wasm; | 196 | const atom = &decl.link.wasm; |
| 194 | block.init = true; | | |
| 195 | | 197 | |
| 196 | if (self.offset_table_free_list.popOrNull()) |index| { | 198 | var symbol: Symbol = .{ |
| 197 | block.offset_index = index; | 199 | .name = undefined, // will be set after updateDecl |
| 198 | } else { | 200 | .flags = 0, |
| 199 | block.offset_index = @intCast(u32, self.offset_table.items.len); | 201 | .tag = undefined, // will be set after updateDecl |
| 200 | _ = self.offset_table.addOneAssumeCapacity(); | 202 | .index = undefined, // will be set after updateDecl |
| 201 | } | 203 | }; |
| 202 | | 204 | |
| 203 | if (self.symbols_free_list.popOrNull()) |index| { | 205 | if (self.symbols_free_list.popOrNull()) |index| { |
| 204 | block.symbol_index = index; | 206 | atom.sym_index = index; |
| 205 | self.symbols.items[block.symbol_index] = decl; | 207 | self.symbols.items[index] = symbol; |
| 206 | } else { | 208 | } else { |
| 207 | block.symbol_index = @intCast(u32, self.symbols.items.len); | 209 | atom.sym_index = @intCast(u32, self.symbols.items.len); |
| 208 | self.symbols.appendAssumeCapacity(decl); | 210 | self.symbols.appendAssumeCapacity(symbol); |
| 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 | } | | |
| 220 | } | 211 | } |
| 221 | } | 212 | } |
| 222 | | 213 | |
| ... | @@ -228,25 +219,19 @@ pub fn updateFunc(self: *Wasm, module: *Module, func: *Module.Fn, air: Air, live | ... | @@ -228,25 +219,19 @@ pub fn updateFunc(self: *Wasm, module: *Module, func: *Module.Fn, air: Air, live |
| 228 | if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(module, func, air, liveness); | 219 | if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(module, func, air, liveness); |
| 229 | } | 220 | } |
| 230 | const decl = func.owner_decl; | 221 | const decl = func.owner_decl; |
| 231 | assert(decl.link.wasm.init); // Must call allocateDeclIndexes() | 222 | assert(decl.link.wasm.sym_index != 0); // Must call allocateDeclIndexes() |
| 232 | | | |
| 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; | | |
| 237 | | 223 | |
| 238 | var codegen: CodeGen = .{ | 224 | var codegen: CodeGen = .{ |
| 239 | .gpa = self.base.allocator, | 225 | .gpa = self.base.allocator, |
| 240 | .air = air, | 226 | .air = air, |
| 241 | .liveness = liveness, | 227 | .liveness = liveness, |
| 242 | .values = .{}, | 228 | .values = .{}, |
| 243 | .code = fn_data.code.toManaged(self.base.allocator), | 229 | .code = std.ArrayList(u8).init(self.base.allocator), |
| 244 | .func_type_data = fn_data.functype.toManaged(self.base.allocator), | | |
| 245 | .decl = decl, | 230 | .decl = decl, |
| 246 | .err_msg = undefined, | 231 | .err_msg = undefined, |
| 247 | .locals = .{}, | 232 | .locals = .{}, |
| 248 | .target = self.base.options.target, | 233 | .target = self.base.options.target, |
| 249 | .bin_file = &self.base, | 234 | .bin_file = self, |
| 250 | .global_error_set = self.base.options.module.?.global_error_set, | 235 | .global_error_set = self.base.options.module.?.global_error_set, |
| 251 | }; | 236 | }; |
| 252 | defer codegen.deinit(); | 237 | defer codegen.deinit(); |
| ... | @@ -272,26 +257,19 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void { | ... | @@ -272,26 +257,19 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void { |
| 272 | if (build_options.have_llvm) { | 257 | if (build_options.have_llvm) { |
| 273 | if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(module, decl); | 258 | if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(module, decl); |
| 274 | } | 259 | } |
| 275 | assert(decl.link.wasm.init); // Must call allocateDeclIndexes() | 260 | assert(decl.link.wasm.sym_index != 0); // Must call allocateDeclIndexes() |
| 276 | | | |
| 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; | | |
| 282 | | 261 | |
| 283 | var codegen: CodeGen = .{ | 262 | var codegen: CodeGen = .{ |
| 284 | .gpa = self.base.allocator, | 263 | .gpa = self.base.allocator, |
| 285 | .air = undefined, | 264 | .air = undefined, |
| 286 | .liveness = undefined, | 265 | .liveness = undefined, |
| 287 | .values = .{}, | 266 | .values = .{}, |
| 288 | .code = fn_data.code.toManaged(self.base.allocator), | 267 | .code = std.ArrayList(u8).init(self.base.allocator), |
| 289 | .func_type_data = fn_data.functype.toManaged(self.base.allocator), | | |
| 290 | .decl = decl, | 268 | .decl = decl, |
| 291 | .err_msg = undefined, | 269 | .err_msg = undefined, |
| 292 | .locals = .{}, | 270 | .locals = .{}, |
| 293 | .target = self.base.options.target, | 271 | .target = self.base.options.target, |
| 294 | .bin_file = &self.base, | 272 | .bin_file = self, |
| 295 | .global_error_set = self.base.options.module.?.global_error_set, | 273 | .global_error_set = self.base.options.module.?.global_error_set, |
| 296 | }; | 274 | }; |
| 297 | defer codegen.deinit(); | 275 | defer codegen.deinit(); |
| ... | @@ -310,33 +288,87 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void { | ... | @@ -310,33 +288,87 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void { |
| 310 | } | 288 | } |
| 311 | | 289 | |
| 312 | fn finishUpdateDecl(self: *Wasm, decl: *Module.Decl, result: CodeGen.Result, codegen: *CodeGen) !void { | 290 | fn 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 | | | |
| 318 | const code: []const u8 = switch (result) { | 291 | const code: []const u8 = switch (result) { |
| 319 | .appended => @as([]const u8, fn_data.code.items), | 292 | .appended => @as([]const u8, codegen.code.items), |
| 320 | .externally_managed => |payload| payload, | 293 | .externally_managed => |payload| payload, |
| 321 | }; | 294 | }; |
| 322 | | 295 | |
| 323 | const block = &decl.link.wasm; | 296 | const atom: *Atom = &decl.link.wasm; |
| 324 | if (decl.ty.zigTypeTag() != .Fn) { | 297 | atom.size = @intCast(u32, code.len); |
| 325 | block.size = @intCast(u32, code.len); | 298 | try atom.code.appendSlice(self.base.allocator, code); |
| 326 | block.data = code.ptr; | | |
| 327 | } | | |
| 328 | | 299 | |
| 329 | // If we're updating an existing decl, unplug it first | 300 | // If we're updating an existing decl, unplug it first |
| 330 | // to avoid infinite loops due to earlier links | 301 | // to avoid infinite loops due to earlier links |
| 331 | block.unplug(); | 302 | atom.unplug(); |
| 332 | | 303 | |
| 333 | if (self.last_block) |last| { | 304 | const symbol: *Symbol = &self.symbols.items[atom.sym_index]; |
| 334 | if (last != block) { | 305 | if (decl.isExtern()) { |
| 335 | last.next = block; | 306 | symbol.setUndefined(true); |
| 336 | block.prev = last; | 307 | } |
| 337 | } | 308 | symbol.name = decl.name; |
| | 309 | const final_index = switch (decl.ty.zigTypeTag()) { |
| | 310 | .Fn => result: { |
| | 311 | const type_index = decl.fn_link.wasm.type_index; |
| | 312 | const index = @intCast(u32, self.functions.items.len); |
| | 313 | try self.functions.append(self.base.allocator, .{ .type_index = type_index }); |
| | 314 | symbol.tag = .function; |
| | 315 | symbol.index = index; |
| | 316 | atom.alignment = 1; |
| | 317 | |
| | 318 | if (self.code_section_index == null) { |
| | 319 | self.code_section_index = @intCast(u32, self.segments.items.len); |
| | 320 | try self.segments.append(self.base.allocator, .{ |
| | 321 | .alignment = atom.alignment, |
| | 322 | .size = atom.size, |
| | 323 | .offset = atom.offset, |
| | 324 | }); |
| | 325 | } else { |
| | 326 | self.segments.items[self.code_section_index.?].size += atom.size; |
| | 327 | } |
| | 328 | |
| | 329 | break :result self.code_section_index.?; |
| | 330 | }, |
| | 331 | else => result: { |
| | 332 | const gop = try self.data_segments.getOrPut(self.base.allocator, ".rodata"); |
| | 333 | const atom_index = if (gop.found_existing) blk: { |
| | 334 | self.segments.items[gop.value_ptr.*].size += atom.size; |
| | 335 | break :blk gop.value_ptr.*; |
| | 336 | } else blk: { |
| | 337 | const index = @intCast(u32, self.segments.items.len) - @boolToInt(self.code_section_index != null); |
| | 338 | try self.segments.append(self.base.allocator, .{ |
| | 339 | .alignment = atom.alignment, |
| | 340 | .size = atom.size, |
| | 341 | .offset = atom.offset, |
| | 342 | }); |
| | 343 | gop.value_ptr.* = index; |
| | 344 | break :blk index; |
| | 345 | }; |
| | 346 | const info_index = @intCast(u32, self.segment_info.items.len); |
| | 347 | const segment_name = try std.mem.concat(self.base.allocator, u8, &.{ |
| | 348 | ".rodata.", |
| | 349 | std.mem.span(symbol.name), |
| | 350 | }); |
| | 351 | errdefer self.base.allocator.free(segment_name); |
| | 352 | try self.segment_info.append(self.base.allocator, .{ |
| | 353 | .name = segment_name, |
| | 354 | .alignment = atom.alignment, |
| | 355 | .flags = 0, |
| | 356 | }); |
| | 357 | symbol.tag = .data; |
| | 358 | symbol.index = info_index; |
| | 359 | atom.alignment = decl.ty.abiAlignment(self.base.options.target); |
| | 360 | break :result atom_index; |
| | 361 | }, |
| | 362 | }; |
| | 363 | |
| | 364 | if (self.atoms.getPtr(final_index)) |last| { |
| | 365 | last.*.next = atom; |
| | 366 | atom.prev = last.*; |
| | 367 | atom.offset = last.*.offset + last.*.size; |
| | 368 | last.* = atom; |
| | 369 | } else { |
| | 370 | try self.atoms.putNoClobber(self.base.allocator, final_index, atom); |
| 338 | } | 371 | } |
| 339 | self.last_block = block; | | |
| 340 | } | 372 | } |
| 341 | | 373 | |
| 342 | pub fn updateDeclExports( | 374 | pub fn updateDeclExports( |
| ... | @@ -358,29 +390,28 @@ pub fn freeDecl(self: *Wasm, decl: *Module.Decl) void { | ... | @@ -358,29 +390,28 @@ pub fn freeDecl(self: *Wasm, decl: *Module.Decl) void { |
| 358 | if (self.llvm_object) |llvm_object| return llvm_object.freeDecl(decl); | 390 | if (self.llvm_object) |llvm_object| return llvm_object.freeDecl(decl); |
| 359 | } | 391 | } |
| 360 | | 392 | |
| 361 | if (self.getFuncidx(decl)) |func_idx| { | 393 | const atom = &decl.link.wasm; |
| 362 | switch (decl.val.tag()) { | | |
| 363 | .function => _ = self.funcs.swapRemove(func_idx), | | |
| 364 | .extern_fn => _ = self.ext_funcs.swapRemove(func_idx), | | |
| 365 | else => unreachable, | | |
| 366 | } | | |
| 367 | } | | |
| 368 | const block = &decl.link.wasm; | | |
| 369 | | 394 | |
| 370 | if (self.last_block == block) { | 395 | if (self.last_atom == atom) { |
| 371 | self.last_block = block.prev; | 396 | self.last_atom = atom.prev; |
| 372 | } | 397 | } |
| 373 | | 398 | |
| 374 | block.unplug(); | 399 | atom.unplug(); |
| 375 | | 400 | self.symbols_free_list.append(self.base.allocator, atom.sym_index) catch {}; |
| 376 | self.offset_table_free_list.append(self.base.allocator, decl.link.wasm.offset_index) catch {}; | 401 | atom.deinit(self.base.allocator); |
| 377 | self.symbols_free_list.append(self.base.allocator, block.symbol_index) catch {}; | 402 | _ = self.decls.remove(decl); |
| 378 | | 403 | } |
| 379 | block.init = false; | | |
| 380 | | 404 | |
| 381 | decl.fn_link.wasm.functype.deinit(self.base.allocator); | 405 | fn createUndefinedSymbol(self: *Wasm, decl: *Module.Decl, symbol_index: u32) !void { |
| 382 | decl.fn_link.wasm.code.deinit(self.base.allocator); | 406 | var symbol: *Symbol = &self.symbols.items[symbol_index]; |
| 383 | decl.fn_link.wasm.idx_refs.deinit(self.base.allocator); | 407 | symbol.setUndefined(true); |
| | 408 | switch (decl.ty.zigTypeTag()) { |
| | 409 | .Fn => { |
| | 410 | symbol.setIndex(self.imported_functions_count); |
| | 411 | self.imported_functions_count += 1; |
| | 412 | }, |
| | 413 | else => @panic("TODO: Wasm implement extern non-function types"), |
| | 414 | } |
| 384 | } | 415 | } |
| 385 | | 416 | |
| 386 | pub fn flush(self: *Wasm, comp: *Compilation) !void { | 417 | pub fn flush(self: *Wasm, comp: *Compilation) !void { |
| ... | @@ -398,27 +429,20 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { | ... | @@ -398,27 +429,20 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { |
| 398 | | 429 | |
| 399 | const file = self.base.file.?; | 430 | const file = self.base.file.?; |
| 400 | const header_size = 5 + 1; | 431 | 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 | 432 | // The size of the emulated stack |
| 408 | const stack_size = @intCast(u32, self.base.options.stack_size_override orelse std.wasm.page_size); | 433 | const stack_size = @intCast(u32, self.base.options.stack_size_override orelse std.wasm.page_size); |
| 409 | | 434 | |
| 410 | // The size of the data, this together with `offset_table_size` amounts to the | 435 | var data_size: u32 = 0; |
| 411 | // total size of the 'data' section | 436 | for (self.segments.items) |segment, index| { |
| 412 | var first_decl: ?*DeclBlock = null; | 437 | // skip 'code' segments as they do not count towards data section size |
| 413 | const data_size: u32 = if (self.last_block) |last| blk: { | 438 | if (self.code_section_index) |code_index| { |
| 414 | var size = last.size; | 439 | if (index == code_index) continue; |
| 415 | var cur = last; | | |
| 416 | while (cur.prev) |prev| : (cur = prev) { | | |
| 417 | size += prev.size; | | |
| 418 | } | 440 | } |
| 419 | first_decl = cur; | 441 | data_size += segment.size; |
| 420 | break :blk size; | 442 | } |
| 421 | } else 0; | 443 | |
| | 444 | // set the stack size on the global |
| | 445 | self.globals.items[0].init = .{ .i32_const = @bitCast(i32, data_size + stack_size) }; |
| 422 | | 446 | |
| 423 | // No need to rewrite the magic/version header | 447 | // No need to rewrite the magic/version header |
| 424 | try file.setEndPos(@sizeOf(@TypeOf(wasm.magic ++ wasm.version))); | 448 | try file.setEndPos(@sizeOf(@TypeOf(wasm.magic ++ wasm.version))); |
| ... | @@ -427,46 +451,62 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { | ... | @@ -427,46 +451,62 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { |
| 427 | // Type section | 451 | // Type section |
| 428 | { | 452 | { |
| 429 | const header_offset = try reserveVecSectionHeader(file); | 453 | const header_offset = try reserveVecSectionHeader(file); |
| | 454 | const writer = file.writer(); |
| 430 | | 455 | |
| 431 | // extern functions are defined in the wasm binary first through the `import` | 456 | for (self.func_types.items) |func_type| { |
| 432 | // section, so define their func types first | 457 | try leb.writeULEB128(writer, wasm.function_type); |
| 433 | for (self.ext_funcs.items) |decl| try file.writeAll(decl.fn_link.wasm.functype.items); | 458 | try leb.writeULEB128(writer, @intCast(u32, func_type.params.len)); |
| 434 | for (self.funcs.items) |decl| try file.writeAll(decl.fn_link.wasm.functype.items); | 459 | for (func_type.params) |param_ty| try leb.writeULEB128(writer, wasm.valtype(param_ty)); |
| | 460 | try leb.writeULEB128(writer, @intCast(u32, func_type.returns.len)); |
| | 461 | for (func_type.returns) |ret_ty| try leb.writeULEB128(writer, wasm.valtype(ret_ty)); |
| | 462 | } |
| 435 | | 463 | |
| 436 | try writeVecSectionHeader( | 464 | try writeVecSectionHeader( |
| 437 | file, | 465 | file, |
| 438 | header_offset, | 466 | header_offset, |
| 439 | .type, | 467 | .type, |
| 440 | @intCast(u32, (try file.getPos()) - header_offset - header_size), | 468 | @intCast(u32, (try file.getPos()) - header_offset - header_size), |
| 441 | @intCast(u32, self.ext_funcs.items.len + self.funcs.items.len), | 469 | @intCast(u32, self.func_types.items.len), |
| 442 | ); | 470 | ); |
| 443 | } | 471 | } |
| 444 | | 472 | |
| 445 | // Import section | 473 | // Import section |
| 446 | { | 474 | if (self.import_symbols.items.len > 0) { |
| 447 | // TODO: implement non-functions imports | | |
| 448 | const header_offset = try reserveVecSectionHeader(file); | 475 | const header_offset = try reserveVecSectionHeader(file); |
| 449 | const writer = file.writer(); | 476 | const writer = file.writer(); |
| 450 | for (self.ext_funcs.items) |decl, typeidx| { | 477 | for (self.import_symbols.items) |symbol_index| { |
| | 478 | const import_symbol = self.symbols.items[symbol_index]; |
| | 479 | std.debug.assert(import_symbol.isUndefined()); |
| 451 | try leb.writeULEB128(writer, @intCast(u32, self.host_name.len)); | 480 | try leb.writeULEB128(writer, @intCast(u32, self.host_name.len)); |
| 452 | try writer.writeAll(self.host_name); | 481 | try writer.writeAll(self.host_name); |
| 453 | | 482 | |
| 454 | // wasm requires the length of the import name with no null-termination | 483 | const name = std.mem.span(import_symbol.name); |
| 455 | const decl_len = mem.len(decl.name); | 484 | try leb.writeULEB128(writer, @intCast(u32, name.len)); |
| 456 | try leb.writeULEB128(writer, @intCast(u32, decl_len)); | 485 | try writer.writeAll(name); |
| 457 | try writer.writeAll(decl.name[0..decl_len]); | 486 | |
| 458 | | 487 | try writer.writeByte(wasm.externalKind(import_symbol.tag.externalType())); |
| 459 | // emit kind and the function type | 488 | const import = self.findImport(import_symbol.index, import_symbol.tag.externalType()).?; |
| 460 | try writer.writeByte(wasm.externalKind(.function)); | 489 | switch (import.kind) { |
| 461 | try leb.writeULEB128(writer, @intCast(u32, typeidx)); | 490 | .function => |type_index| try leb.writeULEB128(writer, type_index), |
| | 491 | .global => |global_type| { |
| | 492 | try leb.writeULEB128(writer, wasm.valtype(global_type.valtype)); |
| | 493 | try writer.writeByte(@boolToInt(global_type.mutable)); |
| | 494 | }, |
| | 495 | .table => |table| { |
| | 496 | try leb.writeULEB128(writer, wasm.reftype(table.reftype)); |
| | 497 | try emitLimits(writer, table.limits); |
| | 498 | }, |
| | 499 | .memory => |limits| { |
| | 500 | try emitLimits(writer, limits); |
| | 501 | }, |
| | 502 | } |
| 462 | } | 503 | } |
| 463 | | | |
| 464 | try writeVecSectionHeader( | 504 | try writeVecSectionHeader( |
| 465 | file, | 505 | file, |
| 466 | header_offset, | 506 | header_offset, |
| 467 | .import, | 507 | .import, |
| 468 | @intCast(u32, (try file.getPos()) - header_offset - header_size), | 508 | @intCast(u32, (try file.getPos()) - header_offset - header_size), |
| 469 | @intCast(u32, self.ext_funcs.items.len), | 509 | @intCast(u32, self.imports.items.len), |
| 470 | ); | 510 | ); |
| 471 | } | 511 | } |
| 472 | | 512 | |
| ... | @@ -474,9 +514,11 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { | ... | @@ -474,9 +514,11 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { |
| 474 | { | 514 | { |
| 475 | const header_offset = try reserveVecSectionHeader(file); | 515 | const header_offset = try reserveVecSectionHeader(file); |
| 476 | const writer = file.writer(); | 516 | const writer = file.writer(); |
| 477 | for (self.funcs.items) |_, typeidx| { | 517 | for (self.functions.items) |function| { |
| 478 | const func_idx = @intCast(u32, self.getFuncIdxOffset() + typeidx); | 518 | try leb.writeULEB128( |
| 479 | try leb.writeULEB128(writer, func_idx); | 519 | writer, |
| | 520 | @intCast(u32, function.type_index), |
| | 521 | ); |
| 480 | } | 522 | } |
| 481 | | 523 | |
| 482 | try writeVecSectionHeader( | 524 | try writeVecSectionHeader( |
| ... | @@ -484,7 +526,7 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { | ... | @@ -484,7 +526,7 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { |
| 484 | header_offset, | 526 | header_offset, |
| 485 | .function, | 527 | .function, |
| 486 | @intCast(u32, (try file.getPos()) - header_offset - header_size), | 528 | @intCast(u32, (try file.getPos()) - header_offset - header_size), |
| 487 | @intCast(u32, self.funcs.items.len), | 529 | @intCast(u32, self.functions.items.len), |
| 488 | ); | 530 | ); |
| 489 | } | 531 | } |
| 490 | | 532 | |
| ... | @@ -500,7 +542,7 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { | ... | @@ -500,7 +542,7 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { |
| 500 | writer, | 542 | writer, |
| 501 | try std.math.divCeil( | 543 | try std.math.divCeil( |
| 502 | u32, | 544 | u32, |
| 503 | offset_table_size + data_size + stack_size, | 545 | data_size + stack_size, |
| 504 | std.wasm.page_size, | 546 | std.wasm.page_size, |
| 505 | ), | 547 | ), |
| 506 | ); | 548 | ); |
| ... | @@ -515,29 +557,21 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { | ... | @@ -515,29 +557,21 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { |
| 515 | | 557 | |
| 516 | // Global section (used to emit stack pointer) | 558 | // Global section (used to emit stack pointer) |
| 517 | { | 559 | { |
| 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 | | |
| 524 | const header_offset = try reserveVecSectionHeader(file); | 560 | const header_offset = try reserveVecSectionHeader(file); |
| 525 | const writer = file.writer(); | 561 | const writer = file.writer(); |
| 526 | | 562 | |
| 527 | try writer.writeByte(wasm.valtype(.i32)); | 563 | for (self.globals.items) |global| { |
| 528 | try writer.writeByte(@boolToInt(mutable)); | 564 | try writer.writeByte(wasm.valtype(global.global_type.valtype)); |
| 529 | | 565 | try writer.writeByte(@boolToInt(global.global_type.mutable)); |
| 530 | // set the initial value of the stack pointer to the data size + stack size | 566 | try emitInit(writer, global.init); |
| 531 | try writer.writeByte(wasm.opcode(.i32_const)); | 567 | } |
| 532 | try leb.writeILEB128(writer, @bitCast(i32, sp_value)); | | |
| 533 | try writer.writeByte(wasm.opcode(.end)); | | |
| 534 | | 568 | |
| 535 | try writeVecSectionHeader( | 569 | try writeVecSectionHeader( |
| 536 | file, | 570 | file, |
| 537 | header_offset, | 571 | header_offset, |
| 538 | .global, | 572 | .global, |
| 539 | @intCast(u32, (try file.getPos()) - header_offset - header_size), | 573 | @intCast(u32, (try file.getPos()) - header_offset - header_size), |
| 540 | @as(u32, 1), | 574 | @intCast(u32, self.globals.items.len), |
| 541 | ); | 575 | ); |
| 542 | } | 576 | } |
| 543 | | 577 | |
| ... | @@ -546,6 +580,7 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { | ... | @@ -546,6 +580,7 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { |
| 546 | const header_offset = try reserveVecSectionHeader(file); | 580 | const header_offset = try reserveVecSectionHeader(file); |
| 547 | const writer = file.writer(); | 581 | const writer = file.writer(); |
| 548 | var count: u32 = 0; | 582 | var count: u32 = 0; |
| | 583 | var func_index: u32 = 0; |
| 549 | for (module.decl_exports.values()) |exports| { | 584 | for (module.decl_exports.values()) |exports| { |
| 550 | for (exports) |exprt| { | 585 | for (exports) |exprt| { |
| 551 | // Export name length + name | 586 | // Export name length + name |
| ... | @@ -557,7 +592,8 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { | ... | @@ -557,7 +592,8 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { |
| 557 | // Type of the export | 592 | // Type of the export |
| 558 | try writer.writeByte(wasm.externalKind(.function)); | 593 | try writer.writeByte(wasm.externalKind(.function)); |
| 559 | // Exported function index | 594 | // Exported function index |
| 560 | try leb.writeULEB128(writer, self.getFuncidx(exprt.exported_decl).?); | 595 | try leb.writeULEB128(writer, func_index); |
| | 596 | func_index += 1; |
| 561 | }, | 597 | }, |
| 562 | else => return error.TODOImplementNonFnDeclsForWasm, | 598 | else => return error.TODOImplementNonFnDeclsForWasm, |
| 563 | } | 599 | } |
| ... | @@ -585,75 +621,108 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { | ... | @@ -585,75 +621,108 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { |
| 585 | } | 621 | } |
| 586 | | 622 | |
| 587 | // Code section | 623 | // Code section |
| 588 | { | 624 | if (self.code_section_index) |code_index| { |
| 589 | const header_offset = try reserveVecSectionHeader(file); | 625 | const header_offset = try reserveVecSectionHeader(file); |
| 590 | const writer = file.writer(); | 626 | const writer = file.writer(); |
| 591 | for (self.funcs.items) |decl| { | 627 | var atom = self.atoms.get(code_index).?.getFirst(); |
| 592 | const fn_data = &decl.fn_link.wasm; | 628 | while (true) { |
| 593 | | 629 | try leb.writeULEB128(writer, atom.size); |
| 594 | // Write the already generated code to the file, inserting | 630 | try writer.writeAll(atom.code.items); |
| 595 | // function indexes where required. | 631 | |
| 596 | for (fn_data.idx_refs.items) |idx_ref| { | 632 | atom = atom.next orelse break; |
| 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); | | |
| 602 | } | 633 | } |
| 603 | try writeVecSectionHeader( | 634 | try writeVecSectionHeader( |
| 604 | file, | 635 | file, |
| 605 | header_offset, | 636 | header_offset, |
| 606 | .code, | 637 | .code, |
| 607 | @intCast(u32, (try file.getPos()) - header_offset - header_size), | 638 | @intCast(u32, (try file.getPos()) - header_offset - header_size), |
| 608 | @intCast(u32, self.funcs.items.len), | 639 | @intCast(u32, self.functions.items.len), |
| 609 | ); | 640 | ); |
| 610 | } | 641 | } |
| 611 | | 642 | |
| 612 | // Data section | 643 | // Data section |
| 613 | if (data_size != 0) { | 644 | if (self.data_segments.count() != 0) { |
| 614 | const header_offset = try reserveVecSectionHeader(file); | 645 | const header_offset = try reserveVecSectionHeader(file); |
| 615 | const writer = file.writer(); | 646 | 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 | | 647 | |
| 626 | // offset table + data size | 648 | var it = self.data_segments.iterator(); |
| 627 | try leb.writeULEB128(writer, total_size); | 649 | while (it.next()) |entry| { |
| 628 | | 650 | // do not output 'bss' section |
| 629 | // fill in the offset table and the data segments | 651 | if (std.mem.eql(u8, entry.key_ptr.*, ".bss")) continue; |
| 630 | const file_offset = try file.getPos(); | 652 | const atom_index = entry.value_ptr.*; |
| 631 | var cur = first_decl; | 653 | var atom = self.atoms.getPtr(atom_index).?.*.getFirst(); |
| 632 | var data_offset = offset_table_size; | 654 | var segment = self.segments.items[atom_index]; |
| 633 | while (cur) |cur_block| : (cur = cur_block.next) { | 655 | |
| 634 | if (cur_block.size == 0) continue; | 656 | // flag and index to memory section (currently, there can only be 1 memory section in wasm) |
| 635 | assert(cur_block.init); | 657 | try leb.writeULEB128(writer, @as(u32, 0)); |
| 636 | | 658 | |
| 637 | const offset = (cur_block.offset_index) * ptr_width; | 659 | // offset into data section |
| 638 | var buf: [4]u8 = undefined; | 660 | try writer.writeByte(wasm.opcode(.i32_const)); |
| 639 | std.mem.writeIntLittle(u32, &buf, data_offset); | 661 | try leb.writeILEB128(writer, @as(i32, 0)); |
| 640 | | 662 | try writer.writeByte(wasm.opcode(.end)); |
| 641 | try file.pwriteAll(&buf, file_offset + offset); | 663 | |
| 642 | try file.pwriteAll(cur_block.data[0..cur_block.size], file_offset + data_offset); | 664 | // offset table + data size |
| 643 | data_offset += cur_block.size; | 665 | try leb.writeULEB128(writer, segment.size); |
| | 666 | |
| | 667 | // fill in the offset table and the data segments |
| | 668 | var current_offset: u32 = 0; |
| | 669 | while (true) { |
| | 670 | std.debug.assert(current_offset == atom.offset); |
| | 671 | std.debug.assert(atom.code.items.len == atom.size); |
| | 672 | |
| | 673 | try writer.writeAll(atom.code.items); |
| | 674 | |
| | 675 | current_offset += atom.size; |
| | 676 | if (atom.next) |next| { |
| | 677 | atom = next; |
| | 678 | } else break; |
| | 679 | } |
| 644 | } | 680 | } |
| 645 | | 681 | |
| 646 | try file.seekTo(file_offset + data_offset); | | |
| 647 | try writeVecSectionHeader( | 682 | try writeVecSectionHeader( |
| 648 | file, | 683 | file, |
| 649 | header_offset, | 684 | header_offset, |
| 650 | .data, | 685 | .data, |
| 651 | @intCast(u32, (file_offset + data_offset) - header_offset - header_size), | 686 | @intCast(u32, (try file.getPos()) - header_offset - header_size), |
| 652 | @intCast(u32, 1), // only 1 data section | 687 | @intCast(u32, 1), // only 1 data section |
| 653 | ); | 688 | ); |
| 654 | } | 689 | } |
| 655 | } | 690 | } |
| 656 | | 691 | |
| | 692 | fn emitLimits(writer: anytype, limits: wasm.Limits) !void { |
| | 693 | try leb.writeULEB128(writer, @boolToInt(limits.max != null)); |
| | 694 | try leb.writeULEB128(writer, limits.min); |
| | 695 | if (limits.max) |max| { |
| | 696 | try leb.writeULEB128(writer, max); |
| | 697 | } |
| | 698 | } |
| | 699 | |
| | 700 | fn emitInit(writer: anytype, init_expr: wasm.InitExpression) !void { |
| | 701 | switch (init_expr) { |
| | 702 | .i32_const => |val| { |
| | 703 | try writer.writeByte(wasm.opcode(.i32_const)); |
| | 704 | try leb.writeILEB128(writer, val); |
| | 705 | }, |
| | 706 | .i64_const => |val| { |
| | 707 | try writer.writeByte(wasm.opcode(.i64_const)); |
| | 708 | try leb.writeILEB128(writer, val); |
| | 709 | }, |
| | 710 | .f32_const => |val| { |
| | 711 | try writer.writeByte(wasm.opcode(.f32_const)); |
| | 712 | try writer.writeIntLittle(u32, @bitCast(u32, val)); |
| | 713 | }, |
| | 714 | .f64_const => |val| { |
| | 715 | try writer.writeByte(wasm.opcode(.f64_const)); |
| | 716 | try writer.writeIntLittle(u64, @bitCast(u64, val)); |
| | 717 | }, |
| | 718 | .global_get => |val| { |
| | 719 | try writer.writeByte(wasm.opcode(.global_get)); |
| | 720 | try leb.writeULEB128(writer, val); |
| | 721 | }, |
| | 722 | } |
| | 723 | try writer.writeByte(wasm.opcode(.end)); |
| | 724 | } |
| | 725 | |
| 657 | fn linkWithLLD(self: *Wasm, comp: *Compilation) !void { | 726 | fn linkWithLLD(self: *Wasm, comp: *Compilation) !void { |
| 658 | const tracy = trace(@src()); | 727 | const tracy = trace(@src()); |
| 659 | defer tracy.end(); | 728 | defer tracy.end(); |
| ... | @@ -970,32 +1039,6 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void { | ... | @@ -970,32 +1039,6 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void { |
| 970 | } | 1039 | } |
| 971 | } | 1040 | } |
| 972 | | 1041 | |
| 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 | | |
| 976 | fn 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 | | |
| 995 | fn getFuncIdxOffset(self: Wasm) u32 { | | |
| 996 | return @intCast(u32, self.ext_funcs.items.len); | | |
| 997 | } | | |
| 998 | | | |
| 999 | fn reserveVecSectionHeader(file: fs.File) !u64 { | 1042 | fn reserveVecSectionHeader(file: fs.File) !u64 { |
| 1000 | // section id + fixed leb contents size + fixed leb vector length | 1043 | // section id + fixed leb contents size + fixed leb vector length |
| 1001 | const header_size = 1 + 5 + 5; | 1044 | const header_size = 1 + 5 + 5; |
| ... | @@ -1012,3 +1055,36 @@ fn writeVecSectionHeader(file: fs.File, offset: u64, section: wasm.Section, size | ... | @@ -1012,3 +1055,36 @@ fn writeVecSectionHeader(file: fs.File, offset: u64, section: wasm.Section, size |
| 1012 | leb.writeUnsignedFixed(5, buf[6..], items); | 1055 | leb.writeUnsignedFixed(5, buf[6..], items); |
| 1013 | try file.pwriteAll(&buf, offset); | 1056 | try file.pwriteAll(&buf, offset); |
| 1014 | } | 1057 | } |
| | 1058 | |
| | 1059 | /// Searches for an a matching function signature, when not found |
| | 1060 | /// a new entry will be made. The index of the existing/new signature will be returned. |
| | 1061 | pub fn putOrGetFuncType(self: *Wasm, func_type: wasm.Type) !u32 { |
| | 1062 | var index: u32 = 0; |
| | 1063 | while (index < self.func_types.items.len) : (index += 1) { |
| | 1064 | if (self.func_types.items[index].eql(func_type)) return index; |
| | 1065 | } |
| | 1066 | |
| | 1067 | // functype does not exist. |
| | 1068 | const params = try self.base.allocator.dupe(wasm.Valtype, func_type.params); |
| | 1069 | errdefer self.base.allocator.free(params); |
| | 1070 | const returns = try self.base.allocator.dupe(wasm.Valtype, func_type.returns); |
| | 1071 | errdefer self.base.allocator.free(returns); |
| | 1072 | try self.func_types.append(self.base.allocator, .{ |
| | 1073 | .params = params, |
| | 1074 | .returns = returns, |
| | 1075 | }); |
| | 1076 | return index; |
| | 1077 | } |
| | 1078 | |
| | 1079 | /// From a given index and an `ExternalKind`, finds the corresponding Import. |
| | 1080 | /// This is due to indexes for imports being unique per type, rather than across all imports. |
| | 1081 | fn findImport(self: Wasm, index: u32, external_type: wasm.ExternalKind) ?*wasm.Import { |
| | 1082 | var current_index: u32 = 0; |
| | 1083 | for (self.imports.items) |*import| { |
| | 1084 | if (import.kind == external_type) { |
| | 1085 | if (current_index == index) return import; |
| | 1086 | current_index += 1; |
| | 1087 | } |
| | 1088 | } |
| | 1089 | return null; |
| | 1090 | } |