Movatterモバイル変換


[0]ホーム

URL:


Next:, Previous:, Up:GCC Command Options   [Contents][Index]


3.13 Program Instrumentation Options

GCC supports a number of command-line options that control addingrun-time instrumentation to the code it normally generates.For example, one purpose of instrumentation is collect profilingstatistics for use in finding program hot spots, code coverageanalysis, or profile-guided optimizations.Another class of program instrumentation is adding run-time checkingto detect programming errors like invalid pointerdereferences or out-of-bounds array accesses, as well as deliberatelyhostile attacks such as stack smashing or C++ vtable hijacking.There is also a general hook which can be used to implement otherforms of tracing or function-level instrumentation for debug orprogram analysis purposes.

-p
--profile
-fprofile
-pg

Generate extra code to write profile information suitable for theanalysis programprof (for-p,--profile,and-fprofile)orgprof(for-pg). You must use this option when compilingthe source files you want data about, and you must also use it whenlinking.

You can use the function attributeno_instrument_function tosuppress profiling of individual functions when compiling with these options.SeeCommon Function Attributes.

-fprofile-arcs

Add code so that program flowarcs are instrumented. Duringexecution the program records how many times each branch and call isexecuted and how many times it is taken or returns. On targets that supportconstructors with priority support, profiling properly handles constructors,destructors and C++ constructors (and destructors) of classes which are usedas a type of a global variable.

When the compiledprogram exits it saves this data to a file calledauxname.gcda for each source file. The data may be used forprofile-directed optimizations (-fbranch-probabilities), or fortest coverage analysis (-ftest-coverage). Each object file’sauxname is generated from the name of the output file, ifexplicitly specified and it is not the final executable, otherwise it isthe basename of the source file. In both cases any suffix is removed(e.g.foo.gcda for input filedir/foo.c, ordir/foo.gcda for output file specified as-o dir/foo.o).

Note that if a command line directly links source files, the corresponding.gcda files will be prefixed with the unsuffixed name of the output file.E.g.gcc a.c b.c -o binary would generatebinary-a.gcda andbinary-b.gcda files.

-fcondition-coverage

Add code so that program conditions are instrumented. During execution theprogram records what terms in a conditional contributes to a decision, whichcan be used to verify that all terms in a Boolean function are tested and havean independent effect on the outcome of a decision. The result can be readwithgcov --conditions.

-fpath-coverage

Add code so that the paths taken are tracked. During execution theprogram records the prime paths taken. The number of paths grows veryfast with complexity, and to avoid exploding compile times GCC will giveup instrumentation if the approximate number of paths exceeds the limitcontrolled by-fpath-coverage-limit. The result can be readwithgcov --prime-paths --prime-paths-lines --prime-paths-source,Seegcov prime paths example.

-fpath-coverage-limit=limit

The threshold at which point-fpath-coverage gives up oninstrumenting a function. This limit is approximate and conservative,as GCC uses a pessimistic heuristic which slightly overcounts therunning number of paths, and gives up if the threshold is reached beforefinding all the paths. This option is not for fine grained control overwhich functions to instrument - rather it is intended to limit theeffect of path explosion and keep compile times reasonable. The defaultis250000.

SeeData File Relocation to Support Cross-Profiling.

--coverage
-coverage

This option is used to compile and link code instrumented for coverageanalysis. The options-coverage and--coverage areequivalent; both are a synonym for-fprofile-arcs-ftest-coverage (when compiling) and-lgcov (whenlinking). See the documentation for those options for more details.

  • Compile the source files with-fprofile-arcs plus optimizationand code generation options. For test coverage analysis, use theadditional-ftest-coverage option. You do not need to profileevery source file in a program.
  • Compile the source files additionally with-fprofile-abs-pathto create absolute path names in the.gcno files. This allowsgcov to find the correct sources in projects where compilationsoccur with different working directories.
  • Link your object files with-lgcov or-fprofile-arcs(the latter implies the former).
  • Run the program on a representative workload to generate the arc profileinformation. This may be repeated any number of times. You can runconcurrent instances of your program, and provided that the file systemsupports locking, the data files will be correctly updated. Unlessa strict ISO C dialect option is in effect,fork calls aredetected and correctly handled without double counting.

    Moreover, an object file can be recompiled multiple timesand the corresponding.gcda file merges as long asthe source file and the compiler options are unchanged.

  • For profile-directed optimizations, compile the source files again withthe same optimization and code generation options plus-fbranch-probabilities (seeOptions thatControl Optimization).
  • For test coverage analysis, usegcov to produce human readableinformation from the.gcno and.gcda files. Refer to thegcov documentation for further information.

With-fprofile-arcs, for each function of your program GCCcreates a program flow graph, then finds a spanning tree for the graph.Only arcs that are not on the spanning tree have to be instrumented: thecompiler adds code to count the number of times that these arcs areexecuted. When an arc is the only exit or only entrance to a block, theinstrumentation code can be added to the block; otherwise, a new basicblock must be created to hold the instrumentation code.

With-fcondition-coverage, for each conditional in your program GCCcreates a bitset and records the exercised boolean values that have anindependent effect on the outcome of that expression.

With-fpath-coverage, GCC finds and enumerates and records thetaken prime paths of each function, unless the number of paths wouldexceed the limit controlled by-fpath-coverage-limit. If thelimit is exceeded the function is not instrumented as if-fpath-coverage was not used. A prime path is the longestsequence of unique blocks, except possibly the first and last, which isnot a subpath of any other path.

-ftest-coverage

Produce a notes file that thegcov code-coverage utility(seegcov—a Test Coverage Program) can use toshow program coverage. Each source file’s note file is calledauxname.gcno. Refer to the-fprofile-arcs optionabove for a description ofauxname and instructions on how togenerate test coverage data. Coverage data matches the source filesmore closely if you do not optimize.

-fprofile-abs-path

Automatically convert relative source file names to absolute path namesin the.gcno files. This allowsgcov to find the correctsources in projects where compilations occur with different workingdirectories.

