TweetFollow Us on Twitter

MACINTOSH C CARBON
MACINTOSH C CARBON: A Hobbyist's Guide To Programming the Macintosh in C
Version 1.0
2001 K. J. Bricknell
Go to Contents

CHAPTER 5

CARBON AND UNIVERSAL PROCEDURE POINTERS

Introduction

Previous demonstration programs have called a function (AEInstallEventHandler) which takes a universal procedure pointer as a parameter; however, an explanation of this term has been delayed until this chapter because the AEInstallEventHandler calls were only incidental to the main purpose of those demonstrations. The demonstration programs at Chapter 7 are the first in which calls to a system software function which takes a universal procedure pointer as a parameter are central to the demonstration. As a brief but necessary prelude for what is to come, therefore, this chapter addresses the role of universal procedure pointers in the general scheme of things, when and why they were introduced, and their relevance in the Carbon environment.

In a sense, universal procedure pointers are a piece of historical baggage dragged into Carbon by Mac OS 8/9. They was first introduced with the so-called Universal Headers which, in turn, were introduced with the Power Macintosh. They had to with the ability of the Power Macintosh to run applications that use the instruction set of the Motorola 680x0 microprocessor (used in 680x0-based Macintoshes) as well as applications that use the native instruction set of the Power Macintosh's PowerPC microprocessor.

