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:

: TEST DUP 2* SWAP DROP . ; 

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.

TOKENS

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

FIND TEST TOKEN>ADDR .

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

 NFA ID.

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:

 $A91F  
/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]         
 NO RIGHTS RESERVED    NO RIGHTS RESERVED    NO RIGHTS RESERVED 

BASE @ DECIMAL   VARIABLE HIGH.PFA  16384 MINIMUM.OBJECT  2048 MINIMUM.VOCAB 
        : .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)     
  DUP W@ 4 .DIGITS 31 SPACE.TO DECIMAL DUP <W@ . HEX  DUP W@    
  NFA ?DUP IF 42 SPACE.TO ID. THEN  2+ ;
: DISP.DBL     ( pfa -- pfa+4 | Display a 32-bit parameter )    
  DUP @ DUP 8 .DIGITS 31 SPACE.TO DECIMAL . HEX 4+ ;  
: 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 )      
  DUP <W@ OVER + DUP HIGH.PFA @ > IF HIGH.PFA ! ELSE DROP THEN  
  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 )    
  DUP @ NFA ?DUP  IF ID.  ELSE DUP @ NEXT.PTR + 8 .DIGITS THEN 4+ ;  
  
: 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 (MENU.SELECTION:) 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
  ENDCASE ;  

: DECODE.TOKENS  ( pfa --  | Display the words starting at pfa )
  DUP HIGH.PFA ! DUP                                            
  BEGIN                                                         
    HEX 2DUP SWAP - CR 4 .R 2 SPACES DUP 2+ SWAP W@ DUP NFA ?DUP     
                            
      IF    ID.    ELSE .” ???” drop 0  THEN                         
        
      20 SPACE.TO SPECIAL.TOKENS ?DUP                           
      IF    FALSE  ELSE  DUP HIGH.PFA @ > THEN                       
        
  UNTIL                                                         
  2DROP ;                                                       

: .VALUE  ( n1\n2 --  | Display constants and UA variables )    
  HEX .DIGITS .”  hex  “ DECIMAL . .” decimal )”  ;             
                                                                
: DECODE.VECTOR  ( pfa\vector -- | Display definition type )    
  CASE                                                          
    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 ) 
  GET.LINE.HEIGHT  GET.TEXTSIZE  BASE @  9 TEXTSIZE  10 LINE.HEIGHT  
                                  
  +FIND CR POCKET COUNT TYPE .”  -- “                           
     IF 
        IF .” IMMEDIATE “ THEN                                  
        CHK.CODE.TYPE IF DECODE.VECTOR ELSE .” Machine code definition” 
THEN                   
     ELSE .” Not in dictionary” THEN                            
  BASE !  TEXTSIZE  LINE.HEIGHT  CR ;                           
                                                                
: #DECOMP ( token --  | Decompile word whose token is supplied )
  BASE @  GET.LINE.HEIGHT  GET.TEXTSIZE  4 PICK DUP             
  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” 
THEN                   
     ELSE HEX 4 .DIGITS .” -- Not a valid token” THEN           
  TEXTSIZE  LINE.HEIGHT  BASE !  DROP  CR ;                     


 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Jump into one of Volkswagen's most...
