| ... | ... | @@ -13,7 +13,6 @@ const windows = std.os.windows; |
| 13 | 13 | const macho = std.macho; |
| 14 | 14 | const fs = std.fs; |
| 15 | 15 | const coff = std.coff; |
| 16 | | const pdb = std.pdb; |
| 17 | 16 | const assert = std.debug.assert; |
| 18 | 17 | const posix = std.posix; |
| 19 | 18 | const elf = std.elf; |
| ... | ... | @@ -22,86 +21,37 @@ const Pdb = std.debug.Pdb; |
| 22 | 21 | const File = std.fs.File; |
| 23 | 22 | const math = std.math; |
| 24 | 23 | const testing = std.testing; |
| 25 | | const StackIterator = std.debug.StackIterator; |
| 26 | 24 | const regBytes = Dwarf.abi.regBytes; |
| 27 | 25 | const regValueNative = Dwarf.abi.regValueNative; |
| 28 | 26 | |
| 29 | 27 | const SelfInfo = @This(); |
| 30 | 28 | |
| 31 | | const root = @import("root"); |
| 32 | | |
| 33 | | allocator: Allocator, |
| 34 | | address_map: std.AutoHashMapUnmanaged(usize, Module), |
| 35 | | modules: if (native_os == .windows) std.ArrayListUnmanaged(WindowsModule) else void, |
| 36 | | |
| 37 | | pub const OpenError = error{ |
| 38 | | MissingDebugInfo, |
| 39 | | UnsupportedOperatingSystem, |
| 40 | | } || @typeInfo(@typeInfo(@TypeOf(SelfInfo.init)).@"fn".return_type.?).error_union.error_set; |
| 41 | | |
| 42 | | pub fn open(allocator: Allocator) OpenError!SelfInfo { |
| 43 | | if (builtin.strip_debug_info) |
| 44 | | return error.MissingDebugInfo; |
| 45 | | switch (native_os) { |
| 46 | | .linux, |
| 47 | | .freebsd, |
| 48 | | .netbsd, |
| 49 | | .dragonfly, |
| 50 | | .openbsd, |
| 51 | | .macos, |
| 52 | | .solaris, |
| 53 | | .illumos, |
| 54 | | .windows, |
| 55 | | => return try SelfInfo.init(allocator), |
| 56 | | else => return error.UnsupportedOperatingSystem, |
| 57 | | } |
| 58 | | } |
| 59 | | |
| 60 | | pub fn init(allocator: Allocator) !SelfInfo { |
| 61 | | var debug_info: SelfInfo = .{ |
| 62 | | .allocator = allocator, |
| 63 | | .address_map = .empty, |
| 64 | | .modules = if (native_os == .windows) .{} else {}, |
| 65 | | }; |
| 66 | | |
| 67 | | if (native_os == .windows) { |
| 68 | | errdefer debug_info.modules.deinit(allocator); |
| 69 | | |
| 70 | | const handle = windows.kernel32.CreateToolhelp32Snapshot(windows.TH32CS_SNAPMODULE | windows.TH32CS_SNAPMODULE32, 0); |
| 71 | | if (handle == windows.INVALID_HANDLE_VALUE) { |
| 72 | | switch (windows.GetLastError()) { |
| 73 | | else => |err| return windows.unexpectedError(err), |
| 74 | | } |
| 75 | | } |
| 76 | | defer windows.CloseHandle(handle); |
| 77 | | |
| 78 | | var module_entry: windows.MODULEENTRY32 = undefined; |
| 79 | | module_entry.dwSize = @sizeOf(windows.MODULEENTRY32); |
| 80 | | if (windows.kernel32.Module32First(handle, &module_entry) == 0) { |
| 81 | | return error.MissingDebugInfo; |
| 82 | | } |
| 83 | | |
| 84 | | var module_valid = true; |
| 85 | | while (module_valid) { |
| 86 | | const module_info = try debug_info.modules.addOne(allocator); |
| 87 | | const name = allocator.dupe(u8, mem.sliceTo(&module_entry.szModule, 0)) catch &.{}; |
| 88 | | errdefer allocator.free(name); |
| 89 | | |
| 90 | | module_info.* = .{ |
| 91 | | .base_address = @intFromPtr(module_entry.modBaseAddr), |
| 92 | | .size = module_entry.modBaseSize, |
| 93 | | .name = name, |
| 94 | | .handle = module_entry.hModule, |
| 95 | | }; |
| 96 | | |
| 97 | | module_valid = windows.kernel32.Module32Next(handle, &module_entry) == 1; |
| 98 | | } |
| 99 | | } |
| 29 | /// MLUGG TODO: what if this field had a less stupid name... |
| 30 | address_map: std.AutoHashMapUnmanaged(usize, Module.DebugInfo), |
| 31 | |
| 32 | module_cache: if (native_os == .windows) std.ArrayListUnmanaged(windows.MODULEENTRY32) else void, |
| 33 | |
| 34 | pub const target_supported: bool = switch (native_os) { |
| 35 | .linux, |
| 36 | .freebsd, |
| 37 | .netbsd, |
| 38 | .dragonfly, |
| 39 | .openbsd, |
| 40 | .macos, |
| 41 | .solaris, |
| 42 | .illumos, |
| 43 | .windows, |
| 44 | => true, |
| 45 | else => false, |
| 46 | }; |
| 100 | 47 | |
| 101 | | return debug_info; |
| 102 | | } |
| 48 | pub const init: SelfInfo = .{ |
| 49 | .address_map = .empty, |
| 50 | .module_cache = if (native_os == .windows) .empty, |
| 51 | }; |
| 103 | 52 | |
| 104 | 53 | pub fn deinit(self: *SelfInfo) void { |
| 54 | // MLUGG TODO: that's amusing, this function is straight-up unused. i... wonder if it even should be used anywhere? perhaps not... so perhaps it should not even exist...???? |
| 105 | 55 | var it = self.address_map.iterator(); |
| 106 | 56 | while (it.next()) |entry| { |
| 107 | 57 | const mdi = entry.value_ptr.*; |
| ... | ... | @@ -118,49 +68,91 @@ pub fn deinit(self: *SelfInfo) void { |
| 118 | 68 | } |
| 119 | 69 | } |
| 120 | 70 | |
| 121 | | fn lookupModuleForAddress(self: *SelfInfo, address: usize) !Module.Lookup { |
| 71 | fn lookupModuleForAddress(self: *SelfInfo, gpa: Allocator, address: usize) !Module { |
| 122 | 72 | if (builtin.target.os.tag.isDarwin()) { |
| 123 | 73 | return self.lookupModuleDyld(address); |
| 124 | 74 | } else if (native_os == .windows) { |
| 125 | | return self.lookupModuleWin32(address); |
| 75 | return self.lookupModuleWin32(gpa, address); |
| 126 | 76 | } else if (native_os == .haiku) { |
| 127 | | return self.lookupModuleHaiku(address); |
| 77 | @panic("TODO implement lookup module for Haiku"); |
| 128 | 78 | } else if (builtin.target.cpu.arch.isWasm()) { |
| 129 | | return self.lookupModuleWasm(address); |
| 79 | @panic("TODO implement lookup module for Wasm"); |
| 130 | 80 | } else { |
| 131 | 81 | return self.lookupModuleDl(address); |
| 132 | 82 | } |
| 133 | 83 | } |
| 134 | 84 | |
| 135 | | fn loadModuleDebugInfo(self: *SelfInfo, lookup: *const Module.Lookup, module: *Module) !void { |
| 85 | fn loadModuleDebugInfo(gpa: Allocator, module: *const Module, di: *Module.DebugInfo) !void { |
| 86 | // MLUGG TODO: this should totally just go into the `Module` impl or something, right? lol |
| 87 | if (builtin.target.os.tag.isDarwin()) { |
| 88 | try loadMachODebugInfo(gpa, module, di); |
| 89 | } else if (native_os == .windows) { |
| 90 | // MLUGG TODO: deal with 'already loaded' properly |
| 91 | try readCoffDebugInfo(gpa, module, di); |
| 92 | } else if (native_os == .haiku) { |
| 93 | unreachable; |
| 94 | } else if (builtin.target.cpu.arch.isWasm()) { |
| 95 | unreachable; |
| 96 | } else { |
| 97 | if (di.mapped_memory != null) return; // already loaded |
| 98 | const filename: ?[]const u8 = if (module.name.len > 0) module.name else null; |
| 99 | const mapped_mem = mapFileOrSelfExe(filename) catch |err| switch (err) { |
| 100 | error.FileNotFound => return error.MissingDebugInfo, |
| 101 | error.FileTooBig => return error.InvalidDebugInfo, |
| 102 | else => |e| return e, |
| 103 | }; |
| 104 | errdefer posix.munmap(mapped_mem); |
| 105 | try di.load(gpa, mapped_mem, module.build_id, null, null, null, filename); |
| 106 | assert(di.mapped_memory != null); |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | fn loadModuleUnwindInfo(gpa: Allocator, module: *const Module, di: *Module.DebugInfo) !void { |
| 136 | 111 | if (builtin.target.os.tag.isDarwin()) { |
| 137 | | @compileError("TODO"); |
| 112 | // MLUGG TODO HACKHACK |
| 113 | try loadMachODebugInfo(gpa, module, di); |
| 138 | 114 | } else if (native_os == .windows) { |
| 139 | | @compileError("TODO"); |
| 115 | comptime unreachable; // not supported |
| 140 | 116 | } else if (native_os == .haiku) { |
| 141 | | @compileError("TODO"); |
| 117 | comptime unreachable; // not supported |
| 142 | 118 | } else if (builtin.target.cpu.arch.isWasm()) { |
| 143 | | @compileError("TODO"); |
| 119 | comptime unreachable; // not supported |
| 144 | 120 | } else { |
| 145 | | if (module.mapped_memory == null) { |
| 146 | | var sections: Dwarf.SectionArray = @splat(null); |
| 147 | | try readElfDebugInfo(module, self.allocator, if (lookup.name.len > 0) lookup.name else null, lookup.build_id, &sections); |
| 148 | | assert(module.mapped_memory != null); |
| 121 | eh_frame: { |
| 122 | if (di.unwind.eh_frame != null) break :eh_frame; // already loaded |
| 123 | const eh_frame_hdr_bytes = module.gnu_eh_frame orelse break :eh_frame; |
| 124 | const eh_frame_hdr: Dwarf.Unwind.EhFrameHeader = try .parse( |
| 125 | @intFromPtr(eh_frame_hdr_bytes.ptr) - module.load_offset, |
| 126 | eh_frame_hdr_bytes, |
| 127 | @sizeOf(usize), |
| 128 | native_endian, |
| 129 | ); |
| 130 | const eh_frame_addr = module.load_offset + @as(usize, @intCast(eh_frame_hdr.eh_frame_vaddr)); |
| 131 | try di.unwind.scanEhFrame( |
| 132 | gpa, |
| 133 | eh_frame_hdr, |
| 134 | @ptrFromInt(eh_frame_addr), |
| 135 | null, |
| 136 | @sizeOf(usize), |
| 137 | native_endian, |
| 138 | ); |
| 149 | 139 | } |
| 150 | 140 | } |
| 151 | 141 | } |
| 152 | 142 | |
| 153 | | pub fn unwindFrame(self: *SelfInfo, context: *UnwindContext) !usize { |
| 154 | | const lookup = try self.lookupModuleForAddress(context.pc); |
| 155 | | const gop = try self.address_map.getOrPut(self.allocator, lookup.base_address); |
| 156 | | if (!gop.found_existing) gop.value_ptr.* = .init(&lookup); |
| 143 | pub fn unwindFrame(self: *SelfInfo, gpa: Allocator, context: *UnwindContext) !usize { |
| 144 | comptime assert(target_supported); |
| 145 | const module = try self.lookupModuleForAddress(gpa, context.pc); |
| 146 | const gop = try self.address_map.getOrPut(gpa, module.load_offset); |
| 147 | if (!gop.found_existing) gop.value_ptr.* = .init; |
| 148 | try loadModuleUnwindInfo(gpa, &module, gop.value_ptr); |
| 157 | 149 | if (native_os.isDarwin()) { |
| 158 | 150 | // __unwind_info is a requirement for unwinding on Darwin. It may fall back to DWARF, but unwinding |
| 159 | 151 | // via DWARF before attempting to use the compact unwind info will produce incorrect results. |
| 160 | 152 | if (gop.value_ptr.unwind_info) |unwind_info| { |
| 161 | 153 | if (unwindFrameMachO( |
| 162 | | self.allocator, |
| 163 | | lookup.base_address, |
| 154 | module.text_base, |
| 155 | module.load_offset, |
| 164 | 156 | context, |
| 165 | 157 | unwind_info, |
| 166 | 158 | gop.value_ptr.eh_frame, |
| ... | ... | @@ -169,292 +161,42 @@ pub fn unwindFrame(self: *SelfInfo, context: *UnwindContext) !usize { |
| 169 | 161 | } else |err| { |
| 170 | 162 | if (err != error.RequiresDWARFUnwind) return err; |
| 171 | 163 | } |
| 172 | | } else return error.MissingUnwindInfo; |
| 164 | } |
| 165 | return error.MissingUnwindInfo; |
| 166 | } |
| 167 | if (try gop.value_ptr.getDwarfUnwindForAddress(gpa, context.pc)) |unwind| { |
| 168 | return unwindFrameDwarf(unwind, module.load_offset, context, null); |
| 173 | 169 | } |
| 174 | | if (try gop.value_ptr.getDwarfUnwindForAddress(self.allocator, context.pc)) |unwind| { |
| 175 | | return unwindFrameDwarf(self.allocator, unwind, lookup.base_address, context, null); |
| 176 | | } else return error.MissingDebugInfo; |
| 170 | return error.MissingDebugInfo; |
| 177 | 171 | } |
| 178 | 172 | |
| 179 | | pub fn getSymbolAtAddress(self: *SelfInfo, address: usize) !std.debug.Symbol { |
| 180 | | const lookup = try self.lookupModuleForAddress(address); |
| 181 | | const gop = try self.address_map.getOrPut(self.allocator, lookup.base_address); |
| 182 | | if (!gop.found_existing) gop.value_ptr.* = .init(&lookup); |
| 183 | | try self.loadModuleDebugInfo(&lookup, gop.value_ptr); |
| 184 | | return gop.value_ptr.getSymbolAtAddress(self.allocator, native_endian, lookup.base_address, address); |
| 173 | pub fn getSymbolAtAddress(self: *SelfInfo, gpa: Allocator, address: usize) !std.debug.Symbol { |
| 174 | comptime assert(target_supported); |
| 175 | const module = try self.lookupModuleForAddress(gpa, address); |
| 176 | const gop = try self.address_map.getOrPut(gpa, module.key()); |
| 177 | if (!gop.found_existing) gop.value_ptr.* = .init; |
| 178 | try loadModuleDebugInfo(gpa, &module, gop.value_ptr); |
| 179 | return module.getSymbolAtAddress(gpa, gop.value_ptr, address); |
| 185 | 180 | } |
| 186 | 181 | |
| 187 | 182 | /// Returns the module name for a given address. |
| 188 | 183 | /// This can be called when getModuleForAddress fails, so implementations should provide |
| 189 | 184 | /// a path that doesn't rely on any side-effects of a prior successful module lookup. |
| 190 | | pub fn getModuleNameForAddress(self: *SelfInfo, address: usize) ?[]const u8 { |
| 191 | | return if (self.lookupModuleForAddress(address)) |lookup| lookup.name else |err| switch (err) { |
| 192 | | error.MissingDebugInfo => null, |
| 193 | | }; |
| 194 | | } |
| 195 | | |
| 196 | | fn lookupModuleDyld(self: *SelfInfo, address: usize) !*Module { |
| 197 | | const image_count = std.c._dyld_image_count(); |
| 198 | | |
| 199 | | var i: u32 = 0; |
| 200 | | while (i < image_count) : (i += 1) { |
| 201 | | const header = std.c._dyld_get_image_header(i) orelse continue; |
| 202 | | const base_address = @intFromPtr(header); |
| 203 | | if (address < base_address) continue; |
| 204 | | const vmaddr_slide = std.c._dyld_get_image_vmaddr_slide(i); |
| 205 | | |
| 206 | | var it = macho.LoadCommandIterator{ |
| 207 | | .ncmds = header.ncmds, |
| 208 | | .buffer = @alignCast(@as( |
| 209 | | [*]u8, |
| 210 | | @ptrFromInt(@intFromPtr(header) + @sizeOf(macho.mach_header_64)), |
| 211 | | )[0..header.sizeofcmds]), |
| 212 | | }; |
| 213 | | |
| 214 | | var unwind_info: ?[]const u8 = null; |
| 215 | | var eh_frame: ?[]const u8 = null; |
| 216 | | while (it.next()) |cmd| switch (cmd.cmd()) { |
| 217 | | .SEGMENT_64 => { |
| 218 | | const segment_cmd = cmd.cast(macho.segment_command_64).?; |
| 219 | | if (!mem.eql(u8, "__TEXT", segment_cmd.segName())) continue; |
| 220 | | |
| 221 | | const seg_start = segment_cmd.vmaddr + vmaddr_slide; |
| 222 | | const seg_end = seg_start + segment_cmd.vmsize; |
| 223 | | if (address >= seg_start and address < seg_end) { |
| 224 | | if (self.address_map.get(base_address)) |obj_di| { |
| 225 | | return obj_di; |
| 226 | | } |
| 227 | | |
| 228 | | for (cmd.getSections()) |sect| { |
| 229 | | const sect_addr: usize = @intCast(sect.addr); |
| 230 | | const sect_size: usize = @intCast(sect.size); |
| 231 | | if (mem.eql(u8, "__unwind_info", sect.sectName())) { |
| 232 | | unwind_info = @as([*]const u8, @ptrFromInt(sect_addr + vmaddr_slide))[0..sect_size]; |
| 233 | | } else if (mem.eql(u8, "__eh_frame", sect.sectName())) { |
| 234 | | eh_frame = @as([*]const u8, @ptrFromInt(sect_addr + vmaddr_slide))[0..sect_size]; |
| 235 | | } |
| 236 | | } |
| 237 | | |
| 238 | | const obj_di = try self.allocator.create(Module); |
| 239 | | errdefer self.allocator.destroy(obj_di); |
| 240 | | |
| 241 | | const macho_path = mem.sliceTo(std.c._dyld_get_image_name(i), 0); |
| 242 | | const macho_file = fs.cwd().openFile(macho_path, .{}) catch |err| switch (err) { |
| 243 | | error.FileNotFound => return error.MissingDebugInfo, |
| 244 | | else => return err, |
| 245 | | }; |
| 246 | | obj_di.* = try readMachODebugInfo(self.allocator, macho_file); |
| 247 | | obj_di.base_address = base_address; |
| 248 | | obj_di.vmaddr_slide = vmaddr_slide; |
| 249 | | obj_di.unwind_info = unwind_info; |
| 250 | | obj_di.eh_frame = eh_frame; |
| 251 | | |
| 252 | | try self.address_map.putNoClobber(base_address, obj_di); |
| 253 | | |
| 254 | | return obj_di; |
| 255 | | } |
| 256 | | }, |
| 257 | | else => {}, |
| 258 | | }; |
| 259 | | } |
| 260 | | |
| 261 | | return error.MissingDebugInfo; |
| 262 | | } |
| 263 | | |
| 264 | | fn lookupModuleNameDyld(self: *SelfInfo, address: usize) ?[]const u8 { |
| 265 | | _ = self; |
| 266 | | const image_count = std.c._dyld_image_count(); |
| 267 | | |
| 268 | | var i: u32 = 0; |
| 269 | | while (i < image_count) : (i += 1) { |
| 270 | | const header = std.c._dyld_get_image_header(i) orelse continue; |
| 271 | | const base_address = @intFromPtr(header); |
| 272 | | if (address < base_address) continue; |
| 273 | | const vmaddr_slide = std.c._dyld_get_image_vmaddr_slide(i); |
| 274 | | |
| 275 | | var it = macho.LoadCommandIterator{ |
| 276 | | .ncmds = header.ncmds, |
| 277 | | .buffer = @alignCast(@as( |
| 278 | | [*]u8, |
| 279 | | @ptrFromInt(@intFromPtr(header) + @sizeOf(macho.mach_header_64)), |
| 280 | | )[0..header.sizeofcmds]), |
| 281 | | }; |
| 282 | | |
| 283 | | while (it.next()) |cmd| switch (cmd.cmd()) { |
| 284 | | .SEGMENT_64 => { |
| 285 | | const segment_cmd = cmd.cast(macho.segment_command_64).?; |
| 286 | | if (!mem.eql(u8, "__TEXT", segment_cmd.segName())) continue; |
| 287 | | |
| 288 | | const original_address = address - vmaddr_slide; |
| 289 | | const seg_start = segment_cmd.vmaddr; |
| 290 | | const seg_end = seg_start + segment_cmd.vmsize; |
| 291 | | if (original_address >= seg_start and original_address < seg_end) { |
| 292 | | return fs.path.basename(mem.sliceTo(std.c._dyld_get_image_name(i), 0)); |
| 293 | | } |
| 294 | | }, |
| 295 | | else => {}, |
| 296 | | }; |
| 297 | | } |
| 298 | | |
| 299 | | return null; |
| 300 | | } |
| 301 | | |
| 302 | | fn lookupModuleWin32(self: *SelfInfo, address: usize) !*Module { |
| 303 | | for (self.modules.items) |*module| { |
| 304 | | if (address >= module.base_address and address < module.base_address + module.size) { |
| 305 | | if (self.address_map.get(module.base_address)) |obj_di| { |
| 306 | | return obj_di; |
| 307 | | } |
| 308 | | |
| 309 | | const obj_di = try self.allocator.create(Module); |
| 310 | | errdefer self.allocator.destroy(obj_di); |
| 311 | | |
| 312 | | const mapped_module = @as([*]const u8, @ptrFromInt(module.base_address))[0..module.size]; |
| 313 | | var coff_obj = try coff.Coff.init(mapped_module, true); |
| 314 | | |
| 315 | | // The string table is not mapped into memory by the loader, so if a section name is in the |
| 316 | | // string table then we have to map the full image file from disk. This can happen when |
| 317 | | // a binary is produced with -gdwarf, since the section names are longer than 8 bytes. |
| 318 | | if (coff_obj.strtabRequired()) { |
| 319 | | var name_buffer: [windows.PATH_MAX_WIDE + 4:0]u16 = undefined; |
| 320 | | // openFileAbsoluteW requires the prefix to be present |
| 321 | | @memcpy(name_buffer[0..4], &[_]u16{ '\\', '?', '?', '\\' }); |
| 322 | | |
| 323 | | const process_handle = windows.GetCurrentProcess(); |
| 324 | | const len = windows.kernel32.GetModuleFileNameExW( |
| 325 | | process_handle, |
| 326 | | module.handle, |
| 327 | | @ptrCast(&name_buffer[4]), |
| 328 | | windows.PATH_MAX_WIDE, |
| 329 | | ); |
| 330 | | |
| 331 | | if (len == 0) return error.MissingDebugInfo; |
| 332 | | const coff_file = fs.openFileAbsoluteW(name_buffer[0 .. len + 4 :0], .{}) catch |err| switch (err) { |
| 333 | | error.FileNotFound => return error.MissingDebugInfo, |
| 334 | | else => return err, |
| 335 | | }; |
| 336 | | errdefer coff_file.close(); |
| 337 | | |
| 338 | | var section_handle: windows.HANDLE = undefined; |
| 339 | | const create_section_rc = windows.ntdll.NtCreateSection( |
| 340 | | &section_handle, |
| 341 | | windows.STANDARD_RIGHTS_REQUIRED | windows.SECTION_QUERY | windows.SECTION_MAP_READ, |
| 342 | | null, |
| 343 | | null, |
| 344 | | windows.PAGE_READONLY, |
| 345 | | // The documentation states that if no AllocationAttribute is specified, then SEC_COMMIT is the default. |
| 346 | | // In practice, this isn't the case and specifying 0 will result in INVALID_PARAMETER_6. |
| 347 | | windows.SEC_COMMIT, |
| 348 | | coff_file.handle, |
| 349 | | ); |
| 350 | | if (create_section_rc != .SUCCESS) return error.MissingDebugInfo; |
| 351 | | errdefer windows.CloseHandle(section_handle); |
| 352 | | |
| 353 | | var coff_len: usize = 0; |
| 354 | | var base_ptr: usize = 0; |
| 355 | | const map_section_rc = windows.ntdll.NtMapViewOfSection( |
| 356 | | section_handle, |
| 357 | | process_handle, |
| 358 | | @ptrCast(&base_ptr), |
| 359 | | null, |
| 360 | | 0, |
| 361 | | null, |
| 362 | | &coff_len, |
| 363 | | .ViewUnmap, |
| 364 | | 0, |
| 365 | | windows.PAGE_READONLY, |
| 366 | | ); |
| 367 | | if (map_section_rc != .SUCCESS) return error.MissingDebugInfo; |
| 368 | | errdefer assert(windows.ntdll.NtUnmapViewOfSection(process_handle, @ptrFromInt(base_ptr)) == .SUCCESS); |
| 369 | | |
| 370 | | const section_view = @as([*]const u8, @ptrFromInt(base_ptr))[0..coff_len]; |
| 371 | | coff_obj = try coff.Coff.init(section_view, false); |
| 372 | | |
| 373 | | module.mapped_file = .{ |
| 374 | | .file = coff_file, |
| 375 | | .section_handle = section_handle, |
| 376 | | .section_view = section_view, |
| 377 | | }; |
| 378 | | } |
| 379 | | errdefer if (module.mapped_file) |mapped_file| mapped_file.deinit(); |
| 380 | | |
| 381 | | obj_di.* = try readCoffDebugInfo(self.allocator, &coff_obj); |
| 382 | | obj_di.base_address = module.base_address; |
| 383 | | |
| 384 | | try self.address_map.putNoClobber(module.base_address, obj_di); |
| 385 | | return obj_di; |
| 386 | | } |
| 387 | | } |
| 388 | | |
| 389 | | return error.MissingDebugInfo; |
| 390 | | } |
| 391 | | |
| 392 | | fn lookupModuleNameWin32(self: *SelfInfo, address: usize) ?[]const u8 { |
| 393 | | for (self.modules.items) |module| { |
| 394 | | if (address >= module.base_address and address < module.base_address + module.size) { |
| 395 | | return module.name; |
| 396 | | } |
| 397 | | } |
| 398 | | return null; |
| 399 | | } |
| 400 | | |
| 401 | | fn lookupModuleNameDl(self: *SelfInfo, address: usize) ?[]const u8 { |
| 402 | | _ = self; |
| 403 | | |
| 404 | | var ctx: struct { |
| 405 | | // Input |
| 406 | | address: usize, |
| 407 | | // Output |
| 408 | | name: []const u8 = "", |
| 409 | | } = .{ .address = address }; |
| 410 | | const CtxTy = @TypeOf(ctx); |
| 411 | | |
| 412 | | if (posix.dl_iterate_phdr(&ctx, error{Found}, struct { |
| 413 | | fn callback(info: *posix.dl_phdr_info, size: usize, context: *CtxTy) !void { |
| 414 | | _ = size; |
| 415 | | if (context.address < info.addr) return; |
| 416 | | const phdrs = info.phdr[0..info.phnum]; |
| 417 | | for (phdrs) |*phdr| { |
| 418 | | if (phdr.p_type != elf.PT_LOAD) continue; |
| 419 | | |
| 420 | | const seg_start = info.addr +% phdr.p_vaddr; |
| 421 | | const seg_end = seg_start + phdr.p_memsz; |
| 422 | | if (context.address >= seg_start and context.address < seg_end) { |
| 423 | | context.name = mem.sliceTo(info.name, 0) orelse ""; |
| 424 | | break; |
| 425 | | } |
| 426 | | } else return; |
| 427 | | |
| 428 | | return error.Found; |
| 429 | | } |
| 430 | | }.callback)) { |
| 431 | | return null; |
| 432 | | } else |err| switch (err) { |
| 433 | | error.Found => return fs.path.basename(ctx.name), |
| 434 | | } |
| 435 | | |
| 436 | | return null; |
| 185 | pub fn getModuleNameForAddress(self: *SelfInfo, gpa: Allocator, address: usize) error{ Unexpected, OutOfMemory, MissingDebugInfo }![]const u8 { |
| 186 | comptime assert(target_supported); |
| 187 | const module = try self.lookupModuleForAddress(gpa, address); |
| 188 | return module.name; |
| 437 | 189 | } |
| 438 | 190 | |
| 439 | | fn lookupModuleDl(self: *SelfInfo, address: usize) !Module.Lookup { |
| 440 | | var ctx: struct { |
| 441 | | // Input |
| 191 | fn lookupModuleDl(self: *SelfInfo, address: usize) !Module { |
| 192 | _ = self; // MLUGG |
| 193 | const DlIterContext = struct { |
| 194 | /// input |
| 442 | 195 | address: usize, |
| 443 | | // Output |
| 444 | | lookup: Module.Lookup, |
| 445 | | } = .{ |
| 446 | | .address = address, |
| 447 | | .lookup = .{ |
| 448 | | .base_address = undefined, |
| 449 | | .name = undefined, |
| 450 | | .build_id = null, |
| 451 | | .gnu_eh_frame = null, |
| 452 | | }, |
| 453 | | }; |
| 454 | | const CtxTy = @TypeOf(ctx); |
| 196 | /// output |
| 197 | module: Module, |
| 455 | 198 | |
| 456 | | posix.dl_iterate_phdr(&ctx, error{Found}, struct { |
| 457 | | fn callback(info: *posix.dl_phdr_info, size: usize, context: *CtxTy) !void { |
| 199 | fn callback(info: *posix.dl_phdr_info, size: usize, context: *@This()) !void { |
| 458 | 200 | _ = size; |
| 459 | 201 | // The base address is too high |
| 460 | 202 | if (context.address < info.addr) |
| ... | ... | @@ -468,10 +210,13 @@ fn lookupModuleDl(self: *SelfInfo, address: usize) !Module.Lookup { |
| 468 | 210 | const seg_start = info.addr +% phdr.p_vaddr; |
| 469 | 211 | const seg_end = seg_start + phdr.p_memsz; |
| 470 | 212 | if (context.address >= seg_start and context.address < seg_end) { |
| 471 | | // Android libc uses NULL instead of an empty string to mark the |
| 472 | | // main program |
| 473 | | context.lookup.name = mem.sliceTo(info.name, 0) orelse ""; |
| 474 | | context.lookup.base_address = info.addr; |
| 213 | context.module = .{ |
| 214 | .load_offset = info.addr, |
| 215 | // Android libc uses NULL instead of "" to mark the main program |
| 216 | .name = mem.sliceTo(info.name, 0) orelse "", |
| 217 | .build_id = null, |
| 218 | .gnu_eh_frame = null, |
| 219 | }; |
| 475 | 220 | break; |
| 476 | 221 | } |
| 477 | 222 | } else return; |
| ... | ... | @@ -480,17 +225,20 @@ fn lookupModuleDl(self: *SelfInfo, address: usize) !Module.Lookup { |
| 480 | 225 | switch (phdr.p_type) { |
| 481 | 226 | elf.PT_NOTE => { |
| 482 | 227 | // Look for .note.gnu.build-id |
| 483 | | const note_bytes = @as([*]const u8, @ptrFromInt(info.addr + phdr.p_vaddr))[0..phdr.p_memsz]; |
| 484 | | const name_size = mem.readInt(u32, note_bytes[0..4], native_endian); |
| 485 | | if (name_size != 4) continue; |
| 486 | | const desc_size = mem.readInt(u32, note_bytes[4..8], native_endian); |
| 487 | | const note_type = mem.readInt(u32, note_bytes[8..12], native_endian); |
| 228 | const segment_ptr: [*]const u8 = @ptrFromInt(info.addr + phdr.p_vaddr); |
| 229 | var r: std.Io.Reader = .fixed(segment_ptr[0..phdr.p_memsz]); |
| 230 | const name_size = r.takeInt(u32, native_endian) catch continue; |
| 231 | const desc_size = r.takeInt(u32, native_endian) catch continue; |
| 232 | const note_type = r.takeInt(u32, native_endian) catch continue; |
| 233 | const name = r.take(name_size) catch continue; |
| 488 | 234 | if (note_type != elf.NT_GNU_BUILD_ID) continue; |
| 489 | | if (!mem.eql(u8, "GNU\x00", note_bytes[12..16])) continue; |
| 490 | | context.lookup.build_id = note_bytes[16..][0..desc_size]; |
| 235 | if (!mem.eql(u8, name, "GNU\x00")) continue; |
| 236 | const desc = r.take(desc_size) catch continue; |
| 237 | context.module.build_id = desc; |
| 491 | 238 | }, |
| 492 | 239 | elf.PT_GNU_EH_FRAME => { |
| 493 | | context.lookup.gnu_eh_frame = @as([*]const u8, @ptrFromInt(info.addr + phdr.p_vaddr))[0..phdr.p_memsz]; |
| 240 | const segment_ptr: [*]const u8 = @ptrFromInt(info.addr + phdr.p_vaddr); |
| 241 | context.module.gnu_eh_frame = segment_ptr[0..phdr.p_memsz]; |
| 494 | 242 | }, |
| 495 | 243 | else => {}, |
| 496 | 244 | } |
| ... | ... | @@ -499,425 +247,558 @@ fn lookupModuleDl(self: *SelfInfo, address: usize) !Module.Lookup { |
| 499 | 247 | // Stop the iteration |
| 500 | 248 | return error.Found; |
| 501 | 249 | } |
| 502 | | }.callback) catch |err| switch (err) { |
| 503 | | error.Found => return ctx.lookup, |
| 504 | 250 | }; |
| 505 | | if (true) return error.MissingDebugInfo; |
| 506 | | |
| 507 | | if (self.address_map.get(ctx.lookup.base_address)) |obj_di| { |
| 508 | | return obj_di; |
| 509 | | } |
| 251 | var ctx: DlIterContext = .{ |
| 252 | .address = address, |
| 253 | .module = undefined, |
| 254 | }; |
| 255 | posix.dl_iterate_phdr(&ctx, error{Found}, DlIterContext.callback) catch |err| switch (err) { |
| 256 | error.Found => return ctx.module, |
| 257 | }; |
| 258 | return error.MissingDebugInfo; |
| 259 | } |
| 510 | 260 | |
| 511 | | var sections: Dwarf.SectionArray = @splat(null); |
| 512 | | if (ctx.lookup.gnu_eh_frame) |eh_frame_hdr| { |
| 513 | | // This is a special case - pointer offsets inside .eh_frame_hdr |
| 514 | | // are encoded relative to its base address, so we must use the |
| 515 | | // version that is already memory mapped, and not the one that |
| 516 | | // will be mapped separately from the ELF file. |
| 517 | | sections[@intFromEnum(Dwarf.Unwind.Section.Id.eh_frame_hdr)] = .{ |
| 518 | | .data = eh_frame_hdr, |
| 519 | | .owned = false, |
| 261 | fn lookupModuleDyld(self: *SelfInfo, address: usize) !Module { |
| 262 | _ = self; // MLUGG |
| 263 | const image_count = std.c._dyld_image_count(); |
| 264 | for (0..image_count) |image_idx| { |
| 265 | const header = std.c._dyld_get_image_header(@intCast(image_idx)) orelse continue; |
| 266 | const text_base = @intFromPtr(header); |
| 267 | if (address < text_base) continue; |
| 268 | const load_offset = std.c._dyld_get_image_vmaddr_slide(@intCast(image_idx)); |
| 269 | |
| 270 | // Find the __TEXT segment |
| 271 | var it: macho.LoadCommandIterator = .{ |
| 272 | .ncmds = header.ncmds, |
| 273 | .buffer = @as([*]u8, @ptrCast(header))[@sizeOf(macho.mach_header_64)..][0..header.sizeofcmds], |
| 274 | }; |
| 275 | const text_segment_cmd, const text_sections = while (it.next()) |load_cmd| { |
| 276 | if (load_cmd.cmd() != .SEGMENT_64) continue; |
| 277 | const segment_cmd = load_cmd.cast(macho.segment_command_64).?; |
| 278 | if (!mem.eql(u8, segment_cmd.segName(), "__TEXT")) continue; |
| 279 | break .{ segment_cmd, load_cmd.getSections() }; |
| 280 | } else continue; |
| 281 | |
| 282 | const seg_start = load_offset + text_segment_cmd.vmaddr; |
| 283 | assert(seg_start == text_base); |
| 284 | const seg_end = seg_start + text_segment_cmd.vmsize; |
| 285 | if (address < seg_start or address >= seg_end) continue; |
| 286 | |
| 287 | // We've found the matching __TEXT segment. This is the image we need, but we must look |
| 288 | // for unwind info in it before returning. |
| 289 | |
| 290 | var result: Module = .{ |
| 291 | .text_base = text_base, |
| 292 | .load_offset = load_offset, |
| 293 | .name = mem.span(std.c._dyld_get_image_name(@intCast(image_idx))), |
| 294 | .unwind_info = null, |
| 295 | .eh_frame = null, |
| 520 | 296 | }; |
| 297 | for (text_sections) |sect| { |
| 298 | if (mem.eql(u8, sect.sectName(), "__unwind_info")) { |
| 299 | const sect_ptr: [*]u8 = @ptrFromInt(@as(usize, @intCast(load_offset + sect.addr))); |
| 300 | result.unwind_info = sect_ptr[0..@intCast(sect.size)]; |
| 301 | } else if (mem.eql(u8, sect.sectName(), "__eh_frame")) { |
| 302 | const sect_ptr: [*]u8 = @ptrFromInt(@as(usize, @intCast(load_offset + sect.addr))); |
| 303 | result.eh_frame = sect_ptr[0..@intCast(sect.size)]; |
| 304 | } |
| 305 | } |
| 306 | return result; |
| 521 | 307 | } |
| 522 | | |
| 523 | | const obj_di = try self.allocator.create(Module); |
| 524 | | errdefer self.allocator.destroy(obj_di); |
| 525 | | obj_di.* = try readElfDebugInfo(self.allocator, if (ctx.lookup.name.len > 0) ctx.lookup.name else null, ctx.lookup.build_id, &sections); |
| 526 | | obj_di.base_address = ctx.lookup.base_address; |
| 527 | | |
| 528 | | // Missing unwind info isn't treated as a failure, as the unwinder will fall back to FP-based unwinding |
| 529 | | obj_di.dwarf.scanAllUnwindInfo(self.allocator, ctx.lookup.base_address) catch {}; |
| 530 | | |
| 531 | | try self.address_map.putNoClobber(self.allocator, ctx.lookup.base_address, obj_di); |
| 532 | | |
| 533 | | return obj_di; |
| 308 | return error.MissingDebugInfo; |
| 534 | 309 | } |
| 535 | 310 | |
| 536 | | fn lookupModuleHaiku(self: *SelfInfo, address: usize) !*Module { |
| 537 | | _ = self; |
| 538 | | _ = address; |
| 539 | | @panic("TODO implement lookup module for Haiku"); |
| 540 | | } |
| 311 | fn lookupModuleWin32(self: *SelfInfo, gpa: Allocator, address: usize) !Module { |
| 312 | if (self.lookupModuleWin32Cache(address)) |m| return m; |
| 541 | 313 | |
| 542 | | fn lookupModuleWasm(self: *SelfInfo, address: usize) !*Module { |
| 543 | | _ = self; |
| 544 | | _ = address; |
| 545 | | @panic("TODO implement lookup module for Wasm"); |
| 546 | | } |
| 314 | { |
| 315 | // Check a new module hasn't been loaded |
| 316 | self.module_cache.clearRetainingCapacity(); |
| 547 | 317 | |
| 548 | | pub const Module = switch (native_os) { |
| 549 | | .macos, .ios, .watchos, .tvos, .visionos => struct { |
| 550 | | base_address: usize, |
| 551 | | vmaddr_slide: usize, |
| 552 | | mapped_memory: []align(std.heap.page_size_min) const u8, |
| 553 | | symbols: []const MachoSymbol, |
| 554 | | strings: [:0]const u8, |
| 555 | | ofiles: OFileTable, |
| 556 | | |
| 557 | | // Backed by the in-memory sections mapped by the loader |
| 558 | | unwind_info: ?[]const u8 = null, |
| 559 | | eh_frame: ?[]const u8 = null, |
| 560 | | |
| 561 | | const OFileTable = std.StringHashMap(OFileInfo); |
| 562 | | const OFileInfo = struct { |
| 563 | | di: Dwarf, |
| 564 | | addr_table: std.StringHashMap(u64), |
| 565 | | }; |
| 318 | const handle = windows.kernel32.CreateToolhelp32Snapshot(windows.TH32CS_SNAPMODULE | windows.TH32CS_SNAPMODULE32, 0); |
| 319 | if (handle == windows.INVALID_HANDLE_VALUE) { |
| 320 | return windows.unexpectedError(windows.GetLastError()); |
| 321 | } |
| 322 | defer windows.CloseHandle(handle); |
| 566 | 323 | |
| 567 | | pub fn deinit(self: *@This(), allocator: Allocator) void { |
| 568 | | var it = self.ofiles.iterator(); |
| 569 | | while (it.next()) |entry| { |
| 570 | | const ofile = entry.value_ptr; |
| 571 | | ofile.di.deinit(allocator); |
| 572 | | ofile.addr_table.deinit(); |
| 324 | var entry: windows.MODULEENTRY32 = undefined; |
| 325 | entry.dwSize = @sizeOf(windows.MODULEENTRY32); |
| 326 | if (windows.kernel32.Module32First(handle, &entry) != 0) { |
| 327 | try self.module_cache.append(gpa, entry); |
| 328 | while (windows.kernel32.Module32Next(handle, &entry) != 0) { |
| 329 | try self.module_cache.append(gpa, entry); |
| 573 | 330 | } |
| 574 | | self.ofiles.deinit(); |
| 575 | | allocator.free(self.symbols); |
| 576 | | posix.munmap(self.mapped_memory); |
| 577 | 331 | } |
| 332 | } |
| 578 | 333 | |
| 579 | | fn loadOFile(self: *@This(), allocator: Allocator, o_file_path: []const u8) !*OFileInfo { |
| 580 | | const o_file = try fs.cwd().openFile(o_file_path, .{}); |
| 581 | | const mapped_mem = try mapWholeFile(o_file); |
| 582 | | |
| 583 | | const hdr: *const macho.mach_header_64 = @ptrCast(@alignCast(mapped_mem.ptr)); |
| 584 | | if (hdr.magic != std.macho.MH_MAGIC_64) |
| 585 | | return error.InvalidDebugInfo; |
| 586 | | |
| 587 | | var segcmd: ?macho.LoadCommandIterator.LoadCommand = null; |
| 588 | | var symtabcmd: ?macho.symtab_command = null; |
| 589 | | var it = macho.LoadCommandIterator{ |
| 590 | | .ncmds = hdr.ncmds, |
| 591 | | .buffer = mapped_mem[@sizeOf(macho.mach_header_64)..][0..hdr.sizeofcmds], |
| 592 | | }; |
| 593 | | while (it.next()) |cmd| switch (cmd.cmd()) { |
| 594 | | .SEGMENT_64 => segcmd = cmd, |
| 595 | | .SYMTAB => symtabcmd = cmd.cast(macho.symtab_command).?, |
| 596 | | else => {}, |
| 334 | if (self.lookupModuleWin32Cache(address)) |m| return m; |
| 335 | return error.MissingDebugInfo; |
| 336 | } |
| 337 | fn lookupModuleWin32Cache(self: *SelfInfo, address: usize) ?Module { |
| 338 | for (self.module_cache.items) |*entry| { |
| 339 | const base_address = @intFromPtr(entry.modBaseAddr); |
| 340 | if (address >= base_address and address < base_address + entry.modBaseSize) { |
| 341 | return .{ |
| 342 | .base_address = base_address, |
| 343 | .size = entry.modBaseSize, |
| 344 | .name = std.mem.sliceTo(&entry.szModule, 0), |
| 345 | .handle = entry.hModule, |
| 597 | 346 | }; |
| 347 | } |
| 348 | } |
| 349 | return null; |
| 350 | } |
| 598 | 351 | |
| 599 | | if (segcmd == null or symtabcmd == null) return error.MissingDebugInfo; |
| 600 | | |
| 601 | | // Parse symbols |
| 602 | | const strtab = @as( |
| 603 | | [*]const u8, |
| 604 | | @ptrCast(&mapped_mem[symtabcmd.?.stroff]), |
| 605 | | )[0 .. symtabcmd.?.strsize - 1 :0]; |
| 606 | | const symtab = @as( |
| 607 | | [*]const macho.nlist_64, |
| 608 | | @ptrCast(@alignCast(&mapped_mem[symtabcmd.?.symoff])), |
| 609 | | )[0..symtabcmd.?.nsyms]; |
| 610 | | |
| 611 | | // TODO handle tentative (common) symbols |
| 612 | | var addr_table = std.StringHashMap(u64).init(allocator); |
| 613 | | try addr_table.ensureTotalCapacity(@as(u32, @intCast(symtab.len))); |
| 614 | | for (symtab) |sym| { |
| 615 | | if (sym.n_strx == 0) continue; |
| 616 | | if (sym.undf() or sym.tentative() or sym.abs()) continue; |
| 617 | | const sym_name = mem.sliceTo(strtab[sym.n_strx..], 0); |
| 618 | | // TODO is it possible to have a symbol collision? |
| 619 | | addr_table.putAssumeCapacityNoClobber(sym_name, sym.n_value); |
| 620 | | } |
| 352 | fn readCoffDebugInfo(gpa: Allocator, module: *const Module, di: *Module.DebugInfo) !void { |
| 353 | const mapped_ptr: [*]const u8 = @ptrFromInt(module.base_address); |
| 354 | const mapped = mapped_ptr[0..module.size]; |
| 355 | var coff_obj = coff.Coff.init(mapped, true) catch return error.InvalidDebugInfo; |
| 356 | // The string table is not mapped into memory by the loader, so if a section name is in the |
| 357 | // string table then we have to map the full image file from disk. This can happen when |
| 358 | // a binary is produced with -gdwarf, since the section names are longer than 8 bytes. |
| 359 | if (coff_obj.strtabRequired()) { |
| 360 | var name_buffer: [windows.PATH_MAX_WIDE + 4:0]u16 = undefined; |
| 361 | name_buffer[0..4].* = .{ '\\', '?', '?', '\\' }; // openFileAbsoluteW requires the prefix to be present |
| 362 | const process_handle = windows.GetCurrentProcess(); |
| 363 | const len = windows.kernel32.GetModuleFileNameExW( |
| 364 | process_handle, |
| 365 | module.handle, |
| 366 | name_buffer[4..], |
| 367 | windows.PATH_MAX_WIDE, |
| 368 | ); |
| 369 | if (len == 0) return error.MissingDebugInfo; |
| 370 | const coff_file = fs.openFileAbsoluteW(name_buffer[0 .. len + 4 :0], .{}) catch |err| switch (err) { |
| 371 | error.FileNotFound => return error.MissingDebugInfo, |
| 372 | else => |e| return e, |
| 373 | }; |
| 374 | errdefer coff_file.close(); |
| 375 | var section_handle: windows.HANDLE = undefined; |
| 376 | const create_section_rc = windows.ntdll.NtCreateSection( |
| 377 | &section_handle, |
| 378 | windows.STANDARD_RIGHTS_REQUIRED | windows.SECTION_QUERY | windows.SECTION_MAP_READ, |
| 379 | null, |
| 380 | null, |
| 381 | windows.PAGE_READONLY, |
| 382 | // The documentation states that if no AllocationAttribute is specified, then SEC_COMMIT is the default. |
| 383 | // In practice, this isn't the case and specifying 0 will result in INVALID_PARAMETER_6. |
| 384 | windows.SEC_COMMIT, |
| 385 | coff_file.handle, |
| 386 | ); |
| 387 | if (create_section_rc != .SUCCESS) return error.MissingDebugInfo; |
| 388 | errdefer windows.CloseHandle(section_handle); |
| 389 | var coff_len: usize = 0; |
| 390 | var section_view_ptr: [*]const u8 = undefined; |
| 391 | const map_section_rc = windows.ntdll.NtMapViewOfSection( |
| 392 | section_handle, |
| 393 | process_handle, |
| 394 | @ptrCast(&section_view_ptr), |
| 395 | null, |
| 396 | 0, |
| 397 | null, |
| 398 | &coff_len, |
| 399 | .ViewUnmap, |
| 400 | 0, |
| 401 | windows.PAGE_READONLY, |
| 402 | ); |
| 403 | if (map_section_rc != .SUCCESS) return error.MissingDebugInfo; |
| 404 | errdefer assert(windows.ntdll.NtUnmapViewOfSection(process_handle, @constCast(section_view_ptr)) == .SUCCESS); |
| 405 | const section_view = section_view_ptr[0..coff_len]; |
| 406 | coff_obj = coff.Coff.init(section_view, false) catch return error.InvalidDebugInfo; |
| 407 | di.mapped_file = .{ |
| 408 | .file = coff_file, |
| 409 | .section_handle = section_handle, |
| 410 | .section_view = section_view, |
| 411 | }; |
| 412 | } |
| 413 | di.coff_image_base = coff_obj.getImageBase(); |
| 621 | 414 | |
| 622 | | var sections: Dwarf.SectionArray = Dwarf.null_section_array; |
| 623 | | if (self.eh_frame) |eh_frame| sections[@intFromEnum(Dwarf.Section.Id.eh_frame)] = .{ |
| 624 | | .data = eh_frame, |
| 625 | | .owned = false, |
| 626 | | }; |
| 415 | if (coff_obj.getSectionByName(".debug_info")) |_| { |
| 416 | di.dwarf = .{}; |
| 627 | 417 | |
| 628 | | for (segcmd.?.getSections()) |sect| { |
| 629 | | if (!std.mem.eql(u8, "__DWARF", sect.segName())) continue; |
| 418 | inline for (@typeInfo(Dwarf.Section.Id).@"enum".fields, 0..) |section, i| { |
| 419 | di.dwarf.?.sections[i] = if (coff_obj.getSectionByName("." ++ section.name)) |section_header| blk: { |
| 420 | break :blk .{ |
| 421 | .data = try coff_obj.getSectionDataAlloc(section_header, gpa), |
| 422 | .virtual_address = section_header.virtual_address, |
| 423 | .owned = true, |
| 424 | }; |
| 425 | } else null; |
| 426 | } |
| 630 | 427 | |
| 631 | | var section_index: ?usize = null; |
| 632 | | inline for (@typeInfo(Dwarf.Section.Id).@"enum".fields, 0..) |section, i| { |
| 633 | | if (mem.eql(u8, "__" ++ section.name, sect.sectName())) section_index = i; |
| 634 | | } |
| 635 | | if (section_index == null) continue; |
| 428 | try di.dwarf.?.open(gpa, native_endian); |
| 429 | } |
| 636 | 430 | |
| 637 | | const section_bytes = try Dwarf.chopSlice(mapped_mem, sect.offset, sect.size); |
| 638 | | sections[section_index.?] = .{ |
| 639 | | .data = section_bytes, |
| 640 | | .virtual_address = @intCast(sect.addr), |
| 641 | | .owned = false, |
| 642 | | }; |
| 431 | if (try coff_obj.getPdbPath()) |raw_path| pdb: { |
| 432 | const path = blk: { |
| 433 | if (fs.path.isAbsolute(raw_path)) { |
| 434 | break :blk raw_path; |
| 435 | } else { |
| 436 | const self_dir = try fs.selfExeDirPathAlloc(gpa); |
| 437 | defer gpa.free(self_dir); |
| 438 | break :blk try fs.path.join(gpa, &.{ self_dir, raw_path }); |
| 643 | 439 | } |
| 440 | }; |
| 441 | defer if (path.ptr != raw_path.ptr) gpa.free(path); |
| 644 | 442 | |
| 645 | | const missing_debug_info = |
| 646 | | sections[@intFromEnum(Dwarf.Section.Id.debug_info)] == null or |
| 647 | | sections[@intFromEnum(Dwarf.Section.Id.debug_abbrev)] == null or |
| 648 | | sections[@intFromEnum(Dwarf.Section.Id.debug_str)] == null or |
| 649 | | sections[@intFromEnum(Dwarf.Section.Id.debug_line)] == null; |
| 650 | | if (missing_debug_info) return error.MissingDebugInfo; |
| 651 | | |
| 652 | | var di: Dwarf = .{ |
| 653 | | .endian = .little, |
| 654 | | .sections = sections, |
| 655 | | .is_macho = true, |
| 656 | | }; |
| 443 | di.pdb = Pdb.init(gpa, path) catch |err| switch (err) { |
| 444 | error.FileNotFound, error.IsDir => break :pdb, |
| 445 | else => return err, |
| 446 | }; |
| 447 | try di.pdb.?.parseInfoStream(); |
| 448 | try di.pdb.?.parseDbiStream(); |
| 657 | 449 | |
| 658 | | try Dwarf.open(&di, allocator); |
| 659 | | const info = OFileInfo{ |
| 660 | | .di = di, |
| 661 | | .addr_table = addr_table, |
| 662 | | }; |
| 450 | if (!mem.eql(u8, &coff_obj.guid, &di.pdb.?.guid) or coff_obj.age != di.pdb.?.age) |
| 451 | return error.InvalidDebugInfo; |
| 663 | 452 | |
| 664 | | // Add the debug info to the cache |
| 665 | | const result = try self.ofiles.getOrPut(o_file_path); |
| 666 | | assert(!result.found_existing); |
| 667 | | result.value_ptr.* = info; |
| 453 | di.coff_section_headers = try coff_obj.getSectionHeadersAlloc(gpa); |
| 454 | } |
| 455 | } |
| 668 | 456 | |
| 669 | | return result.value_ptr; |
| 457 | const Module = switch (native_os) { |
| 458 | else => "MLUGG TODO", // Dwarf, // TODO MLUGG: it's this on master but that's definitely broken atm... |
| 459 | .macos, .ios, .watchos, .tvos, .visionos => struct { |
| 460 | /// The runtime address where __TEXT is loaded. |
| 461 | text_base: usize, |
| 462 | load_offset: usize, |
| 463 | name: []const u8, |
| 464 | unwind_info: ?[]const u8, |
| 465 | eh_frame: ?[]const u8, |
| 466 | fn key(m: *const Module) usize { |
| 467 | return m.text_base; |
| 670 | 468 | } |
| 469 | fn getSymbolAtAddress(module: *const Module, gpa: Allocator, di: *DebugInfo, address: usize) !std.debug.Symbol { |
| 470 | const vaddr = address - module.load_offset; |
| 471 | const symbol = MachoSymbol.find(di.symbols, vaddr) orelse return .{}; // MLUGG TODO null? |
| 671 | 472 | |
| 672 | | pub fn getSymbolAtAddress(self: *@This(), allocator: Allocator, address: usize) !std.debug.Symbol { |
| 673 | | const result = try self.getOFileInfoForAddress(allocator, address); |
| 674 | | if (result.symbol == null) return .{}; |
| 473 | // offset of `address` from start of `symbol` |
| 474 | const address_symbol_offset = vaddr - symbol.addr; |
| 675 | 475 | |
| 676 | 476 | // Take the symbol name from the N_FUN STAB entry, we're going to |
| 677 | 477 | // use it if we fail to find the DWARF infos |
| 678 | | const stab_symbol = mem.sliceTo(self.strings[result.symbol.?.strx..], 0); |
| 679 | | if (result.o_file_info == null) return .{ .name = stab_symbol }; |
| 680 | | |
| 681 | | // Translate again the address, this time into an address inside the |
| 682 | | // .o file |
| 683 | | const relocated_address_o = result.o_file_info.?.addr_table.get(stab_symbol) orelse return .{ |
| 684 | | .name = "???", |
| 478 | const stab_symbol = mem.sliceTo(di.strings[symbol.strx..], 0); |
| 479 | const o_file_path = mem.sliceTo(di.strings[symbol.ofile..], 0); |
| 480 | |
| 481 | const o_file: *DebugInfo.OFile = of: { |
| 482 | const gop = try di.ofiles.getOrPut(gpa, o_file_path); |
| 483 | if (!gop.found_existing) { |
| 484 | gop.value_ptr.* = DebugInfo.loadOFile(gpa, o_file_path) catch |err| { |
| 485 | defer _ = di.ofiles.pop().?; |
| 486 | switch (err) { |
| 487 | error.FileNotFound, |
| 488 | error.MissingDebugInfo, |
| 489 | error.InvalidDebugInfo, |
| 490 | => return .{ .name = stab_symbol }, |
| 491 | else => |e| return e, |
| 492 | } |
| 493 | }; |
| 494 | } |
| 495 | break :of gop.value_ptr; |
| 685 | 496 | }; |
| 686 | 497 | |
| 687 | | const addr_off = result.relocated_address - result.symbol.?.addr; |
| 688 | | const o_file_di = &result.o_file_info.?.di; |
| 689 | | if (o_file_di.findCompileUnit(relocated_address_o)) |compile_unit| { |
| 690 | | return .{ |
| 691 | | .name = o_file_di.getSymbolName(relocated_address_o) orelse "???", |
| 692 | | .compile_unit_name = compile_unit.die.getAttrString( |
| 693 | | o_file_di, |
| 694 | | std.dwarf.AT.name, |
| 695 | | o_file_di.section(.debug_str), |
| 696 | | compile_unit.*, |
| 697 | | ) catch |err| switch (err) { |
| 698 | | error.MissingDebugInfo, error.InvalidDebugInfo => "???", |
| 699 | | }, |
| 700 | | .source_location = o_file_di.getLineNumberInfo( |
| 701 | | allocator, |
| 702 | | compile_unit, |
| 703 | | relocated_address_o + addr_off, |
| 704 | | ) catch |err| switch (err) { |
| 705 | | error.MissingDebugInfo, error.InvalidDebugInfo => null, |
| 706 | | else => return err, |
| 707 | | }, |
| 708 | | }; |
| 709 | | } else |err| switch (err) { |
| 710 | | error.MissingDebugInfo, error.InvalidDebugInfo => { |
| 711 | | return .{ .name = stab_symbol }; |
| 712 | | }, |
| 713 | | else => return err, |
| 714 | | } |
| 715 | | } |
| 498 | const symbol_ofile_vaddr = o_file.addr_table.get(stab_symbol) orelse return .{ .name = stab_symbol }; |
| 716 | 499 | |
| 717 | | pub fn getOFileInfoForAddress(self: *@This(), allocator: Allocator, address: usize) !struct { |
| 718 | | relocated_address: usize, |
| 719 | | symbol: ?*const MachoSymbol = null, |
| 720 | | o_file_info: ?*OFileInfo = null, |
| 721 | | } { |
| 722 | | // Translate the VA into an address into this object |
| 723 | | const relocated_address = address - self.vmaddr_slide; |
| 724 | | |
| 725 | | // Find the .o file where this symbol is defined |
| 726 | | const symbol = machoSearchSymbols(self.symbols, relocated_address) orelse return .{ |
| 727 | | .relocated_address = relocated_address, |
| 500 | const compile_unit = o_file.dwarf.findCompileUnit(native_endian, symbol_ofile_vaddr) catch |err| switch (err) { |
| 501 | error.MissingDebugInfo, error.InvalidDebugInfo => return .{ .name = stab_symbol }, |
| 502 | else => |e| return e, |
| 728 | 503 | }; |
| 729 | 504 | |
| 730 | | // Check if its debug infos are already in the cache |
| 731 | | const o_file_path = mem.sliceTo(self.strings[symbol.ofile..], 0); |
| 732 | | const o_file_info = self.ofiles.getPtr(o_file_path) orelse |
| 733 | | (self.loadOFile(allocator, o_file_path) catch |err| switch (err) { |
| 734 | | error.FileNotFound, |
| 735 | | error.MissingDebugInfo, |
| 736 | | error.InvalidDebugInfo, |
| 737 | | => return .{ |
| 738 | | .relocated_address = relocated_address, |
| 739 | | .symbol = symbol, |
| 740 | | }, |
| 741 | | else => return err, |
| 742 | | }); |
| 743 | | |
| 744 | 505 | return .{ |
| 745 | | .relocated_address = relocated_address, |
| 746 | | .symbol = symbol, |
| 747 | | .o_file_info = o_file_info, |
| 506 | .name = o_file.dwarf.getSymbolName(symbol_ofile_vaddr) orelse stab_symbol, |
| 507 | .compile_unit_name = compile_unit.die.getAttrString( |
| 508 | &o_file.dwarf, |
| 509 | native_endian, |
| 510 | std.dwarf.AT.name, |
| 511 | o_file.dwarf.section(.debug_str), |
| 512 | compile_unit, |
| 513 | ) catch |err| switch (err) { |
| 514 | error.MissingDebugInfo, error.InvalidDebugInfo => "???", |
| 515 | }, |
| 516 | .source_location = o_file.dwarf.getLineNumberInfo( |
| 517 | gpa, |
| 518 | native_endian, |
| 519 | compile_unit, |
| 520 | symbol_ofile_vaddr + address_symbol_offset, |
| 521 | ) catch |err| switch (err) { |
| 522 | error.MissingDebugInfo, error.InvalidDebugInfo => null, |
| 523 | else => return err, |
| 524 | }, |
| 748 | 525 | }; |
| 749 | 526 | } |
| 527 | const DebugInfo = struct { |
| 528 | // MLUGG TODO: these are duplicated state. i actually reckon they should be removed from Module, and loadMachODebugInfo should be the one discovering them! |
| 529 | mapped_memory: []align(std.heap.page_size_min) const u8, |
| 530 | symbols: []const MachoSymbol, |
| 531 | strings: [:0]const u8, |
| 532 | // MLUGG TODO: this could use an adapter to just index straight into `strings`! |
| 533 | ofiles: std.StringArrayHashMapUnmanaged(OFile), |
| 534 | |
| 535 | // Backed by the in-memory sections mapped by the loader |
| 536 | unwind_info: ?[]const u8, |
| 537 | eh_frame: ?[]const u8, |
| 538 | |
| 539 | // MLUGG TODO HACKHACK: this is awful |
| 540 | const init: DebugInfo = undefined; |
| 541 | |
| 542 | const OFile = struct { |
| 543 | dwarf: Dwarf, |
| 544 | // MLUGG TODO: this could use an adapter to just index straight into the strtab! |
| 545 | addr_table: std.StringArrayHashMapUnmanaged(u64), |
| 546 | }; |
| 750 | 547 | |
| 751 | | pub fn getDwarfInfoForAddress(self: *@This(), allocator: Allocator, address: usize) !?*Dwarf { |
| 752 | | return if ((try self.getOFileInfoForAddress(allocator, address)).o_file_info) |o_file_info| &o_file_info.di else null; |
| 753 | | } |
| 754 | | }, |
| 755 | | .uefi, .windows => struct { |
| 756 | | base_address: usize, |
| 757 | | pdb: ?Pdb, |
| 758 | | dwarf: ?Dwarf, |
| 759 | | coff_image_base: u64, |
| 760 | | |
| 761 | | /// Only used if pdb is non-null |
| 762 | | coff_section_headers: []coff.SectionHeader, |
| 763 | | |
| 764 | | pub fn deinit(self: *@This(), gpa: Allocator) void { |
| 765 | | if (self.dwarf) |*dwarf| { |
| 766 | | dwarf.deinit(gpa); |
| 767 | | } |
| 768 | | |
| 769 | | if (self.pdb) |*p| { |
| 770 | | gpa.free(p.file_reader.interface.buffer); |
| 771 | | gpa.destroy(p.file_reader); |
| 772 | | p.deinit(); |
| 773 | | gpa.free(self.coff_section_headers); |
| 548 | fn deinit(di: *DebugInfo, gpa: Allocator) void { |
| 549 | for (di.ofiles.values()) |*ofile| { |
| 550 | ofile.dwarf.deinit(gpa); |
| 551 | ofile.addr_table.deinit(gpa); |
| 552 | } |
| 553 | di.ofiles.deinit(); |
| 554 | gpa.free(di.symbols); |
| 555 | posix.munmap(di.mapped_memory); |
| 774 | 556 | } |
| 775 | 557 | |
| 776 | | self.* = undefined; |
| 777 | | } |
| 558 | fn loadOFile(gpa: Allocator, o_file_path: []const u8) !OFile { |
| 559 | const mapped_mem = try mapFileOrSelfExe(o_file_path); |
| 560 | errdefer posix.munmap(mapped_mem); |
| 778 | 561 | |
| 779 | | fn getSymbolFromPdb(self: *@This(), relocated_address: usize) !?std.debug.Symbol { |
| 780 | | var coff_section: *align(1) const coff.SectionHeader = undefined; |
| 781 | | const mod_index = for (self.pdb.?.sect_contribs) |sect_contrib| { |
| 782 | | if (sect_contrib.section > self.coff_section_headers.len) continue; |
| 783 | | // Remember that SectionContribEntry.Section is 1-based. |
| 784 | | coff_section = &self.coff_section_headers[sect_contrib.section - 1]; |
| 785 | | |
| 786 | | const vaddr_start = coff_section.virtual_address + sect_contrib.offset; |
| 787 | | const vaddr_end = vaddr_start + sect_contrib.size; |
| 788 | | if (relocated_address >= vaddr_start and relocated_address < vaddr_end) { |
| 789 | | break sect_contrib.module_index; |
| 790 | | } |
| 791 | | } else { |
| 792 | | // we have no information to add to the address |
| 793 | | return null; |
| 794 | | }; |
| 562 | if (mapped_mem.len < @sizeOf(macho.mach_header_64)) return error.InvalidDebugInfo; |
| 563 | const hdr: *const macho.mach_header_64 = @ptrCast(@alignCast(mapped_mem.ptr)); |
| 564 | if (hdr.magic != std.macho.MH_MAGIC_64) return error.InvalidDebugInfo; |
| 795 | 565 | |
| 796 | | const module = (try self.pdb.?.getModule(mod_index)) orelse |
| 797 | | return error.InvalidDebugInfo; |
| 798 | | const obj_basename = fs.path.basename(module.obj_file_name); |
| 799 | | |
| 800 | | const symbol_name = self.pdb.?.getSymbolName( |
| 801 | | module, |
| 802 | | relocated_address - coff_section.virtual_address, |
| 803 | | ) orelse "???"; |
| 804 | | const opt_line_info = try self.pdb.?.getLineNumberInfo( |
| 805 | | module, |
| 806 | | relocated_address - coff_section.virtual_address, |
| 807 | | ); |
| 566 | const seg_cmd: macho.LoadCommandIterator.LoadCommand, const symtab_cmd: macho.symtab_command = cmds: { |
| 567 | var seg_cmd: ?macho.LoadCommandIterator.LoadCommand = null; |
| 568 | var symtab_cmd: ?macho.symtab_command = null; |
| 569 | var it: macho.LoadCommandIterator = .{ |
| 570 | .ncmds = hdr.ncmds, |
| 571 | .buffer = mapped_mem[@sizeOf(macho.mach_header_64)..][0..hdr.sizeofcmds], |
| 572 | }; |
| 573 | while (it.next()) |cmd| switch (cmd.cmd()) { |
| 574 | .SEGMENT_64 => seg_cmd = cmd, |
| 575 | .SYMTAB => symtab_cmd = cmd.cast(macho.symtab_command) orelse return error.InvalidDebugInfo, |
| 576 | else => {}, |
| 577 | }; |
| 578 | break :cmds .{ |
| 579 | seg_cmd orelse return error.MissingDebugInfo, |
| 580 | symtab_cmd orelse return error.MissingDebugInfo, |
| 581 | }; |
| 582 | }; |
| 808 | 583 | |
| 809 | | return .{ |
| 810 | | .name = symbol_name, |
| 811 | | .compile_unit_name = obj_basename, |
| 812 | | .source_location = opt_line_info, |
| 813 | | }; |
| 814 | | } |
| 584 | if (mapped_mem.len < symtab_cmd.stroff + symtab_cmd.strsize) return error.InvalidDebugInfo; |
| 585 | if (mapped_mem[symtab_cmd.stroff + symtab_cmd.strsize - 1] != 0) return error.InvalidDebugInfo; |
| 586 | const strtab = mapped_mem[symtab_cmd.stroff..][0 .. symtab_cmd.strsize - 1]; |
| 587 | |
| 588 | const n_sym_bytes = symtab_cmd.nsyms * @sizeOf(macho.nlist_64); |
| 589 | if (mapped_mem.len < symtab_cmd.symoff + n_sym_bytes) return error.InvalidDebugInfo; |
| 590 | const symtab: []align(1) const macho.nlist_64 = @ptrCast(mapped_mem[symtab_cmd.symoff..][0..n_sym_bytes]); |
| 591 | |
| 592 | // TODO handle tentative (common) symbols |
| 593 | // MLUGG TODO: does initCapacity actually make sense? |
| 594 | var addr_table: std.StringArrayHashMapUnmanaged(u64) = .empty; |
| 595 | defer addr_table.deinit(gpa); |
| 596 | try addr_table.ensureUnusedCapacity(gpa, @intCast(symtab.len)); |
| 597 | for (symtab) |sym| { |
| 598 | if (sym.n_strx == 0) continue; |
| 599 | switch (sym.n_type.bits.type) { |
| 600 | .undf => continue, // includes tentative symbols |
| 601 | .abs => continue, |
| 602 | else => {}, |
| 603 | } |
| 604 | const sym_name = mem.sliceTo(strtab[sym.n_strx..], 0); |
| 605 | const gop = addr_table.getOrPutAssumeCapacity(sym_name); |
| 606 | if (gop.found_existing) return error.InvalidDebugInfo; |
| 607 | gop.value_ptr.* = sym.n_value; |
| 608 | } |
| 815 | 609 | |
| 816 | | pub fn getSymbolAtAddress(self: *@This(), allocator: Allocator, address: usize) !std.debug.Symbol { |
| 817 | | // Translate the VA into an address into this object |
| 818 | | const relocated_address = address - self.base_address; |
| 610 | var sections: Dwarf.SectionArray = @splat(null); |
| 611 | for (seg_cmd.getSections()) |sect| { |
| 612 | if (!std.mem.eql(u8, "__DWARF", sect.segName())) continue; |
| 819 | 613 | |
| 820 | | if (self.pdb != null) { |
| 821 | | if (try self.getSymbolFromPdb(relocated_address)) |symbol| return symbol; |
| 822 | | } |
| 614 | const section_index: usize = inline for (@typeInfo(Dwarf.Section.Id).@"enum".fields, 0..) |section, i| { |
| 615 | if (mem.eql(u8, "__" ++ section.name, sect.sectName())) break i; |
| 616 | } else continue; |
| 823 | 617 | |
| 824 | | if (self.dwarf) |*dwarf| { |
| 825 | | const dwarf_address = relocated_address + self.coff_image_base; |
| 826 | | return dwarf.getSymbol(allocator, dwarf_address); |
| 827 | | } |
| 618 | const section_bytes = try Dwarf.chopSlice(mapped_mem, sect.offset, sect.size); |
| 619 | sections[section_index] = .{ |
| 620 | .data = section_bytes, |
| 621 | .virtual_address = @intCast(sect.addr), |
| 622 | .owned = false, |
| 623 | }; |
| 624 | } |
| 828 | 625 | |
| 829 | | return .{}; |
| 830 | | } |
| 626 | const missing_debug_info = |
| 627 | sections[@intFromEnum(Dwarf.Section.Id.debug_info)] == null or |
| 628 | sections[@intFromEnum(Dwarf.Section.Id.debug_abbrev)] == null or |
| 629 | sections[@intFromEnum(Dwarf.Section.Id.debug_str)] == null or |
| 630 | sections[@intFromEnum(Dwarf.Section.Id.debug_line)] == null; |
| 631 | if (missing_debug_info) return error.MissingDebugInfo; |
| 831 | 632 | |
| 832 | | pub fn getDwarfInfoForAddress(self: *@This(), allocator: Allocator, address: usize) !?*Dwarf { |
| 833 | | _ = allocator; |
| 834 | | _ = address; |
| 633 | var dwarf: Dwarf = .{ .sections = sections }; |
| 634 | errdefer dwarf.deinit(gpa); |
| 635 | try dwarf.open(gpa, native_endian); |
| 835 | 636 | |
| 836 | | return switch (self.debug_data) { |
| 837 | | .dwarf => |*dwarf| dwarf, |
| 838 | | else => null, |
| 839 | | }; |
| 840 | | } |
| 637 | return .{ |
| 638 | .dwarf = dwarf, |
| 639 | .addr_table = addr_table.move(), |
| 640 | }; |
| 641 | } |
| 642 | }; |
| 841 | 643 | }, |
| 842 | | .linux, .netbsd, .freebsd, .dragonfly, .openbsd, .haiku, .solaris, .illumos => Dwarf.ElfModule, |
| 843 | 644 | .wasi, .emscripten => struct { |
| 844 | | pub fn deinit(self: *@This(), allocator: Allocator) void { |
| 845 | | _ = self; |
| 846 | | _ = allocator; |
| 847 | | } |
| 848 | | |
| 849 | | pub fn getSymbolAtAddress(self: *@This(), allocator: Allocator, address: usize) !std.debug.Symbol { |
| 850 | | _ = self; |
| 851 | | _ = allocator; |
| 852 | | _ = address; |
| 853 | | return .{}; |
| 645 | const DebugInfo = struct { |
| 646 | const init: DebugInfo = .{}; |
| 647 | fn getSymbolAtAddress(di: *DebugInfo, gpa: Allocator, base_address: usize, address: usize) !std.debug.Symbol { |
| 648 | _ = di; |
| 649 | _ = gpa; |
| 650 | _ = base_address; |
| 651 | _ = address; |
| 652 | unreachable; |
| 653 | } |
| 654 | }; |
| 655 | }, |
| 656 | .linux, .netbsd, .freebsd, .dragonfly, .openbsd, .haiku, .solaris, .illumos => struct { |
| 657 | load_offset: usize, |
| 658 | name: []const u8, |
| 659 | build_id: ?[]const u8, |
| 660 | gnu_eh_frame: ?[]const u8, |
| 661 | fn key(m: Module) usize { |
| 662 | return m.load_offset; // MLUGG TODO: is this technically valid? idk |
| 854 | 663 | } |
| 855 | | |
| 856 | | pub fn getDwarfInfoForAddress(self: *@This(), allocator: Allocator, address: usize) !?*Dwarf { |
| 857 | | _ = self; |
| 858 | | _ = allocator; |
| 859 | | _ = address; |
| 860 | | return null; |
| 664 | const DebugInfo = Dwarf.ElfModule; |
| 665 | fn getSymbolAtAddress(mod: *const Module, gpa: Allocator, di: *DebugInfo, address: usize) !std.debug.Symbol { |
| 666 | return di.getSymbolAtAddress(gpa, native_endian, mod.load_offset, address); |
| 861 | 667 | } |
| 862 | 668 | }, |
| 863 | | else => Dwarf, |
| 864 | | }; |
| 669 | .uefi, .windows => struct { |
| 670 | base_address: usize, |
| 671 | size: usize, |
| 672 | name: []const u8, |
| 673 | handle: windows.HMODULE, |
| 674 | fn key(m: Module) usize { |
| 675 | return m.base_address; |
| 676 | } |
| 677 | const DebugInfo = struct { |
| 678 | coff_image_base: u64, |
| 679 | mapped_file: ?struct { |
| 680 | file: File, |
| 681 | section_handle: windows.HANDLE, |
| 682 | section_view: []const u8, |
| 683 | fn deinit(mapped: @This()) void { |
| 684 | const process_handle = windows.GetCurrentProcess(); |
| 685 | assert(windows.ntdll.NtUnmapViewOfSection(process_handle, @constCast(mapped.section_view.ptr)) == .SUCCESS); |
| 686 | windows.CloseHandle(mapped.section_handle); |
| 687 | mapped.file.close(); |
| 688 | } |
| 689 | }, |
| 865 | 690 | |
| 866 | | /// How is this different than `Module` when the host is Windows? |
| 867 | | /// Why are both stored in the `SelfInfo` struct? |
| 868 | | /// Boy, it sure would be nice if someone added documentation comments for this |
| 869 | | /// struct explaining it. |
| 870 | | pub const WindowsModule = struct { |
| 871 | | base_address: usize, |
| 872 | | size: u32, |
| 873 | | name: []const u8, |
| 874 | | handle: windows.HMODULE, |
| 875 | | |
| 876 | | // Set when the image file needed to be mapped from disk |
| 877 | | mapped_file: ?struct { |
| 878 | | file: File, |
| 879 | | section_handle: windows.HANDLE, |
| 880 | | section_view: []const u8, |
| 881 | | |
| 882 | | pub fn deinit(self: @This()) void { |
| 883 | | const process_handle = windows.GetCurrentProcess(); |
| 884 | | assert(windows.ntdll.NtUnmapViewOfSection(process_handle, @ptrCast(@constCast(self.section_view.ptr))) == .SUCCESS); |
| 885 | | windows.CloseHandle(self.section_handle); |
| 886 | | self.file.close(); |
| 691 | dwarf: ?Dwarf, |
| 692 | |
| 693 | pdb: ?Pdb, |
| 694 | /// Populated iff `pdb != null`; otherwise `&.{}`. |
| 695 | coff_section_headers: []coff.SectionHeader, |
| 696 | |
| 697 | const init: DebugInfo = .{ |
| 698 | .coff_image_base = undefined, |
| 699 | .mapped_file = null, |
| 700 | .dwarf = null, |
| 701 | .pdb = null, |
| 702 | .coff_section_headers = &.{}, |
| 703 | }; |
| 704 | |
| 705 | fn deinit(di: *DebugInfo, gpa: Allocator) void { |
| 706 | if (di.dwarf) |*dwarf| dwarf.deinit(gpa); |
| 707 | if (di.pdb) |*pdb| pdb.deinit(); |
| 708 | gpa.free(di.coff_section_headers); |
| 709 | if (di.mapped_file) |mapped| mapped.deinit(); |
| 710 | } |
| 711 | |
| 712 | fn getSymbolFromPdb(di: *DebugInfo, relocated_address: usize) !?std.debug.Symbol { |
| 713 | var coff_section: *align(1) const coff.SectionHeader = undefined; |
| 714 | const mod_index = for (di.pdb.?.sect_contribs) |sect_contrib| { |
| 715 | if (sect_contrib.section > di.coff_section_headers.len) continue; |
| 716 | // Remember that SectionContribEntry.Section is 1-based. |
| 717 | coff_section = &di.coff_section_headers[sect_contrib.section - 1]; |
| 718 | |
| 719 | const vaddr_start = coff_section.virtual_address + sect_contrib.offset; |
| 720 | const vaddr_end = vaddr_start + sect_contrib.size; |
| 721 | if (relocated_address >= vaddr_start and relocated_address < vaddr_end) { |
| 722 | break sect_contrib.module_index; |
| 723 | } |
| 724 | } else { |
| 725 | // we have no information to add to the address |
| 726 | return null; |
| 727 | }; |
| 728 | |
| 729 | const module = (try di.pdb.?.getModule(mod_index)) orelse |
| 730 | return error.InvalidDebugInfo; |
| 731 | const obj_basename = fs.path.basename(module.obj_file_name); |
| 732 | |
| 733 | const symbol_name = di.pdb.?.getSymbolName( |
| 734 | module, |
| 735 | relocated_address - coff_section.virtual_address, |
| 736 | ) orelse "???"; |
| 737 | const opt_line_info = try di.pdb.?.getLineNumberInfo( |
| 738 | module, |
| 739 | relocated_address - coff_section.virtual_address, |
| 740 | ); |
| 741 | |
| 742 | return .{ |
| 743 | .name = symbol_name, |
| 744 | .compile_unit_name = obj_basename, |
| 745 | .source_location = opt_line_info, |
| 746 | }; |
| 747 | } |
| 748 | }; |
| 749 | |
| 750 | fn getSymbolAtAddress(mod: *const Module, gpa: Allocator, di: *DebugInfo, address: usize) !std.debug.Symbol { |
| 751 | // Translate the runtime address into a virtual address into the module |
| 752 | const vaddr = address - mod.base_address; |
| 753 | |
| 754 | if (di.pdb != null) { |
| 755 | if (try di.getSymbolFromPdb(vaddr)) |symbol| return symbol; |
| 756 | } |
| 757 | |
| 758 | if (di.dwarf) |*dwarf| { |
| 759 | const dwarf_address = vaddr + di.coff_image_base; |
| 760 | return dwarf.getSymbol(gpa, native_endian, dwarf_address); |
| 761 | } |
| 762 | |
| 763 | return error.MissingDebugInfo; |
| 887 | 764 | } |
| 888 | | } = null, |
| 765 | }, |
| 889 | 766 | }; |
| 890 | 767 | |
| 891 | | /// This takes ownership of macho_file: users of this function should not close |
| 892 | | /// it themselves, even on error. |
| 893 | | /// TODO it's weird to take ownership even on error, rework this code. |
| 894 | | fn readMachODebugInfo(allocator: Allocator, macho_file: File) !Module { |
| 895 | | const mapped_mem = try mapWholeFile(macho_file); |
| 768 | fn loadMachODebugInfo(gpa: Allocator, module: *const Module, di: *Module.DebugInfo) !void { |
| 769 | const mapped_mem = mapFileOrSelfExe(module.name) catch |err| switch (err) { |
| 770 | error.FileNotFound => return error.MissingDebugInfo, |
| 771 | error.FileTooBig => return error.InvalidDebugInfo, |
| 772 | else => |e| return e, |
| 773 | }; |
| 774 | errdefer posix.munmap(mapped_mem); |
| 896 | 775 | |
| 897 | 776 | const hdr: *const macho.mach_header_64 = @ptrCast(@alignCast(mapped_mem.ptr)); |
| 898 | 777 | if (hdr.magic != macho.MH_MAGIC_64) |
| 899 | 778 | return error.InvalidDebugInfo; |
| 900 | 779 | |
| 901 | | var it = macho.LoadCommandIterator{ |
| 902 | | .ncmds = hdr.ncmds, |
| 903 | | .buffer = mapped_mem[@sizeOf(macho.mach_header_64)..][0..hdr.sizeofcmds], |
| 780 | const symtab: macho.symtab_command = symtab: { |
| 781 | var it: macho.LoadCommandIterator = .{ |
| 782 | .ncmds = hdr.ncmds, |
| 783 | .buffer = mapped_mem[@sizeOf(macho.mach_header_64)..][0..hdr.sizeofcmds], |
| 784 | }; |
| 785 | while (it.next()) |cmd| switch (cmd.cmd()) { |
| 786 | .SYMTAB => break :symtab cmd.cast(macho.symtab_command) orelse return error.InvalidDebugInfo, |
| 787 | else => {}, |
| 788 | }; |
| 789 | return error.MissingDebugInfo; |
| 904 | 790 | }; |
| 905 | | const symtab = while (it.next()) |cmd| switch (cmd.cmd()) { |
| 906 | | .SYMTAB => break cmd.cast(macho.symtab_command).?, |
| 907 | | else => {}, |
| 908 | | } else return error.MissingDebugInfo; |
| 909 | | |
| 910 | | const syms = @as( |
| 911 | | [*]const macho.nlist_64, |
| 912 | | @ptrCast(@alignCast(&mapped_mem[symtab.symoff])), |
| 913 | | )[0..symtab.nsyms]; |
| 791 | |
| 792 | const syms_ptr: [*]align(1) const macho.nlist_64 = @ptrCast(mapped_mem[symtab.symoff..]); |
| 793 | const syms = syms_ptr[0..symtab.nsyms]; |
| 914 | 794 | const strings = mapped_mem[symtab.stroff..][0 .. symtab.strsize - 1 :0]; |
| 915 | 795 | |
| 916 | | const symbols_buf = try allocator.alloc(MachoSymbol, syms.len); |
| 796 | // MLUGG TODO: does it really make sense to initCapacity here? how many of syms are omitted? |
| 797 | var symbols: std.ArrayList(MachoSymbol) = try .initCapacity(gpa, syms.len); |
| 798 | defer symbols.deinit(gpa); |
| 917 | 799 | |
| 918 | 800 | var ofile: u32 = undefined; |
| 919 | 801 | var last_sym: MachoSymbol = undefined; |
| 920 | | var symbol_index: usize = 0; |
| 921 | 802 | var state: enum { |
| 922 | 803 | init, |
| 923 | 804 | oso_open, |
| ... | ... | @@ -929,64 +810,53 @@ fn readMachODebugInfo(allocator: Allocator, macho_file: File) !Module { |
| 929 | 810 | } = .init; |
| 930 | 811 | |
| 931 | 812 | for (syms) |*sym| { |
| 932 | | if (!sym.stab()) continue; |
| 813 | if (sym.n_type.bits.is_stab == 0) continue; |
| 933 | 814 | |
| 934 | 815 | // TODO handle globals N_GSYM, and statics N_STSYM |
| 935 | | switch (sym.n_type) { |
| 936 | | macho.N_OSO => { |
| 937 | | switch (state) { |
| 938 | | .init, .oso_close => { |
| 939 | | state = .oso_open; |
| 940 | | ofile = sym.n_strx; |
| 941 | | }, |
| 942 | | else => return error.InvalidDebugInfo, |
| 943 | | } |
| 816 | switch (sym.n_type.stab) { |
| 817 | .oso => switch (state) { |
| 818 | .init, .oso_close => { |
| 819 | state = .oso_open; |
| 820 | ofile = sym.n_strx; |
| 821 | }, |
| 822 | else => return error.InvalidDebugInfo, |
| 944 | 823 | }, |
| 945 | | macho.N_BNSYM => { |
| 946 | | switch (state) { |
| 947 | | .oso_open, .ensym => { |
| 948 | | state = .bnsym; |
| 949 | | last_sym = .{ |
| 950 | | .strx = 0, |
| 951 | | .addr = sym.n_value, |
| 952 | | .size = 0, |
| 953 | | .ofile = ofile, |
| 954 | | }; |
| 955 | | }, |
| 956 | | else => return error.InvalidDebugInfo, |
| 957 | | } |
| 824 | .bnsym => switch (state) { |
| 825 | .oso_open, .ensym => { |
| 826 | state = .bnsym; |
| 827 | last_sym = .{ |
| 828 | .strx = 0, |
| 829 | .addr = sym.n_value, |
| 830 | .size = 0, |
| 831 | .ofile = ofile, |
| 832 | }; |
| 833 | }, |
| 834 | else => return error.InvalidDebugInfo, |
| 958 | 835 | }, |
| 959 | | macho.N_FUN => { |
| 960 | | switch (state) { |
| 961 | | .bnsym => { |
| 962 | | state = .fun_strx; |
| 963 | | last_sym.strx = sym.n_strx; |
| 964 | | }, |
| 965 | | .fun_strx => { |
| 966 | | state = .fun_size; |
| 967 | | last_sym.size = @as(u32, @intCast(sym.n_value)); |
| 968 | | }, |
| 969 | | else => return error.InvalidDebugInfo, |
| 970 | | } |
| 836 | .fun => switch (state) { |
| 837 | .bnsym => { |
| 838 | state = .fun_strx; |
| 839 | last_sym.strx = sym.n_strx; |
| 840 | }, |
| 841 | .fun_strx => { |
| 842 | state = .fun_size; |
| 843 | last_sym.size = @intCast(sym.n_value); |
| 844 | }, |
| 845 | else => return error.InvalidDebugInfo, |
| 971 | 846 | }, |
| 972 | | macho.N_ENSYM => { |
| 973 | | switch (state) { |
| 974 | | .fun_size => { |
| 975 | | state = .ensym; |
| 976 | | symbols_buf[symbol_index] = last_sym; |
| 977 | | symbol_index += 1; |
| 978 | | }, |
| 979 | | else => return error.InvalidDebugInfo, |
| 980 | | } |
| 847 | .ensym => switch (state) { |
| 848 | .fun_size => { |
| 849 | state = .ensym; |
| 850 | symbols.appendAssumeCapacity(last_sym); |
| 851 | }, |
| 852 | else => return error.InvalidDebugInfo, |
| 981 | 853 | }, |
| 982 | | macho.N_SO => { |
| 983 | | switch (state) { |
| 984 | | .init, .oso_close => {}, |
| 985 | | .oso_open, .ensym => { |
| 986 | | state = .oso_close; |
| 987 | | }, |
| 988 | | else => return error.InvalidDebugInfo, |
| 989 | | } |
| 854 | .so => switch (state) { |
| 855 | .init, .oso_close => {}, |
| 856 | .oso_open, .ensym => { |
| 857 | state = .oso_close; |
| 858 | }, |
| 859 | else => return error.InvalidDebugInfo, |
| 990 | 860 | }, |
| 991 | 861 | else => {}, |
| 992 | 862 | } |
| ... | ... | @@ -998,560 +868,187 @@ fn readMachODebugInfo(allocator: Allocator, macho_file: File) !Module { |
| 998 | 868 | else => return error.InvalidDebugInfo, |
| 999 | 869 | } |
| 1000 | 870 | |
| 1001 | | const symbols = try allocator.realloc(symbols_buf, symbol_index); |
| 871 | const symbols_slice = try symbols.toOwnedSlice(gpa); |
| 872 | errdefer gpa.free(symbols_slice); |
| 1002 | 873 | |
| 1003 | 874 | // Even though lld emits symbols in ascending order, this debug code |
| 1004 | 875 | // should work for programs linked in any valid way. |
| 1005 | 876 | // This sort is so that we can binary search later. |
| 1006 | | mem.sort(MachoSymbol, symbols, {}, MachoSymbol.addressLessThan); |
| 877 | mem.sort(MachoSymbol, symbols_slice, {}, MachoSymbol.addressLessThan); |
| 1007 | 878 | |
| 1008 | | return .{ |
| 1009 | | .base_address = undefined, |
| 1010 | | .vmaddr_slide = undefined, |
| 879 | di.* = .{ |
| 880 | .unwind_info = module.unwind_info, |
| 881 | .eh_frame = module.eh_frame, |
| 1011 | 882 | .mapped_memory = mapped_mem, |
| 1012 | | .ofiles = Module.OFileTable.init(allocator), |
| 1013 | | .symbols = symbols, |
| 883 | .symbols = symbols_slice, |
| 1014 | 884 | .strings = strings, |
| 885 | .ofiles = .empty, |
| 1015 | 886 | }; |
| 1016 | 887 | } |
| 1017 | 888 | |
| 1018 | | fn readCoffDebugInfo(allocator: Allocator, coff_obj: *coff.Coff) !Module { |
| 1019 | | var di: Module = .{ |
| 1020 | | .base_address = undefined, |
| 1021 | | .coff_image_base = coff_obj.getImageBase(), |
| 1022 | | .coff_section_headers = undefined, |
| 1023 | | }; |
| 1024 | | |
| 1025 | | if (coff_obj.getSectionByName(".debug_info")) |_| { |
| 1026 | | // This coff file has embedded DWARF debug info |
| 1027 | | var sections: Dwarf.SectionArray = Dwarf.null_section_array; |
| 1028 | | errdefer for (sections) |section| if (section) |s| if (s.owned) allocator.free(s.data); |
| 1029 | | |
| 1030 | | inline for (@typeInfo(Dwarf.Section.Id).@"enum".fields, 0..) |section, i| { |
| 1031 | | sections[i] = if (coff_obj.getSectionByName("." ++ section.name)) |section_header| blk: { |
| 1032 | | break :blk .{ |
| 1033 | | .data = try coff_obj.getSectionDataAlloc(section_header, allocator), |
| 1034 | | .virtual_address = section_header.virtual_address, |
| 1035 | | .owned = true, |
| 1036 | | }; |
| 1037 | | } else null; |
| 1038 | | } |
| 1039 | | |
| 1040 | | var dwarf: Dwarf = .{ |
| 1041 | | .endian = native_endian, |
| 1042 | | .sections = sections, |
| 1043 | | .is_macho = false, |
| 1044 | | }; |
| 1045 | | |
| 1046 | | try Dwarf.open(&dwarf, allocator); |
| 1047 | | di.dwarf = dwarf; |
| 1048 | | } |
| 1049 | | |
| 1050 | | const raw_path = try coff_obj.getPdbPath() orelse return di; |
| 1051 | | const path = blk: { |
| 1052 | | if (fs.path.isAbsolute(raw_path)) { |
| 1053 | | break :blk raw_path; |
| 1054 | | } else { |
| 1055 | | const self_dir = try fs.selfExeDirPathAlloc(allocator); |
| 1056 | | defer allocator.free(self_dir); |
| 1057 | | break :blk try fs.path.join(allocator, &.{ self_dir, raw_path }); |
| 1058 | | } |
| 1059 | | }; |
| 1060 | | defer if (path.ptr != raw_path.ptr) allocator.free(path); |
| 1061 | | |
| 1062 | | di.pdb = Pdb.init(allocator, path) catch |err| switch (err) { |
| 1063 | | error.FileNotFound, error.IsDir => { |
| 1064 | | if (di.dwarf == null) return error.MissingDebugInfo; |
| 1065 | | return di; |
| 1066 | | }, |
| 1067 | | else => return err, |
| 1068 | | }; |
| 1069 | | try di.pdb.?.parseInfoStream(); |
| 1070 | | try di.pdb.?.parseDbiStream(); |
| 1071 | | |
| 1072 | | if (!mem.eql(u8, &coff_obj.guid, &di.pdb.?.guid) or coff_obj.age != di.pdb.?.age) |
| 1073 | | return error.InvalidDebugInfo; |
| 1074 | | |
| 1075 | | // Only used by the pdb path |
| 1076 | | di.coff_section_headers = try coff_obj.getSectionHeadersAlloc(allocator); |
| 1077 | | errdefer allocator.free(di.coff_section_headers); |
| 1078 | | |
| 1079 | | return di; |
| 1080 | | } |
| 1081 | | |
| 1082 | | /// Reads debug info from an ELF file, or the current binary if none in specified. |
| 1083 | | /// If the required sections aren't present but a reference to external debug info is, |
| 1084 | | /// then this this function will recurse to attempt to load the debug sections from |
| 1085 | | /// an external file. |
| 1086 | | pub fn readElfDebugInfo( |
| 1087 | | em: *Dwarf.ElfModule, |
| 1088 | | allocator: Allocator, |
| 1089 | | elf_filename: ?[]const u8, |
| 1090 | | build_id: ?[]const u8, |
| 1091 | | parent_sections: *Dwarf.SectionArray, |
| 1092 | | ) !void { |
| 1093 | | const elf_file = (if (elf_filename) |filename| blk: { |
| 1094 | | break :blk fs.cwd().openFile(filename, .{}); |
| 1095 | | } else fs.openSelfExe(.{})) catch |err| switch (err) { |
| 1096 | | error.FileNotFound => return error.MissingDebugInfo, |
| 1097 | | else => return err, |
| 1098 | | }; |
| 1099 | | |
| 1100 | | const mapped_mem = try mapWholeFile(elf_file); |
| 1101 | | return em.load( |
| 1102 | | allocator, |
| 1103 | | mapped_mem, |
| 1104 | | build_id, |
| 1105 | | null, |
| 1106 | | parent_sections, |
| 1107 | | null, |
| 1108 | | elf_filename, |
| 1109 | | ); |
| 1110 | | } |
| 1111 | | |
| 1112 | 889 | const MachoSymbol = struct { |
| 1113 | 890 | strx: u32, |
| 1114 | 891 | addr: u64, |
| 1115 | 892 | size: u32, |
| 1116 | 893 | ofile: u32, |
| 1117 | | |
| 1118 | | /// Returns the address from the macho file |
| 1119 | | fn address(self: MachoSymbol) u64 { |
| 1120 | | return self.addr; |
| 1121 | | } |
| 1122 | | |
| 1123 | 894 | fn addressLessThan(context: void, lhs: MachoSymbol, rhs: MachoSymbol) bool { |
| 1124 | 895 | _ = context; |
| 1125 | 896 | return lhs.addr < rhs.addr; |
| 1126 | 897 | } |
| 1127 | | }; |
| 1128 | | |
| 1129 | | /// Takes ownership of file, even on error. |
| 1130 | | /// TODO it's weird to take ownership even on error, rework this code. |
| 1131 | | fn mapWholeFile(file: File) ![]align(std.heap.page_size_min) const u8 { |
| 1132 | | defer file.close(); |
| 1133 | | |
| 1134 | | const file_len = math.cast(usize, try file.getEndPos()) orelse math.maxInt(usize); |
| 1135 | | const mapped_mem = try posix.mmap( |
| 1136 | | null, |
| 1137 | | file_len, |
| 1138 | | posix.PROT.READ, |
| 1139 | | .{ .TYPE = .SHARED }, |
| 1140 | | file.handle, |
| 1141 | | 0, |
| 1142 | | ); |
| 1143 | | errdefer posix.munmap(mapped_mem); |
| 1144 | | |
| 1145 | | return mapped_mem; |
| 1146 | | } |
| 1147 | | |
| 1148 | | fn machoSearchSymbols(symbols: []const MachoSymbol, address: usize) ?*const MachoSymbol { |
| 1149 | | var min: usize = 0; |
| 1150 | | var max: usize = symbols.len - 1; |
| 1151 | | while (min < max) { |
| 1152 | | const mid = min + (max - min) / 2; |
| 1153 | | const curr = &symbols[mid]; |
| 1154 | | const next = &symbols[mid + 1]; |
| 1155 | | if (address >= next.address()) { |
| 1156 | | min = mid + 1; |
| 1157 | | } else if (address < curr.address()) { |
| 1158 | | max = mid; |
| 1159 | | } else { |
| 1160 | | return curr; |
| 1161 | | } |
| 1162 | | } |
| 1163 | | |
| 1164 | | const max_sym = &symbols[symbols.len - 1]; |
| 1165 | | if (address >= max_sym.address()) |
| 1166 | | return max_sym; |
| 1167 | | |
| 1168 | | return null; |
| 1169 | | } |
| 1170 | | |
| 1171 | | test machoSearchSymbols { |
| 1172 | | const symbols = [_]MachoSymbol{ |
| 1173 | | .{ .addr = 100, .strx = undefined, .size = undefined, .ofile = undefined }, |
| 1174 | | .{ .addr = 200, .strx = undefined, .size = undefined, .ofile = undefined }, |
| 1175 | | .{ .addr = 300, .strx = undefined, .size = undefined, .ofile = undefined }, |
| 1176 | | }; |
| 1177 | | |
| 1178 | | try testing.expectEqual(null, machoSearchSymbols(&symbols, 0)); |
| 1179 | | try testing.expectEqual(null, machoSearchSymbols(&symbols, 99)); |
| 1180 | | try testing.expectEqual(&symbols[0], machoSearchSymbols(&symbols, 100).?); |
| 1181 | | try testing.expectEqual(&symbols[0], machoSearchSymbols(&symbols, 150).?); |
| 1182 | | try testing.expectEqual(&symbols[0], machoSearchSymbols(&symbols, 199).?); |
| 1183 | | |
| 1184 | | try testing.expectEqual(&symbols[1], machoSearchSymbols(&symbols, 200).?); |
| 1185 | | try testing.expectEqual(&symbols[1], machoSearchSymbols(&symbols, 250).?); |
| 1186 | | try testing.expectEqual(&symbols[1], machoSearchSymbols(&symbols, 299).?); |
| 1187 | | |
| 1188 | | try testing.expectEqual(&symbols[2], machoSearchSymbols(&symbols, 300).?); |
| 1189 | | try testing.expectEqual(&symbols[2], machoSearchSymbols(&symbols, 301).?); |
| 1190 | | try testing.expectEqual(&symbols[2], machoSearchSymbols(&symbols, 5000).?); |
| 1191 | | } |
| 1192 | | |
| 1193 | | /// Unwind a frame using MachO compact unwind info (from __unwind_info). |
| 1194 | | /// If the compact encoding can't encode a way to unwind a frame, it will |
| 1195 | | /// defer unwinding to DWARF, in which case `.eh_frame` will be used if available. |
| 1196 | | fn unwindFrameMachO( |
| 1197 | | allocator: Allocator, |
| 1198 | | base_address: usize, |
| 1199 | | context: *UnwindContext, |
| 1200 | | unwind_info: []const u8, |
| 1201 | | eh_frame: ?[]const u8, |
| 1202 | | ) !usize { |
| 1203 | | const header = std.mem.bytesAsValue( |
| 1204 | | macho.unwind_info_section_header, |
| 1205 | | unwind_info[0..@sizeOf(macho.unwind_info_section_header)], |
| 1206 | | ); |
| 1207 | | const indices = std.mem.bytesAsSlice( |
| 1208 | | macho.unwind_info_section_header_index_entry, |
| 1209 | | unwind_info[header.indexSectionOffset..][0 .. header.indexCount * @sizeOf(macho.unwind_info_section_header_index_entry)], |
| 1210 | | ); |
| 1211 | | if (indices.len == 0) return error.MissingUnwindInfo; |
| 1212 | | |
| 1213 | | const mapped_pc = context.pc - base_address; |
| 1214 | | const second_level_index = blk: { |
| 898 | /// Assumes that `symbols` is sorted in order of ascending `addr`. |
| 899 | fn find(symbols: []const MachoSymbol, address: usize) ?*const MachoSymbol { |
| 900 | if (symbols.len == 0) return null; // no potential match |
| 901 | if (address < symbols[0].addr) return null; // address is before the lowest-address symbol |
| 1215 | 902 | var left: usize = 0; |
| 1216 | | var len: usize = indices.len; |
| 1217 | | |
| 903 | var len: usize = symbols.len; |
| 1218 | 904 | while (len > 1) { |
| 1219 | 905 | const mid = left + len / 2; |
| 1220 | | const offset = indices[mid].functionOffset; |
| 1221 | | if (mapped_pc < offset) { |
| 906 | if (address < symbols[mid].addr) { |
| 1222 | 907 | len /= 2; |
| 1223 | 908 | } else { |
| 1224 | 909 | left = mid; |
| 1225 | | if (mapped_pc == offset) break; |
| 1226 | 910 | len -= len / 2; |
| 1227 | 911 | } |
| 1228 | 912 | } |
| 913 | return &symbols[left]; |
| 914 | } |
| 1229 | 915 | |
| 1230 | | // Last index is a sentinel containing the highest address as its functionOffset |
| 1231 | | if (indices[left].secondLevelPagesSectionOffset == 0) return error.MissingUnwindInfo; |
| 1232 | | break :blk &indices[left]; |
| 1233 | | }; |
| 1234 | | |
| 1235 | | const common_encodings = std.mem.bytesAsSlice( |
| 1236 | | macho.compact_unwind_encoding_t, |
| 1237 | | unwind_info[header.commonEncodingsArraySectionOffset..][0 .. header.commonEncodingsArrayCount * @sizeOf(macho.compact_unwind_encoding_t)], |
| 1238 | | ); |
| 1239 | | |
| 1240 | | const start_offset = second_level_index.secondLevelPagesSectionOffset; |
| 1241 | | const kind = std.mem.bytesAsValue( |
| 1242 | | macho.UNWIND_SECOND_LEVEL, |
| 1243 | | unwind_info[start_offset..][0..@sizeOf(macho.UNWIND_SECOND_LEVEL)], |
| 1244 | | ); |
| 1245 | | |
| 1246 | | const entry: struct { |
| 1247 | | function_offset: usize, |
| 1248 | | raw_encoding: u32, |
| 1249 | | } = switch (kind.*) { |
| 1250 | | .REGULAR => blk: { |
| 1251 | | const page_header = std.mem.bytesAsValue( |
| 1252 | | macho.unwind_info_regular_second_level_page_header, |
| 1253 | | unwind_info[start_offset..][0..@sizeOf(macho.unwind_info_regular_second_level_page_header)], |
| 1254 | | ); |
| 1255 | | |
| 1256 | | const entries = std.mem.bytesAsSlice( |
| 1257 | | macho.unwind_info_regular_second_level_entry, |
| 1258 | | unwind_info[start_offset + page_header.entryPageOffset ..][0 .. page_header.entryCount * @sizeOf(macho.unwind_info_regular_second_level_entry)], |
| 1259 | | ); |
| 1260 | | if (entries.len == 0) return error.InvalidUnwindInfo; |
| 1261 | | |
| 1262 | | var left: usize = 0; |
| 1263 | | var len: usize = entries.len; |
| 1264 | | while (len > 1) { |
| 1265 | | const mid = left + len / 2; |
| 1266 | | const offset = entries[mid].functionOffset; |
| 1267 | | if (mapped_pc < offset) { |
| 1268 | | len /= 2; |
| 1269 | | } else { |
| 1270 | | left = mid; |
| 1271 | | if (mapped_pc == offset) break; |
| 1272 | | len -= len / 2; |
| 1273 | | } |
| 1274 | | } |
| 916 | test find { |
| 917 | const symbols: []const MachoSymbol = &.{ |
| 918 | .{ .addr = 100, .strx = undefined, .size = undefined, .ofile = undefined }, |
| 919 | .{ .addr = 200, .strx = undefined, .size = undefined, .ofile = undefined }, |
| 920 | .{ .addr = 300, .strx = undefined, .size = undefined, .ofile = undefined }, |
| 921 | }; |
| 1275 | 922 | |
| 1276 | | break :blk .{ |
| 1277 | | .function_offset = entries[left].functionOffset, |
| 1278 | | .raw_encoding = entries[left].encoding, |
| 1279 | | }; |
| 1280 | | }, |
| 1281 | | .COMPRESSED => blk: { |
| 1282 | | const page_header = std.mem.bytesAsValue( |
| 1283 | | macho.unwind_info_compressed_second_level_page_header, |
| 1284 | | unwind_info[start_offset..][0..@sizeOf(macho.unwind_info_compressed_second_level_page_header)], |
| 1285 | | ); |
| 923 | try testing.expectEqual(null, find(symbols, 0)); |
| 924 | try testing.expectEqual(null, find(symbols, 99)); |
| 925 | try testing.expectEqual(&symbols[0], find(symbols, 100).?); |
| 926 | try testing.expectEqual(&symbols[0], find(symbols, 150).?); |
| 927 | try testing.expectEqual(&symbols[0], find(symbols, 199).?); |
| 1286 | 928 | |
| 1287 | | const entries = std.mem.bytesAsSlice( |
| 1288 | | macho.UnwindInfoCompressedEntry, |
| 1289 | | unwind_info[start_offset + page_header.entryPageOffset ..][0 .. page_header.entryCount * @sizeOf(macho.UnwindInfoCompressedEntry)], |
| 1290 | | ); |
| 1291 | | if (entries.len == 0) return error.InvalidUnwindInfo; |
| 929 | try testing.expectEqual(&symbols[1], find(symbols, 200).?); |
| 930 | try testing.expectEqual(&symbols[1], find(symbols, 250).?); |
| 931 | try testing.expectEqual(&symbols[1], find(symbols, 299).?); |
| 1292 | 932 | |
| 1293 | | var left: usize = 0; |
| 1294 | | var len: usize = entries.len; |
| 1295 | | while (len > 1) { |
| 1296 | | const mid = left + len / 2; |
| 1297 | | const offset = second_level_index.functionOffset + entries[mid].funcOffset; |
| 1298 | | if (mapped_pc < offset) { |
| 1299 | | len /= 2; |
| 1300 | | } else { |
| 1301 | | left = mid; |
| 1302 | | if (mapped_pc == offset) break; |
| 1303 | | len -= len / 2; |
| 1304 | | } |
| 1305 | | } |
| 933 | try testing.expectEqual(&symbols[2], find(symbols, 300).?); |
| 934 | try testing.expectEqual(&symbols[2], find(symbols, 301).?); |
| 935 | try testing.expectEqual(&symbols[2], find(symbols, 5000).?); |
| 936 | } |
| 937 | }; |
| 938 | test { |
| 939 | _ = MachoSymbol; |
| 940 | } |
| 1306 | 941 | |
| 1307 | | const entry = entries[left]; |
| 1308 | | const function_offset = second_level_index.functionOffset + entry.funcOffset; |
| 1309 | | if (entry.encodingIndex < header.commonEncodingsArrayCount) { |
| 1310 | | if (entry.encodingIndex >= common_encodings.len) return error.InvalidUnwindInfo; |
| 1311 | | break :blk .{ |
| 1312 | | .function_offset = function_offset, |
| 1313 | | .raw_encoding = common_encodings[entry.encodingIndex], |
| 1314 | | }; |
| 1315 | | } else { |
| 1316 | | const local_index = try math.sub( |
| 1317 | | u8, |
| 1318 | | entry.encodingIndex, |
| 1319 | | math.cast(u8, header.commonEncodingsArrayCount) orelse return error.InvalidUnwindInfo, |
| 1320 | | ); |
| 1321 | | const local_encodings = std.mem.bytesAsSlice( |
| 1322 | | macho.compact_unwind_encoding_t, |
| 1323 | | unwind_info[start_offset + page_header.encodingsPageOffset ..][0 .. page_header.encodingsCount * @sizeOf(macho.compact_unwind_encoding_t)], |
| 1324 | | ); |
| 1325 | | if (local_index >= local_encodings.len) return error.InvalidUnwindInfo; |
| 1326 | | break :blk .{ |
| 1327 | | .function_offset = function_offset, |
| 1328 | | .raw_encoding = local_encodings[local_index], |
| 1329 | | }; |
| 1330 | | } |
| 1331 | | }, |
| 1332 | | else => return error.InvalidUnwindInfo, |
| 1333 | | }; |
| 942 | pub const UnwindContext = struct { |
| 943 | gpa: Allocator, |
| 944 | cfa: ?usize, |
| 945 | pc: usize, |
| 946 | thread_context: *std.debug.ThreadContext, |
| 947 | reg_context: Dwarf.abi.RegisterContext, |
| 948 | vm: Dwarf.Unwind.VirtualMachine, |
| 949 | stack_machine: Dwarf.expression.StackMachine(.{ .call_frame_context = true }), |
| 1334 | 950 | |
| 1335 | | if (entry.raw_encoding == 0) return error.NoUnwindInfo; |
| 1336 | | const reg_context = Dwarf.abi.RegisterContext{ |
| 1337 | | .eh_frame = false, |
| 1338 | | .is_macho = true, |
| 1339 | | }; |
| 951 | pub fn init(gpa: Allocator, thread_context: *std.debug.ThreadContext) !UnwindContext { |
| 952 | comptime assert(supports_unwinding); |
| 1340 | 953 | |
| 1341 | | const encoding: macho.CompactUnwindEncoding = @bitCast(entry.raw_encoding); |
| 1342 | | const new_ip = switch (builtin.cpu.arch) { |
| 1343 | | .x86_64 => switch (encoding.mode.x86_64) { |
| 1344 | | .OLD => return error.UnimplementedUnwindEncoding, |
| 1345 | | .RBP_FRAME => blk: { |
| 1346 | | const regs: [5]u3 = .{ |
| 1347 | | encoding.value.x86_64.frame.reg0, |
| 1348 | | encoding.value.x86_64.frame.reg1, |
| 1349 | | encoding.value.x86_64.frame.reg2, |
| 1350 | | encoding.value.x86_64.frame.reg3, |
| 1351 | | encoding.value.x86_64.frame.reg4, |
| 1352 | | }; |
| 954 | const pc = stripInstructionPtrAuthCode( |
| 955 | (try regValueNative(thread_context, ip_reg_num, null)).*, |
| 956 | ); |
| 1353 | 957 | |
| 1354 | | const frame_offset = encoding.value.x86_64.frame.frame_offset * @sizeOf(usize); |
| 1355 | | var max_reg: usize = 0; |
| 1356 | | inline for (regs, 0..) |reg, i| { |
| 1357 | | if (reg > 0) max_reg = i; |
| 1358 | | } |
| 958 | const context_copy = try gpa.create(std.debug.ThreadContext); |
| 959 | std.debug.copyContext(thread_context, context_copy); |
| 1359 | 960 | |
| 1360 | | const fp = (try regValueNative(context.thread_context, fpRegNum(reg_context), reg_context)).*; |
| 1361 | | const new_sp = fp + 2 * @sizeOf(usize); |
| 961 | return .{ |
| 962 | .gpa = gpa, |
| 963 | .cfa = null, |
| 964 | .pc = pc, |
| 965 | .thread_context = context_copy, |
| 966 | .reg_context = undefined, |
| 967 | .vm = .{}, |
| 968 | .stack_machine = .{}, |
| 969 | }; |
| 970 | } |
| 1362 | 971 | |
| 1363 | | const ip_ptr = fp + @sizeOf(usize); |
| 1364 | | const new_ip = @as(*const usize, @ptrFromInt(ip_ptr)).*; |
| 1365 | | const new_fp = @as(*const usize, @ptrFromInt(fp)).*; |
| 972 | pub fn deinit(self: *UnwindContext) void { |
| 973 | self.vm.deinit(self.gpa); |
| 974 | self.stack_machine.deinit(self.gpa); |
| 975 | self.gpa.destroy(self.thread_context); |
| 976 | self.* = undefined; |
| 977 | } |
| 1366 | 978 | |
| 1367 | | (try regValueNative(context.thread_context, fpRegNum(reg_context), reg_context)).* = new_fp; |
| 1368 | | (try regValueNative(context.thread_context, spRegNum(reg_context), reg_context)).* = new_sp; |
| 1369 | | (try regValueNative(context.thread_context, ip_reg_num, reg_context)).* = new_ip; |
| 979 | pub fn getFp(self: *const UnwindContext) !usize { |
| 980 | return (try regValueNative(self.thread_context, fpRegNum(self.reg_context), self.reg_context)).*; |
| 981 | } |
| 1370 | 982 | |
| 1371 | | for (regs, 0..) |reg, i| { |
| 1372 | | if (reg == 0) continue; |
| 1373 | | const addr = fp - frame_offset + i * @sizeOf(usize); |
| 1374 | | const reg_number = try Dwarf.compactUnwindToDwarfRegNumber(reg); |
| 1375 | | (try regValueNative(context.thread_context, reg_number, reg_context)).* = @as(*const usize, @ptrFromInt(addr)).*; |
| 983 | /// Resolves the register rule and places the result into `out` (see regBytes) |
| 984 | pub fn resolveRegisterRule( |
| 985 | context: *UnwindContext, |
| 986 | col: Dwarf.Unwind.VirtualMachine.Column, |
| 987 | expression_context: std.debug.Dwarf.expression.Context, |
| 988 | out: []u8, |
| 989 | ) !void { |
| 990 | switch (col.rule) { |
| 991 | .default => { |
| 992 | const register = col.register orelse return error.InvalidRegister; |
| 993 | // The default type is usually undefined, but can be overriden by ABI authors. |
| 994 | // See the doc comment on `Dwarf.Unwind.VirtualMachine.RegisterRule.default`. |
| 995 | if (builtin.cpu.arch.isAARCH64() and register >= 19 and register <= 18) { |
| 996 | // Callee-saved registers are initialized as if they had the .same_value rule |
| 997 | const src = try regBytes(context.thread_context, register, context.reg_context); |
| 998 | if (src.len != out.len) return error.RegisterSizeMismatch; |
| 999 | @memcpy(out, src); |
| 1000 | return; |
| 1376 | 1001 | } |
| 1377 | | |
| 1378 | | break :blk new_ip; |
| 1002 | @memset(out, undefined); |
| 1379 | 1003 | }, |
| 1380 | | .STACK_IMMD, |
| 1381 | | .STACK_IND, |
| 1382 | | => blk: { |
| 1383 | | const sp = (try regValueNative(context.thread_context, spRegNum(reg_context), reg_context)).*; |
| 1384 | | const stack_size = if (encoding.mode.x86_64 == .STACK_IMMD) |
| 1385 | | @as(usize, encoding.value.x86_64.frameless.stack.direct.stack_size) * @sizeOf(usize) |
| 1386 | | else stack_size: { |
| 1387 | | // In .STACK_IND, the stack size is inferred from the subq instruction at the beginning of the function. |
| 1388 | | const sub_offset_addr = |
| 1389 | | base_address + |
| 1390 | | entry.function_offset + |
| 1391 | | encoding.value.x86_64.frameless.stack.indirect.sub_offset; |
| 1392 | | |
| 1393 | | // `sub_offset_addr` points to the offset of the literal within the instruction |
| 1394 | | const sub_operand = @as(*align(1) const u32, @ptrFromInt(sub_offset_addr)).*; |
| 1395 | | break :stack_size sub_operand + @sizeOf(usize) * @as(usize, encoding.value.x86_64.frameless.stack.indirect.stack_adjust); |
| 1396 | | }; |
| 1397 | | |
| 1398 | | // Decode the Lehmer-coded sequence of registers. |
| 1399 | | // For a description of the encoding see lib/libc/include/any-macos.13-any/mach-o/compact_unwind_encoding.h |
| 1400 | | |
| 1401 | | // Decode the variable-based permutation number into its digits. Each digit represents |
| 1402 | | // an index into the list of register numbers that weren't yet used in the sequence at |
| 1403 | | // the time the digit was added. |
| 1404 | | const reg_count = encoding.value.x86_64.frameless.stack_reg_count; |
| 1405 | | const ip_ptr = if (reg_count > 0) reg_blk: { |
| 1406 | | var digits: [6]u3 = undefined; |
| 1407 | | var accumulator: usize = encoding.value.x86_64.frameless.stack_reg_permutation; |
| 1408 | | var base: usize = 2; |
| 1409 | | for (0..reg_count) |i| { |
| 1410 | | const div = accumulator / base; |
| 1411 | | digits[digits.len - 1 - i] = @intCast(accumulator - base * div); |
| 1412 | | accumulator = div; |
| 1413 | | base += 1; |
| 1414 | | } |
| 1415 | | |
| 1416 | | const reg_numbers = [_]u3{ 1, 2, 3, 4, 5, 6 }; |
| 1417 | | var registers: [reg_numbers.len]u3 = undefined; |
| 1418 | | var used_indices = [_]bool{false} ** reg_numbers.len; |
| 1419 | | for (digits[digits.len - reg_count ..], 0..) |target_unused_index, i| { |
| 1420 | | var unused_count: u8 = 0; |
| 1421 | | const unused_index = for (used_indices, 0..) |used, index| { |
| 1422 | | if (!used) { |
| 1423 | | if (target_unused_index == unused_count) break index; |
| 1424 | | unused_count += 1; |
| 1425 | | } |
| 1426 | | } else unreachable; |
| 1427 | | |
| 1428 | | registers[i] = reg_numbers[unused_index]; |
| 1429 | | used_indices[unused_index] = true; |
| 1430 | | } |
| 1431 | | |
| 1432 | | var reg_addr = sp + stack_size - @sizeOf(usize) * @as(usize, reg_count + 1); |
| 1433 | | for (0..reg_count) |i| { |
| 1434 | | const reg_number = try Dwarf.compactUnwindToDwarfRegNumber(registers[i]); |
| 1435 | | (try regValueNative(context.thread_context, reg_number, reg_context)).* = @as(*const usize, @ptrFromInt(reg_addr)).*; |
| 1436 | | reg_addr += @sizeOf(usize); |
| 1437 | | } |
| 1438 | | |
| 1439 | | break :reg_blk reg_addr; |
| 1440 | | } else sp + stack_size - @sizeOf(usize); |
| 1441 | | |
| 1442 | | const new_ip = @as(*const usize, @ptrFromInt(ip_ptr)).*; |
| 1443 | | const new_sp = ip_ptr + @sizeOf(usize); |
| 1444 | | |
| 1445 | | (try regValueNative(context.thread_context, spRegNum(reg_context), reg_context)).* = new_sp; |
| 1446 | | (try regValueNative(context.thread_context, ip_reg_num, reg_context)).* = new_ip; |
| 1447 | | |
| 1448 | | break :blk new_ip; |
| 1004 | .undefined => { |
| 1005 | @memset(out, undefined); |
| 1449 | 1006 | }, |
| 1450 | | .DWARF => { |
| 1451 | | return unwindFrameMachODwarf(allocator, base_address, context, eh_frame orelse return error.MissingEhFrame, @intCast(encoding.value.x86_64.dwarf)); |
| 1007 | .same_value => { |
| 1008 | // TODO: This copy could be eliminated if callers always copy the state then call this function to update it |
| 1009 | const register = col.register orelse return error.InvalidRegister; |
| 1010 | const src = try regBytes(context.thread_context, register, context.reg_context); |
| 1011 | if (src.len != out.len) return error.RegisterSizeMismatch; |
| 1012 | @memcpy(out, src); |
| 1452 | 1013 | }, |
| 1453 | | }, |
| 1454 | | .aarch64, .aarch64_be => switch (encoding.mode.arm64) { |
| 1455 | | .OLD => return error.UnimplementedUnwindEncoding, |
| 1456 | | .FRAMELESS => blk: { |
| 1457 | | const sp = (try regValueNative(context.thread_context, spRegNum(reg_context), reg_context)).*; |
| 1458 | | const new_sp = sp + encoding.value.arm64.frameless.stack_size * 16; |
| 1459 | | const new_ip = (try regValueNative(context.thread_context, 30, reg_context)).*; |
| 1460 | | (try regValueNative(context.thread_context, spRegNum(reg_context), reg_context)).* = new_sp; |
| 1461 | | break :blk new_ip; |
| 1014 | .offset => |offset| { |
| 1015 | if (context.cfa) |cfa| { |
| 1016 | const addr = try applyOffset(cfa, offset); |
| 1017 | const ptr: *const usize = @ptrFromInt(addr); |
| 1018 | mem.writeInt(usize, out[0..@sizeOf(usize)], ptr.*, native_endian); |
| 1019 | } else return error.InvalidCFA; |
| 1462 | 1020 | }, |
| 1463 | | .DWARF => { |
| 1464 | | return unwindFrameMachODwarf(allocator, base_address, context, eh_frame orelse return error.MissingEhFrame, @intCast(encoding.value.arm64.dwarf)); |
| 1021 | .val_offset => |offset| { |
| 1022 | if (context.cfa) |cfa| { |
| 1023 | mem.writeInt(usize, out[0..@sizeOf(usize)], try applyOffset(cfa, offset), native_endian); |
| 1024 | } else return error.InvalidCFA; |
| 1465 | 1025 | }, |
| 1466 | | .FRAME => blk: { |
| 1467 | | const fp = (try regValueNative(context.thread_context, fpRegNum(reg_context), reg_context)).*; |
| 1468 | | const ip_ptr = fp + @sizeOf(usize); |
| 1469 | | |
| 1470 | | var reg_addr = fp - @sizeOf(usize); |
| 1471 | | inline for (@typeInfo(@TypeOf(encoding.value.arm64.frame.x_reg_pairs)).@"struct".fields, 0..) |field, i| { |
| 1472 | | if (@field(encoding.value.arm64.frame.x_reg_pairs, field.name) != 0) { |
| 1473 | | (try regValueNative(context.thread_context, 19 + i, reg_context)).* = @as(*const usize, @ptrFromInt(reg_addr)).*; |
| 1474 | | reg_addr += @sizeOf(usize); |
| 1475 | | (try regValueNative(context.thread_context, 20 + i, reg_context)).* = @as(*const usize, @ptrFromInt(reg_addr)).*; |
| 1476 | | reg_addr += @sizeOf(usize); |
| 1477 | | } |
| 1478 | | } |
| 1479 | | |
| 1480 | | inline for (@typeInfo(@TypeOf(encoding.value.arm64.frame.d_reg_pairs)).@"struct".fields, 0..) |field, i| { |
| 1481 | | if (@field(encoding.value.arm64.frame.d_reg_pairs, field.name) != 0) { |
| 1482 | | // Only the lower half of the 128-bit V registers are restored during unwinding |
| 1483 | | @memcpy( |
| 1484 | | try regBytes(context.thread_context, 64 + 8 + i, context.reg_context), |
| 1485 | | std.mem.asBytes(@as(*const usize, @ptrFromInt(reg_addr))), |
| 1486 | | ); |
| 1487 | | reg_addr += @sizeOf(usize); |
| 1488 | | @memcpy( |
| 1489 | | try regBytes(context.thread_context, 64 + 9 + i, context.reg_context), |
| 1490 | | std.mem.asBytes(@as(*const usize, @ptrFromInt(reg_addr))), |
| 1491 | | ); |
| 1492 | | reg_addr += @sizeOf(usize); |
| 1493 | | } |
| 1494 | | } |
| 1495 | | |
| 1496 | | const new_ip = @as(*const usize, @ptrFromInt(ip_ptr)).*; |
| 1497 | | const new_fp = @as(*const usize, @ptrFromInt(fp)).*; |
| 1498 | | |
| 1499 | | (try regValueNative(context.thread_context, fpRegNum(reg_context), reg_context)).* = new_fp; |
| 1500 | | (try regValueNative(context.thread_context, ip_reg_num, reg_context)).* = new_ip; |
| 1501 | | |
| 1502 | | break :blk new_ip; |
| 1026 | .register => |register| { |
| 1027 | const src = try regBytes(context.thread_context, register, context.reg_context); |
| 1028 | if (src.len != out.len) return error.RegisterSizeMismatch; |
| 1029 | @memcpy(out, try regBytes(context.thread_context, register, context.reg_context)); |
| 1503 | 1030 | }, |
| 1504 | | }, |
| 1505 | | else => return error.UnimplementedArch, |
| 1506 | | }; |
| 1507 | | |
| 1508 | | context.pc = stripInstructionPtrAuthCode(new_ip); |
| 1509 | | if (context.pc > 0) context.pc -= 1; |
| 1510 | | return new_ip; |
| 1511 | | } |
| 1512 | | |
| 1513 | | pub const UnwindContext = struct { |
| 1514 | | allocator: Allocator, |
| 1515 | | cfa: ?usize, |
| 1516 | | pc: usize, |
| 1517 | | thread_context: *std.debug.ThreadContext, |
| 1518 | | reg_context: Dwarf.abi.RegisterContext, |
| 1519 | | vm: VirtualMachine, |
| 1520 | | stack_machine: Dwarf.expression.StackMachine(.{ .call_frame_context = true }), |
| 1521 | | |
| 1522 | | pub fn init( |
| 1523 | | allocator: Allocator, |
| 1524 | | thread_context: *std.debug.ThreadContext, |
| 1525 | | ) !UnwindContext { |
| 1526 | | comptime assert(supports_unwinding); |
| 1527 | | |
| 1528 | | const pc = stripInstructionPtrAuthCode( |
| 1529 | | (try regValueNative(thread_context, ip_reg_num, null)).*, |
| 1530 | | ); |
| 1531 | | |
| 1532 | | const context_copy = try allocator.create(std.debug.ThreadContext); |
| 1533 | | std.debug.copyContext(thread_context, context_copy); |
| 1534 | | |
| 1535 | | return .{ |
| 1536 | | .allocator = allocator, |
| 1537 | | .cfa = null, |
| 1538 | | .pc = pc, |
| 1539 | | .thread_context = context_copy, |
| 1540 | | .reg_context = undefined, |
| 1541 | | .vm = .{}, |
| 1542 | | .stack_machine = .{}, |
| 1543 | | }; |
| 1544 | | } |
| 1545 | | |
| 1546 | | pub fn deinit(self: *UnwindContext) void { |
| 1547 | | self.vm.deinit(self.allocator); |
| 1548 | | self.stack_machine.deinit(self.allocator); |
| 1549 | | self.allocator.destroy(self.thread_context); |
| 1550 | | self.* = undefined; |
| 1551 | | } |
| 1552 | | |
| 1553 | | pub fn getFp(self: *const UnwindContext) !usize { |
| 1554 | | return (try regValueNative(self.thread_context, fpRegNum(self.reg_context), self.reg_context)).*; |
| 1031 | .expression => |expression| { |
| 1032 | context.stack_machine.reset(); |
| 1033 | const value = try context.stack_machine.run(expression, context.gpa, expression_context, context.cfa.?); |
| 1034 | const addr = if (value) |v| blk: { |
| 1035 | if (v != .generic) return error.InvalidExpressionValue; |
| 1036 | break :blk v.generic; |
| 1037 | } else return error.NoExpressionValue; |
| 1038 | |
| 1039 | const ptr: *usize = @ptrFromInt(addr); |
| 1040 | mem.writeInt(usize, out[0..@sizeOf(usize)], ptr.*, native_endian); |
| 1041 | }, |
| 1042 | .val_expression => |expression| { |
| 1043 | context.stack_machine.reset(); |
| 1044 | const value = try context.stack_machine.run(expression, context.gpa, expression_context, context.cfa.?); |
| 1045 | if (value) |v| { |
| 1046 | if (v != .generic) return error.InvalidExpressionValue; |
| 1047 | mem.writeInt(usize, out[0..@sizeOf(usize)], v.generic, native_endian); |
| 1048 | } else return error.NoExpressionValue; |
| 1049 | }, |
| 1050 | .architectural => return error.UnimplementedRegisterRule, |
| 1051 | } |
| 1555 | 1052 | } |
| 1556 | 1053 | }; |
| 1557 | 1054 | |
| ... | ... | @@ -1584,113 +1081,30 @@ pub inline fn stripInstructionPtrAuthCode(ptr: usize) usize { |
| 1584 | 1081 | /// `explicit_fde_offset` is for cases where the FDE offset is known, such as when __unwind_info |
| 1585 | 1082 | /// defers unwinding to DWARF. This is an offset into the `.eh_frame` section. |
| 1586 | 1083 | fn unwindFrameDwarf( |
| 1587 | | allocator: Allocator, |
| 1588 | | unwind: *Dwarf.Unwind, |
| 1589 | | base_address: usize, |
| 1084 | unwind: *const Dwarf.Unwind, |
| 1085 | load_offset: usize, |
| 1590 | 1086 | context: *UnwindContext, |
| 1591 | 1087 | explicit_fde_offset: ?usize, |
| 1592 | 1088 | ) !usize { |
| 1593 | 1089 | if (!supports_unwinding) return error.UnsupportedCpuArchitecture; |
| 1594 | 1090 | if (context.pc == 0) return 0; |
| 1595 | 1091 | |
| 1596 | | // Find the FDE and CIE |
| 1597 | | const cie, const fde = if (explicit_fde_offset) |fde_offset| blk: { |
| 1598 | | const frame_section = unwind.section(.eh_frame) orelse return error.MissingFDE; |
| 1599 | | if (fde_offset >= frame_section.len) return error.MissingFDE; |
| 1600 | | |
| 1601 | | var fbr: std.Io.Reader = .fixed(frame_section); |
| 1602 | | fbr.seek = fde_offset; |
| 1092 | const pc_vaddr = context.pc - load_offset; |
| 1603 | 1093 | |
| 1604 | | const fde_entry_header = try Dwarf.Unwind.EntryHeader.read(&fbr, .eh_frame, native_endian); |
| 1605 | | if (fde_entry_header.type != .fde) return error.MissingFDE; |
| 1094 | const fde_offset = explicit_fde_offset orelse try unwind.findFdeOffset( |
| 1095 | pc_vaddr, |
| 1096 | @sizeOf(usize), |
| 1097 | native_endian, |
| 1098 | ) orelse return error.MissingDebugInfo; |
| 1099 | const format, const cie, const fde = try unwind.loadFde(fde_offset, @sizeOf(usize), native_endian); |
| 1606 | 1100 | |
| 1607 | | const cie_offset = fde_entry_header.type.fde; |
| 1608 | | fbr.seek = @intCast(cie_offset); |
| 1609 | | |
| 1610 | | const cie_entry_header = try Dwarf.Unwind.EntryHeader.read(&fbr, .eh_frame, native_endian); |
| 1611 | | if (cie_entry_header.type != .cie) return Dwarf.bad(); |
| 1612 | | |
| 1613 | | const cie = try Dwarf.Unwind.CommonInformationEntry.parse( |
| 1614 | | cie_entry_header.entry_bytes, |
| 1615 | | 0, |
| 1616 | | true, |
| 1617 | | cie_entry_header.format, |
| 1618 | | .eh_frame, |
| 1619 | | cie_entry_header.length_offset, |
| 1620 | | @sizeOf(usize), |
| 1621 | | native_endian, |
| 1622 | | ); |
| 1623 | | const fde = try Dwarf.Unwind.FrameDescriptionEntry.parse( |
| 1624 | | fde_entry_header.entry_bytes, |
| 1625 | | 0, |
| 1626 | | true, |
| 1627 | | cie, |
| 1628 | | @sizeOf(usize), |
| 1629 | | native_endian, |
| 1630 | | ); |
| 1631 | | |
| 1632 | | break :blk .{ cie, fde }; |
| 1633 | | } else blk: { |
| 1634 | | // `.eh_frame_hdr` may be incomplete. We'll try it first, but if the lookup fails, we fall |
| 1635 | | // back to loading `.eh_frame`/`.debug_frame` and using those from that point on. |
| 1636 | | |
| 1637 | | if (unwind.eh_frame_hdr) |header| hdr: { |
| 1638 | | const eh_frame_len = if (unwind.section(.eh_frame)) |eh_frame| eh_frame.len else { |
| 1639 | | try unwind.scanCieFdeInfo(allocator, native_endian, base_address); |
| 1640 | | unwind.eh_frame_hdr = null; |
| 1641 | | break :hdr; |
| 1642 | | }; |
| 1643 | | |
| 1644 | | var cie: Dwarf.Unwind.CommonInformationEntry = undefined; |
| 1645 | | var fde: Dwarf.Unwind.FrameDescriptionEntry = undefined; |
| 1646 | | |
| 1647 | | header.findEntry( |
| 1648 | | eh_frame_len, |
| 1649 | | @intFromPtr(unwind.section(.eh_frame_hdr).?.ptr), |
| 1650 | | context.pc, |
| 1651 | | &cie, |
| 1652 | | &fde, |
| 1653 | | native_endian, |
| 1654 | | ) catch |err| switch (err) { |
| 1655 | | error.MissingDebugInfo => { |
| 1656 | | // `.eh_frame_hdr` appears to be incomplete, so go ahead and populate `cie_map` |
| 1657 | | // and `fde_list`, and fall back to the binary search logic below. |
| 1658 | | try unwind.scanCieFdeInfo(allocator, native_endian, base_address); |
| 1659 | | |
| 1660 | | // Since `.eh_frame_hdr` is incomplete, we're very likely to get more lookup |
| 1661 | | // failures using it, and we've just built a complete, sorted list of FDEs |
| 1662 | | // anyway, so just stop using `.eh_frame_hdr` altogether. |
| 1663 | | unwind.eh_frame_hdr = null; |
| 1664 | | |
| 1665 | | break :hdr; |
| 1666 | | }, |
| 1667 | | else => return err, |
| 1668 | | }; |
| 1669 | | |
| 1670 | | break :blk .{ cie, fde }; |
| 1671 | | } |
| 1672 | | |
| 1673 | | const index = std.sort.binarySearch(Dwarf.Unwind.FrameDescriptionEntry, unwind.fde_list.items, context.pc, struct { |
| 1674 | | pub fn compareFn(pc: usize, item: Dwarf.Unwind.FrameDescriptionEntry) std.math.Order { |
| 1675 | | if (pc < item.pc_begin) return .lt; |
| 1676 | | |
| 1677 | | const range_end = item.pc_begin + item.pc_range; |
| 1678 | | if (pc < range_end) return .eq; |
| 1679 | | |
| 1680 | | return .gt; |
| 1681 | | } |
| 1682 | | }.compareFn); |
| 1683 | | |
| 1684 | | const fde = if (index) |i| unwind.fde_list.items[i] else return error.MissingFDE; |
| 1685 | | const cie = unwind.cie_map.get(fde.cie_length_offset) orelse return error.MissingCIE; |
| 1686 | | |
| 1687 | | break :blk .{ cie, fde }; |
| 1688 | | }; |
| 1101 | // Check if this FDE *actually* includes the address. |
| 1102 | if (pc_vaddr < fde.pc_begin or pc_vaddr >= fde.pc_begin + fde.pc_range) return error.MissingDebugInfo; |
| 1689 | 1103 | |
| 1690 | 1104 | // Do not set `compile_unit` because the spec states that CFIs |
| 1691 | 1105 | // may not reference other debug sections anyway. |
| 1692 | 1106 | var expression_context: Dwarf.expression.Context = .{ |
| 1693 | | .format = cie.format, |
| 1107 | .format = format, |
| 1694 | 1108 | .thread_context = context.thread_context, |
| 1695 | 1109 | .reg_context = context.reg_context, |
| 1696 | 1110 | .cfa = context.cfa, |
| ... | ... | @@ -1700,7 +1114,7 @@ fn unwindFrameDwarf( |
| 1700 | 1114 | context.reg_context.eh_frame = cie.version != 4; |
| 1701 | 1115 | context.reg_context.is_macho = native_os.isDarwin(); |
| 1702 | 1116 | |
| 1703 | | const row = try context.vm.runToNative(context.allocator, context.pc, cie, fde); |
| 1117 | const row = try context.vm.runTo(context.gpa, context.pc - load_offset, cie, fde, @sizeOf(usize), native_endian); |
| 1704 | 1118 | context.cfa = switch (row.cfa.rule) { |
| 1705 | 1119 | .val_offset => |offset| blk: { |
| 1706 | 1120 | const register = row.cfa.register orelse return error.InvalidCFARule; |
| ... | ... | @@ -1711,7 +1125,7 @@ fn unwindFrameDwarf( |
| 1711 | 1125 | context.stack_machine.reset(); |
| 1712 | 1126 | const value = try context.stack_machine.run( |
| 1713 | 1127 | expr, |
| 1714 | | context.allocator, |
| 1128 | context.gpa, |
| 1715 | 1129 | expression_context, |
| 1716 | 1130 | context.cfa, |
| 1717 | 1131 | ); |
| ... | ... | @@ -1728,9 +1142,9 @@ fn unwindFrameDwarf( |
| 1728 | 1142 | |
| 1729 | 1143 | // Buffering the modifications is done because copying the thread context is not portable, |
| 1730 | 1144 | // some implementations (ie. darwin) use internal pointers to the mcontext. |
| 1731 | | var arena = std.heap.ArenaAllocator.init(context.allocator); |
| 1145 | var arena: std.heap.ArenaAllocator = .init(context.gpa); |
| 1732 | 1146 | defer arena.deinit(); |
| 1733 | | const update_allocator = arena.allocator(); |
| 1147 | const update_arena = arena.allocator(); |
| 1734 | 1148 | |
| 1735 | 1149 | const RegisterUpdate = struct { |
| 1736 | 1150 | // Backed by thread_context |
| ... | ... | @@ -1749,17 +1163,16 @@ fn unwindFrameDwarf( |
| 1749 | 1163 | } |
| 1750 | 1164 | |
| 1751 | 1165 | const dest = try regBytes(context.thread_context, register, context.reg_context); |
| 1752 | | const src = try update_allocator.alloc(u8, dest.len); |
| 1166 | const src = try update_arena.alloc(u8, dest.len); |
| 1167 | try context.resolveRegisterRule(column, expression_context, src); |
| 1753 | 1168 | |
| 1754 | | const prev = update_tail; |
| 1755 | | update_tail = try update_allocator.create(RegisterUpdate); |
| 1756 | | update_tail.?.* = .{ |
| 1169 | const new_update = try update_arena.create(RegisterUpdate); |
| 1170 | new_update.* = .{ |
| 1757 | 1171 | .dest = dest, |
| 1758 | 1172 | .src = src, |
| 1759 | | .prev = prev, |
| 1173 | .prev = update_tail, |
| 1760 | 1174 | }; |
| 1761 | | |
| 1762 | | try column.resolveValue(context, expression_context, src); |
| 1175 | update_tail = new_update; |
| 1763 | 1176 | } |
| 1764 | 1177 | } |
| 1765 | 1178 | |
| ... | ... | @@ -1792,7 +1205,7 @@ fn unwindFrameDwarf( |
| 1792 | 1205 | // The exception to this rule is signal frames, where we return execution would be returned to the instruction |
| 1793 | 1206 | // that triggered the handler. |
| 1794 | 1207 | const return_address = context.pc; |
| 1795 | | if (context.pc > 0 and !cie.isSignalFrame()) context.pc -= 1; |
| 1208 | if (context.pc > 0 and !cie.is_signal_frame) context.pc -= 1; |
| 1796 | 1209 | |
| 1797 | 1210 | return return_address; |
| 1798 | 1211 | } |
| ... | ... | @@ -1843,415 +1256,345 @@ pub fn supportsUnwinding(target: *const std.Target) bool { |
| 1843 | 1256 | }; |
| 1844 | 1257 | } |
| 1845 | 1258 | |
| 1846 | | fn unwindFrameMachODwarf( |
| 1847 | | allocator: Allocator, |
| 1848 | | base_address: usize, |
| 1849 | | context: *UnwindContext, |
| 1850 | | eh_frame: []const u8, |
| 1851 | | fde_offset: usize, |
| 1852 | | ) !usize { |
| 1853 | | var di: Dwarf = .{ |
| 1854 | | .endian = native_endian, |
| 1855 | | .is_macho = true, |
| 1856 | | }; |
| 1857 | | defer di.deinit(context.allocator); |
| 1259 | /// Since register rules are applied (usually) during a panic, |
| 1260 | /// checked addition / subtraction is used so that we can return |
| 1261 | /// an error and fall back to FP-based unwinding. |
| 1262 | fn applyOffset(base: usize, offset: i64) !usize { |
| 1263 | return if (offset >= 0) |
| 1264 | try std.math.add(usize, base, @as(usize, @intCast(offset))) |
| 1265 | else |
| 1266 | try std.math.sub(usize, base, @as(usize, @intCast(-offset))); |
| 1267 | } |
| 1858 | 1268 | |
| 1859 | | di.sections[@intFromEnum(Dwarf.Section.Id.eh_frame)] = .{ |
| 1860 | | .data = eh_frame, |
| 1861 | | .owned = false, |
| 1862 | | }; |
| 1269 | /// Uses `mmap` to map the file at `opt_path` (or, if `null`, the self executable image) into memory. |
| 1270 | fn mapFileOrSelfExe(opt_path: ?[]const u8) ![]align(std.heap.page_size_min) const u8 { |
| 1271 | const file = if (opt_path) |path| |
| 1272 | try fs.cwd().openFile(path, .{}) |
| 1273 | else |
| 1274 | try fs.openSelfExe(.{}); |
| 1275 | defer file.close(); |
| 1863 | 1276 | |
| 1864 | | return unwindFrameDwarf(allocator, &di, base_address, context, fde_offset); |
| 1277 | const file_len = math.cast(usize, try file.getEndPos()) orelse return error.FileTooBig; |
| 1278 | |
| 1279 | return posix.mmap( |
| 1280 | null, |
| 1281 | file_len, |
| 1282 | posix.PROT.READ, |
| 1283 | .{ .TYPE = .SHARED }, |
| 1284 | file.handle, |
| 1285 | 0, |
| 1286 | ); |
| 1865 | 1287 | } |
| 1866 | 1288 | |
| 1867 | | /// This is a virtual machine that runs DWARF call frame instructions. |
| 1868 | | pub const VirtualMachine = struct { |
| 1869 | | /// See section 6.4.1 of the DWARF5 specification for details on each |
| 1870 | | const RegisterRule = union(enum) { |
| 1871 | | // The spec says that the default rule for each column is the undefined rule. |
| 1872 | | // However, it also allows ABI / compiler authors to specify alternate defaults, so |
| 1873 | | // there is a distinction made here. |
| 1874 | | default: void, |
| 1875 | | undefined: void, |
| 1876 | | same_value: void, |
| 1877 | | // offset(N) |
| 1878 | | offset: i64, |
| 1879 | | // val_offset(N) |
| 1880 | | val_offset: i64, |
| 1881 | | // register(R) |
| 1882 | | register: u8, |
| 1883 | | // expression(E) |
| 1884 | | expression: []const u8, |
| 1885 | | // val_expression(E) |
| 1886 | | val_expression: []const u8, |
| 1887 | | // Augmenter-defined rule |
| 1888 | | architectural: void, |
| 1889 | | }; |
| 1289 | /// Unwind a frame using MachO compact unwind info (from __unwind_info). |
| 1290 | /// If the compact encoding can't encode a way to unwind a frame, it will |
| 1291 | /// defer unwinding to DWARF, in which case `.eh_frame` will be used if available. |
| 1292 | fn unwindFrameMachO( |
| 1293 | text_base: usize, |
| 1294 | load_offset: usize, |
| 1295 | context: *UnwindContext, |
| 1296 | unwind_info: []const u8, |
| 1297 | eh_frame: ?[]const u8, |
| 1298 | ) !usize { |
| 1299 | if (unwind_info.len < @sizeOf(macho.unwind_info_section_header)) return error.InvalidUnwindInfo; |
| 1300 | const header: *align(1) const macho.unwind_info_section_header = @ptrCast(unwind_info); |
| 1890 | 1301 | |
| 1891 | | /// Each row contains unwinding rules for a set of registers. |
| 1892 | | pub const Row = struct { |
| 1893 | | /// Offset from `FrameDescriptionEntry.pc_begin` |
| 1894 | | offset: u64 = 0, |
| 1895 | | /// Special-case column that defines the CFA (Canonical Frame Address) rule. |
| 1896 | | /// The register field of this column defines the register that CFA is derived from. |
| 1897 | | cfa: Column = .{}, |
| 1898 | | /// The register fields in these columns define the register the rule applies to. |
| 1899 | | columns: ColumnRange = .{}, |
| 1900 | | /// Indicates that the next write to any column in this row needs to copy |
| 1901 | | /// the backing column storage first, as it may be referenced by previous rows. |
| 1902 | | copy_on_write: bool = false, |
| 1903 | | }; |
| 1302 | const index_byte_count = header.indexCount * @sizeOf(macho.unwind_info_section_header_index_entry); |
| 1303 | if (unwind_info.len < header.indexSectionOffset + index_byte_count) return error.InvalidUnwindInfo; |
| 1304 | const indices: []align(1) const macho.unwind_info_section_header_index_entry = @ptrCast(unwind_info[header.indexSectionOffset..][0..index_byte_count]); |
| 1305 | if (indices.len == 0) return error.MissingUnwindInfo; |
| 1904 | 1306 | |
| 1905 | | pub const Column = struct { |
| 1906 | | register: ?u8 = null, |
| 1907 | | rule: RegisterRule = .{ .default = {} }, |
| 1908 | | |
| 1909 | | /// Resolves the register rule and places the result into `out` (see regBytes) |
| 1910 | | pub fn resolveValue( |
| 1911 | | self: Column, |
| 1912 | | context: *SelfInfo.UnwindContext, |
| 1913 | | expression_context: std.debug.Dwarf.expression.Context, |
| 1914 | | out: []u8, |
| 1915 | | ) !void { |
| 1916 | | switch (self.rule) { |
| 1917 | | .default => { |
| 1918 | | const register = self.register orelse return error.InvalidRegister; |
| 1919 | | try getRegDefaultValue(register, context, out); |
| 1920 | | }, |
| 1921 | | .undefined => { |
| 1922 | | @memset(out, undefined); |
| 1923 | | }, |
| 1924 | | .same_value => { |
| 1925 | | // TODO: This copy could be eliminated if callers always copy the state then call this function to update it |
| 1926 | | const register = self.register orelse return error.InvalidRegister; |
| 1927 | | const src = try regBytes(context.thread_context, register, context.reg_context); |
| 1928 | | if (src.len != out.len) return error.RegisterSizeMismatch; |
| 1929 | | @memcpy(out, src); |
| 1930 | | }, |
| 1931 | | .offset => |offset| { |
| 1932 | | if (context.cfa) |cfa| { |
| 1933 | | const addr = try applyOffset(cfa, offset); |
| 1934 | | const ptr: *const usize = @ptrFromInt(addr); |
| 1935 | | mem.writeInt(usize, out[0..@sizeOf(usize)], ptr.*, native_endian); |
| 1936 | | } else return error.InvalidCFA; |
| 1937 | | }, |
| 1938 | | .val_offset => |offset| { |
| 1939 | | if (context.cfa) |cfa| { |
| 1940 | | mem.writeInt(usize, out[0..@sizeOf(usize)], try applyOffset(cfa, offset), native_endian); |
| 1941 | | } else return error.InvalidCFA; |
| 1942 | | }, |
| 1943 | | .register => |register| { |
| 1944 | | const src = try regBytes(context.thread_context, register, context.reg_context); |
| 1945 | | if (src.len != out.len) return error.RegisterSizeMismatch; |
| 1946 | | @memcpy(out, try regBytes(context.thread_context, register, context.reg_context)); |
| 1947 | | }, |
| 1948 | | .expression => |expression| { |
| 1949 | | context.stack_machine.reset(); |
| 1950 | | const value = try context.stack_machine.run(expression, context.allocator, expression_context, context.cfa.?); |
| 1951 | | const addr = if (value) |v| blk: { |
| 1952 | | if (v != .generic) return error.InvalidExpressionValue; |
| 1953 | | break :blk v.generic; |
| 1954 | | } else return error.NoExpressionValue; |
| 1955 | | |
| 1956 | | const ptr: *usize = @ptrFromInt(addr); |
| 1957 | | mem.writeInt(usize, out[0..@sizeOf(usize)], ptr.*, native_endian); |
| 1958 | | }, |
| 1959 | | .val_expression => |expression| { |
| 1960 | | context.stack_machine.reset(); |
| 1961 | | const value = try context.stack_machine.run(expression, context.allocator, expression_context, context.cfa.?); |
| 1962 | | if (value) |v| { |
| 1963 | | if (v != .generic) return error.InvalidExpressionValue; |
| 1964 | | mem.writeInt(usize, out[0..@sizeOf(usize)], v.generic, native_endian); |
| 1965 | | } else return error.NoExpressionValue; |
| 1966 | | }, |
| 1967 | | .architectural => return error.UnimplementedRegisterRule, |
| 1307 | // MLUGG TODO HACKHACK -- Unwind needs a slight refactor to make this work well |
| 1308 | const opt_dwarf_unwind: ?Dwarf.Unwind = if (eh_frame) |eh_frame_data| .{ |
| 1309 | .debug_frame = null, |
| 1310 | .eh_frame = .{ |
| 1311 | .header = .{ |
| 1312 | .vaddr = undefined, |
| 1313 | .eh_frame_vaddr = @intFromPtr(eh_frame_data.ptr) - load_offset, |
| 1314 | .search_table = null, |
| 1315 | }, |
| 1316 | .eh_frame_data = eh_frame_data, |
| 1317 | .sorted_fdes = null, |
| 1318 | }, |
| 1319 | } else null; |
| 1320 | |
| 1321 | // offset of the PC into the `__TEXT` segment |
| 1322 | const pc_text_offset = context.pc - text_base; |
| 1323 | |
| 1324 | const start_offset: u32, const first_level_offset: u32 = index: { |
| 1325 | var left: usize = 0; |
| 1326 | var len: usize = indices.len; |
| 1327 | while (len > 1) { |
| 1328 | const mid = left + len / 2; |
| 1329 | if (pc_text_offset < indices[mid].functionOffset) { |
| 1330 | len /= 2; |
| 1331 | } else { |
| 1332 | left = mid; |
| 1333 | len -= len / 2; |
| 1968 | 1334 | } |
| 1969 | 1335 | } |
| 1336 | break :index .{ indices[left].secondLevelPagesSectionOffset, indices[left].functionOffset }; |
| 1970 | 1337 | }; |
| 1338 | // An offset of 0 is a sentinel indicating a range does not have unwind info. |
| 1339 | if (start_offset == 0) return error.MissingUnwindInfo; |
| 1971 | 1340 | |
| 1972 | | const ColumnRange = struct { |
| 1973 | | /// Index into `columns` of the first column in this row. |
| 1974 | | start: usize = undefined, |
| 1975 | | len: u8 = 0, |
| 1976 | | }; |
| 1341 | const common_encodings_byte_count = header.commonEncodingsArrayCount * @sizeOf(macho.compact_unwind_encoding_t); |
| 1342 | if (unwind_info.len < header.commonEncodingsArraySectionOffset + common_encodings_byte_count) return error.InvalidUnwindInfo; |
| 1343 | const common_encodings: []align(1) const macho.compact_unwind_encoding_t = @ptrCast( |
| 1344 | unwind_info[header.commonEncodingsArraySectionOffset..][0..common_encodings_byte_count], |
| 1345 | ); |
| 1977 | 1346 | |
| 1978 | | columns: std.ArrayListUnmanaged(Column) = .empty, |
| 1979 | | stack: std.ArrayListUnmanaged(ColumnRange) = .empty, |
| 1980 | | current_row: Row = .{}, |
| 1347 | if (unwind_info.len < start_offset + @sizeOf(macho.UNWIND_SECOND_LEVEL)) return error.InvalidUnwindInfo; |
| 1348 | const kind: *align(1) const macho.UNWIND_SECOND_LEVEL = @ptrCast(unwind_info[start_offset..]); |
| 1981 | 1349 | |
| 1982 | | /// The result of executing the CIE's initial_instructions |
| 1983 | | cie_row: ?Row = null, |
| 1350 | const entry: struct { |
| 1351 | function_offset: usize, |
| 1352 | raw_encoding: u32, |
| 1353 | } = switch (kind.*) { |
| 1354 | .REGULAR => entry: { |
| 1355 | if (unwind_info.len < start_offset + @sizeOf(macho.unwind_info_regular_second_level_page_header)) return error.InvalidUnwindInfo; |
| 1356 | const page_header: *align(1) const macho.unwind_info_regular_second_level_page_header = @ptrCast(unwind_info[start_offset..]); |
| 1357 | |
| 1358 | const entries_byte_count = page_header.entryCount * @sizeOf(macho.unwind_info_regular_second_level_entry); |
| 1359 | if (unwind_info.len < start_offset + entries_byte_count) return error.InvalidUnwindInfo; |
| 1360 | const entries: []align(1) const macho.unwind_info_regular_second_level_entry = @ptrCast( |
| 1361 | unwind_info[start_offset + page_header.entryPageOffset ..][0..entries_byte_count], |
| 1362 | ); |
| 1363 | if (entries.len == 0) return error.InvalidUnwindInfo; |
| 1984 | 1364 | |
| 1985 | | pub fn deinit(self: *VirtualMachine, allocator: std.mem.Allocator) void { |
| 1986 | | self.stack.deinit(allocator); |
| 1987 | | self.columns.deinit(allocator); |
| 1988 | | self.* = undefined; |
| 1989 | | } |
| 1365 | var left: usize = 0; |
| 1366 | var len: usize = entries.len; |
| 1367 | while (len > 1) { |
| 1368 | const mid = left + len / 2; |
| 1369 | if (pc_text_offset < entries[mid].functionOffset) { |
| 1370 | len /= 2; |
| 1371 | } else { |
| 1372 | left = mid; |
| 1373 | len -= len / 2; |
| 1374 | } |
| 1375 | } |
| 1376 | break :entry .{ |
| 1377 | .function_offset = entries[left].functionOffset, |
| 1378 | .raw_encoding = entries[left].encoding, |
| 1379 | }; |
| 1380 | }, |
| 1381 | .COMPRESSED => entry: { |
| 1382 | if (unwind_info.len < start_offset + @sizeOf(macho.unwind_info_compressed_second_level_page_header)) return error.InvalidUnwindInfo; |
| 1383 | const page_header: *align(1) const macho.unwind_info_compressed_second_level_page_header = @ptrCast(unwind_info[start_offset..]); |
| 1384 | |
| 1385 | const entries_byte_count = page_header.entryCount * @sizeOf(macho.UnwindInfoCompressedEntry); |
| 1386 | if (unwind_info.len < start_offset + entries_byte_count) return error.InvalidUnwindInfo; |
| 1387 | const entries: []align(1) const macho.UnwindInfoCompressedEntry = @ptrCast( |
| 1388 | unwind_info[start_offset + page_header.entryPageOffset ..][0..entries_byte_count], |
| 1389 | ); |
| 1390 | if (entries.len == 0) return error.InvalidUnwindInfo; |
| 1990 | 1391 | |
| 1991 | | pub fn reset(self: *VirtualMachine) void { |
| 1992 | | self.stack.clearRetainingCapacity(); |
| 1993 | | self.columns.clearRetainingCapacity(); |
| 1994 | | self.current_row = .{}; |
| 1995 | | self.cie_row = null; |
| 1996 | | } |
| 1392 | var left: usize = 0; |
| 1393 | var len: usize = entries.len; |
| 1394 | while (len > 1) { |
| 1395 | const mid = left + len / 2; |
| 1396 | if (pc_text_offset < first_level_offset + entries[mid].funcOffset) { |
| 1397 | len /= 2; |
| 1398 | } else { |
| 1399 | left = mid; |
| 1400 | len -= len / 2; |
| 1401 | } |
| 1402 | } |
| 1403 | const entry = entries[left]; |
| 1997 | 1404 | |
| 1998 | | /// Return a slice backed by the row's non-CFA columns |
| 1999 | | pub fn rowColumns(self: VirtualMachine, row: Row) []Column { |
| 2000 | | if (row.columns.len == 0) return &.{}; |
| 2001 | | return self.columns.items[row.columns.start..][0..row.columns.len]; |
| 2002 | | } |
| 1405 | const function_offset = first_level_offset + entry.funcOffset; |
| 1406 | if (entry.encodingIndex < common_encodings.len) { |
| 1407 | break :entry .{ |
| 1408 | .function_offset = function_offset, |
| 1409 | .raw_encoding = common_encodings[entry.encodingIndex], |
| 1410 | }; |
| 1411 | } |
| 2003 | 1412 | |
| 2004 | | /// Either retrieves or adds a column for `register` (non-CFA) in the current row. |
| 2005 | | fn getOrAddColumn(self: *VirtualMachine, allocator: std.mem.Allocator, register: u8) !*Column { |
| 2006 | | for (self.rowColumns(self.current_row)) |*c| { |
| 2007 | | if (c.register == register) return c; |
| 2008 | | } |
| 1413 | const local_index = entry.encodingIndex - common_encodings.len; |
| 1414 | const local_encodings_byte_count = page_header.encodingsCount * @sizeOf(macho.compact_unwind_encoding_t); |
| 1415 | if (unwind_info.len < start_offset + page_header.encodingsPageOffset + local_encodings_byte_count) return error.InvalidUnwindInfo; |
| 1416 | const local_encodings: []align(1) const macho.compact_unwind_encoding_t = @ptrCast( |
| 1417 | unwind_info[start_offset + page_header.encodingsPageOffset ..][0..local_encodings_byte_count], |
| 1418 | ); |
| 1419 | if (local_index >= local_encodings.len) return error.InvalidUnwindInfo; |
| 1420 | break :entry .{ |
| 1421 | .function_offset = function_offset, |
| 1422 | .raw_encoding = local_encodings[local_index], |
| 1423 | }; |
| 1424 | }, |
| 1425 | else => return error.InvalidUnwindInfo, |
| 1426 | }; |
| 2009 | 1427 | |
| 2010 | | if (self.current_row.columns.len == 0) { |
| 2011 | | self.current_row.columns.start = self.columns.items.len; |
| 2012 | | } |
| 2013 | | self.current_row.columns.len += 1; |
| 1428 | if (entry.raw_encoding == 0) return error.NoUnwindInfo; |
| 1429 | const reg_context: Dwarf.abi.RegisterContext = .{ .eh_frame = false, .is_macho = true }; |
| 2014 | 1430 | |
| 2015 | | const column = try self.columns.addOne(allocator); |
| 2016 | | column.* = .{ |
| 2017 | | .register = register, |
| 2018 | | }; |
| 1431 | const encoding: macho.CompactUnwindEncoding = @bitCast(entry.raw_encoding); |
| 1432 | const new_ip = switch (builtin.cpu.arch) { |
| 1433 | .x86_64 => switch (encoding.mode.x86_64) { |
| 1434 | .OLD => return error.UnimplementedUnwindEncoding, |
| 1435 | .RBP_FRAME => ip: { |
| 1436 | const frame = encoding.value.x86_64.frame; |
| 2019 | 1437 | |
| 2020 | | return column; |
| 2021 | | } |
| 1438 | const fp = (try regValueNative(context.thread_context, fpRegNum(reg_context), reg_context)).*; |
| 1439 | const new_sp = fp + 2 * @sizeOf(usize); |
| 2022 | 1440 | |
| 2023 | | /// Runs the CIE instructions, then the FDE instructions. Execution halts |
| 2024 | | /// once the row that corresponds to `pc` is known, and the row is returned. |
| 2025 | | pub fn runTo( |
| 2026 | | self: *VirtualMachine, |
| 2027 | | allocator: std.mem.Allocator, |
| 2028 | | pc: u64, |
| 2029 | | cie: std.debug.Dwarf.Unwind.CommonInformationEntry, |
| 2030 | | fde: std.debug.Dwarf.Unwind.FrameDescriptionEntry, |
| 2031 | | addr_size_bytes: u8, |
| 2032 | | endian: std.builtin.Endian, |
| 2033 | | ) !Row { |
| 2034 | | assert(self.cie_row == null); |
| 2035 | | if (pc < fde.pc_begin or pc >= fde.pc_begin + fde.pc_range) return error.AddressOutOfRange; |
| 2036 | | |
| 2037 | | var prev_row: Row = self.current_row; |
| 2038 | | |
| 2039 | | var cie_stream: std.Io.Reader = .fixed(cie.initial_instructions); |
| 2040 | | var fde_stream: std.Io.Reader = .fixed(fde.instructions); |
| 2041 | | const streams = [_]*std.Io.Reader{ &cie_stream, &fde_stream }; |
| 2042 | | |
| 2043 | | for (&streams, 0..) |stream, i| { |
| 2044 | | while (stream.seek < stream.buffer.len) { |
| 2045 | | const instruction = try std.debug.Dwarf.call_frame.Instruction.read(stream, addr_size_bytes, endian); |
| 2046 | | prev_row = try self.step(allocator, cie, i == 0, instruction); |
| 2047 | | if (pc < fde.pc_begin + self.current_row.offset) return prev_row; |
| 2048 | | } |
| 2049 | | } |
| 1441 | const ip_ptr = fp + @sizeOf(usize); |
| 1442 | const new_ip = @as(*const usize, @ptrFromInt(ip_ptr)).*; |
| 1443 | const new_fp = @as(*const usize, @ptrFromInt(fp)).*; |
| 2050 | 1444 | |
| 2051 | | return self.current_row; |
| 2052 | | } |
| 1445 | (try regValueNative(context.thread_context, fpRegNum(reg_context), reg_context)).* = new_fp; |
| 1446 | (try regValueNative(context.thread_context, spRegNum(reg_context), reg_context)).* = new_sp; |
| 1447 | (try regValueNative(context.thread_context, ip_reg_num, reg_context)).* = new_ip; |
| 2053 | 1448 | |
| 2054 | | pub fn runToNative( |
| 2055 | | self: *VirtualMachine, |
| 2056 | | allocator: std.mem.Allocator, |
| 2057 | | pc: u64, |
| 2058 | | cie: std.debug.Dwarf.Unwind.CommonInformationEntry, |
| 2059 | | fde: std.debug.Dwarf.Unwind.FrameDescriptionEntry, |
| 2060 | | ) !Row { |
| 2061 | | return self.runTo(allocator, pc, cie, fde, @sizeOf(usize), native_endian); |
| 2062 | | } |
| 1449 | const regs: [5]u3 = .{ |
| 1450 | frame.reg0, |
| 1451 | frame.reg1, |
| 1452 | frame.reg2, |
| 1453 | frame.reg3, |
| 1454 | frame.reg4, |
| 1455 | }; |
| 1456 | for (regs, 0..) |reg, i| { |
| 1457 | if (reg == 0) continue; |
| 1458 | const addr = fp - frame.frame_offset * @sizeOf(usize) + i * @sizeOf(usize); |
| 1459 | const reg_number = try Dwarf.compactUnwindToDwarfRegNumber(reg); |
| 1460 | (try regValueNative(context.thread_context, reg_number, reg_context)).* = @as(*const usize, @ptrFromInt(addr)).*; |
| 1461 | } |
| 2063 | 1462 | |
| 2064 | | fn resolveCopyOnWrite(self: *VirtualMachine, allocator: std.mem.Allocator) !void { |
| 2065 | | if (!self.current_row.copy_on_write) return; |
| 1463 | break :ip new_ip; |
| 1464 | }, |
| 1465 | .STACK_IMMD, |
| 1466 | .STACK_IND, |
| 1467 | => ip: { |
| 1468 | const frameless = encoding.value.x86_64.frameless; |
| 2066 | 1469 | |
| 2067 | | const new_start = self.columns.items.len; |
| 2068 | | if (self.current_row.columns.len > 0) { |
| 2069 | | try self.columns.ensureUnusedCapacity(allocator, self.current_row.columns.len); |
| 2070 | | self.columns.appendSliceAssumeCapacity(self.rowColumns(self.current_row)); |
| 2071 | | self.current_row.columns.start = new_start; |
| 2072 | | } |
| 2073 | | } |
| 1470 | const sp = (try regValueNative(context.thread_context, spRegNum(reg_context), reg_context)).*; |
| 1471 | const stack_size: usize = stack_size: { |
| 1472 | if (encoding.mode.x86_64 == .STACK_IMMD) { |
| 1473 | break :stack_size @as(usize, frameless.stack.direct.stack_size) * @sizeOf(usize); |
| 1474 | } |
| 1475 | // In .STACK_IND, the stack size is inferred from the subq instruction at the beginning of the function. |
| 1476 | const sub_offset_addr = |
| 1477 | text_base + |
| 1478 | entry.function_offset + |
| 1479 | frameless.stack.indirect.sub_offset; |
| 1480 | // `sub_offset_addr` points to the offset of the literal within the instruction |
| 1481 | const sub_operand = @as(*align(1) const u32, @ptrFromInt(sub_offset_addr)).*; |
| 1482 | break :stack_size sub_operand + @sizeOf(usize) * @as(usize, frameless.stack.indirect.stack_adjust); |
| 1483 | }; |
| 2074 | 1484 | |
| 2075 | | /// Executes a single instruction. |
| 2076 | | /// If this instruction is from the CIE, `is_initial` should be set. |
| 2077 | | /// Returns the value of `current_row` before executing this instruction. |
| 2078 | | pub fn step( |
| 2079 | | self: *VirtualMachine, |
| 2080 | | allocator: std.mem.Allocator, |
| 2081 | | cie: std.debug.Dwarf.Unwind.CommonInformationEntry, |
| 2082 | | is_initial: bool, |
| 2083 | | instruction: Dwarf.call_frame.Instruction, |
| 2084 | | ) !Row { |
| 2085 | | // CIE instructions must be run before FDE instructions |
| 2086 | | assert(!is_initial or self.cie_row == null); |
| 2087 | | if (!is_initial and self.cie_row == null) { |
| 2088 | | self.cie_row = self.current_row; |
| 2089 | | self.current_row.copy_on_write = true; |
| 2090 | | } |
| 1485 | // Decode the Lehmer-coded sequence of registers. |
| 1486 | // For a description of the encoding see lib/libc/include/any-macos.13-any/mach-o/compact_unwind_encoding.h |
| 2091 | 1487 | |
| 2092 | | const prev_row = self.current_row; |
| 2093 | | switch (instruction) { |
| 2094 | | .set_loc => |i| { |
| 2095 | | if (i.address <= self.current_row.offset) return error.InvalidOperation; |
| 2096 | | // TODO: Check cie.segment_selector_size != 0 for DWARFV4 |
| 2097 | | self.current_row.offset = i.address; |
| 2098 | | }, |
| 2099 | | inline .advance_loc, |
| 2100 | | .advance_loc1, |
| 2101 | | .advance_loc2, |
| 2102 | | .advance_loc4, |
| 2103 | | => |i| { |
| 2104 | | self.current_row.offset += i.delta * cie.code_alignment_factor; |
| 2105 | | self.current_row.copy_on_write = true; |
| 2106 | | }, |
| 2107 | | inline .offset, |
| 2108 | | .offset_extended, |
| 2109 | | .offset_extended_sf, |
| 2110 | | => |i| { |
| 2111 | | try self.resolveCopyOnWrite(allocator); |
| 2112 | | const column = try self.getOrAddColumn(allocator, i.register); |
| 2113 | | column.rule = .{ .offset = @as(i64, @intCast(i.offset)) * cie.data_alignment_factor }; |
| 2114 | | }, |
| 2115 | | inline .restore, |
| 2116 | | .restore_extended, |
| 2117 | | => |i| { |
| 2118 | | try self.resolveCopyOnWrite(allocator); |
| 2119 | | if (self.cie_row) |cie_row| { |
| 2120 | | const column = try self.getOrAddColumn(allocator, i.register); |
| 2121 | | column.rule = for (self.rowColumns(cie_row)) |cie_column| { |
| 2122 | | if (cie_column.register == i.register) break cie_column.rule; |
| 2123 | | } else .{ .default = {} }; |
| 2124 | | } else return error.InvalidOperation; |
| 2125 | | }, |
| 2126 | | .nop => {}, |
| 2127 | | .undefined => |i| { |
| 2128 | | try self.resolveCopyOnWrite(allocator); |
| 2129 | | const column = try self.getOrAddColumn(allocator, i.register); |
| 2130 | | column.rule = .{ .undefined = {} }; |
| 2131 | | }, |
| 2132 | | .same_value => |i| { |
| 2133 | | try self.resolveCopyOnWrite(allocator); |
| 2134 | | const column = try self.getOrAddColumn(allocator, i.register); |
| 2135 | | column.rule = .{ .same_value = {} }; |
| 2136 | | }, |
| 2137 | | .register => |i| { |
| 2138 | | try self.resolveCopyOnWrite(allocator); |
| 2139 | | const column = try self.getOrAddColumn(allocator, i.register); |
| 2140 | | column.rule = .{ .register = i.target_register }; |
| 2141 | | }, |
| 2142 | | .remember_state => { |
| 2143 | | try self.stack.append(allocator, self.current_row.columns); |
| 2144 | | self.current_row.copy_on_write = true; |
| 2145 | | }, |
| 2146 | | .restore_state => { |
| 2147 | | const restored_columns = self.stack.pop() orelse return error.InvalidOperation; |
| 2148 | | self.columns.shrinkRetainingCapacity(self.columns.items.len - self.current_row.columns.len); |
| 2149 | | try self.columns.ensureUnusedCapacity(allocator, restored_columns.len); |
| 2150 | | |
| 2151 | | self.current_row.columns.start = self.columns.items.len; |
| 2152 | | self.current_row.columns.len = restored_columns.len; |
| 2153 | | self.columns.appendSliceAssumeCapacity(self.columns.items[restored_columns.start..][0..restored_columns.len]); |
| 2154 | | }, |
| 2155 | | .def_cfa => |i| { |
| 2156 | | try self.resolveCopyOnWrite(allocator); |
| 2157 | | self.current_row.cfa = .{ |
| 2158 | | .register = i.register, |
| 2159 | | .rule = .{ .val_offset = @intCast(i.offset) }, |
| 2160 | | }; |
| 2161 | | }, |
| 2162 | | .def_cfa_sf => |i| { |
| 2163 | | try self.resolveCopyOnWrite(allocator); |
| 2164 | | self.current_row.cfa = .{ |
| 2165 | | .register = i.register, |
| 2166 | | .rule = .{ .val_offset = i.offset * cie.data_alignment_factor }, |
| 2167 | | }; |
| 2168 | | }, |
| 2169 | | .def_cfa_register => |i| { |
| 2170 | | try self.resolveCopyOnWrite(allocator); |
| 2171 | | if (self.current_row.cfa.register == null or self.current_row.cfa.rule != .val_offset) return error.InvalidOperation; |
| 2172 | | self.current_row.cfa.register = i.register; |
| 2173 | | }, |
| 2174 | | .def_cfa_offset => |i| { |
| 2175 | | try self.resolveCopyOnWrite(allocator); |
| 2176 | | if (self.current_row.cfa.register == null or self.current_row.cfa.rule != .val_offset) return error.InvalidOperation; |
| 2177 | | self.current_row.cfa.rule = .{ |
| 2178 | | .val_offset = @intCast(i.offset), |
| 2179 | | }; |
| 2180 | | }, |
| 2181 | | .def_cfa_offset_sf => |i| { |
| 2182 | | try self.resolveCopyOnWrite(allocator); |
| 2183 | | if (self.current_row.cfa.register == null or self.current_row.cfa.rule != .val_offset) return error.InvalidOperation; |
| 2184 | | self.current_row.cfa.rule = .{ |
| 2185 | | .val_offset = i.offset * cie.data_alignment_factor, |
| 2186 | | }; |
| 2187 | | }, |
| 2188 | | .def_cfa_expression => |i| { |
| 2189 | | try self.resolveCopyOnWrite(allocator); |
| 2190 | | self.current_row.cfa.register = undefined; |
| 2191 | | self.current_row.cfa.rule = .{ |
| 2192 | | .expression = i.block, |
| 2193 | | }; |
| 2194 | | }, |
| 2195 | | .expression => |i| { |
| 2196 | | try self.resolveCopyOnWrite(allocator); |
| 2197 | | const column = try self.getOrAddColumn(allocator, i.register); |
| 2198 | | column.rule = .{ |
| 2199 | | .expression = i.block, |
| 1488 | // Decode the variable-based permutation number into its digits. Each digit represents |
| 1489 | // an index into the list of register numbers that weren't yet used in the sequence at |
| 1490 | // the time the digit was added. |
| 1491 | const reg_count = frameless.stack_reg_count; |
| 1492 | const ip_ptr = ip_ptr: { |
| 1493 | var digits: [6]u3 = undefined; |
| 1494 | var accumulator: usize = frameless.stack_reg_permutation; |
| 1495 | var base: usize = 2; |
| 1496 | for (0..reg_count) |i| { |
| 1497 | const div = accumulator / base; |
| 1498 | digits[digits.len - 1 - i] = @intCast(accumulator - base * div); |
| 1499 | accumulator = div; |
| 1500 | base += 1; |
| 1501 | } |
| 1502 | |
| 1503 | var registers: [6]u3 = undefined; |
| 1504 | var used_indices: [6]bool = @splat(false); |
| 1505 | for (digits[digits.len - reg_count ..], 0..) |target_unused_index, i| { |
| 1506 | var unused_count: u8 = 0; |
| 1507 | const unused_index = for (used_indices, 0..) |used, index| { |
| 1508 | if (!used) { |
| 1509 | if (target_unused_index == unused_count) break index; |
| 1510 | unused_count += 1; |
| 1511 | } |
| 1512 | } else unreachable; |
| 1513 | registers[i] = @intCast(unused_index + 1); |
| 1514 | used_indices[unused_index] = true; |
| 1515 | } |
| 1516 | |
| 1517 | var reg_addr = sp + stack_size - @sizeOf(usize) * @as(usize, reg_count + 1); |
| 1518 | for (0..reg_count) |i| { |
| 1519 | const reg_number = try Dwarf.compactUnwindToDwarfRegNumber(registers[i]); |
| 1520 | (try regValueNative(context.thread_context, reg_number, reg_context)).* = @as(*const usize, @ptrFromInt(reg_addr)).*; |
| 1521 | reg_addr += @sizeOf(usize); |
| 1522 | } |
| 1523 | |
| 1524 | break :ip_ptr reg_addr; |
| 2200 | 1525 | }; |
| 1526 | |
| 1527 | const new_ip = @as(*const usize, @ptrFromInt(ip_ptr)).*; |
| 1528 | const new_sp = ip_ptr + @sizeOf(usize); |
| 1529 | |
| 1530 | (try regValueNative(context.thread_context, spRegNum(reg_context), reg_context)).* = new_sp; |
| 1531 | (try regValueNative(context.thread_context, ip_reg_num, reg_context)).* = new_ip; |
| 1532 | |
| 1533 | break :ip new_ip; |
| 2201 | 1534 | }, |
| 2202 | | .val_offset => |i| { |
| 2203 | | try self.resolveCopyOnWrite(allocator); |
| 2204 | | const column = try self.getOrAddColumn(allocator, i.register); |
| 2205 | | column.rule = .{ |
| 2206 | | .val_offset = @as(i64, @intCast(i.offset)) * cie.data_alignment_factor, |
| 2207 | | }; |
| 1535 | .DWARF => { |
| 1536 | const dwarf_unwind = &(opt_dwarf_unwind orelse return error.MissingEhFrame); |
| 1537 | return unwindFrameDwarf(dwarf_unwind, load_offset, context, @intCast(encoding.value.x86_64.dwarf)); |
| 2208 | 1538 | }, |
| 2209 | | .val_offset_sf => |i| { |
| 2210 | | try self.resolveCopyOnWrite(allocator); |
| 2211 | | const column = try self.getOrAddColumn(allocator, i.register); |
| 2212 | | column.rule = .{ |
| 2213 | | .val_offset = i.offset * cie.data_alignment_factor, |
| 2214 | | }; |
| 1539 | }, |
| 1540 | .aarch64, .aarch64_be => switch (encoding.mode.arm64) { |
| 1541 | .OLD => return error.UnimplementedUnwindEncoding, |
| 1542 | .FRAMELESS => ip: { |
| 1543 | const sp = (try regValueNative(context.thread_context, spRegNum(reg_context), reg_context)).*; |
| 1544 | const new_sp = sp + encoding.value.arm64.frameless.stack_size * 16; |
| 1545 | const new_ip = (try regValueNative(context.thread_context, 30, reg_context)).*; |
| 1546 | (try regValueNative(context.thread_context, spRegNum(reg_context), reg_context)).* = new_sp; |
| 1547 | break :ip new_ip; |
| 2215 | 1548 | }, |
| 2216 | | .val_expression => |i| { |
| 2217 | | try self.resolveCopyOnWrite(allocator); |
| 2218 | | const column = try self.getOrAddColumn(allocator, i.register); |
| 2219 | | column.rule = .{ |
| 2220 | | .val_expression = i.block, |
| 2221 | | }; |
| 1549 | .DWARF => { |
| 1550 | const dwarf_unwind = &(opt_dwarf_unwind orelse return error.MissingEhFrame); |
| 1551 | return unwindFrameDwarf(dwarf_unwind, load_offset, context, @intCast(encoding.value.arm64.dwarf)); |
| 2222 | 1552 | }, |
| 2223 | | } |
| 1553 | .FRAME => ip: { |
| 1554 | const frame = encoding.value.arm64.frame; |
| 2224 | 1555 | |
| 2225 | | return prev_row; |
| 2226 | | } |
| 2227 | | }; |
| 1556 | const fp = (try regValueNative(context.thread_context, fpRegNum(reg_context), reg_context)).*; |
| 1557 | const ip_ptr = fp + @sizeOf(usize); |
| 2228 | 1558 | |
| 2229 | | /// Returns the ABI-defined default value this register has in the unwinding table |
| 2230 | | /// before running any of the CIE instructions. The DWARF spec defines these as having |
| 2231 | | /// the .undefined rule by default, but allows ABI authors to override that. |
| 2232 | | fn getRegDefaultValue(reg_number: u8, context: *UnwindContext, out: []u8) !void { |
| 2233 | | switch (builtin.cpu.arch) { |
| 2234 | | .aarch64, .aarch64_be => { |
| 2235 | | // Callee-saved registers are initialized as if they had the .same_value rule |
| 2236 | | if (reg_number >= 19 and reg_number <= 28) { |
| 2237 | | const src = try regBytes(context.thread_context, reg_number, context.reg_context); |
| 2238 | | if (src.len != out.len) return error.RegisterSizeMismatch; |
| 2239 | | @memcpy(out, src); |
| 2240 | | return; |
| 2241 | | } |
| 2242 | | }, |
| 2243 | | else => {}, |
| 2244 | | } |
| 1559 | var reg_addr = fp - @sizeOf(usize); |
| 1560 | inline for (@typeInfo(@TypeOf(frame.x_reg_pairs)).@"struct".fields, 0..) |field, i| { |
| 1561 | if (@field(frame.x_reg_pairs, field.name) != 0) { |
| 1562 | (try regValueNative(context.thread_context, 19 + i, reg_context)).* = @as(*const usize, @ptrFromInt(reg_addr)).*; |
| 1563 | reg_addr += @sizeOf(usize); |
| 1564 | (try regValueNative(context.thread_context, 20 + i, reg_context)).* = @as(*const usize, @ptrFromInt(reg_addr)).*; |
| 1565 | reg_addr += @sizeOf(usize); |
| 1566 | } |
| 1567 | } |
| 2245 | 1568 | |
| 2246 | | @memset(out, undefined); |
| 2247 | | } |
| 1569 | inline for (@typeInfo(@TypeOf(frame.d_reg_pairs)).@"struct".fields, 0..) |field, i| { |
| 1570 | if (@field(frame.d_reg_pairs, field.name) != 0) { |
| 1571 | // Only the lower half of the 128-bit V registers are restored during unwinding |
| 1572 | { |
| 1573 | const dest: *align(1) usize = @ptrCast(try regBytes(context.thread_context, 64 + 8 + i, context.reg_context)); |
| 1574 | dest.* = @as(*const usize, @ptrFromInt(reg_addr)).*; |
| 1575 | } |
| 1576 | reg_addr += @sizeOf(usize); |
| 1577 | { |
| 1578 | const dest: *align(1) usize = @ptrCast(try regBytes(context.thread_context, 64 + 9 + i, context.reg_context)); |
| 1579 | dest.* = @as(*const usize, @ptrFromInt(reg_addr)).*; |
| 1580 | } |
| 1581 | reg_addr += @sizeOf(usize); |
| 1582 | } |
| 1583 | } |
| 2248 | 1584 | |
| 2249 | | /// Since register rules are applied (usually) during a panic, |
| 2250 | | /// checked addition / subtraction is used so that we can return |
| 2251 | | /// an error and fall back to FP-based unwinding. |
| 2252 | | fn applyOffset(base: usize, offset: i64) !usize { |
| 2253 | | return if (offset >= 0) |
| 2254 | | try std.math.add(usize, base, @as(usize, @intCast(offset))) |
| 2255 | | else |
| 2256 | | try std.math.sub(usize, base, @as(usize, @intCast(-offset))); |
| 1585 | const new_ip = @as(*const usize, @ptrFromInt(ip_ptr)).*; |
| 1586 | const new_fp = @as(*const usize, @ptrFromInt(fp)).*; |
| 1587 | |
| 1588 | (try regValueNative(context.thread_context, fpRegNum(reg_context), reg_context)).* = new_fp; |
| 1589 | (try regValueNative(context.thread_context, ip_reg_num, reg_context)).* = new_ip; |
| 1590 | |
| 1591 | break :ip new_ip; |
| 1592 | }, |
| 1593 | }, |
| 1594 | else => comptime unreachable, // unimplemented |
| 1595 | }; |
| 1596 | |
| 1597 | context.pc = stripInstructionPtrAuthCode(new_ip); |
| 1598 | if (context.pc > 0) context.pc -= 1; |
| 1599 | return new_ip; |
| 2257 | 1600 | } |