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

NeoOffice 2017.14 - Mac-tailored, OpenOf...
NeoOffice is a complete office suite for OS X. With NeoOffice, users can view, edit, and save OpenOffice documents, PDF files, and most Microsoft Word, Excel, and PowerPoint documents. NeoOffice 3.x... Read more
Iridient Developer 3.3.1 - Powerful imag...
Iridient Developer (was RAW Developer) is a powerful image-conversion application designed specifically for OS X. Iridient Developer gives advanced photographers total control over every aspect of... Read more
Google Chrome 70.0.3538.110 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Adobe Pepper Flash Player 31.0.0.153 - P...
Adobe Pepper Flash Player is a cross-platform, browser-based application runtime that provides uncompromised viewing of expressive applications, content, and videos across browsers and operating... Read more
Chromium 70.0.3538.110 - 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. Version 70.0.3538.110: Release notes were... Read more
Adobe Flash Player 31.0.0.148 - Plug-in...
Adobe Flash Player is a cross-platform, browser-based application runtime that provides uncompromised viewing of expressive applications, content, and videos across browsers and operating systems.... Read more
Adobe Flash Player 31.0.0.153 - Plug-in...
Adobe Flash Player is a cross-platform, browser-based application runtime that provides uncompromised viewing of expressive applications, content, and videos across browsers and operating systems.... Read more
Tidy Up 5.0.11 - Find duplicate files an...
Tidy Up is a full-featured duplicate finder and disk-tidiness utility. Features Supports Lightroom: it is now possible to search and collect duplicates directly in the Lightroom library. Multiple... Read more
BusyContacts 1.3.1 - 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
Reflector 3.2.0 - AirPlay your iOS devic...
Reflector allows you to AirPlay mirror your iPhone or iPad to your Mac. Features Easily demo iOS apps on any Mac running OS X Lion using AirPlay Mirroring on iOS 5. Enable an iPhone or iPad wrapper... Read more

Latest Forum Discussions

See All

Win a brand new iPad courtesy of SEGA an...
Fancy enjoying a blast from the past on an Apple iPad (9.7 inch)? Well now you have the chance to do just that thanks to Pocket Gamer's latest giveaway to celebrate the launch of SEGA Heroes. Developed by the same team behind Marvel® Puzzle Quest,... | Read more »
How will World of Warcraft, Starcraft, a...
You might have heard that Blizzard is bringing Diablo to mobile with Diablo Ultimate. There's been plenty of controversy surrounding that decision, and it's meant that a really important piece of information has been glossed over a little. Namely... | Read more »
Slots Panther Vegas offers a social gamb...
New era of Online gambling Want to try your luck in online social gambling? More and more people are into online casinos as a risk-free amazing way to experience the excitement of a big game. Online casinos and slots machines are gaining popularity... | Read more »
3 features we think you'll love in...
Well known classic RPG “Shin Megami Tensei” franchise originally created by Atlus, can now be played throughout iOS and Android. Created by Sega, “Shin Megami Tensei” has spawned a mobile-centric installment in the shape of “Shin Megami Tensei:... | Read more »
These are the top 3 games for iPhone and...
The end of the week has rolled around again, which means it's time for us to look forward to the games you're going to be playing over the next seven days. We've got the return of a mobile gaming legend next week, as well as a couple of other... | Read more »
Time for you to pick which of these top...
Oh look, Thursday is upon us once more. And we all know what that means! You guessed it, it's time for you to vote for which of these five games you think deserves to win our game of the week award. And have we got a selection for y'all this week... | Read more »
Dragalia Lost - High Midgardsormr Prep G...
It might not seem like there's a ton to do between events in Dragalia Lost, but there is one high level piece of content that can keep you occupied for a long time. Defeating High Midgardsormr is currently the game's most difficult non-event... | Read more »
Get your friends, these are the top 5 be...
You can't be a lone wolf all the time, especially if you want to show off your gaming prowess. And that's where this list comes in - we're running down what we think are the top 5 multiplayer games for iPhone. There might be some controversial... | Read more »
SpitKiss is the worthy winner of last we...
It's been a rough and tumble battle this week, with all of the games managing to get a few hits in where it counts, but after checking with the independent adjudicators at ringside, we can now reveal that gloriously gross smooching sim SpitKiss has... | 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 »

