TweetFollow Us on Twitter

Code Mechanic

Volume Number: 13 (1997)
Issue Number: 5
Column Tag: develop

Code Mechanic: Better Than Ever Stress Testing

by Dave Evans

There are few things more frustrating than losing access to your debugging tools due to a freeze, because you can't fix what you can't diagnose. The best course is to stop freezes before they start, so I'd like to share a common cause of freezes I've found. I'll also discuss some of the stress-testing options that are available to help you catch freeze-causing problems you might have missed, including an improved debugging tool.

Veteran readers of develop may notice a new title for this column. The previous title, "Balance of Power," was apt for its time, indicating a focus on PowerPC issues. But now that all new MacOS computers are PowerPC-based, everybody's writing about PowerPC, and my efforts in this area are complete. This new title reflects a focus on the mechanics of code tuning, with tips for improving your application's performance and stability, which I hope you'll find just as useful.

Protect Your Vectors

Even if you use a PowerPC-based MacOS computer, the first 256 bytes of memory are dedicated to 680x0 exception vectors, which the 680x0 software emulator uses to emulate 680x0 exceptions and interrupts. On a 680x0-based computer, these values are read by the processor itself when handling an exception or servicing an interrupt.

Under System 7, these important vectors are not memory protected. Any program can read from or write to them, possibly resulting in a serious failure. While not all of the vectors are used, modifying some of them will cause an immediate freeze, leaving you without access to your debugging tools. You probably don't address these vectors intentionally, but it often occurs accidentally when a nil pointer or empty handle is de-referenced.

Unintentionally reading from these vectors will produce a random result. In most cases the vectors are addresses of special system routines; these vectors can have any value, and they vary significantly from one computer model to another. As an example of how easy it is to cause a problem in this area, take a look at the following C code, similar to that found in some applications:

front_window = FrontWindow();
if (front_window->windowKind < 0)
 MyDeskAccessoryRoutine(front_window);

The developers didn't realize that FrontWindow can return nil when no windows are open. In that case the application de-references the nil pointer and makes a logical decision based on the sign of the half word at $6C in low memory, which is the high half of the interrupt level 3 vector. On most Macintosh computers released before 1995, this vector pointed into ROM starting at address $40800000. Because of this, the applications would test the high half word value of $4080, and they wouldn't run the desk accessory routine. This was the right behavior, but for the wrong reason; disaster was averted by luck.

Beginning with all PCI-based PowerPC computers, ROM starts at location $FFC00000. During the development of these computers, we found that applications with code like the above would crash because they executed unexpected code after comparing the new half word value of $FFC0. We were able to work around their problem by changing the interrupt level 3 vector to point to a routine in RAM. This changed the high half word value to be a small positive number, and the applications behaved as expected. Still, the best case would have been if the problem could have been avoided in the first place. The following code is an example of what would have been a better, crash-free approach:

front_window = FrontWindow();
if (front_window && front_window->windowKind < 0)
 MyDeskAccessoryRoutine(front_window);

Checking for nil pointers or handles is one way you can avoid these crashes in the first place. Checking for empty handles is another necessary step, since unlocked relocatable blocks that are marked purgeable may disappear any time memory can move.

To detect problems with purgeable blocks, you'll need tools to stress test your application. Utilities that display heap zones, allowing you to compact and purge a heap on demand, are a good start. For serious testing, however, you'll need a stress tool that operates all the time. One good tool for this is MemHell, which will compact and purge your heap whenever a Memory Manager routine that might move or purge memory is called. This slows down execution of your tests, but it will flush out problems with purgeable blocks.

So, while accidentally reading from low memory can cause unexpected results, accidentally writing to low memory can be fatal, and this is one of the most common causes of freezes that I've noticed. You may think this could never happen in your code, because none of your blocks are purgeable and you always check errors after allocating pointers. Think again; there are plenty of other opportunities. Do you check for an error after every GetResource call? Getting an unexpected error - from a corrupted resource file, for example - is one way you can end up with a nil handle. Besides diligent review of your code, you need to do stress testing to flush out possible errors, or freezes are likely to result.

