TweetFollow Us on Twitter

Forth Decompiler
Volume Number:1
Issue Number:2
Column Tag:Forth Forum

“A Forth Decompiler”

By Joerg Langowski

“A Forth Decompiler”

Everyone of you Mac Forth users is familiar enough with Forth to know that it is a ‘threaded interpretive’ language. A Forth definition (as you type it into your machine) consists of a string of other, previously defined Forth words, and is compiled as a string of addresses that point to the definitions of these other words.

This makes for a rather fast interpretation of the resulting code. However, some of the very primitive words and those words whose execution is time-critical may also be defined in machine language. MacForth has devised a very elegant way to distinguish between Forth words defined from within Forth and machine code.

Structure of a Forth Definition

The object code of any Forth word, as it is compiled into the object dictionary, starts with at least one 16-bit word that is a meaningful executable 68000 machine language instruction. When the Forth word is executed, the interpreter simply jumps to this address. Forth definitions (colon definitions, constants, variables) now start with one of the 68000 TRAP instructions ($4E4X, where X can be anything from $0 to $F). The corresponding trap vector points to a routine which e.g. in the case of a colon definition gets the next 16-bit word and interprets it as a Forth token (converts it to an address and executes it), or - in the case of a variable - puts the address of the variable on the stack.

If the word is defined completely in machine language, the code is executed until a special JMP instruction transfers control to the next higher level (I’ll describe that later).

At this point I have to confess that I would not have come even this far if it had not been for two excellent routines that I found on a CALL-A.P.P.L.E. public domain disk. One of those - a Forth decompiler - is included below so that you can enjoy hacking into the Forth engine, the other one - a disassembler - was too long to be printed here.

An Example

Admittedly, part of the above sounds a bit dry and theoretical. Lets look at a simple example.

Assume you had defined the word TEST as follows:


The Forth compiler will then create a list of 16-bit words that looks like:

 $4E4F  (trap for colon definition)
 $0498  (Forth token for DUP    )
 $074E  (   “          “     “   2*     )
 $049C  (   “          “     “   SWAP)
 $00EC  (   “          “     “   DROP )
 $0EBE  (   “          “     “    .     )
 $0060      (   “          “     “  EXIT  )

Interpretation always ends at the EXIT token.


What are those ‘tokens’? They are the starting addresses of the Forth definitions that are offset by a constant that is contained in register A4 (probably to make the object code relocatable). There is a word in MacForth that converts a token to an address, TOKEN>ADDR. The token of a word is extracted from the vocabulary by the Forth word, FIND. Therefore, you will get the starting address of the example above by executing


