TweetFollow Us on Twitter

Filter Procs
Volume Number:1
Issue Number:10
Column Tag:Programmer's Forum

"C Glue Routines for Filter Procs"

By Van Kichline, John Pence, MacMan, Inc.

The Macintosh ROM is divided into two sections, the operating system and the programmer's toolbox. The programmer's toolbox comprises about two thirds of the ROM and is there to make it easier for the programmer to adhere to Apple's stringent but cohesive user interface guidelines. It provides easy to use routines for creating windows and text edit records, dealing with resources, conducting modal dialogs and alerts, and many, many more functions. Used with a little care, it makes your program look and perform like a commercial Macintosh product, and makes it easy and intuitive for users to use your program.

The toolbox helps the programmer do it right, but what if you want to do it just a little differently? Not many individuals would care to rewrite and debug the routines provided by the toolbox, but in many cases there are alternatives built in. Many toolbox routines include parameters for optional filter or action procedures, which can be used with a default value (usually NIL) or with a pointer to a procedure you supply. Some examples are filterProcs for SFGetFile and ModalDialog, and actionProcs for controls.

A dialog filterProc is invoked by calling ModalDialog with a procPtr to your filter procedure. It changes the way ModalDialog responds to events that take place within its domain. The object of one filter we wrote was to capture keystrokes that occurred while the command key was down, format them, and display them in a rectangle in the ModalDialog box. The filter looked at keyDown events, checked the modifiers field, changed the itemHit to 0 so that a TextEdit box in the same dialog wouldn't know about the keystroke, and then did a little string fiddling. It didn't take long to write, but it took a while to get running!

The Programmer's Toolbox expects you to be a Pascal programmer, not a C programmer, and C passes arguments quite differently than Pascal. This means that the ROM will call your function, but the way it presents its data is incompatible with Mac C. Pascal passes its parameters on the stack, and Mac C passes its parameters in registers.

Can non-Pascal programmers use filters and actionProcs at all? Is there any solution? Is this the end?

There are two solutions, actually. Assembly language routines can be used for all procedures that are called by the ROM. Assembly language is easy to mix with C programs, and allows the programmer the flexibility to deal with data in any format in which it may be presented. There is nothing at all wrong with this solution, and Inside Mac provides much valuable information for the assembly programmer. Assembly code is tight, fast, and efficient. Assembly programming, however, requires a firm grasp of the instruction set of the processor, and is more difficult and time consuming than programming in a medium level language like C.

Functions called by the ROM can be written in C with a little care, a little effort, and a little glue. The term "glue" refers to a few assembly language instructions that fasten your code and the ROM code together. A glue routine is a labeled set of instructions that interface a particular function to another, "incompatible" function. Glue routines are easy to implement , and once a glue routine for a particular case is developed, it can be readily copied to other routines of the same type with only the most trivial modifications. This allows the programmer to rapidly write the filter and action routines in C. Once debugged and tuned, the routines can be converted to assembly if required, but I haven't found a need to convert any yet.

Pascal calls FUNCTIONS and PROCEDUREs by pushing its arguments onto the stack. If the routine being called is a FUNCTION (a Pascal routine that returns a result) a place for the result is cleared on the stack, which may be two or four bytes wide. Then the parameters for the routine, which may also be two or four bytes each, are pushed on the stack in the order which they are declared in the Pascal procedure's definition. In other words, if the procedure Meza is being called, and it's defined:

PROCEDURE Meza(Homos : food ; Gyros: food ; Pita : bread) ;

Then the arguments would be pushed in the order Homos, Gyros, and Pita. When they're retrieved, they'll be popped in the order Pita, Gyros, Homos. Be careful. Think backwards. Finally, the JSR instruction that calls the procedure places the four byte return address on top of the stack, covering the parameters.

