Section 16.11

Keystone assembler engine

Definition

Keystone is an assembler engine: a library that turns assembly language, the text form of processor instructions such as inc ecx, into machine code, the bytes a processor executes. A program passes it the text, an architecture such as x86 or Arm, a mode such as 32-bit, 64-bit or Thumb, and the address at which the code will be placed, and receives the encoded bytes. Keystone does the reverse job of the Capstone §12.34 disassembler, which turns bytes into instructions.

The idea

A tester needs the exact bytes of particular instructions: to build test inputs for a decoder or a verifier, to patch a program, or to place code in memory. Encoding by hand from an architecture manual is slow and error-prone. An x86 instruction is 1 to 15 bytes long, and its bytes depend on the operation, the registers, the operand sizes and the mode. Keystone is a library: one call, text in, bytes out, for many architectures.

An assembler is a translator with a dictionary of encodings. The same sentence translates differently in different dialects, the modes, and a jump translates differently depending on where it is placed, because many jumps store a distance, not a destination. A fluent translation is useless to a reader who speaks another dialect: a processor that lacks an instruction cannot run it. So assembled bytes are checked against the authority behind the dictionary, the architecture manual, and against the reader, the target processor, not against the translator’s own reverse dictionary.

How it works

Keystone is written in C and C++ on top of the assembler of LLVM §12.18, a compiler project whose name began as Low Level Virtual Machine and is now treated as a plain name. It supports x86 in 16-, 32- and 64-bit modes, 32-bit Arm and Thumb, 64-bit Arm and several other architectures, and it has bindings for Python §12.23 and other languages. From Python, assembly takes four steps:

  1. Choose architecture and mode: ks = Ks(KS_ARCH_X86, KS_MODE_32). For Arm, KS_MODE_THUMB selects the Thumb instruction set §4.40, Arm’s compact set of 16-bit and 32-bit instructions, including Thumb-2, the extension that added most of the 32-bit ones.

  2. Choose a syntax if needed. x86 assembly has several syntax styles; Intel syntax is the default.

  3. Assemble: encoding, count = ks.asm(b"inc ecx; dec edx", 0x1000). Statements are separated by semicolons or new lines. The second argument is the address of the first instruction. The result is a list of byte values and the number of statements assembled; an error, such as an unknown instruction, raises KsError.

  4. Check that count equals the number of statements and that the bytes are the intended ones, as described under the question below.

The address matters for instructions that encode a distance. An x86 relative jump stores the distance from the address of the next instruction to the target. Text that names a fixed target address, such as jmp 0x1010, assembles to different bytes at different start addresses. A jump to a label inside the same text does not change, because the distance between two instructions of the text is fixed.

Keystone does not choose the processor model. Its interface selects an architecture, a mode and a syntax; it has no option that names a processor or an architecture revision. In Thumb mode it encodes Thumb-2 instructions, which an older processor such as the Arm Cortex-M0 does not implement.

Worked example

In 32-bit mode, inc ecx; dec edx assembles to the 2 bytes 41 4a, written in hexadecimal. The x86 manual gives the rule: in 32-bit mode, the one-byte increment is 0x40 plus the register number, the one-byte decrement is 0x48 plus the register number, and the registers eax, ecx, edx have the numbers 0, 1, 2. So inc ecx is 𝟶𝚡𝟺𝟶+1=𝟶𝚡𝟺𝟷\texttt{0x40} + 1 = \texttt{0x41} and dec edx is 𝟶𝚡𝟺𝟾+2=𝟶𝚡𝟺𝚊\texttt{0x48} + 2 = \texttt{0x4a}.

In 64-bit mode the same text assembles to the 4 bytes ff c1 ff ca. In 64-bit mode the bytes 0x40 to 0x4f are prefixes that modify the next instruction, so the assembler uses the two-byte form: the operation byte 0xff, then a byte that selects the operation and the register. That second byte has three fields: 2 bits 11, meaning a register operand; 3 bits for the operation, 000 for increment and 001 for decrement; 3 bits for the register, 001 for ecx and 010 for edx. In binary, 11000001 is 128+64+1=193128 + 64 + 1 = 193, which is 0xc1, and 11001010 is 128+64+8+2=202128 + 64 + 8 + 2 = 202, which is 0xca. The 32-bit result 41 4a, read in 64-bit mode, is two prefixes with no instruction after them.

