TweetFollow Us on Twitter

Oct 93 Think 10
Volume Number:9
Issue Number:10
Column Tag:Think Top 10

Related Info: Event Manager

Support’s Solutions

By Kevin Irlen, THINK Technical Support, Symantec Corp.

This is a monthly column written by Symantec's Technical Support Engineers intended to provide you with information on Symantec products. This month we cover a single commonly asked question of Symantec’s THINK group.

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

A jGNE Starter Kit for THINK C

[This month’s THINK Top 10 is actually not a list of the top ten questions to Symantec. Instead, it handles a single commonly asked question of the THINK group. What we’d like to know is do you like this type of article, or would you prefer us to return to the Top 10 Q&A style? Send me your thoughts - my editorial e-mail addresses are on page 2 of this issue. - Ed.]

While all the latest and greatest stuff rushes relentlessly at us - C++, AppleScripting, Bedrock, PowerPC, etc. - there remain the numerous loose ends and open questions concerning Macintosh programming that Symantec Tech Support folks get asked for help with every day. Often, dealing with such questions is a straightforward matter of steering a programmer toward the appropriate sections of Inside Macintosh, the odd Tech Note, or to one of the programming forums online. Certain problems seem to fall between the cracks, however; too general to be solved by a couple of Toolbox calls, yet too Macintosh-specific to be readily solved with no clear documentation path to follow. The more often a given problem of this kind crops up, the more it cries out for a generic solution - a tech support solution.

Writing and installing a GetNextEvent filter is one such recurring problem. Essential to the functioning of many extensions, as well as applications, this oddity is mentioned only in a tiny Tech Note, with scant information about how actually to implement it.

From Macintosh Tech Note #85:

GetNextEvent uses a filter (GNE filter) which allows for a routine to be installed which overrides (or augments) the behavior of the system. The GNE filter is installed by pointing the low-memory global jGNEFilter (a long word at $29A) to the routine. After all other GNE processing is complete, the routine will be called with A1 pointing to the event record and D0 containing the boolean result. The filter may then modify the event record or change the function result by altering the word on the stack at 4(A7). This word will match D0 initially, of course.

Sounds good. This is exactly what you’ll need to blink the Apple menu, intercept disk insert events to check disks for viruses, trap special key sequences system-wide, etc. But this is where many a THINK user throws up his or her hands and calls us, wanting to what in the world to do with this information! How do you write such a routine? Do you have to do the whole thing in assembly? How exactly do you install it?

Clearly, given the register-based calling mechanism, “some assembly is required,” and naturally, installation will need to be done by an INIT. But why isn’t there some standard way of doing this, and shouldn’t you be able to write your filter in C? Why ask why? The jGNE Starter Kit, included in full on the companion disk, asks why, and answers by providing a jGNE installer INIT that can be used and re-used simply by replacing resources with ResEdit, along with everything else needed to develop and test custom jGNE’s. In this article, I’ll explain how the INIT works, and what it expects from the ‘CODE’ resource you drop in.

In solving the jGNE problem, there are essentially two hurdles to be cleared, the first relatively low, the second a bit higher. First, we must have a scheme for dealing with the jGNE calling mechanism described in Tech Note 85; and second, we must allow for multiple jGNE’s to coexist, i.e. to be chained. Credit for the snippet of assembly language that follows belongs, as far as I know, to Steve Stockman, a frequent contributor to the Macintosh Programming and Symantec Development Tools forums on CompuServe. It leaps the first hurdle, and alludes to clearing the second. I discovered it while browsing one day, in a message to a programmer in need, and it is what Mr. Stockman left out of his message that inspired me to create this Kit.

Anyway, here’s the only assembly necessary:

/* 1 */

main()
{  
 asm  
 {   
  move.l   A1   ,-(SP)       ; A1    holds theEvent   
  move.w   8(SP),-(SP)       ; 8(SP) holds hasEvent 
 ; (4(SP) + 4 we just pushed)   
  jsr      myjGNEFilterFunc   
  move.w   D0,10(SP)         ; put return value back 
 ; at what will be 4(SP)   
  addq.l   #2,SP             ; pop hasEvent     (10 - 2 = 8)
  move.l   (SP)+,A1          ; pop theEvent back into A1 
 ; ( 8 - 4 = 4)
  movea.l  #0xFFFFFFFF,A0    ; this gets overwritten at 
 ; INIT time with either the   
  jmp      (A0)              ; next jGNE's address, or an 
 ; RTS if there isn't one!  
 }
}

