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

Maintenance 2.9.9 - System maintenance u...
Maintenance is a system maintenance and cleaning utility. It allows you to run miscellaneous tasks of system maintenance: Check the the structure of the disk Repair permissions Run periodic scripts... Read more
Deeper 2.8.8 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
BetterTouchTool 3.9998 - 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
OnyX 4.3.6 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more
Acorn 7.3.2 - Bitmap image editor.
Acorn is a new image editor built with one goal in mind - simplicity. Fast, easy, and fluid, Acorn provides the options you'll need without any overhead. Acorn feels right, and won't drain your bank... Read more
Google Chrome 109.0.5414.119 - Modern an...
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
ASPPPPP 1.3.99999999999 - Create cursor...
ASPPPPP brings Aperture Science's portal technology to your desktop. Avoid carpal canal syndrome and save millions of pixels of cursor moving. When launching the app, you first set the position of... Read more
beaTunes 5.2.31 - Organize your music co...
beaTunes is a full-featured music player and organizational tool for music collections. How well organized is your music library? Are your artists always spelled the same way? Any R.E.M. vs REM?... Read more
FotoMagico 6.3.3 - Powerful slideshow cr...
FotoMagico lets you create professional slideshows from your photos and music with just a few, simple mouse clicks. It sports a very clean and intuitive yet powerful user interface. High image... Read more
RoboForm 9.4.1 - Password manager; syncs...
RoboForm is a password manager that offers one-click login, mobile syncing, easy form filling, and reliable security. Password Manager. RoboForm remembers your passwords so you don't have to! Just... Read more

Latest Forum Discussions

See All

‘Railbound’ Massive 2.0 Update To Bring...
Railbound from Afterburn Games is set to get a massive update this week. Since its launch, Railbound has gotten a good amount of support already. Read about the most recent big update here. Afterburn Games will bring Railbound 2.0 to mobile and PC... | Read more »
TouchArcade Game of the Week: ‘Madness/E...
Sometimes a game comes along that feels so purely built for mobile, and its controls and mechanics come together so well on the touchscreen, I say that Apple should just pre-install it on every iPhone it sells. I very much feel that way about... | Read more »
SwitchArcade Round-Up: ‘ATONE’, ‘Dance o...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for January 27th, 2023. In today’s article, we mop up the remaining releases of the week. There are quite a few, thanks to some slipping out after I went home last night. There are... | Read more »
‘Prehistoric Isle 2 ACA NEOGEO’ Review –...
It’s somewhat surprising how clearly one can draw a line between SNK before NEOGEO’s launch and after. The likes of Psycho Soldier and Ikari were relegated to cameo appearances, and only a few lucky pre-NEOGEO IPs ever saw follow-ups on the multi-... | Read more »
Old School RuneScape announces landmark...
Jagex has announced some groundbreaking news for fans of its iconic MMORPG, Old School RuneScape. For the first time in the game's 15-year history, the player base has voted in favour of the implementation of a new skill to the retro masterpiece... | Read more »
Physics Puzzler ‘Squiggle Drop’ From Noo...
Noodlecake’s Squiggle Drop () featuring more than 100 puzzles is the final new Apple Arcade release of January 2023. When Apple revealed the games for the month, I was very curious to see how Squiggle Drop would turn out. It seemed like a game I’d... | Read more »
‘Of Two Minds’, a Psychoanalytical FMV G...
We are truly in the renaissance of full-motion video games since the genre first arrived in the late ’80s and early ’90s before dying an ugly death due to the poor quality of those gaming experiences as well as the poor quality of the actual video... | Read more »
SwitchArcade Round-Up: ‘Goldeneye’ Comin...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for January 26th, 2023. The big news is that Goldeneye for Nintendo Switch Online finally has a release date, and it’s soon as it could be. We have a ton of new releases to go through... | Read more »
Previously Cancelled Co-Op City Builder...
Back in August of 2021 developer Supercell formally announced Everdale to the world, a cooperative city building game that had already been in a smaller form of beta testing under a different name for at least a year prior. That announcement kicked... | Read more »
Burgeon and Flourish are releasing an FM...
Game development can take a while, with bugs, reworks and good old-fashioned arguments delaying things. However, the upcoming FMV game Of Two Minds may have the longest source material to game delay of all time, being a huge 30 years in the making... | Read more »