A jump at address 0x1000 to the target 0x1010 has two correct encodings. The 2-byte short form is eb followed by a signed 1-byte distance from the next instruction, 𝟶𝚡𝟷𝟶𝟷𝟶−𝟶𝚡𝟷𝟶𝟶𝟸=𝟶𝚡𝟶𝚎\texttt{0x1010} - \texttt{0x1002} = \texttt{0x0e}, which gives eb 0e. The 5-byte near form is e9 followed by a 4-byte distance stored least significant byte first, 𝟶𝚡𝟷𝟶𝟷𝟶−𝟶𝚡𝟷𝟶𝟶𝟻=𝟶𝚡𝟶𝚋\texttt{0x1010} - \texttt{0x1005} = \texttt{0x0b}, which gives e9 0b 00 00 00. Two correct assemblers can therefore disagree byte for byte.

A wrong start address gives a wrong target. Assembled for start address 0, the jump cannot use the short form: the distance 𝟶𝚡𝟷𝟶𝟷𝟶−2=𝟶𝚡𝟷𝟶𝟶𝚎\texttt{0x1010} - 2 = \texttt{0x100e}, which is 4110, exceeds the largest 1-byte distance, 127. The near form gives the distance 𝟶𝚡𝟷𝟶𝟷𝟶−5=𝟶𝚡𝟷𝟶𝟶𝚋\texttt{0x1010} - 5 = \texttt{0x100b} and the bytes e9 0b 10 00 00. Placed at 0x1000, these bytes jump to 𝟶𝚡𝟷𝟶𝟶𝟻+𝟶𝚡𝟷𝟶𝟶𝚋=𝟶𝚡𝟸𝟶𝟷𝟶\texttt{0x1005} + \texttt{0x100b} = \texttt{0x2010}, not to 0x1010.

Stated precisely

Let tt be the assembly text, AA the architecture, MM the mode, aa the start address and bb the bytes that Keystone returns. Keystone guarantees one thing: bb encodes the statements of tt, placed at aa, according to Keystone’s own encoding tables for AA and MM. The bytes match the intended instructions and revision only when four further facts hold.

  1. Decoding: decoding bb from address aa by the rules of the architecture manual gives exactly the intended instructions, with the same operations, operands, instruction boundaries and jump targets.

  2. Revision: the target processor implements every one of those instructions in its architecture revision and enabled extensions.

  3. Placement: the bytes run at address aa, or contain no encoding that depends on the address.

  4. Byte order §4.21: the target reads multi-byte values in the byte order the encoding assumes.

For a relative jump of length ℓ\ell bytes at address aia_i, the encoded distance is d=target−(ai+ℓ)d = \text{target} - (a_i + \ell), and dd must fit the distance field: −128≤d≤127-128 \le d \le 127 for a 1-byte field.

Limits and common mistakes

A round trip through Capstone is weak evidence. Capstone’s decoding tables also derive from LLVM, so a mistake that both share appears in both directions, and the round trip still agrees. Independent evidence is the architecture manual; a toolchain §12.2 with separate tables, such as the assembler and the objdump disassembler of the GNU project (GNU, a recursive acronym for GNU’s Not Unix, names a free-software project); or running the bytes on the target or an emulator and observing their effect.

Several encodings can be correct, as the jump example shows. Compare meanings, or fix the encoding form, before comparing bytes.

Assembly success is not admission. Assembly text can express any instruction the architecture has, including sequences that no compiler emits. A system that runs supplied code must check the resulting bytes, whatever produced them; the structural bytecode admission §2.26 entry covers that check for bytecode §2.4.

No effect is not no cost. The x86 instruction nop, the byte 0x90, whose name NOP stands for no operation, changes nothing except the instruction pointer §2.9, yet it takes time and space.

Encodings and supported instructions change between Keystone versions; record the version with the bytes.

Questions answered

How do you verify the assembled bytes match the intended instruction and ISA §4.38 revision?

Verify them against an authority that is independent of the assembler: decode the bytes by the rules of the architecture manual, for the same architecture, mode and start address, check that they give exactly the intended instructions, and then check that the target’s ISA (instruction set architecture) revision implements each of them. In practice:

  1. record the architecture, mode, syntax, start address and assembler version used;

  2. for a sample of instructions, compute the expected encoding by hand from the manual’s encoding tables, and decode all the bytes with a tool that does not share the assembler’s tables, such as the GNU tools when the assembler is Keystone;

  3. check instruction boundaries, operands, and the target of every relative jump, recomputing each distance from the start address;

  4. look up each instruction in the target processor’s manual to confirm that its architecture revision and enabled extensions include it, because the assembler’s mode does not check this;

  5. where possible, run the bytes on the target or an emulator and observe the intended effect.

A round trip through a disassembler built from the same tables, such as Capstone for Keystone, is weak evidence, because a shared mistake passes it.

Related entries: Bytecode (§2.4), Instruction encoding (§2.7), Opcode (§2.8), Structural bytecode admission (§2.26), Capstone (§12.34), Instruction set architecture (ISA) (§4.38), Arm Thumb and Thumb-2 (§4.40). Further reading: [60, 182].