authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-02-18 12:41:37-08:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2024-02-18 12:41:37-08:00
log7775e46e8179fd1f4e27ca45fc211ac2e23a6969
treef4b479b4deb3ad2b3c0440f936107adffa81b80c
parent3cafb9655a754743da695af41ef635b79d066127
parent247e4ac3cc18a1a29bc180873b7b9f946f515212
signaturebadge-check Signed by PGP key B5690EEEBB952194

Merge pull request #18983 from jacobly0/dwarf-rewrite

dwarf: optimize dwarf parsing for speed

5 files changed, 765 insertions(+), 777 deletions(-)

lib/std/dwarf.zig+683-703
......@@ -1,12 +1,9 @@
11const builtin = @import("builtin");
22const std = @import("std.zig");
33const debug = std.debug;
4const fs = std.fs;
5const io = std.io;
64const mem = std.mem;
75const math = std.math;
8const leb = @import("leb128.zig");
9const assert = std.debug.assert;
6const assert = debug.assert;
107const native_endian = builtin.cpu.arch.endian();
118
129pub const TAG = @import("dwarf/TAG.zig");
......@@ -167,8 +164,8 @@ const Func = struct {
167164
168165pub const CompileUnit = struct {
169166 version: u16,
170 is_64: bool,
171 die: *Die,
167 format: Format,
168 die: Die,
172169 pc_range: ?PcRange,
173170
174171 str_offsets_base: usize,
......@@ -178,101 +175,88 @@ pub const CompileUnit = struct {
178175 frame_base: ?*const FormValue,
179176};
180177
181const AbbrevTable = std.ArrayList(AbbrevTableEntry);
182
183const AbbrevTableHeader = struct {
184 // offset from .debug_abbrev
185 offset: u64,
186 table: AbbrevTable,
187
188 fn deinit(header: *AbbrevTableHeader) void {
189 for (header.table.items) |*entry| {
190 entry.deinit();
191 }
192 header.table.deinit();
193 }
194};
195
196const AbbrevTableEntry = struct {
197 has_children: bool,
198 abbrev_code: u64,
178const Abbrev = struct {
179 code: u64,
199180 tag_id: u64,
200 attrs: std.ArrayList(AbbrevAttr),
181 has_children: bool,
182 attrs: []Attr,
201183
202 fn deinit(entry: *AbbrevTableEntry) void {
203 entry.attrs.deinit();
184 fn deinit(abbrev: *Abbrev, allocator: mem.Allocator) void {
185 allocator.free(abbrev.attrs);
186 abbrev.* = undefined;
204187 }
205};
206188
207const AbbrevAttr = struct {
208 attr_id: u64,
209 form_id: u64,
210 /// Only valid if form_id is .implicit_const
211 payload: i64,
212};
189 const Attr = struct {
190 id: u64,
191 form_id: u64,
192 /// Only valid if form_id is .implicit_const
193 payload: i64,
194 };
213195
214pub const FormValue = union(enum) {
215 Address: u64,
216 AddrOffset: usize,
217 Block: []u8,
218 Const: Constant,
219 ExprLoc: []u8,
220 Flag: bool,
221 SecOffset: u64,
222 Ref: u64,
223 RefAddr: u64,
224 String: []const u8,
225 StrPtr: u64,
226 StrOffset: usize,
227 LineStrPtr: u64,
228 LocListOffset: u64,
229 RangeListOffset: u64,
230 data16: [16]u8,
231
232 fn getString(fv: FormValue, di: DwarfInfo) ![]const u8 {
233 switch (fv) {
234 .String => |s| return s,
235 .StrPtr => |off| return di.getString(off),
236 .LineStrPtr => |off| return di.getLineString(off),
237 else => return badDwarf(),
196 const Table = struct {
197 // offset from .debug_abbrev
198 offset: u64,
199 abbrevs: []Abbrev,
200
201 fn deinit(table: *Table, allocator: mem.Allocator) void {
202 for (table.abbrevs) |*abbrev| {
203 abbrev.deinit(allocator);
204 }
205 allocator.free(table.abbrevs);
206 table.* = undefined;
238207 }
239 }
240208
241 fn getUInt(fv: FormValue, comptime U: type) !U {
242 switch (fv) {
243 .Const => |c| {
244 const int = try c.asUnsignedLe();
245 return math.cast(U, int) orelse return badDwarf();
246 },
247 .SecOffset => |x| return math.cast(U, x) orelse return badDwarf(),
248 else => return badDwarf(),
209 fn get(table: *const Table, abbrev_code: u64) ?*const Abbrev {
210 return for (table.abbrevs) |*abbrev| {
211 if (abbrev.code == abbrev_code) break abbrev;
212 } else null;
249213 }
250 }
214 };
215};
251216
252 fn getData16(fv: FormValue) ![16]u8 {
217pub const FormValue = union(enum) {
218 addr: u64,
219 addrx: usize,
220 block: []const u8,
221 udata: u64,
222 data16: *const [16]u8,
223 sdata: i64,
224 exprloc: []const u8,
225 flag: bool,
226 sec_offset: u64,
227 ref: u64,
228 ref_addr: u64,
229 string: [:0]const u8,
230 strp: u64,
231 strx: usize,
232 line_strp: u64,
233 loclistx: u64,
234 rnglistx: u64,
235
236 fn getString(fv: FormValue, di: DwarfInfo) ![:0]const u8 {
253237 switch (fv) {
254 .data16 => |d| return d,
238 .string => |s| return s,
239 .strp => |off| return di.getString(off),
240 .line_strp => |off| return di.getLineString(off),
255241 else => return badDwarf(),
256242 }
257243 }
258};
259
260const Constant = struct {
261 payload: u64,
262 signed: bool,
263244
264 fn asUnsignedLe(self: Constant) !u64 {
265 if (self.signed) return badDwarf();
266 return self.payload;
245 fn getUInt(fv: FormValue, comptime U: type) !U {
246 return switch (fv) {
247 inline .udata,
248 .sdata,
249 .sec_offset,
250 => |c| math.cast(U, c) orelse badDwarf(),
251 else => badDwarf(),
252 };
267253 }
268254};
269255
270256const Die = struct {
271 // Arena for Die's Attr's and FormValue's.
272 arena: std.heap.ArenaAllocator,
273257 tag_id: u64,
274258 has_children: bool,
275 attrs: std.ArrayListUnmanaged(Attr) = .{},
259 attrs: []Attr,
276260
277261 const Attr = struct {
278262 id: u64,
......@@ -280,12 +264,12 @@ const Die = struct {
280264 };
281265
282266 fn deinit(self: *Die, allocator: mem.Allocator) void {
283 self.arena.deinit();
284 self.attrs.deinit(allocator);
267 allocator.free(self.attrs);
268 self.* = undefined;
285269 }
286270
287271 fn getAttr(self: *const Die, id: u64) ?*const FormValue {
288 for (self.attrs.items) |*attr| {
272 for (self.attrs) |*attr| {
289273 if (attr.id == id) return &attr.value;
290274 }
291275 return null;
......@@ -299,8 +283,8 @@ const Die = struct {
299283 ) error{ InvalidDebugInfo, MissingDebugInfo }!u64 {
300284 const form_value = self.getAttr(id) orelse return error.MissingDebugInfo;
301285 return switch (form_value.*) {
302 FormValue.Address => |value| value,
303 FormValue.AddrOffset => |index| di.readDebugAddr(compile_unit, index),
286 .addr => |value| value,
287 .addrx => |index| di.readDebugAddr(compile_unit, index),
304288 else => error.InvalidDebugInfo,
305289 };
306290 }
......@@ -313,7 +297,7 @@ const Die = struct {
313297 fn getAttrUnsignedLe(self: *const Die, id: u64) !u64 {
314298 const form_value = self.getAttr(id) orelse return error.MissingDebugInfo;
315299 return switch (form_value.*) {
316 FormValue.Const => |value| value.asUnsignedLe(),
300 .Const => |value| value.asUnsignedLe(),
317301 else => error.InvalidDebugInfo,
318302 };
319303 }
......@@ -321,7 +305,7 @@ const Die = struct {
321305 fn getAttrRef(self: *const Die, id: u64) !u64 {
322306 const form_value = self.getAttr(id) orelse return error.MissingDebugInfo;
323307 return switch (form_value.*) {
324 FormValue.Ref => |value| value,
308 .ref => |value| value,
325309 else => error.InvalidDebugInfo,
326310 };
327311 }
......@@ -335,24 +319,27 @@ const Die = struct {
335319 ) error{ InvalidDebugInfo, MissingDebugInfo }![]const u8 {
336320 const form_value = self.getAttr(id) orelse return error.MissingDebugInfo;
337321 switch (form_value.*) {
338 FormValue.String => |value| return value,
339 FormValue.StrPtr => |offset| return di.getString(offset),
340 FormValue.StrOffset => |index| {
322 .string => |value| return value,
323 .strp => |offset| return di.getString(offset),
324 .strx => |index| {
341325 const debug_str_offsets = di.section(.debug_str_offsets) orelse return badDwarf();
342326 if (compile_unit.str_offsets_base == 0) return badDwarf();
343 if (compile_unit.is_64) {
344 const byte_offset = compile_unit.str_offsets_base + 8 * index;
345 if (byte_offset + 8 > debug_str_offsets.len) return badDwarf();
346 const offset = mem.readInt(u64, debug_str_offsets[byte_offset..][0..8], di.endian);
347 return getStringGeneric(opt_str, offset);
348 } else {
349 const byte_offset = compile_unit.str_offsets_base + 4 * index;
350 if (byte_offset + 4 > debug_str_offsets.len) return badDwarf();
351 const offset = mem.readInt(u32, debug_str_offsets[byte_offset..][0..4], di.endian);
352 return getStringGeneric(opt_str, offset);
327 switch (compile_unit.format) {
328 .@"32" => {
329 const byte_offset = compile_unit.str_offsets_base + 4 * index;
330 if (byte_offset + 4 > debug_str_offsets.len) return badDwarf();
331 const offset = mem.readInt(u32, debug_str_offsets[byte_offset..][0..4], di.endian);
332 return getStringGeneric(opt_str, offset);
333 },
334 .@"64" => {
335 const byte_offset = compile_unit.str_offsets_base + 8 * index;
336 if (byte_offset + 8 > debug_str_offsets.len) return badDwarf();
337 const offset = mem.readInt(u64, debug_str_offsets[byte_offset..][0..8], di.endian);
338 return getStringGeneric(opt_str, offset);
339 },
353340 }
354341 },
355 FormValue.LineStrPtr => |offset| return di.getLineString(offset),
342 .line_strp => |offset| return di.getLineString(offset),
356343 else => return badDwarf(),
357344 }
358345 }
......@@ -458,7 +445,7 @@ const LineNumberProgram = struct {
458445 if (file_entry.dir_index >= self.include_dirs.len) return badDwarf();
459446 const dir_name = self.include_dirs[file_entry.dir_index].path;
460447
461 const file_name = try fs.path.join(allocator, &[_][]const u8{
448 const file_name = try std.fs.path.join(allocator, &[_][]const u8{
462449 dir_name, file_entry.path,
463450 });
464451
......@@ -481,168 +468,97 @@ const LineNumberProgram = struct {
481468 }
482469};
483470
484fn readUnitLength(in_stream: anytype, endian: std.builtin.Endian, is_64: *bool) !u64 {
485 const first_32_bits = try in_stream.readInt(u32, endian);
486 is_64.* = (first_32_bits == 0xffffffff);
487 if (is_64.*) {
488 return in_stream.readInt(u64, endian);
489 } else {
490 if (first_32_bits >= 0xfffffff0) return badDwarf();
491 // TODO this cast should not be needed
492 return @as(u64, first_32_bits);
493 }
494}
495
496// TODO the nosuspends here are workarounds
497fn readAllocBytes(allocator: mem.Allocator, in_stream: anytype, size: usize) ![]u8 {
498 const buf = try allocator.alloc(u8, size);
499 errdefer allocator.free(buf);
500 if ((try nosuspend in_stream.read(buf)) < size) return error.EndOfFile;
501 return buf;
502}
503
504// TODO the nosuspends here are workarounds
505fn readAddress(in_stream: anytype, endian: std.builtin.Endian, is_64: bool) !u64 {
506 return nosuspend if (is_64)
507 try in_stream.readInt(u64, endian)
508 else
509 @as(u64, try in_stream.readInt(u32, endian));
510}
511
512fn parseFormValueBlockLen(allocator: mem.Allocator, in_stream: anytype, size: usize) !FormValue {
513 const buf = try readAllocBytes(allocator, in_stream, size);
514 return FormValue{ .Block = buf };
515}
516
517// TODO the nosuspends here are workarounds
518fn parseFormValueBlock(allocator: mem.Allocator, in_stream: anytype, endian: std.builtin.Endian, size: usize) !FormValue {
519 const block_len = try nosuspend in_stream.readVarInt(usize, endian, size);
520 return parseFormValueBlockLen(allocator, in_stream, block_len);
521}
522
523fn parseFormValueConstant(in_stream: anytype, signed: bool, endian: std.builtin.Endian, comptime size: i32) !FormValue {
524 // TODO: Please forgive me, I've worked around zig not properly spilling some intermediate values here.
525 // `nosuspend` should be removed from all the function calls once it is fixed.
526 return FormValue{
527 .Const = Constant{
528 .signed = signed,
529 .payload = switch (size) {
530 1 => try nosuspend in_stream.readInt(u8, endian),
531 2 => try nosuspend in_stream.readInt(u16, endian),
532 4 => try nosuspend in_stream.readInt(u32, endian),
533 8 => try nosuspend in_stream.readInt(u64, endian),
534 -1 => blk: {
535 if (signed) {
536 const x = try nosuspend leb.readILEB128(i64, in_stream);
537 break :blk @as(u64, @bitCast(x));
538 } else {
539 const x = try nosuspend leb.readULEB128(u64, in_stream);
540 break :blk x;
541 }
542 },
543 else => @compileError("Invalid size"),
544 },
471const UnitHeader = struct {
472 format: Format,
473 header_length: u4,
474 unit_length: u64,
475};
476fn readUnitHeader(fbr: *FixedBufferReader) !UnitHeader {
477 return switch (try fbr.readInt(u32)) {
478 0...0xfffffff0 - 1 => |unit_length| .{
479 .format = .@"32",
480 .header_length = 4,
481 .unit_length = unit_length,
545482 },
546 };
547}
548
549// TODO the nosuspends here are workarounds
550fn parseFormValueRef(in_stream: anytype, endian: std.builtin.Endian, size: i32) !FormValue {
551 return FormValue{
552 .Ref = switch (size) {
553 1 => try nosuspend in_stream.readInt(u8, endian),
554 2 => try nosuspend in_stream.readInt(u16, endian),
555 4 => try nosuspend in_stream.readInt(u32, endian),
556 8 => try nosuspend in_stream.readInt(u64, endian),
557 -1 => try nosuspend leb.readULEB128(u64, in_stream),
558 else => unreachable,
483 0xfffffff0...0xffffffff - 1 => badDwarf(),
484 0xffffffff => .{
485 .format = .@"64",
486 .header_length = 12,
487 .unit_length = try fbr.readInt(u64),
559488 },
560489 };
561490}
562491
563// TODO the nosuspends here are workarounds
564fn parseFormValue(allocator: mem.Allocator, in_stream: anytype, form_id: u64, endian: std.builtin.Endian, is_64: bool) anyerror!FormValue {
492fn parseFormValue(
493 fbr: *FixedBufferReader,
494 form_id: u64,
495 format: Format,
496 implicit_const: ?i64,
497) anyerror!FormValue {
565498 return switch (form_id) {
566 FORM.addr => FormValue{ .Address = try readAddress(in_stream, endian, @sizeOf(usize) == 8) },
567 FORM.addrx1 => return FormValue{ .AddrOffset = try in_stream.readInt(u8, endian) },
568 FORM.addrx2 => return FormValue{ .AddrOffset = try in_stream.readInt(u16, endian) },
569 FORM.addrx3 => return FormValue{ .AddrOffset = try in_stream.readInt(u24, endian) },
570 FORM.addrx4 => return FormValue{ .AddrOffset = try in_stream.readInt(u32, endian) },
571 FORM.addrx => return FormValue{ .AddrOffset = try nosuspend leb.readULEB128(usize, in_stream) },
572
573 FORM.block1 => parseFormValueBlock(allocator, in_stream, endian, 1),
574 FORM.block2 => parseFormValueBlock(allocator, in_stream, endian, 2),
575 FORM.block4 => parseFormValueBlock(allocator, in_stream, endian, 4),
576 FORM.block => {
577 const block_len = try nosuspend leb.readULEB128(usize, in_stream);
578 return parseFormValueBlockLen(allocator, in_stream, block_len);
579 },
580 FORM.data1 => parseFormValueConstant(in_stream, false, endian, 1),
581 FORM.data2 => parseFormValueConstant(in_stream, false, endian, 2),
582 FORM.data4 => parseFormValueConstant(in_stream, false, endian, 4),
583 FORM.data8 => parseFormValueConstant(in_stream, false, endian, 8),
584 FORM.data16 => {
585 var buf: [16]u8 = undefined;
586 if ((try nosuspend in_stream.readAll(&buf)) < 16) return error.EndOfFile;
587 return FormValue{ .data16 = buf };
588 },
589 FORM.udata, FORM.sdata => {
590 const signed = form_id == FORM.sdata;
591 return parseFormValueConstant(in_stream, signed, endian, -1);
592 },
593 FORM.exprloc => {
594 const size = try nosuspend leb.readULEB128(usize, in_stream);
595 const buf = try readAllocBytes(allocator, in_stream, size);
596 return FormValue{ .ExprLoc = buf };
597 },
598 FORM.flag => FormValue{ .Flag = (try nosuspend in_stream.readByte()) != 0 },
599 FORM.flag_present => FormValue{ .Flag = true },
600 FORM.sec_offset => FormValue{ .SecOffset = try readAddress(in_stream, endian, is_64) },
601
602 FORM.ref1 => parseFormValueRef(in_stream, endian, 1),
603 FORM.ref2 => parseFormValueRef(in_stream, endian, 2),
604 FORM.ref4 => parseFormValueRef(in_stream, endian, 4),
605 FORM.ref8 => parseFormValueRef(in_stream, endian, 8),
606 FORM.ref_udata => parseFormValueRef(in_stream, endian, -1),
607
608 FORM.ref_addr => FormValue{ .RefAddr = try readAddress(in_stream, endian, is_64) },
609 FORM.ref_sig8 => FormValue{ .Ref = try nosuspend in_stream.readInt(u64, endian) },
610
611 FORM.string => FormValue{ .String = try in_stream.readUntilDelimiterAlloc(allocator, 0, math.maxInt(usize)) },
612 FORM.strp => FormValue{ .StrPtr = try readAddress(in_stream, endian, is_64) },
613 FORM.strx1 => return FormValue{ .StrOffset = try in_stream.readInt(u8, endian) },
614 FORM.strx2 => return FormValue{ .StrOffset = try in_stream.readInt(u16, endian) },
615 FORM.strx3 => return FormValue{ .StrOffset = try in_stream.readInt(u24, endian) },
616 FORM.strx4 => return FormValue{ .StrOffset = try in_stream.readInt(u32, endian) },
617 FORM.strx => return FormValue{ .StrOffset = try nosuspend leb.readULEB128(usize, in_stream) },
618 FORM.line_strp => FormValue{ .LineStrPtr = try readAddress(in_stream, endian, is_64) },
619 FORM.indirect => {
620 const child_form_id = try nosuspend leb.readULEB128(u64, in_stream);
621 if (true) {
622 return parseFormValue(allocator, in_stream, child_form_id, endian, is_64);
623 }
624 const F = @TypeOf(async parseFormValue(allocator, in_stream, child_form_id, endian, is_64));
625 const frame = try allocator.create(F);
626 defer allocator.destroy(frame);
627 return await @asyncCall(frame, {}, parseFormValue, .{ allocator, in_stream, child_form_id, endian, is_64 });
628 },
629 FORM.implicit_const => FormValue{ .Const = Constant{ .signed = true, .payload = undefined } },
630 FORM.loclistx => return FormValue{ .LocListOffset = try nosuspend leb.readULEB128(u64, in_stream) },
631 FORM.rnglistx => return FormValue{ .RangeListOffset = try nosuspend leb.readULEB128(u64, in_stream) },
499 FORM.addr => .{ .addr = try fbr.readAddress(switch (@bitSizeOf(usize)) {
500 32 => .@"32",
501 64 => .@"64",
502 else => @compileError("unsupported @sizeOf(usize)"),
503 }) },
504 FORM.addrx1 => .{ .addrx = try fbr.readInt(u8) },
505 FORM.addrx2 => .{ .addrx = try fbr.readInt(u16) },
506 FORM.addrx3 => .{ .addrx = try fbr.readInt(u24) },
507 FORM.addrx4 => .{ .addrx = try fbr.readInt(u32) },
508 FORM.addrx => .{ .addrx = try fbr.readUleb128(usize) },
509
510 FORM.block1,
511 FORM.block2,
512 FORM.block4,
513 FORM.block,
514 => .{ .block = try fbr.readBytes(switch (form_id) {
515 FORM.block1 => try fbr.readInt(u8),
516 FORM.block2 => try fbr.readInt(u16),
517 FORM.block4 => try fbr.readInt(u32),
518 FORM.block => try fbr.readUleb128(usize),
519 else => unreachable,
520 }) },
521
522 FORM.data1 => .{ .udata = try fbr.readInt(u8) },
523 FORM.data2 => .{ .udata = try fbr.readInt(u16) },
524 FORM.data4 => .{ .udata = try fbr.readInt(u32) },
525 FORM.data8 => .{ .udata = try fbr.readInt(u64) },
526 FORM.data16 => .{ .data16 = (try fbr.readBytes(16))[0..16] },
527 FORM.udata => .{ .udata = try fbr.readUleb128(u64) },
528 FORM.sdata => .{ .sdata = try fbr.readIleb128(i64) },
529 FORM.exprloc => .{ .exprloc = try fbr.readBytes(try fbr.readUleb128(usize)) },
530 FORM.flag => .{ .flag = (try fbr.readByte()) != 0 },
531 FORM.flag_present => .{ .flag = true },
532 FORM.sec_offset => .{ .sec_offset = try fbr.readAddress(format) },
533
534 FORM.ref1 => .{ .ref = try fbr.readInt(u8) },
535 FORM.ref2 => .{ .ref = try fbr.readInt(u16) },
536 FORM.ref4 => .{ .ref = try fbr.readInt(u32) },
537 FORM.ref8 => .{ .ref = try fbr.readInt(u64) },
538 FORM.ref_udata => .{ .ref = try fbr.readUleb128(u64) },
539
540 FORM.ref_addr => .{ .ref_addr = try fbr.readAddress(format) },
541 FORM.ref_sig8 => .{ .ref = try fbr.readInt(u64) },
542
543 FORM.string => .{ .string = try fbr.readBytesTo(0) },
544 FORM.strp => .{ .strp = try fbr.readAddress(format) },
545 FORM.strx1 => .{ .strx = try fbr.readInt(u8) },
546 FORM.strx2 => .{ .strx = try fbr.readInt(u16) },
547 FORM.strx3 => .{ .strx = try fbr.readInt(u24) },
548 FORM.strx4 => .{ .strx = try fbr.readInt(u32) },
549 FORM.strx => .{ .strx = try fbr.readUleb128(usize) },
550 FORM.line_strp => .{ .line_strp = try fbr.readAddress(format) },
551 FORM.indirect => parseFormValue(fbr, try fbr.readUleb128(u64), format, implicit_const),
552 FORM.implicit_const => .{ .sdata = implicit_const orelse return badDwarf() },
553 FORM.loclistx => .{ .loclistx = try fbr.readUleb128(u64) },
554 FORM.rnglistx => .{ .rnglistx = try fbr.readUleb128(u64) },
632555 else => {
633 //std.debug.print("unrecognized form id: {x}\n", .{form_id});
556 //debug.print("unrecognized form id: {x}\n", .{form_id});
634557 return badDwarf();
635558 },
636559 };
637560}
638561
639fn getAbbrevTableEntry(abbrev_table: *const AbbrevTable, abbrev_code: u64) ?*const AbbrevTableEntry {
640 for (abbrev_table.items) |*table_entry| {
641 if (table_entry.abbrev_code == abbrev_code) return table_entry;
642 }
643 return null;
644}
645
646562pub const DwarfSection = enum {
647563 debug_info,
648564 debug_abbrev,
......@@ -690,7 +606,7 @@ pub const DwarfInfo = struct {
690606 is_macho: bool,
691607
692608 // Filled later by the initializer
693 abbrev_table_list: std.ArrayListUnmanaged(AbbrevTableHeader) = .{},
609 abbrev_table_list: std.ArrayListUnmanaged(Abbrev.Table) = .{},
694610 compile_unit_list: std.ArrayListUnmanaged(CompileUnit) = .{},
695611 func_list: std.ArrayListUnmanaged(Func) = .{},
696612
......@@ -713,17 +629,17 @@ pub const DwarfInfo = struct {
713629 if (opt_section) |s| if (s.owned) allocator.free(s.data);
714630 }
715631 for (di.abbrev_table_list.items) |*abbrev| {
716 abbrev.deinit();
632 abbrev.deinit(allocator);
717633 }
718634 di.abbrev_table_list.deinit(allocator);
719635 for (di.compile_unit_list.items) |*cu| {
720636 cu.die.deinit(allocator);
721 allocator.destroy(cu.die);
722637 }
723638 di.compile_unit_list.deinit(allocator);
724639 di.func_list.deinit(allocator);
725640 di.cie_map.deinit(allocator);
726641 di.fde_list.deinit(allocator);
642 di.* = undefined;
727643 }
728644
729645 pub fn getSymbolName(di: *DwarfInfo, address: u64) ?[]const u8 {
......@@ -739,102 +655,125 @@ pub const DwarfInfo = struct {
739655 }
740656
741657 fn scanAllFunctions(di: *DwarfInfo, allocator: mem.Allocator) !void {
742 var stream = io.fixedBufferStream(di.section(.debug_info).?);
743 const in = stream.reader();
744 const seekable = stream.seekableStream();
658 var fbr: FixedBufferReader = .{ .buf = di.section(.debug_info).?, .endian = di.endian };
745659 var this_unit_offset: u64 = 0;
746660
747 var tmp_arena = std.heap.ArenaAllocator.init(allocator);
748 defer tmp_arena.deinit();
749 const arena = tmp_arena.allocator();
661 while (this_unit_offset < fbr.buf.len) {
662 try fbr.seekTo(this_unit_offset);
750663
751 while (this_unit_offset < try seekable.getEndPos()) {
752 try seekable.seekTo(this_unit_offset);
664 const unit_header = try readUnitHeader(&fbr);
665 if (unit_header.unit_length == 0) return;
666 const next_offset = unit_header.header_length + unit_header.unit_length;
753667
754 var is_64: bool = undefined;
755 const unit_length = try readUnitLength(in, di.endian, &is_64);
756 if (unit_length == 0) return;
757 const next_offset = unit_length + (if (is_64) @as(usize, 12) else @as(usize, 4));
758
759 const version = try in.readInt(u16, di.endian);
668 const version = try fbr.readInt(u16);
760669 if (version < 2 or version > 5) return badDwarf();
761670
762671 var address_size: u8 = undefined;
763672 var debug_abbrev_offset: u64 = undefined;
764673 if (version >= 5) {
765 const unit_type = try in.readInt(u8, di.endian);
674 const unit_type = try fbr.readInt(u8);
766675 if (unit_type != UT.compile) return badDwarf();
767 address_size = try in.readByte();
768 debug_abbrev_offset = if (is_64)
769 try in.readInt(u64, di.endian)
770 else
771 try in.readInt(u32, di.endian);
676 address_size = try fbr.readByte();
677 debug_abbrev_offset = try fbr.readAddress(unit_header.format);
772678 } else {
773 debug_abbrev_offset = if (is_64)
774 try in.readInt(u64, di.endian)
775 else
776 try in.readInt(u32, di.endian);
777 address_size = try in.readByte();
679 debug_abbrev_offset = try fbr.readAddress(unit_header.format);
680 address_size = try fbr.readByte();
778681 }
779682 if (address_size != @sizeOf(usize)) return badDwarf();
780683
781 const compile_unit_pos = try seekable.getPos();
782684 const abbrev_table = try di.getAbbrevTable(allocator, debug_abbrev_offset);
783685
784 try seekable.seekTo(compile_unit_pos);
686 var max_attrs: usize = 0;
687 var zig_padding_abbrev_code: u7 = 0;
688 for (abbrev_table.abbrevs) |abbrev| {
689 max_attrs = @max(max_attrs, abbrev.attrs.len);
690 if (math.cast(u7, abbrev.code)) |code| {
691 if (abbrev.tag_id == TAG.ZIG_padding and
692 !abbrev.has_children and
693 abbrev.attrs.len == 0)
694 {
695 zig_padding_abbrev_code = code;
696 }
697 }
698 }
699 const attrs_buf = try allocator.alloc(Die.Attr, max_attrs * 3);
700 defer allocator.free(attrs_buf);
701 var attrs_bufs: [3][]Die.Attr = undefined;
702 for (&attrs_bufs, 0..) |*buf, index| buf.* = attrs_buf[index * max_attrs ..][0..max_attrs];
785703
786704 const next_unit_pos = this_unit_offset + next_offset;
787705
788 var compile_unit: CompileUnit = undefined;
706 var compile_unit: CompileUnit = .{
707 .version = version,
708 .format = unit_header.format,
709 .die = undefined,
710 .pc_range = null,
789711
790 while ((try seekable.getPos()) < next_unit_pos) {
791 var die_obj = (try di.parseDie(arena, in, abbrev_table, is_64)) orelse continue;
792 const after_die_offset = try seekable.getPos();
712 .str_offsets_base = 0,
713 .addr_base = 0,
714 .rnglists_base = 0,
715 .loclists_base = 0,
716 .frame_base = null,
717 };
718
719 while (true) {
720 fbr.pos = mem.indexOfNonePos(u8, fbr.buf, fbr.pos, &.{
721 zig_padding_abbrev_code, 0,
722 }) orelse fbr.buf.len;
723 if (fbr.pos >= next_unit_pos) break;
724 var die_obj = (try parseDie(
725 &fbr,
726 attrs_bufs[0],
727 abbrev_table,
728 unit_header.format,
729 )) orelse continue;
793730
794731 switch (die_obj.tag_id) {
795732 TAG.compile_unit => {
796 compile_unit = .{
797 .version = version,
798 .is_64 = is_64,
799 .die = &die_obj,
800 .pc_range = null,
801
802 .str_offsets_base = if (die_obj.getAttr(AT.str_offsets_base)) |fv| try fv.getUInt(usize) else 0,
803 .addr_base = if (die_obj.getAttr(AT.addr_base)) |fv| try fv.getUInt(usize) else 0,
804 .rnglists_base = if (die_obj.getAttr(AT.rnglists_base)) |fv| try fv.getUInt(usize) else 0,
805 .loclists_base = if (die_obj.getAttr(AT.loclists_base)) |fv| try fv.getUInt(usize) else 0,
806 .frame_base = die_obj.getAttr(AT.frame_base),
807 };
733 compile_unit.die = die_obj;
734 compile_unit.die.attrs = attrs_bufs[1][0..die_obj.attrs.len];
735 @memcpy(compile_unit.die.attrs, die_obj.attrs);
736
737 compile_unit.str_offsets_base = if (die_obj.getAttr(AT.str_offsets_base)) |fv| try fv.getUInt(usize) else 0;
738 compile_unit.addr_base = if (die_obj.getAttr(AT.addr_base)) |fv| try fv.getUInt(usize) else 0;
739 compile_unit.rnglists_base = if (die_obj.getAttr(AT.rnglists_base)) |fv| try fv.getUInt(usize) else 0;
740 compile_unit.loclists_base = if (die_obj.getAttr(AT.loclists_base)) |fv| try fv.getUInt(usize) else 0;
741 compile_unit.frame_base = die_obj.getAttr(AT.frame_base);
808742 },
809743 TAG.subprogram, TAG.inlined_subroutine, TAG.subroutine, TAG.entry_point => {
810744 const fn_name = x: {
811 var depth: i32 = 3;
812745 var this_die_obj = die_obj;
813746 // Prevent endless loops
814 while (depth > 0) : (depth -= 1) {
747 for (0..3) |_| {
815748 if (this_die_obj.getAttr(AT.name)) |_| {
816749 break :x try this_die_obj.getAttrString(di, AT.name, di.section(.debug_str), compile_unit);
817750 } else if (this_die_obj.getAttr(AT.abstract_origin)) |_| {
751 const after_die_offset = fbr.pos;
752 defer fbr.pos = after_die_offset;
753
818754 // Follow the DIE it points to and repeat
819755 const ref_offset = try this_die_obj.getAttrRef(AT.abstract_origin);
820756 if (ref_offset > next_offset) return badDwarf();
821 try seekable.seekTo(this_unit_offset + ref_offset);
822 this_die_obj = (try di.parseDie(
823 arena,
824 in,
757 try fbr.seekTo(this_unit_offset + ref_offset);
758 this_die_obj = (try parseDie(
759 &fbr,
760 attrs_bufs[2],
825761 abbrev_table,
826 is_64,
762 unit_header.format,
827763 )) orelse return badDwarf();
828764 } else if (this_die_obj.getAttr(AT.specification)) |_| {
765 const after_die_offset = fbr.pos;
766 defer fbr.pos = after_die_offset;
767
829768 // Follow the DIE it points to and repeat
830769 const ref_offset = try this_die_obj.getAttrRef(AT.specification);
831770 if (ref_offset > next_offset) return badDwarf();
832 try seekable.seekTo(this_unit_offset + ref_offset);
833 this_die_obj = (try di.parseDie(
834 arena,
835 in,
771 try fbr.seekTo(this_unit_offset + ref_offset);
772 this_die_obj = (try parseDie(
773 &fbr,
774 attrs_bufs[2],
836775 abbrev_table,
837 is_64,
776 unit_header.format,
838777 )) orelse return badDwarf();
839778 } else {
840779 break :x null;
......@@ -847,15 +786,12 @@ pub const DwarfInfo = struct {
847786 var range_added = if (die_obj.getAttrAddr(di, AT.low_pc, compile_unit)) |low_pc| blk: {
848787 if (die_obj.getAttr(AT.high_pc)) |high_pc_value| {
849788 const pc_end = switch (high_pc_value.*) {
850 FormValue.Address => |value| value,
851 FormValue.Const => |value| b: {
852 const offset = try value.asUnsignedLe();
853 break :b (low_pc + offset);
854 },
789 .addr => |value| value,
790 .udata => |offset| low_pc + offset,
855791 else => return badDwarf(),
856792 };
857793
858 try di.func_list.append(allocator, Func{
794 try di.func_list.append(allocator, .{
859795 .name = fn_name,
860796 .pc_range = .{
861797 .start = low_pc,
......@@ -880,7 +816,7 @@ pub const DwarfInfo = struct {
880816
881817 while (try iter.next()) |range| {
882818 range_added = true;
883 try di.func_list.append(allocator, Func{
819 try di.func_list.append(allocator, .{
884820 .name = fn_name,
885821 .pc_range = .{
886822 .start = range.start_addr,
......@@ -891,7 +827,7 @@ pub const DwarfInfo = struct {
891827 }
892828
893829 if (fn_name != null and !range_added) {
894 try di.func_list.append(allocator, Func{
830 try di.func_list.append(allocator, .{
895831 .name = fn_name,
896832 .pc_range = null,
897833 });
......@@ -899,8 +835,6 @@ pub const DwarfInfo = struct {
899835 },
900836 else => {},
901837 }
902
903 try seekable.seekTo(after_die_offset);
904838 }
905839
906840 this_unit_offset += next_offset;
......@@ -908,56 +842,57 @@ pub const DwarfInfo = struct {
908842 }
909843
910844 fn scanAllCompileUnits(di: *DwarfInfo, allocator: mem.Allocator) !void {
911 var stream = io.fixedBufferStream(di.section(.debug_info).?);
912 const in = stream.reader();
913 const seekable = stream.seekableStream();
845 var fbr: FixedBufferReader = .{ .buf = di.section(.debug_info).?, .endian = di.endian };
914846 var this_unit_offset: u64 = 0;
915847
916 while (this_unit_offset < try seekable.getEndPos()) {
917 try seekable.seekTo(this_unit_offset);
848 var attrs_buf = std.ArrayList(Die.Attr).init(allocator);
849 defer attrs_buf.deinit();
850
851 while (this_unit_offset < fbr.buf.len) {
852 try fbr.seekTo(this_unit_offset);
918853
919 var is_64: bool = undefined;
920 const unit_length = try readUnitLength(in, di.endian, &is_64);
921 if (unit_length == 0) return;
922 const next_offset = unit_length + (if (is_64) @as(usize, 12) else @as(usize, 4));
854 const unit_header = try readUnitHeader(&fbr);
855 if (unit_header.unit_length == 0) return;
856 const next_offset = unit_header.header_length + unit_header.unit_length;
923857
924 const version = try in.readInt(u16, di.endian);
858 const version = try fbr.readInt(u16);
925859 if (version < 2 or version > 5) return badDwarf();
926860
927861 var address_size: u8 = undefined;
928862 var debug_abbrev_offset: u64 = undefined;
929863 if (version >= 5) {
930 const unit_type = try in.readInt(u8, di.endian);
864 const unit_type = try fbr.readInt(u8);
931865 if (unit_type != UT.compile) return badDwarf();
932 address_size = try in.readByte();
933 debug_abbrev_offset = if (is_64)
934 try in.readInt(u64, di.endian)
935 else
936 try in.readInt(u32, di.endian);
866 address_size = try fbr.readByte();
867 debug_abbrev_offset = try fbr.readAddress(unit_header.format);
937868 } else {
938 debug_abbrev_offset = if (is_64)
939 try in.readInt(u64, di.endian)
940 else
941 try in.readInt(u32, di.endian);
942 address_size = try in.readByte();
869 debug_abbrev_offset = try fbr.readAddress(unit_header.format);
870 address_size = try fbr.readByte();
943871 }
944872 if (address_size != @sizeOf(usize)) return badDwarf();
945873
946 const compile_unit_pos = try seekable.getPos();
947874 const abbrev_table = try di.getAbbrevTable(allocator, debug_abbrev_offset);
948875
949 try seekable.seekTo(compile_unit_pos);
876 var max_attrs: usize = 0;
877 for (abbrev_table.abbrevs) |abbrev| {
878 max_attrs = @max(max_attrs, abbrev.attrs.len);
879 }
880 try attrs_buf.resize(max_attrs);
950881
951 const compile_unit_die = try allocator.create(Die);
952 errdefer allocator.destroy(compile_unit_die);
953 compile_unit_die.* = (try di.parseDie(allocator, in, abbrev_table, is_64)) orelse
954 return badDwarf();
882 var compile_unit_die = (try parseDie(
883 &fbr,
884 attrs_buf.items,
885 abbrev_table,
886 unit_header.format,
887 )) orelse return badDwarf();
955888
956889 if (compile_unit_die.tag_id != TAG.compile_unit) return badDwarf();
957890
891 compile_unit_die.attrs = try allocator.dupe(Die.Attr, compile_unit_die.attrs);
892
958893 var compile_unit: CompileUnit = .{
959894 .version = version,
960 .is_64 = is_64,
895 .format = unit_header.format,
961896 .pc_range = null,
962897 .die = compile_unit_die,
963898 .str_offsets_base = if (compile_unit_die.getAttr(AT.str_offsets_base)) |fv| try fv.getUInt(usize) else 0,
......@@ -971,11 +906,8 @@ pub const DwarfInfo = struct {
971906 if (compile_unit_die.getAttrAddr(di, AT.low_pc, compile_unit)) |low_pc| {
972907 if (compile_unit_die.getAttr(AT.high_pc)) |high_pc_value| {
973908 const pc_end = switch (high_pc_value.*) {
974 FormValue.Address => |value| value,
975 FormValue.Const => |value| b: {
976 const offset = try value.asUnsignedLe();
977 break :b (low_pc + offset);
978 },
909 .addr => |value| value,
910 .udata => |offset| low_pc + offset,
979911 else => return badDwarf(),
980912 };
981913 break :x PcRange{
......@@ -1002,40 +934,39 @@ pub const DwarfInfo = struct {
1002934 section_type: DwarfSection,
1003935 di: *const DwarfInfo,
1004936 compile_unit: *const CompileUnit,
1005 stream: io.FixedBufferStream([]const u8),
937 fbr: FixedBufferReader,
1006938
1007939 pub fn init(ranges_value: *const FormValue, di: *const DwarfInfo, compile_unit: *const CompileUnit) !@This() {
1008940 const section_type = if (compile_unit.version >= 5) DwarfSection.debug_rnglists else DwarfSection.debug_ranges;
1009941 const debug_ranges = di.section(section_type) orelse return error.MissingDebugInfo;
1010942
1011943 const ranges_offset = switch (ranges_value.*) {
1012 .SecOffset => |off| off,
1013 .Const => |c| try c.asUnsignedLe(),
1014 .RangeListOffset => |idx| off: {
1015 if (compile_unit.is_64) {
1016 const offset_loc = @as(usize, @intCast(compile_unit.rnglists_base + 8 * idx));
1017 if (offset_loc + 8 > debug_ranges.len) return badDwarf();
1018 const offset = mem.readInt(u64, debug_ranges[offset_loc..][0..8], di.endian);
1019 break :off compile_unit.rnglists_base + offset;
1020 } else {
1021 const offset_loc = @as(usize, @intCast(compile_unit.rnglists_base + 4 * idx));
1022 if (offset_loc + 4 > debug_ranges.len) return badDwarf();
1023 const offset = mem.readInt(u32, debug_ranges[offset_loc..][0..4], di.endian);
1024 break :off compile_unit.rnglists_base + offset;
944 .sec_offset, .udata => |off| off,
945 .rnglistx => |idx| off: {
946 switch (compile_unit.format) {
947 .@"32" => {
948 const offset_loc = @as(usize, @intCast(compile_unit.rnglists_base + 4 * idx));
949 if (offset_loc + 4 > debug_ranges.len) return badDwarf();
950 const offset = mem.readInt(u32, debug_ranges[offset_loc..][0..4], di.endian);
951 break :off compile_unit.rnglists_base + offset;
952 },
953 .@"64" => {
954 const offset_loc = @as(usize, @intCast(compile_unit.rnglists_base + 8 * idx));
955 if (offset_loc + 8 > debug_ranges.len) return badDwarf();
956 const offset = mem.readInt(u64, debug_ranges[offset_loc..][0..8], di.endian);
957 break :off compile_unit.rnglists_base + offset;
958 },
1025959 }
1026960 },
1027961 else => return badDwarf(),
1028962 };
1029963
1030 var stream = io.fixedBufferStream(debug_ranges);
1031 try stream.seekTo(ranges_offset);
1032
1033964 // All the addresses in the list are relative to the value
1034965 // specified by DW_AT.low_pc or to some other value encoded
1035966 // in the list itself.
1036967 // If no starting value is specified use zero.
1037968 const base_address = compile_unit.die.getAttrAddr(di, AT.low_pc, compile_unit.*) catch |err| switch (err) {
1038 error.MissingDebugInfo => @as(u64, 0), // TODO https://github.com/ziglang/zig/issues/11135
969 error.MissingDebugInfo => 0,
1039970 else => return err,
1040971 };
1041972
......@@ -1044,28 +975,31 @@ pub const DwarfInfo = struct {
1044975 .section_type = section_type,
1045976 .di = di,
1046977 .compile_unit = compile_unit,
1047 .stream = stream,
978 .fbr = .{
979 .buf = debug_ranges,
980 .pos = math.cast(usize, ranges_offset) orelse return badDwarf(),
981 .endian = di.endian,
982 },
1048983 };
1049984 }
1050985
1051986 // Returns the next range in the list, or null if the end was reached.
1052987 pub fn next(self: *@This()) !?struct { start_addr: u64, end_addr: u64 } {
1053 const in = self.stream.reader();
1054988 switch (self.section_type) {
1055989 .debug_rnglists => {
1056 const kind = try in.readByte();
990 const kind = try self.fbr.readByte();
1057991 switch (kind) {
1058992 RLE.end_of_list => return null,
1059993 RLE.base_addressx => {
1060 const index = try leb.readULEB128(usize, in);
994 const index = try self.fbr.readUleb128(usize);
1061995 self.base_address = try self.di.readDebugAddr(self.compile_unit.*, index);
1062996 return try self.next();
1063997 },
1064998 RLE.startx_endx => {
1065 const start_index = try leb.readULEB128(usize, in);
999 const start_index = try self.fbr.readUleb128(usize);
10661000 const start_addr = try self.di.readDebugAddr(self.compile_unit.*, start_index);
10671001
1068 const end_index = try leb.readULEB128(usize, in);
1002 const end_index = try self.fbr.readUleb128(usize);
10691003 const end_addr = try self.di.readDebugAddr(self.compile_unit.*, end_index);
10701004
10711005 return .{
......@@ -1074,10 +1008,10 @@ pub const DwarfInfo = struct {
10741008 };
10751009 },
10761010 RLE.startx_length => {
1077 const start_index = try leb.readULEB128(usize, in);
1011 const start_index = try self.fbr.readUleb128(usize);
10781012 const start_addr = try self.di.readDebugAddr(self.compile_unit.*, start_index);
10791013
1080 const len = try leb.readULEB128(usize, in);
1014 const len = try self.fbr.readUleb128(usize);
10811015 const end_addr = start_addr + len;
10821016
10831017 return .{
......@@ -1086,8 +1020,8 @@ pub const DwarfInfo = struct {
10861020 };
10871021 },
10881022 RLE.offset_pair => {
1089 const start_addr = try leb.readULEB128(usize, in);
1090 const end_addr = try leb.readULEB128(usize, in);
1023 const start_addr = try self.fbr.readUleb128(usize);
1024 const end_addr = try self.fbr.readUleb128(usize);
10911025
10921026 // This is the only kind that uses the base address
10931027 return .{
......@@ -1096,12 +1030,12 @@ pub const DwarfInfo = struct {
10961030 };
10971031 },
10981032 RLE.base_address => {
1099 self.base_address = try in.readInt(usize, self.di.endian);
1033 self.base_address = try self.fbr.readInt(usize);
11001034 return try self.next();
11011035 },
11021036 RLE.start_end => {
1103 const start_addr = try in.readInt(usize, self.di.endian);
1104 const end_addr = try in.readInt(usize, self.di.endian);
1037 const start_addr = try self.fbr.readInt(usize);
1038 const end_addr = try self.fbr.readInt(usize);
11051039
11061040 return .{
11071041 .start_addr = start_addr,
......@@ -1109,8 +1043,8 @@ pub const DwarfInfo = struct {
11091043 };
11101044 },
11111045 RLE.start_length => {
1112 const start_addr = try in.readInt(usize, self.di.endian);
1113 const len = try leb.readULEB128(usize, in);
1046 const start_addr = try self.fbr.readInt(usize);
1047 const len = try self.fbr.readUleb128(usize);
11141048 const end_addr = start_addr + len;
11151049
11161050 return .{
......@@ -1122,8 +1056,8 @@ pub const DwarfInfo = struct {
11221056 }
11231057 },
11241058 .debug_ranges => {
1125 const start_addr = try in.readInt(usize, self.di.endian);
1126 const end_addr = try in.readInt(usize, self.di.endian);
1059 const start_addr = try self.fbr.readInt(usize);
1060 const end_addr = try self.fbr.readInt(usize);
11271061 if (start_addr == 0 and end_addr == 0) return null;
11281062
11291063 // This entry selects a new value for the base address
......@@ -1160,93 +1094,96 @@ pub const DwarfInfo = struct {
11601094
11611095 /// Gets an already existing AbbrevTable given the abbrev_offset, or if not found,
11621096 /// seeks in the stream and parses it.
1163 fn getAbbrevTable(di: *DwarfInfo, allocator: mem.Allocator, abbrev_offset: u64) !*const AbbrevTable {
1164 for (di.abbrev_table_list.items) |*header| {
1165 if (header.offset == abbrev_offset) {
1166 return &header.table;
1097 fn getAbbrevTable(di: *DwarfInfo, allocator: mem.Allocator, abbrev_offset: u64) !*const Abbrev.Table {
1098 for (di.abbrev_table_list.items) |*table| {
1099 if (table.offset == abbrev_offset) {
1100 return table;
11671101 }
11681102 }
1169 try di.abbrev_table_list.append(allocator, AbbrevTableHeader{
1170 .offset = abbrev_offset,
1171 .table = try di.parseAbbrevTable(allocator, abbrev_offset),
1172 });
1173 return &di.abbrev_table_list.items[di.abbrev_table_list.items.len - 1].table;
1103 try di.abbrev_table_list.append(
1104 allocator,
1105 try di.parseAbbrevTable(allocator, abbrev_offset),
1106 );
1107 return &di.abbrev_table_list.items[di.abbrev_table_list.items.len - 1];
11741108 }
11751109
1176 fn parseAbbrevTable(di: *DwarfInfo, allocator: mem.Allocator, offset: u64) !AbbrevTable {
1177 var stream = io.fixedBufferStream(di.section(.debug_abbrev).?);
1178 const in = stream.reader();
1179 const seekable = stream.seekableStream();
1110 fn parseAbbrevTable(di: *DwarfInfo, allocator: mem.Allocator, offset: u64) !Abbrev.Table {
1111 var fbr: FixedBufferReader = .{
1112 .buf = di.section(.debug_abbrev).?,
1113 .pos = math.cast(usize, offset) orelse return badDwarf(),
1114 .endian = di.endian,
1115 };
11801116
1181 try seekable.seekTo(offset);
1182 var result = AbbrevTable.init(allocator);
1183 errdefer {
1184 for (result.items) |*entry| {
1185 entry.attrs.deinit();
1117 var abbrevs = std.ArrayList(Abbrev).init(allocator);
1118 defer {
1119 for (abbrevs.items) |*abbrev| {
1120 abbrev.deinit(allocator);
11861121 }
1187 result.deinit();
1122 abbrevs.deinit();
11881123 }
11891124
1125 var attrs = std.ArrayList(Abbrev.Attr).init(allocator);
1126 defer attrs.deinit();
1127
11901128 while (true) {
1191 const abbrev_code = try leb.readULEB128(u64, in);
1192 if (abbrev_code == 0) return result;
1193 try result.append(AbbrevTableEntry{
1194 .abbrev_code = abbrev_code,
1195 .tag_id = try leb.readULEB128(u64, in),
1196 .has_children = (try in.readByte()) == CHILDREN.yes,
1197 .attrs = std.ArrayList(AbbrevAttr).init(allocator),
1198 });
1199 const attrs = &result.items[result.items.len - 1].attrs;
1129 const code = try fbr.readUleb128(u64);
1130 if (code == 0) break;
1131 const tag_id = try fbr.readUleb128(u64);
1132 const has_children = (try fbr.readByte()) == CHILDREN.yes;
12001133
12011134 while (true) {
1202 const attr_id = try leb.readULEB128(u64, in);
1203 const form_id = try leb.readULEB128(u64, in);
1135 const attr_id = try fbr.readUleb128(u64);
1136 const form_id = try fbr.readUleb128(u64);
12041137 if (attr_id == 0 and form_id == 0) break;
1205 // DW_FORM_implicit_const stores its value immediately after the attribute pair :(
1206 const payload = if (form_id == FORM.implicit_const) try leb.readILEB128(i64, in) else undefined;
1207 try attrs.append(AbbrevAttr{
1208 .attr_id = attr_id,
1138 try attrs.append(.{
1139 .id = attr_id,
12091140 .form_id = form_id,
1210 .payload = payload,
1141 .payload = switch (form_id) {
1142 FORM.implicit_const => try fbr.readIleb128(i64),
1143 else => undefined,
1144 },
12111145 });
12121146 }
1147
1148 try abbrevs.append(.{
1149 .code = code,
1150 .tag_id = tag_id,
1151 .has_children = has_children,
1152 .attrs = try attrs.toOwnedSlice(),
1153 });
12131154 }
1155
1156 return .{
1157 .offset = offset,
1158 .abbrevs = try abbrevs.toOwnedSlice(),
1159 };
12141160 }
12151161
12161162 fn parseDie(
1217 di: *DwarfInfo,
1218 allocator: mem.Allocator,
1219 in_stream: anytype,
1220 abbrev_table: *const AbbrevTable,
1221 is_64: bool,
1163 fbr: *FixedBufferReader,
1164 attrs_buf: []Die.Attr,
1165 abbrev_table: *const Abbrev.Table,
1166 format: Format,
12221167 ) !?Die {
1223 const abbrev_code = try leb.readULEB128(u64, in_stream);
1168 const abbrev_code = try fbr.readUleb128(u64);
12241169 if (abbrev_code == 0) return null;
1225 const table_entry = getAbbrevTableEntry(abbrev_table, abbrev_code) orelse return badDwarf();
1226
1227 var result = Die{
1228 // Lives as long as the Die.
1229 .arena = std.heap.ArenaAllocator.init(allocator),
1170 const table_entry = abbrev_table.get(abbrev_code) orelse return badDwarf();
1171
1172 const attrs = attrs_buf[0..table_entry.attrs.len];
1173 for (attrs, table_entry.attrs) |*result_attr, attr| result_attr.* = Die.Attr{
1174 .id = attr.id,
1175 .value = try parseFormValue(
1176 fbr,
1177 attr.form_id,
1178 format,
1179 attr.payload,
1180 ),
1181 };
1182 return .{
12301183 .tag_id = table_entry.tag_id,
12311184 .has_children = table_entry.has_children,
1185 .attrs = attrs,
12321186 };
1233 try result.attrs.resize(allocator, table_entry.attrs.items.len);
1234 for (table_entry.attrs.items, 0..) |attr, i| {
1235 result.attrs.items[i] = Die.Attr{
1236 .id = attr.attr_id,
1237 .value = try parseFormValue(
1238 result.arena.allocator(),
1239 in_stream,
1240 attr.form_id,
1241 di.endian,
1242 is_64,
1243 ),
1244 };
1245 if (attr.form_id == FORM.implicit_const) {
1246 result.attrs.items[i].value.Const.payload = @as(u64, @bitCast(attr.payload));
1247 }
1248 }
1249 return result;
12501187 }
12511188
12521189 pub fn getLineNumberInfo(
......@@ -1255,50 +1192,47 @@ pub const DwarfInfo = struct {
12551192 compile_unit: CompileUnit,
12561193 target_address: u64,
12571194 ) !debug.LineInfo {
1258 var stream = io.fixedBufferStream(di.section(.debug_line).?);
1259 const in = stream.reader();
1260 const seekable = stream.seekableStream();
1261
12621195 const compile_unit_cwd = try compile_unit.die.getAttrString(di, AT.comp_dir, di.section(.debug_line_str), compile_unit);
12631196 const line_info_offset = try compile_unit.die.getAttrSecOffset(AT.stmt_list);
12641197
1265 try seekable.seekTo(line_info_offset);
1198 var fbr: FixedBufferReader = .{ .buf = di.section(.debug_line).?, .endian = di.endian };
1199 try fbr.seekTo(line_info_offset);
12661200
1267 var is_64: bool = undefined;
1268 const unit_length = try readUnitLength(in, di.endian, &is_64);
1269 if (unit_length == 0) {
1270 return missingDwarf();
1271 }
1272 const next_offset = unit_length + (if (is_64) @as(usize, 12) else @as(usize, 4));
1201 const unit_header = try readUnitHeader(&fbr);
1202 if (unit_header.unit_length == 0) return missingDwarf();
1203 const next_offset = unit_header.header_length + unit_header.unit_length;
12731204
1274 const version = try in.readInt(u16, di.endian);
1205 const version = try fbr.readInt(u16);
12751206 if (version < 2) return badDwarf();
12761207
1277 var addr_size: u8 = if (is_64) 8 else 4;
1208 var addr_size: u8 = switch (unit_header.format) {
1209 .@"32" => 4,
1210 .@"64" => 8,
1211 };
12781212 var seg_size: u8 = 0;
12791213 if (version >= 5) {
1280 addr_size = try in.readByte();
1281 seg_size = try in.readByte();
1214 addr_size = try fbr.readByte();
1215 seg_size = try fbr.readByte();
12821216 }
12831217
1284 const prologue_length = if (is_64) try in.readInt(u64, di.endian) else try in.readInt(u32, di.endian);
1285 const prog_start_offset = (try seekable.getPos()) + prologue_length;
1218 const prologue_length = try fbr.readAddress(unit_header.format);
1219 const prog_start_offset = fbr.pos + prologue_length;
12861220
1287 const minimum_instruction_length = try in.readByte();
1221 const minimum_instruction_length = try fbr.readByte();
12881222 if (minimum_instruction_length == 0) return badDwarf();
12891223
12901224 if (version >= 4) {
12911225 // maximum_operations_per_instruction
1292 _ = try in.readByte();
1226 _ = try fbr.readByte();
12931227 }
12941228
1295 const default_is_stmt = (try in.readByte()) != 0;
1296 const line_base = try in.readByteSigned();
1229 const default_is_stmt = (try fbr.readByte()) != 0;
1230 const line_base = try fbr.readByteSigned();
12971231
1298 const line_range = try in.readByte();
1232 const line_range = try fbr.readByte();
12991233 if (line_range == 0) return badDwarf();
13001234
1301 const opcode_base = try in.readByte();
1235 const opcode_base = try fbr.readByte();
13021236
13031237 const standard_opcode_lengths = try allocator.alloc(u8, opcode_base - 1);
13041238 defer allocator.free(standard_opcode_lengths);
......@@ -1306,33 +1240,31 @@ pub const DwarfInfo = struct {
13061240 {
13071241 var i: usize = 0;
13081242 while (i < opcode_base - 1) : (i += 1) {
1309 standard_opcode_lengths[i] = try in.readByte();
1243 standard_opcode_lengths[i] = try fbr.readByte();
13101244 }
13111245 }
13121246
1313 var tmp_arena = std.heap.ArenaAllocator.init(allocator);
1314 defer tmp_arena.deinit();
1315 const arena = tmp_arena.allocator();
1316
1317 var include_directories = std.ArrayList(FileEntry).init(arena);
1318 var file_entries = std.ArrayList(FileEntry).init(arena);
1247 var include_directories = std.ArrayList(FileEntry).init(allocator);
1248 defer include_directories.deinit();
1249 var file_entries = std.ArrayList(FileEntry).init(allocator);
1250 defer file_entries.deinit();
13191251
13201252 if (version < 5) {
13211253 try include_directories.append(.{ .path = compile_unit_cwd });
13221254
13231255 while (true) {
1324 const dir = try in.readUntilDelimiterAlloc(arena, 0, math.maxInt(usize));
1256 const dir = try fbr.readBytesTo(0);
13251257 if (dir.len == 0) break;
13261258 try include_directories.append(.{ .path = dir });
13271259 }
13281260
13291261 while (true) {
1330 const file_name = try in.readUntilDelimiterAlloc(arena, 0, math.maxInt(usize));
1262 const file_name = try fbr.readBytesTo(0);
13311263 if (file_name.len == 0) break;
1332 const dir_index = try leb.readULEB128(u32, in);
1333 const mtime = try leb.readULEB128(u64, in);
1334 const size = try leb.readULEB128(u64, in);
1335 try file_entries.append(FileEntry{
1264 const dir_index = try fbr.readUleb128(u32);
1265 const mtime = try fbr.readUleb128(u64);
1266 const size = try fbr.readUleb128(u64);
1267 try file_entries.append(.{
13361268 .path = file_name,
13371269 .dir_index = dir_index,
13381270 .mtime = mtime,
......@@ -1346,16 +1278,16 @@ pub const DwarfInfo = struct {
13461278 };
13471279 {
13481280 var dir_ent_fmt_buf: [10]FileEntFmt = undefined;
1349 const directory_entry_format_count = try in.readByte();
1281 const directory_entry_format_count = try fbr.readByte();
13501282 if (directory_entry_format_count > dir_ent_fmt_buf.len) return badDwarf();
13511283 for (dir_ent_fmt_buf[0..directory_entry_format_count]) |*ent_fmt| {
13521284 ent_fmt.* = .{
1353 .content_type_code = try leb.readULEB128(u8, in),
1354 .form_code = try leb.readULEB128(u16, in),
1285 .content_type_code = try fbr.readUleb128(u8),
1286 .form_code = try fbr.readUleb128(u16),
13551287 };
13561288 }
13571289
1358 const directories_count = try leb.readULEB128(usize, in);
1290 const directories_count = try fbr.readUleb128(usize);
13591291 try include_directories.ensureUnusedCapacity(directories_count);
13601292 {
13611293 var i: usize = 0;
......@@ -1363,18 +1295,20 @@ pub const DwarfInfo = struct {
13631295 var e: FileEntry = .{ .path = &.{} };
13641296 for (dir_ent_fmt_buf[0..directory_entry_format_count]) |ent_fmt| {
13651297 const form_value = try parseFormValue(
1366 arena,
1367 in,
1298 &fbr,
13681299 ent_fmt.form_code,
1369 di.endian,
1370 is_64,
1300 unit_header.format,
1301 null,
13711302 );
13721303 switch (ent_fmt.content_type_code) {
13731304 LNCT.path => e.path = try form_value.getString(di.*),
13741305 LNCT.directory_index => e.dir_index = try form_value.getUInt(u32),
13751306 LNCT.timestamp => e.mtime = try form_value.getUInt(u64),
13761307 LNCT.size => e.size = try form_value.getUInt(u64),
1377 LNCT.MD5 => e.md5 = try form_value.getData16(),
1308 LNCT.MD5 => e.md5 = switch (form_value) {
1309 .data16 => |data16| data16.*,
1310 else => return badDwarf(),
1311 },
13781312 else => continue,
13791313 }
13801314 }
......@@ -1384,16 +1318,16 @@ pub const DwarfInfo = struct {
13841318 }
13851319
13861320 var file_ent_fmt_buf: [10]FileEntFmt = undefined;
1387 const file_name_entry_format_count = try in.readByte();
1321 const file_name_entry_format_count = try fbr.readByte();
13881322 if (file_name_entry_format_count > file_ent_fmt_buf.len) return badDwarf();
13891323 for (file_ent_fmt_buf[0..file_name_entry_format_count]) |*ent_fmt| {
13901324 ent_fmt.* = .{
1391 .content_type_code = try leb.readULEB128(u8, in),
1392 .form_code = try leb.readULEB128(u16, in),
1325 .content_type_code = try fbr.readUleb128(u8),
1326 .form_code = try fbr.readUleb128(u16),
13931327 };
13941328 }
13951329
1396 const file_names_count = try leb.readULEB128(usize, in);
1330 const file_names_count = try fbr.readUleb128(usize);
13971331 try file_entries.ensureUnusedCapacity(file_names_count);
13981332 {
13991333 var i: usize = 0;
......@@ -1401,18 +1335,20 @@ pub const DwarfInfo = struct {
14011335 var e: FileEntry = .{ .path = &.{} };
14021336 for (file_ent_fmt_buf[0..file_name_entry_format_count]) |ent_fmt| {
14031337 const form_value = try parseFormValue(
1404 arena,
1405 in,
1338 &fbr,
14061339 ent_fmt.form_code,
1407 di.endian,
1408 is_64,
1340 unit_header.format,
1341 null,
14091342 );
14101343 switch (ent_fmt.content_type_code) {
14111344 LNCT.path => e.path = try form_value.getString(di.*),
14121345 LNCT.directory_index => e.dir_index = try form_value.getUInt(u32),
14131346 LNCT.timestamp => e.mtime = try form_value.getUInt(u64),
14141347 LNCT.size => e.size = try form_value.getUInt(u64),
1415 LNCT.MD5 => e.md5 = try form_value.getData16(),
1348 LNCT.MD5 => e.md5 = switch (form_value) {
1349 .data16 => |data16| data16.*,
1350 else => return badDwarf(),
1351 },
14161352 else => continue,
14171353 }
14181354 }
......@@ -1428,17 +1364,17 @@ pub const DwarfInfo = struct {
14281364 version,
14291365 );
14301366
1431 try seekable.seekTo(prog_start_offset);
1367 try fbr.seekTo(prog_start_offset);
14321368
14331369 const next_unit_pos = line_info_offset + next_offset;
14341370
1435 while ((try seekable.getPos()) < next_unit_pos) {
1436 const opcode = try in.readByte();
1371 while (fbr.pos < next_unit_pos) {
1372 const opcode = try fbr.readByte();
14371373
14381374 if (opcode == LNS.extended_op) {
1439 const op_size = try leb.readULEB128(u64, in);
1375 const op_size = try fbr.readUleb128(u64);
14401376 if (op_size < 1) return badDwarf();
1441 const sub_op = try in.readByte();
1377 const sub_op = try fbr.readByte();
14421378 switch (sub_op) {
14431379 LNE.end_sequence => {
14441380 prog.end_sequence = true;
......@@ -1446,25 +1382,22 @@ pub const DwarfInfo = struct {
14461382 prog.reset();
14471383 },
14481384 LNE.set_address => {
1449 const addr = try in.readInt(usize, di.endian);
1385 const addr = try fbr.readInt(usize);
14501386 prog.address = addr;
14511387 },
14521388 LNE.define_file => {
1453 const path = try in.readUntilDelimiterAlloc(arena, 0, math.maxInt(usize));
1454 const dir_index = try leb.readULEB128(u32, in);
1455 const mtime = try leb.readULEB128(u64, in);
1456 const size = try leb.readULEB128(u64, in);
1457 try file_entries.append(FileEntry{
1389 const path = try fbr.readBytesTo(0);
1390 const dir_index = try fbr.readUleb128(u32);
1391 const mtime = try fbr.readUleb128(u64);
1392 const size = try fbr.readUleb128(u64);
1393 try file_entries.append(.{
14581394 .path = path,
14591395 .dir_index = dir_index,
14601396 .mtime = mtime,
14611397 .size = size,
14621398 });
14631399 },
1464 else => {
1465 const fwd_amt = math.cast(isize, op_size - 1) orelse return badDwarf();
1466 try seekable.seekBy(fwd_amt);
1467 },
1400 else => try fbr.seekForward(op_size - 1),
14681401 }
14691402 } else if (opcode >= opcode_base) {
14701403 // special opcodes
......@@ -1482,19 +1415,19 @@ pub const DwarfInfo = struct {
14821415 prog.basic_block = false;
14831416 },
14841417 LNS.advance_pc => {
1485 const arg = try leb.readULEB128(usize, in);
1418 const arg = try fbr.readUleb128(usize);
14861419 prog.address += arg * minimum_instruction_length;
14871420 },
14881421 LNS.advance_line => {
1489 const arg = try leb.readILEB128(i64, in);
1422 const arg = try fbr.readIleb128(i64);
14901423 prog.line += arg;
14911424 },
14921425 LNS.set_file => {
1493 const arg = try leb.readULEB128(usize, in);
1426 const arg = try fbr.readUleb128(usize);
14941427 prog.file = arg;
14951428 },
14961429 LNS.set_column => {
1497 const arg = try leb.readULEB128(u64, in);
1430 const arg = try fbr.readUleb128(u64);
14981431 prog.column = arg;
14991432 },
15001433 LNS.negate_stmt => {
......@@ -1508,14 +1441,13 @@ pub const DwarfInfo = struct {
15081441 prog.address += inc_addr;
15091442 },
15101443 LNS.fixed_advance_pc => {
1511 const arg = try in.readInt(u16, di.endian);
1444 const arg = try fbr.readInt(u16);
15121445 prog.address += arg;
15131446 },
15141447 LNS.set_prologue_end => {},
15151448 else => {
15161449 if (opcode - 1 >= standard_opcode_lengths.len) return badDwarf();
1517 const len_bytes = standard_opcode_lengths[opcode - 1];
1518 try seekable.seekBy(len_bytes);
1450 try fbr.seekForward(standard_opcode_lengths[opcode - 1]);
15191451 },
15201452 }
15211453 }
......@@ -1524,11 +1456,11 @@ pub const DwarfInfo = struct {
15241456 return missingDwarf();
15251457 }
15261458
1527 fn getString(di: DwarfInfo, offset: u64) ![]const u8 {
1459 fn getString(di: DwarfInfo, offset: u64) ![:0]const u8 {
15281460 return getStringGeneric(di.section(.debug_str), offset);
15291461 }
15301462
1531 fn getLineString(di: DwarfInfo, offset: u64) ![]const u8 {
1463 fn getLineString(di: DwarfInfo, offset: u64) ![:0]const u8 {
15321464 return getStringGeneric(di.section(.debug_line_str), offset);
15331465 }
15341466
......@@ -1564,38 +1496,37 @@ pub const DwarfInfo = struct {
15641496 /// of FDEs is built for binary searching during unwinding.
15651497 pub fn scanAllUnwindInfo(di: *DwarfInfo, allocator: mem.Allocator, base_address: usize) !void {
15661498 if (di.section(.eh_frame_hdr)) |eh_frame_hdr| blk: {
1567 var stream = io.fixedBufferStream(eh_frame_hdr);
1568 const reader = stream.reader();
1499 var fbr: FixedBufferReader = .{ .buf = eh_frame_hdr, .endian = native_endian };
15691500
1570 const version = try reader.readByte();
1501 const version = try fbr.readByte();
15711502 if (version != 1) break :blk;
15721503
1573 const eh_frame_ptr_enc = try reader.readByte();
1504 const eh_frame_ptr_enc = try fbr.readByte();
15741505 if (eh_frame_ptr_enc == EH.PE.omit) break :blk;
1575 const fde_count_enc = try reader.readByte();
1506 const fde_count_enc = try fbr.readByte();
15761507 if (fde_count_enc == EH.PE.omit) break :blk;
1577 const table_enc = try reader.readByte();
1508 const table_enc = try fbr.readByte();
15781509 if (table_enc == EH.PE.omit) break :blk;
15791510
1580 const eh_frame_ptr = std.math.cast(usize, try readEhPointer(reader, eh_frame_ptr_enc, @sizeOf(usize), .{
1581 .pc_rel_base = @intFromPtr(&eh_frame_hdr[stream.pos]),
1511 const eh_frame_ptr = math.cast(usize, try readEhPointer(&fbr, eh_frame_ptr_enc, @sizeOf(usize), .{
1512 .pc_rel_base = @intFromPtr(&eh_frame_hdr[fbr.pos]),
15821513 .follow_indirect = true,
1583 }, builtin.cpu.arch.endian()) orelse return badDwarf()) orelse return badDwarf();
1514 }) orelse return badDwarf()) orelse return badDwarf();
15841515
1585 const fde_count = std.math.cast(usize, try readEhPointer(reader, fde_count_enc, @sizeOf(usize), .{
1586 .pc_rel_base = @intFromPtr(&eh_frame_hdr[stream.pos]),
1516 const fde_count = math.cast(usize, try readEhPointer(&fbr, fde_count_enc, @sizeOf(usize), .{
1517 .pc_rel_base = @intFromPtr(&eh_frame_hdr[fbr.pos]),
15871518 .follow_indirect = true,
1588 }, builtin.cpu.arch.endian()) orelse return badDwarf()) orelse return badDwarf();
1519 }) orelse return badDwarf()) orelse return badDwarf();
15891520
15901521 const entry_size = try ExceptionFrameHeader.entrySize(table_enc);
15911522 const entries_len = fde_count * entry_size;
1592 if (entries_len > eh_frame_hdr.len - stream.pos) return badDwarf();
1523 if (entries_len > eh_frame_hdr.len - fbr.pos) return badDwarf();
15931524
15941525 di.eh_frame_hdr = .{
15951526 .eh_frame_ptr = eh_frame_ptr,
15961527 .table_enc = table_enc,
15971528 .fde_count = fde_count,
1598 .entries = eh_frame_hdr[stream.pos..][0..entries_len],
1529 .entries = eh_frame_hdr[fbr.pos..][0..entries_len],
15991530 };
16001531
16011532 // No need to scan .eh_frame, we have a binary search table already
......@@ -1605,16 +1536,16 @@ pub const DwarfInfo = struct {
16051536 const frame_sections = [2]DwarfSection{ .eh_frame, .debug_frame };
16061537 for (frame_sections) |frame_section| {
16071538 if (di.section(frame_section)) |section_data| {
1608 var stream = io.fixedBufferStream(section_data);
1609 while (stream.pos < stream.buffer.len) {
1610 const entry_header = try EntryHeader.read(&stream, frame_section, di.endian);
1539 var fbr: FixedBufferReader = .{ .buf = section_data, .endian = di.endian };
1540 while (fbr.pos < fbr.buf.len) {
1541 const entry_header = try EntryHeader.read(&fbr, frame_section);
16111542 switch (entry_header.type) {
16121543 .cie => {
16131544 const cie = try CommonInformationEntry.parse(
16141545 entry_header.entry_bytes,
16151546 di.sectionVirtualOffset(frame_section, base_address).?,
16161547 true,
1617 entry_header.is_64,
1548 entry_header.format,
16181549 frame_section,
16191550 entry_header.length_offset,
16201551 @sizeOf(usize),
......@@ -1638,7 +1569,7 @@ pub const DwarfInfo = struct {
16381569 }
16391570 }
16401571
1641 std.mem.sortUnstable(FrameDescriptionEntry, di.fde_list.items, {}, struct {
1572 mem.sortUnstable(FrameDescriptionEntry, di.fde_list.items, {}, struct {
16421573 fn lessThan(ctx: void, a: FrameDescriptionEntry, b: FrameDescriptionEntry) bool {
16431574 _ = ctx;
16441575 return a.pc_begin < b.pc_begin;
......@@ -1668,27 +1599,31 @@ pub const DwarfInfo = struct {
16681599 const frame_section = di.section(dwarf_section) orelse return error.MissingFDE;
16691600 if (fde_offset >= frame_section.len) return error.MissingFDE;
16701601
1671 var stream = io.fixedBufferStream(frame_section);
1672 try stream.seekTo(fde_offset);
1602 var fbr: FixedBufferReader = .{
1603 .buf = frame_section,
1604 .pos = fde_offset,
1605 .endian = di.endian,
1606 };
16731607
1674 const fde_entry_header = try EntryHeader.read(&stream, dwarf_section, di.endian);
1608 const fde_entry_header = try EntryHeader.read(&fbr, dwarf_section);
16751609 if (fde_entry_header.type != .fde) return error.MissingFDE;
16761610
16771611 const cie_offset = fde_entry_header.type.fde;
1678 try stream.seekTo(cie_offset);
1612 try fbr.seekTo(cie_offset);
16791613
1680 const cie_entry_header = try EntryHeader.read(&stream, dwarf_section, builtin.cpu.arch.endian());
1614 fbr.endian = native_endian;
1615 const cie_entry_header = try EntryHeader.read(&fbr, dwarf_section);
16811616 if (cie_entry_header.type != .cie) return badDwarf();
16821617
16831618 cie = try CommonInformationEntry.parse(
16841619 cie_entry_header.entry_bytes,
16851620 0,
16861621 true,
1687 cie_entry_header.is_64,
1622 cie_entry_header.format,
16881623 dwarf_section,
16891624 cie_entry_header.length_offset,
16901625 @sizeOf(usize),
1691 builtin.cpu.arch.endian(),
1626 native_endian,
16921627 );
16931628
16941629 fde = try FrameDescriptionEntry.parse(
......@@ -1697,7 +1632,7 @@ pub const DwarfInfo = struct {
16971632 true,
16981633 cie,
16991634 @sizeOf(usize),
1700 builtin.cpu.arch.endian(),
1635 native_endian,
17011636 );
17021637 } else if (di.eh_frame_hdr) |header| {
17031638 const eh_frame_len = if (di.section(.eh_frame)) |eh_frame| eh_frame.len else null;
......@@ -1711,7 +1646,7 @@ pub const DwarfInfo = struct {
17111646 );
17121647 } else {
17131648 const index = std.sort.binarySearch(FrameDescriptionEntry, context.pc, di.fde_list.items, {}, struct {
1714 pub fn compareFn(_: void, pc: usize, mid_item: FrameDescriptionEntry) std.math.Order {
1649 pub fn compareFn(_: void, pc: usize, mid_item: FrameDescriptionEntry) math.Order {
17151650 if (pc < mid_item.pc_begin) return .lt;
17161651
17171652 const range_end = mid_item.pc_begin + mid_item.pc_range;
......@@ -1725,8 +1660,8 @@ pub const DwarfInfo = struct {
17251660 cie = di.cie_map.get(fde.cie_length_offset) orelse return error.MissingCIE;
17261661 }
17271662
1728 var expression_context = .{
1729 .is_64 = cie.is_64,
1663 var expression_context: expressions.ExpressionContext = .{
1664 .format = cie.format,
17301665 .isValidMemory = context.isValidMemory,
17311666 .compile_unit = di.findCompileUnit(fde.pc_begin) catch null,
17321667 .thread_context = context.thread_context,
......@@ -1973,10 +1908,10 @@ pub fn unwindFrameMachO(context: *UnwindContext, unwind_info: []const u8, eh_fra
19731908 .raw_encoding = common_encodings[entry.encodingIndex],
19741909 };
19751910 } else {
1976 const local_index = try std.math.sub(
1911 const local_index = try math.sub(
19771912 u8,
19781913 entry.encodingIndex,
1979 std.math.cast(u8, header.commonEncodingsArrayCount) orelse return error.InvalidUnwindInfo,
1914 math.cast(u8, header.commonEncodingsArrayCount) orelse return error.InvalidUnwindInfo,
19801915 );
19811916 const local_encodings = mem.bytesAsSlice(
19821917 macho.compact_unwind_encoding_t,
......@@ -2187,7 +2122,7 @@ pub fn unwindFrameMachO(context: *UnwindContext, unwind_info: []const u8, eh_fra
21872122
21882123fn unwindFrameMachODwarf(context: *UnwindContext, eh_frame: []const u8, fde_offset: usize) !usize {
21892124 var di = DwarfInfo{
2190 .endian = builtin.cpu.arch.endian(),
2125 .endian = native_endian,
21912126 .is_macho = true,
21922127 };
21932128 defer di.deinit(context.allocator);
......@@ -2207,8 +2142,8 @@ pub const UnwindContext = struct {
22072142 thread_context: *debug.ThreadContext,
22082143 reg_context: abi.RegisterContext,
22092144 isValidMemory: *const fn (address: usize) bool,
2210 vm: call_frame.VirtualMachine = .{},
2211 stack_machine: expressions.StackMachine(.{ .call_frame_context = true }) = .{},
2145 vm: call_frame.VirtualMachine,
2146 stack_machine: expressions.StackMachine(.{ .call_frame_context = true }),
22122147
22132148 pub fn init(allocator: mem.Allocator, thread_context: *const debug.ThreadContext, isValidMemory: *const fn (address: usize) bool) !UnwindContext {
22142149 const pc = abi.stripInstructionPtrAuthCode((try abi.regValueNative(usize, thread_context, abi.ipRegNum(), null)).*);
......@@ -2223,6 +2158,8 @@ pub const UnwindContext = struct {
22232158 .thread_context = context_copy,
22242159 .reg_context = undefined,
22252160 .isValidMemory = isValidMemory,
2161 .vm = .{},
2162 .stack_machine = .{},
22262163 };
22272164 }
22282165
......@@ -2230,6 +2167,7 @@ pub const UnwindContext = struct {
22302167 self.vm.deinit(self.allocator);
22312168 self.stack_machine.deinit(self.allocator);
22322169 self.allocator.destroy(self.thread_context);
2170 self.* = undefined;
22332171 }
22342172
22352173 pub fn getFp(self: *const UnwindContext) !usize {
......@@ -2281,8 +2219,7 @@ const EhPointerContext = struct {
22812219 text_rel_base: ?u64 = null,
22822220 function_rel_base: ?u64 = null,
22832221};
2284
2285fn readEhPointer(reader: anytype, enc: u8, addr_size_bytes: u8, ctx: EhPointerContext, endian: std.builtin.Endian) !?u64 {
2222fn readEhPointer(fbr: *FixedBufferReader, enc: u8, addr_size_bytes: u8, ctx: EhPointerContext) !?u64 {
22862223 if (enc == EH.PE.omit) return null;
22872224
22882225 const value: union(enum) {
......@@ -2291,20 +2228,20 @@ fn readEhPointer(reader: anytype, enc: u8, addr_size_bytes: u8, ctx: EhPointerCo
22912228 } = switch (enc & EH.PE.type_mask) {
22922229 EH.PE.absptr => .{
22932230 .unsigned = switch (addr_size_bytes) {
2294 2 => try reader.readInt(u16, endian),
2295 4 => try reader.readInt(u32, endian),
2296 8 => try reader.readInt(u64, endian),
2231 2 => try fbr.readInt(u16),
2232 4 => try fbr.readInt(u32),
2233 8 => try fbr.readInt(u64),
22972234 else => return error.InvalidAddrSize,
22982235 },
22992236 },
2300 EH.PE.uleb128 => .{ .unsigned = try leb.readULEB128(u64, reader) },
2301 EH.PE.udata2 => .{ .unsigned = try reader.readInt(u16, endian) },
2302 EH.PE.udata4 => .{ .unsigned = try reader.readInt(u32, endian) },
2303 EH.PE.udata8 => .{ .unsigned = try reader.readInt(u64, endian) },
2304 EH.PE.sleb128 => .{ .signed = try leb.readILEB128(i64, reader) },
2305 EH.PE.sdata2 => .{ .signed = try reader.readInt(i16, endian) },
2306 EH.PE.sdata4 => .{ .signed = try reader.readInt(i32, endian) },
2307 EH.PE.sdata8 => .{ .signed = try reader.readInt(i64, endian) },
2237 EH.PE.uleb128 => .{ .unsigned = try fbr.readUleb128(u64) },
2238 EH.PE.udata2 => .{ .unsigned = try fbr.readInt(u16) },
2239 EH.PE.udata4 => .{ .unsigned = try fbr.readInt(u32) },
2240 EH.PE.udata8 => .{ .unsigned = try fbr.readInt(u64) },
2241 EH.PE.sleb128 => .{ .signed = try fbr.readIleb128(i64) },
2242 EH.PE.sdata2 => .{ .signed = try fbr.readInt(i16) },
2243 EH.PE.sdata4 => .{ .signed = try fbr.readInt(i32) },
2244 EH.PE.sdata8 => .{ .signed = try fbr.readInt(i64) },
23082245 else => return badDwarf(),
23092246 };
23102247
......@@ -2396,18 +2333,17 @@ pub const ExceptionFrameHeader = struct {
23962333 var left: usize = 0;
23972334 var len: usize = self.fde_count;
23982335
2399 var stream = io.fixedBufferStream(self.entries);
2400 const reader = stream.reader();
2336 var fbr: FixedBufferReader = .{ .buf = self.entries, .endian = native_endian };
24012337
24022338 while (len > 1) {
24032339 const mid = left + len / 2;
24042340
2405 try stream.seekTo(mid * entry_size);
2406 const pc_begin = try readEhPointer(reader, self.table_enc, @sizeOf(usize), .{
2407 .pc_rel_base = @intFromPtr(&self.entries[stream.pos]),
2341 fbr.pos = mid * entry_size;
2342 const pc_begin = try readEhPointer(&fbr, self.table_enc, @sizeOf(usize), .{
2343 .pc_rel_base = @intFromPtr(&self.entries[fbr.pos]),
24082344 .follow_indirect = true,
24092345 .data_rel_base = eh_frame_hdr_ptr,
2410 }, builtin.cpu.arch.endian()) orelse return badDwarf();
2346 }) orelse return badDwarf();
24112347
24122348 if (pc < pc_begin) {
24132349 len /= 2;
......@@ -2419,20 +2355,20 @@ pub const ExceptionFrameHeader = struct {
24192355 }
24202356
24212357 if (len == 0) return badDwarf();
2422 try stream.seekTo(left * entry_size);
2358 fbr.pos = left * entry_size;
24232359
24242360 // Read past the pc_begin field of the entry
2425 _ = try readEhPointer(reader, self.table_enc, @sizeOf(usize), .{
2426 .pc_rel_base = @intFromPtr(&self.entries[stream.pos]),
2361 _ = try readEhPointer(&fbr, self.table_enc, @sizeOf(usize), .{
2362 .pc_rel_base = @intFromPtr(&self.entries[fbr.pos]),
24272363 .follow_indirect = true,
24282364 .data_rel_base = eh_frame_hdr_ptr,
2429 }, builtin.cpu.arch.endian()) orelse return badDwarf();
2365 }) orelse return badDwarf();
24302366
2431 const fde_ptr = math.cast(usize, try readEhPointer(reader, self.table_enc, @sizeOf(usize), .{
2432 .pc_rel_base = @intFromPtr(&self.entries[stream.pos]),
2367 const fde_ptr = math.cast(usize, try readEhPointer(&fbr, self.table_enc, @sizeOf(usize), .{
2368 .pc_rel_base = @intFromPtr(&self.entries[fbr.pos]),
24332369 .follow_indirect = true,
24342370 .data_rel_base = eh_frame_hdr_ptr,
2435 }, builtin.cpu.arch.endian()) orelse return badDwarf()) orelse return badDwarf();
2371 }) orelse return badDwarf()) orelse return badDwarf();
24362372
24372373 // Verify the length fields of the FDE header are readable
24382374 if (!self.isValidPtr(fde_ptr, isValidMemory, eh_frame_len) or fde_ptr < self.eh_frame_ptr) return badDwarf();
......@@ -2445,17 +2381,20 @@ pub const ExceptionFrameHeader = struct {
24452381 const eh_frame = @as([*]const u8, @ptrFromInt(self.eh_frame_ptr))[0 .. eh_frame_len orelse math.maxInt(u32)];
24462382
24472383 const fde_offset = fde_ptr - self.eh_frame_ptr;
2448 var eh_frame_stream = io.fixedBufferStream(eh_frame);
2449 try eh_frame_stream.seekTo(fde_offset);
2384 var eh_frame_fbr: FixedBufferReader = .{
2385 .buf = eh_frame,
2386 .pos = fde_offset,
2387 .endian = native_endian,
2388 };
24502389
2451 const fde_entry_header = try EntryHeader.read(&eh_frame_stream, .eh_frame, builtin.cpu.arch.endian());
2390 const fde_entry_header = try EntryHeader.read(&eh_frame_fbr, .eh_frame);
24522391 if (!self.isValidPtr(@intFromPtr(&fde_entry_header.entry_bytes[fde_entry_header.entry_bytes.len - 1]), isValidMemory, eh_frame_len)) return badDwarf();
24532392 if (fde_entry_header.type != .fde) return badDwarf();
24542393
24552394 // CIEs always come before FDEs (the offset is a subtraction), so we can assume this memory is readable
24562395 const cie_offset = fde_entry_header.type.fde;
2457 try eh_frame_stream.seekTo(cie_offset);
2458 const cie_entry_header = try EntryHeader.read(&eh_frame_stream, .eh_frame, builtin.cpu.arch.endian());
2396 try eh_frame_fbr.seekTo(cie_offset);
2397 const cie_entry_header = try EntryHeader.read(&eh_frame_fbr, .eh_frame);
24592398 if (!self.isValidPtr(@intFromPtr(&cie_entry_header.entry_bytes[cie_entry_header.entry_bytes.len - 1]), isValidMemory, eh_frame_len)) return badDwarf();
24602399 if (cie_entry_header.type != .cie) return badDwarf();
24612400
......@@ -2463,11 +2402,11 @@ pub const ExceptionFrameHeader = struct {
24632402 cie_entry_header.entry_bytes,
24642403 0,
24652404 true,
2466 cie_entry_header.is_64,
2405 cie_entry_header.format,
24672406 .eh_frame,
24682407 cie_entry_header.length_offset,
24692408 @sizeOf(usize),
2470 builtin.cpu.arch.endian(),
2409 native_endian,
24712410 );
24722411
24732412 fde.* = try FrameDescriptionEntry.parse(
......@@ -2476,7 +2415,7 @@ pub const ExceptionFrameHeader = struct {
24762415 true,
24772416 cie.*,
24782417 @sizeOf(usize),
2479 builtin.cpu.arch.endian(),
2418 native_endian,
24802419 );
24812420 }
24822421};
......@@ -2484,62 +2423,60 @@ pub const ExceptionFrameHeader = struct {
24842423pub const EntryHeader = struct {
24852424 /// Offset of the length field in the backing buffer
24862425 length_offset: usize,
2487 is_64: bool,
2426 format: Format,
24882427 type: union(enum) {
24892428 cie,
24902429 /// Value is the offset of the corresponding CIE
24912430 fde: u64,
2492 terminator: void,
2431 terminator,
24932432 },
24942433 /// The entry's contents, not including the ID field
24952434 entry_bytes: []const u8,
24962435
2497 /// Reads a header for either an FDE or a CIE, then advances the stream to the position after the trailing structure.
2498 /// `stream` must be a stream backed by either the .eh_frame or .debug_frame sections.
2499 pub fn read(stream: *std.io.FixedBufferStream([]const u8), dwarf_section: DwarfSection, endian: std.builtin.Endian) !EntryHeader {
2500 assert(dwarf_section == .eh_frame or dwarf_section == .debug_frame);
2436 /// The length of the entry including the ID field, but not the length field itself
2437 pub fn entryLength(self: EntryHeader) usize {
2438 return self.entry_bytes.len + @as(u8, if (self.is_64) 8 else 4);
2439 }
25012440
2502 const reader = stream.reader();
2503 const length_offset = stream.pos;
2441 /// Reads a header for either an FDE or a CIE, then advances the fbr to the position after the trailing structure.
2442 /// `fbr` must be a FixedBufferReader backed by either the .eh_frame or .debug_frame sections.
2443 pub fn read(fbr: *FixedBufferReader, dwarf_section: DwarfSection) !EntryHeader {
2444 assert(dwarf_section == .eh_frame or dwarf_section == .debug_frame);
25042445
2505 var is_64: bool = undefined;
2506 const length = math.cast(usize, try readUnitLength(reader, endian, &is_64)) orelse return badDwarf();
2507 if (length == 0) return .{
2446 const length_offset = fbr.pos;
2447 const unit_header = try readUnitHeader(fbr);
2448 const unit_length = math.cast(usize, unit_header.unit_length) orelse return badDwarf();
2449 if (unit_length == 0) return .{
25082450 .length_offset = length_offset,
2509 .is_64 = is_64,
2510 .type = .{ .terminator = {} },
2451 .format = unit_header.format,
2452 .type = .terminator,
25112453 .entry_bytes = &.{},
25122454 };
2455 const start_offset = fbr.pos;
2456 const end_offset = start_offset + unit_length;
2457 defer fbr.pos = end_offset;
25132458
2514 const id_len = @as(u8, if (is_64) 8 else 4);
2515 const id = if (is_64) try reader.readInt(u64, endian) else try reader.readInt(u32, endian);
2516 const entry_bytes = stream.buffer[stream.pos..][0 .. length - id_len];
2459 const id = try fbr.readAddress(unit_header.format);
2460 const entry_bytes = fbr.buf[fbr.pos..end_offset];
25172461 const cie_id: u64 = switch (dwarf_section) {
25182462 .eh_frame => CommonInformationEntry.eh_id,
2519 .debug_frame => if (is_64) CommonInformationEntry.dwarf64_id else CommonInformationEntry.dwarf32_id,
2463 .debug_frame => switch (unit_header.format) {
2464 .@"32" => CommonInformationEntry.dwarf32_id,
2465 .@"64" => CommonInformationEntry.dwarf64_id,
2466 },
25202467 else => unreachable,
25212468 };
25222469
2523 const result = EntryHeader{
2470 return .{
25242471 .length_offset = length_offset,
2525 .is_64 = is_64,
2526 .type = if (id == cie_id) .{ .cie = {} } else .{
2527 .fde = switch (dwarf_section) {
2528 .eh_frame => try std.math.sub(u64, stream.pos - id_len, id),
2529 .debug_frame => id,
2530 else => unreachable,
2531 },
2532 },
2472 .format = unit_header.format,
2473 .type = if (id == cie_id) .cie else .{ .fde = switch (dwarf_section) {
2474 .eh_frame => try math.sub(u64, start_offset, id),
2475 .debug_frame => id,
2476 else => unreachable,
2477 } },
25332478 .entry_bytes = entry_bytes,
25342479 };
2535
2536 stream.pos += entry_bytes.len;
2537 return result;
2538 }
2539
2540 /// The length of the entry including the ID field, but not the length field itself
2541 pub fn entryLength(self: EntryHeader) usize {
2542 return self.entry_bytes.len + @as(u8, if (self.is_64) 8 else 4);
25432480 }
25442481};
25452482
......@@ -2558,7 +2495,7 @@ pub const CommonInformationEntry = struct {
25582495 length_offset: u64,
25592496 version: u8,
25602497 address_size: u8,
2561 is_64: bool,
2498 format: Format,
25622499
25632500 // Only present in version 4
25642501 segment_selector_size: ?u8,
......@@ -2602,7 +2539,7 @@ pub const CommonInformationEntry = struct {
26022539 cie_bytes: []const u8,
26032540 pc_rel_offset: i64,
26042541 is_runtime: bool,
2605 is_64: bool,
2542 format: Format,
26062543 dwarf_section: DwarfSection,
26072544 length_offset: u64,
26082545 addr_size_bytes: u8,
......@@ -2610,10 +2547,9 @@ pub const CommonInformationEntry = struct {
26102547 ) !CommonInformationEntry {
26112548 if (addr_size_bytes > 8) return error.UnsupportedAddrSize;
26122549
2613 var stream = io.fixedBufferStream(cie_bytes);
2614 const reader = stream.reader();
2550 var fbr: FixedBufferReader = .{ .buf = cie_bytes, .endian = endian };
26152551
2616 const version = try reader.readByte();
2552 const version = try fbr.readByte();
26172553 switch (dwarf_section) {
26182554 .eh_frame => if (version != 1 and version != 3) return error.UnsupportedDwarfVersion,
26192555 .debug_frame => if (version != 4) return error.UnsupportedDwarfVersion,
......@@ -2624,9 +2560,9 @@ pub const CommonInformationEntry = struct {
26242560 var has_aug_data = false;
26252561
26262562 var aug_str_len: usize = 0;
2627 const aug_str_start = stream.pos;
2628 var aug_byte = try reader.readByte();
2629 while (aug_byte != 0) : (aug_byte = try reader.readByte()) {
2563 const aug_str_start = fbr.pos;
2564 var aug_byte = try fbr.readByte();
2565 while (aug_byte != 0) : (aug_byte = try fbr.readByte()) {
26302566 switch (aug_byte) {
26312567 'z' => {
26322568 if (aug_str_len != 0) return badDwarf();
......@@ -2634,7 +2570,7 @@ pub const CommonInformationEntry = struct {
26342570 },
26352571 'e' => {
26362572 if (has_aug_data or aug_str_len != 0) return badDwarf();
2637 if (try reader.readByte() != 'h') return badDwarf();
2573 if (try fbr.readByte() != 'h') return badDwarf();
26382574 has_eh_data = true;
26392575 },
26402576 else => if (has_eh_data) return badDwarf(),
......@@ -2645,15 +2581,15 @@ pub const CommonInformationEntry = struct {
26452581
26462582 if (has_eh_data) {
26472583 // legacy data created by older versions of gcc - unsupported here
2648 for (0..addr_size_bytes) |_| _ = try reader.readByte();
2584 for (0..addr_size_bytes) |_| _ = try fbr.readByte();
26492585 }
26502586
2651 const address_size = if (version == 4) try reader.readByte() else addr_size_bytes;
2652 const segment_selector_size = if (version == 4) try reader.readByte() else null;
2587 const address_size = if (version == 4) try fbr.readByte() else addr_size_bytes;
2588 const segment_selector_size = if (version == 4) try fbr.readByte() else null;
26532589
2654 const code_alignment_factor = try leb.readULEB128(u32, reader);
2655 const data_alignment_factor = try leb.readILEB128(i32, reader);
2656 const return_address_register = if (version == 1) try reader.readByte() else try leb.readULEB128(u8, reader);
2590 const code_alignment_factor = try fbr.readUleb128(u32);
2591 const data_alignment_factor = try fbr.readIleb128(i32);
2592 const return_address_register = if (version == 1) try fbr.readByte() else try fbr.readUleb128(u8);
26572593
26582594 var lsda_pointer_enc: u8 = EH.PE.omit;
26592595 var personality_enc: ?u8 = null;
......@@ -2662,31 +2598,25 @@ pub const CommonInformationEntry = struct {
26622598
26632599 var aug_data: []const u8 = &[_]u8{};
26642600 const aug_str = if (has_aug_data) blk: {
2665 const aug_data_len = try leb.readULEB128(usize, reader);
2666 const aug_data_start = stream.pos;
2601 const aug_data_len = try fbr.readUleb128(usize);
2602 const aug_data_start = fbr.pos;
26672603 aug_data = cie_bytes[aug_data_start..][0..aug_data_len];
26682604
26692605 const aug_str = cie_bytes[aug_str_start..][0..aug_str_len];
26702606 for (aug_str[1..]) |byte| {
26712607 switch (byte) {
26722608 'L' => {
2673 lsda_pointer_enc = try reader.readByte();
2609 lsda_pointer_enc = try fbr.readByte();
26742610 },
26752611 'P' => {
2676 personality_enc = try reader.readByte();
2677 personality_routine_pointer = try readEhPointer(
2678 reader,
2679 personality_enc.?,
2680 addr_size_bytes,
2681 .{
2682 .pc_rel_base = try pcRelBase(@intFromPtr(&cie_bytes[stream.pos]), pc_rel_offset),
2683 .follow_indirect = is_runtime,
2684 },
2685 endian,
2686 );
2612 personality_enc = try fbr.readByte();
2613 personality_routine_pointer = try readEhPointer(&fbr, personality_enc.?, addr_size_bytes, .{
2614 .pc_rel_base = try pcRelBase(@intFromPtr(&cie_bytes[fbr.pos]), pc_rel_offset),
2615 .follow_indirect = is_runtime,
2616 });
26872617 },
26882618 'R' => {
2689 fde_pointer_enc = try reader.readByte();
2619 fde_pointer_enc = try fbr.readByte();
26902620 },
26912621 'S', 'B', 'G' => {},
26922622 else => return badDwarf(),
......@@ -2694,16 +2624,16 @@ pub const CommonInformationEntry = struct {
26942624 }
26952625
26962626 // aug_data_len can include padding so the CIE ends on an address boundary
2697 try stream.seekTo(aug_data_start + aug_data_len);
2627 fbr.pos = aug_data_start + aug_data_len;
26982628 break :blk aug_str;
26992629 } else &[_]u8{};
27002630
2701 const initial_instructions = cie_bytes[stream.pos..];
2631 const initial_instructions = cie_bytes[fbr.pos..];
27022632 return .{
27032633 .length_offset = length_offset,
27042634 .version = version,
27052635 .address_size = address_size,
2706 .is_64 = is_64,
2636 .format = format,
27072637 .segment_selector_size = segment_selector_size,
27082638 .code_alignment_factor = code_alignment_factor,
27092639 .data_alignment_factor = data_alignment_factor,
......@@ -2751,56 +2681,37 @@ pub const FrameDescriptionEntry = struct {
27512681 ) !FrameDescriptionEntry {
27522682 if (addr_size_bytes > 8) return error.InvalidAddrSize;
27532683
2754 var stream = io.fixedBufferStream(fde_bytes);
2755 const reader = stream.reader();
2684 var fbr: FixedBufferReader = .{ .buf = fde_bytes, .endian = endian };
27562685
2757 const pc_begin = try readEhPointer(
2758 reader,
2759 cie.fde_pointer_enc,
2760 addr_size_bytes,
2761 .{
2762 .pc_rel_base = try pcRelBase(@intFromPtr(&fde_bytes[stream.pos]), pc_rel_offset),
2763 .follow_indirect = is_runtime,
2764 },
2765 endian,
2766 ) orelse return badDwarf();
2767
2768 const pc_range = try readEhPointer(
2769 reader,
2770 cie.fde_pointer_enc,
2771 addr_size_bytes,
2772 .{
2773 .pc_rel_base = 0,
2774 .follow_indirect = false,
2775 },
2776 endian,
2777 ) orelse return badDwarf();
2686 const pc_begin = try readEhPointer(&fbr, cie.fde_pointer_enc, addr_size_bytes, .{
2687 .pc_rel_base = try pcRelBase(@intFromPtr(&fde_bytes[fbr.pos]), pc_rel_offset),
2688 .follow_indirect = is_runtime,
2689 }) orelse return badDwarf();
2690
2691 const pc_range = try readEhPointer(&fbr, cie.fde_pointer_enc, addr_size_bytes, .{
2692 .pc_rel_base = 0,
2693 .follow_indirect = false,
2694 }) orelse return badDwarf();
27782695
27792696 var aug_data: []const u8 = &[_]u8{};
27802697 const lsda_pointer = if (cie.aug_str.len > 0) blk: {
2781 const aug_data_len = try leb.readULEB128(usize, reader);
2782 const aug_data_start = stream.pos;
2698 const aug_data_len = try fbr.readUleb128(usize);
2699 const aug_data_start = fbr.pos;
27832700 aug_data = fde_bytes[aug_data_start..][0..aug_data_len];
27842701
27852702 const lsda_pointer = if (cie.lsda_pointer_enc != EH.PE.omit)
2786 try readEhPointer(
2787 reader,
2788 cie.lsda_pointer_enc,
2789 addr_size_bytes,
2790 .{
2791 .pc_rel_base = try pcRelBase(@intFromPtr(&fde_bytes[stream.pos]), pc_rel_offset),
2792 .follow_indirect = is_runtime,
2793 },
2794 endian,
2795 )
2703 try readEhPointer(&fbr, cie.lsda_pointer_enc, addr_size_bytes, .{
2704 .pc_rel_base = try pcRelBase(@intFromPtr(&fde_bytes[fbr.pos]), pc_rel_offset),
2705 .follow_indirect = is_runtime,
2706 })
27962707 else
27972708 null;
27982709
2799 try stream.seekTo(aug_data_start + aug_data_len);
2710 fbr.pos = aug_data_start + aug_data_len;
28002711 break :blk lsda_pointer;
28012712 } else null;
28022713
2803 const instructions = fde_bytes[stream.pos..];
2714 const instructions = fde_bytes[fbr.pos..];
28042715 return .{
28052716 .cie_length_offset = cie.length_offset,
28062717 .pc_begin = pc_begin,
......@@ -2820,6 +2731,75 @@ fn pcRelBase(field_ptr: usize, pc_rel_offset: i64) !usize {
28202731 }
28212732}
28222733
2734// Reading debug info needs to be fast, even when compiled in debug mode,
2735// so avoid using a `std.io.FixedBufferStream` which is too slow.
2736const FixedBufferReader = struct {
2737 buf: []const u8,
2738 pos: usize = 0,
2739 endian: std.builtin.Endian,
2740
2741 pub const Error = error{ EndOfBuffer, Overflow };
2742
2743 fn seekTo(fbr: *FixedBufferReader, pos: u64) Error!void {
2744 if (pos > fbr.buf.len) return error.EndOfBuffer;
2745 fbr.pos = @intCast(pos);
2746 }
2747
2748 fn seekForward(fbr: *FixedBufferReader, amount: u64) Error!void {
2749 if (fbr.buf.len - fbr.pos < amount) return error.EndOfBuffer;
2750 fbr.pos += @intCast(amount);
2751 }
2752
2753 pub inline fn readByte(fbr: *FixedBufferReader) Error!u8 {
2754 if (fbr.pos >= fbr.buf.len) return error.EndOfBuffer;
2755 defer fbr.pos += 1;
2756 return fbr.buf[fbr.pos];
2757 }
2758
2759 fn readByteSigned(fbr: *FixedBufferReader) Error!i8 {
2760 return @bitCast(try fbr.readByte());
2761 }
2762
2763 fn readInt(fbr: *FixedBufferReader, comptime T: type) Error!T {
2764 const size = @divExact(@typeInfo(T).Int.bits, 8);
2765 if (fbr.buf.len - fbr.pos < size) return error.EndOfBuffer;
2766 defer fbr.pos += size;
2767 return mem.readInt(T, fbr.buf[fbr.pos..][0..size], fbr.endian);
2768 }
2769
2770 fn readUleb128(fbr: *FixedBufferReader, comptime T: type) Error!T {
2771 return std.leb.readULEB128(T, fbr);
2772 }
2773
2774 fn readIleb128(fbr: *FixedBufferReader, comptime T: type) Error!T {
2775 return std.leb.readILEB128(T, fbr);
2776 }
2777
2778 fn readAddress(fbr: *FixedBufferReader, format: Format) Error!u64 {
2779 return switch (format) {
2780 .@"32" => try fbr.readInt(u32),
2781 .@"64" => try fbr.readInt(u64),
2782 };
2783 }
2784
2785 fn readBytes(fbr: *FixedBufferReader, len: usize) Error![]const u8 {
2786 if (fbr.buf.len - fbr.pos < len) return error.EndOfBuffer;
2787 defer fbr.pos += len;
2788 return fbr.buf[fbr.pos..][0..len];
2789 }
2790
2791 fn readBytesTo(fbr: *FixedBufferReader, comptime sentinel: u8) Error![:sentinel]const u8 {
2792 const end = @call(.always_inline, mem.indexOfScalarPos, .{
2793 u8,
2794 fbr.buf,
2795 fbr.pos,
2796 sentinel,
2797 }) orelse return error.EndOfBuffer;
2798 defer fbr.pos = end + 1;
2799 return fbr.buf[fbr.pos..end :sentinel];
2800 }
2801};
2802
28232803test {
28242804 std.testing.refAllDecls(@This());
28252805}
lib/std/dwarf/TAG.zig+3
......@@ -116,3 +116,6 @@ pub const upc_relaxed_type = 0x8767;
116116// PGI (STMicroelectronics; extensions. No documentation available.
117117pub const PGI_kanji_type = 0xA000;
118118pub const PGI_interface_block = 0xA020;
119
120// ZIG extensions.
121pub const ZIG_padding = 0xfdb1;
lib/std/dwarf/expressions.zig+9-9
......@@ -12,8 +12,8 @@ const native_endian = builtin.cpu.arch.endian();
1212/// Callers should specify all the fields relevant to their context. If a field is required
1313/// by the expression and it isn't in the context, error.IncompleteExpressionContext is returned.
1414pub const ExpressionContext = struct {
15 /// This expression is from a DWARF64 section
16 is_64: bool = false,
15 /// The dwarf format of the section this expression is in
16 format: dwarf.Format = .@"32",
1717
1818 /// If specified, any addresses will pass through this function before being acccessed
1919 isValidMemory: ?*const fn (address: usize) bool = null,
......@@ -190,10 +190,10 @@ pub fn StackMachine(comptime options: ExpressionOptions) type {
190190 const reader = stream.reader();
191191 return switch (opcode) {
192192 OP.addr => generic(try reader.readInt(addr_type, options.endian)),
193 OP.call_ref => if (context.is_64)
194 generic(try reader.readInt(u64, options.endian))
195 else
196 generic(try reader.readInt(u32, options.endian)),
193 OP.call_ref => switch (context.format) {
194 .@"32" => generic(try reader.readInt(u32, options.endian)),
195 .@"64" => generic(try reader.readInt(u64, options.endian)),
196 },
197197 OP.const1u,
198198 OP.pick,
199199 => generic(try reader.readByte()),
......@@ -366,15 +366,15 @@ pub fn StackMachine(comptime options: ExpressionOptions) type {
366366 _ = offset;
367367
368368 switch (context.compile_unit.?.frame_base.?.*) {
369 .ExprLoc => {
369 .exprloc => {
370370 // TODO: Run this expression in a nested stack machine
371371 return error.UnimplementedOpcode;
372372 },
373 .LocListOffset => {
373 .loclistx => {
374374 // TODO: Read value from .debug_loclists
375375 return error.UnimplementedOpcode;
376376 },
377 .SecOffset => {
377 .sec_offset => {
378378 // TODO: Read value from .debug_loclists
379379 return error.UnimplementedOpcode;
380380 },
lib/std/io/fixed_buffer_stream.zig+2-6
......@@ -62,11 +62,7 @@ pub fn FixedBufferStream(comptime Buffer: type) type {
6262 if (bytes.len == 0) return 0;
6363 if (self.pos >= self.buffer.len) return error.NoSpaceLeft;
6464
65 const n = if (self.pos + bytes.len <= self.buffer.len)
66 bytes.len
67 else
68 self.buffer.len - self.pos;
69
65 const n = @min(self.buffer.len - self.pos, bytes.len);
7066 @memcpy(self.buffer[self.pos..][0..n], bytes[0..n]);
7167 self.pos += n;
7268
......@@ -76,7 +72,7 @@ pub fn FixedBufferStream(comptime Buffer: type) type {
7672 }
7773
7874 pub fn seekTo(self: *Self, pos: u64) SeekError!void {
79 self.pos = if (std.math.cast(usize, pos)) |x| @min(self.buffer.len, x) else self.buffer.len;
75 self.pos = @min(std.math.lossyCast(usize, pos), self.buffer.len);
8076 }
8177
8278 pub fn seekBy(self: *Self, amt: i64) SeekError!void {
src/link/Dwarf.zig+68-59
......@@ -140,11 +140,11 @@ pub const DeclState = struct {
140140 switch (ty.zigTypeTag(mod)) {
141141 .NoReturn => unreachable,
142142 .Void => {
143 try dbg_info_buffer.append(@intFromEnum(AbbrevKind.pad1));
143 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.zero_bit_type));
144144 },
145145 .Bool => {
146146 try dbg_info_buffer.ensureUnusedCapacity(12);
147 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.base_type));
147 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.base_type));
148148 // DW.AT.encoding, DW.FORM.data1
149149 dbg_info_buffer.appendAssumeCapacity(DW.ATE.boolean);
150150 // DW.AT.byte_size, DW.FORM.udata
......@@ -155,7 +155,7 @@ pub const DeclState = struct {
155155 .Int => {
156156 const info = ty.intInfo(mod);
157157 try dbg_info_buffer.ensureUnusedCapacity(12);
158 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.base_type));
158 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.base_type));
159159 // DW.AT.encoding, DW.FORM.data1
160160 dbg_info_buffer.appendAssumeCapacity(switch (info.signedness) {
161161 .signed => DW.ATE.signed,
......@@ -169,7 +169,7 @@ pub const DeclState = struct {
169169 .Optional => {
170170 if (ty.isPtrLikeOptional(mod)) {
171171 try dbg_info_buffer.ensureUnusedCapacity(12);
172 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.base_type));
172 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.base_type));
173173 // DW.AT.encoding, DW.FORM.data1
174174 dbg_info_buffer.appendAssumeCapacity(DW.ATE.address);
175175 // DW.AT.byte_size, DW.FORM.udata
......@@ -180,7 +180,7 @@ pub const DeclState = struct {
180180 // Non-pointer optionals are structs: struct { .maybe = *, .val = * }
181181 const payload_ty = ty.optionalChild(mod);
182182 // DW.AT.structure_type
183 try dbg_info_buffer.append(@intFromEnum(AbbrevKind.struct_type));
183 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_type));
184184 // DW.AT.byte_size, DW.FORM.udata
185185 const abi_size = ty.abiSize(mod);
186186 try leb128.writeULEB128(dbg_info_buffer.writer(), abi_size);
......@@ -188,7 +188,7 @@ pub const DeclState = struct {
188188 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
189189 // DW.AT.member
190190 try dbg_info_buffer.ensureUnusedCapacity(7);
191 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.struct_member));
191 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_member));
192192 // DW.AT.name, DW.FORM.string
193193 dbg_info_buffer.appendSliceAssumeCapacity("maybe");
194194 dbg_info_buffer.appendAssumeCapacity(0);
......@@ -200,7 +200,7 @@ pub const DeclState = struct {
200200 try dbg_info_buffer.ensureUnusedCapacity(6);
201201 dbg_info_buffer.appendAssumeCapacity(0);
202202 // DW.AT.member
203 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.struct_member));
203 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_member));
204204 // DW.AT.name, DW.FORM.string
205205 dbg_info_buffer.appendSliceAssumeCapacity("val");
206206 dbg_info_buffer.appendAssumeCapacity(0);
......@@ -222,14 +222,14 @@ pub const DeclState = struct {
222222 const ptr_bytes: u8 = @intCast(@divExact(ptr_bits, 8));
223223 // DW.AT.structure_type
224224 try dbg_info_buffer.ensureUnusedCapacity(2);
225 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.struct_type));
225 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_type));
226226 // DW.AT.byte_size, DW.FORM.udata
227227 try leb128.writeULEB128(dbg_info_buffer.writer(), ty.abiSize(mod));
228228 // DW.AT.name, DW.FORM.string
229229 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
230230 // DW.AT.member
231231 try dbg_info_buffer.ensureUnusedCapacity(5);
232 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.struct_member));
232 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_member));
233233 // DW.AT.name, DW.FORM.string
234234 dbg_info_buffer.appendSliceAssumeCapacity("ptr");
235235 dbg_info_buffer.appendAssumeCapacity(0);
......@@ -242,7 +242,7 @@ pub const DeclState = struct {
242242 try dbg_info_buffer.ensureUnusedCapacity(6);
243243 dbg_info_buffer.appendAssumeCapacity(0);
244244 // DW.AT.member
245 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.struct_member));
245 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_member));
246246 // DW.AT.name, DW.FORM.string
247247 dbg_info_buffer.appendSliceAssumeCapacity("len");
248248 dbg_info_buffer.appendAssumeCapacity(0);
......@@ -257,7 +257,7 @@ pub const DeclState = struct {
257257 dbg_info_buffer.appendAssumeCapacity(0);
258258 } else {
259259 try dbg_info_buffer.ensureUnusedCapacity(5);
260 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.ptr_type));
260 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.ptr_type));
261261 // DW.AT.type, DW.FORM.ref4
262262 const index = dbg_info_buffer.items.len;
263263 try dbg_info_buffer.resize(index + 4);
......@@ -266,7 +266,7 @@ pub const DeclState = struct {
266266 },
267267 .Array => {
268268 // DW.AT.array_type
269 try dbg_info_buffer.append(@intFromEnum(AbbrevKind.array_type));
269 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.array_type));
270270 // DW.AT.name, DW.FORM.string
271271 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
272272 // DW.AT.type, DW.FORM.ref4
......@@ -274,7 +274,7 @@ pub const DeclState = struct {
274274 try dbg_info_buffer.resize(index + 4);
275275 try self.addTypeRelocGlobal(atom_index, ty.childType(mod), @intCast(index));
276276 // DW.AT.subrange_type
277 try dbg_info_buffer.append(@intFromEnum(AbbrevKind.array_dim));
277 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.array_dim));
278278 // DW.AT.type, DW.FORM.ref4
279279 index = dbg_info_buffer.items.len;
280280 try dbg_info_buffer.resize(index + 4);
......@@ -287,7 +287,7 @@ pub const DeclState = struct {
287287 },
288288 .Struct => {
289289 // DW.AT.structure_type
290 try dbg_info_buffer.append(@intFromEnum(AbbrevKind.struct_type));
290 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_type));
291291 // DW.AT.byte_size, DW.FORM.udata
292292 try leb128.writeULEB128(dbg_info_buffer.writer(), ty.abiSize(mod));
293293
......@@ -299,7 +299,7 @@ pub const DeclState = struct {
299299
300300 for (fields.types.get(ip), 0..) |field_ty, field_index| {
301301 // DW.AT.member
302 try dbg_info_buffer.append(@intFromEnum(AbbrevKind.struct_member));
302 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_member));
303303 // DW.AT.name, DW.FORM.string
304304 try dbg_info_buffer.writer().print("{d}\x00", .{field_index});
305305 // DW.AT.type, DW.FORM.ref4
......@@ -325,7 +325,7 @@ pub const DeclState = struct {
325325 for (struct_type.field_types.get(ip), struct_type.offsets.get(ip), 0..) |field_ty, field_off, field_index| {
326326 if (!Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
327327 // DW.AT.member
328 try dbg_info_buffer.append(@intFromEnum(AbbrevKind.struct_member));
328 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_member));
329329 // DW.AT.name, DW.FORM.string
330330 try dbg_info_buffer.writer().print("{d}\x00", .{field_index});
331331 // DW.AT.type, DW.FORM.ref4
......@@ -345,7 +345,7 @@ pub const DeclState = struct {
345345 const field_name = ip.stringToSlice(field_name_ip);
346346 // DW.AT.member
347347 try dbg_info_buffer.ensureUnusedCapacity(field_name.len + 2);
348 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.struct_member));
348 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_member));
349349 // DW.AT.name, DW.FORM.string
350350 dbg_info_buffer.appendSliceAssumeCapacity(field_name);
351351 dbg_info_buffer.appendAssumeCapacity(0);
......@@ -367,7 +367,7 @@ pub const DeclState = struct {
367367 },
368368 .Enum => {
369369 // DW.AT.enumeration_type
370 try dbg_info_buffer.append(@intFromEnum(AbbrevKind.enum_type));
370 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.enum_type));
371371 // DW.AT.byte_size, DW.FORM.udata
372372 try leb128.writeULEB128(dbg_info_buffer.writer(), ty.abiSize(mod));
373373 // DW.AT.name, DW.FORM.string
......@@ -379,7 +379,7 @@ pub const DeclState = struct {
379379 const field_name = ip.stringToSlice(field_name_index);
380380 // DW.AT.enumerator
381381 try dbg_info_buffer.ensureUnusedCapacity(field_name.len + 2 + @sizeOf(u64));
382 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.enum_variant));
382 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.enum_variant));
383383 // DW.AT.name, DW.FORM.string
384384 dbg_info_buffer.appendSliceAssumeCapacity(field_name);
385385 dbg_info_buffer.appendAssumeCapacity(0);
......@@ -409,7 +409,7 @@ pub const DeclState = struct {
409409 const is_tagged = layout.tag_size > 0;
410410 if (is_tagged) {
411411 // DW.AT.structure_type
412 try dbg_info_buffer.append(@intFromEnum(AbbrevKind.struct_type));
412 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_type));
413413 // DW.AT.byte_size, DW.FORM.udata
414414 try leb128.writeULEB128(dbg_info_buffer.writer(), layout.abi_size);
415415 // DW.AT.name, DW.FORM.string
......@@ -418,7 +418,7 @@ pub const DeclState = struct {
418418
419419 // DW.AT.member
420420 try dbg_info_buffer.ensureUnusedCapacity(9);
421 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.struct_member));
421 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_member));
422422 // DW.AT.name, DW.FORM.string
423423 dbg_info_buffer.appendSliceAssumeCapacity("payload");
424424 dbg_info_buffer.appendAssumeCapacity(0);
......@@ -431,7 +431,7 @@ pub const DeclState = struct {
431431 }
432432
433433 // DW.AT.union_type
434 try dbg_info_buffer.append(@intFromEnum(AbbrevKind.union_type));
434 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.union_type));
435435 // DW.AT.byte_size, DW.FORM.udata,
436436 try leb128.writeULEB128(dbg_info_buffer.writer(), layout.payload_size);
437437 // DW.AT.name, DW.FORM.string
......@@ -445,7 +445,7 @@ pub const DeclState = struct {
445445 for (union_obj.field_types.get(ip), union_obj.field_names.get(ip)) |field_ty, field_name| {
446446 if (!Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
447447 // DW.AT.member
448 try dbg_info_buffer.append(@intFromEnum(AbbrevKind.struct_member));
448 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_member));
449449 // DW.AT.name, DW.FORM.string
450450 try dbg_info_buffer.appendSlice(ip.stringToSlice(field_name));
451451 try dbg_info_buffer.append(0);
......@@ -462,7 +462,7 @@ pub const DeclState = struct {
462462 if (is_tagged) {
463463 // DW.AT.member
464464 try dbg_info_buffer.ensureUnusedCapacity(5);
465 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.struct_member));
465 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_member));
466466 // DW.AT.name, DW.FORM.string
467467 dbg_info_buffer.appendSliceAssumeCapacity("tag");
468468 dbg_info_buffer.appendAssumeCapacity(0);
......@@ -488,7 +488,7 @@ pub const DeclState = struct {
488488 const error_off = if (error_align.compare(.gte, payload_align)) 0 else payload_ty.abiSize(mod);
489489
490490 // DW.AT.structure_type
491 try dbg_info_buffer.append(@intFromEnum(AbbrevKind.struct_type));
491 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_type));
492492 // DW.AT.byte_size, DW.FORM.udata
493493 try leb128.writeULEB128(dbg_info_buffer.writer(), abi_size);
494494 // DW.AT.name, DW.FORM.string
......@@ -498,7 +498,7 @@ pub const DeclState = struct {
498498 if (!payload_ty.isNoReturn(mod)) {
499499 // DW.AT.member
500500 try dbg_info_buffer.ensureUnusedCapacity(7);
501 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.struct_member));
501 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_member));
502502 // DW.AT.name, DW.FORM.string
503503 dbg_info_buffer.appendSliceAssumeCapacity("value");
504504 dbg_info_buffer.appendAssumeCapacity(0);
......@@ -513,7 +513,7 @@ pub const DeclState = struct {
513513 {
514514 // DW.AT.member
515515 try dbg_info_buffer.ensureUnusedCapacity(5);
516 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.struct_member));
516 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_member));
517517 // DW.AT.name, DW.FORM.string
518518 dbg_info_buffer.appendSliceAssumeCapacity("err");
519519 dbg_info_buffer.appendAssumeCapacity(0);
......@@ -530,7 +530,7 @@ pub const DeclState = struct {
530530 },
531531 else => {
532532 log.debug("TODO implement .debug_info for type '{}'", .{ty.fmt(self.mod)});
533 try dbg_info_buffer.append(@intFromEnum(AbbrevKind.pad1));
533 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.zero_bit_type));
534534 },
535535 }
536536 }
......@@ -565,7 +565,7 @@ pub const DeclState = struct {
565565 switch (loc) {
566566 .register => |reg| {
567567 try dbg_info.ensureUnusedCapacity(4);
568 dbg_info.appendAssumeCapacity(@intFromEnum(AbbrevKind.parameter));
568 dbg_info.appendAssumeCapacity(@intFromEnum(AbbrevCode.parameter));
569569 // DW.AT.location, DW.FORM.exprloc
570570 var expr_len = std.io.countingWriter(std.io.null_writer);
571571 if (reg < 32) {
......@@ -587,7 +587,7 @@ pub const DeclState = struct {
587587 const reg_bytes: u8 = @intCast(@divExact(reg_bits, 8));
588588 const abi_size = ty.abiSize(self.mod);
589589 try dbg_info.ensureUnusedCapacity(10);
590 dbg_info.appendAssumeCapacity(@intFromEnum(AbbrevKind.parameter));
590 dbg_info.appendAssumeCapacity(@intFromEnum(AbbrevCode.parameter));
591591 // DW.AT.location, DW.FORM.exprloc
592592 var expr_len = std.io.countingWriter(std.io.null_writer);
593593 for (regs, 0..) |reg, reg_i| {
......@@ -620,7 +620,7 @@ pub const DeclState = struct {
620620 },
621621 .stack => |info| {
622622 try dbg_info.ensureUnusedCapacity(9);
623 dbg_info.appendAssumeCapacity(@intFromEnum(AbbrevKind.parameter));
623 dbg_info.appendAssumeCapacity(@intFromEnum(AbbrevCode.parameter));
624624 // DW.AT.location, DW.FORM.exprloc
625625 var expr_len = std.io.countingWriter(std.io.null_writer);
626626 if (info.fp_register < 32) {
......@@ -649,7 +649,7 @@ pub const DeclState = struct {
649649 // where each argument is encoded as
650650 // <opcode> i:uleb128
651651 dbg_info.appendSliceAssumeCapacity(&.{
652 @intFromEnum(AbbrevKind.parameter),
652 @intFromEnum(AbbrevCode.parameter),
653653 DW.OP.WASM_location,
654654 DW.OP.WASM_local,
655655 });
......@@ -676,7 +676,7 @@ pub const DeclState = struct {
676676 const dbg_info = &self.dbg_info;
677677 const atom_index = self.di_atom_decls.get(owner_decl).?;
678678 const name_with_null = name.ptr[0 .. name.len + 1];
679 try dbg_info.append(@intFromEnum(AbbrevKind.variable));
679 try dbg_info.append(@intFromEnum(AbbrevCode.variable));
680680 const gpa = self.dwarf.allocator;
681681 const mod = self.mod;
682682 const target = mod.getTarget();
......@@ -991,8 +991,10 @@ pub const ExprlocRelocation = struct {
991991
992992pub const PtrWidth = enum { p32, p64 };
993993
994pub const AbbrevKind = enum(u8) {
995 compile_unit = 1,
994pub const AbbrevCode = enum(u8) {
995 null,
996 padding,
997 compile_unit,
996998 subprogram,
997999 subprogram_retvoid,
9981000 base_type,
......@@ -1002,7 +1004,7 @@ pub const AbbrevKind = enum(u8) {
10021004 enum_type,
10031005 enum_variant,
10041006 union_type,
1005 pad1,
1007 zero_bit_type,
10061008 parameter,
10071009 variable,
10081010 array_type,
......@@ -1162,7 +1164,7 @@ pub fn initDeclState(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclInde
11621164 const fn_ret_type = decl.ty.fnReturnType(mod);
11631165 const fn_ret_has_bits = fn_ret_type.hasRuntimeBits(mod);
11641166 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(
1165 @as(AbbrevKind, if (fn_ret_has_bits) .subprogram else .subprogram_retvoid),
1167 @as(AbbrevCode, if (fn_ret_has_bits) .subprogram else .subprogram_retvoid),
11661168 ));
11671169 // These get overwritten after generating the machine code. These values are
11681170 // "relocations" and have to be in this fixed place so that functions can be
......@@ -1806,7 +1808,14 @@ pub fn writeDbgAbbrev(self: *Dwarf) !void {
18061808 // we can simply append these bytes.
18071809 // zig fmt: off
18081810 const abbrev_buf = [_]u8{
1809 @intFromEnum(AbbrevKind.compile_unit),
1811 @intFromEnum(AbbrevCode.padding),
1812 @as(u8, 0x80) | @as(u7, @truncate(DW.TAG.ZIG_padding >> 0)),
1813 @as(u8, 0x80) | @as(u7, @truncate(DW.TAG.ZIG_padding >> 7)),
1814 @as(u8, 0x00) | @as(u7, @intCast(DW.TAG.ZIG_padding >> 14)),
1815 DW.CHILDREN.no,
1816 0, 0,
1817
1818 @intFromEnum(AbbrevCode.compile_unit),
18101819 DW.TAG.compile_unit,
18111820 DW.CHILDREN.yes,
18121821 DW.AT.stmt_list, DW.FORM.sec_offset,
......@@ -1818,7 +1827,7 @@ pub fn writeDbgAbbrev(self: *Dwarf) !void {
18181827 DW.AT.language, DW.FORM.data2,
18191828 0, 0,
18201829
1821 @intFromEnum(AbbrevKind.subprogram),
1830 @intFromEnum(AbbrevCode.subprogram),
18221831 DW.TAG.subprogram,
18231832 DW.CHILDREN.yes,
18241833 DW.AT.low_pc, DW.FORM.addr,
......@@ -1828,7 +1837,7 @@ pub fn writeDbgAbbrev(self: *Dwarf) !void {
18281837 DW.AT.linkage_name, DW.FORM.string,
18291838 0, 0,
18301839
1831 @intFromEnum(AbbrevKind.subprogram_retvoid),
1840 @intFromEnum(AbbrevCode.subprogram_retvoid),
18321841 DW.TAG.subprogram,
18331842 DW.CHILDREN.yes,
18341843 DW.AT.low_pc, DW.FORM.addr,
......@@ -1837,25 +1846,25 @@ pub fn writeDbgAbbrev(self: *Dwarf) !void {
18371846 DW.AT.linkage_name, DW.FORM.string,
18381847 0, 0,
18391848
1840 @intFromEnum(AbbrevKind.base_type),
1849 @intFromEnum(AbbrevCode.base_type),
18411850 DW.TAG.base_type, DW.CHILDREN.no,
18421851 DW.AT.encoding, DW.FORM.data1,
18431852 DW.AT.byte_size, DW.FORM.udata,
18441853 DW.AT.name, DW.FORM.string,
18451854 0, 0,
18461855
1847 @intFromEnum(AbbrevKind.ptr_type),
1856 @intFromEnum(AbbrevCode.ptr_type),
18481857 DW.TAG.pointer_type, DW.CHILDREN.no,
18491858 DW.AT.type, DW.FORM.ref4,
18501859 0, 0,
18511860
1852 @intFromEnum(AbbrevKind.struct_type),
1861 @intFromEnum(AbbrevCode.struct_type),
18531862 DW.TAG.structure_type, DW.CHILDREN.yes,
18541863 DW.AT.byte_size, DW.FORM.udata,
18551864 DW.AT.name, DW.FORM.string,
18561865 0, 0,
18571866
1858 @intFromEnum(AbbrevKind.struct_member),
1867 @intFromEnum(AbbrevCode.struct_member),
18591868 DW.TAG.member,
18601869 DW.CHILDREN.no,
18611870 DW.AT.name, DW.FORM.string,
......@@ -1863,31 +1872,31 @@ pub fn writeDbgAbbrev(self: *Dwarf) !void {
18631872 DW.AT.data_member_location, DW.FORM.udata,
18641873 0, 0,
18651874
1866 @intFromEnum(AbbrevKind.enum_type),
1875 @intFromEnum(AbbrevCode.enum_type),
18671876 DW.TAG.enumeration_type,
18681877 DW.CHILDREN.yes,
18691878 DW.AT.byte_size, DW.FORM.udata,
18701879 DW.AT.name, DW.FORM.string,
18711880 0, 0,
18721881
1873 @intFromEnum(AbbrevKind.enum_variant),
1882 @intFromEnum(AbbrevCode.enum_variant),
18741883 DW.TAG.enumerator, DW.CHILDREN.no,
18751884 DW.AT.name, DW.FORM.string,
18761885 DW.AT.const_value, DW.FORM.data8,
18771886 0, 0,
18781887
1879 @intFromEnum(AbbrevKind.union_type),
1888 @intFromEnum(AbbrevCode.union_type),
18801889 DW.TAG.union_type, DW.CHILDREN.yes,
18811890 DW.AT.byte_size, DW.FORM.udata,
18821891 DW.AT.name, DW.FORM.string,
18831892 0, 0,
18841893
1885 @intFromEnum(AbbrevKind.pad1),
1894 @intFromEnum(AbbrevCode.zero_bit_type),
18861895 DW.TAG.unspecified_type,
18871896 DW.CHILDREN.no,
18881897 0, 0,
18891898
1890 @intFromEnum(AbbrevKind.parameter),
1899 @intFromEnum(AbbrevCode.parameter),
18911900 DW.TAG.formal_parameter,
18921901 DW.CHILDREN.no,
18931902 DW.AT.location, DW.FORM.exprloc,
......@@ -1895,7 +1904,7 @@ pub fn writeDbgAbbrev(self: *Dwarf) !void {
18951904 DW.AT.name, DW.FORM.string,
18961905 0, 0,
18971906
1898 @intFromEnum(AbbrevKind.variable),
1907 @intFromEnum(AbbrevCode.variable),
18991908 DW.TAG.variable,
19001909 DW.CHILDREN.no,
19011910 DW.AT.location, DW.FORM.exprloc,
......@@ -1903,14 +1912,14 @@ pub fn writeDbgAbbrev(self: *Dwarf) !void {
19031912 DW.AT.name, DW.FORM.string,
19041913 0, 0,
19051914
1906 @intFromEnum(AbbrevKind.array_type),
1915 @intFromEnum(AbbrevCode.array_type),
19071916 DW.TAG.array_type,
19081917 DW.CHILDREN.yes,
19091918 DW.AT.name, DW.FORM.string,
19101919 DW.AT.type, DW.FORM.ref4,
19111920 0, 0,
19121921
1913 @intFromEnum(AbbrevKind.array_dim),
1922 @intFromEnum(AbbrevCode.array_dim),
19141923 DW.TAG.subrange_type,
19151924 DW.CHILDREN.no,
19161925 DW.AT.type, DW.FORM.ref4,
......@@ -2007,7 +2016,7 @@ pub fn writeDbgInfoHeader(self: *Dwarf, zcu: *Module, low_pc: u64, high_pc: u64)
20072016 const comp_dir_strp = try self.strtab.insert(self.allocator, compile_unit_dir);
20082017 const producer_strp = try self.strtab.insert(self.allocator, link.producer_string);
20092018
2010 di_buf.appendAssumeCapacity(@intFromEnum(AbbrevKind.compile_unit));
2019 di_buf.appendAssumeCapacity(@intFromEnum(AbbrevCode.compile_unit));
20112020 self.writeOffsetAssumeCapacity(&di_buf, 0); // DW.AT.stmt_list, DW.FORM.sec_offset
20122021 self.writeAddrAssumeCapacity(&di_buf, low_pc);
20132022 self.writeAddrAssumeCapacity(&di_buf, high_pc);
......@@ -2226,7 +2235,7 @@ fn pwriteDbgInfoNops(
22262235 const tracy = trace(@src());
22272236 defer tracy.end();
22282237
2229 const page_of_nops = [1]u8{@intFromEnum(AbbrevKind.pad1)} ** 4096;
2238 const page_of_nops = [1]u8{@intFromEnum(AbbrevCode.padding)} ** 4096;
22302239 var vecs: [32]std.os.iovec_const = undefined;
22312240 var vec_index: usize = 0;
22322241 {
......@@ -2298,9 +2307,9 @@ fn writeDbgInfoNopsToArrayList(
22982307 buffer.items.len,
22992308 offset + content.len + next_padding_size + 1,
23002309 ));
2301 @memset(buffer.items[offset - prev_padding_size .. offset], @intFromEnum(AbbrevKind.pad1));
2310 @memset(buffer.items[offset - prev_padding_size .. offset], @intFromEnum(AbbrevCode.padding));
23022311 @memcpy(buffer.items[offset..][0..content.len], content);
2303 @memset(buffer.items[offset + content.len ..][0..next_padding_size], @intFromEnum(AbbrevKind.pad1));
2312 @memset(buffer.items[offset + content.len ..][0..next_padding_size], @intFromEnum(AbbrevCode.padding));
23042313
23052314 if (trailing_zero) {
23062315 buffer.items[offset + content.len + next_padding_size] = 0;
......@@ -2842,7 +2851,7 @@ fn addDbgInfoErrorSetNames(
28422851 const target_endian = target.cpu.arch.endian();
28432852
28442853 // DW.AT.enumeration_type
2845 try dbg_info_buffer.append(@intFromEnum(AbbrevKind.enum_type));
2854 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.enum_type));
28462855 // DW.AT.byte_size, DW.FORM.udata
28472856 const abi_size = Type.anyerror.abiSize(mod);
28482857 try leb128.writeULEB128(dbg_info_buffer.writer(), abi_size);
......@@ -2853,7 +2862,7 @@ fn addDbgInfoErrorSetNames(
28532862 // DW.AT.enumerator
28542863 const no_error = "(no error)";
28552864 try dbg_info_buffer.ensureUnusedCapacity(no_error.len + 2 + @sizeOf(u64));
2856 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.enum_variant));
2865 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.enum_variant));
28572866 // DW.AT.name, DW.FORM.string
28582867 dbg_info_buffer.appendSliceAssumeCapacity(no_error);
28592868 dbg_info_buffer.appendAssumeCapacity(0);
......@@ -2865,7 +2874,7 @@ fn addDbgInfoErrorSetNames(
28652874 const error_name = mod.intern_pool.stringToSlice(error_name_ip);
28662875 // DW.AT.enumerator
28672876 try dbg_info_buffer.ensureUnusedCapacity(error_name.len + 2 + @sizeOf(u64));
2868 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.enum_variant));
2877 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.enum_variant));
28692878 // DW.AT.name, DW.FORM.string
28702879 dbg_info_buffer.appendSliceAssumeCapacity(error_name);
28712880 dbg_info_buffer.appendAssumeCapacity(0);