The address that you’ll see displayed, of course, depends on how much object code you have already in your system. Let’s call this number TESTADDR. Then define the following word:

 :  TEST.DISP  7 0 DO I 2* TESTADDR ( insert your # here) + W@ . LOOP 

and execute TEST.DISP; you will see the list of words above.

This way you can decompile any Forth word that you find in the system. The decompiler is somewhat more convenient, of course; if you use the procedure above, you still have to convert the tokens into Forth words. This is done (for one token on the stack) by executing


This converts the token (not the pfa, as the Forth 1.1 manual says) into the name field address (NFA) and then displays the name of the word (ID.).

Machine language definitions

What if the definition is direct machine language code? Again, let us look at an example, the word SWAP. FIND SWAP TOKEN>ADDR gives (in my system) $5B60. At this address, however, we find code that does not start with a trap statement; it is a routine that does what we expect:

 202F 0004MOVE.L 4(A7),D0    /move item below top -> D0
 2F57 0004MOVE.L (A7),4(A7) /move top item one down
 2E80   MOVE.L D0,(A7)       /move D0 -> top of stack
 4ED4   JMP (A4)                  
/get next token

We see that indeed the two top stack items are exchanged. The last statement is the end of any machine language Forth definition. This jump to the address in A4 is what I briefly mentioned above. A4 contains the address of a routine that gets and executes the next Forth token from the object code (which A3 points to):

 MOVE (A3)+,D0 
/next object token -> D0
 BMI L1 
/is it neg. get address from token table
 JMP (A4,D0.W) 
/jump to start of definition (token + A4)
L1 MOVE(A4,D0.W),D1
/get address from table
 JMP (A4,D1.W) 
/and jump to start of definition

Hidden definitions

When you decompile (with the program below) the word SELECT.WINDOW, you’ll see something funny. It seems to be a regular Forth colon definition; however, the tokens displayed seem to have no name. Only ??? and the token numbers are displayed. These are tokens whose names have been deleted from the vocabulary, but their corresponding addresses (A4+token) point to valid definitions. The reason why CSI did this is probably to keep the vocabulary short and to make words inaccessible to users whose misuse could have a disasterous effect on the system. Anyway, the word SUBLEVEL in the definitions below will decompile and display any such ‘hidden’ code, if it is a colon definition. It will display nothing for machine code definitions, you have to disassemble them.

SELECT.WINDOW, with this tool, then becomes very clear. Its first level definition looks like:

: SELECT.WINDOW {2142} {1B0E}  ;

where the braces indicate those ‘no-name’ tokens. {2142} merely checks if the pointer on the stack is a valid window pointer, to keep the toolbox routine from crashing; decompile it with SUBLEVEL to see what it does exactly. {1B0E} is a 2-word machine code routine:

/toolbox trap for SELECT.WINDOW
 JMP (A4) 
/and get next word. That’s all!

Listing 1: Forth decompiler
( DECOMPILER Blocks File -- Version 1.00 )        ( ADG - modif. 110384 
jl ) 
 DECOMP  ( -- )                                                 
Decompiles the definition of the next word in the input stream.  A line 
is displayed for each word in the definition. Each line begins with its 
relative code address in hex.  Next is the name of the word.  Finally, 
if the word has an in-line parameter, it is shown.  If the word is a 
branching word, the value is the target address.  If the parameter is 
a token, its name is shown.  If it is a string, the string is shown in 
double-quotes.  If it is a word or double-word, its hex value is followed 
by its decimal value.                            
#DECOMP in block 8 can also be loaded by those who wish to write a routine 
to pass tokens on the stack to be decompiled. For valid tokens, its output 
is identical to that of DECOMP .
 Written: 07/21/84   By: Alan D. Galumbeck  [70220,200]         

        : .DIGITS  ( n1\n2 --  | Types the low-order n2 digits of n1 
)  0 <# DO # LOOP #> TYPE ;          : SPACE.TO  ( n -- | Spaces to column 
n or 2 spaces if past n ) COL @ - 2 MAX SPACES ;               : DISP.WORD 
   ( pfa -- pfa+2 | Display a 16-bit parameter)     
: DISP.DBL     ( pfa -- pfa+4 | Display a 32-bit parameter )    
: DISP.STRING  ( pfa -- pfa+len | Display a string parameter )  
  34 EMIT COUNT 2DUP TYPE 34 EMIT + =CELLS ;                    
: DISP.TARGET  ( base.pfa\pfa -- base.pfa\pfa+2 )               
  ( Display a branch target and save if it’s the highest )      
  2DUP SWAP - OVER <W@ + . 2+ ;                                 
: DISP.TOKEN   ( pfa -- pfa+2 | Display a token parameter)      
  DUP W@ NFA ?DUP  IF ID.  ELSE DUP W@ 4 .DIGITS  THEN  2+ ;    
