Name
Re: Valgrind-users invalid file descriptor -1 in syscall close Re: Valgrind-users invalid file descriptor -1 in syscall close From: Nicholas Nethercote - 2005-08-11 13:34:59. When enabled, Valgrind will print out a list of open file descriptors on exit. Along with each file descriptor is printed a stack backtrace of where the file was opened and any details relating to the file descriptor such as the file name or socket details.time-stamp= default: no. 6168 Warning: invalid file descriptor 1019 in syscall socket 6168 Warning: invalid file descriptor 1019 in syscall open 6168 Warning: invalid file descriptor 1019 in syscall open. For each of those requests, valgrind reports the warnings shown above but doesn't report the 'invalid.
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, anda 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 itdescribe 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]
-h --help
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), sothis option is arguably badly named. However, most children of fork calls immediately call exec anyway.
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 Valgrindskips 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 specifiedexecutables.
If the embedded gdbserver is enabled but no gdb is currently being used, the ??? command line utility can send 'monitor commands' to Valgrind from a shell.The Valgrind core provides a set of ???. A tool can optionally provide tool specific monitor commands, which are documented in the tool specificchapter.
%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.
%q{FOO} is replaced with the contents of the environment variable FOO. If the {FOO} part is malformed, it causes an abort. Thisspecifier 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 setdifferently 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, itcauses 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.
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]
When enabled, the important parts of the output (e.g. tool error messages) will be in XML format rather than plain text. Furthermore, the XML output will besent to a different output channel than the plain text output. Therefore, you also must use one of --xml-fd, --xml-file or --xml-socket tospecify where the XML is to be sent.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 (thedestination 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 withMemcheck, Helgrind, DRD and SGcheck. The output format is specified in the file docs/internals/xml-output-protocol4.txt in the source tree for Valgrind 3.5.0or 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 outputto 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 filecounts 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 importantinformation which the GUI user should be made aware of.
An important fact about demangling is that function names mentioned in suppressions files should be in their mangled form. Valgrind does not demanglefunction names when searching for applicable suppressions, because to do otherwise would make suppression file contents dependent on the state of Valgrind'sdemangling machinery, and also slow down suppression matching.
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 whenworking with programs with deeply-nested call chains.
If this option is enabled, all stack trace entries will be shown and main-like functions will not be normalised.
For example, consider a file named /home/janedoe/blah/src/foo/bar/xyzzy.c. Specifying --fullpath-after=/home/janedoe/blah/src/ will cause Valgrind toshow 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 containsarbitrary 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 ofthe 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 abovefiltering rule. Each produced path is compared against all the --fullpath-after-specified strings, in the order specified. The first string to matchcauses 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 drawnfrom a number of unrelated directories.
If you choose to, Valgrind will print out a suppression for this error. You can then cut and paste it into a suppression file if you don't want to hearabout 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 usingframe-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 ofrelated 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 needto 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 namehere>; the name doesn't really matter, it's only used with the -v option which prints out all used suppression records.
Pressing Y Ret or y Ret causes Valgrind to start a debugger for the program at this point. When you have finished with the debugger, quit fromit, and the program will continue. Trying to continue from inside the debugger doesn't work.
Note: if you use GDB, more powerful debugging support is provided by the --vgdb=yes or full value. This activates Valgrind's internalgdbserver, which provides more-or-less full GDB-style control of the application: insertion of breakpoints, continuing from inside GDB, inferior functioncalls, and much more.
C Ret or c Ret causes Valgrind not to start a debugger, and not to ask again.
This specifies how Valgrind will invoke the debugger. By default it will use whatever GDB is detected at build time, which is usually /usr/bin/gdb. Usingthis command, you can specify some alternative command to invoke the debugger you want to use.
The command string given can include one or instances of the %p and %f expansions. Each instance of %p expands to the PID of the process to be debugged andeach instance of %f expands to the path to the executable for the process to be debugged.
Since <command> is likely to contain spaces, you will need to put this entire option in quotes to ensure it is correctly handled by the shell.
Mac OS X uses a deferred debug information (debuginfo) linking scheme. When object files containing debuginfo are linked into a .dylib or an executable, thedebuginfo is not copied into the final file. Instead, the debuginfo must be linked manually by running dsymutil, a system-provided utility, on the executableor .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 associatedexecutable 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 practicalpurposes, 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, sinceValgrind 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/ sincedsymutil will always fail in such situations. It fails both because the debuginfo for such pre-installed system components is not available anywhere, and alsobecause 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 thatdsymutil is quite slow, sometimes excessively so.
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 bymore than the threshold amount, Valgrind assumes your program is switching to a different stack, and Memcheck behaves differently than it would for a stackpointer change smaller than the threshold. Usually this heuristic works well. However, if your program allocates large structures on the stack, this heuristicwill be fooled, and Memcheck will subsequently report large numbers of invalid stack accesses. This option allows you to change the threshold to a differentvalue.
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 shouldspecify.
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 memoryor 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 forheap-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 ratherthan on the stack.
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 requiredstack 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 8to 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 youneed (that is, hundreds of megabytes more than you need) constrains Valgrind's memory allocators and may reduce the total amount of memory that Valgrind canuse. 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 notallocate those.
You may need to use both --main-stacksize and --max-stackframe together. It is important to understand that --main-stacksize sets themaximum 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, ifnecessary.
As discussed further in the description of --max-stackframe, a requirement for a large stack is a sign of potential portability problems. You arebest advised to place all large data in heap-allocated memory.
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]
Increasing the redzone size makes it possible to detect overruns of larger distances, but increases the amount of memory used by Valgrind. Decreasing theredzone size will reduce the memory needed by Valgrind but also reduces the chances of detecting over/underruns, so is not recommended.
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: stack]
This option controls Valgrind's detection of self-modifying code. If no checking is done, if a program executes some code, then overwrites it with new code,and executes the new code, Valgrind will continue to execute the translations it made for the old code. This will likely lead to incorrect behaviour and/orcrashes.Valgrind has four levels of self-modifying code detection: no detection, detect self-modifying code on the stack (which is used by GCC to implement nestedfunctions), detect self-modifying code everywhere, and detect self-modifying code everywhere except in file-backed mappings. Note that the default option willcatch the vast majority of cases. The main case it will not catch is programs such as JIT compilers that dynamically generate code and subsequentlyoverwrite part or all of it. Running with all will slow Valgrind down noticeably. Running with none will rarely speed things up, since verylittle code gets put on the stack for most programs. The VALGRIND_DISCARD_TRANSLATIONS client request is an alternative to --smc-check=all thatrequires 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 notoriginate from file-backed memory mappings. Typical applications that generate code, for example JITs in web browsers, generate code into anonymous mmapedareas, 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.
Some architectures (including ppc32, ppc64, ARM and MIPS) require programs which create code at runtime to flush the instruction cache in between codegeneration and first use. Valgrind observes and honours such instructions. Hence, on ppc32/Linux, ppc64/Linux and ARM/Linux, Valgrind always provides complete,transparent support for self-modifying code. It is only on platforms such as x86/Linux, AMD64/Linux, x86/Darwin and AMD64/Darwin that you need to use thisoption.
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 whenthe 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 thereforetries 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 particularlynoticeable 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, butsegfaults at exit, you may find that --run-libc-freeres=no fixes that, although at the cost of possibly falsely reporting space leaks inlibc.so.
You may find this setting improves overall responsiveness if you are running an interactive multithreaded program, for example a web browser, onValgrind.
Both sonamepatt and fnnamepatt can be written using the usual ? and * wildcards. For example: ':*libc.so*:foo?bar'. Youmay 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. Forexample, the above example could also be written 'Q*libc.so*Qfoo?bar'. Multiple --require-text-symbol flags are allowed, in which case sharedobjects 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 beenmarked up with annotations to support Helgrind. It is only too easy and confusing to load the wrong, un-annotated libgomp.so into the application. Sothe 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 thesymbol 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 tostop shells expanding up the * and ? wildcards.
Currently, this flexibility is only allowed for the malloc related functions, using the synonym somalloc. This synonym is usable for all tools doingstandard replacement of malloc related functions (e.g. memcheck, massif, drd, helgrind, exp-dhat, exp-sgcheck).
• Alternate malloc library: to replace the malloc related functions in an alternate library with soname mymalloclib.so, give the option--soname-synonyms=somalloc=mymalloclib.so. A pattern can be used to match multiple libraries sonames. For example,--soname-synonyms=somalloc=*tcmalloc* will match the soname of all variants of the tcmalloc library (native, debug, profiled, ... tcmalloc variants).Note: the soname of a elf shared library can be retrieved using the readelf utility.
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]
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.
When set to yes, Memcheck keeps track of the origins of all uninitialised values. Then, when an uninitialised value error is reported, Memcheck willtry 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 miscellaneousother 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 stackallocation, Memcheck can tell you which function allocated the value, but no more than that -- typically it shows you the source location of the opening braceof 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 productivitywin, 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, althoughunlikely, 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 atstartup.
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 the ISO C/C++ standards, and should be considered broken. If at all possible, such codeshould be fixed. This option should be used only as a last resort.
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 thetotal amount of memory used by Memcheck but may detect invalid uses of freed blocks which would otherwise go undetected.
Setting a value of 0 means that all the blocks are re-circulated in a FIFO order.
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 occasionallyaccesses 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.
Cachegrind Options
--I1=<size>,<associativity>,<line size>
Valgrind Invalid File Descriptor In Syscall Close
- --dump-before=<function>
- Dump when entering function.
- --zero-before=<function>
- Zero all costs when entering function.
- --dump-after=<function>
- Dump when leaving function.
- --instr-atstart=<yes|no> [default: yes] Specify if you want Callgrind to start simulation and profiling from the beginning of the program. When set to no, Callgrind will not be able to collect anyinformation, including calls, but it will have at most a slowdown of around 4, which is the minimum Valgrind overhead. Instrumentation can be interactivelyenabled via callgrind_control -i on.
- --collect-atstart=<yes|no> [default: yes] Specify whether event collection is enabled at beginning of the profile run.
- 1. Zero event counters before entering the program part you want to profile, and dump the event counters to a file after leaving that program part.
- 2. Switch on/off collection state as needed to only see event counters happening while inside of the program part you want to profile. 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.
- --toggle-collect=<function>
- Toggle collection on entry/exit of function.
- --collect-jumps=<no|yes> [default: no]
- This specifies whether information for (conditional) jumps should be collected. As above, callgrind_annotate currently is not able to show you the data. Youhave to use KCachegrind to get jump arrows in the annotated code.
- --collect-systime=<no|yes> [default: no]
- This specifies whether information for system call times should be collected.
- --collect-bus=<no|yes> [default: no]
- This specifies whether the number of global bus events executed should be collected. The event type 'Ge' is used for these events.
- --cache-sim=<yes|no> [default: no]
- Specify if you want to do full cache simulation. By default, only instruction read accesses will be counted ('Ir'). With cache simulation, further eventcounters are enabled: Cache misses on instruction reads ('I1mr'/'ILmr'), data read accesses ('Dr') and related cache misses ('D1mr'/'DLmr'), data writeaccesses ('Dw') and related cache misses ('D1mw'/'DLmw'). For more information, see ???.
- --branch-sim=<yes|no> [default: no]
- Specify if you want to do branch prediction simulation. Further event counters are enabled: Number of executed conditional branches and related predictormisses ('Bc'/'Bcm'), executed indirect jumps and related misses of the jump address predictor ('Bi'/'Bim').
- --track-lockorders=no|yes [default: yes]
- When enabled (the default), Helgrind performs lock order consistency checking. For some buggy programs, the large number of lock order errors reported canbecome annoying, particularly if you're only interested in race errors. You may therefore find it helpful to disable lock order checking.
- --history-level=none|approx|full [default: full] --history-level=full (the default) causes Helgrind collects enough information about 'old' accesses that it can produce two stack traces in a racereport -- both the stack trace for the current access, and the trace for the older, conflicting access. To limit memory usage, 'old' accesses stack traces arelimited to a maximum of 8 entries, even if --num-callers value is bigger.
- --conflict-cache-size=N [default: 1000000] This flag only has any effect at --history-level=full.
- --check-stack-refs=no|yes [default: yes]
- By default Helgrind checks all data memory accesses made by your program. This flag enables you to skip checking for accesses to thread stacks (localvariables). This can improve performance, but comes at the cost of missing races on stack-allocated data.
- • Don't enable this option when using reference-counted objects because that will result in false positives, even when that code has been annotated properlywith ANNOTATE_HAPPENS_BEFORE and ANNOTATE_HAPPENS_AFTER. See e.g. the output of the following command for an example: valgrind --tool=drd --free-is-write=yesdrd/tests/annotate_smart_pointer.
- --report-signal-unlocked=<yes|no> [default: yes]
- Whether to report calls to pthread_cond_signal and pthread_cond_broadcast where the mutex associated with the signal throughpthread_cond_wait or pthread_cond_timed_waitis not locked at the time the signal is sent. Sending a signal without holding a lock on theassociated mutex is a common programming error which can cause subtle race conditions and unpredictable behavior. There exist some uncommon synchronizationpatterns however where it is safe to send a signal without holding a lock on the associated mutex.
- --segment-merging=<yes|no> [default: yes]
- Controls segment merging. Segment merging is an algorithm to limit memory usage of the data race detection algorithm. Disabling segment merging may improvethe accuracy of the so-called 'other segments' displayed in race reports but can also trigger an out of memory error.
- --segment-merging-interval=<n> [default: 10]
- Perform segment merging only after the specified number of new segments have been created. This is an advanced configuration option that allows to choosewhether to minimize DRD's memory usage by choosing a low value or to let DRD run faster by choosing a slightly higher value. The optimal value for thisparameter depends on the program being analyzed. The default value works well for most programs.
- --shared-threshold=<n> [default: off]
- Print an error message if a reader lock has been held longer than the specified time (in milliseconds). This option enables the detection of lockcontention.
- --show-confl-seg=<yes|no> [default: yes]
- Show conflicting segments in race reports. Since this information can help to find the cause of a data race, this option is enabled by default. Disablingthis option makes the output of DRD more compact.
- --show-stack-usage=<yes|no> [default: no]
- Print stack usage at thread exit time. When a program creates a large number of threads it becomes important to limit the amount of virtual memory allocatedfor thread stacks. This option makes it possible to observe how much stack memory has been used by each thread of the the client program. Note: the DRD toolitself allocates some temporary data on the client thread stack. The space necessary for this temporary data must be allocated by the client program when itallocates stack memory, but is not included in stack usage reported by DRD.
- --trace-addr=<address> [default: none]
- Trace all load and store activity for the specified address. This option may be specified more than once.
- --ptrace-addr=<address> [default: none]
- Trace all load and store activity for the specified address and keep doing that even after the memory at that address has been freed andreallocated.
- --trace-alloc=<yes|no> [default: no]
- Trace all memory allocations and deallocations. May produce a huge amount of output.
- --trace-barrier=<yes|no> [default: no]
- Trace all barrier activity.
- --trace-cond=<yes|no> [default: no]
- Trace all condition variable activity.
- --trace-fork-join=<yes|no> [default: no]
- Trace all thread creation and all thread termination events.
- --trace-hb=<yes|no> [default: no]
- Trace execution of the ANNOTATE_HAPPENS_BEFORE(), ANNOTATE_HAPPENS_AFTER() and ANNOTATE_HAPPENS_DONE() client requests.
- --trace-mutex=<yes|no> [default: no]
- Trace all mutex activity.
- --trace-rwlock=<yes|no> [default: no]
- Trace all reader-writer lock activity.
- --trace-semaphore=<yes|no> [default: no]
- Trace all semaphore activity.
- Specifies whether heap profiling should be done.
- --heap-admin=<size> [default: 8]
- If heap profiling is enabled, gives the number of administrative bytes per block to use. This should be an estimate of the average, since it may vary. Forexample, the allocator used by glibc on Linux requires somewhere between 4 to 15 bytes per block, depending on various factors. That allocator also requiresadmin space for freed blocks, but Massif cannot account for this.
- --stacks=<yes|no> [default: no]
- Specifies whether stack profiling should be done. This option slows Massif down greatly, and so is off by default. Note that Massif assumes that the mainstack has size zero at start-up. This is not true, but doing otherwise accurately is difficult. Furthermore, starting at zero better indicates the size of thepart of the main stack that a user program actually has control over.
- --pages-as-heap=<yes|no> [default: no]
- Tells Massif to profile memory at the page level rather than at the malloc'd block level. See above for details.
- --depth=<number> [default: 30]
- Maximum depth of the allocation trees recorded for detailed snapshots. Increasing it will make Massif run somewhat more slowly, use more memory, and producebigger output files.
- --alloc-fn=<name> Functions specified with this option will be treated as though they were a heap allocation function such as malloc. This is useful for functions thatare wrappers to malloc or new, which can fill up the allocation trees with uninteresting information. This option can be specified multiple timeson the command line, to name multiple functions.
- --ignore-fn=<name> Any direct heap allocation (i.e. a call to malloc, new, etc, or a call to a function named by an --alloc-fn option) that occurs in afunction specified by this option will be ignored. This is mostly useful for testing purposes. This option can be specified multiple times on the command line,to name multiple functions.
- --threshold=<m.n> [default: 1.0]
- The significance threshold for heap allocations, as a percentage of total memory size. Allocation tree entries that account for less than this will beaggregated. Note that this should be specified in tandem with ms_print's option of the same name.
- --peak-inaccuracy=<m.n> [default: 1.0]
- Massif does not necessarily record the actual global memory allocation peak; by default it records a peak only when the global memory allocation sizeexceeds the previous peak by at least 1.0%. This is because there can be many local allocation peaks along the way, and doing a detailed snapshot for every onewould be expensive and wasteful, as all but one of them will be later discarded. This inaccuracy can be changed (even to 0.0%) via this option, but Massif willrun drastically slower as the number approaches zero.
- --time-unit=<i|ms|B> [default: i]
- The time unit used for the profiling. There are three possibilities: instructions executed (i), which is good for most cases; real (wallclock) time (ms,i.e. milliseconds), which is sometimes useful; and bytes allocated/deallocated on the heap and/or stack (B), which is useful for very short-run programs, andfor testing purposes, because it is the most reproducible across different machines.
- --detailed-freq=<n> [default: 10]
- Frequency of detailed snapshots. With --detailed-freq=1, every snapshot is detailed.
- --max-snapshots=<n> [default: 100]
- The maximum number of snapshots recorded. If set to N, for all programs except very short-running ones, the final number of snapshots will be between N/2and N.
- --massif-out-file=<file> [default: massif.out.%p]
- Write the profile data to file rather than to the default output file, massif.out.<pid>. The %p and %q format specifiers can be used toembed the process ID and/or the contents of an environment variable in the name, as is the case for the core option --log-file.
- --instr-count-only [default: no]
- This option tells the tool to only display instruction count totals, and to not generate the actual basic block vector file. This is useful for debugging,and for gathering instruction count info without generating the large basic block vector files.
- 5. Ratios between some of these counts.
- 6. The exit code of the client program.
- --detailed-counts=<no|yes> [default: no]
- When enabled, Lackey prints a table containing counts of loads, stores and ALU operations, differentiated by their IR types. The IR types are identified bytheir IR name ('I1', 'I8', ... 'I128', 'F32', 'F64', and 'V128').
- --trace-mem=<no|yes> [default: no]
- When enabled, Lackey prints the size and address of almost every memory access made by the program. See the comments at the top of the file lackey/lk_main.cfor details about the output format, how it works, and inaccuracies in the address trace. Note that this option produces immense amounts of output.
- --trace-superblocks=<no|yes> [default: no]
- When enabled, Lackey prints out the address of every superblock (a single entry, multiple exit, linear chunk of code) executed by the program. This isprimarily of interest to Valgrind developers. See the comments at the top of the file lackey/lk_main.c for details about the output format. Note that thisoption produces large amounts of output.
- --fnname=<name> [default: main]
- Changes the function for which calls are counted when --basic-counts=yes is specified.
- Accepts a positive byte value (0-127) that denotes a pitch as it would be represented in MIDI
- Each number is one semitone / half-step in the chromatic scale.
- 0 represents a very low C and 127 represents a very high G (a standard 88 key piano begins at 9-A and ends at 108-C).
- If the parameter value is outside this range, it applies a default value 60 which is the same as middle C on a piano.
- From middle C, all other pitches in the octave are as follows:
- 61 = C# or Db
- 62 = D
- 63 = D# or Eb
- 64 = E or Fb
- 65 = E# or F
- 66 = F# or Gb
- 67 = G
- 68 = G# or Ab
- 69 = A
- 70 = A# or Bb
- 71 = B or Cb
- 72 = B# or C
- To produce these pitches in other octaves, add or subtract multiples of 12.
- Accepts a positive integer value that is the length of the tone in milliseconds.
- If the parameter value is negative, it applies a default value of one second (1000 milliseconds).
- Accepts a positive byte value (0-127) that denotes the General MIDI 'patch' used to play the tone.
- If the parameter is outside this range, it applies a default value 0 which is an Acoustic Grand Piano.
- General MIDI standardizes the number associated with each possible instrument (often referred to as program change numbers), however it does not determine how the tone will sound. This is determined by the synthesizer that is producing the sound. Thus a Tuba (patch 58) on one computer may sound different than that same patch on another computer.
- The 128 available patches are divided into instrument families of 8:
- Note that outside of Java, General MIDI usually refers to patches 1-128. When referring to a list of General MIDI patches, 1 must be subtracted to play the correct patch. For a full list of General MIDI instruments, see www.midi.org/about-midi/gm/gm1sound.shtml. The General MIDI channel 10 percussion key map is not relevant to the toneGenerator method because it always defaults to MIDI channel 1.
- Accepts a positive byte value (0-127) where 127 is the loudest and 0 is silent. This value denotes MIDI velocity which refers to the initial attack of the tone.
- If the parameter value is outside this range, it applies a default value 100.
- MIDI velocity measures how hard a note on (or note off) message is played, perhaps on a MIDI controller like a keyboard. Most MIDI synthesizers will translate this into volume on a logarithmic scale in which the difference in amplitude decreases as the velocity value increases.
- Note that velocity value on more sophisticated synthesizers can also affect the timbre of the tone (as most instruments sound different when they are played louder or softer).
Note that the resulting call graph will most probably not contain main, but will contain all the functions executed after instrumentation wasenabled. Instrumentation can also programatically enabled/disabled. See the Callgrind include file callgrind.h for the macro you have to use in your sourcecode.
For cache simulation, results will be less accurate when switching on instrumentation later in the program run, as the simulator starts with an empty cacheat that moment. Switch on event collection later to cope with this error.
To only look at parts of your program, you have two possibilities:
Collection state can be toggled at entry and exit of a given function with the option --toggle-collect. If you use this option, collection stateshould 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.
Helgrind Options
--free-is-write=no|yes [default: no]
When enabled (not the default), Helgrind treats freeing of heap memory as if the memory was written immediately before the free. This exposes races wherememory is referenced by one thread, and freed by another, but there is no observable synchronisation event to ensure that the reference happens before thefree.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 memoryallocators is not well understood at present. User feedback is welcomed.
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 youjust 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 dramaticallyfaster 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, andapproximate information regarding the earlier access. This approximate information consists of two stacks, and the earlier access is guaranteed to haveoccurred 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.
Information about 'old' conflicting accesses is stored in a cache of limited size, with LRU-style management. This is necessary because it isn't practicalto 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 youfind 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 memoryrequirement by very roughly 100 bytes, so the maximum value will easily eat up three extra gigabytes or so of memory.
Drd Options
--check-stack-var=<yes|no> [default: no]
Massif Options
--heap=<yes|no> [default: yes]
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. Forexample, 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 thatchecking 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 thatdoesn'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 frombreaking them up. For example:
Any realloc of an ignored block will also be ignored, even if the realloc call does not occur in an ignored function. This avoids thepossibility 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.
Sgcheck Options
<xi:include></xi:include>.SH 'BBV OPTIONS'
--bb-out-file=<name> [default: bb.out.%p]
Lackey Options
--basic-counts=<no|yes> [default: yes]
See Also
cg_annotate(1), callgrind_annotate(1), callgrind_control(1), ms_print(1), $INSTALL/share/doc/valgrind/html/index.html orhttp://www.valgrind.org/docs/manual/index.html.
Author
The Valgrind developers.
This manpage was written by Andres Roldan <aroldan@debian.org> and the Valgrind developers.
Referenced By
lit(1),pulseaudio(1)IntroSettingsSyscallsIDEDebuggingCommandToolsHistoryLimitationsException HandlersMacrosAcknowledgementsMARS home
SYSCALL functions available in MARS
Introduction
A number of system services, mainly for input and output, are available for use by your MIPS program. They are described in the table below.
MIPS register contents are not affected by a system call, except for result registers as specified in the table below.
How to use SYSCALL system services
Step 1. Load the service number in register $v0.Step 2. Load argument values, if any, in $a0, $a1, $a2, or $f12 as specified.
Step 3. Issue the SYSCALL instruction.
Valgrind Invalid File Descriptor In Syscall Closed
Step 4. Retrieve return values, if any, from result registers as specified.Example: display the value stored in $t0 on the console
Table of Available Services
Service | Code in $v0 | Arguments | Result |
---|---|---|---|
print integer | 1 | $a0 = integer to print | |
print float | 2 | $f12 = float to print | |
print double | 3 | $f12 = double to print | |
print string | 4 | $a0 = address of null-terminated string to print | |
read integer | 5 | $v0 contains integer read | |
read float | 6 | $f0 contains float read | |
read double | 7 | $f0 contains double read | |
read string | 8 | $a0 = address of input buffer $a1 = maximum number of characters to read | See note below table |
sbrk (allocate heap memory) | 9 | $a0 = number of bytes to allocate | $v0 contains address of allocated memory |
exit (terminate execution) | 10 | ||
print character | 11 | $a0 = character to print | See note below table |
read character | 12 | $v0 contains character read | |
open file | 13 | $a0 = address of null-terminated string containing filename $a1 = flags $a2 = mode | $v0 contains file descriptor (negative if error). See note below table |
read from file | 14 | $a0 = file descriptor $a1 = address of input buffer $a2 = maximum number of characters to read | $v0 contains number of characters read (0 if end-of-file, negative if error). See note below table |
write to file | 15 | $a0 = file descriptor $a1 = address of output buffer $a2 = number of characters to write | $v0 contains number of characters written (negative if error). See note below table |
close file | 16 | $a0 = file descriptor | |
exit2 (terminate with value) | 17 | $a0 = termination result | See note below table |
Services 1 through 17 are compatible with the SPIM simulator, other than Open File (13) as described in the Notes below the table. Services 30 and higher are exclusive to MARS. | |||
time (system time) | 30 | $a0 = low order 32 bits of system time $a1 = high order 32 bits of system time. See note below table | |
MIDI out | 31 | $a0 = pitch (0-127) $a1 = duration in milliseconds $a2 = instrument (0-127) $a3 = volume (0-127) | Generate tone and return immediately. See note below table |
sleep | 32 | $a0 = the length of time to sleep in milliseconds. | Causes the MARS Java thread to sleep for (at least) the specified number of milliseconds. This timing will not be precise, as the Java implementation will add some overhead. |
MIDI out synchronous | 33 | $a0 = pitch (0-127) $a1 = duration in milliseconds $a2 = instrument (0-127) $a3 = volume (0-127) | Generate tone and return upon tone completion. See note below table |
print integer in hexadecimal | 34 | $a0 = integer to print | Displayed value is 8 hexadecimal digits, left-padding with zeroes if necessary. |
print integer in binary | 35 | $a0 = integer to print | Displayed value is 32 bits, left-padding with zeroes if necessary. |
print integer as unsigned | 36 | $a0 = integer to print | Displayed as unsigned decimal value. |
(not used) | 37-39 | ||
set seed | 40 | $a0 = i.d. of pseudorandom number generator (any int). $a1 = seed for corresponding pseudorandom number generator. | No values are returned. Sets the seed of the corresponding underlying Java pseudorandom number generator (java.util.Random). See note below table |
random int | 41 | $a0 = i.d. of pseudorandom number generator (any int). | $a0 contains the next pseudorandom, uniformly distributed int value from this random number generator's sequence. See note below table |
random int range | 42 | $a0 = i.d. of pseudorandom number generator (any int). $a1 = upper bound of range of returned values. | $a0 contains pseudorandom, uniformly distributed int value in the range 0 <= [int] < [upper bound], drawn from this random number generator's sequence. See note below table |
random float | 43 | $a0 = i.d. of pseudorandom number generator (any int). | $f0 contains the next pseudorandom, uniformly distributed float value in the range 0.0 <= f < 1.0 from this random number generator's sequence. See note below table |
random double | 44 | $a0 = i.d. of pseudorandom number generator (any int). | $f0 contains the next pseudorandom, uniformly distributed double value in the range 0.0 <= f < 1.0 from this random number generator's sequence. See note below table |
(not used) | 45-49 | ||
ConfirmDialog | 50 | $a0 = address of null-terminated string that is the message to user | $a0 contains value of user-chosen option 0: Yes 1: No 2: Cancel |
InputDialogInt | 51 | $a0 = address of null-terminated string that is the message to user | $a0 contains int read $a1 contains status value 0: OK status -1: input data cannot be correctly parsed -2: Cancel was chosen -3: OK was chosen but no data had been input into field |
InputDialogFloat | 52 | $a0 = address of null-terminated string that is the message to user | $f0 contains float read $a1 contains status value 0: OK status -1: input data cannot be correctly parsed -2: Cancel was chosen -3: OK was chosen but no data had been input into field |
InputDialogDouble | 53 | $a0 = address of null-terminated string that is the message to user | $f0 contains double read $a1 contains status value 0: OK status -1: input data cannot be correctly parsed -2: Cancel was chosen -3: OK was chosen but no data had been input into field |
InputDialogString | 54 | $a0 = address of null-terminated string that is the message to user $a1 = address of input buffer $a2 = maximum number of characters to read | See Service 8 note below table $a1 contains status value 0: OK status. Buffer contains the input string. -2: Cancel was chosen. No change to buffer. -3: OK was chosen but no data had been input into field. No change to buffer. -4: length of the input string exceeded the specified maximum. Buffer contains the maximum allowable input string plus a terminating null. |
MessageDialog | 55 | $a0 = address of null-terminated string that is the message to user $a1 = the type of message to be displayed: 0: error message, indicated by Error icon 1: information message, indicated by Information icon 2: warning message, indicated by Warning icon 3: question message, indicated by Question icon other: plain message (no icon displayed) | N/A |
MessageDialogInt | 56 | $a0 = address of null-terminated string that is an information-type message to user $a1 = int value to display in string form after the first string | N/A |
MessageDialogFloat | 57 | $a0 = address of null-terminated string that is an information-type message to user $f12 = float value to display in string form after the first string | N/A |
MessageDialogDouble | 58 | $a0 = address of null-terminated string that is an information-type message to user $f12 = double value to display in string form after the first string | N/A |
MessageDialogString | 59 | $a0 = address of null-terminated string that is an information-type message to user $a1 = address of null-terminated string to display after the first string | N/A |
NOTES: Services numbered 30 and higher are not provided by SPIM
Service 8 - Follows semantics of UNIX 'fgets'. For specified length n, string can be no longer than n-1. If less than that, adds newline to end. In either case, then pads with null byte If n = 1, input is ignored and null byte placed at buffer address. If n < 1, input is ignored and nothing is written to the buffer.
Service 11 - Prints ASCII character corresponding to contents of low-order byte.
Service 13 - MARS implements three flag values: 0 for read-only, 1 for write-only with create, and 9 for write-only with create and append. It ignores mode. The returned file descriptor will be negative if the operation failed. The underlying file I/O implementation uses java.io.FileInputStream.read() to read and java.io.FileOutputStream.write() to write. MARS maintains file descriptors internally and allocates them starting with 3. File descriptors 0, 1 and 2 are always open for: reading from standard input, writing to standard output, and writing to standard error, respectively (new in release 4.3).
Services 13,14,15 - In MARS 3.7, the result register was changed to $v0 for SPIM compatability. It was previously $a0 as erroneously printed in Appendix B of Computer Organization and Design,.
Service 17 - If the MIPS program is run under control of the MARS graphical interface (GUI), the exit code in $a0 is ignored.
Service 30 - System time comes from java.util.Date.getTime() as milliseconds since 1 January 1970.
Services 31,33 - Simulate MIDI output through sound card. Details below.
Services 40-44 use underlying Java pseudorandom number generators provided by the java.util.Random class. Each stream (identified by $a0 contents) is modeled by a different Random object. There are no default seed values, so use the Set Seed service (40) if replicated random sequences are desired.
Example of File I/O
The sample MIPS program below will open a new file for writing, write text to it from a memory buffer, then close it. The file will be created in the directory in which MARS was run.Using SYSCALL system services 31 and 33: MIDI output
These system services are unique to MARS, and provide a means of producing sound. MIDI output is simulated by your system sound card, and the simulation is provided by the javax.sound.midi package.Service 31 will generate the tone then immediately return. Service 33 will generate the tone then sleep for the tone's duration before returning. Thus it essentially combines services 31 and 32.
This service requires four parameters as follows:Valgrind Invalid File Descriptor In Syscall Closet
pitch ($a0) | ||||||||||||||||||||||||||||||||
duration in milliseconds ($a1) | ||||||||||||||||||||||||||||||||
instrument ($a2)
| ||||||||||||||||||||||||||||||||
volume ($a3) |