• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1<html>
2<head>
3<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
4<title>3.�Using and understanding the Valgrind core: Advanced Topics</title>
5<link rel="stylesheet" type="text/css" href="vg_basic.css">
6<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
7<link rel="home" href="index.html" title="Valgrind Documentation">
8<link rel="up" href="manual.html" title="Valgrind User Manual">
9<link rel="prev" href="manual-core.html" title="2.�Using and understanding the Valgrind core">
10<link rel="next" href="mc-manual.html" title="4.�Memcheck: a memory error detector">
11</head>
12<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
13<div><table class="nav" width="100%" cellspacing="3" cellpadding="3" border="0" summary="Navigation header"><tr>
14<td width="22px" align="center" valign="middle"><a accesskey="p" href="manual-core.html"><img src="images/prev.png" width="18" height="21" border="0" alt="Prev"></a></td>
15<td width="25px" align="center" valign="middle"><a accesskey="u" href="manual.html"><img src="images/up.png" width="21" height="18" border="0" alt="Up"></a></td>
16<td width="31px" align="center" valign="middle"><a accesskey="h" href="index.html"><img src="images/home.png" width="27" height="20" border="0" alt="Up"></a></td>
17<th align="center" valign="middle">Valgrind User Manual</th>
18<td width="22px" align="center" valign="middle"><a accesskey="n" href="mc-manual.html"><img src="images/next.png" width="18" height="21" border="0" alt="Next"></a></td>
19</tr></table></div>
20<div class="chapter">
21<div class="titlepage"><div><div><h1 class="title">
22<a name="manual-core-adv"></a>3.�Using and understanding the Valgrind core: Advanced Topics</h1></div></div></div>
23<div class="toc">
24<p><b>Table of Contents</b></p>
25<dl class="toc">
26<dt><span class="sect1"><a href="manual-core-adv.html#manual-core-adv.clientreq">3.1. The Client Request mechanism</a></span></dt>
27<dt><span class="sect1"><a href="manual-core-adv.html#manual-core-adv.gdbserver">3.2. Debugging your program using Valgrind gdbserver and GDB</a></span></dt>
28<dd><dl>
29<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.gdbserver-simple">3.2.1. Quick Start: debugging in 3 steps</a></span></dt>
30<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.gdbserver-concept">3.2.2. Valgrind gdbserver overall organisation</a></span></dt>
31<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.gdbserver-gdb">3.2.3. Connecting GDB to a Valgrind gdbserver</a></span></dt>
32<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.gdbserver-gdb-android">3.2.4. Connecting to an Android gdbserver</a></span></dt>
33<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.gdbserver-commandhandling">3.2.5. Monitor command handling by the Valgrind gdbserver</a></span></dt>
34<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.gdbserver-threads">3.2.6. Valgrind gdbserver thread information</a></span></dt>
35<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.gdbserver-shadowregisters">3.2.7. Examining and modifying Valgrind shadow registers</a></span></dt>
36<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.gdbserver-limitations">3.2.8. Limitations of the Valgrind gdbserver</a></span></dt>
37<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.vgdb">3.2.9. vgdb command line options</a></span></dt>
38<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.valgrind-monitor-commands">3.2.10. Valgrind monitor commands</a></span></dt>
39</dl></dd>
40<dt><span class="sect1"><a href="manual-core-adv.html#manual-core-adv.wrapping">3.3. Function wrapping</a></span></dt>
41<dd><dl>
42<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.wrapping.example">3.3.1. A Simple Example</a></span></dt>
43<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.wrapping.specs">3.3.2. Wrapping Specifications</a></span></dt>
44<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.wrapping.semantics">3.3.3. Wrapping Semantics</a></span></dt>
45<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.wrapping.debugging">3.3.4. Debugging</a></span></dt>
46<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.wrapping.limitations-cf">3.3.5. Limitations - control flow</a></span></dt>
47<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.wrapping.limitations-sigs">3.3.6. Limitations - original function signatures</a></span></dt>
48<dt><span class="sect2"><a href="manual-core-adv.html#manual-core-adv.wrapping.examples">3.3.7. Examples</a></span></dt>
49</dl></dd>
50</dl>
51</div>
52<p>This chapter describes advanced aspects of the Valgrind core
53services, which are mostly of interest to power users who wish to
54customise and modify Valgrind's default behaviours in certain useful
55ways.  The subjects covered are:</p>
56<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
57<li class="listitem"><p>The "Client Request" mechanism</p></li>
58<li class="listitem"><p>Debugging your program using Valgrind's gdbserver
59      and GDB</p></li>
60<li class="listitem"><p>Function Wrapping</p></li>
61</ul></div>
62<div class="sect1">
63<div class="titlepage"><div><div><h2 class="title" style="clear: both">
64<a name="manual-core-adv.clientreq"></a>3.1.�The Client Request mechanism</h2></div></div></div>
65<p>Valgrind has a trapdoor mechanism via which the client
66program can pass all manner of requests and queries to Valgrind
67and the current tool.  Internally, this is used extensively
68to make various things work, although that's not visible from the
69outside.</p>
70<p>For your convenience, a subset of these so-called client
71requests is provided to allow you to tell Valgrind facts about
72the behaviour of your program, and also to make queries.
73In particular, your program can tell Valgrind about things that it
74otherwise would not know, leading to better results.
75</p>
76<p>Clients need to include a header file to make this work.
77Which header file depends on which client requests you use.  Some
78client requests are handled by the core, and are defined in the
79header file <code class="filename">valgrind/valgrind.h</code>.  Tool-specific
80header files are named after the tool, e.g.
81<code class="filename">valgrind/memcheck.h</code>.  Each tool-specific header file
82includes <code class="filename">valgrind/valgrind.h</code> so you don't need to
83include it in your client if you include a tool-specific header.  All header
84files can be found in the <code class="literal">include/valgrind</code> directory of
85wherever Valgrind was installed.</p>
86<p>The macros in these header files have the magical property
87that they generate code in-line which Valgrind can spot.
88However, the code does nothing when not run on Valgrind, so you
89are not forced to run your program under Valgrind just because you
90use the macros in this file.  Also, you are not required to link your
91program with any extra supporting libraries.</p>
92<p>The code added to your binary has negligible performance impact:
93on x86, amd64, ppc32, ppc64 and ARM, the overhead is 6 simple integer
94instructions and is probably undetectable except in tight loops.
95However, if you really wish to compile out the client requests, you
96can compile with <code class="option">-DNVALGRIND</code> (analogous to
97<code class="option">-DNDEBUG</code>'s effect on
98<code class="function">assert</code>).
99</p>
100<p>You are encouraged to copy the <code class="filename">valgrind/*.h</code> headers
101into your project's include directory, so your program doesn't have a
102compile-time dependency on Valgrind being installed.  The Valgrind headers,
103unlike most of the rest of the code, are under a BSD-style license so you may
104include them without worrying about license incompatibility.</p>
105<p>Here is a brief description of the macros available in
106<code class="filename">valgrind.h</code>, which work with more than one
107tool (see the tool-specific documentation for explanations of the
108tool-specific macros).</p>
109<div class="variablelist"><dl class="variablelist">
110<dt><span class="term"><span class="command"><strong><code class="computeroutput">RUNNING_ON_VALGRIND</code></strong></span>:</span></dt>
111<dd><p>Returns 1 if running on Valgrind, 0 if running on the
112    real CPU.  If you are running Valgrind on itself, returns the
113    number of layers of Valgrind emulation you're running on.
114    </p></dd>
115<dt><span class="term"><span class="command"><strong><code class="computeroutput">VALGRIND_DISCARD_TRANSLATIONS</code>:</strong></span></span></dt>
116<dd>
117<p>Discards translations of code in the specified address
118    range.  Useful if you are debugging a JIT compiler or some other
119    dynamic code generation system.  After this call, attempts to
120    execute code in the invalidated address range will cause
121    Valgrind to make new translations of that code, which is
122    probably the semantics you want.  Note that code invalidations
123    are expensive because finding all the relevant translations
124    quickly is very difficult, so try not to call it often.
125    Note that you can be clever about
126    this: you only need to call it when an area which previously
127    contained code is overwritten with new code.  You can choose
128    to write code into fresh memory, and just call this
129    occasionally to discard large chunks of old code all at
130    once.</p>
131<p>
132    Alternatively, for transparent self-modifying-code support,
133    use<code class="option">--smc-check=all</code>, or run
134    on ppc32/Linux, ppc64/Linux or ARM/Linux.
135    </p>
136</dd>
137<dt><span class="term"><span class="command"><strong><code class="computeroutput">VALGRIND_COUNT_ERRORS</code>:</strong></span></span></dt>
138<dd><p>Returns the number of errors found so far by Valgrind.  Can be
139    useful in test harness code when combined with the
140    <code class="option">--log-fd=-1</code> option; this runs Valgrind silently,
141    but the client program can detect when errors occur.  Only useful
142    for tools that report errors, e.g. it's useful for Memcheck, but for
143    Cachegrind it will always return zero because Cachegrind doesn't
144    report errors.</p></dd>
145<dt><span class="term"><span class="command"><strong><code class="computeroutput">VALGRIND_MALLOCLIKE_BLOCK</code>:</strong></span></span></dt>
146<dd><p>If your program manages its own memory instead of using
147    the standard <code class="function">malloc</code> /
148    <code class="function">new</code> /
149    <code class="function">new[]</code>, tools that track
150    information about heap blocks will not do nearly as good a
151    job.  For example, Memcheck won't detect nearly as many
152    errors, and the error messages won't be as informative.  To
153    improve this situation, use this macro just after your custom
154    allocator allocates some new memory.  See the comments in
155    <code class="filename">valgrind.h</code> for information on how to use
156    it.</p></dd>
157<dt><span class="term"><span class="command"><strong><code class="computeroutput">VALGRIND_FREELIKE_BLOCK</code>:</strong></span></span></dt>
158<dd><p>This should be used in conjunction with
159    <code class="computeroutput">VALGRIND_MALLOCLIKE_BLOCK</code>.
160    Again, see <code class="filename">valgrind.h</code> for
161    information on how to use it.</p></dd>
162<dt><span class="term"><span class="command"><strong><code class="computeroutput">VALGRIND_RESIZEINPLACE_BLOCK</code>:</strong></span></span></dt>
163<dd><p>Informs a Valgrind tool that the size of an allocated block has been
164    modified but not its address. See <code class="filename">valgrind.h</code> for
165    more information on how to use it.</p></dd>
166<dt><span class="term">
167   <span class="command"><strong><code class="computeroutput">VALGRIND_CREATE_MEMPOOL</code></strong></span>,
168   <span class="command"><strong><code class="computeroutput">VALGRIND_DESTROY_MEMPOOL</code></strong></span>,
169   <span class="command"><strong><code class="computeroutput">VALGRIND_MEMPOOL_ALLOC</code></strong></span>,
170   <span class="command"><strong><code class="computeroutput">VALGRIND_MEMPOOL_FREE</code></strong></span>,
171   <span class="command"><strong><code class="computeroutput">VALGRIND_MOVE_MEMPOOL</code></strong></span>,
172   <span class="command"><strong><code class="computeroutput">VALGRIND_MEMPOOL_CHANGE</code></strong></span>,
173   <span class="command"><strong><code class="computeroutput">VALGRIND_MEMPOOL_EXISTS</code></strong></span>:
174   </span></dt>
175<dd><p>These are similar to
176    <code class="computeroutput">VALGRIND_MALLOCLIKE_BLOCK</code> and
177    <code class="computeroutput">VALGRIND_FREELIKE_BLOCK</code>
178    but are tailored towards code that uses memory pools.  See
179    <a class="xref" href="mc-manual.html#mc-manual.mempools" title="4.8.�Memory Pools: describing and working with custom allocators">Memory Pools</a> for a detailed description.</p></dd>
180<dt><span class="term"><span class="command"><strong><code class="computeroutput">VALGRIND_NON_SIMD_CALL[0123]</code>:</strong></span></span></dt>
181<dd>
182<p>Executes a function in the client program on the
183    <span class="emphasis"><em>real</em></span> CPU, not the virtual CPU that Valgrind
184    normally runs code on.  The function must take an integer (holding a
185    thread ID) as the first argument and then 0, 1, 2 or 3 more arguments
186    (depending on which client request is used).  These are used in various
187    ways internally to Valgrind.  They might be useful to client
188    programs.</p>
189<p><span class="command"><strong>Warning:</strong></span> Only use these if you
190    <span class="emphasis"><em>really</em></span> know what you are doing.  They aren't
191    entirely reliable, and can cause Valgrind to crash.  See
192    <code class="filename">valgrind.h</code> for more details.
193    </p>
194</dd>
195<dt><span class="term"><span class="command"><strong><code class="computeroutput">VALGRIND_PRINTF(format, ...)</code>:</strong></span></span></dt>
196<dd><p>Print a printf-style message to the Valgrind log file.  The
197    message is prefixed with the PID between a pair of
198    <code class="computeroutput">**</code> markers.  (Like all client requests,
199    nothing is output if the client program is not running under Valgrind.)
200    Output is not produced until a newline is encountered, or subsequent
201    Valgrind output is printed; this allows you to build up a single line of
202    output over multiple calls.  Returns the number of characters output,
203    excluding the PID prefix.</p></dd>
204<dt><span class="term"><span class="command"><strong><code class="computeroutput">VALGRIND_PRINTF_BACKTRACE(format, ...)</code>:</strong></span></span></dt>
205<dd><p>Like <code class="computeroutput">VALGRIND_PRINTF</code> (in
206    particular, the return value is identical), but prints a stack backtrace
207    immediately afterwards.</p></dd>
208<dt><span class="term"><span class="command"><strong><code class="computeroutput">VALGRIND_MONITOR_COMMAND(command)</code>:</strong></span></span></dt>
209<dd><p>Execute the given monitor command (a string).
210    Returns 0 if command is recognised. Returns 1 if command is not recognised.
211    Note that some monitor commands provide access to a functionality
212    also accessible via a specific client request. For example,
213    memcheck leak search can be requested from the client program
214    using VALGRIND_DO_LEAK_CHECK or via the monitor command "leak_search".
215    Note that the syntax of the command string is only verified at
216    run-time. So, if it exists, it is preferable to use a specific
217    client request to have better compile time verifications of the
218    arguments.
219    </p></dd>
220<dt><span class="term"><span class="command"><strong><code class="computeroutput">VALGRIND_STACK_REGISTER(start, end)</code>:</strong></span></span></dt>
221<dd>
222<p>Registers a new stack.  Informs Valgrind that the memory range
223    between start and end is a unique stack.  Returns a stack identifier
224    that can be used with other
225    <code class="computeroutput">VALGRIND_STACK_*</code> calls.</p>
226<p>Valgrind will use this information to determine if a change
227    to the stack pointer is an item pushed onto the stack or a change
228    over to a new stack.  Use this if you're using a user-level thread
229    package and are noticing crashes in stack trace recording or
230    spurious errors from Valgrind about uninitialized memory
231    reads.</p>
232<p><span class="command"><strong>Warning:</strong></span> Unfortunately, this client request is
233    unreliable and best avoided.</p>
234</dd>
235<dt><span class="term"><span class="command"><strong><code class="computeroutput">VALGRIND_STACK_DEREGISTER(id)</code>:</strong></span></span></dt>
236<dd>
237<p>Deregisters a previously registered stack.  Informs
238    Valgrind that previously registered memory range with stack id
239    <code class="computeroutput">id</code> is no longer a stack.</p>
240<p><span class="command"><strong>Warning:</strong></span> Unfortunately, this client request is
241    unreliable and best avoided.</p>
242</dd>
243<dt><span class="term"><span class="command"><strong><code class="computeroutput">VALGRIND_STACK_CHANGE(id, start, end)</code>:</strong></span></span></dt>
244<dd>
245<p>Changes a previously registered stack.  Informs
246    Valgrind that the previously registered stack with stack id
247    <code class="computeroutput">id</code> has changed its start and end
248    values.  Use this if your user-level thread package implements
249    stack growth.</p>
250<p><span class="command"><strong>Warning:</strong></span> Unfortunately, this client request is
251    unreliable and best avoided.</p>
252</dd>
253</dl></div>
254</div>
255<div class="sect1">
256<div class="titlepage"><div><div><h2 class="title" style="clear: both">
257<a name="manual-core-adv.gdbserver"></a>3.2.�Debugging your program using Valgrind gdbserver and GDB</h2></div></div></div>
258<p>A program running under Valgrind is not executed directly by the
259CPU.  Instead it runs on a synthetic CPU provided by Valgrind.  This is
260why a debugger cannot debug your program when it runs on Valgrind.
261</p>
262<p>
263This section describes how GDB can interact with the
264Valgrind gdbserver to provide a fully debuggable program under
265Valgrind. Used in this way, GDB also provides an interactive usage of
266Valgrind core or tool functionalities, including incremental leak search
267under Memcheck and on-demand Massif snapshot production.
268</p>
269<div class="sect2">
270<div class="titlepage"><div><div><h3 class="title">
271<a name="manual-core-adv.gdbserver-simple"></a>3.2.1.�Quick Start: debugging in 3 steps</h3></div></div></div>
272<p>The simplest way to get started is to run Valgrind with the
273flag <code class="option">--vgdb-error=0</code>.  Then follow the on-screen
274directions, which give you the precise commands needed to start GDB
275and connect it to your program.</p>
276<p>Otherwise, here's a slightly more verbose overview.</p>
277<p>If you want to debug a program with GDB when using the Memcheck
278tool, start Valgrind like this:
279</p>
280<pre class="screen">
281valgrind --vgdb=yes --vgdb-error=0 prog
282</pre>
283<p>In another shell, start GDB:
284</p>
285<pre class="screen">
286gdb prog
287</pre>
288<p>Then give the following command to GDB:
289</p>
290<pre class="screen">
291(gdb) target remote | vgdb
292</pre>
293<p>You can now debug your program e.g. by inserting a breakpoint
294and then using the GDB <code class="computeroutput">continue</code>
295command.</p>
296<p>This quick start information is enough for basic usage of the
297Valgrind gdbserver.  The sections below describe more advanced
298functionality provided by the combination of Valgrind and GDB. Note
299that the command line flag <code class="option">--vgdb=yes</code> can be omitted,
300as this is the default value.
301</p>
302</div>
303<div class="sect2">
304<div class="titlepage"><div><div><h3 class="title">
305<a name="manual-core-adv.gdbserver-concept"></a>3.2.2.�Valgrind gdbserver overall organisation</h3></div></div></div>
306<p>The GNU GDB debugger is typically used to debug a process
307running on the same machine.  In this mode, GDB uses system calls to
308control and query the program being debugged.  This works well, but
309only allows GDB to debug a program running on the same computer.
310</p>
311<p>GDB can also debug processes running on a different computer.
312To achieve this, GDB defines a protocol (that is, a set of query and
313reply packets) that facilitates fetching the value of memory or
314registers, setting breakpoints, etc.  A gdbserver is an implementation
315of this "GDB remote debugging" protocol.  To debug a process running
316on a remote computer, a gdbserver (sometimes called a GDB stub)
317must run at the remote computer side.
318</p>
319<p>The Valgrind core provides a built-in gdbserver implementation,
320which is activated using <code class="option">--vgdb=yes</code>
321or <code class="option">--vgdb=full</code>.  This gdbserver allows the process
322running on Valgrind's synthetic CPU to be debugged remotely.
323GDB sends protocol query packets (such as "get register contents") to
324the Valgrind embedded gdbserver.  The gdbserver executes the queries
325(for example, it will get the register values of the synthetic CPU)
326and gives the results back to GDB.
327</p>
328<p>GDB can use various kinds of channels (TCP/IP, serial line, etc)
329to communicate with the gdbserver.  In the case of Valgrind's
330gdbserver, communication is done via a pipe and a small helper program
331called <a class="xref" href="manual-core-adv.html#manual-core-adv.vgdb" title="3.2.9.�vgdb command line options">vgdb</a>, which acts as an
332intermediary.  If no GDB is in use, vgdb can also be
333used to send monitor commands to the Valgrind gdbserver from a shell
334command line.
335</p>
336</div>
337<div class="sect2">
338<div class="titlepage"><div><div><h3 class="title">
339<a name="manual-core-adv.gdbserver-gdb"></a>3.2.3.�Connecting GDB to a Valgrind gdbserver</h3></div></div></div>
340<p>To debug a program "<code class="filename">prog</code>" running under
341Valgrind, you must ensure that the Valgrind gdbserver is activated by
342specifying either <code class="option">--vgdb=yes</code>
343or <code class="option">--vgdb=full</code>.  A secondary command line option,
344<code class="option">--vgdb-error=number</code>, can be used to tell the gdbserver
345only to become active once the specified number of errors have been
346shown.  A value of zero will therefore cause
347the gdbserver to become active at startup, which allows you to
348insert breakpoints before starting the run.  For example:
349</p>
350<pre class="screen">
351valgrind --tool=memcheck --vgdb=yes --vgdb-error=0 ./prog
352</pre>
353<p>The Valgrind gdbserver is invoked at startup
354and indicates it is waiting for a connection from a GDB:</p>
355<pre class="programlisting">
356==2418== Memcheck, a memory error detector
357==2418== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
358==2418== Using Valgrind-3.13.0.SVN and LibVEX; rerun with -h for copyright info
359==2418== Command: ./prog
360==2418==
361==2418== (action at startup) vgdb me ...
362</pre>
363<p>GDB (in another shell) can then be connected to the Valgrind gdbserver.
364For this, GDB must be started on the program <code class="filename">prog</code>:
365</p>
366<pre class="screen">
367gdb ./prog
368</pre>
369<p>You then indicate to GDB that you want to debug a remote target:
370</p>
371<pre class="screen">
372(gdb) target remote | vgdb
373</pre>
374<p>
375GDB then starts a vgdb relay application to communicate with the
376Valgrind embedded gdbserver:</p>
377<pre class="programlisting">
378(gdb) target remote | vgdb
379Remote debugging using | vgdb
380relaying data between gdb and process 2418
381Reading symbols from /lib/ld-linux.so.2...done.
382Reading symbols from /usr/lib/debug/lib/ld-2.11.2.so.debug...done.
383Loaded symbols for /lib/ld-linux.so.2
384[Switching to Thread 2418]
3850x001f2850 in _start () from /lib/ld-linux.so.2
386(gdb)
387</pre>
388<p>Note that vgdb is provided as part of the Valgrind
389distribution.  You do not need to install it separately.</p>
390<p>If vgdb detects that there are multiple Valgrind gdbservers that
391can be connected to, it will list all such servers and their PIDs, and
392then exit.  You can then reissue the GDB "target" command, but
393specifying the PID of the process you want to debug:
394</p>
395<pre class="programlisting">
396(gdb) target remote | vgdb
397Remote debugging using | vgdb
398no --pid= arg given and multiple valgrind pids found:
399use --pid=2479 for valgrind --tool=memcheck --vgdb=yes --vgdb-error=0 ./prog
400use --pid=2481 for valgrind --tool=memcheck --vgdb=yes --vgdb-error=0 ./prog
401use --pid=2483 for valgrind --vgdb=yes --vgdb-error=0 ./another_prog
402Remote communication error: Resource temporarily unavailable.
403(gdb)  target remote | vgdb --pid=2479
404Remote debugging using | vgdb --pid=2479
405relaying data between gdb and process 2479
406Reading symbols from /lib/ld-linux.so.2...done.
407Reading symbols from /usr/lib/debug/lib/ld-2.11.2.so.debug...done.
408Loaded symbols for /lib/ld-linux.so.2
409[Switching to Thread 2479]
4100x001f2850 in _start () from /lib/ld-linux.so.2
411(gdb)
412</pre>
413<p>Once GDB is connected to the Valgrind gdbserver, it can be used
414in the same way as if you were debugging the program natively:</p>
415<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
416<li class="listitem"><p>Breakpoints can be inserted or deleted.</p></li>
417<li class="listitem"><p>Variables and register values can be examined or modified.
418    </p></li>
419<li class="listitem"><p>Signal handling can be configured (printing, ignoring).
420    </p></li>
421<li class="listitem"><p>Execution can be controlled (continue, step, next, stepi, etc).
422    </p></li>
423<li class="listitem"><p>Program execution can be interrupted using Control-C.</p></li>
424</ul></div>
425<p>And so on.  Refer to the GDB user manual for a complete
426description of GDB's functionality.
427</p>
428</div>
429<div class="sect2">
430<div class="titlepage"><div><div><h3 class="title">
431<a name="manual-core-adv.gdbserver-gdb-android"></a>3.2.4.�Connecting to an Android gdbserver</h3></div></div></div>
432<p> When developping applications for Android, you will typically use
433a development system (on which the Android NDK is installed) to compile your
434application. An Android target system or emulator will be used to run
435the application.
436In this setup, Valgrind and vgdb will run on the Android system,
437while GDB will run on the development system. GDB will connect
438to the vgdb running on the Android system using the Android NDK
439'adb forward' application.
440</p>
441<p> Example: on the Android system, execute the following:
442    </p>
443<pre class="screen">
444valgrind --vgdb-error=0 --vgdb=yes prog
445# and then in another shell, run:
446vgdb --port=1234
447</pre>
448<p>
449</p>
450<p> On the development system, execute the following commands:
451</p>
452<pre class="screen">
453adb forward tcp:1234 tcp:1234
454gdb prog
455(gdb) target remote :1234
456</pre>
457<p>
458GDB will use a local tcp/ip connection to connect to the Android adb forwarder.
459Adb will establish a relay connection between the host system and the Android
460target system.  Be sure to use the GDB delivered in the
461Android NDK system (typically, arm-linux-androideabi-gdb), as the host
462GDB is probably not able to debug Android arm applications.
463Note that the local port nr (used by GDB) must not necessarily be equal
464to the port number used by vgdb: adb can forward tcp/ip between different
465port numbers.
466</p>
467<p>In the current release, the GDB server is not enabled by default
468for Android, due to problems in establishing a suitable directory in
469which Valgrind can create the necessary FIFOs (named pipes) for
470communication purposes.  You can stil try to use the GDB server, but
471you will need to explicitly enable it using the flag
472<code class="computeroutput">--vgdb=yes</code> or
473<code class="computeroutput">--vgdb=full</code>.
474</p>
475<p>Additionally, you
476will need to select a temporary directory which is (a) writable
477by Valgrind, and (b) supports FIFOs.  This is the main difficult
478point.  Often, <code class="computeroutput">/sdcard</code> satisfies
479requirement (a), but fails for (b) because it is a VFAT file system
480and VFAT does not support pipes.  Possibilities you could try are
481<code class="computeroutput">/data/local</code>,
482<code class="computeroutput">/data/local/Inst</code> (if you
483installed Valgrind there), or
484<code class="computeroutput">/data/data/name.of.my.app</code>, if you
485are running a specific application and it has its own directory of
486that form.  This last possibility may have the highest probability
487of success.</p>
488<p>You can specify the temporary directory to use either via
489the <code class="computeroutput">--with-tmpdir=</code> configure time
490flag, or by setting environment variable TMPDIR when running Valgrind
491(on the Android device, not on the Android NDK development host).
492Another alternative is to specify the directory for the FIFOs using
493the <code class="computeroutput">--vgdb-prefix=</code> Valgrind command
494line option.
495</p>
496<p>We hope to have a better story for temporary directory handling
497on Android in the future.  The difficulty is that, unlike in standard
498Unixes, there is no single temporary file directory that reliably
499works across all devices and scenarios.
500</p>
501</div>
502<div class="sect2">
503<div class="titlepage"><div><div><h3 class="title">
504<a name="manual-core-adv.gdbserver-commandhandling"></a>3.2.5.�Monitor command handling by the Valgrind gdbserver</h3></div></div></div>
505<p> The Valgrind gdbserver provides additional Valgrind-specific
506functionality via "monitor commands".  Such monitor commands can be
507sent from the GDB command line or from the shell command line or
508requested by the client program using the VALGRIND_MONITOR_COMMAND
509client request.  See
510<a class="xref" href="manual-core-adv.html#manual-core-adv.valgrind-monitor-commands" title="3.2.10.�Valgrind monitor commands">Valgrind monitor commands</a> for the
511list of the Valgrind core monitor commands available regardless of the
512Valgrind tool selected.
513</p>
514<p>The following tools provide tool-specific monitor commands:
515  </p>
516<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
517<li class="listitem"><p><a class="xref" href="mc-manual.html#mc-manual.monitor-commands" title="4.6.�Memcheck Monitor Commands">Memcheck Monitor Commands</a></p></li>
518<li class="listitem"><p><a class="xref" href="cl-manual.html#cl-manual.monitor-commands" title="6.4.�Callgrind Monitor Commands">Callgrind Monitor Commands</a></p></li>
519<li class="listitem"><p><a class="xref" href="ms-manual.html#ms-manual.monitor-commands" title="9.4.�Massif Monitor Commands">Massif Monitor Commands</a></p></li>
520<li class="listitem"><p><a class="xref" href="hg-manual.html#hg-manual.monitor-commands" title="7.7.�Helgrind Monitor Commands">Helgrind Monitor Commands</a></p></li>
521</ul></div>
522<p>
523</p>
524<p>An example of a tool specific monitor command is the Memcheck monitor
525command <code class="computeroutput">leak_check full
526reachable any</code>.  This requests a full reporting of the
527allocated memory blocks.  To have this leak check executed, use the GDB
528command:
529</p>
530<pre class="screen">
531(gdb) monitor leak_check full reachable any
532</pre>
533<p>
534</p>
535<p>GDB will send the <code class="computeroutput">leak_check</code>
536command to the Valgrind gdbserver.  The Valgrind gdbserver will
537execute the monitor command itself, if it recognises it to be a Valgrind core
538monitor command.  If it is not recognised as such, it is assumed to
539be tool-specific and is handed to the tool for execution.  For example:
540</p>
541<pre class="programlisting">
542(gdb) monitor leak_check full reachable any
543==2418== 100 bytes in 1 blocks are still reachable in loss record 1 of 1
544==2418==    at 0x4006E9E: malloc (vg_replace_malloc.c:236)
545==2418==    by 0x804884F: main (prog.c:88)
546==2418==
547==2418== LEAK SUMMARY:
548==2418==    definitely lost: 0 bytes in 0 blocks
549==2418==    indirectly lost: 0 bytes in 0 blocks
550==2418==      possibly lost: 0 bytes in 0 blocks
551==2418==    still reachable: 100 bytes in 1 blocks
552==2418==         suppressed: 0 bytes in 0 blocks
553==2418==
554(gdb)
555</pre>
556<p>As with other GDB commands, the Valgrind gdbserver will accept
557abbreviated monitor command names and arguments, as long as the given
558abbreviation is unambiguous.  For example, the above
559<code class="computeroutput">leak_check</code>
560command can also be typed as:
561</p>
562<pre class="screen">
563(gdb) mo l f r a
564</pre>
565<p>
566
567The letters <code class="computeroutput">mo</code> are recognised by GDB as being
568an abbreviation for <code class="computeroutput">monitor</code>.  So GDB sends the
569string <code class="computeroutput">l f r a</code> to the Valgrind
570gdbserver.  The letters provided in this string are unambiguous for the
571Valgrind gdbserver.  This therefore gives the same output as the
572unabbreviated command and arguments.  If the provided abbreviation is
573ambiguous, the Valgrind gdbserver will report the list of commands (or
574argument values) that can match:
575</p>
576<pre class="programlisting">
577(gdb) mo v. n
578v. can match v.set v.info v.wait v.kill v.translate v.do
579(gdb) mo v.i n
580n_errs_found 0 n_errs_shown 0 (vgdb-error 0)
581(gdb)
582</pre>
583<p>
584</p>
585<p>Instead of sending a monitor command from GDB, you can also send
586these from a shell command line.  For example, the following command
587lines, when given in a shell, will cause the same leak search to be executed
588by the process 3145:
589</p>
590<pre class="screen">
591vgdb --pid=3145 leak_check full reachable any
592vgdb --pid=3145 l f r a
593</pre>
594<p>Note that the Valgrind gdbserver automatically continues the
595execution of the program after a standalone invocation of
596vgdb.  Monitor commands sent from GDB do not cause the program to
597continue: the program execution is controlled explicitly using GDB
598commands such as "continue" or "next".</p>
599</div>
600<div class="sect2">
601<div class="titlepage"><div><div><h3 class="title">
602<a name="manual-core-adv.gdbserver-threads"></a>3.2.6.�Valgrind gdbserver thread information</h3></div></div></div>
603<p>Valgrind's gdbserver enriches the output of the
604GDB <code class="computeroutput">info threads</code> command
605with Valgrind-specific information.
606The operating system's thread number is followed
607by Valgrind's internal index for that thread ("tid") and by
608the Valgrind scheduler thread state:</p>
609<pre class="programlisting">
610(gdb) info threads
611  4 Thread 6239 (tid 4 VgTs_Yielding)  0x001f2832 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
612* 3 Thread 6238 (tid 3 VgTs_Runnable)  make_error (s=0x8048b76 "called from London") at prog.c:20
613  2 Thread 6237 (tid 2 VgTs_WaitSys)  0x001f2832 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
614  1 Thread 6234 (tid 1 VgTs_Yielding)  main (argc=1, argv=0xbedcc274) at prog.c:105
615(gdb)
616</pre>
617</div>
618<div class="sect2">
619<div class="titlepage"><div><div><h3 class="title">
620<a name="manual-core-adv.gdbserver-shadowregisters"></a>3.2.7.�Examining and modifying Valgrind shadow registers</h3></div></div></div>
621<p> When the option <code class="option">--vgdb-shadow-registers=yes</code> is
622given, the Valgrind gdbserver will let GDB examine and/or modify
623Valgrind's shadow registers.  GDB version 7.1 or later is needed for this
624to work. For x86 and amd64, GDB version 7.2 or later is needed.</p>
625<p>For each CPU register, the Valgrind core maintains two
626shadow register sets.  These shadow registers can be accessed from
627GDB by giving a postfix <code class="computeroutput">s1</code>
628or <code class="computeroutput">s2</code> for respectively the first
629and second shadow register.  For example, the x86 register
630<code class="computeroutput">eax</code> and its two shadows
631can be examined using the following commands:</p>
632<pre class="programlisting">
633(gdb) p $eax
634$1 = 0
635(gdb) p $eaxs1
636$2 = 0
637(gdb) p $eaxs2
638$3 = 0
639(gdb)
640</pre>
641<p>Float shadow registers are shown by GDB as unsigned integer
642values instead of float values, as it is expected that these
643shadow values are mostly used for memcheck validity bits. </p>
644<p>Intel/amd64 AVX registers <code class="computeroutput">ymm0</code>
645to <code class="computeroutput">ymm15</code> have also their shadow
646registers. However, GDB presents the shadow values using two
647"half" registers. For example, the half shadow registers for
648<code class="computeroutput">ymm9</code> are
649<code class="computeroutput">xmm9s1</code> (lower half for set 1),
650<code class="computeroutput">ymm9hs1</code> (upper half for set 1),
651<code class="computeroutput">xmm9s2</code> (lower half for set 2),
652<code class="computeroutput">ymm9hs2</code> (upper half for set 2).
653Note the inconsistent notation for the names of the half registers:
654the lower part starts with an <code class="computeroutput">x</code>,
655the upper part starts with an <code class="computeroutput">y</code>
656and has an <code class="computeroutput">h</code> before the shadow postfix.
657</p>
658<p>The special presentation of the AVX shadow registers is due to
659the fact that GDB independently retrieves the lower and upper half of
660the <code class="computeroutput">ymm</code> registers.  GDB does not
661however know that the shadow half registers have to be shown combined.
662</p>
663</div>
664<div class="sect2">
665<div class="titlepage"><div><div><h3 class="title">
666<a name="manual-core-adv.gdbserver-limitations"></a>3.2.8.�Limitations of the Valgrind gdbserver</h3></div></div></div>
667<p>Debugging with the Valgrind gdbserver is very similar to native
668debugging.  Valgrind's gdbserver implementation is quite
669complete, and so provides most of the GDB debugging functionality.  There
670are however some limitations and peculiarities:</p>
671<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
672<li class="listitem">
673<p>Precision of "stop-at" commands.</p>
674<p>
675       GDB commands such as "step", "next", "stepi", breakpoints
676       and watchpoints, will stop the execution of the process.  With
677       the option <code class="option">--vgdb=yes</code>, the process might not
678       stop at the exact requested instruction. Instead, it might
679       continue execution of the current basic block and stop at one
680       of the following basic blocks. This is linked to the fact that
681       Valgrind gdbserver has to instrument a block to allow stopping
682       at the exact instruction requested.  Currently,
683       re-instrumentation of the block currently being executed is not
684       supported. So, if the action requested by GDB (e.g. single
685       stepping or inserting a breakpoint) implies re-instrumentation
686       of the current block, the GDB action may not be executed
687       precisely.
688     </p>
689<p>
690       This limitation applies when the basic block
691       currently being executed has not yet been instrumented for debugging.
692       This typically happens when the gdbserver is activated due to the
693       tool reporting an error or to a watchpoint.  If the gdbserver
694       block has been activated following a breakpoint, or if a
695       breakpoint has been inserted in the block before its execution,
696       then the block has already been instrumented for debugging.
697     </p>
698<p>
699       If you use the option <code class="option">--vgdb=full</code>, then GDB
700       "stop-at" commands will be obeyed precisely.  The
701       downside is that this requires each instruction to be
702       instrumented with an additional call to a gdbserver helper
703       function, which gives considerable overhead (+500% for memcheck)
704       compared to  <code class="option">--vgdb=no</code>.
705       Option <code class="option">--vgdb=yes</code> has neglectible overhead compared
706       to <code class="option">--vgdb=no</code>.
707     </p>
708</li>
709<li class="listitem">
710<p>Processor registers and flags values.</p>
711<p>When Valgrind gdbserver stops on an error, on a breakpoint
712     or when single stepping, registers and flags values might not be always
713     up to date due to the optimisations done by the Valgrind core.
714     The default value
715     <code class="option">--vex-iropt-register-updates=unwindregs-at-mem-access</code>
716     ensures that the registers needed to make a stack trace (typically
717     PC/SP/FP) are up to date at each memory access (i.e. memory exception
718     points).
719     Disabling some optimisations using the following values will increase
720     the precision of registers and flags values (a typical performance
721     impact for memcheck is given for each option).
722       </p>
723<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; ">
724<li class="listitem">
725<code class="option">--vex-iropt-register-updates=allregs-at-mem-access</code> (+10%)
726           ensures that all registers and flags are up to date at each memory
727           access.
728         </li>
729<li class="listitem">
730<code class="option">--vex-iropt-register-updates=allregs-at-each-insn</code> (+25%)
731           ensures that all registers and flags are up to date at each instruction.
732         </li>
733</ul></div>
734<p>
735       Note that <code class="option">--vgdb=full</code> (+500%, see above
736       Precision of "stop-at" commands) automatically
737       activates <code class="option">--vex-iropt-register-updates=allregs-at-each-insn</code>.
738     </p>
739</li>
740<li class="listitem">
741<p>Hardware watchpoint support by the Valgrind
742     gdbserver.</p>
743<p> The Valgrind gdbserver can simulate hardware watchpoints
744     if the selected tool provides support for it.  Currently,
745     only Memcheck provides hardware watchpoint simulation.  The
746     hardware watchpoint simulation provided by Memcheck is much
747     faster that GDB software watchpoints, which are implemented by
748     GDB checking the value of the watched zone(s) after each
749     instruction.  Hardware watchpoint simulation also provides read
750     watchpoints.  The hardware watchpoint simulation by Memcheck has
751     some limitations compared to real hardware
752     watchpoints. However, the number and length of simulated
753     watchpoints are not limited.
754     </p>
755<p>Typically, the number of (real) hardware watchpoints is
756     limited.  For example, the x86 architecture supports a maximum of
757     4 hardware watchpoints, each watchpoint watching 1, 2, 4 or 8
758     bytes. The Valgrind gdbserver does not have any limitation on the
759     number of simulated hardware watchpoints. It also has no
760     limitation on the length of the memory zone being
761     watched.  Using GDB version 7.4 or later allow full use of the
762     flexibility of the Valgrind gdbserver's simulated hardware watchpoints.
763     Previous GDB versions do not understand that Valgrind gdbserver
764     watchpoints have no length limit.
765     </p>
766<p>Memcheck implements hardware watchpoint simulation by
767     marking the watched address ranges as being unaddressable.  When
768     a hardware watchpoint is removed, the range is marked as
769     addressable and defined.  Hardware watchpoint simulation of
770     addressable-but-undefined memory zones works properly, but has
771     the undesirable side effect of marking the zone as defined when
772     the watchpoint is removed.
773     </p>
774<p>Write watchpoints might not be reported at the
775     exact instruction that writes the monitored area,
776     unless option <code class="option">--vgdb=full</code> is given.  Read watchpoints
777     will always be reported at the exact instruction reading the
778     watched memory.
779     </p>
780<p>It is better to avoid using hardware watchpoint of not
781     addressable (yet) memory: in such a case, GDB will fall back to
782     extremely slow software watchpoints.  Also, if you do not quit GDB
783     between two debugging sessions, the hardware watchpoints of the
784     previous sessions will be re-inserted as software watchpoints if
785     the watched memory zone is not addressable at program startup.
786     </p>
787</li>
788<li class="listitem">
789<p>Stepping inside shared libraries on ARM.</p>
790<p>For unknown reasons, stepping inside shared
791     libraries on ARM may fail.  A workaround is to use the
792     <code class="computeroutput">ldd</code> command
793     to find the list of shared libraries and their loading address
794     and inform GDB of the loading address using the GDB command
795     "add-symbol-file". Example:
796     </p>
797<pre class="programlisting">
798(gdb) shell ldd ./prog
799	libc.so.6 =&gt; /lib/libc.so.6 (0x4002c000)
800	/lib/ld-linux.so.3 (0x40000000)
801(gdb) add-symbol-file /lib/libc.so.6 0x4002c000
802add symbol table from file "/lib/libc.so.6" at
803	.text_addr = 0x4002c000
804(y or n) y
805Reading symbols from /lib/libc.so.6...(no debugging symbols found)...done.
806(gdb)
807</pre>
808<p>
809     </p>
810</li>
811<li class="listitem">
812<p>GDB version needed for ARM and PPC32/64.</p>
813<p>You must use a GDB version which is able to read XML
814     target description sent by a gdbserver.  This is the standard setup
815     if GDB was configured and built with the "expat"
816     library.  If your GDB was not configured with XML support, it
817     will report an error message when using the "target"
818     command.  Debugging will not work because GDB will then not be
819     able to fetch the registers from the Valgrind gdbserver.
820     For ARM programs using the Thumb instruction set, you must use
821     a GDB version of 7.1 or later, as earlier versions have problems
822     with next/step/breakpoints in Thumb code.
823     </p>
824</li>
825<li class="listitem">
826<p>Stack unwinding on PPC32/PPC64. </p>
827<p>On PPC32/PPC64, stack unwinding for leaf functions
828     (functions that do not call any other functions) works properly
829     only when you give the option
830     <code class="option">--vex-iropt-register-updates=allregs-at-mem-access</code>
831     or <code class="option">--vex-iropt-register-updates=allregs-at-each-insn</code>.
832     You must also pass this option in order to get a precise stack when
833     a signal is trapped by GDB.
834     </p>
835</li>
836<li class="listitem">
837<p>Breakpoints encountered multiple times.</p>
838<p>Some instructions (e.g. x86 "rep movsb")
839     are translated by Valgrind using a loop.  If a breakpoint is placed
840     on such an instruction, the breakpoint will be encountered
841     multiple times -- once for each step of the "implicit" loop
842     implementing the instruction.
843     </p>
844</li>
845<li class="listitem">
846<p>Execution of Inferior function calls by the Valgrind
847     gdbserver.</p>
848<p>GDB allows the user to "call" functions inside the process
849     being debugged.  Such calls are named "inferior calls" in the GDB
850     terminology.  A typical use of an inferior call is to execute
851     a function that prints a human-readable version of a complex data
852     structure.  To make an inferior call, use the GDB "print" command
853     followed by the function to call and its arguments.  As an
854     example, the following GDB command causes an inferior call to the
855     libc "printf" function to be executed by the process
856     being debugged:
857     </p>
858<pre class="programlisting">
859(gdb) p printf("process being debugged has pid %d\n", getpid())
860$5 = 36
861(gdb)
862</pre>
863<p>The Valgrind gdbserver supports inferior function calls.
864     Whilst an inferior call is running, the Valgrind tool will report
865     errors as usual.  If you do not want to have such errors stop the
866     execution of the inferior call, you can
867     use <code class="computeroutput">v.set vgdb-error</code> to set a
868     big value before the call, then manually reset it to its original
869     value when the call is complete.</p>
870<p>To execute inferior calls, GDB changes registers such as
871     the program counter, and then continues the execution of the
872     program. In a multithreaded program, all threads are continued,
873     not just the thread instructed to make the inferior call.  If
874     another thread reports an error or encounters a breakpoint, the
875     evaluation of the inferior call is abandoned.</p>
876<p>Note that inferior function calls are a powerful GDB
877     feature, but should be used with caution. For example, if
878     the program being debugged is stopped inside the function "printf",
879     forcing a recursive call to printf via an inferior call will
880     very probably create problems.  The Valgrind tool might also add
881     another level of complexity to inferior calls, e.g. by reporting
882     tool errors during the Inferior call or due to the
883     instrumentation done.
884     </p>
885</li>
886<li class="listitem">
887<p>Connecting to or interrupting a Valgrind process blocked in
888     a system call.</p>
889<p>Connecting to or interrupting a Valgrind process blocked in
890     a system call requires the "ptrace" system call to be usable.
891     This may be disabled in your kernel for security reasons.
892     </p>
893<p>When running your program, Valgrind's scheduler
894     periodically checks whether there is any work to be handled by
895     the gdbserver.  Unfortunately this check is only done if at least
896     one thread of the process is runnable.  If all the threads of the
897     process are blocked in a system call, then the checks do not
898     happen, and the Valgrind scheduler will not invoke the gdbserver.
899     In such a case, the vgdb relay application will "force" the
900     gdbserver to be invoked, without the intervention of the Valgrind
901     scheduler.
902     </p>
903<p>Such forced invocation of the Valgrind gdbserver is
904     implemented by vgdb using ptrace system calls.  On a properly
905     implemented kernel, the ptrace calls done by vgdb will not
906     influence the behaviour of the program running under Valgrind.
907     If however they do, giving the
908     option <code class="option">--max-invoke-ms=0</code> to the vgdb relay
909     application will disable the usage of ptrace calls.  The
910     consequence of disabling ptrace usage in vgdb is that a Valgrind
911     process blocked in a system call cannot be woken up or
912     interrupted from GDB until it executes enough basic blocks to let
913     the Valgrind scheduler's normal checking take effect.
914     </p>
915<p>When ptrace is disabled in vgdb, you can increase the
916     responsiveness of the Valgrind gdbserver to commands or
917     interrupts by giving a lower value to the
918     option <code class="option">--vgdb-poll</code>.  If your application is
919     blocked in system calls most of the time, using a very low value
920     for <code class="option">--vgdb-poll</code> will cause a the gdbserver to be
921     invoked sooner.  The gdbserver polling done by Valgrind's
922     scheduler is very efficient, so the increased polling frequency
923     should not cause significant performance degradation.
924     </p>
925<p>When ptrace is disabled in vgdb, a query packet sent by GDB
926     may take significant time to be handled by the Valgrind
927     gdbserver.  In such cases, GDB might encounter a protocol
928     timeout.  To avoid this,
929     you can increase the value of the timeout by using the GDB
930     command "set remotetimeout".
931     </p>
932<p>Ubuntu versions 10.10 and later may restrict the scope of
933     ptrace to the children of the process calling ptrace.  As the
934     Valgrind process is not a child of vgdb, such restricted scoping
935     causes the ptrace calls to fail.  To avoid that, Valgrind will
936     automatically allow all processes belonging to the same userid to
937     "ptrace" a Valgrind process, by using PR_SET_PTRACER.</p>
938<p>Unblocking processes blocked in system calls is not
939     currently implemented on Mac OS X and Android.  So you cannot
940     connect to or interrupt a process blocked in a system call on Mac
941     OS X or Android.
942     </p>
943<p>Unblocking processes blocked in system calls is implemented
944     via agent thread on Solaris. This is quite a different approach
945     than using ptrace on Linux, but leads to equivalent result - Valgrind
946     gdbserver is invoked. Note that agent thread is a Solaris OS
947     feature and cannot be disabled.
948     </p>
949</li>
950<li class="listitem">
951<p>Changing register values.</p>
952<p>The Valgrind gdbserver will only modify the values of the
953     thread's registers when the thread is in status Runnable or
954     Yielding.  In other states (typically, WaitSys), attempts to
955     change register values will fail.  Amongst other things, this
956     means that inferior calls are not executed for a thread which is
957     in a system call, since the Valgrind gdbserver does not implement
958     system call restart.
959     </p>
960</li>
961<li class="listitem">
962<p>Unsupported GDB functionality.</p>
963<p>GDB provides a lot of debugging functionality and not all
964     of it is supported.  Specifically, the following are not
965     supported: reversible debugging and tracepoints.
966     </p>
967</li>
968<li class="listitem">
969<p>Unknown limitations or problems.</p>
970<p>The combination of GDB, Valgrind and the Valgrind gdbserver
971     probably has unknown other limitations and problems.  If you
972     encounter strange or unexpected behaviour, feel free to report a
973     bug.  But first please verify that the limitation or problem is
974     not inherent to GDB or the GDB remote protocol.  You may be able
975     to do so by checking the behaviour when using standard gdbserver
976     part of the GDB package.
977     </p>
978</li>
979</ul></div>
980</div>
981<div class="sect2">
982<div class="titlepage"><div><div><h3 class="title">
983<a name="manual-core-adv.vgdb"></a>3.2.9.�vgdb command line options</h3></div></div></div>
984<p> Usage: <code class="computeroutput">vgdb [OPTION]... [[-c] COMMAND]...</code></p>
985<p> vgdb ("Valgrind to GDB") is a small program that is used as an
986intermediary between Valgrind and GDB or a shell.
987Therefore, it has two usage modes:
988</p>
989<div class="orderedlist">
990<a name="vgdb.desc.modes"></a><ol class="orderedlist" type="1">
991<li class="listitem"><p><a name="manual-core-adv.vgdb-standalone"></a>As a standalone utility, it is used from a shell command
992    line to send monitor commands to a process running under
993    Valgrind. For this usage, the vgdb OPTION(s) must be followed by
994    the monitor command to send. To send more than one command,
995    separate them with the <code class="option">-c</code> option.
996    </p></li>
997<li class="listitem"><p><a name="manual-core-adv.vgdb-relay"></a>In combination with GDB "target remote |" command, it is
998    used as the relay application between GDB and the Valgrind
999    gdbserver.  For this usage, only OPTION(s) can be given, but no
1000    COMMAND can be given.
1001    </p></li>
1002</ol>
1003</div>
1004<p><code class="computeroutput">vgdb</code> accepts the following
1005options:</p>
1006<div class="variablelist">
1007<a name="vgdb.opts.list"></a><dl class="variablelist">
1008<dt><span class="term"><code class="option">--pid=&lt;number&gt;</code></span></dt>
1009<dd><p>Specifies the PID of
1010    the process to which vgdb must connect to.  This option is useful
1011    in case more than one Valgrind gdbserver can be connected to.  If
1012    the <code class="option">--pid</code> argument is not given and multiple
1013    Valgrind gdbserver processes are running, vgdb will report the
1014    list of such processes and then exit.</p></dd>
1015<dt><span class="term"><code class="option">--vgdb-prefix</code></span></dt>
1016<dd><p>Must be given to both
1017    Valgrind and vgdb if you want to change the default prefix for the
1018    FIFOs (named pipes) used for communication between the Valgrind
1019    gdbserver and vgdb.</p></dd>
1020<dt><span class="term"><code class="option">--wait=&lt;number&gt;</code></span></dt>
1021<dd><p>Instructs vgdb to
1022    search for available Valgrind gdbservers for the specified number
1023    of seconds.  This makes it possible start a vgdb process
1024    before starting the Valgrind gdbserver with which you intend the
1025    vgdb to communicate.  This option is useful when used in
1026    conjunction with a <code class="option">--vgdb-prefix</code> that is
1027    unique to the process you want to wait for.
1028    Also, if you use the <code class="option">--wait</code> argument in the GDB
1029    "target remote" command, you must set the GDB remotetimeout to a
1030    value bigger than the --wait argument value.  See option
1031    <code class="option">--max-invoke-ms</code> (just below)
1032    for an example of setting the remotetimeout value.</p></dd>
1033<dt><span class="term"><code class="option">--max-invoke-ms=&lt;number&gt;</code></span></dt>
1034<dd>
1035<p>Gives the
1036    number of milliseconds after which vgdb will force the invocation
1037    of gdbserver embedded in Valgrind.  The default value is 100
1038    milliseconds. A value of 0 disables forced invocation. The forced
1039    invocation is used when vgdb is connected to a Valgrind gdbserver,
1040    and the Valgrind process has all its threads blocked in a system
1041    call.
1042    </p>
1043<p>If you specify a large value, you might need to increase the
1044    GDB "remotetimeout" value from its default value of 2 seconds.
1045    You should ensure that the timeout (in seconds) is
1046    bigger than the <code class="option">--max-invoke-ms</code> value.  For
1047    example, for <code class="option">--max-invoke-ms=5000</code>, the following
1048    GDB command is suitable:
1049    </p>
1050<pre class="screen">
1051    (gdb) set remotetimeout 6
1052    </pre>
1053<p>
1054    </p>
1055</dd>
1056<dt><span class="term"><code class="option">--cmd-time-out=&lt;number&gt;</code></span></dt>
1057<dd><p>Instructs a
1058    standalone vgdb to exit if the Valgrind gdbserver it is connected
1059    to does not process a command in the specified number of seconds.
1060    The default value is to never time out.</p></dd>
1061<dt><span class="term"><code class="option">--port=&lt;portnr&gt;</code></span></dt>
1062<dd>
1063<p>Instructs vgdb to
1064    use tcp/ip and listen for GDB on the specified port nr rather than
1065    to use a pipe to communicate with GDB. Using tcp/ip allows to have
1066    GDB running on one computer and debugging a Valgrind process
1067    running on another target computer.
1068    Example:
1069    </p>
1070<pre class="screen">
1071# On the target computer, start your program under valgrind using
1072valgrind --vgdb-error=0 prog
1073# and then in another shell, run:
1074vgdb --port=1234
1075</pre>
1076<p>On the computer which hosts GDB, execute the command:
1077    </p>
1078<pre class="screen">
1079gdb prog
1080(gdb) target remote targetip:1234
1081</pre>
1082<p>
1083    where targetip is the ip address or hostname of the target computer.
1084    </p>
1085</dd>
1086<dt><span class="term"><code class="option">-c</code></span></dt>
1087<dd>
1088<p>To give more than one command to a
1089    standalone vgdb, separate the commands by an
1090    option <code class="option">-c</code>. Example:
1091    </p>
1092<pre class="screen">
1093vgdb v.set log_output -c leak_check any
1094</pre>
1095</dd>
1096<dt><span class="term"><code class="option">-l</code></span></dt>
1097<dd><p>Instructs a standalone vgdb to report
1098    the list of the Valgrind gdbserver processes running and then
1099    exit.</p></dd>
1100<dt><span class="term"><code class="option">-D</code></span></dt>
1101<dd><p>Instructs a standalone vgdb to show the
1102    state of the shared memory used by the Valgrind gdbserver.  vgdb
1103    will exit after having shown the Valgrind gdbserver shared memory
1104    state.</p></dd>
1105<dt><span class="term"><code class="option">-d</code></span></dt>
1106<dd><p>Instructs vgdb to produce debugging
1107    output.  Give multiple <code class="option">-d</code> args to increase the
1108    verbosity. When giving <code class="option">-d</code> to a relay vgdb, you better
1109    redirect the standard error (stderr) of vgdb to a file to avoid
1110    interaction between GDB and vgdb debugging output.</p></dd>
1111</dl>
1112</div>
1113</div>
1114<div class="sect2">
1115<div class="titlepage"><div><div><h3 class="title">
1116<a name="manual-core-adv.valgrind-monitor-commands"></a>3.2.10.�Valgrind monitor commands</h3></div></div></div>
1117<p>This section describes the Valgrind monitor commands, available
1118regardless of the Valgrind tool selected. For the tool specific
1119commands, refer to <a class="xref" href="mc-manual.html#mc-manual.monitor-commands" title="4.6.�Memcheck Monitor Commands">Memcheck Monitor Commands</a>,
1120<a class="xref" href="hg-manual.html#hg-manual.monitor-commands" title="7.7.�Helgrind Monitor Commands">Helgrind Monitor Commands</a>,
1121<a class="xref" href="cl-manual.html#cl-manual.monitor-commands" title="6.4.�Callgrind Monitor Commands">Callgrind Monitor Commands</a> and
1122<a class="xref" href="ms-manual.html#ms-manual.monitor-commands" title="9.4.�Massif Monitor Commands">Massif Monitor Commands</a>. </p>
1123<p> The monitor commands can be sent either from a shell command line, by using a
1124standalone vgdb, or from GDB, by using GDB's "monitor"
1125command (see <a class="xref" href="manual-core-adv.html#manual-core-adv.gdbserver-commandhandling" title="3.2.5.�Monitor command handling by the Valgrind gdbserver">Monitor command handling by the Valgrind gdbserver</a>).
1126They can also be launched by the client program, using the VALGRIND_MONITOR_COMMAND
1127client request.
1128</p>
1129<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
1130<li class="listitem"><p><code class="varname">help [debug]</code> instructs Valgrind's gdbserver
1131    to give the list of all monitor commands of the Valgrind core and
1132    of the tool. The optional "debug" argument tells to also give help
1133    for the monitor commands aimed at Valgrind internals debugging.
1134    </p></li>
1135<li class="listitem"><p><code class="varname">v.info all_errors</code> shows all errors found
1136    so far.</p></li>
1137<li class="listitem"><p><code class="varname">v.info last_error</code> shows the last error
1138    found.</p></li>
1139<li class="listitem">
1140<p><code class="varname">v.info location &lt;addr&gt;</code> outputs
1141    information about the location &lt;addr&gt;. Possibly, the
1142    following are described: global variables, local (stack)
1143    variables, allocated or freed blocks, ...  The information
1144    produced depends on the tool and on the options given to valgrind.
1145    Some tools (e.g. memcheck and helgrind) produce more detailed
1146    information for client heap blocks. For example, these tools show
1147    the stacktrace where the heap block was allocated. If a tool does
1148    not replace the malloc/free/... functions, then client heap blocks
1149    will not be described.  Use the
1150    option <code class="varname">--read-var-info=yes</code> to obtain more
1151    detailed information about global or local (stack) variables.
1152    </p>
1153<pre class="programlisting">
1154(gdb) monitor v.info location 0x8050b20
1155 Location 0x8050b20 is 0 bytes inside global var "mx"
1156 declared at tc19_shadowmem.c:19
1157
1158(gdb) mo v.in loc 0x582f33c
1159 Location 0x582f33c is 0 bytes inside local var "info"
1160 declared at tc19_shadowmem.c:282, in frame #1 of thread 3
1161(gdb)
1162</pre>
1163</li>
1164<li class="listitem"><p><code class="varname">v.info n_errs_found [msg]</code> shows the number of
1165    errors found so far, the nr of errors shown so far and the current
1166    value of the <code class="option">--vgdb-error</code> argument. The optional
1167    <code class="computeroutput">msg</code> (one or more words) is appended.
1168    Typically, this can be used to insert markers in a process output
1169    file between several tests executed in sequence by a process
1170    started only once. This allows to associate the errors reported
1171    by Valgrind with the specific test that produced these errors.
1172    </p></li>
1173<li class="listitem"><p><code class="varname">v.info open_fds</code> shows the list of open file
1174    descriptors and details related to the file descriptor.
1175    This only works if <code class="option">--track-fds=yes</code>
1176    was given at Valgrind startup.</p></li>
1177<li class="listitem">
1178<p><code class="varname">v.set {gdb_output | log_output |
1179    mixed_output}</code> allows redirection of the Valgrind output
1180    (e.g. the errors detected by the tool).  The default setting is
1181    <code class="computeroutput">mixed_output</code>.</p>
1182<p>With <code class="computeroutput">mixed_output</code>, the
1183    Valgrind output goes to the Valgrind log (typically stderr) while
1184    the output of the interactive GDB monitor commands (e.g.
1185    <code class="computeroutput">v.info last_error</code>)
1186    is displayed by GDB.</p>
1187<p>With <code class="computeroutput">gdb_output</code>, both the
1188    Valgrind output and the interactive GDB monitor commands output are
1189    displayed by GDB.</p>
1190<p>With <code class="computeroutput">log_output</code>, both the
1191    Valgrind output and the interactive GDB monitor commands output go
1192    to the Valgrind log.</p>
1193</li>
1194<li class="listitem"><p><code class="varname">v.wait [ms (default 0)]</code> instructs
1195    Valgrind gdbserver to sleep "ms" milli-seconds and then
1196    continue.  When sent from a standalone vgdb, if this is the last
1197    command, the Valgrind process will continue the execution of the
1198    guest process. The typical usage of this is to use vgdb to send a
1199    "no-op" command to a Valgrind gdbserver so as to continue the
1200    execution of the guest process.
1201    </p></li>
1202<li class="listitem"><p><code class="varname">v.kill</code> requests the gdbserver to kill
1203    the process. This can be used from a standalone vgdb to properly
1204    kill a Valgrind process which is currently expecting a vgdb
1205    connection.</p></li>
1206<li class="listitem"><p><code class="varname">v.set vgdb-error &lt;errornr&gt;</code>
1207    dynamically changes the value of the
1208    <code class="option">--vgdb-error</code> argument. A
1209    typical usage of this is to start with
1210    <code class="option">--vgdb-error=0</code> on the
1211    command line, then set a few breakpoints, set the vgdb-error value
1212    to a huge value and continue execution.</p></li>
1213<li class="listitem"><p><code class="varname">xtmemory [&lt;filename&gt; default xtmemory.kcg.%p.%n]</code>
1214      requests the tool to produce an xtree heap memory report.
1215      See <a class="xref" href="manual-core.html#manual-core.xtree" title="2.9.�Execution Trees">Execution Trees</a> for
1216      a detailed explanation about execution trees. </p></li>
1217</ul></div>
1218<p>The following Valgrind monitor commands are useful for
1219investigating the behaviour of Valgrind or its gdbserver in case of
1220problems or bugs.</p>
1221<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
1222<li class="listitem"><p><code class="varname">v.do expensive_sanity_check_general</code>
1223    executes various sanity checks. In particular, the sanity of the
1224    Valgrind heap is verified. This can be useful if you suspect that
1225    your program and/or Valgrind has a bug corrupting Valgrind data
1226    structure.  It can also be used when a Valgrind tool
1227    reports a client error to the connected GDB, in order to verify
1228    the sanity of Valgrind before continuing the execution.
1229    </p></li>
1230<li class="listitem"><p><code class="varname">v.info gdbserver_status</code> shows the
1231    gdbserver status. In case of problems (e.g. of communications),
1232    this shows the values of some relevant Valgrind gdbserver internal
1233    variables.  Note that the variables related to breakpoints and
1234    watchpoints (e.g. the number of breakpoint addresses and the number of
1235    watchpoints) will be zero, as GDB by default removes all
1236    watchpoints and breakpoints when execution stops, and re-inserts
1237    them when resuming the execution of the debugged process.  You can
1238    change this GDB behaviour by using the GDB command
1239    <code class="computeroutput">set breakpoint always-inserted on</code>.
1240    </p></li>
1241<li class="listitem"><p><code class="varname">v.info memory [aspacemgr]</code> shows the statistics of
1242    Valgrind's internal heap management. If
1243    option <code class="option">--profile-heap=yes</code> was given, detailed
1244    statistics will be output. With the optional argument
1245    <code class="computeroutput">aspacemgr</code>. the segment list maintained
1246    by valgrind address space manager will be output. Note that
1247    this list of segments is always output on the Valgrind log.
1248    </p></li>
1249<li class="listitem"><p><code class="varname">v.info exectxt</code> shows information about
1250    the "executable contexts" (i.e. the stack traces) recorded by
1251    Valgrind.  For some programs, Valgrind can record a very high
1252    number of such stack traces, causing a high memory usage.  This
1253    monitor command shows all the recorded stack traces, followed by
1254    some statistics. This can be used to analyse the reason for having
1255    a big number of stack traces. Typically, you will use this command
1256    if <code class="varname">v.info memory</code> has shown significant memory
1257    usage by the "exectxt" arena.
1258    </p></li>
1259<li class="listitem">
1260<p><code class="varname">v.info scheduler</code> shows various
1261    information about threads. First, it outputs the host stack trace,
1262    i.e. the Valgrind code being executed. Then, for each thread, it
1263    outputs the thread state. For non terminated threads, the state is
1264    followed by the guest (client) stack trace. Finally, for each
1265    active thread or for each terminated thread slot not yet re-used,
1266    it shows the max usage of the valgrind stack.</p>
1267<p>Showing the client stack traces allows to compare the stack
1268    traces produced by the Valgrind unwinder with the stack traces
1269    produced by GDB+Valgrind gdbserver. Pay attention that GDB and
1270    Valgrind scheduler status have their own thread numbering
1271    scheme. To make the link between the GDB thread number and the
1272    corresponding Valgrind scheduler thread number, use the GDB
1273    command <code class="computeroutput">info threads</code>.  The output
1274    of this command shows the GDB thread number and the valgrind
1275    'tid'. The 'tid' is the thread number output
1276    by <code class="computeroutput">v.info scheduler</code>.  When using
1277    the callgrind tool, the callgrind monitor command
1278    <code class="computeroutput">status</code> outputs internal callgrind
1279    information about the stack/call graph it maintains.
1280    </p>
1281</li>
1282<li class="listitem"><p><code class="varname">v.info stats</code> shows various valgrind core and
1283    tool statistics. With this, Valgrind and tool statistics can
1284    be examined while running, even without option <code class="option">--stats=yes</code>.
1285    </p></li>
1286<li class="listitem"><p><code class="varname">v.info unwind  &lt;addr&gt; [&lt;len&gt;]</code> shows
1287    the CFI unwind debug info for the address range [addr, addr+len-1].
1288    The default value of &lt;len&gt; is 1, giving the unwind information
1289    for the instruction at &lt;addr&gt;.
1290    </p></li>
1291<li class="listitem"><p><code class="varname">v.set debuglog &lt;intvalue&gt;</code> sets the
1292    Valgrind debug log level to &lt;intvalue&gt;.  This allows to
1293    dynamically change the log level of Valgrind e.g. when a problem
1294    is detected.</p></li>
1295<li class="listitem">
1296<p><code class="varname">v.set hostvisibility [yes*|no]</code> The value
1297    "yes" indicates to gdbserver that GDB can look at the Valgrind
1298    'host' (internal) status/memory. "no" disables this access.
1299    When hostvisibility is activated, GDB can e.g. look at Valgrind
1300    global variables. As an example, to examine a Valgrind global
1301    variable of the memcheck tool on an x86, do the following setup:</p>
1302<pre class="screen">
1303(gdb) monitor v.set hostvisibility yes
1304(gdb) add-symbol-file /path/to/tool/executable/file/memcheck-x86-linux 0x58000000
1305add symbol table from file "/path/to/tool/executable/file/memcheck-x86-linux" at
1306	.text_addr = 0x58000000
1307(y or n) y
1308Reading symbols from /path/to/tool/executable/file/memcheck-x86-linux...done.
1309(gdb)
1310</pre>
1311<p>After that, variables defined in memcheck-x86-linux can be accessed, e.g.</p>
1312<pre class="screen">
1313(gdb) p /x vgPlain_threads[1].os_state
1314$3 = {lwpid = 0x4688, threadgroup = 0x4688, parent = 0x0,
1315  valgrind_stack_base = 0x62e78000, valgrind_stack_init_SP = 0x62f79fe0,
1316  exitcode = 0x0, fatalsig = 0x0}
1317(gdb) p vex_control
1318$5 = {iropt_verbosity = 0, iropt_level = 2,
1319  iropt_register_updates = VexRegUpdUnwindregsAtMemAccess,
1320  iropt_unroll_thresh = 120, guest_max_insns = 60, guest_chase_thresh = 10,
1321  guest_chase_cond = 0 '\000'}
1322(gdb)
1323</pre>
1324</li>
1325<li class="listitem">
1326<p><code class="varname">v.translate &lt;address&gt;
1327    [&lt;traceflags&gt;]</code> shows the translation of the block
1328    containing <code class="computeroutput">address</code> with the given
1329    trace flags. The <code class="computeroutput">traceflags</code> value
1330    bit patterns have similar meaning to Valgrind's
1331    <code class="option">--trace-flags</code> option.  It can be given
1332    in hexadecimal (e.g. 0x20) or decimal (e.g. 32) or in binary 1s
1333    and 0s bit (e.g. 0b00100000). The default value of the traceflags
1334    is 0b00100000, corresponding to "show after instrumentation".
1335    The output of this command always goes to the Valgrind
1336    log.</p>
1337<p>The additional bit flag 0b100000000 (bit 8)
1338    has no equivalent in the <code class="option">--trace-flags</code> option.
1339    It enables tracing of the gdbserver specific instrumentation.  Note
1340    that this bit 8 can only enable the addition of gdbserver
1341    instrumentation in the trace.  Setting it to 0 will not
1342    disable the tracing of the gdbserver instrumentation if it is
1343    active for some other reason, for example because there is a breakpoint at
1344    this address or because gdbserver is in single stepping
1345    mode.</p>
1346</li>
1347</ul></div>
1348</div>
1349</div>
1350<div class="sect1">
1351<div class="titlepage"><div><div><h2 class="title" style="clear: both">
1352<a name="manual-core-adv.wrapping"></a>3.3.�Function wrapping</h2></div></div></div>
1353<p>
1354Valgrind allows calls to some specified functions to be intercepted and
1355rerouted to a different, user-supplied function.  This can do whatever it
1356likes, typically examining the arguments, calling onwards to the original,
1357and possibly examining the result.  Any number of functions may be
1358wrapped.</p>
1359<p>
1360Function wrapping is useful for instrumenting an API in some way.  For
1361example, Helgrind wraps functions in the POSIX pthreads API so it can know
1362about thread status changes, and the core is able to wrap
1363functions in the MPI (message-passing) API so it can know
1364of memory status changes associated with message arrival/departure.
1365Such information is usually passed to Valgrind by using client
1366requests in the wrapper functions, although the exact mechanism may vary.
1367</p>
1368<div class="sect2">
1369<div class="titlepage"><div><div><h3 class="title">
1370<a name="manual-core-adv.wrapping.example"></a>3.3.1.�A Simple Example</h3></div></div></div>
1371<p>Supposing we want to wrap some function</p>
1372<pre class="programlisting">
1373int foo ( int x, int y ) { return x + y; }</pre>
1374<p>A wrapper is a function of identical type, but with a special name
1375which identifies it as the wrapper for <code class="computeroutput">foo</code>.
1376Wrappers need to include
1377supporting macros from <code class="filename">valgrind.h</code>.
1378Here is a simple wrapper which prints the arguments and return value:</p>
1379<pre class="programlisting">
1380#include &lt;stdio.h&gt;
1381#include "valgrind.h"
1382int I_WRAP_SONAME_FNNAME_ZU(NONE,foo)( int x, int y )
1383{
1384   int    result;
1385   OrigFn fn;
1386   VALGRIND_GET_ORIG_FN(fn);
1387   printf("foo's wrapper: args %d %d\n", x, y);
1388   CALL_FN_W_WW(result, fn, x,y);
1389   printf("foo's wrapper: result %d\n", result);
1390   return result;
1391}
1392</pre>
1393<p>To become active, the wrapper merely needs to be present in a text
1394section somewhere in the same process' address space as the function
1395it wraps, and for its ELF symbol name to be visible to Valgrind.  In
1396practice, this means either compiling to a
1397<code class="computeroutput">.o</code> and linking it in, or
1398compiling to a <code class="computeroutput">.so</code> and
1399<code class="computeroutput">LD_PRELOAD</code>ing it in.  The latter is more
1400convenient in that it doesn't require relinking.</p>
1401<p>All wrappers have approximately the above form.  There are three
1402crucial macros:</p>
1403<p><code class="computeroutput">I_WRAP_SONAME_FNNAME_ZU</code>:
1404this generates the real name of the wrapper.
1405This is an encoded name which Valgrind notices when reading symbol
1406table information.  What it says is: I am the wrapper for any function
1407named <code class="computeroutput">foo</code> which is found in
1408an ELF shared object with an empty
1409("<code class="computeroutput">NONE</code>") soname field.  The specification
1410mechanism is powerful in
1411that wildcards are allowed for both sonames and function names.
1412The details are discussed below.</p>
1413<p><code class="computeroutput">VALGRIND_GET_ORIG_FN</code>:
1414once in the wrapper, the first priority is
1415to get hold of the address of the original (and any other supporting
1416information needed).  This is stored in a value of opaque
1417type <code class="computeroutput">OrigFn</code>.
1418The information is acquired using
1419<code class="computeroutput">VALGRIND_GET_ORIG_FN</code>.  It is crucial
1420to make this macro call before calling any other wrapped function
1421in the same thread.</p>
1422<p><code class="computeroutput">CALL_FN_W_WW</code>: eventually we will
1423want to call the function being
1424wrapped.  Calling it directly does not work, since that just gets us
1425back to the wrapper and leads to an infinite loop.  Instead, the result
1426lvalue,
1427<code class="computeroutput">OrigFn</code> and arguments are
1428handed to one of a family of macros of the form
1429<code class="computeroutput">CALL_FN_*</code>.  These
1430cause Valgrind to call the original and avoid recursion back to the
1431wrapper.</p>
1432</div>
1433<div class="sect2">
1434<div class="titlepage"><div><div><h3 class="title">
1435<a name="manual-core-adv.wrapping.specs"></a>3.3.2.�Wrapping Specifications</h3></div></div></div>
1436<p>This scheme has the advantage of being self-contained.  A library of
1437wrappers can be compiled to object code in the normal way, and does
1438not rely on an external script telling Valgrind which wrappers pertain
1439to which originals.</p>
1440<p>Each wrapper has a name which, in the most general case says: I am the
1441wrapper for any function whose name matches FNPATT and whose ELF
1442"soname" matches SOPATT.  Both FNPATT and SOPATT may contain wildcards
1443(asterisks) and other characters (spaces, dots, @, etc) which are not
1444generally regarded as valid C identifier names.</p>
1445<p>This flexibility is needed to write robust wrappers for POSIX pthread
1446functions, where typically we are not completely sure of either the
1447function name or the soname, or alternatively we want to wrap a whole
1448set of functions at once.</p>
1449<p>For example, <code class="computeroutput">pthread_create</code>
1450in GNU libpthread is usually a
1451versioned symbol - one whose name ends in, eg,
1452<code class="computeroutput">@GLIBC_2.3</code>.  Hence we
1453are not sure what its real name is.  We also want to cover any soname
1454of the form <code class="computeroutput">libpthread.so*</code>.
1455So the header of the wrapper will be</p>
1456<pre class="programlisting">
1457int I_WRAP_SONAME_FNNAME_ZZ(libpthreadZdsoZd0,pthreadZucreateZAZa)
1458  ( ... formals ... )
1459  { ... body ... }
1460</pre>
1461<p>In order to write unusual characters as valid C function names, a
1462Z-encoding scheme is used.  Names are written literally, except that
1463a capital Z acts as an escape character, with the following encoding:</p>
1464<pre class="programlisting">
1465     Za   encodes    *
1466     Zp              +
1467     Zc              :
1468     Zd              .
1469     Zu              _
1470     Zh              -
1471     Zs              (space)
1472     ZA              @
1473     ZZ              Z
1474     ZL              (       # only in valgrind 3.3.0 and later
1475     ZR              )       # only in valgrind 3.3.0 and later
1476</pre>
1477<p>Hence <code class="computeroutput">libpthreadZdsoZd0</code> is an
1478encoding of the soname <code class="computeroutput">libpthread.so.0</code>
1479and <code class="computeroutput">pthreadZucreateZAZa</code> is an encoding
1480of the function name <code class="computeroutput">pthread_create@*</code>.
1481</p>
1482<p>The macro <code class="computeroutput">I_WRAP_SONAME_FNNAME_ZZ</code>
1483constructs a wrapper name in which
1484both the soname (first component) and function name (second component)
1485are Z-encoded.  Encoding the function name can be tiresome and is
1486often unnecessary, so a second macro,
1487<code class="computeroutput">I_WRAP_SONAME_FNNAME_ZU</code>, can be
1488used instead.  The <code class="computeroutput">_ZU</code> variant is
1489also useful for writing wrappers for
1490C++ functions, in which the function name is usually already mangled
1491using some other convention in which Z plays an important role.  Having
1492to encode a second time quickly becomes confusing.</p>
1493<p>Since the function name field may contain wildcards, it can be
1494anything, including just <code class="computeroutput">*</code>.
1495The same is true for the soname.
1496However, some ELF objects - specifically, main executables - do not
1497have sonames.  Any object lacking a soname is treated as if its soname
1498was <code class="computeroutput">NONE</code>, which is why the original
1499example above had a name
1500<code class="computeroutput">I_WRAP_SONAME_FNNAME_ZU(NONE,foo)</code>.</p>
1501<p>Note that the soname of an ELF object is not the same as its
1502file name, although it is often similar.  You can find the soname of
1503an object <code class="computeroutput">libfoo.so</code> using the command
1504<code class="computeroutput">readelf -a libfoo.so | grep soname</code>.</p>
1505</div>
1506<div class="sect2">
1507<div class="titlepage"><div><div><h3 class="title">
1508<a name="manual-core-adv.wrapping.semantics"></a>3.3.3.�Wrapping Semantics</h3></div></div></div>
1509<p>The ability for a wrapper to replace an infinite family of functions
1510is powerful but brings complications in situations where ELF objects
1511appear and disappear (are dlopen'd and dlclose'd) on the fly.
1512Valgrind tries to maintain sensible behaviour in such situations.</p>
1513<p>For example, suppose a process has dlopened (an ELF object with
1514soname) <code class="filename">object1.so</code>, which contains
1515<code class="computeroutput">function1</code>.  It starts to use
1516<code class="computeroutput">function1</code> immediately.</p>
1517<p>After a while it dlopens <code class="filename">wrappers.so</code>,
1518which contains a wrapper
1519for <code class="computeroutput">function1</code> in (soname)
1520<code class="filename">object1.so</code>.  All subsequent calls to
1521<code class="computeroutput">function1</code> are rerouted to the wrapper.</p>
1522<p>If <code class="filename">wrappers.so</code> is
1523later dlclose'd, calls to <code class="computeroutput">function1</code> are
1524naturally routed back to the original.</p>
1525<p>Alternatively, if <code class="filename">object1.so</code>
1526is dlclose'd but <code class="filename">wrappers.so</code> remains,
1527then the wrapper exported by <code class="filename">wrappers.so</code>
1528becomes inactive, since there
1529is no way to get to it - there is no original to call any more.  However,
1530Valgrind remembers that the wrapper is still present.  If
1531<code class="filename">object1.so</code> is
1532eventually dlopen'd again, the wrapper will become active again.</p>
1533<p>In short, valgrind inspects all code loading/unloading events to
1534ensure that the set of currently active wrappers remains consistent.</p>
1535<p>A second possible problem is that of conflicting wrappers.  It is
1536easily possible to load two or more wrappers, both of which claim
1537to be wrappers for some third function.  In such cases Valgrind will
1538complain about conflicting wrappers when the second one appears, and
1539will honour only the first one.</p>
1540</div>
1541<div class="sect2">
1542<div class="titlepage"><div><div><h3 class="title">
1543<a name="manual-core-adv.wrapping.debugging"></a>3.3.4.�Debugging</h3></div></div></div>
1544<p>Figuring out what's going on given the dynamic nature of wrapping
1545can be difficult.  The
1546<code class="option">--trace-redir=yes</code> option makes
1547this possible
1548by showing the complete state of the redirection subsystem after
1549every
1550<code class="function">mmap</code>/<code class="function">munmap</code>
1551event affecting code (text).</p>
1552<p>There are two central concepts:</p>
1553<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
1554<li class="listitem"><p>A "redirection specification" is a binding of
1555  a (soname pattern, fnname pattern) pair to a code address.
1556  These bindings are created by writing functions with names
1557  made with the
1558  <code class="computeroutput">I_WRAP_SONAME_FNNAME_{ZZ,_ZU}</code>
1559  macros.</p></li>
1560<li class="listitem"><p>An "active redirection" is a code-address to
1561  code-address binding currently in effect.</p></li>
1562</ul></div>
1563<p>The state of the wrapping-and-redirection subsystem comprises a set of
1564specifications and a set of active bindings.  The specifications are
1565acquired/discarded by watching all
1566<code class="function">mmap</code>/<code class="function">munmap</code>
1567events on code (text)
1568sections.  The active binding set is (conceptually) recomputed from
1569the specifications, and all known symbol names, following any change
1570to the specification set.</p>
1571<p><code class="option">--trace-redir=yes</code> shows the contents
1572of both sets following any such event.</p>
1573<p><code class="option">-v</code> prints a line of text each
1574time an active specification is used for the first time.</p>
1575<p>Hence for maximum debugging effectiveness you will need to use both
1576options.</p>
1577<p>One final comment.  The function-wrapping facility is closely
1578tied to Valgrind's ability to replace (redirect) specified
1579functions, for example to redirect calls to
1580<code class="function">malloc</code> to its
1581own implementation.  Indeed, a replacement function can be
1582regarded as a wrapper function which does not call the original.
1583However, to make the implementation more robust, the two kinds
1584of interception (wrapping vs replacement) are treated differently.
1585</p>
1586<p><code class="option">--trace-redir=yes</code> shows
1587specifications and bindings for both
1588replacement and wrapper functions.  To differentiate the
1589two, replacement bindings are printed using
1590<code class="computeroutput">R-&gt;</code> whereas
1591wraps are printed using <code class="computeroutput">W-&gt;</code>.
1592</p>
1593</div>
1594<div class="sect2">
1595<div class="titlepage"><div><div><h3 class="title">
1596<a name="manual-core-adv.wrapping.limitations-cf"></a>3.3.5.�Limitations - control flow</h3></div></div></div>
1597<p>For the most part, the function wrapping implementation is robust.
1598The only important caveat is: in a wrapper, get hold of
1599the <code class="computeroutput">OrigFn</code> information using
1600<code class="computeroutput">VALGRIND_GET_ORIG_FN</code> before calling any
1601other wrapped function.  Once you have the
1602<code class="computeroutput">OrigFn</code>, arbitrary
1603calls between, recursion between, and longjumps out of wrappers
1604should work correctly.  There is never any interaction between wrapped
1605functions and merely replaced functions
1606(eg <code class="function">malloc</code>), so you can call
1607<code class="function">malloc</code> etc safely from within wrappers.
1608</p>
1609<p>The above comments are true for {x86,amd64,ppc32,arm,mips32,s390}-linux.
1610On
1611ppc64-linux function wrapping is more fragile due to the (arguably
1612poorly designed) ppc64-linux ABI.  This mandates the use of a shadow
1613stack which tracks entries/exits of both wrapper and replacement
1614functions.  This gives two limitations: firstly, longjumping out of
1615wrappers will rapidly lead to disaster, since the shadow stack will
1616not get correctly cleared.  Secondly, since the shadow stack has
1617finite size, recursion between wrapper/replacement functions is only
1618possible to a limited depth, beyond which Valgrind has to abort the
1619run.  This depth is currently 16 calls.</p>
1620<p>For all platforms ({x86,amd64,ppc32,ppc64,arm,mips32,s390}-linux)
1621all the above
1622comments apply on a per-thread basis.  In other words, wrapping is
1623thread-safe: each thread must individually observe the above
1624restrictions, but there is no need for any kind of inter-thread
1625cooperation.</p>
1626</div>
1627<div class="sect2">
1628<div class="titlepage"><div><div><h3 class="title">
1629<a name="manual-core-adv.wrapping.limitations-sigs"></a>3.3.6.�Limitations - original function signatures</h3></div></div></div>
1630<p>As shown in the above example, to call the original you must use a
1631macro of the form <code class="computeroutput">CALL_FN_*</code>.
1632For technical reasons it is impossible
1633to create a single macro to deal with all argument types and numbers,
1634so a family of macros covering the most common cases is supplied.  In
1635what follows, 'W' denotes a machine-word-typed value (a pointer or a
1636C <code class="computeroutput">long</code>),
1637and 'v' denotes C's <code class="computeroutput">void</code> type.
1638The currently available macros are:</p>
1639<pre class="programlisting">
1640CALL_FN_v_v    -- call an original of type  void fn ( void )
1641CALL_FN_W_v    -- call an original of type  long fn ( void )
1642
1643CALL_FN_v_W    -- call an original of type  void fn ( long )
1644CALL_FN_W_W    -- call an original of type  long fn ( long )
1645
1646CALL_FN_v_WW   -- call an original of type  void fn ( long, long )
1647CALL_FN_W_WW   -- call an original of type  long fn ( long, long )
1648
1649CALL_FN_v_WWW  -- call an original of type  void fn ( long, long, long )
1650CALL_FN_W_WWW  -- call an original of type  long fn ( long, long, long )
1651
1652CALL_FN_W_WWWW -- call an original of type  long fn ( long, long, long, long )
1653CALL_FN_W_5W   -- call an original of type  long fn ( long, long, long, long, long )
1654CALL_FN_W_6W   -- call an original of type  long fn ( long, long, long, long, long, long )
1655and so on, up to
1656CALL_FN_W_12W
1657</pre>
1658<p>The set of supported types can be expanded as needed.  It is
1659regrettable that this limitation exists.  Function wrapping has proven
1660difficult to implement, with a certain apparently unavoidable level of
1661ickiness.  After several implementation attempts, the present
1662arrangement appears to be the least-worst tradeoff.  At least it works
1663reliably in the presence of dynamic linking and dynamic code
1664loading/unloading.</p>
1665<p>You should not attempt to wrap a function of one type signature with a
1666wrapper of a different type signature.  Such trickery will surely lead
1667to crashes or strange behaviour.  This is not a limitation
1668of the function wrapping implementation, merely a reflection of the
1669fact that it gives you sweeping powers to shoot yourself in the foot
1670if you are not careful.  Imagine the instant havoc you could wreak by
1671writing a wrapper which matched any function name in any soname - in
1672effect, one which claimed to be a wrapper for all functions in the
1673process.</p>
1674</div>
1675<div class="sect2">
1676<div class="titlepage"><div><div><h3 class="title">
1677<a name="manual-core-adv.wrapping.examples"></a>3.3.7.�Examples</h3></div></div></div>
1678<p>In the source tree,
1679<code class="filename">memcheck/tests/wrap[1-8].c</code> provide a series of
1680examples, ranging from very simple to quite advanced.</p>
1681<p><code class="filename">mpi/libmpiwrap.c</code> is an example
1682of wrapping a big, complex API (the MPI-2 interface).  This file defines
1683almost 300 different wrappers.</p>
1684</div>
1685</div>
1686</div>
1687<div>
1688<br><table class="nav" width="100%" cellspacing="3" cellpadding="2" border="0" summary="Navigation footer">
1689<tr>
1690<td rowspan="2" width="40%" align="left">
1691<a accesskey="p" href="manual-core.html">&lt;&lt;�2.�Using and understanding the Valgrind core</a>�</td>
1692<td width="20%" align="center"><a accesskey="u" href="manual.html">Up</a></td>
1693<td rowspan="2" width="40%" align="right">�<a accesskey="n" href="mc-manual.html">4.�Memcheck: a memory error detector�&gt;&gt;</a>
1694</td>
1695</tr>
1696<tr><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td></tr>
1697</table>
1698</div>
1699</body>
1700</html>
1701