There are two essential things to note about this code. First, the GetNextEvent call mechanism has been kept completely separate from the filter function itself, which may now be a simple C function of the form:

/* 2 */
            
short myjGNEFilterFunc(short hasEvent,EventRecord *anEvent);  

This function must return zero if it eats the event, non-zero if the event still needs to be handled.

The second feature of this code is something that no doubt looks a bit strange. As the comment indicates: the movea.l line is not in its final form. It is going to be tampered with at INIT time! The reason for this is that you inevitably want to be able to install multiple jGNE’s, and have them chain from one to the next. The problem is that a jGNE has no way of knowing in advance whether or not it will be last in the chain; and therefore no way of knowing whether to RTS when finished (allowing GetNextEvent to return to the current application) or to JMP to the next jGNE in line. This order isn’t determined until INIT time. A jGNE could be “loaded” simply by floating its code in the system heap and storing a pointer to it in the low-memory global jGNEFilter (0x29A). But in order for multiple jGNE’s to coexist, they must cooperate at INIT time by checking to see whether or not someone has loaded before them - and if so, store the previous jGNE’s address to jump to instead of simply returning. In this way, jGNE’s can chain in last-to-load, first-to-execute order.

Now if you just want to use the jGNE Starter Kit, you don’t have to worry about any of this. All you have to do is use the above code in conjunction with the generic jGNE INIT. The latter part of this article contains a brief discussion on building your jGNE project, which should be more than enough to get you “started.” For those of you in the mood for a hack, read on!

There are any number of strategies for stashing a “special” value so that a piece of code can find it later, but the jGNE Starter Kit’s strategy here is to go to the extreme and actually overwrite the machine instruction that depends on the value of the previously loaded jGNE, once, at INIT time, and then not to worry about it again. No finding the stashed value, or testing it, or nuthin. Here’s the entire code for the INIT (excluding the sacred ShowInitIcon routine), and an explanation to follow:

/* 3 */

#define rMyINITIcon  -4094     // ID of icon to be shown 
 // at INIT time
#define rMyjGNE        128     // ID of jGNE 'CODE' resource

#define kBRAoffset  0x0018     // offset of bra to main in a 
 // std header CODE resource
#define kLoadOffset 0x0014     // offset in "main" of the 
 // line to be changed!

Ptr jGNEFilterPtr : 0x029A;   // low-memory global: 
 // jGNEfilter

OSErr ShowInitIcon(short icon_num,short move_x_by);

main()
{
 Handle  myjGNE;
 Ptr     branInstruction,loadInstruction;
 OSErr   iErr;

 SetZone(SysZone);

 myjGNE = Get1Resource('CODE',rMyjGNE);

 if (myjGNE)
 {
  DetachResource(myjGNE);

  branInstruction = *myjGNE         + kBRAoffset;
  loadInstruction = branInstruction + *((short *) 
 (branInstruction + 2)) +kLoadOffset;

  if (jGNEFilterPtr) *((long *) (loadInstruction + 2)) = 
 (long) jGNEFilterPtr;
  else               *loadInstruction = 0x4E75;

  jGNEFilterPtr = *myjGNE;
 }
 else SysBeep(10);

 iErr = ShowInitIcon(rMyINITIcon,-1);

 if (iErr != noErr) SysBeep(10);
}

OK, this is code may be short, but it does have a couple of rather obscure lines, and a couple of unfamiliar constants. We are attempting to locate in memory, within the loaded ‘CODE’ resource that is our jGNE, the exact word where the “movea.l” instruction begins, and this depends on two things. First, since our assembly snippet comprises the main() function of the jGNE resource, one key constant is the offset of the “movea.l” instruction from the beginning of main(). Disassembly (crude, but effective) reveals that this offset is 20 words (0x0014), and we’ll name the constant kLoadOffset since it’s the instruction that loads the next jGNE address to be jumped to.

This is only halfway toward locating the instruction, though, because where, after all, is main()? The answer is that in a code resource, main() can wind up anywhere. Fortunately, the entry point to a THINK C code resource is a standard header (unless you make it otherwise), and this standard header contains an BRA.S instruction whose sole purpose is to branch to main(). Examine a code resource (using MacsBug, or a code editor), and you will see that this branch instruction is 24 words (0x0018) from the beginning (segment loader info and other no-op stuff). Hence the constant kBRAOffset.

