]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/doc/gcc/gcc-command-options/program-instrumentation-options.rst
0549b7dca97b8ccc308b577a19c89f82b1cae6b0
[thirdparty/gcc.git] / gcc / doc / gcc / gcc-command-options / program-instrumentation-options.rst
1 ..
2 Copyright 1988-2022 Free Software Foundation, Inc.
3 This is part of the GCC manual.
4 For copying conditions, see the copyright.rst file.
5
6 .. index:: instrumentation options, program instrumentation options, run-time error checking options, profiling options, options, program instrumentation, options, run-time error checking, options, profiling
7
8 .. _instrumentation-options:
9
10 Program Instrumentation Options
11 *******************************
12
13 GCC supports a number of command-line options that control adding
14 run-time instrumentation to the code it normally generates.
15 For example, one purpose of instrumentation is collect profiling
16 statistics for use in finding program hot spots, code coverage
17 analysis, or profile-guided optimizations.
18 Another class of program instrumentation is adding run-time checking
19 to detect programming errors like invalid pointer
20 dereferences or out-of-bounds array accesses, as well as deliberately
21 hostile attacks such as stack smashing or C++ vtable hijacking.
22 There is also a general hook which can be used to implement other
23 forms of tracing or function-level instrumentation for debug or
24 program analysis purposes.
25
26 .. index:: prof, gprof
27
28 .. option:: -p, -pg
29
30 Generate extra code to write profile information suitable for the
31 analysis program :command:`prof` (for :option:`-p`) or :command:`gprof`
32 (for :option:`-pg`). You must use this option when compiling
33 the source files you want data about, and you must also use it when
34 linking.
35
36 You can use the function attribute ``no_instrument_function`` to
37 suppress profiling of individual functions when compiling with these options.
38 See :ref:`common-function-attributes`.
39
40 .. option:: -fprofile-arcs
41
42 Add code so that program flow :dfn:`arcs` are instrumented. During
43 execution the program records how many times each branch and call is
44 executed and how many times it is taken or returns. On targets that support
45 constructors with priority support, profiling properly handles constructors,
46 destructors and C++ constructors (and destructors) of classes which are used
47 as a type of a global variable.
48
49 When the compiled
50 program exits it saves this data to a file called
51 :samp:`{auxname}.gcda` for each source file. The data may be used for
52 profile-directed optimizations (:option:`-fbranch-probabilities`), or for
53 test coverage analysis (:option:`-ftest-coverage`). Each object file's
54 :samp:`{auxname}` is generated from the name of the output file, if
55 explicitly specified and it is not the final executable, otherwise it is
56 the basename of the source file. In both cases any suffix is removed
57 (e.g. :samp:`foo.gcda` for input file :samp:`dir/foo.c`, or
58 :samp:`dir/foo.gcda` for output file specified as :option:`-o dir/foo.o`).
59
60 Note that if a command line directly links source files, the corresponding
61 :samp:`{.gcda}` files will be prefixed with the unsuffixed name of the output file.
62 E.g. ``gcc a.c b.c -o binary`` would generate :samp:`binary-a.gcda` and
63 :samp:`binary-b.gcda` files.
64
65 See :ref:`cross-profiling`.
66
67 .. index:: gcov
68
69 .. option:: --coverage
70
71 This option is used to compile and link code instrumented for coverage
72 analysis. The option is a synonym for :option:`-fprofile-arcs`
73 :option:`-ftest-coverage` (when compiling) and :option:`-lgcov` (when
74 linking). See the documentation for those options for more details.
75
76 * Compile the source files with :option:`-fprofile-arcs` plus optimization
77 and code generation options. For test coverage analysis, use the
78 additional :option:`-ftest-coverage` option. You do not need to profile
79 every source file in a program.
80
81 * Compile the source files additionally with :option:`-fprofile-abs-path`
82 to create absolute path names in the :samp:`.gcno` files. This allows
83 :command:`gcov` to find the correct sources in projects where compilations
84 occur with different working directories.
85
86 * Link your object files with :option:`-lgcov` or :option:`-fprofile-arcs`
87 (the latter implies the former).
88
89 * Run the program on a representative workload to generate the arc profile
90 information. This may be repeated any number of times. You can run
91 concurrent instances of your program, and provided that the file system
92 supports locking, the data files will be correctly updated. Unless
93 a strict ISO C dialect option is in effect, ``fork`` calls are
94 detected and correctly handled without double counting.
95
96 Moreover, an object file can be recompiled multiple times
97 and the corresponding :samp:`.gcda` file merges as long as
98 the source file and the compiler options are unchanged.
99
100 * For profile-directed optimizations, compile the source files again with
101 the same optimization and code generation options plus
102 :option:`-fbranch-probabilities` (see :ref:`optimize-options`).
103
104 * For test coverage analysis, use :command:`gcov` to produce human readable
105 information from the :samp:`.gcno` and :samp:`.gcda` files. Refer to the
106 :command:`gcov` documentation for further information.
107
108 With :option:`-fprofile-arcs`, for each function of your program GCC
109 creates a program flow graph, then finds a spanning tree for the graph.
110 Only arcs that are not on the spanning tree have to be instrumented: the
111 compiler adds code to count the number of times that these arcs are
112 executed. When an arc is the only exit or only entrance to a block, the
113 instrumentation code can be added to the block; otherwise, a new basic
114 block must be created to hold the instrumentation code.
115
116 .. option:: -ftest-coverage
117
118 Produce a notes file that the :command:`gcov` code-coverage utility
119 (see :ref:`gcov`) can use to
120 show program coverage. Each source file's note file is called
121 :samp:`{auxname}.gcno`. Refer to the :option:`-fprofile-arcs` option
122 above for a description of :samp:`{auxname}` and instructions on how to
123 generate test coverage data. Coverage data matches the source files
124 more closely if you do not optimize.
125
126 .. option:: -fprofile-abs-path
127
128 Automatically convert relative source file names to absolute path names
129 in the :samp:`.gcno` files. This allows :command:`gcov` to find the correct
130 sources in projects where compilations occur with different working
131 directories.
132
133 .. option:: -fprofile-dir={path}
134
135 Set the directory to search for the profile data files in to :samp:`{path}`.
136 This option affects only the profile data generated by
137 :option:`-fprofile-generate`, :option:`-ftest-coverage`, :option:`-fprofile-arcs`
138 and used by :option:`-fprofile-use` and :option:`-fbranch-probabilities`
139 and its related options. Both absolute and relative paths can be used.
140 By default, GCC uses the current directory as :samp:`{path}`, thus the
141 profile data file appears in the same directory as the object file.
142 In order to prevent the file name clashing, if the object file name is
143 not an absolute path, we mangle the absolute path of the
144 :samp:`{sourcename}.gcda` file and use it as the file name of a
145 :samp:`.gcda` file. See details about the file naming in :option:`-fprofile-arcs`.
146 See similar option :option:`-fprofile-note`.
147
148 When an executable is run in a massive parallel environment, it is recommended
149 to save profile to different folders. That can be done with variables
150 in :samp:`{path}` that are exported during run-time:
151
152 ``%p``
153 process ID.
154
155 ``%q{VAR}``
156 value of environment variable :samp:`{VAR}`
157
158 .. option:: -fprofile-generate, -fprofile-generate={path}
159
160 Enable options usually used for instrumenting application to produce
161 profile useful for later recompilation with profile feedback based
162 optimization. You must use :option:`-fprofile-generate` both when
163 compiling and when linking your program.
164
165 The following options are enabled:
166 :option:`-fprofile-arcs`, :option:`-fprofile-values`,
167 :option:`-finline-functions`, and :option:`-fipa-bit-cp`.
168
169 If :samp:`{path}` is specified, GCC looks at the :samp:`{path}` to find
170 the profile feedback data files. See :option:`-fprofile-dir`.
171
172 To optimize the program based on the collected profile information, use
173 :option:`-fprofile-use`. See :ref:`optimize-options`, for more information.
174
175 .. option:: -fprofile-info-section, -fprofile-info-section={name}
176
177 Register the profile information in the specified section instead of using a
178 constructor/destructor. The section name is :samp:`{name}` if it is specified,
179 otherwise the section name defaults to ``.gcov_info``. A pointer to the
180 profile information generated by :option:`-fprofile-arcs` is placed in the
181 specified section for each translation unit. This option disables the profile
182 information registration through a constructor and it disables the profile
183 information processing through a destructor. This option is not intended to be
184 used in hosted environments such as GNU/Linux. It targets freestanding
185 environments (for example embedded systems) with limited resources which do not
186 support constructors/destructors or the C library file I/O.
187
188 The linker could collect the input sections in a continuous memory block and
189 define start and end symbols. A GNU linker script example which defines a
190 linker output section follows:
191
192 .. code-block:: c++
193
194 .gcov_info :
195 {
196 PROVIDE (__gcov_info_start = .);
197 KEEP (*(.gcov_info))
198 PROVIDE (__gcov_info_end = .);
199 }
200
201 The program could dump the profiling information registered in this linker set
202 for example like this:
203
204 .. code-block:: c++
205
206 #include <gcov.h>
207 #include <stdio.h>
208 #include <stdlib.h>
209
210 extern const struct gcov_info *const __gcov_info_start[];
211 extern const struct gcov_info *const __gcov_info_end[];
212
213 static void
214 dump (const void *d, unsigned n, void *arg)
215 {
216 const unsigned char *c = d;
217
218 for (unsigned i = 0; i < n; ++i)
219 printf ("%02x", c[i]);
220 }
221
222 static void
223 filename (const char *f, void *arg)
224 {
225 __gcov_filename_to_gcfn (f, dump, arg );
226 }
227
228 static void *
229 allocate (unsigned length, void *arg)
230 {
231 return malloc (length);
232 }
233
234 static void
235 dump_gcov_info (void)
236 {
237 const struct gcov_info *const *info = __gcov_info_start;
238 const struct gcov_info *const *end = __gcov_info_end;
239
240 /* Obfuscate variable to prevent compiler optimizations. */
241 __asm__ ("" : "+r" (info));
242
243 while (info != end)
244 {
245 void *arg = NULL;
246 __gcov_info_to_gcda (*info, filename, dump, allocate, arg);
247 putchar ('\n');
248 ++info;
249 }
250 }
251
252 int
253 main (void)
254 {
255 dump_gcov_info ();
256 return 0;
257 }
258
259 The :command:`merge-stream` subcommand of :command:`gcov-tool` may be used to
260 deserialize the data stream generated by the ``__gcov_filename_to_gcfn`` and
261 ``__gcov_info_to_gcda`` functions and merge the profile information into
262 :samp:`.gcda` files on the host filesystem.
263
264 .. option:: -fprofile-note={path}
265
266 If :samp:`{path}` is specified, GCC saves :samp:`.gcno` file into :samp:`{path}`
267 location. If you combine the option with multiple source files,
268 the :samp:`.gcno` file will be overwritten.
269
270 .. option:: -fprofile-prefix-path={path}
271
272 This option can be used in combination with
273 :option:`-fprofile-generate=profile_dir` and
274 :option:`-fprofile-use=profile_dir` to inform GCC where is the base
275 directory of built source tree. By default :samp:`{profile_dir}` will contain
276 files with mangled absolute paths of all object files in the built project.
277 This is not desirable when directory used to build the instrumented binary
278 differs from the directory used to build the binary optimized with profile
279 feedback because the profile data will not be found during the optimized build.
280 In such setups :option:`-fprofile-prefix-path=path` with :samp:`{path}`
281 pointing to the base directory of the build can be used to strip the irrelevant
282 part of the path and keep all file names relative to the main build directory.
283
284 .. option:: -fprofile-prefix-map={old}={new}
285
286 When compiling files residing in directory :samp:`{old}`, record
287 profiling information (with :option:`--coverage`)
288 describing them as if the files resided in
289 directory :samp:`{new}` instead.
290 See also :option:`-ffile-prefix-map`.
291
292 .. option:: -fprofile-update={method}
293
294 Alter the update method for an application instrumented for profile
295 feedback based optimization. The :samp:`{method}` argument should be one of
296 :samp:`single`, :samp:`atomic` or :samp:`prefer-atomic`.
297 The first one is useful for single-threaded applications,
298 while the second one prevents profile corruption by emitting thread-safe code.
299
300 .. warning::
301
302 When an application does not properly join all threads
303 (or creates an detached thread), a profile file can be still corrupted.
304
305 Using :samp:`prefer-atomic` would be transformed either to :samp:`atomic`,
306 when supported by a target, or to :samp:`single` otherwise. The GCC driver
307 automatically selects :samp:`prefer-atomic` when :option:`-pthread`
308 is present in the command line.
309
310 .. option:: -fprofile-filter-files={regex}
311
312 Instrument only functions from files whose name matches
313 any of the regular expressions (separated by semi-colons).
314
315 For example, :option:`-fprofile-filter-files=main\\.c;module.*\\.c` will instrument
316 only :samp:`main.c` and all C files starting with 'module'.
317
318 .. option:: -fprofile-exclude-files={regex}
319
320 Instrument only functions from files whose name does not match
321 any of the regular expressions (separated by semi-colons).
322
323 For example, :option:`-fprofile-exclude-files=/usr/.*` will prevent instrumentation
324 of all files that are located in the :samp:`/usr/` folder.
325
326 .. option:: -fprofile-reproducible=[multithreaded|parallel-runs|serial]
327
328 Control level of reproducibility of profile gathered by
329 ``-fprofile-generate``. This makes it possible to rebuild program
330 with same outcome which is useful, for example, for distribution
331 packages.
332
333 With :option:`-fprofile-reproducible=serial` the profile gathered by
334 :option:`-fprofile-generate` is reproducible provided the trained program
335 behaves the same at each invocation of the train run, it is not
336 multi-threaded and profile data streaming is always done in the same
337 order. Note that profile streaming happens at the end of program run but
338 also before ``fork`` function is invoked.
339
340 Note that it is quite common that execution counts of some part of
341 programs depends, for example, on length of temporary file names or
342 memory space randomization (that may affect hash-table collision rate).
343 Such non-reproducible part of programs may be annotated by
344 ``no_instrument_function`` function attribute. :command:`gcov-dump` with
345 :option:`-l` can be used to dump gathered data and verify that they are
346 indeed reproducible.
347
348 With :option:`-fprofile-reproducible=parallel-runs` collected profile
349 stays reproducible regardless the order of streaming of the data into
350 gcda files. This setting makes it possible to run multiple instances of
351 instrumented program in parallel (such as with ``make -j``). This
352 reduces quality of gathered data, in particular of indirect call
353 profiling.
354
355 .. option:: -fsanitize=address
356
357 Enable AddressSanitizer, a fast memory error detector.
358 Memory access instructions are instrumented to detect
359 out-of-bounds and use-after-free bugs.
360 The option enables :option:`-fsanitize-address-use-after-scope`.
361 See https://github.com/google/sanitizers/wiki/AddressSanitizer for
362 more details. The run-time behavior can be influenced using the
363 :envvar:`ASAN_OPTIONS` environment variable. When set to ``help=1``,
364 the available options are shown at startup of the instrumented program. See
365 https://github.com/google/sanitizers/wiki/AddressSanitizerFlags#run-time-flags
366 for a list of supported options.
367 The option cannot be combined with :option:`-fsanitize=thread` or
368 :option:`-fsanitize=hwaddress`. Note that the only target
369 :option:`-fsanitize=hwaddress` is currently supported on is AArch64.
370
371 .. option:: -fsanitize=kernel-address
372
373 Enable AddressSanitizer for Linux kernel.
374 See https://github.com/google/kasan for more details.
375
376 .. option:: -fsanitize=hwaddress
377
378 Enable Hardware-assisted AddressSanitizer, which uses a hardware ability to
379 ignore the top byte of a pointer to allow the detection of memory errors with
380 a low memory overhead.
381 Memory access instructions are instrumented to detect out-of-bounds and
382 use-after-free bugs.
383 The option enables :option:`-fsanitize-address-use-after-scope`.
384 See
385 https://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.html
386 for more details. The run-time behavior can be influenced using the
387 :envvar:`HWASAN_OPTIONS` environment variable. When set to ``help=1``,
388 the available options are shown at startup of the instrumented program.
389 The option cannot be combined with :option:`-fsanitize=thread` or
390 :option:`-fsanitize=address`, and is currently only available on AArch64.
391
392 .. option:: -fsanitize=kernel-hwaddress
393
394 Enable Hardware-assisted AddressSanitizer for compilation of the Linux kernel.
395 Similar to :option:`-fsanitize=kernel-address` but using an alternate
396 instrumentation method, and similar to :option:`-fsanitize=hwaddress` but with
397 instrumentation differences necessary for compiling the Linux kernel.
398 These differences are to avoid hwasan library initialization calls and to
399 account for the stack pointer having a different value in its top byte.
400
401 .. note::
402
403 This option has different defaults to the :option:`-fsanitize=hwaddress`.
404 Instrumenting the stack and alloca calls are not on by default but are still
405 possible by specifying the command-line options
406 :option:`--param` :gcc-param:`hwasan-instrument-stack`:samp:`=1` and
407 :option:`--param` :gcc-param:`hwasan-instrument-allocas`:samp:`=1` respectively. Using a random frame
408 tag is not implemented for kernel instrumentation.
409
410 .. option:: -fsanitize=pointer-compare
411
412 Instrument comparison operation (<, <=, >, >=) with pointer operands.
413 The option must be combined with either :option:`-fsanitize=kernel-address` or
414 :option:`-fsanitize=address`
415 The option cannot be combined with :option:`-fsanitize=thread`.
416 Note: By default the check is disabled at run time. To enable it,
417 add ``detect_invalid_pointer_pairs=2`` to the environment variable
418 :envvar:`ASAN_OPTIONS`. Using ``detect_invalid_pointer_pairs=1`` detects
419 invalid operation only when both pointers are non-null.
420
421 .. option:: -fsanitize=pointer-subtract
422
423 Instrument subtraction with pointer operands.
424 The option must be combined with either :option:`-fsanitize=kernel-address` or
425 :option:`-fsanitize=address`
426 The option cannot be combined with :option:`-fsanitize=thread`.
427 Note: By default the check is disabled at run time. To enable it,
428 add ``detect_invalid_pointer_pairs=2`` to the environment variable
429 :envvar:`ASAN_OPTIONS`. Using ``detect_invalid_pointer_pairs=1`` detects
430 invalid operation only when both pointers are non-null.
431
432 .. option:: -fsanitize=shadow-call-stack
433
434 Enable ShadowCallStack, a security enhancement mechanism used to protect
435 programs against return address overwrites (e.g. stack buffer overflows.)
436 It works by saving a function's return address to a separately allocated
437 shadow call stack in the function prologue and restoring the return address
438 from the shadow call stack in the function epilogue. Instrumentation only
439 occurs in functions that need to save the return address to the stack.
440
441 Currently it only supports the aarch64 platform. It is specifically
442 designed for linux kernels that enable the CONFIG_SHADOW_CALL_STACK option.
443 For the user space programs, runtime support is not currently provided
444 in libc and libgcc. Users who want to use this feature in user space need
445 to provide their own support for the runtime. It should be noted that
446 this may cause the ABI rules to be broken.
447
448 On aarch64, the instrumentation makes use of the platform register ``x18``.
449 This generally means that any code that may run on the same thread as code
450 compiled with ShadowCallStack must be compiled with the flag
451 :option:`-ffixed-x18`, otherwise functions compiled without
452 :option:`-ffixed-x18` might clobber ``x18`` and so corrupt the shadow
453 stack pointer.
454
455 Also, because there is no userspace runtime support, code compiled with
456 ShadowCallStack cannot use exception handling. Use :option:`-fno-exceptions`
457 to turn off exceptions.
458
459 See https://clang.llvm.org/docs/ShadowCallStack.html for more
460 details.
461
462 .. option:: -fsanitize=thread
463
464 Enable ThreadSanitizer, a fast data race detector.
465 Memory access instructions are instrumented to detect
466 data race bugs. See https://github.com/google/sanitizers/wiki#threadsanitizer for more
467 details. The run-time behavior can be influenced using the :envvar:`TSAN_OPTIONS`
468 environment variable; see
469 https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags for a list of
470 supported options.
471 The option cannot be combined with :option:`-fsanitize=address`,
472 :option:`-fsanitize=leak`.
473
474 Note that sanitized atomic builtins cannot throw exceptions when
475 operating on invalid memory addresses with non-call exceptions
476 (:option:`-fnon-call-exceptions`).
477
478 .. option:: -fsanitize=leak
479
480 Enable LeakSanitizer, a memory leak detector.
481 This option only matters for linking of executables and
482 the executable is linked against a library that overrides ``malloc``
483 and other allocator functions. See
484 https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer for more
485 details. The run-time behavior can be influenced using the
486 :envvar:`LSAN_OPTIONS` environment variable.
487 The option cannot be combined with :option:`-fsanitize=thread`.
488
489 .. option:: -fsanitize=undefined
490
491 Enable UndefinedBehaviorSanitizer, a fast undefined behavior detector.
492 Various computations are instrumented to detect undefined behavior
493 at runtime. See https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html for more details. The run-time behavior can be influenced using the
494 :envvar:`UBSAN_OPTIONS` environment variable. Current suboptions are:
495
496 .. option:: -fsanitize=shift
497
498 This option enables checking that the result of a shift operation is
499 not undefined. Note that what exactly is considered undefined differs
500 slightly between C and C++, as well as between ISO C90 and C99, etc.
501 This option has two suboptions, :option:`-fsanitize=shift-base` and
502 :option:`-fsanitize=shift-exponent`.
503
504 .. option:: -fsanitize=shift-exponent
505
506 This option enables checking that the second argument of a shift operation
507 is not negative and is smaller than the precision of the promoted first
508 argument.
509
510 .. option:: -fsanitize=shift-base
511
512 If the second argument of a shift operation is within range, check that the
513 result of a shift operation is not undefined. Note that what exactly is
514 considered undefined differs slightly between C and C++, as well as between
515 ISO C90 and C99, etc.
516
517 .. option:: -fsanitize=integer-divide-by-zero
518
519 Detect integer division by zero.
520
521 .. option:: -fsanitize=unreachable
522
523 With this option, the compiler turns the ``__builtin_unreachable``
524 call into a diagnostics message call instead. When reaching the
525 ``__builtin_unreachable`` call, the behavior is undefined.
526
527 .. option:: -fsanitize=vla-bound
528
529 This option instructs the compiler to check that the size of a variable
530 length array is positive.
531
532 .. option:: -fsanitize=null
533
534 This option enables pointer checking. Particularly, the application
535 built with this option turned on will issue an error message when it
536 tries to dereference a NULL pointer, or if a reference (possibly an
537 rvalue reference) is bound to a NULL pointer, or if a method is invoked
538 on an object pointed by a NULL pointer.
539
540 .. option:: -fsanitize=return
541
542 This option enables return statement checking. Programs
543 built with this option turned on will issue an error message
544 when the end of a non-void function is reached without actually
545 returning a value. This option works in C++ only.
546
547 .. option:: -fsanitize=signed-integer-overflow
548
549 This option enables signed integer overflow checking. We check that
550 the result of ``+``, ``*``, and both unary and binary ``-``
551 does not overflow in the signed arithmetics. This also detects
552 ``INT_MIN / -1`` signed division. Note, integer promotion
553 rules must be taken into account. That is, the following is not an
554 overflow:
555
556 .. code-block:: c++
557
558 signed char a = SCHAR_MAX;
559 a++;
560
561 .. option:: -fsanitize=bounds
562
563 This option enables instrumentation of array bounds. Various out of bounds
564 accesses are detected. Flexible array members, flexible array member-like
565 arrays, and initializers of variables with static storage are not instrumented.
566
567 .. option:: -fsanitize=bounds-strict
568
569 This option enables strict instrumentation of array bounds. Most out of bounds
570 accesses are detected, including flexible array members and flexible array
571 member-like arrays. Initializers of variables with static storage are not
572 instrumented.
573
574 .. option:: -fsanitize=alignment
575
576 This option enables checking of alignment of pointers when they are
577 dereferenced, or when a reference is bound to insufficiently aligned target,
578 or when a method or constructor is invoked on insufficiently aligned object.
579
580 .. option:: -fsanitize=object-size
581
582 This option enables instrumentation of memory references using the
583 ``__builtin_object_size`` function. Various out of bounds pointer
584 accesses are detected.
585
586 .. option:: -fsanitize=float-divide-by-zero
587
588 Detect floating-point division by zero. Unlike other similar options,
589 :option:`-fsanitize=float-divide-by-zero` is not enabled by
590 :option:`-fsanitize=undefined`, since floating-point division by zero can
591 be a legitimate way of obtaining infinities and NaNs.
592
593 .. option:: -fsanitize=float-cast-overflow
594
595 This option enables floating-point type to integer conversion checking.
596 We check that the result of the conversion does not overflow.
597 Unlike other similar options, :option:`-fsanitize=float-cast-overflow` is
598 not enabled by :option:`-fsanitize=undefined`.
599 This option does not work well with ``FE_INVALID`` exceptions enabled.
600
601 .. option:: -fsanitize=nonnull-attribute
602
603 This option enables instrumentation of calls, checking whether null values
604 are not passed to arguments marked as requiring a non-null value by the
605 :fn-attr:`nonnull` function attribute.
606
607 .. option:: -fsanitize=returns-nonnull-attribute
608
609 This option enables instrumentation of return statements in functions
610 marked with :fn-attr:`returns_nonnull` function attribute, to detect returning
611 of null values from such functions.
612
613 .. option:: -fsanitize=bool
614
615 This option enables instrumentation of loads from bool. If a value other
616 than 0/1 is loaded, a run-time error is issued.
617
618 .. option:: -fsanitize=enum
619
620 This option enables instrumentation of loads from an enum type. If
621 a value outside the range of values for the enum type is loaded,
622 a run-time error is issued.
623
624 .. option:: -fsanitize=vptr
625
626 This option enables instrumentation of C++ member function calls, member
627 accesses and some conversions between pointers to base and derived classes,
628 to verify the referenced object has the correct dynamic type.
629
630 .. option:: -fsanitize=pointer-overflow
631
632 This option enables instrumentation of pointer arithmetics. If the pointer
633 arithmetics overflows, a run-time error is issued.
634
635 .. option:: -fsanitize=builtin
636
637 This option enables instrumentation of arguments to selected builtin
638 functions. If an invalid value is passed to such arguments, a run-time
639 error is issued. E.g.passing 0 as the argument to ``__builtin_ctz``
640 or ``__builtin_clz`` invokes undefined behavior and is diagnosed
641 by this option.
642
643 Note that sanitizers tend to increase the rate of false positive
644 warnings, most notably those around :option:`-Wmaybe-uninitialized`.
645 We recommend against combining :option:`-Werror` and [the use of]
646 sanitizers.
647
648 While :option:`-ftrapv` causes traps for signed overflows to be emitted,
649 :option:`-fsanitize=undefined` gives a diagnostic message.
650 This currently works only for the C family of languages.
651
652 .. option:: -fno-sanitize=all
653
654 This option disables all previously enabled sanitizers.
655 :option:`-fsanitize=all` is not allowed, as some sanitizers cannot be used
656 together.
657
658 .. option:: -fasan-shadow-offset={number}
659
660 This option forces GCC to use custom shadow offset in AddressSanitizer checks.
661 It is useful for experimenting with different shadow memory layouts in
662 Kernel AddressSanitizer.
663
664 .. option:: -fsanitize-sections={s1},{s2},...
665
666 Sanitize global variables in selected user-defined sections. :samp:`{si}` may
667 contain wildcards.
668
669 .. option:: -fsanitize-recover[={opts}]
670
671 :option:`-fsanitize-recover=` controls error recovery mode for sanitizers
672 mentioned in comma-separated list of :samp:`{opts}`. Enabling this option
673 for a sanitizer component causes it to attempt to continue
674 running the program as if no error happened. This means multiple
675 runtime errors can be reported in a single program run, and the exit
676 code of the program may indicate success even when errors
677 have been reported. The :option:`-fno-sanitize-recover=` option
678 can be used to alter
679 this behavior: only the first detected error is reported
680 and program then exits with a non-zero exit code.
681
682 Currently this feature only works for :option:`-fsanitize=undefined` (and its suboptions
683 except for :option:`-fsanitize=unreachable` and :option:`-fsanitize=return`),
684 :option:`-fsanitize=float-cast-overflow`, :option:`-fsanitize=float-divide-by-zero`,
685 :option:`-fsanitize=bounds-strict`,
686 :option:`-fsanitize=kernel-address` and :option:`-fsanitize=address`.
687 For these sanitizers error recovery is turned on by default,
688 except :option:`-fsanitize=address`, for which this feature is experimental.
689 :option:`-fsanitize-recover=all` and :option:`-fno-sanitize-recover=all` is also
690 accepted, the former enables recovery for all sanitizers that support it,
691 the latter disables recovery for all sanitizers that support it.
692
693 Even if a recovery mode is turned on the compiler side, it needs to be also
694 enabled on the runtime library side, otherwise the failures are still fatal.
695 The runtime library defaults to ``halt_on_error=0`` for
696 ThreadSanitizer and UndefinedBehaviorSanitizer, while default value for
697 AddressSanitizer is ``halt_on_error=1``. This can be overridden through
698 setting the ``halt_on_error`` flag in the corresponding environment variable.
699
700 Syntax without an explicit :samp:`{opts}` parameter is deprecated. It is
701 equivalent to specifying an :samp:`{opts}` list of:
702
703 .. code-block::
704
705 undefined,float-cast-overflow,float-divide-by-zero,bounds-strict
706
707 .. option:: -fsanitize-address-use-after-scope
708
709 Enable sanitization of local variables to detect use-after-scope bugs.
710 The option sets :option:`-fstack-reuse` to :samp:`none`.
711
712 .. option:: -fsanitize-trap[={opts}]
713
714 The :option:`-fsanitize-trap=` option instructs the compiler to
715 report for sanitizers mentioned in comma-separated list of :samp:`{opts}`
716 undefined behavior using ``__builtin_trap`` rather than a ``libubsan``
717 library routine. If this option is enabled for certain sanitizer,
718 it takes precedence over the :option:`-fsanitizer-recover=` for that
719 sanitizer, ``__builtin_trap`` will be emitted and be fatal regardless
720 of whether recovery is enabled or disabled using :option:`-fsanitize-recover=`.
721
722 The advantage of this is that the ``libubsan`` library is not needed
723 and is not linked in, so this is usable even in freestanding environments.
724
725 Currently this feature works with :option:`-fsanitize=undefined` (and its suboptions
726 except for :option:`-fsanitize=vptr`), :option:`-fsanitize=float-cast-overflow`,
727 :option:`-fsanitize=float-divide-by-zero` and
728 :option:`-fsanitize=bounds-strict`. ``-fsanitize-trap=all`` can be also
729 specified, which enables it for ``undefined`` suboptions,
730 :option:`-fsanitize=float-cast-overflow`,
731 :option:`-fsanitize=float-divide-by-zero` and
732 :option:`-fsanitize=bounds-strict`.
733 If ``-fsanitize-trap=undefined`` or ``-fsanitize-trap=all`` is used
734 and ``-fsanitize=vptr`` is enabled on the command line, the
735 instrumentation is silently ignored as the instrumentation always needs
736 ``libubsan`` support, :option:`-fsanitize-trap=vptr` is not allowed.
737
738 .. option:: -fsanitize-undefined-trap-on-error
739
740 The :option:`-fsanitize-undefined-trap-on-error` option is deprecated
741 equivalent of :option:`-fsanitize-trap=all`.
742
743 .. option:: -fsanitize-coverage=trace-pc
744
745 Enable coverage-guided fuzzing code instrumentation.
746 Inserts a call to ``__sanitizer_cov_trace_pc`` into every basic block.
747
748 .. option:: -fsanitize-coverage=trace-cmp
749
750 Enable dataflow guided fuzzing code instrumentation.
751 Inserts a call to ``__sanitizer_cov_trace_cmp1``,
752 ``__sanitizer_cov_trace_cmp2``, ``__sanitizer_cov_trace_cmp4`` or
753 ``__sanitizer_cov_trace_cmp8`` for integral comparison with both operands
754 variable or ``__sanitizer_cov_trace_const_cmp1``,
755 ``__sanitizer_cov_trace_const_cmp2``,
756 ``__sanitizer_cov_trace_const_cmp4`` or
757 ``__sanitizer_cov_trace_const_cmp8`` for integral comparison with one
758 operand constant, ``__sanitizer_cov_trace_cmpf`` or
759 ``__sanitizer_cov_trace_cmpd`` for float or double comparisons and
760 ``__sanitizer_cov_trace_switch`` for switch statements.
761
762 .. option:: -fcf-protection=[full|branch|return|none|check]
763
764 Enable code instrumentation of control-flow transfers to increase
765 program security by checking that target addresses of control-flow
766 transfer instructions (such as indirect function call, function return,
767 indirect jump) are valid. This prevents diverting the flow of control
768 to an unexpected target. This is intended to protect against such
769 threats as Return-oriented Programming (ROP), and similarly
770 call/jmp-oriented programming (COP/JOP).
771
772 The value ``branch`` tells the compiler to implement checking of
773 validity of control-flow transfer at the point of indirect branch
774 instructions, i.e. call/jmp instructions. The value ``return``
775 implements checking of validity at the point of returning from a
776 function. The value ``full`` is an alias for specifying both
777 ``branch`` and ``return``. The value ``none`` turns off
778 instrumentation.
779
780 The value ``check`` is used for the final link with link-time
781 optimization (LTO). An error is issued if LTO object files are
782 compiled with different :option:`-fcf-protection` values. The
783 value ``check`` is ignored at the compile time.
784
785 The macro ``__CET__`` is defined when :option:`-fcf-protection` is
786 used. The first bit of ``__CET__`` is set to 1 for the value
787 ``branch`` and the second bit of ``__CET__`` is set to 1 for
788 the ``return``.
789
790 You can also use the :fn-attr:`nocf_check` attribute to identify
791 which functions and calls should be skipped from instrumentation
792 (see :ref:`function-attributes`).
793
794 Currently the x86 GNU/Linux target provides an implementation based
795 on Intel Control-flow Enforcement Technology (CET) which works for
796 i686 processor or newer.
797
798 .. option:: -fharden-compares
799
800 For every logical test that survives gimple optimizations and is
801 *not* the condition in a conditional branch (for example,
802 conditions tested for conditional moves, or to store in boolean
803 variables), emit extra code to compute and verify the reversed
804 condition, and to call ``__builtin_trap`` if the results do not
805 match. Use with :samp:`-fharden-conditional-branches` to cover all
806 conditionals.
807
808 .. option:: -fharden-conditional-branches
809
810 For every non-vectorized conditional branch that survives gimple
811 optimizations, emit extra code to compute and verify the reversed
812 condition, and to call ``__builtin_trap`` if the result is
813 unexpected. Use with :samp:`-fharden-compares` to cover all
814 conditionals.
815
816 .. option:: -fstack-protector
817
818 Emit extra code to check for buffer overflows, such as stack smashing
819 attacks. This is done by adding a guard variable to functions with
820 vulnerable objects. This includes functions that call ``alloca``, and
821 functions with buffers larger than or equal to 8 bytes. The guards are
822 initialized when a function is entered and then checked when the function
823 exits. If a guard check fails, an error message is printed and the program
824 exits. Only variables that are actually allocated on the stack are
825 considered, optimized away variables or variables allocated in registers
826 don't count.
827
828 .. option:: -fstack-protector-all
829
830 Like :option:`-fstack-protector` except that all functions are protected.
831
832 .. option:: -fstack-protector-strong
833
834 Like :option:`-fstack-protector` but includes additional functions to
835 be protected --- those that have local array definitions, or have
836 references to local frame addresses. Only variables that are actually
837 allocated on the stack are considered, optimized away variables or variables
838 allocated in registers don't count.
839
840 .. option:: -fstack-protector-explicit
841
842 Like :option:`-fstack-protector` but only protects those functions which
843 have the :fn-attr:`stack_protect` attribute.
844
845 .. option:: -fstack-check
846
847 Generate code to verify that you do not go beyond the boundary of the
848 stack. You should specify this flag if you are running in an
849 environment with multiple threads, but you only rarely need to specify it in
850 a single-threaded environment since stack overflow is automatically
851 detected on nearly all systems if there is only one stack.
852
853 Note that this switch does not actually cause checking to be done; the
854 operating system or the language runtime must do that. The switch causes
855 generation of code to ensure that they see the stack being extended.
856
857 You can additionally specify a string parameter: :samp:`no` means no
858 checking, :samp:`generic` means force the use of old-style checking,
859 :samp:`specific` means use the best checking method and is equivalent
860 to bare :option:`-fstack-check`.
861
862 Old-style checking is a generic mechanism that requires no specific
863 target support in the compiler but comes with the following drawbacks:
864
865 * Modified allocation strategy for large objects: they are always
866 allocated dynamically if their size exceeds a fixed threshold. Note this
867 may change the semantics of some code.
868
869 * Fixed limit on the size of the static frame of functions: when it is
870 topped by a particular function, stack checking is not reliable and
871 a warning is issued by the compiler.
872
873 * Inefficiency: because of both the modified allocation strategy and the
874 generic implementation, code performance is hampered.
875
876 Note that old-style stack checking is also the fallback method for
877 :samp:`specific` if no target support has been added in the compiler.
878
879 :samp:`-fstack-check=` is designed for Ada's needs to detect infinite recursion
880 and stack overflows. :samp:`specific` is an excellent choice when compiling
881 Ada code. It is not generally sufficient to protect against stack-clash
882 attacks. To protect against those you want :samp:`-fstack-clash-protection`.
883
884 .. option:: -fstack-clash-protection
885
886 Generate code to prevent stack clash style attacks. When this option is
887 enabled, the compiler will only allocate one page of stack space at a time
888 and each page is accessed immediately after allocation. Thus, it prevents
889 allocations from jumping over any stack guard page provided by the
890 operating system.
891
892 Most targets do not fully support stack clash protection. However, on
893 those targets :option:`-fstack-clash-protection` will protect dynamic stack
894 allocations. :option:`-fstack-clash-protection` may also provide limited
895 protection for static stack allocations if the target supports
896 :option:`-fstack-check=specific`.
897
898 .. option:: -fstack-limit-register={reg}
899
900 Generate code to ensure that the stack does not grow beyond a certain value,
901 either the value of a register or the address of a symbol. If a larger
902 stack is required, a signal is raised at run time. For most targets,
903 the signal is raised before the stack overruns the boundary, so
904 it is possible to catch the signal without taking special precautions.
905
906 For instance, if the stack starts at absolute address :samp:`0x80000000`
907 and grows downwards, you can use the flags
908 :option:`-fstack-limit-symbol=__stack_limit` and
909 :option:`-Wl,--defsym,__stack_limit=0x7ffe0000` to enforce a stack limit
910 of 128KB. Note that this may only work with the GNU linker.
911
912 You can locally override stack limit checking by using the
913 :fn-attr:`no_stack_limit` function attribute (see :ref:`function-attributes`).
914
915 .. option:: -fsplit-stack
916
917 Generate code to automatically split the stack before it overflows.
918 The resulting program has a discontiguous stack which can only
919 overflow if the program is unable to allocate any more memory. This
920 is most useful when running threaded programs, as it is no longer
921 necessary to calculate a good stack size to use for each thread. This
922 is currently only implemented for the x86 targets running
923 GNU/Linux.
924
925 When code compiled with :option:`-fsplit-stack` calls code compiled
926 without :option:`-fsplit-stack`, there may not be much stack space
927 available for the latter code to run. If compiling all code,
928 including library code, with :option:`-fsplit-stack` is not an option,
929 then the linker can fix up these calls so that the code compiled
930 without :option:`-fsplit-stack` always has a large stack. Support for
931 this is implemented in the gold linker in GNU binutils release 2.21
932 and later.
933
934 .. option:: -fvtable-verify=[std|preinit|none]
935
936 This option is only available when compiling C++ code.
937 It turns on (or off, if using :option:`-fvtable-verify=none`) the security
938 feature that verifies at run time, for every virtual call, that
939 the vtable pointer through which the call is made is valid for the type of
940 the object, and has not been corrupted or overwritten. If an invalid vtable
941 pointer is detected at run time, an error is reported and execution of the
942 program is immediately halted.
943
944 This option causes run-time data structures to be built at program startup,
945 which are used for verifying the vtable pointers.
946 The options :samp:`std` and :samp:`preinit`
947 control the timing of when these data structures are built. In both cases the
948 data structures are built before execution reaches ``main``. Using
949 :option:`-fvtable-verify=std` causes the data structures to be built after
950 shared libraries have been loaded and initialized.
951 :option:`-fvtable-verify=preinit` causes them to be built before shared
952 libraries have been loaded and initialized.
953
954 If this option appears multiple times in the command line with different
955 values specified, :samp:`none` takes highest priority over both :samp:`std` and
956 :samp:`preinit`; :samp:`preinit` takes priority over :samp:`std`.
957
958 .. option:: -fvtv-debug
959
960 When used in conjunction with :option:`-fvtable-verify=std` or
961 :option:`-fvtable-verify=preinit`, causes debug versions of the
962 runtime functions for the vtable verification feature to be called.
963 This flag also causes the compiler to log information about which
964 vtable pointers it finds for each class.
965 This information is written to a file named :samp:`vtv_set_ptr_data.log`
966 in the directory named by the environment variable :envvar:`VTV_LOGS_DIR`
967 if that is defined or the current working directory otherwise.
968
969 .. note::
970 This feature *appends* data to the log file. If you want a fresh log
971 file, be sure to delete any existing one.
972
973 .. option:: -fvtv-counts
974
975 This is a debugging flag. When used in conjunction with
976 :option:`-fvtable-verify=std` or :option:`-fvtable-verify=preinit`, this
977 causes the compiler to keep track of the total number of virtual calls
978 it encounters and the number of verifications it inserts. It also
979 counts the number of calls to certain run-time library functions
980 that it inserts and logs this information for each compilation unit.
981 The compiler writes this information to a file named
982 :samp:`vtv_count_data.log` in the directory named by the environment
983 variable :envvar:`VTV_LOGS_DIR` if that is defined or the current working
984 directory otherwise. It also counts the size of the vtable pointer sets
985 for each class, and writes this information to :samp:`vtv_class_set_sizes.log`
986 in the same directory.
987
988 .. note::
989 This feature *appends* data to the log files. To get fresh log
990 files, be sure to delete any existing ones.
991
992 .. option:: -finstrument-functions
993
994 Generate instrumentation calls for entry and exit to functions. Just
995 after function entry and just before function exit, the following
996 profiling functions are called with the address of the current
997 function and its call site. (On some platforms,
998 ``__builtin_return_address`` does not work beyond the current
999 function, so the call site information may not be available to the
1000 profiling functions otherwise.)
1001
1002 .. code-block:: c++
1003
1004 void __cyg_profile_func_enter (void *this_fn,
1005 void *call_site);
1006 void __cyg_profile_func_exit (void *this_fn,
1007 void *call_site);
1008
1009 The first argument is the address of the start of the current function,
1010 which may be looked up exactly in the symbol table.
1011
1012 This instrumentation is also done for functions expanded inline in other
1013 functions. The profiling calls indicate where, conceptually, the
1014 inline function is entered and exited. This means that addressable
1015 versions of such functions must be available. If all your uses of a
1016 function are expanded inline, this may mean an additional expansion of
1017 code size. If you use ``extern inline`` in your C code, an
1018 addressable version of such functions must be provided. (This is
1019 normally the case anyway, but if you get lucky and the optimizer always
1020 expands the functions inline, you might have gotten away without
1021 providing static copies.)
1022
1023 A function may be given the attribute ``no_instrument_function``, in
1024 which case this instrumentation is not done. This can be used, for
1025 example, for the profiling functions listed above, high-priority
1026 interrupt routines, and any functions from which the profiling functions
1027 cannot safely be called (perhaps signal handlers, if the profiling
1028 routines generate output or allocate memory).
1029 See :ref:`common-function-attributes`.
1030
1031 .. option:: -finstrument-functions-once
1032
1033 This is similar to :option:`-finstrument-functions`, but the profiling
1034 functions are called only once per instrumented function, i.e. the first
1035 profiling function is called after the first entry into the instrumented
1036 function and the second profiling function is called before the exit
1037 corresponding to this first entry.
1038
1039 The definition of ``once`` for the purpose of this option is a little
1040 vague because the implementation is not protected against data races.
1041 As a result, the implementation only guarantees that the profiling
1042 functions are called at *least* once per process and at *most*
1043 once per thread, but the calls are always paired, that is to say, if a
1044 thread calls the first function, then it will call the second function,
1045 unless it never reaches the exit of the instrumented function.
1046
1047 .. option:: -finstrument-functions-exclude-file-list={file},{file},...
1048
1049 Set the list of functions that are excluded from instrumentation (see
1050 the description of :option:`-finstrument-functions`). If the file that
1051 contains a function definition matches with one of :samp:`{file}`, then
1052 that function is not instrumented. The match is done on substrings:
1053 if the :samp:`{file}` parameter is a substring of the file name, it is
1054 considered to be a match.
1055
1056 For example:
1057
1058 :option:`-finstrument-functions-exclude-file-list=/bits/stl,include/sys`
1059 excludes any inline function defined in files whose pathnames
1060 contain :samp:`/bits/stl` or :samp:`include/sys`.
1061
1062 If, for some reason, you want to include letter :samp:`,` in one of
1063 :samp:`{sym}`, write :samp:`\\,`. For example,
1064 :option:`-finstrument-functions-exclude-file-list='\\,\\,tmp'`
1065 (note the single quote surrounding the option).
1066
1067 .. option:: -finstrument-functions-exclude-function-list={sym},{sym},...
1068
1069 This is similar to :option:`-finstrument-functions-exclude-file-list`,
1070 but this option sets the list of function names to be excluded from
1071 instrumentation. The function name to be matched is its user-visible
1072 name, such as ``vector<int> blah(const vector<int> &)``, not the
1073 internal mangled name (e.g., ``_Z4blahRSt6vectorIiSaIiEE``). The
1074 match is done on substrings: if the :samp:`{sym}` parameter is a substring
1075 of the function name, it is considered to be a match. For C99 and C++
1076 extended identifiers, the function name must be given in UTF-8, not
1077 using universal character names.
1078
1079 .. option:: -fpatchable-function-entry={N}[,{M}]
1080
1081 Generate :samp:`{N}` NOPs right at the beginning
1082 of each function, with the function entry point before the :samp:`{M}` th NOP.
1083 If :samp:`{M}` is omitted, it defaults to ``0`` so the
1084 function entry points to the address just at the first NOP.
1085 The NOP instructions reserve extra space which can be used to patch in
1086 any desired instrumentation at run time, provided that the code segment
1087 is writable. The amount of space is controllable indirectly via
1088 the number of NOPs; the NOP instruction used corresponds to the instruction
1089 emitted by the internal GCC back-end interface ``gen_nop``. This behavior
1090 is target-specific and may also depend on the architecture variant and/or
1091 other compilation options.
1092
1093 For run-time identification, the starting addresses of these areas,
1094 which correspond to their respective function entries minus :samp:`{M}`,
1095 are additionally collected in the ``__patchable_function_entries``
1096 section of the resulting binary.
1097
1098 Note that the value of ``__attribute__ ((patchable_function_entry
1099 (N,M)))`` takes precedence over command-line option
1100 :option:`-fpatchable-function-entry=N,M`. This can be used to increase
1101 the area size or to remove it completely on a single function.
1102 If ``N=0``, no pad location is recorded.
1103
1104 The NOP instructions are inserted at---and maybe before, depending on
1105 :samp:`{M}` ---the function entry address, even before the prologue. On
1106 PowerPC with the ELFv2 ABI, for a function with dual entry points,
1107 the local entry point is this function entry address.
1108
1109 The maximum value of :samp:`{N}` and :samp:`{M}` is 65535. On PowerPC with the
1110 ELFv2 ABI, for a function with dual entry points, the supported values
1111 for :samp:`{M}` are 0, 2, 6 and 14.