Section 12.34

Capstone

Definition

Capstone is a disassembly framework: a library that turns machine code, the bytes a processor executes, into readable instructions. The caller supplies the bytes, an instruction set architecture §4.38 (ISA), meaning the instructions and encodings of a processor family such as x86 or Arm, a processor mode such as 64-bit, and the address where the bytes are assumed to start. Capstone returns one record per instruction: its address, its length, its mnemonic (the operation’s short name, such as push) and its operands (the registers, memory locations or constants it acts on).

The idea

A crash report gives the address of a faulting instruction; a security tool must check that machine code contains no forbidden instruction; a debugger must step over a call. Each must turn bytes into instructions. Decoding by hand from an architecture manual is slow and error-prone: an x86 instruction is 1 to 15 bytes long, and prefix bytes change the meaning of the bytes after them. Capstone, written in C with bindings for Python §12.23 and other languages, packages the decoding rules of many architectures behind one interface. Its detail mode adds structured facts, such as the type of each operand and the registers, the processor’s small internal storage slots, that the instruction reads and writes, so a program need not parse printed text.

A disassembler is a dictionary, not a witness. Given bytes, a starting position and a language, it says which instruction the bytes spell. It does not say whether the processor ever arrives at those bytes, and it does not say what the instruction does to the machine. Those are two further questions with their own methods: reachability §3.21, answered by following the program’s possible paths from its entry point, and meaning, answered by a model of each instruction’s effect. The dictionary picture also fits decoding itself: read from a different byte, or in a different mode, the same bytes spell different instructions.

How it works

Using Capstone from Python takes four steps.

  1. Choose the decoder. md = Cs(CS_ARCH_X86, CS_MODE_64) creates a decoder for x86 in 64-bit mode. The first constant names the architecture and the second the mode, for example CS_MODE_32 for 32-bit x86, or CS_ARCH_ARM with CS_MODE_THUMB for the Thumb instruction set §4.40 of Arm processors.

  2. Ask for details if needed. After md.detail = True, each record also lists its operands with their types, the registers the instruction reads and writes, and its groups, such as jump, call or return.

  3. Decode. md.disasm(code, address) decodes the byte string code as if its first byte sat at address. It decodes the instruction at offset 0, then the instruction that starts right after it, and so on to the end of the bytes; this order is called a linear sweep. Each record has the fields address, size, mnemonic, op_str, which holds the operands as text, and bytes.

  4. Check where decoding stopped. At the first bytes that do not form a valid instruction, or that end in the middle of one, disasm stops without raising an error. The caller must compare the decoded length with the input length. With md.skipdata = True, Capstone instead emits a pseudo-instruction named .byte for the bytes it cannot decode and continues after them.

The address argument does not change which instruction the bytes spell. It sets the printed addresses and lets Capstone print absolute targets, such as the destination of a relative jump, which the instruction itself stores as a distance from the next instruction.

Three questions are left to other tools.

Worked example

The Capstone documentation decodes these 8 bytes, written in hexadecimal, as x86 code in 64-bit mode at address 0x1000:

55 48 8b 05 b8 13 00 00

The result is two instructions:

The lengths add up to 1+7=81 + 7 = 8 bytes, so the whole input was decoded.

The second instruction addresses memory relative to rip, the instruction pointer §2.9, which during this instruction holds the address of the next instruction, 𝟶𝚡𝟷𝟶𝟶𝟷+7=𝟶𝚡𝟷𝟶𝟶𝟾\texttt{0x1001} + 7 = \texttt{0x1008}. The load therefore reads from 𝟶𝚡𝟷𝟶𝟶𝟾+𝟶𝚡𝟷𝟹𝚋𝟾=𝟶𝚡𝟸𝟹𝚌𝟶\texttt{0x1008} + \texttt{0x13b8} = \texttt{0x23c0}. That result is right only if the code really runs at 0x1000, which the caller told Capstone and Capstone did not check.

The same bytes, read from other starting points or in another mode:

Every one of these decodings succeeded. Only the address at which execution arrives and the mode the processor is in decide which reading the processor uses.