: DISP.ADDR  ( pfa -- pfa+4 | Display an address parameter )    
: SPECIAL.TOKENS ( base.pfa\pfa\token -- [base.pfa\next.pfa] or 
                                         [base.pfa\next.pfa\0] )
  ( Handle in-line parameters and terminating words )           
  CASE  TOKEN.FOR  EXIT       OF        0                  ENDOF
        TOKEN.FOR  (;CODE@)   OF        DISP.TOKEN 0       ENDOF
        TOKEN.FOR  COMPILE    OF        DISP.TOKEN         ENDOF
        TOKEN.FOR  0BRANCH    OF        DISP.TARGET        ENDOF
        TOKEN.FOR  BRANCH     OF        DISP.TARGET        ENDOF
        TOKEN.FOR  (OF)       OF        DISP.TARGET        ENDOF
        TOKEN.FOR  (LOOP)     OF        DISP.TARGET        ENDOF
        TOKEN.FOR  (+LOOP)    OF        DISP.TARGET        ENDOF
        TOKEN.FOR  ALIT       OF        DISP.ADDR          ENDOF
        TOKEN.FOR  WLIT       OF        DISP.WORD          ENDOF
        TOKEN.FOR  LIT        OF        DISP.DBL           ENDOF
        TOKEN.FOR  (.”)       OF        DISP.STRING        ENDOF
        TOKEN.FOR  ($LIT)     OF        DISP.STRING        ENDOF
        TOKEN.FOR  (ERROR”)   OF        DISP.STRING        ENDOF
        TOKEN.FOR  (ABORT”)   OF        DISP.STRING        ENDOF
        TOKEN.FOR  $ADDR      OF        DISP.STRING        ENDOF
        ( Insert the ones I’ve missed here. )                   
        0                     OF        2 - DISP.TOKEN     ENDOF

: DECODE.TOKENS  ( pfa --  | Display the words starting at pfa )
  DUP HIGH.PFA ! DUP                                            
      IF    ID.    ELSE .” ???” drop 0  THEN                         
      20 SPACE.TO SPECIAL.TOKENS ?DUP                           
      IF    FALSE  ELSE  DUP HIGH.PFA @ > THEN                       
  2DROP ;                                                       

: .VALUE  ( n1\n2 --  | Display constants and UA variables )    
  HEX .DIGITS .”  hex  “ DECIMAL . .” decimal )”  ;             
