TweetFollow Us on Twitter

INITs, Patches
Volume Number:5
Issue Number:6
Column Tag:Forth Forum

Related Info: Resource Manager TrapWords

INITs and Patches

By Jörg Langowski, MacTutor Editorial Staff

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

“INITs and trap patches”

This month’s program started off as an attempt to write a ‘logging’ utility, that is, a routine that will record when applications are launched and closed. Simple, I thought. Just patch the _Launch and _ExittoShell traps and install some code that writes a line to a file giving the time, date and name of the application each time these traps are called. However, I soon realized that it’s not as simple as that. Under Finder, yes, that strategy works; but imagine my surprise when I found that _Launch is never called when an application is started under Multifinder! This ‘feature’ seems not to be documented in the technical notes that I have, nor in the Multifinder documentation.

If you record trap calls with TMON, you’ll find the following sequence for launching an application under Finder:

 ... (until all necessary segments are loaded)

and for exiting, _ExittoShell is called. Multifinder seems to use the same sequence of calls, except for the first call to _Launch, which is left out.

Therefore, if we want to build a routine that logs application launches, we have to find another indicator. One trap call is always made when an application is started: _GetResource is called for CODE ID=0. If we patch _GetResource such that this particular call is intercepted, we have a ‘hook’ that allows us to install any routine to be called at application startup.

Patching traps under Multifinder

Traps cannot be easily patched in a permanent way under Multifinder. Since different application might need different trap patches, Multifinder intercepts (I believe) _SetTrapAddress and switches the trap patches when control is transferred from one program to another. So, when you write a short application that patches a trap, that patch will only be valid in the context of that application - and disappear when the application quits again. Not very useful for a routine that logs application launches, which will have to work independently of any particular context. So we’ll have to install the patch before Multifinder is started, and this is best done with an INIT.

This month’s example will show you how to write an INIT under Mach2 that installs permanent patches to _GetResource and _ExittoShell. For the moment, all these patches do is beep once when the application starts and when it quits. These patches would then have to be extended to write some text to a file that gives the name and time of the application.

I’ll also give an example of a small application that can be used to run an INIT from a file in the same folder as the application. It uses the same mechanism as the system itself to call the INIT. This program is based on an idea of Eric Carrasco from the Calvacom bulletin board in Paris, who wrote a similar program in Pascal.


The mechanism by which an INIT resource is called has been outlined already by Bob Denny in V1#9. In case you’re missing that issue, I’ll quickly repeat it here: First, the INIT resource is loaded into the system heap. Then, _DetachResource is called which tells the resource manager to forget this resource. Finally, the system jumps to the first location of the INIT resource via a JSR. When the INIT later returns via RTS, the first two words in its code are overwritten by NOP instructions. The reason for this procedure, which might seem a little strange, is that an INIT code might consist of a JMP to some installation code at the end, and have the actual memory-resident part at its beginning. That way, when the JMP at the beginning is overwritten by NOPs, any code that jumps to the start of the INIT will now execute its main part. The initialization part at the end can be given back to the memory manager, once the INIT is installed.

Listing 1 shows the INIT code in Mach2. The kernel-independent code is produced in the usual way, using the external definition words which make sure the JMP at the first location if the INIT points to the right piece of code, and which set up the local Forth stack.

The INIT (word INITrun) first creates a handle to its own memory block by calling _RecoverHandle, then locks this handle. A temporary area for the Quickdraw globals is then created in the local variable space. Remember that local variables in Mach2 are allocated from top to bottom in memory, so that the sequence

newA5 myGlobals [ 202 lallot ]

with A5 later pointing to the address of newA5 will have the QD globals allocated correctly below A5. If your INIT needs to use any of them, simply reference them starting at myGlobals.

Our INIT code sets up A5 and the low memory global CurrentA5, then calls the usual manager initialization traps necessary for setting up a dialog box. After these calls, the environment is ready for calling the main Forth code of the INIT, myINIT in our case. From myINIT, all toolbox traps may be used since A5 points to valid QD global space and the managers have been initialized (oh not the menu manager, of course, but you probably wouldn’t want to use menus from an INIT. I doubt whether it would be possible, anyway. Try it out).