In detail mode, push rbp lists rbp as its operand, rsp, the stack pointer register, and rbp as registers read, and rsp as the register written. The record does not state the effect: the processor subtracts 8 from rsp and stores the 8 bytes of rbp at the new address in rsp, and that store faults if the address is not writable memory. A tool that needs the effect needs a model of the instruction.

Stated precisely

Fix an architecture AA, a mode MM, a byte string bb of nn bytes and a start address aa. Capstone’s decoder is a function that, given an offset kk into bb, returns either failure or an instruction record of length ℓk\ell_k bytes. disasm visits the offsets k0=0k_0 = 0 and kj+1=kj+ℓkjk_{j+1} = k_j + \ell_{k_j}, and stops at the first failure or when the offset reaches nn. For each record it returns, Capstone guarantees only this: the bytes b[k],…,b[k+ℓk−1]b[k], \dots, b[k + \ell_k - 1] form an encoding that Capstone’s tables for AA and MM accept, and the record is Capstone’s description of that encoding placed at address a+ka + k.

A claim about execution needs four more facts, each established separately.

  1. Mode. The processor executes those bytes in architecture AA and mode MM.

  2. Reachability. Some execution that starts at the program’s entry point arrives at address a+ka + k, so a+ka + k is an instruction boundary that the processor actually uses.

  3. Correspondence. At that moment the bytes in memory at a+ka + k equal b[k],…,b[k+ℓk−1]b[k], \dots, b[k + \ell_k - 1], after loading, relocation §12.50 and any later writes.

  4. Agreement. The processor implements the instruction as Capstone decodes it. A processor that lacks an optional instruction set extension raises an invalid-instruction exception on an instruction that Capstone decodes without complaint.

A claim about what the instruction does needs a fifth fact: a model of its effect on registers, memory and status flags, including the cases in which it faults.

Limits and common mistakes

A wrong mode gives plausible output. Decoded as Thumb code, in which instructions are 2 or 4 bytes long, the 8 bytes of the example become four 2-byte instructions, the first being ldr r0, [pc, #0x154]. Nothing in the output says that the mode was wrong.

Data decodes too. Jump tables §2.39 (lists of addresses that compiled switch statements jump through), constants that Arm compilers place between functions, and padding all decode as instructions in a linear sweep. On x86, decoding that starts inside data can stay out of step with the true instruction boundaries for several instructions.

Stopping is silent. disasm returns fewer instructions, and no error, when it meets bytes it cannot decode or an instruction cut off by the end of the input. A tool that does not compare lengths reports a partial listing as complete.

Versions differ: decoders gain instructions and fix mistakes between releases, so record the Capstone version with any result. A program should read the structured detail fields rather than parse the op_str text, which is formatted for people.

Recognized is not understood. A verifier, a tool that decides whether code is safe to run, must reject any decoded instruction it has no model for; that is, it must fail closed §1.13. The instructions whose meaning a proof models are part of its machine-code proof boundary §4.48, and an instruction outside that set is outside the proof however cleanly it decodes.

Questions answered

Does successful decoding prove an instruction is reachable or semantically modeled?

No: successful decoding by a disassembler such as Capstone proves only that the bytes at the chosen offset form a valid instruction encoding §2.7 under the architecture and mode the caller selected, as the decoder’s tables define them. The same bytes decode successfully as different instructions from a different starting byte or in a different mode, and bytes that hold data decode as readily as bytes that hold code.

Reachability is a separate claim, that some execution starting at the program’s entry point arrives at that address; it needs control-flow analysis, for example a control-flow graph built from known entry points. Semantic modeling is another, that a model states the instruction’s effect on registers, memory and status flags, and when it faults. A decoder supplies neither; Capstone’s detail mode lists only operands and the registers read and written. A tool that relies on a decoded instruction must establish separately that execution reaches it, in the decoded mode, on the decoded bytes, and what it does.

Related entries: Instruction set architecture (ISA) (§4.38), Machine-code proof boundary (§4.48), eBPF verifier (§3.3), Opcode (§2.8), Control-flow graph (CFG) (§3.13), Reachability (§3.21). Further reading: [40, 188].