TweetFollow Us on Twitter

Spotlight-Illuminate Bugs

Volume Number: 13 (1997)
Issue Number: 8
Column Tag: Tools Of The Trade

Spotlight: Illuminate Your Bugs

by Paul Robichaux

Memory protection, trap parameter checking, and leak checking

Introduction

Generally, Macintosh development tools stand up very well to their counterparts on other platforms -- with one exception. Until recently, the Mac lacked a comprehensive debugging tool to compare with BoundsChecker for Windows or Purify for Unix. These products -- much beloved by developers on other platforms -- generally offer three classes of services: memory protection, parameter checking for system APIs, and leak detection. While their implementations differ, they generally don't require any changes to the source code and can be used throughout the development process to trap offending code before it is referred to QA or user testing.

Of course, the Mac toolbox presents a number of opportunities for doing Bad Things in your code: writing in other apps' heaps, dereferencing a handle after it's been moved, and forgetting to dispose of dynamically allocated resources are three perennial favorites. A tool which could detect these, and other, errors would be valuable indeed. While there are products on the Mac which offer one or two of these services, no one has yet combined all three into a single, easy-to-use package. Spotlight, called by Onyx Technologies an "automatic memory debugger," provides all three services in a robust, easy-to-use package.

What Spotlight Does

Spotlight is designed to be run as part of the development process. When you run it, it loads your executable, makes a copy of it, and patches the copy to insert its watchdog code. You don't have to modify your source code (except in rare cases as described below) or even relink! The watchdog code that Spotlight inserts will cause an exception to occur when your app does something it's not supposed to; Spotlight will catch the exception and show you a window detailing the offense (see Figure 1.) In this case, I deliberately called InsetRect() with a nil pointer. Notice how Spotlight not only flagged the error, but told me what I'd done wrong.

Figure 1. Spotlight's error reporting window.

Spotlight offers three types of debugging services: memory protection, leak detection, and Toolbox call validation. Let's see how Spotlight provides each class of service.

Memory Protection

Unix and Windows NT both offer per-process memory protection. If a process tries to access memory outside its own address range, an exception occurs. The operating system traps these exceptions and stops the offending process. While not perfect, per-process protection usually keeps one ill-behaved application from trashing others -- as frequently happens on the Mac. This same sort of coarse-grained protection was planned for MacOS 8; in the meantime, though, System 7 doesn't offer any OS-level memory protection. Spotlight checks every read and write instruction before executing it. If your application tries to access memory in a heap owned by the system, or another application, Spotlight stops it and displays the offending source line and address, as well as the contents of memory at that address.

In addition to interprocess memory protection, Spotlight also watches memory inside your application's heap. If you try to use a handle block after freeing it, or write past the end of a stack variable, Spotlight will catch it and warn you immediately.

Leak Detection

If Isaac Newton had lived in the time of digital computers, his First Law might well have said "For every allocation, there must be an equal and opposite deallocation." Unfortunately, this law is often recalled in the breach -- it's all too easy to forget that call to delete, DisposeHandle, or ReleaseResource. When you allocate something and forget to free it, that's a leak. Resources, handles, Macintosh or C pointer blocks, and C++ objects can all be leaked. Spotlight will detect leaked blocks, handles, resources, and objects and display them in a summary which lists the block size and a stack trace of the code which allocated it.

Toolbox Call Validation

In an ideal world, your code could pass any kind of garbage to a Toolbox routine and get a useful error code or exception in return. In practice, passing invalid parameters to Toolbox routines is easy to do but hard to detect -- most often, these bad parameters result in buried misbehavior that surfaces, like a great white shark, to bite you when you least expect it. Spotlight does a pre-flight check on arguments to about 400 different Toolbox routines; if you pass in an invalid parameter, you'll get a warning indicating which parameters and which Toolbox call are suspect.

Spotlight also checks for resource-handling errors by checking the value of ResError after each Resource Manager call; I consider this as extra Toolbox validation, so I won't discuss it separately.

At this point, you might be wondering how Spotlight differs from Onyx's QC; after all, they're both debugging tools and seem to have a lot in common. The two products complement each other. QC runs on 68K machines; Spotlight doesn't. Spotlight can detect memory and resource leaks; QC can't. Both offer some memory protection and Toolbox call validation features; Spotlight's implementation is more complete. QC was designed as a stress-testing tool -- besides its debugging features, it can automatically scramble, purge, and free memory and resources to help you find subtle errors which only show up under low-memory conditions. Spotlight is designed as a day-in-and-day-out debugging tool that you use in parallel with your compiler, linker, and source-level debugger.

Plugging in the Light

