








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









We present Memcheck, a tool that has been implemented with the dynamic binary instrumentation framework Val- grind. Memcheck detects a wide range of memory errors in programs as they run. This paper focuses on one kind of error that Memcheck detects: undefined value errors. Such errors are common, and often cause bugs that are hard to find in programs written in languages such as C, C++ and Fortran. Memcheck’s definedness checking im- proves on that of previous tools by being accurate to the level of individual bits. This accuracy gives Memcheck a low false positive and false negative rate. The definedness checking involves shadowing every bit of data in registers and memory with a second bit that indicates if the bit has a defined value. Every value- creating operation is instrumented with a shadow oper- ation that propagates shadow bits appropriately. Mem- check uses these shadow bits to detect uses of undefined values that could adversely affect a program’s behaviour. Under Memcheck, programs typically run 20– times slower than normal. This is fast enough to use with large programs. Memcheck finds many errors in real pro- grams, and has been used during the past two years by thousands of programmers on a wide range of systems, including OpenOffice, Mozilla, Opera, KDE, GNOME, MySQL, Perl, Samba, The GIMP, and Unreal Tourna- ment.
The accidental use of undefined values is a notorious source of bugs in programs written in imperative lan- guages such as C, C++ and Fortran. Such undefined value errors are easy to make, but can be extremely diffi- cult to track down manually, sometimes lurking unfound for years. In this paper we describe Memcheck, a practical tool which detects a wide range of memory errors, including undefined value errors. Memcheck is implemented using the dynamic binary instrumentation framework Valgrind [10, 9].
Memcheck is a dynamic analysis tool, and so checks pro- grams for errors as they run. Memcheck performs four kinds of memory error checking. First, it tracks the addressability of every byte of mem- ory, updating the information as memory is allocated and freed. With this information, it can detect all accesses to unaddressable memory. Second, it tracks all heap blocks allocated with malloc(), new and new[]. With this information it can detect bad or repeated frees of heap blocks, and can detect memory leaks at program termination. Third, it checks that memory blocks supplied as argu- ments to functions like strcpy() and memcpy() do not overlap. This does not require any additional state to be tracked. Fourth, it performs definedness checking : it tracks the definedness of every bit of data in registers and memory. With this information it can detect undefined value errors with bit-precision. All four kinds of checking are useful. However, of the four, definedness checking is easily the most sophis- ticated, and it is this checking that this paper focuses on. Memcheck uses dynamic binary instrumentation to in- strument the program to be checked (the client ) on-the- fly at run-time. Execution of the added instrumentation code is interleaved with the program’s normal execution, not disturbing normal program behaviour (other than slowing it down), but doing extra work “on the side” to detect memory errors. Because it instruments and analy- ses executable machine code, rather than source code or object code, it has the following nice properties.
USENIX Association 2005 USENIX Annual Technical Conference 17
int main(void) { int x, y, z, *p; char buf[10]; write(1, buf, 1); // bug 1 x = ( x == 0? y : z ); // bug 2 return *p + x; // bug 3 } Figure 1: Example program badprog.c
source code is not available on the system. In- deed, it is only by doing this that Memcheck can be accurate—partial coverage leads either to lots of missed errors (false negatives) or lots of invalid er- rors (false positives).
Memcheck is part of the Valgrind suite, which is free (GPL) software, and is available for download from the Valgrind website [14]. It currently runs only on the x86/Linux platform, although work is currently under- way to port it to other platforms such as AMD64/Linux, PowerPC/Linux, x86/FreeBSD, and PowerPC/MacOSX.
Memcheck is easy to use. As an example, consider the (contrived) program badprog.c in Figure 1. It con- tains three undefined value errors. To check the compiled program badprog the user only has to type: valgrind --tool=memcheck badprog The --tool= option specifies which tool in the Val- grind suite is used. The program runs under Mem- check’s control, typically 20–30 times slower than usual. This slow-down is partly due to Memcheck’s definedness checking, partly due to its other checking, and partly due to Valgrind’s inherent overhead. The program’s output is augmented by Memcheck’s output, which goes by de- fault to standard error, although it can be redirected to a file, file descriptor, or socket with a command line op- tion. Figure 2 shows the resulting output. The first three lines are printed by Memcheck on startup. The middle section shows three error messages issued by Memcheck. The final three lines are printed at termination, and sum- marise Memcheck’s findings. Each line of Memcheck’s output is prefixed with the client’s process ID, 27607 in this case. The three error messages are quite precise. The first indicates that the memory passed to the system call write() via the buf argument contains undefined val- ues; its last line indicates that the undefined value is on
void set_bit ( int* arr, int n ) { arr[n/32] |= (1 << (n%32)); } int get_bit ( int* arr, int n ) { return 1 & (arr[n/32] >> (n%32)); } int main ( void ) { int* arr = malloc(10 * sizeof(int)); set_bit(arr, 177); printf("%d\n", get_bit(arr, 178)); return 0; } Figure 3: Unsafe use of a bit-array
the stack of thread 1 (the main thread). The second in- dicates that a conditional jump depends on an undefined value. The third indicates that an undefined value is used as a pointer. All three error messages include a stack trace that indicate precisely where the error is occurring. In order to get exact line numbers in the stack traces, the client must be compiled with debugging information. If this is missing, the code locations are less precise, as can be seen with the location within the write() function (not to be confused with the write() system call)— GNU libc on this system was not compiled with debug- ging information. Attentive readers may note that the final line of badprog.c could cause a segmentation fault due to the use of the uninitialised variable p as an address. On one system we tried this test on, exactly that happened, and so Memcheck issued an additional “Invalid read of size 4” warning immediately before the memory access, thanks to its addressability checking. For the run presented, the memory access (un)luckily hit addressable memory, so no addressability error message was issued.
Memcheck is the first tool we are aware of that tracks definedness down to the level of bits. Other tools track definedness at byte granularity (Purify) or word granu- larity (Third Degree). This means Memcheck correctly handles code which deals with partially-defined bytes. In C and C++, two common idioms give rise to such bytes: use of bit arrays and use of bitfields in structures. Tools which track de- finedness at byte or word granularities necessarily give inaccurate results in such situations – either they fail to report genuine errors resulting from uses of uninitialised bits, or they falsely flag errors resulting from correct uses of partially defined bytes. The program shown in Figure 3 uses an uninitialised bit in a bit-array. Memcheck reports this, but Purify does not^2. Memcheck is known to have found previously-
18 2005 USENIX Annual Technical Conference^ USENIX Association
by a piece of metadata, called a definedness bit. For historical reasons these are often also referred to as V bits (V being short for “validity”). Each V bit indicates whether or not the bit b it shadows is re- garded as currently having a properly defined value.
From this overview, the main overheads of definedness checking are apparent. First, the use of V bits doubles the amount of memory in use. Second, most instructions compute new values, and thus require a shadow opera- tion itself consisting of one or more instructions.
A V bit of zero indicates that the corresponding data bit has a properly defined value, and a V bit of one indicates that it does not. This is counterintuitive, but makes some of the shadow operations more efficient than they would be if the bit values were inverted. Every 32-bit general purpose register is shadowed by a 32-bit shadow register, and every byte of memory has a shadow V byte. After that, there are some exceptions to the basic rule of “one V bit per data bit”.
6 condition codes individually is expensive and mostly unnecessary.
In principle it is possible to directly state the V bit trans- formations required to shadow each x86 instruction. In practice, the x86 instruction set is so complex and irreg- ular that this would be difficult and fragile. Fortunately, UCode (Valgrind’s intermediate representation) is RISC- like and clearly exposes all memory and arithmetic oper- ations, which makes Memcheck’s instrumentation task much easier. Another important aspect of UCode is that it supports the use of an infinite supply of virtual registers. The ini- tial translation from x86 is expressed in terms of such registers. Memcheck interleaves its own instrumentation UCode with it, using as many new virtual registers as required. Valgrind’s core has the job of performing in- struction selection and register allocation to convert this sequence back to executable x86 code.
The V bit instrumentation scheme is best described in terms of a family of simple abstract operations on V bits. We will use d1 and d2 to denote virtual registers holding real values, and v1 and v2 denote virtual shadow regis- ters holding V bits. Also, some operations below use X and Y indicate the operand and result widths in bytes (and 0 represents an operand with a width of a single bit). Those operations for which the width is not specified are width-independent. Memcheck uses the following binary operations.
20 2005 USENIX Annual Technical Conference^ USENIX Association
Each bit of the result indicates definedness if ei- ther corresponding operand bit indicates defined- ness. Since our encoding is zero for defined and one for undefined, DifD can be implemented using a bitwise-AND operation.
ImproveAND(0, undefined) = undefined ImproveAND(0, defined) = defined ImproveAND(1, undefined) = undefined ImproveAND(1, defined) = undefined
The second case is the interesting one. If one of the arguments is a defined zero bit, we don’t care that the other argument might be undefined, since the re- sult will be zero anyway. Hence ImproveAND cre- ates a “defined” V-bit, which, as described in Sec- tion 2.6, is merged into the final result for AND us- ing DifD. This has the effect of forcing that bit of the result to be regarded as defined. “undefined” is the identity value for DifD, so the other three cases have no effect on the final outcome. For exactly analogous reasons, ImproveOR be- haves similarly, with the interesting case being ImproveOR(1, defined) = defined.
The following unary operations are also needed.
else it produces a value with all bits one (unde- fined). For example, PCast12(00010100) = 1111111111111111 , and PCast12(00000000) =
These casts are used in various approximations in which the definedness checking needs to consider the worst-case across a whole word of bits. It is im- portant to appreciate that the narrowing casts (where X > Y) do not simply discard the high bits of the operand. Similarly, the case where X = Y is not the identity function. In all cases, each result bit de- pends on all operand bits, regardless of their relative sizes. PCast can be implemented in at most three x86 instructions: for narrowing casts, negation fol- lowed by subtract-with-borrow; for widening casts, a shift, a negation, and a subtract-with-borrow.
Every operation (instruction or system call) that creates a value must be instrumented with a shadow operation that computes the corresponding V bits. This section de- scribes these shadow operations in detail. Recall that for each virtual register d1, d2... in the incoming UCode, Memcheck allocates a shadow virtual register v1, v2... to carry the corresponding V bits.
Register and memory initialisation At startup, all registers have their V bits set to one, i.e. undefined. The exception is the stack pointer, which has its V bits set to zero, i.e. defined. All memory bytes mapped at startup (i.e. code and data segments, and any shared objects) have their V bits set to zero (defined).
USENIX Association 2005 USENIX Annual Technical Conference 21
v3 = UifU( PCastYX(v2), OP(v1,d2) )
In all five cases, the definedness bits are processed us- ing the same operation as the original. For Rol and Ror, the definedness bits must be rotated exactly as the data bits are. Shl and Shr shift zeroes into the data, and so corresponding zeroes—indicating definedness—need to be shifted into the definedness word. Sar copies the top bit of the data, and so needs to also copy the top bit of the definedness word.
Widening and narrowing conversions A narrowing conversion on data throws away some of the top bits of the word, and so the same operation can be used to throw away the top bits of the shadow word. Signed and unsigned widening conversions give rise respectively to a single SWiden or ZWiden operation.
Instructions which set flags On x86, most integer arithmetic instructions set the condition codes (%eflags) and Memcheck duly tracks the definedness state of %eflags using a single shadow bit. When an integer op- eration sets condition codes, it is first instrumented as described above. Memcheck pessimistically narrows the result value(s) of the shadow operation using PCastX to derive a value for the %eflags shadow bit.
Loads, stores, conditional branches and conditional moves These are discussed in the next section.
Floating point (FP) and MMX, SSE, SSE2 (SIMD) operations Valgrind does not disassemble floating point or SIMD instructions to the same level of detail as it does integer instructions. Instead, it merely modi- fies some of the register fields in the instruction, marks any instructions referencing memory as such, and copies them otherwise unchanged into the output instruction stream. Because of this, Memcheck can only offer crude in- strumentation of such instructions. Such instrumenta- tion is safe in the sense that all uses of undefined values, and all illegitimate memory accesses, will still be caught. The crudeness of the instrumentation has the effect that some computations, when done with FP or SIMD reg- isters, may elicit false-positive undefined value errors, when similar or identical operations done using integer registers would not. The most notable case is that copy- ing undefined data through the FP or SIMD registers will elicit false positives. The instrumentation scheme is as follows. Neither the FP nor SIMD registers have any associated V bits. When a value is loaded from memory into such a register, if any part of the value is undefined, an error message is issued. When a value is written from such a register to memory,
shadow memory is marked as defined. This is in keeping with the Eager approximation scheme described shortly. So far, this crude scheme has proven adequate, mostly because programmers and compilers rarely copy and ma- nipulate partially-undefined data through FP or SIMD registers. However, vectorising compilers for SIMD architectures are becoming increasingly common [8], and this scheme cannot continue much longer—it is the biggest weakness of Memcheck. A new version of Mem- check under development will shadow data in floating point registers and in individual lanes of SIMD registers, thus remedying this deficiency.
Approximating everything else The above cases give sufficient accuracy to achieve a near-zero false positive rate on almost all compiler-generated and handwritten code. There are a multitude of other cases which could be tracked accurately, but for which there appears to be no point. These include: division, rotates through the carry flag, and calls to helper functions which implement ob- scure features (CPUID, RDTSC, BCD arithmetic, etc). In such situations, two approximation schemes are possible.
Memcheck currently uses Eager for all floating point and SIMD operations, as decribed above, and Lazy in all other situations.
At every point where an undefined value could be con- sumed by an operation, Memcheck has a choice: should
USENIX Association 2005 USENIX Annual Technical Conference 23
it report the error right now, or should it silently propa- gate the undefinedness into the result? Both approaches have advantages.
Memcheck mostly takes the second alternative, defer- ring error reporting as far as it can. Checks for undefined values are made only when the program is in immediate danger of performing one of the following actions, which could change its observable behaviour.
Accordingly, instrumentation for such events is as fol- lows.
Conditional moves could be handled using either the eager or lazy scheme. Memcheck handles them eagerly, testing the condition code and reporting any error imme- diately. Each error check consists of testing a shadow virtual register^4 against zero for any undefinedness, and calling a helper function to issue an error message if so. An important but non-obvious extra step is that, immedi- ately following the test, the shadow register should be set to zero (“all defined”). Doing so prevents subsequent checks on it issuing essentially duplicate errors, which would confuse users. Consider the following C frag- ment:
int* p; /* not defined */ ... = *p; *p = ...
For the load, p’s shadow is tested, and an error message is issued if necessary. Subsequently in the store, report- ing another such error for p would not help lead users to the root cause of the problem.
Loads from invalid addresses One interesting ques- tion is how to handle loads from memory which Mem- check regards as not validly addressable. Our solution is counterintuitive: data loaded from unaddressable mem- ory is marked as defined. This helps reduce error cascades. A load from an in- valid address will in any case cause Memcheck to issue an invalid-address error message. If the loaded data was marked as undefined, Memcheck might, as a result, later issue undefined value error messages. These would con- fuse users and obscure the true cause of the error—the in- valid address. Marking the loaded data as defined avoids that problem.
Memcheck has a very low false positive rate. However, a few hand-coded assembly sequences, and a few very rare compiler-generated idioms can cause false positives. The few examples we know of are as follows.
24 2005 USENIX Annual Technical Conference^ USENIX Association
would be equivalent to solving the Halting Problem. Our design attempts to almost completely avoid false nega- tives and to minimise false positives. Experience in prac- tice shows this to be mostly successful. Even so, user feedback over the past two years reveals an interesting fact: many users have an (often unstated) expectation that Memcheck should not report any false positives at all, no matter how strange the code being checked is. We believe this to be unrealistic. A better expectation is to accept that false positives are rare but inevitable. Therefore it will occasionally necessary to add dummy initialisations to code to make Memcheck be quiet. This may lead to code which is slightly more conservative than it strictly needs to be, but at least it gives a stronger assurance that it really doesn’t make use of any undefined values. A worthy aim is to achieve Memcheck-cleanness, so that new errors are immediately apparent. This is no dif- ferent from fixing source code to remove all compiler warnings, even ones which are obviously harmless. Many large programs now do run Memcheck-clean, or very nearly so. In the authors’ personal experi- ence, recent Mozilla releases come close to that, as do cleaned-up versions of the OpenOffice.org-680 develop- ment branch, and much of the KDE desktop environ- ment. So this is an achievable goal. Finally, we would observe that the most effective use of Memcheck comes not only from ad-hoc debugging, but also when routinely used on applications running their automatic regression test suites. Such suites tend to exercise dark corners of implementations, thereby in- creasing their Memcheck-tested code coverage.
For a tool such as Memcheck to be worth using, a user must first be using a language such as C, C++ or Fortran that is susceptible to the kinds of memory errors Mem- check finds. Then, the benefits of use must outweigh the costs. This section considers first the costs of using Memcheck, in terms of its ease of use and performance. It then considers the benefits, that is, its effectiveness in helping programmers find real bugs. As part of this, we refer to a survey of Valgrind users that we conducted in November 2003, to which 116 responses were received. The results are available on the Valgrind website [14]. Memcheck’s operation has changed very little in the time since, so the responses about it are still relevant.
Ease of use has a number of facets: how easy Memcheck is to obtain, how easy it is to run, and how easy it is to
act upon its results.
Obtaining Memcheck Memcheck is very easy to ob- tain, because the Valgrind suite is free software, is avail- able in source form on the Valgrind website [14], and is widely available in binary form on the web, packaged for a number of Linux distributions.
Running Memcheck Memcheck could hardly be eas- ier to run. Using it only requires prefixing a program’s command line with valgrind --tool=memcheck, plus any other desired Valgrind or Memcheck options. Typically, the only further effort a user must make is to compile her program with debugging information, to ensure error messages are as informative as possible. Indeed, 40 of the 116 survey responders praised Val- grind/Memcheck’s ease of running, and another another 14 commented that “it just works”, or similar. Only one responder complained that it could be easier to use.
Custom allocators There are some cases where the user needs to expend a little more effort. If a pro- gram uses custom memory management rather than malloc(), new and new[], Memcheck can miss some errors it would otherwise find. The problem can be avoided by embedding small number of client re- quests into the code. These are special assembly code sequences, encoded as C macros for easy use, that Val- grind recognises, but which perform a cheap no-op if the client is not running on Valgrind. They provide a way for the client to pass information to a Valgrind tool. For example, when using a custom allocator, client requests can be used to inform Memcheck when a heap block has been allocated or deallocated, its size and location, etc.
Self-modifying code Extra effort is also needed to han- dle self-modifying code. Dynamically generated code is not a problem, but if code that has executed is modified and re-executed, Valgrind will not realise this, and will re-run its out-of-date translations. Auto-detecting this is possible but expensive [7]; the cost is not justified by the small number of programs that use self-modifying code. Our compromise solution is to provide another client re- quest which tells Valgrind to discard any cached transla- tions of code in a specified address range.
Different behaviour under Memcheck Client pro- grams sometimes do not behave exactly the same under Valgrind/Memcheck as they do normally. Programs that run successfully normally may fail under Memcheck. This is usually because of latent bugs that are exposed e.g. by different execution timings, or because Valgrind provides its own implementation of the Pthreads library.
26 2005 USENIX Annual Technical Conference^ USENIX Association
This can be regarded as a good thing. More rarely, pro- grams that fail normally may succeed under Memcheck for the same reasons, which can be frustrating for users who hoped to track down a bug with Memcheck. Although Valgrind/Memcheck is robust—we have had feedback from users using it on systems with 25 million lines of code —it occasionally fails due to its own bugs. The main source of problems is that Valgrind interacts closely with the kernel and GNU libc. In particular the signal and thread handling is fragile and hard to get right for all Linux distributions, and a maintenance headache. By comparison, the parts dealing with x86 code and in- strumentation cause few problems, because instruction sets change very slowly. We hope to decrease our level of interaction with the kernel and GNU libc in the fu- ture, and recent development efforts have made major progress in that area.
Acting upon Memcheck’s results In general, Mem- check’s addressability checking, deallocation checking, and overlap checking do quite well here, in that Mem- check’s report of the problem is usually close to the root cause. However, for definedness checking this is often not the case, as Section 2.7 explained. To help on this front, Memcheck provides another client request that can be inserted into the client’s source code. It instructs Memcheck to check if a particular vari- able or memory address range is defined, issuing an error message if not. Judicious uses of this client request can make identifying root causes of undefined value errors much easier. Ideally, error messages would indicate where the un- defined value originated from, e.g. from a heap block whose contents have not been initialised. However, this would require augmenting each value with extra infor- mation about where it came from, and we cannot see how to do this without incurring prohibitive overheads. Ease of interpreting error messages is also important. Ten survey responders complained that the messages are confusing, but 7 praised them. One issue in particular is the depth of stack traces: the default is four, but many users immediately adjust that to a much higher number. This gives more information, but also makes the error messages longer. This is a case where a GUI (requested by 8 responders) would be useful, in that large stack traces could be gathered, shown to a small depth by de- fault, and then “unfolded” by the user if necessary. Some users also simply prefer graphical tools over text-based ones. As it happens, there are several GUI front-ends for Valgrind, including Alleyoop [17] and Valgui [2].
Program t (s) Mem. Addr. Nul. bzip2 10.8 13.8 10.2 2. crafty 3.5 45.3 27.4 7. gap 1.0 26.5 19.2 5. gcc 1.5 35.5 23.7 9. gzip 1.8 22.7 17.7 4. mcf 0.4 14.0 7.1 2. parser 3.6 18.4 13.5 4. twolf 0.2 30.1 20.5 6. vortex 6.4 47.9 36.5 8. ammp 19.1 24.7 23.3 2. art 28.6 13.0 10.9 5. equake 2.1 31.1 28.8 5. mesa 2.3 43.1 35.9 5. median 26.5 20.5 5. geo. mean 25.7 19.0 4.
Table 1: Slow-down factors of Memcheck, Addrcheck and Nulgrind (smaller is better)
This section discusses the performance of three Valgrind tools. Besides Memcheck, it considers two other tools: Addrcheck, and Nulgrind. Addrcheck is a cut-down ver- sion of Memcheck that does not perform definedness checking. The performance difference between Mem- check and Addrcheck give an indication of the cost of Memcheck’s definedness checking. Nulgrind is the “null” Valgrind tool that adds no instrumentation. It gives an idea of the overhead due to Valgrind’s basic op- eration. All measurements were performed using Valgrind 2.1.2 on an 1400 MHz AMD Athlon with 1GB of RAM, running Red Hat Linux 9, kernel version 2.4.20. The test programs are a subset of the SPEC CPU2000 suite [16]. All were tested with the “test” (smallest) inputs. The time measured was the “real” time, as reported by /usr/bin/time. Each program was run once nor- mally, and once under each of the Valgrind tools. This is not a very rigorous approach but that does not matter, as the figures here are only intended to give a broad idea of performance. Table 1 shows the time performance of the three tools. Column 1 gives the benchmark name, column 2 gives its normal running time in seconds, and columns 3– give the slow-down factor for each tool relative to col- umn 2 (smaller is better). The first nine programs are integer programs, the remaining four are floating point programs. The bottom two rows give the median and ge- ometric mean for the slow-down factors. The slow-down figures for Memcheck are quite high. This is partly due to the cost of definedness checking,
USENIX Association 2005 USENIX Annual Technical Conference 27
Ref. no. Error type #problems #files 1 not initialized instance data member ca. 76 10 2 not initialized local variables 7 5 3 not initialized variable used as in/out parameter in method call 11 3 4 overlapping buffers in strncpy() 1 1 5 off by one error 1 1 6 unchecked return value of system call 1 1 7 partly initialized struct used in inappropriate ways 1 1 8 no check for potentially invalidated index 1 1 9 use of buffer size instead of content size for writing out data 1 1 10 write not initialized buffer into stream 1 1 11 feed unterminated buffer into method expecting a C-style string 1 1
Table 2: Errors found by Memcheck in OpenOffice
Huang [4] described, very early, the possibility of us- ing dynamic analysis to detect variables that are written but never read, and reads of undefined variables. How- ever, the proposed instrumentation was at the source code level rather than the machine code level. Kempton and Wichmann [5] discussed the detection of undefined value errors in Pascal programs. They suggest using one shadow definedness bit per data bit in memory, just as Memcheck does. They did not discuss how the shadow bits would be propagated. Purify [3] is a widely used commercial memory check- ing tool that can detect several kinds of memory errors including undefined value errors. It adds instrumentation to object code at link-time, in order to do checking at run-time. It shadows every byte of memory with a two- bit value that encodes one of three states: unaddressable, writable, and readable. Reads of writable (i.e. allocated but undefined) memory bytes may get flagged immedi- ately as errors. This is a form of eager checking, as men- tioned in Section 2.6. Because the shadowing is at the byte-level, it does not feature bit precision. Third Degree [18] is a memory checking tool built us- ing the ATOM object code instrumentation framework [15]. As well as detecting some accesses to unaddress- able memory, it uses a crude form of definedness check- ing: when a stack or heap location first becomes address- able, it is written with a special “canary” value. An error is issued if any loads read this canary value. This could lead to false positives when undefined values are copied around, and there is a small chance that the canary value might occur legitimately, although the value is chosen carefully to minimise this likelihood. As Third Degree only ran on Alphas, it is unfortunately now defunct. Insure++ [12] is a commercial memory checking tool. It detects various kinds of errors, including undefined value errors. It adds instrumentation to the source code (C or C++ only) at compile-time, in order to do checking at run-time. It has two modes of undefined-
ness checking: the first is eager, immediately report- ing any reads of undefined variables; the second is less eager, allowing copies of undefined variables to occur without warning (but not other operations). Insure++ also comes with Chaperon, a tool for x86/Linux that works much like Memcheck—it also uses dynamic bi- nary instrumentation—which can detect reads of unini- tialised memory. The most notable feature of Memcheck compared to previous tools is that its definedness checking is much more sophisticated, featuring bit-precision, which means it can be used reliably with bit-field operations.
We have described a tool named Memcheck, built with the dynamic binary instrumentation framework Valgrind, which can detect several kinds of memory errors that are common in imperative programs. In particular, we described the novel definedness checking that Mem- check performs to detect undefined value errors with bit- precision. We also considered the costs and benefits of using Memcheck, and concluded that it definitely is worth using, as shown by the 102 bugs found in OpenOf- fice by one user, and more generally by the thousands of programmers who use it on a wide range of software. Memcheck works well, and is widely used. Our main challenge is ensuring that this remains true. Work is in progress to develop a new intermediate representation for Valgrind, which will provide sufficient description of FP and SIMD operations to keep up with the increasing ca- pabilities of vectorising compilers. The new intermediate representation will also be architecture-neutral, in order to provide a solid foundation for ports to architectures other than x86, which will help keep Valgrind viable over the long-term. A key challenge here is that instrumenta- tion should also be architecture-neutral, so that tools do not have to be partially or wholly re-written for each new
USENIX Association 2005 USENIX Annual Technical Conference 29
architecture supported. We also are working on ports to other operating systems, in order to remove Valgrind’s dependence on Linux. This is a significant task, but one that is orthogonal to Memcheck’s workings. If you are developing programs in C, C++, Fortran or Pascal on the x86/Linux platform, you almost certainly should be using Memcheck. If you are not, all the bugs Memcheck would find will have to be found manually, wasting your development time, or not be found at all, compromising your code quality.
Thanks to Donna Robinson for encouragement, and Jens-Heiner Rechtien for his meticulous record-keeping. The second author gratefully acknowledges the finan- cial support of Trinity College, University of Cambridge, UK.
(^1) However, it is useful mostly for languages like C, C++ and Fortran, which have scant protection against memory errors. (^2) Purify 2003a.06.13 Solaris 2 (32-bit, sparc) running on Solaris 2.9. Compiler was Sun C 5.5. Optimisation level makes no difference: we tried -xO3, -xO5 and no optimisation, with the same result. (^3) Use of an undefined address is different from use of a defined but invalid address. Memcheck detects both kinds of errors, but only the former is the subject of this discussion. (^4) Or shadow memory byte, for memory arguments to system calls. (^5) A common question from aspiring Valgrind hackers is how to write a simple tool which observes procedure entries/exits. From experience we know that doing so reliably is extraordinarily difficult. Josef Wei- dendorfer’s “Callgrind” tool [19] is the best attempt so far, and it is surprisingly complex. (^6) For similar reasons, the stack-switch heuristic can also confuse Memcheck’s addressability checking. (^7) On the 680 branch, which will become OpenOffice 2.0.
[1] Michael D. Ernst. Static and dynamic analysis: synergy and duality. In Proceedings of WODA 2003 , pages 6–9, Portland, Oregon, May 2003.
[2] Eric Estievenart. Valgui, a GPL front-end for Val- grind. http://valgui.sf.net/.
[3] Reed Hastings and Bob Joyce. Purify: Fast detec- tion of memory leaks and access errors. In Pro- ceedings of the Winter USENIX Conference , pages 125–136, San Francisco, California, USA, January
[4] J. C. Huang. Detection of data flow anomaly through program instrumentation. IEEE Transac- tions on Software Engineering , 5(3):226–236, May
[5] Willett Kempton and Brian A. Wichmann. Run- time detection of undefined variables considered essential. Software—Practice and Experience , 20(4):391–402, April 1990.
[6] Paul Mackerras. Re: Valgrind for PowerPC. Mes- sage to the valgrind-developers mailing list, March
[7] Jonas Maebe and Koen De Bosschere. Instrument- ing self-modifying code. In Proceedings of AADE- BUG2003 , Ghent, Belgium, September 2003.
[8] Dorit Naishlos. Autovectorisation in GCC. In Pro- ceedings of the 2004 GCC Developers’ Summit , Ot- tawa, Canada, June 2004.
[9] Nicholas Nethercote. Dynamic Binary Analysis and Instrumentation. PhD thesis, Computer Labora- tory, University of Cambridge, United Kingdom, November 2004.
[10] Nicholas Nethercote and Julian Seward. Valgrind: A program supervision framework. In Proceedings of RV’03 , Boulder, Colorado, USA, July 2003.
[11] Openoffice.org issue 20184, 2003. http://www.openoffice.org/ issues/show_bug.cgi?id=20184.
[12] Parasoft. Automatic C/C++ application testing with Parasoft Insure++. White paper.
[13] Jens-Heiner Rechtien. Validating and debugging openoffice.org with valgrind, 2003. http://tools.openoffice.org/ debugging/usingvalgrind.sxw.
[14] Julian Seward, Nicholas Nethercote, Jeremy Fitzhardinge, et al. Valgrind. http://www.valgrind.org/.
[15] Amitabh Srivastava and Alan Eustace. ATOM: A system for building customized program analysis tools. In Proceedings of PLDI ’94 , pages 196–205, Orlando, Florida, USA, June 1994.
[16] Standard Performance Evaluation Corporation. SPEC CPU2000 benchmarks. http://www.spec.org/.
[17] Jeffrey Stedfast. Alleyoop. http://alleyoop.sf.net/.
[18] Third Degree User Manual , May 1994.
[19] Josef Weidendorfer. KCachegrind. http://kcachegrind.sf.net/.
30 2005 USENIX Annual Technical Conference^ USENIX Association