Debian Codegraph @

docs/html/hg-manual.html

raw
1 <html>
2 <head>
3 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
4 <title>7. Helgrind: a thread error detector</title>
5 <link rel="stylesheet" type="text/css" href="vg_basic.css">
6 <meta name="generator" content="DocBook XSL Stylesheets Vsnapshot">
7 <link rel="home" href="index.html" title="Valgrind Documentation">
8 <link rel="up" href="manual.html" title="Valgrind User Manual">
9 <link rel="prev" href="cl-manual.html" title="6. Callgrind: a call-graph generating cache and branch prediction profiler">
10 <link rel="next" href="drd-manual.html" title="8. DRD: a thread error detector">
11 </head>
12 <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
13 <div><table class="nav" width="100%" cellspacing="3" cellpadding="3" border="0" summary="Navigation header"><tr>
14 <td width="22px" align="center" valign="middle"><a accesskey="p" href="cl-manual.html"><img src="images/prev.png" width="18" height="21" border="0" alt="Prev"></a></td>
15 <td width="25px" align="center" valign="middle"><a accesskey="u" href="manual.html"><img src="images/up.png" width="21" height="18" border="0" alt="Up"></a></td>
16 <td width="31px" align="center" valign="middle"><a accesskey="h" href="index.html"><img src="images/home.png" width="27" height="20" border="0" alt="Up"></a></td>
17 <th align="center" valign="middle">Valgrind User Manual</th>
18 <td width="22px" align="center" valign="middle"><a accesskey="n" href="drd-manual.html"><img src="images/next.png" width="18" height="21" border="0" alt="Next"></a></td>
19 </tr></table></div>
20 <div class="chapter">
21 <div class="titlepage"><div><div><h1 class="title">
22 <a name="hg-manual"></a>7. Helgrind: a thread error detector</h1></div></div></div>
23 <div class="toc">
24 <p><b>Table of Contents</b></p>
25 <dl class="toc">
26 <dt><span class="sect1"><a href="hg-manual.html#hg-manual.overview">7.1. Overview</a></span></dt>
27 <dt><span class="sect1"><a href="hg-manual.html#hg-manual.api-checks">7.2. Detected errors: Misuses of the POSIX pthreads API</a></span></dt>
28 <dt><span class="sect1"><a href="hg-manual.html#hg-manual.lock-orders">7.3. Detected errors: Inconsistent Lock Orderings</a></span></dt>
29 <dt><span class="sect1"><a href="hg-manual.html#hg-manual.data-races">7.4. Detected errors: Data Races</a></span></dt>
30 <dd><dl>
31 <dt><span class="sect2"><a href="hg-manual.html#hg-manual.data-races.example">7.4.1. A Simple Data Race</a></span></dt>
32 <dt><span class="sect2"><a href="hg-manual.html#hg-manual.data-races.algorithm">7.4.2. Helgrind's Race Detection Algorithm</a></span></dt>
33 <dt><span class="sect2"><a href="hg-manual.html#hg-manual.data-races.errmsgs">7.4.3. Interpreting Race Error Messages</a></span></dt>
34 </dl></dd>
35 <dt><span class="sect1"><a href="hg-manual.html#hg-manual.effective-use">7.5. Hints and Tips for Effective Use of Helgrind</a></span></dt>
36 <dt><span class="sect1"><a href="hg-manual.html#hg-manual.options">7.6. Helgrind Command-line Options</a></span></dt>
37 <dt><span class="sect1"><a href="hg-manual.html#hg-manual.monitor-commands">7.7. Helgrind Monitor Commands</a></span></dt>
38 <dt><span class="sect1"><a href="hg-manual.html#hg-manual.client-requests">7.8. Helgrind Client Requests</a></span></dt>
39 <dt><span class="sect1"><a href="hg-manual.html#hg-manual.todolist">7.9. A To-Do List for Helgrind</a></span></dt>
40 </dl>
41 </div>
42 <p>To use this tool, you must specify
43 <code class="option">--tool=helgrind</code> on the Valgrind
44 command line.</p>
45 <div class="sect1">
46 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
47 <a name="hg-manual.overview"></a>7.1. Overview</h2></div></div></div>
48 <p>Helgrind is a Valgrind tool for detecting synchronisation errors
49 in C, C++ and Fortran programs that use the POSIX pthreads
50 threading primitives.</p>
51 <p>The main abstractions in POSIX pthreads are: a set of threads
52 sharing a common address space, thread creation, thread joining,
53 thread exit, mutexes (locks), condition variables (inter-thread event
54 notifications), reader-writer locks, spinlocks, semaphores and
55 barriers.</p>
56 <p>Helgrind can detect three classes of errors, which are discussed
57 in detail in the next three sections:</p>
58 <div class="orderedlist"><ol class="orderedlist" type="1">
59 <li class="listitem"><p><a class="link" href="hg-manual.html#hg-manual.api-checks" title="7.2. Detected errors: Misuses of the POSIX pthreads API">
60 Misuses of the POSIX pthreads API.</a></p></li>
61 <li class="listitem"><p><a class="link" href="hg-manual.html#hg-manual.lock-orders" title="7.3. Detected errors: Inconsistent Lock Orderings">
62 Potential deadlocks arising from lock
63 ordering problems.</a></p></li>
64 <li class="listitem"><p><a class="link" href="hg-manual.html#hg-manual.data-races" title="7.4. Detected errors: Data Races">
65 Data races -- accessing memory without adequate locking
66 or synchronisation</a>.
67 </p></li>
68 </ol></div>
69 <p>Problems like these often result in unreproducible,
70 timing-dependent crashes, deadlocks and other misbehaviour, and
71 can be difficult to find by other means.</p>
72 <p>Helgrind is aware of all the pthread abstractions and tracks
73 their effects as accurately as it can. On x86 and amd64 platforms, it
74 understands and partially handles implicit locking arising from the
75 use of the LOCK instruction prefix. On PowerPC/POWER and ARM
76 platforms, it partially handles implicit locking arising from
77 load-linked and store-conditional instruction pairs.
78 </p>
79 <p>Helgrind works best when your application uses only the POSIX
80 pthreads API. However, if you want to use custom threading
81 primitives, you can describe their behaviour to Helgrind using the
82 <code class="varname">ANNOTATE_*</code> macros defined
83 in <code class="varname">helgrind.h</code>.</p>
84 <p>Helgrind also provides <a class="xref" href="manual-core.html#manual-core.xtree" title="2.10. Execution Trees">Execution Trees</a> memory
85 profiling using the command line
86 option <code class="computeroutput">--xtree-memory</code> and the monitor command
87 <code class="computeroutput">xtmemory</code>.</p>
88 <p>Following those is a section containing
89 <a class="link" href="hg-manual.html#hg-manual.effective-use" title="7.5. Hints and Tips for Effective Use of Helgrind">
90 hints and tips on how to get the best out of Helgrind.</a>
91 </p>
92 <p>Then there is a
93 <a class="link" href="hg-manual.html#hg-manual.options" title="7.6. Helgrind Command-line Options">summary of command-line
94 options.</a>
95 </p>
96 <p>Finally, there is
97 <a class="link" href="hg-manual.html#hg-manual.todolist" title="7.9. A To-Do List for Helgrind">a brief summary of areas in which Helgrind
98 could be improved.</a>
99 </p>
100 </div>
101 <div class="sect1">
102 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
103 <a name="hg-manual.api-checks"></a>7.2. Detected errors: Misuses of the POSIX pthreads API</h2></div></div></div>
104 <p>Helgrind intercepts calls to many POSIX pthreads functions, and
105 is therefore able to report on various common problems. Although
106 these are unglamourous errors, their presence can lead to undefined
107 program behaviour and hard-to-find bugs later on. The detected errors
108 are:</p>
109 <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
110 <li class="listitem"><p>unlocking an invalid mutex</p></li>
111 <li class="listitem"><p>unlocking a not-locked mutex</p></li>
112 <li class="listitem"><p>unlocking a mutex held by a different
113 thread</p></li>
114 <li class="listitem"><p>destroying an invalid or a locked mutex</p></li>
115 <li class="listitem"><p>recursively locking a non-recursive mutex</p></li>
116 <li class="listitem"><p>deallocation of memory that contains a
117 locked mutex</p></li>
118 <li class="listitem"><p>passing mutex arguments to functions expecting
119 reader-writer lock arguments, and vice
120 versa</p></li>
121 <li class="listitem"><p>when a POSIX pthread function fails with an
122 error code that must be handled</p></li>
123 <li class="listitem"><p>when a thread exits whilst still holding locked
124 locks</p></li>
125 <li class="listitem"><p>calling <code class="function">pthread_cond_wait</code>
126 with a not-locked mutex, an invalid mutex,
127 or one locked by a different
128 thread</p></li>
129 <li class="listitem"><p>inconsistent bindings between condition
130 variables and their associated mutexes</p></li>
131 <li class="listitem"><p>invalid or duplicate initialisation of a pthread
132 barrier</p></li>
133 <li class="listitem"><p>initialisation of a pthread barrier on which threads
134 are still waiting</p></li>
135 <li class="listitem"><p>destruction of a pthread barrier object which was
136 never initialised, or on which threads are still
137 waiting</p></li>
138 <li class="listitem"><p>waiting on an uninitialised pthread
139 barrier</p></li>
140 <li class="listitem"><p>for all of the pthreads functions that Helgrind
141 intercepts, an error is reported, along with a stack
142 trace, if the system threading library routine returns
143 an error code, even if Helgrind itself detected no
144 error</p></li>
145 </ul></div>
146 <p>Checks pertaining to the validity of mutexes are generally also
147 performed for reader-writer locks.</p>
148 <p>Signalling or broadcasting a condition variable when the
149 associated mutex is unlocked is not strictly an error. The resulting
150 thread scheduling may be unpredictable if the mutex is not held.
151 The option <code class="computeroutput">--check-cond-signal-mutex=yes|no</code>
152 turns on checking for this situation. This kind of error is
153 categorised as 'dubious'. The check is not turned on by default
154 because some standard C and C++ libraries use condition
155 signals/broadcasts with the associated mutex unlocked.</p>
156 <p>Various kinds of this-can't-possibly-happen events are also
157 reported. These usually indicate bugs in the system threading
158 library.</p>
159 <p>Reported errors always contain a primary stack trace indicating
160 where the error was detected. They may also contain auxiliary stack
161 traces giving additional information. In particular, most errors
162 relating to mutexes will also tell you where that mutex first came to
163 Helgrind's attention (the "<code class="computeroutput">was first observed
164 at</code>" part), so you have a chance of figuring out which
165 mutex it is referring to. For example:</p>
166 <pre class="programlisting">
167 Thread #1 unlocked a not-locked lock at 0x7FEFFFA90
168 at 0x4C2408D: pthread_mutex_unlock (hg_intercepts.c:492)
169 by 0x40073A: nearly_main (tc09_bad_unlock.c:27)
170 by 0x40079B: main (tc09_bad_unlock.c:50)
171 Lock at 0x7FEFFFA90 was first observed
172 at 0x4C25D01: pthread_mutex_init (hg_intercepts.c:326)
173 by 0x40071F: nearly_main (tc09_bad_unlock.c:23)
174 by 0x40079B: main (tc09_bad_unlock.c:50)
175 </pre>
176 <p>Helgrind has a way of summarising thread identities, as
177 you see here with the text "<code class="computeroutput">Thread
178 #1</code>". This is so that it can speak about threads and
179 sets of threads without overwhelming you with details. See
180 <a class="link" href="hg-manual.html#hg-manual.data-races.errmsgs" title="7.4.3. Interpreting Race Error Messages">below</a>
181 for more information on interpreting error messages.</p>
182 </div>
183 <div class="sect1">
184 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
185 <a name="hg-manual.lock-orders"></a>7.3. Detected errors: Inconsistent Lock Orderings</h2></div></div></div>
186 <p>In this section, and in general, to "acquire" a lock simply
187 means to lock that lock, and to "release" a lock means to unlock
188 it.</p>
189 <p>Helgrind monitors the order in which threads acquire locks.
190 This allows it to detect potential deadlocks which could arise from
191 the formation of cycles of locks. Detecting such inconsistencies is
192 useful because, whilst actual deadlocks are fairly obvious, potential
193 deadlocks may never be discovered during testing and could later lead
194 to hard-to-diagnose in-service failures.</p>
195 <p>The simplest example of such a problem is as
196 follows.</p>
197 <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
198 <li class="listitem"><p>Imagine some shared resource R, which, for whatever
199 reason, is guarded by two locks, L1 and L2, which must both be held
200 when R is accessed.</p></li>
201 <li class="listitem"><p>Suppose a thread acquires L1, then L2, and proceeds
202 to access R. The implication of this is that all threads in the
203 program must acquire the two locks in the order first L1 then L2.
204 Not doing so risks deadlock.</p></li>
205 <li class="listitem"><p>The deadlock could happen if two threads -- call them
206 T1 and T2 -- both want to access R. Suppose T1 acquires L1 first,
207 and T2 acquires L2 first. Then T1 tries to acquire L2, and T2 tries
208 to acquire L1, but those locks are both already held. So T1 and T2
209 become deadlocked.</p></li>
210 </ul></div>
211 <p>Helgrind builds a directed graph indicating the order in which
212 locks have been acquired in the past. When a thread acquires a new
213 lock, the graph is updated, and then checked to see if it now contains
214 a cycle. The presence of a cycle indicates a potential deadlock involving
215 the locks in the cycle.</p>
216 <p>In general, Helgrind will choose two locks involved in the cycle
217 and show you how their acquisition ordering has become inconsistent.
218 It does this by showing the program points that first defined the
219 ordering, and the program points which later violated it. Here is a
220 simple example involving just two locks:</p>
221 <pre class="programlisting">
222 Thread #1: lock order "0x7FF0006D0 before 0x7FF0006A0" violated
223
224 Observed (incorrect) order is: acquisition of lock at 0x7FF0006A0
225 at 0x4C2BC62: pthread_mutex_lock (hg_intercepts.c:494)
226 by 0x400825: main (tc13_laog1.c:23)
227
228 followed by a later acquisition of lock at 0x7FF0006D0
229 at 0x4C2BC62: pthread_mutex_lock (hg_intercepts.c:494)
230 by 0x400853: main (tc13_laog1.c:24)
231
232 Required order was established by acquisition of lock at 0x7FF0006D0
233 at 0x4C2BC62: pthread_mutex_lock (hg_intercepts.c:494)
234 by 0x40076D: main (tc13_laog1.c:17)
235
236 followed by a later acquisition of lock at 0x7FF0006A0
237 at 0x4C2BC62: pthread_mutex_lock (hg_intercepts.c:494)
238 by 0x40079B: main (tc13_laog1.c:18)
239 </pre>
240 <p>When there are more than two locks in the cycle, the error is
241 equally serious. However, at present Helgrind does not show the locks
242 involved, sometimes because that information is not available, but
243 also so as to avoid flooding you with information. For example, a
244 naive implementation of the famous Dining Philosophers problem
245 involves a cycle of five locks
246 (see <code class="computeroutput">helgrind/tests/tc14_laog_dinphils.c</code>).
247 In this case Helgrind has detected that all 5 philosophers could
248 simultaneously pick up their left fork and then deadlock whilst
249 waiting to pick up their right forks.</p>
250 <pre class="programlisting">
251 Thread #6: lock order "0x80499A0 before 0x8049A00" violated
252
253 Observed (incorrect) order is: acquisition of lock at 0x8049A00
254 at 0x40085BC: pthread_mutex_lock (hg_intercepts.c:495)
255 by 0x80485B4: dine (tc14_laog_dinphils.c:18)
256 by 0x400BDA4: mythread_wrapper (hg_intercepts.c:219)
257 by 0x39B924: start_thread (pthread_create.c:297)
258 by 0x2F107D: clone (clone.S:130)
259
260 followed by a later acquisition of lock at 0x80499A0
261 at 0x40085BC: pthread_mutex_lock (hg_intercepts.c:495)
262 by 0x80485CD: dine (tc14_laog_dinphils.c:19)
263 by 0x400BDA4: mythread_wrapper (hg_intercepts.c:219)
264 by 0x39B924: start_thread (pthread_create.c:297)
265 by 0x2F107D: clone (clone.S:130)
266 </pre>
267 </div>
268 <div class="sect1">
269 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
270 <a name="hg-manual.data-races"></a>7.4. Detected errors: Data Races</h2></div></div></div>
271 <p>A data race happens, or could happen, when two threads access a
272 shared memory location without using suitable locks or other
273 synchronisation to ensure single-threaded access. Such missing
274 locking can cause obscure timing dependent bugs. Ensuring programs
275 are race-free is one of the central difficulties of threaded
276 programming.</p>
277 <p>Reliably detecting races is a difficult problem, and most
278 of Helgrind's internals are devoted to dealing with it.
279 We begin with a simple example.</p>
280 <div class="sect2">
281 <div class="titlepage"><div><div><h3 class="title">
282 <a name="hg-manual.data-races.example"></a>7.4.1. A Simple Data Race</h3></div></div></div>
283 <p>About the simplest possible example of a race is as follows. In
284 this program, it is impossible to know what the value
285 of <code class="computeroutput">var</code> is at the end of the program.
286 Is it 2 ? Or 1 ?</p>
287 <pre class="programlisting">
288 #include &lt;pthread.h&gt;
289
290 int var = 0;
291
292 void* child_fn ( void* arg ) {
293 var++; /* Unprotected relative to parent */ /* this is line 6 */
294 return NULL;
295 }
296
297 int main ( void ) {
298 pthread_t child;
299 pthread_create(&amp;child, NULL, child_fn, NULL);
300 var++; /* Unprotected relative to child */ /* this is line 13 */
301 pthread_join(child, NULL);
302 return 0;
303 }
304 </pre>
305 <p>The problem is there is nothing to
306 stop <code class="varname">var</code> being updated simultaneously
307 by both threads. A correct program would
308 protect <code class="varname">var</code> with a lock of type
309 <code class="function">pthread_mutex_t</code>, which is acquired
310 before each access and released afterwards. Helgrind's output for
311 this program is:</p>
312 <pre class="programlisting">
313 Thread #1 is the program's root thread
314
315 Thread #2 was created
316 at 0x511C08E: clone (in /lib64/libc-2.8.so)
317 by 0x4E333A4: do_clone (in /lib64/libpthread-2.8.so)
318 by 0x4E33A30: pthread_create@@GLIBC_2.2.5 (in /lib64/libpthread-2.8.so)
319 by 0x4C299D4: pthread_create@* (hg_intercepts.c:214)
320 by 0x400605: main (simple_race.c:12)
321
322 Possible data race during read of size 4 at 0x601038 by thread #1
323 Locks held: none
324 at 0x400606: main (simple_race.c:13)
325
326 This conflicts with a previous write of size 4 by thread #2
327 Locks held: none
328 at 0x4005DC: child_fn (simple_race.c:6)
329 by 0x4C29AFF: mythread_wrapper (hg_intercepts.c:194)
330 by 0x4E3403F: start_thread (in /lib64/libpthread-2.8.so)
331 by 0x511C0CC: clone (in /lib64/libc-2.8.so)
332
333 Location 0x601038 is 0 bytes inside global var "var"
334 declared at simple_race.c:3
335 </pre>
336 <p>This is quite a lot of detail for an apparently simple error.
337 The last clause is the main error message. It says there is a race as
338 a result of a read of size 4 (bytes), at 0x601038, which is the
339 address of <code class="computeroutput">var</code>, happening in
340 function <code class="computeroutput">main</code> at line 13 in the
341 program.</p>
342 <p>Two important parts of the message are:</p>
343 <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
344 <li class="listitem">
345 <p>Helgrind shows two stack traces for the error, not one. By
346 definition, a race involves two different threads accessing the
347 same location in such a way that the result depends on the relative
348 speeds of the two threads.</p>
349 <p>
350 The first stack trace follows the text "<code class="computeroutput">Possible
351 data race during read of size 4 ...</code>" and the
352 second trace follows the text "<code class="computeroutput">This conflicts with
353 a previous write of size 4 ...</code>". Helgrind is
354 usually able to show both accesses involved in a race. At least
355 one of these will be a write (since two concurrent, unsynchronised
356 reads are harmless), and they will of course be from different
357 threads.</p>
358 <p>By examining your program at the two locations, you should be
359 able to get at least some idea of what the root cause of the
360 problem is. For each location, Helgrind shows the set of locks
361 held at the time of the access. This often makes it clear which
362 thread, if any, failed to take a required lock. In this example
363 neither thread holds a lock during the access.</p>
364 </li>
365 <li class="listitem">
366 <p>For races which occur on global or stack variables, Helgrind
367 tries to identify the name and defining point of the variable.
368 Hence the text "<code class="computeroutput">Location 0x601038 is 0 bytes inside
369 global var "var" declared at simple_race.c:3</code>".</p>
370 <p>Showing names of stack and global variables carries no
371 run-time overhead once Helgrind has your program up and running.
372 However, it does require Helgrind to spend considerable extra time
373 and memory at program startup to read the relevant debug info.
374 Hence this facility is disabled by default. To enable it, you need
375 to give the <code class="varname">--read-var-info=yes</code> option to
376 Helgrind.</p>
377 </li>
378 </ul></div>
379 <p>The following section explains Helgrind's race detection
380 algorithm in more detail.</p>
381 </div>
382 <div class="sect2">
383 <div class="titlepage"><div><div><h3 class="title">
384 <a name="hg-manual.data-races.algorithm"></a>7.4.2. Helgrind's Race Detection Algorithm</h3></div></div></div>
385 <p>Most programmers think about threaded programming in terms of
386 the basic functionality provided by the threading library (POSIX
387 Pthreads): thread creation, thread joining, locks, condition
388 variables, semaphores and barriers.</p>
389 <p>The effect of using these functions is to impose
390 constraints upon the order in which memory accesses can
391 happen. This implied ordering is generally known as the
392 "happens-before relation". Once you understand the happens-before
393 relation, it is easy to see how Helgrind finds races in your code.
394 Fortunately, the happens-before relation is itself easy to understand,
395 and is by itself a useful tool for reasoning about the behaviour of
396 parallel programs. We now introduce it using a simple example.</p>
397 <p>Consider first the following buggy program:</p>
398 <pre class="programlisting">
399 Parent thread: Child thread:
400
401 int var;
402
403 // create child thread
404 pthread_create(...)
405 var = 20; var = 10;
406 exit
407
408 // wait for child
409 pthread_join(...)
410 printf("%d\n", var);
411 </pre>
412 <p>The parent thread creates a child. Both then write different
413 values to some variable <code class="computeroutput">var</code>, and the
414 parent then waits for the child to exit.</p>
415 <p>What is the value of <code class="computeroutput">var</code> at the
416 end of the program, 10 or 20? We don't know. The program is
417 considered buggy (it has a race) because the final value
418 of <code class="computeroutput">var</code> depends on the relative rates
419 of progress of the parent and child threads. If the parent is fast
420 and the child is slow, then the child's assignment may happen later,
421 so the final value will be 10; and vice versa if the child is faster
422 than the parent.</p>
423 <p>The relative rates of progress of parent vs child is not something
424 the programmer can control, and will often change from run to run.
425 It depends on factors such as the load on the machine, what else is
426 running, the kernel's scheduling strategy, and many other factors.</p>
427 <p>The obvious fix is to use a lock to
428 protect <code class="computeroutput">var</code>. It is however
429 instructive to consider a somewhat more abstract solution, which is to
430 send a message from one thread to the other:</p>
431 <pre class="programlisting">
432 Parent thread: Child thread:
433
434 int var;
435
436 // create child thread
437 pthread_create(...)
438 var = 20;
439 // send message to child
440 // wait for message to arrive
441 var = 10;
442 exit
443
444 // wait for child
445 pthread_join(...)
446 printf("%d\n", var);
447 </pre>
448 <p>Now the program reliably prints "10", regardless of the speed of
449 the threads. Why? Because the child's assignment cannot happen until
450 after it receives the message. And the message is not sent until
451 after the parent's assignment is done.</p>
452 <p>The message transmission creates a "happens-before" dependency
453 between the two assignments: <code class="computeroutput">var = 20;</code>
454 must now happen-before <code class="computeroutput">var = 10;</code>.
455 And so there is no longer a race
456 on <code class="computeroutput">var</code>.
457 </p>
458 <p>Note that it's not significant that the parent sends a message
459 to the child. Sending a message from the child (after its assignment)
460 to the parent (before its assignment) would also fix the problem, causing
461 the program to reliably print "20".</p>
462 <p>Helgrind's algorithm is (conceptually) very simple. It monitors all
463 accesses to memory locations. If a location -- in this example,
464 <code class="computeroutput">var</code>,
465 is accessed by two different threads, Helgrind checks to see if the
466 two accesses are ordered by the happens-before relation. If so,
467 that's fine; if not, it reports a race.</p>
468 <p>It is important to understand that the happens-before relation
469 creates only a partial ordering, not a total ordering. An example of
470 a total ordering is comparison of numbers: for any two numbers
471 <code class="computeroutput">x</code> and
472 <code class="computeroutput">y</code>, either
473 <code class="computeroutput">x</code> is less than, equal to, or greater
474 than
475 <code class="computeroutput">y</code>. A partial ordering is like a
476 total ordering, but it can also express the concept that two elements
477 are neither equal, less or greater, but merely unordered with respect
478 to each other.</p>
479 <p>In the fixed example above, we say that
480 <code class="computeroutput">var = 20;</code> "happens-before"
481 <code class="computeroutput">var = 10;</code>. But in the original
482 version, they are unordered: we cannot say that either happens-before
483 the other.</p>
484 <p>What does it mean to say that two accesses from different
485 threads are ordered by the happens-before relation? It means that
486 there is some chain of inter-thread synchronisation operations which
487 cause those accesses to happen in a particular order, irrespective of
488 the actual rates of progress of the individual threads. This is a
489 required property for a reliable threaded program, which is why
490 Helgrind checks for it.</p>
491 <p>The happens-before relations created by standard threading
492 primitives are as follows:</p>
493 <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
494 <li class="listitem"><p>When a mutex is unlocked by thread T1 and later (or
495 immediately) locked by thread T2, then the memory accesses in T1
496 prior to the unlock must happen-before those in T2 after it acquires
497 the lock.</p></li>
498 <li class="listitem"><p>The same idea applies to reader-writer locks,
499 although with some complication so as to allow correct handling of
500 reads vs writes.</p></li>
501 <li class="listitem"><p>When a condition variable (CV) is signalled on by
502 thread T1 and some other thread T2 is thereby released from a wait
503 on the same CV, then the memory accesses in T1 prior to the
504 signalling must happen-before those in T2 after it returns from the
505 wait. If no thread was waiting on the CV then there is no
506 effect.</p></li>
507 <li class="listitem"><p>If instead T1 broadcasts on a CV, then all of the
508 waiting threads, rather than just one of them, acquire a
509 happens-before dependency on the broadcasting thread at the point it
510 did the broadcast.</p></li>
511 <li class="listitem"><p>A thread T2 that continues after completing sem_wait
512 on a semaphore that thread T1 posts on, acquires a happens-before
513 dependence on the posting thread, a bit like dependencies caused
514 mutex unlock-lock pairs. However, since a semaphore can be posted
515 on many times, it is unspecified from which of the post calls the
516 wait call gets its happens-before dependency.</p></li>
517 <li class="listitem"><p>For a group of threads T1 .. Tn which arrive at a
518 barrier and then move on, each thread after the call has a
519 happens-after dependency from all threads before the
520 barrier.</p></li>
521 <li class="listitem"><p>A newly-created child thread acquires an initial
522 happens-after dependency on the point where its parent created it.
523 That is, all memory accesses performed by the parent prior to
524 creating the child are regarded as happening-before all the accesses
525 of the child.</p></li>
526 <li class="listitem"><p>Similarly, when an exiting thread is reaped via a
527 call to <code class="function">pthread_join</code>, once the call returns, the
528 reaping thread acquires a happens-after dependency relative to all memory
529 accesses made by the exiting thread.</p></li>
530 </ul></div>
531 <p>In summary: Helgrind intercepts the above listed events, and builds a
532 directed acyclic graph represented the collective happens-before
533 dependencies. It also monitors all memory accesses.</p>
534 <p>If a location is accessed by two different threads, but Helgrind
535 cannot find any path through the happens-before graph from one access
536 to the other, then it reports a race.</p>
537 <p>There are a couple of caveats:</p>
538 <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
539 <li class="listitem"><p>Helgrind doesn't check for a race in the case where
540 both accesses are reads. That would be silly, since concurrent
541 reads are harmless.</p></li>
542 <li class="listitem"><p>Two accesses are considered to be ordered by the
543 happens-before dependency even through arbitrarily long chains of
544 synchronisation events. For example, if T1 accesses some location
545 L, and then <code class="function">pthread_cond_signals</code> T2, which later
546 <code class="function">pthread_cond_signals</code> T3, which then accesses L, then
547 a suitable happens-before dependency exists between the first and second
548 accesses, even though it involves two different inter-thread
549 synchronisation events.</p></li>
550 </ul></div>
551 </div>
552 <div class="sect2">
553 <div class="titlepage"><div><div><h3 class="title">
554 <a name="hg-manual.data-races.errmsgs"></a>7.4.3. Interpreting Race Error Messages</h3></div></div></div>
555 <p>Helgrind's race detection algorithm collects a lot of
556 information, and tries to present it in a helpful way when a race is
557 detected. Here's an example:</p>
558 <pre class="programlisting">
559 Thread #2 was created
560 at 0x511C08E: clone (in /lib64/libc-2.8.so)
561 by 0x4E333A4: do_clone (in /lib64/libpthread-2.8.so)
562 by 0x4E33A30: pthread_create@@GLIBC_2.2.5 (in /lib64/libpthread-2.8.so)
563 by 0x4C299D4: pthread_create@* (hg_intercepts.c:214)
564 by 0x4008F2: main (tc21_pthonce.c:86)
565
566 Thread #3 was created
567 at 0x511C08E: clone (in /lib64/libc-2.8.so)
568 by 0x4E333A4: do_clone (in /lib64/libpthread-2.8.so)
569 by 0x4E33A30: pthread_create@@GLIBC_2.2.5 (in /lib64/libpthread-2.8.so)
570 by 0x4C299D4: pthread_create@* (hg_intercepts.c:214)
571 by 0x4008F2: main (tc21_pthonce.c:86)
572
573 Possible data race during read of size 4 at 0x601070 by thread #3
574 Locks held: none
575 at 0x40087A: child (tc21_pthonce.c:74)
576 by 0x4C29AFF: mythread_wrapper (hg_intercepts.c:194)
577 by 0x4E3403F: start_thread (in /lib64/libpthread-2.8.so)
578 by 0x511C0CC: clone (in /lib64/libc-2.8.so)
579
580 This conflicts with a previous write of size 4 by thread #2
581 Locks held: none
582 at 0x400883: child (tc21_pthonce.c:74)
583 by 0x4C29AFF: mythread_wrapper (hg_intercepts.c:194)
584 by 0x4E3403F: start_thread (in /lib64/libpthread-2.8.so)
585 by 0x511C0CC: clone (in /lib64/libc-2.8.so)
586
587 Location 0x601070 is 0 bytes inside local var "unprotected2"
588 declared at tc21_pthonce.c:51, in frame #0 of thread 3
589 </pre>
590 <p>Helgrind first announces the creation points of any threads
591 referenced in the error message. This is so it can speak concisely
592 about threads without repeatedly printing their creation point call
593 stacks. Each thread is only ever announced once, the first time it
594 appears in any Helgrind error message.</p>
595 <p>The main error message begins at the text
596 "<code class="computeroutput">Possible data race during read</code>". At
597 the start is information you would expect to see -- address and size
598 of the racing access, whether a read or a write, and the call stack at
599 the point it was detected.</p>
600 <p>A second call stack is presented starting at the text
601 "<code class="computeroutput">This conflicts with a previous
602 write</code>". This shows a previous access which also
603 accessed the stated address, and which is believed to be racing
604 against the access in the first call stack. Note that this second call
605 stack is limited to a maximum of <code class="varname">--history-backtrace-size</code>
606 entries with a default value of 8 to limit the memory usage.</p>
607 <p>Finally, Helgrind may attempt to give a description of the
608 raced-on address in source level terms. In this example, it
609 identifies it as a local variable, shows its name, declaration point,
610 and in which frame (of the first call stack) it lives. Note that this
611 information is only shown when <code class="varname">--read-var-info=yes</code>
612 is specified on the command line. That's because reading the DWARF3
613 debug information in enough detail to capture variable type and
614 location information makes Helgrind much slower at startup, and also
615 requires considerable amounts of memory, for large programs.
616 </p>
617 <p>Once you have your two call stacks, how do you find the root
618 cause of the race?</p>
619 <p>The first thing to do is examine the source locations referred
620 to by each call stack. They should both show an access to the same
621 location, or variable.</p>
622 <p>Now figure out how how that location should have been made
623 thread-safe:</p>
624 <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
625 <li class="listitem"><p>Perhaps the location was intended to be protected by
626 a mutex? If so, you need to lock and unlock the mutex at both
627 access points, even if one of the accesses is reported to be a read.
628 Did you perhaps forget the locking at one or other of the accesses?
629 To help you do this, Helgrind shows the set of locks held by each
630 threads at the time they accessed the raced-on location.</p></li>
631 <li class="listitem">
632 <p>Alternatively, perhaps you intended to use a some
633 other scheme to make it safe, such as signalling on a condition
634 variable. In all such cases, try to find a synchronisation event
635 (or a chain thereof) which separates the earlier-observed access (as
636 shown in the second call stack) from the later-observed access (as
637 shown in the first call stack). In other words, try to find
638 evidence that the earlier access "happens-before" the later access.
639 See the previous subsection for an explanation of the happens-before
640 relation.</p>
641 <p>
642 The fact that Helgrind is reporting a race means it did not observe
643 any happens-before relation between the two accesses. If
644 Helgrind is working correctly, it should also be the case that you
645 also cannot find any such relation, even on detailed inspection
646 of the source code. Hopefully, though, your inspection of the code
647 will show where the missing synchronisation operation(s) should have
648 been.</p>
649 </li>
650 </ul></div>
651 </div>
652 </div>
653 <div class="sect1">
654 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
655 <a name="hg-manual.effective-use"></a>7.5. Hints and Tips for Effective Use of Helgrind</h2></div></div></div>
656 <p>Helgrind can be very helpful in finding and resolving
657 threading-related problems. Like all sophisticated tools, it is most
658 effective when you understand how to play to its strengths.</p>
659 <p>Helgrind will be less effective when you merely throw an
660 existing threaded program at it and try to make sense of any reported
661 errors. It will be more effective if you design threaded programs
662 from the start in a way that helps Helgrind verify correctness. The
663 same is true for finding memory errors with Memcheck, but applies more
664 here, because thread checking is a harder problem. Consequently it is
665 much easier to write a correct program for which Helgrind falsely
666 reports (threading) errors than it is to write a correct program for
667 which Memcheck falsely reports (memory) errors.</p>
668 <p>With that in mind, here are some tips, listed most important first,
669 for getting reliable results and avoiding false errors. The first two
670 are critical. Any violations of them will swamp you with huge numbers
671 of false data-race errors.</p>
672 <div class="orderedlist"><ol class="orderedlist" type="1">
673 <li class="listitem">
674 <p>Make sure your application, and all the libraries it uses,
675 use the POSIX threading primitives. Helgrind needs to be able to
676 see all events pertaining to thread creation, exit, locking and
677 other synchronisation events. To do so it intercepts many POSIX
678 pthreads functions.</p>
679 <p>Do not roll your own threading primitives (mutexes, etc)
680 from combinations of the Linux futex syscall, atomic counters, etc.
681 These throw Helgrind's internal what's-going-on models
682 way off course and will give bogus results.</p>
683 <p>Also, do not reimplement existing POSIX abstractions using
684 other POSIX abstractions. For example, don't build your own
685 semaphore routines or reader-writer locks from POSIX mutexes and
686 condition variables. Instead use POSIX reader-writer locks and
687 semaphores directly, since Helgrind supports them directly.</p>
688 <p>Helgrind directly supports the following POSIX threading
689 abstractions: mutexes, reader-writer locks, condition variables
690 (but see below), semaphores and barriers. Currently spinlocks
691 are not supported, although they could be in future.</p>
692 <p>At the time of writing, the following popular Linux packages
693 are known to implement their own threading primitives:</p>
694 <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
695 <li class="listitem"><p>Qt version 4.X. Qt 3.X is harmless in that it
696 only uses POSIX pthreads primitives. Unfortunately Qt 4.X
697 has its own implementation of mutexes (QMutex) and thread reaping.
698 Helgrind 3.4.x contains direct support
699 for Qt 4.X threading, which is experimental but is believed to
700 work fairly well. A side effect of supporting Qt 4 directly is
701 that Helgrind can be used to debug KDE4 applications. As this
702 is an experimental feature, we would particularly appreciate
703 feedback from folks who have used Helgrind to successfully debug
704 Qt 4 and/or KDE4 applications.</p></li>
705 <li class="listitem">
706 <p>Runtime support library for GNU OpenMP (part of
707 GCC), at least for GCC versions 4.2 and 4.3. The GNU OpenMP runtime
708 library (<code class="filename">libgomp.so</code>) constructs its own
709 synchronisation primitives using combinations of atomic memory
710 instructions and the futex syscall, which causes total chaos since in
711 Helgrind since it cannot "see" those.</p>
712 <p>Fortunately, this can be solved using a configuration-time
713 option (for GCC). Rebuild GCC from source, and configure using
714 <code class="varname">--disable-linux-futex</code>.
715 This makes libgomp.so use the standard
716 POSIX threading primitives instead. Note that this was tested
717 using GCC 4.2.3 and has not been re-tested using more recent GCC
718 versions. We would appreciate hearing about any successes or
719 failures with more recent versions.</p>
720 </li>
721 </ul></div>
722 <p>If you must implement your own threading primitives, there
723 are a set of client request macros
724 in <code class="computeroutput">helgrind.h</code> to help you
725 describe your primitives to Helgrind. You should be able to
726 mark up mutexes, condition variables, etc, without difficulty.
727 </p>
728 <p>
729 It is also possible to mark up the effects of thread-safe
730 reference counting using the
731 <code class="computeroutput">ANNOTATE_HAPPENS_BEFORE</code>,
732 <code class="computeroutput">ANNOTATE_HAPPENS_AFTER</code> and
733 <code class="computeroutput">ANNOTATE_HAPPENS_BEFORE_FORGET_ALL</code>,
734 macros. Thread-safe reference counting using an atomically
735 incremented/decremented refcount variable causes Helgrind
736 problems because a one-to-zero transition of the reference count
737 means the accessing thread has exclusive ownership of the
738 associated resource (normally, a C++ object) and can therefore
739 access it (normally, to run its destructor) without locking.
740 Helgrind doesn't understand this, and markup is essential to
741 avoid false positives.
742 </p>
743 <p>
744 Here are recommended guidelines for marking up thread safe
745 reference counting in C++. You only need to mark up your
746 release methods -- the ones which decrement the reference count.
747 Given a class like this:
748 </p>
749 <pre class="programlisting">
750 class MyClass {
751 unsigned int mRefCount;
752
753 void Release ( void ) {
754 unsigned int newCount = atomic_decrement(&amp;mRefCount);
755 if (newCount == 0) {
756 delete this;
757 }
758 }
759 }
760 </pre>
761 <p>
762 the release method should be marked up as follows:
763 </p>
764 <pre class="programlisting">
765 void Release ( void ) {
766 unsigned int newCount = atomic_decrement(&amp;mRefCount);
767 if (newCount == 0) {
768 ANNOTATE_HAPPENS_AFTER(&amp;mRefCount);
769 ANNOTATE_HAPPENS_BEFORE_FORGET_ALL(&amp;mRefCount);
770 delete this;
771 } else {
772 ANNOTATE_HAPPENS_BEFORE(&amp;mRefCount);
773 }
774 }
775 </pre>
776 <p>
777 There are a number of complex, mostly-theoretical objections to
778 this scheme. From a theoretical standpoint it appears to be
779 impossible to devise a markup scheme which is completely correct
780 in the sense of guaranteeing to remove all false races. The
781 proposed scheme however works well in practice.
782 </p>
783 </li>
784 <li class="listitem">
785 <p>Avoid memory recycling. If you can't avoid it, you must use
786 tell Helgrind what is going on via the
787 <code class="function">VALGRIND_HG_CLEAN_MEMORY</code> client request (in
788 <code class="computeroutput">helgrind.h</code>).</p>
789 <p>Helgrind is aware of standard heap memory allocation and
790 deallocation that occurs via
791 <code class="function">malloc</code>/<code class="function">free</code>/<code class="function">new</code>/<code class="function">delete</code>
792 and from entry and exit of stack frames. In particular, when memory is
793 deallocated via <code class="function">free</code>, <code class="function">delete</code>,
794 or function exit, Helgrind considers that memory clean, so when it is
795 eventually reallocated, its history is irrelevant.</p>
796 <p>However, it is common practice to implement memory recycling
797 schemes. In these, memory to be freed is not handed to
798 <code class="function">free</code>/<code class="function">delete</code>, but instead put
799 into a pool of free buffers to be handed out again as required. The
800 problem is that Helgrind has no
801 way to know that such memory is logically no longer in use, and
802 its history is irrelevant. Hence you must make that explicit,
803 using the <code class="function">VALGRIND_HG_CLEAN_MEMORY</code> client request
804 to specify the relevant address ranges. It's easiest to put these
805 requests into the pool manager code, and use them either when memory is
806 returned to the pool, or is allocated from it.</p>
807 </li>
808 <li class="listitem">
809 <p>Avoid POSIX condition variables. If you can, use POSIX
810 semaphores (<code class="function">sem_t</code>, <code class="function">sem_post</code>,
811 <code class="function">sem_wait</code>) to do inter-thread event signalling.
812 Semaphores with an initial value of zero are particularly useful for
813 this.</p>
814 <p>Helgrind only partially correctly handles POSIX condition
815 variables. This is because Helgrind can see inter-thread
816 dependencies between a <code class="function">pthread_cond_wait</code> call and a
817 <code class="function">pthread_cond_signal</code>/<code class="function">pthread_cond_broadcast</code>
818 call only if the waiting thread actually gets to the rendezvous first
819 (so that it actually calls
820 <code class="function">pthread_cond_wait</code>). It can't see dependencies
821 between the threads if the signaller arrives first. In the latter case,
822 POSIX guidelines imply that the associated boolean condition still
823 provides an inter-thread synchronisation event, but one which is
824 invisible to Helgrind.</p>
825 <p>The result of Helgrind missing some inter-thread
826 synchronisation events is to cause it to report false positives.
827 </p>
828 <p>The root cause of this synchronisation lossage is
829 particularly hard to understand, so an example is helpful. It was
830 discussed at length by Arndt Muehlenfeld ("Runtime Race Detection
831 in Multi-Threaded Programs", Dissertation, TU Graz, Austria). The
832 canonical POSIX-recommended usage scheme for condition variables
833 is as follows:</p>
834 <pre class="programlisting">
835 b is a Boolean condition, which is False most of the time
836 cv is a condition variable
837 mx is its associated mutex
838
839 Signaller: Waiter:
840
841 lock(mx) lock(mx)
842 b = True while (b == False)
843 signal(cv) wait(cv,mx)
844 unlock(mx) unlock(mx)
845 </pre>
846 <p>Assume <code class="computeroutput">b</code> is False most of
847 the time. If the waiter arrives at the rendezvous first, it
848 enters its while-loop, waits for the signaller to signal, and
849 eventually proceeds. Helgrind sees the signal, notes the
850 dependency, and all is well.</p>
851 <p>If the signaller arrives
852 first, <code class="computeroutput">b</code> is set to true, and the
853 signal disappears into nowhere. When the waiter later arrives, it
854 does not enter its while-loop and simply carries on. But even in
855 this case, the waiter code following the while-loop cannot execute
856 until the signaller sets <code class="computeroutput">b</code> to
857 True. Hence there is still the same inter-thread dependency, but
858 this time it is through an arbitrary in-memory condition, and
859 Helgrind cannot see it.</p>
860 <p>By comparison, Helgrind's detection of inter-thread
861 dependencies caused by semaphore operations is believed to be
862 exactly correct.</p>
863 <p>As far as I know, a solution to this problem that does not
864 require source-level annotation of condition-variable wait loops
865 is beyond the current state of the art.</p>
866 </li>
867 <li class="listitem"><p>Make sure you are using a supported Linux distribution. At
868 present, Helgrind only properly supports glibc-2.3 or later. This
869 in turn means we only support glibc's NPTL threading
870 implementation. The old LinuxThreads implementation is not
871 supported.</p></li>
872 <li class="listitem"><p>If your application is using thread local variables,
873 helgrind might report false positive race conditions on these
874 variables, despite being very probably race free. On Linux, you can
875 use <code class="option">--sim-hints=deactivate-pthread-stack-cache-via-hack</code>
876 to avoid such false positive error messages
877 (see <a class="xref" href="manual-core.html#opt.sim-hints">--sim-hints</a>).
878 </p></li>
879 <li class="listitem">
880 <p>Round up all finished threads using
881 <code class="function">pthread_join</code>. Avoid
882 detaching threads: don't create threads in the detached state, and
883 don't call <code class="function">pthread_detach</code> on existing threads.</p>
884 <p>Using <code class="function">pthread_join</code> to round up finished
885 threads provides a clear synchronisation point that both Helgrind and
886 programmers can see. If you don't call
887 <code class="function">pthread_join</code> on a thread, Helgrind has no way to
888 know when it finishes, relative to any
889 significant synchronisation points for other threads in the program. So
890 it assumes that the thread lingers indefinitely and can potentially
891 interfere indefinitely with the memory state of the program. It
892 has every right to assume that -- after all, it might really be
893 the case that, for scheduling reasons, the exiting thread did run
894 very slowly in the last stages of its life.</p>
895 </li>
896 <li class="listitem">
897 <p>Perform thread debugging (with Helgrind) and memory
898 debugging (with Memcheck) together.</p>
899 <p>Helgrind tracks the state of memory in detail, and memory
900 management bugs in the application are liable to cause confusion.
901 In extreme cases, applications which do many invalid reads and
902 writes (particularly to freed memory) have been known to crash
903 Helgrind. So, ideally, you should make your application
904 Memcheck-clean before using Helgrind.</p>
905 <p>It may be impossible to make your application Memcheck-clean
906 unless you first remove threading bugs. In particular, it may be
907 difficult to remove all reads and writes to freed memory in
908 multithreaded C++ destructor sequences at program termination.
909 So, ideally, you should make your application Helgrind-clean
910 before using Memcheck.</p>
911 <p>Since this circularity is obviously unresolvable, at least
912 bear in mind that Memcheck and Helgrind are to some extent
913 complementary, and you may need to use them together.</p>
914 </li>
915 <li class="listitem">
916 <p>POSIX requires that implementations of standard I/O
917 (<code class="function">printf</code>, <code class="function">fprintf</code>,
918 <code class="function">fwrite</code>, <code class="function">fread</code>, etc) are thread
919 safe. Unfortunately GNU libc implements this by using internal locking
920 primitives that Helgrind is unable to intercept. Consequently Helgrind
921 generates many false race reports when you use these functions.</p>
922 <p>Helgrind attempts to hide these errors using the standard
923 Valgrind error-suppression mechanism. So, at least for simple
924 test cases, you don't see any. Nevertheless, some may slip
925 through. Just something to be aware of.</p>
926 </li>
927 <li class="listitem">
928 <p>Helgrind's error checks do not work properly inside the
929 system threading library itself
930 (<code class="computeroutput">libpthread.so</code>), and it usually
931 observes large numbers of (false) errors in there. Valgrind's
932 suppression system then filters these out, so you should not see
933 them.</p>
934 <p>If you see any race errors reported
935 where <code class="computeroutput">libpthread.so</code> or
936 <code class="computeroutput">ld.so</code> is the object associated
937 with the innermost stack frame, please file a bug report at
938 <a class="ulink" href="http://www.valgrind.org/" target="_top">http://www.valgrind.org/</a>.
939 </p>
940 </li>
941 </ol></div>
942 </div>
943 <div class="sect1">
944 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
945 <a name="hg-manual.options"></a>7.6. Helgrind Command-line Options</h2></div></div></div>
946 <p>The following end-user options are available:</p>
947 <div class="variablelist">
948 <a name="hg.opts.list"></a><dl class="variablelist">
949 <dt>
950 <a name="opt.free-is-write"></a><span class="term">
951 <code class="option">--free-is-write=no|yes
952 [default: no] </code>
953 </span>
954 </dt>
955 <dd>
956 <p>When enabled (not the default), Helgrind treats freeing of
957 heap memory as if the memory was written immediately before
958 the free. This exposes races where memory is referenced by
959 one thread, and freed by another, but there is no observable
960 synchronisation event to ensure that the reference happens
961 before the free.
962 </p>
963 <p>This functionality is new in Valgrind 3.7.0, and is
964 regarded as experimental. It is not enabled by default
965 because its interaction with custom memory allocators is not
966 well understood at present. User feedback is welcomed.
967 </p>
968 </dd>
969 <dt>
970 <a name="opt.track-lockorders"></a><span class="term">
971 <code class="option">--track-lockorders=no|yes
972 [default: yes] </code>
973 </span>
974 </dt>
975 <dd><p>When enabled (the default), Helgrind performs lock order
976 consistency checking. For some buggy programs, the large number
977 of lock order errors reported can become annoying, particularly
978 if you're only interested in race errors. You may therefore find
979 it helpful to disable lock order checking.</p></dd>
980 <dt>
981 <a name="opt.history-level"></a><span class="term">
982 <code class="option">--history-level=none|approx|full
983 [default: full] </code>
984 </span>
985 </dt>
986 <dd>
987 <p><code class="option">--history-level=full</code> (the default) causes Helgrind
988 collects enough information about "old" accesses that it can produce two
989 stack traces in a race report -- both the stack trace for the current
990 access, and the trace for the older, conflicting access. To limit memory
991 usage, "old" accesses stack traces are limited to a maximum
992 of <code class="varname">--history-backtrace-size</code> entries (default 8) or
993 to <code class="option">--num-callers</code> value if this value is smaller.</p>
994 <p>Collecting such information is expensive in both speed and
995 memory, particularly for programs that do many inter-thread
996 synchronisation events (locks, unlocks, etc). Without such
997 information, it is more difficult to track down the root
998 causes of races. Nonetheless, you may not need it in
999 situations where you just want to check for the presence or
1000 absence of races, for example, when doing regression testing
1001 of a previously race-free program.</p>
1002 <p><code class="option">--history-level=none</code> is the opposite
1003 extreme. It causes Helgrind not to collect any information
1004 about previous accesses. This can be dramatically faster
1005 than <code class="option">--history-level=full</code>.</p>
1006 <p><code class="option">--history-level=approx</code> provides a
1007 compromise between these two extremes. It causes Helgrind to
1008 show a full trace for the later access, and approximate
1009 information regarding the earlier access. This approximate
1010 information consists of two stacks, and the earlier access is
1011 guaranteed to have occurred somewhere between program points
1012 denoted by the two stacks. This is not as useful as showing
1013 the exact stack for the previous access
1014 (as <code class="option">--history-level=full</code> does), but it is
1015 better than nothing, and it is almost as fast as
1016 <code class="option">--history-level=none</code>.</p>
1017 </dd>
1018 <dt>
1019 <a name="opt.history-backtrace-size"></a><span class="term">
1020 <code class="option">--history-backtrace-size=&lt;number&gt;
1021 [default: 8] </code>
1022 </span>
1023 </dt>
1024 <dd><p>When <code class="varname">--history-level=full</code> is selected,
1025 <code class="varname">--history-backtrace-size=number</code> indicates how many
1026 entries to record in "old" accesses stack traces.</p></dd>
1027 <dt>
1028 <a name="opt.delta-stacktrace"></a><span class="term">
1029 <code class="option">--delta-stacktrace=no|yes
1030 [default: yes on linux amd64/x86] </code>
1031 </span>
1032 </dt>
1033 <dd>
1034 <p>This flag only has any effect
1035 at <code class="option">--history-level=full</code>.</p>
1036 <p><code class="option">--delta-stacktrace</code> configures the way Helgrind
1037 captures the stacktraces for the
1038 option <code class="option">--history-level=full</code>. Such a stacktrace is
1039 typically needed each time a new piece of memory is read or written in a
1040 basic block of instructions. </p>
1041 <p><code class="option">--delta-stacktrace=no</code> causes
1042 Helgrind to compute a full history stacktrace from the unwind info
1043 each time a stacktrace is needed.</p>
1044 <p><code class="option">--delta-stacktrace=yes</code> indicates to Helgrind to
1045 derive a new stacktrace from the previous stacktrace, as long as there
1046 was no call instruction, no return instruction, or any other instruction
1047 changing the call stack since the previous stacktrace was captured. If
1048 no such instruction was executed, the new stacktrace can be derived from
1049 the previous stacktrace by just changing the top frame to the current
1050 program counter. This option can speed up Helgrind by 25% when
1051 using <code class="option">--history-level=full</code>. </p>
1052 <p>The following aspects have to be considered when
1053 using <code class="option">--delta-stacktrace=yes</code> :
1054 </p>
1055 <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
1056 <li class="listitem"><p>In some cases (for example in a function
1057 prologue), the valgrind unwinder might not properly unwind
1058 the stack, due to some limitations and/or due to wrong
1059 unwind info. When using --delta-stacktrace=yes, the wrong
1060 stack trace captured in the function prologue will be kept
1061 till the next call or return.
1062 </p></li>
1063 <li class="listitem"><p>On the other hand, --delta-stacktrace=yes
1064 sometimes helps to obtain a correct stacktrace, for
1065 example when the unwind info allows a correct stacktrace
1066 to be done in the beginning of the sequence, but not later
1067 on in the instruction sequence.</p></li>
1068 <li class="listitem"><p>Determining which instructions are changing
1069 the callstack is partially based on platform dependent
1070 heuristics, which have to be tuned/validated specifically
1071 for the platform. Also, unwinding in a function prologue
1072 must be good enough to allow using
1073 --delta-stacktrace=yes. Currently, the option
1074 --delta-stacktrace=yes has been reasonably validated only
1075 on linux x86 32 bits and linux amd64 64 bits. For more
1076 details about how to validate --delta-stacktrace=yes, see
1077 debug option --hg-sanity-flags and the function
1078 check_cached_rcec_ok in libhb_core.c.</p></li>
1079 </ul></div>
1080 <p>
1081 </p>
1082 </dd>
1083 <dt>
1084 <a name="opt.conflict-cache-size"></a><span class="term">
1085 <code class="option">--conflict-cache-size=N
1086 [default: 1000000] </code>
1087 </span>
1088 </dt>
1089 <dd>
1090 <p>This flag only has any effect
1091 at <code class="option">--history-level=full</code>.</p>
1092 <p>Information about "old" conflicting accesses is stored in
1093 a cache of limited size, with LRU-style management. This is
1094 necessary because it isn't practical to store a stack trace
1095 for every single memory access made by the program.
1096 Historical information on not recently accessed locations is
1097 periodically discarded, to free up space in the cache.</p>
1098 <p>This option controls the size of the cache, in terms of the
1099 number of different memory addresses for which
1100 conflicting access information is stored. If you find that
1101 Helgrind is showing race errors with only one stack instead of
1102 the expected two stacks, try increasing this value.</p>
1103 <p>The minimum value is 10,000 and the maximum is 30,000,000
1104 (thirty times the default value). Increasing the value by 1
1105 increases Helgrind's memory requirement by very roughly 100
1106 bytes, so the maximum value will easily eat up three extra
1107 gigabytes or so of memory.</p>
1108 </dd>
1109 <dt>
1110 <a name="opt.check-stack-refs"></a><span class="term">
1111 <code class="option">--check-stack-refs=no|yes
1112 [default: yes] </code>
1113 </span>
1114 </dt>
1115 <dd><p>
1116 By default Helgrind checks all data memory accesses made by your
1117 program. This flag enables you to skip checking for accesses
1118 to thread stacks (local variables). This can improve
1119 performance, but comes at the cost of missing races on
1120 stack-allocated data.
1121 </p></dd>
1122 <dt>
1123 <a name="opt.ignore-thread-creation"></a><span class="term">
1124 <code class="option">--ignore-thread-creation=&lt;yes|no&gt;
1125 [default: no]</code>
1126 </span>
1127 </dt>
1128 <dd>
1129 <p>
1130 Controls whether all activities during thread creation should be
1131 ignored. By default enabled only on Solaris.
1132 Solaris provides higher throughput, parallelism and scalability than
1133 other operating systems, at the cost of more fine-grained locking
1134 activity. This means for example that when a thread is created under
1135 glibc, just one big lock is used for all thread setup. Solaris libc
1136 uses several fine-grained locks and the creator thread resumes its
1137 activities as soon as possible, leaving for example stack and TLS setup
1138 sequence to the created thread.
1139 This situation confuses Helgrind as it assumes there is some false
1140 ordering in place between creator and created thread; and therefore many
1141 types of race conditions in the application would not be reported.
1142 To prevent such false ordering, this command line option is set to
1143 <code class="computeroutput">yes</code> by default on Solaris.
1144 All activity (loads, stores, client requests) is therefore ignored
1145 during:</p>
1146 <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
1147 <li class="listitem"><p>
1148 pthread_create() call in the creator thread
1149 </p></li>
1150 <li class="listitem"><p>
1151 thread creation phase (stack and TLS setup) in the created thread
1152 </p></li>
1153 </ul></div>
1154 <p>
1155 Also new memory allocated during thread creation is untracked,
1156 that is race reporting is suppressed there. DRD does the same thing
1157 implicitly. This is necessary because Solaris libc caches many objects
1158 and reuses them for different threads and that confuses
1159 Helgrind.</p>
1160 </dd>
1161 </dl>
1162 </div>
1163 </div>
1164 <div class="sect1">
1165 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
1166 <a name="hg-manual.monitor-commands"></a>7.7. Helgrind Monitor Commands</h2></div></div></div>
1167 <p>The Helgrind tool provides monitor commands handled by Valgrind's built-in
1168 gdbserver (see <a class="xref" href="manual-core-adv.html#manual-core-adv.gdbserver-commandhandling" title="3.2.5. Monitor command handling by the Valgrind gdbserver">Monitor command handling by the Valgrind gdbserver</a>).
1169 Valgrind python code provides GDB front end commands giving an easier usage of
1170 the helgrind monitor commands (see
1171 <a class="xref" href="manual-core-adv.html#manual-core-adv.gdbserver-gdbmonitorfrontend" title="3.2.6. GDB front end commands for Valgrind gdbserver monitor commands">GDB front end commands for Valgrind gdbserver monitor commands</a>). To launch an
1172 helgrind monitor command via its GDB front end command, instead of prefixing
1173 the command with "monitor", you must use the GDB <code class="varname">helgrind</code>
1174 command (or the shorter aliases <code class="varname">hg</code>). Using the helgrind
1175 GDB front end command provide a more flexible usage, such as evaluation of
1176 address and length arguments by GDB. In GDB, you can use <code class="varname">help
1177 helgrind</code> to get help about the helgrind front end monitor commands
1178 and you can use <code class="varname">apropos helgrind</code> to get all the commands
1179 mentionning the word "helgrind" in their name or on-line help. </p>
1180 <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
1181 <li class="listitem">
1182 <p><code class="varname">info locks [lock_addr]</code> shows the list of locks
1183 and their status. If <code class="varname">lock_addr</code> is given, only shows
1184 the lock located at this address. </p>
1185 <p>
1186 In the following example, helgrind knows about one lock. This
1187 lock is located at the guest address <code class="varname">ga
1188 0x8049a20</code>. The lock kind is <code class="varname">rdwr</code>
1189 indicating a reader-writer lock. Other possible lock kinds
1190 are <code class="varname">nonRec</code> (simple mutex, non recursive)
1191 and <code class="varname">mbRec</code> (simple mutex, possibly recursive).
1192 The lock kind is then followed by the list of threads helding the
1193 lock. In the below example, <code class="varname">R1:thread #6 tid 3</code>
1194 indicates that the helgrind thread #6 has acquired (once, as the
1195 counter following the letter R is one) the lock in read mode. The
1196 helgrind thread nr is incremented for each started thread. The
1197 presence of 'tid 3' indicates that the thread #6 is has not exited
1198 yet and is the valgrind tid 3. If a thread has terminated, then
1199 this is indicated with 'tid (exited)'.
1200 </p>
1201 <pre class="programlisting">
1202 (gdb) monitor info locks
1203 Lock ga 0x8049a20 {
1204 kind rdwr
1205 { R1:thread #6 tid 3 }
1206 }
1207 (gdb)
1208 </pre>
1209 <p> If you give the option <code class="varname">--read-var-info=yes</code>,
1210 then more information will be provided about the lock location, such as
1211 the global variable or the heap block that contains the lock:
1212 </p>
1213 <pre class="programlisting">
1214 Lock ga 0x8049a20 {
1215 Location 0x8049a20 is 0 bytes inside global var "s_rwlock"
1216 declared at rwlock_race.c:17
1217 kind rdwr
1218 { R1:thread #3 tid 3 }
1219 }
1220 </pre>
1221 <p>The GDB equivalent helgrind front end command <code class="varname">helgrind info locks
1222 [ADDR]</code> accept any address expression for its first ADDR
1223 argument.
1224 </p>
1225 </li>
1226 <li class="listitem">
1227 <p><code class="varname">accesshistory &lt;addr&gt; [&lt;len&gt;]</code>
1228 shows the access history recorded for &lt;len&gt; (default 1) bytes
1229 starting at &lt;addr&gt;. For each recorded access that overlaps
1230 with the given range, <code class="varname">accesshistory</code> shows the operation
1231 type (read or write), the address and size read or written, the helgrind
1232 thread nr/valgrind tid number that did the operation and the locks held
1233 by the thread at the time of the operation.
1234 The oldest access is shown first, the most recent access is shown last.
1235 </p>
1236 <p>
1237 In the following example, we see first a recorded write of 4 bytes by
1238 thread #7 that has modified the given 2 bytes range.
1239 The second recorded write is the most recent recorded write : thread #9
1240 modified the same 2 bytes as part of a 4 bytes write operation.
1241 The list of locks held by each thread at the time of the write operation
1242 are also shown.
1243 </p>
1244 <pre class="programlisting">
1245 (gdb) monitor accesshistory 0x8049D8A 2
1246 write of size 4 at 0x8049D88 by thread #7 tid 3
1247 ==6319== Locks held: 2, at address 0x8049D8C (and 1 that can't be shown)
1248 ==6319== at 0x804865F: child_fn1 (locked_vs_unlocked2.c:29)
1249 ==6319== by 0x400AE61: mythread_wrapper (hg_intercepts.c:234)
1250 ==6319== by 0x39B924: start_thread (pthread_create.c:297)
1251 ==6319== by 0x2F107D: clone (clone.S:130)
1252
1253 write of size 4 at 0x8049D88 by thread #9 tid 2
1254 ==6319== Locks held: 2, at addresses 0x8049DA4 0x8049DD4
1255 ==6319== at 0x804877B: child_fn2 (locked_vs_unlocked2.c:45)
1256 ==6319== by 0x400AE61: mythread_wrapper (hg_intercepts.c:234)
1257 ==6319== by 0x39B924: start_thread (pthread_create.c:297)
1258 ==6319== by 0x2F107D: clone (clone.S:130)
1259
1260 </pre>
1261 <p>The GDB equivalent helgrind front end command <code class="varname">helgrind
1262 accesshistory ADDR [LEN]</code> accept any address expression for its
1263 first ADDR argument. The second optional argument is any integer
1264 expression. Note that these 2 arguments must be separated by a space,
1265 like in the following example:
1266 </p>
1267 <pre class="programlisting">
1268 (gdb) hg accesshistory &amp;mx sizeof(mx)
1269 read of size 4 at 0x1130A8 by thread #2 tid (exited)
1270 ==302== Locks held: none
1271 ==302== at 0x1094AC: child8 (tc19_shadowmem.c:37)
1272 ==302== by 0x10A0DF: steer (tc19_shadowmem.c:288)
1273 ==302== by 0x48448A3: mythread_wrapper (hg_intercepts.c:406)
1274 ==302== by 0x4879EA6: start_thread (pthread_create.c:477)
1275 ==302== by 0x4990A2E: clone (clone.S:95)
1276 </pre>
1277 </li>
1278 <li class="listitem"><p><code class="varname">xtmemory [&lt;filename&gt; default xtmemory.kcg.%p.%n]</code>
1279 requests Helgrind tool to produce an xtree heap memory report.
1280 See <a class="xref" href="manual-core.html#manual-core.xtree" title="2.10. Execution Trees">Execution Trees</a> for
1281 a detailed explanation about execution trees. </p></li>
1282 </ul></div>
1283 </div>
1284 <div class="sect1">
1285 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
1286 <a name="hg-manual.client-requests"></a>7.8. Helgrind Client Requests</h2></div></div></div>
1287 <p>The following client requests are defined in
1288 <code class="filename">helgrind.h</code>. See that file for exact details of their
1289 arguments.</p>
1290 <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
1291 <li class="listitem">
1292 <p><code class="function">VALGRIND_HG_CLEAN_MEMORY</code></p>
1293 <p>This makes Helgrind forget everything it knows about a
1294 specified memory range. This is particularly useful for memory
1295 allocators that wish to recycle memory.</p>
1296 </li>
1297 <li class="listitem"><p><code class="function">ANNOTATE_HAPPENS_BEFORE</code></p></li>
1298 <li class="listitem"><p><code class="function">ANNOTATE_HAPPENS_AFTER</code></p></li>
1299 <li class="listitem"><p><code class="function">ANNOTATE_NEW_MEMORY</code></p></li>
1300 <li class="listitem"><p><code class="function">ANNOTATE_RWLOCK_CREATE</code></p></li>
1301 <li class="listitem"><p><code class="function">ANNOTATE_RWLOCK_DESTROY</code></p></li>
1302 <li class="listitem"><p><code class="function">ANNOTATE_RWLOCK_ACQUIRED</code></p></li>
1303 <li class="listitem">
1304 <p><code class="function">ANNOTATE_RWLOCK_RELEASED</code></p>
1305 <p>These are used to describe to Helgrind, the behaviour of
1306 custom (non-POSIX) synchronisation primitives, which it otherwise
1307 has no way to understand. See comments
1308 in <code class="filename">helgrind.h</code> for further
1309 documentation.</p>
1310 </li>
1311 </ul></div>
1312 </div>
1313 <div class="sect1">
1314 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
1315 <a name="hg-manual.todolist"></a>7.9. A To-Do List for Helgrind</h2></div></div></div>
1316 <p>The following is a list of loose ends which should be tidied up
1317 some time.</p>
1318 <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
1319 <li class="listitem"><p>For lock order errors, print the complete lock
1320 cycle, rather than only doing for size-2 cycles as at
1321 present.</p></li>
1322 <li class="listitem"><p>The conflicting access mechanism sometimes
1323 mysteriously fails to show the conflicting access' stack, even
1324 when provided with unbounded storage for conflicting access info.
1325 This should be investigated.</p></li>
1326 <li class="listitem"><p>Document races caused by GCC's thread-unsafe code
1327 generation for speculative stores. In the interim see
1328 <code class="computeroutput">http://gcc.gnu.org/ml/gcc/2007-10/msg00266.html
1329 </code>
1330 and <code class="computeroutput">http://lkml.org/lkml/2007/10/24/673</code>.
1331 </p></li>
1332 <li class="listitem"><p>Don't update the lock-order graph, and don't check
1333 for errors, when a "try"-style lock operation happens (e.g.
1334 <code class="function">pthread_mutex_trylock</code>). Such calls do not add any real
1335 restrictions to the locking order, since they can always fail to
1336 acquire the lock, resulting in the caller going off and doing Plan
1337 B (presumably it will have a Plan B). Doing such checks could
1338 generate false lock-order errors and confuse users.</p></li>
1339 <li class="listitem"><p> Performance can be very poor. Slowdowns on the
1340 order of 100:1 are not unusual. There is limited scope for
1341 performance improvements.
1342 </p></li>
1343 </ul></div>
1344 </div>
1345 </div>
1346 <div>
1347 <br><table class="nav" width="100%" cellspacing="3" cellpadding="2" border="0" summary="Navigation footer">
1348 <tr>
1349 <td rowspan="2" width="40%" align="left">
1350 <a accesskey="p" href="cl-manual.html">&lt;&lt; 6. Callgrind: a call-graph generating cache and branch prediction profiler</a> </td>
1351 <td width="20%" align="center"><a accesskey="u" href="manual.html">Up</a></td>
1352 <td rowspan="2" width="40%" align="right"> <a accesskey="n" href="drd-manual.html">8. DRD: a thread error detector &gt;&gt;</a>
1353 </td>
1354 </tr>
1355 <tr><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td></tr>
1356 </table>
1357 </div>
1358 </body>
1359 </html>