TweetFollow Us on Twitter

Charting Resource Map
Volume Number:6
Issue Number:9
Column Tag:XCMD Corner

Related Info: Resource Manager

Charting The Resource Map

By Donald Koscheka, Ernst & Young, MacTutor Contributing Editor

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

Fourth Party Developers

If you read this column regularly, you may be a charter member of a new class of programmers that Apple has recently labelled as “Fourth party developers”. This term is used to denote those programmers who add or modify an existing package for a customer. By this token, XCMDs are 4th party programs since you are adding code to an off-the-shelf product (Hypercard) to enhance its capabilities.

4th Party Programming seems to be an interesting way to make a living. First off, the assignments are manageable since most 4th party work tends to be minor additions to existing work. Second, the 4th party developer needs to be a master of all trades. Gone are the days when a programmer could specialize in data base design, or system software or report generation.

If 4th party programming becomes commercially viable, the practitioner will need to be well-versed in many areas but it’s a safe bet that you can focus your expertise on the following: I/O, communications, searching, sorting, report generation, file translators and graphics. The problem is, most programmers don’t have a repertoire that spans this wide a spectrum. If you feel equally comfortable talking LAP as you do discussing the TIFF format, then maybe you should try your hand at becoming a 4th party programmer.

Personally, I think this area can turn out to be very interesting. I remain skeptical as to whether anyone can make a living at it, but I’m willing to consider anything. After all, the most far-fetched ideas are often the ones that lead to innovation.

End of Sermon.

Charting The Resource Map

Although I’ve read just about every page of Inside Macintosh at least twice, there are certain pages that I still find myself glossing over. I don’t skip these pages out of lack of interest, every manager in the Toolbox has some interesting nuance that is just begging to be exploited. I gloss over certain sections of IM solely because I know that reading that section will lead me down a long path that I just never seem to have time for.

One such path for me is decoding the format of the resource fork. I have always looked on pages I-128 through 1-131 as a sort of black hole; the resource forks just seemed too convoluted to ever have to try to understand. Besides, anything one needs to do with the resource fork can be done via the high level resource manager calls. Or so it would seem. But here’s a simple request that cannot be resolved by the resource manager -- give me a list of the type and id of all resources in a particular resource file.

One needs to understand the spirit of the resource manager in order to understand why this seemingly simple problem doesn’t have a simple solution. The resource manager was intended to act as what I call “soft virtual EPROM”. In essence, resources should only be created during the construction of an application. Once the product ships, the resource fork should remain stable. This is exactly how Engineers use EPROM in computer designs. The “soft” nature of resources alludes to the fact that resources are easy to change as one might need to do to internationalize a certain package. This does not mean that the resource fork should be used for storing dynamically altering data. The resource manager is NOT a data base. A lot of early Mac programmers abused the resource fork by using it as a simple sort of data base. The RM doesn’t respond well to constantly changing data -- it is relatively slow for writing and it lacks any inherent compaction scheme. Neither of these are a shortcoming, the resource fork was never meant to be used as a random access data base. Any programmer who uses the resource fork in this way is asking for trouble and is building an inherently unstable program -- if you have data base needs, either buy or develop a data base, but please, keep your paws out of the resource fork.

The next attribute of the resource fork that is significant is its “virtual” nature. The resource manager has a built-in mechanism for searching all open resource files for a given resource. This is good -- it frees the programmer from needing to know how to access the system resources, they just magically appear along with your resources at load time. Of course there is nothing magical about the resource manager develops this virtual behaviour, each file contains a resource map that is loaded into memory when the resource fork is opened. Each resource map stores a handle to the next resource map in the search order. Thus searching all open resource forks becomes straightforward. But herein lies the crux of our problem. The resource manager itself wants to search all open resource files. If we want to get a list of all resources stored in a particular file, then we would first have to close down all open resource files so that they are excluded from the search path. This would be bad and not even worth trying because shutting down your system resource fork and application resource fork would almost certainly be fatal to the application.

