1<section xmlns="http://docbook.org/ns/docbook" version="5.0" 
2	 xml:id="manual.intro.using.debug" xreflabel="Debugging Support">
3<?dbhtml filename="debug.html"?>
4
5<info><title>Debugging Support</title>
6  <keywordset>
7    <keyword>C++</keyword>
8    <keyword>debug</keyword>
9  </keywordset>
10</info>
11
12
13
14<para>
15  There are numerous things that can be done to improve the ease with
16  which C++ binaries are debugged when using the GNU tool chain. Here
17  are some of them.
18</para>
19
20<section xml:id="debug.compiler"><info><title>Using <command>g++</command></title></info>
21
22  <para>
23    Compiler flags determine how debug information is transmitted
24    between compilation and debug or analysis tools.
25  </para>
26
27  <para>
28    The default optimizations and debug flags for a libstdc++ build
29    are <code>-g -O2</code>. However, both debug and optimization
30    flags can be varied to change debugging characteristics. For
31    instance, turning off all optimization via the <code>-g -O0
32    -fno-inline</code> flags will disable inlining and optimizations,
33    and add debugging information, so that stepping through all functions,
34    (including inlined constructors and destructors) is possible. In
35    addition, <code>-fno-eliminate-unused-debug-types</code> can be
36    used when additional debug information, such as nested class info,
37    is desired.
38</para>
39
40<para>
41  Or, the debug format that the compiler and debugger use to
42  communicate information about source constructs can be changed via
43  <code>-gdwarf-2</code> or <code>-gstabs</code> flags: some debugging
44  formats permit more expressive type and scope information to be
45  shown in GDB. Expressiveness can be enhanced by flags like
46  <code>-g3</code>. The default debug information for a particular
47  platform can be identified via the value set by the
48  PREFERRED_DEBUGGING_TYPE macro in the GCC sources.
49</para>
50
51<para>
52  Many other options are available: please see <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html#Debugging%20Options">"Options
53  for Debugging Your Program"</link> in Using the GNU Compiler
54  Collection (GCC) for a complete list.
55</para>
56</section>
57
58<section xml:id="debug.req"><info><title>Debug Versions of Library Binary Files</title></info>
59
60
61<para>
62  If you would like debug symbols in libstdc++, there are two ways to
63  build libstdc++ with debug flags. The first is to create a separate
64  debug build by running make from the top-level of a tree
65  freshly-configured with
66</para>
67<programlisting>
68     --enable-libstdcxx-debug
69</programlisting>
70<para>and perhaps</para>
71<programlisting>
72     --enable-libstdcxx-debug-flags='...'
73</programlisting>
74<para>
75  Both the normal build and the debug build will persist, without
76  having to specify <code>CXXFLAGS</code>, and the debug library will
77  be installed in a separate directory tree, in <code>(prefix)/lib/debug</code>.
78  For more information, look at the
79  <link linkend="manual.intro.setup.configure">configuration</link> section.
80</para>
81
82<para>
83  A second approach is to use the configuration flags
84</para>
85<programlisting>
86     make CXXFLAGS='-g3 -fno-inline -O0' all
87</programlisting>
88
89<para>
90  This quick and dirty approach is often sufficient for quick
91  debugging tasks, when you cannot or don't want to recompile your
92  application to use the <link linkend="manual.ext.debug_mode">debug mode</link>.</para>
93</section>
94
95<section xml:id="debug.memory"><info><title>Memory Leak Hunting</title></info>
96
97<para>
98  On many targets GCC supports AddressSanitizer, a fast memory error detector,
99  which is enabled by the <option>-fsanitize=address</option> option.
100</para>
101
102<para>
103  There are also various third party memory tracing and debug utilities
104  that can be used to provide detailed memory allocation information
105  about C++ code. An exhaustive list of tools is not going to be
106  attempted, but includes <code>mtrace</code>, <code>valgrind</code>,
107  <code>mudflap</code> (no longer supported since GCC 4.9.0), ElectricFence,
108  and the non-free commercial product <code>purify</code>.
109  In addition, <code>libcwd</code>, jemalloc and TCMalloc have replacements
110  for the global <code>new</code> and <code>delete</code> operators
111  that can track memory allocation and deallocation and provide useful
112  memory statistics.
113</para>
114
115<para>
116  For valgrind, there are some specific items to keep in mind. First
117  of all, use a version of valgrind that will work with current GNU
118  C++ tools: the first that can do this is valgrind 1.0.4, but later
119  versions should work better. Second, using an unoptimized build
120  might avoid confusing valgrind.
121</para>
122
123<para>
124  Third, it may be necessary to force deallocation in other libraries
125  as well, namely the "C" library. On GNU/Linux, this can be accomplished
126  with the appropriate use of the <code>__cxa_atexit</code> or
127  <code>atexit</code> functions.
128</para>
129
130<programlisting>
131   #include &lt;cstdlib&gt;
132
133   extern "C" void __libc_freeres(void);
134
135   void do_something() { }
136
137   int main()
138   {
139     atexit(__libc_freeres);
140     do_something();
141     return 0;
142   }
143</programlisting>
144
145<para>or, using <code>__cxa_atexit</code>:</para>
146
147<programlisting>
148   extern "C" void __libc_freeres(void);
149   extern "C" int __cxa_atexit(void (*func) (void *), void *arg, void *d);
150
151   void do_something() { }
152
153   int main()
154   {
155      extern void* __dso_handle __attribute__ ((__weak__));
156      __cxa_atexit((void (*) (void *)) __libc_freeres, NULL,
157		   &amp;__dso_handle ? __dso_handle : NULL);
158      do_test();
159      return 0;
160   }
161</programlisting>
162
163<para>
164  Suggested valgrind flags, given the suggestions above about setting
165  up the runtime environment, library, and test file, might be:
166</para>
167<programlisting>
168   valgrind -v --num-callers=20 --leak-check=yes --leak-resolution=high --show-reachable=yes a.out
169</programlisting>
170
171<section xml:id="debug.memory.mtalloc">
172<info><title>Non-memory leaks in Pool and MT allocators</title></info>
173
174<para>
175  There are different kinds of allocation schemes that can be used by
176  <code>std::allocator</code>. Prior to GCC 3.4.0 the default was to use
177  a pooling allocator, <classname>pool_allocator</classname>,
178  which is still available as the optional
179  <classname>__pool_alloc</classname> extension.
180  Another optional extension, <classname>__mt_alloc</classname>,
181  is a high-performance pool allocator.
182</para>
183
184<para>
185  In a suspect executable these pooling allocators can give
186  the mistaken impression that memory is being leaked,
187  when in reality the memory "leak" is a pool being used
188  by the library's allocator and is reclaimed after program
189  termination.
190</para>
191
192<para>
193  If you're using memory debugging tools on a program that uses
194  one of these pooling allocators, you can set the environment variable
195  <literal>GLIBCXX_FORCE_NEW</literal> to keep extraneous pool allocation
196  noise from cluttering debug information.
197  For more details, see the
198  <link linkend="manual.ext.allocator.mt">mt allocator</link>
199  documentation and look specifically for <code>GLIBCXX_FORCE_NEW</code>.
200</para>
201
202</section>
203
204</section>
205
206<section xml:id="debug.races"><info><title>Data Race Hunting</title></info>
207<para>
208  All synchronization primitives used in the library internals need to be
209  understood by race detectors so that they do not produce false reports.
210</para>
211
212<para>
213  Two annotation macros are used to explain low-level synchronization 
214  to race detectors:
215  <code>_GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE()</code> and
216  <code> _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER()</code>.
217  By default, these macros are defined empty -- anyone who wants
218  to use a race detector needs to redefine them to call an
219  appropriate API.
220  Since these macros are empty by default when the library is built,
221  redefining them will only affect inline functions and template
222  instantiations which are compiled in user code. This allows annotation
223  of templates such as <code>shared_ptr</code>, but not code which is
224  only instantiated in the library.  Code which is only instantiated in
225  the library needs to be recompiled with the annotation macros defined.
226  That can be done by rebuilding the entire
227  <filename class="libraryfile">libstdc++.so</filename> file but a simpler
228  alternative exists for ELF platforms such as GNU/Linux, because ELF
229  symbol interposition allows symbols defined in the shared library to be
230  overridden by symbols with the same name that appear earlier in the
231  runtime search path. This means you only need to recompile the functions
232  that are affected by the annotation macros, which can be done by
233  recompiling individual files.
234  Annotating <code>std::string</code> and <code>std::wstring</code>
235  reference counting can be done by disabling extern templates (by defining 
236  <code>_GLIBCXX_EXTERN_TEMPLATE=-1</code>) or by rebuilding the 
237  <filename>src/string-inst.cc</filename> file.
238  Annotating the remaining atomic operations (at the time of writing these
239  are in <code>ios_base::Init::~Init</code>, <code>locale::_Impl</code>,
240  <code>locale::facet</code> and <code>thread::_M_start_thread</code>)
241  requires rebuilding the relevant source files.
242</para>
243
244<para>
245  The approach described above is known to work with the following race
246  detection tools:
247  <link xmlns:xlink="http://www.w3.org/1999/xlink" 
248  xlink:href="http://valgrind.org/docs/manual/drd-manual.html">
249  DRD</link>,
250  <link xmlns:xlink="http://www.w3.org/1999/xlink" 
251  xlink:href="http://valgrind.org/docs/manual/hg-manual.html"> 
252  Helgrind</link>, and
253  <link xmlns:xlink="http://www.w3.org/1999/xlink" 
254  xlink:href="https://github.com/google/sanitizers"> 
255  ThreadSanitizer</link> (this refers to ThreadSanitizer v1, not the
256  new "tsan" feature built-in to GCC itself).
257</para>
258
259<para>
260  With DRD, Helgrind and ThreadSanitizer you will need to define
261  the macros like this:
262<programlisting>
263  #define _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(A) ANNOTATE_HAPPENS_BEFORE(A)
264  #define _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(A)  ANNOTATE_HAPPENS_AFTER(A)
265</programlisting>
266  Refer to the documentation of each particular tool for details.
267</para>
268
269</section>
270
271<section xml:id="debug.gdb"><info><title>Using <command>gdb</command></title></info>
272
273  <para>
274  </para>
275
276<para>
277  Many options are available for GDB itself: please see <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://sourceware.org/gdb/current/onlinedocs/gdb/">
278  "GDB features for C++" </link> in the GDB documentation. Also
279  recommended: the other parts of this manual.
280</para>
281
282<para>
283  These settings can either be switched on in at the GDB command line,
284  or put into a <filename>.gdbinit</filename> file to establish default
285  debugging characteristics, like so:
286</para>
287
288<programlisting>
289   set print pretty on
290   set print object on
291   set print static-members on
292   set print vtbl on
293   set print demangle on
294   set demangle-style gnu-v3
295</programlisting>
296
297<para>
298  Starting with version 7.0, GDB includes support for writing
299  pretty-printers in Python.  Pretty printers for containers and other
300  classes are distributed with GCC from version 4.5.0 and should be installed
301  alongside the libstdc++ shared library files and found automatically by
302  GDB.
303</para>
304
305<para>
306  Depending where libstdc++ is installed, GDB might refuse to auto-load
307  the python printers and print a warning instead.
308  If this happens the python printers can be enabled by following the
309  instructions GDB gives for setting your <code>auto-load safe-path</code>
310  in your <filename>.gdbinit</filename> configuration file.
311</para>
312
313<para>
314  Once loaded, standard library classes that the printers support
315  should print in a more human-readable format.  To print the classes
316  in the old style, use the <userinput>/r</userinput> (raw) switch in the
317  print command (i.e., <userinput>print /r foo</userinput>).  This will
318  print the classes as if the Python pretty-printers were not loaded.
319</para>
320
321<para>
322  For additional information on STL support and GDB please visit:
323  <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://sourceware.org/gdb/wiki/STLSupport"> "GDB Support
324  for STL" </link> in the GDB wiki.  Additionally, in-depth
325  documentation and discussion of the pretty printing feature can be
326  found in "Pretty Printing" node in the GDB manual.  You can find
327  on-line versions of the GDB user manual in GDB's homepage, at
328  <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://sourceware.org/gdb/"> "GDB: The GNU Project
329  Debugger" </link>.
330</para>
331
332</section>
333
334<section xml:id="debug.exceptions"><info><title>Tracking uncaught exceptions</title></info>
335
336<para>
337  The <link linkend="support.termination.verbose">verbose
338  termination handler</link> gives information about uncaught
339  exceptions which kill the program.
340</para>
341</section>
342
343<section xml:id="debug.debug_mode"><info><title>Debug Mode</title></info>
344
345  <para> The <link linkend="manual.ext.debug_mode">Debug Mode</link>
346  has compile and run-time checks for many containers.
347  </para>
348</section>
349
350<section xml:id="debug.compile_time_checks"><info><title>Compile Time Checking</title></info>
351
352  <para> The <link linkend="manual.ext.compile_checks">Compile-Time
353  Checks</link> extension has compile-time checks for many algorithms.
354  </para>
355</section>
356
357</section>
358