blob: 27ee1bcfd419c32236a7588525aeda833d3df2ae [file] [log] [blame]
njn3e986b22004-11-30 10:43:45 +00001<?xml version="1.0"?> <!-- -*- sgml -*- -->
2<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
de03e0e7c2005-12-03 23:02:33 +00003 "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
4
njn3e986b22004-11-30 10:43:45 +00005
6<chapter id="mc-manual" xreflabel="Memcheck: a heavyweight memory checker">
7<title>Memcheck: a heavyweight memory checker</title>
8
de03e0e7c2005-12-03 23:02:33 +00009<para>To use this tool, you may specify <option>--tool=memcheck</option>
10on the Valgrind command line. You don't have to, though, since Memcheck
11is the default tool.</para>
njn3e986b22004-11-30 10:43:45 +000012
13
14<sect1 id="mc-manual.bugs"
15 xreflabel="Kinds of bugs that Memcheck can find">
16<title>Kinds of bugs that Memcheck can find</title>
17
de03e0e7c2005-12-03 23:02:33 +000018<para>Memcheck is Valgrind's heavyweight memory checking tool. All
19reads and writes of memory are checked, and calls to
20malloc/new/free/delete are intercepted. As a result, Memcheck can detect
21the following problems:</para>
njn3e986b22004-11-30 10:43:45 +000022
23<itemizedlist>
24 <listitem>
25 <para>Use of uninitialised memory</para>
26 </listitem>
27 <listitem>
28 <para>Reading/writing memory after it has been free'd</para>
29 </listitem>
30 <listitem>
31 <para>Reading/writing off the end of malloc'd blocks</para>
32 </listitem>
33 <listitem>
34 <para>Reading/writing inappropriate areas on the stack</para>
35 </listitem>
36 <listitem>
de03e0e7c2005-12-03 23:02:33 +000037 <para>Memory leaks - where pointers to malloc'd blocks are
njn3e986b22004-11-30 10:43:45 +000038 lost forever</para>
39 </listitem>
40 <listitem>
41 <para>Mismatched use of malloc/new/new [] vs
42 free/delete/delete []</para>
43 </listitem>
44 <listitem>
45 <para>Overlapping <computeroutput>src</computeroutput> and
46 <computeroutput>dst</computeroutput> pointers in
de03e0e7c2005-12-03 23:02:33 +000047 <function>memcpy()</function> and related
njn3e986b22004-11-30 10:43:45 +000048 functions</para>
49 </listitem>
njn3e986b22004-11-30 10:43:45 +000050</itemizedlist>
51
52</sect1>
53
54
55
56<sect1 id="mc-manual.flags"
njn779a2d62005-07-25 00:12:19 +000057 xreflabel="Command-line flags specific to Memcheck">
58<title>Command-line flags specific to Memcheck</title>
njn3e986b22004-11-30 10:43:45 +000059
de03e0e7c2005-12-03 23:02:33 +000060<!-- start of xi:include in the manpage -->
61<variablelist id="mc.opts.list">
njn51272982005-07-25 23:18:44 +000062
sewardjcd0f2bd2008-05-04 23:06:28 +000063 <varlistentry id="opt.undef-value-errors" xreflabel="--undef-value-errors">
64 <term>
65 <option><![CDATA[--undef-value-errors=<yes|no> [default: yes] ]]></option>
66 </term>
67 <listitem>
68 <para>Controls whether <constant>memcheck</constant> reports
69 uses of undefined value errors. Set this to
70 <varname>no</varname> if you don't want to see undefined value
71 errors. It also has the side effect of speeding up
72 <constant>memcheck</constant> somewhat.
73 </para>
74 </listitem>
75 </varlistentry>
76
77 <varlistentry id="opt.track-origins" xreflabel="--track-origins">
78 <term>
79 <option><![CDATA[--track-origins=<yes|no> [default: no] ]]></option>
80 </term>
81 <listitem>
82 <para>Controls whether <constant>memcheck</constant> tracks
83 the origin of uninitialised values. By default, it does not,
84 which means that although it can tell you that an
85 uninitialised value is being used in a dangerous way, it
86 cannot tell you where the uninitialised value came from. This
87 often makes it difficult to track down the root problem.
88 </para>
89 <para>When set
90 to <varname>yes</varname>, <constant>memcheck</constant> keeps
91 track of the origins of all uninitialised values. Then, when
92 an uninitialised value error is
93 reported, <constant>memcheck</constant> will try to show the
94 origin of the value. An origin can be one of the following
95 four places: a heap block, a stack allocation, a client
96 request, or miscellaneous other sources (eg, a call
97 to <varname>brk</varname>).
98 </para>
99 <para>For uninitialised values originating from a heap
100 block, <constant>memcheck</constant> shows where the block was
101 allocated. For uninitialised values originating from a stack
102 allocation, <constant>memcheck</constant> can tell you which
103 function allocated the value, but no more than that -- typically
104 it shows you the source location of the opening brace of the
105 function. So you should carefully check that all of the
106 function's local variables are initialised properly.
107 </para>
108 <para>Performance overhead: origin tracking is expensive. It
109 halves <constant>memcheck</constant>'s speed and increases
110 memory use by a minimum of 100MB, and possibly more.
111 Nevertheless it can drastically reduce the effort required to
112 identify the root cause of uninitialised value errors, and so
113 is often a programmer productivity win, despite running
114 more slowly.
115 </para>
116 <para>Accuracy: <constant>memcheck</constant> tracks origins
117 quite accurately. To avoid very large space and time
118 overheads, some approximations are made. It is possible,
119 although unlikely, that
120 <constant>memcheck</constant> will report an incorrect origin,
121 or not be able to identify any origin.
122 </para>
123 <para>Note that the combination
124 <option>--track-origins=yes</option>
125 and <option>--undef-value-errors=no</option> is
126 nonsensical. <constant>memcheck</constant> checks for and
127 rejects this combination at startup.
128 </para>
129 <para>Origin tracking is a new feature, introduced in Valgrind
130 version 3.4.0.
131 </para>
132 </listitem>
133 </varlistentry>
134
de03e0e7c2005-12-03 23:02:33 +0000135 <varlistentry id="opt.leak-check" xreflabel="--leak-check">
136 <term>
137 <option><![CDATA[--leak-check=<no|summary|yes|full> [default: summary] ]]></option>
138 </term>
139 <listitem>
140 <para>When enabled, search for memory leaks when the client
141 program finishes. A memory leak means a malloc'd block, which has
142 not yet been free'd, but to which no pointer can be found. Such a
143 block can never be free'd by the program, since no pointer to it
144 exists. If set to <varname>summary</varname>, it says how many
145 leaks occurred. If set to <varname>full</varname> or
146 <varname>yes</varname>, it gives details of each individual
147 leak.</para>
148 </listitem>
149 </varlistentry>
njn3e986b22004-11-30 10:43:45 +0000150
de03e0e7c2005-12-03 23:02:33 +0000151 <varlistentry id="opt.show-reachable" xreflabel="--show-reachable">
152 <term>
153 <option><![CDATA[--show-reachable=<yes|no> [default: no] ]]></option>
154 </term>
155 <listitem>
156 <para>When disabled, the memory leak detector only shows blocks
157 for which it cannot find a pointer to at all, or it can only find
158 a pointer to the middle of. These blocks are prime candidates for
159 memory leaks. When enabled, the leak detector also reports on
160 blocks which it could find a pointer to. Your program could, at
161 least in principle, have freed such blocks before exit. Contrast
162 this to blocks for which no pointer, or only an interior pointer
163 could be found: they are more likely to indicate memory leaks,
164 because you do not actually have a pointer to the start of the
165 block which you can hand to <function>free</function>, even if you
166 wanted to.</para>
167 </listitem>
168 </varlistentry>
njn3e986b22004-11-30 10:43:45 +0000169
de03e0e7c2005-12-03 23:02:33 +0000170 <varlistentry id="opt.leak-resolution" xreflabel="--leak-resolution">
171 <term>
172 <option><![CDATA[--leak-resolution=<low|med|high> [default: low] ]]></option>
173 </term>
174 <listitem>
175 <para>When doing leak checking, determines how willing
176 <constant>memcheck</constant> is to consider different backtraces to
177 be the same. When set to <varname>low</varname>, only the first
178 two entries need match. When <varname>med</varname>, four entries
179 have to match. When <varname>high</varname>, all entries need to
180 match.</para>
njn3e986b22004-11-30 10:43:45 +0000181
de03e0e7c2005-12-03 23:02:33 +0000182 <para>For hardcore leak debugging, you probably want to use
183 <option>--leak-resolution=high</option> together with
184 <option>--num-callers=40</option> or some such large number. Note
185 however that this can give an overwhelming amount of information,
186 which is why the defaults are 4 callers and low-resolution
187 matching.</para>
njn3e986b22004-11-30 10:43:45 +0000188
de03e0e7c2005-12-03 23:02:33 +0000189 <para>Note that the <option>--leak-resolution=</option> setting
190 does not affect <constant>memcheck's</constant> ability to find
191 leaks. It only changes how the results are presented.</para>
192 </listitem>
193 </varlistentry>
njn3e986b22004-11-30 10:43:45 +0000194
de03e0e7c2005-12-03 23:02:33 +0000195 <varlistentry id="opt.freelist-vol" xreflabel="--freelist-vol">
196 <term>
sewardjfa4ca3b2007-11-30 17:19:36 +0000197 <option><![CDATA[--freelist-vol=<number> [default: 10000000] ]]></option>
de03e0e7c2005-12-03 23:02:33 +0000198 </term>
199 <listitem>
200 <para>When the client program releases memory using
201 <function>free</function> (in <literal>C</literal>) or delete
202 (<literal>C++</literal>), that memory is not immediately made
203 available for re-allocation. Instead, it is marked inaccessible
204 and placed in a queue of freed blocks. The purpose is to defer as
205 long as possible the point at which freed-up memory comes back
206 into circulation. This increases the chance that
207 <constant>memcheck</constant> will be able to detect invalid
208 accesses to blocks for some significant period of time after they
209 have been freed.</para>
njn3e986b22004-11-30 10:43:45 +0000210
de03e0e7c2005-12-03 23:02:33 +0000211 <para>This flag specifies the maximum total size, in bytes, of the
sewardjfa4ca3b2007-11-30 17:19:36 +0000212 blocks in the queue. The default value is ten million bytes.
de03e0e7c2005-12-03 23:02:33 +0000213 Increasing this increases the total amount of memory used by
214 <constant>memcheck</constant> but may detect invalid uses of freed
215 blocks which would otherwise go undetected.</para>
216 </listitem>
217 </varlistentry>
218
219 <varlistentry id="opt.workaround-gcc296-bugs" xreflabel="--workaround-gcc296-bugs">
220 <term>
221 <option><![CDATA[--workaround-gcc296-bugs=<yes|no> [default: no] ]]></option>
222 </term>
223 <listitem>
224 <para>When enabled, assume that reads and writes some small
225 distance below the stack pointer are due to bugs in gcc 2.96, and
226 does not report them. The "small distance" is 256 bytes by
sewardjc678a542007-12-02 02:01:09 +0000227 default. Note that gcc 2.96 is the default compiler on some ancient
de03e0e7c2005-12-03 23:02:33 +0000228 Linux distributions (RedHat 7.X) and so you may need to use this
229 flag. Do not use it if you do not have to, as it can cause real
230 errors to be overlooked. A better alternative is to use a more
231 recent gcc/g++ in which this bug is fixed.</para>
sewardjc678a542007-12-02 02:01:09 +0000232
233 <para>You may also need to use this flag when working with
234 gcc/g++ 3.X or 4.X on 32-bit PowerPC Linux. This is because
235 gcc/g++ generates code which occasionally accesses below the
236 stack pointer, particularly for floating-point to/from integer
237 conversions. This is in violation of the 32-bit PowerPC ELF
238 specification, which makes no provision for locations below the
239 stack pointer to be accessible.</para>
de03e0e7c2005-12-03 23:02:33 +0000240 </listitem>
241 </varlistentry>
242
243 <varlistentry id="opt.partial-loads-ok" xreflabel="--partial-loads-ok">
244 <term>
245 <option><![CDATA[--partial-loads-ok=<yes|no> [default: no] ]]></option>
246 </term>
247 <listitem>
248 <para>Controls how <constant>memcheck</constant> handles word-sized,
249 word-aligned loads from addresses for which some bytes are
sewardj33878892007-11-17 09:43:25 +0000250 addressable and others are not. When <varname>yes</varname>, such
sewardj08e31e22007-05-23 21:58:33 +0000251 loads do not produce an address error. Instead, loaded bytes
252 originating from illegal addresses are marked as uninitialised, and
253 those corresponding to legal addresses are handled in the normal
254 way.</para>
de03e0e7c2005-12-03 23:02:33 +0000255
256 <para>When <varname>no</varname>, loads from partially invalid
257 addresses are treated the same as loads from completely invalid
sewardj08e31e22007-05-23 21:58:33 +0000258 addresses: an illegal-address error is issued, and the resulting
259 bytes are marked as initialised.</para>
de03e0e7c2005-12-03 23:02:33 +0000260
261 <para>Note that code that behaves in this way is in violation of
262 the the ISO C/C++ standards, and should be considered broken. If
263 at all possible, such code should be fixed. This flag should be
264 used only as a last resort.</para>
265 </listitem>
266 </varlistentry>
267
sewardjc678a542007-12-02 02:01:09 +0000268 <varlistentry id="opt.malloc-fill" xreflabel="--malloc-fill">
269 <term>
270 <option><![CDATA[--malloc-fill=<hexnumber> ]]></option>
271 </term>
272 <listitem>
273 <para>Fills blocks allocated
274 by <computeroutput>malloc</computeroutput>,
275 <computeroutput>new</computeroutput>, etc, but not
276 by <computeroutput>calloc</computeroutput>, with the specified
277 byte. This can be useful when trying to shake out obscure
278 memory corruption problems. The allocated area is still
279 regarded by Memcheck as undefined -- this flag only affects its
280 contents.
281 </para>
282 </listitem>
283 </varlistentry>
284
285 <varlistentry id="opt.free-fill" xreflabel="--free-fill">
286 <term>
287 <option><![CDATA[--free-fill=<hexnumber> ]]></option>
288 </term>
289 <listitem>
290 <para>Fills blocks freed
291 by <computeroutput>free</computeroutput>,
292 <computeroutput>delete</computeroutput>, etc, with the
293 specified byte. This can be useful when trying to shake out
294 obscure memory corruption problems. The freed area is still
295 regarded by Memcheck as not valid for access -- this flag only
296 affects its contents.
297 </para>
298 </listitem>
299 </varlistentry>
300
de03e0e7c2005-12-03 23:02:33 +0000301</variablelist>
302<!-- end of xi:include in the manpage -->
303
njn3e986b22004-11-30 10:43:45 +0000304</sect1>
305
306
307<sect1 id="mc-manual.errormsgs"
308 xreflabel="Explanation of error messages from Memcheck">
309<title>Explanation of error messages from Memcheck</title>
310
de03e0e7c2005-12-03 23:02:33 +0000311<para>Despite considerable sophistication under the hood, Memcheck can
312only really detect two kinds of errors: use of illegal addresses, and
313use of undefined values. Nevertheless, this is enough to help you
sewardj08e31e22007-05-23 21:58:33 +0000314discover all sorts of memory-management problems in your code. This
de03e0e7c2005-12-03 23:02:33 +0000315section presents a quick summary of what error messages mean. The
316precise behaviour of the error-checking machinery is described in
317<xref linkend="mc-manual.machine"/>.</para>
njn3e986b22004-11-30 10:43:45 +0000318
319
320<sect2 id="mc-manual.badrw"
321 xreflabel="Illegal read / Illegal write errors">
322<title>Illegal read / Illegal write errors</title>
323
324<para>For example:</para>
325<programlisting><![CDATA[
326Invalid read of size 4
327 at 0x40F6BBCC: (within /usr/lib/libpng.so.2.1.0.9)
328 by 0x40F6B804: (within /usr/lib/libpng.so.2.1.0.9)
sewardj08e31e22007-05-23 21:58:33 +0000329 by 0x40B07FF4: read_png_image(QImageIO *) (kernel/qpngio.cpp:326)
njn3e986b22004-11-30 10:43:45 +0000330 by 0x40AC751B: QImageIO::read() (kernel/qimage.cpp:3621)
njn21f91952005-03-12 22:14:42 +0000331 Address 0xBFFFF0E0 is not stack'd, malloc'd or free'd
njn3e986b22004-11-30 10:43:45 +0000332]]></programlisting>
333
de03e0e7c2005-12-03 23:02:33 +0000334<para>This happens when your program reads or writes memory at a place
335which Memcheck reckons it shouldn't. In this example, the program did a
3364-byte read at address 0xBFFFF0E0, somewhere within the system-supplied
337library libpng.so.2.1.0.9, which was called from somewhere else in the
338same library, called from line 326 of <filename>qpngio.cpp</filename>,
339and so on.</para>
njn3e986b22004-11-30 10:43:45 +0000340
de03e0e7c2005-12-03 23:02:33 +0000341<para>Memcheck tries to establish what the illegal address might relate
342to, since that's often useful. So, if it points into a block of memory
343which has already been freed, you'll be informed of this, and also where
344the block was free'd at. Likewise, if it should turn out to be just off
345the end of a malloc'd block, a common result of off-by-one-errors in
346array subscripting, you'll be informed of this fact, and also where the
347block was malloc'd.</para>
njn3e986b22004-11-30 10:43:45 +0000348
de03e0e7c2005-12-03 23:02:33 +0000349<para>In this example, Memcheck can't identify the address. Actually
350the address is on the stack, but, for some reason, this is not a valid
351stack address -- it is below the stack pointer and that isn't allowed.
352In this particular case it's probably caused by gcc generating invalid
sewardj8d9fec52005-11-15 20:56:23 +0000353code, a known bug in some ancient versions of gcc.</para>
njn3e986b22004-11-30 10:43:45 +0000354
de03e0e7c2005-12-03 23:02:33 +0000355<para>Note that Memcheck only tells you that your program is about to
356access memory at an illegal address. It can't stop the access from
357happening. So, if your program makes an access which normally would
358result in a segmentation fault, you program will still suffer the same
359fate -- but you will get a message from Memcheck immediately prior to
360this. In this particular example, reading junk on the stack is
361non-fatal, and the program stays alive.</para>
njn3e986b22004-11-30 10:43:45 +0000362
363</sect2>
364
365
366
367<sect2 id="mc-manual.uninitvals"
368 xreflabel="Use of uninitialised values">
369<title>Use of uninitialised values</title>
370
371<para>For example:</para>
372<programlisting><![CDATA[
373Conditional jump or move depends on uninitialised value(s)
374 at 0x402DFA94: _IO_vfprintf (_itoa.h:49)
375 by 0x402E8476: _IO_printf (printf.c:36)
376 by 0x8048472: main (tests/manuel1.c:8)
njn3e986b22004-11-30 10:43:45 +0000377]]></programlisting>
378
de03e0e7c2005-12-03 23:02:33 +0000379<para>An uninitialised-value use error is reported when your program
380uses a value which hasn't been initialised -- in other words, is
381undefined. Here, the undefined value is used somewhere inside the
382printf() machinery of the C library. This error was reported when
383running the following small program:</para>
njn3e986b22004-11-30 10:43:45 +0000384<programlisting><![CDATA[
385int main()
386{
387 int x;
388 printf ("x = %d\n", x);
389}]]></programlisting>
390
de03e0e7c2005-12-03 23:02:33 +0000391<para>It is important to understand that your program can copy around
392junk (uninitialised) data as much as it likes. Memcheck observes this
393and keeps track of the data, but does not complain. A complaint is
394issued only when your program attempts to make use of uninitialised
395data. In this example, x is uninitialised. Memcheck observes the value
396being passed to <literal>_IO_printf</literal> and thence to
njn3e986b22004-11-30 10:43:45 +0000397<literal>_IO_vfprintf</literal>, but makes no comment. However,
sewardj08e31e22007-05-23 21:58:33 +0000398<literal>_IO_vfprintf</literal> has to examine the value of
399x so it can turn it into the
de03e0e7c2005-12-03 23:02:33 +0000400corresponding ASCII string, and it is at this point that Memcheck
401complains.</para>
njn3e986b22004-11-30 10:43:45 +0000402
403<para>Sources of uninitialised data tend to be:</para>
404<itemizedlist>
405 <listitem>
de03e0e7c2005-12-03 23:02:33 +0000406 <para>Local variables in procedures which have not been initialised,
407 as in the example above.</para>
njn3e986b22004-11-30 10:43:45 +0000408 </listitem>
409 <listitem>
de03e0e7c2005-12-03 23:02:33 +0000410 <para>The contents of malloc'd blocks, before you write something
411 there. In C++, the new operator is a wrapper round malloc, so if
412 you create an object with new, its fields will be uninitialised
sewardj08e31e22007-05-23 21:58:33 +0000413 until you (or the constructor) fill them in.</para>
njn3e986b22004-11-30 10:43:45 +0000414 </listitem>
415</itemizedlist>
416
sewardjcd0f2bd2008-05-04 23:06:28 +0000417<para>To see information on the sources of uninitialised data in your
418program, use the <option>--track-origins=yes</option> flag. This
419makes Memcheck run more slowly, but can make it much easier to track down
420the root causes of uninitialised value errors.</para>
421
njn3e986b22004-11-30 10:43:45 +0000422</sect2>
423
424
425
426<sect2 id="mc-manual.badfrees" xreflabel="Illegal frees">
427<title>Illegal frees</title>
428
429<para>For example:</para>
430<programlisting><![CDATA[
431Invalid free()
432 at 0x4004FFDF: free (vg_clientmalloc.c:577)
433 by 0x80484C7: main (tests/doublefree.c:10)
njn21f91952005-03-12 22:14:42 +0000434 Address 0x3807F7B4 is 0 bytes inside a block of size 177 free'd
njn3e986b22004-11-30 10:43:45 +0000435 at 0x4004FFDF: free (vg_clientmalloc.c:577)
436 by 0x80484C7: main (tests/doublefree.c:10)
njn3e986b22004-11-30 10:43:45 +0000437]]></programlisting>
438
de03e0e7c2005-12-03 23:02:33 +0000439<para>Memcheck keeps track of the blocks allocated by your program with
440malloc/new, so it can know exactly whether or not the argument to
441free/delete is legitimate or not. Here, this test program has freed the
442same block twice. As with the illegal read/write errors, Memcheck
443attempts to make sense of the address free'd. If, as here, the address
444is one which has previously been freed, you wil be told that -- making
445duplicate frees of the same block easy to spot.</para>
njn3e986b22004-11-30 10:43:45 +0000446
447</sect2>
448
449
450<sect2 id="mc-manual.rudefn"
451 xreflabel="When a block is freed with an inappropriate deallocation
452function">
453<title>When a block is freed with an inappropriate deallocation
454function</title>
455
456<para>In the following example, a block allocated with
de03e0e7c2005-12-03 23:02:33 +0000457<function>new[]</function> has wrongly been deallocated with
458<function>free</function>:</para>
njn3e986b22004-11-30 10:43:45 +0000459<programlisting><![CDATA[
460Mismatched free() / delete / delete []
461 at 0x40043249: free (vg_clientfuncs.c:171)
462 by 0x4102BB4E: QGArray::~QGArray(void) (tools/qgarray.cpp:149)
463 by 0x4C261C41: PptDoc::~PptDoc(void) (include/qmemarray.h:60)
464 by 0x4C261F0E: PptXml::~PptXml(void) (pptxml.cc:44)
njn21f91952005-03-12 22:14:42 +0000465 Address 0x4BB292A8 is 0 bytes inside a block of size 64 alloc'd
sewardj08e31e22007-05-23 21:58:33 +0000466 at 0x4004318C: operator new[](unsigned int) (vg_clientfuncs.c:152)
njn3e986b22004-11-30 10:43:45 +0000467 by 0x4C21BC15: KLaola::readSBStream(int) const (klaola.cc:314)
468 by 0x4C21C155: KLaola::stream(KLaola::OLENode const *) (klaola.cc:416)
469 by 0x4C21788F: OLEFilter::convert(QCString const &) (olefilter.cc:272)
470]]></programlisting>
471
de03e0e7c2005-12-03 23:02:33 +0000472<para>In <literal>C++</literal> it's important to deallocate memory in a
473way compatible with how it was allocated. The deal is:</para>
njn3e986b22004-11-30 10:43:45 +0000474<itemizedlist>
475 <listitem>
476 <para>If allocated with
de03e0e7c2005-12-03 23:02:33 +0000477 <function>malloc</function>,
478 <function>calloc</function>,
479 <function>realloc</function>,
480 <function>valloc</function> or
481 <function>memalign</function>, you must
482 deallocate with <function>free</function>.</para>
njn3e986b22004-11-30 10:43:45 +0000483 </listitem>
484 <listitem>
de03e0e7c2005-12-03 23:02:33 +0000485 <para>If allocated with <function>new[]</function>, you must
486 deallocate with <function>delete[]</function>.</para>
njn3e986b22004-11-30 10:43:45 +0000487 </listitem>
488 <listitem>
de03e0e7c2005-12-03 23:02:33 +0000489 <para>If allocated with <function>new</function>, you must deallocate
490 with <function>delete</function>.</para>
njn3e986b22004-11-30 10:43:45 +0000491 </listitem>
492</itemizedlist>
493
de03e0e7c2005-12-03 23:02:33 +0000494<para>The worst thing is that on Linux apparently it doesn't matter if
sewardj08e31e22007-05-23 21:58:33 +0000495you do mix these up, but the same program may then crash on a
496different platform, Solaris for example. So it's best to fix it
497properly. According to the KDE folks "it's amazing how many C++
498programmers don't know this".</para>
njn3e986b22004-11-30 10:43:45 +0000499
sewardj08e31e22007-05-23 21:58:33 +0000500<para>The reason behind the requirement is as follows. In some C++
501implementations, <function>delete[]</function> must be used for
502objects allocated by <function>new[]</function> because the compiler
503stores the size of the array and the pointer-to-member to the
504destructor of the array's content just before the pointer actually
505returned. This implies a variable-sized overhead in what's returned
506by <function>new</function> or <function>new[]</function>.</para>
de03e0e7c2005-12-03 23:02:33 +0000507
njn3e986b22004-11-30 10:43:45 +0000508</sect2>
509
510
511
512<sect2 id="mc-manual.badperm"
513 xreflabel="Passing system call parameters with
514 inadequate read/write permissions">
515<title>Passing system call parameters with inadequate read/write
516permissions</title>
517
sewardj8d9fec52005-11-15 20:56:23 +0000518<para>Memcheck checks all parameters to system calls:
njnc4fcca32004-12-01 00:02:36 +0000519<itemizedlist>
de03e0e7c2005-12-03 23:02:33 +0000520 <listitem>
521 <para>It checks all the direct parameters themselves.</para>
522 </listitem>
523 <listitem>
524 <para>Also, if a system call needs to read from a buffer provided by
sewardj33878892007-11-17 09:43:25 +0000525 your program, Memcheck checks that the entire buffer is addressable
de03e0e7c2005-12-03 23:02:33 +0000526 and has valid data, ie, it is readable.</para>
527 </listitem>
528 <listitem>
529 <para>Also, if the system call needs to write to a user-supplied
sewardj33878892007-11-17 09:43:25 +0000530 buffer, Memcheck checks that the buffer is addressable.</para>
de03e0e7c2005-12-03 23:02:33 +0000531 </listitem>
njnc4fcca32004-12-01 00:02:36 +0000532</itemizedlist>
533</para>
njn3e986b22004-11-30 10:43:45 +0000534
njnc4fcca32004-12-01 00:02:36 +0000535<para>After the system call, Memcheck updates its tracked information to
de03e0e7c2005-12-03 23:02:33 +0000536precisely reflect any changes in memory permissions caused by the system
537call.</para>
njn3e986b22004-11-30 10:43:45 +0000538
njnc4fcca32004-12-01 00:02:36 +0000539<para>Here's an example of two system calls with invalid parameters:</para>
njn3e986b22004-11-30 10:43:45 +0000540<programlisting><![CDATA[
njn62ad73d2005-08-15 04:26:13 +0000541 #include <stdlib.h>
542 #include <unistd.h>
njnc4fcca32004-12-01 00:02:36 +0000543 int main( void )
544 {
545 char* arr = malloc(10);
546 int* arr2 = malloc(sizeof(int));
547 write( 1 /* stdout */, arr, 10 );
548 exit(arr2[0]);
549 }
njn3e986b22004-11-30 10:43:45 +0000550]]></programlisting>
551
njnc4fcca32004-12-01 00:02:36 +0000552<para>You get these complaints ...</para>
553<programlisting><![CDATA[
554 Syscall param write(buf) points to uninitialised byte(s)
555 at 0x25A48723: __write_nocancel (in /lib/tls/libc-2.3.3.so)
556 by 0x259AFAD3: __libc_start_main (in /lib/tls/libc-2.3.3.so)
557 by 0x8048348: (within /auto/homes/njn25/grind/head4/a.out)
558 Address 0x25AB8028 is 0 bytes inside a block of size 10 alloc'd
559 at 0x259852B0: malloc (vg_replace_malloc.c:130)
560 by 0x80483F1: main (a.c:5)
561
562 Syscall param exit(error_code) contains uninitialised byte(s)
563 at 0x25A21B44: __GI__exit (in /lib/tls/libc-2.3.3.so)
564 by 0x8048426: main (a.c:8)
565]]></programlisting>
566
de03e0e7c2005-12-03 23:02:33 +0000567<para>... because the program has (a) tried to write uninitialised junk
568from the malloc'd block to the standard output, and (b) passed an
569uninitialised value to <function>exit</function>. Note that the first
570error refers to the memory pointed to by
571<computeroutput>buf</computeroutput> (not
572<computeroutput>buf</computeroutput> itself), but the second error
sewardj08e31e22007-05-23 21:58:33 +0000573refers directly to <computeroutput>exit</computeroutput>'s argument
574<computeroutput>arr2[0]</computeroutput>.</para>
njn3e986b22004-11-30 10:43:45 +0000575
576</sect2>
577
578
579<sect2 id="mc-manual.overlap"
580 xreflabel="Overlapping source and destination blocks">
581<title>Overlapping source and destination blocks</title>
582
583<para>The following C library functions copy some data from one
584memory block to another (or something similar):
de03e0e7c2005-12-03 23:02:33 +0000585<function>memcpy()</function>,
586<function>strcpy()</function>,
587<function>strncpy()</function>,
588<function>strcat()</function>,
589<function>strncat()</function>.
590The blocks pointed to by their <computeroutput>src</computeroutput> and
591<computeroutput>dst</computeroutput> pointers aren't allowed to overlap.
592Memcheck checks for this.</para>
njn3e986b22004-11-30 10:43:45 +0000593
594<para>For example:</para>
595<programlisting><![CDATA[
596==27492== Source and destination overlap in memcpy(0xbffff294, 0xbffff280, 21)
597==27492== at 0x40026CDC: memcpy (mc_replace_strmem.c:71)
598==27492== by 0x804865A: main (overlap.c:40)
njn3e986b22004-11-30 10:43:45 +0000599]]></programlisting>
600
de03e0e7c2005-12-03 23:02:33 +0000601<para>You don't want the two blocks to overlap because one of them could
sewardj08e31e22007-05-23 21:58:33 +0000602get partially overwritten by the copying.</para>
njn3e986b22004-11-30 10:43:45 +0000603
njnccad0b82005-07-19 00:48:55 +0000604<para>You might think that Memcheck is being overly pedantic reporting
de03e0e7c2005-12-03 23:02:33 +0000605this in the case where <computeroutput>dst</computeroutput> is less than
606<computeroutput>src</computeroutput>. For example, the obvious way to
607implement <function>memcpy()</function> is by copying from the first
608byte to the last. However, the optimisation guides of some
609architectures recommend copying from the last byte down to the first.
610Also, some implementations of <function>memcpy()</function> zero
611<computeroutput>dst</computeroutput> before copying, because zeroing the
612destination's cache line(s) can improve performance.</para>
njnccad0b82005-07-19 00:48:55 +0000613
sewardj08e31e22007-05-23 21:58:33 +0000614<para>In addition, for many of these functions, the POSIX standards
615have wording along the lines "If copying takes place between objects
616that overlap, the behavior is undefined." Hence overlapping copies
617violate the standard.</para>
618
de03e0e7c2005-12-03 23:02:33 +0000619<para>The moral of the story is: if you want to write truly portable
620code, don't make any assumptions about the language
621implementation.</para>
njnccad0b82005-07-19 00:48:55 +0000622
njn3e986b22004-11-30 10:43:45 +0000623</sect2>
624
625
njnab5b7142005-08-16 02:20:17 +0000626<sect2 id="mc-manual.leaks" xreflabel="Memory leak detection">
627<title>Memory leak detection</title>
628
de03e0e7c2005-12-03 23:02:33 +0000629<para>Memcheck keeps track of all memory blocks issued in response to
630calls to malloc/calloc/realloc/new. So when the program exits, it knows
631which blocks have not been freed.
njnab5b7142005-08-16 02:20:17 +0000632</para>
633
de03e0e7c2005-12-03 23:02:33 +0000634<para>If <option>--leak-check</option> is set appropriately, for each
635remaining block, Memcheck scans the entire address space of the process,
636looking for pointers to the block. Each block fits into one of the
637three following categories.</para>
njnab5b7142005-08-16 02:20:17 +0000638
639<itemizedlist>
640
641 <listitem>
de03e0e7c2005-12-03 23:02:33 +0000642 <para>Still reachable: A pointer to the start of the block is found.
643 This usually indicates programming sloppiness. Since the block is
644 still pointed at, the programmer could, at least in principle, free
645 it before program exit. Because these are very common and arguably
njnab5b7142005-08-16 02:20:17 +0000646 not a problem, Memcheck won't report such blocks unless
de03e0e7c2005-12-03 23:02:33 +0000647 <option>--show-reachable=yes</option> is specified.</para>
njnab5b7142005-08-16 02:20:17 +0000648 </listitem>
649
650 <listitem>
de03e0e7c2005-12-03 23:02:33 +0000651 <para>Possibly lost, or "dubious": A pointer to the interior of the
652 block is found. The pointer might originally have pointed to the
653 start and have been moved along, or it might be entirely unrelated.
654 Memcheck deems such a block as "dubious", because it's unclear
655 whether or not a pointer to it still exists.</para>
njnab5b7142005-08-16 02:20:17 +0000656 </listitem>
657
658 <listitem>
de03e0e7c2005-12-03 23:02:33 +0000659 <para>Definitely lost, or "leaked": The worst outcome is that no
660 pointer to the block can be found. The block is classified as
661 "leaked", because the programmer could not possibly have freed it at
662 program exit, since no pointer to it exists. This is likely a
663 symptom of having lost the pointer at some earlier point in the
664 program.</para>
njnab5b7142005-08-16 02:20:17 +0000665 </listitem>
666
667</itemizedlist>
668
de03e0e7c2005-12-03 23:02:33 +0000669<para>For each block mentioned, Memcheck will also tell you where the
670block was allocated. It cannot tell you how or why the pointer to a
671leaked block has been lost; you have to work that out for yourself. In
672general, you should attempt to ensure your programs do not have any
673leaked or dubious blocks at exit.</para>
njnab5b7142005-08-16 02:20:17 +0000674
675<para>For example:</para>
676<programlisting><![CDATA[
6778 bytes in 1 blocks are definitely lost in loss record 1 of 14
678 at 0x........: malloc (vg_replace_malloc.c:...)
679 by 0x........: mk (leak-tree.c:11)
680 by 0x........: main (leak-tree.c:39)
681
sewardj8d9fec52005-11-15 20:56:23 +000068288 (8 direct, 80 indirect) bytes in 1 blocks are definitely lost
683 in loss record 13 of 14
njnab5b7142005-08-16 02:20:17 +0000684 at 0x........: malloc (vg_replace_malloc.c:...)
685 by 0x........: mk (leak-tree.c:11)
686 by 0x........: main (leak-tree.c:25)
687]]></programlisting>
688
de03e0e7c2005-12-03 23:02:33 +0000689<para>The first message describes a simple case of a single 8 byte block
690that has been definitely lost. The second case mentions both "direct"
691and "indirect" leaks. The distinction is that a direct leak is a block
692which has no pointers to it. An indirect leak is a block which is only
693pointed to by other leaked blocks. Both kinds of leak are bad.</para>
njnab5b7142005-08-16 02:20:17 +0000694
de03e0e7c2005-12-03 23:02:33 +0000695<para>The precise area of memory in which Memcheck searches for pointers
sewardj08e31e22007-05-23 21:58:33 +0000696is: all naturally-aligned machine-word-sized words found in memory
697that Memcheck's records indicate is both accessible and initialised.
698</para>
njnab5b7142005-08-16 02:20:17 +0000699
700</sect2>
701
njn3e986b22004-11-30 10:43:45 +0000702</sect1>
703
704
705
njn62ad73d2005-08-15 04:26:13 +0000706<sect1 id="mc-manual.suppfiles" xreflabel="Writing suppression files">
707<title>Writing suppression files</title>
njn3e986b22004-11-30 10:43:45 +0000708
709<para>The basic suppression format is described in
710<xref linkend="manual-core.suppress"/>.</para>
711
sewardj08e31e22007-05-23 21:58:33 +0000712<para>The suppression-type (second) line should have the form:</para>
njn3e986b22004-11-30 10:43:45 +0000713<programlisting><![CDATA[
714Memcheck:suppression_type]]></programlisting>
715
njn3e986b22004-11-30 10:43:45 +0000716<para>The Memcheck suppression types are as follows:</para>
717
718<itemizedlist>
719 <listitem>
de03e0e7c2005-12-03 23:02:33 +0000720 <para><varname>Value1</varname>,
721 <varname>Value2</varname>,
722 <varname>Value4</varname>,
723 <varname>Value8</varname>,
724 <varname>Value16</varname>,
njn3e986b22004-11-30 10:43:45 +0000725 meaning an uninitialised-value error when
726 using a value of 1, 2, 4, 8 or 16 bytes.</para>
727 </listitem>
728
729 <listitem>
sewardj08e31e22007-05-23 21:58:33 +0000730 <para><varname>Cond</varname> (or its old
de03e0e7c2005-12-03 23:02:33 +0000731 name, <varname>Value0</varname>), meaning use
njn3e986b22004-11-30 10:43:45 +0000732 of an uninitialised CPU condition code.</para>
733 </listitem>
734
735 <listitem>
sewardj08e31e22007-05-23 21:58:33 +0000736 <para><varname>Addr1</varname>,
de03e0e7c2005-12-03 23:02:33 +0000737 <varname>Addr2</varname>,
738 <varname>Addr4</varname>,
739 <varname>Addr8</varname>,
740 <varname>Addr16</varname>,
njn3e986b22004-11-30 10:43:45 +0000741 meaning an invalid address during a
742 memory access of 1, 2, 4, 8 or 16 bytes respectively.</para>
743 </listitem>
744
745 <listitem>
sewardj08e31e22007-05-23 21:58:33 +0000746 <para><varname>Jump</varname>, meaning an
njn718d3b12006-12-16 00:54:12 +0000747 jump to an unaddressable location error.</para>
748 </listitem>
749
750 <listitem>
sewardj08e31e22007-05-23 21:58:33 +0000751 <para><varname>Param</varname>, meaning an
njn3e986b22004-11-30 10:43:45 +0000752 invalid system call parameter error.</para>
753 </listitem>
754
755 <listitem>
sewardj08e31e22007-05-23 21:58:33 +0000756 <para><varname>Free</varname>, meaning an
njn3e986b22004-11-30 10:43:45 +0000757 invalid or mismatching free.</para>
758 </listitem>
759
760 <listitem>
sewardj08e31e22007-05-23 21:58:33 +0000761 <para><varname>Overlap</varname>, meaning a
njn3e986b22004-11-30 10:43:45 +0000762 <computeroutput>src</computeroutput> /
763 <computeroutput>dst</computeroutput> overlap in
de03e0e7c2005-12-03 23:02:33 +0000764 <function>memcpy()</function> or a similar function.</para>
njn3e986b22004-11-30 10:43:45 +0000765 </listitem>
766
767 <listitem>
sewardj08e31e22007-05-23 21:58:33 +0000768 <para><varname>Leak</varname>, meaning
njn62ad73d2005-08-15 04:26:13 +0000769 a memory leak.</para>
njn3e986b22004-11-30 10:43:45 +0000770 </listitem>
771
772</itemizedlist>
773
sewardj08e31e22007-05-23 21:58:33 +0000774<para><computeroutput>Param</computeroutput> errors have an extra
775information line at this point, which is the name of the offending
776system call parameter. No other error kinds have this extra
de03e0e7c2005-12-03 23:02:33 +0000777line.</para>
njn3e986b22004-11-30 10:43:45 +0000778
de03e0e7c2005-12-03 23:02:33 +0000779<para>The first line of the calling context: for Value and Addr errors,
780it is either the name of the function in which the error occurred, or,
781failing that, the full path of the .so file or executable containing the
782error location. For Free errors, is the name of the function doing the
783freeing (eg, <function>free</function>,
784<function>__builtin_vec_delete</function>, etc). For Overlap errors, is
785the name of the function with the overlapping arguments (eg.
786<function>memcpy()</function>, <function>strcpy()</function>,
787etc).</para>
njn3e986b22004-11-30 10:43:45 +0000788
789<para>Lastly, there's the rest of the calling context.</para>
790
791</sect1>
792
793
794
795<sect1 id="mc-manual.machine"
796 xreflabel="Details of Memcheck's checking machinery">
797<title>Details of Memcheck's checking machinery</title>
798
799<para>Read this section if you want to know, in detail, exactly
800what and how Memcheck is checking.</para>
801
802
803<sect2 id="mc-manual.value" xreflabel="Valid-value (V) bit">
804<title>Valid-value (V) bits</title>
805
de03e0e7c2005-12-03 23:02:33 +0000806<para>It is simplest to think of Memcheck implementing a synthetic CPU
807which is identical to a real CPU, except for one crucial detail. Every
808bit (literally) of data processed, stored and handled by the real CPU
809has, in the synthetic CPU, an associated "valid-value" bit, which says
810whether or not the accompanying bit has a legitimate value. In the
811discussions which follow, this bit is referred to as the V (valid-value)
njn3e986b22004-11-30 10:43:45 +0000812bit.</para>
813
de03e0e7c2005-12-03 23:02:33 +0000814<para>Each byte in the system therefore has a 8 V bits which follow it
815wherever it goes. For example, when the CPU loads a word-size item (4
816bytes) from memory, it also loads the corresponding 32 V bits from a
817bitmap which stores the V bits for the process' entire address space.
818If the CPU should later write the whole or some part of that value to
819memory at a different address, the relevant V bits will be stored back
820in the V-bit bitmap.</para>
njn3e986b22004-11-30 10:43:45 +0000821
de03e0e7c2005-12-03 23:02:33 +0000822<para>In short, each bit in the system has an associated V bit, which
823follows it around everywhere, even inside the CPU. Yes, all the CPU's
824registers (integer, floating point, vector and condition registers) have
825their own V bit vectors.</para>
njn3e986b22004-11-30 10:43:45 +0000826
de03e0e7c2005-12-03 23:02:33 +0000827<para>Copying values around does not cause Memcheck to check for, or
828report on, errors. However, when a value is used in a way which might
829conceivably affect the outcome of your program's computation, the
830associated V bits are immediately checked. If any of these indicate
831that the value is undefined, an error is reported.</para>
njn3e986b22004-11-30 10:43:45 +0000832
833<para>Here's an (admittedly nonsensical) example:</para>
834<programlisting><![CDATA[
835int i, j;
836int a[10], b[10];
837for ( i = 0; i < 10; i++ ) {
838 j = a[i];
839 b[i] = j;
840}]]></programlisting>
841
de03e0e7c2005-12-03 23:02:33 +0000842<para>Memcheck emits no complaints about this, since it merely copies
843uninitialised values from <varname>a[]</varname> into
sewardj08e31e22007-05-23 21:58:33 +0000844<varname>b[]</varname>, and doesn't use them in a way which could
845affect the behaviour of the program. However, if
de03e0e7c2005-12-03 23:02:33 +0000846the loop is changed to:</para>
njn3e986b22004-11-30 10:43:45 +0000847<programlisting><![CDATA[
848for ( i = 0; i < 10; i++ ) {
849 j += a[i];
850}
851if ( j == 77 )
852 printf("hello there\n");
853]]></programlisting>
854
sewardj08e31e22007-05-23 21:58:33 +0000855<para>then Memcheck will complain, at the
de03e0e7c2005-12-03 23:02:33 +0000856<computeroutput>if</computeroutput>, that the condition depends on
857uninitialised values. Note that it <command>doesn't</command> complain
858at the <varname>j += a[i];</varname>, since at that point the
859undefinedness is not "observable". It's only when a decision has to be
860made as to whether or not to do the <function>printf</function> -- an
861observable action of your program -- that Memcheck complains.</para>
njn3e986b22004-11-30 10:43:45 +0000862
de03e0e7c2005-12-03 23:02:33 +0000863<para>Most low level operations, such as adds, cause Memcheck to use the
864V bits for the operands to calculate the V bits for the result. Even if
865the result is partially or wholly undefined, it does not
njn62ad73d2005-08-15 04:26:13 +0000866complain.</para>
njn3e986b22004-11-30 10:43:45 +0000867
de03e0e7c2005-12-03 23:02:33 +0000868<para>Checks on definedness only occur in three places: when a value is
869used to generate a memory address, when control flow decision needs to
sewardj08e31e22007-05-23 21:58:33 +0000870be made, and when a system call is detected, Memcheck checks definedness
de03e0e7c2005-12-03 23:02:33 +0000871of parameters as required.</para>
njn3e986b22004-11-30 10:43:45 +0000872
873<para>If a check should detect undefinedness, an error message is
de03e0e7c2005-12-03 23:02:33 +0000874issued. The resulting value is subsequently regarded as well-defined.
sewardj08e31e22007-05-23 21:58:33 +0000875To do otherwise would give long chains of error messages. In other
876words, once Memcheck reports an undefined value error, it tries to
877avoid reporting further errors derived from that same undefined
878value.</para>
njn3e986b22004-11-30 10:43:45 +0000879
de03e0e7c2005-12-03 23:02:33 +0000880<para>This sounds overcomplicated. Why not just check all reads from
881memory, and complain if an undefined value is loaded into a CPU
882register? Well, that doesn't work well, because perfectly legitimate C
883programs routinely copy uninitialised values around in memory, and we
884don't want endless complaints about that. Here's the canonical example.
885Consider a struct like this:</para>
njn3e986b22004-11-30 10:43:45 +0000886<programlisting><![CDATA[
887struct S { int x; char c; };
888struct S s1, s2;
889s1.x = 42;
890s1.c = 'z';
891s2 = s1;
892]]></programlisting>
893
de03e0e7c2005-12-03 23:02:33 +0000894<para>The question to ask is: how large is <varname>struct S</varname>,
895in bytes? An <varname>int</varname> is 4 bytes and a
896<varname>char</varname> one byte, so perhaps a <varname>struct
sewardj08e31e22007-05-23 21:58:33 +0000897S</varname> occupies 5 bytes? Wrong. All non-toy compilers we know
de03e0e7c2005-12-03 23:02:33 +0000898of will round the size of <varname>struct S</varname> up to a whole
899number of words, in this case 8 bytes. Not doing this forces compilers
sewardj08e31e22007-05-23 21:58:33 +0000900to generate truly appalling code for accessing arrays of
901<varname>struct S</varname>'s on some architectures.</para>
njn3e986b22004-11-30 10:43:45 +0000902
de03e0e7c2005-12-03 23:02:33 +0000903<para>So <varname>s1</varname> occupies 8 bytes, yet only 5 of them will
904be initialised. For the assignment <varname>s2 = s1</varname>, gcc
905generates code to copy all 8 bytes wholesale into <varname>s2</varname>
906without regard for their meaning. If Memcheck simply checked values as
907they came out of memory, it would yelp every time a structure assignment
sewardj08e31e22007-05-23 21:58:33 +0000908like this happened. So the more complicated behaviour described above
de03e0e7c2005-12-03 23:02:33 +0000909is necessary. This allows <literal>gcc</literal> to copy
910<varname>s1</varname> into <varname>s2</varname> any way it likes, and a
911warning will only be emitted if the uninitialised values are later
912used.</para>
njn3e986b22004-11-30 10:43:45 +0000913
njn3e986b22004-11-30 10:43:45 +0000914</sect2>
915
916
917<sect2 id="mc-manual.vaddress" xreflabel=" Valid-address (A) bits">
918<title>Valid-address (A) bits</title>
919
de03e0e7c2005-12-03 23:02:33 +0000920<para>Notice that the previous subsection describes how the validity of
921values is established and maintained without having to say whether the
922program does or does not have the right to access any particular memory
sewardj08e31e22007-05-23 21:58:33 +0000923location. We now consider the latter question.</para>
njn3e986b22004-11-30 10:43:45 +0000924
de03e0e7c2005-12-03 23:02:33 +0000925<para>As described above, every bit in memory or in the CPU has an
926associated valid-value (V) bit. In addition, all bytes in memory, but
927not in the CPU, have an associated valid-address (A) bit. This
928indicates whether or not the program can legitimately read or write that
929location. It does not give any indication of the validity or the data
930at that location -- that's the job of the V bits -- only whether or not
931the location may be accessed.</para>
njn3e986b22004-11-30 10:43:45 +0000932
de03e0e7c2005-12-03 23:02:33 +0000933<para>Every time your program reads or writes memory, Memcheck checks
934the A bits associated with the address. If any of them indicate an
935invalid address, an error is emitted. Note that the reads and writes
936themselves do not change the A bits, only consult them.</para>
njn3e986b22004-11-30 10:43:45 +0000937
njn62ad73d2005-08-15 04:26:13 +0000938<para>So how do the A bits get set/cleared? Like this:</para>
njn3e986b22004-11-30 10:43:45 +0000939
940<itemizedlist>
941 <listitem>
942 <para>When the program starts, all the global data areas are
943 marked as accessible.</para>
944 </listitem>
945
946 <listitem>
de03e0e7c2005-12-03 23:02:33 +0000947 <para>When the program does malloc/new, the A bits for exactly the
948 area allocated, and not a byte more, are marked as accessible. Upon
949 freeing the area the A bits are changed to indicate
950 inaccessibility.</para>
njn3e986b22004-11-30 10:43:45 +0000951 </listitem>
952
953 <listitem>
de03e0e7c2005-12-03 23:02:33 +0000954 <para>When the stack pointer register (<literal>SP</literal>) moves
955 up or down, A bits are set. The rule is that the area from
956 <literal>SP</literal> up to the base of the stack is marked as
957 accessible, and below <literal>SP</literal> is inaccessible. (If
958 that sounds illogical, bear in mind that the stack grows down, not
959 up, on almost all Unix systems, including GNU/Linux.) Tracking
960 <literal>SP</literal> like this has the useful side-effect that the
961 section of stack used by a function for local variables etc is
962 automatically marked accessible on function entry and inaccessible
963 on exit.</para>
njn3e986b22004-11-30 10:43:45 +0000964 </listitem>
965
966 <listitem>
de03e0e7c2005-12-03 23:02:33 +0000967 <para>When doing system calls, A bits are changed appropriately.
sewardj08e31e22007-05-23 21:58:33 +0000968 For example, <literal>mmap</literal>
969 magically makes files appear in the process'
970 address space, so the A bits must be updated if <literal>mmap</literal>
de03e0e7c2005-12-03 23:02:33 +0000971 succeeds.</para>
njn3e986b22004-11-30 10:43:45 +0000972 </listitem>
973
974 <listitem>
sewardj08e31e22007-05-23 21:58:33 +0000975 <para>Optionally, your program can tell Memcheck about such changes
de03e0e7c2005-12-03 23:02:33 +0000976 explicitly, using the client request mechanism described
977 above.</para>
njn3e986b22004-11-30 10:43:45 +0000978 </listitem>
979
980</itemizedlist>
981
982</sect2>
983
984
985<sect2 id="mc-manual.together" xreflabel="Putting it all together">
986<title>Putting it all together</title>
987
988<para>Memcheck's checking machinery can be summarised as
989follows:</para>
990
991<itemizedlist>
992 <listitem>
de03e0e7c2005-12-03 23:02:33 +0000993 <para>Each byte in memory has 8 associated V (valid-value) bits,
994 saying whether or not the byte has a defined value, and a single A
995 (valid-address) bit, saying whether or not the program currently has
996 the right to read/write that address.</para>
njn3e986b22004-11-30 10:43:45 +0000997 </listitem>
998
999 <listitem>
de03e0e7c2005-12-03 23:02:33 +00001000 <para>When memory is read or written, the relevant A bits are
sewardj08e31e22007-05-23 21:58:33 +00001001 consulted. If they indicate an invalid address, Memcheck emits an
de03e0e7c2005-12-03 23:02:33 +00001002 Invalid read or Invalid write error.</para>
njn3e986b22004-11-30 10:43:45 +00001003 </listitem>
1004
1005 <listitem>
de03e0e7c2005-12-03 23:02:33 +00001006 <para>When memory is read into the CPU's registers, the relevant V
1007 bits are fetched from memory and stored in the simulated CPU. They
1008 are not consulted.</para>
njn3e986b22004-11-30 10:43:45 +00001009 </listitem>
1010
1011 <listitem>
de03e0e7c2005-12-03 23:02:33 +00001012 <para>When a register is written out to memory, the V bits for that
1013 register are written back to memory too.</para>
njn3e986b22004-11-30 10:43:45 +00001014 </listitem>
1015
1016 <listitem>
de03e0e7c2005-12-03 23:02:33 +00001017 <para>When values in CPU registers are used to generate a memory
1018 address, or to determine the outcome of a conditional branch, the V
1019 bits for those values are checked, and an error emitted if any of
1020 them are undefined.</para>
njn3e986b22004-11-30 10:43:45 +00001021 </listitem>
1022
1023 <listitem>
de03e0e7c2005-12-03 23:02:33 +00001024 <para>When values in CPU registers are used for any other purpose,
sewardj08e31e22007-05-23 21:58:33 +00001025 Memcheck computes the V bits for the result, but does not check
de03e0e7c2005-12-03 23:02:33 +00001026 them.</para>
njn3e986b22004-11-30 10:43:45 +00001027 </listitem>
1028
1029 <listitem>
sewardj08e31e22007-05-23 21:58:33 +00001030 <para>Once the V bits for a value in the CPU have been checked, they
de03e0e7c2005-12-03 23:02:33 +00001031 are then set to indicate validity. This avoids long chains of
1032 errors.</para>
njn3e986b22004-11-30 10:43:45 +00001033 </listitem>
1034
1035 <listitem>
sewardj08e31e22007-05-23 21:58:33 +00001036 <para>When values are loaded from memory, Memcheck checks the A bits
de03e0e7c2005-12-03 23:02:33 +00001037 for that location and issues an illegal-address warning if needed.
1038 In that case, the V bits loaded are forced to indicate Valid,
1039 despite the location being invalid.</para>
1040
1041 <para>This apparently strange choice reduces the amount of confusing
1042 information presented to the user. It avoids the unpleasant
1043 phenomenon in which memory is read from a place which is both
sewardj33878892007-11-17 09:43:25 +00001044 unaddressable and contains invalid values, and, as a result, you get
de03e0e7c2005-12-03 23:02:33 +00001045 not only an invalid-address (read/write) error, but also a
1046 potentially large set of uninitialised-value errors, one for every
1047 time the value is used.</para>
1048
1049 <para>There is a hazy boundary case to do with multi-byte loads from
1050 addresses which are partially valid and partially invalid. See
1051 details of the flag <option>--partial-loads-ok</option> for details.
1052 </para>
njn3e986b22004-11-30 10:43:45 +00001053 </listitem>
1054
1055</itemizedlist>
1056
1057
de03e0e7c2005-12-03 23:02:33 +00001058<para>Memcheck intercepts calls to malloc, calloc, realloc, valloc,
1059memalign, free, new, new[], delete and delete[]. The behaviour you get
njn3e986b22004-11-30 10:43:45 +00001060is:</para>
1061
1062<itemizedlist>
1063
1064 <listitem>
sewardj33878892007-11-17 09:43:25 +00001065 <para>malloc/new/new[]: the returned memory is marked as addressable
sewardj08e31e22007-05-23 21:58:33 +00001066 but not having valid values. This means you have to write to it
de03e0e7c2005-12-03 23:02:33 +00001067 before you can read it.</para>
njn3e986b22004-11-30 10:43:45 +00001068 </listitem>
1069
1070 <listitem>
sewardj33878892007-11-17 09:43:25 +00001071 <para>calloc: returned memory is marked both addressable and valid,
sewardj08e31e22007-05-23 21:58:33 +00001072 since calloc clears the area to zero.</para>
njn3e986b22004-11-30 10:43:45 +00001073 </listitem>
1074
1075 <listitem>
de03e0e7c2005-12-03 23:02:33 +00001076 <para>realloc: if the new size is larger than the old, the new
sewardj33878892007-11-17 09:43:25 +00001077 section is addressable but invalid, as with malloc.</para>
njn3e986b22004-11-30 10:43:45 +00001078 </listitem>
1079
1080 <listitem>
de03e0e7c2005-12-03 23:02:33 +00001081 <para>If the new size is smaller, the dropped-off section is marked
sewardj33878892007-11-17 09:43:25 +00001082 as unaddressable. You may only pass to realloc a pointer previously
de03e0e7c2005-12-03 23:02:33 +00001083 issued to you by malloc/calloc/realloc.</para>
njn3e986b22004-11-30 10:43:45 +00001084 </listitem>
1085
1086 <listitem>
de03e0e7c2005-12-03 23:02:33 +00001087 <para>free/delete/delete[]: you may only pass to these functions a
1088 pointer previously issued to you by the corresponding allocation
sewardj08e31e22007-05-23 21:58:33 +00001089 function. Otherwise, Memcheck complains. If the pointer is indeed
sewardj33878892007-11-17 09:43:25 +00001090 valid, Memcheck marks the entire area it points at as unaddressable,
de03e0e7c2005-12-03 23:02:33 +00001091 and places the block in the freed-blocks-queue. The aim is to defer
1092 as long as possible reallocation of this block. Until that happens,
1093 all attempts to access it will elicit an invalid-address error, as
1094 you would hope.</para>
njn3e986b22004-11-30 10:43:45 +00001095 </listitem>
1096
1097</itemizedlist>
1098
1099</sect2>
1100</sect1>
1101
1102
1103
njn3e986b22004-11-30 10:43:45 +00001104<sect1 id="mc-manual.clientreqs" xreflabel="Client requests">
1105<title>Client Requests</title>
1106
1107<para>The following client requests are defined in
njn1d0825f2006-03-27 11:37:07 +00001108<filename>memcheck.h</filename>.
njn3e986b22004-11-30 10:43:45 +00001109See <filename>memcheck.h</filename> for exact details of their
1110arguments.</para>
1111
1112<itemizedlist>
1113
1114 <listitem>
njndbf7ca72006-03-31 11:57:59 +00001115 <para><varname>VALGRIND_MAKE_MEM_NOACCESS</varname>,
1116 <varname>VALGRIND_MAKE_MEM_UNDEFINED</varname> and
1117 <varname>VALGRIND_MAKE_MEM_DEFINED</varname>.
njn3e986b22004-11-30 10:43:45 +00001118 These mark address ranges as completely inaccessible,
1119 accessible but containing undefined data, and accessible and
1120 containing defined data, respectively. Subsequent errors may
1121 have their faulting addresses described in terms of these
1122 blocks. Returns a "block handle". Returns zero when not run
1123 on Valgrind.</para>
1124 </listitem>
1125
1126 <listitem>
njndbf7ca72006-03-31 11:57:59 +00001127 <para><varname>VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE</varname>.
1128 This is just like <varname>VALGRIND_MAKE_MEM_DEFINED</varname> but only
1129 affects those bytes that are already addressable.</para>
1130 </listitem>
1131
1132 <listitem>
de03e0e7c2005-12-03 23:02:33 +00001133 <para><varname>VALGRIND_DISCARD</varname>: At some point you may
1134 want Valgrind to stop reporting errors in terms of the blocks
1135 defined by the previous three macros. To do this, the above macros
1136 return a small-integer "block handle". You can pass this block
1137 handle to <varname>VALGRIND_DISCARD</varname>. After doing so,
1138 Valgrind will no longer be able to relate addressing errors to the
1139 user-defined block associated with the handle. The permissions
1140 settings associated with the handle remain in place; this just
1141 affects how errors are reported, not whether they are reported.
1142 Returns 1 for an invalid handle and 0 for a valid handle (although
1143 passing invalid handles is harmless). Always returns 0 when not run
njn3e986b22004-11-30 10:43:45 +00001144 on Valgrind.</para>
1145 </listitem>
1146
1147 <listitem>
njndbf7ca72006-03-31 11:57:59 +00001148 <para><varname>VALGRIND_CHECK_MEM_IS_ADDRESSABLE</varname> and
1149 <varname>VALGRIND_CHECK_MEM_IS_DEFINED</varname>: check immediately
de03e0e7c2005-12-03 23:02:33 +00001150 whether or not the given address range has the relevant property,
1151 and if not, print an error message. Also, for the convenience of
1152 the client, returns zero if the relevant property holds; otherwise,
1153 the returned value is the address of the first byte for which the
1154 property is not true. Always returns 0 when not run on
1155 Valgrind.</para>
njn3e986b22004-11-30 10:43:45 +00001156 </listitem>
1157
1158 <listitem>
njndbf7ca72006-03-31 11:57:59 +00001159 <para><varname>VALGRIND_CHECK_VALUE_IS_DEFINED</varname>: a quick and easy
1160 way to find out whether Valgrind thinks a particular value
1161 (lvalue, to be precise) is addressable and defined. Prints an error
de03e0e7c2005-12-03 23:02:33 +00001162 message if not. Returns no value.</para>
njn3e986b22004-11-30 10:43:45 +00001163 </listitem>
1164
1165 <listitem>
sewardj08e31e22007-05-23 21:58:33 +00001166 <para><varname>VALGRIND_DO_LEAK_CHECK</varname>: runs the memory
1167 leak detector right now. Is useful for incrementally checking for
1168 leaks between arbitrary places in the program's execution. Returns
1169 no value.</para>
njn3e986b22004-11-30 10:43:45 +00001170 </listitem>
1171
1172 <listitem>
de03e0e7c2005-12-03 23:02:33 +00001173 <para><varname>VALGRIND_COUNT_LEAKS</varname>: fills in the four
1174 arguments with the number of bytes of memory found by the previous
1175 leak check to be leaked, dubious, reachable and suppressed. Again,
1176 useful in test harness code, after calling
1177 <varname>VALGRIND_DO_LEAK_CHECK</varname>.</para>
njn3e986b22004-11-30 10:43:45 +00001178 </listitem>
1179
1180 <listitem>
de03e0e7c2005-12-03 23:02:33 +00001181 <para><varname>VALGRIND_GET_VBITS</varname> and
1182 <varname>VALGRIND_SET_VBITS</varname>: allow you to get and set the
1183 V (validity) bits for an address range. You should probably only
1184 set V bits that you have got with
1185 <varname>VALGRIND_GET_VBITS</varname>. Only for those who really
njn1d0825f2006-03-27 11:37:07 +00001186 know what they are doing.</para>
njn3e986b22004-11-30 10:43:45 +00001187 </listitem>
1188
1189</itemizedlist>
1190
1191</sect1>
sewardjce10c262006-10-05 17:56:14 +00001192
1193
1194
1195
1196<sect1 id="mc-manual.mempools" xreflabel="Memory pools">
1197<title>Memory Pools: describing and working with custom allocators</title>
1198
1199<para>Some programs use custom memory allocators, often for performance
sewardjae0e07b2006-10-06 11:47:01 +00001200reasons. Left to itself, Memcheck is unable to "understand" the
1201behaviour of custom allocation schemes and so may miss errors and
1202leaks in your program. What this section describes is a way to give
1203Memcheck enough of a description of your custom allocator that it can
1204make at least some sense of what is happening.</para>
1205
1206<para>There are many different sorts of custom allocator, so Memcheck
sewardjce10c262006-10-05 17:56:14 +00001207attempts to reason about them using a loose, abstract model. We
1208use the following terminology when describing custom allocation
1209systems:</para>
1210
1211<itemizedlist>
1212 <listitem>
1213 <para>Custom allocation involves a set of independent "memory pools".
1214 </para>
1215 </listitem>
1216 <listitem>
1217 <para>Memcheck's notion of a a memory pool consists of a single "anchor
1218 address" and a set of non-overlapping "chunks" associated with the
1219 anchor address.</para>
1220 </listitem>
1221 <listitem>
1222 <para>Typically a pool's anchor address is the address of a
1223 book-keeping "header" structure.</para>
1224 </listitem>
1225 <listitem>
1226 <para>Typically the pool's chunks are drawn from a contiguous
1227 "superblock" acquired through the system malloc() or mmap().</para>
1228 </listitem>
1229
1230</itemizedlist>
1231
1232<para>Keep in mind that the last two points above say "typically": the
1233Valgrind mempool client request API is intentionally vague about the
1234exact structure of a mempool. There is no specific mention made of
1235headers or superblocks. Nevertheless, the following picture may help
1236elucidate the intention of the terms in the API:</para>
1237
1238<programlisting><![CDATA[
1239 "pool"
1240 (anchor address)
1241 |
1242 v
1243 +--------+---+
1244 | header | o |
1245 +--------+-|-+
1246 |
1247 v superblock
1248 +------+---+--------------+---+------------------+
1249 | |rzB| allocation |rzB| |
1250 +------+---+--------------+---+------------------+
1251 ^ ^
1252 | |
1253 "addr" "addr"+"size"
1254]]></programlisting>
1255
1256<para>
1257Note that the header and the superblock may be contiguous or
1258discontiguous, and there may be multiple superblocks associated with a
1259single header; such variations are opaque to Memcheck. The API
1260only requires that your allocation scheme can present sensible values
1261of "pool", "addr" and "size".</para>
1262
1263<para>
1264Typically, before making client requests related to mempools, a client
1265program will have allocated such a header and superblock for their
1266mempool, and marked the superblock NOACCESS using the
1267<varname>VALGRIND_MAKE_MEM_NOACCESS</varname> client request.</para>
1268
1269<para>
1270When dealing with mempools, the goal is to maintain a particular
1271invariant condition: that Memcheck believes the unallocated portions
1272of the pool's superblock (including redzones) are NOACCESS. To
1273maintain this invariant, the client program must ensure that the
1274superblock starts out in that state; Memcheck cannot make it so, since
1275Memcheck never explicitly learns about the superblock of a pool, only
1276the allocated chunks within the pool.</para>
1277
1278<para>
1279Once the header and superblock for a pool are established and properly
1280marked, there are a number of client requests programs can use to
1281inform Memcheck about changes to the state of a mempool:</para>
1282
1283<itemizedlist>
1284
1285 <listitem>
1286 <para>
1287 <varname>VALGRIND_CREATE_MEMPOOL(pool, rzB, is_zeroed)</varname>:
1288 This request registers the address "pool" as the anchor address
1289 for a memory pool. It also provides a size "rzB", specifying how
1290 large the redzones placed around chunks allocated from the pool
1291 should be. Finally, it provides an "is_zeroed" flag that specifies
1292 whether the pool's chunks are zeroed (more precisely: defined)
1293 when allocated.
1294 </para>
1295 <para>
1296 Upon completion of this request, no chunks are associated with the
1297 pool. The request simply tells Memcheck that the pool exists, so that
1298 subsequent calls can refer to it as a pool.
1299 </para>
1300 </listitem>
1301
1302 <listitem>
1303 <para><varname>VALGRIND_DESTROY_MEMPOOL(pool)</varname>:
1304 This request tells Memcheck that a pool is being torn down. Memcheck
1305 then removes all records of chunks associated with the pool, as well
1306 as its record of the pool's existence. While destroying its records of
1307 a mempool, Memcheck resets the redzones of any live chunks in the pool
1308 to NOACCESS.
1309 </para>
1310 </listitem>
1311
1312 <listitem>
1313 <para><varname>VALGRIND_MEMPOOL_ALLOC(pool, addr, size)</varname>:
1314 This request informs Memcheck that a "size"-byte chunk has been
1315 allocated at "addr", and associates the chunk with the specified
1316 "pool". If the pool was created with nonzero "rzB" redzones, Memcheck
1317 will mark the "rzB" bytes before and after the chunk as NOACCESS. If
1318 the pool was created with the "is_zeroed" flag set, Memcheck will mark
1319 the chunk as DEFINED, otherwise Memcheck will mark the chunk as
1320 UNDEFINED.
1321 </para>
1322 </listitem>
1323
1324 <listitem>
1325 <para><varname>VALGRIND_MEMPOOL_FREE(pool, addr)</varname>:
1326 This request informs Memcheck that the chunk at "addr" should no
1327 longer be considered allocated. Memcheck will mark the chunk
1328 associated with "addr" as NOACCESS, and delete its record of the
1329 chunk's existence.
1330 </para>
1331 </listitem>
1332
1333 <listitem>
1334 <para><varname>VALGRIND_MEMPOOL_TRIM(pool, addr, size)</varname>:
1335 This request "trims" the chunks associated with "pool". The request
1336 only operates on chunks associated with "pool". Trimming is formally
1337 defined as:</para>
1338 <itemizedlist>
1339 <listitem>
1340 <para> All chunks entirely inside the range [addr,addr+size) are
1341 preserved.</para>
1342 </listitem>
1343 <listitem>
1344 <para>All chunks entirely outside the range [addr,addr+size) are
1345 discarded, as though <varname>VALGRIND_MEMPOOL_FREE</varname>
1346 was called on them. </para>
1347 </listitem>
1348 <listitem>
1349 <para>All other chunks must intersect with the range
1350 [addr,addr+size); areas outside the intersection are marked as
1351 NOACCESS, as though they had been independently freed with
1352 <varname>VALGRIND_MEMPOOL_FREE</varname>.</para>
1353 </listitem>
1354 </itemizedlist>
1355 <para>This is a somewhat rare request, but can be useful in
1356 implementing the type of mass-free operations common in custom
1357 LIFO allocators.</para>
1358 </listitem>
1359
1360 <listitem>
1361 <para><varname>VALGRIND_MOVE_MEMPOOL(poolA, poolB)</varname>:
1362 This request informs Memcheck that the pool previously anchored at
1363 address "poolA" has moved to anchor address "poolB". This is a rare
1364 request, typically only needed if you realloc() the header of
1365 a mempool.</para>
1366 <para>No memory-status bits are altered by this request.</para>
1367 </listitem>
1368
1369 <listitem>
1370 <para>
1371 <varname>VALGRIND_MEMPOOL_CHANGE(pool, addrA, addrB, size)</varname>:
1372 This request informs Memcheck that the chunk previously allocated at
1373 address "addrA" within "pool" has been moved and/or resized, and should
1374 be changed to cover the region [addrB,addrB+size). This is a rare
1375 request, typically only needed if you realloc() a superblock or wish
1376 to extend a chunk without changing its memory-status bits.
1377 </para>
1378 <para>No memory-status bits are altered by this request.
1379 </para>
1380 </listitem>
1381
1382 <listitem>
1383 <para><varname>VALGRIND_MEMPOOL_EXISTS(pool)</varname>:
1384 This request informs the caller whether or not Memcheck is currently
1385 tracking a mempool at anchor address "pool". It evaluates to 1 when
1386 there is a mempool associated with that address, 0 otherwise. This is a
1387 rare request, only useful in circumstances when client code might have
1388 lost track of the set of active mempools.
1389 </para>
1390 </listitem>
1391
1392</itemizedlist>
1393
sewardj778d7832007-11-22 01:21:56 +00001394</sect1>
1395
1396
1397
1398
1399
1400
1401
1402<sect1 id="mc-manual.mpiwrap" xreflabel="MPI Wrappers">
1403<title>Debugging MPI Parallel Programs with Valgrind</title>
1404
1405<para> Valgrind supports debugging of distributed-memory applications
1406which use the MPI message passing standard. This support consists of a
1407library of wrapper functions for the
1408<computeroutput>PMPI_*</computeroutput> interface. When incorporated
1409into the application's address space, either by direct linking or by
1410<computeroutput>LD_PRELOAD</computeroutput>, the wrappers intercept
1411calls to <computeroutput>PMPI_Send</computeroutput>,
1412<computeroutput>PMPI_Recv</computeroutput>, etc. They then
1413use client requests to inform Valgrind of memory state changes caused
1414by the function being wrapped. This reduces the number of false
1415positives that Memcheck otherwise typically reports for MPI
1416applications.</para>
1417
1418<para>The wrappers also take the opportunity to carefully check
1419size and definedness of buffers passed as arguments to MPI functions, hence
1420detecting errors such as passing undefined data to
1421<computeroutput>PMPI_Send</computeroutput>, or receiving data into a
1422buffer which is too small.</para>
1423
1424<para>Unlike most of the rest of Valgrind, the wrapper library is subject to a
1425BSD-style license, so you can link it into any code base you like.
1426See the top of <computeroutput>auxprogs/libmpiwrap.c</computeroutput>
1427for license details.</para>
1428
1429
1430<sect2 id="mc-manual.mpiwrap.build" xreflabel="Building MPI Wrappers">
1431<title>Building and installing the wrappers</title>
1432
1433<para> The wrapper library will be built automatically if possible.
1434Valgrind's configure script will look for a suitable
1435<computeroutput>mpicc</computeroutput> to build it with. This must be
1436the same <computeroutput>mpicc</computeroutput> you use to build the
1437MPI application you want to debug. By default, Valgrind tries
1438<computeroutput>mpicc</computeroutput>, but you can specify a
1439different one by using the configure-time flag
1440<computeroutput>--with-mpicc=</computeroutput>. Currently the
1441wrappers are only buildable with
1442<computeroutput>mpicc</computeroutput>s which are based on GNU
1443<computeroutput>gcc</computeroutput> or Intel's
1444<computeroutput>icc</computeroutput>.</para>
1445
1446<para>Check that the configure script prints a line like this:</para>
1447
1448<programlisting><![CDATA[
1449checking for usable MPI2-compliant mpicc and mpi.h... yes, mpicc
1450]]></programlisting>
1451
1452<para>If it says <computeroutput>... no</computeroutput>, your
1453<computeroutput>mpicc</computeroutput> has failed to compile and link
1454a test MPI2 program.</para>
1455
1456<para>If the configure test succeeds, continue in the usual way with
1457<computeroutput>make</computeroutput> and <computeroutput>make
1458install</computeroutput>. The final install tree should then contain
1459<computeroutput>libmpiwrap.so</computeroutput>.
1460</para>
1461
1462<para>Compile up a test MPI program (eg, MPI hello-world) and try
1463this:</para>
1464
1465<programlisting><![CDATA[
1466LD_PRELOAD=$prefix/lib/valgrind/<platform>/libmpiwrap.so \
1467 mpirun [args] $prefix/bin/valgrind ./hello
1468]]></programlisting>
1469
1470<para>You should see something similar to the following</para>
1471
1472<programlisting><![CDATA[
1473valgrind MPI wrappers 31901: Active for pid 31901
1474valgrind MPI wrappers 31901: Try MPIWRAP_DEBUG=help for possible options
1475]]></programlisting>
1476
1477<para>repeated for every process in the group. If you do not see
1478these, there is an build/installation problem of some kind.</para>
1479
1480<para> The MPI functions to be wrapped are assumed to be in an ELF
1481shared object with soname matching
1482<computeroutput>libmpi.so*</computeroutput>. This is known to be
1483correct at least for Open MPI and Quadrics MPI, and can easily be
1484changed if required.</para>
1485</sect2>
1486
1487
1488<sect2 id="mc-manual.mpiwrap.gettingstarted"
1489 xreflabel="Getting started with MPI Wrappers">
1490<title>Getting started</title>
1491
1492<para>Compile your MPI application as usual, taking care to link it
1493using the same <computeroutput>mpicc</computeroutput> that your
1494Valgrind build was configured with.</para>
1495
1496<para>
1497Use the following basic scheme to run your application on Valgrind with
1498the wrappers engaged:</para>
1499
1500<programlisting><![CDATA[
1501MPIWRAP_DEBUG=[wrapper-args] \
1502 LD_PRELOAD=$prefix/lib/valgrind/<platform>/libmpiwrap.so \
1503 mpirun [mpirun-args] \
1504 $prefix/bin/valgrind [valgrind-args] \
1505 [application] [app-args]
1506]]></programlisting>
1507
1508<para>As an alternative to
1509<computeroutput>LD_PRELOAD</computeroutput>ing
1510<computeroutput>libmpiwrap.so</computeroutput>, you can simply link it
1511to your application if desired. This should not disturb native
1512behaviour of your application in any way.</para>
1513</sect2>
1514
1515
1516<sect2 id="mc-manual.mpiwrap.controlling"
1517 xreflabel="Controlling the MPI Wrappers">
1518<title>Controlling the wrapper library</title>
1519
1520<para>Environment variable
1521<computeroutput>MPIWRAP_DEBUG</computeroutput> is consulted at
1522startup. The default behaviour is to print a starting banner</para>
1523
1524<programlisting><![CDATA[
1525valgrind MPI wrappers 16386: Active for pid 16386
1526valgrind MPI wrappers 16386: Try MPIWRAP_DEBUG=help for possible options
1527]]></programlisting>
1528
1529<para> and then be relatively quiet.</para>
1530
1531<para>You can give a list of comma-separated options in
1532<computeroutput>MPIWRAP_DEBUG</computeroutput>. These are</para>
1533
1534<itemizedlist>
1535 <listitem>
1536 <para><computeroutput>verbose</computeroutput>:
1537 show entries/exits of all wrappers. Also show extra
1538 debugging info, such as the status of outstanding
1539 <computeroutput>MPI_Request</computeroutput>s resulting
1540 from uncompleted <computeroutput>MPI_Irecv</computeroutput>s.</para>
1541 </listitem>
1542 <listitem>
1543 <para><computeroutput>quiet</computeroutput>:
1544 opposite of <computeroutput>verbose</computeroutput>, only print
1545 anything when the wrappers want
1546 to report a detected programming error, or in case of catastrophic
1547 failure of the wrappers.</para>
1548 </listitem>
1549 <listitem>
1550 <para><computeroutput>warn</computeroutput>:
1551 by default, functions which lack proper wrappers
1552 are not commented on, just silently
1553 ignored. This causes a warning to be printed for each unwrapped
1554 function used, up to a maximum of three warnings per function.</para>
1555 </listitem>
1556 <listitem>
1557 <para><computeroutput>strict</computeroutput>:
1558 print an error message and abort the program if
1559 a function lacking a wrapper is used.</para>
1560 </listitem>
1561</itemizedlist>
1562
1563<para> If you want to use Valgrind's XML output facility
1564(<computeroutput>--xml=yes</computeroutput>), you should pass
1565<computeroutput>quiet</computeroutput> in
1566<computeroutput>MPIWRAP_DEBUG</computeroutput> so as to get rid of any
1567extraneous printing from the wrappers.</para>
1568
1569</sect2>
1570
1571
1572<sect2 id="mc-manual.mpiwrap.limitations"
1573 xreflabel="Abilities and Limitations of MPI Wrappers">
1574<title>Abilities and limitations</title>
1575
1576<sect3 id="mc-manual.mpiwrap.limitations.functions"
1577 xreflabel="Functions">
1578<title>Functions</title>
1579
1580<para>All MPI2 functions except
1581<computeroutput>MPI_Wtick</computeroutput>,
1582<computeroutput>MPI_Wtime</computeroutput> and
1583<computeroutput>MPI_Pcontrol</computeroutput> have wrappers. The
1584first two are not wrapped because they return a
1585<computeroutput>double</computeroutput>, and Valgrind's
1586function-wrap mechanism cannot handle that (it could easily enough be
1587extended to). <computeroutput>MPI_Pcontrol</computeroutput> cannot be
1588wrapped as it has variable arity:
1589<computeroutput>int MPI_Pcontrol(const int level, ...)</computeroutput></para>
1590
1591<para>Most functions are wrapped with a default wrapper which does
1592nothing except complain or abort if it is called, depending on
1593settings in <computeroutput>MPIWRAP_DEBUG</computeroutput> listed
1594above. The following functions have "real", do-something-useful
1595wrappers:</para>
1596
1597<programlisting><![CDATA[
1598PMPI_Send PMPI_Bsend PMPI_Ssend PMPI_Rsend
1599
1600PMPI_Recv PMPI_Get_count
1601
1602PMPI_Isend PMPI_Ibsend PMPI_Issend PMPI_Irsend
1603
1604PMPI_Irecv
1605PMPI_Wait PMPI_Waitall
1606PMPI_Test PMPI_Testall
1607
1608PMPI_Iprobe PMPI_Probe
1609
1610PMPI_Cancel
1611
1612PMPI_Sendrecv
1613
1614PMPI_Type_commit PMPI_Type_free
1615
1616PMPI_Pack PMPI_Unpack
1617
1618PMPI_Bcast PMPI_Gather PMPI_Scatter PMPI_Alltoall
1619PMPI_Reduce PMPI_Allreduce PMPI_Op_create
1620
1621PMPI_Comm_create PMPI_Comm_dup PMPI_Comm_free PMPI_Comm_rank PMPI_Comm_size
1622
1623PMPI_Error_string
1624PMPI_Init PMPI_Initialized PMPI_Finalize
1625]]></programlisting>
1626
1627<para> A few functions such as
1628<computeroutput>PMPI_Address</computeroutput> are listed as
1629<computeroutput>HAS_NO_WRAPPER</computeroutput>. They have no wrapper
1630at all as there is nothing worth checking, and giving a no-op wrapper
1631would reduce performance for no reason.</para>
1632
1633<para> Note that the wrapper library itself can itself generate large
1634numbers of calls to the MPI implementation, especially when walking
1635complex types. The most common functions called are
1636<computeroutput>PMPI_Extent</computeroutput>,
1637<computeroutput>PMPI_Type_get_envelope</computeroutput>,
1638<computeroutput>PMPI_Type_get_contents</computeroutput>, and
1639<computeroutput>PMPI_Type_free</computeroutput>. </para>
1640</sect3>
1641
1642<sect3 id="mc-manual.mpiwrap.limitations.types"
1643 xreflabel="Types">
1644<title>Types</title>
1645
1646<para> MPI-1.1 structured types are supported, and walked exactly.
1647The currently supported combiners are
1648<computeroutput>MPI_COMBINER_NAMED</computeroutput>,
1649<computeroutput>MPI_COMBINER_CONTIGUOUS</computeroutput>,
1650<computeroutput>MPI_COMBINER_VECTOR</computeroutput>,
1651<computeroutput>MPI_COMBINER_HVECTOR</computeroutput>
1652<computeroutput>MPI_COMBINER_INDEXED</computeroutput>,
1653<computeroutput>MPI_COMBINER_HINDEXED</computeroutput> and
1654<computeroutput>MPI_COMBINER_STRUCT</computeroutput>. This should
1655cover all MPI-1.1 types. The mechanism (function
1656<computeroutput>walk_type</computeroutput>) should extend easily to
1657cover MPI2 combiners.</para>
1658
1659<para>MPI defines some named structured types
1660(<computeroutput>MPI_FLOAT_INT</computeroutput>,
1661<computeroutput>MPI_DOUBLE_INT</computeroutput>,
1662<computeroutput>MPI_LONG_INT</computeroutput>,
1663<computeroutput>MPI_2INT</computeroutput>,
1664<computeroutput>MPI_SHORT_INT</computeroutput>,
1665<computeroutput>MPI_LONG_DOUBLE_INT</computeroutput>) which are pairs
1666of some basic type and a C <computeroutput>int</computeroutput>.
1667Unfortunately the MPI specification makes it impossible to look inside
1668these types and see where the fields are. Therefore these wrappers
1669assume the types are laid out as <computeroutput>struct { float val;
1670int loc; }</computeroutput> (for
1671<computeroutput>MPI_FLOAT_INT</computeroutput>), etc, and act
1672accordingly. This appears to be correct at least for Open MPI 1.0.2
1673and for Quadrics MPI.</para>
1674
1675<para>If <computeroutput>strict</computeroutput> is an option specified
1676in <computeroutput>MPIWRAP_DEBUG</computeroutput>, the application
1677will abort if an unhandled type is encountered. Otherwise, the
1678application will print a warning message and continue.</para>
1679
1680<para>Some effort is made to mark/check memory ranges corresponding to
1681arrays of values in a single pass. This is important for performance
1682since asking Valgrind to mark/check any range, no matter how small,
1683carries quite a large constant cost. This optimisation is applied to
1684arrays of primitive types (<computeroutput>double</computeroutput>,
1685<computeroutput>float</computeroutput>,
1686<computeroutput>int</computeroutput>,
1687<computeroutput>long</computeroutput>, <computeroutput>long
1688long</computeroutput>, <computeroutput>short</computeroutput>,
1689<computeroutput>char</computeroutput>, and <computeroutput>long
1690double</computeroutput> on platforms where <computeroutput>sizeof(long
1691double) == 8</computeroutput>). For arrays of all other types, the
1692wrappers handle each element individually and so there can be a very
1693large performance cost.</para>
1694
1695</sect3>
1696
1697</sect2>
1698
1699
1700<sect2 id="mc-manual.mpiwrap.writingwrappers"
1701 xreflabel="Writing new MPI Wrappers">
1702<title>Writing new wrappers</title>
1703
1704<para>
1705For the most part the wrappers are straightforward. The only
1706significant complexity arises with nonblocking receives.</para>
1707
1708<para>The issue is that <computeroutput>MPI_Irecv</computeroutput>
1709states the recv buffer and returns immediately, giving a handle
1710(<computeroutput>MPI_Request</computeroutput>) for the transaction.
1711Later the user will have to poll for completion with
1712<computeroutput>MPI_Wait</computeroutput> etc, and when the
1713transaction completes successfully, the wrappers have to paint the
1714recv buffer. But the recv buffer details are not presented to
1715<computeroutput>MPI_Wait</computeroutput> -- only the handle is. The
1716library therefore maintains a shadow table which associates
1717uncompleted <computeroutput>MPI_Request</computeroutput>s with the
1718corresponding buffer address/count/type. When an operation completes,
1719the table is searched for the associated address/count/type info, and
1720memory is marked accordingly.</para>
1721
1722<para>Access to the table is guarded by a (POSIX pthreads) lock, so as
1723to make the library thread-safe.</para>
1724
1725<para>The table is allocated with
1726<computeroutput>malloc</computeroutput> and never
1727<computeroutput>free</computeroutput>d, so it will show up in leak
1728checks.</para>
1729
1730<para>Writing new wrappers should be fairly easy. The source file is
1731<computeroutput>auxprogs/libmpiwrap.c</computeroutput>. If possible,
1732find an existing wrapper for a function of similar behaviour to the
1733one you want to wrap, and use it as a starting point. The wrappers
1734are organised in sections in the same order as the MPI 1.1 spec, to
1735aid navigation. When adding a wrapper, remember to comment out the
1736definition of the default wrapper in the long list of defaults at the
1737bottom of the file (do not remove it, just comment it out).</para>
1738</sect2>
1739
1740<sect2 id="mc-manual.mpiwrap.whattoexpect"
1741 xreflabel="What to expect with MPI Wrappers">
1742<title>What to expect when using the wrappers</title>
1743
1744<para>The wrappers should reduce Memcheck's false-error rate on MPI
1745applications. Because the wrapping is done at the MPI interface,
1746there will still potentially be a large number of errors reported in
1747the MPI implementation below the interface. The best you can do is
1748try to suppress them.</para>
1749
1750<para>You may also find that the input-side (buffer
1751length/definedness) checks find errors in your MPI use, for example
1752passing too short a buffer to
1753<computeroutput>MPI_Recv</computeroutput>.</para>
1754
1755<para>Functions which are not wrapped may increase the false
1756error rate. A possible approach is to run with
1757<computeroutput>MPI_DEBUG</computeroutput> containing
1758<computeroutput>warn</computeroutput>. This will show you functions
1759which lack proper wrappers but which are nevertheless used. You can
1760then write wrappers for them.
1761</para>
1762
1763<para>A known source of potential false errors are the
1764<computeroutput>PMPI_Reduce</computeroutput> family of functions, when
1765using a custom (user-defined) reduction function. In a reduction
1766operation, each node notionally sends data to a "central point" which
1767uses the specified reduction function to merge the data items into a
1768single item. Hence, in general, data is passed between nodes and fed
1769to the reduction function, but the wrapper library cannot mark the
1770transferred data as initialised before it is handed to the reduction
1771function, because all that happens "inside" the
1772<computeroutput>PMPI_Reduce</computeroutput> call. As a result you
1773may see false positives reported in your reduction function.</para>
1774
1775</sect2>
sewardjce10c262006-10-05 17:56:14 +00001776
1777</sect1>
sewardj778d7832007-11-22 01:21:56 +00001778
1779
1780
1781
1782
njn3e986b22004-11-30 10:43:45 +00001783</chapter>