Thus, to read all resources from one particular resource file, we are forced to scan the resource map for that file. Listing 1 (GetRsrcList.c) returns a list of all resources by type and id (names will be added in the future, you can use the resource manager to get the name for now). Notice that in order to do this, I needed to reconstruct the structures used in the resource file. I couldn’t find these structures in my libraries so I create my own.

Our strategy for scanning the resource file goes like this (refer to page I-131 for a good picture of this strategy). First, we read in the resource header (256 bytes). The resource header contains, among other things, the offset and length of the resource map. I find it noteworthy that the resource map always follows the resource data in the file. This seems reasonable enough. Since we know how big the resource map is, allocate a pointer that contains enough space to read the map into, then move the file mark to the start of the map and read it in. Once the map is read in, we need to move through two levels: the type list and the reference list. The type list immediately follows the map header and tells us how many types of resources the fork contains as well as the resource type (4 bytes), the number of resources of that type and where the reference list starts for that type. Type lists and reference lists are constant-sized structures so we can increment a pointer to sashay nicely through the lists.

Each resource type contains a reference list. This list holds information about each individual resource. There are as many entries as there are resources of a given type (counting from 0 not 1). If your file contains 4 XCMDs then your XCMD reference list will contain 4 contiguous entries, one for each XCMD. Pascal programmers take note -- the count is stored as 1 less than the actual number of items. We walk the reference list thusly:

/* 1 */

 for( i = 0; i <= rTL->r_count; i++ ){
 rRef = (resRefPtr)((long)rTL + (long)rTyp->r_ref );
 for( j = 0; j <= rTyp->r_count; j++ )


The outer loop (i) walks through the type list (again these are stored contiguously immediately following the the resource map header). If rTyp is a pointer to a type list entry (an 8-byte struct), then all we need to do to move to the next type is increment the pointer. “C” is a natural for this type of work but the equivalent Pascal code looks like this:

/* 2 */

 rTyp = ResTypPtr( ORD4( rTyp ) + LongInt( sizeof( ResTyp) );
       { rTyp++ }

Each type entry contains the offset to the start of the reference list for this type. This offset is relative to the start of the type list itself. Adding this offset to the start of the type list (rTL in the example above) yields the physical location of the reference list. Each resource in the file has a reference list entry. To scan all resources of a given type (eg ‘XCMD’) we can increment the pointer to the reference list entries (rRef).

You may never need to know how to scan a resource map but it does serve two pedantic purposes -- it shows how resource files are created and it absolutely convinces the serious programmer that the resource fork is not intended to be a data base. The 16-bit offsets used throughout the fork should provide some clue as to the limitations on the fork’s capacity. For example, what is the maximum number of resource types that you can have? What is the total number of resources that can be stored safely in the resource fork? Listing 1 provides clues to the answers (hint: study the structures). Understanding limits is an important part of programming. See what you can do with this information.

The resource manager is fun to poke around in and I will visit this theme in the future. In the meantime, if you have an interesting problem that needs solving in an XCMD, drop me a line. I’ll see what I can do.

Listing 1:  GetRsrcList.c

/* File: GetRsrcList.c    */
/* */
/* Given the name of a file,  */
/* return a list of all the */
/* resources in that file.  The */
/* list contains 1 line per */
/* resource with the following  */
/* format:*/
/* */
/* item1 == Resource Type */
/* item2 == Resource ID   */
/* item3 == Resource name */
/* */
/* If the resource fork is empty*/
/* or non-existent, return empty*/
/* */
/* ----------------------------  */
/* ©1990 Donald Koscheka  */
/* All Rights Reserved    */

#define UsingHypercard

#include  “HyperXCmd.h”

#define nil 0L

/*** definition of resource header ***/
typedef struct {
 long r_data_offset;
 long r_map_offset;
 long r_data_size;
 long r_map_size;
 char r_reserved[112];
 char r_application[128];
} resHdr, *resHdrPtr, **resHdrHand;

/*** definition of resource map ***/
typedef struct {
 long   r_header[4];/* duplicates first 16 bytes in header*/
 long   next_map;
 short  f_ref;
 short  attributes;
 short  r_type_list;
 short  r_name_list;
} resMap, *resMapPtr, **resMapHand;

/*** definition of type list entry ***/
typedef struct {
 char   r_type[4]; /*** this resource type   ***/
 short  r_count; /*** # of resources of this type ***/
 short  r_ref;   
 /*** offset from start of type list to***/
 /*** reference list for resources of  ***/
 /*** this type (not used here)    ***/
} resTyp, *resTypPtr, **resTypHand;

/*** definition of resource type list ***/
typedef struct {
 short  r_count; /* 0..n */
 resTyp r_typ[]; /* array of type entries */
} resTypeList, *resTypeListPtr, **resTypeListHand;

/*** definition of resource reference list ***/
typedef struct {
 short  r_id;    
 short  r_name;  
 /* offset from start of name list to this name */
 long r_offset;  /* offset to date (hi byte == attributes */
 Handle r_handle;/* handle when resource is in memory */
} resRef, *resRefPtr, **resRefHand;

pascal void main( paramPtr )
 XCmdBlockPtr  paramPtr;
 resMapPtrrMap = NIL;
 resTypeListPtr  rTL;
 Handle rsrcList = NIL; /* the output*/
 resHdr rHdr;
 Str31  fName;   /* name of the file */
 short  ref;
 OSErr  err;
 long   temp;
 short  i,j;/* loop counters*/
 Str255 str;
 paramPtr->returnValue = NIL; /* prepare for the worst */
 /* (but plan for the best) */
 if( paramPtr->params[0] ){

 HLock( paramPtr->params[0] );
 ZeroToPas( paramPtr, *(paramPtr->params[0]), &fName );
 HUnlock( paramPtr->params[0] );

 err  = (short)OpenRF( &fName, -1, &ref );

 if( !err ) /*** Move to  start of  file & read header ***/
 err = SetFPos( ref, fsFromStart, 0L );
 if( !err ){/*** read in the resource header ***/
 temp = (long)sizeof( resHdr );
 err = FSRead( ref, &temp, &rHdr );
 if( !err ) /*** Move to start of map & read it in ***/
 err = SetFPos( ref, fsFromStart, rHdr.r_map_offset );
 if( !err ){
 rMap = (resMapPtr)NewPtr( rHdr.r_map_size );
 err = FSRead( ref, &rHdr.r_map_size, rMap);
 if( !err ){
 /*** this calculation doesn’t seem correct ***/
 rTL = (resTypeListPtr)((long)rMap + (long)(rMap->r_type_list));

 /*** move to the start of the reference list ***/
 rTyp = (resTypPtr)((long)rTL + (long)sizeof( short )); 
 /* Allocate handle for the output list*/
 if( rsrcList = NewHandle( 0L ) ){
 for( i = 0; i <= rTL->r_count; i++ ){
 rRef = (resRefPtr)((long)rTL + (long)rTyp->r_ref );
 for( j = 0; j <= rTyp->r_count; j++ ){
 /*** read the reference list entry int ***/
 /*** add this type & id to the output list ***/
 AppendCharToHandle( rsrcList, (char)rTyp->r_type[0]);
 AppendCharToHandle( rsrcList, (char)rTyp->r_type[1]);
 AppendCharToHandle( rsrcList, (char)rTyp->r_type[2]);
 AppendCharToHandle( rsrcList, (char)rTyp->r_type[3]);
 AppendCharToHandle( rsrcList, ‘,’);
 /*** convert id to a string & add to list ***/
 NumToStr( paramPtr, (long)rRef->r_id, &str );
 pStrToField( (char *)str, ‘\r’,  rsrcList );
 }/* for j = 0 to # of resources of this type */
 }/* for i = 0 to the number of resource types */
 }/* if( rsrcList allocated */
 AppendCharToHandle( rsrcList, ‘\0’ );
 if( rMap )
 DisposPtr( (Ptr)rMap );
 /*** Only reach here if file was opened     ***/
 err = FSClose( ref );
 paramPtr->returnValue = rsrcList;


Community Search:
MacTech Search:

Software Updates via MacUpdate

BetterTouchTool 1.989 - Customize Multi-...
BetterTouchTool adds many new, fully customizable gestures to the Magic Mouse, Multi-Touch MacBook trackpad, and Magic Trackpad. These gestures are customizable: Magic Mouse: Pinch in / out (zoom... Read more
calibre 2.77.0 - Complete e-book library...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital librarian... Read more
Quicksilver 1.5.2 - Application launcher...
Quicksilver is a light, fast and free Mac application that gives you the power to control your Mac with keystrokes alone. Quicksilver allows you to find what you need quickly and easily, then act... Read more
Paperless 2.3.9 - $49.95
Paperless is a digital documents manager. Remember when everyone talked about how we would soon be a paperless society? Now it seems like we use paper more than ever. Let's face it - we need and we... Read more
Apple GarageBand 10.1.5 - Complete recor...
The new GarageBand is a whole music creation studio right inside your Mac -- complete with keyboard, synths, orchestral and percussion instruments, presets for guitar and voice, an entirely... Read more
Adobe Audition CC 2017 10.0.2 - Professi...
Audition CC 2017 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous Audition customer). Adobe Audition CC 2017 empowers you to create and... Read more
Adobe After Effects CC 2017 14.1 - Creat...
After Effects CC 2017 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous After Effects customer). The new, more connected After Effects CC... Read more
Adobe Premiere Pro CC 2017 11.0.2 - Digi...
Premiere Pro CC 2017 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous Premiere Pro customer). Adobe Premiere Pro CC 2017 lets you edit... Read more
WALTR 2 2.0.9 - $39.95
WALTR 2 helps you wirelessly drag-and-drop any music, ringtones, videos, PDF, and ePub files onto your iPhone, iPad, or iPod without iTunes. It is the second major version of Softorino's critically-... Read more
Yummy FTP Pro 1.11.14 - $14.99 (50% off)
Yummy FTP Pro is an advanced Mac file transfer app which provides a full-featured professional toolkit combined with blazing speeds and impeccable reliability, so whether you want to transfer a few... Read more

Super Gridland (Entertainment)
Super Gridland 1.0 Device: iOS Universal Category: Entertainment Price: $1.99, Version: 1.0 (iTunes) Description: Match. Build. Survive. "exquisitely tuned" - Rock Paper Shotgun No in-app purches, and no ads! | Read more »
Red's Kingdom (Games)
Red's Kingdom 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: Mad King Mac has kidnapped your father and stolen your golden nut! Solve puzzles and battle goons as you explore and battle your... | Read more »
Turbo League Guide: How to tame the cont...
| Read more »
Fire Emblem: Heroes coming to Google Pla...
Nintendo gave us our first look at Fire Emblem: Heroes, the upcoming mobile Fire Emblem game the company hinted at last year. Revealed at the Fire Emblem Direct event held today, the game will condense the series' tactical RPG combat into bite-... | Read more »
ReSlice (Music)
ReSlice 1.0 Device: iOS Universal Category: Music Price: $9.99, Version: 1.0 (iTunes) Description: Audio Slice Machine Slice your audio samples with ReSlice and create flexible musical atoms which can be triggered by MIDI notes or... | Read more »
Stickman Surfer rides in with the tide t...
Stickson is back and this time he's taken up yet another extreme sport - surfing. Stickman Surfer is out this Thursday on both iOS and Android, so if you've been following the other Stickman adventures, you might be interested in picking this one... | Read more »
Z-Exemplar (Games)
Z-Exemplar 1.4 Device: iOS Universal Category: Games Price: $3.99, Version: 1.4 (iTunes) Description: | Read more »
5 dastardly difficult roguelikes like th...
Edmund McMillen's popular roguelike creation The Binding of Isaac: Rebirth has finally crawled onto mobile devices. It's a grotesque dual-stick shooter that tosses you into an endless, procedurally generated basement as you, the pitiable Isaac,... | Read more »
Last week on PocketGamer
Welcome to a weekly feature looking back on the past seven days of coverage on our sister website, PocketGamer. It’s taken a while for 2017 to really get going, at least when it comes to the world of portable gaming. Thank goodness, then, for... | Read more »
ROME: Total War - Barbarian Invasion set...
To the delight of mobile strategy fans, Feral Interactive released ROME: Total War just a few months ago. Now the game's expansion, Barbarian Invasion is marching onto iPads as a standalone release. [Read more] | Read more »

Price Scanner via

B-Eng introduces SSD Health Check for Mac OS
Fehraltorf, Switzerland based independant Swiss company- B-Eng has announced the release and immediate availability of SSD Health Check 1.0, the company’s new hard drive utility for Mac OS X. As the... Read more
Apple’s Education discount saves up to $300 o...
Purchase a new Mac or iPad using Apple’s Education Store and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free: -... Read more
4-core 3.7GHz Mac Pro on sale for $2290, save...
Guitar Center has the 3.7GHz 4-core Mac Pro (MD253LL/A) on sale for $2289.97 including free shipping or free local store pickup (if available). Their price is a $710 savings over standard MSRP for... Read more
128GB Apple iPad Air 2, refurbished, availabl...
Apple has Certified Refurbished 128GB iPad Air 2s WiFis available for $419 including free shipping. That’s an $80 savings over standard MSRP for this model. A standard Apple one-year warranty is... Read more
13-inch 2.7GHz Retina MacBook Pro on sale for...
B&H Photo has the 2015 13″ 2.7GHz/128GB Retina Apple MacBook Pro on sale for $100 off MSRP. Shipping is free, and B&H charges NY tax only: - 13″ 2.7GHz/128GB Retina MacBook Pro (MF839LL/A): $... Read more
Laptop Market – Flight To Quality? – The ‘Boo...
Preliminary quarterly PC shipments data released by Gartner Inc. last week reveal an interesting disparity between sales performance of major name PC vendors as opposed to that of less well-known... Read more
IBM and Bell Transform Canadian Enterprise Mo...
IBM and Bell Canada have announced they are joining forces to offer IBM MobileFirst for iOS market-ready enterprise applications for iPad, iPhone or Apple Watch. Bell, Canada’s largest communications... Read more
Otter Products is Closing… For a Day of Givin...
On Thursday, Feb. 9, Otter Products is closing doors to open hearts. In partnership with the OtterCares Foundation, the company is pausing operations for a day so all employees can volunteer with... Read more
15-inch 2.2GHz Retina MacBook Pro on sale for...
Amazon has 2015 15″ 2.2GHz Retina MacBook Pros (MJLQ2LL/A) available for $1799.99 including free shipping. Apple charges $1999 for this model, so Amazon’s price is represents a $200 savings. Read more
Back in stock: Apple refurbished 13-inch Reti...
Apple has Certified Refurbished 2015 13″ Retina MacBook Pros available for up to $360 off original MSRP, starting at $1099. An Apple one-year warranty is included with each model, and shipping is... Read more

Jobs Board

*Apple* & PC Desktop Support Technician...
Apple & PC Desktop Support Technician job in Los Angeles, CA Introduction: We have immediate job openings for several Desktop Support Technicians with one of our Read more
*Apple* Retail - Multiple Positions - Apple,...
SalesSpecialist - Retail Customer Service and SalesTransform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (Multi-L...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Retail - Multiple Positions - Apple,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* & PC Desktop Support Technician...
Apple & PC Desktop Support Technician job in Stamford, CT We have immediate job openings for several Desktop Support Technicians with one of our most well-known Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.