In the Chapter 7 demonstration programs, the system software function which takes a universal procedure pointer is TrackControl. This function is called by your application when a mouse-down event occurs in a control, such as a scroll bar. Prior to the introduction of the Power Macintosh and the associated introduction of the Universal Headers, the TrackControl prototype looked like this:

     Sint16  TrackControl(TrackControl(ControlHandle theControl,Point localPoint,
                          ProcPtr actionProc);

The actionProc a parameter is simply the address of an application-defined function, called a callback procedure (or, in C terminology, a callback function) that is called repeatedly while the mouse button remains down. In other words, the TrackControl function used to take a procedure pointer (or, in C terminology, a function pointer) in its actionProc parameter.

The Universal Headers, which, amongst other things, allow you to write Classic API source code capable of being compiled as either 680x0 code or native PowerPC code, changed the prototype for TrackControl to:

     ControlPartCode  TrackControl(ControlHandle theControl,Point startPoint,
                                   ControlActionUPP actionProc);

Notice that the third parameter is now of type ControlActionUPP. This means that the actionProc parameter now takes a universal procedure pointer. This prototype has been carried through to the Carbon headers, hence the necessity to gain a basic understanding of universal procedure pointers.

The 68LC040 Emulator and the Mixed Mode Manager

The Emulator

This ability of the Mac OS 8/9 system software to execute applications that use the instruction set of the Motorola 680x0 microprocessor as well as applications that use the native instruction set of the PowerPC microprocessor is provided by an emulator (the 68LC040 Emulator). The emulator, which is essentially a 680x0 microprocessor implemented in software, provides an execution environment that is virtually identical to the execution environment found on 680x0-based Macintoshes.

One important aspect of the 68LC040 emulator is that it made it possible for parts of the system software to remain as 680x0 code while other parts were progressively re-written, primarily for reasons of speed, as native PowerPC code. In this regard, it is important to understand that some of Mac OS 8/9 still remains as 680x0 code. For example, in Mac OS 8.6, parts of the Control Manager (including, possibly, TrackControl) remain in 680x0 code. For the purposes of explanation, the following assumes that, in Mac OS 8/9, TrackControl still exists as 680x0 code.

The Mixed Mode Manager

In Mac OS 8/9, the emulator works together with a manager called the Mixed Mode Manager. The Mixed Mode Manager manages mode switches between code in different instruction set architectures (ISAs).

Mode Switches

In Mac OS 8/9, mode switches are required when an application calls a system software function (or, indeed, any other code) that exists in a different ISA. For example:

  • When a PowerPC application invokes a system software function that exists only as 680x0 code, a mode switch is required to move from the native environment to the emulator environment. Then, when that system software function completes, another mode switch is required to return from the emulator to the PowerPC environment to allow the PowerPC application to continue executing.

    This situation can occur in a Carbon application running on Mac OS 8/9 because, as previously stated, not all of Mac OS 8/9 has been re-written as native PowerPC code.

  • When a 680x0 application running under the emulator calls a system software function that exists as native PowerPC code, a mode switch is required to move out of the emulator and into the native PowerPC environment. Then, when that system software function completes, another mode switch is required to return to the emulator and to allow the 680x0 application to continue executing.

    This situation cannot occur in a Carbon application running on Mac OS 8/9 because all Carbon applications must be compiled as native PowerPC code.

The Mixed Mode Manager operates transparently to most applications and other types of software, meaning that most cross-mode calls (calls to code in a different ISA from the caller's ISA) are detected automatically by the Mixed Mode Manager and handled without intervention by the calling software.

Intervention in Mode Switching

Sometimes, however, executable code needs to interact directly with the Mixed Mode Manager to ensure that a mode switch occurs at the correct time. When writing native PowerPC code, you only have to intervene in the mode-switching process when you execute code whose ISA might be different from the calling code. For example, when you pass the address of your application-defined action function (native PowerPC code) to TrackControl (680x0 code), the ISA of the code whose address you are passing is different from the ISA of the function you are passing it to. In such cases, you must ensure that the Mixed Mode Manager is called to make the necessary mode switch. You do this by explicitly signalling:

  • The type of code you are passing.

  • The code's calling conventions.

Indicating the ISA of a Callback Function - Routine Descriptors

You create a routine descriptor for a particular function to indicate the ISA of that function (see Fig 1).The first field of a routine descriptor (goMixedModeTrap) is an executable 680x0 instruction which invokes the Mixed Mode Manager. The Mixed Mode Manager having been called, it inspects the remaining fields of the routine descriptor to determine whether a mode switch is required. The Mixed Mode Manager is particularly interested in the routineRecords field.

The routineRecords field is an array of routine structures, each element of which describes a single function. In the simplest case, the array of routine structures contains a single element.

The ISA and procInfo fields are the most important fields in a routine structure:

  • ISA Field. The ISA field contains the ISA code of the function being described, and always contains one of these two constants:

         kM68kISA  = (ISAType) 0  MC680x0 architecture.
         KPowerPCISA  = (ISAType) 1  PowerPC Architecture.
    

  • procInfo Field. The procInfo field contains the function's function information, including the function's calling conventions and information about the function's parameters.

Creating a Routine Descriptor For a Control Action Function

Using the function NewControlActionUPP, you can create a routine descriptor for a control action function as follows, in which myControlAction is your application-defined control action function:

     ControlActionUPP myControlActionUPP;

     myControlActionUPP = NewControlActionUPP(myControlAction);

Notice that the result returned by NewControlActionUPP is of type ControlActionUPP. The UPP stands for a universal procedure pointer, which is defined to be either a 680x0 function pointer or a pointer to a routine descriptor (hence the term "universal"). Thus, in Mac OS 8/9, the effect of the call to NewControlActionUPP depends on whether it is executed in the 680x0 environment or the PowerPC environment:

  • In the 680x0 environment, NewControlActionUPP simply returns its first parameter, that is, a pointer to your application-defined control action function.

  • In the PowerPC environment, NewControlActionUPP creates a routine descriptor in your application heap and returns the address of that routine descriptor.

Effect of the Routine Descriptor

Once you have created the routine descriptor, you can later call TrackControl like this:

     TrackControl(myControl,myPoint,myControlActionUPP);

In Mac OS 8/9, if your application is a PowerPC application (as will be the case in Carbon), the value passed in the myControlActionUPP parameter is not the address of your action function itself, but the address of the routine descriptor. If a 680x0 version of TrackControl executes your action function, it begins by executing the instruction in the first field of the routine descriptor. That instruction invokes the Mixed Mode Manager, which inspects the ISA of the action function (contained in the ISA field of the routine structure). Since that ISA differs from the ISA of the TrackControl function, the Mixed Mode Manager causes a mode switch. (Of course, if TrackControl existed as PowerPC code, the ISAs would be identical, and the Mixed Mode Manager would simply execute the action function without switching modes.)

In short, you solve the problem of indicating a routine's ISA by creating a routine descriptor and by using the address of that routine descriptor (that is, a universal procedure pointer) where you would have used the address of the function (that is, a procedure pointer) in the 680x0 programming environment.

Disposing of Routine Descriptors

Disposing of routine descriptors is only necessary or advisable if you know that you will not be using the descriptor any more during the execution of your application or if you allocate a routine descriptor for temporary use only.

Functions Requiring Universal Procedure Pointers

Some of the functions for which universal procedure pointers must be created are as follows:

Function Type

Examples are at the Demonstration Programs Associated With:

Control action functions

Chapters 7, 14, 17, and 21.

Event filter functions

Chapters 4, 8, 14, and 21.

Apple event handling functions

Chapters 10, 18, and 26.

Key filter functions

Chapter 14.

Edit text validation functions

Chapter 14.

User pane drawing functions

Chapters 14 and 21.

User pane activate functions

Chapter 14.

Carbon event handlers

Chapters 17 to 26.

Carbon event timers

Chapter 17, 18, 21, 23, and 26.

Navigation Services event handlers

Chapter 18, 21, 23, and 26.

TextEdit click loop functions

Chapter 21.

List search functions

Chapter 22.

List definition functions

Chapter 22.

Device loop drawing functions

Chapter 25.

Universal Procedure Pointers and Carbon

Carbon supports universal procedure pointers transparently. By using the system-supplied universal procedure pointer functions, your application will operate correctly in both the Mac OS 8/9 and Mac OS X environments.

On Mac OS 8/9, the universal procedure pointer creation functions allocate routine descriptors in memory just as you would expect. On Mac OS X, the implementation of universal procedure pointers depends on various factors, including the object file format you choose. Universal procedure pointers will allocate memory if your application is compiled as a CFM binary, but are likely to return a simple procedure pointer if your application is compiled as a Mach-O binary. (All demonstration programs in this book are compiled as CFM binaries so that they will run on both Mac OS 8/9 and Mac OS X. Mach-O binaries only run on Mac OS X.)

In Carbon, routine descriptors must be disposed of using the specific disposal function associated with the creation function. For example, routine descriptors created with NewControlActionUPP must be disposed of using DisposeControlActionUPP. The generic disposal function DisposeRoutineDescriptor is not supported in Carbon.

Creation/Disposal Functions Relevant to Demonstration Programs

Creating Routine Descriptors

ControlActionUPP             NewControlActionUPP(ControlActionProcPtr userRoutine);
ModalFilterUPP               NewModalFilterUPP(ModalFilterProcPtr userRoutine);
AEEventHandlerUPP            NewAEEventHandlerUPP(AEEventHandlerProcPtr userRoutine);
ControlKeyFilterUPP          NewControlKeyFilterUPP(ControlKeyFilterProcPtr userRoutine);
ControlEditTextValidationUPP NewControlEditTextValidationUPP(ControlEditTextValidationProcPtr
                             userRoutine);
ControlUserPaneDrawUPP       NewControlUserPaneDrawUPP(ControlUserPaneDrawProcPtr
                             userRoutine);
ControlUserPaneActivateUPP   NewControlUserPaneActivateUPP(ControlUserPaneActivateProcPtr
                             userRoutine);
TEClickLoopUPP               NewTEClickLoopUPP(TEClickLoopProcPtr userRoutine);
ListSearchUPP                NewListSearchUPP(ListSearchProcPtr userRoutine);
ListDefUPP                   NewListDefUPP(ListDefProcPtr  userRoutine);
DeviceLoopDrawingUPP         NewDeviceLoopDrawingUPP(DeviceLoopDrawingProcPtr userRoutine);

Disposing of Routine Descriptors

void  DisposeControlActionUPP(ControlActionUPP userUPP);
void  DisposeModalFilterUPP(ModalFilterUPP userUPP);
void  DisposeAEEventHandlerUPP(AEEventHandlerUPP userUPP);
void  DisposeControlKeyFilterUPP(ControlKeyFilterUPP userUPP);
void  DisposeControlEditTextValidationUPP(ControlEditTextValidationUPP userUPP);
void  DisposeControlUserPaneDrawUPP(ControlUserPaneDrawUPP userUPP);
void  DisposeControlUserPaneActivateUPP(ControlUserPaneActivateUPP userUPP);
void  DisposeTEClickLoopUPP(TEClickLoopUPP userUPP);
void  DisposeListSearchUPP(ListSearchUPP userUPP);
void  DisposeListDefUPP(ListDefUPP userUPP);
void  DisposeDeviceLoopDrawingUPP(DeviceLoopDrawingUPP userUPP);

 
AAPL
$102.50
Apple Inc.
+0.25
MSFT
$45.43
Microsoft Corpora
+0.55
GOOG
$571.60
Google Inc.
+2.40

MacTech Search:
Community Search:

Software Updates via MacUpdate

VueScan 9.4.41 - 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
Cloud 3.0.0 - File sharing from your men...
Cloud is simple file sharing for the Mac. Drag a file from your Mac to the CloudApp icon in the menubar and we take care of the rest. A link to the file will automatically be copied to your clipboard... Read more
LibreOffice 4.3.1.2 - Free Open Source o...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
SlingPlayer Plugin 3.3.20.505 - Browser...
SlingPlayer is the screen interface software that works hand-in-hand with the hardware inside the Slingbox to make your TV viewing experience just like that at home. It features an array of... Read more
Get Lyrical 3.8 - Auto-magically adds ly...
Get Lyrical auto-magically add lyrics to songs in iTunes. You can choose either a selection of tracks, or the current track. Or turn on "Active Tagging" to get lyrics for songs as you play them.... Read more
Viber 4.2.2 - Send messages and make cal...
Viber lets you send free messages and make free calls to other Viber users, on any device and network, in any country! Viber syncs your contacts, messages and call history with your mobile device,... Read more
Cocktail 7.6 - General maintenance and o...
Cocktail is a general purpose utility for OS X that lets you clean, repair and optimize your Mac. It is a powerful digital toolset that helps hundreds of thousands of Mac users around the world get... Read more
LaunchBar 6.1 - Powerful file/URL/email...
LaunchBar is an award-winning productivity utility that offers an amazingly intuitive and efficient way to search and access any kind of information stored on your computer or on the Web. It provides... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
BBEdit 10.5.12 - Powerful text and HTML...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more

Latest Forum Discussions

See All

This Week at 148Apps: August 25-29, 2014
Shiny Happy App Reviews   | Read more »
Qube Kingdom – Tips, Tricks, Strategies,...
Qube Kingdom is a tower defense game from DeNA. You rally your troops – magicians, archers, knights, barbarians, and others – and fight against an evil menace looking to dominate your kingdom of tiny squares. Planning a war isn’t easy, so here are a... | Read more »
Qube Kingdom Review
Qube Kingdom Review By Nadia Oxford on August 29th, 2014 Our Rating: :: KIND OF A SQUARE KINGDOMUniversal App - Designed for iPhone and iPad Qube Kingdom has cute visuals, but it’s a pretty basic tower defense game at heart.   | Read more »
Fire in the Hole Review
Fire in the Hole Review By Rob Thomas on August 29th, 2014 Our Rating: :: WALK THE PLANKUniversal App - Designed for iPhone and iPad Seafoam’s Fire in the Hole looks like a bright, 8-bit throwback, but there’s not enough booty to... | Read more »
Alien Creeps TD is Now Available Worldwi...
Alien Creeps TD is Now Available Worldwide Posted by Ellis Spice on August 29th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Dodo Master Review
Dodo Master Review By Jordan Minor on August 29th, 2014 Our Rating: :: NEST EGGiPad Only App - Designed for the iPad Dodo Master is tough but fair, and that’s what makes it a joy to play.   | Read more »
Motorsport Manager Review
Motorsport Manager Review By Lee Hamlet on August 29th, 2014 Our Rating: :: MARVELOUS MANAGEMENTUniversal App - Designed for iPhone and iPad Despite its depth and sense of tactical freedom, Motorsport Manager is one of the most... | Read more »
Motorsport Manager – Beginner Tips, Tric...
The world of Motorsport management can be an unforgiving and merciless one, so to help with some of the stress that comes with running a successful race team, here are a few hints and tips to leave your opponents in the dust. | Read more »
CalPal Update Brings the App to 2.0, Add...
CalPal Update Brings the App to 2.0, Adds Lots of New Stuff Posted by Ellis Spice on August 29th, 2014 [ permalink ] | Read more »
Baseball Battle Review
Baseball Battle Review By Jennifer Allen on August 29th, 2014 Our Rating: :: SIMPLE HITTINGUniversal App - Designed for iPhone and iPad Simple and cute, Baseball Battle is a fairly fun baseball game for those looking for something... | Read more »

Price Scanner via MacPrices.net

Labor Day Weekend MacBook Pro sale; 15-inch m...
B&H Photo has the new 2014 15″ Retina MacBook Pros on sale for up to $125 off MSRP. Shipping is free, and B&H charges NY sales tax only. They’ll also include free copies of Parallels Desktop... Read more
Labor Day Weekend iPad mini sale; $50 to $100...
Best Buy has the iPad mini with Retina Display (WiFi models) on sale for $50 off MSRP on their online store for Labor Day Weekend. Choose free shipping or free local store pick up. Price is for... Read more
13-inch 1.4GHz MacBook Air on sale for $899,...
Adorama has the new 2014 13″ 1.4GHz/128GB MacBook Air on sale for $899.99 including free shipping plus NY & NJ tax only. Their price is $100 off MSRP. Read more
It’s Official: Apple Issues Invitations To Se...
Apple has issued one of its characteristically cryptic press invitations for a special event to be held at the Flint Center for the Performing Arts in hometown Cupertino on Sept. 9, 2014 at 10:00 am... Read more
Tablet Shipments To See First On-year Decline...
TrendForce analyst Caroline Chen notes that when the iPad launched in 2010, it was an instant hit and spurred a tablet PC revolution, with tablets so popular that that notebook PC sales stagnated and... Read more
SOBERLINK Releases Apple iOS Compatible Handh...
Cypress, California based SOBERLINK, Inc., creator of the first handheld Breathalyzer designed to improve recovery outcomes, continues to show prominence in the mobile alcohol monitoring space with... Read more
New 21″ 1.4GHz iMac on sale again for $999, s...
Best Buy has the new 21″ 1.4GHz iMac on sale for $999.99 on their online store. Their price is $100 off MSRP. Choose free shipping or free local store pick up. Price is for online orders only, in-... Read more
Smartphone Outlook Remains Strong for 2014, U...
According to a new mobile phone forecast from the International Data Corporation (IDC) Worldwide Quarterly Mobile Phone Tracker, more than 1.25 billion smartphones will be shipped worldwide in 2014,... Read more
Save up to $60 with Apple refurbished iPod to...
The Apple Store has Apple Certified Refurbished 5th generation iPod touches available starting at $149. Apple’s one-year warranty is included with each model, and shipping is free. Many, but not all... Read more
12-Inch MacBook Air Coming in 4Q14 or 2015 –...
Digitimes’ Aaron Lee and Joseph Tsai report that according to Taiwan-based upstream supply chain insiders, Apple plans to launch a thinner MacBook model either at year end 2014 or in 2015, and that... Read more

Jobs Board

*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
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.