authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-12-20 22:15:21-08:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-01-15 15:11:36-08:00
log728103467edba5f3407b1aaa89c9b6dda9432884
treeef64a910bd3240e28496e49a7ee98bb784c8edd8
parentfbbb54bab212e8db251ea7409945d5cecfd732c6

wasm linker: implement indirect function calls


5 files changed, 129 insertions(+), 92 deletions(-)

src/arch/wasm/CodeGen.zig+27-3
......@@ -1021,7 +1021,20 @@ fn emitWValue(cg: *CodeGen, value: WValue) InnerError!void {
10211021 .float32 => |val| try cg.addInst(.{ .tag = .f32_const, .data = .{ .float32 = val } }),
10221022 .float64 => |val| try cg.addFloat64(val),
10231023 .nav_ref => |nav_ref| {
1024 if (nav_ref.offset == 0) {
1024 const wasm = cg.wasm;
1025 const comp = wasm.base.comp;
1026 const zcu = comp.zcu.?;
1027 const ip = &zcu.intern_pool;
1028 const ip_index = ip.getNav(nav_ref.nav_index).status.resolved.val;
1029 if (ip.isFunctionType(ip.typeOf(ip_index))) {
1030 assert(nav_ref.offset == 0);
1031 const gop = try wasm.indirect_function_table.getOrPut(comp.gpa, ip_index);
1032 if (!gop.found_existing) gop.value_ptr.* = {};
1033 try cg.addInst(.{
1034 .tag = .func_ref,
1035 .data = .{ .indirect_function_table_index = @enumFromInt(gop.index) },
1036 });
1037 } else if (nav_ref.offset == 0) {
10251038 try cg.addInst(.{ .tag = .nav_ref, .data = .{ .nav_index = nav_ref.nav_index } });
10261039 } else {
10271040 try cg.addInst(.{
......@@ -1037,8 +1050,19 @@ fn emitWValue(cg: *CodeGen, value: WValue) InnerError!void {
10371050 },
10381051 .uav_ref => |uav| {
10391052 const wasm = cg.wasm;
1040 const is_obj = wasm.base.comp.config.output_mode == .Obj;
1041 if (uav.offset == 0) {
1053 const comp = wasm.base.comp;
1054 const is_obj = comp.config.output_mode == .Obj;
1055 const zcu = comp.zcu.?;
1056 const ip = &zcu.intern_pool;
1057 if (ip.isFunctionType(ip.typeOf(uav.ip_index))) {
1058 assert(uav.offset == 0);
1059 const gop = try wasm.indirect_function_table.getOrPut(comp.gpa, uav.ip_index);
1060 if (!gop.found_existing) gop.value_ptr.* = {};
1061 try cg.addInst(.{
1062 .tag = .func_ref,
1063 .data = .{ .indirect_function_table_index = @enumFromInt(gop.index) },
1064 });
1065 } else if (uav.offset == 0) {
10421066 try cg.addInst(.{
10431067 .tag = .uav_ref,
10441068 .data = if (is_obj) .{
src/arch/wasm/Emit.zig+23-31
......@@ -76,7 +76,16 @@ pub fn lowerToCode(emit: *Emit) Error!void {
7676 inst += 1;
7777 continue :loop tags[inst];
7878 },
79
79 .func_ref => {
80 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.i32_const));
81 if (is_obj) {
82 @panic("TODO");
83 } else {
84 leb.writeUleb128(code.fixedWriter(), @intFromEnum(datas[inst].indirect_function_table_index)) catch unreachable;
85 }
86 inst += 1;
87 continue :loop tags[inst];
88 },
8089 .dbg_line => {
8190 inst += 1;
8291 continue :loop tags[inst];
......@@ -938,40 +947,23 @@ fn navRefOff(wasm: *Wasm, code: *std.ArrayListUnmanaged(u8), data: Mir.NavRefOff
938947 const gpa = comp.gpa;
939948 const is_obj = comp.config.output_mode == .Obj;
940949 const nav_ty = ip.getNav(data.nav_index).typeOf(ip);
950 assert(!ip.isFunctionType(nav_ty));
941951
942952 try code.ensureUnusedCapacity(gpa, 11);
943953
944 if (ip.isFunctionType(nav_ty)) {
945 code.appendAssumeCapacity(@intFromEnum(std.wasm.Opcode.i32_const));
946 assert(data.offset == 0);
947 if (is_obj) {
948 try wasm.out_relocs.append(gpa, .{
949 .offset = @intCast(code.items.len),
950 .pointee = .{ .symbol_index = try wasm.navSymbolIndex(data.nav_index) },
951 .tag = .TABLE_INDEX_SLEB,
952 .addend = data.offset,
953 });
954 code.appendNTimesAssumeCapacity(0, 5);
955 } else {
956 const function_imports_len: u32 = @intCast(wasm.function_imports.entries.len);
957 const func_index = Wasm.FunctionIndex.fromIpNav(wasm, data.nav_index).?;
958 leb.writeUleb128(code.fixedWriter(), function_imports_len + @intFromEnum(func_index)) catch unreachable;
959 }
954 const opcode: std.wasm.Opcode = if (is_wasm32) .i32_const else .i64_const;
955 code.appendAssumeCapacity(@intFromEnum(opcode));
956 if (is_obj) {
957 try wasm.out_relocs.append(gpa, .{
958 .offset = @intCast(code.items.len),
959 .pointee = .{ .symbol_index = try wasm.navSymbolIndex(data.nav_index) },
960 .tag = if (is_wasm32) .MEMORY_ADDR_LEB else .MEMORY_ADDR_LEB64,
961 .addend = data.offset,
962 });
963 code.appendNTimesAssumeCapacity(0, if (is_wasm32) 5 else 10);
960964 } else {
961 const opcode: std.wasm.Opcode = if (is_wasm32) .i32_const else .i64_const;
962 code.appendAssumeCapacity(@intFromEnum(opcode));
963 if (is_obj) {
964 try wasm.out_relocs.append(gpa, .{
965 .offset = @intCast(code.items.len),
966 .pointee = .{ .symbol_index = try wasm.navSymbolIndex(data.nav_index) },
967 .tag = if (is_wasm32) .MEMORY_ADDR_LEB else .MEMORY_ADDR_LEB64,
968 .addend = data.offset,
969 });
970 code.appendNTimesAssumeCapacity(0, if (is_wasm32) 5 else 10);
971 } else {
972 const addr = wasm.navAddr(data.nav_index);
973 leb.writeUleb128(code.fixedWriter(), @as(u32, @intCast(@as(i64, addr) + data.offset))) catch unreachable;
974 }
965 const addr = wasm.navAddr(data.nav_index);
966 leb.writeUleb128(code.fixedWriter(), @as(u32, @intCast(@as(i64, addr) + data.offset))) catch unreachable;
975967 }
976968}
977969
src/arch/wasm/Mir.zig+14-10
......@@ -65,9 +65,7 @@ pub const Inst = struct {
6565 /// Lowers to an i32_const (wasm32) or i64_const (wasm64) which is the
6666 /// memory address of a named constant.
6767 ///
68 /// When this refers to a function, this always lowers to an i32_const
69 /// which is the function index. When emitting an object file, this
70 /// adds a `Wasm.Relocation.Tag.TABLE_INDEX_SLEB` relocation.
68 /// May not refer to a function.
7169 ///
7270 /// Uses `nav_index`.
7371 nav_ref,
......@@ -75,10 +73,15 @@ pub const Inst = struct {
7573 /// memory address of named constant, offset by an integer value.
7674 /// When emitting an object file, this adds a relocation.
7775 ///
78 /// This may not refer to a function.
76 /// May not refer to a function.
7977 ///
8078 /// Uses `payload` pointing to a `NavRefOff`.
8179 nav_ref_off,
80 /// Lowers to an i32_const which is the index of the function in the
81 /// table section.
82 ///
83 /// Uses `indirect_function_table_index`.
84 func_ref,
8285 /// Inserts debug information about the current line and column
8386 /// of the source code
8487 ///
......@@ -88,12 +91,6 @@ pub const Inst = struct {
8891 /// names.
8992 /// Uses `tag`.
9093 errors_len,
91 /// Lowers to an i32_const (wasm32) or i64_const (wasm64) containing
92 /// the base address of the table of error code names, with each
93 /// element being a null-terminated slice.
94 ///
95 /// Uses `tag`.
96 error_name_table_ref,
9794 /// Represents the end of a function body or an initialization expression
9895 ///
9996 /// Uses `tag` (no additional data).
......@@ -115,6 +112,12 @@ pub const Inst = struct {
115112 ///
116113 /// Uses `tag`.
117114 @"return" = 0x0F,
115 /// Lowers to an i32_const (wasm32) or i64_const (wasm64) containing
116 /// the base address of the table of error code names, with each
117 /// element being a null-terminated slice.
118 ///
119 /// Uses `tag`.
120 error_name_table_ref,
118121 /// Calls a function using `nav_index`.
119122 call_nav,
120123 /// Calls a function pointer by its function signature
......@@ -612,6 +615,7 @@ pub const Inst = struct {
612615 intrinsic: Intrinsic,
613616 uav_obj: Wasm.UavsObjIndex,
614617 uav_exe: Wasm.UavsExeIndex,
618 indirect_function_table_index: Wasm.IndirectFunctionTableIndex,
615619
616620 comptime {
617621 switch (builtin.mode) {
src/link/Wasm.zig+36-14
......@@ -235,6 +235,10 @@ global_imports: std.AutoArrayHashMapUnmanaged(String, GlobalImportId) = .empty,
235235tables: std.AutoArrayHashMapUnmanaged(TableImport.Resolution, void) = .empty,
236236table_imports: std.AutoArrayHashMapUnmanaged(String, TableImport.Index) = .empty,
237237
238/// All functions that have had their address taken and therefore might be
239/// called via a `call_indirect` function.
240indirect_function_table: std.AutoArrayHashMapUnmanaged(InternPool.Index, void) = .empty,
241
238242error_name_table_ref_count: u32 = 0,
239243
240244/// Set to true if any `GLOBAL_INDEX` relocation is encountered with
......@@ -260,6 +264,11 @@ error_name_bytes: std.ArrayListUnmanaged(u8) = .empty,
260264/// is stored. No need to serialize; trivially reconstructed.
261265error_name_offs: std.ArrayListUnmanaged(u32) = .empty,
262266
267/// Index into `Wasm.indirect_function_table`.
268pub const IndirectFunctionTableIndex = enum(u32) {
269 _,
270};
271
263272pub const UavFixup = extern struct {
264273 uavs_exe_index: UavsExeIndex,
265274 /// Index into `string_bytes`.
......@@ -335,17 +344,24 @@ pub const OutputFunctionIndex = enum(u32) {
335344 return @enumFromInt(wasm.function_imports.entries.len + @intFromEnum(index));
336345 }
337346
347 pub fn fromIpIndex(wasm: *const Wasm, ip_index: InternPool.Index) OutputFunctionIndex {
348 const zcu = wasm.base.comp.zcu.?;
349 const ip = &zcu.intern_pool;
350 return switch (ip.indexToKey(ip_index)) {
351 .@"extern" => |ext| {
352 const name = wasm.getExistingString(ext.name.toSlice(ip)).?;
353 if (wasm.function_imports.getIndex(name)) |i| return @enumFromInt(i);
354 return fromFunctionIndex(wasm, FunctionIndex.fromSymbolName(wasm, name).?);
355 },
356 else => fromResolution(wasm, .fromIpIndex(wasm, ip_index)).?,
357 };
358 }
359
338360 pub fn fromIpNav(wasm: *const Wasm, nav_index: InternPool.Nav.Index) OutputFunctionIndex {
339361 const zcu = wasm.base.comp.zcu.?;
340362 const ip = &zcu.intern_pool;
341363 const nav = ip.getNav(nav_index);
342 if (nav.toExtern(ip)) |ext| {
343 const name = wasm.getExistingString(ext.name.toSlice(ip)).?;
344 if (wasm.function_imports.getIndex(name)) |i| return @enumFromInt(i);
345 return fromFunctionIndex(wasm, FunctionIndex.fromSymbolName(wasm, name).?);
346 } else {
347 return fromFunctionIndex(wasm, FunctionIndex.fromIpNav(wasm, nav_index).?);
348 }
364 return fromIpIndex(wasm, nav.status.resolved.val);
349365 }
350366
351367 pub fn fromTagNameType(wasm: *const Wasm, tag_type: InternPool.Index) OutputFunctionIndex {
......@@ -894,11 +910,11 @@ pub const FunctionImport = extern struct {
894910 pub fn fromIpNav(wasm: *const Wasm, nav_index: InternPool.Nav.Index) Resolution {
895911 const zcu = wasm.base.comp.zcu.?;
896912 const ip = &zcu.intern_pool;
897 const nav = ip.getNav(nav_index);
898 //log.debug("Resolution.fromIpNav {}({})", .{ nav.fqn.fmt(ip), nav_index });
899 return pack(wasm, .{
900 .zcu_func = @enumFromInt(wasm.zcu_funcs.getIndex(nav.status.resolved.val).?),
901 });
913 return fromIpIndex(wasm, ip.getNav(nav_index).status.resolved.val);
914 }
915
916 pub fn fromIpIndex(wasm: *const Wasm, ip_index: InternPool.Index) Resolution {
917 return pack(wasm, .{ .zcu_func = @enumFromInt(wasm.zcu_funcs.getIndex(ip_index).?) });
902918 }
903919
904920 pub fn isNavOrUnresolved(r: Resolution, wasm: *const Wasm) bool {
......@@ -1168,7 +1184,7 @@ pub const TableImport = extern struct {
11681184 pub fn refType(r: Resolution, wasm: *const Wasm) std.wasm.RefType {
11691185 return switch (unpack(r)) {
11701186 .unresolved => unreachable,
1171 .__indirect_function_table => @panic("TODO"),
1187 .__indirect_function_table => .funcref,
11721188 .object_table => |i| i.ptr(wasm).flags.ref_type.to(),
11731189 };
11741190 }
......@@ -1176,7 +1192,11 @@ pub const TableImport = extern struct {
11761192 pub fn limits(r: Resolution, wasm: *const Wasm) std.wasm.Limits {
11771193 return switch (unpack(r)) {
11781194 .unresolved => unreachable,
1179 .__indirect_function_table => @panic("TODO"),
1195 .__indirect_function_table => .{
1196 .flags = .{ .has_max = true, .is_shared = false },
1197 .min = @intCast(wasm.indirect_function_table.entries.len + 1),
1198 .max = @intCast(wasm.indirect_function_table.entries.len + 1),
1199 },
11801200 .object_table => |i| i.ptr(wasm).limits(),
11811201 };
11821202 }
......@@ -2370,10 +2390,12 @@ pub fn deinit(wasm: *Wasm) void {
23702390 wasm.global_exports.deinit(gpa);
23712391 wasm.global_imports.deinit(gpa);
23722392 wasm.table_imports.deinit(gpa);
2393 wasm.tables.deinit(gpa);
23732394 wasm.symbol_table.deinit(gpa);
23742395 wasm.out_relocs.deinit(gpa);
23752396 wasm.uav_fixups.deinit(gpa);
23762397 wasm.nav_fixups.deinit(gpa);
2398 wasm.indirect_function_table.deinit(gpa);
23772399
23782400 wasm.string_bytes.deinit(gpa);
23792401 wasm.string_table.deinit(gpa);
src/link/Wasm/Flush.zig+29-34
......@@ -33,8 +33,6 @@ missing_exports: std.AutoArrayHashMapUnmanaged(String, void) = .empty,
3333function_imports: std.AutoArrayHashMapUnmanaged(String, Wasm.FunctionImportId) = .empty,
3434global_imports: std.AutoArrayHashMapUnmanaged(String, Wasm.GlobalImportId) = .empty,
3535
36indirect_function_table: std.AutoArrayHashMapUnmanaged(Wasm.OutputFunctionIndex, u32) = .empty,
37
3836/// For debug purposes only.
3937memory_layout_finished: bool = false,
4038
......@@ -42,7 +40,6 @@ pub fn clear(f: *Flush) void {
4240 f.data_segments.clearRetainingCapacity();
4341 f.data_segment_groups.clearRetainingCapacity();
4442 f.binary_bytes.clearRetainingCapacity();
45 f.indirect_function_table.clearRetainingCapacity();
4643 f.memory_layout_finished = false;
4744}
4845
......@@ -53,7 +50,6 @@ pub fn deinit(f: *Flush, gpa: Allocator) void {
5350 f.missing_exports.deinit(gpa);
5451 f.function_imports.deinit(gpa);
5552 f.global_imports.deinit(gpa);
56 f.indirect_function_table.deinit(gpa);
5753 f.* = undefined;
5854}
5955
......@@ -72,10 +68,6 @@ pub fn finish(f: *Flush, wasm: *Wasm) !void {
7268 };
7369 const is_obj = comp.config.output_mode == .Obj;
7470 const allow_undefined = is_obj or wasm.import_symbols;
75 //const undef_byte: u8 = switch (comp.root_mod.optimize_mode) {
76 // .Debug, .ReleaseSafe => 0xaa,
77 // .ReleaseFast, .ReleaseSmall => 0x00,
78 //};
7971
8072 if (comp.zcu) |zcu| {
8173 const ip: *const InternPool = &zcu.intern_pool; // No mutations allowed!
......@@ -215,6 +207,12 @@ pub fn finish(f: *Flush, wasm: *Wasm) !void {
215207 wasm.functions.putAssumeCapacity(.__wasm_init_tls, {});
216208 }
217209
210 try wasm.tables.ensureUnusedCapacity(gpa, 1);
211
212 if (wasm.indirect_function_table.entries.len > 0) {
213 wasm.tables.putAssumeCapacity(.__indirect_function_table, {});
214 }
215
218216 // Sort order:
219217 // 0. Segment category (tls, data, zero)
220218 // 1. Segment name prefix
......@@ -642,34 +640,31 @@ pub fn finish(f: *Flush, wasm: *Wasm) !void {
642640 replaceVecSectionHeader(binary_bytes, header_offset, .start, @intFromEnum(func_index));
643641 }
644642
645 // element section (function table)
646 if (f.indirect_function_table.count() > 0) {
647 @panic("TODO");
648 //const header_offset = try reserveVecSectionHeader(gpa, binary_bytes);
649
650 //const table_loc = wasm.globals.get(wasm.preloaded_strings.__indirect_function_table).?;
651 //const table_sym = wasm.finalSymbolByLoc(table_loc);
643 // element section
644 if (wasm.indirect_function_table.entries.len > 0) {
645 const header_offset = try reserveVecSectionHeader(gpa, binary_bytes);
652646
653 //const flags: u32 = if (table_sym.index == 0) 0x0 else 0x02; // passive with implicit 0-index table or set table index manually
654 //try leb.writeUleb128(binary_writer, flags);
655 //if (flags == 0x02) {
656 // try leb.writeUleb128(binary_writer, table_sym.index);
657 //}
658 //try emitInit(binary_writer, .{ .i32_const = 1 }); // We start at index 1, so unresolved function pointers are invalid
659 //if (flags == 0x02) {
660 // try leb.writeUleb128(binary_writer, @as(u8, 0)); // represents funcref
661 //}
662 //try leb.writeUleb128(binary_writer, @as(u32, @intCast(f.indirect_function_table.count())));
663 //var symbol_it = f.indirect_function_table.keyIterator();
664 //while (symbol_it.next()) |symbol_loc_ptr| {
665 // const sym = wasm.finalSymbolByLoc(symbol_loc_ptr.*);
666 // assert(sym.flags.alive);
667 // assert(sym.index < wasm.functions.count() + wasm.imported_functions_count);
668 // try leb.writeUleb128(binary_writer, sym.index);
669 //}
647 // indirect function table elements
648 const table_index: u32 = @intCast(wasm.tables.getIndex(.__indirect_function_table).?);
649 // passive with implicit 0-index table or set table index manually
650 const flags: u32 = if (table_index == 0) 0x0 else 0x02;
651 try leb.writeUleb128(binary_writer, flags);
652 if (flags == 0x02) {
653 try leb.writeUleb128(binary_writer, table_index);
654 }
655 // We start at index 1, so unresolved function pointers are invalid
656 try emitInit(binary_writer, .{ .i32_const = 1 });
657 if (flags == 0x02) {
658 try leb.writeUleb128(binary_writer, @as(u8, 0)); // represents funcref
659 }
660 try leb.writeUleb128(binary_writer, @as(u32, @intCast(wasm.indirect_function_table.entries.len)));
661 for (wasm.indirect_function_table.keys()) |ip_index| {
662 const func_index: Wasm.OutputFunctionIndex = .fromIpIndex(wasm, ip_index);
663 try leb.writeUleb128(binary_writer, @intFromEnum(func_index));
664 }
670665
671 //replaceVecSectionHeader(binary_bytes, header_offset, .element, 1);
672 //section_index += 1;
666 replaceVecSectionHeader(binary_bytes, header_offset, .element, 1);
667 section_index += 1;
673668 }
674669
675670 // When the shared-memory option is enabled, we *must* emit the 'data count' section.