We spoke about PUBG Mobile yesterday and their Esports development, so it is a little early to revisit them, but we have to because this is just too amusing. Someone needs to tell Krafton that PUBG Mobile is a massive title because out of all the... | Read more »
PUBG Mobile will be releasing more ways...
The emergence of Esports is perhaps one of the best things to happen in gaming. It shows our little hobby can be a serious thing, gets more people intrigued, and allows players to use their skills to earn money. And on that last point, PUBG Mobile... | Read more »
Genshin Impact 5.1 launches October 9th...
If you played version 5.0 of Genshin Impact, you would probably be a bit bummed by the lack of a Pyro version of the Traveller. Well, annoyingly HoYo has stopped short of officially announcing them in 5.1 outside a possible sighting in livestream... | Read more »
A Phoenix from the Ashes – The TouchArca...
Hello! We are still in a transitional phase of moving the podcast entirely to our Patreon, but in the meantime the only way we can get the show’s feed pushed out to where it needs to go is to post it to the website. However, the wheels are in motion... | Read more »
Race with the power of the gods as KartR...
I have mentioned it before, somewhere in the aether, but I love mythology. Primarily Norse, but I will take whatever you have. Recently KartRider Rush+ took on the Arthurian legends, a great piece of British mythology, and now they have moved on... | Read more »
Tackle some terrifying bosses in a new g...
Blue Archive has recently released its latest update, packed with quite an arsenal of content. Named Rowdy and Cheery, you will take part in an all-new game mode, recruit two new students, and follow the team's adventures in Hyakkiyako. [Read... | Read more »
Embrace a peaceful life in Middle-Earth...
The Lord of the Rings series shows us what happens to enterprising Hobbits such as Frodo, Bilbo, Sam, Merry and Pippin if they don’t stay in their lane and decide to leave the Shire. It looks bloody dangerous, which is why September 23rd is an... | Read more »
Athena Crisis launches on all platforms...
Athena Crisis is a game I have been following during its development, and not just because of its brilliant marketing genius of letting you play a level on the webpage. Well for me, and I assume many of you, the wait is over as Athena Crisis has... | Read more »
Victrix Pro BFG Tekken 8 Rage Art Editio...
For our last full controller review on TouchArcade, I’ve been using the Victrix Pro BFG Tekken 8 Rage Art Edition for PC and PlayStation across my Steam Deck, PS5, and PS4 Pro for over a month now. | Read more »
Matchday Champions celebrates early acce...
Since colossally shooting themselves in the foot with a bazooka and fumbling their deal with EA Sports, FIFA is no doubt scrambling for other games to plaster its name on to cover the financial blackhole they made themselves. Enter Matchday, with... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra available today at Apple fo...
Apple has several Certified Refurbished Apple Watch Ultra models available in their online store for $589, or $210 off original MSRP. Each Watch includes Apple’s standard one-year warranty, a new... Read more
Amazon is offering coupons worth up to $109 o...
Amazon is offering clippable coupons worth up to $109 off MSRP on certain Silver and Blue M3-powered 24″ iMacs, each including free shipping. With the coupons, these iMacs are $150-$200 off Apple’s... Read more
Amazon is offering coupons to take up to $50...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for up to $110 off MSRP, each including free delivery. Prices are valid after free coupons available on each mini’s product page, detailed... Read more
Use your Education discount to take up to $10...
Need a new Apple iPad? If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $100 off the... Read more
Apple has 15-inch M2 MacBook Airs available f...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more
Mac Studio with M2 Max CPU on sale for $1749,...
B&H Photo has the standard-configuration Mac Studio model with Apple’s M2 Max CPU in stock today and on sale for $250 off MSRP, now $1749 (12-Core CPU and 32GB RAM/512GB SSD). B&H offers... Read more
Save up to $260 on a 15-inch M3 MacBook Pro w...
Apple has Certified Refurbished 15″ M3 MacBook Airs in stock today starting at only $1099 and ranging up to $260 off MSRP. These are the cheapest M3-powered 15″ MacBook Airs for sale today at Apple.... Read more
Apple has 16-inch M3 Pro MacBook Pro in stock...
Apple has a full line of 16″ M3 Pro MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $440 off MSRP. Each model features a new outer case, shipping is free, and an... Read more
Apple M2 Mac minis on sale for $120-$200 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $110-$200 off MSRP this weekend, each including free delivery: – Mac mini M2/256GB SSD: $469, save $130 – Mac mini M2/512GB SSD: $689.... Read more
Clearance 9th-generation iPads are in stock t...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on clearance sale for starting at only $199 on their online store for a limited time. Sale prices for online orders only, in-store prices may vary... Read more

Jobs Board

Senior Mobile Engineer-Android/ *Apple* - Ge...
…Trust/Other Required:** NACI (T1) **Job Family:** Systems Engineering **Skills:** Apple Devices,Device Management,Mobile Device Management (MDM) **Experience:** 10 + Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Full Time (80 hrs/pay period) Evenings General Summary Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.