1 <?xml version="1.0"?> <!-- -*- sgml -*- -->
2 <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
3 "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd"
4 [ <!ENTITY % vg-entities SYSTEM "vg-entities.xml"> %vg-entities; ]>
7 <chapter id="manual-core-adv" xreflabel="Valgrind's core: advanced topics">
8 <title>Using and understanding the Valgrind core: Advanced Topics</title>
10 <para>This chapter describes advanced aspects of the Valgrind core
11 services, which are mostly of interest to power users who wish to
12 customise and modify Valgrind's default behaviours in certain useful
13 ways. The subjects covered are:</para>
16 <listitem><para>The "Client Request" mechanism</para></listitem>
17 <listitem><para>Debugging your program using Valgrind's gdbserver
18 and GDB</para></listitem>
19 <listitem><para>Function Wrapping</para></listitem>
24 <sect1 id="manual-core-adv.clientreq"
25 xreflabel="The Client Request mechanism">
26 <title>The Client Request mechanism</title>
28 <para>Valgrind has a trapdoor mechanism via which the client
29 program can pass all manner of requests and queries to Valgrind
30 and the current tool. Internally, this is used extensively
31 to make various things work, although that's not visible from the
34 <para>For your convenience, a subset of these so-called client
35 requests is provided to allow you to tell Valgrind facts about
36 the behaviour of your program, and also to make queries.
37 In particular, your program can tell Valgrind about things that it
38 otherwise would not know, leading to better results.
41 <para>Clients need to include a header file to make this work.
42 Which header file depends on which client requests you use. Some
43 client requests are handled by the core, and are defined in the
44 header file <filename>valgrind/valgrind.h</filename>. Tool-specific
45 header files are named after the tool, e.g.
46 <filename>valgrind/memcheck.h</filename>. Each tool-specific header file
47 includes <filename>valgrind/valgrind.h</filename> so you don't need to
48 include it in your client if you include a tool-specific header. All header
49 files can be found in the <literal>include/valgrind</literal> directory of
50 wherever Valgrind was installed.</para>
52 <para>The macros in these header files have the magical property
53 that they generate code in-line which Valgrind can spot.
54 However, the code does nothing when not run on Valgrind, so you
55 are not forced to run your program under Valgrind just because you
56 use the macros in this file. Also, you are not required to link your
57 program with any extra supporting libraries.</para>
59 <para>The code added to your binary has negligible performance impact:
60 on x86, amd64, ppc32, ppc64 and ARM, the overhead is 6 simple integer
61 instructions and is probably undetectable except in tight loops.
62 However, if you really wish to compile out the client requests, you
63 can compile with <option>-DNVALGRIND</option> (analogous to
64 <option>-DNDEBUG</option>'s effect on
65 <function>assert</function>).
68 <para>You are encouraged to copy the <filename>valgrind/*.h</filename> headers
69 into your project's include directory, so your program doesn't have a
70 compile-time dependency on Valgrind being installed. The Valgrind headers,
71 unlike most of the rest of the code, are under a BSD-style license so you may
72 include them without worrying about license incompatibility.</para>
74 <para>Here is a brief description of the macros available in
75 <filename>valgrind.h</filename>, which work with more than one
76 tool (see the tool-specific documentation for explanations of the
77 tool-specific macros).</para>
82 <term><command><computeroutput>RUNNING_ON_VALGRIND</computeroutput></command>:</term>
84 <para>Returns 1 if running on Valgrind, 0 if running on the
85 real CPU. If you are running Valgrind on itself, returns the
86 number of layers of Valgrind emulation you're running on.
92 <term><command><computeroutput>VALGRIND_DISCARD_TRANSLATIONS</computeroutput>:</command></term>
94 <para>Discards translations of code in the specified address
95 range. Useful if you are debugging a JIT compiler or some other
96 dynamic code generation system. After this call, attempts to
97 execute code in the invalidated address range will cause
98 Valgrind to make new translations of that code, which is
99 probably the semantics you want. Note that code invalidations
100 are expensive because finding all the relevant translations
101 quickly is very difficult, so try not to call it often.
102 Note that you can be clever about
103 this: you only need to call it when an area which previously
104 contained code is overwritten with new code. You can choose
105 to write code into fresh memory, and just call this
106 occasionally to discard large chunks of old code all at
109 Alternatively, for transparent self-modifying-code support,
110 use<option>--smc-check=all</option>, or run
111 on ppc32/Linux, ppc64/Linux or ARM/Linux.
117 <term><command><computeroutput>VALGRIND_COUNT_ERRORS</computeroutput>:</command></term>
119 <para>Returns the number of errors found so far by Valgrind. Can be
120 useful in test harness code when combined with the
121 <option>--log-fd=-1</option> option; this runs Valgrind silently,
122 but the client program can detect when errors occur. Only useful
123 for tools that report errors, e.g. it's useful for Memcheck, but for
124 Cachegrind it will always return zero because Cachegrind doesn't
125 report errors.</para>
130 <term><command><computeroutput>VALGRIND_MALLOCLIKE_BLOCK</computeroutput>:</command></term>
132 <para>If your program manages its own memory instead of using
133 the standard <function>malloc</function> /
134 <function>new</function> /
135 <function>new[]</function>, tools that track
136 information about heap blocks will not do nearly as good a
137 job. For example, Memcheck won't detect nearly as many
138 errors, and the error messages won't be as informative. To
139 improve this situation, use this macro just after your custom
140 allocator allocates some new memory. See the comments in
141 <filename>valgrind.h</filename> for information on how to use
147 <term><command><computeroutput>VALGRIND_FREELIKE_BLOCK</computeroutput>:</command></term>
149 <para>This should be used in conjunction with
150 <computeroutput>VALGRIND_MALLOCLIKE_BLOCK</computeroutput>.
151 Again, see <filename>valgrind.h</filename> for
152 information on how to use it.</para>
157 <term><command><computeroutput>VALGRIND_RESIZEINPLACE_BLOCK</computeroutput>:</command></term>
159 <para>Informs a Valgrind tool that the size of an allocated block has been
160 modified but not its address. See <filename>valgrind.h</filename> for
161 more information on how to use it.</para>
167 <command><computeroutput>VALGRIND_CREATE_MEMPOOL</computeroutput></command>,
168 <command><computeroutput>VALGRIND_DESTROY_MEMPOOL</computeroutput></command>,
169 <command><computeroutput>VALGRIND_MEMPOOL_ALLOC</computeroutput></command>,
170 <command><computeroutput>VALGRIND_MEMPOOL_FREE</computeroutput></command>,
171 <command><computeroutput>VALGRIND_MOVE_MEMPOOL</computeroutput></command>,
172 <command><computeroutput>VALGRIND_MEMPOOL_CHANGE</computeroutput></command>,
173 <command><computeroutput>VALGRIND_MEMPOOL_EXISTS</computeroutput></command>:
176 <para>These are similar to
177 <computeroutput>VALGRIND_MALLOCLIKE_BLOCK</computeroutput> and
178 <computeroutput>VALGRIND_FREELIKE_BLOCK</computeroutput>
179 but are tailored towards code that uses memory pools. See
180 <xref linkend="mc-manual.mempools"/> for a detailed description.</para>
185 <term><command><computeroutput>VALGRIND_NON_SIMD_CALL[0123]</computeroutput>:</command></term>
187 <para>Executes a function in the client program on the
188 <emphasis>real</emphasis> CPU, not the virtual CPU that Valgrind
189 normally runs code on. The function must take an integer (holding a
190 thread ID) as the first argument and then 0, 1, 2 or 3 more arguments
191 (depending on which client request is used). These are used in various
192 ways internally to Valgrind. They might be useful to client
195 <para><command>Warning:</command> Only use these if you
196 <emphasis>really</emphasis> know what you are doing. They aren't
197 entirely reliable, and can cause Valgrind to crash. See
198 <filename>valgrind.h</filename> for more details.
204 <term><command><computeroutput>VALGRIND_PRINTF(format, ...)</computeroutput>:</command></term>
206 <para>Print a printf-style message to the Valgrind log file. The
207 message is prefixed with the PID between a pair of
208 <computeroutput>**</computeroutput> markers. (Like all client requests,
209 nothing is output if the client program is not running under Valgrind.)
210 Output is not produced until a newline is encountered, or subsequent
211 Valgrind output is printed; this allows you to build up a single line of
212 output over multiple calls. Returns the number of characters output,
213 excluding the PID prefix.</para>
218 <term><command><computeroutput>VALGRIND_PRINTF_BACKTRACE(format, ...)</computeroutput>:</command></term>
220 <para>Like <computeroutput>VALGRIND_PRINTF</computeroutput> (in
221 particular, the return value is identical), but prints a stack backtrace
222 immediately afterwards.</para>
227 <term><command><computeroutput>VALGRIND_MONITOR_COMMAND(command)</computeroutput>:</command></term>
229 <para>Execute the given monitor command (a string).
230 Returns 0 if command is recognised. Returns 1 if command is not recognised.
231 Note that some monitor commands provide access to a functionality
232 also accessible via a specific client request. For example,
233 memcheck leak search can be requested from the client program
234 using VALGRIND_DO_LEAK_CHECK or via the monitor command "leak_search".
235 Note that the syntax of the command string is only verified at
236 run-time. So, if it exists, it is preferable to use a specific
237 client request to have better compile time verifications of the
244 <term><command><computeroutput>VALGRIND_CLO_CHANGE(option)</computeroutput>:</command></term>
246 <para>Changes the value of a dynamically changeable option (a string).
247 See <xref linkend="manual-core.dynopts"/>.
253 <term><command><computeroutput>VALGRIND_STACK_REGISTER(start, end)</computeroutput>:</command></term>
255 <para>Registers a new stack. Informs Valgrind that the memory range
256 between start and end is a unique stack. Returns a stack identifier
257 that can be used with other
258 <computeroutput>VALGRIND_STACK_*</computeroutput> calls.</para>
259 <para>Valgrind will use this information to determine if a change
260 to the stack pointer is an item pushed onto the stack or a change
261 over to a new stack. Use this if you're using a user-level thread
262 package and are noticing crashes in stack trace recording or
263 spurious errors from Valgrind about uninitialized memory
266 <para><command>Warning:</command> Unfortunately, this client request is
267 unreliable and best avoided.</para>
272 <term><command><computeroutput>VALGRIND_STACK_DEREGISTER(id)</computeroutput>:</command></term>
274 <para>Deregisters a previously registered stack. Informs
275 Valgrind that previously registered memory range with stack id
276 <computeroutput>id</computeroutput> is no longer a stack.</para>
278 <para><command>Warning:</command> Unfortunately, this client request is
279 unreliable and best avoided.</para>
284 <term><command><computeroutput>VALGRIND_STACK_CHANGE(id, start, end)</computeroutput>:</command></term>
286 <para>Changes a previously registered stack. Informs
287 Valgrind that the previously registered stack with stack id
288 <computeroutput>id</computeroutput> has changed its start and end
289 values. Use this if your user-level thread package implements
292 <para><command>Warning:</command> Unfortunately, this client request is
293 unreliable and best avoided.</para>
306 <!-- Referenced from both the manual and manpage -->
307 <sect1 id="&vg-gdbserver-id;"
308 xreflabel="&vg-gdbserver-label;">
309 <title>Debugging your program using Valgrind gdbserver and GDB</title>
311 <para>A program running under Valgrind is not executed directly by the CPU.
312 Instead it runs on a synthetic CPU provided by Valgrind. This is why a debugger
313 cannot natively debug your program when it runs on Valgrind.
316 This section describes how GDB can interact with the
317 Valgrind gdbserver to provide a fully debuggable program under
318 Valgrind. Used in this way, GDB also provides an interactive usage of
319 Valgrind core or tool functionalities, including incremental leak search
320 under Memcheck and on-demand Massif snapshot production.
323 <sect2 id="manual-core-adv.gdbserver-simple"
324 xreflabel="gdbserver simple example">
325 <title>Quick Start: debugging in 3 steps</title>
327 <para>The simplest way to get started is to run Valgrind with the
328 flag <option>--vgdb-error=0</option>. Then follow the on-screen
329 directions, which give you the precise commands needed to start GDB
330 and connect it to your program.</para>
332 <para>Otherwise, here's a slightly more verbose overview.</para>
334 <para>If you want to debug a program with GDB when using the Memcheck
335 tool, start Valgrind like this:
337 valgrind --vgdb=yes --vgdb-error=0 prog
340 <para>In another shell, start GDB:
345 <para>Then give the following command to GDB:
347 (gdb) target remote | vgdb
350 <para>You can now debug your program e.g. by inserting a breakpoint
351 and then using the GDB <computeroutput>continue</computeroutput>
354 <para>This quick start information is enough for basic usage of the
355 Valgrind gdbserver. The sections below describe more advanced
356 functionality provided by the combination of Valgrind and GDB. Note
357 that the command line flag <option>--vgdb=yes</option> can be omitted,
358 as this is the default value.
363 <sect2 id="manual-core-adv.gdbserver-concept"
364 xreflabel="gdbserver">
365 <title>Valgrind gdbserver overall organisation</title>
366 <para>The GNU GDB debugger is typically used to debug a process
367 running on the same machine. In this mode, GDB uses system calls to
368 control and query the program being debugged. This works well, but
369 only allows GDB to debug a program running on the same computer.
372 <para>GDB can also debug processes running on a different computer.
373 To achieve this, GDB defines a protocol (that is, a set of query and
374 reply packets) that facilitates fetching the value of memory or
375 registers, setting breakpoints, etc. A gdbserver is an implementation
376 of this "GDB remote debugging" protocol. To debug a process running
377 on a remote computer, a gdbserver (sometimes called a GDB stub)
378 must run at the remote computer side.
381 <para>The Valgrind core provides a built-in gdbserver implementation,
382 which is activated using <option>--vgdb=yes</option>
383 or <option>--vgdb=full</option>. This gdbserver allows the process
384 running on Valgrind's synthetic CPU to be debugged remotely.
385 GDB sends protocol query packets (such as "get register contents") to
386 the Valgrind embedded gdbserver. The gdbserver executes the queries
387 (for example, it will get the register values of the synthetic CPU)
388 and gives the results back to GDB.
391 <para>GDB can use various kinds of channels (TCP/IP, serial line, etc)
392 to communicate with the gdbserver. In the case of Valgrind's
393 gdbserver, communication is done via a pipe and a small helper program
394 called <xref linkend="&vg-vgdb-id;"/>, which acts as an
395 intermediary. If no GDB is in use, vgdb can also be
396 used to send monitor commands to the Valgrind gdbserver from a shell
402 <sect2 id="manual-core-adv.gdbserver-gdb"
403 xreflabel="Connecting GDB to a Valgrind gdbserver">
404 <title>Connecting GDB to a Valgrind gdbserver</title>
405 <para>To debug a program "<filename>prog</filename>" running under
406 Valgrind, you must ensure that the Valgrind gdbserver is activated by
407 specifying either <option>--vgdb=yes</option>
408 or <option>--vgdb=full</option>. A secondary command line option,
409 <option>--vgdb-error=number</option>, can be used to tell the gdbserver
410 only to become active once the specified number of errors have been
411 shown. A value of zero will therefore cause
412 the gdbserver to become active at startup, which allows you to
413 insert breakpoints before starting the run. For example:
415 valgrind --tool=memcheck --vgdb=yes --vgdb-error=0 ./prog
418 <para>The Valgrind gdbserver is invoked at startup
419 and indicates it is waiting for a connection from a GDB:</para>
421 <programlisting><![CDATA[
422 ==2418== Memcheck, a memory error detector
423 ==2418== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
424 ==2418== Using Valgrind-3.14.0.GIT and LibVEX; rerun with -h for copyright info
425 ==2418== Command: ./prog
427 ==2418== (action at startup) vgdb me ...
431 <para>GDB (in another shell) can then be connected to the Valgrind gdbserver.
432 For this, GDB must be started on the program <filename>prog</filename>:
438 <para>You then indicate to GDB that you want to debug a remote target:
440 (gdb) target remote | vgdb
442 GDB then starts a vgdb relay application to communicate with the
443 Valgrind embedded gdbserver:</para>
445 <programlisting><![CDATA[
446 (gdb) target remote | vgdb
447 Remote debugging using | vgdb
448 relaying data between gdb and process 2418
449 Reading symbols from /lib/ld-linux.so.2...done.
450 Reading symbols from /usr/lib/debug/lib/ld-2.11.2.so.debug...done.
451 Loaded symbols for /lib/ld-linux.so.2
452 [Switching to Thread 2418]
453 0x001f2850 in _start () from /lib/ld-linux.so.2
457 <para>Note that vgdb is provided as part of the Valgrind
458 distribution. You do not need to install it separately.</para>
460 <para>If vgdb detects that there are multiple Valgrind gdbservers that
461 can be connected to, it will list all such servers and their PIDs, and
462 then exit. You can then reissue the GDB "target" command, but
463 specifying the PID of the process you want to debug:
466 <programlisting><![CDATA[
467 (gdb) target remote | vgdb
468 Remote debugging using | vgdb
469 no --pid= arg given and multiple valgrind pids found:
470 use --pid=2479 for valgrind --tool=memcheck --vgdb=yes --vgdb-error=0 ./prog
471 use --pid=2481 for valgrind --tool=memcheck --vgdb=yes --vgdb-error=0 ./prog
472 use --pid=2483 for valgrind --vgdb=yes --vgdb-error=0 ./another_prog
473 Remote communication error: Resource temporarily unavailable.
474 (gdb) target remote | vgdb --pid=2479
475 Remote debugging using | vgdb --pid=2479
476 relaying data between gdb and process 2479
477 Reading symbols from /lib/ld-linux.so.2...done.
478 Reading symbols from /usr/lib/debug/lib/ld-2.11.2.so.debug...done.
479 Loaded symbols for /lib/ld-linux.so.2
480 [Switching to Thread 2479]
481 0x001f2850 in _start () from /lib/ld-linux.so.2
485 <para>If you want to use the <option>--multi</option> mode which makes vgdb start in extended-remote mode, set the following in GDB:
488 (gdb) set remote exec-file prog
490 (gdb) target extended-remote | vgdb --multi --vargs -q
492 Temporary breakpoint 1 at 0x24e0
493 Starting program: prog
494 relaying data between gdb and process 2999348
496 Temporary breakpoint 1, 0x000000000010a4a0 in main ()
501 <para>Note that in <option>--multi</option> mode you don't have to
502 start valgrind separately. vgdb will start valgrind for
503 you. vgdb <option>--multi</option> mode is experimental and currently
504 has some limitations like not being able to see program stdin and
505 stdout. Also you have to explicitly set the remote exec-file and
506 sysroot to tell GDB the "remote" and local files are the same.</para>
508 <para>Once GDB is connected to the Valgrind gdbserver, it can be used
509 in the same way as if you were debugging the program natively:</para>
512 <para>Breakpoints can be inserted or deleted.</para>
515 <para>Variables and register values can be examined or modified.
519 <para>Signal handling can be configured (printing, ignoring).
523 <para>Execution can be controlled (continue, step, next, stepi, etc).
527 <para>Program execution can be interrupted using Control-C.</para>
531 <para>And so on. Refer to the GDB user manual for a complete
532 description of GDB's functionality.
537 <sect2 id="manual-core-adv.gdbserver-gdb-android"
538 xreflabel="Connecting to an Android gdbserver">
539 <title>Connecting to an Android gdbserver</title>
540 <para> When developping applications for Android, you will typically use
541 a development system (on which the Android NDK is installed) to compile your
542 application. An Android target system or emulator will be used to run
544 In this setup, Valgrind and vgdb will run on the Android system,
545 while GDB will run on the development system. GDB will connect
546 to the vgdb running on the Android system using the Android NDK
547 'adb forward' application.
549 <para> Example: on the Android system, execute the following:
551 valgrind --vgdb-error=0 --vgdb=yes prog
552 # and then in another shell, run:
557 <para> On the development system, execute the following commands:
559 adb forward tcp:1234 tcp:1234
561 (gdb) target remote :1234
563 GDB will use a local tcp/ip connection to connect to the Android adb forwarder.
564 Adb will establish a relay connection between the host system and the Android
565 target system. Be sure to use the GDB delivered in the
566 Android NDK system (typically, arm-linux-androideabi-gdb), as the host
567 GDB is probably not able to debug Android arm applications.
568 Note that the local port nr (used by GDB) must not necessarily be equal
569 to the port number used by vgdb: adb can forward tcp/ip between different
573 <para>In the current release, the GDB server is not enabled by default
574 for Android, due to problems in establishing a suitable directory in
575 which Valgrind can create the necessary FIFOs (named pipes) for
576 communication purposes. You can stil try to use the GDB server, but
577 you will need to explicitly enable it using the flag
578 <computeroutput>--vgdb=yes</computeroutput> or
579 <computeroutput>--vgdb=full</computeroutput>.
582 <para>Additionally, you
583 will need to select a temporary directory which is (a) writable
584 by Valgrind, and (b) supports FIFOs. This is the main difficult
585 point. Often, <computeroutput>/sdcard</computeroutput> satisfies
586 requirement (a), but fails for (b) because it is a VFAT file system
587 and VFAT does not support pipes. Possibilities you could try are
588 <computeroutput>/data/local</computeroutput>,
589 <computeroutput>/data/local/Inst</computeroutput> (if you
590 installed Valgrind there), or
591 <computeroutput>/data/data/name.of.my.app</computeroutput>, if you
592 are running a specific application and it has its own directory of
593 that form. This last possibility may have the highest probability
596 <para>You can specify the temporary directory to use either via
597 the <computeroutput>--with-tmpdir=</computeroutput> configure time
598 flag, or by setting environment variable TMPDIR when running Valgrind
599 (on the Android device, not on the Android NDK development host).
600 Another alternative is to specify the directory for the FIFOs using
601 the <computeroutput>--vgdb-prefix=</computeroutput> Valgrind command
605 <para>We hope to have a better story for temporary directory handling
606 on Android in the future. The difficulty is that, unlike in standard
607 Unixes, there is no single temporary file directory that reliably
608 works across all devices and scenarios.
613 <sect2 id="manual-core-adv.gdbserver-commandhandling"
614 xreflabel="Monitor command handling by the Valgrind gdbserver">
615 <title>Monitor command handling by the Valgrind gdbserver</title>
617 <para>The Valgrind gdbserver provides additional Valgrind-specific
618 functionality via "monitor commands". Such monitor commands can be
619 sent from the GDB command line or from the shell command line or
620 requested by the client program using the VALGRIND_MONITOR_COMMAND
622 <xref linkend="&vg-monitor-id;"/> for the
623 list of the Valgrind core monitor commands available regardless of the
624 Valgrind tool selected.
627 <para>The following tools provide tool-specific monitor commands:
630 <para><xref linkend="mc-manual.monitor-commands"/></para>
633 <para><xref linkend="cl-manual.monitor-commands"/></para>
636 <para><xref linkend="ms-manual.monitor-commands"/></para>
639 <para><xref linkend="hg-manual.monitor-commands"/></para>
644 <para>An example of a tool specific monitor command is the Memcheck monitor
645 command <computeroutput>leak_check full
646 reachable any</computeroutput>. This requests a full reporting of the
647 allocated memory blocks. To have this leak check executed, use the GDB
650 (gdb) monitor leak_check full reachable any
654 <para>GDB sends as a single string all what follows 'monitor' to the Valgrind
655 gdbserver. The Valgrind gdbserver parses the string and will execute the
656 monitor command itself, if it recognises it to be a Valgrind core monitor
657 command. If it is not recognised as such, it is assumed to be tool-specific and
658 is handed to the tool for execution. For example:
660 <programlisting><![CDATA[
661 (gdb) monitor leak_check full reachable any
662 ==2418== 100 bytes in 1 blocks are still reachable in loss record 1 of 1
663 ==2418== at 0x4006E9E: malloc (vg_replace_malloc.c:236)
664 ==2418== by 0x804884F: main (prog.c:88)
666 ==2418== LEAK SUMMARY:
667 ==2418== definitely lost: 0 bytes in 0 blocks
668 ==2418== indirectly lost: 0 bytes in 0 blocks
669 ==2418== possibly lost: 0 bytes in 0 blocks
670 ==2418== still reachable: 100 bytes in 1 blocks
671 ==2418== suppressed: 0 bytes in 0 blocks
676 <para>Similarly to GDB, the Valgrind gdbserver will accept abbreviated monitor
677 command names and arguments, as long as the given abbreviation is unambiguous.
678 For example, the above
679 <computeroutput>leak_check</computeroutput>
680 command can also be typed as:
685 The letters <computeroutput>mo</computeroutput> are recognised by GDB as being
686 an abbreviation for <computeroutput>monitor</computeroutput>. So GDB sends the
687 string <computeroutput>l f r a</computeroutput> to the Valgrind
688 gdbserver. The letters provided in this string are unambiguous for the
689 Valgrind gdbserver. This therefore gives the same output as the
690 unabbreviated command and arguments. If the provided abbreviation is
691 ambiguous, the Valgrind gdbserver will report the list of commands (or
692 argument values) that can match:
693 <programlisting><![CDATA[
695 v. can match v.set v.info v.wait v.kill v.translate v.do
697 n_errs_found 0 n_errs_shown 0 (vgdb-error 0)
702 <para>Instead of sending a monitor command from GDB, you can also send
703 these from a shell command line. For example, the following command
704 lines, when given in a shell, will cause the same leak search to be executed
707 vgdb --pid=3145 leak_check full reachable any
708 vgdb --pid=3145 l f r a
711 <para>Note that the Valgrind gdbserver automatically continues the
712 execution of the program after a standalone invocation of
713 vgdb. Monitor commands sent from GDB do not cause the program to
714 continue: the program execution is controlled explicitly using GDB
715 commands such as "continue" or "next".</para>
717 <para>Many monitor commands (e.g. v.info location, memcheck who_points_at, ...) require an address
718 argument and an optional length: <varname><addr> [<len>]</varname>.
719 The arguments can also be provided by using a 'C array like syntax' by providing the address
720 followed by the length between square brackets.</para>
721 <para>For example, the following two monitor commands provide the same information:</para>
722 <programlisting><![CDATA[
723 (gdb) mo xb 0x804a2f0 10
725 (gdb) mo xb 0x804a2f0[10]
731 <sect2 id="manual-core-adv.gdbserver-gdbmonitorfrontend"
732 xreflabel="GDB front end commands for Valgrind gdbserver monitor commands">
733 <title>GDB front end commands for Valgrind gdbserver monitor commands</title>
735 <para>As explained in
736 <xref linkend="manual-core-adv.gdbserver-commandhandling"/>, valgrind monitor
737 commands consist in strings that are not interpreted by GDB. GDB has no
738 knowledge of these valgrind monitor commands. The GDB 'command line
739 interface' infrastructure however provides interesting functionalities to help
740 typing commands such as auto-completion, command specific help, searching for
741 a command or command help matching a regexp, ...
744 <para>To have a better integration of the valgrind monitor commands in the GDB
745 command line interface, Valgrind provides python code defining a GDB front end
746 command for each valgrind monitor command. Similarly, for each tool specific
747 monitor command, the python code provides a matching GDB front end command.
750 <para>Like other GDB commands, the GDB front end Valgrind monitor commands are
751 hierarchically structured starting from 5 "top" GDB commands. Subcommands are
752 defined below these "top" commands. To ease typing, shorter aliases are also
757 <para><computeroutput>valgrind</computeroutput> (aliased
758 by <computeroutput>vg</computeroutput>
759 and <computeroutput>v</computeroutput>) is the top GDB command providing
760 front end commands to the Valgrind general monitor commands.</para>
763 <para><computeroutput>memcheck</computeroutput> (aliased
764 by <computeroutput>mc</computeroutput>) is the top GDB command
765 providing the front end commands corresponding to the memcheck specific
766 monitor commands.</para>
769 <para><computeroutput>callgrind</computeroutput> (aliased
770 by <computeroutput>cg</computeroutput>) is the top GDB command
771 providing the front end commands corresponding to the callgrind specific
772 monitor commands.</para>
775 <para><computeroutput>massif</computeroutput> (aliased
776 by <computeroutput>ms</computeroutput>) is the top GDB command
777 providing the front end commands corresponding to the massif specific
778 monitor commands.</para>
781 <para><computeroutput>helgrind</computeroutput> (aliased
782 by <computeroutput>hg</computeroutput>) is the top GDB command
783 providing the front end commands corresponding to the helgrind specific
784 monitor commands.</para>
789 <para>The usage of a GDB front end command is compatible with a direct usage of
790 the Valgrind monitor command. The below example shows a direct usage of the
791 Memcheck monitor command <computeroutput>xb</computeroutput> to examine the
792 definedness status of the some_mem array and equivalent usages based on the GDB
795 <programlisting><![CDATA[
803 $2 = (char (*)[5]) 0x1ffefffe5b
804 (gdb) p sizeof(some_mem)
806 (gdb) monitor xb 0x1ffefffe5b 5
808 0x1FFEFFFE5B: 0x00 0x00 0x00 0x00 0x00
809 (gdb) memcheck xb 0x1ffefffe5b 5
811 0x1FFEFFFE5B: 0x00 0x00 0x00 0x00 0x00
812 (gdb) mc xb &some_mem sizeof(some_mem)
814 0x1FFEFFFE5B: 0x00 0x00 0x00 0x00 0x00
818 It is worth noting down that the third command uses the
819 alias <computeroutput>mc</computeroutput>. This command also shows a
820 significant advantage of using the GDB front end commands: as GDB "understands"
821 the structure of these front end commands, where relevant, these front end
822 commands will evaluate their arguments. In the case of
823 the <computeroutput>xb</computeroutput> command, the
824 GDB <computeroutput>xb</computeroutput> command evaluates its second argument
825 (which must be an address expression) and its optional second argument (which
826 must be an integer expression).
829 <para>GDB will auto-load the python code defining the Valgrind front end
830 commands as soon as GDB detects that the executable being debugged is running
831 under valgrind. This detection is based on observing that the Valgrind
832 process has loaded a specific Valgrind shared library. The loading of this
833 library is done by the dynamic loader very early on in the execution of the
834 process. If GDB is used to connect to a Valgrind process that has not yet
835 started its execution (such as when Valgrind was started with the
836 option <computeroutput>--vgdb-stop-at=startup</computeroutput>
837 or <computeroutput>--vgdb-error=0</computeroutput>), then the GDB front end
838 commands will not yet be auto-loaded. To have the GDB front end commands
839 auto-loaded, you can put a breakpoint e.g. in main and use the GDB
840 command <computeroutput>continue</computeroutput>. Alternatively, you can add
841 in your .gdbinit a line that loads the python code at GDB startup such as:
842 <programlisting><![CDATA[
843 source /path/to/valgrind/python/code/valgrind-monitor.py
847 The exact path to use in the source command depends on your Valgrind
848 installation. The output of the shell command <computeroutput>vgdb
849 --help</computeroutput> contains the absolute path name for the python file you
850 can source in your .gdbinit to define the GDB valgrind front end monitor
855 <sect2 id="manual-core-adv.gdbserver-threads"
856 xreflabel="Valgrind gdbserver thread information">
857 <title>Valgrind gdbserver thread information</title>
859 <para>Valgrind's gdbserver enriches the output of the
860 GDB <computeroutput>info threads</computeroutput> command
861 with Valgrind-specific information.
862 The operating system's thread number is followed
863 by Valgrind's internal index for that thread ("tid") and by
864 the Valgrind scheduler thread state:</para>
866 <programlisting><![CDATA[
868 4 Thread 6239 (tid 4 VgTs_Yielding) 0x001f2832 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
869 * 3 Thread 6238 (tid 3 VgTs_Runnable) make_error (s=0x8048b76 "called from London") at prog.c:20
870 2 Thread 6237 (tid 2 VgTs_WaitSys) 0x001f2832 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
871 1 Thread 6234 (tid 1 VgTs_Yielding) main (argc=1, argv=0xbedcc274) at prog.c:105
877 <sect2 id="manual-core-adv.gdbserver-shadowregisters"
878 xreflabel="Examining and modifying Valgrind shadow registers">
879 <title>Examining and modifying Valgrind shadow registers</title>
881 <para> When the option <option>--vgdb-shadow-registers=yes</option> is
882 given, the Valgrind gdbserver will let GDB examine and/or modify
883 Valgrind's shadow registers. GDB version 7.1 or later is needed for this
884 to work. For x86 and amd64, GDB version 7.2 or later is needed.</para>
886 <para>For each CPU register, the Valgrind core maintains two
887 shadow register sets. These shadow registers can be accessed from
888 GDB by giving a postfix <computeroutput>s1</computeroutput>
889 or <computeroutput>s2</computeroutput> for respectively the first
890 and second shadow register. For example, the x86 register
891 <computeroutput>eax</computeroutput> and its two shadows
892 can be examined using the following commands:</para>
894 <programlisting><![CDATA[
904 <para>Float shadow registers are shown by GDB as unsigned integer
905 values instead of float values, as it is expected that these
906 shadow values are mostly used for memcheck validity bits. </para>
908 <para>Intel/amd64 AVX registers <computeroutput>ymm0</computeroutput>
909 to <computeroutput>ymm15</computeroutput> have also their shadow
910 registers. However, GDB presents the shadow values using two
911 "half" registers. For example, the half shadow registers for
912 <computeroutput>ymm9</computeroutput> are
913 <computeroutput>xmm9s1</computeroutput> (lower half for set 1),
914 <computeroutput>ymm9hs1</computeroutput> (upper half for set 1),
915 <computeroutput>xmm9s2</computeroutput> (lower half for set 2),
916 <computeroutput>ymm9hs2</computeroutput> (upper half for set 2).
917 Note the inconsistent notation for the names of the half registers:
918 the lower part starts with an <computeroutput>x</computeroutput>,
919 the upper part starts with an <computeroutput>y</computeroutput>
920 and has an <computeroutput>h</computeroutput> before the shadow postfix.
922 <para>The special presentation of the AVX shadow registers is due to
923 the fact that GDB independently retrieves the lower and upper half of
924 the <computeroutput>ymm</computeroutput> registers. GDB does not
925 however know that the shadow half registers have to be shown combined.
930 <sect2 id="manual-core-adv.gdbserver-limitations"
931 xreflabel="Limitations of the Valgrind gdbserver">
932 <title>Limitations of the Valgrind gdbserver</title>
934 <para>Debugging with the Valgrind gdbserver is very similar to native
935 debugging. Valgrind's gdbserver implementation is quite
936 complete, and so provides most of the GDB debugging functionality. There
937 are however some limitations and peculiarities:</para>
940 <para>Precision of "stop-at" commands.</para>
942 GDB commands such as "step", "next", "stepi", breakpoints
943 and watchpoints, will stop the execution of the process. With
944 the option <option>--vgdb=yes</option>, the process might not
945 stop at the exact requested instruction. Instead, it might
946 continue execution of the current basic block and stop at one
947 of the following basic blocks. This is linked to the fact that
948 Valgrind gdbserver has to instrument a block to allow stopping
949 at the exact instruction requested. Currently,
950 re-instrumentation of the block currently being executed is not
951 supported. So, if the action requested by GDB (e.g. single
952 stepping or inserting a breakpoint) implies re-instrumentation
953 of the current block, the GDB action may not be executed
957 This limitation applies when the basic block
958 currently being executed has not yet been instrumented for debugging.
959 This typically happens when the gdbserver is activated due to the
960 tool reporting an error or to a watchpoint. If the gdbserver
961 block has been activated following a breakpoint, or if a
962 breakpoint has been inserted in the block before its execution,
963 then the block has already been instrumented for debugging.
966 If you use the option <option>--vgdb=full</option>, then GDB
967 "stop-at" commands will be obeyed precisely. The
968 downside is that this requires each instruction to be
969 instrumented with an additional call to a gdbserver helper
970 function, which gives considerable overhead (+500% for memcheck)
971 compared to <option>--vgdb=no</option>.
972 Option <option>--vgdb=yes</option> has neglectible overhead compared
973 to <option>--vgdb=no</option>.
978 <para>Processor registers and flags values.</para>
979 <para>When Valgrind gdbserver stops on an error, on a breakpoint
980 or when single stepping, registers and flags values might not be always
981 up to date due to the optimisations done by the Valgrind core.
983 <option>--vex-iropt-register-updates=unwindregs-at-mem-access</option>
984 ensures that the registers needed to make a stack trace (typically
985 PC/SP/FP) are up to date at each memory access (i.e. memory exception
987 Disabling some optimisations using the following values will increase
988 the precision of registers and flags values (a typical performance
989 impact for memcheck is given for each option).
992 <option>--vex-iropt-register-updates=allregs-at-mem-access</option> (+10%)
993 ensures that all registers and flags are up to date at each memory
997 <option>--vex-iropt-register-updates=allregs-at-each-insn</option> (+25%)
998 ensures that all registers and flags are up to date at each instruction.
1001 Note that <option>--vgdb=full</option> (+500%, see above
1002 Precision of "stop-at" commands) automatically
1003 activates <option>--vex-iropt-register-updates=allregs-at-each-insn</option>.
1008 <para>Hardware watchpoint support by the Valgrind
1011 <para> The Valgrind gdbserver can simulate hardware watchpoints
1012 if the selected tool provides support for it. Currently,
1013 only Memcheck provides hardware watchpoint simulation. The
1014 hardware watchpoint simulation provided by Memcheck is much
1015 faster that GDB software watchpoints, which are implemented by
1016 GDB checking the value of the watched zone(s) after each
1017 instruction. Hardware watchpoint simulation also provides read
1018 watchpoints. The hardware watchpoint simulation by Memcheck has
1019 some limitations compared to real hardware
1020 watchpoints. However, the number and length of simulated
1021 watchpoints are not limited.
1023 <para>Typically, the number of (real) hardware watchpoints is
1024 limited. For example, the x86 architecture supports a maximum of
1025 4 hardware watchpoints, each watchpoint watching 1, 2, 4 or 8
1026 bytes. The Valgrind gdbserver does not have any limitation on the
1027 number of simulated hardware watchpoints. It also has no
1028 limitation on the length of the memory zone being
1029 watched. Using GDB version 7.4 or later allow full use of the
1030 flexibility of the Valgrind gdbserver's simulated hardware watchpoints.
1031 Previous GDB versions do not understand that Valgrind gdbserver
1032 watchpoints have no length limit.
1034 <para>Memcheck implements hardware watchpoint simulation by
1035 marking the watched address ranges as being unaddressable. When
1036 a hardware watchpoint is removed, the range is marked as
1037 addressable and defined. Hardware watchpoint simulation of
1038 addressable-but-undefined memory zones works properly, but has
1039 the undesirable side effect of marking the zone as defined when
1040 the watchpoint is removed.
1042 <para>Write watchpoints might not be reported at the
1043 exact instruction that writes the monitored area,
1044 unless option <option>--vgdb=full</option> is given. Read watchpoints
1045 will always be reported at the exact instruction reading the
1048 <para>It is better to avoid using hardware watchpoint of not
1049 addressable (yet) memory: in such a case, GDB will fall back to
1050 extremely slow software watchpoints. Also, if you do not quit GDB
1051 between two debugging sessions, the hardware watchpoints of the
1052 previous sessions will be re-inserted as software watchpoints if
1053 the watched memory zone is not addressable at program startup.
1058 <para>Stepping inside shared libraries on ARM.</para>
1059 <para>For unknown reasons, stepping inside shared
1060 libraries on ARM may fail. A workaround is to use the
1061 <computeroutput>ldd</computeroutput> command
1062 to find the list of shared libraries and their loading address
1063 and inform GDB of the loading address using the GDB command
1064 "add-symbol-file". Example:
1065 <programlisting><![CDATA[
1066 (gdb) shell ldd ./prog
1067 libc.so.6 => /lib/libc.so.6 (0x4002c000)
1068 /lib/ld-linux.so.3 (0x40000000)
1069 (gdb) add-symbol-file /lib/libc.so.6 0x4002c000
1070 add symbol table from file "/lib/libc.so.6" at
1071 .text_addr = 0x4002c000
1073 Reading symbols from /lib/libc.so.6...(no debugging symbols found)...done.
1075 ]]></programlisting>
1080 <para>GDB version needed for ARM and PPC32/64.</para>
1081 <para>You must use a GDB version which is able to read XML
1082 target description sent by a gdbserver. This is the standard setup
1083 if GDB was configured and built with the "expat"
1084 library. If your GDB was not configured with XML support, it
1085 will report an error message when using the "target"
1086 command. Debugging will not work because GDB will then not be
1087 able to fetch the registers from the Valgrind gdbserver.
1088 For ARM programs using the Thumb instruction set, you must use
1089 a GDB version of 7.1 or later, as earlier versions have problems
1090 with next/step/breakpoints in Thumb code.
1095 <para>Stack unwinding on PPC32/PPC64. </para>
1096 <para>On PPC32/PPC64, stack unwinding for leaf functions
1097 (functions that do not call any other functions) works properly
1098 only when you give the option
1099 <option>--vex-iropt-register-updates=allregs-at-mem-access</option>
1100 or <option>--vex-iropt-register-updates=allregs-at-each-insn</option>.
1101 You must also pass this option in order to get a precise stack when
1102 a signal is trapped by GDB.
1107 <para>Breakpoints encountered multiple times.</para>
1108 <para>Some instructions (e.g. x86 "rep movsb")
1109 are translated by Valgrind using a loop. If a breakpoint is placed
1110 on such an instruction, the breakpoint will be encountered
1111 multiple times -- once for each step of the "implicit" loop
1112 implementing the instruction.
1117 <para>Execution of Inferior function calls by the Valgrind
1120 <para>GDB allows the user to "call" functions inside the process
1121 being debugged. Such calls are named "inferior calls" in the GDB
1122 terminology. A typical use of an inferior call is to execute
1123 a function that prints a human-readable version of a complex data
1124 structure. To make an inferior call, use the GDB "print" command
1125 followed by the function to call and its arguments. As an
1126 example, the following GDB command causes an inferior call to the
1127 libc "printf" function to be executed by the process
1130 <programlisting><![CDATA[
1131 (gdb) p printf("process being debugged has pid %d\n", getpid())
1134 ]]></programlisting>
1136 <para>The Valgrind gdbserver supports inferior function calls.
1137 Whilst an inferior call is running, the Valgrind tool will report
1138 errors as usual. If you do not want to have such errors stop the
1139 execution of the inferior call, you can
1140 use <computeroutput>v.set vgdb-error</computeroutput> to set a
1141 big value before the call, then manually reset it to its original
1142 value when the call is complete.</para>
1144 <para>To execute inferior calls, GDB changes registers such as
1145 the program counter, and then continues the execution of the
1146 program. In a multithreaded program, all threads are continued,
1147 not just the thread instructed to make the inferior call. If
1148 another thread reports an error or encounters a breakpoint, the
1149 evaluation of the inferior call is abandoned.</para>
1151 <para>Note that inferior function calls are a powerful GDB
1152 feature, but should be used with caution. For example, if
1153 the program being debugged is stopped inside the function "printf",
1154 forcing a recursive call to printf via an inferior call will
1155 very probably create problems. The Valgrind tool might also add
1156 another level of complexity to inferior calls, e.g. by reporting
1157 tool errors during the Inferior call or due to the
1158 instrumentation done.
1164 <para>Connecting to or interrupting a Valgrind process blocked in
1165 a system call.</para>
1167 <para>Connecting to or interrupting a Valgrind process blocked in
1168 a system call requires the "ptrace" system call to be usable.
1169 This may be disabled in your kernel for security reasons.
1172 <para>When running your program, Valgrind's scheduler
1173 periodically checks whether there is any work to be handled by
1174 the gdbserver. Unfortunately this check is only done if at least
1175 one thread of the process is runnable. If all the threads of the
1176 process are blocked in a system call, then the checks do not
1177 happen, and the Valgrind scheduler will not invoke the gdbserver.
1178 In such a case, the vgdb relay application will "force" the
1179 gdbserver to be invoked, without the intervention of the Valgrind
1183 <para>Such forced invocation of the Valgrind gdbserver is
1184 implemented by vgdb using ptrace system calls. On a properly
1185 implemented kernel, the ptrace calls done by vgdb will not
1186 influence the behaviour of the program running under Valgrind.
1187 If however they do, giving the
1188 option <option>--max-invoke-ms=0</option> to the vgdb relay
1189 application will disable the usage of ptrace calls. The
1190 consequence of disabling ptrace usage in vgdb is that a Valgrind
1191 process blocked in a system call cannot be woken up or
1192 interrupted from GDB until it executes enough basic blocks to let
1193 the Valgrind scheduler's normal checking take effect.
1196 <para>When ptrace is disabled in vgdb, you can increase the
1197 responsiveness of the Valgrind gdbserver to commands or
1198 interrupts by giving a lower value to the
1199 option <option>--vgdb-poll</option>. If your application is
1200 blocked in system calls most of the time, using a very low value
1201 for <option>--vgdb-poll</option> will cause a the gdbserver to be
1202 invoked sooner. The gdbserver polling done by Valgrind's
1203 scheduler is very efficient, so the increased polling frequency
1204 should not cause significant performance degradation.
1207 <para>When ptrace is disabled in vgdb, a query packet sent by GDB
1208 may take significant time to be handled by the Valgrind
1209 gdbserver. In such cases, GDB might encounter a protocol
1210 timeout. To avoid this,
1211 you can increase the value of the timeout by using the GDB
1212 command "set remotetimeout".
1215 <para>Ubuntu versions 10.10 and later may restrict the scope of
1216 ptrace to the children of the process calling ptrace. As the
1217 Valgrind process is not a child of vgdb, such restricted scoping
1218 causes the ptrace calls to fail. To avoid that, Valgrind will
1219 automatically allow all processes belonging to the same userid to
1220 "ptrace" a Valgrind process, by using PR_SET_PTRACER.</para>
1222 <para>Unblocking processes blocked in system calls is not
1223 currently implemented on Mac OS X and Android. So you cannot
1224 connect to or interrupt a process blocked in a system call on Mac
1228 <para>Unblocking processes blocked in system calls is implemented
1229 via agent thread on Solaris. This is quite a different approach
1230 than using ptrace on Linux, but leads to equivalent result - Valgrind
1231 gdbserver is invoked. Note that agent thread is a Solaris OS
1232 feature and cannot be disabled.
1237 <para>Changing register values.</para>
1238 <para>The Valgrind gdbserver will only modify the values of the
1239 thread's registers when the thread is in status Runnable or
1240 Yielding. In other states (typically, WaitSys), attempts to
1241 change register values will fail. Amongst other things, this
1242 means that inferior calls are not executed for a thread which is
1243 in a system call, since the Valgrind gdbserver does not implement
1244 system call restart.
1249 <para>Unsupported GDB functionality.</para>
1250 <para>GDB provides a lot of debugging functionality and not all
1251 of it is supported. Specifically, the following are not
1252 supported: reversible debugging and tracepoints.
1257 <para>Unknown limitations or problems.</para>
1258 <para>The combination of GDB, Valgrind and the Valgrind gdbserver
1259 probably has unknown other limitations and problems. If you
1260 encounter strange or unexpected behaviour, feel free to report a
1261 bug. But first please verify that the limitation or problem is
1262 not inherent to GDB or the GDB remote protocol. You may be able
1263 to do so by checking the behaviour when using standard gdbserver
1264 part of the GDB package.
1272 <!-- Referenced from both the manual and manpage -->
1273 <sect2 id="&vg-vgdb-id;"
1274 xreflabel="&vg-vgdb-label;">
1275 <title>vgdb command line options</title>
1276 <para> Usage: <computeroutput>vgdb [OPTION]... [[-c] COMMAND]...</computeroutput></para>
1278 <para> vgdb ("Valgrind to GDB") is a small program that is used as an
1279 intermediary between Valgrind and GDB or a shell.
1280 It has three usage modes:
1282 <!-- start of xi:include in the manpage -->
1283 <orderedlist id="vgdb.desc.modes">
1284 <listitem id="manual-core-adv.vgdb-standalone" xreflabel="vgdb standalone">
1285 <para>As a standalone utility, it is used from a shell command
1286 line to send monitor commands to a process running under
1287 Valgrind. For this usage, the vgdb OPTION(s) must be followed by
1288 the monitor command to send. To send more than one command,
1289 separate them with the <option>-c</option> option.
1293 <listitem id="manual-core-adv.vgdb-relay" xreflabel="vgdb relay">
1294 <para>In combination with GDB "target remote |" command, it is
1295 used as the relay application between GDB and the Valgrind
1296 gdbserver. For this usage, only OPTION(s) can be given, but no
1297 COMMAND can be given.
1301 <listitem id="manual-core-adv.vgdb-multi" xreflabel="vgdb multi">
1302 <para>In the <option>--multi</option> mode, vgdb uses the extended
1303 remote protocol to communicate with GDB. This allows you to view
1304 output from both valgrind and GDB in the GDB session. This is
1305 accomplished via the "target extended-remote | vgdb --multi". In
1306 this mode you no longer need to start valgrind yourself. vgdb will
1307 start up valgrind when gdb tells it to run a new program. For this
1308 usage, the vgdb OPTIONS(s) can also include <option>--valgrind</option>
1309 and <option>--vargs</option> to describe how valgrind should be
1315 <!-- end of xi:include in the manpage -->
1317 <para><computeroutput>vgdb</computeroutput> accepts the following
1319 <!-- start of xi:include in the manpage -->
1320 <variablelist id="vgdb.opts.list">
1322 <term><option>--pid=<number></option></term>
1323 <listitem><para>Specifies the PID of
1324 the process to which vgdb must connect to. This option is useful
1325 in case more than one Valgrind gdbserver can be connected to. If
1326 the <option>--pid</option> argument is not given and multiple
1327 Valgrind gdbserver processes are running, vgdb will report the
1328 list of such processes and then exit.</para></listitem>
1332 <term><option>--vgdb-prefix</option></term>
1333 <listitem><para>Must be given to both
1334 Valgrind and vgdb if you want to change the default prefix for the
1335 FIFOs (named pipes) used for communication between the Valgrind
1336 gdbserver and vgdb.</para></listitem>
1340 <term><option>--wait=<number></option></term>
1341 <listitem><para>Instructs vgdb to
1342 search for available Valgrind gdbservers for the specified number
1343 of seconds. This makes it possible start a vgdb process
1344 before starting the Valgrind gdbserver with which you intend the
1345 vgdb to communicate. This option is useful when used in
1346 conjunction with a <option>--vgdb-prefix</option> that is
1347 unique to the process you want to wait for.
1348 Also, if you use the <option>--wait</option> argument in the GDB
1349 "target remote" command, you must set the GDB remotetimeout to a
1350 value bigger than the --wait argument value. See option
1351 <option>--max-invoke-ms</option> (just below)
1352 for an example of setting the remotetimeout value.</para></listitem>
1356 <term><option>--max-invoke-ms=<number></option></term>
1357 <listitem><para>Gives the
1358 number of milliseconds after which vgdb will force the invocation
1359 of gdbserver embedded in Valgrind. The default value is 100
1360 milliseconds. A value of 0 disables forced invocation. The forced
1361 invocation is used when vgdb is connected to a Valgrind gdbserver,
1362 and the Valgrind process has all its threads blocked in a system
1366 <para>If you specify a large value, you might need to increase the
1367 GDB "remotetimeout" value from its default value of 2 seconds.
1368 You should ensure that the timeout (in seconds) is
1369 bigger than the <option>--max-invoke-ms</option> value. For
1370 example, for <option>--max-invoke-ms=5000</option>, the following
1371 GDB command is suitable:
1373 (gdb) set remotetimeout 6
1379 <term><option>--cmd-time-out=<number></option></term>
1380 <listitem><para>Instructs a
1381 standalone vgdb to exit if the Valgrind gdbserver it is connected
1382 to does not process a command in the specified number of seconds.
1383 The default value is to never time out.</para></listitem>
1387 <term><option>--port=<portnr></option></term>
1388 <listitem><para>Instructs vgdb to
1389 use tcp/ip and listen for GDB on the specified port nr rather than
1390 to use a pipe to communicate with GDB. Using tcp/ip allows to have
1391 GDB running on one computer and debugging a Valgrind process
1392 running on another target computer.
1395 # On the target computer, start your program under valgrind using
1396 valgrind --vgdb-error=0 prog
1397 # and then in another shell, run:
1400 <para>On the computer which hosts GDB, execute the command:
1403 (gdb) target remote targetip:1234
1405 where targetip is the ip address or hostname of the target computer.
1410 <term><option>--vgdb-multi</option></term>
1411 <listitem><para>Makes vgdb start in extended-remote mode and to wait
1412 for gdb to tell us what to run.</para></listitem>
1416 <term><option>--valgrind</option></term>
1417 <listitem><para>The path to valgrind to use, in extended-remote
1418 mode. If not specified, the system valgrind will be
1419 launched.</para></listitem>
1423 <term><option>--vargs</option></term>
1424 <listitem><para>Options to run valgrind with, in extended-remote
1425 mode. For example <option>-q</option>. Everything
1426 following <option>--vargs</option> will be provided as arguments
1427 to valgrind as is. </para></listitem>
1431 <term><option>-c</option></term>
1432 <listitem><para>To give more than one command to a
1433 standalone vgdb, separate the commands by an
1434 option <option>-c</option>. Example:
1436 vgdb v.set log_output -c leak_check any
1437 ]]></screen></para></listitem>
1441 <term><option>-l</option></term>
1442 <listitem><para>Instructs a standalone vgdb to report
1443 the list of the Valgrind gdbserver processes running and then
1444 exit.</para></listitem>
1448 <term><option>-T</option></term>
1449 <listitem><para>Instructs vgdb to add timestamps to vgdb
1450 information messages.
1455 <term><option>-D</option></term>
1456 <listitem><para>Instructs a standalone vgdb to show the
1457 state of the shared memory used by the Valgrind gdbserver. vgdb
1458 will exit after having shown the Valgrind gdbserver shared memory
1459 state.</para></listitem>
1463 <term><option>-d</option></term>
1464 <listitem><para>Instructs vgdb to produce debugging
1465 output. Give multiple <option>-d</option> args to increase the
1466 verbosity. When giving <option>-d</option> to a relay vgdb, you better
1467 redirect the standard error (stderr) of vgdb to a file to avoid
1468 interaction between GDB and vgdb debugging output.</para></listitem>
1472 <!-- end of xi:include in the manpage -->
1477 <!-- Referenced from both the manual and manpage -->
1478 <sect2 id="&vg-monitor-id;"
1479 xreflabel="&vg-monitor-label;">
1480 <title>Valgrind monitor commands</title>
1482 <para>This section describes the Valgrind monitor commands, available
1483 regardless of the Valgrind tool selected. For the tool specific
1484 commands, refer to <xref linkend="mc-manual.monitor-commands"/>,
1485 <xref linkend="hg-manual.monitor-commands"/>,
1486 <xref linkend="cl-manual.monitor-commands"/> and
1487 <xref linkend="ms-manual.monitor-commands"/>. </para>
1489 <para> The monitor commands can be sent either from a shell command line, by using a
1490 standalone vgdb, or from GDB, by using GDB's "monitor"
1491 command (see <xref linkend="manual-core-adv.gdbserver-commandhandling"/>) or
1492 by GDB's "valgrind" front end commands (see
1493 <xref linkend="manual-core-adv.gdbserver-gdbmonitorfrontend"/>).
1494 They can also be launched by the client program, using the VALGRIND_MONITOR_COMMAND
1497 <para>Whatever the way the monitor command is launched, it will behave the same
1498 way. However, using the GDB's valgrind front end commands allows to benefit
1499 from the GDB infrastructure, such as expression evaluation. When relevant,
1500 the description of a monitor command below describes the additional
1501 flexibility provided by the GDB valgrind front end command. To launch a
1502 valgrind monitor command via its GDB front end command, instead of prefixing
1503 the command with "monitor", you must use the GDB <varname>valgrind</varname>
1504 command (or the shorter aliases <varname>vg</varname>
1505 or <varname>v</varname>). In GDB, you can use <varname>help
1506 valgrind</varname> to get help about the valgrind front end monitor commands
1507 and you can use <varname>apropos valgrind</varname> to get all the commands
1508 mentionning the word "valgrind" in their name or on-line help.
1513 <para><varname>help [debug]</varname> instructs Valgrind's gdbserver
1514 to give the list of all monitor commands of the Valgrind core and
1515 of the tool. The optional "debug" argument tells to also give help
1516 for the monitor commands aimed at Valgrind internals debugging.
1518 <para>Note that this monitor command produces the help information as
1519 provided by valgrind gdbserver. The GDB help given e.g. by <varname>help
1520 valgrind</varname> or <varname>help valgrind v.info</varname> provides the
1521 help of the GDB front end command for the equivalent valgrind gdbserver
1522 monitor command. This "GDB help" describes the additional flexibility
1523 provided by the GDB front end command.
1528 <para><varname>v.info all_errors [also_suppressed]</varname> shows all errors found
1530 <para> The optional "also_suppressed" argument indicates to also output
1531 the suppressed errors.</para>
1534 <para><varname>v.info last_error</varname> shows the last error
1539 <para><varname>v.info location <addr></varname> outputs
1540 information about the location <addr>. Possibly, the
1541 following are described: global variables, local (stack)
1542 variables, allocated or freed blocks, ... The information
1543 produced depends on the tool and on the options given to valgrind.
1544 Some tools (e.g. memcheck and helgrind) produce more detailed
1545 information for client heap blocks. For example, these tools show
1546 the stacktrace where the heap block was allocated. If a tool does
1547 not replace the malloc/free/... functions, then client heap blocks
1548 will not be described. Use the
1549 option <varname>--read-var-info=yes</varname> to obtain more
1550 detailed information about global or local (stack) variables.
1552 <programlisting><![CDATA[
1553 (gdb) monitor v.info location 0x1130a0
1554 Location 0x1130a0 is 0 bytes inside global var "mx"
1555 declared at tc19_shadowmem.c:19
1556 (gdb) mo v.in loc 0x1ffefffe10
1557 Location 0x1ffefffe10 is 0 bytes inside info.child,
1558 declared at tc19_shadowmem.c:139, in frame #1 of thread 1
1560 ]]></programlisting>
1562 <para>The GDB valgrind front end command <varname>valgrind v.info location ADDR</varname>
1563 accepts any address expression for its ADDR argument. In the below examples, mx is
1564 a global struct and info is a pointer to a structure. Instead of having to print the
1565 addresses of the structure and printing the pointer variable, you can directly use the
1566 expressions in the GDB valgrind front end command argument.
1568 <programlisting><![CDATA[
1569 (gdb) valgrind v.info location &mx
1570 Location 0x1130a0 is 0 bytes inside global var "mx"
1571 declared at tc19_shadowmem.c:19
1573 Location 0x1ffefffe10 is 0 bytes inside info.child,
1574 declared at tc19_shadowmem.c:139, in frame #1 of thread 1
1576 ]]></programlisting>
1580 <para><varname>v.info n_errs_found [msg]</varname> shows the number of
1581 errors found so far, the nr of errors shown so far and the current
1582 value of the <option>--vgdb-error</option> argument. The optional
1583 <computeroutput>msg</computeroutput> (one or more words) is appended.
1584 Typically, this can be used to insert markers in a process output
1585 file between several tests executed in sequence by a process
1586 started only once. This allows to associate the errors reported
1587 by Valgrind with the specific test that produced these errors.
1592 <para><varname>v.info open_fds</varname> shows the list of open file
1593 descriptors and details related to the file descriptor.
1594 This only works if <option>--track-fds=yes</option> or
1595 <option>--track-fds=all</option> (to include
1596 <computeroutput>stdin</computeroutput>,
1597 <computeroutput>stdout</computeroutput> and
1598 <computeroutput>stderr</computeroutput>) was given at Valgrind startup.</para>
1602 <para><varname>v.clo <clo_option>...</varname> changes one or more
1603 dynamic command line options. If no clo_option is given, lists the
1604 dynamically changeable options. See
1605 <xref linkend="manual-core.dynopts"/>.
1606 The below shows example of changing the value of <varname>--vgdb-error</varname>
1607 using directly the valgrind monitor command, using the equivalent GDB valgrind front end command.
1608 It also shows how a more flexible setting can be done using the GDB eval command.
1610 <programlisting><![CDATA[
1611 (gdb) mo v.clo --vgdb-error=10
1612 ==2808839== Handling new value --vgdb-error=10 for option --vgdb-error
1613 (gdb) v v.clo --vgdb-error=11
1614 ==2808839== Handling new value --vgdb-error=11 for option --vgdb-error
1615 (gdb) set var $nnn = 15
1616 (gdb) eval "v v.clo --vgdb-error=%d", $nnn + 1
1617 ==2808839== Handling new value --vgdb-error=16 for option --vgdb-error
1619 ]]></programlisting>
1623 <para><varname>v.set {gdb_output | log_output |
1624 mixed_output}</varname> allows redirection of the Valgrind output
1625 (e.g. the errors detected by the tool). The default setting is
1626 <computeroutput>mixed_output</computeroutput>.</para>
1628 <para>With <computeroutput>mixed_output</computeroutput>, the
1629 Valgrind output goes to the Valgrind log (typically stderr) while
1630 the output of the interactive GDB monitor commands (e.g.
1631 <computeroutput>v.info last_error</computeroutput>)
1632 is displayed by GDB.</para>
1634 <para>With <computeroutput>gdb_output</computeroutput>, both the
1635 Valgrind output and the interactive GDB monitor commands output are
1636 displayed by GDB.</para>
1638 <para>With <computeroutput>log_output</computeroutput>, both the
1639 Valgrind output and the interactive GDB monitor commands output go
1640 to the Valgrind log.</para>
1644 <para><varname>v.wait [ms (default 0)]</varname> instructs
1645 Valgrind gdbserver to sleep "ms" milli-seconds and then
1646 continue. When sent from a standalone vgdb, if this is the last
1647 command, the Valgrind process will continue the execution of the
1648 guest process. The typical usage of this is to use vgdb to send a
1649 "no-op" command to a Valgrind gdbserver so as to continue the
1650 execution of the guest process.
1652 <para>The GDB valgrind front end command <varname>valgrind v.wait
1653 MS</varname> accepts any integer expression for its MS argument, while the
1654 monitor command accepts only integer numbers.
1658 <para><varname>v.kill</varname> requests the gdbserver to kill
1659 the process. This can be used from a standalone vgdb to properly
1660 kill a Valgrind process which is currently expecting a vgdb
1665 <para><varname>v.set vgdb-error <errornr></varname>
1666 dynamically changes the value of the
1667 <option>--vgdb-error</option> valgrind command line argument. A
1668 typical usage of this is to start with
1669 <option>--vgdb-error=0</option> on the
1670 command line, then set a few breakpoints, set the vgdb-error value
1671 to a huge value and continue execution. Note that you can also change
1672 this value using e.g. <varname>v.clo --vgdb-error=12</varname></para>
1673 <para>The GDB valgrind front end command <varname>valgrind v.set vgdb-error
1674 NUM</varname> accepts any integer expression for its ERRORNR argument, while
1675 the monitor command accepts only integer numbers.
1680 <para><varname>v.set merge-recursive-frames <num></varname>
1681 dynamically changes the value of the
1682 <option>--merge-recursive-frames</option> valgrind command line argument.
1683 Note that you can also change
1684 this value using e.g. <varname>v.clo --merge-recursive-frames=5</varname></para>
1685 <para>The GDB valgrind front end command <varname>valgrind v.set merge-recursive-frames
1686 NUM</varname> accepts any integer expression for its NUM argument, while
1687 the monitor command accepts only integer numbers.
1692 <para><varname>xtmemory [<filename> default xtmemory.kcg.%p.%n]</varname>
1693 requests the tool (Memcheck, Massif, Helgrind) to produce an xtree heap memory report.
1694 See <xref linkend="&vg-xtree-id;"/> for
1695 a detailed explanation about execution trees. </para>
1700 <para>The following Valgrind monitor commands are useful for
1701 investigating the behaviour of Valgrind or its gdbserver in case of
1702 problems or bugs.</para>
1707 <para><varname>v.do expensive_sanity_check_general</varname>
1708 executes various sanity checks. In particular, the sanity of the
1709 Valgrind heap is verified. This can be useful if you suspect that
1710 your program and/or Valgrind has a bug corrupting Valgrind data
1711 structure. It can also be used when a Valgrind tool
1712 reports a client error to the connected GDB, in order to verify
1713 the sanity of Valgrind before continuing the execution.
1718 <para><varname>v.info gdbserver_status</varname> shows the
1719 gdbserver status. In case of problems (e.g. of communications),
1720 this shows the values of some relevant Valgrind gdbserver internal
1721 variables. Note that the variables related to breakpoints and
1722 watchpoints (e.g. the number of breakpoint addresses and the number of
1723 watchpoints) will be zero, as GDB by default removes all
1724 watchpoints and breakpoints when execution stops, and re-inserts
1725 them when resuming the execution of the debugged process. You can
1726 change this GDB behaviour by using the GDB command
1727 <computeroutput>set breakpoint always-inserted on</computeroutput>.
1732 <para><varname>v.info memory [aspacemgr]</varname> shows the statistics of
1733 Valgrind's internal heap management. If
1734 option <option>--profile-heap=yes</option> was given, detailed
1735 statistics will be output. With the optional argument
1736 <computeroutput>aspacemgr</computeroutput>. the segment list maintained
1737 by valgrind address space manager will be output. Note that
1738 this list of segments is always output on the Valgrind log.
1743 <para><varname>v.info exectxt</varname> shows information about
1744 the "executable contexts" (i.e. the stack traces) recorded by
1745 Valgrind. For some programs, Valgrind can record a very high
1746 number of such stack traces, causing a high memory usage. This
1747 monitor command shows all the recorded stack traces, followed by
1748 some statistics. This can be used to analyse the reason for having
1749 a big number of stack traces. Typically, you will use this command
1750 if <varname>v.info memory</varname> has shown significant memory
1751 usage by the "exectxt" arena.
1756 <para><varname>v.info scheduler</varname> shows various
1757 information about threads. First, it outputs the host stack trace,
1758 i.e. the Valgrind code being executed. Then, for each thread, it
1759 outputs the thread state. For non terminated threads, the state is
1760 followed by the guest (client) stack trace. Finally, for each
1761 active thread or for each terminated thread slot not yet re-used,
1762 it shows the max usage of the valgrind stack.</para>
1763 <para>Showing the client stack traces allows to compare the stack
1764 traces produced by the Valgrind unwinder with the stack traces
1765 produced by GDB+Valgrind gdbserver. Pay attention that GDB and
1766 Valgrind scheduler status have their own thread numbering
1767 scheme. To make the link between the GDB thread number and the
1768 corresponding Valgrind scheduler thread number, use the GDB
1769 command <computeroutput>info threads</computeroutput>. The output
1770 of this command shows the GDB thread number and the valgrind
1771 'tid'. The 'tid' is the thread number output
1772 by <computeroutput>v.info scheduler</computeroutput>. When using
1773 the callgrind tool, the callgrind monitor command
1774 <computeroutput>status</computeroutput> outputs internal callgrind
1775 information about the stack/call graph it maintains.
1780 <para><varname>v.info stats</varname> shows various valgrind core and
1781 tool statistics. With this, Valgrind and tool statistics can
1782 be examined while running, even without option <option>--stats=yes</option>.
1787 <para><varname>v.info unwind <addr> [<len>]</varname> shows
1788 the CFI unwind debug info for the address range [addr, addr+len-1].
1789 The default value of <len> is 1, giving the unwind information
1790 for the instruction at <addr>.
1792 <para>The GDB valgrind front end command <varname>valgrind v.info unwind
1793 ADDR [LEN]</varname> accepts any address expression for its first ADDR
1794 argument, such as $pc. The second optional argument is any integer
1795 expression. Note that these 2 arguments must be separated by a space.
1800 <para><varname>v.set debuglog <intvalue></varname> sets the
1801 Valgrind debug log level to <intvalue>. This allows to
1802 dynamically change the log level of Valgrind e.g. when a problem
1804 <para>The GDB valgrind front end command <varname>valgrind v.set debuglog
1805 LEVEL</varname> accepts any address expression for its LEVEL argument.
1810 <para><varname>v.set hostvisibility [yes*|no]</varname> The value
1811 "yes" indicates to gdbserver that GDB can look at the Valgrind
1812 'host' (internal) status/memory. "no" disables this access.
1813 When hostvisibility is activated, GDB can e.g. look at Valgrind
1814 global variables. As an example, to examine a Valgrind global
1815 variable of the memcheck tool on an x86, do the following setup:</para>
1818 (gdb) monitor v.set hostvisibility yes
1819 Enabled access to Valgrind memory/status by GDB
1820 If not yet done, tell GDB which valgrind file(s) to use, typically:
1821 add-symbol-file /home/philippe/valgrind/git/improve/Inst/libexec/valgrind/memcheck-amd64-linux 0x58001000
1822 (gdb) add-symbol-file /home/philippe/valgrind/git/improve/Inst/libexec/valgrind/memcheck-amd64-linux 0x58001000
1823 add symbol table from file "/home/philippe/valgrind/git/improve/Inst/libexec/valgrind/memcheck-amd64-linux" at
1824 .text_addr = 0x58001000
1826 Reading symbols from /home/philippe/valgrind/git/improve/Inst/libexec/valgrind/memcheck-amd64-linux...
1830 <para>After that, variables defined in memcheck-x86-linux can be accessed, e.g.</para>
1833 (gdb) p /x vgPlain_threads[1].os_state
1834 $3 = {lwpid = 0x4688, threadgroup = 0x4688, parent = 0x0,
1835 valgrind_stack_base = 0x62e78000, valgrind_stack_init_SP = 0x62f79fe0,
1836 exitcode = 0x0, fatalsig = 0x0}
1838 $5 = {iropt_verbosity = 0, iropt_level = 2,
1839 iropt_register_updates = VexRegUpdUnwindregsAtMemAccess,
1840 iropt_unroll_thresh = 120, guest_max_insns = 60, guest_chase_thresh = 10}
1846 <para><varname>v.translate <address>
1847 [<traceflags>]</varname> shows the translation of the block
1848 containing <computeroutput>address</computeroutput> with the given
1849 trace flags. The <computeroutput>traceflags</computeroutput> value
1850 bit patterns have similar meaning to Valgrind's
1851 <option>--trace-flags</option> option. It can be given
1852 in hexadecimal (e.g. 0x20) or decimal (e.g. 32) or in binary 1s
1853 and 0s bit (e.g. 0b00100000). The default value of the traceflags
1854 is 0b00100000, corresponding to "show after instrumentation".
1855 The output of this command always goes to the Valgrind
1857 <para>The additional bit flag 0b100000000 (bit 8)
1858 has no equivalent in the <option>--trace-flags</option> option.
1859 It enables tracing of the gdbserver specific instrumentation. Note
1860 that this bit 8 can only enable the addition of gdbserver
1861 instrumentation in the trace. Setting it to 0 will not
1862 disable the tracing of the gdbserver instrumentation if it is
1863 active for some other reason, for example because there is a breakpoint at
1864 this address or because gdbserver is in single stepping
1866 <para>The GDB valgrind front end command <varname>valgrind v.translate ADDR
1867 [TRACEFLAG]</varname> accepts any address expression for its first ADDR
1868 argument, such as $pc. The second optional argument is any integer
1869 expression. Note that these 2 arguments must be separated by a space.
1883 <sect1 id="manual-core-adv.wrapping" xreflabel="Function Wrapping">
1884 <title>Function wrapping</title>
1887 Valgrind allows calls to some specified functions to be intercepted and
1888 rerouted to a different, user-supplied function. This can do whatever it
1889 likes, typically examining the arguments, calling onwards to the original,
1890 and possibly examining the result. Any number of functions may be
1894 Function wrapping is useful for instrumenting an API in some way. For
1895 example, Helgrind wraps functions in the POSIX pthreads API so it can know
1896 about thread status changes, and the core is able to wrap
1897 functions in the MPI (message-passing) API so it can know
1898 of memory status changes associated with message arrival/departure.
1899 Such information is usually passed to Valgrind by using client
1900 requests in the wrapper functions, although the exact mechanism may vary.
1903 <sect2 id="manual-core-adv.wrapping.example" xreflabel="A Simple Example">
1904 <title>A Simple Example</title>
1906 <para>Supposing we want to wrap some function</para>
1908 <programlisting><![CDATA[
1909 int foo ( int x, int y ) { return x + y; }]]></programlisting>
1911 <para>A wrapper is a function of identical type, but with a special name
1912 which identifies it as the wrapper for <computeroutput>foo</computeroutput>.
1913 Wrappers need to include
1914 supporting macros from <filename>valgrind.h</filename>.
1915 Here is a simple wrapper which prints the arguments and return value:</para>
1917 <programlisting><![CDATA[
1919 #include "valgrind.h"
1920 int I_WRAP_SONAME_FNNAME_ZU(NONE,foo)( int x, int y )
1924 VALGRIND_GET_ORIG_FN(fn);
1925 printf("foo's wrapper: args %d %d\n", x, y);
1926 CALL_FN_W_WW(result, fn, x,y);
1927 printf("foo's wrapper: result %d\n", result);
1930 ]]></programlisting>
1932 <para>To become active, the wrapper merely needs to be present in a text
1933 section somewhere in the same process' address space as the function
1934 it wraps, and for its ELF symbol name to be visible to Valgrind. In
1935 practice, this means either compiling to a
1936 <computeroutput>.o</computeroutput> and linking it in, or
1937 compiling to a <computeroutput>.so</computeroutput> and
1938 <computeroutput>LD_PRELOAD</computeroutput>ing it in. The latter is more
1939 convenient in that it doesn't require relinking.</para>
1941 <para>All wrappers have approximately the above form. There are three
1942 crucial macros:</para>
1944 <para><computeroutput>I_WRAP_SONAME_FNNAME_ZU</computeroutput>:
1945 this generates the real name of the wrapper.
1946 This is an encoded name which Valgrind notices when reading symbol
1947 table information. What it says is: I am the wrapper for any function
1948 named <computeroutput>foo</computeroutput> which is found in
1949 an ELF shared object with an empty
1950 ("<computeroutput>NONE</computeroutput>") soname field. The specification
1951 mechanism is powerful in
1952 that wildcards are allowed for both sonames and function names.
1953 The details are discussed below.</para>
1955 <para><computeroutput>VALGRIND_GET_ORIG_FN</computeroutput>:
1956 once in the wrapper, the first priority is
1957 to get hold of the address of the original (and any other supporting
1958 information needed). This is stored in a value of opaque
1959 type <computeroutput>OrigFn</computeroutput>.
1960 The information is acquired using
1961 <computeroutput>VALGRIND_GET_ORIG_FN</computeroutput>. It is crucial
1962 to make this macro call before calling any other wrapped function
1963 in the same thread.</para>
1965 <para><computeroutput>CALL_FN_W_WW</computeroutput>: eventually we will
1966 want to call the function being
1967 wrapped. Calling it directly does not work, since that just gets us
1968 back to the wrapper and leads to an infinite loop. Instead, the result
1970 <computeroutput>OrigFn</computeroutput> and arguments are
1971 handed to one of a family of macros of the form
1972 <computeroutput>CALL_FN_*</computeroutput>. These
1973 cause Valgrind to call the original and avoid recursion back to the
1977 <sect2 id="manual-core-adv.wrapping.specs" xreflabel="Wrapping Specifications">
1978 <title>Wrapping Specifications</title>
1980 <para>This scheme has the advantage of being self-contained. A library of
1981 wrappers can be compiled to object code in the normal way, and does
1982 not rely on an external script telling Valgrind which wrappers pertain
1983 to which originals.</para>
1985 <para>Each wrapper has a name which, in the most general case says: I am the
1986 wrapper for any function whose name matches FNPATT and whose ELF
1987 "soname" matches SOPATT. Both FNPATT and SOPATT may contain wildcards
1988 (asterisks) and other characters (spaces, dots, @, etc) which are not
1989 generally regarded as valid C identifier names.</para>
1991 <para>This flexibility is needed to write robust wrappers for POSIX pthread
1992 functions, where typically we are not completely sure of either the
1993 function name or the soname, or alternatively we want to wrap a whole
1994 set of functions at once.</para>
1996 <para>For example, <computeroutput>pthread_create</computeroutput>
1997 in GNU libpthread is usually a
1998 versioned symbol - one whose name ends in, eg,
1999 <computeroutput>@GLIBC_2.3</computeroutput>. Hence we
2000 are not sure what its real name is. We also want to cover any soname
2001 of the form <computeroutput>libpthread.so*</computeroutput>.
2002 So the header of the wrapper will be</para>
2004 <programlisting><![CDATA[
2005 int I_WRAP_SONAME_FNNAME_ZZ(libpthreadZdsoZd0,pthreadZucreateZAZa)
2008 ]]></programlisting>
2010 <para>In order to write unusual characters as valid C function names, a
2011 Z-encoding scheme is used. Names are written literally, except that
2012 a capital Z acts as an escape character, with the following encoding:</para>
2014 <programlisting><![CDATA[
2024 ZL ( # only in valgrind 3.3.0 and later
2025 ZR ) # only in valgrind 3.3.0 and later
2026 ]]></programlisting>
2028 <para>Hence <computeroutput>libpthreadZdsoZd0</computeroutput> is an
2029 encoding of the soname <computeroutput>libpthread.so.0</computeroutput>
2030 and <computeroutput>pthreadZucreateZAZa</computeroutput> is an encoding
2031 of the function name <computeroutput>pthread_create@*</computeroutput>.
2034 <para>The macro <computeroutput>I_WRAP_SONAME_FNNAME_ZZ</computeroutput>
2035 constructs a wrapper name in which
2036 both the soname (first component) and function name (second component)
2037 are Z-encoded. Encoding the function name can be tiresome and is
2038 often unnecessary, so a second macro,
2039 <computeroutput>I_WRAP_SONAME_FNNAME_ZU</computeroutput>, can be
2040 used instead. The <computeroutput>_ZU</computeroutput> variant is
2041 also useful for writing wrappers for
2042 C++ functions, in which the function name is usually already mangled
2043 using some other convention in which Z plays an important role. Having
2044 to encode a second time quickly becomes confusing.</para>
2046 <para>Since the function name field may contain wildcards, it can be
2047 anything, including just <computeroutput>*</computeroutput>.
2048 The same is true for the soname.
2049 However, some ELF objects - specifically, main executables - do not
2050 have sonames. Any object lacking a soname is treated as if its soname
2051 was <computeroutput>NONE</computeroutput>, which is why the original
2052 example above had a name
2053 <computeroutput>I_WRAP_SONAME_FNNAME_ZU(NONE,foo)</computeroutput>.</para>
2055 <para>Note that the soname of an ELF object is not the same as its
2056 file name, although it is often similar. You can find the soname of
2057 an object <computeroutput>libfoo.so</computeroutput> using the command
2058 <computeroutput>readelf -a libfoo.so | grep soname</computeroutput>.</para>
2061 <sect2 id="manual-core-adv.wrapping.semantics" xreflabel="Wrapping Semantics">
2062 <title>Wrapping Semantics</title>
2064 <para>The ability for a wrapper to replace an infinite family of functions
2065 is powerful but brings complications in situations where ELF objects
2066 appear and disappear (are dlopen'd and dlclose'd) on the fly.
2067 Valgrind tries to maintain sensible behaviour in such situations.</para>
2069 <para>For example, suppose a process has dlopened (an ELF object with
2070 soname) <filename>object1.so</filename>, which contains
2071 <computeroutput>function1</computeroutput>. It starts to use
2072 <computeroutput>function1</computeroutput> immediately.</para>
2074 <para>After a while it dlopens <filename>wrappers.so</filename>,
2075 which contains a wrapper
2076 for <computeroutput>function1</computeroutput> in (soname)
2077 <filename>object1.so</filename>. All subsequent calls to
2078 <computeroutput>function1</computeroutput> are rerouted to the wrapper.</para>
2080 <para>If <filename>wrappers.so</filename> is
2081 later dlclose'd, calls to <computeroutput>function1</computeroutput> are
2082 naturally routed back to the original.</para>
2084 <para>Alternatively, if <filename>object1.so</filename>
2085 is dlclose'd but <filename>wrappers.so</filename> remains,
2086 then the wrapper exported by <filename>wrappers.so</filename>
2087 becomes inactive, since there
2088 is no way to get to it - there is no original to call any more. However,
2089 Valgrind remembers that the wrapper is still present. If
2090 <filename>object1.so</filename> is
2091 eventually dlopen'd again, the wrapper will become active again.</para>
2093 <para>In short, valgrind inspects all code loading/unloading events to
2094 ensure that the set of currently active wrappers remains consistent.</para>
2096 <para>A second possible problem is that of conflicting wrappers. It is
2097 easily possible to load two or more wrappers, both of which claim
2098 to be wrappers for some third function. In such cases Valgrind will
2099 complain about conflicting wrappers when the second one appears, and
2100 will honour only the first one.</para>
2103 <sect2 id="manual-core-adv.wrapping.debugging" xreflabel="Debugging">
2104 <title>Debugging</title>
2106 <para>Figuring out what's going on given the dynamic nature of wrapping
2107 can be difficult. The
2108 <option>--trace-redir=yes</option> option makes
2110 by showing the complete state of the redirection subsystem after
2112 <function>mmap</function>/<function>munmap</function>
2113 event affecting code (text).</para>
2115 <para>There are two central concepts:</para>
2119 <listitem><para>A "redirection specification" is a binding of
2120 a (soname pattern, fnname pattern) pair to a code address.
2121 These bindings are created by writing functions with names
2123 <computeroutput>I_WRAP_SONAME_FNNAME_{ZZ,_ZU}</computeroutput>
2124 macros.</para></listitem>
2126 <listitem><para>An "active redirection" is a code-address to
2127 code-address binding currently in effect.</para></listitem>
2131 <para>The state of the wrapping-and-redirection subsystem comprises a set of
2132 specifications and a set of active bindings. The specifications are
2133 acquired/discarded by watching all
2134 <function>mmap</function>/<function>munmap</function>
2135 events on code (text)
2136 sections. The active binding set is (conceptually) recomputed from
2137 the specifications, and all known symbol names, following any change
2138 to the specification set.</para>
2140 <para><option>--trace-redir=yes</option> shows the contents
2141 of both sets following any such event.</para>
2143 <para><option>-v</option> prints a line of text each
2144 time an active specification is used for the first time.</para>
2146 <para>Hence for maximum debugging effectiveness you will need to use both
2149 <para>One final comment. The function-wrapping facility is closely
2150 tied to Valgrind's ability to replace (redirect) specified
2151 functions, for example to redirect calls to
2152 <function>malloc</function> to its
2153 own implementation. Indeed, a replacement function can be
2154 regarded as a wrapper function which does not call the original.
2155 However, to make the implementation more robust, the two kinds
2156 of interception (wrapping vs replacement) are treated differently.
2159 <para><option>--trace-redir=yes</option> shows
2160 specifications and bindings for both
2161 replacement and wrapper functions. To differentiate the
2162 two, replacement bindings are printed using
2163 <computeroutput>R-></computeroutput> whereas
2164 wraps are printed using <computeroutput>W-></computeroutput>.
2169 <sect2 id="manual-core-adv.wrapping.limitations-cf"
2170 xreflabel="Limitations - control flow">
2171 <title>Limitations - control flow</title>
2173 <para>For the most part, the function wrapping implementation is robust.
2174 The only important caveat is: in a wrapper, get hold of
2175 the <computeroutput>OrigFn</computeroutput> information using
2176 <computeroutput>VALGRIND_GET_ORIG_FN</computeroutput> before calling any
2177 other wrapped function. Once you have the
2178 <computeroutput>OrigFn</computeroutput>, arbitrary
2179 calls between, recursion between, and longjumps out of wrappers
2180 should work correctly. There is never any interaction between wrapped
2181 functions and merely replaced functions
2182 (eg <function>malloc</function>), so you can call
2183 <function>malloc</function> etc safely from within wrappers.
2186 <para>The above comments are true for {x86,amd64,ppc32,arm,mips32,s390}-linux.
2188 ppc64-linux function wrapping is more fragile due to the (arguably
2189 poorly designed) ppc64-linux ABI. This mandates the use of a shadow
2190 stack which tracks entries/exits of both wrapper and replacement
2191 functions. This gives two limitations: firstly, longjumping out of
2192 wrappers will rapidly lead to disaster, since the shadow stack will
2193 not get correctly cleared. Secondly, since the shadow stack has
2194 finite size, recursion between wrapper/replacement functions is only
2195 possible to a limited depth, beyond which Valgrind has to abort the
2196 run. This depth is currently 16 calls.</para>
2198 <para>For all platforms ({x86,amd64,ppc32,ppc64,arm,mips32,s390}-linux)
2200 comments apply on a per-thread basis. In other words, wrapping is
2201 thread-safe: each thread must individually observe the above
2202 restrictions, but there is no need for any kind of inter-thread
2207 <sect2 id="manual-core-adv.wrapping.limitations-sigs"
2208 xreflabel="Limitations - original function signatures">
2209 <title>Limitations - original function signatures</title>
2211 <para>As shown in the above example, to call the original you must use a
2212 macro of the form <computeroutput>CALL_FN_*</computeroutput>.
2213 For technical reasons it is impossible
2214 to create a single macro to deal with all argument types and numbers,
2215 so a family of macros covering the most common cases is supplied. In
2216 what follows, 'W' denotes a machine-word-typed value (a pointer or a
2217 C <computeroutput>long</computeroutput>),
2218 and 'v' denotes C's <computeroutput>void</computeroutput> type.
2219 The currently available macros are:</para>
2221 <programlisting><![CDATA[
2222 CALL_FN_v_v -- call an original of type void fn ( void )
2223 CALL_FN_W_v -- call an original of type long fn ( void )
2225 CALL_FN_v_W -- call an original of type void fn ( long )
2226 CALL_FN_W_W -- call an original of type long fn ( long )
2228 CALL_FN_v_WW -- call an original of type void fn ( long, long )
2229 CALL_FN_W_WW -- call an original of type long fn ( long, long )
2231 CALL_FN_v_WWW -- call an original of type void fn ( long, long, long )
2232 CALL_FN_W_WWW -- call an original of type long fn ( long, long, long )
2234 CALL_FN_W_WWWW -- call an original of type long fn ( long, long, long, long )
2235 CALL_FN_W_5W -- call an original of type long fn ( long, long, long, long, long )
2236 CALL_FN_W_6W -- call an original of type long fn ( long, long, long, long, long, long )
2239 ]]></programlisting>
2241 <para>The set of supported types can be expanded as needed. It is
2242 regrettable that this limitation exists. Function wrapping has proven
2243 difficult to implement, with a certain apparently unavoidable level of
2244 ickiness. After several implementation attempts, the present
2245 arrangement appears to be the least-worst tradeoff. At least it works
2246 reliably in the presence of dynamic linking and dynamic code
2247 loading/unloading.</para>
2249 <para>You should not attempt to wrap a function of one type signature with a
2250 wrapper of a different type signature. Such trickery will surely lead
2251 to crashes or strange behaviour. This is not a limitation
2252 of the function wrapping implementation, merely a reflection of the
2253 fact that it gives you sweeping powers to shoot yourself in the foot
2254 if you are not careful. Imagine the instant havoc you could wreak by
2255 writing a wrapper which matched any function name in any soname - in
2256 effect, one which claimed to be a wrapper for all functions in the
2260 <sect2 id="manual-core-adv.wrapping.examples" xreflabel="Examples">
2261 <title>Examples</title>
2263 <para>In the source tree,
2264 <filename>memcheck/tests/wrap[1-8].c</filename> provide a series of
2265 examples, ranging from very simple to quite advanced.</para>
2267 <para><filename>mpi/libmpiwrap.c</filename> is an example
2268 of wrapping a big, complex API (the MPI-2 interface). This file defines
2269 almost 300 different wrappers.</para>