🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.lang.forth
Article #227

writing an AVR disassembler

#227
From: Ivan Shmakov
Date: Sun, 15 Nov 2026 22:55
304 lines
11734 bytes
	I've decided to write an AVR disassembler in Forth, and while
	I'm reasonably confident that I do most of the actual decoding
	correctly by now, I'm much less confident of my, so to say,
	"design choices," and would appreciate constructive criticism
	on that matter.

	Two important points to stress out:

	 a. my first experience with Forth dates back to c. 1994, but
	    so far as I can recall, this is the first substantial code
	    that I ever wrote in the language; as such, I may miss any
	    number of common Forth coding (and formatting) idioms;
	    in this effort, I /am/ familiarizing myself with the AVR
	    machine code, but also with Forth itself, particularly
	    with the development of complex applications in it;

	 b. ultimately, I intend for the code to run on an AVR MCU
	    itself, on a suitable Forth system running there; I frankly
	    doubt a fully-featured ANS Forth implementation makes sense
	    on a 8-bit architecture, hence I expect something like cmForth
	    or Pygmy Forth there instead; for now, though, I use pForth,
	    which is described as "ANS-like"; (in particular, I treat my
	    cells as if they were 16 bit wide, though they are in fact
	    either 32 bit or 64 bit in the builds pForth I have handy.)

	I prefix all the words of the disassembler proper with "DISA",
	though for testing, I use several additional words not so
	prefixed.  Such as the words that "hex" memory and "unhex"
	strings (note that $ is a word, not a prefix, in pForth):

