TweetFollow Us on Twitter

Accelerating Code Resources

Volume Number: 13 (1997)
Issue Number: 6
Column Tag: Plugging In

Accelerating Code Resources and Import Libraries

by Fabrice Ferino, MDL Information Systems

How your plug-in can take advantage of the Power Macintosh run-time architecture without telling the host application

Import Libraries as Plug-ins

The traditional mechanism for the extension of a Macintosh application has been the use of code resources. The Power Macintosh line of computers, and its associated run-time environment, have enabled applications to provide a new way to implement extensions as import libraries using the "universal plug-in" architecture described in [4]. However, even if the application does not provide explicit support for the use of import libraries as their extension mechanism, it is possible and advantageous for a number of reasons to implement PowerPC native extensions as import libraries, and to still package the complete plug-in a single file without contributing to the clutter of the Extensions folder.

A Bit of History

For a long time, many of the successful Macintosh applications have provided a mechanism to extend their functionality. In the 68k run-time environment, this mechanism relied on the loading and executing of code resources. However, this type of code has been more difficult to write than application code because of the limitations imposed by the 68k run-time environment: no A5 world to reference the globals, the limitation of the size of the code resource to less than 32K, and limit to a single segment (because there is no jump table).

The majority of the modern development environments provide some ways to overcome most of these limitations. The A4 register is cleverly hijacked to reference the globals of the code resource, branch islands or the 68020 32-bit branching instructions are used to allow code resource of a size larger than 32k. Still, writing a 68k code resource requires more care and attention to detail than the common application code. Readers interested in this area are directed to the excellent information available on this subject. ([3], [5]).

The situation improved significantly with the arrival of the PowerPC run-time architecture. With the availability of the Code Fragment Manager (CFM), an integral part of the PowerPC system software, it became possible to implement extensions using import libraries (colloquially known as shared libraries). Each import library is a full-fledged MacOS citizen with its own global data space, and no size limits. Additionally, if virtual memory is enabled and the import library is located on a device that supports paging, the import library will be file-mapped and its code will not take space in the heap of the host application. With all these advantages, many PowerPC native applications (Code Warrior IDE, FreeHand, etc...) quickly adapted their plug-in mechanism to use import libraries.

However, some applications still require their extensions to be code resources (some of them have not be rewritten for the PowerPC architecture and others did not adopt the new mechanism for diverse reasons). For this case, it is still possible to take advantage of the increase of performance provided by the PowerPC family of microprocessors by adopting an accelerated code resource. An accelerated code resource runs only on Power Macintosh but can be called by both a 68k application or a PowerPC application.

The format of an accelerated code resource is simple: this is a CFM code fragment preceded by a routine descriptor. The first instruction in a routine descriptor is the Mixed Mode Magic A-trap that triggers the mode switch necessary when the PowerPC code resource is called by 68k code. But accelerated code resources, although they provide some of the advantages of import libraries, still have some of the old limitations (see [2] 1-39). Finally, accelerated code resources have a very annoying characteristic: they have been difficult to debug with a source level debugger like the Metrowerks Debugger. The Macintosh Debugger from Apple provides some support for debugging memory-based code resource but it is still awkward. Source level debuggers become confused because the CFM removes the connection information from its tables after a memory based fragment has been prepared.

All these problems can be solved if most of the code of the extension resides in an import library. The accelerated code resource then is just used as an interface between the application and the import library. Figure 1 shows the general structure of a 68k code resource plug-in, of an accelerated code resource plug-in, and of a hybrid accelerated code resource-import library.

Figure 1. Some architectures for plug-in code resources. Two other useful types not represented here are safe fat code resources and import library based safe fat code resources. The article focus on the build of the third type of code resources. RD: routine descriptor.

Another advantage is that import libraries can have multiple entry points. If you need to implement several code resources, each one providing an entry point to the application, each of these code resources can call its own entry point in the import library. This design makes the development of plug-ins that share code much easier and offers the possibility for plug-ins to easily share data at run-time. This can be done without having to allocate some data structure in the heap and devising a mechanism to inform the plug-ins how to access this import data. The idea for this plug-in architecture came when reading [2] 1-40:

