Skip to content
AttackwavePublic

About

A robust, modular, and fast two-pass assembler and disassembler for the Motorola 68000 (m68k) family of processors, written in Rust. It supports instructions from the base 68000 up to the 68060, as well as the 68881/68882 Floating Point Unit (FPU) and MMU coprocessor instructions.

Resources

Code of conduct

Contributing

Security policy

Stars

3 stars

Watchers

0 watching

Forks

Repository files navigation

Motorola 68000 Family (m68k) Assembler & Disassembler

A robust, modular, and fast two-pass assembler and disassembler for the Motorola 68000 (m68k) family of processors, written in Rust. It supports instructions from the base 68000 up to the 68060, as well as the 68881/68882 Floating Point Unit (FPU) and MMU coprocessor instructions.

Features

  • Two-Pass Architecture:
    • Pass 1: Performs sequential decoding of instructions and automatically discovers local branch and jump targets to generate label names.
    • Pass 2: Formats the final assembly output, replacing absolute offsets with the discovered branch labels.
  • CPU limits: Constrains decoding based on target CPU models: 68000, 68010, 68020, 68030, 68040, 68060.
  • FPU & MMU Support: Complete decoding of coprocessor instructions, including complex floating-point instructions (FMOVECR, FSINCOS, transcendentals) and MMU structures (PMOVE, PFLUSH, PTEST).
  • Bitfield Manipulation: Decodes 68020+ bitfield instructions (BFEXTU, BFINS, etc.).
  • Symbol Mapping: Ability to feed a symbol file mapping absolute addresses to descriptive label names.
  • Flexible Formatting: Custom flags for outputting addresses, raw instruction hex bytes, uppercase mnemonics, and output redirection.

Building

cargo build --release
# binaries land in target/release/{m68k-asm,m68k-disasm,m68k-floppy}

Disassembler (m68k-disasm)

m68k-disasm <binary-file> [options]

