TweetFollow Us on Twitter

June 96 - KON & BAL's Puzzle Page: New World Order

KON & BAL's Puzzle Page: New World Order

CAMERON ESFAHANI and ALEX ROSENBERG

See if you can solve this programming puzzle, presented in the form of a dialog between Cameron Esfahani (cam) and Alex Rosenberg. The dialog gives clues to help you. Keep guessing until you're done; your score is the number to the left of the clue that gave you the correct answer. Even if you never run into the particular problems being solved here, you'll learn some valuable debugging techniques that will help you solve your own programming conundrums. And you'll also learn interesting Macintosh trivia.

Alex Hey cam, Marathon crashed in a weird manner when I tried to play it under an early version of Mac OS 8.

cam Working hard, eh? I suppose you'll tell me this was compatibility testing.

Alex Yeah, well, it makes a good demo.

cam Hey, wait a minute! If it's an early version of Mac OS 8, Puzzle Page readers won't ever find this bug, and they'll write nasty letters to the editor about it.

Alex Well, they should know that they'll learn some valuable debugging techniques that they can apply to their own programming conundrums. Don't they read the intro to the Puzzle Page?

cam I guess not. Anyway, back to your problem. So, in what way does it fail?

Alex Just after launch, the machine freezes. This happens every time; it's 100% reproducible. I can't seem to get into MacsBug.

cam Philistine! We use the one true debugger, the Macintosh Debugger for PowerPC. Mac OS 8 debugging is generally done from a second machine over a serial cable. You're probably frozen because the program has crashed and the debugger has halted the machine, waiting to start a debugging session.

Alex What? I thought I gave that up with my Lisa. This is a Macintosh, after all.

cam Kernel-based operating systems are typically developed with two-machine debuggers. Besides, think of the wonderful third-party opportunity!

Alex Um, yeah. Anyway, you've hooked up the serial cable and are running the debugger on the second machine. After watching a progress bar for a while, you see a dialog that says "Access Fault."

cam An access fault is caused by an attempt to access an illegal address. The PC is at the instruction that caused the fault.

Alex There's a Show PC command in the debugger's Extras menu. It puts me at 0x626FDE50.

cam Right. We need to isolate whether this fault occurred in application code or in the system. Choose Show Fragment Info from the Views menu and type that address into it.

Alex I can't type anything; the machine is crashed. Oh, I get it: I have to keep switching my head back and forth between machines like a spectator at a tennis match. What fun. So, how long does this barber pole thingy spin for, anyway? Hey look, the Fragment Info window highlighted the Marathon code fragment. The PC is in Marathon's code.

cam What does the code around the PC look like?

Alex It looks like this:

   626FDE34   mflr       r0
626FDE38 stw r0,0x0008(SP)
626FDE3C stwu SP,-0x0038(SP)
626FDE40 lwz r4,0x0000(r3)
626FDE44 lha r3,0x0000(r4)
626FDE48 bl _eGetDCtlEntry
626FDE4C lwz RTOC,0x0014(SP)
626FDE50 lwz r12,0x0000(r3)
626FDE54 lbz r3,0x0028(r12)
626FDE58 extsb r3,r3
626FDE5C lwz r0,0x0040(SP)
626FDE60 addic SP,SP,56
626FDE64 mtlr r0
626FDE68 blr

R3 is the return value from the function call to _eGetDCtlEntry and apparently contained a bad address.

cam Choose Show Registers from the Views menu. This will show all the registers of the current process.

Alex It looks like the return value for _eGetDCtlEntry was 0. The lwz instruction is dereferencing R3 and putting the result in R12.

cam If you select the R12 register and choose Show Memory from the Views menu, you can see the memory at that address.

Alex That entire area of memory is full of 0xEEEEEEEE's.

cam That's unmapped memory. Is _eGetDCtlEntry the internal name of the routine GetDCtlEntry?

Alex Yes, the debugger is able to pick up that name by using a "trace-back table," which is the PowerPC equivalent of MacsBug symbols. I guess the next step would be to figure out why GetDCtlEntry is returning nil. What is it supposed to be doing?