"Note that a code fragment stored as an accelerated code resource can import both code and data from an import library. The code and data in an import library do not move in memory. As a result you can sidestep the restrictions on global data in an accelerated code resource by putting the global data used by the accelerated code resource into an import library."

To solve the debugging problem, this idea is extended to have most of the data and of the code in an import library.

A Model Plug-in Application Based on Sprocket

An example host application is needed to demonstrate the implementation of import library based accelerated code resources. Instead of selecting one of the real world applications that do not take advantage of import libraries for their plug-in mechanism, a modified version of the Sprocket framework that can load and execute plug-ins has been implemented. With these extensions, Sprocket becomes a good model of a 68k CFM unaware application. Note that the implementation is not claimed to be the best one, but is simple and powerful enough to explore the concepts exposed in this article. Using a 68k program makes the environment even more hostile for import libraries.

One main difference with real world applications is that the application does not scan a special plug-in folder but allows the user to load plug-ins by selecting the new Load Plug-in... menu item in the File menu. Consequently, the plug-ins used by the application can be located anywhere on any volume. (This feature will be used later in the article.)

Most of the code for these extensions reside in a new file PlugInSupport.cp. This file implements the loading and initialization of plug-ins and the forwarding of events to the loaded plug-ins. It also implements a simple callback mechanism. The only function provided by the callback is the creation of a new Sprocket window so that a plug-in window behaves correctly in the floating window environment of Sprocket. (A new subclass of Sprocket window designed to be used by plug-ins is also implemented.) Otherwise, the plug-in rules are typical of those found with most applications: the plug-ins must be code resources of a certain type ('PLUG' in our example), and the communication between the plug-in and the application is the exchange of pointers to data structures. The file PlugInBlock.h defines how the application and its plug-ins communicate.

Listing 1: PlugInBlock.h

#define kNumParam (8)

/* 
The align pragma will be ignored by most 68k compilers. If you are 
applying the techniques described here for an old 68k application, 
it is very likely that the include file provided does not include 
these pragma statements: add them now before you build your PowerPC 
native plug-in 
*/
#if PRAGMA_ALIGN_SUPPORTED
#pragma options align=mac68k
#endif

// message that the plug-in can receive 
enum
{
   plugInInit,
   plugInEvt,
   plugInLoadFile,
   plugInWindowClosed,
   plugInExit
};

// callback request message sent by the plug-in
enum
{
   createWindow
};

// the callback in the application will receive a pointer to this structure
// message is the code for the operation requested by the plug-in
// param is used to pass the parameters back and forth between the application
// and the plug-in
typedef struct 
{
   short            message;
   Ptr               param[kNumParam];
} CallbackParamBlock, *CallbackParamPtr; 

// definition of the callback entry point
// we use pascal callling convention because C calling conventions may 
// vary between compilers
typedef pascal Boolean (*CallBackEntryPoint)                                                    (CallbackParamPtr pb);

// the plug-in will receive a pointer to this structure
// similar to the struct received by the callback with the addition of 
// a pointer to the callback function in the application
typedef struct 
{
   short             message;
   Ptr               param[kNumParam];
   CallBackEntryPoint   callback;   
} PlugInParamBlock, *PlugInParamPtr; 

// definition of the plug-in entry point
// we use pascal callling convention because C calling conventions may 
// vary between compilers
typedef pascal Boolean (*PlugInEntryPoint) 
                         (PlugInParamPtr pb);

The Plug-in: a QuickDraw3D Viewer

The plug-in implemented is a QuickDraw3D file viewer. QuickDraw3D is available only on Power Macintosh. (A Windows95 implementation should be available by the time you read this.)

Figure 2. The QuickDraw3D viewer plug-in in action.

To build the plug-in we will use two projects: one for an accelerated code resource as the bridge between an import library and the host application, the other for the import library with all of the code of the plug-in. The accelerated code resource and import library will be packaged as a single file, instead of adding yet another file to the growing crowd in the Extensions folder. This also facilitates installation and removal of the plug-in. (The Extensions folder should really contain only the import libraries used by several applications, that is shared libraries, and not every import library used by any single application.) Each CodeWarrior project will use the product of the other project, so this requires some bootstrapping. Since we must have the PEF of the import library to successfully link the accelerated code resource, we start by building the import library.

The Import Library Project