Spotlight DR1 ships as a single PowerPC binary; it only runs on PowerPC machines. Besides the Spotlight application itself, Onyx includes a copy of Apple's PowerMac Debug Services debug nub and a 6-page electronic manual in self-reading document (SRD) format. During installation, you have to provide the serial number included with the package; once you've done that, you'll be able to run Spotlight on your applications.

To use Spotlight, just launch it and open an .xSYM file; you don't have to recompile or relink your application unless you need to use Spotlight's API routines, which let you turn Spotlight on and off in critical sections of your code. The API itself is very simple -- only 5 routines -- but most applications won't need it.

Spotlight copies your executable and patches in its own routines for inspecting memory allocation, watching for leaks, and validating Toolbox parameters. This patching process takes a noticeable amount of time (about 6 seconds for my app on an 8100/100 with 32Mb of RAM), but you can speed it up by first copying your app and .xSYM file to a RAM disk.

Once Spotlight is finished patching your application, it will launch and run normally -- albeit slower than usual. You can use your app just as you would while running in a source- or low-level debugger; when Spotlight detects an illegal access in your code, it will display its reporting window so you can see what's wrong and choose what to do about it. In addition to highlighting the offending instruction, Spotlight will also tell you what fault it detected. (Note that Spotlight doesn't stop for leaks, since it can't tell whether an allocation is a leak or not until you stop the program.)

When the reporting window appears, you can use commands in the Debug menu to control what Spotlight does:

  • Ignore (cmd-I) will cause Spotlight to pretend that it didn't see anything amiss and continue executing your program. If Spotlight catches something that's not really an error (say, when you call Get1Resource() to see if something exists), you can use this button to skip over it. If the error is real, you ignore it at your peril, because your app can still crash while Spotlight's running.
  • Ignore Address (cmd-A) works like Ignore, but it tells Spotlight to ignore any error generated by the source code address being reported. This is useful if you're doing something in a loop or a frequently called function that's not really an error.
  • Log (cmd-L) tells Spotlight to log the error to its log file, which is named "Spotlight Log" and lives in the same folder as the application and symbol file you're debugging. Each log entry contains the cause of the failure and a stack trace pointing to the offending code. When you use the Log command, Spotlight continues executing your program -- if you log an error that can cause your app to crash, it will crash after the log entry's written.
  • Kill (cmd-K) stops your application. This is often the safest course when Spotlight catches your code writing trash in another process's space.
  • Display Memory and Display Variables show the Memory and Variables windows, which display what you'd expect them to. One nice touch is that Spotlight draws suspect memory addresses in the Memory window in gray, so you can easily spot them.
  • Reset Leaks resets the internal leak counters; you can use this to make Spotlight forget about leaked objects from a previous set of operations (for example, if you're testing leaks when opening documents.)
  • Dump Leaks saves the current leak report to a log file; in conjunction with Reset Leaks, you can easily get leak data for one particular command or action in your application.
  • Debugger (cmd-D) drops you into whatever low-level debugger you have installed. From Macsbug, the G command will return you to Spotlight.

When you're done running your application (either because you quit it or because you used Spotlight's Kill command), Spotlight balances its records of the memory and resource allocations and deallocations your application's made; it will then present a window showing you what it logged. See Figure 2 for an example log window.

Figure 2. The Spotlight log window.

The log file is written into the folder which contains the application and .xSYM file. The first time you run Spotlight on an application, the log file will be named "Spotlight Log"; subsequent logs in the same folder get a number at the end of the filename, so you can separate log files from different runs. In a welcome concession to editor religion, you can specify the type and creator used for log files so they will automatically open in your preferred editor.

Once you’ve reviewed the log file contents, you must quit Spotlight before you can run it again; there’s no way to re-run a program, whether or not it’s been relinked.

Working With Spotlight

For the most part, Spotlight is an extremely unobtrusive addition to the development process. You don’t have to link with any special libraries or make any changes to your source code (except as noted below.) You must run it in place of a source-level debugger (it might work with Jasik’s debugger, but I don’t have it and didn’t test it), so it’s not the best tool to use when you’re looking for control-flow or processing errors. I found that the most productive way for me to use Spotlight in my workflow was to run it after I was satisfied with the overall behavior and performance of my code; it serves as a last hurdle (along with Onyx’s QC Pro) that my code has to pass before it advances to QA.

You have some control over what Spotlight checks; the Options dialog, shown in Figure 3, allows you to turn each of the four primary test categories on or off. At present, there’s no way to turn individual tests on or off; for example, you can’t tell Spotlight to check allocations made with MacOS calls but to not check allocations made with malloc() or operator new.

Figure 3. Spotlight's Options dialog.