-fprofile-dir=path

Set the directory to search for the profile data files in topath.This option affects only the profile data generated by-fprofile-generate,-ftest-coverage,-fprofile-arcsand used by-fprofile-use and-fbranch-probabilitiesand its related options. Both absolute and relative paths can be used.By default, GCC uses the current directory aspath, thus theprofile data file appears in the same directory as the object file.In order to prevent the file name clashing, if the object file name isnot an absolute path, we mangle the absolute path of thesourcename.gcda file and use it as the file name of a.gcda file. See details about the file naming in-fprofile-arcs.See similar option-fprofile-note.

When an executable is run in a massive parallel environment, it is recommendedto save profile to different folders. That can be done with variablesinpath that are exported during run-time:

%p

process ID.

%q{VAR}

value of environment variableVAR

-fprofile-generate
-fprofile-generate=path

Enable options usually used for instrumenting application to produceprofile useful for later recompilation with profile feedback basedoptimization. You must use-fprofile-generate both whencompiling and when linking your program.

The following options are enabled:-fprofile-arcs,-fprofile-values,-finline-functions, and-fipa-bit-cp.

Ifpath is specified, GCC looks at thepath to findthe profile feedback data files. See-fprofile-dir.

To optimize the program based on the collected profile information, use-fprofile-use. SeeOptions That Control Optimization, for more information.

-fprofile-info-section
-fprofile-info-section=name

Register the profile information in the specified section instead of using aconstructor/destructor. The section name isname if it is specified,otherwise the section name defaults to.gcov_info. A pointer to theprofile information generated by-fprofile-arcs is placed in thespecified section for each translation unit. This option disables the profileinformation registration through a constructor and it disables the profileinformation processing through a destructor. This option is not intended to beused in hosted environments such as GNU/Linux. It targets freestandingenvironments (for example embedded systems) with limited resources which do notsupport constructors/destructors or the C library file I/O.

The linker could collect the input sections in a continuous memory block anddefine start and end symbols. A GNU linker script example which defines alinker output section follows:

  .gcov_info      :  {    PROVIDE (__gcov_info_start = .);    KEEP (*(.gcov_info))    PROVIDE (__gcov_info_end = .);  }

The program could dump the profiling information registered in this linker setfor example like this:

#include <gcov.h>#include <stdio.h>#include <stdlib.h>extern const struct gcov_info *const __gcov_info_start[];extern const struct gcov_info *const __gcov_info_end[];static voiddump (const void *d, unsigned n, void *arg){  const unsigned char *c = d;  for (unsigned i = 0; i < n; ++i)    printf ("%02x", c[i]);}static voidfilename (const char *f, void *arg){  __gcov_filename_to_gcfn (f, dump, arg );}static void *allocate (unsigned length, void *arg){  return malloc (length);}static voiddump_gcov_info (void){  const struct gcov_info *const *info = __gcov_info_start;  const struct gcov_info *const *end = __gcov_info_end;  /* Obfuscate variable to prevent compiler optimizations.  */  __asm__ ("" : "+r" (info));  while (info != end)  {    void *arg = NULL;    __gcov_info_to_gcda (*info, filename, dump, allocate, arg);    putchar ('\n');    ++info;  }}intmain (void){  dump_gcov_info ();  return 0;}

Themerge-stream subcommand ofgcov-tool may be used todeserialize the data stream generated by the__gcov_filename_to_gcfn and__gcov_info_to_gcda functions and merge the profile information into.gcda files on the host filesystem.

-fprofile-note=path

Ifpath is specified, GCC saves.gcno file intopathlocation. If you combine the option with multiple source files,the.gcno file will be overwritten.

-fprofile-prefix-path=path

This option can be used in combination withprofile-generate=profile_dir andprofile-use=profile_dir to inform GCC where is the basedirectory of built source tree. By defaultprofile_dir will containfiles with mangled absolute paths of all object files in the built project.This is not desirable when directory used to build the instrumented binarydiffers from the directory used to build the binary optimized with profilefeedback because the profile data will not be found during the optimized build.In such setups-fprofile-prefix-path=path withpathpointing to the base directory of the build can be used to strip the irrelevantpart of the path and keep all file names relative to the main build directory.

-fprofile-prefix-map=old=new

When compiling files residing in directoryold, recordprofiling information (with--coverage)describing them as if the files resided indirectorynew instead.See also-ffile-prefix-map and-fcanon-prefix-map.

-fprofile-update=method

Alter the update method for an application instrumented for profilefeedback based optimization. Themethod argument should be one of‘single’, ‘atomic’ or ‘prefer-atomic’.The first one is useful for single-threaded applications,while the second one prevents profile corruption by emitting thread-safe code.

Warning: When an application does not properly join all threads(or creates an detached thread), a profile file can be still corrupted.

Using ‘prefer-atomic’ would be transformed either to ‘atomic’,when supported by a target, or to ‘single’ otherwise. The GCC driverautomatically selects ‘prefer-atomic’ when-pthreadis present in the command line, otherwise the default method is ‘single’.

If ‘atomic’ is selected, then the profile information is updated usingatomic operations on a best-effort basis. Ideally, the profile information isupdated through atomic operations in hardware. If the target platform does notsupport the required atomic operations in hardware, however,libatomicis available, then the profile information is updated through calls tolibatomic. If the target platform neither supports the required atomicoperations in hardware norlibatomic, then the profile information isnot atomically updated and a warning is issued. In this case, the obtainedprofiling information may be corrupt for multi-threaded applications.

For performance reasons, if 64-bit counters are used for the profilinginformation and the target platform only supports 32-bit atomic operations inhardware, then the performance critical profiling updates are done using two32-bit atomic operations for each counter update. If a signal interrupts thesetwo operations updating a counter, then the profiling information may be in aninconsistent state.

-fprofile-filter-files=regex

Instrument only functions from files whose name matchesany of the regular expressions (separated by semi-colons).

For example,-fprofile-filter-files=main\.c;module.*\.c will instrumentonlymain.c and all C files starting with ’module’.