The import library will export only one symbol: its main function called PlugInMain(). This function, like the code resource entry point, accepts a single parameter, a pointer to a PlugInParamBlock, and returns a Boolean. Displaying a QuickDraw3D file is very easy because QuickDraw3D provides a QD3DViewerObject that does most of the work [1]. The other interesting parts in the code are the definitions to build and call a universal procedure pointer (UPPs) to get to the callback procedure in the 68k application. The classic trap is to copy and paste similar definitions from the universal headers. However, the definitions in the universal headers are there to help set up UPPs for the functions in the source file not for the functions called by the source file. In this example we know that the callback procedure is in 68k code, so we use kM68kISA for the run-time architecture parameter in NewRoutineDescriptor().

Listing 2: main.c

/************************************************************
   main.c
   Entry point for the import library
************************************************************/
#include "PlugInBlock.h"

#include <QD3DViewer.h>
#include <CodeFragments.h>


typedef UniversalProcPtr CallBackUPP;

// procedure info for the callback procedure
enum {    
   callBackProcInfo = kPascalStackBased
       | RESULT_SIZE(SIZE_CODE(sizeof(Boolean)))
       | STACK_ROUTINE_PARAMETER(1,
     SIZE_CODE(sizeof(CallbackParamPtr)))
};

// macro to create and call a Universal Procedure Pointer for the callback
// We know the callback is 68K code so we make sure we are using 
// the constant kM68kISA. 
#define NewCallBackProc(userRoutine)      \
      (CallBackUPP) \ 
      NewRoutineDescriptor((ProcPtr)(userRoutine),\
               callBackProcInfo, kM68kISA)

#define CallCallBackProc(userRoutine,param)\
      CallUniversalProc((UniversalProcPtr)(userRoutine),\
                                 callBackProcInfo, param)

// typedef to satisfy the compiler when checking for unresolved symbols
typedef TQ3ViewerObject (*Q3ViewerNewProcType) 
                     (CGrafPtr, Rect*, unsigned long);
// Our globals
WindowPtr         gMyWindow;         // our window
TQ3ViewerObject    gMyViewer;         // the QD3D viewer object
Boolean            gFileOpened;      // has a file been opened ?
FSSpec            gCurrentFile;      // FSSpec of the file being displayed

// prototype for the exported function. We use pragma export
// to inform CodeWarrior that this is an exported function.
#pragma export on
Boolean PlugInMain(PlugInParamPtr pb);
#pragma export off

// prototypes for functions in this file
Boolean DoInit(PlugInParamPtr pb);
Boolean DoOpenFile(PlugInParamPtr pb);
Boolean DoWindowClosed(PlugInParamPtr pb);
Boolean DoEvent(PlugInParamPtr pb);
Boolean DoExit(PlugInParamPtr pb);
Boolean Get3DViewer( PlugInParamPtr pb);
Boolean IsColorPort(GrafPtr port);
Boolean SameFile( FSSpec *spec1, FSSpec *spec2 );

PlugInMain
/*********************************************************************
   PlugInMain
   Exported function.
   Based on the message, forwards the call to the appropriate 
   function
*********************************************************************/
Boolean PlugInMain( PlugInParamPtr pb)
{
   Boolean retVal;
   
   switch( pb->message)
      {
      case plugInInit:
         retVal = DoInit(pb);
         break;
      
      case plugInLoadFile:
         retVal = DoOpenFile(pb);
         break;
      
      case plugInWindowClosed:
         retVal = DoWindowClosed(pb);
         break;
         
      case plugInEvt:
         retVal = DoEvent(pb);
         break;
         
      case plugInExit:
         retVal = DoExit(pb);
         break;
         
      default:
         retVal = false;
         break;   
      }
      
   return retVal;
}

DoInit
/*********************************************************************
   DoInit
   Deal with the init message. 
*********************************************************************/
Boolean DoInit(PlugInParamPtr /*pb*/)
{
   // verify the presence of QuickDraw3D Viewer
   return (Q3ViewerNew != 
      (Q3ViewerNewProcType) kUnresolvedCFragSymbolAddress);
}