For an INIT that is supposed to stay in the system heap ‘as is’, you don’t need to take any special action in the code to free its memory space. However, when - as in our case - the INIT copies part of itself to a non-relocatable block in the system heap and is not needed anymore, we want to purge the memory space after action. This is done by calling _DisposHandle after myINIT has returned.

gINIT is the glue code that calls the standard ‘INIT interface’ INITrun. Here, the registers are saved, stacks are set up, and CurrentA5 is restored after INITrun has returned.

The main INIT code, myINIT, first moves the patch code into a non-relocatable block in the system heap. It then patches _GetResource, using _SetTrapAddress, and moves a vector to the trap’s old address into the appropriate location inside the patch. The user is notified of the patch by an alert. The _GetResource patch itself (GetResPatch) checks whether this trap has been called with resource type CODE, ID=0. In that case, it beeps once. Instead of the beep, one could insert some code that writes a line to a file which has been opened in the installation part of the INIT. Something left as an exercise

There is also a patch to _ExittoShell, ExitPatch, which is supposed to beep when an application quits. Now look at the code where the INIT installs that patch. We do a _GetTrapAddress, right, but then the ugly part starts. If _ExittoShell is patched by _SetTrapAddress at system INIT time, the patch gets installed correctly, and you hear the beep when the Finder quits and calls the Multifinder, but then, silence. The patch has disappeared. Multifinder patches _ExittoShell as well and probably doesn’t conserve previous patches. I don’t know whether this is a bug or a feature (such as not calling _Launch when starting an application); but it makes life a great deal more difficult. Apple, can you hear me?

Here’s the workaround that I thought up, which works under System 6.0.2, and is not guaranteed to work under a new release (no, don’t leave the room yet, PLEASE!). When Multifinder patches _ExittoShell, it installs a JMP instruction to its patch code in RAM. Our INIT code tests whether the pointer returned by _GetTrapAddress points to a JMP <absolute> instruction. In that case, it patches the next two words with a pointer to our patch code and saves the old JMP address in the patch code. If the first instruction is not a JMP <absolute>, we assume we’re running under Finder and use _SetTrapAddress to patch the trap. Ugly, isn’t it. The worst part is that if you run under Multifinder your patch will be installed and then removed again; then you have to run the INIT again under Multifinder to install the _ExittoShell patch permanently. But I couldn’t find an easier way, please tell me if you have one.

How can you run an INIT at all when Multifinder runs already? This is where the short runINIT application comes in (Listing 2). This program will simulate the way the system calls an INIT resource. It will locate the file ‘theINIT’ which must be in the same folder, get the INIT ID=12 resource from that file and execute it the same way the system boot code would do it. So for installing the _ExittoShell patch under Multifinder, you simply double-click runINIT in the system folder, or make it one of your startup applications.

INIT incompatibilities

Our INIT is also a practical case where we can document that frequent disease of Mac system folders, INIT incompatibility. This INIT calls all the toolbox managers necessary to set up an alert, and then actually displays one. That means, _WaitNextEvent will be called from the alert. Other INITs might patch _WaitNextEvent, _GetNextEvent or _SystemTask to take some action when the system is fully booted up. That way, for instance, the ‘Remember’ INIT seems to call its associated desk accessory when some important dates are coming up. The problem is, when Remember is executed before an INIT that displays a dialog, the patch will open the desk accessory, which produces disaster in form of a bomb box.

I guess this incompatibility will always occur when you have one INIT which patches _SystemTask or similar routines to execute some other application or DA later on. If another INIT happens to call the patched trap and the system is not ready yet for whatever the first INIT wanted to be executed, a crash will probably follow. Make sure that this INIT is executed before any INITs that patch _WaitNextEvent, _GetNextEvent or _SystemTask.

