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

Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »
Live, Playdate, Live! – The TouchArcade...
In this week’s episode of The TouchArcade Show we kick things off by talking about all the games I splurged on during the recent Playdate Catalog one-year anniversary sale, including the new Lucas Pope jam Mars After Midnight. We haven’t played any... | Read more »

Price Scanner via MacPrices.net

Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
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
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more
New promo at Visible: Buy a new iPhone, get $...
Switch to Visible, and buy a new iPhone, and Visible will take $10 off their monthly Visible+ service for 24 months. Visible+ is normally $45 per month. With this promotion, the cost of Visible+ is... Read more
B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for $100 off Apple’s new MSRP, only $899. Free 1-2 day delivery is available to most US addresses. Their... Read more
Take advantage of Apple’s steep discounts on...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply 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
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
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
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.