Options

  • input: Path to the input binary file. Use - to read the image from standard input.
  • -a, --address: Set the origin base execution address (e.g. 0x1000, $1000, or 4096). Default is 0.
  • -r, --raw: Include raw instruction hexadecimal bytes in the output.
  • --source: emit assembler source instead of a listing: an ORG line, no address column, instructions indented. Assembling the output with the same --cpu reproduces the input byte for byte (see below).
  • -c, --cpu: Target CPU limit for decoding (68000, 68010, 68020, 68030, 68040, 68060). Default is 68000.
  • --system <megadrive|neogeo|atarist>: name the machine's hardware registers, system variables and OS entry points, and apply its cartridge layout (see below).
  • --symbols <file>: name addresses from a symbol file (address name or name = address per line, see below). Repeatable.
  • --equates <file.i>: name addresses from an assembler include file: every EQU and label in it whose value lies outside the image becomes a label (--system is this with the machine's own includes). Repeatable.
  • --project <file>: analysis notes for this image, kept across runs: entry points, data ranges, pointers, labels and comments, one directive per line (see below). Repeatable.
  • -e, --entry <addr>: follow control flow from this address (repeatable). Only code reachable from the entry points is proven to be code; everything else falls back to the linear decode, with strings, pointers and tables recognised where the bytes look like them. Hunk executables, TOS programs and --system cartridge images supply their own entry points.
  • --scan-tables: also treat runs of in-image longword pointers as entry points, and tables of 16-bit offsets whose address reached code takes with lea/pea (adda.w (a0,d0.w),a0; jmp (a0)); either recovers code reached only through a jump table. The offset form is only accepted where every word leads to an even in-image address at which an instruction decodes.
  • -t, --pc-trace <file>: program counter values recorded while the image actually ran, one per line (decimal or $hex). Every one is a proven instruction start, which settles computed jumps and jump tables that no static analysis can follow (see below). Values outside the image are ignored.
  • --trace-only: treat the PC trace as complete. Only recorded addresses are code, nothing is walked on from them, everything else is data. Right for a trace from an emulator that logged every executed instruction; with a sparse trace it hides code.
  • --lvo <library>: annotate jsr -$xx(a6) calls with AmigaOS routine names (exec, dos, graphics, intuition, gadtools, utility, asl, layers, diskfont).

The disassembly is always written to standard output; the address column is always included. Redirect or pipe stdout to capture it:

m68k-asm hello.s -o - | m68k-disasm - --cpu 68020

Amiga Hunk executables

If the input file starts with the HUNK_HEADER magic (0x000003F3), m68k-disasm loads it as a classic AmigaOS executable instead of raw binary data: hunks are relocated and flattened automatically (no --org needed — --address becomes the load base instead, defaulting to 0), and any HUNK_SYMBOL names recovered from the file are shown in place of auto-generated label<N> names at branch/jump targets and other referenced addresses.

System knowledge

--system tells the disassembler which machine the image is for. The names come from the same include files the assembler ships in include/, so move.w d0,$c00004 reads move.w d0,VDP_CTRL on the Mega Drive and jsr $c00444 reads jsr SYSTEM_INT1 on the Neo Geo. Only equates whose values lie in the machine's address ranges are used; register numbers and bit masks are left alone.

For a Mega Drive or Neo Geo cartridge image at address 0 the 64 exception vectors are emitted as dc.l pointers, every vector into the image is an entry point for control-flow tracing, and the header at $100 is data with its fields labelled (on the Neo Geo the four JMP entries in the header are entry points as well). For the Atari ST, trap #1, #13 and #14 are annotated with the GEMDOS, BIOS or XBIOS function named by the word pushed just before them. On the Mega Drive an immediate written to the VDP control port is explained: move.w #$8f02,VDP_CTRL reads ; VDP reg 15 AUTOINC = $02, a longword either sets two registers or selects an address (; VDP VRAM write $c000 (DMA)).

Recording a PC trace

Hatari logs every executed instruction with --trace cpu_disasm, so a TOS program can be traced without modifying the emulator. With EmuTOS as etos512us.img and the program in a directory hd served as drive C:

m68k-asm -I include -f prg -o hd/HELLO.PRG examples/atarist/hello.s
hatari --tos etos512us.img --gemdos-drive c --auto 'C:\HELLO.PRG' \
       --trace cpu_disasm,gemdos --trace-file trace.txt --run-vbls 400 hd
perl -ne 'print "\$$1\n" if /^([0-9a-f]{8}) / && !$s{$1}++' trace.txt > pcs.txt
m68k-disasm -a '$187b0' --system atarist -t pcs.txt hd/HELLO.PRG

The whole log can be fed in: PCs inside the TOS fall outside the image and are dropped. The load address is the first PC below the ROM after the Basepage has been created line of the gemdos trace ($187b0 with this EmuTOS and memory size). A routine that is only reached through a computed jump (jmp (a0) after an offset table) is data to the static walk and code with the trace.

m68k-disasm --system megadrive game.bin
m68k-disasm --system atarist -a $20000 program.bin

Atari ST programs

A TOS program (.PRG, .TOS, .TTP, .ACC; magic $601A with a consistent header) is loaded the same way: text and data are placed back to back at --address, the relocation table is applied, every relocated longword is emitted as a dc.l pointer, the data segment as data, the names in the symbol table replace generated labels, and disassembly follows control flow from the start of the text segment.

Symbol File Format

The file given to --symbols maps absolute addresses to symbol names, one per line, either as address name or as name = address (the form m68k-asm --sym writes, so an assembler's symbol table can be fed straight back). Blank lines and lines starting with # or ; are ignored.

Reverse engineering is iterative: what one run reveals (a jump-table target, a block that is really data, what a routine does) has to go into the next run. --project takes a file of such notes, one directive per line, so they accumulate instead of being retyped as flags:

; notes on game.bin
entry   $1200               ; reached through jmp (a0), invisible to tracing
data    $2000 $2100         ; [start, end): a lookup table
pointer $2100               ; one longword address
label   $1200 draw_sprite
comment $1200 called once per frame

entry, data and pointer do what --entry, a container's data ranges and its relocations do; label is a --symbols line; comment replaces whatever comment the line at that address would otherwise carry.

# custom_symbols.txt
$00001000 main_entry
$00002054 interrupt_handler
4500      my_data_offset
draw_line = $00002100

Library usage

m68k-disasm is usable as a Rust library, not just a CLI binary — see the crate docs (cargo doc --open -p m68k-disasm) for a runnable example, starting with m68k_disasm::disassembler::Disassembler.


Assembler (m68k-asm)

A complete two-pass assembler that matches the disassembler output, enabling full roundtrip (disassemble → assemble → byte-compare).

CLI Usage

m68k-asm hello.s -o hello.bin [options]

Write a source file:

; hello.s
    ORG $1000
START:
    MOVEQ   #1,D0
    MOVE.L  #MESSAGE,A0
    RTS
MESSAGE:
    DC.B    "Hello, 68000!",0
    EVEN

Assemble it to a raw binary:

m68k-asm hello.s -o hello.bin
# Assembled 3 instructions, ... bytes -> hello.bin

Other output formats via -f/--format:

m68k-asm hello.s -f srecord -o hello.srec     # Motorola S-Record
m68k-asm hello.s -f intel-hex -o hello.hex    # Intel Hex
m68k-asm hello.s -f elf -o hello.o            # ELF32 (EM_68K, ET_REL)
m68k-asm hello.s -f ieee695 -o hello.ieee     # IEEE-695
m68k-asm hello.s -f hunk-exe -o hello         # Amiga Hunk executable (LoadSeg()-able)
m68k-asm hello.s -f prg -o hello.prg          # Atari ST / TOS program

Options

  • input: Path to the input source file. Use - to read the source from standard input; -o is then required, since there is no filename to derive an output path from. Relative INCLUDE paths resolve against the current directory in that case — pass -I for anything else.
  • -o, --output: Path to the output file. Use - to write to standard output (works for every format, including the binary ones). Defaults to the input name with a format-specific extension.
  • -c, --cpu: Target CPU model (68000, 68010, 68020, 68030, 68040, 68060). Default is 68000.
  • --origin <addr> — default origin if the source has no ORG (hex with $ or 0x prefix, or decimal).
  • -f, --format: Output format (binary, srecord, intel-hex, elf, ieee695, hunk-exe, prg). Default is binary.
  • -l/--listing <file> — write an address/bytes/cycles/source listing. The cycles column gives 68000 clock periods per instruction (10/8 for a branch taken/not taken, 38-70 for a data-dependent range); the footer sums them.
  • --sym <file> — export the resolved symbol table.
  • --map <file> — export a memory map (address ranges per instruction).
  • -V, --version — print the version (all three tools).
  • --Werror — treat warnings as errors: no output is written and the exit status is 1.
  • --stack-check, --stack-report <file>, --flag-check — static checks over the encoded program (see below).
  • --depfile <file> — write make dependencies: the output depends on the source and every INCLUDE/INCBIN file, each also listed as an empty rule (like gcc -MD -MP). Use with -include in a Makefile.
  • -I, --include <dir> — add a directory to the INCLUDE search path (repeatable). Needed for sources that include the Amiga system headers by their logical path, e.g. include 'exec/types.i'.
  • --optimize — enable size-changing optimizations (see below). Off by default.
  • --pad <size|pow2>, --fill <byte> — pad a binary image to a fixed size ($80000, 512K, 4M) or the next power of two, the way a cartridge or EPROM image fills its chip; the filler is $FF unless --fill says otherwise.
  • --checksum megadrive — write the Mega Drive cartridge checksum (the word sum from $200 to the end) into the header word at $18E, after padding.
  • --linedebug — add source line debug info to a hunk-exe (see below).

Diagnostics

Every error and warning is printed to stderr as file:line: severity: message, located in the file it was written in (an included file is named by its INCLUDE name, a line expanded from a macro carries (in macro name)). Pass 2 keeps going after an error, so one run reports every line it could not encode — the location counter continues at the address pass 1 gave the next line, so later branch distances and symbols stay right. Any error means no output is written and the exit status is 1; a summary line gives the counts.

Stack analysis

--stack-check and --stack-report <file> walk the encoded program routine by routine. A routine is a global label that is called, or that nothing refers to (a reset vector, an exception handler, a table entry); a label that is only ever branched to is a continuation of whoever branches there. Along every path the stack pointer offset from the routine's entry is followed through pushes and pops (-(SP)/(SP)+, MOVEM, PEA, LINK/UNLK, ADDQ/SUBQ/LEA on SP). --stack-check makes these errors: a return or a jump to another routine with the stack off its entry level, or with its height unknown. --stack-report writes one line per routine with its maximum stack depth including everything it calls (>= n when a callee could not be followed, unbounded (a -> b -> a) for recursion), its balance, and notes on where the arithmetic stopped: an indirect call or jump, SP loaded from somewhere (a context switch), two paths meeting at different heights. RTE and RTR are not balance-checked. Declare routines that never return with NORETURN name[,name...], so a call to them ends the path (BSR error_exit as the last instruction before the next routine is assumed not to return even without it). A routine that recurses to a known depth is declared with RECURSES name,n, where n is how many times it is entered again while already active: the report then unrolls its cycle that often and gives a figure instead of unbounded, for it and for everything that calls it. The figure is only as good as the declaration.

--flag-check warns about a TST, CMP or BTST whose condition codes every following path overwrites before any instruction reads them. Calls, returns and indirect jumps count as reads, since the flags may be used there.

Optimization

By default the assembler emits the same encoding a Motorola-syntax assembler produces without optimization:

  • an absolute address is encoded long unless the source writes .W;
  • an unsuffixed branch uses the 16-bit displacement form.

--optimize shortens both where the value fits — an absolute address that fits in 16 bits becomes absolute-short, and a branch in range becomes the 8-bit form. An explicit .W/.L or .S/.B suffix is always honoured and overrides both modes. It also relaxes a JSR/JMP to a label into BSR/BRA and an LEA/PEA of a label into the (d16,PC) form when the label is within 16-bit reach, which saves two bytes and two to four cycles each; a target named by an EQU (which may be hardware) or a program with more than one section is left alone, since a PC-relative reference needs a fixed distance. A run of JMPs is a jump table whose entries are reached by a fixed stride, so its entries keep their size; an explicit suffix (JMP.L sub, JMP sub.L) pins the form of any single instruction.

    MOVE.W  $1234,D0        ; default: 3039 00001234   --optimize: 3038 1234
    MOVE.W  $1234.W,D0      ; always:  3038 1234
    BRA     loop            ; default: 6000 fffc       --optimize: 60fc
    BRA.S   loop            ; always:  60fc
    JSR     sub             ; default: 4eb9 00001000   --optimize: 6100 0ffa
    LEA     table,A0        ; default: 41f9 00001200   --optimize: 41fa 11f8

Syntax notes

The assembler accepts the conventions shared by vasm, Devpac, PhxAss and ASM-One:

  • Local labels — a label starting with . is scoped to the preceding global label, so .loop may repeat once per subroutine. Its qualified name (draw.loop) is a normal symbol, so code outside draw can still branch to it — a second entry point that keeps the routine's local scope.
  • Labels without a colon when written in column 1.
  • * as a comment marker where an operand cannot continue, while keeping its meaning as multiply (WIDTH*HEIGHT) and as the current PC (BRA *, DC.L *+4).
  • IFD/IFND/ENDC as spellings of IFDEF/IFNDEF/ENDIF.
  • Optional macro arguments — an argument the invocation omits substitutes to the empty string, so the usual IFC '\1','' idiom works.
  • Include-once — a file is spliced in at most once per assembly, which is what the IFND FOO_I guards in the Amiga headers are written to achieve.

m68k-asm -f elf output has been checked against readelf -a for structural validity. m68k-asm -f ieee695 output has been checked against a self-built GNU binutils ieee BFD reader (objdump -b ieee -m m68k) — see crates/m68k-asm/src/ieee695.rs's module docs for details. m68k-asm -f hunk-exe output has been checked against a real AmigaOS-target objdump (m68k-amigaos-objdump -t -D, format amiga) and round-trips through this project's own Hunk reader (m68k_core::amiga_hunk, also used by m68k-disasm to load Amiga executables directly).

-f elf, -f ieee695, and -f hunk-exe emit one section/hunk per non-empty SECTION in the source. The ELF and IEEE-695 writers resolve all symbols to absolute addresses and emit no relocation entries.

hunk-exe output is a directly loadable executable, not a relinkable object file. It carries a HUNK_RELOC32 table, so every 32-bit absolute address (LEA label,A0, MOVE.L #label,D0, DC.L label) is patched to wherever LoadSeg() places each hunk. An address in a smaller field (MOVE.W #label,D0) or a scaled one (#label*2) cannot be relocated and is reported as an error with its line. A _C/_F type suffix (SECTION gfx,DATA_C) or a CHIP/FAST argument (SECTION buf,BSS,FAST) sets the hunk's memory requirement, so bitplanes and samples land in chip RAM. --linedebug adds LINE debug hunks that map addresses back to source lines for debuggers; they embed absolute source paths, so leave the option off for release builds.

prg output is an Atari ST / TOS program (.PRG, .TOS, .TTP, .ACC are the same format): the text, data and bss sections laid out back to back, as GEMDOS loads them, followed by a DRI symbol table (every label, with names longer than 8 characters in the GST extended form that holds 22) and a relocation table so the program can be loaded at any address. The same rule as for hunk-exe applies: only full 32-bit address fields can be relocated. Named sections are not allowed.

System includes

include/ holds hardware maps and OS interfaces for the systems the assembler is used for, and examples/ a minimal program for each. Both ship with the release archives; pass the include directory with -I:

Directory Contents
megadrive/hardware.i Sega Mega Drive / Genesis: memory map, cartridge header offsets, VDP registers and access codes, Z80 bus, YM2612, I/O ports, TMSS; VDP_SETREG/VDP_SETADDR macros
neogeo/hardware.i SNK Neo Geo: memory map, cartridge header, system and LSPC registers, VRAM layout, BIOS calls and BIOS RAM, controller bits
atarist/hardware.i Atari ST/STE: shifter, DMA, YM2149, STE sound, blitter, MFP, ACIAs, system variables
atarist/tos.i GEMDOS, BIOS and XBIOS function numbers; GEMDOS/BIOS/XBIOS macros
m68k-asm -I include -f binary --pad pow2 --checksum megadrive -o hello.bin examples/megadrive/hello.s
m68k-asm -I include -f prg -o hello.prg examples/atarist/hello.s

The Amiga system headers are not included; Commodore's own Include directory is used with -I as before.

Supported Directives

Directive Description
org <addr> Set origin address
equ <expr> Define constant
dc.b/w/l Define byte/word/long data. A value must fit its size (signed or unsigned). In dc.b a quoted literal is a byte string ('it''s' embeds a quote); in dc.w/dc.l it is a character constant ('ab' = $6162). Word and long data at an odd address draws a warning.
dc.s/d/x Define single/double/extended float
dc.p Define packed decimal (raw hex)
ds.b/w/l Define storage space
even Align to word boundary
align <n> Align to n-byte boundary
include "file" Include external source file
incbin "file" Include binary file
macro / endm Define macros with arguments
noreturn sym[,sym...] Declare routines that never return (stack analysis)
recurses sym,n Declare a routine re-entered at most n times while active (stack analysis)
rept <count> / endm Repeat block
section <name> Define named sections

Library usage

m68k-asm is usable as a Rust library, not just a CLI binary — see the crate docs (cargo doc --open -p m68k-asm) for runnable examples, starting with m68k_asm::assembler::Assembler.


Floppy Disk Support

Read Amiga floppy disk images (ADF, IPF, UAE extended ADF) and Atari ST images (ST, MSA), and disassemble directly:

m68k-disasm --bootblock --org 0xF80000 roms/game.adf
m68k-disasm --sector 0 0 0 --org 0xF80000 roms/game.adf
m68k-floppy --bootblock roms/game.adf > bootblock.bin

Supported Formats

Format Backend Description
Standard ADF adf 80 tracks, 2 sides, 11 sectors (DD)
Extended ADF adf Larger images with more sectors per track
UAE-0/1ADF uae Raw MFM bitstream per track (copy-protected disks)
IPF native Clean-room reader for SPS/CAPS IPF images: record CRCs checked, track element streams rebuilt to MFM and decoded
Atari ST .st st Raw sector dump; geometry from the boot sector, else from the size
Atari ST .msa msa Magic Shadow Archiver, decompressed on reading

FAT12 filesystem (Atari ST)

--list, --list-all, --extract and --extract-all work on FAT12 disks as well, which is what the boot sector of an Atari ST (or PC) floppy describes; the filesystem is chosen by the boot sector, so a FAT-formatted .adf is read the same way. Paths may use / or \ and are matched without regard to case.

m68k-floppy game.st --list-all
m68k-floppy game.msa --extract AUTO/BOOT.PRG -o boot.prg

The writing options below work on a .st image too: --format on a path ending in .st creates an empty 720 KiB double-sided FAT12 disk (non-bootable), and --add-file, --delete-file, --make-dir, --delete-dir and --rename edit whichever filesystem the boot sector announces. Names are stored in 8.3 form; --set-comment and --set-protection have no FAT12 counterpart and are refused. An .msa archive cannot be written back; convert it to .st first.

m68k-floppy disk.st --format DISK --make-dir AUTO --add-file hello.prg AUTO/HELLO.PRG
m68k-floppy disk.st --add-file readme.txt README.TXT --delete-file AUTO/HELLO.PRG

AmigaDOS filesystem (OFS/FFS)

m68k-floppy reads the filesystem on a disk image, at any directory depth — paths are slash-separated and matched case-insensitively:

m68k-floppy disk.adf --list                     # root directory
m68k-floppy disk.adf --list C                   # one subdirectory
m68k-floppy disk.adf --list-all                 # whole tree, full paths
m68k-floppy disk.adf --extract C/List -o List   # one file, by path
m68k-floppy disk.adf --extract-all ./out        # everything, tree preserved
m68k-floppy disk.adf --fix-bootblock            # repair bootblock checksum

Verified against all eight Workbench 1.3 and 3.1 disks: 981 files extract at their exact recorded length. Writing to a filesystem is not supported — adf_writer can create empty, mountable OFS/FFS images and repair bootblock checksums, but file creation is not implemented.


Running Tests

cargo test --all --verbose
cargo clippy --all-targets -- -D warnings
cargo fmt --all -- --check

The disassembler's reach on a real Kickstart ROM (instructions found by a linear scan, by control-flow tracing from the reset vector, and with pointer table scanning) is guarded by an ignored test; run it with a ROM at hand: M68K_ROM=tmp/<rom> cargo test -p m68k-disasm --test rom_reach -- --ignored --nocapture.

The listing is also required to reassemble to the input: m68k-disasm --source on a Kickstart ROM, fed to m68k-asm, must give back the ROM byte for byte. Every encoding the decoder accepts must therefore be one the assembler produces, so opwords no assembler emits (a byte operation on an address register, a byte immediate with its high byte set, a branch to an odd address, an empty MOVEM list, a write to a PC-relative operand) are data. The same ignored test exists for this property: M68K_ROM=tmp/<rom> cargo test -p m68k-cli --test rom_roundtrip -- --ignored --nocapture.

The Amiga example (examples/amiga/hello.s) is also run as a Hunk executable under vamos from amitools, which implements LoadSeg() and the dos.library calls the program makes on a 68k core; it has to print its line. Ignored as well, since vamos must be installed: cargo test -p m68k-cli --test vamos_examples -- --ignored --nocapture.

Golden-vector tests (crates/m68k-asm/tests/golden_*.rs) check encoder, decoder, float, expression, and token behavior against fixed reference output in tests/golden/vectors.json.

About

A robust, modular, and fast two-pass assembler and disassembler for the Motorola 68000 (m68k) family of processors, written in Rust. It supports instructions from the base 68000 up to the 68060, as well as the 68881/68882 Floating Point Unit (FPU) and MMU coprocessor instructions.

Resources

Code of conduct

Contributing

Security policy

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages