Algorithm Search⌘K

Algorithmcore

Recursive traversal disassembly

Also called recursive descent disassembly.

Decodes instructions by following the control flow from entry points, which skips data but misses code reached only by indirect jumps.

Time
O(n + e) worst · averageO(e) best
Space
O(n + e) extra
Where
e = the number of entry points; n = the number of bytes of the code
Properties
not complete coveragedeterministicofflineiterativesound
Origin
Benjamin Schwarz, Saumya Debray, Gregory Andrews, 2002

Recursive traversal disassembly decodes only the bytes that control can reach. It starts at the entry points of a program, decodes the instruction there, and follows its successors: the next instruction, the target of a jump, both sides of a conditional branch, and the target of a call. Bytes that no path reaches are never decoded, so data placed between functions or after an unconditional jump is not mistaken for code, which is the weakness of linear sweep. The price is that code reached only through an indirect jump, such as a jump table or a function pointer, is missed unless another analysis finds the targets. The method is a graph search on a graph that is built while it is searched, and its output is the raw material of the control flow graph and the call graph. This page uses a small toy instruction set defined below, not the encoding of a real processor.

In plain words

Think of a book of instructions where each page says what to do and which page to read next. Some pages say "go to page 40", some say "if this is true go to page 12, else read on". Some pages are not instructions at all, but tables or notes.

Linear sweep reads every page from the first to the last, including the tables. Recursive traversal starts at page 1 and goes only where the pages send it. It keeps a list of pages still to visit, and it never reads a page twice. A table that no page points to is never read, so it is never mistaken for an instruction.

The problem is a page that says "go to the page whose number is in box 3". The method cannot tell where that leads, so the pages reached only that way stay unread.

The problem

The input is a byte string code with an end address ee and a list of entry points, such as the program entry and the exported functions. The output is the set of instructions that the program can execute, each at its address. As for linear sweep, this aim cannot be met exactly in general, because whether a byte is executed is a semantic property of the program, undecidable by Rice's theorem. Recursive traversal computes a safe part of the answer: the instructions reachable by direct control flow.

The toy instruction set. It is the same as on the linear sweep page. There are 4 registers, and targets are absolute byte addresses.

opcode size instruction successors
00 1 NOP the next instruction
01 3 MOV r, imm the next instruction
02 3 ADD r, s the next instruction
10 2 JMP t t
11 3 JZ r, t the next instruction and t
12 2 CALL t t, and the next instruction when the call returns
13 1 RET none known from the bytes
14 2 JMPI r unknown (an indirect jump to the address in r)
FF 1 HALT none

Any other opcode byte, or a register byte of 4 or more, is not a valid instruction.

The algorithm

  1. RECURSIVE-TRAVERSAL(code, E) ▷ E is the list of entry points
  2. 1W ← a stack that holds E; found ← empty map; bad ← empty set
  3. 2while W is not empty do
  4. 3p ← pop(W)
  5. 4if p is in found or in bad then continue
  6. 5ins ← DECODE(code, p); if ins is not valid then add p to bad; continue
  7. 6found[p] ← ins
  8. 7if ins is an indirect jump then record p as unresolved
  9. 8for each q in SUCC(ins) do push q onto W
  10. 9return the instructions of found in address order, bad, the unresolved jumps, and the pairs of found instructions that overlap

Line L4 makes each address be decoded at most once, which is what makes the method stop on loops. Line L5 handles a path that leads to a byte where no instruction starts, or past the end of the code: such an address is recorded as bad, which usually means a wrong assumption or obfuscated code. Line L8 is where the method differs from linear sweep. After an unconditional jump, a return or a halt there is no fall-through successor, so the bytes that follow are not decoded unless another path reaches them. For a CALL, line L8 assumes that the called function returns and pushes the next address as well. Line L7 records an indirect jump: the bytes do not say where it goes, so the walk stops there, and a later analysis can add the targets it finds as new entry points.

The stack gives a depth-first order. A queue gives the same set of instructions in a different order, because the result is the set of reachable addresses, whatever the order of the search.

Example

The same 18 bytes as on the linear sweep page, with the entry point 0:

address  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17
byte    01 00 05 10 07 01 02 02 00 01 12 0E FF 2A 01 01 03 13
step pop decoded pushed stack after (top on the right)
1 0 MOV r0, 5 3 [3]
2 3 JMP 7 7 [7]
3 7 ADD r0, r1 10 [10]
4 10 CALL 14 12, then 14 [12, 14]
5 14 MOV r1, 3 17 [12, 17]
6 17 RET nothing [12]
7 12 HALT nothing []