So here’s the deal: load the code resource, dereference the handle, add kBRAOffset to its value, and you’re pointing at the BRA.S instruction. The second word of that instruction is the number of bytes to branch over to get to main(). So add kLoadOffset to that and you’re pointing at your load instruction:

/* 4 */

branInstruction = *myjGNE         + kBRAoffset;
loadInstruction = branInstruction + *((short *) 
 (branInstruction + 2)) + kLoadOffset;

Now we’re home free. All we do now is decide whether to change the second word of that load instruction to the address of the next jGNE, or just replace the instruction with an RTS (0x4E75):

/* 5 */

if (jGNEFilterPtr) *((long *) (loadInstruction + 2)) = 
 (long) jGNEFilterPtr;
else               *loadInstruction = 0x4E75;

Now we can safely replace whatever was in jGNEFilterPtr with a pointer to our jGNE filter, and chaining will take care of itself (assuming the other jGNE’s you’ve installed are just as polite).

That’s all there is to it. Although this technique may be a bit unorthodox, it provides an extremely high degree of modularity to an aspect of Mac programming that is usually shrouded in mystery - one of those tasks that is more often abandoned than solved, or else solved so painfully that one shudders at the thought of having to go through it again.

An additional windfall is that this installation procedure does not in any way depend upon being executed at INIT time. It can be run from a regular THINK C project, allowing you to install a jGNE filter on the fly, as you’re developing it. If you install a faulty filter, removing it is as easy as restoring the previous value to the low-memory global jGNEFilter. Just be sure to note the value of jGNEFilter before you do your install, then, in MacsBug for example, it’s just “SM jGNEFilter oldval” to restore it. Of course the detached resource will just lay there in your system heap, but why worry?

To wrap things up, let’s look briefly at the process of writing the jGNE filter itself. The Starter Kit comes with a generic jGNE code resource project that contains a single file, “generic jGNE.c”. If you build this project, you’ll get a resource of type ‘CODE’ and id 128 that can be dropped into the generic jGNE INIT with ResEdit (in fact, it’s already been put there, but you can do it again just to see how fun and easy it is). Once installed, this filter demonstrates the awesome power of the jGNE mechanism by beeping whenever the user types cmd-shift j, g, n, or e (author is not responsible if this interferes with the proper functioning of any other applications). Your filter will hopefully do something more useful, but the basic structure will be essentially the same. Here’s the code:

/* 6 */

main()
{  
 asm  
 {   
  move.l   A1   ,-(SP)       ; A1    holds theEvent   
  move.w   8(SP),-(SP)       ; 8(SP) holds hasEvent 
 ; (4(SP) + 4 we just pushed)   
  jsr      myjGNEFilterFunc   
  move.w   D0,10(SP)         ; put return value back at 
 ; what will be 4(SP)   
  addq.l   #2,SP             ; pop hasEvent   
  move.l   (SP)+,A1          ; pop theEvent back into A1   
  movea.l  #0xFFFFFFFF,A0    ; this gets overwritten at INIT 
 ; time with either the   
  jmp      (A0)              ; next jGNE's address, or an 
 ; RTS if there isn't one!  
 }
}

#include <SetUpA4.h>         // DO NOT move this before main! 
 // (It generates code.)

short myjGNEFilterFunc(short hasEvent,EventRecord *theEvent)
{
 char theChar;

 RememberA0(); SetUpA4();

 if (hasEvent)
 {
  switch (theEvent->what)
  {
   case keyDown:
   case autoKey:
    theChar = theEvent->message & charCodeMask;

    if  ((theEvent->modifiers & cmdKey) && 
 (theEvent->modifiers & shiftKey))
     if ((theChar == 'j') || (theChar == 'g') ||
         (theChar == 'n') || (theChar == 'e'))
     {
      SysBeep(10);

      hasEvent = 0;
     }

   default:
    break;
  }
 }
 RestoreA4();

 return hasEvent;
}

Just your basic event-handling switch block, plus RememberA0, SetupA4, and RestoreA4 to allow for global and static variables. Of course, you can handle any events you like and in as sophisticated a manner as you’d like, with additional function calls, multiple source files and segments if necessary, MacTraps, ANSI-A4, etc.

With the jGNE Starter Kit, you’ll have that Apple menu blinking in no time!

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but 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 MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
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
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.