Mach2 news

Finally I want to advertise the GEnie Mach2 and FIG round tables again. There is simply more interesting stuff in the software libraries than I could ever discuss here; the Mach2 system has been extended by hundreds of useful words already (by the way, v2.15 is on its way), and you find more in the FIG Forth libraries. Especially with the ANSI Forth standard coming up, a lot of the discussion on that new standard - and its implications on Mach2 - takes place on GEnie. For those of you who can’t access GEnie, but have access to Bitnet directly or via a gateway, I’ll try to get a compilation of the most important new words to you if you send me electronic mail:


Happy threading.

Listing 1: Trap patch INIT
\ INIT example which patches _GetResource 
\ with a call to _Sysbeep if type=CODE id=0
\ Also patches _ExitToShell, using an absolutely
\ AWFUL hack, but a _SetTrapAddress patch
\ seems to be removed under Multifinder
\ J. Langowski / MacTutor April 1989
only forth also mac also assembler
( *** compiler support words for external definitions *** )
: :xdef 
 create -4 allot
 $4EFA w, ( JMP )
 0 w,  ( entry point to be filled later )
 0 ,   ( length of routine to be filled later )
 here 6 - 76543

: ;xdef { branch marker entry | -- }
 marker 76543 <> abort” xdef mismatch”
 entry branch - branch w!
 here branch - 2+ branch 2+ !
: xlen 4 + @ ; ( get length word of external definition )

\ **** ext procedure glue macros

CODE ext.prelude
 LINK A6,#-700   ( 700 bytes of local Forth stack )
 MOVEM.L A0-A5/D0-D7,-(A7)( save registers )
 MOVE.L A6,A3    ( setup local loop return stack )
 SUBA.L #500,A3  ( in the low 200 local stack bytes )
 RTS    \ just to indicate the MACHro stops here 

CODE ext.epilogue
 MOVEM.L (A7)+,A0-A5/D0-D7( restore registers )

.trap _newPtr,SYS$A51E

-4 CONSTANT thePort
$904    CONSTANT CurrentA5
$A9A0 CONSTANT tGetRes  \ GetResource
$A9F4   CONSTANT tExit    \ ExitToShell

\ |--------------------------------|
\ | INIT resource code starts here |
\ |--------------------------------|

:xdef beeperINIT

header PatchStart
header oldGetRes
 DC.L 0
header oldExit
 DC.L 0

: GetResPatch
 CLR.L  D0
 MOVE.W 8(A6),D0
 MOVE.L 10(A6),D1
 MOVE.L D0,-(A6)
 MOVE.L D1,-(A6)

\ main FORTH code starts here
\ this can be used to log any launch
\ (i.e. GetResource CODE 0 ) to a log file
\ which has to be created/opened by the INIT code

 ascii CODE = swap 0= and IF
 \ (call) debugger
 1 (call) sysbeep
\ end of main code

 LEA    oldGetRes,A0
 MOVE.L (A0),A0
 JMP    (A0) 

: ExitPatch

\ main FORTH code starts here
\ this can eventually be used to write a line to 
\ the same log file as before
\(call) debugger
 1 (call) sysbeep
\ end of main code

 LEA    oldExit,A0
 MOVE.L (A0),A0
 JMP    (A0) 

header PatchEnd

: movePatch { | length -- patch }
 [‘] patchEnd [‘] PatchStart -   -> length
 MOVE.L (A6)+,D0
 MOVE.L A0,-(A6)
 dup IF ( we have space in system heap )
 [‘] PatchStart over length swap 
 (call) blockMove drop
