table of contents
- NAME
- SYNOPSIS
- DESCRIPTION
- TOOL SELECTION OPTIONS
- BASIC OPTIONS
- ERROR-RELATED OPTIONS
- MALLOC()-RELATED OPTIONS
- UNCOMMON OPTIONS
- DEBUGGING VALGRIND OPTIONS
- MEMCHECK OPTIONS
- CACHEGRIND OPTIONS
- CALLGRIND OPTIONS
- HELGRIND OPTIONS
- DRD OPTIONS
- MASSIF OPTIONS
- BBV OPTIONS
- LACKEY OPTIONS
- SEE ALSO
- AUTHOR
- NOTES
- bullseye 1:3.16.1-1
- testing 1:3.19.0-1
- unstable 1:3.19.0-1
- experimental 1:3.20.0-1
VALGRIND(1) | valgrind | VALGRIND(1) |
NAME¶
valgrind - a suite of tools for debugging and profiling programs
SYNOPSIS¶
valgrind [valgrind-options] [your-program] [your-program-options]
DESCRIPTION¶
Valgrind is a flexible program for debugging and profiling Linux executables. It consists of a core, which provides a synthetic CPU in software, and a series of debugging and profiling tools. The architecture is modular, so that new tools can be created easily and without disturbing the existing structure.
Some of the options described below work with all Valgrind tools, and some only work with a few or one. The section MEMCHECK OPTIONS and those below it describe tool-specific options.
This manual page covers only basic usage and options. For more comprehensive information, please see the HTML documentation on your system: $INSTALL/share/doc/valgrind/html/index.html, or online: http://www.valgrind.org/docs/manual/index.html.
TOOL SELECTION OPTIONS¶
The single most important option.
--tool=<toolname> [default: memcheck]
BASIC OPTIONS¶
These options work with all tools.
-h --help
--help-debug
--version
-q, --quiet
-v, --verbose
--trace-children=<yes|no> [default: no]
Note that Valgrind does trace into the child of a fork (it would be difficult not to, since fork makes an identical copy of a process), so this option is arguably badly named. However, most children of fork calls immediately call exec anyway.
--trace-children-skip=patt1,patt2,...
This can be useful for pruning uninteresting branches from a tree of processes being run on Valgrind. But you should be careful when using it. When Valgrind skips tracing into an executable, it doesn't just skip tracing that executable, it also skips tracing any of that executable's child processes. In other words, the flag doesn't merely cause tracing to stop at the specified executables -- it skips tracing of entire process subtrees rooted at any of the specified executables.
--trace-children-skip-by-arg=patt1,patt2,...
--child-silent-after-fork=<yes|no> [default: no]
--vgdb=<no|yes|full> [default: yes]
If the embedded gdbserver is enabled but no gdb is currently being used, the vgdb command line utility can send "monitor commands" to Valgrind from a shell. The Valgrind core provides a set of Valgrind monitor commands. A tool can optionally provide tool specific monitor commands, which are documented in the tool specific chapter.
--vgdb-error=<number> [default: 999999999]
--vgdb-stop-at=<set> [default: none]
The values startup exit valgrindabexit respectively indicate to invoke gdbserver before your program is executed, after the last instruction of your program, on Valgrind abnormal exit (e.g. internal error, out of memory, ...).
Note: startup and --vgdb-error=0 will both cause Valgrind gdbserver to be invoked before your program is executed. The --vgdb-error=0 will in addition cause your program to stop on all subsequent errors.
--track-fds=<yes|no> [default: no]
--time-stamp=<yes|no> [default: no]
--log-fd=<number> [default: 2, stderr]
--log-file=<filename>
%p is replaced with the current process ID. This is very useful for program that invoke multiple processes. WARNING: If you use --trace-children=yes and your program invokes multiple processes OR your program forks without calling exec afterwards, and you don't use this specifier (or the %q specifier below), the Valgrind output from all those processes will go into one file, possibly jumbled up, and possibly incomplete. Note: If the program forks and calls exec afterwards, Valgrind output of the child from the period between fork and exec will be lost. Fortunately this gap is really tiny for most programs; and modern programs use posix_spawn anyway.
%n is replaced with a file sequence number unique for this process. This is useful for processes that produces several files from the same filename template.
%q{FOO} is replaced with the contents of the environment variable FOO. If the {FOO} part is malformed, it causes an abort. This specifier is rarely needed, but very useful in certain circumstances (eg. when running MPI programs). The idea is that you specify a variable which will be set differently for each process in the job, for example BPROC_RANK or whatever is applicable in your MPI setup. If the named environment variable is not set, it causes an abort. Note that in some shells, the { and } characters may need to be escaped with a backslash.
%% is replaced with %.
If an % is followed by any other character, it causes an abort.
If the file name specifies a relative file name, it is put in the program's initial working directory: this is the current directory when the program started its execution after the fork or after the exec. If it specifies an absolute file name (ie. starts with '/') then it is put there.
--log-socket=<ip-address:port-number>
ERROR-RELATED OPTIONS¶
These options are used by all tools that can report errors, e.g. Memcheck, but not Cachegrind.
--xml=<yes|no> [default: no]
Less important messages will still be printed in plain text, but because the XML output and plain text output are sent to different output channels (the destination of the plain text output is still controlled by --log-fd, --log-file and --log-socket) this should not cause problems.
This option is aimed at making life easier for tools that consume Valgrind's output as input, such as GUI front ends. Currently this option works with Memcheck, Helgrind and DRD. The output format is specified in the file docs/internals/xml-output-protocol4.txt in the source tree for Valgrind 3.5.0 or later.
The recommended options for a GUI to pass, when requesting XML output, are: --xml=yes to enable XML output, --xml-file to send the XML output to a (presumably GUI-selected) file, --log-file to send the plain text output to a second GUI-selected file, --child-silent-after-fork=yes, and -q to restrict the plain text output to critical error messages created by Valgrind itself. For example, failure to read a specified suppressions file counts as a critical error message. In this way, for a successful run the text output file will be empty. But if it isn't empty, then it will contain important information which the GUI user should be made aware of.
--xml-fd=<number> [default: -1, disabled]
--xml-file=<filename>
--xml-socket=<ip-address:port-number>
--xml-user-comment=<string>
--demangle=<yes|no> [default: yes]
An important fact about demangling is that function names mentioned in suppressions files should be in their mangled form. Valgrind does not demangle function names when searching for applicable suppressions, because to do otherwise would make suppression file contents dependent on the state of Valgrind's demangling machinery, and also slow down suppression matching.
--num-callers=<number> [default: 12]
The maximum value for this is 500. Note that higher settings will make Valgrind run a bit more slowly and take a bit more memory, but can be useful when working with programs with deeply-nested call chains.
--unw-stack-scan-thresh=<number> [default: 0] , --unw-stack-scan-frames=<number> [default: 5]
These flags enable and control stack unwinding by stack scanning. When the normal stack unwinding mechanisms -- usage of Dwarf CFI records, and frame-pointer following -- fail, stack scanning may be able to recover a stack trace.
Note that stack scanning is an imprecise, heuristic mechanism that may give very misleading results, or none at all. It should be used only in emergencies, when normal unwinding fails, and it is important to nevertheless have stack traces.
Stack scanning is a simple technique: the unwinder reads words from the stack, and tries to guess which of them might be return addresses, by checking to see if they point just after ARM or Thumb call instructions. If so, the word is added to the backtrace.
The main danger occurs when a function call returns, leaving its return address exposed, and a new function is called, but the new function does not overwrite the old address. The result of this is that the backtrace may contain entries for functions which have already returned, and so be very confusing.
A second limitation of this implementation is that it will scan only the page (4KB, normally) containing the starting stack pointer. If the stack frames are large, this may result in only a few (or not even any) being present in the trace. Also, if you are unlucky and have an initial stack pointer near the end of its containing page, the scan may miss all interesting frames.
By default stack scanning is disabled. The normal use case is to ask for it when a stack trace would otherwise be very short. So, to enable it, use --unw-stack-scan-thresh=number. This requests Valgrind to try using stack scanning to "extend" stack traces which contain fewer than number frames.
If stack scanning does take place, it will only generate at most the number of frames specified by --unw-stack-scan-frames. Typically, stack scanning generates so many garbage entries that this value is set to a low value (5) by default. In no case will a stack trace larger than the value specified by --num-callers be created.
--error-limit=<yes|no> [default: yes]
--error-exitcode=<number> [default: 0]
--exit-on-first-error=<yes|no> [default: no]
--error-markers=<begin>,<end> [default: none]
Such marker lines facilitate searching for errors and/or extracting errors in an output file that contain valgrind errors mixed with the program output.
Note that empty markers are accepted. So, only using a begin (or an end) marker is possible.
--show-error-list=no|yes [default: no]
Note that at verbosity 2 and above, valgrind automatically shows the list of detected errors and the list of used suppressions at exit, unless --show-error-list=no is selected.
-s
--sigill-diagnostics=<yes|no> [default: yes]
When enabled, a warning message will be printed, along with some diagnostics, whenever an instruction is encountered that Valgrind cannot decode or translate, before the program is given a SIGILL signal. Often an illegal instruction indicates a bug in the program or missing support for the particular instruction in Valgrind. But some programs do deliberately try to execute an instruction that might be missing and trap the SIGILL signal to detect processor features. Using this flag makes it possible to avoid the diagnostic output that you would otherwise get in such cases.
--keep-debuginfo=<yes|no> [default: no]
Some tools and some functionalities have only limited support for archived debug info. Memcheck fully supports it. Generally, tools that report errors can use archived debug info to show the error stack traces. The known limitations are: Helgrind's past access stack trace of a race condition is does not use archived debug info. Massif (and more generally the xtree Massif output format) does not make use of archived debug info. Only Memcheck has been (somewhat) tested with --keep-debuginfo=yes, so other tools may have unknown limitations.
--show-below-main=<yes|no> [default: no]
If this option is enabled, all stack trace entries will be shown and main-like functions will not be normalised.
--fullpath-after=<string> [default: don't show source paths]
For example, consider a file named /home/janedoe/blah/src/foo/bar/xyzzy.c. Specifying --fullpath-after=/home/janedoe/blah/src/ will cause Valgrind to show the name as foo/bar/xyzzy.c.
Because the string is not required to be a prefix, --fullpath-after=src/ will produce the same output. This is useful when the path contains arbitrary machine-generated characters. For example, the path /my/build/dir/C32A1B47/blah/src/foo/xyzzy can be pruned to foo/xyzzy using --fullpath-after=/blah/src/.
If you simply want to see the full path, just specify an empty string: --fullpath-after=. This isn't a special case, merely a logical consequence of the above rules.
Finally, you can use --fullpath-after multiple times. Any appearance of it causes Valgrind to switch to producing full paths and applying the above filtering rule. Each produced path is compared against all the --fullpath-after-specified strings, in the order specified. The first string to match causes the path to be truncated as described above. If none match, the full path is shown. This facilitates chopping off prefixes when the sources are drawn from a number of unrelated directories.
--extra-debuginfo-path=<path> [default: undefined and unused]
However, there may be scenarios where you may wish to put debug objects at an arbitrary location, such as external storage when running Valgrind on a mobile device with limited local storage. Another example might be a situation where you do not have permission to install debug object packages on the system where you are running Valgrind.
In these scenarios, you may provide an absolute path as an extra, final place for Valgrind to search for debug objects by specifying --extra-debuginfo-path=/path/to/debug/objects. The given path will be prepended to the absolute path name of the searched-for object. For example, if Valgrind is looking for the debuginfo for /w/x/y/zz.so and --extra-debuginfo-path=/a/b/c is specified, it will look for a debug object at /a/b/c/w/x/y/zz.so.
This flag should only be specified once. If it is specified multiple times, only the last instance is honoured.
--debuginfo-server=ipaddr:port [default: undefined and unused]
In some scenarios it may be convenient to read debuginfo from objects stored on a different machine. With this flag, Valgrind will query a debuginfo server running on ipaddr and listening on port port, if it cannot find the debuginfo object in the local filesystem.
The debuginfo server must accept TCP connections on port port. The debuginfo server is contained in the source file auxprogs/valgrind-di-server.c. It will only serve from the directory it is started in. port defaults to 1500 in both client and server if not specified.
If Valgrind looks for the debuginfo for /w/x/y/zz.so by using the debuginfo server, it will strip the pathname components and merely request zz.so on the server. That in turn will look only in its current working directory for a matching debuginfo object.
The debuginfo data is transmitted in small fragments (8 KB) as requested by Valgrind. Each block is compressed using LZO to reduce transmission time. The implementation has been tuned for best performance over a single-stage 802.11g (WiFi) network link.
Note that checks for matching primary vs debug objects, using GNU debuglink CRC scheme, are performed even when using the debuginfo server. To disable such checking, you need to also specify --allow-mismatched-debuginfo=yes.
By default the Valgrind build system will build valgrind-di-server for the target platform, which is almost certainly not what you want. So far we have been unable to find out how to get automake/autoconf to build it for the build platform. If you want to use it, you will have to recompile it by hand using the command shown at the top of auxprogs/valgrind-di-server.c.
--allow-mismatched-debuginfo=no|yes [no]
This check can be overridden using --allow-mismatched-debuginfo=yes. This may be useful when the debuginfo and main objects have not been split in the proper way. Be careful when using this, though: it disables all consistency checking, and Valgrind has been observed to crash when the main and debuginfo objects don't match.
--suppressions=<filename> [default: $PREFIX/lib/valgrind/default.supp]
--gen-suppressions=<yes|no|all> [default: no]
---- Print suppression ? --- [Return/N/n/Y/y/C/c] ----
Pressing Ret, or N Ret or n Ret, causes Valgrind continue execution without printing a suppression for this error.
Pressing Y Ret or y Ret causes Valgrind to write a suppression for this error. You can then cut and paste it into a suppression file if you don't want to hear about the error in the future.
When set to all, Valgrind will print a suppression for every reported error, without querying the user.
This option is particularly useful with C++ programs, as it prints out the suppressions with mangled names, as required.
Note that the suppressions printed are as specific as possible. You may want to common up similar ones, by adding wildcards to function names, and by using frame-level wildcards. The wildcarding facilities are powerful yet flexible, and with a bit of careful editing, you may be able to suppress a whole family of related errors with only a few suppressions.
Sometimes two different errors are suppressed by the same suppression, in which case Valgrind will output the suppression more than once, but you only need to have one copy in your suppression file (but having more than one won't cause problems). Also, the suppression name is given as <insert a suppression name here>; the name doesn't really matter, it's only used with the -v option which prints out all used suppression records.
--input-fd=<number> [default: 0, stdin]
--dsymutil=no|yes [yes]
Mac OS X uses a deferred debug information (debuginfo) linking scheme. When object files containing debuginfo are linked into a .dylib or an executable, the debuginfo is not copied into the final file. Instead, the debuginfo must be linked manually by running dsymutil, a system-provided utility, on the executable or .dylib. The resulting combined debuginfo is placed in a directory alongside the executable or .dylib, but with the extension .dSYM.
With --dsymutil=no, Valgrind will detect cases where the .dSYM directory is either missing, or is present but does not appear to match the associated executable or .dylib, most likely because it is out of date. In these cases, Valgrind will print a warning message but take no further action.
With --dsymutil=yes, Valgrind will, in such cases, automatically run dsymutil as necessary to bring the debuginfo up to date. For all practical purposes, if you always use --dsymutil=yes, then there is never any need to run dsymutil manually or as part of your applications's build system, since Valgrind will run it as necessary.
Valgrind will not attempt to run dsymutil on any executable or library in /usr/, /bin/, /sbin/, /opt/, /sw/, /System/, /Library/ or /Applications/ since dsymutil will always fail in such situations. It fails both because the debuginfo for such pre-installed system components is not available anywhere, and also because it would require write privileges in those directories.
Be careful when using --dsymutil=yes, since it will cause pre-existing .dSYM directories to be silently deleted and re-created. Also note that dsymutil is quite slow, sometimes excessively so.
--max-stackframe=<number> [default: 2000000]
You may need to use this option if your program has large stack-allocated arrays. Valgrind keeps track of your program's stack pointer. If it changes by more than the threshold amount, Valgrind assumes your program is switching to a different stack, and Memcheck behaves differently than it would for a stack pointer change smaller than the threshold. Usually this heuristic works well. However, if your program allocates large structures on the stack, this heuristic will be fooled, and Memcheck will subsequently report large numbers of invalid stack accesses. This option allows you to change the threshold to a different value.
You should only consider use of this option if Valgrind's debug output directs you to do so. In that case it will tell you the new threshold you should specify.
In general, allocating large structures on the stack is a bad idea, because you can easily run out of stack space, especially on systems with limited memory or which expect to support large numbers of threads each with a small stack, and also because the error checking performed by Memcheck is more effective for heap-allocated data than for stack-allocated data. If you have to use this option, you may wish to consider rewriting your code to allocate on the heap rather than on the stack.
--main-stacksize=<number> [default: use current 'ulimit' value]
To simplify its memory management, Valgrind reserves all required space for the main thread's stack at startup. That means it needs to know the required stack size at startup.
By default, Valgrind uses the current "ulimit" value for the stack size, or 16 MB, whichever is lower. In many cases this gives a stack size in the range 8 to 16 MB, which almost never overflows for most applications.
If you need a larger total stack size, use --main-stacksize to specify it. Only set it as high as you need, since reserving far more space than you need (that is, hundreds of megabytes more than you need) constrains Valgrind's memory allocators and may reduce the total amount of memory that Valgrind can use. This is only really of significance on 32-bit machines.
On Linux, you may request a stack of size up to 2GB. Valgrind will stop with a diagnostic message if the stack cannot be allocated.
--main-stacksize only affects the stack size for the program's initial thread. It has no bearing on the size of thread stacks, as Valgrind does not allocate those.
You may need to use both --main-stacksize and --max-stackframe together. It is important to understand that --main-stacksize sets the maximum total stack size, whilst --max-stackframe specifies the largest size of any one stack frame. You will have to work out the --main-stacksize value for yourself (usually, if your applications segfaults). But Valgrind will tell you the needed --max-stackframe size, if necessary.
As discussed further in the description of --max-stackframe, a requirement for a large stack is a sign of potential portability problems. You are best advised to place all large data in heap-allocated memory.
--max-threads=<number> [default: 500]
MALLOC()-RELATED OPTIONS¶
For tools that use their own version of malloc (e.g. Memcheck, Massif, Helgrind, DRD), the following options apply.
--alignment=<number> [default: 8 or 16, depending on the platform]
--redzone-size=<number> [default: depends on the tool]
Increasing the redzone size makes it possible to detect overruns of larger distances, but increases the amount of memory used by Valgrind. Decreasing the redzone size will reduce the memory needed by Valgrind but also reduces the chances of detecting over/underruns, so is not recommended.
--xtree-memory=none|allocs|full [none]
When set to none, no memory execution tree is produced.
When set to allocs, the memory execution tree gives the current number of allocated bytes and the current number of allocated blocks.
When set to full, the memory execution tree gives 6 different measurements : the current number of allocated bytes and blocks (same values as for allocs), the total number of allocated bytes and blocks, the total number of freed bytes and blocks.
Note that the overhead in cpu and memory to produce an xtree depends on the tool. The overhead in cpu is small for the value allocs, as the information needed to produce this report is maintained in any case by the tool. For massif and helgrind, specifying full implies to capture a stack trace for each free operation, while normally these tools only capture an allocation stack trace. For Memcheck, the cpu overhead for the value full is small, as this can only be used in combination with --keep-stacktraces=alloc-and-free or --keep-stacktraces=alloc-then-free, which already records a stack trace for each free operation. The memory overhead varies between 5 and 10 words per unique stacktrace in the xtree, plus the memory needed to record the stack trace for the free operations, if needed specifically for the xtree.
--xtree-memory-file=<filename> [default: xtmemory.kcg.%p]
If the filename contains the extension .ms, then the produced file format will be a massif output file format. If the filename contains the extension .kcg or no extension is provided or recognised, then the produced file format will be a callgrind output format.
See Execution Trees for a detailed explanation about execution trees formats.
UNCOMMON OPTIONS¶
These options apply to all tools, as they affect certain obscure workings of the Valgrind core. Most people won't need to use them.
--smc-check=<none|stack|all|all-non-file> [default: all-non-file for x86/amd64/s390x, stack for other archs]
For "modern" architectures -- anything that's not x86, amd64 or s390x -- the default is stack. This is because a correct program must take explicit action to reestablish D-I cache coherence following code modification. Valgrind observes and honours such actions, with the result that self-modifying code is transparently handled with zero extra cost.
For x86, amd64 and s390x, the program is not required to notify the hardware of required D-I coherence syncing. Hence the default is all-non-file, which covers the normal case of generating code into an anonymous (non-file-backed) mmap'd area.
The meanings of the four available settings are as follows. No detection (none), detect self-modifying code on the stack (which is used by GCC to implement nested functions) (stack), detect self-modifying code everywhere (all), and detect self-modifying code everywhere except in file-backed mappings (all-non-file).
Running with all will slow Valgrind down noticeably. Running with none will rarely speed things up, since very little code gets dynamically generated in most programs. The VALGRIND_DISCARD_TRANSLATIONS client request is an alternative to --smc-check=all and --smc-check=all-non-file that requires more programmer effort but allows Valgrind to run your program faster, by telling it precisely when translations need to be re-made.
--smc-check=all-non-file provides a cheaper but more limited version of --smc-check=all. It adds checks to any translations that do not originate from file-backed memory mappings. Typical applications that generate code, for example JITs in web browsers, generate code into anonymous mmaped areas, whereas the "fixed" code of the browser always lives in file-backed mappings. --smc-check=all-non-file takes advantage of this observation, limiting the overhead of checking to code which is likely to be JIT generated.
--read-inline-info=<yes|no> [default: see below]
==15380== Conditional jump or move depends on uninitialised value(s) ==15380== at 0x80484EA: main (inlinfo.c:6) ==15380== ==15380== Conditional jump or move depends on uninitialised value(s) ==15380== at 0x8048550: fun_noninline (inlinfo.c:6) ==15380== by 0x804850E: main (inlinfo.c:34) ==15380== ==15380== Conditional jump or move depends on uninitialised value(s) ==15380== at 0x8048520: main (inlinfo.c:6)
And here are the same errors with --read-inline-info=yes:
==15377== Conditional jump or move depends on uninitialised value(s) ==15377== at 0x80484EA: fun_d (inlinfo.c:6) ==15377== by 0x80484EA: fun_c (inlinfo.c:14) ==15377== by 0x80484EA: fun_b (inlinfo.c:20) ==15377== by 0x80484EA: fun_a (inlinfo.c:26) ==15377== by 0x80484EA: main (inlinfo.c:33) ==15377== ==15377== Conditional jump or move depends on uninitialised value(s) ==15377== at 0x8048550: fun_d (inlinfo.c:6) ==15377== by 0x8048550: fun_noninline (inlinfo.c:41) ==15377== by 0x804850E: main (inlinfo.c:34) ==15377== ==15377== Conditional jump or move depends on uninitialised value(s) ==15377== at 0x8048520: fun_d (inlinfo.c:6) ==15377== by 0x8048520: main (inlinfo.c:35)
--read-var-info=<yes|no> [default: no]
==15363== Uninitialised byte(s) found during client check request ==15363== at 0x80484A9: croak (varinfo1.c:28) ==15363== by 0x8048544: main (varinfo1.c:55) ==15363== Address 0x80497f7 is 7 bytes inside data symbol "global_i2" ==15363== ==15363== Uninitialised byte(s) found during client check request ==15363== at 0x80484A9: croak (varinfo1.c:28) ==15363== by 0x8048550: main (varinfo1.c:56) ==15363== Address 0xbea0d0cc is on thread 1's stack ==15363== in frame #1, created by main (varinfo1.c:45)
And here are the same errors with --read-var-info=yes:
==15370== Uninitialised byte(s) found during client check request ==15370== at 0x80484A9: croak (varinfo1.c:28) ==15370== by 0x8048544: main (varinfo1.c:55) ==15370== Location 0x80497f7 is 0 bytes inside global_i2[7], ==15370== a global variable declared at varinfo1.c:41 ==15370== ==15370== Uninitialised byte(s) found during client check request ==15370== at 0x80484A9: croak (varinfo1.c:28) ==15370== by 0x8048550: main (varinfo1.c:56) ==15370== Location 0xbeb4a0cc is 0 bytes inside local var "local" ==15370== declared at varinfo1.c:46, in frame #1 of thread 1
--vgdb-poll=<number> [default: 5000]
--vgdb-shadow-registers=no|yes [default: no]
--vgdb-prefix=<prefix> [default: /tmp/vgdb-pipe]
--run-libc-freeres=<yes|no> [default: yes]
The GNU C library (libc.so), which is used by all programs, may allocate memory for its own uses. Usually it doesn't bother to free that memory when the program ends—there would be no point, since the Linux kernel reclaims all process resources when a process exits anyway, so it would just slow things down.
The glibc authors realised that this behaviour causes leak checkers, such as Valgrind, to falsely report leaks in glibc, when a leak check is done at exit. In order to avoid this, they provided a routine called __libc_freeres specifically to make glibc release all memory it has allocated. Memcheck therefore tries to run __libc_freeres at exit.
Unfortunately, in some very old versions of glibc, __libc_freeres is sufficiently buggy to cause segmentation faults. This was particularly noticeable on Red Hat 7.1. So this option is provided in order to inhibit the run of __libc_freeres. If your program seems to run fine on Valgrind, but segfaults at exit, you may find that --run-libc-freeres=no fixes that, although at the cost of possibly falsely reporting space leaks in libc.so.
--run-cxx-freeres=<yes|no> [default: yes]
The GNU Standard C++ library (libstdc++.so), which is used by all C++ programs compiled with g++, may allocate memory for its own uses. Usually it doesn't bother to free that memory when the program ends—there would be no point, since the kernel reclaims all process resources when a process exits anyway, so it would just slow things down.
The gcc authors realised that this behaviour causes leak checkers, such as Valgrind, to falsely report leaks in libstdc++, when a leak check is done at exit. In order to avoid this, they provided a routine called __gnu_cxx::__freeres specifically to make libstdc++ release all memory it has allocated. Memcheck therefore tries to run __gnu_cxx::__freeres at exit.
For the sake of flexibility and unforeseen problems with __gnu_cxx::__freeres, option --run-cxx-freeres=no exists, although at the cost of possibly falsely reporting space leaks in libstdc++.so.
--sim-hints=hint1,hint2,...
The GNU glibc pthread library (libpthread.so), which is used by pthread programs, maintains a cache of pthread stacks. When a pthread terminates, the memory used for the pthread stack and some thread local storage related data structure are not always directly released. This memory is kept in a cache (up to a certain size), and is re-used if a new thread is started.
This cache causes the helgrind tool to report some false positive race condition errors on this cached memory, as helgrind does not understand the internal glibc cache synchronisation primitives. So, when using helgrind, disabling the cache helps to avoid false positive race conditions, in particular when using thread local storage variables (e.g. variables using the __thread qualifier).
When using the memcheck tool, disabling the cache ensures the memory used by glibc to handle __thread variables is directly released when a thread terminates.
Note: Valgrind disables the cache using some internal knowledge of the glibc stack cache implementation and by examining the debug information of the pthread library. This technique is thus somewhat fragile and might not work for all glibc versions. This has been successfully tested with various glibc versions (e.g. 2.11, 2.16, 2.18) on various platforms.
--fair-sched=<no|yes|try> [default: no]
You may find this setting improves overall responsiveness if you are running an interactive multithreaded program, for example a web browser, on Valgrind.
--kernel-variant=variant1,variant2,...
--merge-recursive-frames=<number> [default: 0]
The option --merge-recursive-frames=<number> instructs Valgrind to detect and merge recursive call cycles having a size of up to <number> frames. When such a cycle is detected, Valgrind records the cycle in the stack trace as a unique program counter.
The value 0 (the default) causes no recursive call merging. A value of 1 will cause stack traces of simple recursive algorithms (for example, a factorial implementation) to be collapsed. A value of 2 will usually be needed to collapse stack traces produced by recursive algorithms such as binary trees, quick sort, etc. Higher values might be needed for more complex recursive algorithms.
Note: recursive calls are detected by analysis of program counter values. They are not detected by looking at function names.
--num-transtab-sectors=<number> [default: 6 for Android platforms, 16 for all others]
--avg-transtab-entry-size=<number> [default: 0, meaning use tool provided default]
--aspace-minaddr=<address> [default: depends on the platform]
--valgrind-stacksize=<number> [default: 1MB]
Use the option --valgrind-stacksize if such an (unlikely) warning is produced, or Valgrind dies due to a segmentation violation. Such segmentation violations have been seen when demangling huge C++ symbols.
If your application uses many threads and needs a lot of memory, you can gain some memory by reducing the size of these Valgrind stacks using the option --valgrind-stacksize.
--show-emwarns=<yes|no> [default: no]
--require-text-symbol=:sonamepatt:fnnamepatt
Both sonamepatt and fnnamepatt can be written using the usual ? and * wildcards. For example: ":*libc.so*:foo?bar". You may use characters other than a colon to separate the two patterns. It is only important that the first character and the separator character are the same. For example, the above example could also be written "Q*libc.so*Qfoo?bar". Multiple --require-text-symbol flags are allowed, in which case shared objects that are loaded into the process will be checked against all of them.
The purpose of this is to support reliable usage of marked-up libraries. For example, suppose we have a version of GCC's libgomp.so which has been marked up with annotations to support Helgrind. It is only too easy and confusing to load the wrong, un-annotated libgomp.so into the application. So the idea is: add a text symbol in the marked-up library, for example annotated_for_helgrind_3_6, and then give the flag --require-text-symbol=:*libgomp*so*:annotated_for_helgrind_3_6 so that when libgomp.so is loaded, Valgrind scans its symbol table, and if the symbol isn't present the run is aborted, rather than continuing silently with the un-marked-up library. Note that you should put the entire flag in quotes to stop shells expanding up the * and ? wildcards.
--soname-synonyms=syn1=pattern1,syn2=pattern2,...
Currently, this flexibility is only allowed for the malloc related functions, using the synonym somalloc. This synonym is usable for all tools doing standard replacement of malloc related functions (e.g. memcheck, helgrind, drd, massif, dhat).
Note: the soname of a elf shared library can be retrieved using the readelf utility.
--progress-interval=<number> [default: 0, meaning 'disabled']
When number is set to a non-zero value, Valgrind will print a one-line progress summary every number seconds. Valid settings for number are between 0 and 3600 inclusive. Here's some example output with number set to 10:
PROGRESS: U 110s, W 113s, 97.3% CPU, EvC 414.79M, TIn 616.7k, TOut 0.5k, #thr 67 PROGRESS: U 120s, W 124s, 96.8% CPU, EvC 505.27M, TIn 636.6k, TOut 3.0k, #thr 64 PROGRESS: U 130s, W 134s, 97.0% CPU, EvC 574.90M, TIn 657.5k, TOut 3.0k, #thr 63
Each line shows:
From the progress of these, it is possible to observe:
DEBUGGING VALGRIND OPTIONS¶
There are also some options for debugging Valgrind itself. You shouldn't need to use them in the normal run of things. If you wish to see the list, use the --help-debug option.
MEMCHECK OPTIONS¶
--leak-check=<no|summary|yes|full> [default: summary]
If --xml=yes is given, memcheck will automatically use the value --leak-check=full. You can use --show-leak-kinds=none to reduce the size of the xml output if you are not interested in the leak results.
--leak-resolution=<low|med|high> [default: high]
For hardcore leak debugging, you probably want to use --leak-resolution=high together with --num-callers=40 or some such large number.
Note that the --leak-resolution setting does not affect Memcheck's ability to find leaks. It only changes how the results are presented.
--show-leak-kinds=<set> [default: definite,possible]
--errors-for-leak-kinds=<set> [default: definite,possible]
--leak-check-heuristics=<set> [default: all]
Note that these heuristics are dependent on the layout of the objects produced by the C++ compiler. They have been tested with some gcc versions (e.g. 4.4 and 4.7). They might not work properly with other C++ compilers.
--show-reachable=<yes|no> , --show-possibly-lost=<yes|no>
Note that --show-possibly-lost=no has no effect if --show-reachable=yes is specified.
--xtree-leak=<no|yes> [no]
The increase or decrease for all events above will also be output in the file to provide the delta (increase or decrease) between 2 successive leak searches. For example, iRB is the increase of the RB event, dPBk is the decrease of PBk event. The values for the increase and decrease events will be zero for the first leak search done.
See Execution Trees for a detailed explanation about execution trees.
--xtree-leak-file=<filename> [default: xtleak.kcg.%p]
See Execution Trees for a detailed explanation about execution trees formats.
--undef-value-errors=<yes|no> [default: yes]
--track-origins=<yes|no> [default: no]
When set to yes, Memcheck keeps track of the origins of all uninitialised values. Then, when an uninitialised value error is reported, Memcheck will try to show the origin of the value. An origin can be one of the following four places: a heap block, a stack allocation, a client request, or miscellaneous other sources (eg, a call to brk).
For uninitialised values originating from a heap block, Memcheck shows where the block was allocated. For uninitialised values originating from a stack allocation, Memcheck can tell you which function allocated the value, but no more than that -- typically it shows you the source location of the opening brace of the function. So you should carefully check that all of the function's local variables are initialised properly.
Performance overhead: origin tracking is expensive. It halves Memcheck's speed and increases memory use by a minimum of 100MB, and possibly more. Nevertheless it can drastically reduce the effort required to identify the root cause of uninitialised value errors, and so is often a programmer productivity win, despite running more slowly.
Accuracy: Memcheck tracks origins quite accurately. To avoid very large space and time overheads, some approximations are made. It is possible, although unlikely, that Memcheck will report an incorrect origin, or not be able to identify any origin.
Note that the combination --track-origins=yes and --undef-value-errors=no is nonsensical. Memcheck checks for and rejects this combination at startup.
--partial-loads-ok=<yes|no> [default: yes]
When no, loads from partially invalid addresses are treated the same as loads from completely invalid addresses: an illegal-address error is issued, and the resulting bytes are marked as initialised.
Note that code that behaves in this way is in violation of the ISO C/C++ standards, and should be considered broken. If at all possible, such code should be fixed.
--expensive-definedness-checks=<no|auto|yes> [default: auto]
Selecting --expensive-definedness-checks=yes causes Memcheck to use the most accurate analysis possible. This minimises false error rates but can cause up to 30% performance degradation.
Selecting --expensive-definedness-checks=no causes Memcheck to use the cheapest instrumentation possible. This maximises performance but will normally give an unusably high false error rate.
The default setting, --expensive-definedness-checks=auto, is strongly recommended. This causes Memcheck to use the minimum of expensive instrumentation needed to achieve the same false error rate as --expensive-definedness-checks=yes. It also enables an instrumentation-time analysis pass which aims to further reduce the costs of accurate instrumentation. Overall, the performance loss is generally around 5% relative to --expensive-definedness-checks=no, although this is strongly workload dependent. Note that the exact instrumentation settings in this mode are architecture dependent.
--keep-stacktraces=alloc|free|alloc-and-free|alloc-then-free|none [default: alloc-and-free]
With alloc-then-free, a stack trace is recorded at allocation time, and is associated with the block. When the block is freed, a second stack trace is recorded, and this replaces the allocation stack trace. As a result, any "use after free" errors relating to this block can only show a stack trace for where the block was freed.
With alloc-and-free, both allocation and the deallocation stack traces for the block are stored. Hence a "use after free" error will show both, which may make the error easier to diagnose. Compared to alloc-then-free, this setting slightly increases Valgrind's memory use as the block contains two references instead of one.
With alloc, only the allocation stack trace is recorded (and reported). With free, only the deallocation stack trace is recorded (and reported). These values somewhat decrease Valgrind's memory and cpu usage. They can be useful depending on the error types you are searching for and the level of detail you need to analyse them. For example, if you are only interested in memory leak errors, it is sufficient to record the allocation stack traces.
With none, no stack traces are recorded for malloc and free operations. If your program allocates a lot of blocks and/or allocates/frees from many different stack traces, this can significantly decrease cpu and/or memory required. Of course, few details will be reported for errors related to heap blocks.
Note that once a stack trace is recorded, Valgrind keeps the stack trace in memory even if it is not referenced by any block. Some programs (for example, recursive algorithms) can generate a huge number of stack traces. If Valgrind uses too much memory in such circumstances, you can reduce the memory required with the options --keep-stacktraces and/or by using a smaller value for the option --num-callers.
If you want to use --xtree-memory=full memory profiling (see Execution Trees), then you cannot specify --keep-stacktraces=free or --keep-stacktraces=none.
--freelist-vol=<number> [default: 20000000]
This option specifies the maximum total size, in bytes, of the blocks in the queue. The default value is twenty million bytes. Increasing this increases the total amount of memory used by Memcheck but may detect invalid uses of freed blocks which would otherwise go undetected.
--freelist-big-blocks=<number> [default: 1000000]
Setting a value of 0 means that all the blocks are re-circulated in a FIFO order.
--workaround-gcc296-bugs=<yes|no> [default: no]
You may also need to use this option when working with GCC 3.X or 4.X on 32-bit PowerPC Linux. This is because GCC generates code which occasionally accesses below the stack pointer, particularly for floating-point to/from integer conversions. This is in violation of the 32-bit PowerPC ELF specification, which makes no provision for locations below the stack pointer to be accessible.
This option is deprecated as of version 3.12 and may be removed from future versions. You should instead use --ignore-range-below-sp to specify the exact range of offsets below the stack pointer that should be ignored. A suitable equivalent is --ignore-range-below-sp=1024-1.
--ignore-range-below-sp=<number>-<number>
--show-mismatched-frees=<yes|no> [default: yes]
There is however a scenario where such mismatches cannot be avoided. That is when the user provides implementations of new/new[] that call malloc and of delete/delete[] that call free, and these functions are asymmetrically inlined. For example, imagine that delete[] is inlined but new[] is not. The result is that Memcheck "sees" all delete[] calls as direct calls to free, even when the program source contains no mismatched calls.
This causes a lot of confusing and irrelevant error reports. --show-mismatched-frees=no disables these checks. It is not generally advisable to disable them, though, because you may miss real errors as a result.
--ignore-ranges=0xPP-0xQQ[,0xRR-0xSS]
--malloc-fill=<hexnumber>
--free-fill=<hexnumber>
CACHEGRIND OPTIONS¶
--I1=<size>,<associativity>,<line size>
--D1=<size>,<associativity>,<line size>
--LL=<size>,<associativity>,<line size>
--cache-sim=no|yes [yes]
--branch-sim=no|yes [no]
--cachegrind-out-file=<file>
CALLGRIND OPTIONS¶
--callgrind-out-file=<file>
--dump-line=<no|yes> [default: yes]
--dump-instr=<no|yes> [default: no]
--compress-strings=<no|yes> [default: yes]
--compress-pos=<no|yes> [default: yes]
--combine-dumps=<no|yes> [default: no]
--dump-every-bb=<count> [default: 0, never]
--dump-before=<function>
--zero-before=<function>
--dump-after=<function>
--instr-atstart=<yes|no> [default: yes]
Note that the resulting call graph will most probably not contain main, but will contain all the functions executed after instrumentation was enabled. Instrumentation can also be programmatically enabled/disabled. See the Callgrind include file callgrind.h for the macro you have to use in your source code.
For cache simulation, results will be less accurate when switching on instrumentation later in the program run, as the simulator starts with an empty cache at that moment. Switch on event collection later to cope with this error.
--collect-atstart=<yes|no> [default: yes]
To only look at parts of your program, you have two possibilities:
The second option can be used if the program part you want to profile is called many times. Option 1, i.e. creating a lot of dumps is not practical here.
Collection state can be toggled at entry and exit of a given function with the option --toggle-collect. If you use this option, collection state should be disabled at the beginning. Note that the specification of --toggle-collect implicitly sets --collect-state=no.
Collection state can be toggled also by inserting the client request CALLGRIND_TOGGLE_COLLECT ; at the needed code positions.
--toggle-collect=<function>
--collect-jumps=<no|yes> [default: no]
--collect-systime=<no|yes|msec|usec|nsec> [default: no]
The value no indicates to record no system call information.
The other values indicate to record the number of system calls done (sysCount event) and the elapsed time (sysTime event) spent in system calls. The --collect-systime value gives the unit used for sysTime : milli seconds, micro seconds or nano seconds. With the value nsec, callgrind also records the cpu time spent during system calls (sysCpuTime).
The value yes is a synonym of msec. The value nsec is not supported on Darwin.
--collect-bus=<no|yes> [default: no]
--cache-sim=<yes|no> [default: no]
--branch-sim=<yes|no> [default: no]
HELGRIND OPTIONS¶
--free-is-write=no|yes [default: no]
This functionality is new in Valgrind 3.7.0, and is regarded as experimental. It is not enabled by default because its interaction with custom memory allocators is not well understood at present. User feedback is welcomed.
--track-lockorders=no|yes [default: yes]
--history-level=none|approx|full [default: full]
Collecting such information is expensive in both speed and memory, particularly for programs that do many inter-thread synchronisation events (locks, unlocks, etc). Without such information, it is more difficult to track down the root causes of races. Nonetheless, you may not need it in situations where you just want to check for the presence or absence of races, for example, when doing regression testing of a previously race-free program.
--history-level=none is the opposite extreme. It causes Helgrind not to collect any information about previous accesses. This can be dramatically faster than --history-level=full.
--history-level=approx provides a compromise between these two extremes. It causes Helgrind to show a full trace for the later access, and approximate information regarding the earlier access. This approximate information consists of two stacks, and the earlier access is guaranteed to have occurred somewhere between program points denoted by the two stacks. This is not as useful as showing the exact stack for the previous access (as --history-level=full does), but it is better than nothing, and it is almost as fast as --history-level=none.
--delta-stacktrace=no|yes [default: yes on linux amd64/x86]
--delta-stacktrace configures the way Helgrind captures the stacktraces for the option --history-level=full. Such a stacktrace is typically needed each time a new piece of memory is read or written in a basic block of instructions.
--delta-stacktrace=no causes Helgrind to compute a full history stacktrace from the unwind info each time a stacktrace is needed.
--delta-stacktrace=yes indicates to Helgrind to derive a new stacktrace from the previous stacktrace, as long as there was no call instruction, no return instruction, or any other instruction changing the call stack since the previous stacktrace was captured. If no such instruction was executed, the new stacktrace can be derived from the previous stacktrace by just changing the top frame to the current program counter. This option can speed up Helgrind by 25% when using --history-level=full.
The following aspects have to be considered when using --delta-stacktrace=yes :
--conflict-cache-size=N [default: 1000000]
Information about "old" conflicting accesses is stored in a cache of limited size, with LRU-style management. This is necessary because it isn't practical to store a stack trace for every single memory access made by the program. Historical information on not recently accessed locations is periodically discarded, to free up space in the cache.
This option controls the size of the cache, in terms of the number of different memory addresses for which conflicting access information is stored. If you find that Helgrind is showing race errors with only one stack instead of the expected two stacks, try increasing this value.
The minimum value is 10,000 and the maximum is 30,000,000 (thirty times the default value). Increasing the value by 1 increases Helgrind's memory requirement by very roughly 100 bytes, so the maximum value will easily eat up three extra gigabytes or so of memory.
--check-stack-refs=no|yes [default: yes]
--ignore-thread-creation=<yes|no> [default: no]
Also new memory allocated during thread creation is untracked, that is race reporting is suppressed there. DRD does the same thing implicitly. This is necessary because Solaris libc caches many objects and reuses them for different threads and that confuses Helgrind.
DRD OPTIONS¶
--check-stack-var=<yes|no> [default: no]
--exclusive-threshold=<n> [default: off]
--join-list-vol=<n> [default: 10]
--first-race-only=<yes|no> [default: no]
--free-is-write=<yes|no> [default: no]
--report-signal-unlocked=<yes|no> [default: yes]
--segment-merging=<yes|no> [default: yes]
--segment-merging-interval=<n> [default: 10]
--shared-threshold=<n> [default: off]
--show-confl-seg=<yes|no> [default: yes]
--show-stack-usage=<yes|no> [default: no]
--ignore-thread-creation=<yes|no> [default: no]
--trace-addr=<address> [default: none]
--ptrace-addr=<address> [default: none]
--trace-alloc=<yes|no> [default: no]
--trace-barrier=<yes|no> [default: no]
--trace-cond=<yes|no> [default: no]
--trace-fork-join=<yes|no> [default: no]
--trace-hb=<yes|no> [default: no]
--trace-mutex=<yes|no> [default: no]
--trace-rwlock=<yes|no> [default: no]
--trace-semaphore=<yes|no> [default: no]
MASSIF OPTIONS¶
--heap=<yes|no> [default: yes]
--heap-admin=<size> [default: 8]
--stacks=<yes|no> [default: no]
--pages-as-heap=<yes|no> [default: no]
--depth=<number> [default: 30]
--alloc-fn=<name>
Note that the named function will only be treated this way if it is the top entry in a stack trace, or just below another function treated this way. For example, if you have a function malloc1 that wraps malloc, and malloc2 that wraps malloc1, just specifying --alloc-fn=malloc2 will have no effect. You need to specify --alloc-fn=malloc1 as well. This is a little inconvenient, but the reason is that checking for allocation functions is slow, and it saves a lot of time if Massif can stop looking through the stack trace entries as soon as it finds one that doesn't match rather than having to continue through all the entries.
Note that C++ names are demangled. Note also that overloaded C++ names must be written in full. Single quotes may be necessary to prevent the shell from breaking them up. For example:
--alloc-fn='operator new(unsigned, std::nothrow_t const&)'
--ignore-fn=<name>
Any realloc of an ignored block will also be ignored, even if the realloc call does not occur in an ignored function. This avoids the possibility of negative heap sizes if ignored blocks are shrunk with realloc.
The rules for writing C++ function names are the same as for --alloc-fn above.
--threshold=<m.n> [default: 1.0]
--peak-inaccuracy=<m.n> [default: 1.0]
--time-unit=<i|ms|B> [default: i]
--detailed-freq=<n> [default: 10]
--max-snapshots=<n> [default: 100]
--massif-out-file=<file> [default: massif.out.%p]
BBV OPTIONS¶
--bb-out-file=<name> [default: bb.out.%p]
--pc-out-file=<name> [default: pc.out.%p]
--interval-size=<number> [default: 100000000]
--instr-count-only [default: no]
LACKEY OPTIONS¶
--basic-counts=<no|yes> [default: yes]
--detailed-counts=<no|yes> [default: no]
--trace-mem=<no|yes> [default: no]
--trace-superblocks=<no|yes> [default: no]
--fnname=<name> [default: main]
SEE ALSO¶
cg_annotate(1), callgrind_annotate(1), callgrind_control(1), ms_print(1), $INSTALL/share/doc/valgrind/html/index.html or http://www.valgrind.org/docs/manual/index.html, Debugging your program using Valgrind's gdbserver and GDB[1] vgdb[2], Valgrind monitor commands[3], The Commentary[4], Scheduling and Multi-Thread Performance[5], Cachegrind: a cache and branch-prediction profiler[6]. Execution Trees[7]
AUTHOR¶
See the AUTHORS file in the valgrind distribution for a comprehensive list of authors.
This manpage was written by Andres Roldan <aroldan@debian.org> and the Valgrind developers.
NOTES¶
- 1.
- Debugging your program using Valgrind's gdbserver and GDB
- 2.
- vgdb
- 3.
- Valgrind monitor commands
- 4.
- The Commentary
- 5.
- Scheduling and Multi-Thread Performance
- 6.
- Cachegrind: a cache and branch-prediction profiler
- 7.
- Execution Trees
06/28/2020 | Release 3.16.1 |