-fprofile-exclude-files=regex

Instrument only functions from files whose name does not matchany of the regular expressions (separated by semi-colons).

For example,-fprofile-exclude-files=/usr/.* will prevent instrumentationof all files that are located in the/usr/ folder.

-fprofile-reproducible=[multithreaded|parallel-runs|serial]

Control level of reproducibility of profile gathered by-fprofile-generate. This makes it possible to rebuild programwith same outcome which is useful, for example, for distributionpackages.

With-fprofile-reproducible=serial the profile gathered by-fprofile-generate is reproducible provided the trained programbehaves the same at each invocation of the train run, it is notmulti-threaded and profile data streaming is always done in the sameorder. Note that profile streaming happens at the end of program run butalso beforefork function is invoked.

Note that it is quite common that execution counts of some part ofprograms depends, for example, on length of temporary file names ormemory space randomization (that may affect hash-table collision rate).Such non-reproducible part of programs may be annotated byno_instrument_function function attribute.gcov-dump with-l can be used to dump gathered data and verify that they areindeed reproducible.

With-fprofile-reproducible=parallel-runs collected profilestays reproducible regardless the order of streaming of the data intogcda files. This setting makes it possible to run multiple instances ofinstrumented program in parallel (such as withmake -j). Thisreduces quality of gathered data, in particular of indirect callprofiling.

-fsanitize=address

Enable AddressSanitizer, a fast memory error detector.Memory access instructions are instrumented to detectout-of-bounds and use-after-free bugs.The option enables-fsanitize-address-use-after-scope.Seehttps://github.com/google/sanitizers/wiki/AddressSanitizer formore details. The run-time behavior can be influenced using theASAN_OPTIONS environment variable. When set tohelp=1,the available options are shown at startup of the instrumented program. Seehttps://github.com/google/sanitizers/wiki/AddressSanitizerFlags#run-time-flagsfor a list of supported options.The option cannot be combined with-fsanitize=thread or-fsanitize=hwaddress. Note that the only targets-fsanitize=hwaddress is currently supported on are x86-64(only with-mlam=u48 or-mlam=u57 options) and AArch64, in bothcases only in ABIs with 64-bit pointers. Similarly,-fsanitize=memtag-stack is currently only supported on AArch64 ABIswith 64-bit pointers.

When compiling with-fsanitize=address, you should alsouse-g to produce more meaningful output.To get more accurate stack traces, it is possible to use options such as-O0,-O1, or-Og (which, for instance, preventmost function inlining),-fno-optimize-sibling-calls (which preventsoptimizing sibling and tail recursive calls; this option is implicit for-O0,-O1, or-Og), or-fno-ipa-icf (whichdisables Identical Code Folding for functions).Using-fno-omit-frame-pointer also improves stack traces.Since multiple runs of theprogram may yield backtraces with different addresses due to ASLR (AddressSpace Layout Randomization), it may be desirable to turn ASLR off. On Linux,this can be achieved with ‘setarch `uname -m` -R ./prog’.

-fsanitize=kernel-address

Enable AddressSanitizer for Linux kernel.Seehttps://github.com/google/kernel-sanitizers for more details.

-fsanitize=hwaddress

Enable Hardware-assisted AddressSanitizer, which uses a hardware ability toignore the top byte of a pointer to allow the detection of memory errors witha low memory overhead.Memory access instructions are instrumented to detect out-of-bounds anduse-after-free bugs.The option enables-fsanitize-address-use-after-scope.Seehttps://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.htmlfor more details. The run-time behavior can be influenced using theHWASAN_OPTIONS environment variable. When set tohelp=1,the available options are shown at startup of the instrumented program.The option cannot be combined with-fsanitize=thread or-fsanitize=address, and is currently only available on AArch64.

-fsanitize=kernel-hwaddress

Enable Hardware-assisted AddressSanitizer for compilation of the Linux kernel.Similar to-fsanitize=kernel-address but using an alternateinstrumentation method, and similar to-fsanitize=hwaddress but withinstrumentation differences necessary for compiling the Linux kernel.These differences are to avoid hwasan library initialization calls and toaccount for the stack pointer having a different value in its top byte.

Note: This option has different defaults than-fsanitize=hwaddress.Instrumenting the stack and alloca calls are not on by default.Using a random frame tag is not implemented for kernel instrumentation.

-fsanitize=memtag-stack

Use Memory Tagging Extension instructions instead of instrumentationto allow the detection of memory errors. Similar to HWASAN, it isalso a probabilistic method. This option is available only on thoseAArch64 architectures that support Memory Tagging Extensions.

-fsanitize=pointer-compare

Instrument comparison operation (<, <=, >, >=) with pointer operands.The option must be combined with either-fsanitize=kernel-address or-fsanitize=addressThe option cannot be combined with-fsanitize=thread.Note: By default the check is disabled at run time. To enable it,adddetect_invalid_pointer_pairs=2 to the environment variableASAN_OPTIONS. Usingdetect_invalid_pointer_pairs=1 detectsinvalid operation only when both pointers are non-null.

-fsanitize=pointer-subtract

Instrument subtraction with pointer operands.The option must be combined with either-fsanitize=kernel-address or-fsanitize=addressThe option cannot be combined with-fsanitize=thread.Note: By default the check is disabled at run time. To enable it,adddetect_invalid_pointer_pairs=2 to the environment variableASAN_OPTIONS. Usingdetect_invalid_pointer_pairs=1 detectsinvalid operation only when both pointers are non-null.

-fsanitize=shadow-call-stack

Enable ShadowCallStack, a security enhancement mechanism used to protectprograms against return address overwrites (e.g. stack buffer overflows.)It works by saving a function’s return address to a separately allocatedshadow call stack in the function prologue and restoring the return addressfrom the shadow call stack in the function epilogue. Instrumentation onlyoccurs in functions that need to save the return address to the stack.

