TweetFollow Us on Twitter

Executing Code
Volume Number:10
Issue Number:4
Column Tag:Powering UP

Executing Code
On A Power Macintosh

PEF files are more than just object code; at last you get initialization routines and global data

By Richard Clark, Apple Computer, Inc.

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

This month’s Powering Up takes a different approach than previous columns - in the past, we told you about moving existing code to the Power Macintosh. Today, we’ll tell you some things about using the new capabilities of the Power Macintosh runtime to enhance new and existing applications.

The greatest advantages on the Power Macintosh come from its speed and a new runtime architecture. This architecture was designed from the ground up for operation on a RISC processor; in fact, most of the new runtime was derived from IBM’s runtime model for their RISC systems. The new runtime architecture supports:

• Executable code that may be stored anywhere (i.e. in ROM, in a resource, or in the data fork of a file)

• Executable code which may have its own static data (including global variables)

• Executable code which may export code and data, and which can import code and data automatically from other executables, and

• Register-based calling conventions which execute quickly and efficiently

The structure of executable code

On a Power Macintosh, all native code is packaged up as “fragments.” An application consists of one large fragment (stored in the data fork of the application file), with supporting resources such as windows and menus in the resource fork. Other kinds of PowerPC code, such as INITs and CDEVs, may be stored as fragments in a resource or in the data fork of the file. Finally, the ROMs on a Power Macintosh include fragments which implement parts of the System software.

To support such a wide range of uses, each fragment has some important common capabilities: each has its own static data, references to imported code or data, and pointers to functions and variables that it exports. Each fragment is stored in a “PEF container”, which holds code in the Preferred Executable Format (PEF). Each PEF container consists of three parts: a Data Segment, a Code Segment, and a Loader Segment. Each of these segments is used when loading a fragment into memory:

• The Code Segment holds the executable code. The system treats code as read only, and may load the code anywhere in memory. As a result, all branches in the code have to be either relative to the current location, or go through pointers.

• The Data Segment holds the static data for the code, and a special table called the “Table of Contents” or TOC. The TOC contains pointers to each global variable used by the program, as well as pointers to code which cannot be accessed through a PC-relative branch or which exist in other code fragments.

• The Loader Segment contains tables which list each import and export for the current fragment, and other information as required to load a fragment.

PEF containers always retain the same format no matter where they are stored.

When a fragment is first loaded, the Code and Data segments are copied into memory (where they become Code and Data sections.) If a fragment uses code or data from other fragments, the Code Fragment Manager (CFM) locates and loads the referenced fragments. The CFM then sets up the static data for each loaded fragment; this involves filling in pointers in the Table Of Contents, expanding initialized data values, and calling the fragment’s optional “initialization routine.” Once this is done, the CFM returns the fragment’s “main” address and a unique “connection ID.”

If you try to load an already loaded fragment, the code is not loaded twice, but a second copy of the data might be loaded. Fragments support three types of data sharing:

• Global data sharing uses only one data section no matter now many times the code is loaded.

• Per-context data sharing - the default setting - loads the code once, but allocates a different data section for each “context.” (A “context” is a name space associated with each application, so all of the fragments used by an application (and all of the fragments they use) fall into the same context.) This setting allows a fragment to treat each application which calls it as a separate entity.

• Per-load data sharing allocates a data section each time the fragment is loaded, even if multiple load requests come from the same context. You might use this feature to implement a “network communications” fragment where each time you load the fragment you get another connection to the network. Each connection would get its own copy of the static data.

The Fragment Loading API

Fragments are loaded through calls to the Code Fragment Manager, as documented in FragLoad.h. The FragLoad API consists of 7 calls for loading and unloading fragments, as well as looking up function and data pointers in a loaded fragment:

• GetDiskFragment is commonly used for loading “plug-in additions” - it takes an FSSpec for a file and loads the container contained in the data fork.

• GetMemFragment “prepares” a fragment that was loaded into memory without using the Code Fragment Manager.

• GetSharedLibrary locates an existing Shared Library on the disk and loads it. This call is normally used to get a connection ID for one of the standard shared libraries (such as the System software “InterfaceLib”) before looking up the address of an exported function.

• CloseConnection is used to unload a fragment. This function takes the Connection ID returned by one of the above calls, checks a reference count which is maintained by the CFM, and unloads the code and/or data sections for the given fragment.

• FindSymbol looks up a symbol (code or data pointer) by name given a string and a connection ID. If your application supports drop-in additions similar to HyperCard XCMDs, you could use this to look up the address of an optional function in an addition. As we will see later, this function plays a key role in linking 68K code to a PowerPC application.

• CountSymbols counts the total number of symbols exported from a fragment. Like FindSymbol, this call also requires a connection ID.

• GetIndSymbol can be used to index through all of the symbols exported from a fragment. It takes a connection ID and an index number, and returns the symbol’s name and address.

The API calls in action

We now know enough to start loading and executing code contained in a PEF container. The following code loads a fragment from the data fork of a file and prepares it for execution. (This code is part of “SimpleApp”, which is located on the MacTech source code disks or from the MacTech forums on line.)