: myINIT { | patch pExit -- }
 movePatch -> patch
 patch IF
 \ patch _GetResource
 tGetRes (call) GetTrapAddress
 patch !\  old GetResource
 [‘] GetResPatch [‘] PatchStart -
 patch + tGetRes (call) SetTrapAddress
 “ GetResource patch has been installed.” 
 0 0 0 (call) ParamText
 1000 0 (call) NoteAlert drop

 \ patch _ExitToShell, using hack
 tExit (call) GetTrapAddress -> pExit
 pExit w@ $4EF9 = 
 IF \ is it a JMP <absolute> 
 \ ? we’re probably in Multifinder...
 pExit 2+ @
 patch 4+ ! \  old ExitToShell
 [‘] ExitPatch [‘] PatchStart -
 patch + pExit 2+ ! 
 \ patch directly into Juggler’s innards. BOO!
 “ ExitToShell patch in Multifinder.” 
 0 0 0 (call) ParamText
 1000 0 (call) NoteAlert drop
 pExit patch 4+ !
 [‘] ExitPatch [‘] PatchStart -
 patch + tExit (call) SetTrapAddress
 “ ExitToShell patch in Finder.” 
 0 0 0 (call) ParamText
 1000 0 (call) NoteAlert drop
 “ Can’t get memory for patches.”
  0 0 0 (call) ParamText
 1000 0 (call) NoteAlert drop

: INITrun { | newA5 myGlobals [ 202 lallot ] theHandle -- } 
\(call) debugger 
 [‘] beeperINIT (call) recoverHandle -> theHandle
 theHandle (call) Hlock drop
 ^ newA5
 MOVE.L (A6)+,A5 \ create area for QD globals
 MOVE.L A5,CurrentA5 \ A5 points to it
 ^ newA5 thePort + (call) InitGraf
 (call) InitFonts
 (call) InitWindows
 (call) TEInit
 0 (call) InitDialogs
 (call) InitCursor

 myINIT \ call main INIT routine

 theHandle (call) HUnLock drop
 theHandle (call) DisposHandle drop

 ext.prelude INITrun ext.epilogue
 MOVE.L A5,CurrentA5 

‘ gINIT ;xdef

( *** creating the INIT file *** )
: $create-res call CreateResFile call ResError L_ext ;

: $open-res { addr | refNum -- result }
 addr call openresfile -> refNum
 call ResError L_ext
 dup not IF drop refNum THEN 

: $close-res call CloseResFile call ResError L_ext ;

: make-init { | refNum -- }
 “ theINIT” dup $create-res drop
 $open-res dup -> refNum call UseResFile 
 ascii INIT 12 call GetResource 
 ?dup IF call RmveResource THEN
 [‘] beeperINIT dup xlen
 call PtrToHand drop ( result code )
 ascii INIT 12 call GetResource 
 ?dup IF call RmveResource THEN
 ascii INIT 12 “ Beeper” call AddResource
 refNum $close-res drop ( result code )
Listing 2: INIT runner application
\ INIT 12 starter
\ J. Langowski / MacTutor April 1989
\ Thanks to Eric Carrasco (Calvacom EC10) to this idea
\ which he implemented in Pascal
: $open-res { addr | refNum -- result }
 addr call openresfile -> refNum
 call ResError L_ext
 dup not IF drop refNum THEN 

: $close-res call CloseResFile call ResError L_ext ;

$4E714E71 CONSTANT nopnop

: runINIT { | refNum hINIT -- }
 “ theInit” $open-res -> refNum
 refNum 0 > IF
 ascii INIT 12 call GetResource -> hINIT
 hINIT call HomeResFile
 refNum = IF
 hINIT call DetachResource
 hINIT @ execute \ run the INIT
 nopnop hINIT @ !  
 \ fill first 2 words with NOPs
 “ INIT not from my file” 0 0 0 call ParamText
 1000 0 call NoteAlert drop
 “ Can’t find INIT 12 resource” 
 0 0 0 call ParamText
 1000 0 call NoteAlert drop
 “ Can’t open file ‘theINIT’” 0 0 0 call ParamText
 1000 0 call NoteAlert drop

Community Search:
MacTech Search:

Software Updates via MacUpdate