: DECODE.VECTOR  ( pfa\vector -- | Display definition type )    
    11 OF .” User Area variable ( Offset = “ W@ DUP 4  .VALUE  ENDOF
    12 OF .” 16 bit constant ( Value = “ <W@ DUP 4 .VALUE  ENDOF
    13 OF .” 32 bit constant ( Value = “ @ DUP 8 .VALUE   ENDOF
    14 OF .” Variable, array, or string” DROP              ENDOF
    15 OF .” Colon definition” DECODE.TOKENS               ENDOF
    .” Unknown code type ( Vector = “ 2 .VALUE .” )”            
  ENDCASE ;                                                     
: CHK.CODE.TYPE  ( token -- [pfa\vector\true] or [false] |      
   Returns false for machine code definitions, true for others )
   TOKEN>ADDR DUP 2+ SWAP W@ DUP 16/ 1252 = 
   IF 15 AND TRUE ELSE 2DROP FALSE THEN ;                     
 ( Note: 1252 is the machine code for a 68000 TRAP instruction  
         divided by 16.  Vector is the low-order four bits of   
         the TRAP instruction. )                                
: sublevel chk.code.type if drop decode.tokens then ;           
: DECOMP  ( --  | Decompile the next word in the input stream ) 
  +FIND CR POCKET COUNT TYPE .”  -- “                           
        IF .” IMMEDIATE “ THEN                                  
        CHK.CODE.TYPE IF DECODE.VECTOR ELSE .” Machine code definition” 
     ELSE .” Not in dictionary” THEN                            
  BASE !  TEXTSIZE  LINE.HEIGHT  CR ;                           
: #DECOMP ( token --  | Decompile word whose token is supplied )
  9 TEXTSIZE  10 LINE.HEIGHT NFA ?DUP CR                        
     IF DUP ID.  .” -- “ C@ 128 AND                              
        IF .” IMMEDIATE “ THEN                                  
        CHK.CODE.TYPE  IF DECODE.VECTOR  ELSE .” Machine code definition” 
     ELSE HEX 4 .DIGITS .” -- Not a valid token” THEN           
  TEXTSIZE  LINE.HEIGHT  BASE !  DROP  CR ;                     


Community Search:
MacTech Search:

Software Updates via MacUpdate

MacUpdate Desktop 6.0.8 - Search and ins...
MacUpdate Desktop 6 brings seamless 1-click installs and version updates to your Mac. With a free MacUpdate account and MacUpdate Desktop 6, Mac users can now install almost any Mac app on macupdate.... Read more
BitTorrent Sync 2.1.1 - Sync files secur...
BitTorrent Sync allows you to sync unlimited files between your own devices, or share a folder with friends and family to automatically sync anything. File transfers are encrypted. Your information... Read more
Quicksilver 1.3.0 - Application launcher...
Quicksilver is a light, fast and free Mac application that gives you the power to control your Mac with keystrokes alone. Quicksilver allows you to find what you need quickly and easily, then act... Read more
iWatermark Pro 1.72 - Easily add waterma...
iWatermark Pro is the essential watermarking app for professional, business, and personal use. iWatermark, is the number 1 and only watermarking tool available for all 4 platforms iPhone/iPad, Mac,... Read more
RapidWeaver 6.3 - Create template-based...
RapidWeaver is a next-generation Web design application to help you easily create professional-looking Web sites in minutes. No knowledge of complex code is required, RapidWeaver will take care of... Read more
Adobe Photoshop CC 2015 16.0.1 - Profess...
Photoshop CC 2015 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous Photoshop customer). Photoshop CS6 is still available for purchase (... Read more
Together 3.4.6 - Store and organize all...
Together helps you organize your Mac, giving you the ability to store, edit and preview your files in a single clean, uncluttered interface. Smart storage. With simple drag-and-drop functionality,... Read more
Monosnap 3.1.0 - Versatile screenshot ut...
Monosnap lets you capture screenshots, share files, and record video and .gifs! Capture: Capture full screen, just part of the screen, or a selected window Make your crop area pixel perfect with... Read more
Cocktail 8.5.1 - General maintenance and...
Cocktail is a general purpose utility for OS X that lets you clean, repair and optimize your Mac. It is a powerful digital toolset that helps hundreds of thousands of Mac users around the world get... Read more
Vienna 3.0.6 :5eaf312: - RSS and Atom ne...
Vienna is a freeware and Open-Source RSS/Atom newsreader with article storage and management via a SQLite database, written in Objective-C and Cocoa, for the OS X operating system. It provides... Read more

Five Nights at Freddy's 4 has Been...
In keeping with tradition, Five Nights at Freddy's 4 has made its way to the App Store with zero warning fanfare. Honestly I'd be disappointed it if happened any other way at this point. [Read more] | Read more »
Doom & Destiny Advanced (Games)
Doom & Destiny Advanced Device: iOS Universal Category: Games Price: $.99, Version: (iTunes) Description: ---SUPER GIGA LAUNCH DISCOUNT! Get it now for cheap or pay more later!---An additional 143 MB download is... | Read more »
Five Nights at Freddys 4 (Games)
Five Nights at Freddys 4 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: This time, the terror has followed you home. | Read more »
This Week at 148Apps: July 27-31, 2015
Winding Down July With 148Apps How do you know what apps are worth your time and money? Just look to the review team at 148Apps. We sort through the chaos and find the apps you're looking for. The ones we love become Editor’s Choice, standing out... | Read more »
You'll Want to Keep an Eye Out for...
If you're the kind of person who had fun hunting down and completing all the codex puzzles in Assassin's Creed 2, then are you ever in for a treat. The Guides looks like it's going to be a very robust collection of similarily odd, seemingly... | Read more »
Vivid Games has Announced Real Boxing 2...
The original Real Boxing was a pretty impressive bit of fisticuffs, but if the trailer Vivid Games is showing off for GamesCom is any indication Real Boxing 2 is going to be even better. [Read more] | Read more »
PAC-MAN Championship Edition DX - Tips,...
[Read more] | Read more »
Card King: Dragon Wars - Tips, Tricks an...
[Read more] | Read more »
Pac-Man Championship Edition DX has brou...
Bandai Namco has released Pac-Man Championship Edition DX on iOS and Android, which features the classic arcade gameplay that we've all grown to love. Pac-Man Championship Edition DX can be enjoyed in much shorter bursts than the arcade versions... | Read more »
Cosmonautica (Games)
Cosmonautica 1.1 Device: iOS Universal Category: Games Price: $6.99, Version: 1.1 (iTunes) Description: Cast off! Are you ready for some hilarious adventures in outer space? | Read more »

Price Scanner via

MacBook 12 Retina Pundit’s New Favorite Mac
If you’re eyeing the purchase of a new 12-inch Retina MacBook, but wondering if you can live with a single USB-C port, 2011-level CPU performance, and the unorthodox keyboard, you should find... Read more
PDF Element Tool Kit For PDF For Windows 10,...
South Surrey, British Columbia based software developer Wondershare has posted an interesting infographic tracking the development of Microsoft’s flagship Windows operating system over the years,... Read more
27-inch 3.5GHz 5K iMac on sale for $81 off MS...
Adorama has the 27″ 3.5GHz 5K iMac on sale for $2218, $81 off MSRP, including a free copy of Apple’s 3-Year AppleCare Protection Plan. Shipping is free, and Adorama charges sales tax in NY & NJ... Read more
Back-to-School with Tablet and Smartphone Acc...
Belkin helps you prepare for the coming school year with a wide variety of the latest mobile and tablet accessories to outfit both grade school and college students. The line-up includes charging... Read more
11-inch MacBook Airs on sale for $100 off MSR...
Best Buy has 11-inch MacBook Airs on sale for $100 off MSRP. Choose free shipping or free local store pickup (if available). Sale prices for online orders only, in-store prices may vary: - 11″ 1.6GHz... Read more
iPad Air 2 on sale for up to $100 off MSRP
Best Buy has iPad Air 2s on sale for up to $100 off MSRP on their online store for a limited time. Choose free shipping or free local store pickup (if available). Sale prices available for online... Read more
Sale! 13-inch MacBook Pros on sale for $100 o...
B&H Photo has 13″ MacBook Pros on sale for $100 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 13″ 2.5GHz/500GB MacBook Pro: $999.99 save $100 - 13″ 2.7GHz/128GB Retina... Read more
Sale! Save $100 on 13-inch MacBook Airs this...
B&H Photo has the 13″ 1.6GHz/128GB MacBook Air on sale for $899.99 including free shipping plus NY tax only. Their price is $100 off MSRP, and it’s the lowest price available for this model.... Read more
Worldwide Tablet Market Decline Continues, Ap...
The worldwide tablet market declined -7.0% year-over-year in the second quarter of 2015 (2Q15) with shipments totaling 44.7 million units according to preliminary data from the International Data... Read more
TP-LINK TL-PA8030P KIT Powerline Featuring Ho...
Consumer and business networking products provider TP-LINK is now shipping its TL-PA8030P KIT AV1200 3-Port Gigabit Passthrough Powerline Starter Kit that expands your home’s network over its... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Infrastructure Engineer - *Apple* /Mac - Hil...
Infrastructure Engineer - Apple /Mac Job Code: 1608 # of openings: 1 Description Our fortune 500 client is looking to hire an experienced Infrastructure Engineer to join Read more
Executive Administrative Assistant, *Apple*...
…supporting presentation development for senior leadership. * User experience with Apple hardware and software is preferred. Additional Requirements The following list Read more
*Apple* Bus Company is now hirin - Apple Bus...
Apple Bus Company is now hiring school bus drivers in the Pettis County area. Class B CDL preferred. Free training provided. No nights or weekends required. Flexible Read more
*Apple* Certified Mac Technician - Updated 6...
…and friendly, hands-on technical support to customers troubleshooting and repairing Apple /Mac products with courtesy, speed and skill. Use your problem-solving skills Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.