Are You Stressed Enough?

There are a number of tools to help add stress to your testing. I've already mentioned MemHell for finding problems with purgeable blocks. You'll similarly need a tool to find reads and writes to the exception vectors.

The simplest choice is the ubiquitous and venerable EvenBetterBusError, written by Greg Marriott. This tool safeguards the first four bytes of memory, which are very often accidentally written over or read from. To detect reads, it places in the first four bytes of memory a value which when de-referenced will cause a crash. If you use a nil pointer or empty handle, the illegal value is likely to be used as data or de-referenced, leading to a crash. To detect writes, it checks periodically to see if the value that it placed has been overwritten; if so, you'll be notified with a DebugStr message. EvenBetterBusError is included as a dcmd in MacsBug beginning with version 6.5.4.

I've extended EvenBetterBusError to be more aggressive. The new version, YetEvenBetterBusError, writes a value over the first 256 bytes of memory which will cause a crash into your debugger when de-referenced. It also checks periodically for writes to these locations, but more frequently than EvenBetterBusError does. Like EvenBetterBusError, upon noticing a write to these locations it will notify you with a DebugStr message. YetEvenBetterBusError can be found at www.mactech.com.

To implement YetEvenBetterBusError, I had to sacrifice some compatibility with existing applications. Any application code that assumes the exception vectors start at address 0 will no longer function correctly. Most applications don't use the exception vectors directly, but some copy protection schemes do modify the vectors.

The correct way to determine the location of the exception vectors is by using the 680x0 instruction MOVEC, which must always be executed in supervisor mode. The location of the first vector is stored in the 680x0 VBR (Vector Base Register). To read the address, you would write the following assembly code:

_EnterSupervisorMode ; old sr result in d0
movec   vbr,a0   ; get the vbr
move.w  d0,sr    ; restore the old sr

Always use the VBR to find these vectors. Although early versions of the MacOS always placed them at location 0, they're now often elsewhere. When virtual memory is turned on, for example, the vectors will actually reside in the system heap, and the VBR will point to them. To maintain compatibility, however, if virtual memory doesn't handle an exception it calls through to the original vector table at location 0. This is why even with virtual memory on, writing over the low-memory exception vectors can still cause a freeze.

YetEvenBetterBusError is able to overwrite and then monitor the first 256 bytes of memory by moving the exception vector table entirely. So, even when virtual memory is on, with YetEvenBetterBusError installed the original low-memory vectors are never called. This is why some existing applications may be incompatible with YetEvenBetterBusError.

A Cure for Test Anxiety

It's true that fully testing your code to reflect all possible configurations and user actions can be a near-impossible task. But the perceived stability of both your application and the computer depends on how well we all write and test our software. To do the best possible job, use the stress-testing tools mentioned in this column or in the article "Squashing Memory Leaks with TidyHeap" in this issue. Do the right thing: stress test, then relax!

Thanks to Pete Gontier, Chris Jalbert, Bo3b Johnson, Dave Lyons, Quinn "The Eskimo!", and Keith Stattenfield for reviewing this column.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