OmniGraffle Pro 7.2.2 - Create diagrams,...
OmniGraffle Pro helps you draw beautiful diagrams, family trees, flow charts, org charts, layouts, and (mathematically speaking) any other directed or non-directed graphs. We've had people use... Read more
OmniGraffle 7.2.2 - Create diagrams, flo...
OmniGraffle helps you draw beautiful diagrams, family trees, flow charts, org charts, layouts, and (mathematically speaking) any other directed or non-directed graphs. We've had people use Graffle to... Read more
Spotify - Stream music, crea...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more
Microsoft OneNote 15.29 - Free digital n...
OneNote is your very own digital notebook. With OneNote, you can capture that flash of genius, that moment of inspiration, or that list of errands that's too important to forget. Whether you're at... Read more
WALTR 2 2.0.8 - $39.95
WALTR 2 helps you wirelessly drag-and-drop any music, ringtones, videos, PDF, and ePub files onto your iPhone, iPad, or iPod without iTunes. It is the second major version of Softorino's critically-... Read more
Dropbox 16.3.27 - Cloud backup and synch...
Dropbox is an application that creates a special Finder folder that automatically syncs online and between your computers. It allows you to both backup files and keep them up-to-date between systems... Read more
EtreCheck 3.1.5 - For troubleshooting yo...
EtreCheck is an app that displays the important details of your system configuration and allow you to copy that information to the Clipboard. It is meant to be used with Apple Support Communities to... Read more
Carbon Copy Cloner 4.1.12 - Easy-to-use...
Carbon Copy Cloner backups are better than ordinary backups. Suppose the unthinkable happens while you're under deadline to finish a project: your Mac is unresponsive and all you hear is an ominous,... Read more
VueScan 9.5.62 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
SpamSieve 2.9.27 - Robust spam filter fo...
SpamSieve is a robust spam filter for major email clients that uses powerful Bayesian spam filtering. SpamSieve understands what your spam looks like in order to block it all, but also learns what... Read more

Latest Forum Discussions

See All

Track Santa with these three festive app...
Christmas is fast approaching and that means it's time to prepare for Santa's yearly pilgrimage around the globe. Christmas Eve is an exciting time as parents help their kids get ready to welcome Santa. You've got the cookies and milk all planned... | Read more »
Galaxy on Fire 3 and four other fantasti...
Galaxy on Fire 3 - Manticore brings the series back for another round of daring space battles. It's familiar territory for folks who are familiar with the franchise. If you've beaten the game and are looking to broaden your horizons, might we... | Read more »
The best apps for your holiday gift exch...
What's that, you say? You still haven't started your holiday shopping? Don't beat yourself up over it -- a lot of people have been putting it off, too. It's become easier and easier to procrastinate gift shopping thanks to a number of apps that... | Read more »
Toca Hair Salon 3 (Education)
Toca Hair Salon 3 1.0 Device: iOS Universal Category: Education Price: $2.99, Version: 1.0 (iTunes) Description: | Read more »
Winter comes to Darkwood as Seekers Note...
MyTona, based in the chilly Siberian city of Yakutsk, has brought a little festive fun to its hidden object game Seekers Notes: Hidden Mystery. The Christmas update introduces some new inhabitants to players, and with them a chance to win plenty of... | Read more »
Bully: Anniversary Edition (Games)
Bully: Anniversary Edition 1.03.1 Device: iOS Universal Category: Games Price: $6.99, Version: 1.03.1 (iTunes) Description: *** PLEASE NOTE: This game is officially supported on the following devices: iPhone 5 and newer, iPod Touch... | Read more »
PINE GROVE 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: A pine grove where there are no footsteps of people due to continuous missing cases. The case is still unsolved and nothing has... | Read more »
Niantic teases new Pokémon announcement...
After rumors started swirling yesterday, it turns out there is an official Pokémon GO update on its way. We’ll find out what’s in store for us and our growing Pokémon collections tomorrow during the Starbucks event, but Niantic will be revealing... | Read more »
3 reasons why Nicki Minaj: The Empire is...
Nicki Minaj is as business-savvy as she is musically talented and she’s proved that by launching her own game. Designed by Glu, purveyors of other fine celebrity games like cult favorite Kim Kardashian: Hollywood, Nicki Minaj: The Empire launched... | Read more »
Clash of Clans is getting its own animat...
Riding on its unending wave of fame and success, Clash of Clans is getting an animated web series based on its Clash-A-Rama animated shorts.As opposed to the current shorts' 60 second run time, the new and improved Clash-A-Rama will be comprised of... | Read more »

