Keystone Engine Assembler
Keystone Engine is a lightweight multi-architecture assembler framework, providing Python bindings to its powerful C core. It supports various architectures including X86, ARM, ARM64, MIPS, PowerPC, SPARC, SystemZ, and more. The current version is 0.9.2, and it maintains a stable release cadence focused on feature enhancements and bug fixes.
Common errors
-
ImportError: No module named 'keystone'
cause The Python package is named `keystone-engine` on PyPI, but its internal module is `keystone`. This error usually occurs if the package was not installed or if there's a virtual environment issue.fixEnsure `keystone-engine` is installed correctly: `pip install keystone-engine`. If in a virtual environment, ensure it's activated. -
keystone.KeystoneError: Invalid architecture (KS_ERR_ARCH)
cause The architecture specified during `Ks` initialization is invalid or not supported by Keystone.fixVerify that you are using a valid `KS_ARCH_*` constant (e.g., `KS_ARCH_X86`, `KS_ARCH_ARM`). Refer to the `keystone` module for available constants. -
keystone.KeystoneError: Syntax error (KS_ERR_ASM_SYNTAX)
cause The provided assembly instruction string is syntactically incorrect for the chosen architecture and mode.fixReview the assembly instruction for typos, incorrect registers, or unsupported mnemonics. Ensure it conforms to the target architecture's assembly syntax.
Warnings
- gotcha Incorrectly specifying the architecture (KS_ARCH_*) or mode (KS_MODE_*) can lead to assembly failures or incorrect output. Always ensure these constants match the target CPU and instruction set.
- gotcha Assembly instructions are case-insensitive for most architectures, but the syntax must be correct for the chosen architecture. Malformed instructions will raise `KeystoneError: Syntax error`.
- gotcha The `Ks.asm()` method expects a byte string (e.g., `b"inc eax"`) for the instruction. Passing a regular string might work on some Python versions or implicitly convert, but explicit byte strings are safer and more consistent.
Install
-
pip install keystone-engine
Imports
- Ks
from keystone import Ks
- KS_ARCH_X86
from keystone import KS_ARCH_X86, KS_MODE_32
- KeystoneError
from keystone import KeystoneError
Quickstart
from keystone import *
try:
# Initialize Keystone for X86-32bit architecture
ks = Ks(KS_ARCH_X86, KS_MODE_32)
# Assemble a simple instruction
opcode, count = ks.asm(b"inc eax")
print(f"Assembled instruction bytes: {opcode}")
print(f"Number of instructions assembled: {count}")
# Example with multiple instructions
opcode_multi, count_multi = ks.asm(b"add ecx, 10; mov eax, ebx")
print(f"Assembled multiple instructions bytes: {opcode_multi}")
print(f"Number of instructions assembled: {count_multi}")
except KeystoneError as e:
print(f"Keystone error: {e}")