Mac C functions pass the values of the first seven arguments, assuming there are more, in the data registers D0 through D6. Excess arguments are stored on the stack, but we won't deal with the complexities of excess arguments here. The prologue code for each function defined in Mac C actually takes the arguments out of the registers and stores them on the stack in a "stack frame," but we are free to ignore what takes place once the C function is invoked. What's of importance to the writer of a glue routine is taking the Pascal parameters off the stack and placing them in the appropriate registers while preserving the return address. For Pascal FUNCTIONS, the result must also be placed in the appropriate location on the stack.

Assembling the Solution

There are several ways to construct glue routines. The way I've presented here is applicable for routines requiring up to three parameters. Another way would be to "seal" the parameters in a stack frame and extract each parameter relative to A6. (See Robert Denny's column in MT 1, 7) I've selected the more direct approach because it's easier to describe, and is sufficient for all routines I've encountered except window and menu definition procedures, which are extremely complex. Our goal is to present enough information for the reader to construct his/her own glue routines without further aid, so we've selected the direct, or "brute force" method for presentation.

Assembly language may be included in Mac C source code by bracketing the lines with the terms #asm and #endasm. What goes in between is assembly source code that's exactly like MDS assembly source. Here's the skeleton of a Pascal to Mac C glue routine:

#asm
routineName:; what you call the function 
MOVE.L  (SP)+, A0; pop return address to A0
MOVE.X  (SP)+, DX; save up to 3 params, of 2             ; or 4 bytes.
MOVEM.L A0, -(SP); return address on top of        ; stack
MOVEM.L A3-A4/D3-D7, -(SP); save the registers
JSR myFunctionInC; execute the C code
MOVEM.L (SP)+,  A3-A4/D3-D7 ; Restore registers.
MOVE.X  X0, 4(SP); if it's a function, return a          ; value
RTS
#endasm

The first line of the glue routine is the label, "routineName." This would be replaced with a unique function name in your application. The toolbox routine calls this label, not myFunctionInC. If the C function is called by the ROM instead of the glue routine, the system will crash. The label is declared as a C function at the beginning of the file. For example, if this where to be a ModalDialog filterProc, I would declare it in advance:

short routineName() ;   /* type short : returns Pascal BOOLEAN */

Thereafter, the term "routineName" represents a pointer to the function. To use it as a function for a particular modal filter, you'd use:

do{
 ModalDialog(routineName, &itemHit) ;
 switch(itemHit)
 {
 case QUIT:         (code) break 
 case CANCEL:  (code) break ;
 case CRASH:     (code) break ;
 default:                SysBeep(8) ;
 }
} while TRUE ;

Thus, the label of the glue routine is treated exactly as if it where the name of the C function it calls. The actual C function is referenced by nobody but the glue routine.

The second item in the glue routine skeleton pops the top four bytes off the stack and puts them in A0 for temporary storage. This is the return address of the routine calling our filter, pushed on the stack by a JSR in the ROM. In this case, it is ModalDialog who called, and the return address is the only way back to it.

Next is the part that does the actual gluing, and varies for different usages. Parameters, being two or four bytes in length, are popped off the stack and stored in data registers. (See the illustration "Data Configurations.") This data, remember, was pushed there by the toolbox routine before calling us and comprises the parameters our C function needs in its registers. If the data is two bytes in length MOVE.W is used, and if the data is four bytes long MOVE.L is used in place of MOVE.X. See the illustration of the stack at entry to the glue routine.

After the parameters are moved into the registers the return address, which we'd stored in A0, is placed back on top of the stack.

Next, the register set is saved. The MoveMultiple instruction saves all the registers desired in a single line. Then, the JSR instruction to the private name myFunctionInC executes the real code.

After the last parameter is moved to the appropriate data register, the stack pointer (A7) points at the place holder for the FUNCTION result if there is one, or else to "unknown territory," or other essential data that remains on the stack and must be preserved. Next, the return address is placed back on top of the stack (four bytes) followed by the registers (28 bytes.) When the JSR myFunctionInC instruction is executed, it pushes a return address to the instruction following the JSR onto the stack and puts the address of myFunctionInC in the program counter. The data the C code needs is in the registers. The C function doesn't disturb anything on the stack except the return address on the very top, which it uses to return to the glue routine with an RTS.