Price Scanner via

Never Settle for Low Performing Wifi With iOS...
AppYogi Software has announced the release of WiFi Signal Strength Status App 1.0, the company’s new utility developed exclusively for macOS. WiFi Signal Strength Status App features a unique, single... Read more
New 2016 13-inch Touch Bar MacBook Pros in st...
B&H Photo has stock of new 2016 Apple 13″ Touch Bar MacBook Pro models, each including free shipping plus NY sales tax only: - 13″ 2.9GHz/512GB Touch Bar MacBook Pro Space Gray: $1999 - 13″ 2.... Read more
New 2016 15″ Touch Bar MacBook Pros in stock...
B&H Photo has new 2016 Apple 15″ Touch Bar MacBook Pro models in stock today including free shipping plus NY sales tax only: - 15″ 2.7GHz Touch Bar MacBook Pro Space Gray: $2799 - 15″ 2.7GHz... Read more
DietSensor App Targeting Diabetes and Obesity...
DietSensor, Inc., a developer of smart food and nutrition applications designed to fight diabetes and obesity and help improve overall fitness, has announced the launch of its DietSensor app for... Read more
Holiday 2016 13-inch 2.0GHz MacBook Pro sales...
B&H has the non-Touch Bar 13″ MacBook Pros in stock today for $50-$100 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 13″ 2.0GHz MacBook Pro Space Gray (MLL42LL/A): $1449 $... Read more
Holiday sale: Apple TVs for $51-$40 off MSRP,...
Best Buy has dropped their price on the 64GB Apple TV to $159.99 including free shipping. That’s $40 off MSRP. 32GB Apple TVs are on sale right now for $98 on Sams Club’s online store. That’s $51 off... Read more
12-inch Retina MacBooks, Apple refurbished, n...
Apple has restocked a full line of Certified Refurbished 2016 12″ Retina MacBooks, now available for $200-$260 off MSRP. Refurbished 2015 models are available starting at $929. Apple will include a... Read more
Holiday sale: 12-inch Retina MacBook for $100...
B&H has 12″ Retina MacBooks on sale for $100 off MSRP as part of their Holiday sale. Shipping is free, and B&H charges NY sales tax only: - 12″ 1.1GHz Space Gray Retina MacBook: $1199 $100... Read more
Apple refurbished 13-inch MacBook Airs availa...
Apple has Certified Refurbished 13″ MacBook Airs available starting at $849. An Apple one-year warranty is included with each MacBook, and shipping is free: - 13″ 1.6GHz/8GB/128GB MacBook Air: $849 $... Read more
Apple refurbished iMacs available for up to $...
Apple has Certified Refurbished 2015 21″ & 27″ iMacs available for up to $350 off MSRP. Apple’s one-year warranty is standard, and shipping is free. The following models are available: - 21″ 3.... Read more

Jobs Board

Integration Technician, *Apple* - Zones, In...
…at Zones and for our customers each day. Position Overview The Apple Integration Technician will be responsible for performing customer specific configuration Read more
*Apple* Brand Ambassador (Macy's) - The...
…(T-ROC), is proud of its unprecedented relationship with our partner and client, APPLE ,in bringing amazing" APPLE ADVOCATES"to "non" Apple store locations. Read more
*Apple* Retail - Multiple Positions- Trumbul...
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
*Apple* Retail - Multiple Positions - Apple,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
US- *Apple* Store Leader Program - Apple (Un...
…Summary Learn and grow as you explore the art of leadership at the Apple Store. You'll master our retail business inside and out through training, hands-on Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.