PCalc 4.6.3 - Full-featured scientific c...
PCalc is a full-featured, scriptable scientific calculator with support for hexadecimal, octal, and binary calculations, as well as an RPN mode, programmable functions, and an extensive set of unit... Read more
Uncrook 1.2 - Uncrook - Straighten horiz...
Uncrook - Straighten horizons. You just took a bunch of great pictures, but the horizon is crooked on some of them? A great sunset over the ocean. Mountains in the background of your hiking trip... Read more
xScope 4.3.3 - Onscreen graphic measurem...
xScope is powerful set of tools that are ideal for measuring, inspecting, and testing on-screen graphics and layouts. Its tools float above your desktop windows and can be accessed via a toolbar,... Read more
Smultron 11.0.3 - Easy-to-use, powerful...
Smultron 11 is the text editor for all of us. Smultron is powerful and confident without being complicated. Its elegance and simplicity helps everyone being creative and to write and edit all sorts... Read more
Macs Fan Control 1.4.12.0 - Monitor and...
Macs Fan Control allows you to monitor and control almost any aspect of your computer's fans, with support for controlling fan speed, temperature sensors pane, menu-bar icon, and autostart with... Read more
Merlin Project 5.0.8 - Project managemen...
Merlin Project is the leading professional project management software for OS X. If you plan complex projects on your Mac, you won’t get far with a simple list of tasks. Good planning raises... Read more
WhatsApp 0.3.1242 - Desktop client for W...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
BusyContacts 1.3.0 - Fast, efficient con...
BusyContacts is a contact manager for OS X that makes creating, finding, and managing contacts faster and more efficient. It brings to contact management the same power, flexibility, and sharing... Read more
X Lossless Decoder 20181019 - Encode, tr...
X Lossless Decoder (XLD) is a tool for OS X that is able to decode/convert/play various 'lossless' audio files. The supported audio files can be split into some tracks with cue sheet when decoding.... Read more
calibre 3.33.1 - 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

Dragalia Lost Trick or Treasure Jumpstar...
It’s finally here! Loyalty’s Requiem ended in Dragalia Lost, but it has swiftly been replaced with a new Halloween event. This event—called Trick or Treasure—had quite a bit of hype surrounding it before it came out, and for good reason too. | Read more »
Here are the awesome iPhone and iPad gam...
Ah the working week is crawling towards its end. But fret not, dear reader, there's still time for us to share with you the iPhone and iPad games that you should be excited about playing next week. And we reckon there are at least three games on... | Read more »
It's up to you to decide the winner...
Thursday is the day when most of the new releases come out on the App Store. It's also the day when we pick what we think are the best five games that have come out over the last seven days. Then we pose you, our readers, a simple question - which... | Read more »
Grimvalor is last week's 148Apps iP...
What a week it has been here at 148Apps towers. We've been swamped, which means we're a bit late letting you know what last week's game of the week was. Don't worry though, we're here now, and we can reveal that Grimvalor takes away the prize. It... | Read more »
My scariest mobile game - Final Fantasy...
This is going to be a bit of a weird one, but bear with me. The game that has scared me the most isn't a horror experience (don't get me wrong, I won't go outside if it's foggy thanks to Silent Hill 2), it's actually Final Fantasy 7. Sounds... | Read more »
My scariest mobile game - Final Fantasy...
This is going to be a bit of a weird one, but bear with me. The game that has scared me the most isn't a horror experience (don't get me wrong, I won't go outside if it's foggy thanks to Silent Hill 2), it's actually Final Fantasy 7. Sounds... | Read more »
Dragalia Lost Daily Tasks Guide
Part of what makes gacha games compelling (and sometimes annoying) is their grind. You’re always supposed to be advancing something in these games, meaning you need to be checking in on your progress once or multiple times a day to make sure you’re... | Read more »
Why I'm looking forward to Stardew...
Last week I read the words I'd been hoping for and got so excited I almost cried: Stardew Valley is coming to mobile on October 24th. While, my colleagues know of my love for the game I think my reasons behind it have always been a bit of a... | Read more »
The best games for iPhone - The definiti...
Hi there, and welcome to our ever-increasing list of the very best games for iPhone. We're going to be updating this regularly with new content, so make sure you check back often, because you're not going to want to miss out on even one of the... | Read more »
Mad Rocket: Fog of War is the next big b...
Mad Rocket: Fog of War is the latest title from pblisher Four Thirty Three, and it’s a game that will have you rethinking your approach to strategic war games. In this new base-building card battler, you’ll be invading bases enshrouded in thick fog... | Read more »

Price Scanner via MacPrices.net

