Skip to content

Latest commit

 

History

History
202 lines (163 loc) · 13 KB

README.md

File metadata and controls

202 lines (163 loc) · 13 KB

appthreat-nyxstone

Python bindings for nyxstone, the assembler and disassembler built on LLVM, from the AppThreat fork at AppThreat/nyxstone.

The fork adds to upstream nyxstone:

  • disassemble_to_structured, which returns for each instruction what LLVM's machine-code layer knows about it: the opcode, control-flow flags, typed operands, the registers read and written (implicit ones included), branch targets and memory accesses split into base, index, scale, displacement and width. See Structured disassembly.
  • Wheels for Linux (glibc and musl), macOS and Windows that carry a statically linked LLVM 23, so installing the package needs no LLVM and no compiler.
  • A binding written with nanobind. One wheel per platform covers CPython 3.12 and later (stable ABI); CPython 3.10 and 3.11 have their own wheels.

The distribution is called appthreat-nyxstone, but it installs the same import names as upstream: nyxstone and the compiled module nyxstone_cpp. Code written for upstream's Python binding keeps working without a change to its imports. Do not install it next to upstream's nyxstone package. Both write nyxstone/__init__.py and the nyxstone_cpp module into site-packages, and pip does not warn about it. Uninstall nyxstone first (pip uninstall nyxstone), and make sure nothing else in the environment depends on it.

Installation

pip install appthreat-nyxstone

The package has no dependencies. The wheels are for CPython 3.10 and later on:

Platform Architectures
Linux, glibc (manylinux_2_28) x86-64, aarch64
Linux, musl (musllinux_1_2) x86-64, aarch64
macOS arm64 (macOS 11 and later), x86-64 (macOS 10.15 and later)
Windows x86-64 (needs the Visual C++ 2015 to 2022 runtime, which a python.org install brings)

The package and the LLVM version it is linked with are available at run time:

import nyxstone

nyxstone.__version__   # '0.3.5'
nyxstone.llvm_version  # '23.1.7'

Building from source

Wheels are the only distribution: no source distribution is published. To build one yourself you need a C++17 compiler, nanobind, and LLVM 23 with its static libraries. setup.py finds LLVM by running $NYXSTONE_LLVM_PREFIX/bin/llvm-config, or llvm-config on $PATH. Where there is no llvm-config (the libraries that ci/build-llvm.sh builds), set NYXSTONE_LLVM_PREFIX to a directory with include/ and lib/. The official LLVM 20 release archives cannot be linked: the Linux and macOS ones hold LTO bitcode, and the Windows one mixes two C runtimes. ci/build-llvm.sh builds the libraries from the LLVM sources instead.

The extension sources are symlinks into the top of the repository, so build from the repository root:

NYXSTONE_LLVM_PREFIX=/opt/homebrew/opt/llvm@23 pip install ./bindings/python

On Arch Linux (and other distros that mark the system Python as externally managed), do this inside a virtualenv.

Example

Import the Nyxstone and Instruction classes:

from nyxstone import Nyxstone, Instruction

Create a Nyxstone instance for the target architecture:

nyxstone = Nyxstone("x86_64")

Assemble and disassemble raw bytes / text:

assert nyxstone.assemble("mov rax, rbx") == [0x48, 0x89, 0xd8]
assert nyxstone.disassemble([0x48, 0x89, 0xd8]) == "mov rax, rbx\n"

Or work with Instruction objects that bundle address, bytes, and assembly text:

instructions = [Instruction(0x0, "mov rax, rbx", [0x48, 0x89, 0xd8])]
assert nyxstone.assemble_to_instructions("mov rax, rbx") == instructions
assert nyxstone.disassemble_to_instructions([0x48, 0x89, 0xd8]) == instructions

When assembling, you can supply a base address and a label-to-address map for external labels; inline labels are resolved automatically:

assert nyxstone.assemble("jmp .label", address=0x1000, labels={".label": 0x1200}) == [0xe9, 0xfb, 0x01, 0x00, 0x00]
assert nyxstone.assemble("jmp .label; nop; .label:", address=0x1000) == [0xeb, 0x01, 0x90]

When disassembling, you can specify the base address and a maximum instruction count (0 means "until the bytes are exhausted"):