The result is the 7 real instructions. The bytes at 5, 6 and 13 are never decoded, so they stay as unknown bytes, which is right: they are data. Linear sweep on the same bytes decoded the data byte 01 at 5 as a MOV, lost the real ADD at 7, and was out of step for two more items.

Now change the CALL 14 at 10 into JMPI r1 followed by a NOP, with r1 = 14 at run time. Step 4 then decodes an indirect jump, records it as unresolved, and pushes only the NOP. The function at 14 is never decoded, although the program runs it. This is the typical failure of the method.

Correctness

Define the successor graph DD: a valid address has an edge to each successor of its instruction, and an address where no instruction starts has no edges. Let RR be the set of addresses reachable from the entries in DD. The loop keeps three invariants: everything found or bad is in RR; everything on the stack is in RR; and every successor of a found instruction is on the stack or already handled. When the stack is empty, the handled set contains the entries and is closed under the edges, so it is exactly RR. So the method decodes exactly the valid addresses of RR, each once, and stops, because each address is handled once and pushes at most two others. If every direct target and every fall-through leads to a real instruction, then every address in RR is a real instruction start, so no data is ever decoded. The full proof is in the proofs folder.

Proof: Recursive traversal decodes exactly the instructions reachable by direct control flowfull

We use the toy instruction set of the page. Fix the byte string code, its end ee and a list of entry addresses EE. Call an address pp valid if DECODE(p)(p) returns an instruction, and write ins(p)\mathrm{ins}(p) for it.

The successor graph. Let DD be the directed graph whose vertices are the integers that appear as entries or as successors. A valid address pp has an edge to each address in SUCC(ins(p))(\mathrm{ins}(p)): the next address for NOP, MOV and ADD; the target for JMP; both the next address and the target for JZ and CALL; none for RET, HALT and JMPI. An address that is not valid has no outgoing edge. Let RR be the set of vertices reachable from EE in DD, including EE itself.

Theorem 1. RECURSIVE-TRAVERSAL stops. When it stops, the set of decoded instructions is {ins(p):p∈R, p valid}\{\mathrm{ins}(p) : p \in R,\ p \text{ valid}\}, each decoded once, the list of bad addresses is the set of addresses of RR that are not valid, and the list of unresolved addresses is the set of p∈Rp \in R with ins(p)\mathrm{ins}(p) a JMPI.

Proof. Write FF for the keys of the map of found instructions and BB for the set of bad addresses. We use three invariants of the loop of line L2.

  1. F∪B⊆RF \cup B \subseteq R, every p∈Fp \in F is valid with found[p]=ins(p)\mathrm{found}[p] = \mathrm{ins}(p), and every p∈Bp \in B is not valid.
  2. Every address on the stack WW is in RR.
  3. For each p∈Fp \in F, every successor of ins(p)\mathrm{ins}(p) is on WW or in F∪BF \cup B.

Line L1 puts EE on the stack, with F=B=∅F = B = \emptyset, so all three hold. Consider one iteration, which pops pp at line L3; by (2), p∈Rp \in R. If p∈F∪Bp \in F \cup B, line L4 skips it and nothing else changes; (3) still holds because pp was already handled. Otherwise line L5 decodes pp. If pp is not valid, it goes to BB, which keeps (1). If it is valid, line L6 puts it in FF with its instruction, and line L8 pushes all its successors. They are in RR, because p∈Rp \in R and they are its successors in DD, so (2) holds, and (3) now holds for pp as well.

Termination: each iteration either moves an address from outside F∪BF \cup B into it, or pops a stack entry without pushing. An address enters F∪BF \cup B at most once, because line L4 skips it later. Each address put into FF pushes at most 2 entries. So the total number of pushes is at most ∣E∣+2∣F∣|E| + 2|F|, which is finite because F⊆RF \subseteq R and RR is finite (every vertex of DD is an entry or the successor of a byte address of code, and code is finite). So the loop runs a finite number of times.

When the loop stops, WW is empty. By (3), F∪BF \cup B is closed under the edges of DD: each successor of an address of FF is in F∪BF \cup B, and the addresses of BB have no successors. It contains EE, because each entry was pushed and later popped, and a popped address that is not skipped enters F∪BF \cup B. A set that contains EE and is closed under the edges contains every vertex reachable from EE, so R⊆F∪BR \subseteq F \cup B. With (1), F∪B=RF \cup B = R, FF is the valid part of RR and BB is the rest. Line L7 records each JMPI of FF once, when it enters FF. ■\blacksquare