Price Scanner via MacPrices.net

Sprint offers 32GB 9.7″ iPads with Apple Penc...
Sprint is offering 32GB 9.7″ WiFi + Cellular iPads for only $99.99 when added to your Sprint account. Standard MSRP for these iPads is $459, so their Black Friday week 2018 savings amounts to $360!... Read more
Apple to host four day shopping event this 20...
Apple will be hosting a four day shopping event beginning Friday November 23, 2018 and lasting through Monday November 26th. Special offers will be posted each day, and we will have all the details... Read more
Get a 2018 13″ 4-Core Touch Bar MacBook Pro f...
Apple has Certified Refurbished 2018 13″ 2.3GHz 4-Core Touch Bar MacBook Pros available for $270-$300 off the cost of new models, with prices starting at $1529. Apple’s refurbished prices are the... Read more
Score the best price on Apple’s Macs, iPads,...
Our Apple award-winning price trackers are the best place to look for the best deals and lowest prices on Apple gear this Black Friday and Holiday shopping season. Scan our price trackers for the... Read more
The cheapest price on a 15″ MacBook Pro today...
Save $360 to $420 on the purchase of a 2018 15″ Touch Bar MacBook Pro with these Certified Refurbished models available at Apple. Each model features a new outer case, shipping is free, and an Apple... Read more
Black Friday deal: 12″ 1.3GHz Gold MacBook fo...
Amazon today is has the 12″ 1.3GHz Gold MacBook on sale for $301 off Apple’s price, only $1298 shipped, as part of their Black Friday 2018 week sales: – 12″ 1.3GHz Gold MacBook: $1298 $301 off MSRP... Read more
Score Black Friday Prices On Apple Items Now...
NEWS: 11.19.18- The best bet for anyone shopping for a new shiny Apple product and looking to save the most amount of money going in to this holiday season need not look further than our price... Read more
Save on a new MacBook with these early Black...
B&H Photo has posted early Black Friday sale prices on Apple MacBooks, including up to $300 off MSRP on 15″ MacBook Pros, $100 off new 13″ MacBook Airs, and more. Most of these deals expire... Read more
T-Mobile Black Friday deal: Free iPhone Xr wi...
T-Mobile is offering the 64GB iPhone Xr for free as part of their Black Friday 2018 sale. Two new lines are required, as well as an eligible trade-in (iPhone 6s models or newer). $20.84 is applied to... Read more
Save up to $157 on a 10.5″ iPad Pro with thes...
Apple’s newest authorized reseller, Jet, has 10.5″ iPad Pros on sale for up to $157 off MSRP as part of their Black Friday week sale. Shipping is free. Note that some sale prices may be restricted to... Read more

Jobs Board

*Apple* Mobile Master - Best Buy (United Sta...
**658288BR** **Job Title:** Apple Mobile Master **Job Category:** Store Associates **Location Number:** 000262-Carolina Mall-Store **Job Description:** **What does a Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States- Apple Blossom Mall 1850 Apple Blossom Dr Job ID:1044618 Date:Today Job Read more
Sephora Product Consultant - *Apple* Blosso...
Sephora Product Consultant - Apple Blossom Mall Location:Winchester, VA, United States- Apple Blossom Mall 1850 Apple Blossom Dr Job ID:1056553 Date:Today Job Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States- Apple Blossom Mall 1850 Apple Blossom Dr Job ID:1042611 Date:Today Job Description Read more
Omni-Channel Associate - *Apple* Blossom Ma...
Omni-Channel Associate - Apple Blossom Mall Location:Winchester, VA, United States- Apple Blossom Mall 1850 Apple Blossom Dr Job ID:1074107 Date:Today Job Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.