DoOpenFile
/*********************************************************************
   DoOpenFile
   User wanted to load a file. Snif it and open it if we can.
   Application sends us a pointer to the FSSpec in param[0].
*********************************************************************/
Boolean DoOpenFile(PlugInParamPtr pb)
{
   Boolean   retVal;
   short      refNum;
   FInfo     fileInfo;
   Boolean     dataFileOpen = false;
   
   // Is it again the same file ?
   if (gFileOpened && 
         SameFile( &gCurrentFile, (FSSpecPtr) pb->param[0]))
   {
      return true;
   }
   
   retVal = (FSpGetFInfo( (FSSpecPtr) pb->param[0],
            &fileInfo) == noErr &&
            fileInfo.fdType == '3DMF');
   // open the data fork of the file then...
   if (retVal)
   {
      dataFileOpen = 
         retVal = 
         (FSpOpenDF( (FSSpecPtr) pb->param[0], fsCurPerm,                               &refNum) == noErr);
   }
   // make sure we have a 3D viewer
   if (retVal)
   {
      retVal = Get3DViewer(pb);
   }
      
   //and tell the QD3DViewer to use it as the source of its data
   if (retVal)
   {
      retVal = (Q3ViewerUseFile( gMyViewer, refNum) == noErr);
      // force a full redraw right now.
      Q3ViewerDraw(gMyViewer);
   }
   // close the file here if it was opened
   if (dataFileOpen)
   {
      FSClose( refNum);
   }
   
   if (retVal)
   {
      // store data in our globals for next call
      gFileOpened = true;
      BlockMoveData( pb->param[0], 
                           &gCurrentFile, 
                           sizeof(FSSpec));
   }
   return retVal;
}

DoWindowClosed
/*********************************************************************
   DoWindowClosed
   User closed a window. If it is ours, release our data.
   Application sends us a pointer to the WindowRecord in param[0].
*********************************************************************/
Boolean DoWindowClosed( PlugInParamPtr pb)
{
   Boolean retVal;
   
   retVal= (gMyWindow == (WindowPtr) pb->param[0]);
   if (retVal)
   {
      Q3ViewerDispose( gMyViewer);
      gMyViewer = NULL;
   }
   return retVal;
}

DoEvent
/*********************************************************************
   DoEvent
   Application got an event? Is it ours?
*********************************************************************/
Boolean DoEvent(PlugInParamPtr pb)
{
   Boolean retVal;
   
   if (gMyViewer)
   {
      retVal = Q3ViewerEvent( gMyViewer, 
                        (EventRecord *) pb->param[0]);
   }
   else
   {
      retVal= false;
   }
   return retVal;
}

DoExit
/*********************************************************************
   DoExit
   We are being closed down. Release our objects.
*********************************************************************/
Boolean DoExit(PlugInParamPtr /*pb*/)
{
   if (gMyViewer)
   {
      Q3ViewerDispose( gMyViewer);
      gMyViewer = NULL;
   }
}

Get3DViewer
/*********************************************************************
   Get3DViewer
   make sure we have a 3DViewer
*********************************************************************/
Boolean Get3DViewer( PlugInParamPtr pb)
{
   CallbackParamBlock    cpb;
      CallBackUPP          callBack; // UPP for the callback
   Rect            wRect;

   // do we have a viewer already ?
   if (gMyViewer == NULL)
   {
      Boolean ok;
      
      // asks the application for a window using the callback
      // create UPP on the heap
      callBack = NewCallBackProc( pb->callback);
      // fill callback parameters
      cpb.message = createWindow;               
      ok = CallCallBackProc( callBack, &cpb);
      // dispose of UPP
      DisposeRoutineDescriptor( callBack);      
   
      // extract the WindowPtr if callback successful and verify the
      // portRect is not empty and it is a color port
      if (ok)
      {
         gMyWindow = (WindowPtr) cpb.param[0];   
         wRect = gMyWindow->portRect;          
         ok = (! (EmptyRect(&wRect))) &&
                  (IsColorPort(gMyWindow));             
      }
      
      // All the checks have been done: create a QD3D Viewer object
      if (ok)
      {
         gMyViewer = Q3ViewerNew( (CGrafPtr) gMyWindow, 
                              &wRect,
                              kQ3ViewerDefault);
      }
   }
   return (gMyViewer != NULL);   
}