Apple now offering Certified Refurbished 2018...
Save $360 to $420 on the purchase of a 2018 15″ Touch Bar MacBook Pro with these Certified Refurbished models now available at Apple. Each model features a new outer case, shipping is free, and an... Read more
Pay as little as $1439 for a 13″ Touch Bar Ma...
Apple has Certified Refurbished 2017 13″ 2.3GHz/256GB Touch Bar MacBook Pros available starting at $1439. Apple’s refurbished prices are the lowest available for each model from any reseller. An... Read more
2018 15″ MacBook Pros on sale for up to $300...
B&H Photo has new 2018 15″ Touch Bar MacBook Pros on sale for $100-$300 off Apple’s prices. Shipping is free at B&H, and they charge sales tax for residents of NY & NJ only: – 15″ 2.2GHz... Read more
Apple drops prices on Series 3 GPS Apple Watc...
Apple has restocked Certified Refurbished Series 3 Apple Watch GPS models starting at only $239. Apple’s standard 1-year warranty is included, and shipping is free. Numerous bands are available: –... Read more
Apple now offering Certified Refurbished 2018...
Apple is now offering Certified Refurbished 2018 13″ 2.3GHz Touch Bar MacBook Pros for $270-$300 off the cost of new models, with prices starting at $1529. Apple’s refurbished prices are the lowest... Read more
21″ and 27″ iMacs available starting at only...
Apple has a full line of Certified Refurbished iMacs available for up to $350 off original MSRP. Apple’s one-year warranty is standard, and shipping is free. The following models are available: – 27... Read more
Apple offers a wide range of refurbished iPad...
Apple has Certified Refurbished 2017 10.5″ iPad Pros available for $100-$170 off MSRP, depending on the model. An Apple one-year warranty is included with each model, and shipping is free: – 64GB 10... Read more
Get a new 2018 13″ 2.3GHz Touch Bar MacBook P...
B&H Photo has new 2018 13″ 2.3GHz/256GB Touch Bar MacBook Pros on sale for $100 off MSRP. Shipping is free at B&H, and they charge sales tax for residents of NY & NJ only: – 13″ 2.3GHz/... Read more
Order a new 2018 15″ MacBook Pro from Adorama...
Adorama is offering new 2018 15″ Touch Bar MacBook Pros for up to $300 off MSRP. Shipping is free, and they charge sales tax for residents of NY & NJ only: – 15″ 2.2GHz Touch Bar MacBook Pros (... Read more
2017 15″ 2.9GHz Touch Bar MacBook Pro availab...
Adorama has clearance 2017 high-end 15″ 2.9GHz Space Gray Touch Bar MacBook Pros available for $2099 or $700 off original MSRP. Shipping is free, and Adorama charges sales tax in NJ and NY only: – 15... Read more

Jobs Board

Best Buy *Apple* Computing Master - Best Bu...
**652484BR** **Job Title:** Best Buy Apple Computing Master **Job Category:** Store Associates **Location Number:** 001545-Port Arthur-Store **Job Description:** The Read more
*Apple* Mobile Master - Best Buy (United Sta...
**652223BR** **Job Title:** Apple Mobile Master **Job Category:** Store Associates **Location Number:** 001768-East Houston-Store **Job Description:** **What does a Read more
Best Buy *Apple* Computing Master - Best Bu...
**652342BR** **Job Title:** Best Buy Apple Computing Master **Job Category:** Sales **Location Number:** 001012-Bismarck-Store **Job Description:** **What does a Read more
Geek Squad *Apple* Master Consultation Agen...
**651961BR** **Job Title:** Geek Squad Apple Master Consultation Agent **Job Category:** Services/Installation/Repair **Location Number:** 001468-West Simsbury-Store Read more
Best Buy *Apple* Computing Master - Best Bu...
**651761BR** **Job Title:** Best Buy Apple Computing Master **Job Category:** Store Associates **Location Number:** 001165-Glenview-Store **Job Description:** The Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.