Once the C function returns to the glue routine that called it, the registers that the glue routine saved are restored, popping them from the stack. Directly under those registers is the return address of the caller that we were so careful to preserve earlier. If our C code was emulating a Pascal FUNCTION, the place holder for the result is directly under the return address. We must place the result of our function in this location. Mac C returns results that are values in D0, and results that are pointers in A0. So a BOOLEAN result would be in D0, and two bytes long. In this case, the last instruction before the RTS would be MOVE.W DO, 4(SP). It's always 4(SP), because the return address always four bytes long, but the instruction may move a word or a long word from D0, or a long word from A0, depending on the data type of the result. Don't put a result there if it's not required! You'll mash irreplaceable data and crash. Now a simple JSR propels us back into the ROM and the inner sanctums of ModalDialog.

Concrete Glue

Here's a concrete example. The toolbox routine TrackControl can use a pointer to an actionProc as a parameter. This actionProc represents a continuous action to be performed while the control is being tracked. Scroll bars require an actionProc in order to make the arrows and paging parts work. First, the label is declared globally.

void trackScroll() ;

The function's declared as void because it's used as a Pascal PROCEDURE, and returns no result. Then, when a mousedown occurs in a scroll bar, the application finds the controls handle and calls:

if(TestControl(controlHand, &theEvent->where) == inThumb)
 TrackControl(controlHand, &theEvent->where, NIL) ;
else
 TrackControl(controlHand, &theEvent->where, trackScroll) ;

Note that TrackControl doesn't need an actionProc for the thumb (the moving box part of the scroller), so why rewrite one?

If the else branch is taken, our glue routine is called by the ROM. An action proc for an indicator like a scroll bar receives two parameters; a ControlHandle and a short representing the partCode of the control that was activated. No result is returned. Thus the glue routine goes:

#asm
trackSrcoll:
MOVE.L  (SP)+, A0; temp storage for return addr
MOVE.W  (SP)+, D1; partCode goes in D1, 2 bytes
MOVE.L  (SP)+, D0; controlHandle goes in D0, 4 bytes
MOVE.L  A0, -(SP); push return address
MOVEM.L A3-A4/D3-D7, -(SP)       ; save regs
JSR   Cscroll  ; do the function written in C
MOVEM.L (SP)+, A3-A4/D3-D7      ; restore regs
RTS; no result. go back to TrackControl
#endasm

The labels trackScroll and Csrcoll are specific to an implementation, while the rest is constant from one actionProc to another. The size of the parameters determines which MOVE instructions to use. D1 is loaded first, then D0, because they where pushed onto the stack in order, and are popped off in reverse.

The glue routine may be contained entirely within the function called by it. This makes cutting and pasting the routine to another application easier. A complete, albeit simple example of a scrolling actionProc in C might be:

void deadCscrolls (theControl, partCode)
 ControlHandle   theControl ;
 short  partCode ;
{
 short  amount, startVal, up ;
 
 if(!partCode)
 return ;
 startVal = GetCtlValue(theControl) ;
 up = (partCode == inUpButton || 
 partCode == inPageUp) ? TRUE : FALSE;
 
 if ((up && (startVal > GetCtlMin(theControl))) ||
 (!up && (startVal<GetCtlMax(theControl))))
 {
 amount = (up) ? -1 :  1 ;
 SetCtlValue(theControl, startVal + amount) ;
 }
 return ;
 
 /* the Glue routine */
 
#asm
trackScroll:; TrackControl calls trackScroll, not        ; deadCscrolls!
 MOVE.L (SP)+, A0; save the return address
 MOVE.W (SP)+, D1; partCode to D1
 MOVE.L (SP)+, D0; theControl to D0
 MOVE.L A0, -(SP); return address goes here
 MOVEM.L  A3-A4/D3-D7, -(SP); save the registers   JSR   deadCscrolls
 ; the scroll actionproc - C
 MOVEM.L  (SP)+, A3-A4/D3-D7; restore the registers      RTS   
 ; there's nothing to return
#endasm
}

