##CONTINUE##
Recently I've come across some interesting bugs in C-family programs. In this article, I'll share a few of these experiences. As with most debugging problems, the second time you see the issue it's obvious, so hopefully this will save at least one reader from spending a few days chasing down a problem.
The C family is generally regarded as being low-level, and therefore exposes a lot of detail about the implementation to the programmer. If you've never worked on a C compiler, a lot of these details might be slightly surprising to you.
Schrödinger's Variable
For some reason, I've come across this problem a lot recently. I hadn't paid particular attention to it, probably because it had gone away after doing a clean build. This particular instance was on someone else's system, however, and remote debugging meant that I wanted to fully understand the issue.
The code in this case was Objective-C, although you can see something similar in most C-like languages. A simplified version of the problem looks something like this:
static MapTable *table = NULL;In Objective-C, the +initialize method has special significance—it's automatically called (in a thread-safe way) before the first message is sent to a class. This setup allows lazy initialization of variables referenced in a compilation unit, and is one of the main reasons why Objective-C programs start a lot faster than their C++ counterparts.
void doInitialisation()
{
...
MapInsert(table, key, value);
}
...
@implementation AClass
+ (void) initialize
{
table = createMapTable();
...
doInitialisation();
}
...
@end
The issue in this case was that the function was crashing because table was NULL. In the stack trace, it was clear that the function was called from the method. Looking further up the stack trace, you could see the table variable was a pointer to something in memory. Stepping back down the stack trace, it suddenly became NULL again.
What was the problem? It turned out to be the first word in the snippet I've shown here: static. What does static mean in a C program? To the programmer, it means that the variable is visible only in this file. To the compiler, it means almost the same thing. To the linker, however, it means something different. The linker (on UNIX-like systems, at least) has no notion of visibility. A variable that's static to the programmer is "renaming" to the linker. Rather than restricting access to it, the linker simply renames the variable if there's a conflict.
Linker renaming was exactly the problem in this case. Running ldd showed that the program was linked against two copies of the library containing this module. In most cases, this conflict would just cause one copy of the variable to be invisible. In this case, however, the renaming caused a problem due to the interference between two loaders.
In Objective-C, there are two ways of resolving a symbol to a function. The first option is via the C linker. At load time, the linker resolves all function names to pointers to functions. The second approach is via the Objective-C runtime library. The runtime library resolves method names to methods when they are caused. Due to implementation differences, one reference to the variable used the first mapping it came across, while the other used the second mapping. Again, normally this mismatch wouldn't be a problem. In this case, however, the duplication meant that the method was seeing the function (which wasn't static) in the other copy of the module. Since the variable was static, it was renamed when the second version of the module was loaded. This meant that the method was setting its local copy of the variable and then calling the function, which saw its own copy of the variable, which was still NULL.
So, what's the correct solution? There are several things wrong with this particular code. The first is that the function was not written defensively, and therefore was not checking that the variable was not NULL before doing something that would fail if it were NULL. A test could have initialized the variable. (Although in this case it would have actually made things worse—there would have been two valid but independent versions of the variable.) This omission is understandable, however, since the function was called from only one place, so the variable could never be NULL.
Or was it? The second thing that's wrong with this code is that the function, which was meant to be called only inside this module, wasn't static. Because it wasn't static, it could have been called from any other code in the program. Since it was in a library, it could have been called accidentally from anywhere if other programmers had picked the same name for one of their functions. (This is a huge problem with many current languages, and largely ignored. Modeling it is a subject for some of my current research.) If the function had been static, the method would have called its private copy, and the function would have seen the same copy of the variable as the method did.
Of course, the real bug is the loader, which should have thrown an error as soon as two modules containing different symbols with the same name in the same scope were loaded. This problem is well known, but no one seems keen to fix it.
Empty Empty Strings
I came across another C-language issue in some C++ code, when I encountered a strange bug in my Smalltalk compiler. A number of people were complaining that a program would compile when it contained an unreferenced constant string, but when you removed this string the program would crash.
I wasn't able to reproduce this bug, but I did find one in which assignments to variables as the result of arithmetic were sometimes becoming NULL rather than the correct result. Before explaining this issue, I need to sidetrack a little and talk about how arithmetic works in Smalltalk. Since Smalltalk is a pure object-oriented language, everything is an object, including integers. This is fudged slightly, however. Objects are structures containing a pointer to their class and any local state. Allocating a real object and going via the dynamic dispatch mechanism for integer arithmetic would take up a lot of space and be very slow, so there's a means of short-circuiting it. Since objects must be aligned on at least word boundaries, the lowest bit is always 0 in any object pointer. Setting this bit to 1 indicates that the object is a SmallInt—a special kind of object that stores its state in the other 31 or 63 bits.
When you send a + message to a SmallInt, a special lookup mechanism is used. In my implementation, SmallInt methods are implemented as C functions in an Objective-C file, which is compiled to LLVM bitcode with clang and then linked to the Smalltalk code. The LLVM inliner can then inline the implementations.
The issue, I discovered, was in cases where the arithmetic overflowed. In Smalltalk, arithmetic overflow is meant to result in a BigInt, a real object containing an arbitrary-precision integer, and this is exactly what I had implemented. My BigInt object was implemented in Objective-C and constructed in the SmallInt method by sending a message to the BigInt class.
I discovered that the constructor was not being called. I added a debugging line that called printf(), and I got a different result. Now it worked correctly. I added a static variable to which I assigned an intermediate value. This arrangement worked the first time, and then failed.
By this stage, I was quite confused. I added a breakpoint in the Objective-C runtime function for resolving the class name to a class pointer, and discovered that it was being called with "BigInt\129\205..." as the argument, not "BigInt", as I expected.
At this point, a light went on in my head, and I checked the bitcode that clang was generating. Sure enough, the "BigInt" string literal was missing the NULL terminator. Still a compiler bug, but since I also wrote the Objective-C code-generation stuff for the GNU runtime in clang, this one was still my fault.
Only it wasn't. Looking at the code, I saw that it was calling the correct function for emitting a NULL-terminated string. I went to the definition of this function, and here it is:
llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
const char *GlobalName){
return GetAddrOfConstantString(str + "\0", GlobalName);
GetAddrOfConstantString() emits a constant array of bytes, whereas GetAddrOfConstantCString() emits a constant C string—an array of bytes with a NULL terminator. At first glance, it takes a string argument, ensures that it's NULL-terminated, and then emits it as an array of bytes.
This is where I realized why I hate the C++ type system. A good type system reduces the number of valid-but-incorrect programs. In my experience, the C++ type system rejects programs that are correct and completely fails to spot most real errors.
Understanding this error requires you to understand that there are two kinds of string in C++. The first is C strings, which are NULL-terminated arrays of bytes. The second is C++ std::string objects. These are like Pascal strings—an array of bytes and a length—with some operations defined on them. Most of the time, you can pass a C string to something that expects a C++ string, and the compiler will do the correct conversion for you. This allows you to use the double-quote notation for constructing std::string objects—it's not really what you're doing, but you can pretend that it is.
In this case, the distinction is important. "\0" is a C string, being passed to the + operator method on a C++ string. What is "\0" really? It's a two-byte array, where both bytes are NULL. And what is a C string? It's a variable-sized array of bytes from some pointer to the first NULL byte. And herein lies the problem: The string literals "" and "\0" are semantically equivalent when treated as C strings.
This function was appending the empty string to the C++ string and then emitting the result. Appending the empty string is a no-op, so GetAddrOfConstantCString() did exactly the same thing as GetAddrOfConstantString().
Sometimes the string literals would be followed by a variable that happened to be 0. Sometimes they would be followed by nothing, so reading along the string would cause a crash. Sometimes they'd be followed by another string, or something else followed by a 0 byte, so they would just contain the wrong value.
Once this bug was identified, it was easy to fix. Replace the double quotes with single quotes, so you get this:
return GetAddrOfConstantString(str + '\0', GlobalName);This now appends the 0 character to the string, which is what the original author wanted. Again, this was something that could have been prevented by a more defensive programming style. Style guidelines could have said that single-character strings should not be used. Operator overloading in C++ lets you implement methods that do the same thing on a single character as on a single-character string, and a character literal is always what you mean it to be, while a C string might not be.
More importantly, there's no good reason for emitting array constants that aren't NULL-terminated. If you add a NULL to the end of something that doesn't check beyond a fixed length, you just waste one byte of space in your data segment. If you write the extra byte, you can treat the array as NULL-terminated. The result? For a very low space cost, you get a result that doesn't fail for valid code and doesn't fail for some categories of invalid code.
Technically speaking, doing the right thing on incorrect input is a bug, but it's the kind of bug no one ever complains about, and this is a good rule for avoiding bugs. The general rule is to be strict in what you send and relaxed in what you receive. (Always generate data that's easy to use to do the right thing, but don't expect anyone else to follow that principle.)
Coding ConventionsI mentioned coding conventions only briefly, but their importance can't be stressed enough. The idea behind good coding conventions is to make correct code and incorrect code look different at a glance. Common examples include writing (NULL == variable) instead of (variable == NULL) in comparisons. These two look a lot more different from each other than (variable = NULL) looks from either.
I mentioned coding conventions only briefly, but their importance can't be stressed enough. The idea behind good coding conventions is to make correct code and incorrect code look different at a glance. Common examples include writing (NULL == variable) instead of (variable == NULL) in comparisons. These two look a lot more different from each other than (variable = NULL) looks from either.
Indenting is another issue. Some coding conventions require braces to be on separate lines, which makes it easy to tell the difference between beginning a block and run-on lines. Conventions that require if statements to be followed by a new block do so to avoid the dangling else problem.
One of the most misunderstood conventions is Hungarian notation. Joel Spolsky explained how this notation should be used—to encode type information that your type system can't encode, not to redundantly duplicate information that it can encode. Using different prefixes for column and row indexes, for example, means that you can easily tell when you have accidentally switched your coordinate orientation. Having different prefixes for feet and meters means that you can easily see which line will cause you to crash into Mars.
Good coding conventions don't eliminate bugs, but they do make certain categories more obvious, which leaves you with more time to spend looking for the really hard bugs.
-----------------------------BY David Chisnall
Source:inform IT
Article is provided courtesy of Prentice Hall
© 2009 Pearson Education, Informit. All rights reserved.
0 comments:
Post a Comment