cam According to Inside Macintosh: Devices, GetDCtlEntry returns the device control entry for the device specified by the value passed in refNum.

If we look at the rest of the code in this function, right before we call GetDCtlEntry, we seem to be getting the refNum from the first 16 bits of some "handle" (or some other kind of pointer to a pointer), which is getting passed into this function.

Alex All right, but we're going to have to restart. Any information passed into this function has been lost because we're after the call to GetDCtlEntry.

cam To restart we'll need to remember the offset into the Marathon fragment where the fault will occur, because the Marathon fragment could be loaded in a different address range.

Alex The offset can be calculated by subtracting the faulting address from the beginning address for the fragment, which was shown in the Fragment Info window. For this address, the offset is 0x4832C.

cam Right, but we'd like to get control a little before the actual crash. The offset to the beginning of that function is 0x48310. Restart the system, and hold down the Control key when you relaunch Marathon. On a debugging system, this will break into the debugger after it has completely loaded the application but just before it begins to execute it.

Alex All right. The machine seems to have stopped at that point. The new start of the Marathon code fragment is 0x6337D6A0. Adding in the offset of 0x48310, we get an address of 0x633C59B0.

cam Bring up the Show Instructions window and enter 0x633C59B0 as the address. It will be exactly the same code as what we saw before. Set a breakpoint at the first instruction in this function -- the mflr instruction -- and run.

Alex We've reached that breakpoint.

cam Do a stack crawl and see who called us. Head over to the ever useful Views menu; there's a Show Stack Crawl command.

Alex All right. Apparently the caller is address 0x633988E0.

cam OK, let's step through this function and see what they end up passing to GetDCtlEntry for the refNum.

Alex It looks like they're passing in 0 for the refNum.

cam Well, there's your problem: 0 is not a valid refNum. It seems that they're getting an invalid refNum from some part of the system and passing that to GetDCtlEntry. GetDCtlEntry is returning nil and we're crashing by dereferencing nil.

Alex Uh, that's great, but I still can't play Marathon.

cam Where does the caller of this function, 0x633988E0, get the "handle" from?

Alex I'll bring up an instruction window at that address:

63398778 mflr r0

...

633987B0 lwz r24,-0x0218(RTOC)

...

633988D8 lwz r3,0x0000(r24)

633988DC addic r3,r3,0x001C

633988E0 bl $+0x2D340 ; 0x633C5C20

633988E4 nop

633988E8 stw r3,0x0000(r30)

R3 seems to be loaded from a global. Let's figure out where this global gets initialized. The "handle" lives inside a structure that's pointed to by the global at -0x218(RTOC). This pointer has the "handle" stored at offset 0x1C within it.

cam We could try to track down where the field at offset 0x1C gets initialized. A pointer wouldn't move around, so we wouldn't have to worry about relocation. We can use the Data Breakpoint window feature of the Macintosh Debugger. The PowerPC 601 has a special register that allows you to stop execution whenever a specified address is read or written to. It's like hardware support for our old friend step spy.

Alex Sounds like a plan. So, I bring up the Data Breakpoint window and will break whenever someone writes to that address.

cam Of course, you realize that just as the code fragment could be loaded in a different place each time it's launched, the RTOC could have a different value as well.

Alex Good point. I'll be sure to use the new RTOC value when I restart Marathon.

cam What happens after we set up the data breakpoint?

Alex It's kind of strange. We seem to be stopping a lot, but people aren't writing to offset 0x1C in this structure; they seem to be writing 32 bits to offset 0x1A and overwriting 0x1C.

cam I don't understand. The routine that called the crashing routine was passing in a value at offset 0x1C.

Alex Apparently we calculated something wrong.

cam I don't know where we could have gone wrong. Wait a second. Look at address 0x633988E0; it says we're branching to address 0x633C5C20, but the routine we're crashing in is at 0x633C59B0.

Alex Well, maybe it's just a call to a different code fragment, a "cross-TOC" call, and it has to use some indirection to get to the crashing function.