IsColorPort
/*********************************************************************
   IsColorPort
   The magic routine to test if a GrafPort is just a CGrafPort
   in disguise
*********************************************************************/
Boolean IsColorPort(GrafPtr port)
{
   return port & ((((CGrafPtr)port)->portVersion &                            (short)0xC000)) == (short)0xC000 : false;
}

SameFile
/**********************************************************************
   SameFile
   Are two FSSpec refering to the same file?
***********************************************************************/
Boolean SameFile ( FSSpec *spec1, FSSpec *spec2 )
{
   return (spec1->vRefNum == spec2->vRefNum) &&
            (spec1->parID != spec2->parID) &&
            EqualString( spec1->name, spec2->name, false, true );
}

The last thing to mention about the import library is the settings for the project: make sure to specify PlugInMain as the main function of the Import library in the PPC Linker preferences panel, and in the PEF preferences, select use #pragma in the topmost popup menu for the export symbols. (CodeWarrior offers other ways to specify which symbols are exported, the point here is to make sure the PlugInMain is indeed exported.) The MPW tool DumpPEF can be invaluable to check which symbols are exported or imported by a PEF container like an import library.

The Accelerated Code Resource Project

The accelerated code resource project is even simpler, at least in its first version. It consists of only two files: stub.c to forward the parameters to the import library entry point and then return the result of the call to the application, and the import library which was just built and which will be used by the linker to set up the imports of our code resource.

In its first version, the code for the accelerated code resource has an almost embarassing simplicity: it just calls the exported function from the import library. (Remember that this simplicity is desired because of the difficulty of debugging accelerated code resources.)

Listing 3: Stub.c (version 1)

// Procedure info for the code resource entry point. This will be used by 
//Code Warrior to set up the routine descriptor in front of the code fragment.
enum {
   codeResourceProcInfo = kPascalStackBased
      | RESULT_SIZE(SIZE_CODE(sizeof(Boolean)))
      | STACK_ROUTINE_PARAMETER(1,
       SIZE_CODE(sizeof(PlugInParamPtr)))
};

// prototype for the import library exported function
extern Boolean PlugInMain( PlugInParamPtr pb );

// symbol used by CodeWarrior when building the accelerated code resource
ProcInfoType __procinfo = codeResourceProcInfo; 

// prototype for the code resource entry point
pascal Boolean main( PlugInParamPtr pb);

main
/************************************************************
   main
   Code Resource entry point
   In this first version, just call the entry point
************************************************************/
pascal Boolean main( PlugInParamPtr pb)
{   
   return PlugInMain( pb);
}

The project generates a file that contains the 'PLUG' accelerated code resource, which is then added to the import library project in the final step of the bootstrapping sequence. From now on, the 'PLUG' resource will be automatically added (like any other resource) to the resource fork of the import library file by the CodeWarrior linker.

Figure 3. The final project for the plug-in. QD3DPlugInStub.rsrc is the file providing the 'PLUG' accelerated code resource.

The plug-in is now ready to use. The application calls the PLUG resource that forwards the request to the import library that can directly call back to the application. Everything works perfectly until we move the plug-in away a directory other than the application directory, such as to a Plug-ins folder. What is happening?

The Need for Manual Load

The problem is that our accelerated code resource is not a full citizen in the MacOS, and the CFM cannot resolve the import in the code resource, namely PlugInMain(). The code resource resides in its host application process and, although the import library is the same physical file as the code resource, it is no longer in the CFM search path. The CFM search path is thoroughly described in [2] (p 3-7). The CFM searches for imported libraries in the directory of the fragment being loaded only (and this is not the case here) if the fragment is being loaded by a call to GetDiskFragment() or GetSharedLibrary(). If this search is not sucessful, the CFM tries to locate the import library in the application file, the application library directory (specified by the application 'cfrg' resource), the application directory, the Extensions folder in the System Folder, the ROM registry and finally, a file and directory registry currently private to the CFM. Placing our code resource-import library hybrid in a plug-in folder effectively removes the import library from the search path. Does it mean our hybrid will have to either clutter the application directory or the Extensions folder? The solution would be to programmatically load the import library. The CFM provides the necessary function: GetDiskFragment() will load a fragment contained in the data fork of a file specified by a FSSpec:

OSErr GetDiskFragment( FSSpecPtr fileSpec, long offset,
                  long length, Str63 fragName,
                  LoadFlags findFlags, 
                  ConnectionID* connID, Ptr* mainAddr,
                  Str255 errName);