/* 1 */
FSSpec  fileSpec;
ProcPtr mainAddr;
ConnectionIDconnID;
OSErr err;
Str255  errName;
err = GetDiskFragment ( &fileSpec, 0, 0, fileSpec.name,
 kLoadNewCopy, &mainAddr, (Ptr*)&gMain,
 errName);

That’s all there is to it - once this call is made, “mainAddr” contains a pointer into the fragment (usually the entry point for the code, though the fragment could put a pointer to some static data there if it wanted to export a table of procedure pointers, for example.) The returned connection ID can be used to look up other exports from the fragment, or to unload the fragment via a call to CloseConnection:

CloseConnection(&connID);

Loading a resource-based fragment is a little more difficult: it’s your responsibility to get the fragment into memory, then you have to ask the CFM to “prepare” the fragment for execution:


/* 2 */
FSSpec  fileSpec;
ProcPtr mainAddr;
ConnectionIDconnID;
short refNum;
Handle  codeResource;
OSErr err;
Str255  errName;

refNum = FSpOpenResFile(&fileSpec, fsCurPerm);
if (ResError() == noErr) {
  codeResource = Get1IndResource('PEF ', 1);
  if (codeResource != NULL) {
    DetachResource(codeResource );
    HLock(codeResource );
    // We have the code, but it's not ready to use yet
    // Ask the Code Fragment Manager to "prepare" the code for execution
    err = GetMemFragment (*codeResource , 0, fileSpec.name,
 kLoadNewCopy, &connID, (Ptr*)&mainAddr,
 errName);
  }
  CloseResFile(refNum);

In both of these cases, if the load fails, err will return an appropriate error code and errName will contain the name of the offending fragment.

Using global variables in fragments -
the Initialization routine

One of the more interesting aspects of fragments is how global variables are supported. Every fragment may have its own static data, including global variables, automatically, and this data can be initialized to set values by the Code Fragment Manager. Thus, if you wrote:

 static int x = 1234;
 static ProcPtr y = &z;

x would receive the value 1234 (stored in the container’s data segment), and y would receive the address of function “z”. (This is actually the address of a Transition Vector, as described in “How TOC switches occur” below, and is computed at load time.)

However, the CFM allows fragments to go beyond these simple initializations. Each fragment may designate optional “Initialization” and optional “Termination” routines which will be called when the fragment’s data section is being set up and torn down. The Initialization routine receives a pointer to a block of useful information, including a FSSpec for the fragment’s file, and can return an error value to stop the fragment from loading. (Otherwise, the Initialization routine must return noErr.) The termination routine takes no parameters and returns non values, and release memory, close files, and otherwise undo whatever the initialization routine did.

The initialization and termination routines could be used to implement fully self-initializing Macintosh managers, for instance, or C++ classes complete with their own constructors and destructors. In the sample application, the initialization routine is used to get the FSSpec for a drop-in addition file from within that file’s code. This allows the addition to access its own resources.


/* 3 */
OSErr OurInitRoutine (InitBlockPtr initBlkPtr)
{
 OSErr  err = noErr;
 short  refNum = -1;
 
 // Make sure this code is coming from the data fork of a file
 if (initBlkPtr->fragLocator.where == kOnDiskFlat) {
 refNum = FSpOpenResFile(
 initBlkPtr->fragLocator.u.onDisk.fileSpec,
 fsCurPerm);
 // and so on 

Next month in Powering Up

Next month’s column takes a look at the Power Macintosh calling conventions, and at how that affects debugging.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fallout Shelter pulls in ten times its u...
When the Fallout TV series was announced I, like I assume many others, assumed it was going to be an utter pile of garbage. Well, as we now know that couldn't be further from the truth. It was a smash hit, and this success has of course given the... | Read more »
Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »
The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »

Price Scanner via MacPrices.net

Verizon has Apple AirPods on sale this weeken...
Verizon has Apple AirPods on sale for up to 31% off MSRP on their online store this weekend. Their prices are the lowest price available for AirPods from any Apple retailer. Verizon service is not... Read more
Apple has 15-inch M2 MacBook Airs available s...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more
May 2024 Apple Education discounts on MacBook...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $300 off the purchase of a new MacBook... Read more
Clearance 16-inch M2 Pro MacBook Pros in stoc...
Apple has clearance 16″ M2 Pro MacBook Pros available in their Certified Refurbished store starting at $2049 and ranging up to $450 off original MSRP. Each model features a new outer case, shipping... Read more
Save $300 at Apple on 14-inch M3 MacBook Pros...
Apple has 14″ M3 MacBook Pros with 16GB of RAM, Certified Refurbished, available for $270-$300 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year warranty is... Read more
Apple continues to offer 14-inch M3 MacBook P...
Apple has 14″ M3 MacBook Pros, Certified Refurbished, available starting at only $1359 and ranging up to $270 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year... Read more
Apple AirPods Pro with USB-C return to all-ti...
Amazon has Apple’s AirPods Pro with USB-C in stock and on sale for $179.99 including free shipping. Their price is $70 (28%) off MSRP, and it’s currently the lowest price available for new AirPods... Read more
Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more

Jobs Board

Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
*Apple* App Developer - Datrose (United Stat...
…year experiencein programming and have computer knowledge with SWIFT. Job Responsibilites: Apple App Developer is expected to support essential tasks for the RxASL Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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.