cam No, it can't be a cross-TOC call, for two reasons: first, there's no TOC reload after the function call, and second, the routine we crashed in is in the Marathon fragment. You saw the Fragment Info results.

Alex I'll buy that. Now let's set our breakpoint just before this function call to the unknown address. We can step through that code.

cam All right. After we hit the breakpoint, step into that function.

45 Alex Holy cow! It's some totally different piece of code.

cam Look through the instruction disassembly of this new routine. Is there anywhere in there where they call the crashing function?

633C5C98 bl 0x6337E150

633C5C9C lwz RTOC,0x0014(SP)

633C5CA0 ori r31,r3,0x0000

...

633C5CDC ori r3,r31,0x0000

* 633C5CE0 bl 0x633C59B0

Alex Yeah. At address 0x633C5CE0, they call our crashing function with a parameter obtained from R31. Working further back in the instruction disassembly, we see that a function call is made and the result of that is put in R31. This occurs at 0x633C5C98. It calls a routine at address 0x6337E150.

cam And looking at that, it appears to be a cross-TOC call. I restart Marathon and step into the routine at 0x6337E150.

Alex It appears to be cross-TOC glue:

6337E150 lwz r12,-0x0A90(RTOC)

6337E154 stw RTOC,0x0014(SP)

6337E158 lwz r0,0x0000(r12)

6337E15C lwz RTOC,0x0004(r12)

6337E160 mtctr r0

6337E164 bctr

cam So apparently Marathon is calling another library to get this mystical "handle."

Alex Yep. Whenever you're going to go from one library context to another, you need to save and restore the TOC. That's one of the things this glue code does. As you can see, R12 is loaded from -0x0A90(RTOC). R12 will contain a pointer to a transition vector, which contains an address of a routine and a new TOC value. The transition vector is imported from the library we're linking against.

cam So we should be able to plop the transition vector address into the Fragment Info window and figure out which library that comes from, right?

Alex Good idea. Dumping the address at -0x0A90(RTOC) we get the following:

0200CC0C: 01FC9D98 01FC9DA4 01FC9DB0 01FC9DBC

0200CC1C: 01FC9DE0 01FC9DEC 01FC9D80 01FC9D74

...

cam I use the Fragment Info window to find out which fragment contains the address 0x01FC9D98.

Alex It seems to live in the QuickDraw data section, which makes sense, since a transition vector is data.

cam Aha! QuickDraw! That figures. And you wondered why they call it KON & BAL's Puzzle Page. I use the Show Exports button in the Fragment Info window to list all of the exports of the QuickDraw library.

Alex I was wondering when we were going to use that button. You end up getting a long list of all the routines exported by QuickDraw, sorted alphabetically.

cam But I have an address I want to match. If you click on the Address column title, that list will get resorted by address. I search through the list for address 0x01FC9D98.

Alex That address is the address of the GetDeviceList transition vector.

cam That makes sense. This "handle" we've been worrying about has a refNum in the first 16 bits of the structure, and a GDHandle has the refNum of the associated driver stored in the first field in the structure. I bring up a memory window and examine the device list stored in low memory to see if the gdRefNum is 0.

Alex It is. Who's responsible for initializing the GDevice record?

cam NewGDevice and InitGDevice. NewGDevice will pass the refNum to InitGDevice. Let's disassemble the code for NewGDevice.

Alex Apparently it does a NewHandleClear to allocate the GDHandle, and never initializes the refNum.

cam Whoops. Ah, the joys of pre-alpha software. Well, it should be reasonably easy to get one of the QuickDraw engineers to fix this bug. I install a fixed version of the QuickDraw shared library. We should be rockin' now!

Alex Not so fast! When I restart Marathon, I crash. If I do a stack crawl and examine the code, I seem to be crashing in exactly the same place. GetDCtlEntry still seems to return nil.

cam Just another day at the salt mines. OK, it's time to step through GetDCtlEntry. I put a breakpoint just before we call it.

Alex The refNum from the GDHandle is -51.

cam That looks like a valid refNum. Step into GetDCtlEntry.