Because of the way Spotlight patches your application, you may have to make some minor changes to keep things running smoothly. The documentation warns that Spotlight will crash the machine when it catches an error in an interrupt handler routine unless you've bracketed the routine with calls to the SLEnterInterrupt() and SLLeaveInterrupt() routines. Spotlight also offers two routines to programmatically turn it on or off. You can use SLEnable() and SLDisable() to bracket code sections which trigger false alarms in Spotlight, or where performance is critical.

These interfaces are provided as C and Pascal header files, so you can call them from C, C++, Pascal, Object Pascal, or any other language which can import either type of declaration.

Documentation and Support

Spotlight is delivered electronically; unlike its sister product QC, there's no current way to get a physical copy of the product. Onyx will ship physical product free of charge to all purchasers of the DR releases once the final version ships. The distribution archive comes with a 6-page self-reading document. The bad news is that this document is very short and contains relatively little information on how to use Spotlight. The good news is that Spotlight is easy enough to use that the skimpy docs aren't a hindrance. Better still, Onyx promises a more substantial printed manual for the final release. Having said that, one item that I particularly missed was a list of which Toolbox routines Spotlight can do parameter checking on.

Onyx provides technical support to users via e-mail and fax; they also maintain WWW and FTP sites with updates and patches. Onyx has earned a reputation for excellent support of their QC product, including providing free patches and updaters on their web site. The questions and comments I sent in during my evaluation were promptly and courteously answered. One particularly nice touch that other vendors should emulate is Onyx's maintenance of a mailing list for upgrade and release announcements. Onyx also maintains an active presence on Usenet.

Many development tool vendors have moved away from irregularly scheduled point releases and to a subscription model. Onyx has adopted this approach for Spotlight. If you buy Spotlight now, you'll get whichever developer release is currently shipping. As of this writing, that would be DR1, but by the time this reaches print DR2 should be shipping instead. When Onyx releases DR3 and the final 1.0 version, anyone who purchased DR1 or DR2 will get them automatically.

Spotlight lists for US$199, but it's available for $149 to QC owners, or you can buy the two products together for $248. Because the physical version isn't shipping yet, it's only available directly from Onyx, although other distributors (notably DevDepot) will be selling the release version when available.

Spotlight Limitations

The DR1 release does have a few rough edges and limitations. Let's deal with the limitations first: most significantly, you can only use Spotlight on PowerPC applications. If you're writing code for the 68K, or writing code resources or shared libraries like Component Manager components or Photoshop plugins, Spotlight won't help you at present. Spotlight requires a .SYM-format symbol file, so your development environment must be able to generate one.

Spotlight doesn't integrate with the Metrowerks or Symantec debuggers, so you can either debug your code or Spotlight it at any one time. Onyx has promised better integration with MWDebug as their #1 future priority; the two companies did a very nice job of integrating Onyx's QC and MWDebug, so let's hope they follow through on this as well.

As might be expected with a DR1 product, the user interface is not as polished as a final release product; you can't cut or copy text from the log window, and the Close command doesn't close the log window. Some little touches would ease the daily process of using Spotlight. For example, it would be handy to open a source file in its creating application by double-clicking it in Spotlight's stack trace pane, and it would be useful to be able to attach a note in the log file when you use the Log command.

Is It Magic?

The first few times Spotlight flushed out camouflaged defects in my code, I couldn't do anything but smile. Every flaw that a tool like Spotlight finds is one flaw that my QA team, beta testers, and end users won't have to deal with. In that sense, it really is like magic.

The magic comes at a reasonable cost, too. You don't have to learn any arcane commands to use Spotlight, and the majority of applications won't require any changes to take advantage of its defect-finding abilities. Despite the fact that it can't debug anything but PowerPC applications, Spotlight is a valuable tool which I highly recommend. At US$199, it's a bargain compared to the amount of time you can waste hunting for bugs which can be Spotlighted in minutes.

Product Reviewed in this Article

Spotlight DR1, Onyx Technology. 7811 27th Avenue West, Bradenton, FL 34209. (941) 795-7801.

Useful URLs

http://www.onyx-tech.com - Home page for Onyx Technology.