assert nyxstone.disassemble([0x48, 0x31, 0xc0, 0x48, 0x01, 0xd8], 0x1000, 0) == "xor rax, rax\nadd rax, rbx\n"
assert nyxstone.disassemble([0x48, 0x31, 0xc0, 0x48, 0x01, 0xd8], 0x1000, 1) == "xor rax, rax\n"

Structured disassembly

disassemble_to_structured returns, for each instruction, what LLVM's machine-code layer knows about it beyond the text. It leaves disassemble and disassemble_to_instructions as they are.

from nyxstone import Nyxstone

nyx = Nyxstone("aarch64-linux-gnu")
insn = nyx.disassemble_to_structured([0xfd, 0x7b, 0xbe, 0xa9], 0x108a8)[0]  # stp x29, x30, [sp, #-32]!
insn.opcode_name                                  # 'STPXpre'
insn.kind.name                                    # 'Other' (also Call, IndirectCall, Return, Branch, ConditionalBranch, IndirectBranch, Trap)
[r.reg.asm_name for r in insn.regs_read]          # ['x29', 'x30', 'sp']
[r.reg.asm_name for r in insn.regs_written]       # ['sp']
mem = insn.memory[0]
(mem.direction.name, mem.base.asm_name, mem.displacement, mem.width_bytes, mem.writeback.name)
# ('Write', 'sp', -32, 16, 'PreIndex')