Corollary 2 (no data is decoded when the jumps are right). Suppose the bytes are a program made of real instructions with data placed between them, every direct jump and call target is the start of a real instruction, every real instruction that can fall through is followed by a real instruction, and the entries are real instruction starts. Then every decoded instruction is a real instruction, and no data byte is ever decoded as the start of an instruction.

Proof. By induction along the paths of DD from EE: an entry is a real instruction start; and from a real instruction start, each successor is the next real instruction (by the assumption on fall-through) or a real target (by the assumption on targets). So RR contains only real instruction starts, and Theorem 1 says that the decoded set is the valid part of RR. □\square

What the theorem does not say. The set RR is defined by the bytes, and it is an under-approximation of the code that runs. It misses an instruction that is reached only through an indirect jump (the JMPI of the toy set, a jump table or a function pointer in real code), or only from an entry that the caller did not give. It is wrong when a CALL never returns, because then the edge to the next address is not real and the bytes after the call can be data. Both cases are outside the assumptions of Corollary 2. As with every static disassembler, no method that sees only the bytes can find exactly the executed instructions in general, because that is a semantic property of the program (see Rice's theorem).

Overlaps. Line L9 reports the pairs of decoded instructions whose byte ranges intersect. Under the assumptions of Corollary 2 this list is empty, because real instructions do not share bytes. A non-empty list therefore shows that one of the assumptions fails: a jump into the middle of an instruction, which an obfuscator can do on purpose, or a wrong edge.

Complexity

Each address is decoded at most once (line L4), and each decoded instruction pushes at most 2 addresses (line L8). So the number of stack operations is at most e+2ne + 2n for nn bytes and ee entries, and each costs O(1)O(1) with a hash map or an array indexed by address. The time is O(n+e)O(n + e) in the worst case. When the entries lead to only a few instructions, the time is O(e)O(e) plus the size of that part, which is the best case. The map and the stack take O(n+e)O(n + e) space. Line L9 sorts the found addresses, which takes O(n)O(n) with an array indexed by address, and finds overlaps by looking at each instruction and the few that start inside it. The model is the word RAM.

Properties

  • Sound under its assumptions. If direct targets and fall-through edges are right, every decoded instruction is real, and data is never decoded.
  • Incomplete. Code reached only through indirect jumps, from an unknown entry, or through a return address computed at run time is missed.
  • Order-independent. The set of decoded instructions does not depend on the order of the entries or on stack versus queue.
  • Detects overlaps. Two decoded instructions that share bytes show a jump into the middle of an instruction. Compiled code does not do this, so an overlap is a strong sign of hand-written or obfuscated code.
  • Builds the graph. The edges followed in line L8 are the edges of the control flow graph and, for CALL, of the call graph. Cutting the found instructions at the targets of jumps and after branches gives the basic blocks.

Variants and improvements

  • Jump table recovery. Look at the code before an indirect jump for the pattern of a bounds check and a load from a table, read the table, and add its entries as targets. Schwarz, Debray and Andrews describe such a step. With it, most indirect jumps of compiled switch statements are resolved.
  • Value analysis. Use abstract interpretation over the registers to find the possible values at an indirect jump, add them as targets, and repeat until nothing changes. This finds more targets than a pattern, at a higher cost.
  • Function start detection. Find likely function starts in the bytes that are not yet decoded, for example common prologues or the targets of call instructions in data, and use them as new entries. Andriesse and coauthors (2016) found this to be one of the harder parts of disassembly of compiled code.
  • The hybrid with linear sweep. Sweep the gaps between the found instructions, and accept the result where it is consistent with the found code.
  • Disassembly of obfuscated code. Kruegel, Robertson, Valeur and Vigna (2004) built a control-flow-based method that keeps several candidate instructions and resolves conflicts between them, to handle junk bytes and branches that are never taken.
  • Non-returning functions. Find the functions that never return, such as an exit routine, and do not push the fall-through after a call to them.

When to use it

Use recursive traversal when data is mixed with code, or when you need the control flow graph anyway, which is the usual case in reverse engineering and binary analysis. Combine it with jump table recovery, because without it a large part of any program with switch statements is lost. Use linear sweep when the code section is known to hold only code and you need every byte covered. For the code that a static method cannot reach, dynamic analysis observes the addresses that actually run, at the price of seeing only the paths of the test inputs.

Pitfalls

  • Decoding an address twice. Without line L4, a loop in the program makes the walk run forever. Skip every address that is found or bad, as line L4 does.
  • Following the fall-through of an unconditional jump. If SUCC of JMP, RET or HALT includes the next address, the method decodes the bytes after them, which is the mistake of linear sweep. Give these instructions no fall-through successor in line L8.
  • Assuming that every call returns. Line L8 pushes the address after a CALL. After a call to a function that never returns, these bytes can be data or padding. Mark the non-returning functions and do not push the fall-through for them.
  • Ignoring the unresolved list. An empty result after an indirect jump is not a proof that there is no more code. Report the unresolved jumps of line L7, and feed the targets that another analysis finds back as entries.
  • Recursion in place of a stack. A recursive implementation that calls itself for each successor reaches the depth limit on a long straight run of code. Use an explicit stack, as line L1 does.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

recursive_traversal_disassembly.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/recursive-traversal-disassembly/. The authors are listed in prov/ZRGWE6.jsonl.

"""Recursive traversal disassembly of a toy instruction set that the page defines.

The toy ISA has variable-length instructions, 4 registers and absolute 8-bit
targets. It is not the encoding of any real processor. The input is a byte
string that the caller builds; the code never reads a file or real memory.

    opcode  length  form            successors
    0x00    1       NOP             next
    0x01    3       MOV r, imm      next             r < 4
    0x02    3       ADD r, s        next             r < 4 and s < 4
    0x10    2       JMP t           t
    0x11    3       JZ r, t         next and t       r < 4
    0x12    2       CALL t          t and next
    0x13    1       RET             none
    0x14    2       JMPI r          unknown          r < 4, an indirect jump
    0xFF    1       HALT            none
"""

from typing import NamedTuple, Optional

LENGTH = {0x00: 1, 0x01: 3, 0x02: 3, 0x10: 2, 0x11: 3, 0x12: 2, 0x13: 1, 0x14: 2, 0xFF: 1}
NAME = {0x00: "NOP", 0x01: "MOV", 0x02: "ADD", 0x10: "JMP", 0x11: "JZ", 0x12: "CALL", 0x13: "RET", 0x14: "JMPI", 0xFF: "HALT"}
REGISTER_OPERANDS = {0x01: (1,), 0x02: (1, 2), 0x11: (1,), 0x14: (1,)}


class Insn(NamedTuple):
    addr: int
    size: int
    op: str
    operands: tuple[int, ...]


class Result(NamedTuple):
    insns: list[Insn]  # in address order
    bad: list[int]  # reached addresses where no valid instruction starts
    unresolved: list[int]  # addresses of indirect jumps, whose targets are unknown
    overlaps: list[tuple[int, int]]  # pairs of decoded instructions that share bytes


def decode(code: bytes, p: int, end: int) -> Optional[Insn]:
    """The instruction that starts at p and ends by end, or None. Cost: O(1)."""
    if not 0 <= p < end <= len(code):
        return None
    opcode = code[p]
    size = LENGTH.get(opcode)
    if size is None or p + size > end:
        return None
    operands = tuple(code[p + 1 : p + size])
    if any(operands[i - 1] >= 4 for i in REGISTER_OPERANDS.get(opcode, ())):
        return None
    return Insn(p, size, NAME[opcode], operands)


def successors(ins: Insn) -> list[int]:
    """The addresses that control can reach next, as far as the bytes tell."""
    nxt = ins.addr + ins.size
    if ins.op in ("NOP", "MOV", "ADD"):
        return [nxt]
    if ins.op == "JMP":
        return [ins.operands[0]]
    if ins.op == "JZ":
        return [nxt, ins.operands[1]]
    if ins.op == "CALL":
        return [ins.operands[0], nxt]  # assumes that the called function returns
    return []  # RET, HALT, and JMPI whose target is not known


def recursive_traversal(code: bytes, entries: list[int], end: Optional[int] = None) -> Result:
    """Decode the instructions reachable from the entry points by direct control flow.

    Precondition: the entries are addresses in code. Postcondition: insns is
    the set of valid instructions reachable from the entries along the
    successor edges, each decoded once. Cost: O(n) time and space for a code
    of n bytes, since each address is decoded at most once and each
    instruction has at most two successors.
    """
    if end is None:
        end = len(code)
    work = list(reversed(entries))  # @line L1
    found: dict[int, Insn] = {}
    bad: set[int] = set()
    unresolved: list[int] = []
    while work:  # @line L2
        p = work.pop()  # @line L3
        if p in found or p in bad:  # @line L4
            continue
        ins = decode(code, p, end)  # @line L5
        if ins is None:
            bad.add(p)
            continue
        found[p] = ins  # @line L6
        if ins.op == "JMPI":  # @line L7
            unresolved.append(p)
        for q in reversed(successors(ins)):  # @line L8
            work.append(q)
    insns = [found[a] for a in sorted(found)]  # @line L9
    overlaps = []
    for i, a in enumerate(insns):
        for b in insns[i + 1 :]:
            if b.addr >= a.addr + a.size:
                break
            overlaps.append((a.addr, b.addr))
    return Result(insns, sorted(bad), sorted(unresolved), overlaps)
test_recursive_traversal_disassembly.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/recursive-traversal-disassembly/. The authors are listed in prov/ZRGWE6.jsonl.

import random

from recursive_traversal_disassembly import decode, recursive_traversal, successors

SIZE = {"NOP": 1, "MOV": 3, "ADD": 3, "JMP": 2, "JZ": 3, "CALL": 2, "RET": 1, "JMPI": 2, "HALT": 1}
OPCODE = {"NOP": 0x00, "MOV": 0x01, "ADD": 0x02, "JMP": 0x10, "JZ": 0x11, "CALL": 0x12, "RET": 0x13, "JMPI": 0x14, "HALT": 0xFF}
ENDS_FLOW = {"JMP", "RET", "HALT", "JMPI"}

PAGE_EXAMPLE = bytes(
    [0x01, 0x00, 0x05, 0x10, 0x07, 0x01, 0x02, 0x02, 0x00, 0x01, 0x12, 0x0E, 0xFF, 0x2A, 0x01, 0x01, 0x03, 0x13]
)


def random_program(rng: random.Random, count: int, indirect: bool) -> tuple[bytes, list[tuple[int, str, int]]]:
    """A program with known instructions (address, op, target) and random data after flow-ending instructions."""
    ops = [rng.choice(["NOP", "MOV", "ADD", "JMP", "JZ", "CALL", "RET"] + (["JMPI"] if indirect else [])) for _ in range(count - 1)]
    ops.append("HALT")
    gaps = [rng.randrange(0, 4) if op in ENDS_FLOW else 0 for op in ops]
    addrs, p = [], 0
    for op, gap in zip(ops, gaps):
        addrs.append(p)
        p += SIZE[op] + gap
    truth, code = [], bytearray()
    for op, gap, a in zip(ops, gaps, addrs):
        target = rng.choice(addrs)
        r = rng.randrange(4)
        enc = {
            "NOP": [0x00],
            "MOV": [0x01, r, rng.randrange(256)],
            "ADD": [0x02, r, rng.randrange(4)],
            "JMP": [0x10, target],
            "JZ": [0x11, r, target],
            "CALL": [0x12, target],
            "RET": [0x13],
            "JMPI": [0x14, r],
            "HALT": [0xFF],
        }[op]
        code += bytes(enc)
        code += bytes(rng.randrange(256) for _ in range(gap))
        truth.append((a, op, target))
    return bytes(code), truth


def reachable_in_truth(truth: list[tuple[int, str, int]], entry: int) -> set[int]:
    """Breadth-first search over the known instructions, without decoding any byte."""
    index = {a: i for i, (a, _, _) in enumerate(truth)}
    seen, queue = {entry}, [entry]
    while queue:
        a = queue.pop(0)
        i = index[a]
        _, op, target = truth[i]
        nxt = truth[i + 1][0] if i + 1 < len(truth) else None
        succ = {"JMP": [target], "JZ": [nxt, target], "CALL": [target, nxt]}.get(op, [] if op in ENDS_FLOW else [nxt])
        for b in succ:
            if b is not None and b not in seen:
                seen.add(b)
                queue.append(b)
    return seen


def fixpoint(code: bytes, entries: list[int]) -> set[int]:
    """The reachable set as the least fixed point, by repeated rounds until nothing changes."""
    reach = set(entries)
    while True:
        new = set(reach)
        for p in reach:
            ins = decode(code, p, len(code))
            if ins is not None:
                new.update(successors(ins))
        if new == reach:
            return {p for p in reach if decode(code, p, len(code)) is not None}
        reach = new


def test_page_example() -> None:
    res = recursive_traversal(PAGE_EXAMPLE, [0])
    assert [(i.addr, i.op, i.operands) for i in res.insns] == [
        (0, "MOV", (0, 5)),
        (3, "JMP", (7,)),
        (7, "ADD", (0, 1)),
        (10, "CALL", (14,)),
        (12, "HALT", ()),
        (14, "MOV", (1, 3)),
        (17, "RET", ()),
    ]
    assert res.bad == [] and res.unresolved == [] and res.overlaps == []
    decoded = {a for i in res.insns for a in range(i.addr, i.addr + i.size)}
    assert sorted(set(range(18)) - decoded) == [5, 6, 13]


def test_finds_exactly_the_reachable_instructions() -> None:
    rng = random.Random(30)
    for trial in range(500):
        code, truth = random_program(rng, rng.randrange(1, 25), indirect=trial % 2 == 1)
        res = recursive_traversal(code, [0])
        want = reachable_in_truth(truth, 0)
        assert {i.addr for i in res.insns} == want
        ops = {a: op for a, op, _ in truth}
        assert all(ops[i.addr] == i.op for i in res.insns)
        assert res.bad == [] and res.overlaps == []
        assert res.unresolved == sorted(a for a in want if ops[a] == "JMPI")


def test_random_bytes_match_the_fixpoint() -> None:
    rng = random.Random(31)
    for _ in range(500):
        code = bytes(rng.choice([0x00, 0x01, 0x02, 0x10, 0x11, 0x12, 0x13, 0xFF, rng.randrange(256)]) if rng.random() < 0.6 else rng.randrange(16) for _ in range(rng.randrange(1, 30)))
        entries = [rng.randrange(len(code)) for _ in range(rng.randrange(1, 3))]
        res = recursive_traversal(code, entries)
        assert {i.addr for i in res.insns} == fixpoint(code, entries)
        found = {i.addr for i in res.insns}
        for i in res.insns:
            for q in successors(i):
                assert q in found or q in res.bad


def test_overlapping_instructions_are_reported() -> None:
    # MOV r0, 0x13 at 0; JZ r0, 2 at 3; HALT at 6. The byte 0x13 at 2 is also a RET.
    code = bytes([0x01, 0x00, 0x13, 0x11, 0x00, 0x02, 0xFF])
    res = recursive_traversal(code, [0])
    assert [(i.addr, i.op) for i in res.insns] == [(0, "MOV"), (2, "RET"), (3, "JZ"), (6, "HALT")]
    assert res.overlaps == [(0, 2)]


def test_bad_targets_and_indirect_jumps() -> None:
    # JZ r1, 9 at 0 jumps past the end; JMPI r2 at 3 stops the walk.
    code = bytes([0x11, 0x01, 0x09, 0x14, 0x02, 0xFF])
    res = recursive_traversal(code, [0])
    assert [i.addr for i in res.insns] == [0, 3]
    assert res.bad == [9] and res.unresolved == [3]
    # The HALT at 5 is missed: only the indirect jump reaches it.
    assert recursive_traversal(code, [0, 5]).insns[-1].op == "HALT"

History

Following the control flow is the natural method for a disassembler that wants to separate code from data, and it was used in interactive disassemblers and in tools for binary translation. Schwarz, Debray and Andrews (WCRE 2002) described it together with linear sweep, measured both, improved the handling of jump tables, and combined the two methods. Kruegel, Robertson, Valeur and Vigna (USENIX Security 2004) adapted control-flow-based disassembly to binaries that were obfuscated against it. Andriesse and coauthors (USENIX Security 2016) measured the main disassemblers on a large set of compiled x86 and x64 binaries and showed that, for code from standard compilers, the main errors come from function starts and indirect control flow rather than from the decoding of instructions.

References

  1. Benjamin Schwarz, Saumya Debray and Gregory Andrews, Disassembly of executable code revisited, Working Conference on Reverse Engineering (WCRE) 2002, pages 45 to 54, the description of recursive traversal, its problem with indirect jumps, the handling of jump tables, and the hybrid with linear sweep
  2. Christopher Kruegel, William Robertson, Fredrik Valeur and Giovanni Vigna, Static disassembly of obfuscated binaries, USENIX Security Symposium 2004, disassembly of code with junk bytes and misleading branches by a control flow analysis with conflict resolution
  3. Dennis Andriesse, Xi Chen, Victor van der Veen, Asia Slowinska and Herbert Bos, An in-depth analysis of disassembly on full-scale x86/x64 binaries, USENIX Security Symposium 2016, pages 583 to 600, the measurement of instruction recovery, function starts, call graph and control flow graph accuracy of common disassemblers

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example