Alex We first go through the cross-TOC glue and eventually get into GetDCtlEntry.

cam What does GetDCtlEntry look like?

Alex It seems fine, but when you step through the routine and actually fetch the DCtlHandle from the unit table, it ends up being nil.

...

626FC79C cntlzw r3,r3

626FC7A0 srwi r3,r3,5

...

cam That obviously shouldn't happen. There's a driver entry in the table and the refNum seems valid. What is the code at 0x626FC79C doing?

Alex It's performing a logical NOT operation on R3. Groovy, huh?

cam But the bitwise NOT of the refNum should be used as the index into the unit table, not the logical NOT!

Alex So, you claim that GetDCtlEntry is looking at the wrong place in the unit table to get the DCtlHandle. Are you sure?

cam Let's go to the source. What does Inside Macintosh: Devices say?

Alex It says, "The device reference number is the one's complement (logical NOT) of the unit number." But the logical NOT isn't the one's complement; the bitwise NOT is.

cam Um, OK, what does Inside Macintosh Volume II say?

Alex It claims that the unit number is "equal to -1 * (refNum + 1)."

cam And that's a bitwise NOT. So it seems that Inside Macintosh: Devices is wrong. Weird, wacky stuff. But I still don't understand why the stack crawl we did earlier pointed us to the wrong place.

Alex We did the stack crawl when we had just entered the crashing function, even before it executed the mflr instruction. The debugger, when it does a stack crawl, is going to look for stack frames to see where the callers are. Since we hadn't allocated a stack frame in the crashing function yet, we were still using the caller's stack frame. So that was the stack frame the debugger started from. If we had stepped a few more instructions in and allocated our stack frame, the debugger would have figured it out. It would be interesting to see if the debugger could actually detect the case of a nonexistent stack frame and use the link register to work back to the caller.

cam That also explains why the data breakpoint stuff didn't work. We thought that the data structure we were watching held the GDHandle. It didn't; it contained something totally unrelated, which was passed into the function that called the crashing routine.

Alex So, because NewGDevice didn't initialize the gdRefNum and GetDCtlEntry was returning the wrong entry from the unit table, I don't get to teach the Pfhor about large caliber, high-velocity rounds.

cam Nasty.

Alex Yeah.

SCORING

Your performance compares to these memorable screen roles:

80-100	 Chuck Heston in El Cid

55-75 Anne Parillaud in La Femme Nikita

30-50 Chow Yun-Fat in Hard Boiled

5-25 Richard Roundtree in Shaft*

CAMERON ESFAHANI (cameron_esfahani@powertalk.apple.com, AppleLink DIRTY) SWM, 24, 5' 7", 180 pounds, brown hair, brown eyes. Apple engineer. Loves movies and music. Plays golf and tennis, rollerblades, ice-skates, and is learning to ski again. Enjoys life but has a serious side. Likes cooking, reading, shopping. Once a dog guy, now a definite cat man. Believes the American musical of the '50s and '60s to be the second greatest invention of the twentieth century. Favorites include West Side Story, The Sound of Music, Music Man, and Singin' in the Rain.*

ALEX ROSENBERG (alexr@bungie.com) Alex's left brain works on everything from communications software to the latest 3D graphics tricks. His right brain is constantly thinking up interesting T-shirts that Apple's Marketing folks don't approve of. While working as a member of the Mac OS 8 "Ministry of Information," he experimented with optimization for PowerPC, worked closely with Apple's compiler team, and contributed to IBM's The PowerPC Compiler Writer's Guide. Now one of the minions at Bungie Software, Alex recently decided that eating is overrated.*

Thanks to Tom Dowdy, Wayne Meretsky, Mike Neil, Tom Saulpaugh, KON (Konstantin Othmer), and BAL (Bruce Leak) for reviewing this column.*

 
AAPL
$100.96
Apple Inc.
-0.83
MSFT
$47.52
Microsoft Corpora
+0.84
GOOG
$596.08
Google Inc.
+6.81

MacTech Search:
Community Search:

Software Updates via MacUpdate

Audio Hijack Pro 2.11.3 - Record and enh...
Audio Hijack Pro drastically changes the way you use audio on your computer, giving you the freedom to listen to audio when you want and how you want. Record and enhance any audio with Audio Hijack... Read more
Airfoil 4.8.9 - Send audio from any app...
Airfoil allows you to send any audio to AirPort Express units, Apple TVs, and even other Macs and PCs, all in sync! It's your audio - everywhere. With Airfoil you can take audio from any... Read more
WhatRoute 1.13.0 - Geographically trace...
WhatRoute is designed to find the names of all the routers an IP packet passes through on its way from your Mac to a destination host. It also measures the round-trip time from your Mac to the... Read more
Chromium 37.0.2062.122 - Fast and stable...
Chromium is an open-source browser project that aims to build a safer, faster, and more stable way for all Internet users to experience the web. FreeSMUG-Free OpenSource Mac User Group build is... Read more
Attachment Tamer 3.1.14b9 - Take control...
Attachment Tamer gives you control over attachment handling in Apple Mail. It fixes the most annoying Apple Mail flaws, ensures compatibility with other email software, and allows you to set up how... Read more
Duplicate Annihilator 5.0 - Find and del...
Duplicate Annihilator takes on the time-consuming task of comparing the images in your iPhoto library using effective algorithms to make sure that no duplicate escapes. Duplicate Annihilator detects... Read more
jAlbum Pro 12.2 - Organize your digital...
jAlbum Pro has all the features you love in jAlbum, but comes with a commercial license. With jAlbum, you can create gorgeous custom photo galleries for the Web without writing a line of code!... Read more
jAlbum 12.2 - Create custom photo galler...
With jAlbum, you can create gorgeous custom photo galleries for the Web without writing a line of code! Beginner-friendly, with pro results Simply drag and drop photos into groups, choose a design... Read more
Quicken 2015 2.0.4 - Complete personal f...
Quicken 2015 helps you manage all your personal finances in one place, so you can see where you're spending and where you can save. Quicken automatically categorizes your financial transactions,... Read more
iMazing 1.0 - Complete iOS device manage...
iMazing (formerly DiskAid) is the ultimate iOS device manager with capabilities far beyond what iTunes offers. With iMazing and your iOS device (iPhone, iPad, or iPod), you can: Copy music to and... Read more

Latest Forum Discussions

See All