Each result carries:

  • the opcode name, the control-flow flags (is_call, is_return, is_branch, is_conditional_branch, is_indirect_branch, is_barrier, is_trap, is_syscall, may_load, may_store, has_delay_slot, is_predicable) and the direct branch target where there is one;
  • the operands in LLVM's order, each with its kind (register, immediate, PC-relative), whether it is a definition or a use, and its role in a memory access (base, index, scale, displacement, segment, register_list, ...);
  • the registers read and written, explicit ones first and then LLVM's implicit ones, each with the architectural register that holds it (eax and al give RAX, w0 gives X0) and its width;
  • the memory accesses, each split into base, index, scale, displacement, segment, direction, writeback and width in bytes, with width_source saying where the width came from (opcode, printer, operand, list, element for a NEON lane access, first_word for an ARM coprocessor transfer or size_register for an AArch64 memory copy or set, whose byte count is in a register, or dczid_block for dc zva, dc gva and dc gzva, whose block size is in DCZID_EL0);
  • for a memory access with writeback, writeback_offset (the decoded amount the base changes by, None when a register supplies it, in which case that register's operand has the role writeback_offset) on ARM, Thumb and AArch64, for pre-indexed, post-indexed and block forms alike;
  • for an ARM access whose index register is subtracted (ldr r0, [r1], -r2), index_subtract;
  • for AArch64 tag instructions, allocation_tags_only (stg, st2g and ldg work on tags and not data), and for SVE and SME accesses, whose extent depends on the vector length, vl_scaled with vl_unit_divisor and vl_unit_count (the access is at most count units of VL / divisor bytes, width_bytes is 0) and displacement_in_vl_units (the displacement counts units of VL / divisor bytes, as in [x0, #3, mul vl], and is not a byte count);
  • for SVE gathers, scatters and prefetches, element_addressed: every active element makes its own access, at the base plus the index plus the displacement, where base_is_vector and index_is_vector say which of them is a vector register whose element i is used, element_container_bytes is the element size of that vector (4, 8 or 16) and width_bytes the size of one element's access (0 for a prefetch);
  • for an immediate operand whose LLVM encoding packs fields, value and value_meaning: rotated_immediate (an ARM modified immediate, decoded to the 32-bit number), shift_amount with shift (the decoded shift of an ARM register operand, where lsr #32 and asr #32 are 32 and rrx is 1), and for ldc, stc, ldc2 and stc2 coprocessor, coprocessor_register and coprocessor_option. The same fields give, for ARM and Thumb, the shift of asr, lsr, ssat, usat and pkh (shift_amount), byte_offset for the stack-pointer adds and subtracts, saturate_width, bitfield_lsb (with value_width for bfc and bfi) and bitfield_width, rotation for the extensions, coprocessor_opcode and the register fields of mcr, mrc, cdp, mcrr and mrrc, modified_immediate and float_bits for NEON and VFP immediates, and fraction_bits for fixed-point vcvt. On AArch64 the same fields give logical immediates (bitmask_immediate), shifted and extended register operands (shift_amount, extend_amount), condition codes (condition with the name in value_name, and nzcv), bit-field bitfield_lsb and bitfield_width, the shifts of movz, movn and movk, fmov and vector immediates, and system_register with its name in value_name;
  • for 32-bit ARM the condition code and the position in a Thumb IT block, and for MIPS whether the instruction sits in a delay slot;
  • target_code, the list of things that this library's own per-architecture code added to what LLVM's tables give, so that a consumer can tell the two apart.

unpredictable is set for the encodings that the architecture manual calls UNPREDICTABLE (ARM vld3 and vld4 with the PC as base, ARM multiplies that write the PC, NEON register lists that run past d31, ARM ldm, stm, vst1 to vst4, ldc and stc with a PC base (the literal loads such as vldr and ldr are not marked), ldrex, strex, ldrd and strd, register-offset and base-update forms with a PC or overlapping register, blx pc, T32 ldm with LR and PC, AArch64 stxr with its status register equal to a data or base register, PowerPC bcctr with BO bit 2 clear), which also have unpredictable in target_code. Other target_code entries added in this release are count_register (x86 loop, jcxz), jump_region (MIPS j, jal), absolute_target (RISC-V jalr from x0), fp_state (RISC-V frm and fflags), q_flag (ARM saturating arithmetic), pstate_svcr (AArch64 smstart, smstop) and fpsr_flags (AArch64 floating-point instructions that write FPSR). Branch targets wrap at 32 bits on 32-bit targets. x86 fxsave, xsave and fnsave write and the restore forms read, with widths 512, 108 (94 with a 16-bit operand size) and, for fnstenv and fldenv, 28 (14); xsave and xrstor have no fixed width. PowerPC mfspr and mtspr carry the SPR number with value_meaning special_purpose_register. PowerPC conditional branches read CTR (and write it) only when BO bit 2 is clear and read the condition register bit only when BO bit 0 is clear (branch_bo), and read no rounding mode. AArch64 bl and blr and ARM bl, blx and svc read no stack pointer. An AArch64 instruction with condition AL or NV reads no NZCV (condition_always). The FPCR read and FPSR write cover every floating-point arithmetic, compare, convert and round opcode family (fpsr_flags), and the Advanced SIMD saturating integer instructions write FPSR only (fpsr_qc, the QC flag). vg is listed for the SVE instructions whose result depends on the vector length (rdvl, addvl, cnt*, ptrue) and not for addsvl, addspl or the constant forms of mov, fmov and index (no_vector_length). MIPS floating-point arithmetic, conversion, rounding and compare instructions list $31 (FCSR) as written and implicit (fcsr_flags), because they can raise an IEEE exception; the conversions to integer do not read it. The RISC-V Zicbop prefetches have direction None. The x86 clflush, clflushopt, clwb and prefetch* instructions also have direction None (cache_hint): they name a cache line and move no data. ldmxcsr is a four-byte Read and stmxcsr a four-byte Write (mxcsr_direction), and arpl with a memory destination is ReadWrite. Implicit writes of ESI, EDI, ECX and the other 32-bit registers set clears_upper in 64-bit mode, and a REX prefix does not change the address size. The one-operand byte mul and imul list AX, not AL, as written (byte_multiply_ax), and ud0, ud1 and ud2 list no register. The x86 ud0, ud1 and ud2 raise #UD at decode: they have no memory access and no load or store flag even with a memory-form ModRM byte, and the base and index registers are not read. memory_incomplete is set when an opcode loads or stores and this library does not decompose its address. The zero register (xzr, MIPS $zero, RISC-V x0) and x86's eiz never appear in the register lists. structured_to_dict turns a result into plain data.

Building wheels

bindings/python/pyproject.toml holds the cibuildwheel configuration, and ci/ the scripts that install a static LLVM inside the build containers. .github/workflows/wheels.yml runs the whole matrix. From the repository root:

cibuildwheel --platform linux bindings/python