]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/valgrind/src/valgrind-3.6.0-svn/drd/docs/drd-manual.xml
Inital import
[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[--report-signal-unlocked=<yes|no> [default: yes]]]>
368       </option>
369     </term>
370     <listitem>
371       <para>
372         Whether to report calls to
373         <function>pthread_cond_signal</function> and
374         <function>pthread_cond_broadcast</function> where the mutex
375         associated with the signal through
376         <function>pthread_cond_wait</function> or
377         <function>pthread_cond_timed_wait</function>is not locked at
378         the time the signal is sent.  Sending a signal without holding
379         a lock on the associated mutex is a common programming error
380         which can cause subtle race conditions and unpredictable
381         behavior. There exist some uncommon synchronization patterns
382         however where it is safe to send a signal without holding a
383         lock on the associated mutex.
384       </para>
385     </listitem>
386   </varlistentry>
387   <varlistentry>
388     <term>
389       <option><![CDATA[--segment-merging=<yes|no> [default: yes]]]></option>
390     </term>
391     <listitem>
392       <para>
393         Controls segment merging. Segment merging is an algorithm to
394         limit memory usage of the data race detection
395         algorithm. Disabling segment merging may improve the accuracy
396         of the so-called 'other segments' displayed in race reports
397         but can also trigger an out of memory error.
398       </para>
399     </listitem>
400   </varlistentry>
401   <varlistentry>
402     <term>
403       <option><![CDATA[--segment-merging-interval=<n> [default: 10]]]></option>
404     </term>
405     <listitem>
406       <para>
407         Perform segment merging only after the specified number of new
408         segments have been created. This is an advanced configuration option
409         that allows to choose whether to minimize DRD's memory usage by
410         choosing a low value or to let DRD run faster by choosing a slightly
411         higher value. The optimal value for this parameter depends on the
412         program being analyzed. The default value works well for most programs.
413       </para>
414     </listitem>
415   </varlistentry>
416   <varlistentry>
417     <term>
418       <option><![CDATA[--shared-threshold=<n> [default: off]]]></option>
419     </term>
420     <listitem>
421       <para>
422         Print an error message if a reader lock has been held longer
423         than the specified time (in milliseconds). This option enables
424         the detection of lock contention.
425       </para>
426     </listitem>
427   </varlistentry>
428   <varlistentry>
429     <term>
430       <option><![CDATA[--show-confl-seg=<yes|no> [default: yes]]]></option>
431     </term>
432     <listitem>
433       <para>
434          Show conflicting segments in race reports. Since this
435          information can help to find the cause of a data race, this
436          option is enabled by default. Disabling this option makes the
437          output of DRD more compact.
438       </para>
439     </listitem>
440   </varlistentry>
441   <varlistentry>
442     <term>
443       <option><![CDATA[--show-stack-usage=<yes|no> [default: no]]]></option>
444     </term>
445     <listitem>
446       <para>
447         Print stack usage at thread exit time. When a program creates a large
448         number of threads it becomes important to limit the amount of virtual
449         memory allocated for thread stacks. This option makes it possible to
450         observe how much stack memory has been used by each thread of the the
451         client program. Note: the DRD tool itself allocates some temporary
452         data on the client thread stack. The space necessary for this
453         temporary data must be allocated by the client program when it
454         allocates stack memory, but is not included in stack usage reported by
455         DRD.
456       </para>
457     </listitem>
458   </varlistentry>
459 </variablelist>
460 <!-- end of xi:include in the manpage -->
461
462 <!-- start of xi:include in the manpage -->
463 <para>
464 The following options are available for monitoring the behavior of the
465 client program:
466 </para>
467
468 <variablelist id="drd.debugopts.list">
469   <varlistentry>
470     <term>
471       <option><![CDATA[--trace-addr=<address> [default: none]]]></option>
472     </term>
473     <listitem>
474       <para>
475         Trace all load and store activity for the specified
476         address. This option may be specified more than once.
477       </para>
478     </listitem>
479   </varlistentry>
480   <varlistentry>
481     <term>
482       <option><![CDATA[--trace-barrier=<yes|no> [default: no]]]></option>
483     </term>
484     <listitem>
485       <para>
486         Trace all barrier activity.
487       </para>
488     </listitem>
489   </varlistentry>
490   <varlistentry>
491     <term>
492       <option><![CDATA[--trace-cond=<yes|no> [default: no]]]></option>
493     </term>
494     <listitem>
495       <para>
496         Trace all condition variable activity.
497       </para>
498     </listitem>
499   </varlistentry>
500   <varlistentry>
501     <term>
502       <option><![CDATA[--trace-fork-join=<yes|no> [default: no]]]></option>
503     </term>
504     <listitem>
505       <para>
506         Trace all thread creation and all thread termination events.
507       </para>
508     </listitem>
509   </varlistentry>
510   <varlistentry>
511     <term>
512       <option><![CDATA[--trace-mutex=<yes|no> [default: no]]]></option>
513     </term>
514     <listitem>
515       <para>
516         Trace all mutex activity.
517       </para>
518     </listitem>
519   </varlistentry>
520   <varlistentry>
521     <term>
522       <option><![CDATA[--trace-rwlock=<yes|no> [default: no]]]></option>
523     </term>
524     <listitem>
525       <para>
526          Trace all reader-writer lock activity.
527       </para>
528     </listitem>
529   </varlistentry>
530   <varlistentry>
531     <term>
532       <option><![CDATA[--trace-semaphore=<yes|no> [default: no]]]></option>
533     </term>
534     <listitem>
535       <para>
536         Trace all semaphore activity.
537       </para>
538     </listitem>
539   </varlistentry>
540 </variablelist>
541 <!-- end of xi:include in the manpage -->
542
543 </sect2>
544
545
546 <sect2 id="drd-manual.data-races" xreflabel="Data Races">
547 <title>Detected Errors: Data Races</title>
548
549 <para>
550 DRD prints a message every time it detects a data race. Please keep
551 the following in mind when interpreting DRD's output:
552 <itemizedlist>
553   <listitem>
554     <para>
555       Every thread is assigned a <emphasis>thread ID</emphasis> by the DRD
556       tool. A thread ID is a number. Thread ID's start at one and are never
557       recycled.
558     </para>
559   </listitem>
560   <listitem>
561     <para>
562       The term <emphasis>segment</emphasis> refers to a consecutive
563       sequence of load, store and synchronization operations, all
564       issued by the same thread. A segment always starts and ends at a
565       synchronization operation. Data race analysis is performed
566       between segments instead of between individual load and store
567       operations because of performance reasons.
568     </para>
569   </listitem>
570   <listitem>
571     <para>
572       There are always at least two memory accesses involved in a data
573       race. Memory accesses involved in a data race are called
574       <emphasis>conflicting memory accesses</emphasis>. DRD prints a
575       report for each memory access that conflicts with a past memory
576       access.
577     </para>
578   </listitem>
579 </itemizedlist>
580 </para>
581
582 <para>
583 Below you can find an example of a message printed by DRD when it
584 detects a data race:
585 </para>
586 <programlisting><![CDATA[
587 $ valgrind --tool=drd --read-var-info=yes drd/tests/rwlock_race
588 ...
589 ==9466== Thread 3:
590 ==9466== Conflicting load by thread 3 at 0x006020b8 size 4
591 ==9466==    at 0x400B6C: thread_func (rwlock_race.c:29)
592 ==9466==    by 0x4C291DF: vg_thread_wrapper (drd_pthread_intercepts.c:186)
593 ==9466==    by 0x4E3403F: start_thread (in /lib64/libpthread-2.8.so)
594 ==9466==    by 0x53250CC: clone (in /lib64/libc-2.8.so)
595 ==9466== Location 0x6020b8 is 0 bytes inside local var "s_racy"
596 ==9466== declared at rwlock_race.c:18, in frame #0 of thread 3
597 ==9466== Other segment start (thread 2)
598 ==9466==    at 0x4C2847D: pthread_rwlock_rdlock* (drd_pthread_intercepts.c:813)
599 ==9466==    by 0x400B6B: thread_func (rwlock_race.c:28)
600 ==9466==    by 0x4C291DF: vg_thread_wrapper (drd_pthread_intercepts.c:186)
601 ==9466==    by 0x4E3403F: start_thread (in /lib64/libpthread-2.8.so)
602 ==9466==    by 0x53250CC: clone (in /lib64/libc-2.8.so)
603 ==9466== Other segment end (thread 2)
604 ==9466==    at 0x4C28B54: pthread_rwlock_unlock* (drd_pthread_intercepts.c:912)
605 ==9466==    by 0x400B84: thread_func (rwlock_race.c:30)
606 ==9466==    by 0x4C291DF: vg_thread_wrapper (drd_pthread_intercepts.c:186)
607 ==9466==    by 0x4E3403F: start_thread (in /lib64/libpthread-2.8.so)
608 ==9466==    by 0x53250CC: clone (in /lib64/libc-2.8.so)
609 ...
610 ]]></programlisting>
611
612 <para>
613 The above report has the following meaning:
614 <itemizedlist>
615   <listitem>
616     <para>
617       The number in the column on the left is the process ID of the
618       process being analyzed by DRD.
619     </para>
620   </listitem>
621   <listitem>
622     <para>
623       The first line ("Thread 3") tells you the thread ID for
624       the thread in which context the data race has been detected.
625     </para>
626   </listitem>
627   <listitem>
628     <para>
629       The next line tells which kind of operation was performed (load or
630       store) and by which thread. On the same line the start address and the
631       number of bytes involved in the conflicting access are also displayed.
632     </para>
633   </listitem>
634   <listitem>
635     <para>
636       Next, the call stack of the conflicting access is displayed. If
637       your program has been compiled with debug information
638       (<option>-g</option>), this call stack will include file names and
639       line numbers. The two
640       bottommost frames in this call stack (<function>clone</function>
641       and <function>start_thread</function>) show how the NPTL starts
642       a thread. The third frame
643       (<function>vg_thread_wrapper</function>) is added by DRD. The
644       fourth frame (<function>thread_func</function>) is the first
645       interesting line because it shows the thread entry point, that
646       is the function that has been passed as the third argument to
647       <function>pthread_create</function>.
648     </para>
649   </listitem>
650   <listitem>
651     <para>
652       Next, the allocation context for the conflicting address is
653       displayed. For dynamically allocated data the allocation call
654       stack is shown. For static variables and stack variables the
655       allocation context is only shown when the option
656       <option>--read-var-info=yes</option> has been
657       specified. Otherwise DRD will print <computeroutput>Allocation
658       context: unknown</computeroutput>.
659     </para>
660   </listitem>
661   <listitem>
662     <para>
663       A conflicting access involves at least two memory accesses. For
664       one of these accesses an exact call stack is displayed, and for
665       the other accesses an approximate call stack is displayed,
666       namely the start and the end of the segments of the other
667       accesses. This information can be interpreted as follows:
668       <orderedlist>
669         <listitem>
670           <para>
671             Start at the bottom of both call stacks, and count the
672             number stack frames with identical function name, file
673             name and line number. In the above example the three
674             bottommost frames are identical
675             (<function>clone</function>,
676             <function>start_thread</function> and
677             <function>vg_thread_wrapper</function>).
678           </para>
679         </listitem>
680         <listitem>
681           <para>
682             The next higher stack frame in both call stacks now tells
683             you between in which source code region the other memory
684             access happened. The above output tells that the other
685             memory access involved in the data race happened between
686             source code lines 28 and 30 in file
687             <computeroutput>rwlock_race.c</computeroutput>.
688           </para>
689         </listitem>
690       </orderedlist>
691     </para>
692   </listitem>
693 </itemizedlist>
694 </para>
695
696 </sect2>
697
698
699 <sect2 id="drd-manual.lock-contention" xreflabel="Lock Contention">
700 <title>Detected Errors: Lock Contention</title>
701
702 <para>
703 Threads must be able to make progress without being blocked for too long by
704 other threads. Sometimes a thread has to wait until a mutex or reader-writer
705 synchronization object is unlocked by another thread. This is called
706 <emphasis>lock contention</emphasis>.
707 </para>
708
709 <para>
710 Lock contention causes delays. Such delays should be as short as
711 possible. The two command line options
712 <literal>--exclusive-threshold=&lt;n&gt;</literal> and
713 <literal>--shared-threshold=&lt;n&gt;</literal> make it possible to
714 detect excessive lock contention by making DRD report any lock that
715 has been held longer than the specified threshold. An example:
716 </para>
717 <programlisting><![CDATA[
718 $ valgrind --tool=drd --exclusive-threshold=10 drd/tests/hold_lock -i 500
719 ...
720 ==10668== Acquired at:
721 ==10668==    at 0x4C267C8: pthread_mutex_lock (drd_pthread_intercepts.c:395)
722 ==10668==    by 0x400D92: main (hold_lock.c:51)
723 ==10668== Lock on mutex 0x7fefffd50 was held during 503 ms (threshold: 10 ms).
724 ==10668==    at 0x4C26ADA: pthread_mutex_unlock (drd_pthread_intercepts.c:441)
725 ==10668==    by 0x400DB5: main (hold_lock.c:55)
726 ...
727 ]]></programlisting>
728
729 <para>
730 The <literal>hold_lock</literal> test program holds a lock as long as
731 specified by the <literal>-i</literal> (interval) argument. The DRD
732 output reports that the lock acquired at line 51 in source file
733 <literal>hold_lock.c</literal> and released at line 55 was held during
734 503 ms, while a threshold of 10 ms was specified to DRD.
735 </para>
736
737 </sect2>
738
739
740 <sect2 id="drd-manual.api-checks" xreflabel="API Checks">
741 <title>Detected Errors: Misuse of the POSIX threads API</title>
742
743 <para>
744   DRD is able to detect and report the following misuses of the POSIX
745   threads API:
746   <itemizedlist>
747     <listitem>
748       <para>
749         Passing the address of one type of synchronization object
750         (e.g. a mutex) to a POSIX API call that expects a pointer to
751         another type of synchronization object (e.g. a condition
752         variable).
753       </para>
754     </listitem>
755     <listitem>
756       <para>
757         Attempts to unlock a mutex that has not been locked.
758       </para>
759     </listitem>
760     <listitem>
761       <para>
762         Attempts to unlock a mutex that was locked by another thread.
763       </para>
764     </listitem>
765     <listitem>
766       <para>
767         Attempts to lock a mutex of type
768         <literal>PTHREAD_MUTEX_NORMAL</literal> or a spinlock
769         recursively.
770       </para>
771     </listitem>
772     <listitem>
773       <para>
774         Destruction or deallocation of a locked mutex.
775       </para>
776     </listitem>
777     <listitem>
778       <para>
779         Sending a signal to a condition variable while no lock is held
780         on the mutex associated with the condition variable.
781       </para>
782     </listitem>
783     <listitem>
784       <para>
785         Calling <function>pthread_cond_wait</function> on a mutex
786         that is not locked, that is locked by another thread or that
787         has been locked recursively.
788       </para>
789     </listitem>
790     <listitem>
791       <para>
792         Associating two different mutexes with a condition variable
793         through <function>pthread_cond_wait</function>.
794       </para>
795     </listitem>
796     <listitem>
797       <para>
798         Destruction or deallocation of a condition variable that is
799         being waited upon.
800       </para>
801     </listitem>
802     <listitem>
803       <para>
804         Destruction or deallocation of a locked reader-writer synchronization
805         object.
806       </para>
807     </listitem>
808     <listitem>
809       <para>
810         Attempts to unlock a reader-writer synchronization object that was not
811         locked by the calling thread.
812       </para>
813     </listitem>
814     <listitem>
815       <para>
816         Attempts to recursively lock a reader-writer synchronization object
817         exclusively.
818       </para>
819     </listitem>
820     <listitem>
821       <para>
822         Attempts to pass the address of a user-defined reader-writer
823         synchronization object to a POSIX threads function.
824       </para>
825     </listitem>
826     <listitem>
827       <para>
828         Attempts to pass the address of a POSIX reader-writer synchronization
829         object to one of the annotations for user-defined reader-writer
830         synchronization objects.
831       </para>
832     </listitem>
833     <listitem>
834       <para>
835         Reinitialization of a mutex, condition variable, reader-writer
836         lock, semaphore or barrier.
837       </para>
838     </listitem>
839     <listitem>
840       <para>
841         Destruction or deallocation of a semaphore or barrier that is
842         being waited upon.
843       </para>
844     </listitem>
845     <listitem>
846       <para>
847         Missing synchronization between barrier wait and barrier destruction.
848       </para>
849     </listitem>
850     <listitem>
851       <para>
852         Exiting a thread without first unlocking the spinlocks, mutexes or
853         reader-writer synchronization objects that were locked by that thread.
854       </para>
855     </listitem>
856     <listitem>
857       <para>
858         Passing an invalid thread ID to <function>pthread_join</function>
859         or <function>pthread_cancel</function>.
860       </para>
861     </listitem>
862   </itemizedlist>
863 </para>
864
865 </sect2>
866
867
868 <sect2 id="drd-manual.clientreqs" xreflabel="Client requests">
869 <title>Client Requests</title>
870
871 <para>
872 Just as for other Valgrind tools it is possible to let a client program
873 interact with the DRD tool through client requests. In addition to the
874 client requests several macros have been defined that allow to use the
875 client requests in a convenient way.
876 </para>
877
878 <para>
879 The interface between client programs and the DRD tool is defined in
880 the header file <literal>&lt;valgrind/drd.h&gt;</literal>. The
881 available macros and client requests are:
882 <itemizedlist>
883   <listitem>
884     <para>
885       The macro <literal>DRD_GET_VALGRIND_THREADID</literal> and the
886       corresponding client
887       request <varname>VG_USERREQ__DRD_GET_VALGRIND_THREAD_ID</varname>.
888       Query the thread ID that has been assigned by the Valgrind core to the
889       thread executing this client request. Valgrind's thread ID's start at
890       one and are recycled in case a thread stops.
891     </para>
892   </listitem>
893   <listitem>
894     <para>
895       The macro <literal>DRD_GET_DRD_THREADID</literal> and the corresponding
896       client request <varname>VG_USERREQ__DRD_GET_DRD_THREAD_ID</varname>.
897       Query the thread ID that has been assigned by DRD to the thread
898       executing this client request. These are the thread ID's reported by DRD
899       in data race reports and in trace messages. DRD's thread ID's start at
900       one and are never recycled.
901     </para>
902   </listitem>
903   <listitem>
904     <para>
905       The macros <literal>DRD_IGNORE_VAR(x)</literal>,
906       <literal>ANNOTATE_TRACE_MEMORY(&amp;x)</literal> and the corresponding
907       client request <varname>VG_USERREQ__DRD_START_SUPPRESSION</varname>. Some
908       applications contain intentional races. There exist e.g. applications
909       where the same value is assigned to a shared variable from two different
910       threads. It may be more convenient to suppress such races than to solve
911       these. This client request allows to suppress such races.
912     </para>
913   </listitem>
914   <listitem>
915     <para>
916       The macro <literal>DRD_STOP_IGNORING_VAR(x)</literal> and the
917       corresponding client request
918       <varname>VG_USERREQ__DRD_FINISH_SUPPRESSION</varname>. Tell DRD
919       to no longer ignore data races for the address range that was suppressed
920       either via the macro <literal>DRD_IGNORE_VAR(x)</literal> or via the
921       client request <varname>VG_USERREQ__DRD_START_SUPPRESSION</varname>.
922     </para>
923   </listitem>
924   <listitem>
925     <para>
926       The macro <literal>DRD_TRACE_VAR(x)</literal>. Trace all load and store
927       activity for the address range starting at <literal>&amp;x</literal> and
928       occupying <literal>sizeof(x)</literal> bytes. When DRD reports a data
929       race on a specified variable, and it's not immediately clear which
930       source code statements triggered the conflicting accesses, it can be
931       very helpful to trace all activity on the offending memory location.
932     </para>
933   </listitem>
934   <listitem>
935     <para>
936       The macro <literal>ANNOTATE_TRACE_MEMORY(&amp;x)</literal>. Trace all
937       load and store activity that touches at least the single byte at the
938       address <literal>&amp;x</literal>.
939     </para>
940   </listitem>
941   <listitem>
942     <para>
943       The client request <varname>VG_USERREQ__DRD_START_TRACE_ADDR</varname>,
944       which allows to trace all load and store activity for the specified
945       address range.
946     </para>
947   </listitem>
948   <listitem>
949     <para>
950       The client
951       request <varname>VG_USERREQ__DRD_STOP_TRACE_ADDR</varname>. Do no longer
952       trace load and store activity for the specified address range.
953     </para>
954   </listitem>
955   <listitem>
956     <para>
957       The macro <literal>ANNOTATE_HAPPENS_BEFORE(addr)</literal> tells DRD to
958       insert a mark. Insert this macro just after an access to the variable at
959       the specified address has been performed.
960     </para>
961   </listitem>
962   <listitem>
963     <para>
964       The macro <literal>ANNOTATE_HAPPENS_AFTER(addr)</literal> tells DRD that
965       the next access to the variable at the specified address should be
966       considered to have happened after the access just before the latest
967       <literal>ANNOTATE_HAPPENS_BEFORE(addr)</literal> annotation that
968       references the same variable. The purpose of these two macros is to
969       tell DRD about the order of inter-thread memory accesses implemented via
970       atomic memory operations.
971     </para>
972   </listitem>
973   <listitem>
974     <para>
975       The macro <literal>ANNOTATE_RWLOCK_CREATE(rwlock)</literal> tells DRD
976       that the object at address <literal>rwlock</literal> is a
977       reader-writer synchronization object that is not a
978       <literal>pthread_rwlock_t</literal> synchronization object.
979     </para>
980   </listitem>
981   <listitem>
982     <para>
983       The macro <literal>ANNOTATE_RWLOCK_DESTROY(rwlock)</literal> tells DRD
984       that the reader-writer synchronization object at
985       address <literal>rwlock</literal> has been destroyed.
986     </para>
987   </listitem>
988   <listitem>
989     <para>
990       The macro <literal>ANNOTATE_WRITERLOCK_ACQUIRED(rwlock)</literal> tells
991       DRD that a writer lock has been acquired on the reader-writer
992       synchronization object at address <literal>rwlock</literal>.
993     </para>
994   </listitem>
995   <listitem>
996     <para>
997       The macro <literal>ANNOTATE_READERLOCK_ACQUIRED(rwlock)</literal> tells
998       DRD that a reader lock has been acquired on the reader-writer
999       synchronization object at address <literal>rwlock</literal>.
1000     </para>
1001   </listitem>
1002   <listitem>
1003     <para>
1004       The macro <literal>ANNOTATE_RWLOCK_ACQUIRED(rwlock, is_w)</literal>
1005       tells DRD that a writer lock (when <literal>is_w != 0</literal>) or that
1006       a reader lock (when <literal>is_w == 0</literal>) has been acquired on
1007       the reader-writer synchronization object at
1008       address <literal>rwlock</literal>.
1009     </para>
1010   </listitem>
1011   <listitem>
1012     <para>
1013       The macro <literal>ANNOTATE_WRITERLOCK_RELEASED(rwlock)</literal> tells
1014       DRD that a writer lock has been released on the reader-writer
1015       synchronization object at address <literal>rwlock</literal>.
1016     </para>
1017   </listitem>
1018   <listitem>
1019     <para>
1020       The macro <literal>ANNOTATE_READERLOCK_RELEASED(rwlock)</literal> tells
1021       DRD that a reader lock has been released on the reader-writer
1022       synchronization object at address <literal>rwlock</literal>.
1023     </para>
1024   </listitem>
1025   <listitem>
1026     <para>
1027       The macro <literal>ANNOTATE_RWLOCK_RELEASED(rwlock, is_w)</literal>
1028       tells DRD that a writer lock (when <literal>is_w != 0</literal>) or that
1029       a reader lock (when <literal>is_w == 0</literal>) has been released on
1030       the reader-writer synchronization object at
1031       address <literal>rwlock</literal>.
1032     </para>
1033   </listitem>
1034   <listitem>
1035     <para>
1036       The macro <literal>ANNOTATE_BENIGN_RACE(addr, descr)</literal> tells
1037       DRD that any races detected on the specified address are benign and
1038       hence should not be reported. The <literal>descr</literal> argument is
1039       ignored but can be used to document why data races
1040       on <literal>addr</literal> are benign.
1041     </para>
1042   </listitem>
1043   <listitem>
1044     <para>
1045       The macro <literal>ANNOTATE_IGNORE_READS_BEGIN</literal> tells
1046       DRD to ignore all memory loads performed by the current thread.
1047     </para>
1048   </listitem>
1049   <listitem>
1050     <para>
1051       The macro <literal>ANNOTATE_IGNORE_READS_END</literal> tells
1052       DRD to stop ignoring the memory loads performed by the current thread.
1053     </para>
1054   </listitem>
1055   <listitem>
1056     <para>
1057       The macro <literal>ANNOTATE_IGNORE_WRITES_BEGIN</literal> tells
1058       DRD to ignore all memory stores performed by the current thread.
1059     </para>
1060   </listitem>
1061   <listitem>
1062     <para>
1063       The macro <literal>ANNOTATE_IGNORE_WRITES_END</literal> tells
1064       DRD to stop ignoring the memory stores performed by the current thread.
1065     </para>
1066   </listitem>
1067   <listitem>
1068     <para>
1069       The macro <literal>ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN</literal> tells
1070       DRD to ignore all memory accesses performed by the current thread.
1071     </para>
1072   </listitem>
1073   <listitem>
1074     <para>
1075       The macro <literal>ANNOTATE_IGNORE_READS_AND_WRITES_END</literal> tells
1076       DRD to stop ignoring the memory accesses performed by the current thread.
1077     </para>
1078   </listitem>
1079   <listitem>
1080     <para>
1081       The macro <literal>ANNOTATE_NEW_MEMORY(addr, size)</literal> tells
1082       DRD that the specified memory range has been allocated by a custom
1083       memory allocator in the client program and that the client program
1084       will start using this memory range.
1085     </para>
1086   </listitem>
1087   <listitem>
1088     <para>
1089       The macro <literal>ANNOTATE_THREAD_NAME(name)</literal> tells DRD to
1090       associate the specified name with the current thread and to include this
1091       name in the error messages printed by DRD.
1092     </para>
1093   </listitem>
1094   <listitem>
1095     <para>
1096       The macros <literal>VALGRIND_MALLOCLIKE_BLOCK</literal> and
1097       <literal>VALGRIND_FREELIKE_BLOCK</literal> from the Valgrind core are
1098       implemented;  they are described in 
1099       <xref linkend="manual-core-adv.clientreq"/>.
1100     </para>
1101   </listitem>
1102 </itemizedlist>
1103 </para>
1104
1105 <para>
1106 For an example of how to use the annotations for user-defined reader-writer
1107 synchronization objects, see
1108 also the source file <literal>drd/tests/annotate_rwlock.c</literal> in the
1109 Valgrind source archive. And an example of how to
1110 use the <literal>ANNOTATE_HAPPENS_BEFORE</literal> and
1111 the <literal>ANNOTATE_HAPPENS_AFTER</literal> annotations can be found
1112 in the source code of the <ulink url="http://code.google.com/chromium/">Chromium</ulink>
1113 web browser.
1114 </para>
1115
1116 <para>
1117 Note: if you compiled Valgrind yourself, the header file
1118 <literal>&lt;valgrind/drd.h&gt;</literal> will have been installed in
1119 the directory <literal>/usr/include</literal> by the command
1120 <literal>make install</literal>. If you obtained Valgrind by
1121 installing it as a package however, you will probably have to install
1122 another package with a name like <literal>valgrind-devel</literal>
1123 before Valgrind's header files are available.
1124 </para>
1125
1126 </sect2>
1127
1128
1129 <sect2 id="drd-manual.gnome" xreflabel="GNOME">
1130 <title>Debugging GNOME Programs</title>
1131
1132 <para>
1133 GNOME applications use the threading primitives provided by the
1134 <computeroutput>glib</computeroutput> and
1135 <computeroutput>gthread</computeroutput> libraries. These libraries
1136 are built on top of POSIX threads, and hence are directly supported by
1137 DRD. Please keep in mind that you have to call
1138 <function>g_thread_init</function> before creating any threads, or
1139 DRD will report several data races on glib functions. See also the
1140 <ulink
1141 url="http://library.gnome.org/devel/glib/stable/glib-Threads.html">GLib
1142 Reference Manual</ulink> for more information about
1143 <function>g_thread_init</function>.
1144 </para>
1145
1146 <para>
1147 One of the many facilities provided by the <literal>glib</literal>
1148 library is a block allocator, called <literal>g_slice</literal>. You
1149 have to disable this block allocator when using DRD by adding the
1150 following to the shell environment variables:
1151 <literal>G_SLICE=always-malloc</literal>. See also the <ulink
1152 url="http://library.gnome.org/devel/glib/stable/glib-Memory-Slices.html">GLib
1153 Reference Manual</ulink> for more information.
1154 </para>
1155
1156 </sect2>
1157
1158
1159 <sect2 id="drd-manual.qt" xreflabel="Qt">
1160 <title>Debugging Qt Programs</title>
1161
1162 <para>
1163 The Qt library is the GUI library used by the KDE project.  Currently
1164 there are two versions of the Qt library in use: Qt3 by KDE 3 and Qt4
1165 by KDE 4. If possible, use Qt4 instead of Qt3. Qt3 is no longer
1166 supported, and there are known problems with multithreading support in
1167 Qt3. As an example, using QString objects in more than one thread will
1168 trigger race reports (this has been confirmed by Trolltech -- see also
1169 Trolltech task <ulink
1170 url="http://trolltech.com/developer/task-tracker/index_html">#206152</ulink>).
1171 </para>
1172
1173 <para>
1174 Qt4 applications are supported by DRD, but only if the
1175 <literal>libqt4-debuginfo</literal> package has been installed. Some
1176 of the synchronization and threading primitives in Qt4 bypass the
1177 POSIX threads library, and DRD can only intercept these if symbol
1178 information for the Qt4 library is available. DRD won't tell you if it
1179 has not been able to load the Qt4 debug information, but a huge number
1180 of data races will be reported on data protected via
1181 <literal>QMutex</literal> objects.
1182 </para>
1183
1184 </sect2>
1185
1186
1187 <sect2 id="drd-manual.boost.thread" xreflabel="Boost.Thread">
1188 <title>Debugging Boost.Thread Programs</title>
1189
1190 <para>
1191 The Boost.Thread library is the threading library included with the
1192 cross-platform Boost Libraries. This threading library is an early
1193 implementation of the upcoming C++0x threading library.
1194 </para>
1195
1196 <para>
1197 Applications that use the Boost.Thread library should run fine under DRD.
1198 </para>
1199
1200 <para>
1201 More information about Boost.Thread can be found here:
1202 <itemizedlist>
1203   <listitem>
1204     <para>
1205       Anthony Williams, <ulink
1206       url="http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html">Boost.Thread</ulink>
1207       Library Documentation, Boost website, 2007.
1208     </para>
1209   </listitem>
1210   <listitem>
1211     <para>
1212       Anthony Williams, <ulink
1213       url="http://www.ddj.com/cpp/211600441">What's New in Boost
1214       Threads?</ulink>, Recent changes to the Boost Thread library,
1215       Dr. Dobbs Magazine, October 2008.
1216     </para>
1217   </listitem>
1218 </itemizedlist>
1219 </para>
1220
1221 </sect2>
1222
1223
1224 <sect2 id="drd-manual.openmp" xreflabel="OpenMP">
1225 <title>Debugging OpenMP Programs</title>
1226
1227 <para>
1228 OpenMP stands for <emphasis>Open Multi-Processing</emphasis>. The OpenMP
1229 standard consists of a set of compiler directives for C, C++ and Fortran
1230 programs that allows a compiler to transform a sequential program into a
1231 parallel program. OpenMP is well suited for HPC applications and allows to
1232 work at a higher level compared to direct use of the POSIX threads API. While
1233 OpenMP ensures that the POSIX API is used correctly, OpenMP programs can still
1234 contain data races. So it definitely makes sense to verify OpenMP programs
1235 with a thread checking tool.
1236 </para>
1237
1238 <para>
1239 DRD supports OpenMP shared-memory programs generated by GCC. GCC
1240 supports OpenMP since version 4.2.0.  GCC's runtime support
1241 for OpenMP programs is provided by a library called
1242 <literal>libgomp</literal>. The synchronization primitives implemented
1243 in this library use Linux' futex system call directly, unless the
1244 library has been configured with the
1245 <literal>--disable-linux-futex</literal> option. DRD only supports
1246 libgomp libraries that have been configured with this option and in
1247 which symbol information is present. For most Linux distributions this
1248 means that you will have to recompile GCC. See also the script
1249 <literal>drd/scripts/download-and-build-gcc</literal> in the
1250 Valgrind source tree for an example of how to compile GCC. You will
1251 also have to make sure that the newly compiled
1252 <literal>libgomp.so</literal> library is loaded when OpenMP programs
1253 are started. This is possible by adding a line similar to the
1254 following to your shell startup script:
1255 </para>
1256 <programlisting><![CDATA[
1257 export LD_LIBRARY_PATH=~/gcc-4.4.0/lib64:~/gcc-4.4.0/lib:
1258 ]]></programlisting>
1259
1260 <para>
1261 As an example, the test OpenMP test program
1262 <literal>drd/tests/omp_matinv</literal> triggers a data race
1263 when the option -r has been specified on the command line. The data
1264 race is triggered by the following code:
1265 </para>
1266 <programlisting><![CDATA[
1267 #pragma omp parallel for private(j)
1268 for (j = 0; j < rows; j++)
1269 {
1270   if (i != j)
1271   {
1272     const elem_t factor = a[j * cols + i];
1273     for (k = 0; k < cols; k++)
1274     {
1275       a[j * cols + k] -= a[i * cols + k] * factor;
1276     }
1277   }
1278 }
1279 ]]></programlisting>
1280
1281 <para>
1282 The above code is racy because the variable <literal>k</literal> has
1283 not been declared private. DRD will print the following error message
1284 for the above code:
1285 </para>
1286 <programlisting><![CDATA[
1287 $ valgrind --tool=drd --check-stack-var=yes --read-var-info=yes drd/tests/omp_matinv 3 -t 2 -r
1288 ...
1289 Conflicting store by thread 1/1 at 0x7fefffbc4 size 4
1290    at 0x4014A0: gj.omp_fn.0 (omp_matinv.c:203)
1291    by 0x401211: gj (omp_matinv.c:159)
1292    by 0x40166A: invert_matrix (omp_matinv.c:238)
1293    by 0x4019B4: main (omp_matinv.c:316)
1294 Location 0x7fefffbc4 is 0 bytes inside local var "k"
1295 declared at omp_matinv.c:160, in frame #0 of thread 1
1296 ...
1297 ]]></programlisting>
1298 <para>
1299 In the above output the function name <function>gj.omp_fn.0</function>
1300 has been generated by GCC from the function name
1301 <function>gj</function>. The allocation context information shows that the
1302 data race has been caused by modifying the variable <literal>k</literal>.
1303 </para>
1304
1305 <para>
1306 Note: for GCC versions before 4.4.0, no allocation context information is
1307 shown. With these GCC versions the most usable information in the above output
1308 is the source file name and the line number where the data race has been
1309 detected (<literal>omp_matinv.c:203</literal>).
1310 </para>
1311
1312 <para>
1313 For more information about OpenMP, see also 
1314 <ulink url="http://openmp.org/">openmp.org</ulink>.
1315 </para>
1316
1317 </sect2>
1318
1319
1320 <sect2 id="drd-manual.cust-mem-alloc" xreflabel="Custom Memory Allocators">
1321 <title>DRD and Custom Memory Allocators</title>
1322
1323 <para>
1324 DRD tracks all memory allocation events that happen via the
1325 standard memory allocation and deallocation functions
1326 (<function>malloc</function>, <function>free</function>,
1327 <function>new</function> and <function>delete</function>), via entry
1328 and exit of stack frames or that have been annotated with Valgrind's
1329 memory pool client requests. DRD uses memory allocation and deallocation
1330 information for two purposes:
1331 <itemizedlist>
1332   <listitem>
1333     <para>
1334       To know where the scope ends of POSIX objects that have not been
1335       destroyed explicitly. It is e.g. not required by the POSIX
1336       threads standard to call
1337       <function>pthread_mutex_destroy</function> before freeing the
1338       memory in which a mutex object resides.
1339     </para>
1340   </listitem>
1341   <listitem>
1342     <para>
1343       To know where the scope of variables ends. If e.g. heap memory
1344       has been used by one thread, that thread frees that memory, and
1345       another thread allocates and starts using that memory, no data
1346       races must be reported for that memory.
1347     </para>
1348   </listitem>
1349 </itemizedlist>
1350 </para>
1351
1352 <para>
1353 It is essential for correct operation of DRD that the tool knows about
1354 memory allocation and deallocation events. When analyzing a client program
1355 with DRD that uses a custom memory allocator, either instrument the custom
1356 memory allocator with the <literal>VALGRIND_MALLOCLIKE_BLOCK</literal>
1357 and <literal>VALGRIND_FREELIKE_BLOCK</literal> macros or disable the
1358 custom memory allocator.
1359 </para>
1360
1361 <para>
1362 As an example, the GNU libstdc++ library can be configured
1363 to use standard memory allocation functions instead of memory pools by
1364 setting the environment variable
1365 <literal>GLIBCXX_FORCE_NEW</literal>. For more information, see also
1366 the <ulink
1367 url="http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt04ch11.html">libstdc++
1368 manual</ulink>.
1369 </para>
1370
1371 </sect2>
1372
1373
1374 <sect2 id="drd-manual.drd-versus-memcheck" xreflabel="DRD Versus Memcheck">
1375 <title>DRD Versus Memcheck</title>
1376
1377 <para>
1378 It is essential for correct operation of DRD that there are no memory
1379 errors such as dangling pointers in the client program. Which means that
1380 it is a good idea to make sure that your program is Memcheck-clean
1381 before you analyze it with DRD. It is possible however that some of
1382 the Memcheck reports are caused by data races. In this case it makes
1383 sense to run DRD before Memcheck.
1384 </para>
1385
1386 <para>
1387 So which tool should be run first? In case both DRD and Memcheck
1388 complain about a program, a possible approach is to run both tools
1389 alternatingly and to fix as many errors as possible after each run of
1390 each tool until none of the two tools prints any more error messages.
1391 </para>
1392
1393 </sect2>
1394
1395
1396 <sect2 id="drd-manual.resource-requirements" xreflabel="Resource Requirements">
1397 <title>Resource Requirements</title>
1398
1399 <para>
1400 The requirements of DRD with regard to heap and stack memory and the
1401 effect on the execution time of client programs are as follows:
1402 <itemizedlist>
1403   <listitem>
1404     <para>
1405       When running a program under DRD with default DRD options,
1406       between 1.1 and 3.6 times more memory will be needed compared to
1407       a native run of the client program. More memory will be needed
1408       if loading debug information has been enabled
1409       (<literal>--read-var-info=yes</literal>).
1410     </para>
1411   </listitem>
1412   <listitem>
1413     <para>
1414       DRD allocates some of its temporary data structures on the stack
1415       of the client program threads. This amount of data is limited to
1416       1 - 2 KB. Make sure that thread stacks are sufficiently large.
1417     </para>
1418   </listitem>
1419   <listitem>
1420     <para>
1421       Most applications will run between 20 and 50 times slower under
1422       DRD than a native single-threaded run. The slowdown will be most
1423       noticeable for applications which perform frequent mutex lock /
1424       unlock operations.
1425     </para>
1426   </listitem>
1427 </itemizedlist>
1428 </para>
1429
1430 </sect2>
1431
1432
1433 <sect2 id="drd-manual.effective-use" xreflabel="Effective Use">
1434 <title>Hints and Tips for Effective Use of DRD</title>
1435
1436 <para>
1437 The following information may be helpful when using DRD:
1438 <itemizedlist>
1439   <listitem>
1440     <para>
1441       Make sure that debug information is present in the executable
1442       being analyzed, such that DRD can print function name and line
1443       number information in stack traces. Most compilers can be told
1444       to include debug information via compiler option
1445       <option>-g</option>.
1446     </para>
1447   </listitem>
1448   <listitem>
1449     <para>
1450       Compile with option <option>-O1</option> instead of
1451       <option>-O0</option>. This will reduce the amount of generated
1452       code, may reduce the amount of debug info and will speed up
1453       DRD's processing of the client program. For more information,
1454       see also <xref linkend="manual-core.started"/>.
1455     </para>
1456   </listitem>
1457   <listitem>
1458     <para>
1459       If DRD reports any errors on libraries that are part of your
1460       Linux distribution like e.g. <literal>libc.so</literal> or
1461       <literal>libstdc++.so</literal>, installing the debug packages
1462       for these libraries will make the output of DRD a lot more
1463       detailed.
1464     </para>
1465   </listitem>
1466   <listitem>
1467     <para>
1468       When using C++, do not send output from more than one thread to
1469       <literal>std::cout</literal>. Doing so would not only
1470       generate multiple data race reports, it could also result in
1471       output from several threads getting mixed up.  Either use
1472       <function>printf</function> or do the following:
1473       <orderedlist>
1474         <listitem>
1475           <para>Derive a class from <literal>std::ostreambuf</literal>
1476           and let that class send output line by line to
1477           <literal>stdout</literal>. This will avoid that individual
1478           lines of text produced by different threads get mixed
1479           up.</para>
1480         </listitem>
1481         <listitem>
1482           <para>Create one instance of <literal>std::ostream</literal>
1483           for each thread. This makes stream formatting settings
1484           thread-local. Pass a per-thread instance of the class
1485           derived from <literal>std::ostreambuf</literal> to the
1486           constructor of each instance. </para>
1487         </listitem>
1488         <listitem>
1489           <para>Let each thread send its output to its own instance of
1490           <literal>std::ostream</literal> instead of
1491           <literal>std::cout</literal>.</para>
1492         </listitem>
1493       </orderedlist>
1494     </para>
1495   </listitem>
1496 </itemizedlist>
1497 </para>
1498
1499 </sect2>
1500
1501
1502 </sect1>
1503
1504
1505 <sect1 id="drd-manual.Pthreads" xreflabel="Pthreads">
1506 <title>Using the POSIX Threads API Effectively</title>
1507
1508 <sect2 id="drd-manual.mutex-types" xreflabel="mutex-types">
1509 <title>Mutex types</title>
1510
1511 <para>
1512 The Single UNIX Specification version two defines the following four
1513 mutex types (see also the documentation of <ulink
1514 url="http://www.opengroup.org/onlinepubs/007908799/xsh/pthread_mutexattr_settype.html"><function>pthread_mutexattr_settype</function></ulink>):
1515 <itemizedlist>
1516   <listitem>
1517     <para>
1518       <emphasis>normal</emphasis>, which means that no error checking
1519       is performed, and that the mutex is non-recursive.
1520     </para>
1521   </listitem>
1522   <listitem>
1523     <para>
1524       <emphasis>error checking</emphasis>, which means that the mutex
1525       is non-recursive and that error checking is performed.
1526     </para>
1527   </listitem>
1528   <listitem>
1529     <para>
1530       <emphasis>recursive</emphasis>, which means that a mutex may be
1531       locked recursively.
1532     </para>
1533   </listitem>
1534   <listitem>
1535     <para>
1536       <emphasis>default</emphasis>, which means that error checking
1537       behavior is undefined, and that the behavior for recursive
1538       locking is also undefined. Or: portable code must neither
1539       trigger error conditions through the Pthreads API nor attempt to
1540       lock a mutex of default type recursively.
1541     </para>
1542   </listitem>
1543 </itemizedlist>
1544 </para>
1545
1546 <para>
1547 In complex applications it is not always clear from beforehand which
1548 mutex will be locked recursively and which mutex will not be locked
1549 recursively. Attempts lock a non-recursive mutex recursively will
1550 result in race conditions that are very hard to find without a thread
1551 checking tool. So either use the error checking mutex type and
1552 consistently check the return value of Pthread API mutex calls, or use
1553 the recursive mutex type.
1554 </para>
1555
1556 </sect2>
1557
1558 <sect2 id="drd-manual.condvar" xreflabel="condition-variables">
1559 <title>Condition variables</title>
1560
1561 <para>
1562 A condition variable allows one thread to wake up one or more other
1563 threads. Condition variables are often used to notify one or more
1564 threads about state changes of shared data. Unfortunately it is very
1565 easy to introduce race conditions by using condition variables as the
1566 only means of state information propagation. A better approach is to
1567 let threads poll for changes of a state variable that is protected by
1568 a mutex, and to use condition variables only as a thread wakeup
1569 mechanism. See also the source file
1570 <computeroutput>drd/tests/monitor_example.cpp</computeroutput> for an
1571 example of how to implement this concept in C++. The monitor concept
1572 used in this example is a well known and very useful concept -- see
1573 also Wikipedia for more information about the <ulink
1574 url="http://en.wikipedia.org/wiki/Monitor_(synchronization)">monitor</ulink>
1575 concept.
1576 </para>
1577
1578 </sect2>
1579
1580 <sect2 id="drd-manual.pctw" xreflabel="pthread_cond_timedwait">
1581 <title><function>pthread_cond_timedwait</function> and timeouts</title>
1582
1583 <para>
1584 Historically the function
1585 <function>pthread_cond_timedwait</function> only allowed the
1586 specification of an absolute timeout, that is a timeout independent of
1587 the time when this function was called. However, almost every call to
1588 this function expresses a relative timeout. This typically happens by
1589 passing the sum of
1590 <computeroutput>clock_gettime(CLOCK_REALTIME)</computeroutput> and a
1591 relative timeout as the third argument. This approach is incorrect
1592 since forward or backward clock adjustments by e.g. ntpd will affect
1593 the timeout. A more reliable approach is as follows:
1594 <itemizedlist>
1595   <listitem>
1596     <para>
1597       When initializing a condition variable through
1598       <function>pthread_cond_init</function>, specify that the timeout of
1599       <function>pthread_cond_timedwait</function> will use the clock
1600       <literal>CLOCK_MONOTONIC</literal> instead of
1601       <literal>CLOCK_REALTIME</literal>. You can do this via
1602       <computeroutput>pthread_condattr_setclock(...,
1603       CLOCK_MONOTONIC)</computeroutput>.
1604     </para>
1605   </listitem>
1606   <listitem>
1607     <para>
1608       When calling <function>pthread_cond_timedwait</function>, pass
1609       the sum of
1610       <computeroutput>clock_gettime(CLOCK_MONOTONIC)</computeroutput>
1611       and a relative timeout as the third argument.
1612     </para>
1613   </listitem>
1614 </itemizedlist>
1615 See also
1616 <computeroutput>drd/tests/monitor_example.cpp</computeroutput> for an
1617 example.
1618 </para>
1619
1620 </sect2>
1621
1622 <sect2 id="drd-manual.naming-threads" xreflabel="naming threads">
1623 <title>Assigning names to threads</title>
1624
1625 <para>
1626 Many applications log information about changes in internal or
1627 external state to a file. When analyzing log files of a multithreaded
1628 application it can be very convenient to know which thread logged
1629 which information. One possible approach is to identify threads in
1630 logging output by including the result of
1631 <function>pthread_self</function> in every log line. However, this approach
1632 has two disadvantages: there is no direct relationship between these
1633 values and the source code and these values can be different in each
1634 run. A better approach is to assign a brief name to each thread and to
1635 include the assigned thread name in each log line. One possible
1636 approach for managing thread names is as follows:
1637 <itemizedlist>
1638   <listitem>
1639     <para>
1640       Allocate a key for the pointer to the thread name through
1641       <function>pthread_key_create</function>.
1642     </para>
1643   </listitem>
1644   <listitem>
1645     <para>
1646       Just after thread creation, set the thread name through
1647       <function>pthread_setspecific</function>.
1648     </para>
1649   </listitem>
1650   <listitem>
1651     <para>
1652       In the code that generates the logging information, query the thread
1653       name by calling <function>pthread_getspecific</function>.
1654     </para>
1655   </listitem>
1656 </itemizedlist>
1657
1658 </para>
1659
1660 </sect2>
1661
1662 </sect1>
1663
1664
1665 <sect1 id="drd-manual.limitations" xreflabel="Limitations">
1666 <title>Limitations</title>
1667
1668 <para>DRD currently has the following limitations:</para>
1669
1670 <itemizedlist>
1671   <listitem>
1672     <para>
1673       DRD has only been tested on Linux and Mac OS X.
1674     </para>
1675   </listitem>
1676   <listitem>
1677     <para>
1678       Of the two POSIX threads implementations for Linux, only the
1679       NPTL (Native POSIX Thread Library) is supported. The older
1680       LinuxThreads library is not supported.
1681     </para>
1682   </listitem>
1683   <listitem>
1684     <para>
1685       DRD, just like Memcheck, will refuse to start on Linux
1686       distributions where all symbol information has been removed from
1687       <filename>ld.so</filename>. This is e.g. the case for the PPC editions
1688       of openSUSE and Gentoo. You will have to install the glibc debuginfo
1689       package on these platforms before you can use DRD. See also openSUSE
1690       bug <ulink url="http://bugzilla.novell.com/show_bug.cgi?id=396197">
1691       396197</ulink> and Gentoo bug <ulink
1692       url="http://bugs.gentoo.org/214065">214065</ulink>.
1693     </para>
1694   </listitem>
1695   <listitem>
1696     <para>
1697       When address tracing is enabled, no information on atomic stores
1698       will be displayed. This functionality is easy to add
1699       however. Please contact the Valgrind authors if you would like
1700       to see this functionality enabled.
1701     </para>
1702   </listitem>
1703   <listitem>
1704     <para>
1705       If you compile the DRD source code yourself, you need GCC 3.0 or
1706       later. GCC 2.95 is not supported.
1707     </para>
1708   </listitem>
1709 </itemizedlist>
1710
1711 </sect1>
1712
1713
1714 <sect1 id="drd-manual.feedback" xreflabel="Feedback">
1715 <title>Feedback</title>
1716
1717 <para>
1718 If you have any comments, suggestions, feedback or bug reports about
1719 DRD, feel free to either post a message on the Valgrind users mailing
1720 list or to file a bug report. See also <ulink
1721 url="&vg-url;">&vg-url;</ulink> for more information.
1722 </para>
1723
1724 </sect1>
1725
1726
1727 </chapter>