1 CELLS .
VARIABLE DUMORG  0 DUMORG !
: DUMX ( a - a' )
    ( Dump $ 10 bytes from a in HEX; return a + $ 10 )
    BASE @ >R HEX
    CR DUP DUMORG @ - 4 U.R
    3 SPACES
    $ 10 0 DO SPACE DUP C@ 2 U.R 1+ LOOP
    R> BASE ! ;
: DU ( a n - )
    ( Dump n lines $ 10 bytes each from a in HEX )
    0 DO DUMX LOOP DROP ;
: 2C@ ( a - c0 c1 )
    ( Fetch two characters from a )
    DUP C@ SWAP 1+ C@ ;
: UNNIBBLE ( c - n )
    ( Convert a hex digit character into a number )
    [CHAR] 0 2DUP [CHAR] 9 BETWEEN IF - EXIT THEN DROP
    [CHAR] A 2DUP [CHAR] F BETWEEN IF - $ A + EXIT THEN DROP
    [CHAR] a 2DUP [CHAR] f BETWEEN IF - $ A + EXIT THEN DROP
    ABORT" character not in the 0-9a-fA-F range" ;
: UNX- ( from len to - to' )
    ( Unhex a from, len string into memory at to )
    BEGIN OVER 2 >= WHILE
        ROT ( len to from )
        DUP 2C@ UNNIBBLE SWAP UNNIBBLE 4 LSHIFT OR
        ( len to from n ) 2 PICK C!
        ( len to from ) 2+ ROT 2- ROT 1+
        ( from len to ) REPEAT
    ( from len to ) NIP NIP ;
: UNX ( from len to - ) ( like PLACE )
    UNX- DROP ;

	(As usual, I prefix the prose of my post with a TAB code,
	so if you filter out lines like that, you can run the body
	of this article as a program in pForth.)

	I /think/ that UNNIBBLE in particular can be made simpler,
	but it's not obvious to me how.  (Or do I just use some
	built-in word here instead?)

	An example of how the above is used:

CREATE EXAMPLE
EXAMPLE DUP
   " 05c000000000000000002ec0002708bb" COUNT ROT UNX-
   " 0ce107bb02e003bf02e009bf97ee8ce4" COUNT ROT UNX-
   " aa249924789400e205bfaa2029f4bb24" COUNT ROT UNX-
   " b094a82eaa2071f0b3948894a79410f0" COUNT ROT UNX-
   " b1f3facf3b2d330f330f3c7108b3037e" COUNT ROT UNX-
   " 032b08bb00e8901628f0901a082f0795" COUNT ROT UNX-
   " 979587958895e1cf1fb693941fbe1895" COUNT ROT UNX-
OVER - ALLOT
HERE CONSTANT EXAMPLE-END ( will need this later )
DUP DUMORG !
7 DU

	Expected output:

	   0     5 C0  0  0  0  0  0  0  0  0 2E C0  0 27  8 BB
	  10     C E1  7 BB  2 E0  3 BF  2 E0  9 BF 97 EE 8C E4
	  20    AA 24 99 24 78 94  0 E2  5 BF AA 20 29 F4 BB 24
	  30    B0 94 A8 2E AA 20 71 F0 B3 94 88 94 A7 94 10 F0
	  40    B1 F3 FA CF 3B 2D 33  F 33  F 3C 71  8 B3  3 7E
	  50     3 2B  8 BB  0 E8 90 16 28 F0 90 1A  8 2F  7 95
	  60    97 95 87 95 88 95 E1 CF 1F B6 93 94 1F BE 18 95

	Now as to disassembler proper.  I'm not going to include the
	entire source here - just the parts that decode opcodes in
	the 0000 .. 2FFF and B000 .. BFFF ranges, as I believe they're
	representative of the approach I follow.

( F E D C B A 9 8 7 6 5 4 3 2 1 0 )
( . . . . . . . [   d   ] . . . . )
: DISA/RD ( opc - d )
    ( Extract destination register from an opcode )
    4 RSHIFT $ 1F AND ;

: DISA-TYOP ( num base stride - )
    ( Type a string number num out of a string table at base )
    ROT ( base stride num )
    OVER * ( base stride offset ) ROT + 1+ SWAP TYPE ;

( NB: we reserve DISA_ prefix for words of this signature )
: DISA_UNK ( op - )
    ( Type raw opcode in hex - used if decoding fails )
    ." ?" BASE @ HEX SWAP 1 U.R BASE ! ;

( 0000 : NOP )
: DISA_NOP ( op - )
    ?DUP IF DISA_UNK EXIT THEN
    ." NOP" ;

( 01.. : MOVW Rd, Rr )
( F E D C B A 9 8 7 6 5 4 3 2 1 0 )
( 0 0 0 0 0 0 0 1 [  d  ] [  r  ] )
: DISA_MOVW ( op - )
    ." MOVW   r" DUP 3 RSHIFT $ 1E AND 1 U.R
    ." , r" $ F AND 1 LSHIFT 1 U.R ;

	Conventionally, I'd need to ensure I print all registers in
	decimal (like MOVW r8, r30) - regardless of BASE.  I've decided
	/not/ to do that for the sake of simplicity of the code.

( 02.. : MULS Rd, Rr )
( F E D C B A 9 8 7 6 5 4 3 2 1 0 )
( 0 0 0 0 0 0 1 0 [  d  ] [  r  ] )
: DISA_MULS ( op - )
    ." MULS   r" DUP DISA/RD $ 10 OR 1 U.R
    ." , r" $ F AND $ 10 OR 1 U.R ;

( 03.. : F?MULS?U? Rd, Rr )
( Elided )

( 0400 .. 2FFF : op Rd, Rr )
( F E D C B A 9 8 7 6 5 4 3 2 1 0 )
( 0 0 [ opc ] r^[   d   ] [  r  ]   opc != 0 )
CREATE DISA~RR  ," CPC SBC ADD CPSECP  SUB ADC AND EOR OR  MOV "
: DISA-RR ( pc op - )
    NIP ( pc not needed )
    DUP $ A RSHIFT 1-     DISA~RR 4 DISA-TYOP
    ( we get Rd with an RSHIFT , getting Rr is harder )
    3 SPACES DUP 4 RSHIFT
    ( op op-rsh-4 ) DUP $ 1F AND ." r" 1 U.R
    ( op op-rsh-4 ) ." , r" 1 RSHIFT $ 10 AND
    ( op op-rr-hi ) SWAP $ F AND OR 1 U.R ;

( Test it:       PC   opcode )
CR ." ADD   " $ 544E $ 0DB9 DISA-RR

	Expected output (in DECIMAL and HEX):

	ADD   ADD    r27, r9
	ADD   ADD    r1B, r9

	The program counter value is not used here, but is needed to
	print absolute addresses in instructions that take relative
	ones as operands - such as RJMP and RCALL.

( 0... : Miscellaneous opcodes with 0 in the MSN )
( F E D C B A 9 8 7 6 5 4 3 2 1 0 )
( 0 0 0 0 [x] [y] )
CREATE DISA-0TAB
    ' DISA_NOP , ' DISA_MOVW , ' DISA_MULS , ' DISA_UNK ,
: DISA-0 ( pc op - )
    ( Call DISA-RR iff the opcode is within  0400 .. 0FFF )
    DUP $ C00 AND IF ( x != 0 ) DISA-RR EXIT THEN
    ( Call one of DISA-0TAB words otherwise: 0000 .. 03FF )
    NIP ( pc not needed )
    DUP $ 8 RSHIFT 3 AND ( op y ) CELLS
    ( op off ) DISA-0TAB + @ EXECUTE ;

( Test it:       PC   opcode )
CR ." ADD   " $ 544E $ 0DB9 DISA-0
CR ." NOP   " $ E58C $    0 DISA-0
CR ." ?     " $ E58C $   23 DISA-0
CR ." MULS  " $ DD8E $ 02DF DISA-0
CR ." FMULS " $ D1E2 $ 03E4 DISA-0

	Expected output (in DECIMAL):

	ADD   ADD    r27, r9
	NOP   NOP
	?     ?23
	MULS  MULS   r29, r31
	FMULS ?3E4

	Note that FMULS was not decoded as the respective entry
	in DISA-0TAB was dummied out with ' DISA_UNK.  (And as the
	respective DISA_FMULSU word was elided from this post.)

	The above is relatively straightforward.  Printing the
	disassembled IN Rd, A and OUT A, Rr instructions is a tad
	more involved, and we need branching rather than just
	printing a string from some DISA~IO table:

( B... : IN Rd, A and OUT A, Rr )
( F E D C B A 9 8 7 6 5 4 3 2 1 0 )
( 1 0 1 1 o [A^][  r/d  ] [  A  ] )
: DISA-IO
    NIP ( pc not needed )
    DUP DISA/RD ( op r# )
    OVER DUP $ F AND SWAP 5 RSHIFT $ 30 AND OR
    ( op r# a ) ROT $ 800 AND ( r# a out? )
    IF   ." OUT    "  1 U.R ." , r"
    ELSE SWAP   ( a r# )
         ." IN     r" 1 U.R ." , "
    THEN 1 U.R ;

	And decoding instructions with 9 in the MSN is perhaps the
	single most complex part of the code, as that range includes
	such diverse ones as: COM Rd; SBIC A, b; BSET s; and RET.

	It /seems/ that I've nailed much of it down, but I'm frankly
	way less sure of that code right now, so not going to include
	it here.

	Now we can tie the above into the "top-level" disassembly words.

: DISA-UNK ( pc op - )
    NIP DISA_UNK ;
CREATE DISATAB
( 0 )       ' DISA-0 ,
( 1 .. 3 )  ' DISA-RR  DUP , , ' DISA-UNK DUP ,
( 4 .. 7 )       DUP , DUP , DUP , DUP ,
( 8 .. B )       DUP , DUP , DUP , ' DISA-IO ,
( C .. F )       DUP , DUP , DUP , ,
: DISA-W ( pc op - )
    ( Disassemble a single 16-bit "word" instruction )
    OVER 7 U.R SPACE
    DUP  7 U.R SPACE
    DUP $ C RSHIFT $ F AND CELLS DISATAB +
    ( pc op addr ) @ EXECUTE ;
: DISA@ ( a - op )
    ( Fetch an instruction at a Forth address )
    2C@ $ 8 LSHIFT OR ;
VARIABLE DISAORG  0 DISAORG !
: DISA- ( a - a' )
    ( Disassemble an instruction at a Forth address )
    DUP DISA@ ( a op )
    ( DUP DISA/WI ) 2 ( a op oct )
    ROT ( op oct a )
    SWAP 2DUP + ( op a oct a' )
    >R -ROT ( oct op a | a' )
    DISAORG @ - ROT ( op pc oct | a' )
    2 = IF SWAP DISA-W
        ELSE ( FIXME: implement 4-octet instructions ) THEN
    R> CR ;
: DISA ( from to - )
    ( Disassemble a memory region )
    BEGIN ( to a ) 2DUP > WHILE DISA- REPEAT
    2DROP ;

( Test it )
HEX
CR EXAMPLE-END EXAMPLE DUP DISAORG ! DISA

	Expected output, or at least the interesting parts of it
	(much of the EXAMPLE uses instructions not decoded by this
	abridged version of the code):

	      0    C005 ?C005
	      2       0 NOP
	      4       0 NOP
	      6       0 NOP
	      8       0 NOP
	      A    C02E ?C02E
	      C    2700 EOR    r10, r10
	      E    BB08 OUT    18, r10
	...
	     68    B61F IN     r1, 3F
	     6A    9493 ?9493
	     6C    BE1F OUT    3F, r1
	     6E    9518 ?9518

	Note that the "AVR Instruction Set Manual", be it [1] or [2],
	provides a terse "CLR Rd" alias for "EOR Rd, Rd".  Yet again,
	for the sake of simplicity, I don't plan implementing shortcuts
	like that in this disassembler.

	(The initial six words are effectively interrupt vectors:
	C005 is RJMP +5, or 000C, for "power up or reset"; and
	C02E is RJMP +2E, or 0068, for a timer/counter overflow.
	3F is the status, or flag, register, AKA "SREG" - it gets
	saved in r1, otherwise reserved in this code, for the
	duration of the ISR.  9493 is INC r9, and 9518 is RETI.)

	That would be all for now.  Thoughts?

	[1] http://web.archive.org/web/20160411235033
	    /http://www.atmel.com/images/Atmel-0856
	    -AVR-Instruction-Set-Manual.pdf
	[2] http://ww1.microchip.com/downloads/en/DeviceDoc
	    /AVR-InstructionSet-Manual-DS40002198.pdf
Technical Details
Message-ID: <UOSz15Vn9V7SG_X-@violet.siamics.net>
Path: mbox-mo1.pugleaf.net!news-lax.pugleaf.net!srl.newsdeef.eu!news.hispagatos.org!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!.POSTED!not-for-mail

Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!news-lax.pugleaf.net!srl.newsdeef.eu!news.hispagatos.org!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!.POSTED!not-for-mail
From: Ivan Shmakov <ivan@siamics.netREMOVE.invalid>
Newsgroups: comp.lang.forth
Subject: writing an AVR disassembler
Date: Sun, 15 Nov 2026 22:55:25 +0000
Organization: Dbus-free station.
Lines: 304
Message-ID: <UOSz15Vn9V7SG_X-@violet.siamics.net>
Injection-Date: Sun, 15 Nov 2026 23:00:50 +0000 (UTC)
Injection-Info: dont-email.me;
	logging-data="3314349"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX1/FGQGH8MKfh0X4vTHk4arq"; posting-host="9354f853c633b1388e4a10d9b752ed3f"
Cancel-Lock: sha1:H/4JYo8DYl5rXG5+DxDV8Cs6Lxo= sha256:sVUo3D+LyaaZ3j9OfynjyrCN8qHeKHJhnAnKczgzwFw=
	sha1:R+TFuunJkTcIHlo0+HMmgbBu3cw= sha256:bv9Ml+i9vhD56mEZ2+NO3K5NuBw2oAf9IlQ7o0CBARg=
License: CC0-1.0 (original contributions only)