Currently it only supports the aarch64 platform. It is specificallydesigned for linux kernels that enable the CONFIG_SHADOW_CALL_STACK option.For the user space programs, runtime support is not currently providedin libc and libgcc. Users who want to use this feature in user space needto provide their own support for the runtime. It should be noted thatthis may cause the ABI rules to be broken.

On aarch64, the instrumentation makes use of the platform registerx18.This generally means that any code that may run on the same thread as codecompiled with ShadowCallStack must be compiled with the flag-ffixed-x18, otherwise functions compiled without-ffixed-x18 might clobberx18 and so corrupt the shadowstack pointer.

Also, because there is no userspace runtime support, code compiled withShadowCallStack cannot use exception handling. Use-fno-exceptionsto turn off exceptions.

Seehttps://clang.llvm.org/docs/ShadowCallStack.html for moredetails.

-fsanitize=thread

Enable ThreadSanitizer, a fast data race detector.Memory access instructions are instrumented to detectdata race bugs. Seehttps://github.com/google/sanitizers/wiki#threadsanitizer for moredetails. The run-time behavior can be influenced using theTSAN_OPTIONSenvironment variable; seehttps://github.com/google/sanitizers/wiki/ThreadSanitizerFlags for a list ofsupported options.The option cannot be combined with-fsanitize=address,-fsanitize=leak.

When compiling with-fsanitize=thread, you should also use-g to produce more meaningful output.

Note that sanitized atomic builtins cannot throw exceptions whenoperating on invalid memory addresses with non-call exceptions(-fnon-call-exceptions).

-fsanitize=leak

Enable LeakSanitizer, a memory leak detector.This option only matters for linking of executables.The executable is linked against a library that overridesmallocand other allocator functions. Seehttps://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer for moredetails. The run-time behavior can be influenced using theLSAN_OPTIONS environment variable.The option cannot be combined with-fsanitize=thread.

-fsanitize=undefined

Enable UndefinedBehaviorSanitizer, a fast undefined behavior detector.Various computations are instrumented to detect undefined behaviorat runtime. Seehttps://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html for more details. The run-time behavior can be influenced using theUBSAN_OPTIONS environment variable. Current suboptions are:

-fsanitize=shift

This option enables checking that the result of a shift operation isnot undefined. Note that what exactly is considered undefined differsslightly between C and C++, as well as between ISO C90 and C99, etc.This option has two suboptions,-fsanitize=shift-base and-fsanitize=shift-exponent.

-fsanitize=shift-exponent

This option enables checking that the second argument of a shift operationis not negative and is smaller than the precision of the promoted firstargument.

-fsanitize=shift-base

If the second argument of a shift operation is within range, check that theresult of a shift operation is not undefined. Note that what exactly isconsidered undefined differs slightly between C and C++, as well as betweenISO C90 and C99, etc.

-fsanitize=integer-divide-by-zero

Detect integer division by zero.

-fsanitize=unreachable

With this option, the compiler turns the__builtin_unreachablecall into a diagnostics message call instead. When reaching the__builtin_unreachable call, the behavior is undefined.

-fsanitize=vla-bound

This option instructs the compiler to check that the size of a variablelength array is positive.

-fsanitize=null

This option enables pointer checking. Particularly, the applicationbuilt with this option turned on will issue an error message when ittries to dereference a NULL pointer, or if a reference (possibly anrvalue reference) is bound to a NULL pointer, or if a method is invokedon an object pointed by a NULL pointer.

-fsanitize=return

This option enables return statement checking. Programsbuilt with this option turned on will issue an error messagewhen the end of a non-void function is reached without actuallyreturning a value. This option works in C++ only.

-fsanitize=signed-integer-overflow

This option enables signed integer overflow checking. We check thatthe result of+,*, and both unary and binary-does not overflow in the signed arithmetics. This also detectsINT_MIN / -1 signed division. Note, integer promotionrules must be taken into account. That is, the following is not anoverflow:

signed char a = SCHAR_MAX;a++;
-fsanitize=bounds

This option enables instrumentation of array bounds. Various out of boundsaccesses are detected. Flexible array members, flexible array member-likearrays, and initializers of variables with static storage are notinstrumented, with the exception of flexible array member-like arraysfor which-fstrict-flex-arrays or-fstrict-flex-arrays=options orstrict_flex_array attributes say they shouldn’t be treatedlike flexible array member-like arrays.

-fsanitize=bounds-strict

This option enables strict instrumentation of array bounds. Most out of boundsaccesses are detected, including flexible array member-like arrays.Initializers of variables with static storage are not instrumented.

-fsanitize=alignment

This option enables checking of alignment of pointers when they aredereferenced, or when a reference is bound to insufficiently aligned target,or when a method or constructor is invoked on insufficiently aligned object.

-fsanitize=object-size

This option enables instrumentation of memory references using the__builtin_dynamic_object_size function. Various out of boundspointer accesses are detected.

-fsanitize=float-divide-by-zero

Detect floating-point division by zero. Unlike other similar options,-fsanitize=float-divide-by-zero is not enabled by-fsanitize=undefined, since floating-point division by zero canbe a legitimate way of obtaining infinities and NaNs.

-fsanitize=float-cast-overflow

This option enables floating-point type to integer conversion checking.We check that the result of the conversion does not overflow.Unlike other similar options,-fsanitize=float-cast-overflow isnot enabled by-fsanitize=undefined.This option does not work well withFE_INVALID exceptions enabled.

-fsanitize=nonnull-attribute

This option enables instrumentation of calls, checking whether null valuesare not passed to arguments marked as requiring a non-null value by thenonnull function attribute.

-fsanitize=returns-nonnull-attribute

This option enables instrumentation of return statements in functionsmarked withreturns_nonnull function attribute, to detect returningof null values from such functions.

-fsanitize=bool

This option enables instrumentation of loads from bool. If a value otherthan 0/1 is loaded, a run-time error is issued.

-fsanitize=enum

This option enables instrumentation of loads from an enum type. Ifa value outside the range of values for the enum type is loaded,a run-time error is issued.

-fsanitize=vptr

