authorgravatar for kcbanner@gmail.comCasey Banner <kcbanner@gmail.com> 2026-06-05 01:55:36-04:00
committergravatar for kcbanner@gmail.comCasey Banner <kcbanner@gmail.com> 2026-06-23 00:27:14-04:00
log1c6d19b0ff6c816cf9f73507e7e4ff35b19a1e1d
tree00f0bd41894a6d55f7552960516b94a64c9c2f18
parentab46b8235450cd1d8cb1a483859c2265588a1863

tests: more work on the linker snapshot testing framework

build: add the ability to test the output of a Run step against a snapshot objdump: add --redact, --omit-element, --snapshot, and --only-symbol

11 files changed, 634 insertions(+), 344 deletions(-)

lib/compiler/Maker/Step/Run.zig+47-2
......@@ -2100,6 +2100,47 @@ fn runCommand(
21002100 });
21012101 }
21022102 }
2103 const snapshots: []const ?struct {
2104 path: Cache.Path,
2105 result: enum { stderr, stdout },
2106 } = &.{
2107 if (conf_run.expect_stderr_snapshot.value) |path| .{
2108 .path = try maker.resolveLazyPathIndex(arena, path, run_index),
2109 .result = .stderr,
2110 } else null,
2111 if (conf_run.expect_stdout_snapshot.value) |path| .{
2112 .path = try maker.resolveLazyPathIndex(arena, path, run_index),
2113 .result = .stdout,
2114 } else null,
2115 };
2116 for (snapshots) |opt_snapshot| {
2117 const snapshot = opt_snapshot orelse continue;
2118
2119 const file = snapshot.path.root_dir.handle.openFile(io, snapshot.path.sub_path, .{}) catch |err|
2120 return step.fail(maker, "unable to open snapshot file {f}: {t}", .{ snapshot.path, err });
2121 defer file.close(io);
2122
2123 var file_reader = file.reader(io, &.{});
2124 const snapshot_contents = file_reader.interface.allocRemaining(gpa, .unlimited) catch |err|
2125 return step.fail(maker, "unable to read snapshot file {f}: {t}", .{ snapshot.path, err });
2126 defer gpa.free(snapshot_contents);
2127
2128 const result = switch (snapshot.result) {
2129 .stdout => generic_result.stdout.?,
2130 .stderr => generic_result.stderr.?,
2131 };
2132 if (!mem.eql(u8, snapshot_contents, result)) {
2133 return step.fail(maker,
2134 \\
2135 \\========= snapshot file: =========
2136 \\{f}
2137 \\========= contained: =============
2138 \\{s}
2139 \\========= {t} output was: ========
2140 \\{s}
2141 , .{ snapshot.path, snapshot_contents, snapshot.result, result });
2142 }
2143 }
21032144 },
21042145 else => {
21052146 // On failure, report captured stderr like normal standard error output.
......@@ -2283,11 +2324,15 @@ fn setColorEnvironmentVariables(
22832324}
22842325
22852326fn checksContainStdout(conf_run: *const Configuration.Step.Run) bool {
2286 return conf_run.expect_stdout_exact.value != null or conf_run.expect_stdout_match.slice.len != 0;
2327 return conf_run.expect_stdout_exact.value != null or
2328 conf_run.expect_stdout_match.slice.len != 0 or
2329 conf_run.expect_stdout_snapshot.value != null;
22872330}
22882331
22892332fn checksContainStderr(conf_run: *const Configuration.Step.Run) bool {
2290 return conf_run.expect_stderr_exact.value != null or conf_run.expect_stderr_match.slice.len != 0;
2333 return conf_run.expect_stderr_exact.value != null or
2334 conf_run.expect_stderr_match.slice.len != 0 or
2335 conf_run.expect_stderr_snapshot.value != null;
22912336}
22922337
22932338/// If `path` is cwd-relative, make it relative to the cwd of the child instead.
lib/compiler/configurer.zig+8
......@@ -1006,6 +1006,8 @@ fn serialize(b: *std.Build, wc: *Configuration.Wip, writer: *Io.Writer) !void {
10061006 status: Configuration.Step.Run.ExpectTermStatus,
10071007 value: u32,
10081008 } = null;
1009 var expect_stderr_snapshot: ?Configuration.LazyPath.Index = null;
1010 var expect_stdout_snapshot: ?Configuration.LazyPath.Index = null;
10091011 switch (run.stdio) {
10101012 .check => |checks| for (checks.items) |check| switch (check) {
10111013 .expect_stderr_exact => |bytes| expect_stderr_exact = try wc.addBytes(bytes),
......@@ -1022,6 +1024,8 @@ fn serialize(b: *std.Build, wc: *Configuration.Wip, writer: *Io.Writer) !void {
10221024 .stopped => |x| .{ .status = .stopped, .value = @intFromEnum(x) },
10231025 .unknown => |x| .{ .status = .unknown, .value = x },
10241026 },
1027 .expect_stderr_snapshot => |path| expect_stderr_snapshot = try s.addLazyPath(path),
1028 .expect_stdout_snapshot => |path| expect_stdout_snapshot = try s.addLazyPath(path),
10251029 },
10261030 else => {},
10271031 }
......@@ -1061,6 +1065,8 @@ fn serialize(b: *std.Build, wc: *Configuration.Wip, writer: *Io.Writer) !void {
10611065 .expect_stdout_match = expect_stdout_match.items.len != 0,
10621066 .expect_term = expect_term != null,
10631067 .expect_term_status = if (expect_term) |t| t.status else .exited,
1068 .expect_stderr_snapshot = expect_stderr_snapshot != null,
1069 .expect_stdout_snapshot = expect_stdout_snapshot != null,
10641070 },
10651071 .file_inputs = .{ .slice = try s.initLazyPathList(run.file_inputs.items) },
10661072 .args = .{ .slice = try s.initArgsList(run.argv.items) },
......@@ -1081,6 +1087,8 @@ fn serialize(b: *std.Build, wc: *Configuration.Wip, writer: *Io.Writer) !void {
10811087 .expect_stdout_exact = .{ .value = if (expect_stdout_exact) |bytes| bytes else null },
10821088 .expect_stderr_match = .{ .slice = expect_stderr_match.items },
10831089 .expect_stdout_match = .{ .slice = expect_stdout_match.items },
1090 .expect_stderr_snapshot = .{ .value = expect_stderr_snapshot orelse null },
1091 .expect_stdout_snapshot = .{ .value = expect_stdout_snapshot orelse null },
10841092 .stdin = .{ .u = switch (run.stdin) {
10851093 .none => .none,
10861094 .bytes => |bytes| .{ .bytes = try wc.addBytes(bytes) },
lib/compiler/objdump.zig+448-297
......@@ -16,9 +16,12 @@ const Options = struct {
1616 input_path: []const u8,
1717 member_filters: []const []const u8 = &.{},
1818 member_headers: bool,
19 omit_elements: std.enums.EnumArray(Element, bool),
20 redact: std.enums.EnumArray(FieldKind, bool),
1921 relocs: bool,
2022 section_filters: []const []const u8 = &.{},
2123 section_headers: bool,
24 symbol_filters: []const []const u8 = &.{},
2225 strings: bool,
2326 symbols: bool,
2427 tls: bool,
......@@ -27,6 +30,20 @@ const Options = struct {
2730 linker_member: ?std.coff.ArchiveMemberHeader.Kind,
2831};
2932
33const FieldKind = enum {
34 va,
35 rva,
36 ord,
37 size,
38};
39
40const Element = enum {
41 @"file-type",
42 @"table-header",
43 @"header-names",
44 newlines,
45};
46
3047pub fn main(init: std.process.Init) !void {
3148 const io = init.io;
3249 const args = try init.minimal.args.toSlice(init.arena.allocator());
......@@ -40,12 +57,15 @@ pub fn main(init: std.process.Init) !void {
4057 var opt_input_path: ?[]const u8 = null;
4158 var opt_linker_member: ?std.coff.ArchiveMemberHeader.Kind = null;
4259 var opt_member_headers: ?bool = null;
60 var omit_elements: @FieldType(Options, "omit_elements") = .initFill(false);
61 var redact: @FieldType(Options, "redact") = .initFill(false);
4362 var opt_relocs: ?bool = null;
4463 var opt_section_headers: ?bool = null;
4564 var opt_strings: ?bool = null;
4665 var opt_symbols: ?bool = null;
4766 var opt_tls: ?bool = null;
4867 var section_filters: std.ArrayList([]const u8) = .empty;
68 var symbol_filters: std.ArrayList([]const u8) = .empty;
4969 var member_filters: std.ArrayList([]const u8) = .empty;
5070 while (i < args.len) : (i += 1) {
5171 const arg = args[i];
......@@ -73,14 +93,37 @@ pub fn main(init: std.process.Init) !void {
7393 opt_linker_member = .second_linker;
7494 } else if (mem.eql(u8, arg, "--member-headers")) {
7595 opt_member_headers = true;
76 } else if (mem.startsWith(u8, arg, "--only-section=")) {
77 (try section_filters.addOne(arena)).* = try arena.dupe(u8, arg["--only-section=".len..]);
96 } else if (mem.startsWith(u8, arg, "--omit-element=")) {
97 const kind = arg["--omit-element=".len..];
98 if (std.meta.stringToEnum(Element, kind)) |format_kind| {
99 omit_elements.set(format_kind, true);
100 } else if (std.mem.eql(u8, kind, "all")) {
101 omit_elements = .initFill(true);
102 } else {
103 fatal("unrecognized element: {s}", .{kind});
104 }
78105 } else if (mem.startsWith(u8, arg, "--only-member=")) {
79106 (try member_filters.addOne(arena)).* = try arena.dupe(u8, arg["--only-member=".len..]);
107 } else if (mem.startsWith(u8, arg, "--only-section=")) {
108 (try section_filters.addOne(arena)).* = try arena.dupe(u8, arg["--only-section=".len..]);
109 } else if (mem.startsWith(u8, arg, "--only-symbol=")) {
110 (try symbol_filters.addOne(arena)).* = try arena.dupe(u8, arg["--only-symbol=".len..]);
111 } else if (mem.startsWith(u8, arg, "--redact=")) {
112 const kind = arg["--redact=".len..];
113 if (std.meta.stringToEnum(FieldKind, kind)) |field_kind| {
114 redact.set(field_kind, true);
115 } else if (std.mem.eql(u8, kind, "all")) {
116 redact = .initFill(true);
117 } else {
118 fatal("unrecognized redaction kind: {s}", .{kind});
119 }
80120 } else if (mem.eql(u8, arg, "--relocs")) {
81121 opt_relocs = true;
82122 } else if (mem.eql(u8, arg, "--section-headers")) {
83123 opt_section_headers = true;
124 } else if (mem.eql(u8, arg, "-s") or mem.eql(u8, arg, "--snapshot")) {
125 omit_elements = .initFill(true);
126 redact = .initFill(true);
84127 } else if (mem.eql(u8, arg, "--strings")) {
85128 opt_strings = true;
86129 } else if (mem.eql(u8, arg, "--symbols")) {
......@@ -105,10 +148,13 @@ pub fn main(init: std.process.Init) !void {
105148 .linker_member = opt_linker_member,
106149 .member_filters = member_filters.items,
107150 .member_headers = opt_member_headers orelse false,
151 .omit_elements = omit_elements,
152 .redact = redact,
153 .relocs = opt_relocs orelse false,
108154 .section_filters = section_filters.items,
109155 .section_headers = opt_section_headers orelse false,
110 .relocs = opt_relocs orelse false,
111156 .strings = opt_strings orelse false,
157 .symbol_filters = symbol_filters.items,
112158 .symbols = opt_symbols orelse false,
113159 .tls = opt_tls orelse false,
114160 };
......@@ -120,7 +166,15 @@ pub fn main(init: std.process.Init) !void {
120166 var buffer: [4096]u8 = undefined;
121167 var file_reader = file.reader(io, &buffer);
122168 var stdout_writer = std.Io.File.stdout().writerStreaming(io, &stdout_buffer);
123 dump(init.gpa, &opts, &file_reader, &stdout_writer.interface) catch |err| switch (err) {
169
170 const ctx: DumpContext = .{
171 .gpa = init.gpa,
172 .opts = &opts,
173 .fr = &file_reader,
174 .w = &stdout_writer.interface,
175 };
176
177 dump(&ctx) catch |err| switch (err) {
124178 error.ReadFailed => return file_reader.err.?,
125179 error.WriteFailed => return stdout_writer.err.?,
126180 error.UnknownFile => fatal("unrecognized file: {s}", .{opts.input_path}),
......@@ -130,60 +184,82 @@ pub fn main(init: std.process.Init) !void {
130184 try stdout_writer.flush();
131185}
132186
133fn dump(gpa: std.mem.Allocator, opts: *const Options, fr: *Io.File.Reader, w: *Io.Writer) !void {
134 const r = &fr.interface;
187fn dump(d: *const DumpContext) !void {
188 const r = &d.fr.interface;
135189 try r.fill(4);
136190 elf: {
137191 if (!mem.eql(u8, r.buffered()[0..4], std.elf.MAGIC)) break :elf;
138 return elf.dump(r, w);
192 return elf.dump(r, d.w);
139193 }
140194 macho: {
141195 if (mem.readInt(u32, r.buffered()[0..4], .little) != std.macho.MH_MAGIC_64) break :macho;
142 return macho.dump(r, w);
196 return macho.dump(r, d.w);
143197 }
144198 wasm: {
145199 comptime assert(std.wasm.magic.len == 4);
146200 if (!mem.eql(u8, r.buffered()[0..4], &std.wasm.magic)) break :wasm;
147 return wasm.dump(r, w);
201 return wasm.dump(r, d.w);
148202 }
149203 coff: {
150 const ext = std.fs.path.extension(opts.input_path);
151 const basename = std.fs.path.basename(opts.input_path);
204 const ext = std.fs.path.extension(d.opts.input_path);
205 const basename = std.fs.path.basename(d.opts.input_path);
152206 if (std.mem.eql(u8, ext, ".exe") or std.mem.eql(u8, ext, ".dll")) {
153207 if (!mem.eql(u8, r.buffered()[0..2], "MZ")) break :coff;
154208 try r.discardAll(std.coff.pe_pointer_offset);
155209 const sig_offset = try r.takeInt(u32, .little);
156 try fr.seekTo(sig_offset);
210 try d.fr.seekTo(sig_offset);
157211 const sig = try r.take(4);
158212
159213 if (!std.mem.eql(u8, sig, std.coff.pe_signature)) {
160 try w.print("invalid PE signature: {x}", .{sig});
214 try d.w.print("invalid PE signature: {x}", .{sig});
161215 return error.ParseFailure;
162216 }
163217
164 try w.print("{s}: PE/COFF image\n\n", .{basename});
165 return coff.dumpObject(gpa, opts, true, basename, fr, w);
218 if (d.element(.@"file-type"))
219 try d.w.print("{s}: PE/COFF image\n\n", .{basename});
220
221 return coff.dumpObject(d, true, basename);
166222 } else if (std.mem.eql(u8, ext, ".lib")) {
167223 r.fill(std.coff.archive_signature.len) catch break :coff;
168224 if (!mem.eql(u8, r.buffered()[0..std.coff.archive_signature.len], std.coff.archive_signature)) break :coff;
169 try w.print("{s}: COFF archive\n\n", .{basename});
170 return coff.dumpArchive(gpa, opts, fr, w);
225 if (d.element(.@"file-type"))
226 try d.w.print("{s}: COFF archive\n\n", .{basename});
227
228 return coff.dumpArchive(d);
171229 } else if (std.mem.eql(u8, ext, ".obj")) {
172 try w.print("{s}: COFF object\n\n", .{basename});
173 return coff.dumpObject(gpa, opts, false, basename, fr, w);
230 if (d.element(.@"file-type"))
231 try d.w.print("{s}: COFF object\n\n", .{basename});
232
233 return coff.dumpObject(d, false, basename);
174234 }
175235 }
176236 return error.UnknownFile;
177237}
178238
179fn failParse(
239const DumpContext = struct {
240 gpa: std.mem.Allocator,
180241 opts: *const Options,
181 comptime fmt: []const u8,
182 args: anytype,
183) noreturn {
184 std.log.err("error parsing '{s}'", .{std.fs.path.basename(opts.input_path)});
185 fatal(fmt, args);
186}
242 fr: *Io.File.Reader,
243 w: *Io.Writer,
244
245 fn element(self: *const DumpContext, e: Element) bool {
246 return !self.opts.omit_elements.get(e);
247 }
248
249 fn redacted(self: *const DumpContext, opt_kind: ?FieldKind) bool {
250 const kind = opt_kind orelse return false;
251 return self.opts.redact.get(kind);
252 }
253
254 fn failParse(
255 ctx: *const DumpContext,
256 comptime fmt: []const u8,
257 args: anytype,
258 ) noreturn {
259 std.log.err("error parsing '{s}'", .{std.fs.path.basename(ctx.opts.input_path)});
260 fatal(fmt, args);
261 }
262};
187263
188264const elf = struct {
189265 fn dump(r: *Io.Reader, w: *Io.Writer) !void {
......@@ -230,29 +306,33 @@ const coff = struct {
230306 file_mode: u24,
231307 size: u34,
232308
233 pub fn fromRaw(opts: *const Options, raw_header: *const std.coff.ArchiveMemberHeader, opt_longnames: ?[]const u8) @This() {
309 pub fn fromRaw(d: *const DumpContext, raw_header: *const std.coff.ArchiveMemberHeader, opt_longnames: ?[]const u8) @This() {
234310 const name = raw_header.parseName(opt_longnames) catch |err| switch (err) {
235 error.BadName => failParse(opts, "malformed member name: '{s}'", .{&raw_header.name}),
236 error.NoLongNames => failParse(opts, "member uses a long name, but there was no longnames member", .{}),
311 error.BadName => d.failParse("malformed member name: '{s}'", .{&raw_header.name}),
312 error.NoLongNames => d.failParse("member uses a long name, but there was no longnames member", .{}),
237313 };
238314
239315 return .{
240316 .name = name,
241317 .date = raw_header.parseDate() catch |err|
242 failParse(opts, "unable to parse date '{s}' in member '{s}': {t}", .{ raw_header.date, name, err }),
318 d.failParse("unable to parse date '{s}' in member '{s}': {t}", .{ raw_header.date, name, err }),
243319 .user_id = raw_header.parseUserId() catch |err|
244 failParse(opts, "unable to parse user_id '{s}' in member '{s}': {t}", .{ raw_header.user_id, name, err }),
320 d.failParse("unable to parse user_id '{s}' in member '{s}': {t}", .{ raw_header.user_id, name, err }),
245321 .group_id = raw_header.parseGroupId() catch |err|
246 failParse(opts, "unable to parse group_id '{s}' in member '{s}': {t}", .{ raw_header.group_id, name, err }),
322 d.failParse("unable to parse group_id '{s}' in member '{s}': {t}", .{ raw_header.group_id, name, err }),
247323 .file_mode = raw_header.parseFileMode() catch |err|
248 failParse(opts, "unable to parse file_mode '{s}' in member '{s}': {t}", .{ raw_header.file_mode, name, err }),
324 d.failParse("unable to parse file_mode '{s}' in member '{s}': {t}", .{ raw_header.file_mode, name, err }),
249325 .size = raw_header.parseSize() catch |err|
250 failParse(opts, "unable to parse size '{s}' in member '{s}': {t}", .{ raw_header.size, name, err }),
326 d.failParse("unable to parse size '{s}' in member '{s}': {t}", .{ raw_header.size, name, err }),
251327 };
252328 }
253329 };
254330
255 fn dumpArchive(gpa: std.mem.Allocator, opts: *const Options, fr: *Io.File.Reader, w: *Io.Writer) !void {
331 fn dumpArchive(d: *const DumpContext) !void {
332 const gpa = d.gpa;
333 const fr = d.fr;
334 const w = d.w;
335
256336 const r = &fr.interface;
257337 r.toss(std.coff.archive_signature.len);
258338
......@@ -272,26 +352,26 @@ const coff = struct {
272352 while (pos < size) : (pos = fr.logicalPos()) {
273353 if ((pos & 1) != 0) try r.discardAll(1);
274354 const raw_header = try r.takeStruct(std.coff.ArchiveMemberHeader, .little);
275 const header: ArchiveHeader = .fromRaw(opts, &raw_header, opt_longnames);
355 const header: ArchiveHeader = .fromRaw(d, &raw_header, opt_longnames);
276356
277357 if (!std.mem.eql(u8, &raw_header.end_of_header, std.coff.archive_end_of_header))
278 return failParse(opts, "malformed end-of-header field in member '{s}': {x}", .{ header.name, raw_header.end_of_header });
358 return d.failParse("malformed end-of-header field in member '{s}': {x}", .{ header.name, raw_header.end_of_header });
279359
280360 const dump_header =
281 (opts.member_headers and filterMatches(opts.member_filters, header.name)) or
282 (opts.linker_member == opt_expected_kind);
361 (d.opts.member_headers and filterMatches(d.opts.member_filters, header.name)) or
362 (d.opts.linker_member == opt_expected_kind);
283363
284364 if (dump_header)
285 try dumpArchiveHeader(w, &header, @intCast(pos));
365 try dumpArchiveHeader(d, &header, @intCast(pos));
286366
287367 const member_end = fr.logicalPos() + header.size;
288368 if (member_end > size)
289 return failParse(opts, "out-of-bounds length 0x{x} in member '{s}'", .{ header.size, header.name });
369 return d.failParse("out-of-bounds length 0x{x} in member '{s}'", .{ header.size, header.name });
290370
291371 if (opt_expected_kind) |expected_kind| switch (expected_kind) {
292372 .first_linker => {
293373 if (!std.mem.eql(u8, header.name, "/"))
294 return failParse(opts, "expected first linker member, found '{s}'", .{header.name});
374 return d.failParse("expected first linker member, found '{s}'", .{header.name});
295375
296376 const num_symbols = try r.takeInt(u32, .big);
297377 if (dump_header)
......@@ -301,7 +381,7 @@ const coff = struct {
301381 \\
302382 , .{ expected_kind, num_symbols });
303383
304 if (opts.linker_member == .first_linker) {
384 if (d.opts.linker_member == .first_linker) {
305385 try w.writeAll(
306386 \\
307387 \\Archive symbols:
......@@ -314,11 +394,15 @@ const coff = struct {
314394
315395 for (0..num_symbols) |symbol_i| {
316396 const symbol = r.takeDelimiter(0) catch |err|
317 return failParse(opts, "unable to read first linker member string table: {t}", .{err});
318 try w.print("{x: >8} {s}\n", .{ std.mem.readInt(u32, offsets[symbol_i * 4 ..][0..4], .big), symbol.? });
397 return d.failParse("unable to read first linker member string table: {t}", .{err});
398 const offset = std.mem.readInt(u32, offsets[symbol_i * 4 ..][0..4], .big);
399 try w.print("{f} {s}\n", .{
400 fmtIntField(d, offset, .{ .kind = .va }),
401 symbol.?,
402 });
319403 }
320404 }
321 if (dump_header) try w.writeByte('\n');
405 if (dump_header and d.element(.newlines)) try w.writeByte('\n');
322406
323407 try fr.seekTo(member_end);
324408 opt_expected_kind = .second_linker;
......@@ -326,12 +410,12 @@ const coff = struct {
326410 },
327411 .second_linker => {
328412 if (!std.mem.eql(u8, header.name, "/"))
329 return failParse(opts, "expected second linker member, found '{s}'", .{header.name});
413 return d.failParse("expected second linker member, found '{s}'", .{header.name});
330414
331415 const num_members = try r.takeInt(u32, .little);
332416 pos = fr.logicalPos();
333417 if (pos + num_members * @sizeOf(u32) > member_end)
334 return failParse(opts, "invalid member count 0x{x} in second linker member", .{num_members});
418 return d.failParse("invalid member count 0x{x} in second linker member", .{num_members});
335419
336420 try members.ensureTotalCapacity(gpa, num_members);
337421 for (0..num_members) |_|
......@@ -342,7 +426,7 @@ const coff = struct {
342426 const num_symbols = try r.takeInt(u32, .little);
343427 pos = fr.logicalPos();
344428 if (pos + num_symbols * @sizeOf(u16) > member_end)
345 return failParse(opts, "invalid symbol count 0x{x} in second linker member", .{num_symbols});
429 return d.failParse("invalid symbol count 0x{x} in second linker member", .{num_symbols});
346430
347431 if (dump_header)
348432 try w.print(
......@@ -356,13 +440,14 @@ const coff = struct {
356440 for (0..num_symbols) |_|
357441 symbol_member_indices.addOneAssumeCapacity().* = (try r.takeInt(u16, .little)) - 1;
358442
359 if (opts.linker_member == .second_linker) {
360 try w.writeAll(
361 \\
362 \\Archive Symbols:
363 \\& Member Symbol
364 \\
365 );
443 if (d.opts.linker_member == .second_linker) {
444 if (d.element(.@"table-header"))
445 try w.writeAll(
446 \\
447 \\Archive Symbols:
448 \\& Member Symbol
449 \\
450 );
366451
367452 pos = fr.logicalPos();
368453 var symbol_i: u32 = 0;
......@@ -373,23 +458,26 @@ const coff = struct {
373458 const symbol_name = if (r.takeDelimiter(0) catch |err| switch (err) {
374459 error.StreamTooLong => null,
375460 else => |e| return e,
376 }) |n| n else return failParse(opts, "unterminated string found in second linker member", .{});
377
378 try w.print("{x: >8} {s}\n", .{
379 members.items[symbol_member_indices.items[symbol_i]].offset,
461 }) |n| n else return d.failParse("unterminated string found in second linker member", .{});
462
463 try w.print("{f} {s}\n", .{
464 fmtIntField(
465 d,
466 members.items[symbol_member_indices.items[symbol_i]].offset,
467 .{ .kind = .va },
468 ),
380469 symbol_name,
381470 });
382471 }
383472
384473 if (symbol_i != num_symbols)
385 return failParse(
386 opts,
474 return d.failParse(
387475 " expected {d} entries in second linker member string table, but found {d}",
388476 .{ num_symbols, symbol_i },
389477 );
390478 }
391479
392 try w.writeByte('\n');
480 if (d.element(.newlines)) try w.writeByte('\n');
393481 try fr.seekTo(member_end);
394482 opt_expected_kind = .longnames;
395483 continue;
......@@ -401,12 +489,13 @@ const coff = struct {
401489 if (dump_header)
402490 try w.print("{t: >16} type\n", .{expected_kind});
403491
404 if (opts.linker_member == .longnames) {
405 try w.print(
406 \\
407 \\Longnames (0x{x} bytes):
408 \\
409 , .{opt_longnames.?.len});
492 if (d.opts.linker_member == .longnames) {
493 if (d.element(.@"table-header"))
494 try w.print(
495 \\
496 \\Longnames (0x{x} bytes):
497 \\
498 , .{opt_longnames.?.len});
410499
411500 var lr = Io.Reader.fixed(opt_longnames.?);
412501 while (try lr.takeDelimiter(0)) |str| {
......@@ -415,7 +504,7 @@ const coff = struct {
415504 }
416505 }
417506
418 try w.writeByte('\n');
507 if (d.element(.newlines)) try w.writeByte('\n');
419508 }
420509
421510 opt_expected_kind = null;
......@@ -426,18 +515,18 @@ const coff = struct {
426515 }
427516
428517 if (opt_expected_kind) |expected_kind| switch (expected_kind) {
429 .first_linker => failParse(opts, "missing first linker member", .{}),
430 .second_linker => failParse(opts, "missing second linker member", .{}),
518 .first_linker => d.failParse("missing first linker member", .{}),
519 .second_linker => d.failParse("missing second linker member", .{}),
431520 else => {},
432521 };
433522
434523 for (members.items, 0..) |member, member_i| {
435524 fr.seekTo(member.offset) catch |err|
436 failParse(opts, "unable to read member {d} at offset 0x{x}: {t}", .{ member_i, member.offset, err });
525 d.failParse("unable to read member {d} at offset 0x{x}: {t}", .{ member_i, member.offset, err });
437526
438527 const raw_header = try r.takeStruct(std.coff.ArchiveMemberHeader, .little);
439 const header: ArchiveHeader = .fromRaw(opts, &raw_header, opt_longnames);
440 if (!filterMatches(opts.member_filters, header.name)) continue;
528 const header: ArchiveHeader = .fromRaw(d, &raw_header, opt_longnames);
529 if (!filterMatches(d.opts.member_filters, header.name)) continue;
441530
442531 const member_sig = try r.peek(4);
443532 const machine: std.coff.IMAGE.FILE.MACHINE =
......@@ -445,17 +534,17 @@ const coff = struct {
445534 const sig = std.mem.readInt(u16, member_sig[2..4], .little);
446535
447536 const is_imp_lib = machine == std.coff.IMAGE.FILE.MACHINE.UNKNOWN and sig == 0xffff;
448 if (opts.member_headers or (opts.exports and is_imp_lib)) {
449 try dumpArchiveHeader(w, &header, member.offset);
537 if (d.opts.member_headers or (d.opts.exports and is_imp_lib)) {
538 try dumpArchiveHeader(d, &header, member.offset);
450539 if (is_imp_lib) {
451540 try w.writeAll("\nImport header:\n");
452541
453542 const imp_header = try r.takeStruct(std.coff.ImportHeader, .little);
454 try dumpHeader(w, std.coff.ImportHeader, &imp_header, struct {
455 pub fn sig1(_: *const std.coff.ImportHeader, _: *Io.Writer) !void {}
456 pub fn sig2(_: *const std.coff.ImportHeader, _: *Io.Writer) !void {}
457 pub fn types(h: *const std.coff.ImportHeader, cw: *Io.Writer) !void {
458 try cw.print(
543 try dumpHeader(d, std.coff.ImportHeader, &imp_header, struct {
544 pub fn sig1(_: *const DumpContext, _: *const std.coff.ImportHeader) !void {}
545 pub fn sig2(_: *const DumpContext, _: *const std.coff.ImportHeader) !void {}
546 pub fn types(id: *const DumpContext, h: *const std.coff.ImportHeader) !void {
547 try id.w.print(
459548 \\{t: >16} import_type
460549 \\{t: >16} name_type
461550 \\
......@@ -490,51 +579,53 @@ const coff = struct {
490579 } else {
491580 try w.writeAll(" COFF object type\n");
492581 }
493 try w.writeByte('\n');
582 if (d.element(.newlines)) try w.writeByte('\n');
494583 }
495584
496585 if (is_imp_lib) continue;
497 if (opts.section_headers or
498 opts.file_headers or
499 opts.relocs or
500 opts.strings or
501 opts.symbols)
586 if (d.opts.section_headers or
587 d.opts.file_headers or
588 d.opts.relocs or
589 d.opts.strings or
590 d.opts.symbols)
502591 {
503 try w.print("{s}({s}): COFF object\n\n", .{ std.fs.path.basename(opts.input_path), header.name });
504 try dumpObject(gpa, opts, false, header.name, fr, w);
592 if (d.element(.@"file-type"))
593 try w.print("{s}({s}): COFF object\n\n", .{ std.fs.path.basename(d.opts.input_path), header.name });
594 try dumpObject(d, false, header.name);
505595 }
506596 }
507597 }
508598
509599 fn dumpObject(
510 gpa: std.mem.Allocator,
511 opts: *const Options,
600 d: *const DumpContext,
512601 is_image: bool,
513602 obj_name: []const u8,
514 fr: *Io.File.Reader,
515 w: *Io.Writer,
516603 ) !void {
604 const gpa = d.gpa;
605 const fr = d.fr;
606 const w = d.w;
607
517608 const file_location = fr.logicalPos();
518609 const r = &fr.interface;
519610 const header = r.takeStruct(std.coff.Header, .little) catch |err|
520 return failParse(opts, "unable to read COFF header: {t}", .{err});
611 return d.failParse("unable to read COFF header: {t}", .{err});
521612
522 if (opts.file_headers) {
523 try w.writeAll("COFF Header:\n");
524 try dumpHeader(w, std.coff.Header, &header, struct {});
525 try w.writeByte('\n');
613 if (d.opts.file_headers) {
614 if (d.element(.@"header-names")) try w.writeAll("COFF Header:\n");
615 try dumpHeader(d, std.coff.Header, &header, struct {});
616 if (d.element(.newlines)) try w.writeByte('\n');
526617 }
527618
528619 switch (header.machine) {
529 _ => return failParse(opts, "unknown machine type: {x}", .{header.machine}),
620 _ => return d.failParse("unknown machine type: {x}", .{header.machine}),
530621 else => {},
531622 }
532623
533624 var known_dirs: [DIRECTORY_ENTRY.len]std.coff.ImageDataDirectory = undefined;
534625 const needs_data_dirs =
535 opts.exports or
536 opts.imports or
537 opts.tls;
626 d.opts.exports or
627 d.opts.imports or
628 d.opts.tls;
538629
539630 const ImageInfo = struct {
540631 data_dirs: []const std.coff.ImageDataDirectory,
......@@ -543,12 +634,14 @@ const coff = struct {
543634 };
544635
545636 const image_info: ?ImageInfo = if (header.size_of_optional_header > 0) image_info: {
546 if (!opts.file_headers and !needs_data_dirs) {
637 if (!d.opts.file_headers and !needs_data_dirs) {
547638 try fr.seekBy(header.size_of_optional_header);
548639 break :image_info null;
549640 }
550641
551 if (opts.file_headers) try w.writeAll("COFF Optional Header:\n");
642 if (d.opts.file_headers and d.element(.@"header-names"))
643 try w.writeAll("COFF Optional Header:\n");
644
552645 const magic: std.coff.OptionalHeader.Magic = @enumFromInt(try r.peekInt(u16, .little));
553646 const num_directory_entries, const image_base = switch (magic) {
554647 inline .PE32, .@"PE32+" => |v| num_data_dirs: {
......@@ -558,46 +651,46 @@ const coff = struct {
558651 std.coff.OptionalHeader.@"PE32+";
559652
560653 const optional_header = r.takeStruct(OptionalHeader, .little) catch |err|
561 return failParse(opts, "unable to read optional header: {t}", .{err});
654 return d.failParse("unable to read optional header: {t}", .{err});
562655
563 if (opts.file_headers) {
564 try dumpHeader(w, OptionalHeader, &optional_header, struct {
565 pub fn base_of_code(h: *const std.coff.OptionalHeader, cw: *Io.Writer) !void {
656 if (d.opts.file_headers) {
657 try dumpHeader(d, OptionalHeader, &optional_header, struct {
658 pub fn base_of_code(id: *const DumpContext, h: *const std.coff.OptionalHeader) !void {
566659 const base = @as(*const OptionalHeader, @ptrCast(@alignCast(h))).image_base;
567 try dumpRvaField(cw, @src().fn_name, h.base_of_code, base);
660 try dumpRvaField(id, @src().fn_name, h.base_of_code, base);
568661 }
569662
570 pub fn address_of_entry_point(h: *const std.coff.OptionalHeader, cw: *Io.Writer) !void {
663 pub fn address_of_entry_point(id: *const DumpContext, h: *const std.coff.OptionalHeader) !void {
571664 const base = @as(*const OptionalHeader, @ptrCast(@alignCast(h))).image_base;
572 try dumpRvaField(cw, @src().fn_name, h.base_of_code, base);
665 try dumpRvaField(id, @src().fn_name, h.base_of_code, base);
573666 }
574667
575 pub fn major_linker_version(h: *const std.coff.OptionalHeader, cw: *Io.Writer) !void {
576 try dumpVersionField(cw, "linker_version", h.major_linker_version, h.minor_linker_version);
668 pub fn major_linker_version(id: *const DumpContext, h: *const std.coff.OptionalHeader) !void {
669 try dumpVersionField(id.w, "linker_version", h.major_linker_version, h.minor_linker_version);
577670 }
578 pub fn minor_linker_version(_: *const std.coff.OptionalHeader, _: *Io.Writer) !void {}
671 pub fn minor_linker_version(_: *const DumpContext, _: *const std.coff.OptionalHeader) !void {}
579672
580 pub fn major_operating_system_version(h: *const OptionalHeader, cw: *Io.Writer) !void {
673 pub fn major_operating_system_version(id: *const DumpContext, h: *const OptionalHeader) !void {
581674 try dumpVersionField(
582 cw,
675 id.w,
583676 "operating_system_version",
584677 h.major_operating_system_version,
585678 h.minor_operating_system_version,
586679 );
587680 }
588 pub fn minor_operating_system_version(_: *const OptionalHeader, _: *Io.Writer) !void {}
681 pub fn minor_operating_system_version(_: *const DumpContext, _: *const OptionalHeader) !void {}
589682
590 pub fn major_image_version(h: *const OptionalHeader, cw: *Io.Writer) !void {
591 try dumpVersionField(cw, "image_version", h.major_image_version, h.minor_image_version);
683 pub fn major_image_version(id: *const DumpContext, h: *const OptionalHeader) !void {
684 try dumpVersionField(id.w, "image_version", h.major_image_version, h.minor_image_version);
592685 }
593 pub fn minor_image_version(_: *const OptionalHeader, _: *Io.Writer) !void {}
686 pub fn minor_image_version(_: *const DumpContext, _: *const OptionalHeader) !void {}
594687
595 pub fn major_subsystem_version(h: *const OptionalHeader, cw: *Io.Writer) !void {
596 try dumpVersionField(cw, "subsystem_version", h.major_subsystem_version, h.minor_subsystem_version);
688 pub fn major_subsystem_version(id: *const DumpContext, h: *const OptionalHeader) !void {
689 try dumpVersionField(id.w, "subsystem_version", h.major_subsystem_version, h.minor_subsystem_version);
597690 }
598 pub fn minor_subsystem_version(_: *const OptionalHeader, _: *Io.Writer) !void {}
691 pub fn minor_subsystem_version(_: *const DumpContext, _: *const OptionalHeader) !void {}
599692 });
600 try w.writeByte('\n');
693 if (d.element(.newlines)) try w.writeByte('\n');
601694 }
602695
603696 break :num_data_dirs .{
......@@ -605,24 +698,26 @@ const coff = struct {
605698 optional_header.image_base,
606699 };
607700 },
608 else => return failParse(opts, "invalid optional header magic number: {x}", .{magic}),
701 else => return d.failParse("invalid optional header magic number: {x}", .{magic}),
609702 };
610703
611 if (opts.file_headers) try w.writeAll("Data Directories:\n");
704 if (d.opts.file_headers and d.element(.@"header-names"))
705 try w.writeAll("Data Directories:\n");
706
612707 for (0..num_directory_entries) |dir_i| {
613708 const dir = r.takeStruct(std.coff.ImageDataDirectory, .little) catch |err|
614 return failParse(opts, "unable to read data directory {x}: {t}", .{ dir_i, err });
709 return d.failParse("unable to read data directory {x}: {t}", .{ dir_i, err });
615710
616711 if (dir_i < known_dirs.len)
617712 known_dirs[dir_i] = dir;
618713
619 if (opts.file_headers)
714 if (d.opts.file_headers)
620715 try w.print(
621716 "{x: >16} {x: >8} {t}\n",
622717 .{ dir.virtual_address, dir.size, @as(DIRECTORY_ENTRY, @enumFromInt(dir_i)) },
623718 );
624719 }
625 if (opts.file_headers) try w.writeByte('\n');
720 if (d.opts.file_headers and d.element(.newlines)) try w.writeByte('\n');
626721
627722 break :image_info .{
628723 .data_dirs = known_dirs[0..@min(known_dirs.len, num_directory_entries)],
......@@ -630,32 +725,33 @@ const coff = struct {
630725 .image_base = image_base,
631726 };
632727 } else if (is_image) {
633 return failParse(opts, "image did not contain an optional header", .{});
728 return d.failParse("image did not contain an optional header", .{});
634729 } else null;
635730
636731 // Section names in images don't use the string table, as they must fit inline in the header
637 const load_string_table = (opts.strings or !is_image) and header.pointer_to_symbol_table > 0;
732 const load_string_table = (d.opts.strings or !is_image) and header.pointer_to_symbol_table > 0;
638733 const string_table = if (load_string_table) string_table: {
639734 const pos = fr.logicalPos();
640735 fr.seekTo(file_location + header.pointer_to_symbol_table + header.number_of_symbols * std.coff.Symbol.sizeOf()) catch |err|
641 return failParse(opts, "unable to seek to string table: {t}", .{err});
736 return d.failParse("unable to seek to string table: {t}", .{err});
642737
643738 const string_table_len = r.peekInt(u32, .little) catch |err|
644 return failParse(opts, "unable to read string table length: {t}", .{err});
739 return d.failParse("unable to read string table length: {t}", .{err});
645740
646741 const table = r.readAlloc(gpa, string_table_len) catch |err|
647 return failParse(opts, "unable to read string table: {t}", .{err});
742 return d.failParse("unable to read string table: {t}", .{err});
648743
649744 try fr.seekTo(pos);
650745 break :string_table table;
651746 } else &.{};
652747 defer gpa.free(string_table);
653748
654 if (opts.strings) {
655 try w.print(
656 \\String Table (0x{x} bytes):
657 \\
658 , .{string_table.len});
749 if (d.opts.strings) {
750 if (d.element(.@"table-header"))
751 try w.print(
752 \\String Table (0x{x} bytes):
753 \\
754 , .{string_table.len});
659755
660756 var sr = Io.Reader.fixed(string_table[4..]);
661757 while (try sr.takeDelimiter(0)) |str| {
......@@ -663,7 +759,7 @@ const coff = struct {
663759 try w.writeByte('\n');
664760 }
665761
666 try w.writeByte('\n');
762 if (d.element(.newlines)) try w.writeByte('\n');
667763 }
668764
669765 var sections: std.ArrayList(Section) = .empty;
......@@ -671,13 +767,13 @@ const coff = struct {
671767 var sections_with_data: u16 = 0;
672768
673769 const load_sections =
674 opts.section_headers or
675 opts.symbols or
676 opts.relocs or
770 d.opts.section_headers or
771 d.opts.symbols or
772 d.opts.relocs or
677773 needs_data_dirs;
678774
679775 if (load_sections) {
680 if (opts.section_headers)
776 if (d.opts.section_headers and d.element(.@"table-header"))
681777 try w.print(
682778 \\Sections in '{s}':
683779 \\Num Name RVA Virt Size Data Size & Data & Relocs & Lines # Relocs # Lines Flags
......@@ -687,37 +783,37 @@ const coff = struct {
687783 try sections.resize(gpa, header.number_of_sections);
688784 for (sections.items, 0..) |*section, section_i| {
689785 section.header = r.takeStruct(std.coff.SectionHeader, .little) catch |err|
690 return failParse(opts, "unable to read section header {x}: {t}", .{ section_i, err });
786 return d.failParse("unable to read section header {x}: {t}", .{ section_i, err });
691787 section.name = headerName(&section.header.name, string_table) catch |err| switch (err) {
692788 error.Overflow,
693789 error.InvalidCharacter,
694 => return failParse(opts, "unable to parse section name offset '{s}': {t}", .{
790 => return d.failParse("unable to parse section name offset '{s}': {t}", .{
695791 section.name,
696792 err,
697793 }),
698 error.OutOfBounds => return failParse(opts, "section name offset '{s}' was out of bounds (>= {x})", .{
794 error.OutOfBounds => return d.failParse("section name offset '{s}' was out of bounds (>= {x})", .{
699795 section.name,
700796 string_table.len,
701797 }),
702798 };
703799
704800 sections_with_data += @intFromBool(section.header.size_of_raw_data > 0);
705 if (opts.section_headers) {
706 if (!filterMatches(opts.section_filters, section.name)) continue;
801 if (d.opts.section_headers) {
802 if (!filterMatches(d.opts.section_filters, section.name)) continue;
707803 const raw_name = std.mem.sliceTo(&section.header.name, 0);
708804 try w.print(
709 "{x: >3} {s: <8} {x: >8} {x: >9} {x: >9} {x: >8} {x: >8} {x: >8} {x: >8} {x: >8} {x:0>8} |",
805 "{x: >3} {s: <8} {f} {f} {f} {f} {f} {f} {f} {f} {x:0>8} |",
710806 .{
711807 section_i + 1,
712808 raw_name,
713 section.header.virtual_address,
714 section.header.virtual_size,
715 section.header.size_of_raw_data,
716 section.header.pointer_to_raw_data,
717 section.header.pointer_to_relocations,
718 section.header.pointer_to_linenumbers,
719 section.header.number_of_relocations,
720 section.header.number_of_linenumbers,
809 fmtIntField(d, section.header.virtual_address, .{ .kind = .va }),
810 fmtIntField(d, section.header.virtual_size, .{ .kind = .size, .width = 9 }),
811 fmtIntField(d, section.header.size_of_raw_data, .{ .kind = .size, .width = 9 }),
812 fmtIntField(d, section.header.pointer_to_raw_data, .{ .kind = .va }),
813 fmtIntField(d, section.header.pointer_to_relocations, .{ .kind = .va }),
814 fmtIntField(d, section.header.pointer_to_linenumbers, .{ .kind = .va }),
815 fmtIntField(d, section.header.number_of_relocations, .{ .kind = .va }),
816 fmtIntField(d, section.header.number_of_linenumbers, .{ .kind = .va }),
721817 @as(u32, @bitCast(section.header.flags)),
722818 },
723819 );
......@@ -730,7 +826,7 @@ const coff = struct {
730826 }
731827 }
732828
733 if (opts.section_headers) try w.writeByte('\n');
829 if (d.opts.section_headers and d.element(.newlines)) try w.writeByte('\n');
734830 }
735831
736832 var symbols: std.ArrayList(struct {
......@@ -738,15 +834,15 @@ const coff = struct {
738834 section_number: std.coff.SectionNumber,
739835 }) = .empty;
740836 defer symbols.deinit(gpa);
741 if (opts.relocs)
837 if (d.opts.relocs)
742838 try symbols.ensureUnusedCapacity(gpa, header.number_of_symbols);
743839
744 if (opts.symbols or opts.relocs) {
840 if (d.opts.symbols or d.opts.relocs) {
745841 if (header.pointer_to_symbol_table > 0) {
746842 fr.seekTo(file_location + header.pointer_to_symbol_table) catch |err|
747 return failParse(opts, "unable to seek to symbol table: {t}", .{err});
843 return d.failParse("unable to seek to symbol table: {t}", .{err});
748844
749 if (opts.symbols)
845 if (d.opts.symbols and d.element(.@"table-header"))
750846 try w.print(
751847 \\Symbols in '{s}':
752848 \\ Ord Value Sect Type Storage Name
......@@ -758,7 +854,7 @@ const coff = struct {
758854 while (symbol_i < header.number_of_symbols) {
759855 var symbol: std.coff.Symbol = undefined;
760856 const symbol_bytes = r.take(symbol_size) catch |err|
761 return failParse(opts, "unable to read symbol {x}: {t}", .{ symbol_i, err });
857 return d.failParse("unable to read symbol {x}: {t}", .{ symbol_i, err });
762858
763859 @memcpy(std.mem.asBytes(&symbol)[0..symbol_size], symbol_bytes);
764860 if (native_endian != .little)
......@@ -773,7 +869,7 @@ const coff = struct {
773869 const name = std.mem.sliceTo(if (std.mem.eql(u8, symbol.name[0..4], "\x00\x00\x00\x00")) name: {
774870 const index = std.mem.readInt(u32, symbol.name[4..], .little);
775871 if (index >= string_table.len)
776 return failParse(opts, "invalid name offset for symbol {x} ({x} >= {x})", .{
872 return d.failParse("invalid name offset for symbol {x} ({x} >= {x})", .{
777873 symbol_i,
778874 index,
779875 string_table.len,
......@@ -781,16 +877,19 @@ const coff = struct {
781877 break :name string_table[index..];
782878 } else &symbol.name, 0);
783879
784 if (opts.relocs)
880 if (d.opts.relocs)
785881 symbols.appendNTimesAssumeCapacity(.{
786882 .name = name,
787883 .section_number = symbol.section_number,
788884 }, 1 + symbol.number_of_aux_symbols);
789885
790 if (!opts.symbols)
886 if (!d.opts.symbols or !filterMatches(d.opts.symbol_filters, name))
791887 continue;
792888
793 try w.print("{x: >4} {x:0>8} ", .{ symbol_i, symbol.value });
889 try w.print("{f} {x:0>8} ", .{
890 fmtIntField(d, @as(u16, @intCast(symbol_i)), .{ .kind = .ord }),
891 symbol.value,
892 });
794893 try switch (symbol.section_number) {
795894 .UNDEFINED => w.writeAll("UNDEF"),
796895 .ABSOLUTE => w.writeAll(" ABS"),
......@@ -814,8 +913,7 @@ const coff = struct {
814913 else => null,
815914 }) |suffix| try w.writeAll(suffix) else try w.print("{x}", .{symbol.type.complex_type});
816915
817 try w.print("{t: >16} | {s}", .{ symbol.storage_class, name });
818 try w.writeByte('\n');
916 try w.print("{t: >16} | {s}\n", .{ symbol.storage_class, name });
819917
820918 for (0..symbol.number_of_aux_symbols) |aux_i| {
821919 _ = aux_i;
......@@ -838,8 +936,7 @@ const coff = struct {
838936 try w.writeAll("TODO bf / ef aux symbol");
839937 } else if (symbol.storage_class == .WEAK_EXTERNAL and symbol.section_number == .UNDEFINED) {
840938 if (symbol.value != 0)
841 return failParse(
842 opts,
939 return d.failParse(
843940 "invalid value 0x{x} for weak external symbol 0x{x}",
844941 .{ symbol.value, symbol_i },
845942 );
......@@ -850,14 +947,11 @@ const coff = struct {
850947 std.mem.byteSwapAllFields(std.coff.SectionDefinition, &weak_external);
851948
852949 if (weak_external.tag_index >= header.number_of_symbols)
853 return failParse(
854 opts,
950 return d.failParse(
855951 "invalid tag_index 0x{x} for weak external symbol 0x{x}",
856952 .{ weak_external.tag_index, symbol_i },
857953 );
858954
859 // TODO
860
861955 try w.print(" Weak External [falls back to {x:0>8} via {t}]", .{
862956 weak_external.tag_index,
863957 weak_external.flag,
......@@ -914,8 +1008,8 @@ const coff = struct {
9141008 continue;
9151009 }
9161010
917 try w.print(" [size {x:0>8} chksum {x:0>8} relocs {x:0>4} lines {x:0>4}]", .{
918 section_def.length,
1011 try w.print(" [size {f} chksum {x:0>8} relocs {x:0>4} lines {x:0>4}]", .{
1012 fmtIntField(d, section_def.length, .{ .kind = .size, .zero_fill = true }),
9191013 section_def.checksum,
9201014 section_def.number_of_relocations,
9211015 section_def.number_of_linenumbers,
......@@ -930,19 +1024,19 @@ const coff = struct {
9301024 try w.writeAll(")");
9311025 },
9321026 }
933 } else {}
1027 }
9341028
9351029 try w.writeByte('\n');
9361030 }
9371031 }
9381032
939 if (opts.symbols) try w.writeByte('\n');
940 } else if (opts.symbols) {
1033 if (d.opts.symbols and d.element(.newlines)) try w.writeByte('\n');
1034 } else if (d.opts.symbols) {
9411035 try w.writeAll("No symbol table found\n");
9421036 }
9431037 }
9441038
945 if (opts.relocs) {
1039 if (d.opts.relocs) {
9461040 const relocation_size = std.coff.Relocation.sizeOf();
9471041
9481042 for (sections.items, 0..) |section, section_i| {
......@@ -955,7 +1049,7 @@ const coff = struct {
9551049 , .{ section_i + 1, section.name, obj_name });
9561050
9571051 fr.seekTo(file_location + section.header.pointer_to_relocations) catch |err|
958 return failParse(opts, "unable to seek to section {x} relocation table: {t}", .{ section_i + 1, err });
1052 return d.failParse("unable to seek to section {x} relocation table: {t}", .{ section_i + 1, err });
9591053
9601054 for (0..section.header.number_of_relocations) |reloc_i| {
9611055 var reloc: std.coff.Relocation = undefined;
......@@ -963,7 +1057,13 @@ const coff = struct {
9631057 if (native_endian != .little)
9641058 std.mem.byteSwapAllFields(std.coff.Relocation, &reloc);
9651059
966 try w.print("{x:0>8} ", .{reloc.virtual_address});
1060 const sym = &symbols.items[reloc.symbol_table_index];
1061 if (!filterMatches(d.opts.symbol_filters, sym.name))
1062 continue;
1063
1064 try w.print("{f} ", .{
1065 fmtIntField(d, reloc.virtual_address, .{ .kind = .va, .zero_fill = true }),
1066 });
9671067 switch (header.machine) {
9681068 _ => unreachable,
9691069 inline else => |m| switch (m.RelocationType()) {
......@@ -976,20 +1076,18 @@ const coff = struct {
9761076 }
9771077
9781078 if (reloc.symbol_table_index >= symbols.items.len)
979 return failParse(
980 opts,
1079 return d.failParse(
9811080 "reloc {x} in section {x} has out-of-bounds symbol index {x}",
9821081 .{ reloc_i, section_i + 1, reloc.symbol_table_index },
9831082 );
9841083
985 const sym = &symbols.items[reloc.symbol_table_index];
986 try w.print("{x: >8} {f} | {s}\n", .{
987 reloc.symbol_table_index,
1084 try w.print("{f} {f} | {s}\n", .{
1085 fmtIntField(d, reloc.symbol_table_index, .{ .kind = .ord }),
9881086 fmtSectionNumber(sym.section_number),
9891087 sym.name,
9901088 });
9911089 }
992 try w.writeByte('\n');
1090 if (d.element(.newlines)) try w.writeByte('\n');
9931091 }
9941092 }
9951093
......@@ -1026,44 +1124,40 @@ const coff = struct {
10261124 } else &.{};
10271125 defer gpa.free(rva_index);
10281126
1029 if (opts.exports) {
1030 if (try seekToDataDirectory(opts, fr, w, rva_index, sections.items, image_info.?.data_dirs, .EXPORT)) |section_index| {
1127 if (d.opts.exports) {
1128 if (try seekToDataDirectory(d, rva_index, sections.items, image_info.?.data_dirs, .EXPORT)) |section_index| {
10311129 const export_dir = r.takeStruct(std.coff.ExportDirectoryTable, .little) catch |err|
1032 return failParse(opts, "unable to read export directory: {t}", .{err});
1130 return d.failParse("unable to read export directory: {t}", .{err});
10331131
10341132 try w.print("Export directory:\n", .{});
1035 try dumpHeader(w, std.coff.ExportDirectoryTable, &export_dir, struct {
1036 pub fn major_version(h: *const std.coff.ExportDirectoryTable, cw: *Io.Writer) !void {
1037 try dumpVersionField(cw, "version", h.major_version, h.minor_version);
1133 try dumpHeader(d, std.coff.ExportDirectoryTable, &export_dir, struct {
1134 pub fn major_version(id: *const DumpContext, h: *const std.coff.ExportDirectoryTable) !void {
1135 try dumpVersionField(id.w, "version", h.major_version, h.minor_version);
10381136 }
1039 pub fn minor_version(_: *const std.coff.ExportDirectoryTable, _: *Io.Writer) !void {}
1137 pub fn minor_version(_: *const DumpContext, _: *const std.coff.ExportDirectoryTable) !void {}
10401138 });
10411139
10421140 const section = sections.items[section_index];
10431141 const name_loc = section.rvaFileOffset(export_dir.name_rva) catch
1044 return failParse(
1045 opts,
1142 return d.failParse(
10461143 "export name rva 0x{x} was not within the export section",
10471144 .{export_dir.name_rva},
10481145 );
10491146
10501147 const eat_loc = section.rvaFileOffset(export_dir.export_address_table_rva) catch
1051 return failParse(
1052 opts,
1148 return d.failParse(
10531149 "export address table rva 0x{x} was not within the export section",
10541150 .{export_dir.export_address_table_rva},
10551151 );
10561152
10571153 const name_pointer_loc = section.rvaFileOffset(export_dir.name_pointer_table_rva) catch
1058 return failParse(
1059 opts,
1154 return d.failParse(
10601155 "export name pointer table rva 0x{x} was not within the export section",
10611156 .{export_dir.name_pointer_table_rva},
10621157 );
10631158
10641159 const ord_loc = section.rvaFileOffset(export_dir.ordinal_table_rva) catch
1065 return failParse(
1066 opts,
1160 return d.failParse(
10671161 "export ordinal table rva 0x{x} was not within the export section",
10681162 .{export_dir.ordinal_table_rva},
10691163 );
......@@ -1077,12 +1171,13 @@ const coff = struct {
10771171 defer gpa.free(dir_slice);
10781172
10791173 const dll_name = std.mem.sliceTo(dir_slice[name_loc - dir_loc ..], 0);
1080 try w.print(
1081 \\
1082 \\Exports from {s}:
1083 \\ Ord Hint RVA Name
1084 \\
1085 , .{dll_name});
1174 if (d.element(.@"table-header"))
1175 try w.print(
1176 \\
1177 \\Exports from {s}:
1178 \\ Ord Hint RVA Name
1179 \\
1180 , .{dll_name});
10861181
10871182 const name_pointers = dir_slice[name_pointer_loc - dir_loc ..][0 .. export_dir.number_of_names * @sizeOf(u32)];
10881183 const ords = dir_slice[ord_loc - dir_loc ..][0 .. export_dir.number_of_names * @sizeOf(u16)];
......@@ -1090,18 +1185,24 @@ const coff = struct {
10901185 const name_rva_to_offset = dir.virtual_address + @sizeOf(std.coff.ExportDirectoryTable);
10911186 for (0..export_dir.number_of_names) |name_i| {
10921187 const name_rva = std.mem.readInt(u32, name_pointers[name_i * @sizeOf(u32) ..][0..@sizeOf(u32)], .little);
1188 const name = std.mem.sliceTo(dir_slice[name_rva - name_rva_to_offset ..], 0);
1189 if (!filterMatches(d.opts.symbol_filters, name))
1190 continue;
1191
10931192 const ord = std.mem.readInt(u16, ords[name_i * @sizeOf(u16) ..][0..@sizeOf(u16)], .little);
10941193 const addr = std.mem.readInt(u32, addrs[@as(u32, ord) * @sizeOf(u32) ..][0..@sizeOf(u32)], .little);
10951194
1096 try w.print("{x: >4} {x: >4} ", .{ export_dir.ordinal_base + ord, name_i });
1195 try w.print("{f} {f} ", .{
1196 fmtIntField(d, @as(u16, @intCast(export_dir.ordinal_base + ord)), .{ .kind = .ord }),
1197 fmtIntField(d, @as(u16, @intCast(name_i)), .{ .kind = .ord }),
1198 });
10971199 const is_forwarder = addr >= dir.virtual_address and addr < dir_end_rva;
10981200 if (is_forwarder) {
10991201 try w.writeAll("forwards");
11001202 } else {
1101 try w.print("{x: >8}", .{addr});
1203 try w.print("{f}", .{fmtIntField(d, addr, .{ .kind = .rva })});
11021204 }
11031205
1104 const name = std.mem.sliceTo(dir_slice[name_rva - name_rva_to_offset ..], 0);
11051206 try w.print(" | {s}", .{name});
11061207 if (is_forwarder)
11071208 try w.print(" -> {s}", .{std.mem.sliceTo(dir_slice[addr - name_rva_to_offset ..], 0)});
......@@ -1110,11 +1211,9 @@ const coff = struct {
11101211 }
11111212 }
11121213
1113 if (opts.imports) {
1214 if (d.opts.imports) {
11141215 if (try seekToDataDirectory(
1115 opts,
1116 fr,
1117 w,
1216 d,
11181217 rva_index,
11191218 sections.items,
11201219 image_info.?.data_dirs,
......@@ -1125,8 +1224,7 @@ const coff = struct {
11251224 defer directory_entries.deinit(gpa);
11261225 while (true) {
11271226 const entry = r.takeStruct(Entry, .little) catch |err|
1128 return failParse(
1129 opts,
1227 return d.failParse(
11301228 "unable to read import directory entry {x}: {t}",
11311229 .{ directory_entries.items.len, err },
11321230 );
......@@ -1141,8 +1239,7 @@ const coff = struct {
11411239 sections.items,
11421240 entry.name_rva,
11431241 ) orelse
1144 return failParse(
1145 opts,
1242 return d.failParse(
11461243 "import directory entry name rva 0x{x} was not found in any section",
11471244 .{entry.name_rva},
11481245 );
......@@ -1151,8 +1248,7 @@ const coff = struct {
11511248 entry.name_rva,
11521249 ) catch unreachable;
11531250 fr.seekTo(name_loc) catch |err|
1154 return failParse(
1155 opts,
1251 return d.failParse(
11561252 "unable to seek to import directory entry name at 0x{x}: {t}",
11571253 .{ name_loc, err },
11581254 );
......@@ -1160,7 +1256,7 @@ const coff = struct {
11601256 const dll_name = (try r.takeDelimiter(0)).?;
11611257
11621258 try w.print("Import table entry for {s}:\n", .{dll_name});
1163 try dumpHeader(w, Entry, &entry, struct {});
1259 try dumpHeader(d, Entry, &entry, struct {});
11641260
11651261 try w.print(
11661262 \\
......@@ -1173,8 +1269,7 @@ const coff = struct {
11731269 sections.items,
11741270 entry.import_lookup_table_rva,
11751271 ) orelse
1176 return failParse(
1177 opts,
1272 return d.failParse(
11781273 "import directory entry ilt rva 0x{x} was not found in any section",
11791274 .{entry.import_lookup_table_rva},
11801275 );
......@@ -1183,8 +1278,7 @@ const coff = struct {
11831278 entry.import_lookup_table_rva,
11841279 ) catch unreachable;
11851280 fr.seekTo(ilt_loc) catch |err|
1186 return failParse(
1187 opts,
1281 return d.failParse(
11881282 "unable to seek to import directory ilt at 0x{x}: {t}",
11891283 .{ ilt_loc, err },
11901284 );
......@@ -1199,8 +1293,7 @@ const coff = struct {
11991293 defer ilt_entries.deinit(gpa);
12001294 while (true) {
12011295 const table_entry = r.takeStruct(TableEntry, .little) catch |err|
1202 return failParse(
1203 opts,
1296 return d.failParse(
12041297 "unable to read ilt entry {s}:{x}: {t}",
12051298 .{ dll_name, ilt_entries.items.len, err },
12061299 );
......@@ -1217,8 +1310,7 @@ const coff = struct {
12171310 sections.items,
12181311 ilt_entry.payload.hint_name_rva,
12191312 ) orelse
1220 return failParse(
1221 opts,
1313 return d.failParse(
12221314 "import directory ilt entry 0x{x}'s hint rva 0x{x} was not found in any section",
12231315 .{ ilt_entry_i, ilt_entry.payload.hint_name_rva },
12241316 );
......@@ -1227,22 +1319,19 @@ const coff = struct {
12271319 ilt_entry.payload.hint_name_rva,
12281320 ) catch unreachable;
12291321 fr.seekTo(hint_loc) catch |err|
1230 return failParse(
1231 opts,
1322 return d.failParse(
12321323 "unable to seek to ilt entry 0x{x}'s hint at 0x{x}: {t}",
12331324 .{ ilt_entry_i, hint_loc, err },
12341325 );
12351326
12361327 const hint = r.takeInt(u16, .little) catch |err|
1237 return failParse(
1238 opts,
1328 return d.failParse(
12391329 "unable to read import directory ilt entry 0x{x}'s hint: {t}",
12401330 .{ ilt_entry_i, err },
12411331 );
12421332
12431333 const name = r.takeDelimiter(0) catch |err|
1244 return failParse(
1245 opts,
1334 return d.failParse(
12461335 "unable to read import directory ilt entry 0x{x}'s name: {t}",
12471336 .{ ilt_entry_i, err },
12481337 );
......@@ -1250,18 +1339,16 @@ const coff = struct {
12501339 try w.print(" {x: >4} | {s}\n", .{ hint, name.? });
12511340 }
12521341 }
1253 try w.writeByte('\n');
1342 if (d.element(.newlines)) try w.writeByte('\n');
12541343 },
12551344 }
12561345 }
12571346 }
12581347 }
12591348
1260 if (opts.tls) {
1349 if (d.opts.tls) {
12611350 if (try seekToDataDirectory(
1262 opts,
1263 fr,
1264 w,
1351 d,
12651352 rva_index,
12661353 sections.items,
12671354 image_info.?.data_dirs,
......@@ -1272,10 +1359,10 @@ const coff = struct {
12721359 inline else => |m| {
12731360 const TlsDirectoryEntry = std.coff.TlsDirectoryEntry(m);
12741361 const tls_entry = r.takeStruct(TlsDirectoryEntry, .little) catch |err|
1275 return failParse(opts, "unable to read tls directory: {t}", .{err});
1362 return d.failParse("unable to read tls directory: {t}", .{err});
12761363
12771364 try w.writeAll("TLS Directory:\n");
1278 try dumpHeader(w, TlsDirectoryEntry, &tls_entry, struct {});
1365 try dumpHeader(d, TlsDirectoryEntry, &tls_entry, struct {});
12791366
12801367 try w.writeAll(" | ");
12811368 if (tls_entry.characteristics.alignment == .NONE) {
......@@ -1301,8 +1388,7 @@ const coff = struct {
13011388 sections.items,
13021389 callbacks_rva,
13031390 ) orelse
1304 return failParse(
1305 opts,
1391 return d.failParse(
13061392 "tls callbacks rva 0x{x} was not found in any section",
13071393 .{callbacks_rva},
13081394 );
......@@ -1311,24 +1397,22 @@ const coff = struct {
13111397 .rvaFileOffset(callbacks_rva) catch unreachable;
13121398
13131399 fr.seekTo(callbacks_loc) catch |err|
1314 return failParse(
1315 opts,
1400 return d.failParse(
13161401 "unable to seek to tls callbacks array at offset 0x{x}: {t}",
13171402 .{ callbacks_loc, err },
13181403 );
13191404
13201405 while (true) {
13211406 const callback_va = r.takeInt(@FieldType(TlsDirectoryEntry, "callbacks_va"), .little) catch |err|
1322 return failParse(
1323 opts,
1407 return d.failParse(
13241408 "unable to read tls callbacks array: {t}",
13251409 .{err},
13261410 );
13271411
1328 try w.print("{x: >16} \n", .{callback_va});
1412 try w.print("{f}\n", .{fmtIntField(d, callback_va, .{ .kind = .va })});
13291413 if (callback_va == 0) break;
13301414 }
1331 try w.writeByte('\n');
1415 if (d.element(.newlines)) try w.writeByte('\n');
13321416 },
13331417 }
13341418 }
......@@ -1336,9 +1420,7 @@ const coff = struct {
13361420 }
13371421
13381422 fn seekToDataDirectory(
1339 opts: *const Options,
1340 fr: *Io.File.Reader,
1341 w: *Io.Writer,
1423 d: *const DumpContext,
13421424 rva_index: []const u16,
13431425 sections: []const Section,
13441426 data_dirs: []const std.coff.ImageDataDirectory,
......@@ -1349,16 +1431,14 @@ const coff = struct {
13491431 if (rva == 0) break :blk;
13501432
13511433 const section_index = sectionContainingRva(rva_index, sections, rva) orelse
1352 return failParse(
1353 opts,
1434 return d.failParse(
13541435 "{t} directory rva 0x{x} was not found in any section",
13551436 .{ entry, rva },
13561437 );
13571438
13581439 const file_offset = sections[section_index].rvaFileOffset(rva) catch unreachable;
1359 fr.seekTo(file_offset) catch |err|
1360 return failParse(
1361 opts,
1440 d.fr.seekTo(file_offset) catch |err|
1441 return d.failParse(
13621442 "unable to seek to {t} directory at offset 0x{x}: {t}",
13631443 .{ entry, file_offset, err },
13641444 );
......@@ -1366,7 +1446,7 @@ const coff = struct {
13661446 return section_index;
13671447 }
13681448
1369 try w.print("{t} directory was not present in optional header\n", .{entry});
1449 try d.w.print("{t} directory was not present in optional header\n", .{entry});
13701450 return null;
13711451 }
13721452
......@@ -1382,19 +1462,18 @@ const coff = struct {
13821462
13831463 fn order(ctx: @This(), section_index: u16) std.math.Order {
13841464 const h = &ctx.sections[section_index].header;
1385 const start = h.virtual_address;
1386 if (ctx.rva < start) return .lt;
1465 if (ctx.rva < h.virtual_address) return .lt;
13871466 const end = h.virtual_address + h.size_of_raw_data;
13881467 if (ctx.rva >= end) return .gt;
13891468 return .eq;
13901469 }
13911470 };
13921471
1393 const index = std.sort.binarySearch(u16, indices, Context{
1472 const indices_index = std.sort.binarySearch(u16, indices, Context{
13941473 .rva = rva,
13951474 .sections = sections,
13961475 }, Context.order) orelse return null;
1397 return @intCast(index);
1476 return @intCast(indices[indices_index]);
13981477 }
13991478
14001479 fn headerName(raw: *const [8]u8, string_table: []const u8) ![]const u8 {
......@@ -1427,6 +1506,40 @@ const coff = struct {
14271506 };
14281507 }
14291508
1509 const FormatIntField = struct {
1510 val: ?u64,
1511 width: usize,
1512 zero_fill: bool,
1513 };
1514
1515 fn fmtIntField(
1516 d: *const DumpContext,
1517 val: anytype,
1518 params: struct {
1519 kind: ?FieldKind = null,
1520 width: ?usize = null,
1521 zero_fill: bool = false,
1522 },
1523 ) std.fmt.Alt(FormatIntField, intFieldString) {
1524 return .{
1525 .data = .{
1526 .val = if (d.redacted(params.kind)) null else val,
1527 .width = params.width orelse @typeInfo(@TypeOf(val)).int.bits / 4,
1528 .zero_fill = params.zero_fill,
1529 },
1530 };
1531 }
1532
1533 fn intFieldString(field: FormatIntField, w: *std.Io.Writer) std.Io.Writer.Error!void {
1534 if (field.val) |val| {
1535 try w.printInt(val, 16, .lower, .{
1536 .width = field.width,
1537 .alignment = .right,
1538 .fill = if (field.zero_fill) '0' else ' ',
1539 });
1540 } else try w.splatByteAll('x', field.width);
1541 }
1542
14301543 fn dumpFlags(w: *Io.Writer, comptime fmt: []const u8, comptime T: type, flags: *const T, cols: u32) !void {
14311544 const s = @typeInfo(T).@"struct";
14321545 inline for (s.fields) |flag_field| {
......@@ -1437,33 +1550,53 @@ const coff = struct {
14371550 }
14381551 }
14391552
1440 fn dumpArchiveHeader(w: *Io.Writer, header: *const ArchiveHeader, pos: u32) !void {
1441 try w.print("Archive member at offset 0x{x}: '{s}'\n", .{ pos, header.name });
1442 try dumpHeader(w, ArchiveHeader, header, struct {
1443 pub fn name(_: *const ArchiveHeader, _: *Io.Writer) !void {}
1444 pub fn file_mode(h: *const ArchiveHeader, cw: *Io.Writer) !void {
1445 try cw.print("{o: >16} file_mode\n", .{h.file_mode});
1553 fn dumpArchiveHeader(d: *const DumpContext, header: *const ArchiveHeader, pos: u32) !void {
1554 try d.w.print("Archive member at offset 0x{x}: '{s}'\n", .{ pos, header.name });
1555 try dumpHeader(d, ArchiveHeader, header, struct {
1556 pub fn name(_: *const DumpContext, _: *const ArchiveHeader) !void {}
1557 pub fn file_mode(id: *const DumpContext, h: *const ArchiveHeader) !void {
1558 try id.w.print("{o: >16} file_mode\n", .{h.file_mode});
14461559 }
14471560 });
14481561 }
14491562
1450 fn dumpHeader(w: *Io.Writer, comptime T: type, header: *const T, Custom: type) !void {
1563 fn fieldKind(name: []const u8) ?FieldKind {
1564 if (std.mem.endsWith(u8, name, "_rva"))
1565 return .rva;
1566 if (std.mem.endsWith(u8, name, "_va") or
1567 std.mem.endsWith(u8, name, "_address") or
1568 std.mem.startsWith(u8, name, "pointer_"))
1569 return .va;
1570 if (std.mem.startsWith(u8, name, "number_"))
1571 return .size;
1572 return null;
1573 }
1574
1575 fn dumpHeader(
1576 d: *const DumpContext,
1577 comptime T: type,
1578 header: *const T,
1579 Custom: type,
1580 ) !void {
14511581 inline for (@typeInfo(T).@"struct".fields) |field| {
14521582 const val = &@field(header, field.name);
14531583 if (@hasDecl(Custom, field.name)) {
1454 try @field(Custom, field.name)(header, w);
1584 try @field(Custom, field.name)(d, header);
14551585 } else {
14561586 switch (@typeInfo(field.type)) {
1457 .int => try w.print("{x: >16} {s}\n", .{ val.*, field.name }),
1458 .@"enum" => try w.print("{x: >16} {s} ({t})\n", .{ val.*, field.name, val.* }),
1587 .int => try d.w.print("{f} {s}\n", .{ fmtIntField(d, val.*, .{
1588 .kind = comptime fieldKind(field.name),
1589 .width = 16,
1590 }), field.name }),
1591 .@"enum" => try d.w.print("{x: >16} {s} ({t})\n", .{ val.*, field.name, val.* }),
14591592 .@"struct" => |s| {
14601593 switch (s.layout) {
14611594 .auto,
14621595 .@"extern",
1463 => try dumpHeader(w, field.type, val, Custom),
1596 => try dumpHeader(d, field.type, val, Custom),
14641597 .@"packed" => {
1465 try w.print("{x: >16} {s}\n", .{ @as(s.backing_integer.?, @bitCast(val.*)), field.name });
1466 try dumpFlags(w, "| {s}\n", field.type, val, 15);
1598 try d.w.print("{x: >16} {s}\n", .{ @as(s.backing_integer.?, @bitCast(val.*)), field.name });
1599 try dumpFlags(d.w, "| {s}\n", field.type, val, 15);
14671600 },
14681601 }
14691602 },
......@@ -1477,8 +1610,12 @@ const coff = struct {
14771610 try w.print("{d: >13}.{x:0<2} {s}\n", .{ major, minor, name });
14781611 }
14791612
1480 fn dumpRvaField(w: *Io.Writer, name: []const u8, rva: u64, base: u64) !void {
1481 try w.print("{x: >16} {s} ({x})\n", .{ rva, name, base + rva });
1613 fn dumpRvaField(d: *const DumpContext, name: []const u8, rva: u64, base: u64) !void {
1614 try d.w.print("{f} {s} ({f})\n", .{
1615 fmtIntField(d, rva, .{ .kind = .rva }),
1616 name,
1617 fmtIntField(d, base + rva, .{ .kind = .va }),
1618 });
14821619 }
14831620};
14841621
......@@ -1492,18 +1629,32 @@ const usage =
14921629 \\Usage: zig objdump [options] file
14931630 \\
14941631 \\Options:
1495 \\ -h, --help Print this help and exit
1496 \\ --all-headers Alias for --file-headers --member-headers --section-headers --relocs --symbols
1497 \\ --file-headers Display file-format specific headers
1498 \\ --imports Display imported symbols
1499 \\ --exports Display exported symbols
1500 \\ --linker-member[=1|2|longnames] (Coff) Display contents of the specified linker member (default 2)
1501 \\ --member-headers Display archive member headers
1502 \\ --only-member=[name] Only consider archive members names that contain [name]. Can be specified multiple times.
1503 \\ --only-section=[name] Only consider section names that contain [name]. Can be specified multiple times.
1504 \\ --relocs Display relocations
1505 \\ --section-headers Display section headers
1506 \\ --strings Display string tables
1507 \\ --symbols Display symbol tables
1508 \\ --tls Display TLS information
1632 \\ -h, --help Print this help and exit
1633 \\ --all-headers Alias for --file-headers --member-headers --section-headers --relocs --symbols
1634 \\ --file-headers Display file-format specific headers
1635 \\ --imports Display imported symbols
1636 \\ --exports Display exported symbols
1637 \\ --linker-member[=1|2|longnames] (Coff) Display contents of the specified archive linker member (default 2)
1638 \\ --member-headers Display archive member headers
1639 \\ --redact=[kind] Redact the specified field kind. Intended for snapshot testing.
1640 \\ rva Relative virtual addresses
1641 \\ va Virtual addresses and file offsets
1642 \\ ord Symbol ordinals / hints
1643 \\ size Sizes and lengths
1644 \\ all All of the above
1645 \\ --omit-element=[kind] Omit specific parts of the output. Intended for snapshot testing.
1646 \\ file-type File type summary
1647 \\ table-headers Table headers with column names
1648 \\ header-names Name that precedes a header block
1649 \\ newlines Newlines between output sections
1650 \\ all All of the above
1651 \\ --only-member=[name] Only consider archive members names that contain [name]. Can be specified multiple times.
1652 \\ --only-section=[name] Only consider section names that contain [name]. Can be specified multiple times.
1653 \\ --only-symbol=[name] Only consider symbol names that contain [name]. Can be specified multiple times.
1654 \\ --relocs Display relocations
1655 \\ -s, --snapshot Alias for --redact=all --omit-format=all
1656 \\ --section-headers Display section headers
1657 \\ --strings Display string tables
1658 \\ --symbols Display symbol tables
1659 \\ --tls Display TLS information
15091660;
lib/std/Build/Configuration.zig+5-1
......@@ -585,6 +585,8 @@ pub const Step = extern struct {
585585 expect_stderr_match: Storage.FlagLengthPrefixedList(.flags2, .expect_stderr_match, Bytes),
586586 expect_stdout_match: Storage.FlagLengthPrefixedList(.flags2, .expect_stdout_match, Bytes),
587587 expect_term_value: Storage.FlagOptional(.flags2, .expect_term, u32),
588 expect_stdout_snapshot: Storage.FlagOptional(.flags2, .expect_stdout_snapshot, LazyPath.Index),
589 expect_stderr_snapshot: Storage.FlagOptional(.flags2, .expect_stderr_snapshot, LazyPath.Index),
588590
589591 pub const CapturedStream = extern struct {
590592 generated_file: GeneratedFileIndex,
......@@ -683,7 +685,9 @@ pub const Step = extern struct {
683685 expect_stdout_match: bool,
684686 expect_term: bool,
685687 expect_term_status: ExpectTermStatus,
686 _: u25 = 0,
688 expect_stdout_snapshot: bool,
689 expect_stderr_snapshot: bool,
690 _: u23 = 0,
687691 };
688692 };
689693
lib/std/Build/Step/Run.zig+9
......@@ -129,6 +129,8 @@ pub const StdIo = union(enum) {
129129 expect_stdout_exact: []const u8,
130130 expect_stdout_match: []const u8,
131131 expect_term: process.Child.Term,
132 expect_stderr_snapshot: std.Build.LazyPath,
133 expect_stdout_snapshot: std.Build.LazyPath,
132134 };
133135};
134136
......@@ -632,6 +634,13 @@ pub fn addCheck(run: *Run, new_check: StdIo.Check) void {
632634 .check => |*checks| checks.append(b.allocator, new_check) catch @panic("OOM"),
633635 else => @panic("illegal call to addCheck: conflicting helper method calls. Suggest to directly set stdio field of Run instead"),
634636 }
637
638 switch (new_check) {
639 .expect_stderr_snapshot,
640 .expect_stdout_snapshot,
641 => |file| run.addFileInput(file),
642 else => {},
643 }
635644}
636645
637646pub fn captureStdErr(run: *Run, options: CapturedStdIo.Options) std.Build.LazyPath {
test/link.zig+24-11
......@@ -1,17 +1,30 @@
1pub fn addCases(cases: @import("tests.zig").LinkContext) void {
2 if (cases.addTestStep("static-lib-exports")) |name| {
3 const lib = cases.addStaticLibrary(.{
1pub fn addCases(ctx: *@import("tests.zig").LinkContext) void {
2 if (ctx.includeTest("exports-static")) |prefix| {
3 const lib = ctx.addLibrary(.static, .{
44 .name = "lib",
5 .zig_source_bytes =
6 \\export fn foo() void {}
7 \\var bar: u32 = 1234;
8 \\comptime { @export(&bar, .{ .name = "bar", .linkage = .strong }); }
9 \\const baz: u64 = 5678;
10 \\comptime { @export(&baz, .{ .name = "baz", .linkage = .strong }); }
11 ,
5 .zig_source_file = ctx.sourcePath("exports.zig"),
126 });
13 cases.verifyObjdump(name, lib, &.{"--symbols"}, .{ .os = true });
7 ctx.verifyObjdump(prefix, lib, &.{
8 "-s",
9 "--symbols",
10 "--only-symbol=foo",
11 }, .{});
1412 }
13
14 if (ctx.includeTest("exports-dynamic")) |prefix| {
15 const lib = ctx.addLibrary(.dynamic, .{
16 .name = "lib",
17 .zig_source_file = ctx.sourcePath("exports.zig"),
18 });
19 ctx.verifyObjdump(prefix, lib, &.{
20 "-s",
21 "--exports",
22 "--only-symbol=foo",
23 }, .{});
24 }
25
26
27
1528}
1629
1730const std = @import("std");
test/link/exports.zig created+9
......@@ -0,0 +1,9 @@
1export fn foo_fn() void {}
2var foo_var: u32 = 1234;
3comptime {
4 @export(&foo_var, .{ .name = "foo_var", .linkage = .strong });
5}
6const foo_const: u64 = 5678;
7comptime {
8 @export(&foo_const, .{ .name = "foo_const", .linkage = .strong });
9}
test/link/snapshots/exports-dynamic.lib.dmp created+14
......@@ -0,0 +1,14 @@
1Export directory:
2 0 flags
3 0 time_date_stamp
4 0.00 version
5xxxxxxxxxxxxxxxx name_rva
6 1 ordinal_base
7xxxxxxxxxxxxxxxx number_of_entries
8xxxxxxxxxxxxxxxx number_of_names
9xxxxxxxxxxxxxxxx export_address_table_rva
10xxxxxxxxxxxxxxxx name_pointer_table_rva
11xxxxxxxxxxxxxxxx ordinal_table_rva
12xxxx xxxx xxxxxxxx | foo_const
13xxxx xxxx xxxxxxxx | foo_fn
14xxxx xxxx xxxxxxxx | foo_var
test/link/snapshots/exports-static.lib.dmp created+3
......@@ -0,0 +1,3 @@
1xxxx 00000000 4 NULL() EXTERNAL | foo_fn
2xxxx 00000000 2 NULL EXTERNAL | foo_var
3xxxx 00000008 3 NULL EXTERNAL | foo_const
test/src/Link.zig+43-24
......@@ -5,21 +5,29 @@ target: std.Build.ResolvedTarget,
55use_llvm: bool,
66use_lld: bool,
77link_libc: bool,
8suffix: []const u8,
98test_filters: []const []const u8,
9update_step: ?*Step.UpdateSourceFiles,
10updated_snapshots: std.StringArrayHashMapUnmanaged(void),
1011max_rss: usize,
1112
12pub fn addTestStep(self: *const Link, prefix: []const u8) ?[]const u8 {
13pub fn includeTest(self: *const Link, prefix: []const u8) ?[]const u8 {
1314 if (for (self.test_filters) |filter| {
1415 if (std.mem.containsAtLeast(u8, prefix, 1, filter)) break false;
1516 } else self.test_filters.len > 0) return null;
17 return prefix;
18}
1619
17 return std.fmt.allocPrint(self.b.allocator, "test-{s}", .{prefix}) catch @panic("OOM");
20pub fn sourcePath(self: *const Link, sub_path: []const u8) std.Build.LazyPath {
21 return self.b.path(self.b.pathJoin(&.{ "test/link", sub_path }));
1822}
1923
20pub fn addStaticLibrary(self: *const Link, overlay: OverlayOptions) *Step.Compile {
24pub fn addLibrary(
25 self: *const Link,
26 linkage: std.builtin.LinkMode,
27 overlay: OverlayOptions,
28) *Step.Compile {
2129 return self.b.addLibrary(.{
22 .linkage = .static,
30 .linkage = linkage,
2331 .name = overlay.name,
2432 .root_module = self.createModule(overlay),
2533 .use_llvm = self.use_llvm,
......@@ -27,7 +35,6 @@ pub fn addStaticLibrary(self: *const Link, overlay: OverlayOptions) *Step.Compil
2735 });
2836}
2937
30// TODO: Use std.meta.FieldEnum on TargetQuery?
3138const SnapshotScope = packed struct {
3239 arch: bool = false,
3340 os: bool = false,
......@@ -38,33 +45,44 @@ const SnapshotScope = packed struct {
3845 link_libc: bool = false,
3946};
4047
48/// Verify the results of a `zig objdump` call against a snapshot, which
49/// contains the expected output. Snapshots alias between all build
50/// configurations by default, but by specifying fields in `scope`,
51/// unique snapshot names are generated for each value of that field.
4152pub fn verifyObjdump(
42 self: *const Link,
43 name: []const u8,
53 self: *Link,
54 prefix: []const u8,
4455 compile: *Step.Compile,
4556 args: []const []const u8,
4657 scope: SnapshotScope,
4758) void {
48 const snapshot_name = self.snapshotName(name, compile.name, scope) catch @panic("OOM");
59 const snapshot_name = self.snapshotName(prefix, compile.name, scope) catch @panic("OOM");
60 const snapshot_sub_path = self.b.pathJoin(&.{ "test/link/snapshots/", snapshot_name });
61
62 // Many tests may read the same snapshot, so only use the first one to update.
63 // If there are differences in output, they will show up on the next test run.
64 if (self.update_step != null) {
65 const gop = self.updated_snapshots.getOrPut(self.b.allocator, snapshot_sub_path) catch @panic("OOM");
66 if (gop.found_existing) return;
67 }
68
4969 const run_step = Step.Run.create(self.b, self.b.fmt("objdump {s}", .{snapshot_name}));
5070 run_step.addArgs(&.{ self.b.graph.zig_exe, "objdump" });
5171 run_step.addArtifactArg(compile);
5272 run_step.addArgs(args);
5373 run_step.addCheck(.{ .expect_term = .{ .exited = 0 } });
5474
55 const actual_path = run_step.captureStdOut(.{ .trim_whitespace = .none });
56 const expected_path = self.b.path(self.b.pathJoin(&.{ "test/link/snapshots/", snapshot_name }));
75 if (self.update_step) |update_step| {
76 // Workaround for the build system not realizing objdump itself has changed
77 run_step.has_side_effects = true;
5778
58 const check_step = self.b.addCheckFile(actual_path, .{
59 .expected_file = .{
60 .file = expected_path,
61 .if_missing = .fail,
62 // TODO: Option to do UpdateSourceFiles if not matching / missing?
63 // TODO: Option to output to <name>-<self.suffix>.actual.dmp file?
64 },
65 });
79 const snapshot_update_path = run_step.captureStdOut(.{});
80 update_step.addCopyFileToSource(snapshot_update_path, snapshot_sub_path);
81 } else {
82 run_step.addCheck(.{ .snapshot = .{ .file = self.b.path(snapshot_sub_path) } });
83 }
6684
67 self.step.dependOn(&check_step.step);
85 self.step.dependOn(&run_step.step);
6886}
6987
7088fn snapshotName(
......@@ -81,9 +99,9 @@ fn snapshotName(
8199 if (scope.os) try w.print("-{t}", .{self.target.result.os.tag});
82100 if (scope.abi) try w.print("-{t}", .{self.target.result.abi});
83101 if (scope.optimize) try w.print("-{t}", .{self.optimize});
84 if (scope.use_llvm and self.use_llvm) try w.writeAll("-llvm");
85 if (scope.use_lld and self.use_lld) try w.writeAll("-lld");
86 if (scope.link_libc and self.link_libc) try w.writeAll("-libc");
102 if (scope.use_llvm) try w.writeAll(if (self.use_llvm) "-llvm" else "-no-llvm");
103 if (scope.use_lld) try w.writeAll(if (self.use_lld) "-lld" else "-no-lld");
104 if (scope.link_libc) try w.writeAll(if (self.link_libc) "-libc" else "-no-libc");
87105 try w.writeAll(".dmp");
88106
89107 return try snapshot_name.toOwnedSlice();
......@@ -95,7 +113,7 @@ fn createModule(self: *const Link, overlay: OverlayOptions) *Build.Module {
95113 const mod = self.b.createModule(.{
96114 .target = self.target,
97115 .optimize = self.optimize,
98 .root_source_file = rsf: {
116 .root_source_file = overlay.zig_source_file orelse rsf: {
99117 const bytes = overlay.zig_source_bytes orelse break :rsf null;
100118 const name = self.b.fmt("{s}.zig", .{overlay.name});
101119 break :rsf write_files.add(name, bytes);
......@@ -148,6 +166,7 @@ const OverlayOptions = struct {
148166 objcpp_source_bytes: ?[]const u8 = null,
149167 objcpp_source_flags: []const []const u8 = &.{},
150168 zig_source_bytes: ?[]const u8 = null,
169 zig_source_file: ?std.Build.LazyPath = null,
151170 pic: ?bool = null,
152171 strip: ?bool = null,
153172};
test/tests.zig+24-9
......@@ -3148,6 +3148,11 @@ const LinkTestOptions = struct {
31483148
31493149pub fn addLinkTests(b: *std.Build, options: LinkTestOptions) *Step {
31503150 const step = b.step("test-link", "Run the linker tests");
3151 const update_snapshots = b.option(
3152 bool,
3153 "link-snapshot-update",
3154 "Update linker test snapshots in-place instead of testing against them",
3155 ) orelse false;
31513156
31523157 for (link_targets) |link_target| {
31533158 if (options.skip_non_native and !link_target.target.isNative()) continue;
......@@ -3168,24 +3173,34 @@ pub fn addLinkTests(b: *std.Build, options: LinkTestOptions) *Step {
31683173 if (options.skip_llvm and would_use_llvm) continue;
31693174 if (link_target.link_libc and target.abi == .msvc and b.graph.host.result.os.tag != .windows) continue;
31703175
3171 link.addCases(.{
3176 const opt_update_step = if (update_snapshots) update: {
3177 const update_step = Step.UpdateSourceFiles.create(b);
3178 step.dependOn(&update_step.step);
3179 break :update update_step;
3180 } else null;
3181
3182 var context: LinkContext = .{
31723183 .b = b,
31733184 .step = step,
31743185 .optimize = optimize_mode,
31753186 .target = resolved_target,
3176 .suffix = std.fmt.allocPrint(b.allocator, "{s}-{t}{s}{s}{s}", .{
3177 target.zigTriple(b.allocator) catch @panic("OOM"),
3178 optimize_mode,
3179 if (link_target.use_llvm) "-llvm" else "",
3180 if (link_target.use_lld) "-lld" else "",
3181 if (link_target.link_libc) "-libc" else "",
3182 }) catch @panic("OOM"),
3187 // .suffix = std.fmt.allocPrint(b.allocator, "{s}-{t}{s}{s}{s}", .{
3188 // target.zigTriple(b.allocator) catch @panic("OOM"),
3189 // optimize_mode,
3190 // if (link_target.use_llvm) "-llvm" else "",
3191 // if (link_target.use_lld) "-lld" else "",
3192 // if (link_target.link_libc) "-libc" else "",
3193 // }) catch @panic("OOM"),
31833194 .use_llvm = link_target.use_llvm,
31843195 .use_lld = link_target.use_lld,
31853196 .link_libc = link_target.link_libc,
31863197 .test_filters = options.test_filters,
3198 .update_step = opt_update_step,
3199 .updated_snapshots = .empty,
31873200 .max_rss = options.max_rss,
3188 });
3201 };
3202
3203 link.addCases(&context);
31893204 }
31903205 }
31913206 return step;