mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 09:28:37 +00:00
Tested: Ran 79 tests in 22.512s ... OK (test_call_trace_diff.py); Ran 3 tests in 15.268s ... OK (test_text_write_line_endings.py). Not run in game.
732 lines
34 KiB
Python
732 lines
34 KiB
Python
"""Align two import-call traces of the same game executable and report where they first diverge.
|
|
|
|
`gta6rt` and the d3d12 stack `leonida-hle` run the same title executable; each writes a call trace of the title's
|
|
import calls (`LEONIDA_CALL_TRACE`, rules in `tools/call_trace_rules.def`). This tool aligns the two traces thread by
|
|
thread and lists the divergences.
|
|
|
|
Trace format (version 1; `parse_trace` is the only place that knows it): UTF-8, LF, fields separated by TAB.
|
|
|
|
# leonida-call-trace 1 stack=<gta6rt|leonida-hle> rules=<16 hex>
|
|
# title-bound <dll> imports of this DLL go to a title module and are untraced (any position)
|
|
# truncated the size cap was reached and tracing stopped
|
|
# dropped <n> records dropped so far (writer lock not taken in time); repeated, the last one wins
|
|
<seq> <tid> T <start> <created> a thread's first traced call
|
|
<seq> <tid> C <module>!<function> <caller> <bind> call entered
|
|
<seq> <tid> R <call-seq> <ret> the call with that seq returned
|
|
<seq> <tid> E <module>!<function> <caller> <bind> entry-only call, no R follows
|
|
|
|
`module` is compared case-insensitively, `function` (an import name or `#<ordinal>`) case-sensitively; `caller` and
|
|
`start` are `game+0x<hex>`, `<dll>+0x<hex>`, `?` (and `main` for `start`); `bind` is shim, hle, host or unimpl and is
|
|
shown in the report but is not part of a call's identity. The file is memory-mapped, so it may end in NUL bytes and in
|
|
a partial last line: trailing NULs are stripped and a last line without a trailing LF is ignored. Any other malformed
|
|
line is an error with file and line number, and so is a seq that does not exceed the previous one. Blank lines are
|
|
ignored; other `#` lines are comments; a file without the header is accepted with a WARNING. The file is read line by
|
|
line, so its size is not limited by memory, only the calls kept (about 150 bytes each) are.
|
|
|
|
A dropped C is a call missing entirely and a dropped R leaves its C open, so the report warns when a side has
|
|
dropped records.
|
|
|
|
A call is a C record joined with its R record by call-seq (nested calls appear as C C R R), or an E record. A C with no
|
|
R is `open` (it never returned: a crash, a longjmp or a call still running at the end). Return classes: `hr:0x<8 hex>`
|
|
and `u:0x<hex>` (compared exactly), `b:0` / `b:1`, `p:0` / `p:1` / `p:-1` (null / other / all ones), `-` (void or
|
|
unknown) and `open`. Two returns are compared when both are one of the first four kinds; `-` (and an E record) is never
|
|
compared.
|
|
|
|
Divergences are listed in positional order: by the seq of the nearest left call at or before the place in the
|
|
alignment (`anchor`; the left seq is one order shared by all threads), then by thread pairing order, then by place.
|
|
Divergence kinds: `only-left` / `only-right` (a run of calls one side makes in a thread and the other does not),
|
|
`ret` (a matched call with a different comparable return), `open` (a matched call that returned on one side and never
|
|
returned on the other; a matched E record is never an `open`), `count` (per thread and module!function the call counts
|
|
differ) and `thread` (a thread present on one side only). The section "Open calls at end of trace" lists, per thread
|
|
and side, the calls that never returned (the crash site); it is shown even without other divergences and does not by
|
|
itself change the exit code. Exit code 0: no divergence, 1: divergences, 2: usage or parse error.
|
|
|
|
python -I tools/call_trace_diff.py gta6rt.trace leonida-hle.trace --max 20 --out diff.txt
|
|
|
|
Threads: the T record gives `start` and `created`. A thread with start `main` is keyed `main` (`main#n` when a side has
|
|
several). Other threads are grouped by `start` on each side and paired inside a group by the longest common prefix of
|
|
their call identity sequences (greedy, best pair first, ties by creation order); a pair is keyed `<start>#<n>`, n
|
|
counting the group's pairs in the left trace's creation order, then the unpaired threads. A thread left unpaired
|
|
because the other side has fewer threads in the group is reported as a thread on one side only.
|
|
|
|
Modules named by a `# title-bound` line on either side are dropped from both sides before alignment. Differing
|
|
`rules=` hashes print a WARNING: the two traces were not made with the same rules and are not comparable.
|
|
|
|
Alignment: per thread, a call's identity is (module, function, caller offset); a (module, function) that has an
|
|
unknown caller (`?`) on either side in that thread is compared by (module, function) only. The two identity
|
|
sequences are aligned with difflib.SequenceMatcher (autojunk=False) in chunks of `--window` calls: the chunk is
|
|
aligned, everything up to the end of its last matching block is committed and the next chunk starts there. A chunk
|
|
without any match is doubled until it matches, so a long insertion is still bridged. A divergence that is longer
|
|
than the window can in rare cases be reported as a wider only-left/only-right pair than the shortest edit script.
|
|
Standard library only; no game data.
|
|
"""
|
|
import argparse
|
|
import array
|
|
import collections
|
|
import difflib
|
|
import json
|
|
import os
|
|
import re
|
|
import sys
|
|
|
|
ROOT = os.path.dirname(os.path.abspath(__file__))
|
|
if ROOT not in sys.path:
|
|
sys.path.insert(0, ROOT)
|
|
from report_paths import same_report_path # noqa: E402
|
|
|
|
DEFAULT_WINDOW = 2000
|
|
DEFAULT_MAX = 20
|
|
BINDS = ("shim", "hle", "host", "unimpl")
|
|
|
|
_HR = re.compile(r"hr:0x([0-9a-fA-F]{8})\Z")
|
|
_UINT = re.compile(r"u:0x([0-9a-fA-F]+)\Z")
|
|
_BOOL = re.compile(r"b:([01])\Z")
|
|
_PTR = re.compile(r"p:(0|1|-1)\Z")
|
|
_CALLER = re.compile(r"(.+)\+0x([0-9a-fA-F]+)\Z")
|
|
_HEADER = re.compile(r"#\s*leonida-call-trace\s+(\S+)(.*)\Z")
|
|
_STACK = re.compile(r"(?:^|\s)stack=(\S+)")
|
|
_RULES = re.compile(r"(?:^|\s)rules=(\S+)")
|
|
_RULES_VALUE = re.compile(r"[0-9a-fA-F]{16}\Z")
|
|
_TITLE_BOUND = re.compile(r"#\s*title-bound\s+(\S+)\s*\Z")
|
|
_TRUNCATED = re.compile(r"#\s*truncated\s*\Z")
|
|
_DROPPED = re.compile(r"#\s*dropped(?:\s+(.*?))?\s*\Z")
|
|
|
|
|
|
class TraceError(Exception):
|
|
pass
|
|
|
|
|
|
class Call:
|
|
"""One call: a C record joined with its R (or an E record). ret is None (never compared) or (kind, value)."""
|
|
__slots__ = ("seq", "module", "func", "caller_text", "caller", "bind", "entry", "open", "ret_text", "ret")
|
|
|
|
def __init__(self, seq, module, func, caller_text, caller, bind, entry):
|
|
self.seq = seq
|
|
self.module = module
|
|
self.func = func
|
|
self.caller_text = caller_text
|
|
self.caller = caller
|
|
self.bind = bind
|
|
self.entry = entry
|
|
self.open = not entry
|
|
self.ret_text = "-" if entry else "open"
|
|
self.ret = None
|
|
|
|
|
|
class Thread:
|
|
__slots__ = ("tid", "start", "created", "calls", "opens")
|
|
|
|
def __init__(self, tid, start, created):
|
|
self.tid = tid
|
|
self.start = start
|
|
self.created = created
|
|
self.calls = []
|
|
self.opens = {} # seq -> Call entered on this thread and not yet returned (parse time only)
|
|
|
|
|
|
class Trace:
|
|
def __init__(self, path):
|
|
self.path = path
|
|
self.label = None
|
|
self.stack = None
|
|
self.rules = None
|
|
self.has_header = False
|
|
self.truncated = False
|
|
self.dropped = 0 # records the writer dropped (lock not taken in time): the last `# dropped` value
|
|
self.title_bound = set()
|
|
self.threads = []
|
|
self.ncalls = 0
|
|
|
|
|
|
def _decimal(text):
|
|
return text.isascii() and text.isdigit()
|
|
|
|
|
|
_CACHE_LIMIT = 100000
|
|
_BIND = {b: b for b in BINDS}
|
|
|
|
|
|
def parse_trace(path):
|
|
"""Read one trace file into a Trace, line by line. Raises TraceError("<file>:<line>: ...") on a malformed record."""
|
|
name = os.path.basename(path)
|
|
trace = Trace(path)
|
|
current = {} # tid -> its newest Thread (an OS thread id can be reused after a thread exits)
|
|
call_cache, caller_cache, ret_cache = {}, {}, {}
|
|
intern = sys.intern
|
|
last_seq = 0
|
|
lineno = 0
|
|
|
|
def fail(message):
|
|
raise TraceError("%s:%d: %s" % (name, lineno, message))
|
|
|
|
try:
|
|
handle = open(path, "rb")
|
|
except OSError as exc:
|
|
raise TraceError("%s: cannot read: %s" % (name, exc))
|
|
with handle:
|
|
try:
|
|
for lineno, raw in enumerate(handle, 1):
|
|
if not raw.endswith(b"\n"):
|
|
break # a last chunk without its LF: a partial write and/or the NUL padding of the mapped file
|
|
try:
|
|
line = raw[:-1].decode("utf-8")
|
|
except UnicodeDecodeError as exc:
|
|
fail("not valid UTF-8: %s" % exc)
|
|
line = line.rstrip("\r")
|
|
if not line.strip():
|
|
continue
|
|
if line.startswith("#"):
|
|
header = _HEADER.match(line)
|
|
if header:
|
|
if header.group(1) != "1":
|
|
fail("unsupported trace version %r" % header.group(1))
|
|
if not trace.has_header:
|
|
trace.has_header = True
|
|
stack = _STACK.search(header.group(2))
|
|
trace.stack = stack.group(1) if stack else None
|
|
rules = _RULES.search(header.group(2))
|
|
if rules:
|
|
if not _RULES_VALUE.match(rules.group(1)):
|
|
fail("bad rules hash %r (16 hex digits)" % rules.group(1))
|
|
trace.rules = rules.group(1).lower()
|
|
continue
|
|
bound = _TITLE_BOUND.match(line)
|
|
if bound:
|
|
trace.title_bound.add(bound.group(1).lower())
|
|
elif _TRUNCATED.match(line):
|
|
trace.truncated = True
|
|
else:
|
|
lost = _DROPPED.match(line)
|
|
if lost:
|
|
if lost.group(1) is None or not _decimal(lost.group(1)):
|
|
fail("bad dropped count %r (a decimal integer)" % (lost.group(1) or ""))
|
|
trace.dropped = int(lost.group(1))
|
|
continue
|
|
fields = line.split("\t")
|
|
if len(fields) < 3:
|
|
fail("expected <seq> TAB <tid> TAB <T|C|R|E> ..., got %d TAB-separated fields" % len(fields))
|
|
seq_text, tid_text, kind = fields[:3]
|
|
if not _decimal(seq_text):
|
|
fail("seq %r is not a decimal integer" % seq_text)
|
|
if not _decimal(tid_text):
|
|
fail("tid %r is not a decimal integer" % tid_text)
|
|
seq, tid = int(seq_text), int(tid_text)
|
|
if seq <= last_seq:
|
|
fail("seq %d does not exceed the previous seq %d (seq starts at 1 and increases)"
|
|
% (seq, last_seq))
|
|
last_seq = seq
|
|
if kind == "T":
|
|
if len(fields) != 5:
|
|
fail("T record needs 5 TAB-separated fields (seq tid T start created), got %d" % len(fields))
|
|
start = _parse_start(fields[3])
|
|
if start is False:
|
|
fail("bad thread start %r (main, <module>+0x<hex> or ?)" % fields[3])
|
|
if not _decimal(fields[4]):
|
|
fail("created %r is not a decimal integer" % fields[4])
|
|
thread = Thread(tid, intern(start), int(fields[4]))
|
|
current[tid] = thread
|
|
trace.threads.append(thread)
|
|
continue
|
|
if kind not in ("C", "E", "R"):
|
|
fail("unknown record kind %r (T, C, R or E)" % kind)
|
|
thread = current.get(tid)
|
|
if thread is None:
|
|
fail("thread %d has no T record before its first call" % tid)
|
|
if kind == "R":
|
|
if len(fields) != 5:
|
|
fail("R record needs 5 TAB-separated fields (seq tid R call-seq ret), got %d" % len(fields))
|
|
if not _decimal(fields[3]):
|
|
fail("call-seq %r is not a decimal integer" % fields[3])
|
|
call = thread.opens.pop(int(fields[3]), None)
|
|
if call is None:
|
|
fail("call-seq %s is not a C record of thread %d that is still open" % (fields[3], tid))
|
|
ret_text = fields[4]
|
|
ret = ret_cache.get(ret_text, False)
|
|
if ret is False:
|
|
ret = _parse_ret(ret_text)
|
|
if ret is False:
|
|
fail("bad return %r (hr:0x<8 hex>, u:0x<hex>, b:0|1, p:0|1|-1 or -)" % ret_text)
|
|
if len(ret_cache) < _CACHE_LIMIT:
|
|
ret_cache[ret_text] = ret
|
|
call.open = False
|
|
call.ret_text = intern(ret_text)
|
|
call.ret = ret
|
|
continue
|
|
if len(fields) != 6:
|
|
fail("%s record needs 6 TAB-separated fields (seq tid %s module!function caller bind), got %d"
|
|
% (kind, kind, len(fields)))
|
|
named = call_cache.get(fields[3])
|
|
if named is None:
|
|
module, bang, func = fields[3].partition("!")
|
|
if not bang or not module or not func:
|
|
fail("call %r is not <module>!<function>" % fields[3])
|
|
named = (intern(module.lower()), intern(func))
|
|
if len(call_cache) < _CACHE_LIMIT:
|
|
call_cache[fields[3]] = named
|
|
caller = caller_cache.get(fields[4])
|
|
if caller is None:
|
|
parsed = _parse_caller(fields[4])
|
|
if parsed is False:
|
|
fail("bad caller %r (<module>+0x<hex> or ?)" % fields[4])
|
|
caller = (intern(fields[4]), parsed) # one shared text and tuple per distinct caller
|
|
if len(caller_cache) < _CACHE_LIMIT:
|
|
caller_cache[fields[4]] = caller
|
|
bind = _BIND.get(fields[5])
|
|
if bind is None:
|
|
fail("bad bind %r (shim, hle, host or unimpl)" % fields[5])
|
|
call = Call(seq, named[0], named[1], caller[0], caller[1], bind, kind == "E")
|
|
if kind == "C":
|
|
thread.opens[seq] = call
|
|
thread.calls.append(call)
|
|
trace.ncalls += 1
|
|
except OSError as exc:
|
|
raise TraceError("%s: cannot read: %s" % (name, exc))
|
|
for thread in trace.threads:
|
|
thread.opens = None
|
|
trace.label = trace.stack or name
|
|
return trace
|
|
|
|
|
|
def _parse_ret(text):
|
|
if text == "-":
|
|
return None
|
|
match = _HR.match(text)
|
|
if match:
|
|
return ("hr", int(match.group(1), 16))
|
|
match = _UINT.match(text)
|
|
if match:
|
|
return ("u", int(match.group(1), 16))
|
|
match = _BOOL.match(text)
|
|
if match:
|
|
return ("b", int(match.group(1)))
|
|
match = _PTR.match(text)
|
|
if match:
|
|
return ("p", int(match.group(1)))
|
|
return False
|
|
|
|
|
|
def _parse_caller(text):
|
|
if text == "?":
|
|
return None
|
|
match = _CALLER.match(text)
|
|
if match:
|
|
return (match.group(1).lower(), int(match.group(2), 16))
|
|
return False
|
|
|
|
|
|
def _parse_start(text):
|
|
if text == "main" or text == "?":
|
|
return text
|
|
match = _CALLER.match(text)
|
|
if match:
|
|
return "%s+0x%x" % (match.group(1).lower(), int(match.group(2), 16))
|
|
return False
|
|
|
|
|
|
def visible_threads(trace, dropped):
|
|
"""The trace's threads without the calls of `dropped` modules; a thread left with no call is dropped."""
|
|
out = []
|
|
for thread in trace.threads:
|
|
calls = [c for c in thread.calls if c.module not in dropped] if dropped else thread.calls
|
|
if calls:
|
|
kept = Thread(thread.tid, thread.start, thread.created)
|
|
kept.calls = calls
|
|
out.append(kept)
|
|
return out
|
|
|
|
|
|
def _prefix(a, b):
|
|
"""Length of the common prefix of two identity arrays (binary search over slice equality)."""
|
|
n = min(len(a), len(b))
|
|
if n == 0 or a[0] != b[0]:
|
|
return 0
|
|
if a[:n] == b[:n]:
|
|
return n
|
|
lo, hi = 1, n - 1 # a[:1] matches, a[:n] does not
|
|
while lo < hi:
|
|
mid = (lo + hi + 1) // 2
|
|
if a[:mid] == b[:mid]:
|
|
lo = mid
|
|
else:
|
|
hi = mid - 1
|
|
return lo
|
|
|
|
|
|
def _identity_arrays(threads, wild, table):
|
|
"""Per thread an array of small integers, one per call: equal numbers are equal identities."""
|
|
out = []
|
|
for thread in threads:
|
|
ids = array.array("I")
|
|
for c in thread.calls:
|
|
key = (c.module, c.func)
|
|
if key not in wild:
|
|
key += (c.caller,)
|
|
number = table.get(key)
|
|
if number is None:
|
|
number = table[key] = len(table)
|
|
ids.append(number)
|
|
out.append(ids)
|
|
return out
|
|
|
|
|
|
Entry = collections.namedtuple("Entry", "key start n left right")
|
|
|
|
|
|
def pair_threads(left_threads, right_threads):
|
|
"""Pair the two sides' threads: [Entry(key, start, n, left Thread or None, right Thread or None)]."""
|
|
groups = {}
|
|
for side, threads in enumerate((left_threads, right_threads)):
|
|
for thread in sorted(threads, key=lambda t: t.created): # stable: file order for equal created
|
|
groups.setdefault(thread.start, ([], []))[side].append(thread)
|
|
entries = []
|
|
for start in sorted(groups):
|
|
lefts, rights = groups[start]
|
|
if len(lefts) == 1 and len(rights) == 1:
|
|
pairs = [(0, 0)]
|
|
elif not lefts or not rights:
|
|
pairs = []
|
|
else:
|
|
wild = set()
|
|
for thread in lefts + rights:
|
|
for c in thread.calls:
|
|
if c.caller is None:
|
|
wild.add((c.module, c.func))
|
|
table = {}
|
|
ids_left = _identity_arrays(lefts, wild, table)
|
|
ids_right = _identity_arrays(rights, wild, table)
|
|
candidates = sorted((-_prefix(a, b), i, j) for i, a in enumerate(ids_left)
|
|
for j, b in enumerate(ids_right))
|
|
used_left, used_right, pairs = set(), set(), []
|
|
for _, i, j in candidates:
|
|
if i not in used_left and j not in used_right:
|
|
used_left.add(i)
|
|
used_right.add(j)
|
|
pairs.append((i, j))
|
|
pairs.sort()
|
|
used_left = {i for i, _ in pairs}
|
|
used_right = {j for _, j in pairs}
|
|
ordered = [(lefts[i], rights[j]) for i, j in pairs]
|
|
ordered += [(lefts[i], None) for i in range(len(lefts)) if i not in used_left]
|
|
ordered += [(None, rights[j]) for j in range(len(rights)) if j not in used_right]
|
|
for n, (a, b) in enumerate(ordered, 1):
|
|
key = start if start == "main" and len(ordered) == 1 else "%s#%d" % (start, n)
|
|
entries.append(Entry(key, start, n, a, b))
|
|
return entries
|
|
|
|
|
|
def select_entries(entries, selector):
|
|
"""--thread: `main`, a start value (the whole group) or `<start>#<n>` (one thread of the group)."""
|
|
base, hash_, number = selector.rpartition("#")
|
|
if hash_ and _decimal(number):
|
|
number = int(number)
|
|
else:
|
|
base, number = selector, None
|
|
start = _parse_start(base) # the same normalisation as the T records: game+0x01A matches game+0x1a
|
|
if start is False:
|
|
start = base.lower()
|
|
return [e for e in entries if e.start == start and (number is None or e.n == number)]
|
|
|
|
|
|
def align(a, b, window):
|
|
"""Align two lists of hashable identities: [(tag, i1, i2, j1, j2)], tag in equal / left / right."""
|
|
n, m = len(a), len(b)
|
|
ops = []
|
|
i = j = 0
|
|
size = window
|
|
while i < n or j < m:
|
|
k = 0
|
|
while i + k < n and j + k < m and a[i + k] == b[j + k]:
|
|
k += 1
|
|
if k:
|
|
ops.append(("equal", i, i + k, j, j + k))
|
|
i += k
|
|
j += k
|
|
size = window
|
|
continue
|
|
if i == n:
|
|
ops.append(("right", i, i, j, m))
|
|
break
|
|
if j == m:
|
|
ops.append(("left", i, n, j, j))
|
|
break
|
|
ae, be = min(n, i + size), min(m, j + size)
|
|
final = ae == n and be == m
|
|
matcher = difflib.SequenceMatcher(None, a[i:ae], b[j:be], autojunk=False)
|
|
opcodes = matcher.get_opcodes()
|
|
if not final:
|
|
equal = [op for op in opcodes if op[0] == "equal"]
|
|
if not equal:
|
|
size *= 2 # no common call in the chunk: widen it rather than commit a guess
|
|
continue
|
|
last = equal[-1]
|
|
opcodes = opcodes[:opcodes.index(last) + 1]
|
|
for tag, i1, i2, j1, j2 in opcodes:
|
|
ops.append(("equal" if tag == "equal" else "left" if tag == "delete" else "right" if tag == "insert"
|
|
else "replace", i + i1, i + i2, j + j1, j + j2))
|
|
i, j = i + opcodes[-1][2], j + opcodes[-1][4]
|
|
size = window
|
|
if final:
|
|
break
|
|
out = []
|
|
for tag, i1, i2, j1, j2 in ops:
|
|
if tag == "replace":
|
|
out.append(("left", i1, i2, j1, j1))
|
|
out.append(("right", i2, i2, j1, j2))
|
|
else:
|
|
out.append((tag, i1, i2, j1, j2))
|
|
return out
|
|
|
|
|
|
def identities(left, right):
|
|
"""Alignment identities of one thread's two call lists (see the module docstring for the `?` rule)."""
|
|
wild = set()
|
|
for rec in left + right:
|
|
if rec.caller is None:
|
|
wild.add((rec.module, rec.func))
|
|
|
|
def ident(rec):
|
|
key = (rec.module, rec.func)
|
|
return key if key in wild else key + (rec.caller,)
|
|
|
|
return [ident(r) for r in left], [ident(r) for r in right]
|
|
|
|
|
|
def call_name(rec):
|
|
return "%s!%s" % (rec.module, rec.func)
|
|
|
|
|
|
def _caller_text(first, second=None):
|
|
if first.caller is not None or second is None:
|
|
return first.caller_text
|
|
return second.caller_text
|
|
|
|
|
|
def compare_thread(key, left, right, window, ignore_ret):
|
|
"""Divergences of one thread: only-left / only-right runs, ret differences and calls open on one side.
|
|
|
|
Each carries `anchor` (the seq of the nearest left call at or before its place in the alignment, 0 before the
|
|
first; the left counter is the one order shared by all threads) and `_pos`, its ordinal in the alignment."""
|
|
found = []
|
|
ids_left, ids_right = identities(left, right)
|
|
for tag, i1, i2, j1, j2 in align(ids_left, ids_right, window):
|
|
if tag == "equal":
|
|
for k, (x, y) in enumerate(zip(left[i1:i2], right[j1:j2])):
|
|
kind = None
|
|
if x.open != y.open:
|
|
if (y if x.open else x).entry:
|
|
continue # an E record never returns: nothing to compare with
|
|
kind = "open"
|
|
elif (x.ret is None or y.ret is None or x.ret == y.ret or call_name(x) in ignore_ret):
|
|
continue
|
|
else:
|
|
kind = "ret"
|
|
found.append({"thread": key, "kind": kind, "left_seq": x.seq, "right_seq": y.seq,
|
|
"call": call_name(x), "caller": _caller_text(x, y), "calls": 1,
|
|
"left": x.ret_text, "right": y.ret_text,
|
|
"left_bind": x.bind, "right_bind": y.bind,
|
|
"anchor": x.seq, "_pos": i1 + j1 + 2 * k})
|
|
elif tag == "left" and i2 > i1:
|
|
first, last = left[i1], left[i2 - 1]
|
|
found.append({"thread": key, "kind": "only-left", "left_seq": first.seq, "right_seq": None,
|
|
"call": call_name(first), "caller": first.caller_text, "calls": i2 - i1,
|
|
"last_seq": last.seq, "left": first.ret_text, "right": None,
|
|
"left_bind": first.bind, "right_bind": None,
|
|
"anchor": first.seq, "_pos": i1 + j1})
|
|
elif tag == "right" and j2 > j1:
|
|
first, last = right[j1], right[j2 - 1]
|
|
found.append({"thread": key, "kind": "only-right", "left_seq": None, "right_seq": first.seq,
|
|
"call": call_name(first), "caller": first.caller_text, "calls": j2 - j1,
|
|
"last_seq": last.seq, "left": None, "right": first.ret_text,
|
|
"left_bind": None, "right_bind": first.bind,
|
|
"anchor": left[i1 - 1].seq if i1 > 0 else 0, "_pos": i1 + j1})
|
|
return found
|
|
|
|
|
|
def diff_threads(left_threads, right_threads, window=DEFAULT_WINDOW, ignore_ret=(), only_thread=None):
|
|
"""Everything the report shows, unlimited: divergences, count differences, thread-only keys, open calls."""
|
|
entries = pair_threads(left_threads, right_threads)
|
|
if only_thread is not None:
|
|
entries = select_entries(entries, only_thread)
|
|
if not entries:
|
|
raise TraceError("thread %r is in neither trace" % only_thread)
|
|
ignore = set(ignore_ret)
|
|
divergences, counts, thread_only, opens = [], [], [], []
|
|
for order, entry in enumerate(entries):
|
|
left = entry.left.calls if entry.left else None
|
|
right = entry.right.calls if entry.right else None
|
|
for side, calls in (("left", left), ("right", right)):
|
|
for call in calls or ():
|
|
if call.open:
|
|
opens.append({"side": side, "thread": entry.key, "seq": call.seq, "call": call_name(call),
|
|
"caller": call.caller_text, "bind": call.bind})
|
|
if left is None or right is None:
|
|
side = "left" if right is None else "right"
|
|
thread_only.append({"thread": entry.key, "side": side, "calls": len(left or right)})
|
|
continue
|
|
for d in compare_thread(entry.key, left, right, window, ignore):
|
|
d["_order"] = order
|
|
divergences.append(d)
|
|
count_left = collections.Counter((r.module, r.func) for r in left)
|
|
count_right = collections.Counter((r.module, r.func) for r in right)
|
|
for module, func in sorted(set(count_left) | set(count_right)):
|
|
lc, rc = count_left[(module, func)], count_right[(module, func)]
|
|
if lc != rc:
|
|
counts.append({"thread": entry.key, "call": "%s!%s" % (module, func), "left": lc, "right": rc,
|
|
"delta": rc - lc})
|
|
# positional: by the left call each divergence sits at or after, then thread pairing order, then place
|
|
divergences.sort(key=lambda d: (d["anchor"], d["_order"], d["_pos"]))
|
|
for d in divergences:
|
|
del d["_order"], d["_pos"]
|
|
counts.sort(key=lambda c: (-abs(c["delta"]), c["thread"], c["call"]))
|
|
opens.sort(key=lambda o: (o["thread"], o["side"], o["seq"]))
|
|
return divergences, counts, thread_only, opens
|
|
|
|
|
|
def _seq(value):
|
|
return "-" if value is None else str(value)
|
|
|
|
|
|
def divergence_line(d):
|
|
parts = ["thread=%s" % d["thread"], "kind=%s" % d["kind"], "left_seq=%s" % _seq(d["left_seq"]),
|
|
"right_seq=%s" % _seq(d["right_seq"]), "call=%s" % d["call"], "caller=%s" % d["caller"]]
|
|
if d["kind"] in ("ret", "open"):
|
|
parts += ["left=%s" % d["left"], "right=%s" % d["right"],
|
|
"left_bind=%s" % d["left_bind"], "right_bind=%s" % d["right_bind"]]
|
|
else:
|
|
parts.append("bind=%s" % (d["left_bind"] or d["right_bind"]))
|
|
if d["calls"] > 1:
|
|
parts += ["calls=%d" % d["calls"], "last_seq=%d" % d["last_seq"]]
|
|
return " ".join(parts)
|
|
|
|
|
|
def rules_differ(info):
|
|
return info["left"]["rules"] != info["right"]["rules"]
|
|
|
|
|
|
def format_report(info, divergences, counts, thread_only, opens, limit):
|
|
out = []
|
|
for side in ("left", "right"):
|
|
i = info[side]
|
|
out.append("%s: %s (%s) records=%d threads=%d rules=%s truncated=%s unimpl=%d dropped=%d" % (
|
|
side, i["label"], i["path"], i["records"], i["threads"], i["rules"] or "-",
|
|
"yes" if i["truncated"] else "no", i["unimpl"], i["dropped"]))
|
|
|
|
for side in ("left", "right"):
|
|
if info[side]["dropped"]:
|
|
out.append("WARNING: %s: the writer dropped %d records (lock not taken in time): calls missing from "
|
|
"this side and its open calls may be drops, not behaviour" % (side, info[side]["dropped"]))
|
|
for side in ("left", "right"):
|
|
if not info[side]["header"]:
|
|
out.append("WARNING: %s: no leonida-call-trace header" % os.path.basename(info[side]["path"]))
|
|
if rules_differ(info):
|
|
out.append("WARNING: rules differ (left=%s right=%s): the traces were not made with the same rules"
|
|
% (info["left"]["rules"] or "-", info["right"]["rules"] or "-"))
|
|
if info["title_bound"]:
|
|
out.append("title-bound modules dropped from both sides: %s (calls dropped: left=%d right=%d)" % (
|
|
", ".join(info["title_bound"]), info["left"]["title_bound_calls"], info["right"]["title_bound_calls"]))
|
|
if info["thread"] is not None:
|
|
out.append("limited to thread %s" % info["thread"])
|
|
out.append("divergences: %d (showing %d)" % (len(divergences), min(limit, len(divergences))))
|
|
out.extend(divergence_line(d) for d in divergences[:limit])
|
|
out.append("count differences: %d (showing %d)" % (len(counts), min(limit, len(counts))))
|
|
for c in counts[:limit]:
|
|
out.append("thread=%s call=%s left=%d right=%d delta=%+d" % (c["thread"], c["call"], c["left"], c["right"],
|
|
c["delta"]))
|
|
out.append("threads on one side only: %d" % len(thread_only))
|
|
for t in thread_only:
|
|
out.append("thread=%s only-%s calls=%d" % (t["thread"], t["side"], t["calls"]))
|
|
out.append("Open calls at end of trace: %d" % len(opens))
|
|
for o in opens:
|
|
out.append("side=%s thread=%s seq=%d call=%s caller=%s bind=%s" % (
|
|
o["side"], o["thread"], o["seq"], o["call"], o["caller"], o["bind"]))
|
|
return "\n".join(out) + "\n"
|
|
|
|
|
|
def build_parser():
|
|
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
ap.add_argument("left", help="call trace of the first stack (e.g. gta6rt)")
|
|
ap.add_argument("right", help="call trace of the second stack (e.g. leonida-hle)")
|
|
ap.add_argument("--max", type=int, default=DEFAULT_MAX, metavar="N",
|
|
help="divergences and count differences to list (default %d); open calls are always all listed"
|
|
% DEFAULT_MAX)
|
|
ap.add_argument("--window", type=int, default=DEFAULT_WINDOW, metavar="N",
|
|
help="calls aligned per chunk (default %d)" % DEFAULT_WINDOW)
|
|
ap.add_argument("--ignore-ret", action="append", default=[], metavar="MODULE!FUNC",
|
|
help="do not compare the return of this function (repeatable)")
|
|
ap.add_argument("--thread", metavar="main|START[#N]",
|
|
help="limit the comparison to the main thread (`main`), to the threads with this start "
|
|
"(e.g. game+0x1a2b3c) or to one thread of that group (`START#N`: N counts the group's pairs "
|
|
"in the left trace's creation order, from 1, as the report's thread keys show)")
|
|
ap.add_argument("--json", action="store_true", help="emit JSON instead of text")
|
|
ap.add_argument("--out", metavar="PATH", help="write the report here instead of stdout")
|
|
return ap
|
|
|
|
|
|
def _side_info(trace, path, threads, dropped):
|
|
calls = [c for t in threads for c in t.calls]
|
|
return {"label": trace.label, "path": path, "records": len(calls), "threads": len(threads),
|
|
"rules": trace.rules, "truncated": trace.truncated, "stack": trace.stack,
|
|
"header": trace.has_header,
|
|
"unimpl": sum(1 for c in calls if c.bind == "unimpl"),
|
|
"dropped": trace.dropped,
|
|
"title_bound_calls": trace.ncalls - len(calls) if dropped else 0}
|
|
|
|
|
|
def main(argv=None):
|
|
ap = build_parser()
|
|
args = ap.parse_args(argv)
|
|
if args.max < 0:
|
|
ap.error("--max must not be negative")
|
|
if args.window < 1:
|
|
ap.error("--window must be at least 1")
|
|
ignore = []
|
|
for item in args.ignore_ret:
|
|
module, bang, func = item.partition("!")
|
|
if not bang or not module or not func:
|
|
ap.error("--ignore-ret %r is not MODULE!FUNC" % item)
|
|
ignore.append("%s!%s" % (module.lower(), func))
|
|
if args.out:
|
|
for name, path in (("left", args.left), ("right", args.right)):
|
|
if same_report_path(path, args.out):
|
|
ap.error("--out must not overwrite the %s input" % name)
|
|
try:
|
|
left = parse_trace(args.left)
|
|
right = parse_trace(args.right)
|
|
dropped = left.title_bound | right.title_bound
|
|
left_threads = visible_threads(left, dropped)
|
|
right_threads = visible_threads(right, dropped)
|
|
divergences, counts, thread_only, opens = diff_threads(left_threads, right_threads, args.window, ignore,
|
|
args.thread)
|
|
except TraceError as exc:
|
|
sys.stderr.write("error: %s\n" % exc)
|
|
return 2
|
|
info = {"left": _side_info(left, args.left, left_threads, dropped),
|
|
"right": _side_info(right, args.right, right_threads, dropped),
|
|
"title_bound": sorted(dropped), "thread": args.thread}
|
|
if args.json:
|
|
text = json.dumps({
|
|
"left": info["left"], "right": info["right"], "thread": args.thread, "max": args.max,
|
|
"title_bound": info["title_bound"], "rules_differ": rules_differ(info),
|
|
"divergences": {"total": len(divergences), "shown": divergences[:args.max]},
|
|
"counts": {"total": len(counts), "shown": counts[:args.max]},
|
|
"threads_only": thread_only,
|
|
"open_calls": {"total": len(opens), "shown": opens},
|
|
"diverged": bool(divergences or counts or thread_only),
|
|
}, sort_keys=True, indent=2) + "\n"
|
|
else:
|
|
text = format_report(info, divergences, counts, thread_only, opens, args.max)
|
|
if args.out:
|
|
try:
|
|
with open(args.out, "w", encoding="utf-8", newline="\n") as handle:
|
|
handle.write(text)
|
|
except OSError as exc:
|
|
sys.stderr.write("error: cannot write %s: %s\n" % (args.out, exc))
|
|
return 2
|
|
else:
|
|
sys.stdout.write(text)
|
|
return 1 if (divergences or counts or thread_only) else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|