This option enables instrumentation of C++ member function calls, memberaccesses and some conversions between pointers to base and derived classes,to verify the referenced object has the correct dynamic type.

-fsanitize=pointer-overflow

This option enables instrumentation of pointer arithmetics. If the pointerarithmetics overflows, a run-time error is issued.

-fsanitize=builtin

This option enables instrumentation of arguments to selected builtinfunctions. If an invalid value is passed to such arguments, a run-timeerror is issued. E.g. passing 0 as the argument to__builtin_ctzor__builtin_clz invokes undefined behavior and is diagnosedby this option.

Note that sanitizers tend to increase the rate of false positivewarnings, most notably those around-Wmaybe-uninitialized.We recommend against combining-Werror and [the use of]sanitizers.

While-ftrapv causes traps for signed overflows to be emitted,-fsanitize=undefined gives a diagnostic message.This currently works only for the C family of languages.

-fno-sanitize=all

This option disables all previously enabled sanitizers.-fsanitize=all is not allowed, as some sanitizers cannot be usedtogether.

-fasan-shadow-offset=number

This option forces GCC to use custom shadow offset in AddressSanitizer checks.It is useful for experimenting with different shadow memory layouts inKernel AddressSanitizer.

-fsanitize-sections=s1,s2,...

Sanitize global variables in selected user-defined sections.si maycontain wildcards.

-fsanitize-recover[=opts]

-fsanitize-recover= controls error recovery mode for sanitizersmentioned in comma-separated list ofopts. Enabling this optionfor a sanitizer component causes it to attempt to continuerunning the program as if no error happened. This means multipleruntime errors can be reported in a single program run, and the exitcode of the program may indicate success even when errorshave been reported. The-fno-sanitize-recover= optioncan be used to alterthis behavior: only the first detected error is reportedand program then exits with a non-zero exit code.

Currently this feature only works for-fsanitize=undefined (and its suboptionsexcept for-fsanitize=unreachable and-fsanitize=return),-fsanitize=float-cast-overflow,-fsanitize=float-divide-by-zero,-fsanitize=bounds-strict,-fsanitize=kernel-address and-fsanitize=address.For these sanitizers error recovery is turned on by default,except-fsanitize=address, for which this feature is experimental.-fsanitize-recover=all and-fno-sanitize-recover=all is alsoaccepted, the former enables recovery for all sanitizers that support it,the latter disables recovery for all sanitizers that support it.

Even if a recovery mode is turned on the compiler side, it needs to be alsoenabled on the runtime library side, otherwise the failures are still fatal.The runtime library defaults tohalt_on_error=0 forThreadSanitizer and UndefinedBehaviorSanitizer, while default value forAddressSanitizer ishalt_on_error=1. This can be overridden throughsetting thehalt_on_error flag in the corresponding environment variable.

Syntax without an explicitopts parameter is deprecated. It isequivalent to specifying anopts list of:

undefined,float-cast-overflow,float-divide-by-zero,bounds-strict
-fsanitize-address-use-after-scope

Enable sanitization of local variables to detect use-after-scope bugs.The option sets-fstack-reuse to ‘none’.

-fsanitize-trap[=opts]

The-fsanitize-trap= option instructs the compiler toreport for sanitizers mentioned in comma-separated list ofoptsundefined behavior using__builtin_trap rather than alibubsanlibrary routine. If this option is enabled for certain sanitizer,it takes precedence over the-fsanitizer-recover= for thatsanitizer,__builtin_trap will be emitted and be fatal regardlessof whether recovery is enabled or disabled using-fsanitize-recover=.

The advantage of this is that thelibubsan library is not neededand is not linked in, so this is usable even in freestanding environments.

Currently this feature works with-fsanitize=undefined (and its suboptionsexcept for-fsanitize=vptr),-fsanitize=float-cast-overflow,-fsanitize=float-divide-by-zero and-fsanitize=bounds-strict.-fsanitize-trap=all can be alsospecified, which enables it forundefined suboptions,-fsanitize=float-cast-overflow,-fsanitize=float-divide-by-zero and-fsanitize=bounds-strict.If-fsanitize-trap=undefined or-fsanitize-trap=all is usedand-fsanitize=vptr is enabled on the command line, theinstrumentation is silently ignored as the instrumentation always needslibubsan support,-fsanitize-trap=vptr is not allowed.

-fsanitize-undefined-trap-on-error

The-fsanitize-undefined-trap-on-error option is deprecatedequivalent of-fsanitize-trap=all.

-fsanitize-coverage=trace-pc

Enable coverage-guided fuzzing code instrumentation.Inserts a call to__sanitizer_cov_trace_pc into every basic block.

-fsanitize-coverage=trace-cmp

Enable dataflow guided fuzzing code instrumentation.Inserts a call to__sanitizer_cov_trace_cmp1,__sanitizer_cov_trace_cmp2,__sanitizer_cov_trace_cmp4 or__sanitizer_cov_trace_cmp8 for integral comparison with both operandsvariable or__sanitizer_cov_trace_const_cmp1,__sanitizer_cov_trace_const_cmp2,__sanitizer_cov_trace_const_cmp4 or__sanitizer_cov_trace_const_cmp8 for integral comparison with oneoperand constant,__sanitizer_cov_trace_cmpf or__sanitizer_cov_trace_cmpd for float or double comparisons and__sanitizer_cov_trace_switch for switch statements.

-fcf-protection=[full|branch|return|none|check]
-fcf-protection

Enable code instrumentation to increaseprogram security by checking that target addresses of control-flowtransfer instructions (such as indirect function call, function return,indirect jump) are valid. This prevents diverting the flow of controlto an unexpected target. This is intended to protect against suchthreats as Return-oriented Programming (ROP), and similarlycall/jmp-oriented programming (COP/JOP).

The-fcf-protection= keywords are interpreted as follows.

The valuebranch tells the compiler to implement checking ofvalidity of control-flow transfer at the point of indirect branchinstructions, i.e. call/jmp instructions.

The valuereturn implements checking of validity at the point ofreturning from a function.