Note that every actionProc of this type uses the exact same glue routine. It may take a little while to work out the first time, but the effort doesn't need to be repeated. A small collection is all you need.

Glue routines can be used to rapidly implement toolbox modifying procedures and functions in C. Such implementation allows the programmer to write filters and actionProcs readily, and simplifies debugging and maintaining them. Such routines can be converted entirely to assembly after testing for greater efficiency, or may be left as is with little or no difference in performance.

Authors note: The techniques described here may or may not apply to other C compilers. We'd be interested in hearing.

 
AAPL
$101.79
Apple Inc.
+0.21
MSFT
$46.68
Microsoft Corpora
+0.16
GOOG
$589.27
Google Inc.
+4.50

MacTech Search:
Community Search:

Software Updates via MacUpdate

iMazing 1.0 - Complete iOS device manage...
iMazing (formerly DiskAid) is the ultimate iOS device manager with capabilities far beyond what iTunes offers. With iMazing and your iOS device (iPhone, iPad, or iPod), you can: Copy music to and... Read more
Xcode 6.0.1 - Integrated development env...
Apple Xcode is Apple Computer's integrated development environment (IDE) for OS X. The full Xcode package is free to ADC members and includes all the tools you need to create, debug, and optimize... Read more
Apple Safari 7.1 - Apple's Web brow...
Apple Safari in OS X Mavericks brings you all-new ways to find and enjoy the best of the web. It works with iCloud to give you a seamless browsing experience across all your devices. It looks out for... Read more
Delivery Status 6.1.2 - Check delivery s...
Delivery Status displays delivery status of packages for a variety of shipment services. Can't wait for your packages to arrive? Don't waste your time checking the site constantly, just open this all... Read more
Mavericks Cache Cleaner 8.0.9 - Clear ca...
Mavericks Cache Cleaner is an award-winning general purpose tool for OS X. MCC makes system maintenance simple with an easy point-and-click interface to many OS X functions. Novice and expert users... Read more
OneNote 15.2.2 - Free digital notebook f...
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
Apple Configurator 1.6 - Configure and d...
Apple Configurator makes it easy for anyone to mass configure and deploy iPhone, iPad, and iPod touch in a school, business, or institution. Three simple workflows let you prepare new iOS devices... Read more
SpamSieve 2.9.16 - 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
OS X Server 3.2.1 - For OS X 10.9.5 Mave...
OS X Server is the next generation of Apple's award winning server software. Designed for OS X and iOS devices, OS X Server makes it easy to share files, schedule meetings, synchronize contacts, host... Read more
Apple Security Update 2014-004 - For OS...
Apple Security Update is recommended for all users and improves the security of Mac OS X. For information on the security content of this update, please visit this website: http://support.apple.com/... Read more

Latest Forum Discussions

See All