The last remaining problem is to get the FSSpec of the file containing the accelerated code resource. If the fragment had been disk based, it could get its own FSSpec courtesy of the CFM by exporting a connection initialization routine. This type of routine is called by the CFM after a fragment has been loaded and prepared and should conform to the following definition:

OSErr MyConnectionInitializationRoutine( InitBlock*
                                connectionInfo);

For disk based fragments, one of the fields in the InitBlock structure is actually the FSSpec of the file containing the code fragment. However, if the fragment is memory based (and this is the case for accelerated code resources), the InitBlock specifies the address and size of the fragment but not the FSSpec of the file. However, since the loading of the plug-in import library is only needed once, using the connection initialization routine to perform this step is convenient.

There is no universal solution to this problem, because it really depends on the run-time environment provided by the application for its plug-ins. The technique described here will be applicable in almost all the cases however, since it relies on minimal assumptions typical of most applications: the resource file of the plug-in is left opened by the application, and the plug-in has either a unique resource ID or a unique name. The loading code will work even if the plug-in is not the current resource file (some applications set the current resource file to themselves after loading plug-ins). The current resource file is not necessarily the plug-in file since the connection routine is executed just before the first call to the main() routine of an accelerated code resource and not when the resource is loaded.

To get the FSSpec of its own file, the code resource will set the current resource file to the top of the resource chain to be sure its file is in the resource chain, look for itself in the resource chain with GetResource() (or GetNamedResource()), obtain its own file reference number with HomeResFile(), and convert the file reference number to a FSSpec with PBGetFCBInfo().

Listing 4: Stub.c (version 2)

#include "PlugInBlock.h"
#include <CodeFragments.h>

// our own identity 
#define kResType 'PLUG'
#define kResId      (1000)
// this structure is the C description of a Mac Resource Map
typedef struct {
   long dataOffset;
   long mapOffset;
   long dataLength;
   long mapLength;
   Handle nextMap;
   short fileRefNum;
   short fileResAttr;
   short typeListOffset;
   short nameListOffset;
} ResourceMap, *ResourceMapPtr, **ResourceMapHandle; 
// exported from the import lib
typedef Boolean (*CFMPlugInEntryPoint) (PlugInParamPtr pb);

enum {
         codeResourceProcInfo = kPascalStackBased
                | RESULT_SIZE(SIZE_CODE(sizeof(Boolean)))
                | STACK_ROUTINE_PARAMETER(1,
                    SIZE_CODE(sizeof(PlugInParamPtr)))
};

// for auto-load
extern Boolean PlugInMain( PlugInParamPtr pb );

// the import library entry point
CFMPlugInEntryPoint gPlugInMain; 

// used by CW for accelerated code resource
ProcInfoType __procinfo = codeResourceProcInfo; 

// prototype for the code resource entry point
pascal Boolean main( PlugInParamPtr pb);

// connection initialization routine and prototype of the utilities
OSErr VerifySharedLibrary( InitBlockPtr initBlock);
static OSErr RefNum2FSSpec( short theRefNum, 
                      FSSpecPtr theSpec);
static short SetResToTop(void);

main
/************************************************************
   main
   Code Resource entry point
   verify our global is set up and call the import library       
   entry point as before
************************************************************/
pascal Boolean main( PlugInParamPtr pb)
{   
   Boolean retVal = false;
   
   // Verify we did resolve the import   
   if (gPlugInMain != 
         (CFMPlugInEntryPoint) kUnresolvedCFragSymbolAddress)
   {
       retVal = (*gPlugInMain) (pb);
   }
   return retVal;
}

