2 /*--------------------------------------------------------------------*/
3 /*--- Startup: the real stuff m_main.c ---*/
4 /*--------------------------------------------------------------------*/
7 This file is part of Valgrind, a dynamic binary instrumentation
10 Copyright (C) 2000-2012 Julian Seward
13 This program is free software; you can redistribute it and/or
14 modify it under the terms of the GNU General Public License as
15 published by the Free Software Foundation; either version 2 of the
16 License, or (at your option) any later version.
18 This program is distributed in the hope that it will be useful, but
19 WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 General Public License for more details.
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
28 The GNU General Public License is contained in the file COPYING.
31 #include "pub_core_basics.h"
32 #include "pub_core_vki.h"
33 #include "pub_core_vkiscnums.h"
34 #include "pub_core_libcsetjmp.h" // to keep _threadstate.h happy
35 #include "pub_core_threadstate.h"
36 #include "pub_core_xarray.h"
37 #include "pub_core_clientstate.h"
38 #include "pub_core_aspacemgr.h"
39 #include "pub_core_aspacehl.h"
40 #include "pub_core_commandline.h"
41 #include "pub_core_debuglog.h"
42 #include "pub_core_errormgr.h"
43 #include "pub_core_execontext.h"
44 #include "pub_core_gdbserver.h"
45 #include "pub_core_initimg.h"
46 #include "pub_core_libcbase.h"
47 #include "pub_core_libcassert.h"
48 #include "pub_core_libcfile.h"
49 #include "pub_core_libcprint.h"
50 #include "pub_core_libcproc.h"
51 #include "pub_core_libcsignal.h"
52 #include "pub_core_syscall.h" // VG_(strerror)
53 #include "pub_core_mach.h"
54 #include "pub_core_machine.h"
55 #include "pub_core_mallocfree.h"
56 #include "pub_core_options.h"
57 #include "pub_core_debuginfo.h"
58 #include "pub_core_redir.h"
59 #include "pub_core_scheduler.h"
60 #include "pub_core_seqmatch.h" // For VG_(string_match)
61 #include "pub_core_signals.h"
62 #include "pub_core_stacks.h" // For VG_(register_stack)
63 #include "pub_core_syswrap.h"
64 #include "pub_core_tooliface.h"
65 #include "pub_core_translate.h" // For VG_(translate)
66 #include "pub_core_trampoline.h"
67 #include "pub_core_transtab.h"
68 #include "pub_tool_inner.h"
69 #if defined(ENABLE_INNER_CLIENT_REQUEST)
74 /*====================================================================*/
75 /*=== Counters, for profiling purposes only ===*/
76 /*====================================================================*/
78 static void print_all_stats ( void )
80 VG_(print_translation_stats)();
81 VG_(print_tt_tc_stats)();
82 VG_(print_scheduler_stats)();
83 VG_(print_ExeContext_stats)();
84 VG_(print_errormgr_stats)();
87 if (VG_(clo_verbosity) > 2) {
88 VG_(message)(Vg_DebugMsg, "\n");
89 VG_(message)(Vg_DebugMsg,
90 "------ Valgrind's internal memory use stats follow ------\n" );
91 VG_(sanity_check_malloc_all)();
92 VG_(message)(Vg_DebugMsg, "------\n" );
93 VG_(print_all_arena_stats)();
94 VG_(message)(Vg_DebugMsg, "\n");
99 /*====================================================================*/
100 /*=== Command-line: variables, processing, etc ===*/
101 /*====================================================================*/
103 // See pub_{core,tool}_options.h for explanations of all these.
105 static void usage_NORETURN ( Bool debug_help )
107 /* 'usage1' contains a %s
108 - for the name of the GDB executable
109 - for the name of vgdb's path prefix
110 which must be supplied when they are VG_(printf)'d. */
111 const HChar* usage1 =
112 "usage: valgrind [options] prog-and-args\n"
114 " tool-selection option, with default in [ ]:\n"
115 " --tool=<name> use the Valgrind tool named <name> [memcheck]\n"
117 " basic user options for all Valgrind tools, with defaults in [ ]:\n"
118 " -h --help show this message\n"
119 " --help-debug show this message, plus debugging options\n"
120 " --version show version\n"
121 " -q --quiet run silently; only print error msgs\n"
122 " -v --verbose be more verbose -- show misc extra info\n"
123 " --trace-children=no|yes Valgrind-ise child processes (follow execve)? [no]\n"
124 " --trace-children-skip=patt1,patt2,... specifies a list of executables\n"
125 " that --trace-children=yes should not trace into\n"
126 " --trace-children-skip-by-arg=patt1,patt2,... same as --trace-children-skip=\n"
127 " but check the argv[] entries for children, rather\n"
128 " than the exe name, to make a follow/no-follow decision\n"
129 " --child-silent-after-fork=no|yes omit child output between fork & exec? [no]\n"
130 " --vgdb=no|yes|full activate gdbserver? [yes]\n"
131 " full is slower but provides precise watchpoint/step\n"
132 " --vgdb-error=<number> invoke gdbserver after <number> errors [%d]\n"
133 " to get started quickly, use --vgdb-error=0\n"
134 " and follow the on-screen directions\n"
135 " --track-fds=no|yes track open file descriptors? [no]\n"
136 " --time-stamp=no|yes add timestamps to log messages? [no]\n"
137 " --log-fd=<number> log messages to file descriptor [2=stderr]\n"
138 " --log-file=<file> log messages to <file>\n"
139 " --log-socket=ipaddr:port log messages to socket ipaddr:port\n"
141 " user options for Valgrind tools that report errors:\n"
142 " --xml=yes emit error output in XML (some tools only)\n"
143 " --xml-fd=<number> XML output to file descriptor\n"
144 " --xml-file=<file> XML output to <file>\n"
145 " --xml-socket=ipaddr:port XML output to socket ipaddr:port\n"
146 " --xml-user-comment=STR copy STR verbatim into XML output\n"
147 " --demangle=no|yes automatically demangle C++ names? [yes]\n"
148 " --num-callers=<number> show <number> callers in stack traces [12]\n"
149 " --error-limit=no|yes stop showing new errors if too many? [yes]\n"
150 " --error-exitcode=<number> exit code to return if errors found [0=disable]\n"
151 " --show-below-main=no|yes continue stack traces below main() [no]\n"
152 " --suppressions=<filename> suppress errors described in <filename>\n"
153 " --gen-suppressions=no|yes|all print suppressions for errors? [no]\n"
154 " --db-attach=no|yes start debugger when errors detected? [no]\n"
155 " --db-command=<command> command to start debugger [%s -nw %%f %%p]\n"
156 " --input-fd=<number> file descriptor for input [0=stdin]\n"
157 " --dsymutil=no|yes run dsymutil on Mac OS X when helpful? [no]\n"
158 " --max-stackframe=<number> assume stack switch for SP changes larger\n"
159 " than <number> bytes [2000000]\n"
160 " --main-stacksize=<number> set size of main thread's stack (in bytes)\n"
161 " [use current 'ulimit' value]\n"
163 " user options for Valgrind tools that replace malloc:\n"
164 " --alignment=<number> set minimum alignment of heap allocations [%s]\n"
165 " --redzone-size=<number> set minimum size of redzones added before/after\n"
166 " heap blocks (in bytes). [%s]\n"
168 " uncommon user options for all Valgrind tools:\n"
169 " --fullpath-after= (with nothing after the '=')\n"
170 " show full source paths in call stacks\n"
171 " --fullpath-after=string like --fullpath-after=, but only show the\n"
172 " part of the path after 'string'. Allows removal\n"
173 " of path prefixes. Use this flag multiple times\n"
174 " to specify a set of prefixes to remove.\n"
175 " --smc-check=none|stack|all|all-non-file [stack]\n"
176 " checks for self-modifying code: none, only for\n"
177 " code found in stacks, for all code, or for all\n"
178 " code except that from file-backed mappings\n"
179 " --read-var-info=yes|no read debug info on stack and global variables\n"
180 " and use it to print better error messages in\n"
181 " tools that make use of it (Memcheck, Helgrind,\n"
183 " --vgdb-poll=<number> gdbserver poll max every <number> basic blocks [%d] \n"
184 " --vgdb-shadow-registers=no|yes let gdb see the shadow registers [no]\n"
185 " --vgdb-prefix=<prefix> prefix for vgdb FIFOs [%s]\n"
186 " --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]\n"
187 " --sim-hints=hint1,hint2,... known hints:\n"
188 " lax-ioctls, enable-outer, fuse-compatible [none]\n"
189 " --fair-sched=no|yes|try schedule threads fairly on multicore systems [no]\n"
190 " --kernel-variant=variant1,variant2,... known variants: bproc [none]\n"
191 " handle non-standard kernel variants\n"
192 " --show-emwarns=no|yes show warnings about emulation limits? [no]\n"
193 " --require-text-symbol=:sonamepattern:symbolpattern abort run if the\n"
194 " stated shared object doesn't have the stated\n"
195 " text symbol. Patterns can contain ? and *.\n"
196 " --soname-synonyms=syn1=pattern1,syn2=pattern2,... synonym soname\n"
197 " specify patterns for function wrapping or replacement.\n"
198 " To use a non-libc malloc library that is\n"
199 " in the main exe: --soname-synonyms=somalloc=NONE\n"
200 " in libxyzzy.so: --soname-synonyms=somalloc=libxyzzy.so\n"
203 const HChar* usage2 =
205 " debugging options for all Valgrind tools:\n"
206 " -d show verbose debugging output\n"
207 " --stats=no|yes show tool and core statistics [no]\n"
208 " --sanity-level=<number> level of sanity checking to do [1]\n"
209 " --trace-flags=<XXXXXXXX> show generated code? (X = 0|1) [00000000]\n"
210 " --profile-flags=<XXXXXXXX> ditto, but for profiling (X = 0|1) [00000000]\n"
211 " --trace-notbelow=<number> only show BBs above <number> [999999999]\n"
212 " --trace-notabove=<number> only show BBs below <number> [0]\n"
213 " --trace-syscalls=no|yes show all system calls? [no]\n"
214 " --trace-signals=no|yes show signal handling details? [no]\n"
215 " --trace-symtab=no|yes show symbol table details? [no]\n"
216 " --trace-symtab-patt=<patt> limit debuginfo tracing to obj name <patt>\n"
217 " --trace-cfi=no|yes show call-frame-info details? [no]\n"
218 " --debug-dump=syms mimic /usr/bin/readelf --syms\n"
219 " --debug-dump=line mimic /usr/bin/readelf --debug-dump=line\n"
220 " --debug-dump=frames mimic /usr/bin/readelf --debug-dump=frames\n"
221 " --trace-redir=no|yes show redirection details? [no]\n"
222 " --trace-sched=no|yes show thread scheduler details? [no]\n"
223 " --profile-heap=no|yes profile Valgrind's own space use\n"
224 " --core-redzone-size=<number> set minimum size of redzones added before/after\n"
225 " heap blocks allocated for Valgrind internal use (in bytes) [4]\n"
226 " --wait-for-gdb=yes|no pause on startup to wait for gdb attach\n"
227 " --sym-offsets=yes|no show syms in form 'name+offset' ? [no]\n"
228 " --command-line-only=no|yes only use command line options [no]\n"
230 " Vex options for all Valgrind tools:\n"
231 " --vex-iropt-verbosity=<0..9> [0]\n"
232 " --vex-iropt-level=<0..2> [2]\n"
233 " --vex-iropt-register-updates=sp-at-mem-access\n"
234 " |unwindregs-at-mem-access\n"
235 " |allregs-at-mem-access\n"
236 " |allregs-at-each-insn [unwindregs-at-mem-access]\n"
237 " --vex-iropt-unroll-thresh=<0..400> [120]\n"
238 " --vex-guest-max-insns=<1..100> [50]\n"
239 " --vex-guest-chase-thresh=<0..99> [10]\n"
240 " --vex-guest-chase-cond=no|yes [no]\n"
241 " --trace-flags and --profile-flags values (omit the middle space):\n"
242 " 1000 0000 show conversion into IR\n"
243 " 0100 0000 show after initial opt\n"
244 " 0010 0000 show after instrumentation\n"
245 " 0001 0000 show after second opt\n"
246 " 0000 1000 show after tree building\n"
247 " 0000 0100 show selecting insns\n"
248 " 0000 0010 show after reg-alloc\n"
249 " 0000 0001 show final assembly\n"
250 " (Nb: you need --trace-notbelow and/or --trace-notabove with --trace-flags for full details)\n"
252 " debugging options for Valgrind tools that report errors\n"
253 " --dump-error=<number> show translation for basic block associated\n"
254 " with <number>'th error context [0=show none]\n"
256 " debugging options for Valgrind tools that replace malloc:\n"
257 " --trace-malloc=no|yes show client malloc details? [no]\n"
260 const HChar* usage3 =
262 " Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc\n"
265 " Valgrind is Copyright (C) 2000-2012, and GNU GPL'd, by Julian Seward et al.\n"
266 " LibVEX is Copyright (C) 2004-2012, and GNU GPL'd, by OpenWorks LLP et al.\n"
268 " Bug reports, feedback, admiration, abuse, etc, to: %s.\n"
271 const HChar* gdb_path = GDB_PATH;
272 Char default_alignment[30];
273 Char default_redzone_size[30];
275 // Ensure the message goes to stdout
276 VG_(log_output_sink).fd = 1;
277 VG_(log_output_sink).is_socket = False;
279 if (VG_(needs).malloc_replacement) {
280 VG_(sprintf)(default_alignment, "%d", VG_MIN_MALLOC_SZB);
281 VG_(sprintf)(default_redzone_size, "%lu", VG_(tdict).tool_client_redzone_szB);
283 VG_(strcpy)(default_alignment, "not used by this tool");
284 VG_(strcpy)(default_redzone_size, "not used by this tool");
286 /* 'usage1' a type as described after each arg. */
288 VG_(clo_vgdb_error) /* int */,
289 gdb_path /* char* */,
290 default_alignment /* char* */,
291 default_redzone_size /* char* */,
292 VG_(clo_vgdb_poll) /* int */,
293 VG_(vgdb_prefix_default)() /* char* */
295 if (VG_(details).name) {
296 VG_(printf)(" user options for %s:\n", VG_(details).name);
297 if (VG_(needs).command_line_options)
298 VG_TDICT_CALL(tool_print_usage);
300 VG_(printf)(" (none)\n");
303 VG_(printf)("%s", usage2);
305 if (VG_(details).name) {
306 VG_(printf)(" debugging options for %s:\n", VG_(details).name);
308 if (VG_(needs).command_line_options)
309 VG_TDICT_CALL(tool_print_debug_usage);
311 VG_(printf)(" (none)\n");
314 VG_(printf)(usage3, VG_(details).name, VG_(details).copyright_author,
320 /* Peer at previously set up VG_(args_for_valgrind) and do some
321 minimal command line processing that must happen early on:
323 - show the version string, if requested (-v)
324 - extract any request for help (--help, -h, --help-debug)
325 - get the toolname (--tool=)
326 - set VG_(clo_max_stackframe) (--max-stackframe=)
327 - set VG_(clo_main_stacksize) (--main-stacksize=)
328 - set VG_(clo_sim_hints) (--sim-hints=)
330 That's all it does. The main command line processing is done below
331 by main_process_cmd_line_options. Note that
332 main_process_cmd_line_options has to handle but ignore the ones we
335 static void early_process_cmd_line_options ( /*OUT*/Int* need_help,
336 /*OUT*/HChar** tool )
341 vg_assert( VG_(args_for_valgrind) );
343 /* parse the options we have (only the options we care about now) */
344 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
346 str = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
349 // Nb: the version string goes to stdout.
350 if VG_XACT_CLO(str, "--version", VG_(log_output_sink).fd, 1) {
351 VG_(log_output_sink).is_socket = False;
352 VG_(printf)("valgrind-" VERSION "\n");
355 else if VG_XACT_CLO(str, "--help", *need_help, *need_help+1) {}
356 else if VG_XACT_CLO(str, "-h", *need_help, *need_help+1) {}
358 else if VG_XACT_CLO(str, "--help-debug", *need_help, *need_help+2) {}
360 // The tool has already been determined, but we need to know the name
362 else if VG_STR_CLO(str, "--tool", *tool) {}
364 // Set up VG_(clo_max_stackframe) and VG_(clo_main_stacksize).
365 // These are needed by VG_(ii_create_image), which happens
366 // before main_process_cmd_line_options().
367 else if VG_INT_CLO(str, "--max-stackframe", VG_(clo_max_stackframe)) {}
368 else if VG_INT_CLO(str, "--main-stacksize", VG_(clo_main_stacksize)) {}
370 // Set up VG_(clo_sim_hints). This is needed a.o. for an inner
371 // running in an outer, to have "no-inner-prefix" enabled
372 // as early as possible.
373 else if VG_STR_CLO (str, "--sim-hints", VG_(clo_sim_hints)) {}
377 /* The main processing for command line options. See comments above
378 on early_process_cmd_line_options.
380 Comments on how the logging options are handled:
383 --log-fd= for a fd to write to (default setting, fd = 2)
384 --log-file= for a file name to write to
385 --log-socket= for a socket to write to
387 As a result of examining these and doing relevant socket/file
388 opening, a final fd is established. This is stored in
389 VG_(log_output_sink) in m_libcprint. Also, if --log-file=STR was
390 specified, then STR, after expansion of %p and %q templates within
391 it, is stored in VG_(clo_log_fname_expanded), in m_options, just in
392 case anybody wants to know what it is.
394 When printing, VG_(log_output_sink) is consulted to find the
395 fd to send output to.
397 Exactly analogous actions are undertaken for the XML output
398 channel, with the one difference that the default fd is -1, meaning
399 the channel is disabled by default.
402 void main_process_cmd_line_options ( /*OUT*/Bool* logging_to_fd,
403 /*OUT*/Char** xml_fname_unexpanded,
404 const HChar* toolname )
406 // VG_(clo_log_fd) is used by all the messaging. It starts as 2 (stderr)
407 // and we cannot change it until we know what we are changing it to is
408 // ok. So we have tmp_log_fd to hold the tmp fd prior to that point.
410 Int i, tmp_log_fd, tmp_xml_fd;
411 Int toolname_len = VG_(strlen)(toolname);
412 Char* tmp_str; // Used in a couple of places.
417 } log_to = VgLogTo_Fd, // Where is logging output to be sent?
418 xml_to = VgLogTo_Fd; // Where is XML output to be sent?
420 /* Temporarily holds the string STR specified with
421 --{log,xml}-{name,socket}=STR. 'fs' stands for
423 Char* log_fsname_unexpanded = NULL;
424 Char* xml_fsname_unexpanded = NULL;
426 /* Log to stderr by default, but usage message goes to stdout. XML
427 output is initially disabled. */
431 /* Check for sane path in ./configure --prefix=... */
432 if (VG_LIBDIR[0] != '/')
433 VG_(err_config_error)("Please use absolute paths in "
434 "./configure --prefix=... or --libdir=...\n");
436 vg_assert( VG_(args_for_valgrind) );
438 /* BEGIN command-line processing loop */
440 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
442 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
445 // Look for a colon in the option name.
446 while (*colon && *colon != ':' && *colon != '=')
449 // Does it have the form "--toolname:foo"? We have to do it at the start
450 // in case someone has combined a prefix with a core-specific option,
451 // eg. "--memcheck:verbose".
453 if (VG_STREQN(2, arg, "--") &&
454 VG_STREQN(toolname_len, arg+2, toolname) &&
455 VG_STREQN(1, arg+2+toolname_len, ":"))
457 // Prefix matches, convert "--toolname:foo" to "--foo".
458 // Two things to note:
459 // - We cannot modify the option in-place. If we did, and then
460 // a child was spawned with --trace-children=yes, the
461 // now-non-prefixed option would be passed and could screw up
463 // - We create copies, and never free them. Why? Non-prefixed
464 // options hang around forever, so tools need not make copies
465 // of strings within them. We need to have the same behaviour
466 // for prefixed options. The pointer to the copy will be lost
467 // once we leave this function (although a tool may keep a
468 // pointer into it), but the space wasted is insignificant.
469 // (In bug #142197, the copies were being freed, which caused
470 // problems for tools that reasonably assumed that arguments
471 // wouldn't disappear on them.)
473 VG_(printf)("tool-specific arg: %s\n", arg);
474 arg = VG_(strdup)("main.mpclo.1", arg + toolname_len + 1);
479 // prefix doesn't match, skip to next arg
484 /* Ignore these options - they've already been handled */
485 if VG_STREQN( 7, arg, "--tool=") {}
486 else if VG_STREQN(20, arg, "--command-line-only=") {}
487 else if VG_STREQ( arg, "--") {}
488 else if VG_STREQ( arg, "-d") {}
489 else if VG_STREQN(17, arg, "--max-stackframe=") {}
490 else if VG_STREQN(17, arg, "--main-stacksize=") {}
491 else if VG_STREQN(12, arg, "--sim-hints=") {}
492 else if VG_STREQN(15, arg, "--profile-heap=") {}
493 else if VG_STREQN(20, arg, "--core-redzone-size=") {}
494 else if VG_STREQN(15, arg, "--redzone-size=") {}
496 /* Obsolete options. Report an error and exit */
497 else if VG_STREQN(34, arg, "--vex-iropt-precise-memory-exns=no") {
500 "--vex-iropt-precise-memory-exns is obsolete\n"
501 "Use --vex-iropt-register-updates=unwindregs-at-mem-access instead\n");
503 else if VG_STREQN(35, arg, "--vex-iropt-precise-memory-exns=yes") {
506 "--vex-iropt-precise-memory-exns is obsolete\n"
507 "Use --vex-iropt-register-updates=allregs-at-mem-access instead\n"
508 " (or --vex-iropt-register-updates=allregs-at-each-insn)\n");
511 // These options are new.
512 else if (VG_STREQ(arg, "-v") ||
513 VG_STREQ(arg, "--verbose"))
514 VG_(clo_verbosity)++;
516 else if (VG_STREQ(arg, "-q") ||
517 VG_STREQ(arg, "--quiet"))
518 VG_(clo_verbosity)--;
520 else if VG_BOOL_CLO(arg, "--stats", VG_(clo_stats)) {}
521 else if VG_BOOL_CLO(arg, "--xml", VG_(clo_xml))
522 VG_(debugLog_setXml)(VG_(clo_xml));
524 else if VG_XACT_CLO(arg, "--vgdb=no", VG_(clo_vgdb), Vg_VgdbNo) {}
525 else if VG_XACT_CLO(arg, "--vgdb=yes", VG_(clo_vgdb), Vg_VgdbYes) {}
526 else if VG_XACT_CLO(arg, "--vgdb=full", VG_(clo_vgdb), Vg_VgdbFull) {
527 /* automatically updates register values at each insn
529 VG_(clo_vex_control).iropt_register_updates
530 = VexRegUpdAllregsAtEachInsn;
532 else if VG_INT_CLO (arg, "--vgdb-poll", VG_(clo_vgdb_poll)) {}
533 else if VG_INT_CLO (arg, "--vgdb-error", VG_(clo_vgdb_error)) {}
534 else if VG_STR_CLO (arg, "--vgdb-prefix", VG_(clo_vgdb_prefix)) {}
535 else if VG_BOOL_CLO(arg, "--vgdb-shadow-registers",
536 VG_(clo_vgdb_shadow_registers)) {}
537 else if VG_BOOL_CLO(arg, "--db-attach", VG_(clo_db_attach)) {}
538 else if VG_BOOL_CLO(arg, "--demangle", VG_(clo_demangle)) {}
539 else if VG_STR_CLO (arg, "--soname-synonyms",VG_(clo_soname_synonyms)) {}
540 else if VG_BOOL_CLO(arg, "--error-limit", VG_(clo_error_limit)) {}
541 else if VG_INT_CLO (arg, "--error-exitcode", VG_(clo_error_exitcode)) {}
542 else if VG_BOOL_CLO(arg, "--show-emwarns", VG_(clo_show_emwarns)) {}
544 else if VG_BOOL_CLO(arg, "--run-libc-freeres", VG_(clo_run_libc_freeres)) {}
545 else if VG_BOOL_CLO(arg, "--show-below-main", VG_(clo_show_below_main)) {}
546 else if VG_BOOL_CLO(arg, "--time-stamp", VG_(clo_time_stamp)) {}
547 else if VG_BOOL_CLO(arg, "--track-fds", VG_(clo_track_fds)) {}
548 else if VG_BOOL_CLO(arg, "--trace-children", VG_(clo_trace_children)) {}
549 else if VG_BOOL_CLO(arg, "--child-silent-after-fork",
550 VG_(clo_child_silent_after_fork)) {}
551 else if VG_STR_CLO(arg, "--fair-sched", tmp_str) {
552 if (VG_(strcmp)(tmp_str, "yes") == 0)
553 VG_(clo_fair_sched) = enable_fair_sched;
554 else if (VG_(strcmp)(tmp_str, "try") == 0)
555 VG_(clo_fair_sched) = try_fair_sched;
556 else if (VG_(strcmp)(tmp_str, "no") == 0)
557 VG_(clo_fair_sched) = disable_fair_sched;
559 VG_(fmsg_bad_option)(arg, "");
562 else if VG_BOOL_CLO(arg, "--trace-sched", VG_(clo_trace_sched)) {}
563 else if VG_BOOL_CLO(arg, "--trace-signals", VG_(clo_trace_signals)) {}
564 else if VG_BOOL_CLO(arg, "--trace-symtab", VG_(clo_trace_symtab)) {}
565 else if VG_STR_CLO (arg, "--trace-symtab-patt", VG_(clo_trace_symtab_patt)) {}
566 else if VG_BOOL_CLO(arg, "--trace-cfi", VG_(clo_trace_cfi)) {}
567 else if VG_XACT_CLO(arg, "--debug-dump=syms", VG_(clo_debug_dump_syms),
569 else if VG_XACT_CLO(arg, "--debug-dump=line", VG_(clo_debug_dump_line),
571 else if VG_XACT_CLO(arg, "--debug-dump=frames",
572 VG_(clo_debug_dump_frames), True) {}
573 else if VG_BOOL_CLO(arg, "--trace-redir", VG_(clo_trace_redir)) {}
575 else if VG_BOOL_CLO(arg, "--trace-syscalls", VG_(clo_trace_syscalls)) {}
576 else if VG_BOOL_CLO(arg, "--wait-for-gdb", VG_(clo_wait_for_gdb)) {}
577 else if VG_STR_CLO (arg, "--db-command", VG_(clo_db_command)) {}
578 else if VG_BOOL_CLO(arg, "--sym-offsets", VG_(clo_sym_offsets)) {}
579 else if VG_BOOL_CLO(arg, "--read-var-info", VG_(clo_read_var_info)) {}
581 else if VG_INT_CLO (arg, "--dump-error", VG_(clo_dump_error)) {}
582 else if VG_INT_CLO (arg, "--input-fd", VG_(clo_input_fd)) {}
583 else if VG_INT_CLO (arg, "--sanity-level", VG_(clo_sanity_level)) {}
584 else if VG_BINT_CLO(arg, "--num-callers", VG_(clo_backtrace_size), 1,
585 VG_DEEPEST_BACKTRACE) {}
587 else if VG_XACT_CLO(arg, "--smc-check=none", VG_(clo_smc_check),
589 else if VG_XACT_CLO(arg, "--smc-check=stack", VG_(clo_smc_check),
591 else if VG_XACT_CLO(arg, "--smc-check=all", VG_(clo_smc_check),
593 else if VG_XACT_CLO(arg, "--smc-check=all-non-file",
597 else if VG_STR_CLO (arg, "--kernel-variant", VG_(clo_kernel_variant)) {}
599 else if VG_BOOL_CLO(arg, "--dsymutil", VG_(clo_dsymutil)) {}
601 else if VG_STR_CLO (arg, "--trace-children-skip",
602 VG_(clo_trace_children_skip)) {}
603 else if VG_STR_CLO (arg, "--trace-children-skip-by-arg",
604 VG_(clo_trace_children_skip_by_arg)) {}
606 else if VG_BINT_CLO(arg, "--vex-iropt-verbosity",
607 VG_(clo_vex_control).iropt_verbosity, 0, 10) {}
608 else if VG_BINT_CLO(arg, "--vex-iropt-level",
609 VG_(clo_vex_control).iropt_level, 0, 2) {}
610 else if VG_XACT_CLO(arg,
611 "--vex-iropt-register-updates=sp-at-mem-access",
612 VG_(clo_vex_control).iropt_register_updates,
613 VexRegUpdSpAtMemAccess);
614 else if VG_XACT_CLO(arg,
615 "--vex-iropt-register-updates=unwindregs-at-mem-access",
616 VG_(clo_vex_control).iropt_register_updates,
617 VexRegUpdUnwindregsAtMemAccess);
618 else if VG_XACT_CLO(arg,
619 "--vex-iropt-register-updates=allregs-at-mem-access",
620 VG_(clo_vex_control).iropt_register_updates,
621 VexRegUpdAllregsAtMemAccess);
622 else if VG_XACT_CLO(arg,
623 "--vex-iropt-register-updates=allregs-at-each-insn",
624 VG_(clo_vex_control).iropt_register_updates,
625 VexRegUpdAllregsAtEachInsn);
626 else if VG_BINT_CLO(arg, "--vex-iropt-unroll-thresh",
627 VG_(clo_vex_control).iropt_unroll_thresh, 0, 400) {}
628 else if VG_BINT_CLO(arg, "--vex-guest-max-insns",
629 VG_(clo_vex_control).guest_max_insns, 1, 100) {}
630 else if VG_BINT_CLO(arg, "--vex-guest-chase-thresh",
631 VG_(clo_vex_control).guest_chase_thresh, 0, 99) {}
632 else if VG_BOOL_CLO(arg, "--vex-guest-chase-cond",
633 VG_(clo_vex_control).guest_chase_cond) {}
635 else if VG_INT_CLO(arg, "--log-fd", tmp_log_fd) {
637 log_fsname_unexpanded = NULL;
639 else if VG_INT_CLO(arg, "--xml-fd", tmp_xml_fd) {
641 xml_fsname_unexpanded = NULL;
644 else if VG_STR_CLO(arg, "--log-file", log_fsname_unexpanded) {
645 log_to = VgLogTo_File;
647 else if VG_STR_CLO(arg, "--xml-file", xml_fsname_unexpanded) {
648 xml_to = VgLogTo_File;
651 else if VG_STR_CLO(arg, "--log-socket", log_fsname_unexpanded) {
652 log_to = VgLogTo_Socket;
654 else if VG_STR_CLO(arg, "--xml-socket", xml_fsname_unexpanded) {
655 xml_to = VgLogTo_Socket;
658 else if VG_STR_CLO(arg, "--xml-user-comment",
659 VG_(clo_xml_user_comment)) {}
661 else if VG_STR_CLO(arg, "--suppressions", tmp_str) {
662 if (VG_(clo_n_suppressions) >= VG_CLO_MAX_SFILES) {
663 VG_(fmsg_bad_option)(arg,
664 "Too many suppression files specified.\n"
665 "Increase VG_CLO_MAX_SFILES and recompile.\n");
667 VG_(clo_suppressions)[VG_(clo_n_suppressions)] = tmp_str;
668 VG_(clo_n_suppressions)++;
671 else if VG_STR_CLO (arg, "--fullpath-after", tmp_str) {
672 if (VG_(clo_n_fullpath_after) >= VG_CLO_MAX_FULLPATH_AFTER) {
673 VG_(fmsg_bad_option)(arg,
674 "Too many --fullpath-after= specifications.\n"
675 "Increase VG_CLO_MAX_FULLPATH_AFTER and recompile.\n");
677 VG_(clo_fullpath_after)[VG_(clo_n_fullpath_after)] = tmp_str;
678 VG_(clo_n_fullpath_after)++;
681 else if VG_STR_CLO(arg, "--require-text-symbol", tmp_str) {
682 if (VG_(clo_n_req_tsyms) >= VG_CLO_MAX_REQ_TSYMS) {
683 VG_(fmsg_bad_option)(arg,
684 "Too many --require-text-symbol= specifications.\n"
685 "Increase VG_CLO_MAX_REQ_TSYMS and recompile.\n");
687 /* String needs to be of the form C?*C?*, where C is any
688 character, but is the same both times. Having it in this
689 form facilitates finding the boundary between the sopatt
690 and the fnpatt just by looking for the second occurrence
691 of C, without hardwiring any assumption about what C
695 ok = tmp_str && VG_(strlen)(tmp_str) > 0;
697 patt[0] = patt[3] = tmp_str[0];
698 patt[1] = patt[4] = '?';
699 patt[2] = patt[5] = '*';
701 ok = VG_(string_match)(patt, tmp_str);
704 VG_(fmsg_bad_option)(arg,
705 "Invalid --require-text-symbol= specification.\n");
707 VG_(clo_req_tsyms)[VG_(clo_n_req_tsyms)] = tmp_str;
708 VG_(clo_n_req_tsyms)++;
711 /* "stuvwxyz" --> stuvwxyz (binary) */
712 else if VG_STR_CLO(arg, "--trace-flags", tmp_str) {
715 if (8 != VG_(strlen)(tmp_str)) {
716 VG_(fmsg_bad_option)(arg,
717 "--trace-flags argument must have 8 digits\n");
719 for (j = 0; j < 8; j++) {
720 if ('0' == tmp_str[j]) { /* do nothing */ }
721 else if ('1' == tmp_str[j]) VG_(clo_trace_flags) |= (1 << (7-j));
723 VG_(fmsg_bad_option)(arg,
724 "--trace-flags argument can only contain 0s and 1s\n");
729 /* "stuvwxyz" --> stuvwxyz (binary) */
730 else if VG_STR_CLO(arg, "--profile-flags", tmp_str) {
733 if (8 != VG_(strlen)(tmp_str)) {
734 VG_(fmsg_bad_option)(arg,
735 "--profile-flags argument must have 8 digits\n");
737 for (j = 0; j < 8; j++) {
738 if ('0' == tmp_str[j]) { /* do nothing */ }
739 else if ('1' == tmp_str[j]) VG_(clo_profile_flags) |= (1 << (7-j));
741 VG_(fmsg_bad_option)(arg,
742 "--profile-flags argument can only contain 0s and 1s\n");
747 else if VG_INT_CLO (arg, "--trace-notbelow", VG_(clo_trace_notbelow)) {}
749 else if VG_INT_CLO (arg, "--trace-notabove", VG_(clo_trace_notabove)) {}
751 else if VG_XACT_CLO(arg, "--gen-suppressions=no",
752 VG_(clo_gen_suppressions), 0) {}
753 else if VG_XACT_CLO(arg, "--gen-suppressions=yes",
754 VG_(clo_gen_suppressions), 1) {}
755 else if VG_XACT_CLO(arg, "--gen-suppressions=all",
756 VG_(clo_gen_suppressions), 2) {}
758 else if ( ! VG_(needs).command_line_options
759 || ! VG_TDICT_CALL(tool_process_cmd_line_option, arg) ) {
760 VG_(fmsg_bad_option)(arg, "");
764 /* END command-line processing loop */
766 /* Determine the path prefix for vgdb */
767 if (VG_(clo_vgdb_prefix) == NULL)
768 VG_(clo_vgdb_prefix) = VG_(vgdb_prefix_default)();
770 /* Make VEX control parameters sane */
772 if (VG_(clo_vex_control).guest_chase_thresh
773 >= VG_(clo_vex_control).guest_max_insns)
774 VG_(clo_vex_control).guest_chase_thresh
775 = VG_(clo_vex_control).guest_max_insns - 1;
777 if (VG_(clo_vex_control).guest_chase_thresh < 0)
778 VG_(clo_vex_control).guest_chase_thresh = 0;
780 /* Check various option values */
782 if (VG_(clo_verbosity) < 0)
783 VG_(clo_verbosity) = 0;
785 if (VG_(clo_trace_notbelow) == -1) {
786 if (VG_(clo_trace_notabove) == -1) {
788 VG_(clo_trace_notbelow) = 2147483647;
789 VG_(clo_trace_notabove) = 0;
791 /* [0 .. notabove] */
792 VG_(clo_trace_notbelow) = 0;
795 if (VG_(clo_trace_notabove) == -1) {
797 VG_(clo_trace_notabove) = 2147483647;
799 /* [notbelow .. notabove] */
803 VG_(dyn_vgdb_error) = VG_(clo_vgdb_error);
805 if (VG_(clo_gen_suppressions) > 0 &&
806 !VG_(needs).core_errors && !VG_(needs).tool_errors) {
807 VG_(fmsg_bad_option)("--gen-suppressions=yes",
808 "Can't use --gen-suppressions= with %s\n"
809 "because it doesn't generate errors.\n", VG_(details).name);
812 /* If XML output is requested, check that the tool actually
814 if (VG_(clo_xml) && !VG_(needs).xml_output) {
815 VG_(clo_xml) = False;
816 VG_(fmsg_bad_option)("--xml=yes",
817 "%s does not support XML output.\n", VG_(details).name);
821 vg_assert( VG_(clo_gen_suppressions) >= 0 );
822 vg_assert( VG_(clo_gen_suppressions) <= 2 );
824 /* If we've been asked to emit XML, mash around various other
825 options so as to constrain the output somewhat, and to remove
826 any need for user input during the run.
830 /* We can't allow --gen-suppressions=yes, since that requires us
831 to print the error and then ask the user if she wants a
832 suppression for it, but in XML mode we won't print it until
833 we know whether we also need to print a suppression. Hence a
834 circular dependency. So disallow this.
835 (--gen-suppressions=all is still OK since we don't need any
836 user interaction in this case.) */
837 if (VG_(clo_gen_suppressions) == 1) {
838 VG_(fmsg_bad_option)(
839 "--xml=yes together with --gen-suppressions=yes",
840 "When --xml=yes is specified, --gen-suppressions=no\n"
841 "or --gen-suppressions=all is allowed, but not "
842 "--gen-suppressions=yes.\n");
845 /* We can't allow DB attaching (or we maybe could, but results
846 could be chaotic ..) since it requires user input. Hence
848 if (VG_(clo_db_attach)) {
849 VG_(fmsg_bad_option)(
850 "--xml=yes together with --db-attach=yes",
851 "--db-attach=yes is not allowed with --xml=yes\n"
852 "because it would require user input.\n");
855 /* Disallow dump_error in XML mode; sounds like a recipe for
856 chaos. No big deal; dump_error is a flag for debugging V
858 if (VG_(clo_dump_error) > 0) {
859 VG_(fmsg_bad_option)("--xml=yes together with --dump-error", "");
862 /* Disable error limits (this might be a bad idea!) */
863 VG_(clo_error_limit) = False;
864 /* Disable emulation warnings */
866 /* Also, we want to set options for the leak checker, but that
867 will have to be done in Memcheck's flag-handling code, not
871 /* All non-logging-related options have been checked. If the logging
872 option specified is ok, we can switch to it, as we know we won't
873 have to generate any other command-line-related error messages.
874 (So far we should be still attached to stderr, so we can show on
875 the terminal any problems to do with processing command line
878 So set up logging now. After this is done, VG_(log_output_sink)
879 and (if relevant) VG_(xml_output_sink) should be connected to
880 whatever sink has been selected, and we indiscriminately chuck
881 stuff into it without worrying what the nature of it is. Oh the
882 wonder of Unix streams. */
884 vg_assert(VG_(log_output_sink).fd == 2 /* stderr */);
885 vg_assert(VG_(log_output_sink).is_socket == False);
886 vg_assert(VG_(clo_log_fname_expanded) == NULL);
888 vg_assert(VG_(xml_output_sink).fd == -1 /* disabled */);
889 vg_assert(VG_(xml_output_sink).is_socket == False);
890 vg_assert(VG_(clo_xml_fname_expanded) == NULL);
892 /* --- set up the normal text output channel --- */
897 vg_assert(log_fsname_unexpanded == NULL);
903 vg_assert(log_fsname_unexpanded != NULL);
904 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
906 // Nb: we overwrite an existing file of this name without asking
908 logfilename = VG_(expand_file_name)("--log-file",
909 log_fsname_unexpanded);
910 sres = VG_(open)(logfilename,
911 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
912 VKI_S_IRUSR|VKI_S_IWUSR);
913 if (!sr_isError(sres)) {
914 tmp_log_fd = sr_Res(sres);
915 VG_(clo_log_fname_expanded) = logfilename;
917 VG_(fmsg)("can't create log file '%s': %s\n",
918 logfilename, VG_(strerror)(sr_Err(sres)));
925 case VgLogTo_Socket: {
926 vg_assert(log_fsname_unexpanded != NULL);
927 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
928 tmp_log_fd = VG_(connect_via_socket)( log_fsname_unexpanded );
929 if (tmp_log_fd == -1) {
930 VG_(fmsg)("Invalid --log-socket spec of '%s'\n",
931 log_fsname_unexpanded);
935 if (tmp_log_fd == -2) {
936 VG_(umsg)("failed to connect to logging server '%s'.\n"
937 "Log messages will sent to stderr instead.\n",
938 log_fsname_unexpanded );
940 /* We don't change anything here. */
941 vg_assert(VG_(log_output_sink).fd == 2);
944 vg_assert(tmp_log_fd > 0);
945 VG_(log_output_sink).is_socket = True;
951 /* --- set up the XML output channel --- */
956 vg_assert(xml_fsname_unexpanded == NULL);
962 vg_assert(xml_fsname_unexpanded != NULL);
963 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
965 // Nb: we overwrite an existing file of this name without asking
967 xmlfilename = VG_(expand_file_name)("--xml-file",
968 xml_fsname_unexpanded);
969 sres = VG_(open)(xmlfilename,
970 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
971 VKI_S_IRUSR|VKI_S_IWUSR);
972 if (!sr_isError(sres)) {
973 tmp_xml_fd = sr_Res(sres);
974 VG_(clo_xml_fname_expanded) = xmlfilename;
975 /* strdup here is probably paranoid overkill, but ... */
976 *xml_fname_unexpanded = VG_(strdup)( "main.mpclo.2",
977 xml_fsname_unexpanded );
979 VG_(fmsg)("can't create XML file '%s': %s\n",
980 xmlfilename, VG_(strerror)(sr_Err(sres)));
987 case VgLogTo_Socket: {
988 vg_assert(xml_fsname_unexpanded != NULL);
989 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
990 tmp_xml_fd = VG_(connect_via_socket)( xml_fsname_unexpanded );
991 if (tmp_xml_fd == -1) {
992 VG_(fmsg)("Invalid --xml-socket spec of '%s'\n",
993 xml_fsname_unexpanded );
997 if (tmp_xml_fd == -2) {
998 VG_(umsg)("failed to connect to XML logging server '%s'.\n"
999 "XML output will sent to stderr instead.\n",
1000 xml_fsname_unexpanded);
1001 /* We don't change anything here. */
1002 vg_assert(VG_(xml_output_sink).fd == 2);
1005 vg_assert(tmp_xml_fd > 0);
1006 VG_(xml_output_sink).is_socket = True;
1012 /* If we've got this far, and XML mode was requested, but no XML
1013 output channel appears to have been specified, just stop. We
1014 could continue, and XML output will simply vanish into nowhere,
1015 but that is likely to confuse the hell out of users, which is
1016 distinctly Ungood. */
1017 if (VG_(clo_xml) && tmp_xml_fd == -1) {
1018 VG_(fmsg_bad_option)(
1019 "--xml=yes, but no XML destination specified",
1020 "--xml=yes has been specified, but there is no XML output\n"
1021 "destination. You must specify an XML output destination\n"
1022 "using --xml-fd, --xml-file or --xml-socket.\n"
1026 // Finalise the output fds: the log fd ..
1028 if (tmp_log_fd >= 0) {
1029 // Move log_fd into the safe range, so it doesn't conflict with
1031 tmp_log_fd = VG_(fcntl)(tmp_log_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
1032 if (tmp_log_fd < 0) {
1033 VG_(message)(Vg_UserMsg, "valgrind: failed to move logfile fd "
1034 "into safe range, using stderr\n");
1035 VG_(log_output_sink).fd = 2; // stderr
1036 VG_(log_output_sink).is_socket = False;
1038 VG_(log_output_sink).fd = tmp_log_fd;
1039 VG_(fcntl)(VG_(log_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
1042 // If they said --log-fd=-1, don't print anything. Plausible for use in
1043 // regression testing suites that use client requests to count errors.
1044 VG_(log_output_sink).fd = -1;
1045 VG_(log_output_sink).is_socket = False;
1048 // Finalise the output fds: and the XML fd ..
1050 if (tmp_xml_fd >= 0) {
1051 // Move xml_fd into the safe range, so it doesn't conflict with
1053 tmp_xml_fd = VG_(fcntl)(tmp_xml_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
1054 if (tmp_xml_fd < 0) {
1055 VG_(message)(Vg_UserMsg, "valgrind: failed to move XML file fd "
1056 "into safe range, using stderr\n");
1057 VG_(xml_output_sink).fd = 2; // stderr
1058 VG_(xml_output_sink).is_socket = False;
1060 VG_(xml_output_sink).fd = tmp_xml_fd;
1061 VG_(fcntl)(VG_(xml_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
1064 // If they said --xml-fd=-1, don't print anything. Plausible for use in
1065 // regression testing suites that use client requests to count errors.
1066 VG_(xml_output_sink).fd = -1;
1067 VG_(xml_output_sink).is_socket = False;
1070 // Suppressions related stuff
1072 if (VG_(clo_n_suppressions) < VG_CLO_MAX_SFILES-1 &&
1073 (VG_(needs).core_errors || VG_(needs).tool_errors)) {
1074 /* If we haven't reached the max number of suppressions, load
1076 static const HChar default_supp[] = "default.supp";
1077 Int len = VG_(strlen)(VG_(libdir)) + 1 + sizeof(default_supp);
1078 Char *buf = VG_(arena_malloc)(VG_AR_CORE, "main.mpclo.3", len);
1079 VG_(sprintf)(buf, "%s/%s", VG_(libdir), default_supp);
1080 VG_(clo_suppressions)[VG_(clo_n_suppressions)] = buf;
1081 VG_(clo_n_suppressions)++;
1084 *logging_to_fd = log_to == VgLogTo_Fd || log_to == VgLogTo_Socket;
1087 // Write the name and value of log file qualifiers to the xml file.
1088 static void print_file_vars(Char* format)
1093 if (format[i] == '%') {
1094 // We saw a '%'. What's next...
1096 if ('q' == format[i]) {
1098 if ('{' == format[i]) {
1099 // Get the env var name, print its contents.
1103 qualname = &format[i];
1105 if ('}' == format[i]) {
1106 // Temporarily replace the '}' with NUL to extract var
1109 qual = VG_(getenv)(qualname);
1116 "<logfilequalifier> <var>%pS</var> "
1117 "<value>%pS</value> </logfilequalifier>\n",
1131 /*====================================================================*/
1132 /*=== Printing the preamble ===*/
1133 /*====================================================================*/
1135 // Print the argument, escaping any chars that require it.
1136 static void umsg_arg(const Char* arg)
1138 SizeT len = VG_(strlen)(arg);
1139 const HChar* special = " \\<>";
1141 for (i = 0; i < len; i++) {
1142 if (VG_(strchr)(special, arg[i])) {
1143 VG_(umsg)("\\"); // escape with a backslash if necessary
1145 VG_(umsg)("%c", arg[i]);
1149 // Send output to the XML-stream and escape any XML meta-characters.
1150 static void xml_arg(const Char* arg)
1152 VG_(printf_xml)("%pS", arg);
1155 /* Ok, the logging sink is running now. Print a suitable preamble.
1156 If logging to file or a socket, write details of parent PID and
1157 command line args, to help people trying to interpret the
1158 results of a run which encompasses multiple processes. */
1159 static void print_preamble ( Bool logging_to_fd,
1160 Char* xml_fname_unexpanded,
1161 const HChar* toolname )
1164 HChar* xpre = VG_(clo_xml) ? " <line>" : "";
1165 HChar* xpost = VG_(clo_xml) ? "</line>" : "";
1166 UInt (*umsg_or_xml)( const HChar*, ... )
1167 = VG_(clo_xml) ? VG_(printf_xml) : VG_(umsg);
1169 void (*umsg_or_xml_arg)( const Char* )
1170 = VG_(clo_xml) ? xml_arg : umsg_arg;
1172 vg_assert( VG_(args_for_client) );
1173 vg_assert( VG_(args_for_valgrind) );
1174 vg_assert( toolname );
1177 VG_(printf_xml)("<?xml version=\"1.0\"?>\n");
1178 VG_(printf_xml)("\n");
1179 VG_(printf_xml)("<valgrindoutput>\n");
1180 VG_(printf_xml)("\n");
1181 VG_(printf_xml)("<protocolversion>4</protocolversion>\n");
1182 VG_(printf_xml)("<protocoltool>%s</protocoltool>\n", toolname);
1183 VG_(printf_xml)("\n");
1186 if (VG_(clo_xml) || VG_(clo_verbosity > 0)) {
1189 VG_(printf_xml)("<preamble>\n");
1192 umsg_or_xml( VG_(clo_xml) ? "%s%pS%pS%pS, %pS%s\n" : "%s%s%s%s, %s%s\n",
1195 NULL == VG_(details).version ? "" : "-",
1196 NULL == VG_(details).version
1197 ? "" : VG_(details).version,
1198 VG_(details).description,
1201 if (VG_(strlen)(toolname) >= 4 && VG_STREQN(4, toolname, "exp-")) {
1203 "%sNOTE: This is an Experimental-Class Valgrind Tool%s\n",
1208 umsg_or_xml( VG_(clo_xml) ? "%s%pS%s\n" : "%s%s%s\n",
1209 xpre, VG_(details).copyright_author, xpost );
1213 "%sUsing Valgrind-%s and LibVEX; rerun with -h for copyright info%s\n",
1214 xpre, VERSION, xpost
1217 // Print the command line. At one point we wrapped at 80 chars and
1218 // printed a '\' as a line joiner, but that makes it hard to cut and
1219 // paste the command line (because of the "==pid==" prefixes), so we now
1220 // favour utility and simplicity over aesthetics.
1221 umsg_or_xml("%sCommand: ", xpre);
1222 if (VG_(args_the_exename))
1223 umsg_or_xml_arg(VG_(args_the_exename));
1225 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1226 HChar* s = *(HChar**)VG_(indexXA)( VG_(args_for_client), i );
1230 umsg_or_xml("%s\n", xpost);
1233 VG_(printf_xml)("</preamble>\n");
1236 // Print the parent PID, and other stuff, if necessary.
1237 if (!VG_(clo_xml) && VG_(clo_verbosity) > 0 && !logging_to_fd) {
1238 VG_(umsg)("Parent PID: %d\n", VG_(getppid)());
1242 VG_(printf_xml)("\n");
1243 VG_(printf_xml)("<pid>%d</pid>\n", VG_(getpid)());
1244 VG_(printf_xml)("<ppid>%d</ppid>\n", VG_(getppid)());
1245 VG_(printf_xml)("<tool>%pS</tool>\n", toolname);
1246 if (xml_fname_unexpanded)
1247 print_file_vars(xml_fname_unexpanded);
1248 if (VG_(clo_xml_user_comment)) {
1249 /* Note: the user comment itself is XML and is therefore to
1250 be passed through verbatim (%s) rather than escaped
1252 VG_(printf_xml)("<usercomment>%s</usercomment>\n",
1253 VG_(clo_xml_user_comment));
1255 VG_(printf_xml)("\n");
1256 VG_(printf_xml)("<args>\n");
1258 VG_(printf_xml)(" <vargv>\n");
1259 if (VG_(name_of_launcher))
1260 VG_(printf_xml)(" <exe>%pS</exe>\n",
1261 VG_(name_of_launcher));
1263 VG_(printf_xml)(" <exe>%pS</exe>\n",
1264 "(launcher name unknown)");
1265 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
1267 " <arg>%pS</arg>\n",
1268 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1271 VG_(printf_xml)(" </vargv>\n");
1273 VG_(printf_xml)(" <argv>\n");
1274 if (VG_(args_the_exename))
1275 VG_(printf_xml)(" <exe>%pS</exe>\n",
1276 VG_(args_the_exename));
1277 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1279 " <arg>%pS</arg>\n",
1280 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1283 VG_(printf_xml)(" </argv>\n");
1285 VG_(printf_xml)("</args>\n");
1288 // Last thing in the preamble is a blank line.
1290 VG_(printf_xml)("\n");
1291 else if (VG_(clo_verbosity) > 0)
1294 # if defined(VGO_darwin) && DARWIN_VERS == DARWIN_10_8
1295 /* Uh, this doesn't play nice with XML output. */
1296 umsg_or_xml( "WARNING: Support on MacOS 10.8 is experimental and mostly broken.\n");
1297 umsg_or_xml( "WARNING: Expect incorrect results, assertions and crashes.\n");
1298 umsg_or_xml( "WARNING: In particular, Memcheck on 32-bit programs will fail to\n");
1299 umsg_or_xml( "WARNING: detect any errors associated with heap-allocated data.\n");
1300 umsg_or_xml( "\n" );
1303 if (VG_(clo_verbosity) > 1) {
1306 VexArchInfo vex_archinfo;
1308 VG_(message)(Vg_DebugMsg, "\n");
1309 VG_(message)(Vg_DebugMsg, "Valgrind options:\n");
1310 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
1311 VG_(message)(Vg_DebugMsg,
1313 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ));
1316 VG_(message)(Vg_DebugMsg, "Contents of /proc/version:\n");
1317 fd = VG_(open) ( "/proc/version", VKI_O_RDONLY, 0 );
1318 if (sr_isError(fd)) {
1319 VG_(message)(Vg_DebugMsg, " can't open /proc/version\n");
1321 # define BUF_LEN 256
1322 Char version_buf[BUF_LEN];
1323 Int n = VG_(read) ( sr_Res(fd), version_buf, BUF_LEN );
1324 vg_assert(n <= BUF_LEN);
1326 version_buf[n-1] = '\0';
1327 VG_(message)(Vg_DebugMsg, " %s\n", version_buf);
1329 VG_(message)(Vg_DebugMsg, " (empty?)\n");
1331 VG_(close)(sr_Res(fd));
1335 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
1338 "Arch and hwcaps: %s, %s\n",
1339 LibVEX_ppVexArch ( vex_arch ),
1340 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1344 "Page sizes: currently %d, max supported %d\n",
1345 (Int)VKI_PAGE_SIZE, (Int)VKI_MAX_PAGE_SIZE
1347 VG_(message)(Vg_DebugMsg,
1348 "Valgrind library directory: %s\n", VG_(libdir));
1353 /*====================================================================*/
1354 /*=== File descriptor setup ===*/
1355 /*====================================================================*/
1357 /* Number of file descriptors that Valgrind tries to reserve for
1358 it's own use - just a small constant. */
1359 #define N_RESERVED_FDS (10)
1361 static void setup_file_descriptors(void)
1363 struct vki_rlimit rl;
1366 /* Get the current file descriptor limits. */
1367 if (VG_(getrlimit)(VKI_RLIMIT_NOFILE, &rl) < 0) {
1372 # if defined(VGO_darwin)
1373 /* Darwin lies. It reports file max as RLIM_INFINITY but
1374 silently disallows anything bigger than 10240. */
1375 if (rl.rlim_cur >= 10240 && rl.rlim_max == 0x7fffffffffffffffULL) {
1376 rl.rlim_max = 10240;
1381 VG_(printf)("fd limits: host, before: cur %lu max %lu\n",
1382 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
1384 /* Work out where to move the soft limit to. */
1385 if (rl.rlim_cur + N_RESERVED_FDS <= rl.rlim_max) {
1386 rl.rlim_cur = rl.rlim_cur + N_RESERVED_FDS;
1388 rl.rlim_cur = rl.rlim_max;
1391 /* Reserve some file descriptors for our use. */
1392 VG_(fd_soft_limit) = rl.rlim_cur - N_RESERVED_FDS;
1393 VG_(fd_hard_limit) = rl.rlim_cur - N_RESERVED_FDS;
1395 /* Update the soft limit. */
1396 VG_(setrlimit)(VKI_RLIMIT_NOFILE, &rl);
1399 VG_(printf)("fd limits: host, after: cur %lu max %lu\n",
1400 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
1401 VG_(printf)("fd limits: guest : cur %u max %u\n",
1402 VG_(fd_soft_limit), VG_(fd_hard_limit));
1405 if (VG_(cl_exec_fd) != -1)
1406 VG_(cl_exec_fd) = VG_(safe_fd)( VG_(cl_exec_fd) );
1410 /*====================================================================*/
1411 /*=== BB profiling ===*/
1412 /*====================================================================*/
1415 void show_BB_profile ( BBProfEntry tops[], UInt n_tops, ULong score_total )
1417 ULong score_cumul, score_here;
1418 Char buf_cumul[10], buf_here[10];
1423 VG_(printf)("-----------------------------------------------------------\n");
1424 VG_(printf)("--- BEGIN BB Profile (summary of scores) ---\n");
1425 VG_(printf)("-----------------------------------------------------------\n");
1428 VG_(printf)("Total score = %lld\n\n", score_total);
1431 for (r = 0; r < n_tops; r++) {
1432 if (tops[r].addr == 0)
1435 VG_(get_fnname_w_offset)(tops[r].addr, name, 64);
1437 score_here = tops[r].score;
1438 score_cumul += score_here;
1439 VG_(percentify)(score_cumul, score_total, 2, 6, buf_cumul);
1440 VG_(percentify)(score_here, score_total, 2, 6, buf_here);
1441 VG_(printf)("%3d: (%9lld %s) %9lld %s 0x%llx %s\n",
1443 score_cumul, buf_cumul,
1444 score_here, buf_here, tops[r].addr, name );
1448 VG_(printf)("-----------------------------------------------------------\n");
1449 VG_(printf)("--- BB Profile (BB details) ---\n");
1450 VG_(printf)("-----------------------------------------------------------\n");
1454 for (r = 0; r < n_tops; r++) {
1455 if (tops[r].addr == 0)
1458 VG_(get_fnname_w_offset)(tops[r].addr, name, 64);
1460 score_here = tops[r].score;
1461 score_cumul += score_here;
1462 VG_(percentify)(score_cumul, score_total, 2, 6, buf_cumul);
1463 VG_(percentify)(score_here, score_total, 2, 6, buf_here);
1465 VG_(printf)("=-=-=-=-=-=-=-=-=-=-=-=-=-= begin BB rank %d "
1466 "=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n", r);
1467 VG_(printf)("%3d: (%9lld %s) %9lld %s 0x%llx %s\n",
1469 score_cumul, buf_cumul,
1470 score_here, buf_here, tops[r].addr, name );
1472 VG_(discard_translations)(tops[r].addr, 1, "bb profile");
1473 VG_(translate)(0, tops[r].addr, True, VG_(clo_profile_flags), 0, True);
1474 VG_(printf)("=-=-=-=-=-=-=-=-=-=-=-=-=-= end BB rank %d "
1475 "=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n", r);
1479 VG_(printf)("-----------------------------------------------------------\n");
1480 VG_(printf)("--- END BB Profile ---\n");
1481 VG_(printf)("-----------------------------------------------------------\n");
1486 /*====================================================================*/
1488 /*====================================================================*/
1490 /* When main() is entered, we should be on the following stack, not
1491 the one the kernel gave us. We will run on this stack until
1492 simulation of the root thread is started, at which point a transfer
1493 is made to a dynamically allocated stack. This is for the sake of
1494 uniform overflow detection for all Valgrind threads. This is
1495 marked global even though it isn't, because assembly code below
1496 needs to reference the name. */
1498 /*static*/ VgStack VG_(interim_stack);
1500 /* These are the structures used to hold info for creating the initial
1503 'iicii' mostly holds important register state present at system
1504 startup (_start_valgrind). valgrind_main() then fills in the rest
1505 of it and passes it to VG_(ii_create_image)(). That produces
1506 'iifii', which is later handed to VG_(ii_finalise_image). */
1508 /* In all OS-instantiations, the_iicii has a field .sp_at_startup.
1509 This should get some address inside the stack on which we gained
1510 control (eg, it could be the SP at startup). It doesn't matter
1511 exactly where in the stack it is. This value is passed to the
1512 address space manager at startup. On Linux, aspacem then uses it
1513 to identify the initial stack segment and hence the upper end of
1514 the usable address space. */
1516 static IICreateImageInfo the_iicii;
1517 static IIFinaliseImageInfo the_iifii;
1520 /* A simple pair structure, used for conveying debuginfo handles to
1521 calls to VG_TRACK(new_mem_startup, ...). */
1522 typedef struct { Addr a; ULong ull; } Addr_n_ULong;
1525 /* --- Forwards decls to do with shutdown --- */
1527 static void final_tidyup(ThreadId tid);
1529 /* Do everything which needs doing when the last thread exits */
1531 void shutdown_actions_NORETURN( ThreadId tid,
1532 VgSchedReturnCode tids_schedretcode );
1534 /* --- end of Forwards decls to do with shutdown --- */
1537 /* By the time we get to valgrind_main, the_iicii should already have
1538 been filled in with any important details as required by whatever
1539 OS we have been built for.
1542 Int valgrind_main ( Int argc, HChar **argv, HChar **envp )
1544 HChar* toolname = "memcheck"; // default to Memcheck
1545 Int need_help = 0; // 0 = no, 1 = --help, 2 = --help-debug
1546 ThreadId tid_main = VG_INVALID_THREADID;
1547 Bool logging_to_fd = False;
1548 Char* xml_fname_unexpanded = NULL;
1550 struct vki_rlimit zero = { 0, 0 };
1551 XArray* addr2dihandle = NULL;
1553 // For an inner Valgrind, register the interim stack asap.
1554 // This is needed to allow the outer valgrind to do stacktraces during init.
1555 // Note that this stack is not unregistered when the main thread
1556 // is switching to the (real) stack. Unregistering this would imply
1557 // to save the stack id in a global variable, and have a "if"
1558 // in run_a_thread_NORETURN to do the unregistration only for the
1559 // main thread. This unregistration is not worth this complexity.
1561 ((void) VALGRIND_STACK_REGISTER
1562 (&VG_(interim_stack).bytes[0],
1563 &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack))));
1566 //============================================================
1568 // Nb: startup is complex. Prerequisites are shown at every step.
1569 // *** Be very careful when messing with the order ***
1571 // The first order of business is to get debug logging, the address
1572 // space manager and the dynamic memory manager up and running.
1573 // Once that's done, we can relax a bit.
1575 //============================================================
1577 /* This is needed to make VG_(getenv) usable early. */
1578 VG_(client_envp) = (Char**)envp;
1580 //--------------------------------------------------------------
1581 // Start up Mach kernel interface, if any
1583 //--------------------------------------------------------------
1584 # if defined(VGO_darwin)
1588 //--------------------------------------------------------------
1589 // Start up the logging mechanism
1591 //--------------------------------------------------------------
1592 /* Start the debugging-log system ASAP. First find out how many
1593 "-d"s were specified. This is a pre-scan of the command line. Also
1594 get --profile-heap=yes, --core-redzone-size, --redzone-size which are
1595 needed by the time we start up dynamic memory management. */
1597 for (i = 1; i < argc; i++) {
1598 if (argv[i][0] != '-') break;
1599 if VG_STREQ(argv[i], "--") break;
1600 if VG_STREQ(argv[i], "-d") loglevel++;
1601 if VG_BOOL_CLO(argv[i], "--profile-heap", VG_(clo_profile_heap)) {}
1602 if VG_BINT_CLO(argv[i], "--core-redzone-size", VG_(clo_core_redzone_size),
1603 0, MAX_CLO_REDZONE_SZB) {}
1604 if VG_BINT_CLO(argv[i], "--redzone-size", VG_(clo_redzone_size),
1605 0, MAX_CLO_REDZONE_SZB) {}
1608 /* ... and start the debug logger. Now we can safely emit logging
1609 messages all through startup. */
1610 VG_(debugLog_startup)(loglevel, "Stage 2 (main)");
1611 VG_(debugLog)(1, "main", "Welcome to Valgrind version "
1612 VERSION " debug logging\n");
1614 //--------------------------------------------------------------
1615 // Ensure we're on a plausible stack.
1617 //--------------------------------------------------------------
1618 VG_(debugLog)(1, "main", "Checking current stack is plausible\n");
1619 { HChar* limLo = (HChar*)(&VG_(interim_stack).bytes[0]);
1620 HChar* limHi = limLo + sizeof(VG_(interim_stack));
1622 aLocal = (HChar*)&limLo; /* any auto local will do */
1623 /* Re "volatile": Apple clang version 4.0
1624 (tags/Apple/clang-421.0.57) (based on LLVM 3.1svn)" appeared
1625 to miscompile the following check, causing run to abort at
1626 this point (in 64-bit mode) even though aLocal is within limLo
1627 .. limHi. But in fact clang is within its rights to do
1628 strange things here. "The reason is that the comparisons
1629 aLocal < limLo and aLocal >= limHi cause undefined behaviour
1630 (according to c99 6.5.8) because they compare pointers that do
1631 not point into the same aggregate." Adding "volatile" appears
1632 to fix it because "The compiler would have to prove that there
1633 is undefined behavior in order to exploit it. But as a
1634 volatile variable can change its value in ways invisible to
1635 the compiler, the compiler must make the conservative
1636 assumption that it points into the same aggregate as the other
1637 pointer its compared against. I.e. the behaviour is possibly
1638 defined." (Analysis by Florian Krohm). */
1639 if (aLocal < limLo || aLocal >= limHi) {
1640 /* something's wrong. Stop. */
1641 VG_(debugLog)(0, "main", "Root stack %p to %p, a local %p\n",
1642 limLo, limHi, aLocal );
1643 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1644 "Initial stack switched failed.\n");
1645 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1650 //--------------------------------------------------------------
1651 // Ensure we have a plausible pointer to the stack on which
1652 // we gained control (not the current stack!)
1654 //--------------------------------------------------------------
1655 VG_(debugLog)(1, "main", "Checking initial stack was noted\n");
1656 if (the_iicii.sp_at_startup == 0) {
1657 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1658 "Initial stack was not noted.\n");
1659 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1663 //--------------------------------------------------------------
1664 // Start up the address space manager, and determine the
1665 // approximate location of the client's stack
1666 // p: logging, plausible-stack
1667 //--------------------------------------------------------------
1668 VG_(debugLog)(1, "main", "Starting the address space manager\n");
1669 vg_assert(VKI_PAGE_SIZE == 4096 || VKI_PAGE_SIZE == 65536
1670 || VKI_PAGE_SIZE == 16384);
1671 vg_assert(VKI_MAX_PAGE_SIZE == 4096 || VKI_MAX_PAGE_SIZE == 65536
1672 || VKI_MAX_PAGE_SIZE == 16384);
1673 vg_assert(VKI_PAGE_SIZE <= VKI_MAX_PAGE_SIZE);
1674 vg_assert(VKI_PAGE_SIZE == (1 << VKI_PAGE_SHIFT));
1675 vg_assert(VKI_MAX_PAGE_SIZE == (1 << VKI_MAX_PAGE_SHIFT));
1676 the_iicii.clstack_top = VG_(am_startup)( the_iicii.sp_at_startup );
1677 VG_(debugLog)(1, "main", "Address space manager is running\n");
1679 //--------------------------------------------------------------
1680 // Start up the dynamic memory manager
1681 // p: address space management
1682 // p: getting --profile-heap,--core-redzone-size,--redzone-size
1683 // In fact m_mallocfree is self-initialising, so there's no
1684 // initialisation call to do. Instead, try a simple malloc/
1685 // free pair right now to check that nothing is broken.
1686 //--------------------------------------------------------------
1687 VG_(debugLog)(1, "main", "Starting the dynamic memory manager\n");
1688 { void* p = VG_(malloc)( "main.vm.1", 12345 );
1689 if (p) VG_(free)( p );
1691 VG_(debugLog)(1, "main", "Dynamic memory manager is running\n");
1693 //============================================================
1695 // Dynamic memory management is now available.
1697 //============================================================
1699 //--------------------------------------------------------------
1700 // Initialise m_debuginfo
1701 // p: dynamic memory allocation
1702 VG_(debugLog)(1, "main", "Initialise m_debuginfo\n");
1703 VG_(di_initialise)();
1705 //--------------------------------------------------------------
1706 // Look for alternative libdir
1707 { HChar *cp = VG_(getenv)(VALGRIND_LIB);
1710 VG_(debugLog)(1, "main", "VG_(libdir) = %s\n", VG_(libdir));
1713 //--------------------------------------------------------------
1714 // Extract the launcher name from the environment.
1715 VG_(debugLog)(1, "main", "Getting launcher's name ...\n");
1716 VG_(name_of_launcher) = VG_(getenv)(VALGRIND_LAUNCHER);
1717 if (VG_(name_of_launcher) == NULL) {
1718 VG_(printf)("valgrind: You cannot run '%s' directly.\n", argv[0]);
1719 VG_(printf)("valgrind: You should use $prefix/bin/valgrind.\n");
1722 VG_(debugLog)(1, "main", "... %s\n", VG_(name_of_launcher));
1724 //--------------------------------------------------------------
1725 // Get the current process datasize rlimit, and set it to zero.
1726 // This prevents any internal uses of brk() from having any effect.
1727 // We remember the old value so we can restore it on exec, so that
1728 // child processes will have a reasonable brk value.
1729 VG_(getrlimit)(VKI_RLIMIT_DATA, &VG_(client_rlimit_data));
1730 zero.rlim_max = VG_(client_rlimit_data).rlim_max;
1731 VG_(setrlimit)(VKI_RLIMIT_DATA, &zero);
1733 // Get the current process stack rlimit.
1734 VG_(getrlimit)(VKI_RLIMIT_STACK, &VG_(client_rlimit_stack));
1736 //--------------------------------------------------------------
1737 // Figure out what sort of CPU we're on, and whether it is
1739 VG_(debugLog)(1, "main", "Get hardware capabilities ...\n");
1741 VexArchInfo vex_archinfo;
1742 Bool ok = VG_(machine_get_hwcaps)();
1745 VG_(printf)("valgrind: fatal error: unsupported CPU.\n");
1746 VG_(printf)(" Supported CPUs are:\n");
1747 VG_(printf)(" * x86 (practically any; Pentium-I or above), "
1748 "AMD Athlon or above)\n");
1749 VG_(printf)(" * AMD Athlon64/Opteron\n");
1750 VG_(printf)(" * PowerPC (most; ppc405 and above)\n");
1751 VG_(printf)(" * System z (64bit only - s390x; z900 and above)\n");
1755 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
1757 1, "main", "... arch = %s, hwcaps = %s\n",
1758 LibVEX_ppVexArch ( vex_arch ),
1759 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1763 //--------------------------------------------------------------
1764 // Record the working directory at startup
1766 VG_(debugLog)(1, "main", "Getting the working directory at startup\n");
1767 { Bool ok = VG_(record_startup_wd)();
1769 VG_(err_config_error)( "Can't establish current working "
1770 "directory at startup\n");
1772 { Char buf[VKI_PATH_MAX+1];
1773 Bool ok = VG_(get_startup_wd)( buf, sizeof(buf) );
1775 buf[VKI_PATH_MAX] = 0;
1776 VG_(debugLog)(1, "main", "... %s\n", buf );
1779 //============================================================
1780 // Command line argument handling order:
1781 // * If --help/--help-debug are present, show usage message
1782 // (including the tool-specific usage)
1783 // * (If no --tool option given, default to Memcheck)
1784 // * Then, if client is missing, abort with error msg
1785 // * Then, if any cmdline args are bad, abort with error msg
1786 //============================================================
1788 //--------------------------------------------------------------
1789 // Split up argv into: C args, V args, V extra args, and exename.
1790 // p: dynamic memory allocation
1791 //--------------------------------------------------------------
1792 VG_(debugLog)(1, "main", "Split up command line\n");
1793 VG_(split_up_argv)( argc, argv );
1794 vg_assert( VG_(args_for_valgrind) );
1795 vg_assert( VG_(args_for_client) );
1797 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++)
1800 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1802 VG_(printf)(" exe %s\n", VG_(args_the_exename));
1803 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++)
1806 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1810 //--------------------------------------------------------------
1811 // Extract tool name and whether help has been requested.
1812 // Note we can't print the help message yet, even if requested,
1813 // because the tool has not been initialised.
1814 // p: split_up_argv [for VG_(args_for_valgrind)]
1815 //--------------------------------------------------------------
1816 VG_(debugLog)(1, "main",
1817 "(early_) Process Valgrind's command line options\n");
1818 early_process_cmd_line_options(&need_help, &toolname);
1820 // Set default vex control params
1821 LibVEX_default_VexControl(& VG_(clo_vex_control));
1823 //--------------------------------------------------------------
1824 // Load client executable, finding in $PATH if necessary
1825 // p: early_process_cmd_line_options() [for 'exec', 'need_help',
1826 // clo_max_stackframe,
1827 // clo_main_stacksize]
1828 // p: layout_remaining_space [so there's space]
1830 // Set up client's environment
1831 // p: set-libdir [for VG_(libdir)]
1832 // p: early_process_cmd_line_options [for toolname]
1834 // Setup client stack, eip, and VG_(client_arg[cv])
1835 // p: load_client() [for 'info']
1836 // p: fix_environment() [for 'env']
1838 // Setup client data (brk) segment. Initially a 1-page segment
1839 // which abuts a shrinkable reservation.
1840 // p: load_client() [for 'info' and hence VG_(brk_base)]
1842 // p: _start_in_C (for zeroing out the_iicii and putting some
1843 // initial values into it)
1844 //--------------------------------------------------------------
1846 VG_(debugLog)(1, "main", "Create initial image\n");
1848 # if defined(VGO_linux) || defined(VGO_darwin)
1849 the_iicii.argv = argv;
1850 the_iicii.envp = envp;
1851 the_iicii.toolname = toolname;
1853 # error "Unknown platform"
1856 /* NOTE: this call reads VG_(clo_main_stacksize). */
1857 the_iifii = VG_(ii_create_image)( the_iicii );
1860 //==============================================================
1862 // Finished loading/setting up the client address space.
1864 //==============================================================
1866 //--------------------------------------------------------------
1867 // setup file descriptors
1869 //--------------------------------------------------------------
1870 VG_(debugLog)(1, "main", "Setup file descriptors\n");
1871 setup_file_descriptors();
1873 //--------------------------------------------------------------
1874 // create fake /proc/<pid>/cmdline and /proc/<pid>/auxv files
1875 // and then unlink them, but hold onto the fds, so we can handr
1876 // them out to the client when it tries to open
1877 // /proc/<pid>/cmdline or /proc/<pid>/auxv for itself.
1878 // p: setup file descriptors
1879 // p: ii_create_image for VG_(client_auxv) setup.
1880 //--------------------------------------------------------------
1881 #if !defined(VGO_linux)
1882 // client shouldn't be using /proc!
1883 VG_(cl_cmdline_fd) = -1;
1884 VG_(cl_auxv_fd) = -1;
1887 HChar buf[50], buf2[50+64];
1890 const HChar* exename;
1892 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/cmdline\n");
1894 VG_(sprintf)(buf, "proc_%d_cmdline", VG_(getpid)());
1895 fd = VG_(mkstemp)( buf, buf2 );
1897 VG_(err_config_error)("Can't create client cmdline file in %s\n", buf2);
1900 exename = VG_(args_the_exename) ? VG_(args_the_exename)
1901 : "unknown_exename";
1902 VG_(write)(fd, exename, VG_(strlen)( exename ));
1903 VG_(write)(fd, nul, 1);
1905 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1906 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i );
1907 VG_(write)(fd, arg, VG_(strlen)( arg ));
1908 VG_(write)(fd, nul, 1);
1911 /* Don't bother to seek the file back to the start; instead do
1912 it every time a copy of it is given out (by PRE(sys_open)).
1913 That is probably more robust across fork() etc. */
1915 /* Now delete it, but hang on to the fd. */
1916 r = VG_(unlink)( buf2 );
1918 VG_(err_config_error)("Can't delete client cmdline file in %s\n", buf2);
1920 VG_(cl_cmdline_fd) = fd;
1922 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/auxv\n");
1924 VG_(sprintf)(buf, "proc_%d_auxv", VG_(getpid)());
1925 fd = VG_(mkstemp)( buf, buf2 );
1927 VG_(err_config_error)("Can't create client auxv file in %s\n", buf2);
1929 UWord *client_auxv = VG_(client_auxv);
1930 unsigned int client_auxv_len = 0;
1931 while (*client_auxv != 0) {
1934 client_auxv_len += 2 * sizeof(UWord);
1936 client_auxv_len += 2 * sizeof(UWord);
1938 VG_(write)(fd, VG_(client_auxv), client_auxv_len);
1940 /* Don't bother to seek the file back to the start; instead do
1941 it every time a copy of it is given out (by PRE(sys_open)).
1942 That is probably more robust across fork() etc. */
1944 /* Now delete it, but hang on to the fd. */
1945 r = VG_(unlink)( buf2 );
1947 VG_(err_config_error)("Can't delete client auxv file in %s\n", buf2);
1949 VG_(cl_auxv_fd) = fd;
1953 //--------------------------------------------------------------
1954 // Init tool part 1: pre_clo_init
1955 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1956 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1957 //--------------------------------------------------------------
1958 VG_(debugLog)(1, "main", "Initialise the tool part 1 (pre_clo_init)\n");
1959 VG_(tl_pre_clo_init)();
1961 //--------------------------------------------------------------
1962 // If --tool and --help/--help-debug was given, now give the core+tool
1964 // p: early_process_cmd_line_options() [for 'need_help']
1965 // p: tl_pre_clo_init [for 'VG_(tdict).usage']
1966 //--------------------------------------------------------------
1967 VG_(debugLog)(1, "main", "Print help and quit, if requested\n");
1969 usage_NORETURN(/*--help-debug?*/need_help >= 2);
1972 //--------------------------------------------------------------
1973 // Process command line options to Valgrind + tool
1974 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1975 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1976 //--------------------------------------------------------------
1977 VG_(debugLog)(1, "main",
1978 "(main_) Process Valgrind's command line options, "
1980 main_process_cmd_line_options ( &logging_to_fd, &xml_fname_unexpanded,
1983 //--------------------------------------------------------------
1984 // Zeroise the millisecond counter by doing a first read of it.
1986 //--------------------------------------------------------------
1987 (void) VG_(read_millisecond_timer)();
1989 //--------------------------------------------------------------
1990 // Print the preamble
1991 // p: tl_pre_clo_init [for 'VG_(details).name' and friends]
1992 // p: main_process_cmd_line_options()
1993 // [for VG_(clo_verbosity), VG_(clo_xml),
1994 // logging_to_fd, xml_fname_unexpanded]
1995 //--------------------------------------------------------------
1996 VG_(debugLog)(1, "main", "Print the preamble...\n");
1997 print_preamble(logging_to_fd, xml_fname_unexpanded, toolname);
1998 VG_(debugLog)(1, "main", "...finished the preamble\n");
2000 //--------------------------------------------------------------
2001 // Init tool part 2: post_clo_init
2002 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
2003 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
2004 // p: print_preamble() [so any warnings printed in post_clo_init
2005 // are shown after the preamble]
2006 //--------------------------------------------------------------
2007 VG_(debugLog)(1, "main", "Initialise the tool part 2 (post_clo_init)\n");
2008 VG_TDICT_CALL(tool_post_clo_init);
2010 /* The tool's "needs" will by now be finalised, since it has no
2011 further opportunity to specify them. So now sanity check
2015 ok = VG_(sanity_check_needs)( &s );
2021 //--------------------------------------------------------------
2022 // Initialise translation table and translation cache
2024 // p: tl_pre_clo_init [for 'VG_(details).avg_translation_sizeB']
2025 //--------------------------------------------------------------
2026 VG_(debugLog)(1, "main", "Initialise TT/TC\n");
2029 //--------------------------------------------------------------
2030 // Initialise the redirect table.
2031 // p: init_tt_tc [so it can call VG_(search_transtab) safely]
2032 // p: aspacem [so can change ownership of sysinfo pages]
2033 //--------------------------------------------------------------
2034 VG_(debugLog)(1, "main", "Initialise redirects\n");
2035 VG_(redir_initialise)();
2037 //--------------------------------------------------------------
2039 // p: main_process_cmd_line_options() [for VG_(clo_wait_for_gdb)]
2040 //--------------------------------------------------------------
2041 /* Hook to delay things long enough so we can get the pid and
2042 attach GDB in another shell. */
2043 if (VG_(clo_wait_for_gdb)) {
2045 VG_(debugLog)(1, "main", "Wait for GDB\n");
2046 VG_(printf)("pid=%d, entering delay loop\n", VG_(getpid)());
2048 # if defined(VGP_x86_linux)
2050 # elif defined(VGP_amd64_linux) || defined(VGP_ppc64_linux)
2052 # elif defined(VGP_ppc32_linux)
2054 # elif defined(VGP_arm_linux)
2056 # elif defined(VGP_s390x_linux)
2058 # elif defined(VGP_mips32_linux)
2060 # elif defined(VGO_darwin)
2063 # error "Unknown plat"
2066 iters *= 1000ULL * 1000 * 1000;
2067 for (q = 0; q < iters; q++)
2068 __asm__ __volatile__("" ::: "memory","cc");
2071 //--------------------------------------------------------------
2072 // Search for file descriptors that are inherited from our parent
2073 // p: main_process_cmd_line_options [for VG_(clo_track_fds)]
2074 //--------------------------------------------------------------
2075 if (VG_(clo_track_fds)) {
2076 VG_(debugLog)(1, "main", "Init preopened fds\n");
2077 VG_(init_preopened_fds)();
2080 //--------------------------------------------------------------
2081 // Load debug info for the existing segments.
2082 // p: setup_code_redirect_table [so that redirs can be recorded]
2084 // p: probably: setup fds and process CLOs, so that logging works
2085 // p: initialise m_debuginfo
2087 // While doing this, make a note of the debuginfo-handles that
2088 // come back from VG_(di_notify_mmap).
2089 // Later, in "Tell the tool about the initial client memory permissions"
2090 // (just below) we can then hand these handles off to the tool in
2091 // calls to VG_TRACK(new_mem_startup, ...). This gives the tool the
2092 // opportunity to make further queries to m_debuginfo before the
2093 // client is started, if it wants. We put this information into an
2094 // XArray, each handle along with the associated segment start address,
2095 // and search the XArray for the handles later, when calling
2096 // VG_TRACK(new_mem_startup, ...).
2097 //--------------------------------------------------------------
2098 VG_(debugLog)(1, "main", "Load initial debug info\n");
2100 tl_assert(!addr2dihandle);
2101 addr2dihandle = VG_(newXA)( VG_(malloc), "main.vm.2",
2102 VG_(free), sizeof(Addr_n_ULong) );
2103 tl_assert(addr2dihandle);
2105 # if defined(VGO_linux)
2110 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
2111 vg_assert(seg_starts && n_seg_starts >= 0);
2113 /* show them all to the debug info reader. allow_SkFileV has to
2114 be True here so that we read info from the valgrind executable
2116 for (i = 0; i < n_seg_starts; i++) {
2117 anu.ull = VG_(di_notify_mmap)( seg_starts[i], True/*allow_SkFileV*/,
2118 -1/*Don't use_fd*/);
2119 /* anu.ull holds the debuginfo handle returned by di_notify_mmap,
2122 anu.a = seg_starts[i];
2123 VG_(addToXA)( addr2dihandle, &anu );
2127 VG_(free)( seg_starts );
2129 # elif defined(VGO_darwin)
2132 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
2133 vg_assert(seg_starts && n_seg_starts >= 0);
2135 /* show them all to the debug info reader.
2136 Don't read from V segments (unlike Linux) */
2137 // GrP fixme really?
2138 for (i = 0; i < n_seg_starts; i++) {
2139 VG_(di_notify_mmap)( seg_starts[i], False/*don't allow_SkFileV*/,
2140 -1/*don't use_fd*/);
2143 VG_(free)( seg_starts );
2149 //--------------------------------------------------------------
2150 // Tell aspacem of ownership change of the asm helpers, so that
2151 // m_translate allows them to be translated. However, only do this
2152 // after the initial debug info read, since making a hole in the
2153 // address range for the stage2 binary confuses the debug info reader.
2155 //--------------------------------------------------------------
2156 { Bool change_ownership_v_c_OK;
2157 Addr co_start = VG_PGROUNDDN( (Addr)&VG_(trampoline_stuff_start) );
2158 Addr co_endPlus = VG_PGROUNDUP( (Addr)&VG_(trampoline_stuff_end) );
2159 VG_(debugLog)(1,"redir",
2160 "transfer ownership V -> C of 0x%llx .. 0x%llx\n",
2161 (ULong)co_start, (ULong)co_endPlus-1 );
2163 change_ownership_v_c_OK
2164 = VG_(am_change_ownership_v_to_c)( co_start, co_endPlus - co_start );
2165 vg_assert(change_ownership_v_c_OK);
2170 VG_(elapsed_wallclock_time)(buf);
2171 VG_(printf_xml)( "<status>\n"
2172 " <state>RUNNING</state>\n"
2173 " <time>%pS</time>\n"
2176 VG_(printf_xml)( "\n" );
2179 VG_(init_Threads)();
2181 //--------------------------------------------------------------
2182 // Initialise the scheduler (phase 1) [generates tid_main]
2184 //--------------------------------------------------------------
2185 VG_(debugLog)(1, "main", "Initialise scheduler (phase 1)\n");
2186 tid_main = VG_(scheduler_init_phase1)();
2187 vg_assert(tid_main >= 0 && tid_main < VG_N_THREADS
2188 && tid_main != VG_INVALID_THREADID);
2189 /* Tell the tool about tid_main */
2190 VG_TRACK( pre_thread_ll_create, VG_INVALID_THREADID, tid_main );
2192 //--------------------------------------------------------------
2193 // Tell the tool about the initial client memory permissions
2196 // p: setup_client_stack
2197 // p: setup_client_dataseg
2199 // For each segment we tell the client about, look up in
2200 // addr2dihandle as created above, to see if there's a debuginfo
2201 // handle associated with the segment, that we can hand along
2202 // to the tool, to be helpful.
2203 //--------------------------------------------------------------
2204 VG_(debugLog)(1, "main", "Tell tool about initial permissions\n");
2208 tl_assert(addr2dihandle);
2210 /* Mark the main thread as running while we tell the tool about
2211 the client memory so that the tool can associate that memory
2212 with the main thread. */
2213 tl_assert(VG_(running_tid) == VG_INVALID_THREADID);
2214 VG_(running_tid) = tid_main;
2216 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
2217 vg_assert(seg_starts && n_seg_starts >= 0);
2219 /* show interesting ones to the tool */
2220 for (i = 0; i < n_seg_starts; i++) {
2223 = VG_(am_find_nsegment)( seg_starts[i] );
2225 if (seg->kind == SkFileC || seg->kind == SkAnonC) {
2226 /* This next assertion is tricky. If it is placed
2227 immediately before this 'if', it very occasionally fails.
2228 Why? Because previous iterations of the loop may have
2229 caused tools (via the new_mem_startup calls) to do
2230 dynamic memory allocation, and that may affect the mapped
2231 segments; in particular it may cause segment merging to
2232 happen. Hence we cannot assume that seg_starts[i], which
2233 reflects the state of the world before we started this
2234 loop, is the same as seg->start, as the latter reflects
2235 the state of the world (viz, mappings) at this particular
2236 iteration of the loop.
2238 Why does moving it inside the 'if' make it safe? Because
2239 any dynamic memory allocation done by the tools will
2240 affect only the state of Valgrind-owned segments, not of
2241 Client-owned segments. And the 'if' guards against that
2242 -- we only get in here for Client-owned segments.
2244 In other words: the loop may change the state of
2245 Valgrind-owned segments as it proceeds. But it should
2246 not cause the Client-owned segments to change. */
2247 vg_assert(seg->start == seg_starts[i]);
2248 VG_(debugLog)(2, "main",
2249 "tell tool about %010lx-%010lx %c%c%c\n",
2250 seg->start, seg->end,
2251 seg->hasR ? 'r' : '-',
2252 seg->hasW ? 'w' : '-',
2253 seg->hasX ? 'x' : '-' );
2254 /* search addr2dihandle to see if we have an entry
2255 matching seg->start. */
2256 n = VG_(sizeXA)( addr2dihandle );
2257 for (j = 0; j < n; j++) {
2258 Addr_n_ULong* anl = VG_(indexXA)( addr2dihandle, j );
2259 if (anl->a == seg->start) {
2260 tl_assert(anl->ull > 0); /* check it's a valid handle */
2264 vg_assert(j >= 0 && j <= n);
2265 VG_TRACK( new_mem_startup, seg->start, seg->end+1-seg->start,
2266 seg->hasR, seg->hasW, seg->hasX,
2267 /* and the retrieved debuginfo handle, if any */
2269 ? ((Addr_n_ULong*)VG_(indexXA)( addr2dihandle, j ))->ull
2274 VG_(free)( seg_starts );
2275 VG_(deleteXA)( addr2dihandle );
2277 /* Also do the initial stack permissions. */
2279 SSizeT inaccessible_len;
2281 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
2283 vg_assert(seg->kind == SkAnonC);
2284 vg_assert(the_iifii.initial_client_SP >= seg->start);
2285 vg_assert(the_iifii.initial_client_SP <= seg->end);
2287 /* Stuff below the initial SP is unaddressable. Take into
2288 account any ABI-mandated space below the stack pointer that
2289 is required (VG_STACK_REDZONE_SZB). setup_client_stack()
2290 will have allocated an extra page if a red zone is required,
2291 to be on the safe side. */
2292 inaccessible_len = the_iifii.initial_client_SP - VG_STACK_REDZONE_SZB
2294 vg_assert(inaccessible_len >= 0);
2295 if (inaccessible_len > 0)
2296 VG_TRACK( die_mem_stack,
2299 VG_(debugLog)(2, "main", "mark stack inaccessible %010lx-%010lx\n",
2301 the_iifii.initial_client_SP-1 - VG_STACK_REDZONE_SZB);
2304 /* Also the assembly helpers. */
2305 VG_TRACK( new_mem_startup,
2306 (Addr)&VG_(trampoline_stuff_start),
2307 (Addr)&VG_(trampoline_stuff_end)
2308 - (Addr)&VG_(trampoline_stuff_start),
2309 False, /* readable? */
2310 False, /* writable? */
2311 True /* executable? */,
2312 0 /* di_handle: no associated debug info */ );
2314 /* Clear the running thread indicator */
2315 VG_(running_tid) = VG_INVALID_THREADID;
2316 tl_assert(VG_(running_tid) == VG_INVALID_THREADID);
2319 //--------------------------------------------------------------
2320 // Initialise the scheduler (phase 2)
2321 // p: Initialise the scheduler (phase 1) [for tid_main]
2322 // p: setup_file_descriptors() [else VG_(safe_fd)() breaks]
2323 // p: setup_client_stack
2324 //--------------------------------------------------------------
2325 VG_(debugLog)(1, "main", "Initialise scheduler (phase 2)\n");
2326 { NSegment const* seg
2327 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
2329 vg_assert(seg->kind == SkAnonC);
2330 vg_assert(the_iifii.initial_client_SP >= seg->start);
2331 vg_assert(the_iifii.initial_client_SP <= seg->end);
2332 VG_(scheduler_init_phase2)( tid_main,
2333 seg->end, the_iifii.clstack_max_size );
2336 //--------------------------------------------------------------
2337 // Set up state for the root thread
2339 // setup_scheduler() [for sched-specific thread 1 stuff]
2340 // VG_(ii_create_image) [for 'the_iicii' initial info]
2341 //--------------------------------------------------------------
2342 VG_(debugLog)(1, "main", "Finalise initial image\n");
2343 VG_(ii_finalise_image)( the_iifii );
2345 //--------------------------------------------------------------
2346 // Initialise the signal handling subsystem
2348 //--------------------------------------------------------------
2349 // Nb: temporarily parks the saved blocking-mask in saved_sigmask.
2350 VG_(debugLog)(1, "main", "Initialise signal management\n");
2351 /* Check that the kernel-interface signal definitions look sane */
2352 VG_(vki_do_initial_consistency_checks)();
2353 /* .. and go on to use them. */
2354 VG_(sigstartup_actions)();
2356 //--------------------------------------------------------------
2357 // Read suppression file
2358 // p: main_process_cmd_line_options() [for VG_(clo_suppressions)]
2359 //--------------------------------------------------------------
2360 if (VG_(needs).core_errors || VG_(needs).tool_errors) {
2361 VG_(debugLog)(1, "main", "Load suppressions\n");
2362 VG_(load_suppressions)();
2365 //--------------------------------------------------------------
2366 // register client stack
2367 //--------------------------------------------------------------
2368 VG_(clstk_id) = VG_(register_stack)(VG_(clstk_base), VG_(clstk_end));
2370 //--------------------------------------------------------------
2371 // Show the address space state so far
2372 //--------------------------------------------------------------
2373 VG_(debugLog)(1, "main", "\n");
2374 VG_(debugLog)(1, "main", "\n");
2375 VG_(am_show_nsegments)(1,"Memory layout at client startup");
2376 VG_(debugLog)(1, "main", "\n");
2377 VG_(debugLog)(1, "main", "\n");
2379 //--------------------------------------------------------------
2381 //--------------------------------------------------------------
2382 VG_(debugLog)(1, "main", "Running thread 1\n");
2384 /* As a result of the following call, the last thread standing
2385 eventually winds up running shutdown_actions_NORETURN
2386 just below. Unfortunately, simply exporting said function
2387 causes m_main to be part of a module cycle, which is pretty
2388 nonsensical. So instead of doing that, the address of said
2389 function is stored in a global variable 'owned' by m_syswrap,
2390 and it uses that function pointer to get back here when it needs
2393 /* Set continuation address. */
2394 VG_(address_of_m_main_shutdown_actions_NORETURN)
2395 = & shutdown_actions_NORETURN;
2397 /* Run the first thread, eventually ending up at the continuation
2399 VG_(main_thread_wrapper_NORETURN)(1);
2405 /* Do everything which needs doing when the last thread exits or when
2406 a thread exits requesting a complete process exit.
2408 We enter here holding The Lock. For the case VgSrc_ExitProcess we
2409 must never release it, because to do so would allow other threads
2410 to continue after the system is ostensibly shut down. So we must
2411 go to our grave, so to speak, holding the lock.
2413 In fact, there is never any point in releasing the lock at this
2414 point - we have it, we're shutting down the entire system, and
2415 for the case VgSrc_ExitProcess doing so positively causes trouble.
2418 The final_tidyup call makes a bit of a nonsense of the ExitProcess
2419 case, since it will run the libc_freeres function, thus allowing
2420 other lurking threads to run again. Hmm. */
2423 void shutdown_actions_NORETURN( ThreadId tid,
2424 VgSchedReturnCode tids_schedretcode )
2426 VG_(debugLog)(1, "main", "entering VG_(shutdown_actions_NORETURN)\n");
2427 VG_(am_show_nsegments)(1,"Memory layout at client shutdown");
2429 vg_assert(VG_(is_running_thread)(tid));
2431 vg_assert(tids_schedretcode == VgSrc_ExitThread
2432 || tids_schedretcode == VgSrc_ExitProcess
2433 || tids_schedretcode == VgSrc_FatalSig );
2435 if (tids_schedretcode == VgSrc_ExitThread) {
2437 // We are the last surviving thread. Right?
2438 vg_assert( VG_(count_living_threads)() == 1 );
2440 // Wait for all other threads to exit.
2441 // jrs: Huh? but they surely are already gone
2442 VG_(reap_threads)(tid);
2444 // Clean the client up before the final report
2445 // this causes the libc_freeres function to run
2449 vg_assert(VG_(is_running_thread)(tid));
2450 vg_assert(VG_(count_living_threads)() == 1);
2454 // We may not be the last surviving thread. However, we
2455 // want to shut down the entire process. We hold the lock
2456 // and we need to keep hold of it all the way out, in order
2457 // that none of the other threads ever run again.
2458 vg_assert( VG_(count_living_threads)() >= 1 );
2460 // Clean the client up before the final report
2461 // this causes the libc_freeres function to run
2462 // perhaps this is unsafe, as per comment above
2466 vg_assert(VG_(is_running_thread)(tid));
2467 vg_assert(VG_(count_living_threads)() >= 1);
2470 VG_(threads)[tid].status = VgTs_Empty;
2471 //--------------------------------------------------------------
2472 // Finalisation: cleanup, messages, etc. Order not so important, only
2473 // affects what order the messages come.
2474 //--------------------------------------------------------------
2475 // First thing in the post-amble is a blank line.
2477 VG_(printf_xml)("\n");
2478 else if (VG_(clo_verbosity) > 0)
2479 VG_(message)(Vg_UserMsg, "\n");
2483 VG_(elapsed_wallclock_time)(buf);
2484 VG_(printf_xml)( "<status>\n"
2485 " <state>FINISHED</state>\n"
2486 " <time>%pS</time>\n"
2492 /* Print out file descriptor summary and stats. */
2493 if (VG_(clo_track_fds))
2494 VG_(show_open_fds)("at exit");
2496 /* Call the tool's finalisation function. This makes Memcheck's
2497 leak checker run, and possibly chuck a bunch of leak errors into
2498 the error management machinery. */
2499 VG_TDICT_CALL(tool_fini, 0/*exitcode*/);
2501 /* Show the error counts. */
2503 && (VG_(needs).core_errors || VG_(needs).tool_errors)) {
2504 VG_(show_error_counts_as_XML)();
2507 /* In XML mode, this merely prints the used suppressions. */
2508 if (VG_(needs).core_errors || VG_(needs).tool_errors)
2509 VG_(show_all_errors)(VG_(clo_verbosity), VG_(clo_xml));
2512 VG_(printf_xml)("\n");
2513 VG_(printf_xml)("</valgrindoutput>\n");
2514 VG_(printf_xml)("\n");
2517 VG_(sanity_check_general)( True /*include expensive checks*/ );
2522 /* Show a profile of the heap(s) at shutdown. Optionally, first
2523 throw away all the debug info, as that makes it easy to spot
2524 leaks in the debuginfo reader. */
2525 if (VG_(clo_profile_heap)) {
2526 if (0) VG_(di_discard_ALL_debuginfo)();
2527 VG_(print_arena_cc_analysis)();
2530 if (VG_(clo_profile_flags) > 0) {
2532 BBProfEntry tops[N_MAX];
2533 ULong score_total = VG_(get_BB_profile) (tops, N_MAX);
2534 show_BB_profile(tops, N_MAX, score_total);
2537 /* Print Vex storage stats */
2539 LibVEX_ShowAllocStats();
2541 /* Flush any output cached by previous calls to VG_(message). */
2542 VG_(message_flush)();
2544 /* terminate gdbserver if ever it was started. We terminate it here so that it get
2545 the output above if output was redirected to gdb */
2546 VG_(gdbserver_exit) (tid, tids_schedretcode);
2548 /* Ok, finally exit in the os-specific way, according to the scheduler's
2549 return code. In short, if the (last) thread exited by calling
2550 sys_exit, do likewise; if the (last) thread stopped due to a fatal
2551 signal, terminate the entire system with that same fatal signal. */
2552 VG_(debugLog)(1, "core_os",
2553 "VG_(terminate_NORETURN)(tid=%lld)\n", (ULong)tid);
2555 switch (tids_schedretcode) {
2556 case VgSrc_ExitThread: /* the normal way out (Linux) */
2557 case VgSrc_ExitProcess: /* the normal way out (AIX) -- still needed? */
2558 /* Change the application return code to user's return code,
2559 if an error was found */
2560 if (VG_(clo_error_exitcode) > 0
2561 && VG_(get_n_errs_found)() > 0) {
2562 VG_(exit)( VG_(clo_error_exitcode) );
2564 /* otherwise, return the client's exit code, in the normal
2566 VG_(exit)( VG_(threads)[tid].os_state.exitcode );
2568 /* NOT ALIVE HERE! */
2569 VG_(core_panic)("entered the afterlife in main() -- ExitT/P");
2570 break; /* what the hell :) */
2572 case VgSrc_FatalSig:
2573 /* We were killed by a fatal signal, so replicate the effect */
2574 vg_assert(VG_(threads)[tid].os_state.fatalsig != 0);
2575 VG_(kill_self)(VG_(threads)[tid].os_state.fatalsig);
2576 /* we shouldn't be alive at this point. But VG_(kill_self)
2577 sometimes fails with EPERM on Darwin, for unclear reasons. */
2578 # if defined(VGO_darwin)
2579 VG_(debugLog)(0, "main", "VG_(kill_self) failed. Exiting normally.\n");
2580 VG_(exit)(0); /* bogus, but we really need to exit now */
2581 /* fall through .. */
2583 VG_(core_panic)("main(): signal was supposed to be fatal");
2587 VG_(core_panic)("main(): unexpected scheduler return code");
2591 /* -------------------- */
2593 /* Final clean-up before terminating the process.
2594 Clean up the client by calling __libc_freeres() (if requested)
2595 This is Linux-specific?
2596 GrP fixme glibc-specific, anyway
2598 static void final_tidyup(ThreadId tid)
2600 #if !defined(VGO_darwin)
2601 # if defined(VGP_ppc64_linux)
2604 Addr __libc_freeres_wrapper = VG_(client___libc_freeres_wrapper);
2606 vg_assert(VG_(is_running_thread)(tid));
2608 if ( !VG_(needs).libc_freeres ||
2609 !VG_(clo_run_libc_freeres) ||
2610 0 == __libc_freeres_wrapper )
2611 return; /* can't/won't do it */
2613 # if defined(VGP_ppc64_linux)
2614 r2 = VG_(get_tocptr)( __libc_freeres_wrapper );
2616 VG_(message)(Vg_UserMsg,
2617 "Caught __NR_exit, but can't run __libc_freeres()\n");
2618 VG_(message)(Vg_UserMsg,
2619 " since cannot establish TOC pointer for it.\n");
2624 if (VG_(clo_verbosity) > 2 ||
2625 VG_(clo_trace_syscalls) ||
2626 VG_(clo_trace_sched))
2627 VG_(message)(Vg_DebugMsg,
2628 "Caught __NR_exit; running __libc_freeres()\n");
2630 /* set thread context to point to libc_freeres_wrapper */
2631 /* ppc64-linux note: __libc_freeres_wrapper gives us the real
2632 function entry point, not a fn descriptor, so can use it
2633 directly. However, we need to set R2 (the toc pointer)
2635 VG_(set_IP)(tid, __libc_freeres_wrapper);
2636 # if defined(VGP_ppc64_linux)
2637 VG_(threads)[tid].arch.vex.guest_GPR2 = r2;
2639 /* mips-linux note: we need to set t9 */
2640 # if defined(VGP_mips32_linux)
2641 VG_(threads)[tid].arch.vex.guest_r25 = __libc_freeres_wrapper;
2644 /* Block all blockable signals by copying the real block state into
2645 the thread's block state*/
2646 VG_(sigprocmask)(VKI_SIG_BLOCK, NULL, &VG_(threads)[tid].sig_mask);
2647 VG_(threads)[tid].tmp_sig_mask = VG_(threads)[tid].sig_mask;
2649 /* and restore handlers to default */
2650 VG_(set_default_handler)(VKI_SIGSEGV);
2651 VG_(set_default_handler)(VKI_SIGBUS);
2652 VG_(set_default_handler)(VKI_SIGILL);
2653 VG_(set_default_handler)(VKI_SIGFPE);
2655 // We were exiting, so assert that...
2656 vg_assert(VG_(is_exiting)(tid));
2657 // ...but now we're not again
2658 VG_(threads)[tid].exitreason = VgSrc_None;
2660 // run until client thread exits - ideally with LIBC_FREERES_DONE,
2661 // but exit/exitgroup/signal will do
2662 VG_(scheduler)(tid);
2664 vg_assert(VG_(is_exiting)(tid));
2669 /*====================================================================*/
2670 /*=== Getting to main() alive: LINUX ===*/
2671 /*====================================================================*/
2673 #if defined(VGO_linux)
2675 /* If linking of the final executables is done with glibc present,
2676 then Valgrind starts at main() above as usual, and all of the
2677 following code is irrelevant.
2679 However, this is not the intended mode of use. The plan is to
2680 avoid linking against glibc, by giving gcc the flags
2681 -nodefaultlibs -lgcc -nostartfiles at startup.
2683 From this derive two requirements:
2685 1. gcc may emit calls to memcpy and memset to deal with structure
2686 assignments etc. Since we have chosen to ignore all the
2687 "normal" supporting libraries, we have to provide our own
2688 implementations of them. No problem.
2690 2. We have to provide a symbol "_start", to which the kernel
2691 hands control at startup. Hence the code below.
2694 /* ---------------- Requirement 1 ---------------- */
2696 void* memcpy(void *dest, const void *src, SizeT n);
2697 void* memcpy(void *dest, const void *src, SizeT n) {
2698 return VG_(memcpy)(dest,src,n);
2700 void* memset(void *s, int c, SizeT n);
2701 void* memset(void *s, int c, SizeT n) {
2702 return VG_(memset)(s,c,n);
2705 /* BVA: abort() for those platforms that need it (PPC and ARM). */
2708 VG_(printf)("Something called raise().\n");
2712 /* EAZG: ARM's EABI will call floating point exception handlers in
2713 libgcc which boil down to an abort or raise, that's usually defined
2714 in libc. Instead, define them here. */
2715 #if defined(VGP_arm_linux)
2718 VG_(printf)("Something called raise().\n");
2722 void __aeabi_unwind_cpp_pr0(void);
2723 void __aeabi_unwind_cpp_pr0(void){
2724 VG_(printf)("Something called __aeabi_unwind_cpp_pr0()\n");
2728 void __aeabi_unwind_cpp_pr1(void);
2729 void __aeabi_unwind_cpp_pr1(void){
2730 VG_(printf)("Something called __aeabi_unwind_cpp_pr1()\n");
2735 /* ---------------- Requirement 2 ---------------- */
2737 /* Glibc's sysdeps/i386/elf/start.S has the following gem of a
2738 comment, which explains how the stack looks right at process start
2739 (when _start is jumped to). Hence _start passes %esp to
2740 _start_in_C_linux, which extracts argc/argv/envp and starts up
2743 /* This is the canonical entry point, usually the first thing in the text
2744 segment. The SVR4/i386 ABI (pages 3-31, 3-32) says that when the entry
2745 point runs, most registers' values are unspecified, except for:
2747 %edx Contains a function pointer to be registered with `atexit'.
2748 This is how the dynamic linker arranges to have DT_FINI
2749 functions called for shared libraries that have been loaded
2750 before this code runs.
2752 %esp The stack contains the arguments and environment:
2757 (4*(argc+1))(%esp) envp[0]
2762 /* The kernel hands control to _start, which extracts the initial
2763 stack pointer and calls onwards to _start_in_C_linux. This also switches
2765 #if defined(VGP_x86_linux)
2769 "\t.type _start,@function\n"
2771 /* set up the new stack in %eax */
2772 "\tmovl $vgPlain_interim_stack, %eax\n"
2773 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
2774 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
2775 "\tsubl $16, %eax\n"
2776 "\tandl $~15, %eax\n"
2777 /* install it, and collect the original one */
2778 "\txchgl %eax, %esp\n"
2779 /* call _start_in_C_linux, passing it the startup %esp */
2781 "\tcall _start_in_C_linux\n"
2785 #elif defined(VGP_amd64_linux)
2789 "\t.type _start,@function\n"
2791 /* set up the new stack in %rdi */
2792 "\tmovq $vgPlain_interim_stack, %rdi\n"
2793 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
2794 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
2795 "\tandq $~15, %rdi\n"
2796 /* install it, and collect the original one */
2797 "\txchgq %rdi, %rsp\n"
2798 /* call _start_in_C_linux, passing it the startup %rsp */
2799 "\tcall _start_in_C_linux\n"
2803 #elif defined(VGP_ppc32_linux)
2807 "\t.type _start,@function\n"
2809 /* set up the new stack in r16 */
2810 "\tlis 16,vgPlain_interim_stack@ha\n"
2811 "\tla 16,vgPlain_interim_stack@l(16)\n"
2812 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2813 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2814 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2815 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2818 "\trlwinm 16,16,0,0,27\n"
2819 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2820 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2821 boundary. And r1 is the original SP. Set the SP to r16 and
2822 call _start_in_C_linux, passing it the initial SP. */
2825 "\tbl _start_in_C_linux\n"
2829 #elif defined(VGP_ppc64_linux)
2831 /* PPC64 ELF ABI says '_start' points to a function descriptor.
2832 So we must have one, and that is what goes into the .opd section. */
2834 "\t.global _start\n"
2835 "\t.section \".opd\",\"aw\"\n"
2838 "\t.quad ._start,.TOC.@tocbase,0\n"
2840 "\t.type ._start,@function\n"
2841 "\t.global ._start\n"
2843 /* set up the new stack in r16 */
2844 "\tlis 16, vgPlain_interim_stack@highest\n"
2845 "\tori 16,16,vgPlain_interim_stack@higher\n"
2847 "\toris 16,16,vgPlain_interim_stack@h\n"
2848 "\tori 16,16,vgPlain_interim_stack@l\n"
2850 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2851 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2853 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2854 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2857 "\trldicr 16,16,0,59\n"
2858 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2859 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2860 boundary. And r1 is the original SP. Set the SP to r16 and
2861 call _start_in_C_linux, passing it the initial SP. */
2864 "\tlis 14, _start_in_C_linux@highest\n"
2865 "\tori 14,14,_start_in_C_linux@higher\n"
2867 "\toris 14,14,_start_in_C_linux@h\n"
2868 "\tori 14,14,_start_in_C_linux@l\n"
2875 #elif defined(VGP_s390x_linux)
2877 This is the canonical entry point, usually the first thing in the text
2878 segment. Most registers' values are unspecified, except for:
2880 %r14 Contains a function pointer to be registered with `atexit'.
2881 This is how the dynamic linker arranges to have DT_FINI
2882 functions called for shared libraries that have been loaded
2883 before this code runs.
2885 %r15 The stack contains the arguments and environment:
2890 (8*(argc+1))(%r15) envp[0]
2897 ".type _start,@function\n\t"
2899 /* set up the new stack in %r1 */
2900 "larl %r1, vgPlain_interim_stack\n\t"
2902 "ag %r1, 0(%r5)\n\t"
2903 "ag %r1, 2f-1f(%r5)\n\t"
2904 "nill %r1, 0xFFF0\n\t"
2905 /* install it, and collect the original one */
2908 /* call _start_in_C_linux, passing it the startup %r15 */
2909 "brasl %r14, _start_in_C_linux\n\t"
2910 /* trigger execution of an invalid opcode -> halt machine */
2912 "1: .quad "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n\t"
2913 "2: .quad "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n\t"
2916 #elif defined(VGP_arm_linux)
2920 "\t.type _start,#function\n"
2921 "\t.global _start\n"
2923 "\tldr r0, [pc, #36]\n"
2924 "\tldr r1, [pc, #36]\n"
2925 "\tadd r0, r1, r0\n"
2926 "\tldr r1, [pc, #32]\n"
2927 "\tadd r0, r1, r0\n"
2929 "\tand r0, r0, r1\n"
2933 "\tb _start_in_C_linux\n"
2934 "\t.word vgPlain_interim_stack\n"
2935 "\t.word "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
2936 "\t.word "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
2938 #elif defined(VGP_mips32_linux)
2940 "\t.type _gp_disp,@object\n"
2942 "\t.globl __start\n"
2943 "\t.type __start,@function\n"
2951 "\tlui $28, %hi(_gp_disp)\n"
2952 "\taddiu $28, $28, %lo(_gp_disp)\n"
2953 "\taddu $28, $28, $31\n"
2954 /* t1/$9 <- Addr(interim_stack) */
2955 "\tlui $9, %hi(vgPlain_interim_stack)\n"
2956 /* t1/$9 <- Addr(interim_stack) */
2957 "\taddiu $9, %lo(vgPlain_interim_stack)\n"
2960 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
2961 "\tli $11, "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
2963 "\taddu $9, $9, $10\n"
2964 "\taddu $9, $9, $11\n"
2965 "\tli $12, 0xFFFFFFF0\n"
2966 "\tand $9, $9, $12\n"
2967 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2968 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2969 boundary. And $29 is the original SP. Set the SP to t1 and
2970 call _start_in_C, passing it the initial SP. */
2972 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
2973 "\tmove $29, $9\n" // $sp <- t1 (new sp)
2975 "\tlui $25, %hi(_start_in_C_linux)\n"
2976 "\taddiu $25, %lo(_start_in_C_linux)\n"
2978 "\tbal _start_in_C_linux\n"
2983 # error "Unknown linux platform"
2986 /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
2988 #define _FILE_OFFSET_BITS 64
2989 /* This is in order to get AT_NULL and AT_PAGESIZE. */
2991 /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
2993 /* Avoid compiler warnings: this fn _is_ used, but labelling it
2994 'static' causes gcc to complain it isn't.
2995 attribute 'used' also ensures the code is not eliminated at link
2997 __attribute__ ((used))
2998 void _start_in_C_linux ( UWord* pArgc );
2999 __attribute__ ((used))
3000 void _start_in_C_linux ( UWord* pArgc )
3003 Word argc = pArgc[0];
3004 HChar** argv = (HChar**)&pArgc[1];
3005 HChar** envp = (HChar**)&pArgc[1+argc+1];
3007 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3008 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3010 the_iicii.sp_at_startup = (Addr)pArgc;
3012 # if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux)
3014 /* ppc/ppc64 can be configured with different page sizes.
3015 Determine this early. This is an ugly hack and really should
3016 be moved into valgrind_main. */
3017 UWord *sp = &pArgc[1+argc+1];
3020 for (; *sp != AT_NULL && *sp != AT_PAGESZ; sp += 2);
3021 if (*sp == AT_PAGESZ) {
3022 VKI_PAGE_SIZE = sp[1];
3023 for (VKI_PAGE_SHIFT = 12;
3024 VKI_PAGE_SHIFT <= VKI_MAX_PAGE_SHIFT; VKI_PAGE_SHIFT++)
3025 if (VKI_PAGE_SIZE == (1UL << VKI_PAGE_SHIFT))
3031 r = valgrind_main( (Int)argc, argv, envp );
3037 /*====================================================================*/
3038 /*=== Getting to main() alive: darwin ===*/
3039 /*====================================================================*/
3041 #elif defined(VGO_darwin)
3044 Memory layout established by kernel:
3055 executable name (presumably, a pointer to it)
3058 Ditto in the 64-bit case, except all offsets from SP are obviously
3062 /* The kernel hands control to _start, which extracts the initial
3063 stack pointer and calls onwards to _start_in_C_darwin. This also
3064 switches to the new stack. */
3065 #if defined(VGP_x86_darwin)
3069 "\t.globl __start\n"
3071 /* set up the new stack in %eax */
3072 "\tmovl $_vgPlain_interim_stack, %eax\n"
3073 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
3074 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
3075 "\tsubl $16, %eax\n"
3076 "\tandl $~15, %eax\n"
3077 /* install it, and collect the original one */
3078 "\txchgl %eax, %esp\n"
3079 "\tsubl $12, %esp\n" // keep stack 16 aligned; see #295428
3080 /* call _start_in_C_darwin, passing it the startup %esp */
3082 "\tcall __start_in_C_darwin\n"
3086 #elif defined(VGP_amd64_darwin)
3089 "\t.globl __start\n"
3092 /* set up the new stack in %rdi */
3093 "\tmovabsq $_vgPlain_interim_stack, %rdi\n"
3094 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
3095 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
3096 "\tandq $~15, %rdi\n"
3097 /* install it, and collect the original one */
3098 "\txchgq %rdi, %rsp\n"
3099 /* call _start_in_C_darwin, passing it the startup %rsp */
3100 "\tcall __start_in_C_darwin\n"
3106 void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2);
3107 void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2) {
3109 return VG_(memcpy)(dest,src,n);
3111 void* __memset_chk(void *s, int c, SizeT n, SizeT n2);
3112 void* __memset_chk(void *s, int c, SizeT n, SizeT n2) {
3114 return VG_(memset)(s,c,n);
3116 void bzero(void *s, SizeT n);
3117 void bzero(void *s, SizeT n) {
3121 void* memcpy(void *dest, const void *src, SizeT n);
3122 void* memcpy(void *dest, const void *src, SizeT n) {
3123 return VG_(memcpy)(dest,src,n);
3125 void* memset(void *s, int c, SizeT n);
3126 void* memset(void *s, int c, SizeT n) {
3127 return VG_(memset)(s,c,n);
3130 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3131 'static' causes gcc to complain it isn't. */
3132 void _start_in_C_darwin ( UWord* pArgc );
3133 void _start_in_C_darwin ( UWord* pArgc )
3136 Int argc = *(Int *)pArgc; // not pArgc[0] on LP64
3137 HChar** argv = (HChar**)&pArgc[1];
3138 HChar** envp = (HChar**)&pArgc[1+argc+1];
3140 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3141 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3143 the_iicii.sp_at_startup = (Addr)pArgc;
3145 r = valgrind_main( (Int)argc, argv, envp );
3153 # error "Unknown OS"
3157 /*====================================================================*/
3158 /*=== {u,}{div,mod}di3 replacements ===*/
3159 /*====================================================================*/
3161 /* For static linking on x86-darwin, we need to supply our own 64-bit
3162 integer division code, else the link dies thusly:
3164 ld_classic: Undefined symbols:
3168 #if defined(VGP_x86_darwin)
3170 /* Routines for doing signed/unsigned 64 x 64 ==> 64 div and mod
3171 (udivdi3, umoddi3, divdi3, moddi3) using only 32 x 32 ==> 32
3172 division. Cobbled together from
3174 http://www.hackersdelight.org/HDcode/divlu.c
3175 http://www.hackersdelight.org/HDcode/divls.c
3176 http://www.hackersdelight.org/HDcode/newCode/divDouble.c
3178 The code from those three files is covered by the following license,
3181 http://www.hackersdelight.org/permissions.htm
3183 You are free to use, copy, and distribute any of the code on
3184 this web site, whether modified by you or not. You need not give
3185 attribution. This includes the algorithms (some of which appear
3186 in Hacker's Delight), the Hacker's Assistant, and any code
3187 submitted by readers. Submitters implicitly agree to this.
3190 /* Long division, unsigned (64/32 ==> 32).
3191 This procedure performs unsigned "long division" i.e., division of a
3192 64-bit unsigned dividend by a 32-bit unsigned divisor, producing a
3193 32-bit quotient. In the overflow cases (divide by 0, or quotient
3194 exceeds 32 bits), it returns a remainder of 0xFFFFFFFF (an impossible
3196 The dividend is u1 and u0, with u1 being the most significant word.
3197 The divisor is parameter v. The value returned is the quotient.
3198 Max line length is 57, to fit in hacker.book. */
3200 static Int nlz32(UInt x)
3203 if (x == 0) return(32);
3205 if (x <= 0x0000FFFF) {n = n +16; x = x <<16;}
3206 if (x <= 0x00FFFFFF) {n = n + 8; x = x << 8;}
3207 if (x <= 0x0FFFFFFF) {n = n + 4; x = x << 4;}
3208 if (x <= 0x3FFFFFFF) {n = n + 2; x = x << 2;}
3209 if (x <= 0x7FFFFFFF) {n = n + 1;}
3213 /* 64 x 32 ==> 32 unsigned division, using only 32 x 32 ==> 32
3214 division as a primitive. */
3215 static UInt divlu2(UInt u1, UInt u0, UInt v, UInt *r)
3217 const UInt b = 65536; // Number base (16 bits).
3218 UInt un1, un0, // Norm. dividend LSD's.
3219 vn1, vn0, // Norm. divisor digits.
3220 q1, q0, // Quotient digits.
3221 un32, un21, un10, // Dividend digit pairs.
3222 rhat; // A remainder.
3223 Int s; // Shift amount for norm.
3225 if (u1 >= v) { // If overflow, set rem.
3226 if (r != NULL) // to an impossible value,
3227 *r = 0xFFFFFFFF; // and return the largest
3228 return 0xFFFFFFFF;} // possible quotient.
3230 s = nlz32(v); // 0 <= s <= 31.
3231 v = v << s; // Normalize divisor.
3232 vn1 = v >> 16; // Break divisor up into
3233 vn0 = v & 0xFFFF; // two 16-bit digits.
3235 un32 = (u1 << s) | ((u0 >> (32 - s)) & (-s >> 31));
3236 un10 = u0 << s; // Shift dividend left.
3238 un1 = un10 >> 16; // Break right half of
3239 un0 = un10 & 0xFFFF; // dividend into two digits.
3241 q1 = un32/vn1; // Compute the first
3242 rhat = un32 - q1*vn1; // quotient digit, q1.
3244 if (q1 >= b || q1*vn0 > b*rhat + un1) {
3247 if (rhat < b) goto again1;}
3249 un21 = un32*b + un1 - q1*v; // Multiply and subtract.
3251 q0 = un21/vn1; // Compute the second
3252 rhat = un21 - q0*vn1; // quotient digit, q0.
3254 if (q0 >= b || q0*vn0 > b*rhat + un0) {
3257 if (rhat < b) goto again2;}
3259 if (r != NULL) // If remainder is wanted,
3260 *r = (un21*b + un0 - q0*v) >> s; // return it.
3265 /* 64 x 32 ==> 32 signed division, using only 32 x 32 ==> 32 division
3267 static Int divls(Int u1, UInt u0, Int v, Int *r)
3269 Int q, uneg, vneg, diff, borrow;
3271 uneg = u1 >> 31; // -1 if u < 0.
3272 if (uneg) { // Compute the absolute
3273 u0 = -u0; // value of the dividend u.
3277 vneg = v >> 31; // -1 if v < 0.
3278 v = (v ^ vneg) - vneg; // Absolute value of v.
3280 if ((UInt)u1 >= (UInt)v) goto overflow;
3282 q = divlu2(u1, u0, v, (UInt *)r);
3284 diff = uneg ^ vneg; // Negate q if signs of
3285 q = (q ^ diff) - diff; // u and v differed.
3286 if (uneg && r != NULL)
3289 if ((diff ^ q) < 0 && q != 0) { // If overflow,
3290 overflow: // set remainder
3291 if (r != NULL) // to an impossible value,
3292 *r = 0x80000000; // and return the largest
3293 q = 0x80000000;} // possible neg. quotient.
3299 /* This file contains a program for doing 64/64 ==> 64 division, on a
3300 machine that does not have that instruction but that does have
3301 instructions for "long division" (64/32 ==> 32). Code for unsigned
3302 division is given first, followed by a simple program for doing the
3303 signed version by using the unsigned version.
3304 These programs are useful in implementing "long long" (64-bit)
3305 arithmetic on a machine that has the long division instruction. It will
3306 work on 64- and 32-bit machines, provided the compiler implements long
3307 long's (64-bit integers). It is desirable that the machine have the
3308 Count Leading Zeros instruction.
3309 In the GNU world, these programs are known as __divdi3 and __udivdi3,
3310 and similar names are used here.
3311 This material is not in HD, but may be in a future edition.
3312 Max line length is 57, to fit in hacker.book. */
3315 static Int nlz64(ULong x)
3318 if (x == 0) return(64);
3320 if (x <= 0x00000000FFFFFFFFULL) {n = n + 32; x = x << 32;}
3321 if (x <= 0x0000FFFFFFFFFFFFULL) {n = n + 16; x = x << 16;}
3322 if (x <= 0x00FFFFFFFFFFFFFFULL) {n = n + 8; x = x << 8;}
3323 if (x <= 0x0FFFFFFFFFFFFFFFULL) {n = n + 4; x = x << 4;}
3324 if (x <= 0x3FFFFFFFFFFFFFFFULL) {n = n + 2; x = x << 2;}
3325 if (x <= 0x7FFFFFFFFFFFFFFFULL) {n = n + 1;}
3329 // ---------------------------- udivdi3 --------------------------------
3331 /* The variables u0, u1, etc. take on only 32-bit values, but they
3332 are declared long long to avoid some compiler warning messages and to
3333 avoid some unnecessary EXTRs that the compiler would put in, to
3334 convert long longs to ints.
3336 First the procedure takes care of the case in which the divisor is a
3337 32-bit quantity. There are two subcases: (1) If the left half of the
3338 dividend is less than the divisor, one execution of DIVU is all that
3339 is required (overflow is not possible). (2) Otherwise it does two
3340 divisions, using the grade school method, with variables used as
3350 /* These macros must be used with arguments of the appropriate type
3351 (unsigned long long for DIVU and long long for DIVS. They are
3352 simulations of the presumed machines ops. I.e., they look at only the
3353 low-order 32 bits of the divisor, they return garbage if the division
3354 overflows, and they return garbage in the high-order half of the
3355 quotient doubleword.
3356 In practice, these would be replaced with uses of the machine's DIVU
3357 and DIVS instructions (e.g., by using the GNU "asm" facility). */
3359 static UInt DIVU ( ULong u, UInt v )
3361 UInt uHi = (UInt)(u >> 32);
3363 return divlu2(uHi, uLo, v, NULL);
3366 static Int DIVS ( Long u, Int v )
3368 Int uHi = (Int)(u >> 32);
3370 return divls(uHi, uLo, v, NULL);
3373 /* 64 x 64 ==> 64 unsigned division, using only 32 x 32 ==> 32
3374 division as a primitive. */
3375 static ULong udivdi3(ULong u, ULong v)
3377 ULong u0, u1, v1, q0, q1, k, n;
3379 if (v >> 32 == 0) { // If v < 2**32:
3380 if (u >> 32 < v) // If u/v cannot overflow,
3381 return DIVU(u, v) // just do one division.
3383 else { // If u/v would overflow:
3384 u1 = u >> 32; // Break u up into two
3385 u0 = u & 0xFFFFFFFF; // halves.
3386 q1 = DIVU(u1, v) // First quotient digit.
3388 k = u1 - q1*v; // First remainder, < v.
3389 q0 = DIVU((k << 32) + u0, v) // 2nd quot. digit.
3391 return (q1 << 32) + q0;
3395 n = nlz64(v); // 0 <= n <= 31.
3396 v1 = (v << n) >> 32; // Normalize the divisor
3398 u1 = u >> 1; // To ensure no overflow.
3399 q1 = DIVU(u1, v1) // Get quotient from
3400 & 0xFFFFFFFF; // divide unsigned insn.
3401 q0 = (q1 << n) >> 31; // Undo normalization and
3402 // division of u by 2.
3403 if (q0 != 0) // Make q0 correct or
3404 q0 = q0 - 1; // too small by 1.
3405 if ((u - q0*v) >= v)
3406 q0 = q0 + 1; // Now q0 is correct.
3411 // ----------------------------- divdi3 --------------------------------
3413 /* This routine presumes that smallish cases (those which can be done in
3414 one execution of DIVS) are common. If this is not the case, the test for
3415 this case should be deleted.
3416 Note that the test for when DIVS can be used is not entirely
3417 accurate. For example, DIVS is not used if v = 0xFFFFFFFF8000000,
3418 whereas if could be (if u is sufficiently small in magnitude). */
3420 // ------------------------------ cut ----------------------------------
3422 static ULong my_llabs ( Long x )
3428 /* 64 x 64 ==> 64 signed division, using only 32 x 32 ==> 32 division
3430 static Long divdi3(Long u, Long v)
3436 if (av >> 31 == 0) { // If |v| < 2**31 and
3437 // if (v << 32 >> 32 == v) { // If v is in range and
3438 if (au < av << 31) { // |u|/|v| cannot
3439 q = DIVS(u, v); // overflow, use DIVS.
3440 return (q << 32) >> 32;
3443 q = udivdi3(au,av); // Invoke udivdi3.
3444 t = (u ^ v) >> 63; // If u, v have different
3445 return (q ^ t) - t; // signs, negate q.
3448 // ---------------------------- end cut --------------------------------
3450 ULong __udivdi3 (ULong u, ULong v);
3451 ULong __udivdi3 (ULong u, ULong v)
3453 return udivdi3(u,v);
3456 Long __divdi3 (Long u, Long v);
3457 Long __divdi3 (Long u, Long v)
3462 ULong __umoddi3 (ULong u, ULong v);
3463 ULong __umoddi3 (ULong u, ULong v)
3465 ULong q = __udivdi3(u, v);
3466 ULong r = u - q * v;
3470 Long __moddi3 (Long u, Long v);
3471 Long __moddi3 (Long u, Long v)
3473 Long q = __divdi3(u, v);
3478 /* ------------------------------------------------
3479 ld_classic: Undefined symbols:
3481 ------------------------------------------------
3484 /* ===-- fixunsdfdi.c - Implement __fixunsdfdi -----------------------------===
3486 * The LLVM Compiler Infrastructure
3488 * This file is dual licensed under the MIT and the University of Illinois Open
3489 * Source Licenses. See LICENSE.TXT for details.
3491 * ===----------------------------------------------------------------------===
3493 * This file implements __fixunsdfdi for the compiler_rt library.
3495 * ===----------------------------------------------------------------------===
3498 /* As per http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses,
3500 the "NCSA/University of Illinois Open Source License" is compatible
3501 with the GPL (both version 2 and 3). What is claimed to be
3504 http://www.opensource.org/licenses/UoI-NCSA.php
3506 and the LLVM documentation at
3508 http://www.llvm.org/docs/DeveloperPolicy.html#license
3510 says all the code in LLVM is available under the University of
3511 Illinois/NCSA Open Source License, at this URL
3513 http://www.opensource.org/licenses/UoI-NCSA.php
3515 viz, the same one that the FSF pages claim is compatible. So I
3516 think it's OK to include it.
3519 /* Returns: convert a to a unsigned long long, rounding toward zero.
3520 * Negative values all become zero.
3523 /* Assumption: double is a IEEE 64 bit floating point type
3524 * du_int is a 64 bit integral type
3525 * value in double is representable in du_int or is negative
3526 * (no range checking performed)
3529 /* seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm */
3531 typedef unsigned long long du_int;
3532 typedef unsigned su_int;
3545 #endif /* VG_LITTLEENDIAN */
3555 du_int __fixunsdfdi(double a);
3558 __fixunsdfdi(double a)
3562 int e = ((fb.u.s.high & 0x7FF00000) >> 20) - 1023;
3563 if (e < 0 || (fb.u.s.high & 0x80000000))
3566 r.s.high = (fb.u.s.high & 0x000FFFFF) | 0x00100000;
3567 r.s.low = fb.u.s.low;
3579 /*--------------------------------------------------------------------*/
3581 /*--------------------------------------------------------------------*/