Algorithmcore
Linear sweep disassembly
Also called linear disassembly.
Decodes instructions one after the other from the start of a code section. It covers every byte, but data mixed with the code is decoded as instructions and can push it out of step.
- Time
- O(n) worst · average · best
- Space
- O(1) extra
- Where
- n = the number of bytes in the section
- Model
- Word RAM
- Properties
- complete coveragedeterministiconlineiterativenot sound
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Benjamin Schwarz, Saumya Debray, Gregory Andrews, 2002
Linear sweep disassembly turns the bytes of a code section into a list of instructions by decoding them one after the other, from the first byte to the last. Each instruction starts where the one before it ends. It is the simplest disassembler, it takes linear time, and it covers every byte of the section. Its weakness is data inside the code: a jump table, a constant, or padding between functions is decoded as if it were instructions, and on an instruction set with variable-length instructions a wrong instruction can also take the first bytes of the real instruction after it. The other classic method, recursive traversal, follows the jumps instead and has the opposite strengths and weaknesses. This page uses a small toy instruction set defined below, not the encoding of a real processor.
In plain words
Imagine a sentence written with no spaces, in a language whose words have different lengths, where you can always tell the length of a word from its first letter. Read the first letter, take that many letters as the first word, and go on from there. If the text is all words, you read it correctly.
Now suppose someone put a few random letters in the middle. You read them as the start of a word, and that word takes some letters of the next real word. For a short time you are out of step. Usually you get back in step after a word or two, because the false word happens to end where a real word starts.
Linear sweep reads machine code in this way. It never skips a byte, and it never knows which bytes were not code.
The problem
The input is a byte string code and a range , the code section. The output is a list of items that covers each byte of the range once: instructions, each with its address, size and operands, and data bytes where no valid instruction starts. The aim is that the instruction items are the instructions the processor would execute, at the right addresses. In general this aim cannot be met by any method, because whether a byte is ever executed is a semantic property of the program, and such properties are undecidable by Rice's theorem. Disassemblers use rules that work on the code that compilers produce.
The toy instruction set of this page. There are 4 registers, and jump targets are absolute byte addresses.
| opcode | size | instruction | notes |
|---|---|---|---|
| 00 | 1 | NOP | |
| 01 | 3 | MOV r, imm | r < 4, imm any byte |
| 02 | 3 | ADD r, s | r < 4, s < 4 |
| 10 | 2 | JMP t | unconditional jump to t |
| 11 | 3 | JZ r, t | jump to t if r = 0, else fall through |
| 12 | 2 | CALL t | call t, continue after the call |
| 13 | 1 | RET | return |
| 14 | 2 | JMPI r | jump to the address in r (indirect) |
| FF | 1 | HALT | stop |
Any other opcode byte, or a register byte of 4 or more, is not a valid instruction. The size of an instruction follows from its first byte, so no valid encoding is a prefix of another. Real instruction sets with variable length, such as x86, have the same structure with many more forms.
The algorithm
DECODE reads the opcode at , looks up the size, and checks that the instruction ends by and that its register bytes are valid. It returns the instruction, or "not valid".
LINEAR-SWEEP(code, s, e)- 1
p ← s; out ← empty list - 2
while p < e do - 3
ins ← DECODE(code, p) - 4
if ins is not valid then append DATA(p) to out; p ← p + 1 - 5
else append ins to out; p ← p + size(ins) - 6
return out
Line L4 is the choice of what to do with a byte where no instruction starts. This version marks one byte as data and tries again at the next byte. Some disassemblers stop, some print a "bad" marker, and some skip to the next aligned address. Line L5 is the step that makes the method linear: the next instruction is assumed to start right after this one, whatever this one was.
Example
The section has 18 bytes. The real program is MOV r0, 5 at 0; JMP 7 at 3; two data bytes 01 02 at 5; ADD r0, r1 at 7; CALL 14 at 10; HALT at 12; one data byte 2A at 13; and a function MOV r1, 3; RET at 14.
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 | p | bytes read | linear sweep says | the truth |
|---|---|---|---|---|
| 1 | 0 | 01 00 05 | MOV r0, 5 | MOV r0, 5 |
| 2 | 3 | 10 07 | JMP 7 | JMP 7 |
| 3 | 5 | 01 02 02 | MOV r2, 2 | data 01 02, then the first byte of ADD |
| 4 | 8 | 00 | NOP | the middle of ADD r0, r1 |
| 5 | 9 | 01 | data (01 12 0E has register byte 12) | the last byte of ADD |
| 6 | 10 | 12 0E | CALL 14 | CALL 14, in step again |
| 7 | 12 | FF | HALT | HALT |
| 8 | 13 | 2A | data (2A is no opcode) | data |
| 9 | 14 | 01 01 03 | MOV r1, 3 | MOV r1, 3 |
| 10 | 17 | 13 | RET | RET |
Step 3 is the failure: the data byte 01 is the opcode of MOV, so the sweep reads a MOV of 3 bytes and takes byte 7, the first byte of the real ADD. The ADD is lost, and two false items follow. At step 6 the sweep is in step again. The byte 2A at step 8 is not an opcode, so it is correctly reported as data. A recursive traversal of the same bytes from address 0 finds exactly the 7 real instructions, because it follows JMP 7 and never decodes the bytes at 5 and 6.
Correctness
The encodings of the toy instruction set are prefix-free, so DECODE has one answer at each position. The loop invariant of line L2 is that the items so far cover in order, each byte once; each iteration moves forward by at least one byte. So the sweep stops after at most iterations and covers each byte of the section exactly once. If the section is a concatenation of instructions with no data, an induction on the instructions shows that each iteration starts at a true instruction start, so the output is exactly the real instruction list. With data inside the section, the output can be wrong, and nothing that looks only at the bytes can always be right. The full proof is in the proofs folder.
Proof: Linear sweep covers each byte once and decodes a section of pure code exactlyfull
We use the toy instruction set of the page. An encoding is a byte string that DECODE accepts as one whole instruction: an opcode byte from the table, followed by exactly as many operand bytes as the table gives for that opcode, with each register operand below 4. Fix a byte string code and a range with .
Lemma 1 (the encodings are prefix-free). No encoding is a proper prefix of another. So at each position at most one encoding starts and fits in , and DECODE returns it if it exists, and "not valid" otherwise.
Proof. The first byte of an encoding is its opcode, and the table gives one length for each opcode. Two encodings with the same first byte have the same length, so neither is a proper prefix of the other. Two encodings with different first bytes differ at position 0. DECODE reads the opcode, looks up the length, checks that the instruction fits before and that each register byte is below 4. These are exactly the conditions of an encoding, so DECODE returns the encoding at if one exists.
Theorem 2 (coverage and termination). LINEAR-SWEEP stops after at most iterations, and its output is a list of items with addresses and sizes such that and . So each byte of belongs to exactly one item.
Proof. The invariant of the loop of line L2 is: the items so far cover in order, each byte once, and . Line L1 makes it true with and no items. An iteration of line L4 adds a data item of size 1 at and sets . An iteration of line L5 adds an instruction at of size and sets , and DECODE accepts it only if . In both cases the invariant holds again, and grows by at least 1. So the loop runs at most times, and when it stops, and the items cover .
Theorem 3 (pure code is decoded exactly). If code is the concatenation of encodings, then LINEAR-SWEEP returns exactly the instructions at their true addresses , , ..., and no data items.
Proof. Let be the true address of . We show by induction on that the -th iteration starts with . For , line L1 sets . If the -th iteration starts at , the encoding starts at and ends at , so by Lemma 1 DECODE returns , line L5 records it, and becomes . After iterations and the loop stops.
What the theorems do not say. If data bytes lie inside the range, Theorem 2 still holds, but the items can be wrong in two ways. A data byte that is a valid opcode is decoded as an instruction, and that instruction can take the first bytes of the real instruction after it. Then the sweep is out of step with the real instruction starts until a position where its item ends exactly at a real instruction start. Lemma 1 shows that from that position on, the output agrees with the real instructions again, until the next data byte. No test that sees only the bytes can tell code from data in general, because whether a byte is ever executed is a semantic property of the program, and by Rice's theorem such properties are undecidable.
Complexity
Each iteration does work, a table lookup and a few byte checks, and consumes at least one byte, so the time is for a section of bytes, in every case. The loop needs extra space besides the output list, which has at most items. The model is the word RAM. The sweep reads the bytes in order, so it can also run on a stream, one instruction at a time.
Properties
- Complete coverage. Every byte of the section is in exactly one item, so no code is ever missed by being skipped. This is the main advantage over recursive traversal.
- No soundness. Data bytes become instructions when they happen to form valid encodings. The output says nothing about which items are code.
- Self-synchronizing in practice. After a wrong item, the sweep is in step again as soon as an item ends at a real instruction start. On the toy set this is fast: in the test file, after 1 to 5 random data bytes placed among random instructions, the sweep missed at most one real instruction (in 7 of 300 trials) before it was in step again. This is a measurement on random data, not a bound. On x86, short runs out of step are also common, and an obfuscator can make them long on purpose.
- Simple and deterministic. The output depends only on the bytes and the start address.
Variants and improvements
- Skip known data. Use the symbol table, relocation entries or debug information to mark the ranges that are data, and sweep only the rest. Schwarz, Debray and Andrews used such information to improve the sweep.
- The hybrid. Run linear sweep and recursive traversal and compare the two outputs. Where they agree, the result is very likely right. Where they disagree, flag the region for closer analysis. This was proposed by Schwarz, Debray and Andrews (2002).
- Restart at a better point. After a data byte, some disassemblers look for a likely function start, such as a common function prologue, instead of the next byte.
- Superset disassembly. Decode an instruction at every byte offset, keep all of them, and let a later analysis decide which ones are real. This keeps every possible instruction and never loses the real one.
When to use it
Use linear sweep when the code sections contain little or no data, which is the common case for code from the usual compilers on Linux. Andriesse and coauthors (2016) measured the main disassemblers on compiled x86 and x64 binaries and found instruction recovery to be very accurate there, with function start detection and indirect control flow as the harder problems. Use recursive traversal when data and code are mixed, for example with jump tables placed inside functions, or when a program is obfuscated against static analysis. Use both together when the result matters, as in the hybrid above.
Pitfalls
- Stopping at the first invalid byte. Writing
if ins is not valid then return outin line L4 loses the rest of the section after one data byte. Mark the byte as data and go on, as line L4 does. - Trusting an instruction that runs past the end. A DECODE that does not check reads the bytes of the next section as operands. Check the end of the range in DECODE, so that the last bytes become data.
- Treating every decoded item as code. The output of line L5 is a guess. A later step that builds a control flow graph from it must not follow a jump decoded from data. Use the items that recursive traversal also reaches, or mark the others as unsure.
- Assuming fixed alignment. On a variable-length instruction set, skipping to the next multiple of 4 after a bad byte can step into the middle of a real instruction. Restart at the next byte, as line L4 does, or at a known function start.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/linear-sweep-disassembly/. The authors are listed in prov/B218H3.jsonl.
"""Linear sweep 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
0x00 1 NOP
0x01 3 MOV r, imm r < 4
0x02 3 ADD r, s r < 4 and s < 4
0x10 2 JMP t
0x11 3 JZ r, t r < 4
0x12 2 CALL t
0x13 1 RET
0x14 2 JMPI r r < 4, an indirect jump
0xFF 1 HALT
Any other opcode byte, or a register byte of 4 or more, is not a valid
instruction.
"""
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 Data(NamedTuple):
addr: int
value: int
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 linear_sweep(code: bytes, start: int = 0, end: Optional[int] = None) -> list[Insn | Data]:
"""Decode code[start:end] from left to right.
Precondition: 0 <= start <= end <= len(code). Postcondition: the items
cover each byte of the range exactly once, in address order. A byte where
no valid instruction starts is reported as Data and skipped. Cost: O(end -
start) time, since each step consumes at least one byte.
"""
if end is None:
end = len(code)
p = start # @line L1
out: list[Insn | Data] = []
while p < end: # @line L2
ins = decode(code, p, end) # @line L3
if ins is None: # @line L4
out.append(Data(p, code[p]))
p += 1
else:
out.append(ins) # @line L5
p += ins.size
return out # @line L6
test_linear_sweep_disassembly.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/linear-sweep-disassembly/. The authors are listed in prov/B218H3.jsonl.
import random
import re
from linear_sweep_disassembly import Data, Insn, linear_sweep
# An independent description of the valid encodings, as one regular expression.
R = b"[\x00-\x03]"
VALID = re.compile(
b"\x00|\x01" + R + b"[\x00-\xff]|\x02" + R + R + b"|\x10[\x00-\xff]|\x11" + R + b"[\x00-\xff]"
b"|\x12[\x00-\xff]|\x13|\x14" + R + b"|\xff",
re.DOTALL,
)
def oracle_sweep(code: bytes, start: int, end: int) -> list[tuple[int, int, bool]]:
out, p = [], start
while p < end:
m = VALID.match(code, p, end)
if m:
out.append((p, m.end() - p, True))
p = m.end()
else:
out.append((p, 1, False))
p += 1
return out
def as_triples(items: list[Insn | Data]) -> list[tuple[int, int, bool]]:
return [(x.addr, x.size, True) if isinstance(x, Insn) else (x.addr, 1, False) for x in items]
def random_instruction(rng: random.Random) -> bytes:
op = rng.choice([0x00, 0x01, 0x02, 0x10, 0x11, 0x12, 0x13, 0x14, 0xFF])
r = rng.randrange(4)
return {
0x00: bytes([0x00]),
0x01: bytes([0x01, r, rng.randrange(256)]),
0x02: bytes([0x02, r, rng.randrange(4)]),
0x10: bytes([0x10, rng.randrange(256)]),
0x11: bytes([0x11, r, rng.randrange(256)]),
0x12: bytes([0x12, rng.randrange(256)]),
0x13: bytes([0x13]),
0x14: bytes([0x14, r]),
0xFF: bytes([0xFF]),
}[op]
PAGE_EXAMPLE = bytes(
[0x01, 0x00, 0x05, 0x10, 0x07, 0x01, 0x02, 0x02, 0x00, 0x01, 0x12, 0x0E, 0xFF, 0x2A, 0x01, 0x01, 0x03, 0x13]
)
def test_page_example() -> None:
got = [(x.addr, x.op, x.operands) if isinstance(x, Insn) else (x.addr, "data", (x.value,)) for x in linear_sweep(PAGE_EXAMPLE)]
assert got == [
(0, "MOV", (0, 5)),
(3, "JMP", (7,)),
(5, "MOV", (2, 2)), # the data bytes 01 02 and the first byte of ADD
(8, "NOP", ()),
(9, "data", (0x01,)), # 01 12 0E is not valid: register 0x12
(10, "CALL", (14,)), # back in step with the real instructions
(12, "HALT", ()),
(13, "data", (0x2A,)),
(14, "MOV", (1, 3)),
(17, "RET", ()),
]
def test_code_only_sections_are_decoded_exactly() -> None:
rng = random.Random(20)
for _ in range(500):
program = [random_instruction(rng) for _ in range(rng.randrange(0, 30))]
code = b"".join(program)
want, p = [], 0
for ins in program:
want.append((p, len(ins), True))
p += len(ins)
assert as_triples(linear_sweep(code)) == want
def test_random_bytes_match_the_oracle_and_cover_each_byte_once() -> None:
rng = random.Random(21)
for _ in range(500):
code = bytes(rng.randrange(256) if rng.random() < 0.3 else rng.choice([0, 1, 2, 3, 0x10, 0x11, 0x13, 0xFF]) for _ in range(rng.randrange(0, 40)))
start = rng.randrange(0, len(code) + 1)
end = rng.randrange(start, len(code) + 1)
items = as_triples(linear_sweep(code, start, end))
assert items == oracle_sweep(code, start, end)
covered = [a for a, size, _ in items for a in range(a, a + size)]
assert covered == list(range(start, end))
def test_truncated_instruction_at_the_end_is_data() -> None:
assert as_triples(linear_sweep(bytes([0x00, 0x01, 0x02]))) == [(0, 1, True), (1, 1, False), (2, 1, False)]
assert as_triples(linear_sweep(bytes([0x01, 0x00, 0x05]), 0, 2)) == [(0, 1, False), (1, 1, True)]
def test_resynchronization_after_data() -> None:
# After a run of data bytes, the sweep is back in step at most a few instructions later.
rng = random.Random(22)
lost = []
for _ in range(300):
before = b"".join(random_instruction(rng) for _ in range(5))
data = bytes(rng.randrange(256) for _ in range(rng.randrange(1, 6)))
after = [random_instruction(rng) for _ in range(20)]
code = before + data + b"".join(after)
starts = {x.addr for x in linear_sweep(code) if isinstance(x, Insn)}
p, missed = len(before) + len(data), 0
for ins in after:
if p in starts:
break
missed += 1
p += len(ins)
lost.append(missed)
assert max(lost) <= 3 and sum(lost) / len(lost) < 0.5 # measured on this seed: at most 1, in 7 of 300 trials
History
Linear sweep is the oldest and simplest method, used by early disassemblers and by the GNU objdump tool. Its weakness with data in the code section was well known. Schwarz, Debray and Andrews (WCRE 2002) compared linear sweep and recursive traversal on real programs and proposed improvements and a hybrid of the two. Linn and Debray (CCS 2003) showed how inserting junk bytes after unconditional jumps makes linear sweep go wrong, which made the method a standard target of anti-disassembly. Andriesse and coauthors (USENIX Security 2016) measured modern disassemblers on a large set of compiled binaries and found that the common belief that disassembly of compiled code is very hard was too pessimistic for instruction recovery.
References
- 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 linear sweep and recursive traversal, their failure cases, and the hybrid of the two
- 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 start detection and control flow recovery by common disassemblers on compiled binaries
- Cullen Linn and Saumya Debray, Obfuscation of executable code to improve resistance to static disassembly, ACM Conference on Computer and Communications Security (CCS) 2003, why junk bytes after unconditional jumps break linear sweep, and the measures of how much of a program is disassembled wrongly
Where this leads
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag B218H3 Edit this page History Report an error Markdown