Price Scanner via MacPrices.net

Apple may release high-end Reality Pro device...
Mark Gurman, in this weeks’s Power On newsletter, states that Apple may attempt to release a high-end, nearly $3000, Reality Pro device in an attempt to move the VR market forward. With potential... Read more
13″ M2 MacBook Pros available today at Apple...
Apple standard-configuration 13″ MacBook Pros with M2 CPUs in stock and available today starting at $1169, Certified Refurbished, and ranging up to $150 off original MSRP. These are the cheapest 13″... Read more
Get a 13″ M2 MacBook Air at Apple today for a...
Apple has standard-configuration 13″ M2 MacBook Airs in stock and on sale starting at only $1079, Certified Refurbished, and ranging up to $150 off MSRP. These are the cheapest M2-powered MacBooks... Read more
Apple Card special offers for January and Feb...
Apple Card is offering special offers for January & February, 2023 which include a $75 Daily Cash offer for customers who open a new Apple Card through February and a $55 Daily Cash offer for new... Read more
New low price: Clearance 14″ M1 Pro MacBook P...
B&H Photo has dropped prices on Apple’s previous-generation 14″ 8-Core M1 Pro MacBook Pros by $300 off original MSRP, now only $1699. Free 1-2 day shipping is available to most US addresses: – 14... Read more
Apple has clearance 27-inch 5K iMacs in stock...
Apple has a full line of Certified Refurbished 2020 27″ 5K iMacs available starting at only $1169 and ranging up to $810 off original MSRP. Apple’s one-year warranty is standard, shipping is free,... Read more
Price drop! Apple has M1 Mac mini in stock fo...
Apple has dropped prices on clearance M1-powered Mac minis in their Certified Refurbished section to a new low starting price of only $469. Each mini comes with Apple’s one-year warranty, and... Read more
The Latest Rumors and Potential Features of a...
The rumors are flying and speculation is running rampant around the possibility of a new Apple iMac Pro. It is expected to be a powerful computer in Apple’s lineup, and people are already asking what... Read more
New low price: Apple Studio Display for $1399...
Amazon has Apple Studio Displays on sale for $200-$150 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1399.99 $200 off MSRP – Studio Display (Nano glass): $1749 $... Read more
Week’s Best Apple Deals: Clearance 14-inch M1...
With the introduction of new M2 Pro and M2 Max-powered 14″ MacBook Pros, Apple and its retailers have dropped prices on standard-configuration 14″ MacBook Pros with M1 Pro CPUs by as $570 off... Read more

Jobs Board

Wireless Device Portfolio Manager - *Apple*...
…in our Retail Wireless journey. The successful Device Portfolio Manager - Apple will work cross-functionally to develop, oversee and execute a device roadmap Read more
Bilingual Level 1 *Apple* Support Specialis...
…generous employee benefits! Our client is currently seeking a qualified Bilingual Level 1 Apple Support Specialist to join their team. This role can be hybrid / Read more
Security Officer - *Apple* Store - NANA Reg...
…security is our \#1 priority\. This is a public environment at the Apple Store and surrounding areas with the corresponding levels of traffic \(employees, visitors, Read more
Device Portfolio Manager - *Apple* - DISH (...
…in our Retail Wireless journey. The successful Device Portfolio Manager - Apple will work cross-functionally to develop, oversee and execute a device roadmap Read more
Senior STE / *Apple* / OTT / Streaming Serv...
…and perform tests to validate large-scale content operations and releases. As an Apple STE, you'll partner with the content and streaming teams to ensure smooth Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.