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.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.