Paul Robichaux must be the luckiest guy alive -- he gets paid to write Macintosh cryptography and security software by day and still manages to have free time to enjoy his family. He welcomes your comments via e-mail to paulr@hiwaay.net.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Jump into one of Volkswagen's most...
We spoke about PUBG Mobile yesterday and their Esports development, so it is a little early to revisit them, but we have to because this is just too amusing. Someone needs to tell Krafton that PUBG Mobile is a massive title because out of all the... | Read more »
PUBG Mobile will be releasing more ways...
The emergence of Esports is perhaps one of the best things to happen in gaming. It shows our little hobby can be a serious thing, gets more people intrigued, and allows players to use their skills to earn money. And on that last point, PUBG Mobile... | Read more »
Genshin Impact 5.1 launches October 9th...
If you played version 5.0 of Genshin Impact, you would probably be a bit bummed by the lack of a Pyro version of the Traveller. Well, annoyingly HoYo has stopped short of officially announcing them in 5.1 outside a possible sighting in livestream... | Read more »
A Phoenix from the Ashes – The TouchArca...
Hello! We are still in a transitional phase of moving the podcast entirely to our Patreon, but in the meantime the only way we can get the show’s feed pushed out to where it needs to go is to post it to the website. However, the wheels are in motion... | Read more »
Race with the power of the gods as KartR...
I have mentioned it before, somewhere in the aether, but I love mythology. Primarily Norse, but I will take whatever you have. Recently KartRider Rush+ took on the Arthurian legends, a great piece of British mythology, and now they have moved on... | Read more »
Tackle some terrifying bosses in a new g...
Blue Archive has recently released its latest update, packed with quite an arsenal of content. Named Rowdy and Cheery, you will take part in an all-new game mode, recruit two new students, and follow the team's adventures in Hyakkiyako. [Read... | Read more »
Embrace a peaceful life in Middle-Earth...
The Lord of the Rings series shows us what happens to enterprising Hobbits such as Frodo, Bilbo, Sam, Merry and Pippin if they don’t stay in their lane and decide to leave the Shire. It looks bloody dangerous, which is why September 23rd is an... | Read more »
Athena Crisis launches on all platforms...
Athena Crisis is a game I have been following during its development, and not just because of its brilliant marketing genius of letting you play a level on the webpage. Well for me, and I assume many of you, the wait is over as Athena Crisis has... | Read more »
Victrix Pro BFG Tekken 8 Rage Art Editio...
For our last full controller review on TouchArcade, I’ve been using the Victrix Pro BFG Tekken 8 Rage Art Edition for PC and PlayStation across my Steam Deck, PS5, and PS4 Pro for over a month now. | Read more »
Matchday Champions celebrates early acce...
Since colossally shooting themselves in the foot with a bazooka and fumbling their deal with EA Sports, FIFA is no doubt scrambling for other games to plaster its name on to cover the financial blackhole they made themselves. Enter Matchday, with... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra available today at Apple fo...
Apple has several Certified Refurbished Apple Watch Ultra models available in their online store for $589, or $210 off original MSRP. Each Watch includes Apple’s standard one-year warranty, a new... Read more
Amazon is offering coupons worth up to $109 o...
Amazon is offering clippable coupons worth up to $109 off MSRP on certain Silver and Blue M3-powered 24″ iMacs, each including free shipping. With the coupons, these iMacs are $150-$200 off Apple’s... Read more
Amazon is offering coupons to take up to $50...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for up to $110 off MSRP, each including free delivery. Prices are valid after free coupons available on each mini’s product page, detailed... Read more
Use your Education discount to take up to $10...
Need a new Apple iPad? If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $100 off the... Read more
Apple has 15-inch M2 MacBook Airs available f...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more
Mac Studio with M2 Max CPU on sale for $1749,...
B&H Photo has the standard-configuration Mac Studio model with Apple’s M2 Max CPU in stock today and on sale for $250 off MSRP, now $1749 (12-Core CPU and 32GB RAM/512GB SSD). B&H offers... Read more
Save up to $260 on a 15-inch M3 MacBook Pro w...
Apple has Certified Refurbished 15″ M3 MacBook Airs in stock today starting at only $1099 and ranging up to $260 off MSRP. These are the cheapest M3-powered 15″ MacBook Airs for sale today at Apple.... Read more
Apple has 16-inch M3 Pro MacBook Pro in stock...
Apple has a full line of 16″ M3 Pro MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $440 off MSRP. Each model features a new outer case, shipping is free, and an... Read more
Apple M2 Mac minis on sale for $120-$200 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $110-$200 off MSRP this weekend, each including free delivery: – Mac mini M2/256GB SSD: $469, save $130 – Mac mini M2/512GB SSD: $689.... Read more
Clearance 9th-generation iPads are in stock t...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on clearance sale for starting at only $199 on their online store for a limited time. Sale prices for online orders only, in-store prices may vary... Read more

Jobs Board

Senior Mobile Engineer-Android/ *Apple* - Ge...
…Trust/Other Required:** NACI (T1) **Job Family:** Systems Engineering **Skills:** Apple Devices,Device Management,Mobile Device Management (MDM) **Experience:** 10 + Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Full Time (80 hrs/pay period) Evenings General Summary Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.