Down Among the Dead Men (Games)
Down Among the Dead Men 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: Avast! Take to the high seas in a fully interactive piratical tale of broadsides and buccaneers. From author Dave... | Read more »
Sling Adds Chromecast Support Through Sl...
Sling Adds Chromecast Support Through Slingplaye​r Mobile Apps Posted by Jessica Fisher on September 18th, 2014 [ permalink ] | Read more »
How to Completely Delete Your iPhone’s C...
The iPhone 6 is out tomorrow, and plenty of people are excited about it. So much so that they’re planning to – or already have – traded in their old iPhone to go towards it. The thing about trading in hardware is it’s very important to make sure... | Read more »
Dragon Quest I Review
Dragon Quest I Review By Andrew Fisher on September 18th, 2014 Our Rating: :: THINE QUEST AWAITETHUniversal App - Designed for iPhone and iPad Its historical significance aside, Dragon Quest 1 is a fun, campy, difficult, thoroughly... | Read more »
It Came From Canada: Overkill 3
Overkill 3 is like every trope of big modern gaming rolled into one. It’s a sequel to an action-packed military shooter. It’s flashy and scripted and flaunts its sophisticated graphics. And it’s a mobile game with a heavy emphasis on in-app... | Read more »
New Modes and Leader Boards in Update fo...
New Modes and Leader Boards in Update for Rules! Posted by Jessica Fisher on September 18th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
TwistedRun Review
TwistedRun Review By Rob Thomas on September 18th, 2014 Our Rating: :: DON'T TWIST YOUR ANKLE!Universal App - Designed for iPhone and iPad TwistedRun is kind of like running up a giant curly fry into the sky. Or maybe that was just... | Read more »
Scope Review
Scope Review By Jennifer Allen on September 18th, 2014 Our Rating: :: LOCATION AWAREiPhone App - Designed for the iPhone, compatible with the iPad Want to easily find photos from around the world based on their location? Scope is a... | Read more »
HipstaFox Review
HipstaFox Review By Jordan Minor on September 18th, 2014 Our Rating: :: FANTASTIC MR. FOXUniversal App - Designed for iPhone and iPad HipstaFox is a great single that makes players long for the whole album.   | Read more »
Ninja Raft (Games)
Ninja Raft 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: ** Special Launch Price ** "Ninja Raft is definitely the game to play if you’re into Tower Defense games and want to play something... | Read more »

Price Scanner via MacPrices.net

Save up to $300 on the price of a new Mac wit...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more
13-inch 2.8GHz Retina MacBook Pro available f...
B&H Photo has the new 2014 13″ 2.8GHz Retina MacBook Pro on sale for $1699.99 including free shipping plus NY sales tax only. They’ll also include free copies of Parallels Desktop and LoJack for... Read more
16GB iPad Air on sale for $449, save $50
Walmart has the 16GB iPad Air WiFi on sale for $449 on their online store for a limited time. Choose free home shipping or free local store pickup. Their price represents a $50 savings over standard... Read more
13-inch 256GB MacBook Air on sale for $1099,...
B&H Photo has the 2014 13″ 1.4GHz 256GB MacBook Air on sale for $1099.99. Shipping is free, and B&H charges NY sales tax only. Their price is $100 off MSRP. Read more
Toshiba Introduces TransMemory ID High-Speed...
Toshiba’s Digital Products Division (DPD), a division of Toshiba America Information Systems, Inc., today introduced the TransMemory ID USB 3.0 Flash Drive, a simpler storage solution for people who... Read more
New iPads and OS X Yosemite Release Coming Oc...
The DailyDot’s Micah Singleton reports that Apple is planning to hold its next product announcement event on Oct. 21, at which it will unveil the iPad Air 2 and iPad mini 3 and release a final build... Read more
Logitech Bluetooth Multi-Device Cross-Platfor...
Logitech has an enviable track record of making some of the best computer keyboards and mice. At least in my estimation, the best freestanding keyboards I’ve ever used have been Logitech units,... Read more
Roundup of Apple refurbished iPad Airs and iP...
Apple is offering Certified Refurbished iPad Airs for up to $140 off MSRP. Apple’s one-year warranty is included with each model, and shipping is free. Stock tends to come and go with some of these... Read more
Sprint offers 16GB iPad mini for $199.99 with...
Sprint is offering 1st generation 16GB iPad minis for $199.99 with a 2-year service agreement. Standard MSRP for this iPad is $429. Their price is the lowest available for this model. Read more
2.5GHz Mac mini remains on sale for $549, sav...
B&H Photo has the 2.5GHz Mac mini on sale for $549.99 including free shipping. That’s $50 off MSRP, and B&H will also include a free copy of Parallels Desktop software. NY sales tax only. Read more

Jobs Board

Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
*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
*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
*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
*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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.