]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/valgrind/src/valgrind-3.6.0-svn/drd/docs/drd-manual.xml
update
[l4.git] / l4 / pkg / valgrind / src / valgrind-3.6.0-svn / drd / docs / drd-manual.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 "../../docs/xml/vg-entities.xml"> %vg-entities; ]>
5
6
7 <chapter id="drd-manual" xreflabel="DRD: a thread error detector">
8   <title>DRD: a thread error detector</title>
9
10 <para>To use this tool, you must specify
11 <option>--tool=drd</option>
12 on the Valgrind command line.</para>
13
14
15 <sect1 id="drd-manual.overview" xreflabel="Overview">
16 <title>Overview</title>
17
18 <para>
19 DRD is a Valgrind tool for detecting errors in multithreaded C and C++
20 programs. The tool works for any program that uses the POSIX threading
21 primitives or that uses threading concepts built on top of the POSIX threading
22 primitives.
23 </para>
24
25 <sect2 id="drd-manual.mt-progr-models" xreflabel="MT-progr-models">
26 <title>Multithreaded Programming Paradigms</title>
27
28 <para>
29 There are two possible reasons for using multithreading in a program:
30 <itemizedlist>
31   <listitem>
32     <para>
33       To model concurrent activities. Assigning one thread to each activity
34       can be a great simplification compared to multiplexing the states of
35       multiple activities in a single thread. This is why most server software
36       and embedded software is multithreaded.
37     </para>
38   </listitem>
39   <listitem>
40     <para>
41       To use multiple CPU cores simultaneously for speeding up
42       computations. This is why many High Performance Computing (HPC)
43       applications are multithreaded.
44     </para>
45   </listitem>
46 </itemizedlist>
47 </para>
48
49 <para>
50 Multithreaded programs can use one or more of the following programming
51 paradigms. Which paradigm is appropriate depends e.g. on the application type.
52 Some examples of multithreaded programming paradigms are:
53 <itemizedlist>
54   <listitem>
55     <para>
56       Locking. Data that is shared over threads is protected from concurrent
57       accesses via locking. E.g. the POSIX threads library, the Qt library
58       and the Boost.Thread library support this paradigm directly.
59     </para>
60   </listitem>
61   <listitem>
62     <para>
63       Message passing. No data is shared between threads, but threads exchange
64       data by passing messages to each other. Examples of implementations of
65       the message passing paradigm are MPI and CORBA.
66     </para>
67   </listitem>
68   <listitem>
69     <para>
70       Automatic parallelization. A compiler converts a sequential program into
71       a multithreaded program. The original program may or may not contain
72       parallelization hints. One example of such parallelization hints is the
73       OpenMP standard. In this standard a set of directives are defined which
74       tell a compiler how to parallelize a C, C++ or Fortran program. OpenMP
75       is well suited for computational intensive applications. As an example,
76       an open source image processing software package is using OpenMP to
77       maximize performance on systems with multiple CPU
78       cores. GCC supports the
79       OpenMP standard from version 4.2.0 on.
80     </para>
81   </listitem>
82   <listitem>
83     <para>
84       Software Transactional Memory (STM). Any data that is shared between
85       threads is updated via transactions. After each transaction it is
86       verified whether there were any conflicting transactions. If there were
87       conflicts, the transaction is aborted, otherwise it is committed. This
88       is a so-called optimistic approach. There is a prototype of the Intel C++
89       Compiler available that supports STM. Research about the addition of
90       STM support to GCC is ongoing.
91     </para>
92   </listitem>
93 </itemizedlist>
94 </para>
95
96 <para>
97 DRD supports any combination of multithreaded programming paradigms as
98 long as the implementation of these paradigms is based on the POSIX
99 threads primitives. DRD however does not support programs that use
100 e.g. Linux' futexes directly. Attempts to analyze such programs with
101 DRD will cause DRD to report many false positives.
102 </para>
103
104 </sect2>
105
106
107 <sect2 id="drd-manual.pthreads-model" xreflabel="Pthreads-model">
108 <title>POSIX Threads Programming Model</title>
109
110 <para>
111 POSIX threads, also known as Pthreads, is the most widely available
112 threading library on Unix systems.
113 </para>
114
115 <para>
116 The POSIX threads programming model is based on the following abstractions:
117 <itemizedlist>
118   <listitem>
119     <para>
120       A shared address space. All threads running within the same
121       process share the same address space. All data, whether shared or
122       not, is identified by its address.
123     </para>
124   </listitem>
125   <listitem>
126     <para>
127       Regular load and store operations, which allow to read values
128       from or to write values to the memory shared by all threads
129       running in the same process.
130     </para>
131   </listitem>
132   <listitem>
133     <para>
134       Atomic store and load-modify-store operations. While these are
135       not mentioned in the POSIX threads standard, most
136       microprocessors support atomic memory operations.
137     </para>
138   </listitem>
139   <listitem>
140     <para>
141       Threads. Each thread represents a concurrent activity.
142     </para>
143   </listitem>
144   <listitem>
145     <para>
146       Synchronization objects and operations on these synchronization
147       objects. The following types of synchronization objects have been
148       defined in the POSIX threads standard: mutexes, condition variables,
149       semaphores, reader-writer synchronization objects, barriers and
150       spinlocks.
151     </para>
152   </listitem>
153 </itemizedlist>
154 </para>
155
156 <para>
157 Which source code statements generate which memory accesses depends on
158 the <emphasis>memory model</emphasis> of the programming language being
159 used. There is not yet a definitive memory model for the C and C++
160 languages. For a draft memory model, see also the document
161 <ulink url="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2338.html">
162 WG21/N2338: Concurrency memory model compiler consequences</ulink>.
163 </para>
164
165 <para>
166 For more information about POSIX threads, see also the Single UNIX
167 Specification version 3, also known as
168 <ulink url="http://www.opengroup.org/onlinepubs/000095399/idx/threads.html">
169 IEEE Std 1003.1</ulink>.
170 </para>
171
172 </sect2>
173
174
175 <sect2 id="drd-manual.mt-problems" xreflabel="MT-Problems">
176 <title>Multithreaded Programming Problems</title>
177
178 <para>
179 Depending on which multithreading paradigm is being used in a program,
180 one or more of the following problems can occur:
181 <itemizedlist>
182   <listitem>
183     <para>
184       Data races. One or more threads access the same memory location without
185       sufficient locking. Most but not all data races are programming errors
186       and are the cause of subtle and hard-to-find bugs.
187     </para>
188   </listitem>
189   <listitem>
190     <para>
191       Lock contention. One thread blocks the progress of one or more other
192       threads by holding a lock too long.
193     </para>
194   </listitem>
195   <listitem>
196     <para>
197       Improper use of the POSIX threads API. Most implementations of the POSIX
198       threads API have been optimized for runtime speed. Such implementations
199       will not complain on certain errors, e.g. when a mutex is being unlocked
200       by another thread than the thread that obtained a lock on the mutex.
201     </para>
202   </listitem>
203   <listitem>
204     <para>
205       Deadlock. A deadlock occurs when two or more threads wait for
206       each other indefinitely.
207     </para>
208   </listitem>
209   <listitem>
210     <para>
211       False sharing. If threads that run on different processor cores
212       access different variables located in the same cache line
213       frequently, this will slow down the involved threads a lot due
214       to frequent exchange of cache lines.
215     </para>
216   </listitem>
217 </itemizedlist>
218 </para>
219
220 <para>
221 Although the likelihood of the occurrence of data races can be reduced
222 through a disciplined programming style, a tool for automatic
223 detection of data races is a necessity when developing multithreaded
224 software. DRD can detect these, as well as lock contention and
225 improper use of the POSIX threads API.
226 </para>
227
228 </sect2>
229
230
231 <sect2 id="drd-manual.data-race-detection" xreflabel="data-race-detection">
232 <title>Data Race Detection</title>
233
234 <para>
235 The result of load and store operations performed by a multithreaded program
236 depends on the order in which memory operations are performed. This order is
237 determined by:
238 <orderedlist>
239   <listitem>
240     <para>
241       All memory operations performed by the same thread are performed in
242       <emphasis>program order</emphasis>, that is, the order determined by the
243       program source code and the results of previous load operations.
244     </para>
245   </listitem>
246   <listitem>
247     <para>
248       Synchronization operations determine certain ordering constraints on
249       memory operations performed by different threads. These ordering
250       constraints are called the <emphasis>synchronization order</emphasis>.
251     </para>
252   </listitem>
253 </orderedlist>
254 The combination of program order and synchronization order is called the
255 <emphasis>happens-before relationship</emphasis>. This concept was first
256 defined by S. Adve et al in the paper <emphasis>Detecting data races on weak
257 memory systems</emphasis>, ACM SIGARCH Computer Architecture News, v.19 n.3,
258 p.234-243, May 1991.
259 </para>
260
261 <para>
262 Two memory operations <emphasis>conflict</emphasis> if both operations are
263 performed by different threads, refer to the same memory location and at least
264 one of them is a store operation.
265 </para>
266
267 <para>
268 A multithreaded program is <emphasis>data-race free</emphasis> if all
269 conflicting memory accesses are ordered by synchronization
270 operations.
271 </para>
272
273 <para>
274 A well known way to ensure that a multithreaded program is data-race
275 free is to ensure that a locking discipline is followed. It is e.g.
276 possible to associate a mutex with each shared data item, and to hold
277 a lock on the associated mutex while the shared data is accessed.
278 </para>
279
280 <para>
281 All programs that follow a locking discipline are data-race free, but not all
282 data-race free programs follow a locking discipline. There exist multithreaded
283 programs where access to shared data is arbitrated via condition variables,
284 semaphores or barriers. As an example, a certain class of HPC applications
285 consists of a sequence of computation steps separated in time by barriers, and
286 where these barriers are the only means of synchronization. Although there are
287 many conflicting memory accesses in such applications and although such
288 applications do not make use mutexes, most of these applications do not
289 contain data races.
290 </para>
291
292 <para>
293 There exist two different approaches for verifying the correctness of
294 multithreaded programs at runtime. The approach of the so-called Eraser
295 algorithm is to verify whether all shared memory accesses follow a consistent
296 locking strategy. And the happens-before data race detectors verify directly
297 whether all interthread memory accesses are ordered by synchronization
298 operations. While the last approach is more complex to implement, and while it
299 is more sensitive to OS scheduling, it is a general approach that works for
300 all classes of multithreaded programs. An important advantage of
301 happens-before data race detectors is that these do not report any false
302 positives.
303 </para>
304
305 <para>
306 DRD is based on the happens-before algorithm.
307 </para>
308
309 </sect2>
310
311
312 </sect1>
313
314
315 <sect1 id="drd-manual.using-drd" xreflabel="Using DRD">
316 <title>Using DRD</title>
317
318 <sect2 id="drd-manual.options" xreflabel="DRD Command-line Options">
319 <title>DRD Command-line Options</title>
320
321 <para>The following command-line options are available for controlling the
322 behavior of the DRD tool itself:</para>
323
324 <!-- start of xi:include in the manpage -->
325 <variablelist id="drd.opts.list">
326   <varlistentry>
327     <term>
328       <option><![CDATA[--check-stack-var=<yes|no> [default: no]]]></option>
329     </term>
330     <listitem>
331       <para>
332         Controls whether DRD detects data races on stack
333         variables. Verifying stack variables is disabled by default because
334         most programs do not share stack variables over threads.
335       </para>
336     </listitem>
337   </varlistentry>
338   <varlistentry>
339     <term>
340       <option><![CDATA[--exclusive-threshold=<n> [default: off]]]></option>
341     </term>
342     <listitem>
343       <para>
344         Print an error message if any mutex or writer lock has been
345         held longer than the time specified in milliseconds. This
346         option enables the detection of lock contention.
347       </para>
348     </listitem>
349   </varlistentry>
350   <varlistentry>
351     <term>
352       <option>
353         <![CDATA[--first-race-only=<yes|no> [default: no]]]>
354       </option>
355     </term>
356     <listitem>
357       <para>
358         Whether to report only the first data race that has been detected on a
359         memory location or all data races that have been detected on a memory
360         location.
361       </para>
362     </listitem>
363   </varlistentry>
364   <varlistentry>
365     <term>
366       <option>
367         <![CDATA[--free-is-write=<yes|no> [default: no]]]>
368       </option>
369     </term>
370     <listitem>
371       <para>
372         Whether to report races between accessing memory and freeing
373         memory. Enabling this option may cause DRD to run slightly
374         slower. Notes:
375         <itemizedlist>
376           <listitem>
377             <para>
378               Don't enable this option when using custom memory allocators
379               that use
380               the <computeroutput>VG_USERREQ__MALLOCLIKE_BLOCK</computeroutput>
381               and <computeroutput>VG_USERREQ__FREELIKE_BLOCK</computeroutput>
382               because that would result in false positives.
383             </para>
384           </listitem>
385           <listitem>
386             <para>Don't enable this option when using reference-counted
387               objects because that will result in false positives, even when
388               that code has been annotated properly with
389               <computeroutput>ANNOTATE_HAPPENS_BEFORE</computeroutput>
390               and <computeroutput>ANNOTATE_HAPPENS_AFTER</computeroutput>. See
391               e.g.  the output of the following command for an example:
392               <computeroutput>valgrind --tool=drd --free-is-write=yes
393                 drd/tests/annotate_smart_pointer</computeroutput>.
394             </para>
395           </listitem>
396         </itemizedlist>
397       </para>
398     </listitem>
399   </varlistentry>
400   <varlistentry>
401     <term>
402       <option>
403         <![CDATA[--report-signal-unlocked=<yes|no> [default: yes]]]>
404       </option>
405     </term>
406     <listitem>
407       <para>
408         Whether to report calls to
409         <function>pthread_cond_signal</function> and
410         <function>pthread_cond_broadcast</function> where the mutex
411         associated with the signal through
412         <function>pthread_cond_wait</function> or
413         <function>pthread_cond_timed_wait</function>is not locked at
414         the time the signal is sent.  Sending a signal without holding
415         a lock on the associated mutex is a common programming error
416         which can cause subtle race conditions and unpredictable
417         behavior. There exist some uncommon synchronization patterns
418         however where it is safe to send a signal without holding a
419         lock on the associated mutex.
420       </para>
421     </listitem>
422   </varlistentry>
423   <varlistentry>
424     <term>
425       <option><![CDATA[--segment-merging=<yes|no> [default: yes]]]></option>
426     </term>
427     <listitem>
428       <para>
429         Controls segment merging. Segment merging is an algorithm to
430         limit memory usage of the data race detection
431         algorithm. Disabling segment merging may improve the accuracy
432         of the so-called 'other segments' displayed in race reports
433         but can also trigger an out of memory error.
434       </para>
435     </listitem>
436   </varlistentry>
437   <varlistentry>
438     <term>
439       <option><![CDATA[--segment-merging-interval=<n> [default: 10]]]></option>
440     </term>
441     <listitem>
442       <para>
443         Perform segment merging only after the specified number of new
444         segments have been created. This is an advanced configuration option
445         that allows to choose whether to minimize DRD's memory usage by
446         choosing a low value or to let DRD run faster by choosing a slightly
447         higher value. The optimal value for this parameter depends on the
448         program being analyzed. The default value works well for most programs.
449       </para>
450     </listitem>
451   </varlistentry>
452   <varlistentry>
453     <term>
454       <option><![CDATA[--shared-threshold=<n> [default: off]]]></option>
455     </term>
456     <listitem>
457       <para>
458         Print an error message if a reader lock has been held longer
459         than the specified time (in milliseconds). This option enables
460         the detection of lock contention.
461       </para>
462     </listitem>
463   </varlistentry>
464   <varlistentry>
465     <term>
466       <option><![CDATA[--show-confl-seg=<yes|no> [default: yes]]]></option>
467     </term>
468     <listitem>
469       <para>
470          Show conflicting segments in race reports. Since this
471          information can help to find the cause of a data race, this
472          option is enabled by default. Disabling this option makes the
473          output of DRD more compact.
474       </para>
475     </listitem>
476   </varlistentry>
477   <varlistentry>
478     <term>
479       <option><![CDATA[--show-stack-usage=<yes|no> [default: no]]]></option>
480     </term>
481     <listitem>
482       <para>
483         Print stack usage at thread exit time. When a program creates a large
484         number of threads it becomes important to limit the amount of virtual
485         memory allocated for thread stacks. This option makes it possible to
486         observe how much stack memory has been used by each thread of the the
487         client program. Note: the DRD tool itself allocates some temporary
488         data on the client thread stack. The space necessary for this
489         temporary data must be allocated by the client program when it
490         allocates stack memory, but is not included in stack usage reported by
491         DRD.
492       </para>
493     </listitem>
494   </varlistentry>
495 </variablelist>
496 <!-- end of xi:include in the manpage -->
497
498 <!-- start of xi:include in the manpage -->
499 <para>
500 The following options are available for monitoring the behavior of the
501 client program:
502 </para>
503
504 <variablelist id="drd.debugopts.list">
505   <varlistentry>
506     <term>
507       <option><![CDATA[--trace-addr=<address> [default: none]]]></option>
508     </term>
509     <listitem>
510       <para>
511         Trace all load and store activity for the specified
512         address. This option may be specified more than once.
513       </para>
514     </listitem>
515   </varlistentry>
516   <varlistentry>
517     <term>
518       <option><![CDATA[--trace-alloc=<yes|no> [default: no]]]></option>
519     </term>
520     <listitem>
521       <para>
522         Trace all memory allocations and deallocations. May produce a huge
523         amount of output.
524       </para>
525     </listitem>
526   </varlistentry>
527   <varlistentry>
528     <term>
529       <option><![CDATA[--trace-barrier=<yes|no> [default: no]]]></option>
530     </term>
531     <listitem>
532       <para>
533         Trace all barrier activity.
534       </para>
535     </listitem>
536   </varlistentry>
537   <varlistentry>
538     <term>
539       <option><![CDATA[--trace-cond=<yes|no> [default: no]]]></option>
540     </term>
541     <listitem>
542       <para>
543         Trace all condition variable activity.
544       </para>
545     </listitem>
546   </varlistentry>
547   <varlistentry>
548     <term>
549       <option><![CDATA[--trace-fork-join=<yes|no> [default: no]]]></option>
550     </term>
551     <listitem>
552       <para>
553         Trace all thread creation and all thread termination events.
554       </para>
555     </listitem>
556   </varlistentry>
557   <varlistentry>
558     <term>
559       <option><![CDATA[--trace-mutex=<yes|no> [default: no]]]></option>
560     </term>
561     <listitem>
562       <para>
563         Trace all mutex activity.
564       </para>
565     </listitem>
566   </varlistentry>
567   <varlistentry>
568     <term>
569       <option><![CDATA[--trace-rwlock=<yes|no> [default: no]]]></option>
570     </term>
571     <listitem>
572       <para>
573          Trace all reader-writer lock activity.
574       </para>
575     </listitem>
576   </varlistentry>
577   <varlistentry>
578     <term>
579       <option><![CDATA[--trace-semaphore=<yes|no> [default: no]]]></option>
580     </term>
581     <listitem>
582       <para>
583         Trace all semaphore activity.
584       </para>
585     </listitem>
586   </varlistentry>
587 </variablelist>
588 <!-- end of xi:include in the manpage -->
589
590 </sect2>
591
592
593 <sect2 id="drd-manual.data-races" xreflabel="Data Races">
594 <title>Detected Errors: Data Races</title>
595
596 <para>
597 DRD prints a message every time it detects a data race. Please keep
598 the following in mind when interpreting DRD's output:
599 <itemizedlist>
600   <listitem>
601     <para>
602       Every thread is assigned a <emphasis>thread ID</emphasis> by the DRD
603       tool. A thread ID is a number. Thread ID's start at one and are never
604       recycled.
605     </para>
606   </listitem>
607   <listitem>
608     <para>
609       The term <emphasis>segment</emphasis> refers to a consecutive
610       sequence of load, store and synchronization operations, all
611       issued by the same thread. A segment always starts and ends at a
612       synchronization operation. Data race analysis is performed
613       between segments instead of between individual load and store
614       operations because of performance reasons.
615     </para>
616   </listitem>
617   <listitem>
618     <para>
619       There are always at least two memory accesses involved in a data
620       race. Memory accesses involved in a data race are called
621       <emphasis>conflicting memory accesses</emphasis>. DRD prints a
622       report for each memory access that conflicts with a past memory
623       access.
624     </para>
625   </listitem>
626 </itemizedlist>
627 </para>
628
629 <para>
630 Below you can find an example of a message printed by DRD when it
631 detects a data race:
632 </para>
633 <programlisting><![CDATA[
634 $ valgrind --tool=drd --read-var-info=yes drd/tests/rwlock_race
635 ...
636 ==9466== Thread 3:
637 ==9466== Conflicting load by thread 3 at 0x006020b8 size 4
638 ==9466==    at 0x400B6C: thread_func (rwlock_race.c:29)
639 ==9466==    by 0x4C291DF: vg_thread_wrapper (drd_pthread_intercepts.c:186)
640 ==9466==    by 0x4E3403F: start_thread (in /lib64/libpthread-2.8.so)
641 ==9466==    by 0x53250CC: clone (in /lib64/libc-2.8.so)
642 ==9466== Location 0x6020b8 is 0 bytes inside local var "s_racy"
643 ==9466== declared at rwlock_race.c:18, in frame #0 of thread 3
644 ==9466== Other segment start (thread 2)
645 ==9466==    at 0x4C2847D: pthread_rwlock_rdlock* (drd_pthread_intercepts.c:813)
646 ==9466==    by 0x400B6B: thread_func (rwlock_race.c:28)
647 ==9466==    by 0x4C291DF: vg_thread_wrapper (drd_pthread_intercepts.c:186)
648 ==9466==    by 0x4E3403F: start_thread (in /lib64/libpthread-2.8.so)
649 ==9466==    by 0x53250CC: clone (in /lib64/libc-2.8.so)
650 ==9466== Other segment end (thread 2)
651 ==9466==    at 0x4C28B54: pthread_rwlock_unlock* (drd_pthread_intercepts.c:912)
652 ==9466==    by 0x400B84: thread_func (rwlock_race.c:30)
653 ==9466==    by 0x4C291DF: vg_thread_wrapper (drd_pthread_intercepts.c:186)
654 ==9466==    by 0x4E3403F: start_thread (in /lib64/libpthread-2.8.so)
655 ==9466==    by 0x53250CC: clone (in /lib64/libc-2.8.so)
656 ...
657 ]]></programlisting>
658
659 <para>
660 The above report has the following meaning:
661 <itemizedlist>
662   <listitem>
663     <para>
664       The number in the column on the left is the process ID of the
665       process being analyzed by DRD.
666     </para>
667   </listitem>
668   <listitem>
669     <para>
670       The first line ("Thread 3") tells you the thread ID for
671       the thread in which context the data race has been detected.
672     </para>
673   </listitem>
674   <listitem>
675     <para>
676       The next line tells which kind of operation was performed (load or
677       store) and by which thread. On the same line the start address and the
678       number of bytes involved in the conflicting access are also displayed.
679     </para>
680   </listitem>
681   <listitem>
682     <para>
683       Next, the call stack of the conflicting access is displayed. If
684       your program has been compiled with debug information
685       (<option>-g</option>), this call stack will include file names and
686       line numbers. The two
687       bottommost frames in this call stack (<function>clone</function>
688       and <function>start_thread</function>) show how the NPTL starts
689       a thread. The third frame
690       (<function>vg_thread_wrapper</function>) is added by DRD. The
691       fourth frame (<function>thread_func</function>) is the first
692       interesting line because it shows the thread entry point, that
693       is the function that has been passed as the third argument to
694       <function>pthread_create</function>.
695     </para>
696   </listitem>
697   <listitem>
698     <para>
699       Next, the allocation context for the conflicting address is
700       displayed. For dynamically allocated data the allocation call
701       stack is shown. For static variables and stack variables the
702       allocation context is only shown when the option
703       <option>--read-var-info=yes</option> has been
704       specified. Otherwise DRD will print <computeroutput>Allocation
705       context: unknown</computeroutput>.
706     </para>
707   </listitem>
708   <listitem>
709     <para>
710       A conflicting access involves at least two memory accesses. For
711       one of these accesses an exact call stack is displayed, and for
712       the other accesses an approximate call stack is displayed,
713       namely the start and the end of the segments of the other
714       accesses. This information can be interpreted as follows:
715       <orderedlist>
716         <listitem>
717           <para>
718             Start at the bottom of both call stacks, and count the
719             number stack frames with identical function name, file
720             name and line number. In the above example the three
721             bottommost frames are identical
722             (<function>clone</function>,
723             <function>start_thread</function> and
724             <function>vg_thread_wrapper</function>).
725           </para>
726         </listitem>
727         <listitem>
728           <para>
729             The next higher stack frame in both call stacks now tells
730             you between in which source code region the other memory
731             access happened. The above output tells that the other
732             memory access involved in the data race happened between
733             source code lines 28 and 30 in file
734             <computeroutput>rwlock_race.c</computeroutput>.
735           </para>
736         </listitem>
737       </orderedlist>
738     </para>
739   </listitem>
740 </itemizedlist>
741 </para>
742
743 </sect2>
744
745
746 <sect2 id="drd-manual.lock-contention" xreflabel="Lock Contention">
747 <title>Detected Errors: Lock Contention</title>
748
749 <para>
750 Threads must be able to make progress without being blocked for too long by
751 other threads. Sometimes a thread has to wait until a mutex or reader-writer
752 synchronization object is unlocked by another thread. This is called
753 <emphasis>lock contention</emphasis>.
754 </para>
755
756 <para>
757 Lock contention causes delays. Such delays should be as short as
758 possible. The two command line options
759 <literal>--exclusive-threshold=&lt;n&gt;</literal> and
760 <literal>--shared-threshold=&lt;n&gt;</literal> make it possible to
761 detect excessive lock contention by making DRD report any lock that
762 has been held longer than the specified threshold. An example:
763 </para>
764 <programlisting><![CDATA[
765 $ valgrind --tool=drd --exclusive-threshold=10 drd/tests/hold_lock -i 500
766 ...
767 ==10668== Acquired at:
768 ==10668==    at 0x4C267C8: pthread_mutex_lock (drd_pthread_intercepts.c:395)
769 ==10668==    by 0x400D92: main (hold_lock.c:51)
770 ==10668== Lock on mutex 0x7fefffd50 was held during 503 ms (threshold: 10 ms).
771 ==10668==    at 0x4C26ADA: pthread_mutex_unlock (drd_pthread_intercepts.c:441)
772 ==10668==    by 0x400DB5: main (hold_lock.c:55)
773 ...
774 ]]></programlisting>
775
776 <para>
777 The <literal>hold_lock</literal> test program holds a lock as long as
778 specified by the <literal>-i</literal> (interval) argument. The DRD
779 output reports that the lock acquired at line 51 in source file
780 <literal>hold_lock.c</literal> and released at line 55 was held during
781 503 ms, while a threshold of 10 ms was specified to DRD.
782 </para>
783
784 </sect2>
785
786
787 <sect2 id="drd-manual.api-checks" xreflabel="API Checks">
788 <title>Detected Errors: Misuse of the POSIX threads API</title>
789
790 <para>
791   DRD is able to detect and report the following misuses of the POSIX
792   threads API:
793   <itemizedlist>
794     <listitem>
795       <para>
796         Passing the address of one type of synchronization object
797         (e.g. a mutex) to a POSIX API call that expects a pointer to
798         another type of synchronization object (e.g. a condition
799         variable).
800       </para>
801     </listitem>
802     <listitem>
803       <para>
804         Attempts to unlock a mutex that has not been locked.
805       </para>
806     </listitem>
807     <listitem>
808       <para>
809         Attempts to unlock a mutex that was locked by another thread.
810       </para>
811     </listitem>
812     <listitem>
813       <para>
814         Attempts to lock a mutex of type
815         <literal>PTHREAD_MUTEX_NORMAL</literal> or a spinlock
816         recursively.
817       </para>
818     </listitem>
819     <listitem>
820       <para>
821         Destruction or deallocation of a locked mutex.
822       </para>
823     </listitem>
824     <listitem>
825       <para>
826         Sending a signal to a condition variable while no lock is held
827         on the mutex associated with the condition variable.
828       </para>
829     </listitem>
830     <listitem>
831       <para>
832         Calling <function>pthread_cond_wait</function> on a mutex
833         that is not locked, that is locked by another thread or that
834         has been locked recursively.
835       </para>
836     </listitem>
837     <listitem>
838       <para>
839         Associating two different mutexes with a condition variable
840         through <function>pthread_cond_wait</function>.
841       </para>
842     </listitem>
843     <listitem>
844       <para>
845         Destruction or deallocation of a condition variable that is
846         being waited upon.
847       </para>
848     </listitem>
849     <listitem>
850       <para>
851         Destruction or deallocation of a locked reader-writer synchronization
852         object.
853       </para>
854     </listitem>
855     <listitem>
856       <para>
857         Attempts to unlock a reader-writer synchronization object that was not
858         locked by the calling thread.
859       </para>
860     </listitem>
861     <listitem>
862       <para>
863         Attempts to recursively lock a reader-writer synchronization object
864         exclusively.
865       </para>
866     </listitem>
867     <listitem>
868       <para>
869         Attempts to pass the address of a user-defined reader-writer
870         synchronization object to a POSIX threads function.
871       </para>
872     </listitem>
873     <listitem>
874       <para>
875         Attempts to pass the address of a POSIX reader-writer synchronization
876         object to one of the annotations for user-defined reader-writer
877         synchronization objects.
878       </para>
879     </listitem>
880     <listitem>
881       <para>
882         Reinitialization of a mutex, condition variable, reader-writer
883         lock, semaphore or barrier.
884       </para>
885     </listitem>
886     <listitem>
887       <para>
888         Destruction or deallocation of a semaphore or barrier that is
889         being waited upon.
890       </para>
891     </listitem>
892     <listitem>
893       <para>
894         Missing synchronization between barrier wait and barrier destruction.
895       </para>
896     </listitem>
897     <listitem>
898       <para>
899         Exiting a thread without first unlocking the spinlocks, mutexes or
900         reader-writer synchronization objects that were locked by that thread.
901       </para>
902     </listitem>
903     <listitem>
904       <para>
905         Passing an invalid thread ID to <function>pthread_join</function>
906         or <function>pthread_cancel</function>.
907       </para>
908     </listitem>
909   </itemizedlist>
910 </para>
911
912 </sect2>
913
914
915 <sect2 id="drd-manual.clientreqs" xreflabel="Client requests">
916 <title>Client Requests</title>
917
918 <para>
919 Just as for other Valgrind tools it is possible to let a client program
920 interact with the DRD tool through client requests. In addition to the
921 client requests several macros have been defined that allow to use the
922 client requests in a convenient way.
923 </para>
924
925 <para>
926 The interface between client programs and the DRD tool is defined in
927 the header file <literal>&lt;valgrind/drd.h&gt;</literal>. The
928 available macros and client requests are:
929 <itemizedlist>
930   <listitem>
931     <para>
932       The macro <literal>DRD_GET_VALGRIND_THREADID</literal> and the
933       corresponding client
934       request <varname>VG_USERREQ__DRD_GET_VALGRIND_THREAD_ID</varname>.
935       Query the thread ID that has been assigned by the Valgrind core to the
936       thread executing this client request. Valgrind's thread ID's start at
937       one and are recycled in case a thread stops.
938     </para>
939   </listitem>
940   <listitem>
941     <para>
942       The macro <literal>DRD_GET_DRD_THREADID</literal> and the corresponding
943       client request <varname>VG_USERREQ__DRD_GET_DRD_THREAD_ID</varname>.
944       Query the thread ID that has been assigned by DRD to the thread
945       executing this client request. These are the thread ID's reported by DRD
946       in data race reports and in trace messages. DRD's thread ID's start at
947       one and are never recycled.
948     </para>
949   </listitem>
950   <listitem>
951     <para>
952       The macros <literal>DRD_IGNORE_VAR(x)</literal>,
953       <literal>ANNOTATE_TRACE_MEMORY(&amp;x)</literal> and the corresponding
954       client request <varname>VG_USERREQ__DRD_START_SUPPRESSION</varname>. Some
955       applications contain intentional races. There exist e.g. applications
956       where the same value is assigned to a shared variable from two different
957       threads. It may be more convenient to suppress such races than to solve
958       these. This client request allows to suppress such races.
959     </para>
960   </listitem>
961   <listitem>
962     <para>
963       The macro <literal>DRD_STOP_IGNORING_VAR(x)</literal> and the
964       corresponding client request
965       <varname>VG_USERREQ__DRD_FINISH_SUPPRESSION</varname>. Tell DRD
966       to no longer ignore data races for the address range that was suppressed
967       either via the macro <literal>DRD_IGNORE_VAR(x)</literal> or via the
968       client request <varname>VG_USERREQ__DRD_START_SUPPRESSION</varname>.
969     </para>
970   </listitem>
971   <listitem>
972     <para>
973       The macro <literal>DRD_TRACE_VAR(x)</literal>. Trace all load and store
974       activity for the address range starting at <literal>&amp;x</literal> and
975       occupying <literal>sizeof(x)</literal> bytes. When DRD reports a data
976       race on a specified variable, and it's not immediately clear which
977       source code statements triggered the conflicting accesses, it can be
978       very helpful to trace all activity on the offending memory location.
979     </para>
980   </listitem>
981   <listitem>
982     <para>
983       The macro <literal>ANNOTATE_TRACE_MEMORY(&amp;x)</literal>. Trace all
984       load and store activity that touches at least the single byte at the
985       address <literal>&amp;x</literal>.
986     </para>
987   </listitem>
988   <listitem>
989     <para>
990       The client request <varname>VG_USERREQ__DRD_START_TRACE_ADDR</varname>,
991       which allows to trace all load and store activity for the specified
992       address range.
993     </para>
994   </listitem>
995   <listitem>
996     <para>
997       The client
998       request <varname>VG_USERREQ__DRD_STOP_TRACE_ADDR</varname>. Do no longer
999       trace load and store activity for the specified address range.
1000     </para>
1001   </listitem>
1002   <listitem>
1003     <para>
1004       The macro <literal>ANNOTATE_HAPPENS_BEFORE(addr)</literal> tells DRD to
1005       insert a mark. Insert this macro just after an access to the variable at
1006       the specified address has been performed.
1007     </para>
1008   </listitem>
1009   <listitem>
1010     <para>
1011       The macro <literal>ANNOTATE_HAPPENS_AFTER(addr)</literal> tells DRD that
1012       the next access to the variable at the specified address should be
1013       considered to have happened after the access just before the latest
1014       <literal>ANNOTATE_HAPPENS_BEFORE(addr)</literal> annotation that
1015       references the same variable. The purpose of these two macros is to tell
1016       DRD about the order of inter-thread memory accesses implemented via
1017       atomic memory operations. See
1018       also <literal>drd/tests/annotate_smart_pointer.cpp</literal> for an
1019       example.
1020     </para>
1021   </listitem>
1022   <listitem>
1023     <para>
1024       The macro <literal>ANNOTATE_RWLOCK_CREATE(rwlock)</literal> tells DRD
1025       that the object at address <literal>rwlock</literal> is a
1026       reader-writer synchronization object that is not a
1027       <literal>pthread_rwlock_t</literal> synchronization object.  See
1028       also <literal>drd/tests/annotate_rwlock.c</literal> for an example.
1029     </para>
1030   </listitem>
1031   <listitem>
1032     <para>
1033       The macro <literal>ANNOTATE_RWLOCK_DESTROY(rwlock)</literal> tells DRD
1034       that the reader-writer synchronization object at
1035       address <literal>rwlock</literal> has been destroyed.
1036     </para>
1037   </listitem>
1038   <listitem>
1039     <para>
1040       The macro <literal>ANNOTATE_WRITERLOCK_ACQUIRED(rwlock)</literal> tells
1041       DRD that a writer lock has been acquired on the reader-writer
1042       synchronization object at address <literal>rwlock</literal>.
1043     </para>
1044   </listitem>
1045   <listitem>
1046     <para>
1047       The macro <literal>ANNOTATE_READERLOCK_ACQUIRED(rwlock)</literal> tells
1048       DRD that a reader lock has been acquired on the reader-writer
1049       synchronization object at address <literal>rwlock</literal>.
1050     </para>
1051   </listitem>
1052   <listitem>
1053     <para>
1054       The macro <literal>ANNOTATE_RWLOCK_ACQUIRED(rwlock, is_w)</literal>
1055       tells DRD that a writer lock (when <literal>is_w != 0</literal>) or that
1056       a reader lock (when <literal>is_w == 0</literal>) has been acquired on
1057       the reader-writer synchronization object at
1058       address <literal>rwlock</literal>.
1059     </para>
1060   </listitem>
1061   <listitem>
1062     <para>
1063       The macro <literal>ANNOTATE_WRITERLOCK_RELEASED(rwlock)</literal> tells
1064       DRD that a writer lock has been released on the reader-writer
1065       synchronization object at address <literal>rwlock</literal>.
1066     </para>
1067   </listitem>
1068   <listitem>
1069     <para>
1070       The macro <literal>ANNOTATE_READERLOCK_RELEASED(rwlock)</literal> tells
1071       DRD that a reader lock has been released on the reader-writer
1072       synchronization object at address <literal>rwlock</literal>.
1073     </para>
1074   </listitem>
1075   <listitem>
1076     <para>
1077       The macro <literal>ANNOTATE_RWLOCK_RELEASED(rwlock, is_w)</literal>
1078       tells DRD that a writer lock (when <literal>is_w != 0</literal>) or that
1079       a reader lock (when <literal>is_w == 0</literal>) has been released on
1080       the reader-writer synchronization object at
1081       address <literal>rwlock</literal>.
1082     </para>
1083   </listitem>
1084   <listitem>
1085     <para>
1086       The macro <literal>ANNOTATE_BARRIER_INIT(barrier, count,
1087       reinitialization_allowed)</literal> tells DRD that a new barrier object
1088       at the address <literal>barrier</literal> has been initialized,
1089       that <literal>count</literal> threads participate in each barrier and
1090       also whether or not barrier reinitialization without intervening
1091       destruction should be reported as an error. See
1092       also <literal>drd/tests/annotate_barrier.c</literal> for an example.
1093     </para>
1094   </listitem>
1095   <listitem>
1096     <para>
1097       The macro <literal>ANNOTATE_BARRIER_DESTROY(barrier)</literal>
1098       tells DRD that a barrier object is about to be destroyed.
1099     </para>
1100   </listitem>
1101   <listitem>
1102     <para>
1103       The macro <literal>ANNOTATE_BARRIER_WAIT_BEFORE(barrier)</literal>
1104       tells DRD that waiting for a barrier will start.
1105     </para>
1106   </listitem>
1107   <listitem>
1108     <para>
1109       The macro <literal>ANNOTATE_BARRIER_WAIT_AFTER(barrier)</literal>
1110       tells DRD that waiting for a barrier has finished.
1111     </para>
1112   </listitem>
1113   <listitem>
1114     <para>
1115       The macro <literal>ANNOTATE_BENIGN_RACE_SIZED(addr, size,
1116       descr)</literal> tells DRD that any races detected on the specified
1117       address are benign and hence should not be
1118       reported. The <literal>descr</literal> argument is ignored but can be
1119       used to document why data races on <literal>addr</literal> are benign.
1120     </para>
1121   </listitem>
1122   <listitem>
1123     <para>
1124       The macro <literal>ANNOTATE_BENIGN_RACE_STATIC(var, descr)</literal>
1125       tells DRD that any races detected on the specified static variable are
1126       benign and hence should not be reported. The <literal>descr</literal>
1127       argument is ignored but can be used to document why data races
1128       on <literal>var</literal> are benign. Note: this macro can only be
1129       used in C++ programs and not in C programs.
1130     </para>
1131   </listitem>
1132   <listitem>
1133     <para>
1134       The macro <literal>ANNOTATE_IGNORE_READS_BEGIN</literal> tells
1135       DRD to ignore all memory loads performed by the current thread.
1136     </para>
1137   </listitem>
1138   <listitem>
1139     <para>
1140       The macro <literal>ANNOTATE_IGNORE_READS_END</literal> tells
1141       DRD to stop ignoring the memory loads performed by the current thread.
1142     </para>
1143   </listitem>
1144   <listitem>
1145     <para>
1146       The macro <literal>ANNOTATE_IGNORE_WRITES_BEGIN</literal> tells
1147       DRD to ignore all memory stores performed by the current thread.
1148     </para>
1149   </listitem>
1150   <listitem>
1151     <para>
1152       The macro <literal>ANNOTATE_IGNORE_WRITES_END</literal> tells
1153       DRD to stop ignoring the memory stores performed by the current thread.
1154     </para>
1155   </listitem>
1156   <listitem>
1157     <para>
1158       The macro <literal>ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN</literal> tells
1159       DRD to ignore all memory accesses performed by the current thread.
1160     </para>
1161   </listitem>
1162   <listitem>
1163     <para>
1164       The macro <literal>ANNOTATE_IGNORE_READS_AND_WRITES_END</literal> tells
1165       DRD to stop ignoring the memory accesses performed by the current thread.
1166     </para>
1167   </listitem>
1168   <listitem>
1169     <para>
1170       The macro <literal>ANNOTATE_NEW_MEMORY(addr, size)</literal> tells
1171       DRD that the specified memory range has been allocated by a custom
1172       memory allocator in the client program and that the client program
1173       will start using this memory range.
1174     </para>
1175   </listitem>
1176   <listitem>
1177     <para>
1178       The macro <literal>ANNOTATE_THREAD_NAME(name)</literal> tells DRD to
1179       associate the specified name with the current thread and to include this
1180       name in the error messages printed by DRD.
1181     </para>
1182   </listitem>
1183   <listitem>
1184     <para>
1185       The macros <literal>VALGRIND_MALLOCLIKE_BLOCK</literal> and
1186       <literal>VALGRIND_FREELIKE_BLOCK</literal> from the Valgrind core are
1187       implemented;  they are described in 
1188       <xref linkend="manual-core-adv.clientreq"/>.
1189     </para>
1190   </listitem>
1191 </itemizedlist>
1192 </para>
1193
1194 <para>
1195 Note: if you compiled Valgrind yourself, the header file
1196 <literal>&lt;valgrind/drd.h&gt;</literal> will have been installed in
1197 the directory <literal>/usr/include</literal> by the command
1198 <literal>make install</literal>. If you obtained Valgrind by
1199 installing it as a package however, you will probably have to install
1200 another package with a name like <literal>valgrind-devel</literal>
1201 before Valgrind's header files are available.
1202 </para>
1203
1204 </sect2>
1205
1206
1207 <sect2 id="drd-manual.gnome" xreflabel="GNOME">
1208 <title>Debugging GNOME Programs</title>
1209
1210 <para>
1211 GNOME applications use the threading primitives provided by the
1212 <computeroutput>glib</computeroutput> and
1213 <computeroutput>gthread</computeroutput> libraries. These libraries
1214 are built on top of POSIX threads, and hence are directly supported by
1215 DRD. Please keep in mind that you have to call
1216 <function>g_thread_init</function> before creating any threads, or
1217 DRD will report several data races on glib functions. See also the
1218 <ulink
1219 url="http://library.gnome.org/devel/glib/stable/glib-Threads.html">GLib
1220 Reference Manual</ulink> for more information about
1221 <function>g_thread_init</function>.
1222 </para>
1223
1224 <para>
1225 One of the many facilities provided by the <literal>glib</literal>
1226 library is a block allocator, called <literal>g_slice</literal>. You
1227 have to disable this block allocator when using DRD by adding the
1228 following to the shell environment variables:
1229 <literal>G_SLICE=always-malloc</literal>. See also the <ulink
1230 url="http://library.gnome.org/devel/glib/stable/glib-Memory-Slices.html">GLib
1231 Reference Manual</ulink> for more information.
1232 </para>
1233
1234 </sect2>
1235
1236
1237 <sect2 id="drd-manual.boost.thread" xreflabel="Boost.Thread">
1238 <title>Debugging Boost.Thread Programs</title>
1239
1240 <para>
1241 The Boost.Thread library is the threading library included with the
1242 cross-platform Boost Libraries. This threading library is an early
1243 implementation of the upcoming C++0x threading library.
1244 </para>
1245
1246 <para>
1247 Applications that use the Boost.Thread library should run fine under DRD.
1248 </para>
1249
1250 <para>
1251 More information about Boost.Thread can be found here:
1252 <itemizedlist>
1253   <listitem>
1254     <para>
1255       Anthony Williams, <ulink
1256       url="http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html">Boost.Thread</ulink>
1257       Library Documentation, Boost website, 2007.
1258     </para>
1259   </listitem>
1260   <listitem>
1261     <para>
1262       Anthony Williams, <ulink
1263       url="http://www.ddj.com/cpp/211600441">What's New in Boost
1264       Threads?</ulink>, Recent changes to the Boost Thread library,
1265       Dr. Dobbs Magazine, October 2008.
1266     </para>
1267   </listitem>
1268 </itemizedlist>
1269 </para>
1270
1271 </sect2>
1272
1273
1274 <sect2 id="drd-manual.openmp" xreflabel="OpenMP">
1275 <title>Debugging OpenMP Programs</title>
1276
1277 <para>
1278 OpenMP stands for <emphasis>Open Multi-Processing</emphasis>. The OpenMP
1279 standard consists of a set of compiler directives for C, C++ and Fortran
1280 programs that allows a compiler to transform a sequential program into a
1281 parallel program. OpenMP is well suited for HPC applications and allows to
1282 work at a higher level compared to direct use of the POSIX threads API. While
1283 OpenMP ensures that the POSIX API is used correctly, OpenMP programs can still
1284 contain data races. So it definitely makes sense to verify OpenMP programs
1285 with a thread checking tool.
1286 </para>
1287
1288 <para>
1289 DRD supports OpenMP shared-memory programs generated by GCC. GCC
1290 supports OpenMP since version 4.2.0.  GCC's runtime support
1291 for OpenMP programs is provided by a library called
1292 <literal>libgomp</literal>. The synchronization primitives implemented
1293 in this library use Linux' futex system call directly, unless the
1294 library has been configured with the
1295 <literal>--disable-linux-futex</literal> option. DRD only supports
1296 libgomp libraries that have been configured with this option and in
1297 which symbol information is present. For most Linux distributions this
1298 means that you will have to recompile GCC. See also the script
1299 <literal>drd/scripts/download-and-build-gcc</literal> in the
1300 Valgrind source tree for an example of how to compile GCC. You will
1301 also have to make sure that the newly compiled
1302 <literal>libgomp.so</literal> library is loaded when OpenMP programs
1303 are started. This is possible by adding a line similar to the
1304 following to your shell startup script:
1305 </para>
1306 <programlisting><![CDATA[
1307 export LD_LIBRARY_PATH=~/gcc-4.4.0/lib64:~/gcc-4.4.0/lib:
1308 ]]></programlisting>
1309
1310 <para>
1311 As an example, the test OpenMP test program
1312 <literal>drd/tests/omp_matinv</literal> triggers a data race
1313 when the option -r has been specified on the command line. The data
1314 race is triggered by the following code:
1315 </para>
1316 <programlisting><![CDATA[
1317 #pragma omp parallel for private(j)
1318 for (j = 0; j < rows; j++)
1319 {
1320   if (i != j)
1321   {
1322     const elem_t factor = a[j * cols + i];
1323     for (k = 0; k < cols; k++)
1324     {
1325       a[j * cols + k] -= a[i * cols + k] * factor;
1326     }
1327   }
1328 }
1329 ]]></programlisting>
1330
1331 <para>
1332 The above code is racy because the variable <literal>k</literal> has
1333 not been declared private. DRD will print the following error message
1334 for the above code:
1335 </para>
1336 <programlisting><![CDATA[
1337 $ valgrind --tool=drd --check-stack-var=yes --read-var-info=yes drd/tests/omp_matinv 3 -t 2 -r
1338 ...
1339 Conflicting store by thread 1/1 at 0x7fefffbc4 size 4
1340    at 0x4014A0: gj.omp_fn.0 (omp_matinv.c:203)
1341    by 0x401211: gj (omp_matinv.c:159)
1342    by 0x40166A: invert_matrix (omp_matinv.c:238)
1343    by 0x4019B4: main (omp_matinv.c:316)
1344 Location 0x7fefffbc4 is 0 bytes inside local var "k"
1345 declared at omp_matinv.c:160, in frame #0 of thread 1
1346 ...
1347 ]]></programlisting>
1348 <para>
1349 In the above output the function name <function>gj.omp_fn.0</function>
1350 has been generated by GCC from the function name
1351 <function>gj</function>. The allocation context information shows that the
1352 data race has been caused by modifying the variable <literal>k</literal>.
1353 </para>
1354
1355 <para>
1356 Note: for GCC versions before 4.4.0, no allocation context information is
1357 shown. With these GCC versions the most usable information in the above output
1358 is the source file name and the line number where the data race has been
1359 detected (<literal>omp_matinv.c:203</literal>).
1360 </para>
1361
1362 <para>
1363 For more information about OpenMP, see also 
1364 <ulink url="http://openmp.org/">openmp.org</ulink>.
1365 </para>
1366
1367 </sect2>
1368
1369
1370 <sect2 id="drd-manual.cust-mem-alloc" xreflabel="Custom Memory Allocators">
1371 <title>DRD and Custom Memory Allocators</title>
1372
1373 <para>
1374 DRD tracks all memory allocation events that happen via the
1375 standard memory allocation and deallocation functions
1376 (<function>malloc</function>, <function>free</function>,
1377 <function>new</function> and <function>delete</function>), via entry
1378 and exit of stack frames or that have been annotated with Valgrind's
1379 memory pool client requests. DRD uses memory allocation and deallocation
1380 information for two purposes:
1381 <itemizedlist>
1382   <listitem>
1383     <para>
1384       To know where the scope ends of POSIX objects that have not been
1385       destroyed explicitly. It is e.g. not required by the POSIX
1386       threads standard to call
1387       <function>pthread_mutex_destroy</function> before freeing the
1388       memory in which a mutex object resides.
1389     </para>
1390   </listitem>
1391   <listitem>
1392     <para>
1393       To know where the scope of variables ends. If e.g. heap memory
1394       has been used by one thread, that thread frees that memory, and
1395       another thread allocates and starts using that memory, no data
1396       races must be reported for that memory.
1397     </para>
1398   </listitem>
1399 </itemizedlist>
1400 </para>
1401
1402 <para>
1403 It is essential for correct operation of DRD that the tool knows about
1404 memory allocation and deallocation events. When analyzing a client program
1405 with DRD that uses a custom memory allocator, either instrument the custom
1406 memory allocator with the <literal>VALGRIND_MALLOCLIKE_BLOCK</literal>
1407 and <literal>VALGRIND_FREELIKE_BLOCK</literal> macros or disable the
1408 custom memory allocator.
1409 </para>
1410
1411 <para>
1412 As an example, the GNU libstdc++ library can be configured
1413 to use standard memory allocation functions instead of memory pools by
1414 setting the environment variable
1415 <literal>GLIBCXX_FORCE_NEW</literal>. For more information, see also
1416 the <ulink
1417 url="http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt04ch11.html">libstdc++
1418 manual</ulink>.
1419 </para>
1420
1421 </sect2>
1422
1423
1424 <sect2 id="drd-manual.drd-versus-memcheck" xreflabel="DRD Versus Memcheck">
1425 <title>DRD Versus Memcheck</title>
1426
1427 <para>
1428 It is essential for correct operation of DRD that there are no memory
1429 errors such as dangling pointers in the client program. Which means that
1430 it is a good idea to make sure that your program is Memcheck-clean
1431 before you analyze it with DRD. It is possible however that some of
1432 the Memcheck reports are caused by data races. In this case it makes
1433 sense to run DRD before Memcheck.
1434 </para>
1435
1436 <para>
1437 So which tool should be run first? In case both DRD and Memcheck
1438 complain about a program, a possible approach is to run both tools
1439 alternatingly and to fix as many errors as possible after each run of
1440 each tool until none of the two tools prints any more error messages.
1441 </para>
1442
1443 </sect2>
1444
1445
1446 <sect2 id="drd-manual.resource-requirements" xreflabel="Resource Requirements">
1447 <title>Resource Requirements</title>
1448
1449 <para>
1450 The requirements of DRD with regard to heap and stack memory and the
1451 effect on the execution time of client programs are as follows:
1452 <itemizedlist>
1453   <listitem>
1454     <para>
1455       When running a program under DRD with default DRD options,
1456       between 1.1 and 3.6 times more memory will be needed compared to
1457       a native run of the client program. More memory will be needed
1458       if loading debug information has been enabled
1459       (<literal>--read-var-info=yes</literal>).
1460     </para>
1461   </listitem>
1462   <listitem>
1463     <para>
1464       DRD allocates some of its temporary data structures on the stack
1465       of the client program threads. This amount of data is limited to
1466       1 - 2 KB. Make sure that thread stacks are sufficiently large.
1467     </para>
1468   </listitem>
1469   <listitem>
1470     <para>
1471       Most applications will run between 20 and 50 times slower under
1472       DRD than a native single-threaded run. The slowdown will be most
1473       noticeable for applications which perform frequent mutex lock /
1474       unlock operations.
1475     </para>
1476   </listitem>
1477 </itemizedlist>
1478 </para>
1479
1480 </sect2>
1481
1482
1483 <sect2 id="drd-manual.effective-use" xreflabel="Effective Use">
1484 <title>Hints and Tips for Effective Use of DRD</title>
1485
1486 <para>
1487 The following information may be helpful when using DRD:
1488 <itemizedlist>
1489   <listitem>
1490     <para>
1491       Make sure that debug information is present in the executable
1492       being analyzed, such that DRD can print function name and line
1493       number information in stack traces. Most compilers can be told
1494       to include debug information via compiler option
1495       <option>-g</option>.
1496     </para>
1497   </listitem>
1498   <listitem>
1499     <para>
1500       Compile with option <option>-O1</option> instead of
1501       <option>-O0</option>. This will reduce the amount of generated
1502       code, may reduce the amount of debug info and will speed up
1503       DRD's processing of the client program. For more information,
1504       see also <xref linkend="manual-core.started"/>.
1505     </para>
1506   </listitem>
1507   <listitem>
1508     <para>
1509       If DRD reports any errors on libraries that are part of your
1510       Linux distribution like e.g. <literal>libc.so</literal> or
1511       <literal>libstdc++.so</literal>, installing the debug packages
1512       for these libraries will make the output of DRD a lot more
1513       detailed.
1514     </para>
1515   </listitem>
1516   <listitem>
1517     <para>
1518       When using C++, do not send output from more than one thread to
1519       <literal>std::cout</literal>. Doing so would not only
1520       generate multiple data race reports, it could also result in
1521       output from several threads getting mixed up.  Either use
1522       <function>printf</function> or do the following:
1523       <orderedlist>
1524         <listitem>
1525           <para>Derive a class from <literal>std::ostreambuf</literal>
1526           and let that class send output line by line to
1527           <literal>stdout</literal>. This will avoid that individual
1528           lines of text produced by different threads get mixed
1529           up.</para>
1530         </listitem>
1531         <listitem>
1532           <para>Create one instance of <literal>std::ostream</literal>
1533           for each thread. This makes stream formatting settings
1534           thread-local. Pass a per-thread instance of the class
1535           derived from <literal>std::ostreambuf</literal> to the
1536           constructor of each instance. </para>
1537         </listitem>
1538         <listitem>
1539           <para>Let each thread send its output to its own instance of
1540           <literal>std::ostream</literal> instead of
1541           <literal>std::cout</literal>.</para>
1542         </listitem>
1543       </orderedlist>
1544     </para>
1545   </listitem>
1546 </itemizedlist>
1547 </para>
1548
1549 </sect2>
1550
1551
1552 </sect1>
1553
1554
1555 <sect1 id="drd-manual.Pthreads" xreflabel="Pthreads">
1556 <title>Using the POSIX Threads API Effectively</title>
1557
1558 <sect2 id="drd-manual.mutex-types" xreflabel="mutex-types">
1559 <title>Mutex types</title>
1560
1561 <para>
1562 The Single UNIX Specification version two defines the following four
1563 mutex types (see also the documentation of <ulink
1564 url="http://www.opengroup.org/onlinepubs/007908799/xsh/pthread_mutexattr_settype.html"><function>pthread_mutexattr_settype</function></ulink>):
1565 <itemizedlist>
1566   <listitem>
1567     <para>
1568       <emphasis>normal</emphasis>, which means that no error checking
1569       is performed, and that the mutex is non-recursive.
1570     </para>
1571   </listitem>
1572   <listitem>
1573     <para>
1574       <emphasis>error checking</emphasis>, which means that the mutex
1575       is non-recursive and that error checking is performed.
1576     </para>
1577   </listitem>
1578   <listitem>
1579     <para>
1580       <emphasis>recursive</emphasis>, which means that a mutex may be
1581       locked recursively.
1582     </para>
1583   </listitem>
1584   <listitem>
1585     <para>
1586       <emphasis>default</emphasis>, which means that error checking
1587       behavior is undefined, and that the behavior for recursive
1588       locking is also undefined. Or: portable code must neither
1589       trigger error conditions through the Pthreads API nor attempt to
1590       lock a mutex of default type recursively.
1591     </para>
1592   </listitem>
1593 </itemizedlist>
1594 </para>
1595
1596 <para>
1597 In complex applications it is not always clear from beforehand which
1598 mutex will be locked recursively and which mutex will not be locked
1599 recursively. Attempts lock a non-recursive mutex recursively will
1600 result in race conditions that are very hard to find without a thread
1601 checking tool. So either use the error checking mutex type and
1602 consistently check the return value of Pthread API mutex calls, or use
1603 the recursive mutex type.
1604 </para>
1605
1606 </sect2>
1607
1608 <sect2 id="drd-manual.condvar" xreflabel="condition-variables">
1609 <title>Condition variables</title>
1610
1611 <para>
1612 A condition variable allows one thread to wake up one or more other
1613 threads. Condition variables are often used to notify one or more
1614 threads about state changes of shared data. Unfortunately it is very
1615 easy to introduce race conditions by using condition variables as the
1616 only means of state information propagation. A better approach is to
1617 let threads poll for changes of a state variable that is protected by
1618 a mutex, and to use condition variables only as a thread wakeup
1619 mechanism. See also the source file
1620 <computeroutput>drd/tests/monitor_example.cpp</computeroutput> for an
1621 example of how to implement this concept in C++. The monitor concept
1622 used in this example is a well known and very useful concept -- see
1623 also Wikipedia for more information about the <ulink
1624 url="http://en.wikipedia.org/wiki/Monitor_(synchronization)">monitor</ulink>
1625 concept.
1626 </para>
1627
1628 </sect2>
1629
1630 <sect2 id="drd-manual.pctw" xreflabel="pthread_cond_timedwait">
1631 <title>pthread_cond_timedwait and timeouts</title>
1632
1633 <para>
1634 Historically the function
1635 <function>pthread_cond_timedwait</function> only allowed the
1636 specification of an absolute timeout, that is a timeout independent of
1637 the time when this function was called. However, almost every call to
1638 this function expresses a relative timeout. This typically happens by
1639 passing the sum of
1640 <computeroutput>clock_gettime(CLOCK_REALTIME)</computeroutput> and a
1641 relative timeout as the third argument. This approach is incorrect
1642 since forward or backward clock adjustments by e.g. ntpd will affect
1643 the timeout. A more reliable approach is as follows:
1644 <itemizedlist>
1645   <listitem>
1646     <para>
1647       When initializing a condition variable through
1648       <function>pthread_cond_init</function>, specify that the timeout of
1649       <function>pthread_cond_timedwait</function> will use the clock
1650       <literal>CLOCK_MONOTONIC</literal> instead of
1651       <literal>CLOCK_REALTIME</literal>. You can do this via
1652       <computeroutput>pthread_condattr_setclock(...,
1653       CLOCK_MONOTONIC)</computeroutput>.
1654     </para>
1655   </listitem>
1656   <listitem>
1657     <para>
1658       When calling <function>pthread_cond_timedwait</function>, pass
1659       the sum of
1660       <computeroutput>clock_gettime(CLOCK_MONOTONIC)</computeroutput>
1661       and a relative timeout as the third argument.
1662     </para>
1663   </listitem>
1664 </itemizedlist>
1665 See also
1666 <computeroutput>drd/tests/monitor_example.cpp</computeroutput> for an
1667 example.
1668 </para>
1669
1670 </sect2>
1671
1672 </sect1>
1673
1674
1675 <sect1 id="drd-manual.limitations" xreflabel="Limitations">
1676 <title>Limitations</title>
1677
1678 <para>DRD currently has the following limitations:</para>
1679
1680 <itemizedlist>
1681   <listitem>
1682     <para>
1683       DRD, just like Memcheck, will refuse to start on Linux
1684       distributions where all symbol information has been removed from
1685       <filename>ld.so</filename>. This is e.g. the case for the PPC editions
1686       of openSUSE and Gentoo. You will have to install the glibc debuginfo
1687       package on these platforms before you can use DRD. See also openSUSE
1688       bug <ulink url="http://bugzilla.novell.com/show_bug.cgi?id=396197">
1689       396197</ulink> and Gentoo bug <ulink
1690       url="http://bugs.gentoo.org/214065">214065</ulink>.
1691     </para>
1692   </listitem>
1693   <listitem>
1694     <para>
1695       With gcc 4.4.3 and before, DRD may report data races on the C++
1696       class <literal>std::string</literal> in a multithreaded program. This is
1697       a know <literal>libstdc++</literal> issue -- see also GCC bug
1698       <ulink url="http://gcc.gnu.org/bugzilla/show_bug.cgi?id=40518">40518</ulink>
1699       for more information.
1700     </para>
1701   </listitem>
1702   <listitem>
1703     <para>
1704       When address tracing is enabled, no information on atomic stores
1705       will be displayed.
1706     </para>
1707   </listitem>
1708   <listitem>
1709     <para>
1710       If you compile the DRD source code yourself, you need GCC 3.0 or
1711       later. GCC 2.95 is not supported.
1712     </para>
1713   </listitem>
1714   <listitem>
1715     <para>
1716       Of the two POSIX threads implementations for Linux, only the
1717       NPTL (Native POSIX Thread Library) is supported. The older
1718       LinuxThreads library is not supported.
1719     </para>
1720   </listitem>
1721 </itemizedlist>
1722
1723 </sect1>
1724
1725
1726 <sect1 id="drd-manual.feedback" xreflabel="Feedback">
1727 <title>Feedback</title>
1728
1729 <para>
1730 If you have any comments, suggestions, feedback or bug reports about
1731 DRD, feel free to either post a message on the Valgrind users mailing
1732 list or to file a bug report. See also <ulink
1733 url="&vg-url;">&vg-url;</ulink> for more information.
1734 </para>
1735
1736 </sect1>
1737
1738
1739 </chapter>