From 58643dab07a803dbb579d84f68419911f5a2a16d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 10 Nov 2026 23:04:17 -0300 Subject: trace: glibc's heap, read from a recording at any moment record --heap keeps the arena, the tcache and, of every chunk, its size word and the links of those on a list: free chunks stay readable, which --alloc dropped at the free. zt.heap.glibc gives the chunks in address order, the tcache's and the bins' chains (safe-linking as the stored value and the pointer it protects), the top; each with the address of the word it was read from, each chain saying how it ended. ztrace show prints it. Layouts for glibc 2.44 (no fastbins; a tcache made at the first free, counting the slots left) and 2.40; the arena found by symbol or by the struct whose next points at itself. Against pwndbg on 2.40: the same at every stop. Three bytes a moment and a sixth slower on the list by instruction. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016Y9MNCKgYCGiANnEwcEQxa --- build/heap.zig | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 build/heap.zig (limited to 'build') diff --git a/build/heap.zig b/build/heap.zig new file mode 100644 index 0000000..ae93d78 --- /dev/null +++ b/build/heap.zig @@ -0,0 +1,36 @@ +//! glibc's heap: a program that mallocs and frees a step at a time, +//! recorded with `--heap` and read back. +const std = @import("std"); +const Ctx = @import("../build.zig").Ctx; + +pub fn add(ctx: Ctx) void { + const b = ctx.b; + const target = ctx.cTarget("heap", &.{"heap.c"}); + b.getInstallStep().dependOn(&b.addInstallArtifact(target, .{ .dest_dir = .{ .override = .{ .custom = "targets" } } }).step); + const step = ctx.areaTest("test-heap", "glibc's heap, recorded at each step and read back"); + + // The library, driven from Zig: the reader against the live process. + const paths = b.addOptions(); + paths.addOptionPath("heap", target.getEmittedBin()); + step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("src/trace/heap_test.zig"), + .target = ctx.target, + .optimize = ctx.optimize, + .imports = &.{ .{ .name = "ztrace", .module = ctx.ztrace }, .{ .name = "targets", .module = paths.createModule() } }, + }) })).step); + + // The commands: a recording with the heap, and its last moment shown. + const record = b.addRunArtifact(ctx.exe); + record.addArgs(&.{ "record", "--by", "break", "-b", "heap_step", "--heap", "-o" }); + const recording = record.addOutputFileArg("heap.ztrace"); + record.addArg("--"); + record.addArtifactArg(target); + record.expectStdErrMatch("heap: glibc "); + record.expectStdErrMatch("exit 0"); + const show = b.addRunArtifact(ctx.exe); + show.addArg("show"); + show.addFileArg(recording); + show.addArg("-1"); + inline for (.{ " heap: main_arena ", " top\n", "\ntcache ", " tcache 30 [" }) |part| show.expectStdOutMatch(part); + step.dependOn(&show.step); +} -- cgit v1.3