VerifySharedLibrary
/************************************************************
   VerifySharedLibrary
   ConnectionInitialization routine that verifies that the import library is 
   loaded, and if not load it programmatically.
************************************************************/
OSErr VerifySharedLibrary( InitBlockPtr /*initBlock*/)
{
   Handle             codeResourceHandle;
   FSSpec             myFSSpec;
   ConnectionID      myConnection;
   Str255            myError;
   short            myRefNum;
   OSErr              myErr = noErr;
   unsigned char      myEmptyString = 0x00;
   if (gPlugInMain == 
         (CFMPlugInEntryPoint) kUnresolvedCFragSymbolAddress)
   {
      // the CFM has not been loaded -> do it ourselves
      // the first part is to find our resource handle
      // so that we get to our ref num. The inMem info from the InitBlock 
      // is useless
      short oldResFile = SetResToTop();
      
      // get our own handle
      codeResourceHandle = GetResource(kResType, kResId);
      if (codeResourceHandle == NULL)
      {
         myErr = ResError();
      }
      // with the handle, get our file refnum
      if (myErr == noErr)
      {
         myRefNum = HomeResFile(codeResourceHandle);
         
         // now get the FSSpec corresponding to the refnum
         // this is much easier than you think   
         myErr = RefNum2FSSpec( myRefNum, &myFSSpec);
      }
      if (myErr == noErr)
      {
         myErr = GetDiskFragment( &myFSSpec, 
                       0,      // offset 0 for fragment 
                       kWholeFork, // whole data fork
                       &myEmptyString, // used for debug
                       kLoadLib, // load it
                       &myConnection, // get the connection
                       (Ptr*)&gPlugInMain, //get address directly
                       myError);
      }      
         
      if (myErr != noErr)
      {
         // just to stay on the safe side
         gPlugInMain = kUnresolvedCFragSymbolAddress; 
      }
      
      // restore current res file to its old value not to confuse the 
      // application
      UseResFile(oldResFile); 
   }
   else
   {
      gPlugInMain = PlugInMain; //Fragment loaded automatically
   }
   return myErr;
}

RefNum2FSSpec
/************************************************************
   RefNum2FSSpec
   given a file refNum, returns the file FSSpec
************************************************************/
   OSErr RefNum2FSSpec( short theRefNum, FSSpecPtr theSpec)
{
   FCBPBRec   paramBlock;
   OSErr         theError;
   Str255      theName;

   paramBlock.ioCompletion   = nil;
   paramBlock.ioNamePtr   = theName;
   paramBlock.ioVRefNum   = 0;
   paramBlock.ioRefNum   = theRefNum;
   paramBlock.ioFCBIndx   = 0;
   theError = PBGetFCBInfo(&paramBlock, false);

   if (theError == noErr) 
   {
      theError = FSMakeFSSpec(paramBlock.ioFCBVRefNum,
                    paramBlock.ioFCBParID,
                    theName, 
                    theSpec);
   }
   return theError;
}

SetResToTop
/*******************************************************
   SetResToTop
   Sets the current resource file to the top of the resource map
   Returns the current resource file before the call.
********************************************************/
short SetResToTop(void)
{
   short topResFile;
   short oldResFile;
   
   // Save the current resource file 
   oldResFile = CurResFile();
   
   // now sets the current Resfile to the top of the resource map
   // using the low-memory global TopMapHndl
   topResFile = (**((ResourceMapHandle)                                     LMGetTopMapHndl())).fileRefNum;
   UseResFile(topResFile);
   return oldResFile;
}

To improve the robustness of the manual loading of the import library, instead of relying on GetDiskFragment() which simply returns a transition vector to the main entry point of the import library, the code could use FindSymbol() to verify that the import library loaded by GetDiskFragment() exports a routine with the expected name.

myErr = FindSymbol( 
         myConnection,         // obtained with GetDiskFragment()
         "\pPlugInMain",         // name of routine to look for
         (Ptr*)&gPlugInMain,  //get address directly
         &symbolType);      // get class of symbol (transition vector, data)

Evidently, calls to FindSymbol() are necessary if the code resource does not call the main entry point (this would happen if the import library implemented the code for several distinct code resources all calling different entry points).

The other modifications to the import library project are the specification of VerifySharedLibrary as the connection initialization routine (Figure 4) and the addition of two libraries: InterfaceLib to link with all the Toolbox routines used, and MWCRuntimeLib to provide the glue to call the transition vectors obtained with GetDiskFragment() or FindSymbol(). A transition vector is a function pointer associated with the value of the Table Of Contents register (RTOC) used to reference global data in the called code fragment ([2] p.1-26). Calling a function located in another code fragment is known as a cross-TOC call, and the MWCRuntimeLib automatically provides the glue to set the TOC register before and after cross-TOC calls. The C programmer just deals with classic C pointers to functions.

