1 <?xml version="1.0"?> <!-- -*- sgml -*- -->
2 <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
3 "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
6 <chapter id="mc-manual" xreflabel="Memcheck: a memory error detector">
7 <title>Memcheck: a memory error detector</title>
9 <para>To use this tool, you may specify <option>--tool=memcheck</option>
10 on the Valgrind command line. You don't have to, though, since Memcheck
11 is the default tool.</para>
14 <sect1 id="mc-manual.overview" xreflabel="Overview">
15 <title>Overview</title>
17 <para>Memcheck is a memory error detector. It can detect the following
18 problems that are common in C and C++ programs.</para>
22 <para>Accessing memory you shouldn't, e.g. overrunning and underrunning
23 heap blocks, overrunning the top of the stack, and accessing memory after
24 it has been freed.</para>
28 <para>Using undefined values, i.e. values that have not been initialised,
29 or that have been derived from other undefined values.</para>
33 <para>Incorrect freeing of heap memory, such as double-freeing heap
34 blocks, or mismatched use of
35 <function>malloc</function>/<computeroutput>new</computeroutput>/<computeroutput>new[]</computeroutput>
37 <function>free</function>/<computeroutput>delete</computeroutput>/<computeroutput>delete[]</computeroutput></para>
41 <para>Overlapping <computeroutput>src</computeroutput> and
42 <computeroutput>dst</computeroutput> pointers in
43 <computeroutput>memcpy</computeroutput> and related
48 <para>Memory leaks.</para>
52 <para>Problems like these can be difficult to find by other means,
53 often remaining undetected for long periods, then causing occasional,
54 difficult-to-diagnose crashes.</para>
60 <sect1 id="mc-manual.errormsgs"
61 xreflabel="Explanation of error messages from Memcheck">
62 <title>Explanation of error messages from Memcheck</title>
64 <para>Memcheck issues a range of error messages. This section presents a
65 quick summary of what error messages mean. The precise behaviour of the
66 error-checking machinery is described in <xref
67 linkend="mc-manual.machine"/>.</para>
70 <sect2 id="mc-manual.badrw"
71 xreflabel="Illegal read / Illegal write errors">
72 <title>Illegal read / Illegal write errors</title>
74 <para>For example:</para>
75 <programlisting><![CDATA[
76 Invalid read of size 4
77 at 0x40F6BBCC: (within /usr/lib/libpng.so.2.1.0.9)
78 by 0x40F6B804: (within /usr/lib/libpng.so.2.1.0.9)
79 by 0x40B07FF4: read_png_image(QImageIO *) (kernel/qpngio.cpp:326)
80 by 0x40AC751B: QImageIO::read() (kernel/qimage.cpp:3621)
81 Address 0xBFFFF0E0 is not stack'd, malloc'd or free'd
84 <para>This happens when your program reads or writes memory at a place
85 which Memcheck reckons it shouldn't. In this example, the program did a
86 4-byte read at address 0xBFFFF0E0, somewhere within the system-supplied
87 library libpng.so.2.1.0.9, which was called from somewhere else in the
88 same library, called from line 326 of <filename>qpngio.cpp</filename>,
91 <para>Memcheck tries to establish what the illegal address might relate
92 to, since that's often useful. So, if it points into a block of memory
93 which has already been freed, you'll be informed of this, and also where
94 the block was freed. Likewise, if it should turn out to be just off
95 the end of a heap block, a common result of off-by-one-errors in
96 array subscripting, you'll be informed of this fact, and also where the
97 block was allocated. If you use the <option><xref
98 linkend="opt.read-var-info"/></option> option Memcheck will run more slowly
99 but may give a more detailed description of any illegal address.</para>
101 <para>In this example, Memcheck can't identify the address. Actually
102 the address is on the stack, but, for some reason, this is not a valid
103 stack address -- it is below the stack pointer and that isn't allowed.
104 In this particular case it's probably caused by GCC generating invalid
105 code, a known bug in some ancient versions of GCC.</para>
107 <para>Note that Memcheck only tells you that your program is about to
108 access memory at an illegal address. It can't stop the access from
109 happening. So, if your program makes an access which normally would
110 result in a segmentation fault, you program will still suffer the same
111 fate -- but you will get a message from Memcheck immediately prior to
112 this. In this particular example, reading junk on the stack is
113 non-fatal, and the program stays alive.</para>
119 <sect2 id="mc-manual.uninitvals"
120 xreflabel="Use of uninitialised values">
121 <title>Use of uninitialised values</title>
123 <para>For example:</para>
124 <programlisting><![CDATA[
125 Conditional jump or move depends on uninitialised value(s)
126 at 0x402DFA94: _IO_vfprintf (_itoa.h:49)
127 by 0x402E8476: _IO_printf (printf.c:36)
128 by 0x8048472: main (tests/manuel1.c:8)
131 <para>An uninitialised-value use error is reported when your program
132 uses a value which hasn't been initialised -- in other words, is
133 undefined. Here, the undefined value is used somewhere inside the
134 <function>printf</function> machinery of the C library. This error was
135 reported when running the following small program:</para>
136 <programlisting><![CDATA[
140 printf ("x = %d\n", x);
141 }]]></programlisting>
143 <para>It is important to understand that your program can copy around
144 junk (uninitialised) data as much as it likes. Memcheck observes this
145 and keeps track of the data, but does not complain. A complaint is
146 issued only when your program attempts to make use of uninitialised
147 data in a way that might affect your program's externally-visible behaviour.
148 In this example, <varname>x</varname> is uninitialised. Memcheck observes
149 the value being passed to <function>_IO_printf</function> and thence to
150 <function>_IO_vfprintf</function>, but makes no comment. However,
151 <function>_IO_vfprintf</function> has to examine the value of
152 <varname>x</varname> so it can turn it into the corresponding ASCII string,
153 and it is at this point that Memcheck complains.</para>
155 <para>Sources of uninitialised data tend to be:</para>
158 <para>Local variables in procedures which have not been initialised,
159 as in the example above.</para>
162 <para>The contents of heap blocks (allocated with
163 <function>malloc</function>, <function>new</function>, or a similar
164 function) before you (or a constructor) write something there.
169 <para>To see information on the sources of uninitialised data in your
170 program, use the <option>--track-origins=yes</option> option. This
171 makes Memcheck run more slowly, but can make it much easier to track down
172 the root causes of uninitialised value errors.</para>
178 <sect2 id="mc-manual.bad-syscall-args"
179 xreflabel="Use of uninitialised or unaddressable values in system
181 <title>Use of uninitialised or unaddressable values in system
184 <para>Memcheck checks all parameters to system calls:
187 <para>It checks all the direct parameters themselves, whether they are
191 <para>Also, if a system call needs to read from a buffer provided by
192 your program, Memcheck checks that the entire buffer is addressable
193 and its contents are initialised.</para>
196 <para>Also, if the system call needs to write to a user-supplied
197 buffer, Memcheck checks that the buffer is addressable.</para>
202 <para>After the system call, Memcheck updates its tracked information to
203 precisely reflect any changes in memory state caused by the system
206 <para>Here's an example of two system calls with invalid parameters:</para>
207 <programlisting><![CDATA[
212 char* arr = malloc(10);
213 int* arr2 = malloc(sizeof(int));
214 write( 1 /* stdout */, arr, 10 );
219 <para>You get these complaints ...</para>
220 <programlisting><![CDATA[
221 Syscall param write(buf) points to uninitialised byte(s)
222 at 0x25A48723: __write_nocancel (in /lib/tls/libc-2.3.3.so)
223 by 0x259AFAD3: __libc_start_main (in /lib/tls/libc-2.3.3.so)
224 by 0x8048348: (within /auto/homes/njn25/grind/head4/a.out)
225 Address 0x25AB8028 is 0 bytes inside a block of size 10 alloc'd
226 at 0x259852B0: malloc (vg_replace_malloc.c:130)
227 by 0x80483F1: main (a.c:5)
229 Syscall param exit(error_code) contains uninitialised byte(s)
230 at 0x25A21B44: __GI__exit (in /lib/tls/libc-2.3.3.so)
231 by 0x8048426: main (a.c:8)
234 <para>... because the program has (a) written uninitialised junk
235 from the heap block to the standard output, and (b) passed an
236 uninitialised value to <function>exit</function>. Note that the first
237 error refers to the memory pointed to by
238 <computeroutput>buf</computeroutput> (not
239 <computeroutput>buf</computeroutput> itself), but the second error
240 refers directly to <computeroutput>exit</computeroutput>'s argument
241 <computeroutput>arr2[0]</computeroutput>.</para>
246 <sect2 id="mc-manual.badfrees" xreflabel="Illegal frees">
247 <title>Illegal frees</title>
249 <para>For example:</para>
250 <programlisting><![CDATA[
252 at 0x4004FFDF: free (vg_clientmalloc.c:577)
253 by 0x80484C7: main (tests/doublefree.c:10)
254 Address 0x3807F7B4 is 0 bytes inside a block of size 177 free'd
255 at 0x4004FFDF: free (vg_clientmalloc.c:577)
256 by 0x80484C7: main (tests/doublefree.c:10)
259 <para>Memcheck keeps track of the blocks allocated by your program
260 with <function>malloc</function>/<computeroutput>new</computeroutput>,
261 so it can know exactly whether or not the argument to
262 <function>free</function>/<computeroutput>delete</computeroutput> is
263 legitimate or not. Here, this test program has freed the same block
264 twice. As with the illegal read/write errors, Memcheck attempts to
265 make sense of the address freed. If, as here, the address is one
266 which has previously been freed, you wil be told that -- making
267 duplicate frees of the same block easy to spot. You will also get this
268 message if you try to free a pointer that doesn't point to the start of a
274 <sect2 id="mc-manual.rudefn"
275 xreflabel="When a heap block is freed with an inappropriate deallocation
277 <title>When a heap block is freed with an inappropriate deallocation
280 <para>In the following example, a block allocated with
281 <function>new[]</function> has wrongly been deallocated with
282 <function>free</function>:</para>
283 <programlisting><![CDATA[
284 Mismatched free() / delete / delete []
285 at 0x40043249: free (vg_clientfuncs.c:171)
286 by 0x4102BB4E: QGArray::~QGArray(void) (tools/qgarray.cpp:149)
287 by 0x4C261C41: PptDoc::~PptDoc(void) (include/qmemarray.h:60)
288 by 0x4C261F0E: PptXml::~PptXml(void) (pptxml.cc:44)
289 Address 0x4BB292A8 is 0 bytes inside a block of size 64 alloc'd
290 at 0x4004318C: operator new[](unsigned int) (vg_clientfuncs.c:152)
291 by 0x4C21BC15: KLaola::readSBStream(int) const (klaola.cc:314)
292 by 0x4C21C155: KLaola::stream(KLaola::OLENode const *) (klaola.cc:416)
293 by 0x4C21788F: OLEFilter::convert(QCString const &) (olefilter.cc:272)
296 <para>In <literal>C++</literal> it's important to deallocate memory in a
297 way compatible with how it was allocated. The deal is:</para>
300 <para>If allocated with
301 <function>malloc</function>,
302 <function>calloc</function>,
303 <function>realloc</function>,
304 <function>valloc</function> or
305 <function>memalign</function>, you must
306 deallocate with <function>free</function>.</para>
309 <para>If allocated with <function>new</function>, you must deallocate
310 with <function>delete</function>.</para>
313 <para>If allocated with <function>new[]</function>, you must
314 deallocate with <function>delete[]</function>.</para>
318 <para>The worst thing is that on Linux apparently it doesn't matter if
319 you do mix these up, but the same program may then crash on a
320 different platform, Solaris for example. So it's best to fix it
321 properly. According to the KDE folks "it's amazing how many C++
322 programmers don't know this".</para>
324 <para>The reason behind the requirement is as follows. In some C++
325 implementations, <function>delete[]</function> must be used for
326 objects allocated by <function>new[]</function> because the compiler
327 stores the size of the array and the pointer-to-member to the
328 destructor of the array's content just before the pointer actually
329 returned. <function>delete</function> doesn't account for this and will get
330 confused, possibly corrupting the heap.</para>
336 <sect2 id="mc-manual.overlap"
337 xreflabel="Overlapping source and destination blocks">
338 <title>Overlapping source and destination blocks</title>
340 <para>The following C library functions copy some data from one
341 memory block to another (or something similar):
342 <function>memcpy</function>,
343 <function>strcpy</function>,
344 <function>strncpy</function>,
345 <function>strcat</function>,
346 <function>strncat</function>.
347 The blocks pointed to by their <computeroutput>src</computeroutput> and
348 <computeroutput>dst</computeroutput> pointers aren't allowed to overlap.
349 The POSIX standards have wording along the lines "If copying takes place
350 between objects that overlap, the behavior is undefined." Therefore,
351 Memcheck checks for this.
354 <para>For example:</para>
355 <programlisting><![CDATA[
356 ==27492== Source and destination overlap in memcpy(0xbffff294, 0xbffff280, 21)
357 ==27492== at 0x40026CDC: memcpy (mc_replace_strmem.c:71)
358 ==27492== by 0x804865A: main (overlap.c:40)
361 <para>You don't want the two blocks to overlap because one of them could
362 get partially overwritten by the copying.</para>
364 <para>You might think that Memcheck is being overly pedantic reporting
365 this in the case where <computeroutput>dst</computeroutput> is less than
366 <computeroutput>src</computeroutput>. For example, the obvious way to
367 implement <function>memcpy</function> is by copying from the first
368 byte to the last. However, the optimisation guides of some
369 architectures recommend copying from the last byte down to the first.
370 Also, some implementations of <function>memcpy</function> zero
371 <computeroutput>dst</computeroutput> before copying, because zeroing the
372 destination's cache line(s) can improve performance.</para>
374 <para>The moral of the story is: if you want to write truly portable
375 code, don't make any assumptions about the language
376 implementation.</para>
381 <sect2 id="mc-manual.leaks" xreflabel="Memory leak detection">
382 <title>Memory leak detection</title>
384 <para>Memcheck keeps track of all heap blocks issued in response to
386 <function>malloc</function>/<function>new</function> et al.
387 So when the program exits, it knows which blocks have not been freed.
390 <para>If <option>--leak-check</option> is set appropriately, for each
391 remaining block, Memcheck determines if the block is reachable from pointers
392 within the root-set. The root-set consists of (a) general purpose registers
393 of all threads, and (b) initialised, aligned, pointer-sized data words in
394 accessible client memory, including stacks.</para>
396 <para>There are two ways a block can be reached. The first is with a
397 "start-pointer", i.e. a pointer to the start of the block. The second is with
398 an "interior-pointer", i.e. a pointer to the middle of the block. There are
399 three ways we know of that an interior-pointer can occur:</para>
403 <para>The pointer might have originally been a start-pointer and have been
404 moved along deliberately (or not deliberately) by the program.</para>
408 <para>It might be a random junk value in memory, entirely unrelated, just
409 a coincidence.</para>
413 <para>It might be a pointer to an array of C++ objects (which possess
414 destructors) allocated with <computeroutput>new[]</computeroutput>. In
415 this case, some compilers store a "magic cookie" containing the array
416 length at the start of the allocated block, and return a pointer to just
417 past that magic cookie, i.e. an interior-pointer.
418 See <ulink url="http://theory.uwinnipeg.ca/gnu/gcc/gxxint_14.html">this
419 page</ulink> for more information.</para>
423 <para>With that in mind, consider the nine possible cases described by the
424 following figure.</para>
426 <programlisting><![CDATA[
427 Pointer chain AAA Category BBB Category
428 ------------- ------------ ------------
429 (1) RRR ------------> BBB DR
430 (2) RRR ---> AAA ---> BBB DR IR
432 (4) RRR AAA ---> BBB DL IL
433 (5) RRR ------?-----> BBB (y)DR, (n)DL
434 (6) RRR ---> AAA -?-> BBB DR (y)IR, (n)DL
435 (7) RRR -?-> AAA ---> BBB (y)DR, (n)DL (y)IR, (n)IL
436 (8) RRR -?-> AAA -?-> BBB (y)DR, (n)DL (y,y)IR, (n,y)IL, (_,n)DL
437 (9) RRR AAA -?-> BBB DL (y)IL, (n)DL
439 Pointer chain legend:
440 - RRR: a root set node or DR block
441 - AAA, BBB: heap blocks
442 - --->: a start-pointer
443 - -?->: an interior-pointer
446 - DR: Directly reachable
447 - IR: Indirectly reachable
449 - IL: Indirectly lost
450 - (y)XY: it's XY if the interior-pointer is a real pointer
451 - (n)XY: it's XY if the interior-pointer is not a real pointer
452 - (_)XY: it's XY in either case
455 <para>Every possible case can be reduced to one of the above nine. Memcheck
456 merges some of these cases in its output, resulting in the following four
463 <para>"Still reachable". This covers cases 1 and 2 (for the BBB blocks)
464 above. A start-pointer or chain of start-pointers to the block is
465 found. Since the block is still pointed at, the programmer could, at
466 least in principle, have freed it before program exit. Because these
467 are very common and arguably not a problem, Memcheck won't report such
468 blocks individually unless <option>--show-reachable=yes</option> is
473 <para>"Definitely lost". This covers case 3 (for the BBB blocks) above.
474 This means that no pointer to the block can be found. The block is
475 classified as "lost", because the programmer could not possibly have
476 freed it at program exit, since no pointer to it exists. This is likely
477 a symptom of having lost the pointer at some earlier point in the
478 program. Such cases should be fixed by the programmer.</para>
482 <para>"Indirectly lost". This covers cases 4 and 9 (for the BBB blocks)
483 above. This means that the block is lost, not because there are no
484 pointers to it, but rather because all the blocks that point to it are
485 themselves lost. For example, if you have a binary tree and the root
486 node is lost, all its children nodes will be indirectly lost. Because
487 the problem will disappear if the definitely lost block that caused the
488 indirect leak is fixed, Memcheck won't report such blocks individually
489 unless <option>--show-reachable=yes</option> is specified.</para>
493 <para>"Possibly lost". This covers cases 5--8 (for the BBB blocks)
494 above. This means that a chain of one or more pointers to the block has
495 been found, but at least one of the pointers is an interior-pointer.
496 This could just be a random value in memory that happens to point into a
497 block, and so you shouldn't consider this ok unless you know you have
498 interior-pointers.</para>
503 <para>(Note: This mapping of the nine possible cases onto four categories is
504 not necessarily the best way that leaks could be reported; in particular,
505 interior-pointers are treated inconsistently. It is possible the
506 categorisation may be improved in the future.)</para>
508 <para>Furthermore, if suppressions exists for a block, it will be reported
509 as "suppressed" no matter what which of the above four categories it belongs
513 <para>The following is an example leak summary.</para>
515 <programlisting><![CDATA[
517 definitely lost: 48 bytes in 3 blocks.
518 indirectly lost: 32 bytes in 2 blocks.
519 possibly lost: 96 bytes in 6 blocks.
520 still reachable: 64 bytes in 4 blocks.
521 suppressed: 0 bytes in 0 blocks.
524 <para>If <option>--leak-check=full</option> is specified,
525 Memcheck will give details for each definitely lost or possibly lost block,
526 including where it was allocated. (Actually, it merges results for all
527 blocks that have the same category and sufficiently similar stack traces
528 into a single "loss record". The
529 <option>--leak-resolution</option> lets you control the
530 meaning of "sufficiently similar".) It cannot tell you when or how or why
531 the pointer to a leaked block was lost; you have to work that out for
532 yourself. In general, you should attempt to ensure your programs do not
533 have any definitely lost or possibly lost blocks at exit.</para>
535 <para>For example:</para>
536 <programlisting><![CDATA[
537 8 bytes in 1 blocks are definitely lost in loss record 1 of 14
538 at 0x........: malloc (vg_replace_malloc.c:...)
539 by 0x........: mk (leak-tree.c:11)
540 by 0x........: main (leak-tree.c:39)
542 88 (8 direct, 80 indirect) bytes in 1 blocks are definitely lost in loss record 13 of 14
543 at 0x........: malloc (vg_replace_malloc.c:...)
544 by 0x........: mk (leak-tree.c:11)
545 by 0x........: main (leak-tree.c:25)
548 <para>The first message describes a simple case of a single 8 byte block
549 that has been definitely lost. The second case mentions another 8 byte
550 block that has been definitely lost; the difference is that a further 80
551 bytes in other blocks are indirectly lost because of this lost block.
552 The loss records are not presented in any notable order, so the loss record
553 numbers aren't particularly meaningful.</para>
555 <para>If you specify <option>--show-reachable=yes</option>,
556 reachable and indirectly lost blocks will also be shown, as the following
557 two examples show.</para>
559 <programlisting><![CDATA[
560 64 bytes in 4 blocks are still reachable in loss record 2 of 4
561 at 0x........: malloc (vg_replace_malloc.c:177)
562 by 0x........: mk (leak-cases.c:52)
563 by 0x........: main (leak-cases.c:74)
565 32 bytes in 2 blocks are indirectly lost in loss record 1 of 4
566 at 0x........: malloc (vg_replace_malloc.c:177)
567 by 0x........: mk (leak-cases.c:52)
568 by 0x........: main (leak-cases.c:80)
571 <para>Because there are different kinds of leaks with different severities, an
572 interesting question is this: which leaks should be counted as true "errors"
573 and which should not? The answer to this question affects the numbers printed
574 in the <computeroutput>ERROR SUMMARY</computeroutput> line, and also the effect
575 of the <option>--error-exitcode</option> option. Memcheck uses the following
580 <para>First, a leak is only counted as a true "error" if
581 <option>--leak-check=full</option> is specified. In other words, an
582 unprinted leak is not considered a true "error". If this were not the
583 case, it would be possible to get a high error count but not have any
584 errors printed, which would be confusing.</para>
588 <para>After that, definitely lost and possibly lost blocks are counted as
589 true "errors". Indirectly lost and still reachable blocks are not counted
590 as true "errors", even if <option>--show-reachable=yes</option> is
591 specified and they are printed; this is because such blocks don't need
592 direct fixing by the programmer.
603 <sect1 id="mc-manual.options"
604 xreflabel="Memcheck Command-Line Options">
605 <title>Memcheck Command-Line Options</title>
607 <!-- start of xi:include in the manpage -->
608 <variablelist id="mc.opts.list">
610 <varlistentry id="opt.leak-check" xreflabel="--leak-check">
612 <option><![CDATA[--leak-check=<no|summary|yes|full> [default: summary] ]]></option>
615 <para>When enabled, search for memory leaks when the client
616 program finishes. If set to <varname>summary</varname>, it says how
617 many leaks occurred. If set to <varname>full</varname> or
618 <varname>yes</varname>, it also gives details of each individual
623 <varlistentry id="opt.leak-resolution" xreflabel="--leak-resolution">
625 <option><![CDATA[--leak-resolution=<low|med|high> [default: high] ]]></option>
628 <para>When doing leak checking, determines how willing
629 Memcheck is to consider different backtraces to
630 be the same for the purposes of merging multiple leaks into a single
631 leak report. When set to <varname>low</varname>, only the first
632 two entries need match. When <varname>med</varname>, four entries
633 have to match. When <varname>high</varname>, all entries need to
636 <para>For hardcore leak debugging, you probably want to use
637 <option>--leak-resolution=high</option> together with
638 <option>--num-callers=40</option> or some such large number.
641 <para>Note that the <option>--leak-resolution</option> setting
642 does not affect Memcheck's ability to find
643 leaks. It only changes how the results are presented.</para>
647 <varlistentry id="opt.show-reachable" xreflabel="--show-reachable">
649 <option><![CDATA[--show-reachable=<yes|no> [default: no] ]]></option>
652 <para>When disabled, the memory leak detector only shows "definitely
653 lost" and "possibly lost" blocks. When enabled, the leak detector also
654 shows "reachable" and "indirectly lost" blocks. (In other words, it
655 shows all blocks, except suppressed ones, so
656 <option>--show-all</option> would be a better name for
661 <varlistentry id="opt.undef-value-errors" xreflabel="--undef-value-errors">
663 <option><![CDATA[--undef-value-errors=<yes|no> [default: yes] ]]></option>
666 <para>Controls whether Memcheck reports
667 uses of undefined value errors. Set this to
668 <varname>no</varname> if you don't want to see undefined value
669 errors. It also has the side effect of speeding up
675 <varlistentry id="opt.track-origins" xreflabel="--track-origins">
677 <option><![CDATA[--track-origins=<yes|no> [default: no] ]]></option>
680 <para>Controls whether Memcheck tracks
681 the origin of uninitialised values. By default, it does not,
682 which means that although it can tell you that an
683 uninitialised value is being used in a dangerous way, it
684 cannot tell you where the uninitialised value came from. This
685 often makes it difficult to track down the root problem.
688 to <varname>yes</varname>, Memcheck keeps
689 track of the origins of all uninitialised values. Then, when
690 an uninitialised value error is
691 reported, Memcheck will try to show the
692 origin of the value. An origin can be one of the following
693 four places: a heap block, a stack allocation, a client
694 request, or miscellaneous other sources (eg, a call
695 to <varname>brk</varname>).
697 <para>For uninitialised values originating from a heap
698 block, Memcheck shows where the block was
699 allocated. For uninitialised values originating from a stack
700 allocation, Memcheck can tell you which
701 function allocated the value, but no more than that -- typically
702 it shows you the source location of the opening brace of the
703 function. So you should carefully check that all of the
704 function's local variables are initialised properly.
706 <para>Performance overhead: origin tracking is expensive. It
707 halves Memcheck's speed and increases
708 memory use by a minimum of 100MB, and possibly more.
709 Nevertheless it can drastically reduce the effort required to
710 identify the root cause of uninitialised value errors, and so
711 is often a programmer productivity win, despite running
714 <para>Accuracy: Memcheck tracks origins
715 quite accurately. To avoid very large space and time
716 overheads, some approximations are made. It is possible,
717 although unlikely, that Memcheck will report an incorrect origin, or
718 not be able to identify any origin.
720 <para>Note that the combination
721 <option>--track-origins=yes</option>
722 and <option>--undef-value-errors=no</option> is
723 nonsensical. Memcheck checks for and
724 rejects this combination at startup.
729 <varlistentry id="opt.partial-loads-ok" xreflabel="--partial-loads-ok">
731 <option><![CDATA[--partial-loads-ok=<yes|no> [default: no] ]]></option>
734 <para>Controls how Memcheck handles word-sized,
735 word-aligned loads from addresses for which some bytes are
736 addressable and others are not. When <varname>yes</varname>, such
737 loads do not produce an address error. Instead, loaded bytes
738 originating from illegal addresses are marked as uninitialised, and
739 those corresponding to legal addresses are handled in the normal
742 <para>When <varname>no</varname>, loads from partially invalid
743 addresses are treated the same as loads from completely invalid
744 addresses: an illegal-address error is issued, and the resulting
745 bytes are marked as initialised.</para>
747 <para>Note that code that behaves in this way is in violation of
748 the the ISO C/C++ standards, and should be considered broken. If
749 at all possible, such code should be fixed. This option should be
750 used only as a last resort.</para>
754 <varlistentry id="opt.freelist-vol" xreflabel="--freelist-vol">
756 <option><![CDATA[--freelist-vol=<number> [default: 10000000] ]]></option>
759 <para>When the client program releases memory using
760 <function>free</function> (in <literal>C</literal>) or
761 <computeroutput>delete</computeroutput>
762 (<literal>C++</literal>), that memory is not immediately made
763 available for re-allocation. Instead, it is marked inaccessible
764 and placed in a queue of freed blocks. The purpose is to defer as
765 long as possible the point at which freed-up memory comes back
766 into circulation. This increases the chance that
767 Memcheck will be able to detect invalid
768 accesses to blocks for some significant period of time after they
769 have been freed.</para>
771 <para>This option specifies the maximum total size, in bytes, of the
772 blocks in the queue. The default value is ten million bytes.
773 Increasing this increases the total amount of memory used by
774 Memcheck but may detect invalid uses of freed
775 blocks which would otherwise go undetected.</para>
779 <varlistentry id="opt.workaround-gcc296-bugs" xreflabel="--workaround-gcc296-bugs">
781 <option><![CDATA[--workaround-gcc296-bugs=<yes|no> [default: no] ]]></option>
784 <para>When enabled, assume that reads and writes some small
785 distance below the stack pointer are due to bugs in GCC 2.96, and
786 does not report them. The "small distance" is 256 bytes by
787 default. Note that GCC 2.96 is the default compiler on some ancient
788 Linux distributions (RedHat 7.X) and so you may need to use this
789 option. Do not use it if you do not have to, as it can cause real
790 errors to be overlooked. A better alternative is to use a more
791 recent GCC in which this bug is fixed.</para>
793 <para>You may also need to use this option when working with
794 GCC 3.X or 4.X on 32-bit PowerPC Linux. This is because
795 GCC generates code which occasionally accesses below the
796 stack pointer, particularly for floating-point to/from integer
797 conversions. This is in violation of the 32-bit PowerPC ELF
798 specification, which makes no provision for locations below the
799 stack pointer to be accessible.</para>
803 <varlistentry id="opt.ignore-ranges" xreflabel="--ignore-ranges">
805 <option><![CDATA[--ignore-ranges=0xPP-0xQQ[,0xRR-0xSS] ]]></option>
808 <para>Any ranges listed in this option (and multiple ranges can be
809 specified, separated by commas) will be ignored by Memcheck's
810 addressability checking.</para>
814 <varlistentry id="opt.malloc-fill" xreflabel="--malloc-fill">
816 <option><![CDATA[--malloc-fill=<hexnumber> ]]></option>
819 <para>Fills blocks allocated
820 by <computeroutput>malloc</computeroutput>,
821 <computeroutput>new</computeroutput>, etc, but not
822 by <computeroutput>calloc</computeroutput>, with the specified
823 byte. This can be useful when trying to shake out obscure
824 memory corruption problems. The allocated area is still
825 regarded by Memcheck as undefined -- this option only affects its
831 <varlistentry id="opt.free-fill" xreflabel="--free-fill">
833 <option><![CDATA[--free-fill=<hexnumber> ]]></option>
836 <para>Fills blocks freed
837 by <computeroutput>free</computeroutput>,
838 <computeroutput>delete</computeroutput>, etc, with the
839 specified byte value. This can be useful when trying to shake out
840 obscure memory corruption problems. The freed area is still
841 regarded by Memcheck as not valid for access -- this option only
842 affects its contents.
848 <!-- end of xi:include in the manpage -->
853 <sect1 id="mc-manual.suppfiles" xreflabel="Writing suppression files">
854 <title>Writing suppression files</title>
856 <para>The basic suppression format is described in
857 <xref linkend="manual-core.suppress"/>.</para>
859 <para>The suppression-type (second) line should have the form:</para>
860 <programlisting><![CDATA[
861 Memcheck:suppression_type]]></programlisting>
863 <para>The Memcheck suppression types are as follows:</para>
867 <para><varname>Value1</varname>,
868 <varname>Value2</varname>,
869 <varname>Value4</varname>,
870 <varname>Value8</varname>,
871 <varname>Value16</varname>,
872 meaning an uninitialised-value error when
873 using a value of 1, 2, 4, 8 or 16 bytes.</para>
877 <para><varname>Cond</varname> (or its old
878 name, <varname>Value0</varname>), meaning use
879 of an uninitialised CPU condition code.</para>
883 <para><varname>Addr1</varname>,
884 <varname>Addr2</varname>,
885 <varname>Addr4</varname>,
886 <varname>Addr8</varname>,
887 <varname>Addr16</varname>,
888 meaning an invalid address during a
889 memory access of 1, 2, 4, 8 or 16 bytes respectively.</para>
893 <para><varname>Jump</varname>, meaning an
894 jump to an unaddressable location error.</para>
898 <para><varname>Param</varname>, meaning an
899 invalid system call parameter error.</para>
903 <para><varname>Free</varname>, meaning an
904 invalid or mismatching free.</para>
908 <para><varname>Overlap</varname>, meaning a
909 <computeroutput>src</computeroutput> /
910 <computeroutput>dst</computeroutput> overlap in
911 <function>memcpy</function> or a similar function.</para>
915 <para><varname>Leak</varname>, meaning
916 a memory leak.</para>
921 <para><computeroutput>Param</computeroutput> errors have an extra
922 information line at this point, which is the name of the offending
923 system call parameter. No other error kinds have this extra
926 <para>The first line of the calling context: for <varname>ValueN</varname>
927 and <varname>AddrN</varname> errors, it is either the name of the function
928 in which the error occurred, or, failing that, the full path of the
929 <filename>.so</filename> file
930 or executable containing the error location. For <varname>Free</varname> errors, is the name
931 of the function doing the freeing (eg, <function>free</function>,
932 <function>__builtin_vec_delete</function>, etc). For
933 <varname>Overlap</varname> errors, is the name of the function with the
934 overlapping arguments (eg. <function>memcpy</function>,
935 <function>strcpy</function>, etc).</para>
937 <para>Lastly, there's the rest of the calling context.</para>
943 <sect1 id="mc-manual.machine"
944 xreflabel="Details of Memcheck's checking machinery">
945 <title>Details of Memcheck's checking machinery</title>
947 <para>Read this section if you want to know, in detail, exactly
948 what and how Memcheck is checking.</para>
951 <sect2 id="mc-manual.value" xreflabel="Valid-value (V) bit">
952 <title>Valid-value (V) bits</title>
954 <para>It is simplest to think of Memcheck implementing a synthetic CPU
955 which is identical to a real CPU, except for one crucial detail. Every
956 bit (literally) of data processed, stored and handled by the real CPU
957 has, in the synthetic CPU, an associated "valid-value" bit, which says
958 whether or not the accompanying bit has a legitimate value. In the
959 discussions which follow, this bit is referred to as the V (valid-value)
962 <para>Each byte in the system therefore has a 8 V bits which follow it
963 wherever it goes. For example, when the CPU loads a word-size item (4
964 bytes) from memory, it also loads the corresponding 32 V bits from a
965 bitmap which stores the V bits for the process' entire address space.
966 If the CPU should later write the whole or some part of that value to
967 memory at a different address, the relevant V bits will be stored back
968 in the V-bit bitmap.</para>
970 <para>In short, each bit in the system has (conceptually) an associated V
971 bit, which follows it around everywhere, even inside the CPU. Yes, all the
972 CPU's registers (integer, floating point, vector and condition registers)
973 have their own V bit vectors. For this to work, Memcheck uses a great deal
974 of compression to represent the V bits compactly.</para>
976 <para>Copying values around does not cause Memcheck to check for, or
977 report on, errors. However, when a value is used in a way which might
978 conceivably affect your program's externally-visible behaviour,
979 the associated V bits are immediately checked. If any of these indicate
980 that the value is undefined (even partially), an error is reported.</para>
982 <para>Here's an (admittedly nonsensical) example:</para>
983 <programlisting><![CDATA[
986 for ( i = 0; i < 10; i++ ) {
989 }]]></programlisting>
991 <para>Memcheck emits no complaints about this, since it merely copies
992 uninitialised values from <varname>a[]</varname> into
993 <varname>b[]</varname>, and doesn't use them in a way which could
994 affect the behaviour of the program. However, if
995 the loop is changed to:</para>
996 <programlisting><![CDATA[
997 for ( i = 0; i < 10; i++ ) {
1001 printf("hello there\n");
1002 ]]></programlisting>
1004 <para>then Memcheck will complain, at the
1005 <computeroutput>if</computeroutput>, that the condition depends on
1006 uninitialised values. Note that it <command>doesn't</command> complain
1007 at the <varname>j += a[i];</varname>, since at that point the
1008 undefinedness is not "observable". It's only when a decision has to be
1009 made as to whether or not to do the <function>printf</function> -- an
1010 observable action of your program -- that Memcheck complains.</para>
1012 <para>Most low level operations, such as adds, cause Memcheck to use the
1013 V bits for the operands to calculate the V bits for the result. Even if
1014 the result is partially or wholly undefined, it does not
1017 <para>Checks on definedness only occur in three places: when a value is
1018 used to generate a memory address, when control flow decision needs to
1019 be made, and when a system call is detected, Memcheck checks definedness
1020 of parameters as required.</para>
1022 <para>If a check should detect undefinedness, an error message is
1023 issued. The resulting value is subsequently regarded as well-defined.
1024 To do otherwise would give long chains of error messages. In other
1025 words, once Memcheck reports an undefined value error, it tries to
1026 avoid reporting further errors derived from that same undefined
1029 <para>This sounds overcomplicated. Why not just check all reads from
1030 memory, and complain if an undefined value is loaded into a CPU
1031 register? Well, that doesn't work well, because perfectly legitimate C
1032 programs routinely copy uninitialised values around in memory, and we
1033 don't want endless complaints about that. Here's the canonical example.
1034 Consider a struct like this:</para>
1035 <programlisting><![CDATA[
1036 struct S { int x; char c; };
1041 ]]></programlisting>
1043 <para>The question to ask is: how large is <varname>struct S</varname>,
1044 in bytes? An <varname>int</varname> is 4 bytes and a
1045 <varname>char</varname> one byte, so perhaps a <varname>struct
1046 S</varname> occupies 5 bytes? Wrong. All non-toy compilers we know
1047 of will round the size of <varname>struct S</varname> up to a whole
1048 number of words, in this case 8 bytes. Not doing this forces compilers
1049 to generate truly appalling code for accessing arrays of
1050 <varname>struct S</varname>'s on some architectures.</para>
1052 <para>So <varname>s1</varname> occupies 8 bytes, yet only 5 of them will
1053 be initialised. For the assignment <varname>s2 = s1</varname>, GCC
1054 generates code to copy all 8 bytes wholesale into <varname>s2</varname>
1055 without regard for their meaning. If Memcheck simply checked values as
1056 they came out of memory, it would yelp every time a structure assignment
1057 like this happened. So the more complicated behaviour described above
1058 is necessary. This allows GCC to copy
1059 <varname>s1</varname> into <varname>s2</varname> any way it likes, and a
1060 warning will only be emitted if the uninitialised values are later
1066 <sect2 id="mc-manual.vaddress" xreflabel=" Valid-address (A) bits">
1067 <title>Valid-address (A) bits</title>
1069 <para>Notice that the previous subsection describes how the validity of
1070 values is established and maintained without having to say whether the
1071 program does or does not have the right to access any particular memory
1072 location. We now consider the latter question.</para>
1074 <para>As described above, every bit in memory or in the CPU has an
1075 associated valid-value (V) bit. In addition, all bytes in memory, but
1076 not in the CPU, have an associated valid-address (A) bit. This
1077 indicates whether or not the program can legitimately read or write that
1078 location. It does not give any indication of the validity or the data
1079 at that location -- that's the job of the V bits -- only whether or not
1080 the location may be accessed.</para>
1082 <para>Every time your program reads or writes memory, Memcheck checks
1083 the A bits associated with the address. If any of them indicate an
1084 invalid address, an error is emitted. Note that the reads and writes
1085 themselves do not change the A bits, only consult them.</para>
1087 <para>So how do the A bits get set/cleared? Like this:</para>
1091 <para>When the program starts, all the global data areas are
1092 marked as accessible.</para>
1096 <para>When the program does
1097 <function>malloc</function>/<computeroutput>new</computeroutput>,
1098 the A bits for exactly the area allocated, and not a byte more,
1099 are marked as accessible. Upon freeing the area the A bits are
1100 changed to indicate inaccessibility.</para>
1104 <para>When the stack pointer register (<literal>SP</literal>) moves
1105 up or down, A bits are set. The rule is that the area from
1106 <literal>SP</literal> up to the base of the stack is marked as
1107 accessible, and below <literal>SP</literal> is inaccessible. (If
1108 that sounds illogical, bear in mind that the stack grows down, not
1109 up, on almost all Unix systems, including GNU/Linux.) Tracking
1110 <literal>SP</literal> like this has the useful side-effect that the
1111 section of stack used by a function for local variables etc is
1112 automatically marked accessible on function entry and inaccessible
1117 <para>When doing system calls, A bits are changed appropriately.
1118 For example, <literal>mmap</literal>
1119 magically makes files appear in the process'
1120 address space, so the A bits must be updated if <literal>mmap</literal>
1125 <para>Optionally, your program can tell Memcheck about such changes
1126 explicitly, using the client request mechanism described
1135 <sect2 id="mc-manual.together" xreflabel="Putting it all together">
1136 <title>Putting it all together</title>
1138 <para>Memcheck's checking machinery can be summarised as
1143 <para>Each byte in memory has 8 associated V (valid-value) bits,
1144 saying whether or not the byte has a defined value, and a single A
1145 (valid-address) bit, saying whether or not the program currently has
1146 the right to read/write that address. (But, as mentioned above, heavy
1147 use of compression means the overhead is typically less than 25%.)</para>
1151 <para>When memory is read or written, the relevant A bits are
1152 consulted. If they indicate an invalid address, Memcheck emits an
1153 Invalid read or Invalid write error.</para>
1157 <para>When memory is read into the CPU's registers, the relevant V
1158 bits are fetched from memory and stored in the simulated CPU. They
1159 are not consulted.</para>
1163 <para>When a register is written out to memory, the V bits for that
1164 register are written back to memory too.</para>
1168 <para>When values in CPU registers are used to generate a memory
1169 address, or to determine the outcome of a conditional branch, the V
1170 bits for those values are checked, and an error emitted if any of
1171 them are undefined.</para>
1175 <para>When values in CPU registers are used for any other purpose,
1176 Memcheck computes the V bits for the result, but does not check
1181 <para>Once the V bits for a value in the CPU have been checked, they
1182 are then set to indicate validity. This avoids long chains of
1187 <para>When values are loaded from memory, Memcheck checks the A bits
1188 for that location and issues an illegal-address warning if needed.
1189 In that case, the V bits loaded are forced to indicate Valid,
1190 despite the location being invalid.</para>
1192 <para>This apparently strange choice reduces the amount of confusing
1193 information presented to the user. It avoids the unpleasant
1194 phenomenon in which memory is read from a place which is both
1195 unaddressable and contains invalid values, and, as a result, you get
1196 not only an invalid-address (read/write) error, but also a
1197 potentially large set of uninitialised-value errors, one for every
1198 time the value is used.</para>
1200 <para>There is a hazy boundary case to do with multi-byte loads from
1201 addresses which are partially valid and partially invalid. See
1202 details of the option <option>--partial-loads-ok</option> for details.
1209 <para>Memcheck intercepts calls to <function>malloc</function>,
1210 <function>calloc</function>, <function>realloc</function>,
1211 <function>valloc</function>, <function>memalign</function>,
1212 <function>free</function>, <computeroutput>new</computeroutput>,
1213 <computeroutput>new[]</computeroutput>,
1214 <computeroutput>delete</computeroutput> and
1215 <computeroutput>delete[]</computeroutput>. The behaviour you get
1221 <para><function>malloc</function>/<function>new</function>/<computeroutput>new[]</computeroutput>:
1222 the returned memory is marked as addressable but not having valid
1223 values. This means you have to write to it before you can read
1228 <para><function>calloc</function>: returned memory is marked both
1229 addressable and valid, since <function>calloc</function> clears
1230 the area to zero.</para>
1234 <para><function>realloc</function>: if the new size is larger than
1235 the old, the new section is addressable but invalid, as with
1236 <function>malloc</function>. If the new size is smaller, the
1237 dropped-off section is marked as unaddressable. You may only pass to
1238 <function>realloc</function> a pointer previously issued to you by
1239 <function>malloc</function>/<function>calloc</function>/<function>realloc</function>.</para>
1243 <para><function>free</function>/<computeroutput>delete</computeroutput>/<computeroutput>delete[]</computeroutput>:
1244 you may only pass to these functions a pointer previously issued
1245 to you by the corresponding allocation function. Otherwise,
1246 Memcheck complains. If the pointer is indeed valid, Memcheck
1247 marks the entire area it points at as unaddressable, and places
1248 the block in the freed-blocks-queue. The aim is to defer as long
1249 as possible reallocation of this block. Until that happens, all
1250 attempts to access it will elicit an invalid-address error, as you
1261 <sect1 id="mc-manual.clientreqs" xreflabel="Client requests">
1262 <title>Client Requests</title>
1264 <para>The following client requests are defined in
1265 <filename>memcheck.h</filename>.
1266 See <filename>memcheck.h</filename> for exact details of their
1272 <para><varname>VALGRIND_MAKE_MEM_NOACCESS</varname>,
1273 <varname>VALGRIND_MAKE_MEM_UNDEFINED</varname> and
1274 <varname>VALGRIND_MAKE_MEM_DEFINED</varname>.
1275 These mark address ranges as completely inaccessible,
1276 accessible but containing undefined data, and accessible and
1277 containing defined data, respectively. Subsequent errors may
1278 have their faulting addresses described in terms of these
1279 blocks. Returns a "block handle". Returns zero when not run
1284 <para><varname>VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE</varname>.
1285 This is just like <varname>VALGRIND_MAKE_MEM_DEFINED</varname> but only
1286 affects those bytes that are already addressable.</para>
1290 <para><varname>VALGRIND_DISCARD</varname>: At some point you may
1291 want Valgrind to stop reporting errors in terms of the blocks
1292 defined by the previous three macros. To do this, the above macros
1293 return a small-integer "block handle". You can pass this block
1294 handle to <varname>VALGRIND_DISCARD</varname>. After doing so,
1295 Valgrind will no longer be able to relate addressing errors to the
1296 user-defined block associated with the handle. The permissions
1297 settings associated with the handle remain in place; this just
1298 affects how errors are reported, not whether they are reported.
1299 Returns 1 for an invalid handle and 0 for a valid handle (although
1300 passing invalid handles is harmless). Always returns 0 when not run
1305 <para><varname>VALGRIND_CHECK_MEM_IS_ADDRESSABLE</varname> and
1306 <varname>VALGRIND_CHECK_MEM_IS_DEFINED</varname>: check immediately
1307 whether or not the given address range has the relevant property,
1308 and if not, print an error message. Also, for the convenience of
1309 the client, returns zero if the relevant property holds; otherwise,
1310 the returned value is the address of the first byte for which the
1311 property is not true. Always returns 0 when not run on
1316 <para><varname>VALGRIND_CHECK_VALUE_IS_DEFINED</varname>: a quick and easy
1317 way to find out whether Valgrind thinks a particular value
1318 (lvalue, to be precise) is addressable and defined. Prints an error
1319 message if not. It has no return value.</para>
1323 <para><varname>VALGRIND_DO_LEAK_CHECK</varname>: does a full memory leak
1324 check (like <option>--leak-check=full</option>) right now.
1325 This is useful for incrementally checking for leaks between arbitrary
1326 places in the program's execution. It has no return value.</para>
1330 <para><varname>VALGRIND_DO_QUICK_LEAK_CHECK</varname>: like
1331 <varname>VALGRIND_DO_LEAK_CHECK</varname>, except it produces only a leak
1332 summary (like <option>--leak-check=summary</option>).
1333 It has no return value.</para>
1337 <para><varname>VALGRIND_COUNT_LEAKS</varname>: fills in the four
1338 arguments with the number of bytes of memory found by the previous
1339 leak check to be leaked (i.e. the sum of direct leaks and indirect leaks),
1340 dubious, reachable and suppressed. This is useful in test harness code,
1341 after calling <varname>VALGRIND_DO_LEAK_CHECK</varname> or
1342 <varname>VALGRIND_DO_QUICK_LEAK_CHECK</varname>.</para>
1346 <para><varname>VALGRIND_COUNT_LEAK_BLOCKS</varname>: identical to
1347 <varname>VALGRIND_COUNT_LEAKS</varname> except that it returns the
1348 number of blocks rather than the number of bytes in each
1353 <para><varname>VALGRIND_GET_VBITS</varname> and
1354 <varname>VALGRIND_SET_VBITS</varname>: allow you to get and set the
1355 V (validity) bits for an address range. You should probably only
1356 set V bits that you have got with
1357 <varname>VALGRIND_GET_VBITS</varname>. Only for those who really
1358 know what they are doing.</para>
1368 <sect1 id="mc-manual.mempools" xreflabel="Memory Pools">
1369 <title>Memory Pools: describing and working with custom allocators</title>
1371 <para>Some programs use custom memory allocators, often for performance
1372 reasons. Left to itself, Memcheck is unable to understand the
1373 behaviour of custom allocation schemes as well as it understands the
1374 standard allocators, and so may miss errors and leaks in your program. What
1375 this section describes is a way to give Memcheck enough of a description of
1376 your custom allocator that it can make at least some sense of what is
1379 <para>There are many different sorts of custom allocator, so Memcheck
1380 attempts to reason about them using a loose, abstract model. We
1381 use the following terminology when describing custom allocation
1386 <para>Custom allocation involves a set of independent "memory pools".
1390 <para>Memcheck's notion of a a memory pool consists of a single "anchor
1391 address" and a set of non-overlapping "chunks" associated with the
1392 anchor address.</para>
1395 <para>Typically a pool's anchor address is the address of a
1396 book-keeping "header" structure.</para>
1399 <para>Typically the pool's chunks are drawn from a contiguous
1400 "superblock" acquired through the system
1401 <function>malloc</function> or
1402 <function>mmap</function>.</para>
1407 <para>Keep in mind that the last two points above say "typically": the
1408 Valgrind mempool client request API is intentionally vague about the
1409 exact structure of a mempool. There is no specific mention made of
1410 headers or superblocks. Nevertheless, the following picture may help
1411 elucidate the intention of the terms in the API:</para>
1413 <programlisting><![CDATA[
1423 +------+---+--------------+---+------------------+
1424 | |rzB| allocation |rzB| |
1425 +------+---+--------------+---+------------------+
1428 "addr" "addr"+"size"
1429 ]]></programlisting>
1432 Note that the header and the superblock may be contiguous or
1433 discontiguous, and there may be multiple superblocks associated with a
1434 single header; such variations are opaque to Memcheck. The API
1435 only requires that your allocation scheme can present sensible values
1436 of "pool", "addr" and "size".</para>
1439 Typically, before making client requests related to mempools, a client
1440 program will have allocated such a header and superblock for their
1441 mempool, and marked the superblock NOACCESS using the
1442 <varname>VALGRIND_MAKE_MEM_NOACCESS</varname> client request.</para>
1445 When dealing with mempools, the goal is to maintain a particular
1446 invariant condition: that Memcheck believes the unallocated portions
1447 of the pool's superblock (including redzones) are NOACCESS. To
1448 maintain this invariant, the client program must ensure that the
1449 superblock starts out in that state; Memcheck cannot make it so, since
1450 Memcheck never explicitly learns about the superblock of a pool, only
1451 the allocated chunks within the pool.</para>
1454 Once the header and superblock for a pool are established and properly
1455 marked, there are a number of client requests programs can use to
1456 inform Memcheck about changes to the state of a mempool:</para>
1462 <varname>VALGRIND_CREATE_MEMPOOL(pool, rzB, is_zeroed)</varname>:
1463 This request registers the address <varname>pool</varname> as the anchor
1464 address for a memory pool. It also provides a size
1465 <varname>rzB</varname>, specifying how large the redzones placed around
1466 chunks allocated from the pool should be. Finally, it provides an
1467 <varname>is_zeroed</varname> argument that specifies whether the pool's
1468 chunks are zeroed (more precisely: defined) when allocated.
1471 Upon completion of this request, no chunks are associated with the
1472 pool. The request simply tells Memcheck that the pool exists, so that
1473 subsequent calls can refer to it as a pool.
1478 <para><varname>VALGRIND_DESTROY_MEMPOOL(pool)</varname>:
1479 This request tells Memcheck that a pool is being torn down. Memcheck
1480 then removes all records of chunks associated with the pool, as well
1481 as its record of the pool's existence. While destroying its records of
1482 a mempool, Memcheck resets the redzones of any live chunks in the pool
1488 <para><varname>VALGRIND_MEMPOOL_ALLOC(pool, addr, size)</varname>:
1489 This request informs Memcheck that a <varname>size</varname>-byte chunk
1490 has been allocated at <varname>addr</varname>, and associates the chunk with the
1492 <varname>pool</varname>. If the pool was created with nonzero
1493 <varname>rzB</varname> redzones, Memcheck will mark the
1494 <varname>rzB</varname> bytes before and after the chunk as NOACCESS. If
1495 the pool was created with the <varname>is_zeroed</varname> argument set,
1496 Memcheck will mark the chunk as DEFINED, otherwise Memcheck will mark
1497 the chunk as UNDEFINED.
1502 <para><varname>VALGRIND_MEMPOOL_FREE(pool, addr)</varname>:
1503 This request informs Memcheck that the chunk at <varname>addr</varname>
1504 should no longer be considered allocated. Memcheck will mark the chunk
1505 associated with <varname>addr</varname> as NOACCESS, and delete its
1506 record of the chunk's existence.
1511 <para><varname>VALGRIND_MEMPOOL_TRIM(pool, addr, size)</varname>:
1512 This request trims the chunks associated with <varname>pool</varname>.
1513 The request only operates on chunks associated with
1514 <varname>pool</varname>. Trimming is formally defined as:</para>
1517 <para> All chunks entirely inside the range
1518 <varname>addr..(addr+size-1)</varname> are preserved.</para>
1521 <para>All chunks entirely outside the range
1522 <varname>addr..(addr+size-1)</varname> are discarded, as though
1523 <varname>VALGRIND_MEMPOOL_FREE</varname> was called on them. </para>
1526 <para>All other chunks must intersect with the range
1527 <varname>addr..(addr+size-1)</varname>; areas outside the
1528 intersection are marked as NOACCESS, as though they had been
1529 independently freed with
1530 <varname>VALGRIND_MEMPOOL_FREE</varname>.</para>
1533 <para>This is a somewhat rare request, but can be useful in
1534 implementing the type of mass-free operations common in custom
1535 LIFO allocators.</para>
1539 <para><varname>VALGRIND_MOVE_MEMPOOL(poolA, poolB)</varname>: This
1540 request informs Memcheck that the pool previously anchored at
1541 address <varname>poolA</varname> has moved to anchor address
1542 <varname>poolB</varname>. This is a rare request, typically only needed
1543 if you <function>realloc</function> the header of a mempool.</para>
1544 <para>No memory-status bits are altered by this request.</para>
1549 <varname>VALGRIND_MEMPOOL_CHANGE(pool, addrA, addrB,
1550 size)</varname>: This request informs Memcheck that the chunk
1551 previously allocated at address <varname>addrA</varname> within
1552 <varname>pool</varname> has been moved and/or resized, and should be
1553 changed to cover the region <varname>addrB..(addrB+size-1)</varname>. This
1554 is a rare request, typically only needed if you
1555 <function>realloc</function> a superblock or wish to extend a chunk
1556 without changing its memory-status bits.
1558 <para>No memory-status bits are altered by this request.
1563 <para><varname>VALGRIND_MEMPOOL_EXISTS(pool)</varname>:
1564 This request informs the caller whether or not Memcheck is currently
1565 tracking a mempool at anchor address <varname>pool</varname>. It
1566 evaluates to 1 when there is a mempool associated with that address, 0
1567 otherwise. This is a rare request, only useful in circumstances when
1568 client code might have lost track of the set of active mempools.
1582 <sect1 id="mc-manual.mpiwrap" xreflabel="MPI Wrappers">
1583 <title>Debugging MPI Parallel Programs with Valgrind</title>
1585 <para>Memcheck supports debugging of distributed-memory applications
1586 which use the MPI message passing standard. This support consists of a
1587 library of wrapper functions for the
1588 <computeroutput>PMPI_*</computeroutput> interface. When incorporated
1589 into the application's address space, either by direct linking or by
1590 <computeroutput>LD_PRELOAD</computeroutput>, the wrappers intercept
1591 calls to <computeroutput>PMPI_Send</computeroutput>,
1592 <computeroutput>PMPI_Recv</computeroutput>, etc. They then
1593 use client requests to inform Memcheck of memory state changes caused
1594 by the function being wrapped. This reduces the number of false
1595 positives that Memcheck otherwise typically reports for MPI
1596 applications.</para>
1598 <para>The wrappers also take the opportunity to carefully check
1599 size and definedness of buffers passed as arguments to MPI functions, hence
1600 detecting errors such as passing undefined data to
1601 <computeroutput>PMPI_Send</computeroutput>, or receiving data into a
1602 buffer which is too small.</para>
1604 <para>Unlike most of the rest of Valgrind, the wrapper library is subject to a
1605 BSD-style license, so you can link it into any code base you like.
1606 See the top of <computeroutput>mpi/libmpiwrap.c</computeroutput>
1607 for license details.</para>
1610 <sect2 id="mc-manual.mpiwrap.build" xreflabel="Building MPI Wrappers">
1611 <title>Building and installing the wrappers</title>
1613 <para> The wrapper library will be built automatically if possible.
1614 Valgrind's configure script will look for a suitable
1615 <computeroutput>mpicc</computeroutput> to build it with. This must be
1616 the same <computeroutput>mpicc</computeroutput> you use to build the
1617 MPI application you want to debug. By default, Valgrind tries
1618 <computeroutput>mpicc</computeroutput>, but you can specify a
1619 different one by using the configure-time option
1620 <option>--with-mpicc</option>. Currently the
1621 wrappers are only buildable with
1622 <computeroutput>mpicc</computeroutput>s which are based on GNU
1623 GCC or Intel's C++ Compiler.</para>
1625 <para>Check that the configure script prints a line like this:</para>
1627 <programlisting><![CDATA[
1628 checking for usable MPI2-compliant mpicc and mpi.h... yes, mpicc
1629 ]]></programlisting>
1631 <para>If it says <computeroutput>... no</computeroutput>, your
1632 <computeroutput>mpicc</computeroutput> has failed to compile and link
1633 a test MPI2 program.</para>
1635 <para>If the configure test succeeds, continue in the usual way with
1636 <computeroutput>make</computeroutput> and <computeroutput>make
1637 install</computeroutput>. The final install tree should then contain
1638 <computeroutput>libmpiwrap-<platform>.so</computeroutput>.
1641 <para>Compile up a test MPI program (eg, MPI hello-world) and try
1644 <programlisting><![CDATA[
1645 LD_PRELOAD=$prefix/lib/valgrind/libmpiwrap-<platform>.so \
1646 mpirun [args] $prefix/bin/valgrind ./hello
1647 ]]></programlisting>
1649 <para>You should see something similar to the following</para>
1651 <programlisting><![CDATA[
1652 valgrind MPI wrappers 31901: Active for pid 31901
1653 valgrind MPI wrappers 31901: Try MPIWRAP_DEBUG=help for possible options
1654 ]]></programlisting>
1656 <para>repeated for every process in the group. If you do not see
1657 these, there is an build/installation problem of some kind.</para>
1659 <para> The MPI functions to be wrapped are assumed to be in an ELF
1660 shared object with soname matching
1661 <computeroutput>libmpi.so*</computeroutput>. This is known to be
1662 correct at least for Open MPI and Quadrics MPI, and can easily be
1663 changed if required.</para>
1667 <sect2 id="mc-manual.mpiwrap.gettingstarted"
1668 xreflabel="Getting started with MPI Wrappers">
1669 <title>Getting started</title>
1671 <para>Compile your MPI application as usual, taking care to link it
1672 using the same <computeroutput>mpicc</computeroutput> that your
1673 Valgrind build was configured with.</para>
1676 Use the following basic scheme to run your application on Valgrind with
1677 the wrappers engaged:</para>
1679 <programlisting><![CDATA[
1680 MPIWRAP_DEBUG=[wrapper-args] \
1681 LD_PRELOAD=$prefix/lib/valgrind/libmpiwrap-<platform>.so \
1682 mpirun [mpirun-args] \
1683 $prefix/bin/valgrind [valgrind-args] \
1684 [application] [app-args]
1685 ]]></programlisting>
1687 <para>As an alternative to
1688 <computeroutput>LD_PRELOAD</computeroutput>ing
1689 <computeroutput>libmpiwrap-<platform>.so</computeroutput>, you can
1690 simply link it to your application if desired. This should not disturb
1691 native behaviour of your application in any way.</para>
1695 <sect2 id="mc-manual.mpiwrap.controlling"
1696 xreflabel="Controlling the MPI Wrappers">
1697 <title>Controlling the wrapper library</title>
1699 <para>Environment variable
1700 <computeroutput>MPIWRAP_DEBUG</computeroutput> is consulted at
1701 startup. The default behaviour is to print a starting banner</para>
1703 <programlisting><![CDATA[
1704 valgrind MPI wrappers 16386: Active for pid 16386
1705 valgrind MPI wrappers 16386: Try MPIWRAP_DEBUG=help for possible options
1706 ]]></programlisting>
1708 <para> and then be relatively quiet.</para>
1710 <para>You can give a list of comma-separated options in
1711 <computeroutput>MPIWRAP_DEBUG</computeroutput>. These are</para>
1715 <para><computeroutput>verbose</computeroutput>:
1716 show entries/exits of all wrappers. Also show extra
1717 debugging info, such as the status of outstanding
1718 <computeroutput>MPI_Request</computeroutput>s resulting
1719 from uncompleted <computeroutput>MPI_Irecv</computeroutput>s.</para>
1722 <para><computeroutput>quiet</computeroutput>:
1723 opposite of <computeroutput>verbose</computeroutput>, only print
1724 anything when the wrappers want
1725 to report a detected programming error, or in case of catastrophic
1726 failure of the wrappers.</para>
1729 <para><computeroutput>warn</computeroutput>:
1730 by default, functions which lack proper wrappers
1731 are not commented on, just silently
1732 ignored. This causes a warning to be printed for each unwrapped
1733 function used, up to a maximum of three warnings per function.</para>
1736 <para><computeroutput>strict</computeroutput>:
1737 print an error message and abort the program if
1738 a function lacking a wrapper is used.</para>
1742 <para> If you want to use Valgrind's XML output facility
1743 (<option>--xml=yes</option>), you should pass
1744 <computeroutput>quiet</computeroutput> in
1745 <computeroutput>MPIWRAP_DEBUG</computeroutput> so as to get rid of any
1746 extraneous printing from the wrappers.</para>
1751 <sect2 id="mc-manual.mpiwrap.limitations.functions"
1752 xreflabel="Functions: Abilities and Limitations">
1753 <title>Functions</title>
1755 <para>All MPI2 functions except
1756 <computeroutput>MPI_Wtick</computeroutput>,
1757 <computeroutput>MPI_Wtime</computeroutput> and
1758 <computeroutput>MPI_Pcontrol</computeroutput> have wrappers. The
1759 first two are not wrapped because they return a
1760 <computeroutput>double</computeroutput>, which Valgrind's
1761 function-wrap mechanism cannot handle (but it could easily be
1762 extended to do so). <computeroutput>MPI_Pcontrol</computeroutput> cannot be
1763 wrapped as it has variable arity:
1764 <computeroutput>int MPI_Pcontrol(const int level, ...)</computeroutput></para>
1766 <para>Most functions are wrapped with a default wrapper which does
1767 nothing except complain or abort if it is called, depending on
1768 settings in <computeroutput>MPIWRAP_DEBUG</computeroutput> listed
1769 above. The following functions have "real", do-something-useful
1772 <programlisting><![CDATA[
1773 PMPI_Send PMPI_Bsend PMPI_Ssend PMPI_Rsend
1775 PMPI_Recv PMPI_Get_count
1777 PMPI_Isend PMPI_Ibsend PMPI_Issend PMPI_Irsend
1780 PMPI_Wait PMPI_Waitall
1781 PMPI_Test PMPI_Testall
1783 PMPI_Iprobe PMPI_Probe
1789 PMPI_Type_commit PMPI_Type_free
1791 PMPI_Pack PMPI_Unpack
1793 PMPI_Bcast PMPI_Gather PMPI_Scatter PMPI_Alltoall
1794 PMPI_Reduce PMPI_Allreduce PMPI_Op_create
1796 PMPI_Comm_create PMPI_Comm_dup PMPI_Comm_free PMPI_Comm_rank PMPI_Comm_size
1799 PMPI_Init PMPI_Initialized PMPI_Finalize
1800 ]]></programlisting>
1802 <para> A few functions such as
1803 <computeroutput>PMPI_Address</computeroutput> are listed as
1804 <computeroutput>HAS_NO_WRAPPER</computeroutput>. They have no wrapper
1805 at all as there is nothing worth checking, and giving a no-op wrapper
1806 would reduce performance for no reason.</para>
1808 <para> Note that the wrapper library itself can itself generate large
1809 numbers of calls to the MPI implementation, especially when walking
1810 complex types. The most common functions called are
1811 <computeroutput>PMPI_Extent</computeroutput>,
1812 <computeroutput>PMPI_Type_get_envelope</computeroutput>,
1813 <computeroutput>PMPI_Type_get_contents</computeroutput>, and
1814 <computeroutput>PMPI_Type_free</computeroutput>. </para>
1817 <sect2 id="mc-manual.mpiwrap.limitations.types"
1818 xreflabel="Types: Abilities and Limitations">
1819 <title>Types</title>
1821 <para> MPI-1.1 structured types are supported, and walked exactly.
1822 The currently supported combiners are
1823 <computeroutput>MPI_COMBINER_NAMED</computeroutput>,
1824 <computeroutput>MPI_COMBINER_CONTIGUOUS</computeroutput>,
1825 <computeroutput>MPI_COMBINER_VECTOR</computeroutput>,
1826 <computeroutput>MPI_COMBINER_HVECTOR</computeroutput>
1827 <computeroutput>MPI_COMBINER_INDEXED</computeroutput>,
1828 <computeroutput>MPI_COMBINER_HINDEXED</computeroutput> and
1829 <computeroutput>MPI_COMBINER_STRUCT</computeroutput>. This should
1830 cover all MPI-1.1 types. The mechanism (function
1831 <computeroutput>walk_type</computeroutput>) should extend easily to
1832 cover MPI2 combiners.</para>
1834 <para>MPI defines some named structured types
1835 (<computeroutput>MPI_FLOAT_INT</computeroutput>,
1836 <computeroutput>MPI_DOUBLE_INT</computeroutput>,
1837 <computeroutput>MPI_LONG_INT</computeroutput>,
1838 <computeroutput>MPI_2INT</computeroutput>,
1839 <computeroutput>MPI_SHORT_INT</computeroutput>,
1840 <computeroutput>MPI_LONG_DOUBLE_INT</computeroutput>) which are pairs
1841 of some basic type and a C <computeroutput>int</computeroutput>.
1842 Unfortunately the MPI specification makes it impossible to look inside
1843 these types and see where the fields are. Therefore these wrappers
1844 assume the types are laid out as <computeroutput>struct { float val;
1845 int loc; }</computeroutput> (for
1846 <computeroutput>MPI_FLOAT_INT</computeroutput>), etc, and act
1847 accordingly. This appears to be correct at least for Open MPI 1.0.2
1848 and for Quadrics MPI.</para>
1850 <para>If <computeroutput>strict</computeroutput> is an option specified
1851 in <computeroutput>MPIWRAP_DEBUG</computeroutput>, the application
1852 will abort if an unhandled type is encountered. Otherwise, the
1853 application will print a warning message and continue.</para>
1855 <para>Some effort is made to mark/check memory ranges corresponding to
1856 arrays of values in a single pass. This is important for performance
1857 since asking Valgrind to mark/check any range, no matter how small,
1858 carries quite a large constant cost. This optimisation is applied to
1859 arrays of primitive types (<computeroutput>double</computeroutput>,
1860 <computeroutput>float</computeroutput>,
1861 <computeroutput>int</computeroutput>,
1862 <computeroutput>long</computeroutput>, <computeroutput>long
1863 long</computeroutput>, <computeroutput>short</computeroutput>,
1864 <computeroutput>char</computeroutput>, and <computeroutput>long
1865 double</computeroutput> on platforms where <computeroutput>sizeof(long
1866 double) == 8</computeroutput>). For arrays of all other types, the
1867 wrappers handle each element individually and so there can be a very
1868 large performance cost.</para>
1873 <sect2 id="mc-manual.mpiwrap.writingwrappers"
1874 xreflabel="Writing new MPI Wrappers">
1875 <title>Writing new wrappers</title>
1878 For the most part the wrappers are straightforward. The only
1879 significant complexity arises with nonblocking receives.</para>
1881 <para>The issue is that <computeroutput>MPI_Irecv</computeroutput>
1882 states the recv buffer and returns immediately, giving a handle
1883 (<computeroutput>MPI_Request</computeroutput>) for the transaction.
1884 Later the user will have to poll for completion with
1885 <computeroutput>MPI_Wait</computeroutput> etc, and when the
1886 transaction completes successfully, the wrappers have to paint the
1887 recv buffer. But the recv buffer details are not presented to
1888 <computeroutput>MPI_Wait</computeroutput> -- only the handle is. The
1889 library therefore maintains a shadow table which associates
1890 uncompleted <computeroutput>MPI_Request</computeroutput>s with the
1891 corresponding buffer address/count/type. When an operation completes,
1892 the table is searched for the associated address/count/type info, and
1893 memory is marked accordingly.</para>
1895 <para>Access to the table is guarded by a (POSIX pthreads) lock, so as
1896 to make the library thread-safe.</para>
1898 <para>The table is allocated with
1899 <computeroutput>malloc</computeroutput> and never
1900 <computeroutput>free</computeroutput>d, so it will show up in leak
1903 <para>Writing new wrappers should be fairly easy. The source file is
1904 <computeroutput>mpi/libmpiwrap.c</computeroutput>. If possible,
1905 find an existing wrapper for a function of similar behaviour to the
1906 one you want to wrap, and use it as a starting point. The wrappers
1907 are organised in sections in the same order as the MPI 1.1 spec, to
1908 aid navigation. When adding a wrapper, remember to comment out the
1909 definition of the default wrapper in the long list of defaults at the
1910 bottom of the file (do not remove it, just comment it out).</para>
1913 <sect2 id="mc-manual.mpiwrap.whattoexpect"
1914 xreflabel="What to expect with MPI Wrappers">
1915 <title>What to expect when using the wrappers</title>
1917 <para>The wrappers should reduce Memcheck's false-error rate on MPI
1918 applications. Because the wrapping is done at the MPI interface,
1919 there will still potentially be a large number of errors reported in
1920 the MPI implementation below the interface. The best you can do is
1921 try to suppress them.</para>
1923 <para>You may also find that the input-side (buffer
1924 length/definedness) checks find errors in your MPI use, for example
1925 passing too short a buffer to
1926 <computeroutput>MPI_Recv</computeroutput>.</para>
1928 <para>Functions which are not wrapped may increase the false
1929 error rate. A possible approach is to run with
1930 <computeroutput>MPI_DEBUG</computeroutput> containing
1931 <computeroutput>warn</computeroutput>. This will show you functions
1932 which lack proper wrappers but which are nevertheless used. You can
1933 then write wrappers for them.
1936 <para>A known source of potential false errors are the
1937 <computeroutput>PMPI_Reduce</computeroutput> family of functions, when
1938 using a custom (user-defined) reduction function. In a reduction
1939 operation, each node notionally sends data to a "central point" which
1940 uses the specified reduction function to merge the data items into a
1941 single item. Hence, in general, data is passed between nodes and fed
1942 to the reduction function, but the wrapper library cannot mark the
1943 transferred data as initialised before it is handed to the reduction
1944 function, because all that happens "inside" the
1945 <computeroutput>PMPI_Reduce</computeroutput> call. As a result you
1946 may see false positives reported in your reduction function.</para>