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

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... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.