summaryrefslogtreecommitdiff
path: root/src/trace/debugger_test.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/trace/debugger_test.zig')
-rw-r--r--src/trace/debugger_test.zig281
1 files changed, 281 insertions, 0 deletions
diff --git a/src/trace/debugger_test.zig b/src/trace/debugger_test.zig
index 15ecc71..bd35560 100644
--- a/src/trace/debugger_test.zig
+++ b/src/trace/debugger_test.zig
@@ -323,6 +323,287 @@ test "a call followed down by instruction: through the PLT, the loader's resolve
try std.testing.expect(resolver > 300);
}
+/// Every jump and return a recording by instruction made, tied to its
+/// block's edge: the `branch` event at a stop is the instruction at its
+/// pc, the last of its block; the next stop is at the edge it took.
+/// Returns how many were tied, and how many were in code with no bounds,
+/// recorded as no blocks.
+fn tieBranches(trace: *const zt.Trace) ![2]usize {
+ var tied: usize = 0;
+ var loose: usize = 0;
+ var out: [512]zt.telescope.Block = undefined;
+ var text: [256]u8 = undefined;
+ for (0..trace.len - 1) |i| {
+ const m = try trace.moment(i);
+ var events = try m.events(gpa);
+ defer events.deinit(gpa);
+ const branch = while (events.next()) |item| {
+ if (item.ev.kind == .branch and (item.ev.aux == 2 or item.ev.aux == 3)) break item.ev;
+ } else continue;
+ const pc = branch.a[2];
+ const g = zt.telescope.blocks(m, pc, &out) orelse {
+ // Code with no bounds: no symbol with a size, no unwind information (the C runtime's start).
+ try std.testing.expect(zt.telescope.function(m, pc) == null);
+ loose += 1;
+ continue;
+ };
+ const block = g.blocks[g.here.?];
+ try std.testing.expectEqual(block.start + block.len, pc + (try zt.telescope.instruction(m, pc, &text)).?.len);
+ // The next stop of the same thread: the next moment by instruction, or the one after a syscall's.
+ const next = next: for (i + 1..trace.len) |j| {
+ const later = try trace.moment(j);
+ var after = try later.events(gpa);
+ defer after.deinit(gpa);
+ while (after.next()) |item| if (item.ev.kind == .step and item.ev.tid == branch.tid) break :next item.ev.a[0];
+ } else unreachable;
+ switch (block.end) {
+ .ret => try std.testing.expectEqual(@as(u16, 3), branch.aux),
+ .jump, .tail => try std.testing.expectEqual(block.to.?, next),
+ .branch => try std.testing.expectEqual(if (branch.a[1] != 0) block.to.? else block.falls.?, next),
+ // A jump through memory goes where the event says.
+ .indirect => try std.testing.expectEqual(branch.a[0], next),
+ else => return error.NotABranch,
+ }
+ tied += 1;
+ }
+ return .{ tied, loose };
+}
+
+test "a function's basic blocks from a recording, and the edges a run took: two loops" {
+ var trace = try zt.Trace.open(gpa, io, targets.list_recording);
+ defer trace.close();
+ var out: [16]zt.telescope.Block = undefined;
+ // Their blocks, by `objdump -d` of zig-out/targets/list (-O1):
+ //
+ // reverse: +0 test rdi, rdi list_done: +0 test rdi, rdi
+ // +3 je +25 +3 je +1e
+ // +5 push rbp +5 push rbp
+ // +6 mov rbp, rsp +6 mov rbp, rsp
+ // +9 xor eax, eax +9 xor eax, eax
+ // +b nop +b nop
+ // +10 mov rcx, rax +10 add rax, [rdi]
+ // +13 mov rax, rdi +13 mov rdi, [rdi + 8]
+ // +16 mov rdi, [rdi + 8] +17 test rdi, rdi
+ // +1a mov [rax + 8], rcx +1a jne +10
+ // +1e test rdi, rdi +1c pop rbp
+ // +21 jne +10 +1d ret
+ // +23 pop rbp +1e xor eax, eax
+ // +24 ret +20 ret
+ // +25 xor eax, eax
+ // +27 ret
+ //
+ // The empty list's test, the frame falling into the loop, the loop
+ // back to itself, and two returns.
+ const Want = struct { u64, u64, zt.Debugger.End, ?u64, ?u64 };
+ for ([_][]const u8{ "reverse", "list_done" }, [_][5]Want{
+ .{ .{ 0, 5, .branch, 0x25, 5 }, .{ 5, 0xb, .fall, null, 0x10 }, .{ 0x10, 0x13, .branch, 0x10, 0x23 }, .{ 0x23, 2, .ret, null, null }, .{ 0x25, 3, .ret, null, null } },
+ .{ .{ 0, 5, .branch, 0x1e, 5 }, .{ 5, 0xb, .fall, null, 0x10 }, .{ 0x10, 0xc, .branch, 0x10, 0x1c }, .{ 0x1c, 2, .ret, null, null }, .{ 0x1e, 3, .ret, null, null } },
+ }) |name, want| {
+ // The first stop in the function.
+ const m, const pc = find: for (0..trace.len) |i| {
+ const m = try trace.moment(i);
+ const tids = try m.threads(gpa);
+ defer gpa.free(tids);
+ const regs = (try m.regs(tids[0])) orelse continue;
+ if (std.mem.startsWith(u8, m.trace.strings.get(regs.rip) orelse "", name)) break :find .{ m, regs.rip };
+ } else return error.NotReached;
+ const g = zt.telescope.blocks(m, pc, &out).?;
+ try std.testing.expect(g.text);
+ try std.testing.expectEqual(want.len, g.count);
+ const here: []const u8 = m.trace.strings.get(pc).?;
+ try std.testing.expectEqual(g.start, pc - try std.fmt.parseInt(u64, here[name.len + 1 ..], 10));
+ for (want, g.blocks) |w, b| {
+ try std.testing.expectEqual(g.start + w[0], b.start);
+ try std.testing.expectEqual(w[1], b.len);
+ try std.testing.expectEqual(w[2], b.end);
+ try std.testing.expectEqual(if (w[3]) |to| g.start + to else null, b.to);
+ try std.testing.expectEqual(if (w[4]) |falls| g.start + falls else null, b.falls);
+ }
+ }
+ const tied, const loose = try tieBranches(&trace);
+ try std.testing.expect(tied > 10 and loose == 0);
+}
+
+test "a libc function's basic blocks, from its unwind bounds, at its system call" {
+ var trace = try zt.Trace.open(gpa, io, targets.hello_recording);
+ defer trace.close();
+ var out: [64]zt.telescope.Block = undefined;
+ var text: [256]u8 = undefined;
+ var checked: usize = 0;
+ for (0..trace.len) |i| {
+ const m = try trace.moment(i);
+ const tids = try m.threads(gpa);
+ defer gpa.free(tids);
+ const regs = (try m.regs(tids[0])) orelse continue;
+ const insn = (try zt.telescope.instruction(m, regs.rip, &text)) orelse continue;
+ if (!std.mem.eql(u8, insn.text, "syscall") or !std.mem.startsWith(u8, m.trace.strings.get(regs.rip) orelse "", "libc.so.6!open+")) continue;
+ const g = zt.telescope.blocks(m, regs.rip, &out).?;
+ // open's, whole: from its first instruction, every instruction's text there.
+ try std.testing.expectEqualStrings("libc.so.6!open+0", m.trace.strings.get(g.start).?);
+ try std.testing.expect(g.text and g.count <= out.len);
+ const here = g.blocks[g.here.?];
+ try std.testing.expect(here.start <= regs.rip and regs.rip < here.start + here.len);
+ // The blocks run end to end, each a run of instructions, every edge in the function to a block's start.
+ var at = g.start;
+ for (g.blocks) |b| {
+ try std.testing.expectEqual(at, b.start);
+ at += b.len;
+ var pc = b.start;
+ while (pc < b.start + b.len) pc += (try zt.telescope.instruction(m, pc, &text)).?.len;
+ try std.testing.expectEqual(b.start + b.len, pc);
+ for ([_]?u64{ b.to, b.falls }) |edge| if (edge) |to| if (to -% g.start < g.len) {
+ for (g.blocks) |c| {
+ if (c.start == to) break;
+ } else return error.EdgeIntoABlock;
+ };
+ }
+ try std.testing.expectEqual(g.start + g.len, at);
+ // Its return, and a call that does not return: __stack_chk_fail.
+ var ends: [2]bool = @splat(false);
+ for (g.blocks) |b| {
+ if (b.end == .ret) ends[0] = true;
+ if (b.end == .noreturn) if (b.to) |callee| if (std.mem.indexOf(u8, m.trace.strings.get(callee) orelse "", "__stack_chk_fail") != null) {
+ ends[1] = true;
+ };
+ }
+ try std.testing.expectEqual([2]bool{ true, true }, ends);
+ checked += 1;
+ }
+ try std.testing.expectEqual(@as(usize, 1), checked);
+ // Every jump and return of main, the PLT, the resolver and libc, tied to its edge.
+ const tied, const loose = try tieBranches(&trace);
+ try std.testing.expect(tied > 300 and loose < 10);
+}
+
+/// Runs a command, its output kept, with the environment ASan wants under a
+/// tracer: no leak check (LeakSanitizer cannot work under ptrace).
+fn runQuiet(argv: []const []const u8) !std.process.RunResult {
+ var env = std.process.Environ.Map.init(gpa);
+ defer env.deinit();
+ try env.put("ASAN_OPTIONS", "detect_leaks=0");
+ return std.process.run(gpa, io, .{ .argv = argv, .environ_map = &env });
+}
+
+fn exited(result: std.process.RunResult) ?u8 {
+ defer gpa.free(result.stdout);
+ defer gpa.free(result.stderr);
+ return switch (result.term) {
+ .exited => |code| code,
+ else => null,
+ };
+}
+
+/// The last moment's events of a kind, from a recording: the stops and exits that end a run.
+fn lastOf(trace: *const zt.Trace, kind: zt.Kind) !?zt.Event {
+ var found: ?zt.Event = null;
+ for (0..trace.len) |i| {
+ var events = try (try trace.moment(i)).events(gpa);
+ defer events.deinit(gpa);
+ while (events.next()) |item| if (item.ev.kind == kind) {
+ found = item.ev;
+ };
+ }
+ return found;
+}
+
+test "a stack overflow built plain: past the buffer, its own counter smashed, it writes to the stack's end and faults there" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
+ const dir = dir_buf[0..try tmp.dir.realPath(io, &dir_buf)];
+ const path = try std.fs.path.join(gpa, &.{ dir, "plain.ztrace" });
+ defer gpa.free(path);
+ try std.testing.expectEqual(@as(?u8, 0), exited(try runQuiet(&.{ targets.ztrace, "record", "--by", "syscall", "--from", "fill", "-o", path, "--", targets.overflow, "x" })));
+ var trace = try zt.Trace.open(gpa, io, path);
+ defer trace.close();
+ // SIGSEGV at a store of the loop in fill, its address just past the stack's top.
+ const signal = (try lastOf(&trace, .signal)).?;
+ try std.testing.expectEqual(@as(u16, @backingInt(linux.SIG.SEGV)), signal.aux);
+ const m = try trace.moment(trace.len - 1);
+ try std.testing.expect(std.mem.startsWith(u8, m.trace.strings.get(signal.a[1]) orelse "", "fill+"));
+ var name: []const u8 = "";
+ var buf: [64]u8 = undefined;
+ try std.testing.expect(try m.mapping(signal.a[0], null, &buf) == null);
+ _ = (try m.mapping(signal.a[0] - 1, &name, &buf)).?;
+ try std.testing.expectEqualStrings("[stack]", name);
+ try std.testing.expectEqual(@as(u64, 128 + @backingInt(linux.SIG.SEGV)), (try lastOf(&trace, .exit)).?.a[0]);
+}
+
+test "the same overflow built with ASan, by gcc and by clang: its shadow round the buffer, the branch into its report, the report's text and the exit" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
+ const dir = dir_buf[0..try tmp.dir.realPath(io, &dir_buf)];
+ var built: usize = 0;
+ for ([_][]const u8{ "gcc", "clang" }) |cc| {
+ const exe = try std.fs.path.join(gpa, &.{ dir, cc });
+ defer gpa.free(exe);
+ // A compiler that is not here, or has no ASan runtime, is passed over.
+ const compiled = exited(runQuiet(&.{ cc, "-fsanitize=address", "-O0", "-g", targets.overflow_source, "-o", exe }) catch continue);
+ if (compiled != 0) continue;
+ built += 1;
+
+ // By instruction from fill into the report: the stop at its first instruction.
+ const steps = try std.fs.path.join(gpa, &.{ dir, "steps.ztrace" });
+ defer gpa.free(steps);
+ try std.testing.expectEqual(@as(?u8, 0), exited(try runQuiet(&.{ targets.ztrace, "record", "--by", "insn", "--from", "fill", "--asan", "--stack", "512", "--steps", "3000", "-o", steps, "--", exe, "x" })));
+ var trace = try zt.Trace.open(gpa, io, steps);
+ defer trace.close();
+ const at = for (1..trace.len) |i| {
+ const m = try trace.moment(i);
+ const tids = try m.threads(gpa);
+ defer gpa.free(tids);
+ const regs = (try m.regs(tids[0])) orelse continue;
+ if (std.mem.indexOf(u8, m.trace.strings.get(regs.rip) orelse "", "__asan_report_store1+0") != null) break i;
+ } else return error.NoReport;
+ const m = try trace.moment(at);
+ const tids = try m.threads(gpa);
+ defer gpa.free(tids);
+ const regs = (try m.regs(tids[0])).?;
+ // Its argument is the first byte past buf: buf's 16 bytes addressable
+ // (00 00), the left redzone before them (f1), the right one from there (f3).
+ for ([_]i64{ -48, -40, -32, -24, -16, -8, 0, 8 }, [_]u8{ 0xf1, 0xf1, 0xf1, 0xf1, 0, 0, 0xf3, 0xf3 }) |off, want| {
+ const s = (try zt.telescope.shadow(m, regs.rdi +% @as(u64, @bitCast(off)))).?;
+ try std.testing.expectEqual(@as(?u8, want), s.value);
+ }
+ // Reached by a branch taken (gcc's through its PLT stub), and walked back to main.
+ var events = try (try trace.moment(at - 1)).events(gpa);
+ defer events.deinit(gpa);
+ const into = while (events.next()) |item| {
+ if (item.ev.kind == .branch) break item.ev;
+ } else return error.NoBranch;
+ try std.testing.expectEqual(regs.rip, into.a[0]);
+ try std.testing.expectEqual(@as(u64, 1), into.a[1]);
+ var chain_buf: [16]u64 = undefined;
+ const chain = try zt.telescope.backtrace(m, &regs, &chain_buf);
+ try std.testing.expect(std.mem.startsWith(u8, m.trace.strings.get(chain[1]).?, "fill+"));
+ try std.testing.expect(std.mem.startsWith(u8, m.trace.strings.get(chain[2]).?, "main+"));
+ // The runtime's calls in fill are named: its fake stack's allocation too.
+ var names = trace.strings.valueIterator();
+ while (names.next()) |text| {
+ if (std.mem.indexOf(u8, text.*, "__asan_stack_malloc_") != null) break;
+ } else return error.NoStackMalloc;
+
+ // By syscall to the end: the report as it was written, and the exit.
+ const end = try std.fs.path.join(gpa, &.{ dir, "end.ztrace" });
+ defer gpa.free(end);
+ try std.testing.expectEqual(@as(?u8, 0), exited(try runQuiet(&.{ targets.ztrace, "record", "--by", "syscall", "--from", "fill", "--asan", "-s", "4096", "-o", end, "--", exe, "x" })));
+ var whole = try zt.Trace.open(gpa, io, end);
+ defer whole.close();
+ var reported = false;
+ for (0..whole.len) |i| {
+ var all = try (try whole.moment(i)).events(gpa);
+ defer all.deinit(gpa);
+ while (all.next()) |item| if (item.ev.kind == .syscall_enter and item.ev.aux == @backingInt(linux.SYS.write) and item.ev.a[0] == 2) {
+ if (std.mem.indexOf(u8, item.payload, "ERROR: AddressSanitizer: stack-buffer-overflow") != null) reported = true;
+ };
+ }
+ try std.testing.expect(reported);
+ try std.testing.expectEqual(@as(u64, 1), (try lastOf(&whole, .exit)).?.a[0]);
+ }
+ if (built == 0) return error.SkipZigTest;
+}
+
test "step walks the source lines, in and out of calls, as gdb does" {
var d = try spawn(targets.list, "2", null);
defer d.deinit();