summaryrefslogtreecommitdiff
path: root/design/mock/context.py
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-10 23:25:40 -0300
committerGabriel Schneider <[email protected]>2026-11-10 23:34:16 -0300
commit2a97030c9743d4680d698414c28e8d8739614215 (patch)
tree8415bb3aeeb5d5d909a2d311c2a30ab07f91c9fa /design/mock/context.py
parent58643dab07a803dbb579d84f68419911f5a2a16d (diff)
downloadcomputeranim-2a97030c9743d4680d698414c28e8d8739614215.tar.gz
computeranim-2a97030c9743d4680d698414c28e8d8739614215.zip
design: down is deeper; a call followed down; operands without size words; the heap as a scene
From the user. Direction and nearness are rules: the idea, the source, its instructions, the callee and the kernel go down the frame, a call goes down and a return comes up, and every tie runs one of those ways. The disassembly can descend: a window a call depth, the caller keeping three rows with its call waiting, a PLT stub its jump, the kernel at the bottom on vellum, with verbs descend, cross and ascend. The kernel leaves the band, which keeps the calls so far as strace writes them; the backtrace has its newest frame at the bottom. Size words are dropped from operands and a width is shown as byte cells where nothing else says it; a compare shows its values and flags, a jump the flags it reads, an indirect call its target and the slot it was read from. libc's heap is a scene of blocks that exist (a dump by fields with a size and a protected pointer read, arcs as the free list, a loupe into the tcache, the list drawn over malloc's own), storyboarded on glibc 2.44. Mocks 16 to 18. Co-Authored-By: Claude Fable 5.2 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNCKgYCGiANnEwcEQxa
Diffstat (limited to 'design/mock/context.py')
-rw-r--r--design/mock/context.py458
1 files changed, 391 insertions, 67 deletions
diff --git a/design/mock/context.py b/design/mock/context.py
index 8c99956..efae74c 100644
--- a/design/mock/context.py
+++ b/design/mock/context.py
@@ -436,14 +436,19 @@ def wide(total):
return max(len(str(total)) - 3, 0) * A
-def source(g, y, rows, lines, first, cur, trail, name, total):
- """Returns the y of the current line's row. Numbers as wide as the file's last: the text moves by the extra."""
+def source(g, y, rows, lines, first, cur, trail, name, total, waiting=None):
+ """Returns the y of the current line's row. Numbers as wide as the file's last: the text moves by the extra.
+ waiting: the pc is in code with no source; cur is the line whose call it is under, ringed, and the tag says
+ where the pc is."""
w = wide(total)
- y0 = panel(g, LX, y, CW, rows, name, note=f"lines {first} to {min(first + rows - 1, total)} of {total}")
+ y0 = panel(g, LX, y, CW, rows, name, note=waiting or f"lines {first} to {min(first + rows - 1, total)} of {total}")
for i in range(rows):
n = first + i
yy = y0 + i * ROW
- if n == cur:
+ if n == cur and waiting:
+ g.frame(LX + 2, yy, 50 + w, ROW, VELLUM, 2)
+ g.t(LX + 46 + w, b(yy), str(n), S, VELLUM, BOLD, "end")
+ elif n == cur:
g.t(LX + 46 + w, b(yy), str(n), S, current_row(g, LX + 2, yy, CW - 4, 50 + w), BOLD, "end")
else:
if n in trail:
@@ -454,17 +459,81 @@ def source(g, y, rows, lines, first, cur, trail, name, total):
DX_ADDR, DX_LINE, DX_MN, DX_OPS, DX_NOTE = 40, 134, 180, 264, 564
+SIZES = {"byte": 1, "word": 2, "dword": 4, "qword": 8, "tbyte": 10, "xmmword": 16, "ymmword": 32, "zmmword": 64}
+IMPLIED = {"push", "pop", "call", "jmp", "lea", "nop", "endbr64"} # the width is the mnemonic's, or nothing is touched
-def disasm(g, y, rows, func, cur_line, jump=None, w=0):
+def reg_width(r):
+ """The bytes a register names, or None for what is not one (a segment, a number)."""
+ m = re.fullmatch(r"([xyz])mm\d+", r) or re.fullmatch(r"r(\d+)([dwb]?)", r)
+ if m and m.re.pattern.startswith("(["):
+ return {"x": 16, "y": 32, "z": 64}[m.group(1)]
+ if m:
+ return {"": 8, "d": 4, "w": 2, "b": 1}[m.group(2)]
+ for n, pat in ((8, r"r([abcd]x|[sd]i|[sb]p|ip)"), (4, r"e([abcd]x|[sd]i|[sb]p|ip)"), (2, r"[abcd]x|[sd]i|[sb]p"),
+ (1, r"[abcd][lh]|[sd]il|[sb]pl")):
+ if re.fullmatch(pat, r):
+ return n
+ return None
+
+
+def width(g, x, y, n):
+ """`width`: an access's size as byte cells after the operand it is the size of: 5 by 10, 7 apart, 3 after
+ the bracket, in dim; what follows the operand goes on 4 after the last. Returns where it goes on."""
+ for i in range(min(n, 8)):
+ g.rect(x + 3 + i * 7, y + 9, 5, 10, DIM)
+ end = x + 3 + min(n, 8) * 7 - 2
+ if n > 8: # wider than a word: the count after the cells
+ g.t(end + 4, b(y), str(n), S, FAINT, MONO)
+ end += 4 + len(str(n)) * A
+ return end + 4
+
+
+def operands(g, x, y, mn, s, ink, sizes=False):
+ """Operands as the disassembler writes them, less the size word (`qword ptr `). Where no register of the
+ same instruction has the access's size, a `width` after the bracket says it. sizes: draw them as written
+ (the mock's 'before'). Returns where the row's text ends."""
+ m = re.search(r"\b(%s) ptr " % "|".join(SIZES), s)
+ if sizes or not m:
+ g.t(x, b(y), s, S, FAINT if mn in ("nop", "endbr64") else ink, MONO)
+ return x + len(s) * A
+ n, s = SIZES[m.group(1)], s[:m.start()] + s[m.end():]
+ if mn in ("nop", "endbr64"): # padding: nothing is read or written
+ g.t(x, b(y), s, S, FAINT, MONO)
+ return x + len(s) * A
+ outside = re.sub(r"\[.*?\]", "", s)
+ if mn in IMPLIED or n in [reg_width(t) for t in re.findall(r"[a-z][a-z0-9]*", outside)]:
+ g.t(x, b(y), s, S, ink, MONO)
+ return x + len(s) * A
+ cut = s.index("]") + 1
+ g.t(x, b(y), s[:cut], S, ink, MONO)
+ x = width(g, x + cut * A, y, n)
+ g.t(x, b(y), s[cut:], S, ink, MONO)
+ return x + len(s[cut:]) * A
+
+
+def disasm(g, y, rows, func, cur_line, jump=None, w=0, sizes=False):
"""rows: (address, line, mnemonic, operands, state, note), in address order: the pc's row and as many
- above as below. state: cur | trail0..2 (it ran just now) | out (past the function's end) | None.
- note, the row's annotation: ("chain", links, end, marks) | ("set", register, links, end) | ("text", s).
+ above as below. state: cur | trail0..2 (it ran just now) | out (past the function's end) | wait (a call
+ whose callee is open under it, in a descent) | None.
+ note, the row's annotation: ("chain", links, end, marks) | ("set", register, links, end) | ("text", s) |
+ ("runs", [(s, ink)]).
jump: (from, to): a jump that was taken, drawn in the lane. w: how much wider than three characters the
program's line numbers are; every column right of the line's moves by it.
Returns each address's row y."""
y0 = panel(g, LX, y, CW, len(rows), "disassembly", note=func)
- lead = shared([r[0] for r in rows if r[4] != "out"])
+ where = insn_rows(g, y0, rows, cur_line, w, sizes=sizes)
+ if jump: # how control came here: up the lane, into the row it landed on
+ ya, yb = where[jump[0]] + 12, where[jump[1]] + 12
+ gen.arrow(g, [(LX + 38, ya), (LX + 31, ya), (LX + 31, yb), (LX + 39, yb)], TRAIL[0], 2, r=4, hl=7, hw=8)
+ return where
+
+
+def insn_rows(g, y0, rows, cur_line, w=0, lead=None, sizes=False):
+ """`insn` rows from y0, a row each. Addresses wider than seven digits (a library's, 7ffff7d10fc5) move every
+ column right of theirs by the extra, for the rows of this window only."""
+ lead = shared([r[0] for r in rows if r[4] != "out"]) if lead is None else lead
+ w += max(max(len("%x" % r[0]) for r in rows) - 7, 0) * A
where, last_line = {}, None
for i, (a, line, mn, ops, st, note) in enumerate(rows):
yy = y0 + i * ROW
@@ -474,50 +543,115 @@ def disasm(g, y, rows, func, cur_line, jump=None, w=0):
g.rect(LX + 2, yy, CW - 4, 2, RULE)
if st == "cur":
g.path(f"M{LX + 20},{yy + 12} l-10,-6 v12 Z", fill=current_row(g, LX + 2, yy, CW - 4, 24))
+ elif st == "wait": # it called, and waits: the plaque's place ringed, as a waiting call node
+ g.frame(LX + 2, yy, 24, ROW, VELLUM, 2)
+ g.path(f"M{LX + 19},{yy + 12} l-8,-5 v10 Z", fill=VELLUM)
elif st and st.startswith("trail"):
g.rect(LX + 2, yy + 1, 4, ROW - 2, TRAIL[int(st[-1])])
+ elif st == "pass": # a stub's jump, passed through on the way down
+ g.rect(LX + 2, yy + 1, 4, ROW - 2, TRAIL[1])
addr(g, LX + DX_ADDR, yy, a, mix(CODE, PAGE, 0.6) if dim else CODE, lead=0 if dim else lead)
if line is not None and line != last_line and not dim: # the line this run was compiled from
on = line == cur_line
g.t(LX + DX_LINE + 3 * A + w, b(yy), str(line), S, GOLD if on else FAINT, BOLD if on else MONO, "end")
last_line = line
- g.t(LX + DX_MN + w, b(yy), mn, S, FAINT if dim else KW, MONO if dim else BOLD)
+ g.t(LX + DX_MN + w, b(yy), mn, S, FAINT if dim or mn in ("nop", "endbr64") else KW,
+ MONO if dim or mn in ("nop", "endbr64") else BOLD)
x = LX + DX_OPS + w
for part, ink in ops:
if isinstance(part, int):
x = addr(g, x, yy, part, ink)
+ elif isinstance(part, tuple): # a target and its name: `401070 open@plt`
+ x = addr(g, x, yy, part[0], ink)
+ g.t(x + A, b(yy), part[1], S, VELLUM, MONO)
+ x += A + len(part[1]) * A
else:
- g.t(x, b(yy), part, S, FAINT if dim else ink, MONO)
- x += len(part) * A
+ x = operands(g, x, yy, mn, part, FAINT if dim else ink, sizes)
if not note:
continue
x = max(LX + DX_NOTE + w, x + A) # operands are never cut where the row has room
if note[0] == "text":
g.t(x, b(yy), note[1], S, note[2] if len(note) > 2 else DIM, MONO)
+ elif note[0] == "runs": # a line of the row's own: words, values, chips
+ for s_, ink in note[1]:
+ if isinstance(s_, int):
+ x = addr(g, x, yy, s_, ink)
+ elif ink == "arrow": # `points`
+ x = link_arrow(g, x, yy)
+ elif ink == "chip": # a flag the instruction set, as rip's row draws it
+ g.rect(x, yy + 2, 32, 20, RAISED)
+ g.t(x + 16, b(yy), s_, S, BRIGHT, BOLD, "middle")
+ x += 32 + 6
+ else:
+ g.t(x, b(yy), s_, S, ink, MONO)
+ x += len(s_) * A
elif note[0] == "set": # what an instruction that ran left in a register: a register row, small
g.t(x, b(yy), note[1], S, DIM, MONO)
chain(g, x + (len(note[1]) + 1) * A, yy, note[2], note[3], room=LX + CW - 12)
else:
where["note"] = (yy, chain(g, x, yy, note[1], note[2], note[3], room=LX + CW - 12))
- if jump: # how control came here: up the lane, into the row it landed on
- ya, yb = where[jump[0]] + 12, where[jump[1]] + 12
- gen.arrow(g, [(LX + 38, ya), (LX + 31, ya), (LX + 31, yb), (LX + 39, yb)], TRAIL[0], 2, r=4, hl=7, hw=8)
return where
-def thread(g, ys, spans):
+def descent(g, y, windows, note=None, w=0, sizes=False):
+ """`disasm` as a descent: a window of code a call deep, the caller's first, each callee's under the row that
+ called it. windows: (name, about, rows) for code, rows as disasm's; ("kernel", about, lines) last, lines
+ being runs [(s, ink)] on vellum. A window after the first opens with a head row: a rule, the call lane
+ arriving from the row that called (a `wait` row) or jumped (the row before the head), the name, what it is.
+ Returns {address: y}, and each head's y under its name."""
+ n = sum(len(wn[2]) for wn in windows) + len(windows) - 1
+ y0 = panel(g, LX, y, CW, n, "disassembly", note=note)
+ yy, where, came = y0, {}, None
+ for k, (name, about, rows) in enumerate(windows):
+ if k:
+ kern = name == "kernel"
+ if kern: # solid vellum is the kernel
+ g.rect(LX + 2, yy, CW - 4, (len(rows) + 1) * ROW, gen.KERNEL)
+ g.rect(LX + 2, yy, CW - 4, 2, gen.KERNEL_RULE if kern else RULE)
+ g.t(LX + DX_ADDR, b(yy), name if not kern else "the kernel", 18, PAGE if kern else VELLUM, "sansm")
+ g.t(LX + CW - 12, b(yy), about, 18, gen.KERNEL_DIM if kern else FAINT, "sans", "end")
+ if came is not None and not kern: # the call lane: down from the row that went, into the head
+ gen.arrow(g, [(LX + 14, came), (LX + 14, yy + 12), (LX + 34, yy + 12)], VELLUM, 2, r=4, hl=7, hw=8)
+ elif came is not None: # the crossing: down from the `syscall` row onto the vellum, its head in ink
+ g.rect(LX + 12.5, came, 3, yy - came, VELLUM)
+ g.path(f"M{LX + 14},{yy + 14} l-6,-10 h12 Z", fill=PAGE)
+ where[name] = yy
+ yy += ROW
+ if kern:
+ for i, runs in enumerate(rows):
+ x = LX + DX_ADDR
+ for s_, ink in runs:
+ if ink == "struck":
+ g.rect(x - 5, yy + i * ROW + 1, len(s_) * A + 10, ROW - 2, SOFT)
+ g.t(x, b(yy + i * ROW), s_, S, BRIGHT, BOLD)
+ else:
+ g.t(x, b(yy + i * ROW), s_, S, ink, MONO)
+ x += len(s_) * A
+ yy += len(rows) * ROW
+ continue
+ at = insn_rows(g, yy, rows, None, w, sizes=sizes)
+ where.update(at)
+ went = [r for r in rows if r[4] in ("wait", "pass", "cur")]
+ came = (at[went[-1][0]] + (ROW if went[-1][4] == "wait" else 18)) if went else None
+ yy += len(rows) * ROW
+ return where
+
+
+def thread(g, ys, spans, ink=GOLD, sw=3):
"""The gold thread: the source's current line and the instructions it was compiled to are one mark.
- A bracket on the line, a bracket on each run of its instructions, and a line in the margin between."""
+ A bracket on the line, a bracket on each run of its instructions, and a line in the margin between.
+ Waiting (the pc is in code with no source, under this line's call): primary, 2."""
x = LX - 10
- bracket(g, x, ys + 2, ys + ROW - 2, GOLD, 3, 7)
+ bracket(g, x, ys + 2, ys + ROW - 2, ink, sw, 7)
for ya, yb in spans:
- bracket(g, x, ya + 2, yb - 2, GOLD, 3, 7)
- g.rect(x - 1.5, ys + 2, 3, spans[-1][1] - 2 - ys - 2, GOLD)
+ bracket(g, x, ya + 2, yb - 2, ink, sw, 7)
+ g.rect(x - sw / 2, ys + 2, sw, spans[-1][1] - 2 - ys - 2, ink)
# ---- the lens: a list, and beside it the bytes it is drawn from -------------------------
def fields(g, y, h, about, base, length, flist, mem, region, region_of, marks=(), title="its bytes", x=None,
- framed=(), bare=False, rows_shown=None, more_rows=True, touched=(), withhold=None, hot=False):
+ framed=(), bare=False, rows_shown=None, more_rows=True, touched=(), withhold=None, hot=False, changed=(),
+ held_at=()):
"""`hexdump` by `fields`: the region a scene names, read by the fields it gives it, in the band's view.
flist: (at, len, reads, big, mark) with reads in number | pointer | text | bytes. mem: {address: byte} of what
the stop shown saw (or the kernel took); a byte not in it is unread. marks: the field marks framed as read.
@@ -576,19 +710,60 @@ def fields(g, y, h, about, base, length, flist, mem, region, region_of, marks=()
for fa, fl in framed: # the target: framed bright, as attention
if base + fa < a0 + i0 + n and base + fa + fl > a0 + i0:
g.frame(x0 - 3, yy - 1, x1 - x0 + 6, ROW + 2, BRIGHT, 2)
- ink = {"number": VELLUM, "bytes": VELLUM, "text": LIT, "loose": DIM, "malloc": DIM,
- "pointer": (region_of(word) or VELLUM) if known else VELLUM}[reads]
+ ink = {"number": VELLUM, "bytes": VELLUM, "text": LIT, "loose": DIM, "malloc": DIM, "size": VELLUM,
+ "protected": VELLUM, "pointer": (region_of(word) or VELLUM) if known else VELLUM}[reads]
nz = [k for k, v in enumerate(vals) if v]
+ hit = [k for k in range(n) if a0 + i0 + k in changed]
+ if hit: # struck: the bytes whose value changed, first to last, in the run
+ g.rect(bx(i0 + hit[0]) - 5, yy + 1, bx(i0 + hit[-1]) - bx(i0 + hit[0]) + 34, ROW - 2, SOFT)
+ if any(a0 + i0 + k in held_at for k in range(n)):
+ held(g, bx(i0 + min(k for k in range(n) if a0 + i0 + k in held_at)), yy, 24)
for k, v in enumerate(vals):
xx = bx(i0 + k)
+ if hit and hit[0] <= k <= hit[-1] and v is not None:
+ g.t(xx, b(yy), "%02x" % v, S, BRIGHT, BOLD)
+ continue
if v is None: # not read at this stop: two dots, on the field's paper
g.rect(xx + 5, yy + 11, 4, 4, FAINT)
g.rect(xx + 15, yy + 11, 4, 4, FAINT)
continue
- padded = reads in ("number", "pointer") and nz and (k < nz[0] if f[3] else k > nz[-1])
+ padded = reads in ("number", "pointer", "size", "protected") and nz and (k < nz[0] if f[3] else k > nz[-1])
g.t(xx, b(yy), "%02x" % v, S, mix(ink, PAGE, 0.45) if padded else ink, MONO)
+ if known and f and len(f) > 5 and reads in ("bytes", "loose"): # a field the scene names, left to the eye
+ g.t(x, b(yy) - 1, f[5], 18, FAINT, "sans")
+ x += tw(f[5], 18, "sans") + A
if not known or reads in ("bytes", "loose"):
continue
+ if reads == "size": # a chunk's size word: the size, and its three low bits as flags
+ s_ = "0x%x" % (word & ~7)
+ g.t(x, b(yy), s_, S, VELLUM, MONO)
+ x += (len(s_) + 1) * A
+ for bit, letter in ((2, "A"), (1, "M"), (0, "P")):
+ if word >> bit & 1: # set: on a chip, as rip's flags; clear: lower case, dim
+ g.rect(x - 4, yy + 2, 20, 20, RAISED)
+ g.t(x, b(yy), letter, S, BRIGHT, BOLD)
+ else:
+ g.t(x, b(yy), letter.lower(), S, DIM, MONO)
+ x += 18
+ x += 6
+ if len(f) > 5:
+ g.t(x, b(yy) - 1, f[5], 18, FAINT, "sans")
+ x += tw(f[5], 18, "sans") + A
+ continue
+ if reads == "protected": # safe-linking: the bytes are the pointer xor its own address >> 12
+ fa = a0 + i0
+ ptr = word ^ (fa >> 12)
+ if ptr and base <= ptr < base + length:
+ found.append((a0, fa, ptr, region_of(ptr) or VELLUM, None))
+ if ptr:
+ x = addr(g, link_arrow(g, x, yy), yy, ptr, region_of(ptr) or VELLUM) + A
+ else:
+ g.t(x, b(yy), "NULL", S, DIM, MONO)
+ x += 5 * A
+ s_ = "^ %x" % (fa >> 12)
+ g.t(x, b(yy), s_, S, FAINT, MONO)
+ x += (len(s_) + 1) * A
+ continue
if reads == "malloc": # the allocator's own: the size word of the chunk after it
note = "malloc's: a chunk of %d" % (word & ~7) if word < 0x10000 else "malloc's: the top chunk"
g.t(x, b(yy) - 1, note, 18, FAINT, "sans")
@@ -610,6 +785,9 @@ def fields(g, y, h, about, base, length, flist, mem, region, region_of, marks=()
s_ = s_[:max(int((X + CW - 12 - x) // A) - 1, 0)] + "…"
g.t(x, b(yy), s_, S, sink, MONO)
x += (len(s_) + 1) * A
+ if f and len(f) > 5: # what the scene says the number is
+ g.t(x, b(yy) - 1, f[5], 18, FAINT, "sans")
+ x += tw(f[5], 18, "sans") + A
yy += ROW
if more_rows and shown and shown[-1] < total - 1: # the rows after the last field: one row, and how many
more(g, X + 34 - 6, yy)
@@ -621,37 +799,22 @@ def fields(g, y, h, about, base, length, flist, mem, region, region_of, marks=()
return ys
-def kernel(g, y, h, calls, name, nr, rows, given):
- """`syscalls` in the band: the kernel's side, on vellum. calls: (name, result), newest first (the first is
- the call in hand, gold: where execution is); rows: (register, argument, value, note); given: the bytes it took."""
- tag(g, LX, y, CW, h, "kernel", note="the other side of a system call")
- g.rect(LX + 2, y + TAG, CW - 4, h - TAG - 2, gen.KERNEL)
- g.t(LX + 12, y + TAG + 20, "calls so far", 18, gen.KERNEL_DIM, "sans")
- for i, (c, ret) in enumerate(calls[:(h - TAG - 40) // 28]):
- yy = y + TAG + 28 + i * 28
- if i == 0:
- g.rect(LX + 12, yy, 196, 24, GOLD)
- g.frame(LX + 12, yy, 196, 24, PAGE, 2)
- g.t(LX + 20, b(yy), c, S, PAGE, MONO)
- g.t(LX + 200, b(yy), str(ret), S, PAGE, MONO, "end")
- x = LX + 236
- g.t(x, y + TAG + 46, name, 35, PAGE, "monob")
- g.t(x + len(name) * 21 + 16, y + TAG + 44, "system call %d" % nr, 18, gen.KERNEL_DIM, "sans")
- for i, (reg, arg, val, note) in enumerate(rows):
- yy = y + TAG + 60 + i * 28
- g.rect(x, yy, 300, 2, gen.KERNEL_RULE)
- g.t(x, b(yy + 2), reg, S, gen.KERNEL_DIM, MONO)
- g.t(x + 52, b(yy + 2), arg, 20, PAGE, "sansm")
- g.t(x + 130, b(yy + 2), val, S, PAGE, MONO)
- if note:
- g.t(x + 130 + (len(val) + 1) * A, b(yy + 2), note, S, PAGE, MONO)
- x = LX + 564
- g.t(x, y + TAG + 20, "the bytes it was given", 18, gen.KERNEL_DIM, "sans")
- for i, v in enumerate(given):
- xx, yy = x + (i % 10) * 28, y + TAG + 28 + (i // 10) * 30
- g.rect(xx, yy, 26, 26, gen.KERNEL_HELD)
- g.frame(xx, yy, 26, 26, PAGE, 2)
- g.t(xx + 1, b(yy + 1), "%02x" % v, S, PAGE, MONO)
+def calls_log(g, y, h, calls):
+ """`syscalls`'s drawing: the calls so far, as strace writes them, oldest on top, the newest last; the kernel's
+ own side is under the `syscall` row while a call is made (`descent`), not here. calls: runs [(s, ink)] a row,
+ oldest first; the newest's result carries the turned corner."""
+ rows = (h - TAG - 2 * PAD) // ROW
+ note = "oldest on top · newest at the bottom" + (" · %d more above" % (len(calls) - rows) if len(calls) > rows else "")
+ y0 = panel(g, LX, y, CW, rows, "system calls", focus=True, note=note)
+ shown = calls[-rows:]
+ for i, runs in enumerate(shown):
+ yy, x = y0 + i * ROW, LX + 12
+ for s_, ink in runs:
+ if ink == "held":
+ held(g, x, yy, len(s_) * A)
+ ink = VELLUM
+ g.t(x, b(yy), s_, S, ink, BOLD if x == LX + 12 else MONO)
+ x += len(s_) * A
def dump_row(g, y, a, runs, lead, mark=None, node=False):
@@ -987,15 +1150,17 @@ def calls(g, y, h, tree, made, caller, project_from=None):
return cx, cy
-def backtrace(g, y, h, frames, x=RX, note="the calls waiting · newest on top", focus=False):
- """The call chain as rows, newest on top: the view of the calls, or a lens's drawing (x = LX). frames: (name,
- args, file, line), file None where the recording does not know it. More frames than rows: the oldest go, counted."""
+def backtrace(g, y, h, frames, x=RX, note="the calls waiting · newest at the bottom", focus=False):
+ """The call chain as rows, newest at the bottom (a call goes down): the view of the calls, or a lens's drawing
+ (x = LX). frames: (name, args, file, line), newest first, as numbered; file None where the recording does not
+ know it. More frames than rows: the oldest go from the top, counted."""
rows = (h - TAG - 2 * PAD) // ROW
if len(frames) > rows:
- note += " · %d more" % (len(frames) - rows)
+ note += " · %d more above" % (len(frames) - rows)
y0 = panel(g, x, y, CW, rows, "backtrace", focus=focus, note=note)
- for i, (name, args, file, line) in enumerate(frames[:rows]):
- yy = y0 + i * ROW
+ shown = frames[:rows]
+ for i, (name, args, file, line) in enumerate(shown):
+ yy = y0 + (len(shown) - 1 - i) * ROW + (rows - len(shown)) * ROW
if i == 0:
g.t(x + 12, b(yy), "#0", S, current_row(g, x + 2, yy, CW - 4, 40), BOLD)
else:
@@ -1146,7 +1311,9 @@ SQ_DIS_120 = [(a, 80895, mn, [(ops, P)], "cur" if a == 0x448d84 else None, None)
(0x448d80, "push", "rbp"), (0x448d81, "mov", "rbp, rsp"), (0x448d84, "push", "r15"), (0x448d86, "push", "r14"),
(0x448d88, "push", "r13"), (0x448d8a, "push", "r12"), (0x448d8c, "push", "rbx"), (0x448d8d, "sub", "rsp, 0xa8"),
(0x448d94, "mov", "r14d, ecx")]]
-SQ_DIS_169 = [(a, 42290, mn, ops, "cur" if a == 0x422051 else None, None) for a, mn, ops in [
+SQ_DIS_169 = [(a, 42290, mn, ops, "cur" if a == 0x422051 else "trail0" if a == 0x42204b else None,
+ ("runs", [("", "arrow"), ("__pwrite64", VELLUM), (" = 4096", DIM)]) if a == 0x42204b else None)
+ for a, mn, ops in [
(0x422042, "mov", [("rsi, r15", P)]), (0x422045, "mov", [("rdx, r12", P)]), (0x422048, "mov", [("rcx, r14", P)]),
(0x42204b, "call", [("qword ptr [rip + 0xf1567]", P)]), (0x422051, "mov", [("r13, rax", P)]),
(0x422054, "test", [("r13d, r13d", P)]), (0x422057, "jns", [(0x422070, C_)]), (0x422059, "call", [(0x4021c0, C_)]),
@@ -1196,7 +1363,7 @@ def frame_sqlite(name, late):
registers(g, yr, SQ_REGS_120, SQ_FLAGS_120, changed)
stack(g, yr + ph(17) + 12, SQ_STACK_120, [("sqlite3BtreeInsert", 0, 1), ("sqlite3VdbeExec", 2, 9)],
rsp=0x7fffffffe980, roles={0: ("saved rbp", DIM)})
- backtrace(g, TOP, sp["band"], SQ_BT_120, x=LX, note="newest on top", focus=True)
+ backtrace(g, TOP, sp["band"], SQ_BT_120, x=LX, note="newest at the bottom", focus=True)
base = 0x7fffffffea60
fields(g, TOP, sp["view"], "pX, the row: a BtreePayload, at rsi", base, 48, PAYLOAD,
{base + i: v for i, v in enumerate(ROW_BYTES)}, STACK, sq_region, marks=(0, 1))
@@ -1213,11 +1380,12 @@ def frame_sqlite(name, late):
roles={4: ("saved rbp", DIM)})
page = bytes(4096 - len(PAGE_END) - len(PAGE0)) # the middle of the page is not drawn: `more`
page = PAGE0 + page + PAGE_END
- kernel(g, TOP, sp["band"], [("pwrite64", 4096), ("pwrite64", 4096), ("fsync", 0), ("pwrite64", 12),
- ("close", 0), ("fsync", 0), ("openat", 5), ("fsync", 0)],
- "pwrite64", 18, [("rdi", "fd", "3", '"t.db"'), ("rsi", "buf", "538b28", None),
- ("rdx", "count", "4096", None), ("r10", "offset", "4096", None),
- ("rax", "returns", "4096", None)], PAGE0 + bytes(4))
+ F = FAINT
+ older = [("fsync", 0), ("openat", 5), ("fsync", 0), ("close", 0), ("pwrite64", 12), ("fsync", 0), ("pwrite64", 4096)]
+ log = [[(c, VELLUM), ("(…) = ", F), (str(r), VELLUM)] for c, r in older] # their arguments: not in this mock's data
+ log.append([("pwrite64", VELLUM), ("(fd ", F), ("3", VELLUM), (' "t.db"', F), (", buf ", F), ("538b28", HEAP),
+ (", count ", F), ("4096", VELLUM), (", offset ", F), ("4096", VELLUM), (") = ", F), ("4096", "held")])
+ calls_log(g, TOP, sp["band"], log)
base = 0x538b28
took = {base + i: v for i, v in enumerate(PAGE0)}
took.update({base + 0xfe0 + i: v for i, v in enumerate(PAGE_END)})
@@ -1230,6 +1398,160 @@ def frame_sqlite(name, late):
g.save(name)
+# ---- the call followed down: the syscalls scene's `open`, from main through the PLT and libc into the kernel ----
+# `ztrace dbg` on anim/tools/hello.c (cc -O0 -no-pie -Wl,-z,now; env -i setarch -R): moments 1 (at the call),
+# 2 (in the stub), 4 (at libc's `syscall`), 5 (after it) and 6 (back in main).
+HELLO = open(__file__.replace("design/mock/context.py", "anim/tools/hello.c")).read().split("\n")
+R_ = VELLUM # read-only data: the string, and the GOT once relro has sealed it
+HM = [(0x40117a, 4, "sub", "rsp, 0x40"), (0x40117e, 4, "mov", "rax, qword ptr fs:[0x28]"),
+ (0x401187, 4, "mov", "qword ptr [rbp - 8], rax"), (0x40118b, 4, "xor", "eax, eax"),
+ (0x40118d, 6, "lea", "rax, [rip + 0xe70]"), (0x401194, 6, "mov", "esi, 0"), (0x401199, 6, "mov", "rdi, rax"),
+ (0x40119c, 6, "mov", "eax, 0"), (0x4011a1, 6, "call", (0x401070, "open@plt")),
+ (0x4011a6, 6, "mov", "dword ptr [rbp - 0x38], eax"), (0x4011a9, 7, "lea", "rcx, [rbp - 0x30]"),
+ (0x4011ad, 7, "mov", "eax, dword ptr [rbp - 0x38]"), (0x4011b0, 7, "mov", "edx, 0x20"),
+ (0x4011b5, 7, "mov", "rsi, rcx"), (0x4011b8, 7, "mov", "edi, eax"), (0x4011ba, 7, "call", (0x401060, "read@plt")),
+ (0x4011bf, 7, "mov", "dword ptr [rbp - 0x34], eax")]
+OPEN_ARGS = [("set", "rdi", [(0x402004, R_)], ("str", "note")), ("runs", [("rsi ", DIM), ("O_RDONLY", VELLUM)])]
+STATIC = {0x40117e: ("runs", [("the stack's canary", DIM)]), # what a row says before it runs, and after
+ 0x40118d: ("runs", [("= ", FAINT), (0x402004, R_), (' "note"', LIT)]),
+ 0x4011ba: ("text", "read", VELLUM)}
+
+
+def main_rows(first, n, states, notes):
+ out = []
+ for a, line, mn, ops in HM:
+ if a < first or len(out) == n:
+ continue
+ parts = [(ops, CODE)] if isinstance(ops, tuple) else [(ops, P)]
+ out.append((a, line, mn, parts, states.get(a), notes.get(a, STATIC.get(a))))
+ return out
+
+
+LIBC_OPEN = [(0x7ffff7d10fb6, "xor", "r8d, r8d"), (0x7ffff7d10fb9, "mov", "rdi, 0xffffffffffffff9c"),
+ (0x7ffff7d10fc0, "mov", "eax, 0x101"), (0x7ffff7d10fc5, "syscall", ""), (0x7ffff7d10fc7, "mov", "rdx, rax"),
+ (0x7ffff7d10fca, "cmp", "rax, -0x1000"), (0x7ffff7d10fd0, "ja", 0x7ffff7d10fe8),
+ (0x7ffff7d10fd2, "mov", "eax, edx")]
+
+
+def frame_descent(name):
+ """Mock 16: four instants of one call followed down, each the program column of the working frame (`beside`):
+ the source over the disassembly, as a descent of windows by call depth."""
+ gen.W, gen.H = 3840, 1000
+ g = Svg()
+ syscall_args = [("set", "rdi", [], ("int", -100)), ("set", "rsi", [(0x402004, R_)], ("str", "note")),
+ ("runs", [("rdx ", DIM), ("O_RDONLY", VELLUM)]), ("runs", [("r10 ", DIM), ("0", VELLUM)])]
+ call_c = ("runs", [("open", BRIGHT), ('("note", O_RDONLY)', VELLUM)])
+ instants = [
+ ("1", "at the call", "moment 1", None, "main",
+ [("main", None, main_rows(0, 17, {0x401194: "trail2", 0x401199: "trail1", 0x40119c: "trail0", 0x4011a1: "cur"},
+ {0x401194: ("set", "rsi", [], ("int", 0)),
+ 0x401199: ("set", "rdi", [(0x402004, R_)], ("str", "note")),
+ 0x40119c: ("set", "rax", [], ("int", 0)),
+ 0x4011a1: ("runs", [("open", BRIGHT), (" in libc, by the PLT", FAINT)]),
+ 0x4011a6: OPEN_ARGS[0], 0x4011a9: OPEN_ARGS[1]}))],
+ ["main calls open by its stub in the PLT. The arguments",
+ 'are in rdi and rsi: "note" and O_RDONLY.']),
+ ("2", "in the stub", "moment 2", "main waits at line 6 · the pc is in the PLT", "open@plt · the PLT",
+ [("main", None, main_rows(0x401187, 13, {0x401199: "trail2", 0x40119c: "trail1", 0x4011a1: "wait"},
+ {0x4011a1: call_c})),
+ ("open@plt", "the PLT · its jmp reads open@got, 403fd8",
+ [(0x401070, None, "jmp", [("qword ptr [rip + 0x2f62]", P)], "cur",
+ ("runs", [("", "arrow"), (0x7ffff7d10ec0, CODE), (" open", VELLUM)])),
+ (0x401076, None, "push", [("4", P)], None, ("text", "lazy binding: unused", FAINT)),
+ (0x40107b, None, "jmp", [(0x401020, CODE)], None, None)])],
+ ["The call pushed main+48 and went down: main's window keeps",
+ "its call, ringed; the stub's opens under it, and its jmp reads the GOT."]),
+ ("3", "the crossing", "moments 4 and 5", "main waits at line 6 · the pc is in libc's open",
+ "open · libc.so.6",
+ [("main", None, main_rows(0x40119c, 3, {0x40119c: "trail2", 0x4011a1: "wait"}, {0x4011a1: call_c})),
+ ("open@plt", "the PLT, jumped through", [(0x401070, None, "jmp", [("qword ptr [rip + 0x2f62]", P)], "pass",
+ ("runs", [("", "arrow"), (0x7ffff7d10ec0, CODE), (" open", VELLUM)]))]),
+ ("open", "libc.so.6 · no source",
+ [(a, None, mn, [(ops, CODE)] if isinstance(ops, int) else ([(ops, P)] if ops else []),
+ {0x7ffff7d10fb6: "trail2", 0x7ffff7d10fb9: "trail1", 0x7ffff7d10fc0: "trail0", 0x7ffff7d10fc5: "cur"}.get(a),
+ {0x7ffff7d10fb6: ("set", "r8", [], ("int", 0)),
+ 0x7ffff7d10fb9: ("runs", [("rdi ", DIM), ("-100", VELLUM), (" AT_FDCWD", FAINT)]),
+ 0x7ffff7d10fc0: ("runs", [("rax ", DIM), ("0x101", VELLUM), (" 257", FAINT)]),
+ 0x7ffff7d10fc5: ("runs", [("openat", BRIGHT), (" nr 257", FAINT)]),
+ 0x7ffff7d10fc7: syscall_args[0], 0x7ffff7d10fca: syscall_args[1],
+ 0x7ffff7d10fd0: syscall_args[2], 0x7ffff7d10fd2: syscall_args[3]}.get(a))
+ for a, mn, ops in LIBC_OPEN]),
+ ("kernel", "openat, system call 257",
+ [[("openat(AT_FDCWD, \"note\", O_RDONLY, 0)", PAGE)],
+ [("returns ", gen.KERNEL_DIM), ("3", "struck"), (' "note"', PAGE), (" rcx, r11: clobbered", gen.KERNEL_DIM)]])],
+ ["libc's open is a wrapper: it puts openat's number in rax",
+ "and its arguments in rdi, rsi, rdx, r10; syscall crosses down."]),
+ ("4", "back up", "moment 6", None, "main",
+ [("main", None, main_rows(0, 17, {0x401199: "trail2", 0x40119c: "trail1", 0x4011a1: "trail0", 0x4011a6: "cur"},
+ {0x4011a1: ("runs", [("open", VELLUM), ('("note", O_RDONLY) = ', DIM), ("3", VELLUM)]),
+ 0x4011a6: ("chain", [(0x7fffffffecc8, S_)], ("int", 0), None)}))],
+ ["open's ret came straight back to main+48: the stub was a jump,",
+ "not a call. The windows close up, and eax holds 3, the descriptor."]),
+ ]
+ for k, (num, title, when, waiting, note, windows, cap) in enumerate(instants):
+ dx = k * 928
+ g.o.append(f'<g transform="translate({dx},0)">')
+ g.t(LX, 40, num, 28, GOLD, "sansb")
+ g.t(LX + 28, 40, title, 28, VELLUM, "sansm")
+ g.t(LX + CW, 40, when, 20, FAINT, "sans", "end")
+ ys = source(g, 64, 8, HELLO, 3, 6, [] if waiting else [], "hello.c", 11, waiting=waiting)
+ at = descent(g, 300, windows, note=note)
+ run = [a for a in (0x40118d, 0x401194, 0x401199, 0x40119c, 0x4011a1, 0x4011a6) if a in at]
+ thread(g, ys, [(at[run[0]], at[run[-1]] + ROW)], *((VELLUM, 2) if waiting else (GOLD, 3)))
+ for i, line in enumerate(cap):
+ g.t(LX, 800 + i * 40, line, 28, VELLUM, "sans")
+ g.o.append("</g>")
+ g.save(name)
+
+
+def frame_operands(name):
+ """Mock 17: real rows, as the disassembler writes them and as canim draws them: no size words, and a
+ `width` where no register of the instruction says the size; then the row's detail on rows of the strip."""
+ gen.W, gen.H = 1920, 640
+ g = Svg()
+ L = 0x7ffff7c00000 # libc's base in the recording
+ rows = [(0x100191b, "nop", "dword ptr [rax + rax]", "list"), (0x1001926, "mov", "rdi, qword ptr [rdi + 8]", "list"),
+ (0x100192a, "mov", "qword ptr [rax + 8], rcx", "list"), (0x40117e, "mov", "rax, qword ptr fs:[0x28]", "hello"),
+ (0x4011a6, "mov", "dword ptr [rbp - 0x38], eax", "hello"),
+ (0x401070, "jmp", "qword ptr [rip + 0x2f62]", "hello"),
+ (L + 0x110f07, "mov", "eax, dword ptr [r11 + 0x308]", "libc"),
+ (L + 0x110f0e, "cmp", "byte ptr [rip + 0x11018b], 0", "libc"),
+ (L + 0x110f94, "mov", "dword ptr [rbp - 0x60], 0x10", "libc"),
+ (L + 0x110f9b, "movsxd", "r10, dword ptr [rbp - 0x30]", "libc"),
+ (L + 0x110f85, "mov", "dword ptr fs:[rax], edx", "libc"),
+ (L + 0x110fe5, "nop", "dword ptr [rax]", "libc")]
+ for k, (title, sizes) in enumerate([("as the disassembler writes them", True), ("as canim draws them", False)]):
+ x0 = 64 + k * 912
+ g.o.append(f'<g transform="translate({x0 - LX},0)">')
+ y0 = panel(g, LX, 48, CW, len(rows), title, focus=not sizes, note="list, hello, libc's open")
+ for i, (a, mn, ops, where) in enumerate(rows):
+ yy = y0 + i * ROW
+ addr(g, LX + DX_ADDR, yy, a, CODE) # libc's twelve digits move the columns after them by 60
+ g.t(LX + DX_MN + 60, b(yy), mn, S, FAINT if mn == "nop" else KW, MONO if mn == "nop" else BOLD)
+ operands(g, LX + DX_OPS + 60, yy, mn, ops, VELLUM, sizes)
+ g.o.append("</g>")
+ detail = [
+ (0x40117e, "mov", "rax, qword ptr fs:[0x28]", ("runs", [("the stack's canary ", DIM), ("191a6a1f012bed00", VELLUM)])),
+ (0x40118d, "lea", "rax, [rip + 0xe70]", ("runs", [("rip + 0xe70 = ", FAINT), (0x402004, R_), (' "note"', LIT)])),
+ (0x401070, "jmp", "qword ptr [rip + 0x2f62]",
+ ("runs", [("", "arrow"), (0x7ffff7d10ec0, CODE), (" open", VELLUM), (" · read from open@got, ", FAINT),
+ (0x403fd8, R_)])),
+ (L + 0x110f0e, "cmp", "byte ptr [rip + 0x11018b], 0",
+ ("runs", [("1", VELLUM), (" : ", FAINT), ("0", VELLUM), (" ", FAINT), ("zf", DIM), (" ", FAINT)])),
+ (L + 0x110f15, "jne", L + 0x110fb0, ("runs", [("taken", VELLUM), (" · reads ", FAINT), ("zf", DIM),
+ (" → 7ffff7d10fb0 open+240", DIM)])),
+ (L + 0x110fca, "cmp", "rax, -0x1000", ("runs", [("3", VELLUM), (" : ", FAINT), ("-4096", VELLUM), (" ", FAINT),
+ ("CF", "chip"), ("zf", DIM)])),
+ (L + 0x110fd0, "ja", L + 0x110fe8, ("runs", [("not taken", DIM), (" · reads ", FAINT), ("CF", "chip"),
+ ("zf", DIM)])),
+ ]
+ y0 = panel(g, LX, 48 + ph(len(rows)) + 36, CW * 2 + 32, len(detail), "the row's detail",
+ note="what a row says: a name for a known place, lea's sum, the slot a jump goes through, a compare's two values and the flags it leaves")
+ insn_rows(g, y0, [(a, None, mn, [(ops, CODE)] if isinstance(ops, int) else [(ops, P)], None, note)
+ for a, mn, ops, note in detail], None, lead=0)
+ g.save(name)
+
+
if __name__ == "__main__":
assert ph(8) + 12 + ph(17) == ph(17) + 12 + ph(8) == BOTTOM - TOP - 152 - 12 # lens beside
assert ph(10) + 12 + ph(9) == BOTTOM - TOP - 296 - 12 # lens as subject: the drawing
@@ -1240,3 +1562,5 @@ if __name__ == "__main__":
frame_calls("12-calls-subject")
frame_sqlite("13-sqlite-row", False)
frame_sqlite("14-sqlite-page", True)
+ frame_descent("16-descent")
+ frame_operands("17-operands")