Finally, the link to the import library should be set as "weak" so that the CFM does not give up loading and preparing the accelerated code resource if it cannot resolve the import. A weak link gives the connection initialization routine a chance to resolve the imports.

Figure 4. Setting the connection initialization routine of the accelerated code resource.

Conclusion

Adopting the mixed architecture with import libraries for accelerated code resources offers several advantages: the code of the plug-in does not impact the amount of free memory of the application, data can be easily shared between the plug-ins, the developer does not have to deal with the limitations inherent to the use of code resources, and can debug using mainstream source level debuggers. The implementation of these hybrid files is very easy once the stub resource has been built. Most, if not all of the development effort is then spent in the import library code. It is even easy to convert an existing accelerated code resource to use the hybrid architecture. All these advantages should speed up the development of new plug-ins of better quality for all the applications that still do not take explicitly advantage of the CFM. This hybrid design also can be used to develop private or fat safe code resources. (For more information on this type of code resource, see [5].) Finally, packaging the code resource in the same file helps reduce the System Folder clutter.

Even if you do not have a accelerated code resource project in the foreseeable future, the techniques presented here may give new ideas on how to take advantage of the power and versatility of the CFM, one of the most awesome parts of the Macintosh Operating System.

Bibliography and References

  1. Apple Computer Inc. "3D Graphics Programming with QuickDraw 3D", (1995) Addison-Wesley.
  2. Apple Computer Inc. "Inside Macintosh: PowerPC System Software", (1994) Addison-Wesley.
  3. Prouse, Craig. "Technical Note PT35-Stand alone code, ad nauseam", (1990) Apple Computer Inc.
  4. Nichols, Tim. "Standalone code on the PowerPC". (1994) develop 17, Apple Computer Inc.
  5. Zobkiw, Joe. "A fragment of your imagination", (1995) Addison-Wesley.
 
AAPL
$102.37
Apple Inc.
+0.12
MSFT
$45.26
Microsoft Corpora
+0.38
GOOG
$569.76
Google Inc.
+0.56

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

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 »
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 »
Checkmark 2.1 Update Released, and it’s...
Checkmark 2.1 Update Released, and it’s on Sale for a Limited Time Posted by Jessica Fisher on August 29th, 2014 [ permalink ] | Read more »
The Walking Dead Pinball Review
The Walking Dead Pinball Review By Blake Grundman on August 29th, 2014 Our Rating: :: DECISIONS, DECISIONS...Universal App - Designed for iPhone and iPad Zen Studios is at it again, taking a property that would never seem to work... | Read more »
Stupeflix Has Released a Major Update fo...
Stupeflix Has Released a Major Update for Replay Posted by Jessica Fisher on August 29th, 2014 [ permalink ] iPhone App - Designed for the iPhone, compatible with the iPad | Read more »
ALONE… Review
ALONE… Review By Jennifer Allen on August 29th, 2014 Our Rating: :: MINIMALISTIC AND TOUGHUniversal App - Designed for iPhone and iPad Tough yet satisfying, ALONE… is a challenging endless flyer with some suitably sensitive... | Read more »
Hyperlapse Review
Hyperlapse Review By Jennifer Allen on August 28th, 2014 Our Rating: :: SPEEDY VIDEO SNAPSUniversal App - Designed for iPhone and iPad Want to make a great time-lapse video quickly? Hyperlapse is perfect for that.   | Read more »
Back To Bed Review
Back To Bed Review By Jennifer Allen on August 28th, 2014 Our Rating: :: STYLISH BUT LIMITEDUniversal App - Designed for iPhone and iPad It looks gorgeous, but Back to Bed is actually a fairly simple and uneventful puzzle game.   | Read more »

Price Scanner via MacPrices.net

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
Sapphire Screen “Most Wanted” iPhone 6 New Fe...
According to the ‘uSell.com iPhone Most Wanted Survey’ — a representative survey of 1,000 U.S. smartphone users conducted by used iPhone marketplace uSell.com — close to half of all smartphone users... Read more
The iPad’s Real Competitive Challenger (Not S...
It’s been my contention for some time that the iPad is suffering from something of an identity crisis, and I suspect that may be a factor in slackening sales this year. Apple can’t seem to decide... 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
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
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.