]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/valgrind/src/valgrind-3.6.0-svn/docs/xml/manual-core-adv.xml
update
[l4.git] / l4 / pkg / valgrind / src / valgrind-3.6.0-svn / docs / xml / manual-core-adv.xml
1 <?xml version="1.0"?> <!-- -*- sgml -*- -->
2 <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
3   "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
4 [ <!ENTITY % vg-entities SYSTEM "vg-entities.xml"> %vg-entities; ]>
5
6
7 <chapter id="manual-core-adv" xreflabel="Valgrind's core: advanced topics">
8 <title>Using and understanding the Valgrind core: Advanced Topics</title>
9
10 <para>This chapter describes advanced aspects of the Valgrind core
11 services, which are mostly of interest to power users who wish to
12 customise and modify Valgrind's default behaviours in certain useful
13 ways.  The subjects covered are:</para>
14
15 <itemizedlist>
16   <listitem><para>The "Client Request" mechanism</para></listitem>
17   <listitem><para>Function Wrapping</para></listitem>
18 </itemizedlist>
19
20
21
22 <sect1 id="manual-core-adv.clientreq" 
23        xreflabel="The Client Request mechanism">
24 <title>The Client Request mechanism</title>
25
26 <para>Valgrind has a trapdoor mechanism via which the client
27 program can pass all manner of requests and queries to Valgrind
28 and the current tool.  Internally, this is used extensively 
29 to make various things work, although that's not visible from the
30 outside.</para>
31
32 <para>For your convenience, a subset of these so-called client
33 requests is provided to allow you to tell Valgrind facts about
34 the behaviour of your program, and also to make queries.
35 In particular, your program can tell Valgrind about things that it
36 otherwise would not know, leading to better results.
37 </para>
38
39 <para>Clients need to include a header file to make this work.
40 Which header file depends on which client requests you use.  Some
41 client requests are handled by the core, and are defined in the
42 header file <filename>valgrind/valgrind.h</filename>.  Tool-specific
43 header files are named after the tool, e.g.
44 <filename>valgrind/memcheck.h</filename>.  Each tool-specific header file
45 includes <filename>valgrind/valgrind.h</filename> so you don't need to
46 include it in your client if you include a tool-specific header.  All header
47 files can be found in the <literal>include/valgrind</literal> directory of
48 wherever Valgrind was installed.</para>
49
50 <para>The macros in these header files have the magical property
51 that they generate code in-line which Valgrind can spot.
52 However, the code does nothing when not run on Valgrind, so you
53 are not forced to run your program under Valgrind just because you
54 use the macros in this file.  Also, you are not required to link your
55 program with any extra supporting libraries.</para>
56
57 <para>The code added to your binary has negligible performance impact:
58 on x86, amd64, ppc32, ppc64 and ARM, the overhead is 6 simple integer
59 instructions and is probably undetectable except in tight loops.
60 However, if you really wish to compile out the client requests, you
61 can compile with <option>-DNVALGRIND</option> (analogous to
62 <option>-DNDEBUG</option>'s effect on
63 <function>assert</function>).
64 </para>
65
66 <para>You are encouraged to copy the <filename>valgrind/*.h</filename> headers
67 into your project's include directory, so your program doesn't have a
68 compile-time dependency on Valgrind being installed.  The Valgrind headers,
69 unlike most of the rest of the code, are under a BSD-style license so you may
70 include them without worrying about license incompatibility.</para>
71
72 <para>Here is a brief description of the macros available in
73 <filename>valgrind.h</filename>, which work with more than one
74 tool (see the tool-specific documentation for explanations of the
75 tool-specific macros).</para>
76
77  <variablelist>
78
79   <varlistentry>
80    <term><command><computeroutput>RUNNING_ON_VALGRIND</computeroutput></command>:</term>
81    <listitem>
82     <para>Returns 1 if running on Valgrind, 0 if running on the
83     real CPU.  If you are running Valgrind on itself, returns the
84     number of layers of Valgrind emulation you're running on.
85     </para>
86    </listitem>
87   </varlistentry>
88
89   <varlistentry>
90    <term><command><computeroutput>VALGRIND_DISCARD_TRANSLATIONS</computeroutput>:</command></term>
91    <listitem>
92     <para>Discards translations of code in the specified address
93     range.  Useful if you are debugging a JIT compiler or some other
94     dynamic code generation system.  After this call, attempts to
95     execute code in the invalidated address range will cause
96     Valgrind to make new translations of that code, which is
97     probably the semantics you want.  Note that code invalidations
98     are expensive because finding all the relevant translations
99     quickly is very difficult, so try not to call it often.
100     Note that you can be clever about
101     this: you only need to call it when an area which previously
102     contained code is overwritten with new code.  You can choose
103     to write code into fresh memory, and just call this
104     occasionally to discard large chunks of old code all at
105     once.</para>
106     <para>
107     Alternatively, for transparent self-modifying-code support,
108     use<option>--smc-check=all</option>, or run
109     on ppc32/Linux, ppc64/Linux or ARM/Linux.
110     </para>
111    </listitem>
112   </varlistentry>
113
114   <varlistentry>
115    <term><command><computeroutput>VALGRIND_COUNT_ERRORS</computeroutput>:</command></term>
116    <listitem>
117     <para>Returns the number of errors found so far by Valgrind.  Can be
118     useful in test harness code when combined with the
119     <option>--log-fd=-1</option> option; this runs Valgrind silently,
120     but the client program can detect when errors occur.  Only useful
121     for tools that report errors, e.g. it's useful for Memcheck, but for
122     Cachegrind it will always return zero because Cachegrind doesn't
123     report errors.</para>
124    </listitem>
125   </varlistentry>
126
127   <varlistentry>
128    <term><command><computeroutput>VALGRIND_MALLOCLIKE_BLOCK</computeroutput>:</command></term>
129    <listitem>
130     <para>If your program manages its own memory instead of using
131     the standard <function>malloc</function> /
132     <function>new</function> /
133     <function>new[]</function>, tools that track
134     information about heap blocks will not do nearly as good a
135     job.  For example, Memcheck won't detect nearly as many
136     errors, and the error messages won't be as informative.  To
137     improve this situation, use this macro just after your custom
138     allocator allocates some new memory.  See the comments in
139     <filename>valgrind.h</filename> for information on how to use
140     it.</para>
141    </listitem>
142   </varlistentry>
143
144   <varlistentry>
145    <term><command><computeroutput>VALGRIND_FREELIKE_BLOCK</computeroutput>:</command></term>
146    <listitem>
147     <para>This should be used in conjunction with
148     <computeroutput>VALGRIND_MALLOCLIKE_BLOCK</computeroutput>.
149     Again, see <filename>valgrind.h</filename> for
150     information on how to use it.</para>
151    </listitem>
152   </varlistentry>
153
154   <varlistentry>
155    <term><command><computeroutput>VALGRIND_RESIZEINPLACE_BLOCK</computeroutput>:</command></term>
156    <listitem>
157     <para>Informs a Valgrind tool that the size of an allocated block has been
158     modified but not its address. See <filename>valgrind.h</filename> for
159     more information on how to use it.</para>
160    </listitem>
161   </varlistentry>
162
163   <varlistentry>
164    <term>
165    <command><computeroutput>VALGRIND_CREATE_MEMPOOL</computeroutput></command>,
166    <command><computeroutput>VALGRIND_DESTROY_MEMPOOL</computeroutput></command>,
167    <command><computeroutput>VALGRIND_MEMPOOL_ALLOC</computeroutput></command>,
168    <command><computeroutput>VALGRIND_MEMPOOL_FREE</computeroutput></command>,
169    <command><computeroutput>VALGRIND_MOVE_MEMPOOL</computeroutput></command>,
170    <command><computeroutput>VALGRIND_MEMPOOL_CHANGE</computeroutput></command>,
171    <command><computeroutput>VALGRIND_MEMPOOL_EXISTS</computeroutput></command>:
172    </term>
173    <listitem>
174     <para>These are similar to 
175     <computeroutput>VALGRIND_MALLOCLIKE_BLOCK</computeroutput> and
176     <computeroutput>VALGRIND_FREELIKE_BLOCK</computeroutput>
177     but are tailored towards code that uses memory pools.  See 
178     <xref linkend="mc-manual.mempools"/> for a detailed description.</para>
179    </listitem>
180   </varlistentry>
181   
182   <varlistentry>
183    <term><command><computeroutput>VALGRIND_NON_SIMD_CALL[0123]</computeroutput>:</command></term>
184    <listitem>
185     <para>Executes a function in the client program on the
186     <emphasis>real</emphasis> CPU, not the virtual CPU that Valgrind
187     normally runs code on.  The function must take an integer (holding a
188     thread ID) as the first argument and then 0, 1, 2 or 3 more arguments
189     (depending on which client request is used).  These are used in various
190     ways internally to Valgrind.  They might be useful to client
191     programs.</para> 
192
193     <para><command>Warning:</command> Only use these if you
194     <emphasis>really</emphasis> know what you are doing.  They aren't 
195     entirely reliable, and can cause Valgrind to crash.  See
196     <filename>valgrind.h</filename> for more details.
197     </para>
198    </listitem>
199   </varlistentry>
200
201   <varlistentry>
202    <term><command><computeroutput>VALGRIND_PRINTF(format, ...)</computeroutput>:</command></term>
203    <listitem>
204     <para>Print a printf-style message to the Valgrind log file.  The
205     message is prefixed with the PID between a pair of
206     <computeroutput>**</computeroutput> markers.  (Like all client requests,
207     nothing is output if the client program is not running under Valgrind.)
208     Output is not produced until a newline is encountered, or subsequent
209     Valgrind output is printed; this allows you to build up a single line of
210     output over multiple calls.  Returns the number of characters output,
211     excluding the PID prefix.</para>
212    </listitem>
213   </varlistentry>
214
215   <varlistentry>
216    <term><command><computeroutput>VALGRIND_PRINTF_BACKTRACE(format, ...)</computeroutput>:</command></term>
217    <listitem>
218     <para>Like <computeroutput>VALGRIND_PRINTF</computeroutput> (in
219     particular, the return value is identical), but prints a stack backtrace
220     immediately afterwards.</para>
221    </listitem>
222   </varlistentry>
223
224   <varlistentry>
225    <term><command><computeroutput>VALGRIND_STACK_REGISTER(start, end)</computeroutput>:</command></term>
226    <listitem>
227     <para>Registers a new stack.  Informs Valgrind that the memory range
228     between start and end is a unique stack.  Returns a stack identifier
229     that can be used with other
230     <computeroutput>VALGRIND_STACK_*</computeroutput> calls.</para>
231     <para>Valgrind will use this information to determine if a change to
232     the stack pointer is an item pushed onto the stack or a change over
233     to a new stack.  Use this if you're using a user-level thread package
234     and are noticing spurious errors from Valgrind about uninitialized
235     memory reads.</para>
236
237     <para><command>Warning:</command> Unfortunately, this client request is
238     unreliable and best avoided.</para>
239    </listitem>
240   </varlistentry>
241
242   <varlistentry>
243    <term><command><computeroutput>VALGRIND_STACK_DEREGISTER(id)</computeroutput>:</command></term>
244    <listitem>
245     <para>Deregisters a previously registered stack.  Informs
246     Valgrind that previously registered memory range with stack id
247     <computeroutput>id</computeroutput> is no longer a stack.</para>
248
249     <para><command>Warning:</command> Unfortunately, this client request is
250     unreliable and best avoided.</para>
251    </listitem>
252   </varlistentry>
253
254   <varlistentry>
255    <term><command><computeroutput>VALGRIND_STACK_CHANGE(id, start, end)</computeroutput>:</command></term>
256    <listitem>
257     <para>Changes a previously registered stack.  Informs
258     Valgrind that the previously registered stack with stack id
259     <computeroutput>id</computeroutput> has changed its start and end
260     values.  Use this if your user-level thread package implements
261     stack growth.</para>
262
263     <para><command>Warning:</command> Unfortunately, this client request is
264     unreliable and best avoided.</para>
265    </listitem>
266   </varlistentry>
267
268  </variablelist>
269
270 </sect1>
271
272
273
274
275
276 <sect1 id="manual-core-adv.wrapping" xreflabel="Function Wrapping">
277 <title>Function wrapping</title>
278
279 <para>
280 Valgrind allows calls to some specified functions to be intercepted and
281 rerouted to a different, user-supplied function.  This can do whatever it
282 likes, typically examining the arguments, calling onwards to the original,
283 and possibly examining the result.  Any number of functions may be
284 wrapped.</para>
285
286 <para>
287 Function wrapping is useful for instrumenting an API in some way.  For
288 example, Helgrind wraps functions in the POSIX pthreads API so it can know
289 about thread status changes, and the core is able to wrap
290 functions in the MPI (message-passing) API so it can know
291 of memory status changes associated with message arrival/departure.
292 Such information is usually passed to Valgrind by using client
293 requests in the wrapper functions, although the exact mechanism may vary.
294 </para>
295
296 <sect2 id="manual-core-adv.wrapping.example" xreflabel="A Simple Example">
297 <title>A Simple Example</title>
298
299 <para>Supposing we want to wrap some function</para>
300
301 <programlisting><![CDATA[
302 int foo ( int x, int y ) { return x + y; }]]></programlisting>
303
304 <para>A wrapper is a function of identical type, but with a special name
305 which identifies it as the wrapper for <computeroutput>foo</computeroutput>.
306 Wrappers need to include
307 supporting macros from <filename>valgrind.h</filename>.
308 Here is a simple wrapper which prints the arguments and return value:</para>
309
310 <programlisting><![CDATA[
311 #include <stdio.h>
312 #include "valgrind.h"
313 int I_WRAP_SONAME_FNNAME_ZU(NONE,foo)( int x, int y )
314 {
315    int    result;
316    OrigFn fn;
317    VALGRIND_GET_ORIG_FN(fn);
318    printf("foo's wrapper: args %d %d\n", x, y);
319    CALL_FN_W_WW(result, fn, x,y);
320    printf("foo's wrapper: result %d\n", result);
321    return result;
322 }
323 ]]></programlisting>
324
325 <para>To become active, the wrapper merely needs to be present in a text
326 section somewhere in the same process' address space as the function
327 it wraps, and for its ELF symbol name to be visible to Valgrind.  In
328 practice, this means either compiling to a 
329 <computeroutput>.o</computeroutput> and linking it in, or
330 compiling to a <computeroutput>.so</computeroutput> and 
331 <computeroutput>LD_PRELOAD</computeroutput>ing it in.  The latter is more
332 convenient in that it doesn't require relinking.</para>
333
334 <para>All wrappers have approximately the above form.  There are three
335 crucial macros:</para>
336
337 <para><computeroutput>I_WRAP_SONAME_FNNAME_ZU</computeroutput>: 
338 this generates the real name of the wrapper.
339 This is an encoded name which Valgrind notices when reading symbol
340 table information.  What it says is: I am the wrapper for any function
341 named <computeroutput>foo</computeroutput> which is found in 
342 an ELF shared object with an empty
343 ("<computeroutput>NONE</computeroutput>") soname field.  The specification 
344 mechanism is powerful in
345 that wildcards are allowed for both sonames and function names.  
346 The details are discussed below.</para>
347
348 <para><computeroutput>VALGRIND_GET_ORIG_FN</computeroutput>: 
349 once in the the wrapper, the first priority is
350 to get hold of the address of the original (and any other supporting
351 information needed).  This is stored in a value of opaque 
352 type <computeroutput>OrigFn</computeroutput>.
353 The information is acquired using 
354 <computeroutput>VALGRIND_GET_ORIG_FN</computeroutput>.  It is crucial
355 to make this macro call before calling any other wrapped function
356 in the same thread.</para>
357
358 <para><computeroutput>CALL_FN_W_WW</computeroutput>: eventually we will
359 want to call the function being
360 wrapped.  Calling it directly does not work, since that just gets us
361 back to the wrapper and leads to an infinite loop.  Instead, the result
362 lvalue, 
363 <computeroutput>OrigFn</computeroutput> and arguments are
364 handed to one of a family of macros of the form 
365 <computeroutput>CALL_FN_*</computeroutput>.  These
366 cause Valgrind to call the original and avoid recursion back to the
367 wrapper.</para>
368 </sect2>
369
370 <sect2 id="manual-core-adv.wrapping.specs" xreflabel="Wrapping Specifications">
371 <title>Wrapping Specifications</title>
372
373 <para>This scheme has the advantage of being self-contained.  A library of
374 wrappers can be compiled to object code in the normal way, and does
375 not rely on an external script telling Valgrind which wrappers pertain
376 to which originals.</para>
377
378 <para>Each wrapper has a name which, in the most general case says: I am the
379 wrapper for any function whose name matches FNPATT and whose ELF
380 "soname" matches SOPATT.  Both FNPATT and SOPATT may contain wildcards
381 (asterisks) and other characters (spaces, dots, @, etc) which are not 
382 generally regarded as valid C identifier names.</para> 
383
384 <para>This flexibility is needed to write robust wrappers for POSIX pthread
385 functions, where typically we are not completely sure of either the
386 function name or the soname, or alternatively we want to wrap a whole
387 set of functions at once.</para> 
388
389 <para>For example, <computeroutput>pthread_create</computeroutput> 
390 in GNU libpthread is usually a
391 versioned symbol - one whose name ends in, eg, 
392 <computeroutput>@GLIBC_2.3</computeroutput>.  Hence we
393 are not sure what its real name is.  We also want to cover any soname
394 of the form <computeroutput>libpthread.so*</computeroutput>.
395 So the header of the wrapper will be</para>
396
397 <programlisting><![CDATA[
398 int I_WRAP_SONAME_FNNAME_ZZ(libpthreadZdsoZd0,pthreadZucreateZAZa)
399   ( ... formals ... )
400   { ... body ... }
401 ]]></programlisting>
402
403 <para>In order to write unusual characters as valid C function names, a
404 Z-encoding scheme is used.  Names are written literally, except that
405 a capital Z acts as an escape character, with the following encoding:</para>
406
407 <programlisting><![CDATA[
408      Za   encodes    *
409      Zp              +
410      Zc              :
411      Zd              .
412      Zu              _
413      Zh              -
414      Zs              (space)
415      ZA              @
416      ZZ              Z
417      ZL              (       # only in valgrind 3.3.0 and later
418      ZR              )       # only in valgrind 3.3.0 and later
419 ]]></programlisting>
420
421 <para>Hence <computeroutput>libpthreadZdsoZd0</computeroutput> is an 
422 encoding of the soname <computeroutput>libpthread.so.0</computeroutput>
423 and <computeroutput>pthreadZucreateZAZa</computeroutput> is an encoding 
424 of the function name <computeroutput>pthread_create@*</computeroutput>.
425 </para>
426
427 <para>The macro <computeroutput>I_WRAP_SONAME_FNNAME_ZZ</computeroutput> 
428 constructs a wrapper name in which
429 both the soname (first component) and function name (second component)
430 are Z-encoded.  Encoding the function name can be tiresome and is
431 often unnecessary, so a second macro,
432 <computeroutput>I_WRAP_SONAME_FNNAME_ZU</computeroutput>, can be
433 used instead.  The <computeroutput>_ZU</computeroutput> variant is 
434 also useful for writing wrappers for
435 C++ functions, in which the function name is usually already mangled
436 using some other convention in which Z plays an important role.  Having
437 to encode a second time quickly becomes confusing.</para>
438
439 <para>Since the function name field may contain wildcards, it can be
440 anything, including just <computeroutput>*</computeroutput>.
441 The same is true for the soname.
442 However, some ELF objects - specifically, main executables - do not
443 have sonames.  Any object lacking a soname is treated as if its soname
444 was <computeroutput>NONE</computeroutput>, which is why the original 
445 example above had a name
446 <computeroutput>I_WRAP_SONAME_FNNAME_ZU(NONE,foo)</computeroutput>.</para>
447
448 <para>Note that the soname of an ELF object is not the same as its
449 file name, although it is often similar.  You can find the soname of
450 an object <computeroutput>libfoo.so</computeroutput> using the command
451 <computeroutput>readelf -a libfoo.so | grep soname</computeroutput>.</para>
452 </sect2>
453
454 <sect2 id="manual-core-adv.wrapping.semantics" xreflabel="Wrapping Semantics">
455 <title>Wrapping Semantics</title>
456
457 <para>The ability for a wrapper to replace an infinite family of functions
458 is powerful but brings complications in situations where ELF objects
459 appear and disappear (are dlopen'd and dlclose'd) on the fly.
460 Valgrind tries to maintain sensible behaviour in such situations.</para>
461
462 <para>For example, suppose a process has dlopened (an ELF object with
463 soname) <filename>object1.so</filename>, which contains 
464 <computeroutput>function1</computeroutput>.  It starts to use
465 <computeroutput>function1</computeroutput> immediately.</para>
466
467 <para>After a while it dlopens <filename>wrappers.so</filename>,
468 which contains a wrapper
469 for <computeroutput>function1</computeroutput> in (soname) 
470 <filename>object1.so</filename>.  All subsequent calls to 
471 <computeroutput>function1</computeroutput> are rerouted to the wrapper.</para>
472
473 <para>If <filename>wrappers.so</filename> is 
474 later dlclose'd, calls to <computeroutput>function1</computeroutput> are 
475 naturally routed back to the original.</para>
476
477 <para>Alternatively, if <filename>object1.so</filename>
478 is dlclose'd but <filename>wrappers.so</filename> remains,
479 then the wrapper exported by <filename>wrappers.so</filename>
480 becomes inactive, since there
481 is no way to get to it - there is no original to call any more.  However,
482 Valgrind remembers that the wrapper is still present.  If 
483 <filename>object1.so</filename> is
484 eventually dlopen'd again, the wrapper will become active again.</para>
485
486 <para>In short, valgrind inspects all code loading/unloading events to
487 ensure that the set of currently active wrappers remains consistent.</para>
488
489 <para>A second possible problem is that of conflicting wrappers.  It is 
490 easily possible to load two or more wrappers, both of which claim
491 to be wrappers for some third function.  In such cases Valgrind will
492 complain about conflicting wrappers when the second one appears, and
493 will honour only the first one.</para>
494 </sect2>
495
496 <sect2 id="manual-core-adv.wrapping.debugging" xreflabel="Debugging">
497 <title>Debugging</title>
498
499 <para>Figuring out what's going on given the dynamic nature of wrapping
500 can be difficult.  The 
501 <option>--trace-redir=yes</option> option makes 
502 this possible
503 by showing the complete state of the redirection subsystem after
504 every
505 <function>mmap</function>/<function>munmap</function>
506 event affecting code (text).</para>
507
508 <para>There are two central concepts:</para>
509
510 <itemizedlist>
511
512   <listitem><para>A "redirection specification" is a binding of 
513   a (soname pattern, fnname pattern) pair to a code address.
514   These bindings are created by writing functions with names
515   made with the 
516   <computeroutput>I_WRAP_SONAME_FNNAME_{ZZ,_ZU}</computeroutput>
517   macros.</para></listitem>
518
519   <listitem><para>An "active redirection" is a code-address to 
520   code-address binding currently in effect.</para></listitem>
521
522 </itemizedlist>
523
524 <para>The state of the wrapping-and-redirection subsystem comprises a set of
525 specifications and a set of active bindings.  The specifications are
526 acquired/discarded by watching all 
527 <function>mmap</function>/<function>munmap</function>
528 events on code (text)
529 sections.  The active binding set is (conceptually) recomputed from
530 the specifications, and all known symbol names, following any change
531 to the specification set.</para>
532
533 <para><option>--trace-redir=yes</option> shows the contents 
534 of both sets following any such event.</para>
535
536 <para><option>-v</option> prints a line of text each 
537 time an active specification is used for the first time.</para>
538
539 <para>Hence for maximum debugging effectiveness you will need to use both
540 options.</para>
541
542 <para>One final comment.  The function-wrapping facility is closely
543 tied to Valgrind's ability to replace (redirect) specified
544 functions, for example to redirect calls to 
545 <function>malloc</function> to its
546 own implementation.  Indeed, a replacement function can be
547 regarded as a wrapper function which does not call the original.
548 However, to make the implementation more robust, the two kinds
549 of interception (wrapping vs replacement) are treated differently.
550 </para>
551
552 <para><option>--trace-redir=yes</option> shows 
553 specifications and bindings for both
554 replacement and wrapper functions.  To differentiate the 
555 two, replacement bindings are printed using 
556 <computeroutput>R-></computeroutput> whereas 
557 wraps are printed using <computeroutput>W-></computeroutput>.
558 </para>
559 </sect2>
560
561
562 <sect2 id="manual-core-adv.wrapping.limitations-cf" 
563        xreflabel="Limitations - control flow">
564 <title>Limitations - control flow</title>
565
566 <para>For the most part, the function wrapping implementation is robust.
567 The only important caveat is: in a wrapper, get hold of
568 the <computeroutput>OrigFn</computeroutput> information using 
569 <computeroutput>VALGRIND_GET_ORIG_FN</computeroutput> before calling any
570 other wrapped function.  Once you have the 
571 <computeroutput>OrigFn</computeroutput>, arbitrary
572 calls between, recursion between, and longjumps out of wrappers
573 should work correctly.  There is never any interaction between wrapped
574 functions and merely replaced functions 
575 (eg <function>malloc</function>), so you can call
576 <function>malloc</function> etc safely from within wrappers.
577 </para>
578
579 <para>The above comments are true for {x86,amd64,ppc32,arm}-linux.  On
580 ppc64-linux function wrapping is more fragile due to the (arguably
581 poorly designed) ppc64-linux ABI.  This mandates the use of a shadow
582 stack which tracks entries/exits of both wrapper and replacement
583 functions.  This gives two limitations: firstly, longjumping out of
584 wrappers will rapidly lead to disaster, since the shadow stack will
585 not get correctly cleared.  Secondly, since the shadow stack has
586 finite size, recursion between wrapper/replacement functions is only
587 possible to a limited depth, beyond which Valgrind has to abort the
588 run.  This depth is currently 16 calls.</para>
589
590 <para>For all platforms ({x86,amd64,ppc32,ppc64,arm}-linux) all the above
591 comments apply on a per-thread basis.  In other words, wrapping is
592 thread-safe: each thread must individually observe the above
593 restrictions, but there is no need for any kind of inter-thread
594 cooperation.</para>
595 </sect2>
596
597
598 <sect2 id="manual-core-adv.wrapping.limitations-sigs" 
599        xreflabel="Limitations - original function signatures">
600 <title>Limitations - original function signatures</title>
601
602 <para>As shown in the above example, to call the original you must use a
603 macro of the form <computeroutput>CALL_FN_*</computeroutput>.  
604 For technical reasons it is impossible
605 to create a single macro to deal with all argument types and numbers,
606 so a family of macros covering the most common cases is supplied.  In
607 what follows, 'W' denotes a machine-word-typed value (a pointer or a
608 C <computeroutput>long</computeroutput>), 
609 and 'v' denotes C's <computeroutput>void</computeroutput> type.
610 The currently available macros are:</para>
611
612 <programlisting><![CDATA[
613 CALL_FN_v_v    -- call an original of type  void fn ( void )
614 CALL_FN_W_v    -- call an original of type  long fn ( void )
615
616 CALL_FN_v_W    -- call an original of type  void fn ( long )
617 CALL_FN_W_W    -- call an original of type  long fn ( long )
618
619 CALL_FN_v_WW   -- call an original of type  void fn ( long, long )
620 CALL_FN_W_WW   -- call an original of type  long fn ( long, long )
621
622 CALL_FN_v_WWW  -- call an original of type  void fn ( long, long, long )
623 CALL_FN_W_WWW  -- call an original of type  long fn ( long, long, long )
624
625 CALL_FN_W_WWWW -- call an original of type  long fn ( long, long, long, long )
626 CALL_FN_W_5W   -- call an original of type  long fn ( long, long, long, long, long )
627 CALL_FN_W_6W   -- call an original of type  long fn ( long, long, long, long, long, long )
628 and so on, up to 
629 CALL_FN_W_12W
630 ]]></programlisting>
631
632 <para>The set of supported types can be expanded as needed.  It is
633 regrettable that this limitation exists.  Function wrapping has proven
634 difficult to implement, with a certain apparently unavoidable level of
635 ickiness.  After several implementation attempts, the present
636 arrangement appears to be the least-worst tradeoff.  At least it works
637 reliably in the presence of dynamic linking and dynamic code
638 loading/unloading.</para>
639
640 <para>You should not attempt to wrap a function of one type signature with a
641 wrapper of a different type signature.  Such trickery will surely lead
642 to crashes or strange behaviour.  This is not a limitation
643 of the function wrapping implementation, merely a reflection of the
644 fact that it gives you sweeping powers to shoot yourself in the foot
645 if you are not careful.  Imagine the instant havoc you could wreak by
646 writing a wrapper which matched any function name in any soname - in
647 effect, one which claimed to be a wrapper for all functions in the
648 process.</para>
649 </sect2>
650
651 <sect2 id="manual-core-adv.wrapping.examples" xreflabel="Examples">
652 <title>Examples</title>
653
654 <para>In the source tree, 
655 <filename>memcheck/tests/wrap[1-8].c</filename> provide a series of
656 examples, ranging from very simple to quite advanced.</para>
657
658 <para><filename>mpi/libmpiwrap.c</filename> is an example 
659 of wrapping a big, complex API (the MPI-2 interface).  This file defines 
660 almost 300 different wrappers.</para>
661 </sect2>
662
663 </sect1>
664
665
666
667
668 </chapter>