TweetFollow Us on Twitter

PowerPC Code
Volume Number:10
Issue Number:4
Column Tag:Powering Up

Connecting A 68k Object File
To PowerPC Code

A robust technique for loading and calling 68K modules from your PowerPC application

By Richard Clark, Apple Computer, Inc.

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

Many developers run into a major problem when porting code to PowerPC: incorporating 68K object models which came from an outside vendor. Since you can’t just hand a 68K module to the PowerPC linker, you have to find some alternative for loading the library and calling the library’s functions. Fortunately, developers can use the Code Fragment Manager and the Mixed Mode Manager together to solve this problem.

The solution involves creating a stand-alone version of the 68K code, then assembling a “jump table” of Universal Procedure Pointers which the application can use to call this code. Since applications (and, in fact, any PowerPC code fragment) can have global variables, it makes sense to allocate this table within the application. However, since the 68K library entry points are only available to the 68K code, that code has to create the universal procedure pointers. This would create an impossible dilemma except for one fact - both Mixed Mode and the Code Fragment Manager can be called from emulation on a Power Macintosh via A-Traps.

Thus we have a solution - the application must create the jump table as a global variable, and then pass its address to the 68K code which assembles the jump table. (An alternate method involves exporting the table from the application. The 68K code must open a connection back to the application, and ask the CFM for the address of the jump table.) The 68K code creates Universal Procedure Pointers to fill the table, which allows the application to call the library functions using Mixed Mode.

Creating the Jump Table

The first step is to prepare a list of all of the functions that your application calls in the library. Next, define ProcInfo values for each of these functions, using the MixedMode.h header and any header which defines callback functions (such as Controls.h) as a guide. You should also create macros for creating and calling a UniversalProcPtr in this way.

Next, create a data structure which contains Mixed Mode “Universal Procedure Pointers” for each of these functions. Put a copy of this data structure into a global variable in your PowerPC application, and don’t declare it as “static” (i.e. hidden.) You should also export this table, for a reason that will become clear shortly.


/* 1 */
// This is a header file common to the application and 68K code 

#include <ConditionalMacros.h>
#include <MixedMode.h>

typedef void (*CallbackPtr)(void); // A pointer which is fed to the library

typedef pascal OSErr (*Routine1ProcPtr)(CallbackPtr callbackRoutine);

enum {
 uppRoutine1ProcInfo = kPascalStackBased
  | RESULT_SIZE (SIZE_CODE(sizeof(OSErr)))
  | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(CallbackPtr)))
};

#if USESROUTINEDESCRIPTORS
// Use these definitions if we're compiling for Power Macintosh or another
// Macintosh system which supports Mixed Mode
typedef UniversalProcPtr Routine1UPP;

#define CallRoutine1Proc(userRoutine, longValue)         \
 CallUniversalProc((UniversalProcPtr)(userRoutine),\
 uppRoutine1ProcInfo, longValue)
#define NewRoutine1Proc(userRoutine) \
 (RoutineUPP) NewRoutineDescriptor((ProcPtr)userRoutine, \
    uppRoutine1ProcInfo, GetCurrentISA())
#else
// Use these definitions if we're compiling for a 68K-based Macintosh
typedef Routine1ProcPtr Routine1UPP;

#define CallRoutine1Proc(userRoutine, longValue)         \
 (*((Routine1ProcPtr )userRoutine))(longValue)
#define NewRoutine1Proc(userRoutine) \
 (Routine1UPP)(userRoutine)
#endif

 
// Here's the list of Universal Procedure Pointers
struct JumpTable {
 Routine1UPProutine1;
};

typedef struct JumpTable JumpTable, *JumpTablePtr;

// === Information on calling the 68K setup functions
typedef pascal OSErr (*SetupProcPtr)(JumpTablePtr);

enum {
 uppSetupProcInfo = kPascalStackBased
  | RESULT_SIZE (SIZE_CODE(sizeof(OSErr)))
  | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(JumpTablePtr)))
};

#if USESROUTINEDESCRIPTORS
// Use these definitions if we're compiling for Power Macintosh or another
// Macintosh system which supports Mixed Mode
typedef UniversalProcPtr SetupUPP;