The valuefull is an alias for specifying bothbranch andreturn.

The valuecheck is used for the final link with link-timeoptimization (LTO). An error is issued if LTO object files arecompiled with different-fcf-protection values. Thevaluecheck is ignored at the compile time.

The valuenone turns off instrumentation.

-fcf-protection is an alias for-fcf-protection=full.To override a previous-fcf-protection option on the commandline, add-fcf-protection=none and then-fcf-protection=kind.

The macro__CET__ is defined when-fcf-protection isused. The first bit of__CET__ is set to 1 for the valuebranch and the second bit of__CET__ is set to 1 forthereturn.

You can also use thenocf_check attribute to identifywhich functions and calls should be skipped from instrumentation(seeDeclaring Attributes of Functions).

Currently the x86 GNU/Linux target provides an implementation basedon Intel Control-flow Enforcement Technology (CET) which works fori686 processor or newer.

-fharden-compares

For every logical test that survives gimple optimizations and isnot the condition in a conditional branch (for example,conditions tested for conditional moves, or to store in booleanvariables), emit extra code to compute and verify the reversedcondition, and to call__builtin_trap if the results do notmatch. Use with ‘-fharden-conditional-branches’ to cover allconditionals.

-fharden-conditional-branches

For every non-vectorized conditional branch that survives gimpleoptimizations, emit extra code to compute and verify the reversedcondition, and to call__builtin_trap if the result isunexpected. Use with ‘-fharden-compares’ to cover allconditionals.

-fharden-control-flow-redundancy

Emit extra code to set booleans when entering basic blocks, and toverify and trap, at function exits, when the booleans do not form anexecution path that is compatible with the control flow graph.

Verification takes place before returns, before mandatory tail calls(see below) and, optionally, before escaping exceptions with-fhardcfr-check-exceptions, before returning calls with-fhardcfr-check-returning-calls, and before noreturn calls with-fhardcfr-check-noreturn-calls).

Tail call optimization takes place too late to affect control flowredundancy, but calls annotated as mandatory tail calls by languagefront-ends, and any calls marked early enough as potential tail callswould also have verification issued before the call, but thesepossibilities are merely theoretical, as these conditions can only bemet when using custom compiler plugins.

-fhardcfr-skip-leaf

Disable-fharden-control-flow-redundancy in leaf functions.

-fhardcfr-check-exceptions

When-fharden-control-flow-redundancy is active, check therecorded execution path against the control flow graph at exceptionescape points, as if the function body was wrapped with a cleanuphandler that performed the check and reraised. This option is enabledby default; use-fno-hardcfr-check-exceptions to disable it.

-fhardcfr-check-returning-calls

When-fharden-control-flow-redundancy is active, check therecorded execution path against the control flow graph before anyfunction call immediately followed by a return of its result, if any, soas to not prevent tail-call optimization, whether or not it isultimately optimized to a tail call.

This option is enabled by default whenever sibling call optimizationsare enabled (see-foptimize-sibling-calls), but it can beenabled (or disabled, using its negated form) explicitly, regardless ofthe optimizations.

-fhardcfr-check-noreturn-calls=[always|no-xthrow|nothrow|never]

When-fharden-control-flow-redundancy is active, check therecorded execution path against the control flow graph beforenoreturn calls, either all of them (always), those thataren’t expected to return control to the caller through an exception(no-xthrow, the default), those that may not return control tothe caller through an exception either (nothrow), or none ofthem (never).

Checking before anoreturn function that may return control tothe caller through an exception may cause checking to be performed morethan once, if the exception is caught in the caller, whether by ahandler or a cleanup. When-fhardcfr-check-exceptions is alsoenabled, the compiler will avoid associating anoreturn call withthe implicitly-added cleanup handler, since it would be redundant withthe check performed before the call, but other handlers or cleanups inthe function, if activated, will modify the recorded execution path andcheck it again when another checkpoint is hit. The checkpoint may evenbe anothernoreturn call, so checking may end up performedmultiple times.

Various optimizers may cause calls to be marked asnoreturnand/ornothrow, even in the absence of the correspondingattributes, which may affect the placement of checks before calls, aswell as the addition of implicit cleanup handlers for them. Thisunpredictability, and the fact that raising and reraising exceptionsfrequently amounts to implicitly callingnoreturn functions, havemadeno-xthrow the default setting for this option: it excludesfrom thenoreturn treatment only internal functions used to(re)raise exceptions, that are not affected by these optimizations.

-fhardened

Enable a set of flags for C and C++ that improve the security of thegenerated code without affecting its ABI. The precise flags enabledmay change between major releases of GCC, but are currently:

-D_FORTIFY_SOURCE=3-D_GLIBCXX_ASSERTIONS-ftrivial-auto-var-init=zero-fPIE  -pie  -Wl,-z,relro,-z,now-fstack-protector-strong-fstack-clash-protection-fcf-protection=full(x86 GNU/Linux only)

The list of options enabled by-fhardened can be generated usingthe--help=hardened option.

When the system glibc is older than 2.35,-D_FORTIFY_SOURCE=2is used instead.

This option is intended to be used in production builds, not merelyin debug builds.

Currently,-fhardened is only supported on GNU/Linux targets.

-fhardened only enables a particular option if it wasn’talready specified anywhere on the command line. For instance,-fhardened-fstack-protector will only enable-fstack-protector, but not-fstack-protector-strong.

-fstack-protector

Emit extra code to check for buffer overflows, such as stack smashingattacks. This is done by adding a guard variable to functions withvulnerable objects. This includes functions that callalloca, andfunctions with buffers larger than or equal to 8 bytes. The guards areinitialized when a function is entered and then checked when the functionexits. If a guard check fails, an error message is printed and the programexits. Only variables that are actually allocated on the stack areconsidered, optimized away variables or variables allocated in registersdon’t count.

-fstack-protector-all

Like-fstack-protector except that all functions are protected.

-fstack-protector-strong