View Source – HTML, JavaScript and CSS...
View Source – HTML, JavaScript and CSS 1.0 Device: iOS Universal Category: Utilities Price: $.99, Version: 1.0 (iTunes) Description: View Source is an app plus an iOS 8 Safari extension that makes it easy to do one key web developer... | Read more »
Avenged Sevenfold’s Hail To The King: De...
Avenged Sevenfold’s Hail To The King: Deathbat is Coming to iOS on October 16th Posted by Jessica Fisher on September 19th, 2014 [ permalink ] Just in time for Halloween, on October 16 Avenged Sevenfold will be launching | Read more »
Talisman Has Gone Universal – Can Now be...
Talisman Has Gone Universal – Can Now be Played on the iPhone Posted by Jessica Fisher on September 19th, 2014 [ permalink ] | Read more »
Tap Army Review
Tap Army Review By Jennifer Allen on September 19th, 2014 Our Rating: :: SHOOT EM ALLUniversal App - Designed for iPhone and iPad Mindless but fun, Tap Army is a lane-based shooter that should help you relieve some stress.   | Read more »
Monsters! Volcanoes! Loot! Epic Island f...
Monsters! Volcanoes! Loot! | Read more »
Plunder Pirates: Tips, Tricks, Strategie...
Ahoy There, Seadogs: Interested in knowing our thoughts on all this plundering and pirating? Check out our Plunder Pirates Review! Have you just downloaded the rather enjoyable pirate-em-up Plunder Pirates and are in need of some assistance? Never... | Read more »
Goat Simulator Review
Goat Simulator Review By Lee Hamlet on September 19th, 2014 Our Rating: :: THE GRUFFEST OF BILLY GOATSUniversal App - Designed for iPhone and iPad Unleash chaos as a grumpy goat in this humorous but short-lived casual game.   | Read more »
A New and Improved Wunderlist is Here fo...
A New and Improved Wunderlist is Here for iOS 8 Posted by Jessica Fisher on September 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Evernote Update for iOS 8 Adds Web Clipp...
Evernote Update for iOS 8 Adds Web Clipping, Quick Notes, and More Posted by Ellis Spice on September 19th, 2014 [ permalink ] | Read more »
Apple Names Ultimate Productivity Bundl...
Apple Names Ultimate Productivity Bundle by Readdle as the Essential Bundle on the App Store Posted by Jessica Fisher on September 19th, 2014 [ permalink | Read more »

Price Scanner via MacPrices.net

iFixIt Tears Down iPhone 6; Awards Respectabl...
iFixit notes that even the smaller 4.7″ iPhone 6 is a giant among iPhones; so big that Apple couldn’t fit it into the familiar iPhone form factor. In a welcome reversal of a recent trend to more or... Read more
Phone 6 Guide – Tips Book For Both iPhone 6...
iOS Guides has announced its latest eBook: iPhone 6 Guide. Brought to you by the expert team at iOS Guides, and written by best-selling technology author Tom Rudderham, iPhone 6 Guide is packed with... Read more
How to Upgrade iPhone iPad to iOS 8 without D...
PhoneClean, a iPhone cleaner utility offered by iMobie Inc., reveals a solution for upgrading iPhone and iPad to iOS 8 without deleting photos, apps, the new U2 album or anything. Thanks to more than... Read more
Inpaint 6 – Photo Retouching Tool Gets Faster...
TeoreX has announced Inpaint 6, a simple retouching tool for end users that helps remove scratches, watermarks, and timestamps as well as more complex objects like strangers, unwanted elements and... Read more
Worldwide PC Monitor Market Sees Growth in To...
Worldwide PC monitor shipments totaled 32.5 million units in the second quarter of 2014 (2Q14), a year-over-year decline of -2.9%, according to the International Data Corporation (IDC) Worldwide... Read more
Updated Price Trackers
We’ve updated our Mac Price Trackers with the latest information on prices, bundles, and availability on systems from Apple’s authorized internet/catalog resellers: - 15″ MacBook Pros - 13″ MacBook... Read more
Mac Pros available for up to $260 off MSRP
Adorama has Mac Pros on sale for up to $260 off MSRP. Shipping is free, and Adorama charges sales tax in NY & NJ only: - 4-core Mac Pro: $2839.99, $160 off MSRP - 6-core Mac Pro: $3739.99, $260... Read more
13-inch 2.6GHz/256GB Retina MacBook Pros avai...
B&H Photo has the 13″ 2.6GHz/256GB Retina MacBook Pro on sale for $1379 including free shipping plus NY sales tax only. Their price is $120 off MSRP. Read more
Previous-generation 15-inch 2.0GHz Retina Mac...
B&H Photo has leftover previous-generation 15″ 2.0GHz Retina MacBook Pros now available for $1599 including free shipping plus NY sales tax only. Their price is $400 off original MSRP. B&H... Read more
21″ 2.7GHz iMac available for $1179, save $12...
Adorama has 21″ 2.7GHz Hawell iMacs on sale for $1179.99 including free shipping. Their price is $120 off MSRP. NY and NJ sales tax only. 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
Position Opening at *Apple* - Apple (United...
**Job Summary** At the Apple Store, you connect business professionals and entrepreneurs with the tools they need in order to put Apple solutions to work in their Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** The Apple Store is a retail environment like no other - uniquely focused on delivering amazing customer experiences. As an Expert, you introduce people Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** As businesses discover the power of Apple computers and mobile devices, it's your job - as a Solutions Engineer - to show them how to introduce these Read more
Position Opening at *Apple* - Apple (United...
…Summary** As a Specialist, you help create the energy and excitement around Apple products, providing the right solutions and getting products into customers' hands. You Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.