#define CallSetupProc(userRoutine, jumpTableAddr)        \
 CallUniversalProc((UniversalProcPtr)(userRoutine),\
 uppSetupProcInfo, jumpTableAddr)
#define NewSetupProc(userRoutine)  \
 (SetupUPP) NewRoutineDescriptor((ProcPtr)userRoutine, \
    uppSetupProcInfo, GetCurrentISA())
#else
// Use these definitions if we're compiling for a 68K-based Macintosh
typedef SetupProcPtr SetupUPP;

#define CallSetupProc(userRoutine, jumpTableAddr)        \
 (*((SetupProcPtr)userRoutine))(jumpTableAddr)
#define NewSetupProc(userRoutine)  \
 (SetupUPP)(userRoutine)
#endif

Next, you have to create the “setup” function in 68K code and link it to your 68K object library. This routine needs to fill in each of the pointers in the table. The resulting code should be compiled, linked, and made into a stand-alone 68K code resource.

Granted, this technique could prove difficult if the library depends on having an A5 world. If your 68K library requires global variables, you must apply one of the special coding techniques documented in the Macintosh Developer Technical Notes or develop magazine.) Also note that if you want this code to run on a 68K machine, you should check for the presence of Mixed Mode and react appropriately.


/* 2 */
pascal OSErr BuildJumpTable(JumpTablePtr theJumpTable)
// Build a table of pointers to functions in our linked library
{
 OSErr  err;
 // Fill in the table with pointers to each library function
 theJumpTable->routine1 = NewMyRoutineProc(Routine1);
 err = MemError();
 return err;
}

The alternate approach involves exporting the jump table from the Application using the CFM, and letting the 68K code ask the CFM for the table’s address. Note the use of a STR# resource to store the application and table name strings - this avoids needing an A5 world just for the string constants. (Note that this code will not work on a machine which doesn’t have the Code Fragment Manager or Mixed Mode.)


/* 3 */
OSErr   err;
 JumpTablePtr  theJumpTable;
 ConnectionID  connID = 0;
 Ptr    mainAddr;
 Str255 errName, appName, tableName;
 SymClass symClass;
// Locate the application that called us
 GetIndString(&appName, 128, 1); // Assuming the name is in a STR#
 err = GetSharedLibrary(&appName, kPowerPCArch, 0, 
 &connID, &mainAddr, &errName);
 if (err) goto done;
 
 // Now, locate the shared table
 // (it's a pointer stored in a global variable)
 GetIndString(&tableName, 128, 2);// The table name is in the same STR#
 err = FindSymbol(connID, &tableName, 
 (Ptr*)&myTablePointer, &symClass);
 if (err) goto done;
// Insert the code to create UniversalProcPtrs here
done:
 if (connID)
 CloseConnection(&connID);
  return err;

To initialize this table, simply load the code resource from the application and call it via Mixed Mode. When the resource returns, the jump table will be full of Universal Procedure Pointers. Therefore, you should then modify your application to use Mixed Mode and the pointers in the table to call the library functions.


/* 4 */
// include the usual macros for creating a UniversalProcPtr for our callback 
routine
JumpTable gJumpTable;
// Load the stand-alone code
Handle  theResource;
theResource= Get1IndResource('STUB', 1);
if (theResource) {
  MoveHHi(theResource);
  HLock(theResource);// Lock it -- and NEVER unlock it
  // Call the entry point, no parameters
  CallSetupProc(*theResource, &gJumpTable);  
 // we know it's 68K, so we didn't
 // bother with creating a Routine Descriptor
  // Create a UniversalProcPtr for our callback routine
  CallbackUPP ourCallback;
  ourCallback = NewCallbackProc(MyCallbackRoutine);
  result = CallRoutine1Proc(gJumpTable.routine1,ourCallback );
  DisposeRoutineDescriptor(ourCallback);
}

Note that since the library function takes a callback pointer, we had to create a UniversalProcPtr and pass that instead of the address of the actual code. (If we hadn't done this, the machine would crash.) Since this causes memory to be allocated for a Routine Descriptor, we call DisposeRoutineDescriptor afterwards to release the memory.

That’s all there is to it! This is a robust technique which is now being used in several commercial applications - perhaps it will prove useful in yours.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
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 »

Price Scanner via MacPrices.net

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 up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
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

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.