Like-fstack-protector but includes additional functions tobe protected — those that have local array definitions, or havereferences to local frame addresses. Only variables that are actuallyallocated on the stack are considered, optimized away variables or variablesallocated in registers don’t count.

-fstack-protector-explicit

Like-fstack-protector but only protects those functions whichhave thestack_protect attribute.

-fstack-check

Generate code to verify that you do not go beyond the boundary of thestack. You should specify this flag if you are running in anenvironment with multiple threads, but you only rarely need to specify it ina single-threaded environment since stack overflow is automaticallydetected on nearly all systems if there is only one stack.

Note that this switch does not actually cause checking to be done; theoperating system or the language runtime must do that. The switch causesgeneration of code to ensure that they see the stack being extended.

You can additionally specify a string parameter: ‘no’ means nochecking, ‘generic’ means force the use of old-style checking,‘specific’ means use the best checking method and is equivalentto bare-fstack-check.

Old-style checking is a generic mechanism that requires no specifictarget support in the compiler but comes with the following drawbacks:

  1. Modified allocation strategy for large objects: they are alwaysallocated dynamically if their size exceeds a fixed threshold. Note thismay change the semantics of some code.
  2. Fixed limit on the size of the static frame of functions: when it istopped by a particular function, stack checking is not reliable anda warning is issued by the compiler.
  3. Inefficiency: because of both the modified allocation strategy and thegeneric implementation, code performance is hampered.

Note that old-style stack checking is also the fallback method for‘specific’ if no target support has been added in the compiler.

-fstack-check=’ is designed for Ada’s needs to detect infinite recursionand stack overflows. ‘specific’ is an excellent choice when compilingAda code. It is not generally sufficient to protect against stack-clashattacks. To protect against those you want ‘-fstack-clash-protection’.

-fstack-clash-protection

Generate code to prevent stack clash style attacks. When this option isenabled, the compiler will only allocate one page of stack space at a timeand each page is accessed immediately after allocation. Thus, it preventsallocations from jumping over any stack guard page provided by theoperating system.

Most targets do not fully support stack clash protection. However, onthose targets-fstack-clash-protection will protect dynamic stackallocations.-fstack-clash-protection may also provide limitedprotection for static stack allocations if the target supports-fstack-check=specific.

-fstack-limit-register=reg
-fstack-limit-symbol=sym
-fno-stack-limit

Generate code to ensure that the stack does not grow beyond a certain value,either the value of a register or the address of a symbol. If a largerstack is required, a signal is raised at run time. For most targets,the signal is raised before the stack overruns the boundary, soit is possible to catch the signal without taking special precautions.

For instance, if the stack starts at absolute address ‘0x80000000’and grows downwards, you can use the flags-fstack-limit-symbol=__stack_limit and-Wl,--defsym,__stack_limit=0x7ffe0000 to enforce a stack limitof 128KB. Note that this may only work with the GNU linker.

You can locally override stack limit checking by using theno_stack_limit function attribute (seeDeclaring Attributes of Functions).

-fsplit-stack

Generate code to automatically split the stack before it overflows.The resulting program has a discontiguous stack which can onlyoverflow if the program is unable to allocate any more memory. Thisis most useful when running threaded programs, as it is no longernecessary to calculate a good stack size to use for each thread. Thisis currently only implemented for the x86 targets runningGNU/Linux.

When code compiled with-fsplit-stack calls code compiledwithout-fsplit-stack, there may not be much stack spaceavailable for the latter code to run. If compiling all code,including library code, with-fsplit-stack is not an option,then the linker can fix up these calls so that the code compiledwithout-fsplit-stack always has a large stack. Support forthis is implemented in the gold linker in GNU Binutils release 2.21and later.

-fstrub=disable

Disable stack scrubbing entirely, ignoring anystrub attributes.See SeeCommon Type Attributes.

-fstrub=strict

Functions default tostrub modedisabled, and applystrictly the restriction that only functions associated withstrub-callable modes (at-calls,callable andalways_inlineinternal) arecallable by functionswithstrub-enabled modes (at-calls andinternal).

-fstrub=relaxed

Restore the default stack scrub (strub) setting, namely,strub is only enabled as required bystrub attributesassociated with function and data types.Relaxed means thatstrub contexts are only prevented from calling functions explicitlyassociated withstrub modedisabled. This option is onlyuseful to override other-fstrub=* options that precede it inthe command line.

-fstrub=at-calls

Enableat-callsstrub mode where viable. The primary useof this option is for testing. It exercises thestrub machineryin scenarios strictly local to a translation unit. Thisstrubmode modifies function interfaces, so any function that is visible toother translation units, or that has its address taken, willnotbe affected by this option. Optimization options may also affectviability. See thestrub attribute documentation for details onviability and eligibility requirements.

-fstrub=internal

Enableinternalstrub mode where viable. The primary useof this option is for testing. This option is intended to exercisethoroughly parts of thestrub machinery that implement the lessefficient, but interface-preservingstrub mode. Functions thatwould not be affected by this option are quite uncommon.

-fstrub=all

Enable somestrub mode where viable. When both strub modes areviable,at-calls is preferred.-fdump-ipa-strubm addsfunction attributes that tell which mode was selected for each function.The primary use of this option is for testing, to exercise thoroughlythestrub machinery.

-fvtable-verify=[std|preinit|none]

This option is only available when compiling C++ code.It turns on (or off, if using-fvtable-verify=none) the securityfeature that verifies at run time, for every virtual call, thatthe vtable pointer through which the call is made is valid for the type ofthe object, and has not been corrupted or overwritten. If an invalid vtablepointer is detected at run time, an error is reported and execution of theprogram is immediately halted.

This option causes run-time data structures to be built at program startup,which are used for verifying the vtable pointers.The options ‘std’ and ‘preinit’control the timing of when these data structures are built. In both cases thedata structures are built before execution reachesmain. Using-fvtable-verify=std causes the data structures to be built aftershared libraries have been loaded and initialized.-fvtable-verify=preinit causes them to be built before sharedlibraries have been loaded and initialized.

If this option appears multiple times in the command line with differentvalues specified, ‘none’ takes highest priority over both ‘std’ and‘preinit’; ‘preinit’ takes priority over ‘std’.

-fvtv-debug

When used in conjunction with-fvtable-verify=std or-fvtable-verify=preinit, causes debug versions of theruntime functions for the vtable verification feature to be called.This flag also causes the compiler to log information about whichvtable pointers it finds for each class.This information is written to a file namedvtv_set_ptr_data.login the directory named by the environment variableVTV_LOGS_DIRif that is defined or the current working directory otherwise.

Note: This featureappends data to the log file. If you want a fresh logfile, be sure to delete any existing one.

-fvtv-counts

This is a debugging flag. When used in conjunction with-fvtable-verify=std or-fvtable-verify=preinit, thiscauses the compiler to keep track of the total number of virtual callsit encounters and the number of verifications it inserts. It alsocounts the number of calls to certain run-time library functionsthat it inserts and logs this information for each compilation unit.The compiler writes this information to a file namedvtv_count_data.log in the directory named by the environmentvariableVTV_LOGS_DIR if that is defined or the current workingdirectory otherwise. It also counts the size of the vtable pointer setsfor each class, and writes this information tovtv_class_set_sizes.login the same directory.

Note: This featureappends data to the log files. To get fresh logfiles, be sure to delete any existing ones.

-finstrument-functions

Generate instrumentation calls for entry and exit to functions. Justafter function entry and just before function exit, the followingprofiling functions are called with the address of the currentfunction and its call site. (On some platforms,__builtin_return_address does not work beyond the currentfunction, so the call site information may not be available to theprofiling functions otherwise.)

void __cyg_profile_func_enter (void *this_fn,                               void *call_site);void __cyg_profile_func_exit  (void *this_fn,                               void *call_site);

The first argument is the address of the start of the current function,which may be looked up exactly in the symbol table.

This instrumentation is also done for functions expanded inline in otherfunctions. The profiling calls indicate where, conceptually, theinline function is entered and exited. This means that addressableversions of such functions must be available. If all your uses of afunction are expanded inline, this may mean an additional expansion ofcode size. If you useextern inline in your C code, anaddressable version of such functions must be provided. (This isnormally the case anyway, but if you get lucky and the optimizer alwaysexpands the functions inline, you might have gotten away withoutproviding static copies.)

A function may be given the attributeno_instrument_function, inwhich case this instrumentation is not done. This can be used, forexample, for the profiling functions listed above, high-priorityinterrupt routines, and any functions from which the profiling functionscannot safely be called (perhaps signal handlers, if the profilingroutines generate output or allocate memory).SeeCommon Function Attributes.

-finstrument-functions-once

This is similar to-finstrument-functions, but the profilingfunctions are called only once per instrumented function, i.e. the firstprofiling function is called after the first entry into the instrumentedfunction and the second profiling function is called before the exitcorresponding to this first entry.

The definition ofonce for the purpose of this option is a littlevague because the implementation is not protected against data races.As a result, the implementation only guarantees that the profilingfunctions are called atleast once per process and atmostonce per thread, but the calls are always paired, that is to say, if athread calls the first function, then it will call the second function,unless it never reaches the exit of the instrumented function.

-finstrument-functions-exclude-file-list=file,file,…

Set the list of functions that are excluded from instrumentation (seethe description of-finstrument-functions). If the file thatcontains a function definition matches with one offile, thenthat function is not instrumented. The match is done on substrings:if thefile parameter is a substring of the file name, it isconsidered to be a match.

For example:

-finstrument-functions-exclude-file-list=/bits/stl,include/sys

excludes any inline function defined in files whose pathnamescontain/bits/stl orinclude/sys.

If, for some reason, you want to include letter ‘,’ in one ofsym, write ‘\,’. For example,-finstrument-functions-exclude-file-list='\,\,tmp'(note the single quote surrounding the option).

-finstrument-functions-exclude-function-list=sym,sym,…

This is similar to-finstrument-functions-exclude-file-list,but this option sets the list of function names to be excluded frominstrumentation. The function name to be matched is its user-visiblename, such asvector<int> blah(const vector<int> &), not theinternal mangled name (e.g.,_Z4blahRSt6vectorIiSaIiEE). Thematch is done on substrings: if thesym parameter is a substringof the function name, it is considered to be a match. For C99 and C++extended identifiers, the function name must be given in UTF-8, notusing universal character names.

-fpatchable-function-entry=N[,M]

GenerateN NOPs right at the beginningof each function, with the function entry point before theMth NOP.IfM is omitted, it defaults to0 so thefunction entry points to the address just at the first NOP.The NOP instructions reserve extra space which can be used to patch inany desired instrumentation at run time, provided that the code segmentis writable. The amount of space is controllable indirectly viathe number of NOPs; the NOP instruction used corresponds to the instructionemitted by the internal GCC back-end interfacegen_nop. This behavioris target-specific and may also depend on the architecture variant and/orother compilation options.

For run-time identification, the starting addresses of these areas,which correspond to their respective function entries minusM,are additionally collected in the__patchable_function_entriessection of the resulting binary.

Note that the value of__attribute__ ((patchable_function_entry(N,M))) takes precedence over command-line option-fpatchable-function-entry=N,M. This can be used to increasethe area size or to remove it completely on a single function.IfN=0, no pad location is recorded.

The NOP instructions are inserted at—and maybe before, depending onM—the function entry address, even before the prologue. OnPowerPC with the ELFv2 ABI, for a function with dual entry points,the local entry point is this function entry address by default. Seethe-msplit-patch-nops option to change this.

The maximum value ofN andM is 65535. On PowerPC with theELFv2 ABI, for a function with dual entry points, the supported valuesforM are 0, 2, 6 and 14 when not using-msplit-patch-nops.


Next:Options Controlling the Preprocessor, Previous:Options That Control Optimization, Up:GCC Command Options   [Contents][Index]


[8]ページ先頭

©2009-2026 Movatter.jp