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-2010 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"
69 /* Stuff for reading AIX5 /proc/<pid>/sysent files */
71 /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
72 # include <sys/procfs.h> /* prsysent_t */
73 /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
74 # define VG_AIX5_SYSENT_SIZE 100000
75 static UChar aix5_sysent_buf[VG_AIX5_SYSENT_SIZE];
80 #include <l4/sys/debugger.h>
81 #include <l4/re/env.h>
82 #include <l4/re/c/rm.h>
84 #include "pub_l4re_consts.h"
85 #include "l4re_helper.h"
86 #include "pub_core_debuginfo.h"
89 /*====================================================================*/
90 /*=== Counters, for profiling purposes only ===*/
91 /*====================================================================*/
93 static void print_all_stats ( void )
95 VG_(print_translation_stats)();
96 VG_(print_tt_tc_stats)();
97 VG_(print_scheduler_stats)();
98 VG_(print_ExeContext_stats)();
99 VG_(print_errormgr_stats)();
102 if (VG_(clo_verbosity) > 2) {
103 VG_(message)(Vg_DebugMsg, "\n");
104 VG_(message)(Vg_DebugMsg,
105 "------ Valgrind's internal memory use stats follow ------\n" );
106 VG_(sanity_check_malloc_all)();
107 VG_(message)(Vg_DebugMsg, "------\n" );
108 VG_(print_all_arena_stats)();
109 VG_(message)(Vg_DebugMsg, "\n");
114 /*====================================================================*/
115 /*=== Command-line: variables, processing, etc ===*/
116 /*====================================================================*/
118 // See pub_{core,tool}_options.h for explanations of all these.
120 static void usage_NORETURN ( Bool debug_help )
122 /* 'usage1' contains a %s for the name of the GDB executable, which
123 must be supplied when it is VG_(printf)'d. */
125 "usage: valgrind [options] prog-and-args\n"
127 " tool-selection option, with default in [ ]:\n"
128 " --tool=<name> use the Valgrind tool named <name> [memcheck]\n"
130 " basic user options for all Valgrind tools, with defaults in [ ]:\n"
131 " -h --help show this message\n"
132 " --help-debug show this message, plus debugging options\n"
133 " --version show version\n"
134 " -q --quiet run silently; only print error msgs\n"
135 " -v --verbose be more verbose -- show misc extra info\n"
136 " --trace-children=no|yes Valgrind-ise child processes (follow execve)? [no]\n"
137 " --trace-children-skip=patt1,patt2,... specifies a list of executables\n"
138 " that --trace-children=yes should not trace into\n"
139 " --trace-children-skip-by-arg=patt1,patt2,... same as --trace-children-skip=\n"
140 " but check the argv[] entries for children, rather\n"
141 " than the exe name, to make a follow/no-follow decision\n"
142 " --child-silent-after-fork=no|yes omit child output between fork & exec? [no]\n"
143 " --vgdb=no|yes|full activate gdbserver? [yes]\n"
144 " full is slower but provides precise watchpoint/step\n"
145 " --vgdb-error=<number> invoke gdbserver after <number> errors [%d] \n"
146 " --track-fds=no|yes track open file descriptors? [no]\n"
147 " --time-stamp=no|yes add timestamps to log messages? [no]\n"
148 " --log-fd=<number> log messages to file descriptor [2=stderr]\n"
149 " --log-file=<file> log messages to <file>\n"
150 " --log-socket=ipaddr:port log messages to socket ipaddr:port\n"
152 " user options for Valgrind tools that report errors:\n"
153 " --xml=yes emit error output in XML (some tools only)\n"
154 " --xml-fd=<number> XML output to file descriptor\n"
155 " --xml-file=<file> XML output to <file>\n"
156 " --xml-socket=ipaddr:port XML output to socket ipaddr:port\n"
157 " --xml-user-comment=STR copy STR verbatim into XML output\n"
158 " --demangle=no|yes automatically demangle C++ names? [yes]\n"
159 " --num-callers=<number> show <number> callers in stack traces [12]\n"
160 " --error-limit=no|yes stop showing new errors if too many? [yes]\n"
161 " --error-exitcode=<number> exit code to return if errors found [0=disable]\n"
162 " --show-below-main=no|yes continue stack traces below main() [no]\n"
163 " --suppressions=<filename> suppress errors described in <filename>\n"
164 " --gen-suppressions=no|yes|all print suppressions for errors? [no]\n"
165 " --db-attach=no|yes start debugger when errors detected? [no]\n"
166 " --db-command=<command> command to start debugger [%s -nw %%f %%p]\n"
167 " --input-fd=<number> file descriptor for input [0=stdin]\n"
168 " --dsymutil=no|yes run dsymutil on Mac OS X when helpful? [no]\n"
169 " --max-stackframe=<number> assume stack switch for SP changes larger\n"
170 " than <number> bytes [2000000]\n"
171 " --main-stacksize=<number> set size of main thread's stack (in bytes)\n"
172 " [use current 'ulimit' value]\n"
174 " user options for Valgrind tools that replace malloc:\n"
175 " --alignment=<number> set minimum alignment of heap allocations [%ld]\n"
177 " uncommon user options for all Valgrind tools:\n"
178 " --fullpath-after= (with nothing after the '=')\n"
179 " show full source paths in call stacks\n"
180 " --fullpath-after=string like --fullpath-after=, but only show the\n"
181 " part of the path after 'string'. Allows removal\n"
182 " of path prefixes. Use this flag multiple times\n"
183 " to specify a set of prefixes to remove.\n"
184 " --smc-check=none|stack|all checks for self-modifying code: none,\n"
185 " only for code found in stacks, or all [stack]\n"
186 " --read-var-info=yes|no read debug info on stack and global variables\n"
187 " and use it to print better error messages in\n"
188 " tools that make use of it (Memcheck, Helgrind,\n"
190 " --vgdb-poll=<number> gdbserver poll max every <number> basic blocks [%d] \n"
191 " --vgdb-shadow-registers=no|yes let gdb see the shadow registers [no]\n"
192 " --vgdb-prefix=<prefix> prefix for vgdb FIFOs [%s]\n"
193 " --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]\n"
194 " --sim-hints=hint1,hint2,... known hints:\n"
195 " lax-ioctls, enable-outer [none]\n"
196 " --kernel-variant=variant1,variant2,... known variants: bproc [none]\n"
197 " handle non-standard kernel variants\n"
198 " --show-emwarns=no|yes show warnings about emulation limits? [no]\n"
199 " --require-text-symbol=:sonamepattern:symbolpattern abort run if the\n"
200 " stated shared object doesn't have the stated\n"
201 " text symbol. Patterns can contain ? and *.\n"
206 " debugging options for all Valgrind tools:\n"
207 " -d show verbose debugging output\n"
208 " --stats=no|yes show tool and core statistics [no]\n"
209 " --sanity-level=<number> level of sanity checking to do [1]\n"
210 " --trace-flags=<XXXXXXXX> show generated code? (X = 0|1) [00000000]\n"
211 " --profile-flags=<XXXXXXXX> ditto, but for profiling (X = 0|1) [00000000]\n"
212 " --trace-notbelow=<number> only show BBs above <number> [999999999]\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 " --wait-for-gdb=yes|no pause on startup to wait for gdb attach\n"
225 " --sym-offsets=yes|no show syms in form 'name+offset' ? [no]\n"
226 " --command-line-only=no|yes only use command line options [no]\n"
228 " Vex options for all Valgrind tools:\n"
229 " --vex-iropt-verbosity=<0..9> [0]\n"
230 " --vex-iropt-level=<0..2> [2]\n"
231 " --vex-iropt-precise-memory-exns=no|yes [no]\n"
232 " --vex-iropt-unroll-thresh=<0..400> [120]\n"
233 " --vex-guest-max-insns=<1..100> [50]\n"
234 " --vex-guest-chase-thresh=<0..99> [10]\n"
235 " --trace-flags and --profile-flags values (omit the middle space):\n"
236 " 1000 0000 show conversion into IR\n"
237 " 0100 0000 show after initial opt\n"
238 " 0010 0000 show after instrumentation\n"
239 " 0001 0000 show after second opt\n"
240 " 0000 1000 show after tree building\n"
241 " 0000 0100 show selecting insns\n"
242 " 0000 0010 show after reg-alloc\n"
243 " 0000 0001 show final assembly\n"
244 " (Nb: you need --trace-notbelow with --trace-flags for full details)\n"
246 " debugging options for Valgrind tools that report errors\n"
247 " --dump-error=<number> show translation for basic block associated\n"
248 " with <number>'th error context [0=show none]\n"
250 " debugging options for Valgrind tools that replace malloc:\n"
251 " --trace-malloc=no|yes show client malloc details? [no]\n"
256 " Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc\n"
259 " Valgrind is Copyright (C) 2000-2010, and GNU GPL'd, by Julian Seward et al.\n"
260 " LibVEX is Copyright (C) 2004-2010, and GNU GPL'd, by OpenWorks LLP et al.\n"
262 " Bug reports, feedback, admiration, abuse, etc, to: %s.\n"
265 Char* gdb_path = GDB_PATH;
267 // Ensure the message goes to stdout
268 VG_(log_output_sink).fd = 1;
269 VG_(log_output_sink).is_socket = False;
271 /* 'usage1' expects two int, two char* argument, and one SizeT argument. */
273 VG_(clo_vgdb_error), gdb_path, VG_MIN_MALLOC_SZB,
274 VG_(clo_vgdb_poll), VG_(clo_vgdb_prefix));
275 if (VG_(details).name) {
276 VG_(printf)(" user options for %s:\n", VG_(details).name);
277 if (VG_(needs).command_line_options)
278 VG_TDICT_CALL(tool_print_usage);
280 VG_(printf)(" (none)\n");
283 VG_(printf)("%s", usage2);
285 if (VG_(details).name) {
286 VG_(printf)(" debugging options for %s:\n", VG_(details).name);
288 if (VG_(needs).command_line_options)
289 VG_TDICT_CALL(tool_print_debug_usage);
291 VG_(printf)(" (none)\n");
294 VG_(printf)(usage3, VG_(details).name, VG_(details).copyright_author,
300 /* Peer at previously set up VG_(args_for_valgrind) and do some
301 minimal command line processing that must happen early on:
303 - show the version string, if requested (-v)
304 - extract any request for help (--help, -h, --help-debug)
305 - get the toolname (--tool=)
306 - set VG_(clo_max_stackframe) (--max-stackframe=)
307 - set VG_(clo_main_stacksize) (--main-stacksize=)
309 That's all it does. The main command line processing is done below
310 by main_process_cmd_line_options. Note that
311 main_process_cmd_line_options has to handle but ignore the ones we
314 static void early_process_cmd_line_options ( /*OUT*/Int* need_help,
315 /*OUT*/HChar** tool )
320 vg_assert( VG_(args_for_valgrind) );
322 /* parse the options we have (only the options we care about now) */
323 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
325 str = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
328 // Nb: the version string goes to stdout.
329 if VG_XACT_CLO(str, "--version", VG_(log_output_sink).fd, 1) {
330 VG_(log_output_sink).is_socket = False;
331 VG_(printf)("valgrind-" VERSION "\n");
334 else if VG_XACT_CLO(str, "--help", *need_help, *need_help+1) {}
335 else if VG_XACT_CLO(str, "-h", *need_help, *need_help+1) {}
337 else if VG_XACT_CLO(str, "--help-debug", *need_help, *need_help+2) {}
339 // The tool has already been determined, but we need to know the name
341 else if VG_STR_CLO(str, "--tool", *tool) {}
343 // Set up VG_(clo_max_stackframe) and VG_(clo_main_stacksize).
344 // These are needed by VG_(ii_create_image), which happens
345 // before main_process_cmd_line_options().
346 else if VG_INT_CLO(str, "--max-stackframe", VG_(clo_max_stackframe)) {}
347 else if VG_INT_CLO(str, "--main-stacksize", VG_(clo_main_stacksize)) {}
351 /* The main processing for command line options. See comments above
352 on early_process_cmd_line_options.
354 Comments on how the logging options are handled:
357 --log-fd= for a fd to write to (default setting, fd = 2)
358 --log-file= for a file name to write to
359 --log-socket= for a socket to write to
361 As a result of examining these and doing relevant socket/file
362 opening, a final fd is established. This is stored in
363 VG_(log_output_sink) in m_libcprint. Also, if --log-file=STR was
364 specified, then STR, after expansion of %p and %q templates within
365 it, is stored in VG_(clo_log_fname_expanded), in m_options, just in
366 case anybody wants to know what it is.
368 When printing, VG_(log_output_sink) is consulted to find the
369 fd to send output to.
371 Exactly analogous actions are undertaken for the XML output
372 channel, with the one difference that the default fd is -1, meaning
373 the channel is disabled by default.
376 void main_process_cmd_line_options ( /*OUT*/Bool* logging_to_fd,
377 /*OUT*/Char** xml_fname_unexpanded,
378 const HChar* toolname )
380 // VG_(clo_log_fd) is used by all the messaging. It starts as 2 (stderr)
381 // and we cannot change it until we know what we are changing it to is
382 // ok. So we have tmp_log_fd to hold the tmp fd prior to that point.
384 Int i, tmp_log_fd, tmp_xml_fd;
385 Int toolname_len = VG_(strlen)(toolname);
386 Char* tmp_str; // Used in a couple of places.
391 } log_to = VgLogTo_Fd, // Where is logging output to be sent?
392 xml_to = VgLogTo_Fd; // Where is XML output to be sent?
394 /* Temporarily holds the string STR specified with
395 --{log,xml}-{name,socket}=STR. 'fs' stands for
397 Char* log_fsname_unexpanded = NULL;
398 Char* xml_fsname_unexpanded = NULL;
400 /* Log to stderr by default, but usage message goes to stdout. XML
401 output is initially disabled. */
405 #if !defined(VGO_l4re)
406 /* Check for sane path in ./configure --prefix=... */
407 if (VG_LIBDIR[0] != '/')
408 VG_(err_config_error)("Please use absolute paths in "
409 "./configure --prefix=... or --libdir=...");
412 vg_assert( VG_(args_for_valgrind) );
414 /* BEGIN command-line processing loop */
416 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
418 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
421 // Look for a colon in the option name.
422 while (*colon && *colon != ':' && *colon != '=')
425 // Does it have the form "--toolname:foo"? We have to do it at the start
426 // in case someone has combined a prefix with a core-specific option,
427 // eg. "--memcheck:verbose".
429 if (VG_STREQN(2, arg, "--") &&
430 VG_STREQN(toolname_len, arg+2, toolname) &&
431 VG_STREQN(1, arg+2+toolname_len, ":"))
433 // Prefix matches, convert "--toolname:foo" to "--foo".
434 // Two things to note:
435 // - We cannot modify the option in-place. If we did, and then
436 // a child was spawned with --trace-children=yes, the
437 // now-non-prefixed option would be passed and could screw up
439 // - We create copies, and never free them. Why? Non-prefixed
440 // options hang around forever, so tools need not make copies
441 // of strings within them. We need to have the same behaviour
442 // for prefixed options. The pointer to the copy will be lost
443 // once we leave this function (although a tool may keep a
444 // pointer into it), but the space wasted is insignificant.
445 // (In bug #142197, the copies were being freed, which caused
446 // problems for tools that reasonably assumed that arguments
447 // wouldn't disappear on them.)
449 VG_(printf)("tool-specific arg: %s\n", arg);
450 arg = VG_(strdup)("main.mpclo.1", arg + toolname_len + 1);
455 // prefix doesn't match, skip to next arg
460 /* Ignore these options - they've already been handled */
461 if VG_STREQN( 7, arg, "--tool=") {}
462 else if VG_STREQN(20, arg, "--command-line-only=") {}
463 else if VG_STREQ( arg, "--") {}
464 else if VG_STREQ( arg, "-d") {}
465 else if VG_STREQN(16, arg, "--max-stackframe") {}
466 else if VG_STREQN(16, arg, "--main-stacksize") {}
467 else if VG_STREQN(14, arg, "--profile-heap") {}
469 // These options are new.
470 else if (VG_STREQ(arg, "-v") ||
471 VG_STREQ(arg, "--verbose"))
472 VG_(clo_verbosity)++;
474 else if (VG_STREQ(arg, "-q") ||
475 VG_STREQ(arg, "--quiet"))
476 VG_(clo_verbosity)--;
478 else if VG_BOOL_CLO(arg, "--stats", VG_(clo_stats)) {}
479 else if VG_BOOL_CLO(arg, "--xml", VG_(clo_xml)) {}
480 else if VG_XACT_CLO(arg, "--vgdb=no", VG_(clo_vgdb), Vg_VgdbNo) {}
481 else if VG_XACT_CLO(arg, "--vgdb=yes", VG_(clo_vgdb), Vg_VgdbYes) {}
482 else if VG_XACT_CLO(arg, "--vgdb=full", VG_(clo_vgdb), Vg_VgdbFull) {}
483 else if VG_INT_CLO (arg, "--vgdb-poll", VG_(clo_vgdb_poll)) {}
484 else if VG_INT_CLO (arg, "--vgdb-error", VG_(clo_vgdb_error)) {}
485 else if VG_STR_CLO (arg, "--vgdb-prefix", VG_(clo_vgdb_prefix)) {}
486 else if VG_BOOL_CLO(arg, "--vgdb-shadow-registers",
487 VG_(clo_vgdb_shadow_registers)) {}
488 else if VG_BOOL_CLO(arg, "--db-attach", VG_(clo_db_attach)) {}
489 else if VG_BOOL_CLO(arg, "--demangle", VG_(clo_demangle)) {}
490 else if VG_BOOL_CLO(arg, "--error-limit", VG_(clo_error_limit)) {}
491 else if VG_INT_CLO (arg, "--error-exitcode", VG_(clo_error_exitcode)) {}
492 else if VG_BOOL_CLO(arg, "--show-emwarns", VG_(clo_show_emwarns)) {}
494 else if VG_BOOL_CLO(arg, "--run-libc-freeres", VG_(clo_run_libc_freeres)) {}
495 else if VG_BOOL_CLO(arg, "--show-below-main", VG_(clo_show_below_main)) {}
496 else if VG_BOOL_CLO(arg, "--time-stamp", VG_(clo_time_stamp)) {}
497 else if VG_BOOL_CLO(arg, "--track-fds", VG_(clo_track_fds)) {}
498 else if VG_BOOL_CLO(arg, "--trace-children", VG_(clo_trace_children)) {}
499 else if VG_BOOL_CLO(arg, "--child-silent-after-fork",
500 VG_(clo_child_silent_after_fork)) {}
501 else if VG_BOOL_CLO(arg, "--trace-sched", VG_(clo_trace_sched)) {}
502 else if VG_BOOL_CLO(arg, "--trace-signals", VG_(clo_trace_signals)) {}
503 else if VG_BOOL_CLO(arg, "--trace-symtab", VG_(clo_trace_symtab)) {}
504 else if VG_STR_CLO (arg, "--trace-symtab-patt", VG_(clo_trace_symtab_patt)) {}
505 else if VG_BOOL_CLO(arg, "--trace-cfi", VG_(clo_trace_cfi)) {}
506 else if VG_XACT_CLO(arg, "--debug-dump=syms", VG_(clo_debug_dump_syms),
508 else if VG_XACT_CLO(arg, "--debug-dump=line", VG_(clo_debug_dump_line),
510 else if VG_XACT_CLO(arg, "--debug-dump=frames",
511 VG_(clo_debug_dump_frames), True) {}
512 else if VG_BOOL_CLO(arg, "--trace-redir", VG_(clo_trace_redir)) {}
514 else if VG_BOOL_CLO(arg, "--trace-syscalls", VG_(clo_trace_syscalls)) {}
515 else if VG_BOOL_CLO(arg, "--wait-for-gdb", VG_(clo_wait_for_gdb)) {}
516 else if VG_STR_CLO (arg, "--db-command", VG_(clo_db_command)) {}
517 else if VG_STR_CLO (arg, "--sim-hints", VG_(clo_sim_hints)) {}
518 else if VG_BOOL_CLO(arg, "--sym-offsets", VG_(clo_sym_offsets)) {}
519 else if VG_BOOL_CLO(arg, "--read-var-info", VG_(clo_read_var_info)) {}
521 else if VG_INT_CLO (arg, "--dump-error", VG_(clo_dump_error)) {}
522 else if VG_INT_CLO (arg, "--input-fd", VG_(clo_input_fd)) {}
523 else if VG_INT_CLO (arg, "--sanity-level", VG_(clo_sanity_level)) {}
524 else if VG_BINT_CLO(arg, "--num-callers", VG_(clo_backtrace_size), 1,
525 VG_DEEPEST_BACKTRACE) {}
527 else if VG_XACT_CLO(arg, "--smc-check=none", VG_(clo_smc_check),
529 else if VG_XACT_CLO(arg, "--smc-check=stack", VG_(clo_smc_check),
531 else if VG_XACT_CLO(arg, "--smc-check=all", VG_(clo_smc_check),
534 else if VG_STR_CLO (arg, "--kernel-variant", VG_(clo_kernel_variant)) {}
536 else if VG_BOOL_CLO(arg, "--dsymutil", VG_(clo_dsymutil)) {}
538 else if VG_STR_CLO (arg, "--trace-children-skip",
539 VG_(clo_trace_children_skip)) {}
540 else if VG_STR_CLO (arg, "--trace-children-skip-by-arg",
541 VG_(clo_trace_children_skip_by_arg)) {}
543 else if VG_BINT_CLO(arg, "--vex-iropt-verbosity",
544 VG_(clo_vex_control).iropt_verbosity, 0, 10) {}
545 else if VG_BINT_CLO(arg, "--vex-iropt-level",
546 VG_(clo_vex_control).iropt_level, 0, 2) {}
547 else if VG_BOOL_CLO(arg, "--vex-iropt-precise-memory-exns",
548 VG_(clo_vex_control).iropt_precise_memory_exns) {}
549 else if VG_BINT_CLO(arg, "--vex-iropt-unroll-thresh",
550 VG_(clo_vex_control).iropt_unroll_thresh, 0, 400) {}
551 else if VG_BINT_CLO(arg, "--vex-guest-max-insns",
552 VG_(clo_vex_control).guest_max_insns, 1, 100) {}
553 else if VG_BINT_CLO(arg, "--vex-guest-chase-thresh",
554 VG_(clo_vex_control).guest_chase_thresh, 0, 99) {}
556 else if VG_INT_CLO(arg, "--log-fd", tmp_log_fd) {
558 log_fsname_unexpanded = NULL;
560 else if VG_INT_CLO(arg, "--xml-fd", tmp_xml_fd) {
562 xml_fsname_unexpanded = NULL;
565 else if VG_STR_CLO(arg, "--log-file", log_fsname_unexpanded) {
566 log_to = VgLogTo_File;
568 else if VG_STR_CLO(arg, "--xml-file", xml_fsname_unexpanded) {
569 xml_to = VgLogTo_File;
572 else if VG_STR_CLO(arg, "--log-socket", log_fsname_unexpanded) {
573 log_to = VgLogTo_Socket;
575 else if VG_STR_CLO(arg, "--xml-socket", xml_fsname_unexpanded) {
576 xml_to = VgLogTo_Socket;
579 else if VG_STR_CLO(arg, "--xml-user-comment",
580 VG_(clo_xml_user_comment)) {}
582 else if VG_STR_CLO(arg, "--suppressions", tmp_str) {
583 if (VG_(clo_n_suppressions) >= VG_CLO_MAX_SFILES) {
584 VG_(fmsg_bad_option)(arg,
585 "Too many suppression files specified.\n"
586 "Increase VG_CLO_MAX_SFILES and recompile.\n");
588 VG_(clo_suppressions)[VG_(clo_n_suppressions)] = tmp_str;
589 VG_(clo_n_suppressions)++;
592 else if VG_STR_CLO (arg, "--fullpath-after", tmp_str) {
593 if (VG_(clo_n_fullpath_after) >= VG_CLO_MAX_FULLPATH_AFTER) {
594 VG_(fmsg_bad_option)(arg,
595 "Too many --fullpath-after= specifications.\n"
596 "Increase VG_CLO_MAX_FULLPATH_AFTER and recompile.\n");
598 VG_(clo_fullpath_after)[VG_(clo_n_fullpath_after)] = tmp_str;
599 VG_(clo_n_fullpath_after)++;
602 else if VG_STR_CLO(arg, "--require-text-symbol", tmp_str) {
603 if (VG_(clo_n_req_tsyms) >= VG_CLO_MAX_REQ_TSYMS) {
604 VG_(fmsg_bad_option)(arg,
605 "Too many --require-text-symbol= specifications.\n"
606 "Increase VG_CLO_MAX_REQ_TSYMS and recompile.\n");
608 /* String needs to be of the form C?*C?*, where C is any
609 character, but is the same both times. Having it in this
610 form facilitates finding the boundary between the sopatt
611 and the fnpatt just by looking for the second occurrence
612 of C, without hardwiring any assumption about what C
616 ok = tmp_str && VG_(strlen)(tmp_str) > 0;
618 patt[0] = patt[3] = tmp_str[0];
619 patt[1] = patt[4] = '?';
620 patt[2] = patt[5] = '*';
622 ok = VG_(string_match)(patt, tmp_str);
625 VG_(fmsg_bad_option)(arg,
626 "Invalid --require-text-symbol= specification.\n");
628 VG_(clo_req_tsyms)[VG_(clo_n_req_tsyms)] = tmp_str;
629 VG_(clo_n_req_tsyms)++;
632 /* "stuvwxyz" --> stuvwxyz (binary) */
633 else if VG_STR_CLO(arg, "--trace-flags", tmp_str) {
636 if (8 != VG_(strlen)(tmp_str)) {
637 VG_(fmsg_bad_option)(arg,
638 "--trace-flags argument must have 8 digits\n");
640 for (j = 0; j < 8; j++) {
641 if ('0' == tmp_str[j]) { /* do nothing */ }
642 else if ('1' == tmp_str[j]) VG_(clo_trace_flags) |= (1 << (7-j));
644 VG_(fmsg_bad_option)(arg,
645 "--trace-flags argument can only contain 0s and 1s\n");
650 /* "stuvwxyz" --> stuvwxyz (binary) */
651 else if VG_STR_CLO(arg, "--profile-flags", tmp_str) {
654 if (8 != VG_(strlen)(tmp_str)) {
655 VG_(fmsg_bad_option)(arg,
656 "--profile-flags argument must have 8 digits\n");
658 for (j = 0; j < 8; j++) {
659 if ('0' == tmp_str[j]) { /* do nothing */ }
660 else if ('1' == tmp_str[j]) VG_(clo_profile_flags) |= (1 << (7-j));
662 VG_(fmsg_bad_option)(arg,
663 "--profile-flags argument can only contain 0s and 1s\n");
668 else if VG_INT_CLO (arg, "--trace-notbelow", VG_(clo_trace_notbelow)) {}
670 else if VG_XACT_CLO(arg, "--gen-suppressions=no",
671 VG_(clo_gen_suppressions), 0) {}
672 else if VG_XACT_CLO(arg, "--gen-suppressions=yes",
673 VG_(clo_gen_suppressions), 1) {}
674 else if VG_XACT_CLO(arg, "--gen-suppressions=all",
675 VG_(clo_gen_suppressions), 2) {}
677 else if ( ! VG_(needs).command_line_options
678 || ! VG_TDICT_CALL(tool_process_cmd_line_option, arg) ) {
679 VG_(fmsg_bad_option)(arg, "");
683 /* END command-line processing loop */
685 /* Make VEX control parameters sane */
687 if (VG_(clo_vex_control).guest_chase_thresh
688 >= VG_(clo_vex_control).guest_max_insns)
689 VG_(clo_vex_control).guest_chase_thresh
690 = VG_(clo_vex_control).guest_max_insns - 1;
692 if (VG_(clo_vex_control).guest_chase_thresh < 0)
693 VG_(clo_vex_control).guest_chase_thresh = 0;
695 /* Check various option values */
697 if (VG_(clo_verbosity) < 0)
698 VG_(clo_verbosity) = 0;
700 VG_(dyn_vgdb_error) = VG_(clo_vgdb_error);
702 if (VG_(clo_gen_suppressions) > 0 &&
703 !VG_(needs).core_errors && !VG_(needs).tool_errors) {
704 VG_(fmsg_bad_option)("--gen-suppressions=yes",
705 "Can't use --gen-suppressions= with %s\n"
706 "because it doesn't generate errors.\n", VG_(details).name);
709 /* If XML output is requested, check that the tool actually
711 if (VG_(clo_xml) && !VG_(needs).xml_output) {
712 VG_(clo_xml) = False;
713 VG_(fmsg_bad_option)("--xml=yes",
714 "%s does not support XML output.\n", VG_(details).name);
718 vg_assert( VG_(clo_gen_suppressions) >= 0 );
719 vg_assert( VG_(clo_gen_suppressions) <= 2 );
721 /* If we've been asked to emit XML, mash around various other
722 options so as to constrain the output somewhat, and to remove
723 any need for user input during the run.
727 /* We can't allow --gen-suppressions=yes, since that requires us
728 to print the error and then ask the user if she wants a
729 suppression for it, but in XML mode we won't print it until
730 we know whether we also need to print a suppression. Hence a
731 circular dependency. So disallow this.
732 (--gen-suppressions=all is still OK since we don't need any
733 user interaction in this case.) */
734 if (VG_(clo_gen_suppressions) == 1) {
735 VG_(fmsg_bad_option)(
736 "--xml=yes together with --gen-suppressions=yes",
737 "When --xml=yes is specified, --gen-suppressions=no\n"
738 "or --gen-suppressions=all is allowed, but not "
739 "--gen-suppressions=yes.\n");
742 /* We can't allow DB attaching (or we maybe could, but results
743 could be chaotic ..) since it requires user input. Hence
745 if (VG_(clo_db_attach)) {
746 VG_(fmsg_bad_option)(
747 "--xml=yes together with --db-attach=yes",
748 "--db-attach=yes is not allowed with --xml=yes\n"
749 "because it would require user input.\n");
752 /* Disallow dump_error in XML mode; sounds like a recipe for
753 chaos. No big deal; dump_error is a flag for debugging V
755 if (VG_(clo_dump_error) > 0) {
756 VG_(fmsg_bad_option)("--xml=yes together with --dump-error", "");
759 /* Disable error limits (this might be a bad idea!) */
760 VG_(clo_error_limit) = False;
761 /* Disable emulation warnings */
763 /* Also, we want to set options for the leak checker, but that
764 will have to be done in Memcheck's flag-handling code, not
768 /* All non-logging-related options have been checked. If the logging
769 option specified is ok, we can switch to it, as we know we won't
770 have to generate any other command-line-related error messages.
771 (So far we should be still attached to stderr, so we can show on
772 the terminal any problems to do with processing command line
775 So set up logging now. After this is done, VG_(log_output_sink)
776 and (if relevant) VG_(xml_output_sink) should be connected to
777 whatever sink has been selected, and we indiscriminately chuck
778 stuff into it without worrying what the nature of it is. Oh the
779 wonder of Unix streams. */
781 vg_assert(VG_(log_output_sink).fd == 2 /* stderr */);
782 vg_assert(VG_(log_output_sink).is_socket == False);
783 vg_assert(VG_(clo_log_fname_expanded) == NULL);
785 vg_assert(VG_(xml_output_sink).fd == -1 /* disabled */);
786 vg_assert(VG_(xml_output_sink).is_socket == False);
787 vg_assert(VG_(clo_xml_fname_expanded) == NULL);
789 /* --- set up the normal text output channel --- */
794 vg_assert(log_fsname_unexpanded == NULL);
800 vg_assert(log_fsname_unexpanded != NULL);
801 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
803 // Nb: we overwrite an existing file of this name without asking
805 logfilename = VG_(expand_file_name)("--log-file",
806 log_fsname_unexpanded);
807 sres = VG_(open)(logfilename,
808 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
809 VKI_S_IRUSR|VKI_S_IWUSR);
810 if (!sr_isError(sres)) {
811 tmp_log_fd = sr_Res(sres);
812 VG_(clo_log_fname_expanded) = logfilename;
814 VG_(fmsg)("can't create log file '%s': %s\n",
815 logfilename, VG_(strerror)(sr_Err(sres)));
822 case VgLogTo_Socket: {
823 vg_assert(log_fsname_unexpanded != NULL);
824 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
825 tmp_log_fd = VG_(connect_via_socket)( log_fsname_unexpanded );
826 if (tmp_log_fd == -1) {
827 VG_(fmsg)("Invalid --log-socket spec of '%s'\n",
828 log_fsname_unexpanded);
832 if (tmp_log_fd == -2) {
833 VG_(umsg)("failed to connect to logging server '%s'.\n"
834 "Log messages will sent to stderr instead.\n",
835 log_fsname_unexpanded );
837 /* We don't change anything here. */
838 vg_assert(VG_(log_output_sink).fd == 2);
841 vg_assert(tmp_log_fd > 0);
842 VG_(log_output_sink).is_socket = True;
848 /* --- set up the XML output channel --- */
853 vg_assert(xml_fsname_unexpanded == NULL);
859 vg_assert(xml_fsname_unexpanded != NULL);
860 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
862 // Nb: we overwrite an existing file of this name without asking
864 xmlfilename = VG_(expand_file_name)("--xml-file",
865 xml_fsname_unexpanded);
866 sres = VG_(open)(xmlfilename,
867 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
868 VKI_S_IRUSR|VKI_S_IWUSR);
869 if (!sr_isError(sres)) {
870 tmp_xml_fd = sr_Res(sres);
871 VG_(clo_xml_fname_expanded) = xmlfilename;
872 /* strdup here is probably paranoid overkill, but ... */
873 *xml_fname_unexpanded = VG_(strdup)( "main.mpclo.2",
874 xml_fsname_unexpanded );
876 VG_(fmsg)("can't create XML file '%s': %s\n",
877 xmlfilename, VG_(strerror)(sr_Err(sres)));
884 case VgLogTo_Socket: {
885 vg_assert(xml_fsname_unexpanded != NULL);
886 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
887 tmp_xml_fd = VG_(connect_via_socket)( xml_fsname_unexpanded );
888 if (tmp_xml_fd == -1) {
889 VG_(fmsg)("Invalid --xml-socket spec of '%s'\n",
890 xml_fsname_unexpanded );
894 if (tmp_xml_fd == -2) {
895 VG_(umsg)("failed to connect to XML logging server '%s'.\n"
896 "XML output will sent to stderr instead.\n",
897 xml_fsname_unexpanded);
898 /* We don't change anything here. */
899 vg_assert(VG_(xml_output_sink).fd == 2);
902 vg_assert(tmp_xml_fd > 0);
903 VG_(xml_output_sink).is_socket = True;
909 /* If we've got this far, and XML mode was requested, but no XML
910 output channel appears to have been specified, just stop. We
911 could continue, and XML output will simply vanish into nowhere,
912 but that is likely to confuse the hell out of users, which is
913 distinctly Ungood. */
914 if (VG_(clo_xml) && tmp_xml_fd == -1) {
915 VG_(fmsg_bad_option)(
916 "--xml=yes, but no XML destination specified",
917 "--xml=yes has been specified, but there is no XML output\n"
918 "destination. You must specify an XML output destination\n"
919 "using --xml-fd, --xml-file or --xml-socket.\n"
923 // Finalise the output fds: the log fd ..
925 if (tmp_log_fd >= 0) {
926 // Move log_fd into the safe range, so it doesn't conflict with
928 tmp_log_fd = VG_(fcntl)(tmp_log_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
929 if (tmp_log_fd < 0) {
930 VG_(message)(Vg_UserMsg, "valgrind: failed to move logfile fd "
931 "into safe range, using stderr\n");
932 VG_(log_output_sink).fd = 2; // stderr
933 VG_(log_output_sink).is_socket = False;
935 VG_(log_output_sink).fd = tmp_log_fd;
936 VG_(fcntl)(VG_(log_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
939 // If they said --log-fd=-1, don't print anything. Plausible for use in
940 // regression testing suites that use client requests to count errors.
941 VG_(log_output_sink).fd = -1;
942 VG_(log_output_sink).is_socket = False;
945 // Finalise the output fds: and the XML fd ..
947 if (tmp_xml_fd >= 0) {
948 // Move xml_fd into the safe range, so it doesn't conflict with
950 tmp_xml_fd = VG_(fcntl)(tmp_xml_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
951 if (tmp_xml_fd < 0) {
952 VG_(message)(Vg_UserMsg, "valgrind: failed to move XML file fd "
953 "into safe range, using stderr\n");
954 VG_(xml_output_sink).fd = 2; // stderr
955 VG_(xml_output_sink).is_socket = False;
957 VG_(xml_output_sink).fd = tmp_xml_fd;
958 VG_(fcntl)(VG_(xml_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
961 // If they said --xml-fd=-1, don't print anything. Plausible for use in
962 // regression testing suites that use client requests to count errors.
963 VG_(xml_output_sink).fd = -1;
964 VG_(xml_output_sink).is_socket = False;
967 // Suppressions related stuff
969 if (VG_(clo_n_suppressions) < VG_CLO_MAX_SFILES-1 &&
970 (VG_(needs).core_errors || VG_(needs).tool_errors)) {
971 /* If we haven't reached the max number of suppressions, load
973 static const Char default_supp[] = "default.supp";
974 Int len = VG_(strlen)(VG_(libdir)) + 1 + sizeof(default_supp);
975 Char *buf = VG_(arena_malloc)(VG_AR_CORE, "main.mpclo.3", len);
976 VG_(sprintf)(buf, "%s/%s", VG_(libdir), default_supp);
977 VG_(clo_suppressions)[VG_(clo_n_suppressions)] = buf;
978 VG_(clo_n_suppressions)++;
981 *logging_to_fd = log_to == VgLogTo_Fd || log_to == VgLogTo_Socket;
984 // Write the name and value of log file qualifiers to the xml file.
985 static void print_file_vars(Char* format)
990 if (format[i] == '%') {
991 // We saw a '%'. What's next...
993 if ('q' == format[i]) {
995 if ('{' == format[i]) {
996 // Get the env var name, print its contents.
1000 qualname = &format[i];
1002 if ('}' == format[i]) {
1003 // Temporarily replace the '}' with NUL to extract var
1006 qual = VG_(getenv)(qualname);
1012 VG_(printf_xml_no_f_c)(
1013 "<logfilequalifier> <var>%t</var> "
1014 "<value>%t</value> </logfilequalifier>\n",
1028 /*====================================================================*/
1029 /*=== Printing the preamble ===*/
1030 /*====================================================================*/
1032 // Print the command, escaping any chars that require it.
1033 static void umsg_or_xml_arg(const Char* arg,
1034 UInt (*umsg_or_xml)( const HChar*, ... ) )
1036 SizeT len = VG_(strlen)(arg);
1037 Char* special = " \\<>";
1039 for (i = 0; i < len; i++) {
1040 if (VG_(strchr)(special, arg[i])) {
1041 umsg_or_xml("\\"); // escape with a backslash if necessary
1043 umsg_or_xml("%c", arg[i]);
1047 /* Ok, the logging sink is running now. Print a suitable preamble.
1048 If logging to file or a socket, write details of parent PID and
1049 command line args, to help people trying to interpret the
1050 results of a run which encompasses multiple processes. */
1051 static void print_preamble ( Bool logging_to_fd,
1052 Char* xml_fname_unexpanded,
1053 const HChar* toolname )
1056 HChar* xpre = VG_(clo_xml) ? " <line>" : "";
1057 HChar* xpost = VG_(clo_xml) ? "</line>" : "";
1058 UInt (*umsg_or_xml)( const HChar*, ... )
1059 = VG_(clo_xml) ? VG_(printf_xml) : VG_(umsg);
1061 vg_assert( VG_(args_for_client) );
1062 vg_assert( VG_(args_for_valgrind) );
1063 vg_assert( toolname );
1066 VG_(printf_xml)("<?xml version=\"1.0\"?>\n");
1067 VG_(printf_xml)("\n");
1068 VG_(printf_xml)("<valgrindoutput>\n");
1069 VG_(printf_xml)("\n");
1070 VG_(printf_xml)("<protocolversion>4</protocolversion>\n");
1071 VG_(printf_xml)("<protocoltool>%s</protocoltool>\n", toolname);
1072 VG_(printf_xml)("\n");
1075 if (VG_(clo_xml) || VG_(clo_verbosity > 0)) {
1078 VG_(printf_xml)("<preamble>\n");
1081 umsg_or_xml( VG_(clo_xml) ? "%s%t%t%t, %t%s\n" : "%s%s%s%s, %s%s\n",
1084 NULL == VG_(details).version ? "" : "-",
1085 NULL == VG_(details).version
1086 ? (Char*)"" : VG_(details).version,
1087 VG_(details).description,
1090 if (VG_(strlen)(toolname) >= 4 && VG_STREQN(4, toolname, "exp-")) {
1092 "%sNOTE: This is an Experimental-Class Valgrind Tool%s\n",
1097 umsg_or_xml( VG_(clo_xml) ? "%s%t%s\n" : "%s%s%s\n",
1098 xpre, VG_(details).copyright_author, xpost );
1102 "%sUsing Valgrind-%s and LibVEX; rerun with -h for copyright info%s\n",
1103 xpre, VERSION, xpost
1106 // Print the command line. At one point we wrapped at 80 chars and
1107 // printed a '\' as a line joiner, but that makes it hard to cut and
1108 // paste the command line (because of the "==pid==" prefixes), so we now
1109 // favour utility and simplicity over aesthetics.
1110 umsg_or_xml("%sCommand: ", xpre);
1111 if (VG_(args_the_exename))
1112 umsg_or_xml_arg(VG_(args_the_exename), umsg_or_xml);
1113 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1114 HChar* s = *(HChar**)VG_(indexXA)( VG_(args_for_client), i );
1116 umsg_or_xml_arg(s, umsg_or_xml);
1118 umsg_or_xml("%s\n", xpost);
1121 VG_(printf_xml)("</preamble>\n");
1124 // Print the parent PID, and other stuff, if necessary.
1125 if (!VG_(clo_xml) && VG_(clo_verbosity) > 0 && !logging_to_fd) {
1126 VG_(umsg)("Parent PID: %d\n", VG_(getppid)());
1130 VG_(printf_xml)("\n");
1131 VG_(printf_xml)("<pid>%d</pid>\n", VG_(getpid)());
1132 VG_(printf_xml)("<ppid>%d</ppid>\n", VG_(getppid)());
1133 VG_(printf_xml_no_f_c)("<tool>%t</tool>\n", toolname);
1134 if (xml_fname_unexpanded)
1135 print_file_vars(xml_fname_unexpanded);
1136 if (VG_(clo_xml_user_comment)) {
1137 /* Note: the user comment itself is XML and is therefore to
1138 be passed through verbatim (%s) rather than escaped
1140 VG_(printf_xml)("<usercomment>%s</usercomment>\n",
1141 VG_(clo_xml_user_comment));
1143 VG_(printf_xml)("\n");
1144 VG_(printf_xml)("<args>\n");
1146 VG_(printf_xml)(" <vargv>\n");
1147 if (VG_(name_of_launcher))
1148 VG_(printf_xml_no_f_c)(" <exe>%t</exe>\n",
1149 VG_(name_of_launcher));
1151 VG_(printf_xml_no_f_c)(" <exe>%t</exe>\n",
1152 "(launcher name unknown)");
1153 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
1154 VG_(printf_xml_no_f_c)(
1156 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1159 VG_(printf_xml)(" </vargv>\n");
1161 VG_(printf_xml)(" <argv>\n");
1162 if (VG_(args_the_exename))
1163 VG_(printf_xml_no_f_c)(" <exe>%t</exe>\n",
1164 VG_(args_the_exename));
1165 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1166 VG_(printf_xml_no_f_c)(
1168 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1171 VG_(printf_xml)(" </argv>\n");
1173 VG_(printf_xml)("</args>\n");
1176 // Last thing in the preamble is a blank line.
1178 VG_(printf_xml)("\n");
1179 else if (VG_(clo_verbosity) > 0)
1182 if (VG_(clo_verbosity) > 1) {
1185 VexArchInfo vex_archinfo;
1187 VG_(message)(Vg_DebugMsg, "\n");
1188 VG_(message)(Vg_DebugMsg, "Valgrind options:\n");
1189 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
1190 VG_(message)(Vg_DebugMsg,
1192 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ));
1195 VG_(message)(Vg_DebugMsg, "Contents of /proc/version:\n");
1196 fd = VG_(open) ( "/proc/version", VKI_O_RDONLY, 0 );
1197 if (sr_isError(fd)) {
1198 VG_(message)(Vg_DebugMsg, " can't open /proc/version\n");
1200 # define BUF_LEN 256
1201 Char version_buf[BUF_LEN];
1202 Int n = VG_(read) ( sr_Res(fd), version_buf, BUF_LEN );
1203 vg_assert(n <= BUF_LEN);
1205 version_buf[n-1] = '\0';
1206 VG_(message)(Vg_DebugMsg, " %s\n", version_buf);
1208 VG_(message)(Vg_DebugMsg, " (empty?)\n");
1210 VG_(close)(sr_Res(fd));
1214 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
1217 "Arch and hwcaps: %s, %s\n",
1218 LibVEX_ppVexArch ( vex_arch ),
1219 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1223 "Page sizes: currently %d, max supported %d\n",
1224 (Int)VKI_PAGE_SIZE, (Int)VKI_MAX_PAGE_SIZE
1226 VG_(message)(Vg_DebugMsg,
1227 "Valgrind library directory: %s\n", VG_(libdir));
1232 /*====================================================================*/
1233 /*=== File descriptor setup ===*/
1234 /*====================================================================*/
1236 /* Number of file descriptors that Valgrind tries to reserve for
1237 it's own use - just a small constant. */
1238 #define N_RESERVED_FDS (10)
1240 static void setup_file_descriptors(void)
1242 struct vki_rlimit rl;
1245 #if !defined(VGO_l4re)
1246 /* Get the current file descriptor limits. */
1247 if (VG_(getrlimit)(VKI_RLIMIT_NOFILE, &rl) < 0) {
1256 # if defined(VGO_darwin)
1257 /* Darwin lies. It reports file max as RLIM_INFINITY but
1258 silently disallows anything bigger than 10240. */
1259 if (rl.rlim_cur >= 10240 && rl.rlim_max == 0x7fffffffffffffffULL) {
1260 rl.rlim_max = 10240;
1265 VG_(printf)("fd limits: host, before: cur %lu max %lu\n",
1266 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
1268 # if defined(VGP_ppc32_aix5) || defined(VGP_ppc64_aix5)
1269 /* I don't know why this kludge is needed; however if rl.rlim_cur
1270 is RLIM_INFINITY, then VG_(safe_fd)'s attempts using VG_(fcntl)
1271 to lift V's file descriptors above the threshold RLIM_INFINITY -
1272 N_RESERVED_FDS fail. So just use a relatively conservative
1273 value in this case. */
1274 if (rl.rlim_cur > 1024)
1278 /* Work out where to move the soft limit to. */
1279 if (rl.rlim_cur + N_RESERVED_FDS <= rl.rlim_max) {
1280 rl.rlim_cur = rl.rlim_cur + N_RESERVED_FDS;
1282 rl.rlim_cur = rl.rlim_max;
1285 /* Reserve some file descriptors for our use. */
1286 VG_(fd_soft_limit) = rl.rlim_cur - N_RESERVED_FDS;
1287 VG_(fd_hard_limit) = rl.rlim_cur - N_RESERVED_FDS;
1289 #if !defined(VGO_l4re)
1290 /* Update the soft limit. */
1291 VG_(setrlimit)(VKI_RLIMIT_NOFILE, &rl);
1295 VG_(printf)("fd limits: host, after: cur %lu max %lu\n",
1296 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
1297 VG_(printf)("fd limits: guest : cur %u max %u\n",
1298 VG_(fd_soft_limit), VG_(fd_hard_limit));
1301 if (VG_(cl_exec_fd) != -1)
1302 VG_(cl_exec_fd) = VG_(safe_fd)( VG_(cl_exec_fd) );
1306 /*====================================================================*/
1307 /*=== BB profiling ===*/
1308 /*====================================================================*/
1311 void show_BB_profile ( BBProfEntry tops[], UInt n_tops, ULong score_total )
1313 ULong score_cumul, score_here;
1314 Char buf_cumul[10], buf_here[10];
1319 VG_(printf)("-----------------------------------------------------------\n");
1320 VG_(printf)("--- BEGIN BB Profile (summary of scores) ---\n");
1321 VG_(printf)("-----------------------------------------------------------\n");
1324 VG_(printf)("Total score = %lld\n\n", score_total);
1327 for (r = 0; r < n_tops; r++) {
1328 if (tops[r].addr == 0)
1331 VG_(get_fnname_w_offset)(tops[r].addr, name, 64);
1333 score_here = tops[r].score;
1334 score_cumul += score_here;
1335 VG_(percentify)(score_cumul, score_total, 2, 6, buf_cumul);
1336 VG_(percentify)(score_here, score_total, 2, 6, buf_here);
1337 VG_(printf)("%3d: (%9lld %s) %9lld %s 0x%llx %s\n",
1339 score_cumul, buf_cumul,
1340 score_here, buf_here, tops[r].addr, name );
1344 VG_(printf)("-----------------------------------------------------------\n");
1345 VG_(printf)("--- BB Profile (BB details) ---\n");
1346 VG_(printf)("-----------------------------------------------------------\n");
1350 for (r = 0; r < n_tops; r++) {
1351 if (tops[r].addr == 0)
1354 VG_(get_fnname_w_offset)(tops[r].addr, name, 64);
1356 score_here = tops[r].score;
1357 score_cumul += score_here;
1358 VG_(percentify)(score_cumul, score_total, 2, 6, buf_cumul);
1359 VG_(percentify)(score_here, score_total, 2, 6, buf_here);
1361 VG_(printf)("=-=-=-=-=-=-=-=-=-=-=-=-=-= begin BB rank %d "
1362 "=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n", r);
1363 VG_(printf)("%3d: (%9lld %s) %9lld %s 0x%llx %s\n",
1365 score_cumul, buf_cumul,
1366 score_here, buf_here, tops[r].addr, name );
1368 VG_(discard_translations)(tops[r].addr, 1, "bb profile");
1369 VG_(translate)(0, tops[r].addr, True, VG_(clo_profile_flags), 0, True);
1370 VG_(printf)("=-=-=-=-=-=-=-=-=-=-=-=-=-= end BB rank %d "
1371 "=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n", r);
1375 VG_(printf)("-----------------------------------------------------------\n");
1376 VG_(printf)("--- END BB Profile ---\n");
1377 VG_(printf)("-----------------------------------------------------------\n");
1382 /*====================================================================*/
1384 /*====================================================================*/
1386 /* When main() is entered, we should be on the following stack, not
1387 the one the kernel gave us. We will run on this stack until
1388 simulation of the root thread is started, at which point a transfer
1389 is made to a dynamically allocated stack. This is for the sake of
1390 uniform overflow detection for all Valgrind threads. This is
1391 marked global even though it isn't, because assembly code below
1392 needs to reference the name. */
1394 /*static*/ VgStack VG_(interim_stack);
1396 /* These are the structures used to hold info for creating the initial
1399 'iicii' mostly holds important register state present at system
1400 startup (_start_valgrind). valgrind_main() then fills in the rest
1401 of it and passes it to VG_(ii_create_image)(). That produces
1402 'iifii', which is later handed to VG_(ii_finalise_image). */
1404 /* In all OS-instantiations, the_iicii has a field .sp_at_startup.
1405 This should get some address inside the stack on which we gained
1406 control (eg, it could be the SP at startup). It doesn't matter
1407 exactly where in the stack it is. This value is passed to the
1408 address space manager at startup. On Linux, aspacem then uses it
1409 to identify the initial stack segment and hence the upper end of
1410 the usable address space. */
1412 static IICreateImageInfo the_iicii;
1413 static IIFinaliseImageInfo the_iifii;
1416 /* A simple pair structure, used for conveying debuginfo handles to
1417 calls to VG_TRACK(new_mem_startup, ...). */
1418 typedef struct { Addr a; ULong ull; } Addr_n_ULong;
1421 /* --- Forwards decls to do with shutdown --- */
1423 static void final_tidyup(ThreadId tid);
1425 /* Do everything which needs doing when the last thread exits */
1427 void shutdown_actions_NORETURN( ThreadId tid,
1428 VgSchedReturnCode tids_schedretcode );
1430 /* --- end of Forwards decls to do with shutdown --- */
1432 #if defined(VGO_l4re)
1434 static Int valgrind_main ( Int argc, HChar **argv, HChar **envp );
1435 Int _valgrind_main(Int argc, char** argv, char** envp);
1438 #define PATH_MAX 4096 /* POSIX refers to this a lot but I dunno
1439 where it is defined */
1440 int _valgrind_main(int argc, char** argv, char** envp)
1443 const char *toolname = VG_(toolname);
1444 const char *clientname = NULL;
1445 const char *platform;
1446 /* Start the debugging-log system ASAP. First find out how many
1447 "-d"s were specified. This is a pre-scan of the command line.
1448 At the same time, look for the tool name. */
1450 for (i = 1; i < argc; i++) {
1451 if (argv[i][0] != '-') {
1452 clientname = argv[i];
1455 if (0 == VG_(strcmp)(argv[i], "--")) {
1457 clientname = argv[i+1];
1460 if (0 == VG_(strcmp)(argv[i], "-d"))
1462 // in l4re tool are started directly - so parsing cmdline for
1463 // toolname is not necessary
1464 // if (0 == VG_(strncmp)(argv[i], "--tool=", 7))
1465 // toolname = argv[i] + 7;
1468 /* ... and start the debug logger. Now we can safely emit logging
1469 messages all through startup. */
1470 VG_(debugLog_startup)(loglevel, "Stage 1");
1471 VG_(debugLog)(1, "main", "VG main thread id: %lx\n", l4_debugger_global_id(l4re_env()->main_thread));
1474 /* Make sure we know which tool we're using */
1476 VG_(debugLog)(1, "launcher", "tool '%s' requested\n", toolname);
1479 VG_(debugLog)(1, "launcher",
1480 "no tool requested, defaulting to '%s'\n", toolname);
1483 platform = "x86-l4re";
1485 return valgrind_main(argc, argv, envp);
1489 /* By the time we get to valgrind_main, the_iicii should already have
1490 been filled in with any important details as required by whatever
1491 OS we have been built for.
1494 Int valgrind_main ( Int argc, HChar **argv, HChar **envp )
1496 HChar* toolname = "memcheck"; // default to Memcheck
1497 Int need_help = 0; // 0 = no, 1 = --help, 2 = --help-debug
1498 ThreadId tid_main = VG_INVALID_THREADID;
1499 Bool logging_to_fd = False;
1500 Char* xml_fname_unexpanded = NULL;
1502 struct vki_rlimit zero = { 0, 0 };
1503 XArray* addr2dihandle = NULL;
1504 #if defined(VGO_l4re)
1505 l4_utcb_tcr()->user[2] = 1; // thread id
1506 toolname = VG_(toolname);
1509 //============================================================
1511 // Nb: startup is complex. Prerequisites are shown at every step.
1512 // *** Be very careful when messing with the order ***
1514 // The first order of business is to get debug logging, the address
1515 // space manager and the dynamic memory manager up and running.
1516 // Once that's done, we can relax a bit.
1518 //============================================================
1520 /* This is needed to make VG_(getenv) usable early. */
1521 VG_(client_envp) = (Char**)envp;
1523 //--------------------------------------------------------------
1524 // Start up Mach kernel interface, if any
1526 //--------------------------------------------------------------
1527 # if defined(VGO_darwin)
1531 //--------------------------------------------------------------
1532 // Start up the logging mechanism
1534 //--------------------------------------------------------------
1535 /* Start the debugging-log system ASAP. First find out how many
1536 "-d"s were specified. This is a pre-scan of the command line. Also
1537 get --profile-heap=yes which is needed by the time we start up dynamic
1538 memory management. */
1540 for (i = 1; i < argc; i++) {
1541 if (argv[i][0] != '-') break;
1542 if VG_STREQ(argv[i], "--") break;
1543 if VG_STREQ(argv[i], "-d") loglevel++;
1544 if VG_BOOL_CLO(argv[i], "--profile-heap", VG_(clo_profile_heap)) {}
1547 /* ... and start the debug logger. Now we can safely emit logging
1548 messages all through startup. */
1549 VG_(debugLog_startup)(loglevel, "Stage 2 (main)");
1550 VG_(debugLog)(1, "main", "Welcome to Valgrind version "
1551 VERSION " debug logging\n");
1553 //--------------------------------------------------------------
1554 // AIX5 only: register the system call numbers
1556 // p: that the initial few syscall numbers stated in the
1557 // bootblock have been installed (else we can't
1558 // open/read/close).
1559 //--------------------------------------------------------------
1560 # if defined(VGO_aix5)
1561 VG_(debugLog)(1, "main", "aix5: registering syscalls ..\n");
1562 { UChar sysent_name[50];
1565 Int n_unregd, sysent_used = 0;
1566 prsysent_t* sysent_hdr;
1568 VG_(sprintf)(sysent_name, "/proc/%d/sysent", VG_(getpid)());
1569 fd = VG_(open)(sysent_name, VKI_O_RDONLY, 0);
1571 VG_(err_config_error)("aix5: can't open /proc/<pid>/sysent");
1573 sysent_used = VG_(read)(fd.res, aix5_sysent_buf, VG_AIX5_SYSENT_SIZE);
1574 if (sysent_used < 0)
1575 VG_(err_config_error)("aix5: error reading /proc/<pid>/sysent");
1576 if (sysent_used >= VG_AIX5_SYSENT_SIZE)
1577 VG_(err_config_error)("aix5: VG_AIX5_SYSENT_SIZE is too low; "
1578 "increase and recompile");
1581 vg_assert(sysent_used > 0 && sysent_used < VG_AIX5_SYSENT_SIZE);
1583 sysent_hdr = (prsysent_t*)&aix5_sysent_buf[0];
1586 for (i = 0; i < sysent_hdr->pr_nsyscalls; i++) {
1587 UChar* name = &aix5_sysent_buf[ sysent_hdr
1588 ->pr_syscall[i].pr_nameoff ];
1589 UInt nmbr = sysent_hdr->pr_syscall[i].pr_number;
1590 VG_(debugLog)(3, "main", "aix5: bind syscall %d to \"%s\"\n",
1592 ok = VG_(aix5_register_syscall)(nmbr, name);
1596 VG_(debugLog)(3, "main",
1597 "aix5: bind FAILED: %d to \"%s\"\n",
1600 VG_(debugLog)(1, "main", "aix5: .. %d syscalls known, %d unknown\n",
1601 sysent_hdr->pr_nsyscalls - n_unregd, n_unregd );
1602 VG_(debugLog)(1, "main", "aix5: __NR_AIX5_FAKE_SIGRETURN = %d\n",
1603 __NR_AIX5_FAKE_SIGRETURN );
1607 //--------------------------------------------------------------
1608 // Ensure we're on a plausible stack.
1610 //--------------------------------------------------------------
1611 VG_(debugLog)(1, "main", "Checking current stack is plausible\n");
1612 { HChar* limLo = (HChar*)(&VG_(interim_stack).bytes[0]);
1613 HChar* limHi = limLo + sizeof(VG_(interim_stack));
1614 HChar* aLocal = (HChar*)&zero; /* any auto local will do */
1615 if (aLocal < limLo || aLocal >= limHi) {
1616 /* something's wrong. Stop. */
1617 VG_(debugLog)(0, "main", "Root stack %p to %p, a local %p\n",
1618 limLo, limHi, aLocal );
1619 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1620 "Initial stack switched failed.\n");
1621 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1626 //--------------------------------------------------------------
1627 // Ensure we have a plausible pointer to the stack on which
1628 // we gained control (not the current stack!)
1630 //--------------------------------------------------------------
1631 VG_(debugLog)(1, "main", "Checking initial stack was noted\n");
1632 if (the_iicii.sp_at_startup == 0) {
1633 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1634 "Initial stack was not noted.\n");
1635 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1639 //--------------------------------------------------------------
1640 // Start up the address space manager, and determine the
1641 // approximate location of the client's stack
1642 // p: logging, plausible-stack
1643 //--------------------------------------------------------------
1644 VG_(debugLog)(1, "main", "Starting the address space manager\n");
1645 vg_assert(VKI_PAGE_SIZE == 4096 || VKI_PAGE_SIZE == 65536);
1646 vg_assert(VKI_MAX_PAGE_SIZE == 4096 || VKI_MAX_PAGE_SIZE == 65536);
1647 vg_assert(VKI_PAGE_SIZE <= VKI_MAX_PAGE_SIZE);
1648 vg_assert(VKI_PAGE_SIZE == (1 << VKI_PAGE_SHIFT));
1649 vg_assert(VKI_MAX_PAGE_SIZE == (1 << VKI_MAX_PAGE_SHIFT));
1650 the_iicii.clstack_top = VG_(am_startup)( the_iicii.sp_at_startup );
1651 VG_(debugLog)(1, "main", "Address space manager is running\n");
1653 //--------------------------------------------------------------
1654 // Start up the dynamic memory manager
1655 // p: address space management
1656 // p: getting --profile-heap
1657 // In fact m_mallocfree is self-initialising, so there's no
1658 // initialisation call to do. Instead, try a simple malloc/
1659 // free pair right now to check that nothing is broken.
1660 //--------------------------------------------------------------
1661 VG_(debugLog)(1, "main", "Starting the dynamic memory manager\n");
1662 { void* p = VG_(malloc)( "main.vm.1", 12345 );
1663 if (p) VG_(free)( p );
1665 VG_(debugLog)(1, "main", "Dynamic memory manager is running\n");
1667 #if defined(VGO_l4re)
1668 //--------------------------------------------------------------
1669 // Start the L4Re virtual region mapper, which interposes all
1670 // memory management and therefore makes sure that VG always
1671 // knows about which areas and regions in memory are mapped
1673 //--------------------------------------------------------------
1674 VG_(debugLog)(1, "main", "Starting L4Re VCap thread.\n");
1675 l4re_vcap_start_thread();
1677 //============================================================
1679 // Dynamic memory management is now available.
1681 //============================================================
1683 //--------------------------------------------------------------
1684 // Initialise m_debuginfo
1685 // p: dynamic memory allocation
1686 VG_(debugLog)(1, "main", "Initialise m_debuginfo\n");
1687 VG_(di_initialise)();
1689 //--------------------------------------------------------------
1690 // Look for alternative libdir
1691 { HChar *cp = VG_(getenv)(VALGRIND_LIB);
1694 VG_(debugLog)(1, "main", "VG_(libdir) = %s\n", VG_(libdir));
1697 //--------------------------------------------------------------
1698 // Since there is no implementation of exec in L4Re, we must start
1699 // the tools direcly.
1700 #if !defined(VGO_l4re)
1701 // Extract the launcher name from the environment.
1702 VG_(debugLog)(1, "main", "Getting launcher's name ...\n");
1703 VG_(name_of_launcher) = VG_(getenv)(VALGRIND_LAUNCHER);
1704 if (VG_(name_of_launcher) == NULL) {
1705 VG_(printf)("valgrind: You cannot run '%s' directly.\n", argv[0]);
1706 VG_(printf)("valgrind: You should use $prefix/bin/valgrind.\n");
1709 VG_(debugLog)(1, "main", "... %s\n", VG_(name_of_launcher));
1712 //--------------------------------------------------------------
1713 // L4Re doesn't support set/getrlimit()...
1714 #if !defined(VGO_l4re)
1715 // Get the current process datasize rlimit, and set it to zero.
1716 // This prevents any internal uses of brk() from having any effect.
1717 // We remember the old value so we can restore it on exec, so that
1718 // child processes will have a reasonable brk value.
1719 VG_(getrlimit)(VKI_RLIMIT_DATA, &VG_(client_rlimit_data));
1720 zero.rlim_max = VG_(client_rlimit_data).rlim_max;
1721 VG_(setrlimit)(VKI_RLIMIT_DATA, &zero);
1724 // Get the current process stack rlimit.
1725 #if defined(VGO_l4re)
1726 VG_(client_rlimit_stack).rlim_cur=8*1024*10424;
1727 VG_(client_rlimit_stack).rlim_max=64*1024*1024;
1728 // TODO move to header file
1730 VG_(getrlimit)(VKI_RLIMIT_STACK, &VG_(client_rlimit_stack));
1733 //--------------------------------------------------------------
1734 // Figure out what sort of CPU we're on, and whether it is
1736 VG_(debugLog)(1, "main", "Get hardware capabilities ...\n");
1738 VexArchInfo vex_archinfo;
1739 Bool ok = VG_(machine_get_hwcaps)();
1742 VG_(printf)("valgrind: fatal error: unsupported CPU.\n");
1743 VG_(printf)(" Supported CPUs are:\n");
1744 VG_(printf)(" * x86 (practically any; Pentium-I or above), "
1745 "AMD Athlon or above)\n");
1746 VG_(printf)(" * AMD Athlon64/Opteron\n");
1747 VG_(printf)(" * PowerPC (most; ppc405 and above)\n");
1748 VG_(printf)(" * System z (64bit only - s390x; z900 and above)\n");
1752 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
1754 1, "main", "... arch = %s, hwcaps = %s\n",
1755 LibVEX_ppVexArch ( vex_arch ),
1756 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1760 //--------------------------------------------------------------
1761 // Record the working directory at startup
1762 // p: none (Linux), getenv and sys_getpid work (AIX)
1763 VG_(debugLog)(1, "main", "Getting the working directory at startup\n");
1764 { Bool ok = VG_(record_startup_wd)();
1766 VG_(err_config_error)( "Can't establish current working "
1767 "directory at startup");
1769 { Char buf[VKI_PATH_MAX+1];
1770 Bool ok = VG_(get_startup_wd)( buf, sizeof(buf) );
1772 buf[VKI_PATH_MAX] = 0;
1773 VG_(debugLog)(1, "main", "... %s\n", buf );
1776 //============================================================
1777 // Command line argument handling order:
1778 // * If --help/--help-debug are present, show usage message
1779 // (including the tool-specific usage)
1780 // * (If no --tool option given, default to Memcheck)
1781 // * Then, if client is missing, abort with error msg
1782 // * Then, if any cmdline args are bad, abort with error msg
1783 //============================================================
1785 //--------------------------------------------------------------
1786 // Split up argv into: C args, V args, V extra args, and exename.
1787 // p: dynamic memory allocation
1788 //--------------------------------------------------------------
1789 VG_(debugLog)(1, "main", "Split up command line\n");
1790 VG_(split_up_argv)( argc, argv );
1791 vg_assert( VG_(args_for_valgrind) );
1792 vg_assert( VG_(args_for_client) );
1794 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++)
1797 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1799 VG_(printf)(" exe %s\n", VG_(args_the_exename));
1800 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++)
1803 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1807 # if defined(VGO_aix5)
1808 /* Tolerate ptraced-based launchers. They can't run 'no program'
1809 if the user types "valgrind --help", so they run a do-nothing
1810 program $prefix/bin/no_op_client_for_valgrind, and we catch that
1811 here and turn it the exe name back into NULL. Then --help,
1812 --version etc work as they should. */
1813 if (VG_(args_the_exename)
1814 && VG_(strstr)( VG_(args_the_exename), "/no_op_client_for_valgrind" )) {
1815 VG_(args_the_exename) = NULL;
1819 //--------------------------------------------------------------
1820 // Extract tool name and whether help has been requested.
1821 // Note we can't print the help message yet, even if requested,
1822 // because the tool has not been initialised.
1823 // p: split_up_argv [for VG_(args_for_valgrind)]
1824 //--------------------------------------------------------------
1825 VG_(debugLog)(1, "main",
1826 "(early_) Process Valgrind's command line options\n");
1827 early_process_cmd_line_options(&need_help, &toolname);
1829 // Set default vex control params
1830 LibVEX_default_VexControl(& VG_(clo_vex_control));
1832 //--------------------------------------------------------------
1833 // Load client executable, finding in $PATH if necessary
1834 // p: early_process_cmd_line_options() [for 'exec', 'need_help',
1835 // clo_max_stackframe,
1836 // clo_main_stacksize]
1837 // p: layout_remaining_space [so there's space]
1839 // Set up client's environment
1840 // p: set-libdir [for VG_(libdir)]
1841 // p: early_process_cmd_line_options [for toolname]
1843 // Setup client stack, eip, and VG_(client_arg[cv])
1844 // p: load_client() [for 'info']
1845 // p: fix_environment() [for 'env']
1847 // Setup client data (brk) segment. Initially a 1-page segment
1848 // which abuts a shrinkable reservation.
1849 // p: load_client() [for 'info' and hence VG_(brk_base)]
1851 // p: _start_in_C (for zeroing out the_iicii and putting some
1852 // initial values into it)
1853 //--------------------------------------------------------------
1855 VG_(debugLog)(1, "main", "Create initial image\n");
1857 # if defined(VGO_linux) || defined(VGO_darwin) || defined(VGO_l4re)
1858 the_iicii.argv = argv;
1859 the_iicii.envp = envp;
1860 the_iicii.toolname = toolname;
1861 # elif defined(VGO_aix5)
1862 /* the_iicii.intregs37 already set up */
1863 /* the_iicii.bootblock already set up */
1864 /* the_iicii.adler32_exp already set up */
1865 /* the_iicii.sp_at_startup is irrelevant */
1866 /* the_iicii.clstack_top is irrelevant */
1867 the_iicii.toolname = toolname;
1869 # error "Unknown platform"
1872 #if defined(VGO_l4re)
1873 // for clients to make systemcalls, they require access to the L4 KIP
1875 NSegment * seg = (NSegment *)VG_(am_find_nsegment)( (Addr) L4RE_KIP_ADDR );
1877 seg->kind = SkAnonC;
1881 NSegment * seg = (NSegment *)VG_(am_find_nsegment)( (Addr) L4RE_KERNEL_START );
1883 seg->kind = SkAnonC;
1887 /* NOTE: this call reads VG_(clo_main_stacksize). */
1888 the_iifii = VG_(ii_create_image)( the_iicii );
1890 # if defined(VGO_aix5)
1891 /* Tell aspacem where the initial client stack is, so that it
1892 can later produce a faked-up NSegment in response to
1893 VG_(am_find_nsegment) for that address range, if asked. */
1894 /* NOTE: this call reads VG_(clo_main_stacksize). */
1895 VG_(am_aix5_set_initial_client_sp)( the_iifii.initial_client_SP );
1896 /* Now have a look at said fake segment, so we can find out
1900 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
1902 sz = seg->end - seg->start + 1;
1903 vg_assert(sz >= 0 && sz <= (256+1)*1024*1024); /* stay sane */
1904 the_iifii.clstack_max_size = sz;
1909 //==============================================================
1911 // Finished loading/setting up the client address space.
1913 //==============================================================
1915 //--------------------------------------------------------------
1916 // setup file descriptors
1918 //--------------------------------------------------------------
1919 VG_(debugLog)(1, "main", "Setup file descriptors\n");
1920 setup_file_descriptors();
1922 //--------------------------------------------------------------
1923 // create the fake /proc/<pid>/cmdline file and then unlink it,
1924 // but hold onto the fd, so we can hand it out to the client
1925 // when it tries to open /proc/<pid>/cmdline for itself.
1926 // p: setup file descriptors
1927 //--------------------------------------------------------------
1928 #if !defined(VGO_linux)
1929 // client shouldn't be using /proc!
1930 VG_(cl_cmdline_fd) = -1;
1933 HChar buf[50], buf2[50+64];
1936 const HChar* exename;
1938 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/cmdline\n");
1940 VG_(sprintf)(buf, "proc_%d_cmdline", VG_(getpid)());
1941 fd = VG_(mkstemp)( buf, buf2 );
1943 VG_(err_config_error)("Can't create client cmdline file in /tmp.");
1946 exename = VG_(args_the_exename) ? VG_(args_the_exename)
1947 : "unknown_exename";
1948 VG_(write)(fd, exename, VG_(strlen)( exename ));
1949 VG_(write)(fd, nul, 1);
1951 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1952 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i );
1953 VG_(write)(fd, arg, VG_(strlen)( arg ));
1954 VG_(write)(fd, nul, 1);
1957 /* Don't bother to seek the file back to the start; instead do
1958 it every time a copy of it is given out (by PRE(sys_open)).
1959 That is probably more robust across fork() etc. */
1961 /* Now delete it, but hang on to the fd. */
1962 r = VG_(unlink)( buf2 );
1964 VG_(err_config_error)("Can't delete client cmdline file in /tmp.");
1966 VG_(cl_cmdline_fd) = fd;
1970 //--------------------------------------------------------------
1971 // Init tool part 1: pre_clo_init
1972 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1973 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1974 //--------------------------------------------------------------
1975 VG_(debugLog)(1, "main", "Initialise the tool part 1 (pre_clo_init)\n");
1976 VG_(tl_pre_clo_init)();
1978 //--------------------------------------------------------------
1979 // If --tool and --help/--help-debug was given, now give the core+tool
1981 // p: early_process_cmd_line_options() [for 'need_help']
1982 // p: tl_pre_clo_init [for 'VG_(tdict).usage']
1983 //--------------------------------------------------------------
1984 VG_(debugLog)(1, "main", "Print help and quit, if requested\n");
1986 usage_NORETURN(/*--help-debug?*/need_help >= 2);
1989 //--------------------------------------------------------------
1990 // Process command line options to Valgrind + tool
1991 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1992 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1993 //--------------------------------------------------------------
1994 VG_(debugLog)(1, "main",
1995 "(main_) Process Valgrind's command line options, "
1997 main_process_cmd_line_options ( &logging_to_fd, &xml_fname_unexpanded,
2000 //--------------------------------------------------------------
2001 // Zeroise the millisecond counter by doing a first read of it.
2003 //--------------------------------------------------------------
2004 (void) VG_(read_millisecond_timer)();
2006 //--------------------------------------------------------------
2007 // Print the preamble
2008 // p: tl_pre_clo_init [for 'VG_(details).name' and friends]
2009 // p: main_process_cmd_line_options()
2010 // [for VG_(clo_verbosity), VG_(clo_xml),
2011 // logging_to_fd, xml_fname_unexpanded]
2012 //--------------------------------------------------------------
2013 VG_(debugLog)(1, "main", "Print the preamble...\n");
2014 print_preamble(logging_to_fd, xml_fname_unexpanded, toolname);
2015 VG_(debugLog)(1, "main", "...finished the preamble\n");
2017 //--------------------------------------------------------------
2018 // Init tool part 2: post_clo_init
2019 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
2020 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
2021 // p: print_preamble() [so any warnings printed in post_clo_init
2022 // are shown after the preamble]
2023 //--------------------------------------------------------------
2024 VG_(debugLog)(1, "main", "Initialise the tool part 2 (post_clo_init)\n");
2025 VG_TDICT_CALL(tool_post_clo_init);
2027 /* The tool's "needs" will by now be finalised, since it has no
2028 further opportunity to specify them. So now sanity check
2032 ok = VG_(sanity_check_needs)( &s );
2038 //--------------------------------------------------------------
2039 // Initialise translation table and translation cache
2041 // p: tl_pre_clo_init [for 'VG_(details).avg_translation_sizeB']
2042 //--------------------------------------------------------------
2043 VG_(debugLog)(1, "main", "Initialise TT/TC\n");
2046 //--------------------------------------------------------------
2047 // Initialise the redirect table.
2048 // p: init_tt_tc [so it can call VG_(search_transtab) safely]
2049 // p: aspacem [so can change ownership of sysinfo pages]
2050 //--------------------------------------------------------------
2051 VG_(debugLog)(1, "main", "Initialise redirects\n");
2052 VG_(redir_initialise)();
2054 //--------------------------------------------------------------
2056 // p: main_process_cmd_line_options() [for VG_(clo_wait_for_gdb)]
2057 //--------------------------------------------------------------
2058 /* Hook to delay things long enough so we can get the pid and
2059 attach GDB in another shell. */
2060 if (VG_(clo_wait_for_gdb)) {
2063 VG_(debugLog)(1, "main", "Wait for GDB\n");
2064 VG_(printf)("pid=%d, entering delay loop\n", VG_(getpid)());
2066 # if defined(VGP_x86_linux) || defined(VGP_x86_l4re)
2068 # elif defined(VGP_amd64_linux) || defined(VGP_ppc64_linux)
2070 # elif defined(VGP_ppc32_linux)
2072 # elif defined(VGP_arm_linux)
2074 # elif defined(VGP_s390x_linux)
2076 # elif defined(VGP_ppc32_aix5) || defined(VGP_ppc64_aix5)
2078 # elif defined(VGO_darwin)
2081 # error "Unknown plat"
2084 iters *= 1000*1000*1000;
2085 for (q = 0; q < iters; q++)
2089 //--------------------------------------------------------------
2090 // Search for file descriptors that are inherited from our parent
2091 // p: main_process_cmd_line_options [for VG_(clo_track_fds)]
2092 //--------------------------------------------------------------
2093 if (VG_(clo_track_fds)) {
2094 VG_(debugLog)(1, "main", "Init preopened fds\n");
2095 VG_(init_preopened_fds)();
2098 //--------------------------------------------------------------
2099 // Load debug info for the existing segments.
2100 // p: setup_code_redirect_table [so that redirs can be recorded]
2102 // p: probably: setup fds and process CLOs, so that logging works
2103 // p: initialise m_debuginfo
2105 // While doing this, make a note of the debuginfo-handles that
2106 // come back from VG_(di_notify_mmap)/VG_(di_aix5_notify_segchange).
2107 // Later, in "Tell the tool about the initial client memory permissions"
2108 // (just below) we can then hand these handles off to the tool in
2109 // calls to VG_TRACK(new_mem_startup, ...). This gives the tool the
2110 // opportunity to make further queries to m_debuginfo before the
2111 // client is started, if it wants. We put this information into an
2112 // XArray, each handle along with the associated segment start address,
2113 // and search the XArray for the handles later, when calling
2114 // VG_TRACK(new_mem_startup, ...).
2115 //--------------------------------------------------------------
2116 VG_(debugLog)(1, "main", "Load initial debug info\n");
2118 tl_assert(!addr2dihandle);
2119 addr2dihandle = VG_(newXA)( VG_(malloc), "main.vm.2",
2120 VG_(free), sizeof(Addr_n_ULong) );
2121 tl_assert(addr2dihandle);
2123 # if defined(VGO_linux) || defined(VGO_l4re)
2128 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
2129 vg_assert(seg_starts && n_seg_starts >= 0);
2131 /* show them all to the debug info reader. allow_SkFileV has to
2132 be True here so that we read info from the valgrind executable
2134 for (i = 0; i < n_seg_starts; i++) {
2135 anu.ull = VG_(di_notify_mmap)( seg_starts[i], True/*allow_SkFileV*/ );
2136 /* anu.ull holds the debuginfo handle returned by di_notify_mmap,
2139 anu.a = seg_starts[i];
2140 VG_(addToXA)( addr2dihandle, &anu );
2144 VG_(free)( seg_starts );
2146 # elif defined(VGO_aix5)
2147 { AixCodeSegChange* changes;
2148 Int changes_size, changes_used;
2151 /* Find out how many AixCodeSegChange records we will need,
2152 and acquire them. */
2153 changes_size = VG_(am_aix5_reread_procmap_howmany_directives)();
2154 changes = VG_(malloc)("main.vm.3", changes_size * sizeof(AixCodeSegChange));
2157 /* Now re-read /proc/<pid>/map and acquire a change set */
2158 VG_(am_aix5_reread_procmap)( changes, &changes_used );
2159 vg_assert(changes_used >= 0 && changes_used <= changes_size);
2161 /* And notify m_debuginfo of the changes. */
2162 for (i = 0; i < changes_used; i++) {
2163 anu.ull = VG_(di_aix5_notify_segchange)(
2164 changes[i].code_start,
2165 changes[i].code_len,
2166 changes[i].data_start,
2167 changes[i].data_len,
2168 changes[i].file_name,
2169 changes[i].mem_name,
2170 changes[i].is_mainexe,
2174 tl_assert(changes[i].acquire);
2175 anu.a = changes[i].code_start; /* is this correct? */
2176 VG_(addToXA)( addr2dihandle, &anu );
2182 # elif defined(VGO_darwin)
2185 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
2186 vg_assert(seg_starts && n_seg_starts >= 0);
2188 /* show them all to the debug info reader.
2189 Don't read from V segments (unlike Linux) */
2190 // GrP fixme really?
2191 for (i = 0; i < n_seg_starts; i++)
2192 VG_(di_notify_mmap)( seg_starts[i], False/*don't allow_SkFileV*/ );
2194 VG_(free)( seg_starts );
2200 //--------------------------------------------------------------
2201 // Tell aspacem of ownership change of the asm helpers, so that
2202 // m_translate allows them to be translated. However, only do this
2203 // after the initial debug info read, since making a hole in the
2204 // address range for the stage2 binary confuses the debug info reader.
2206 //--------------------------------------------------------------
2207 { Bool change_ownership_v_c_OK;
2208 Addr co_start = VG_PGROUNDDN( (Addr)&VG_(trampoline_stuff_start) );
2209 Addr co_endPlus = VG_PGROUNDUP( (Addr)&VG_(trampoline_stuff_end) );
2210 VG_(debugLog)(1,"redir",
2211 "transfer ownership V -> C of 0x%llx .. 0x%llx\n",
2212 (ULong)co_start, (ULong)co_endPlus-1 );
2214 change_ownership_v_c_OK
2215 = VG_(am_change_ownership_v_to_c)( co_start, co_endPlus - co_start );
2216 vg_assert(change_ownership_v_c_OK);
2219 #if defined(VGO_l4re)
2220 { Bool change_ownership_v_c_OK;
2221 Addr co_start = VG_PGROUNDDN( (Addr)&VG_(l4re_trampoline_stuff_start) );
2222 Addr co_endPlus = VG_PGROUNDUP( (Addr)&VG_(l4re_trampoline_stuff_end) );
2223 VG_(debugLog)(1,"redir",
2224 "transfer ownership V -> C of 0x%llx .. 0x%llx (l4re_trampoline_stuff)\n",
2225 (ULong)co_start, (ULong)co_endPlus-1 );
2227 change_ownership_v_c_OK
2228 = VG_(am_change_ownership_v_to_c)( co_start, co_endPlus - co_start );
2229 vg_assert(change_ownership_v_c_OK);
2231 vrm_track_utcb_area();
2235 //--------------------------------------------------------------
2236 // Initialise the scheduler (phase 1) [generates tid_main]
2238 //--------------------------------------------------------------
2239 VG_(debugLog)(1, "main", "Initialise scheduler (phase 1)\n");
2240 tid_main = VG_(scheduler_init_phase1)();
2241 vg_assert(tid_main >= 0 && tid_main < VG_N_THREADS
2242 && tid_main != VG_INVALID_THREADID);
2243 /* Tell the tool about tid_main */
2244 VG_TRACK( pre_thread_ll_create, VG_INVALID_THREADID, tid_main );
2246 //--------------------------------------------------------------
2247 // Tell the tool about the initial client memory permissions
2250 // p: setup_client_stack
2251 // p: setup_client_dataseg
2253 // For each segment we tell the client about, look up in
2254 // addr2dihandle as created above, to see if there's a debuginfo
2255 // handle associated with the segment, that we can hand along
2256 // to the tool, to be helpful.
2257 //--------------------------------------------------------------
2258 VG_(debugLog)(1, "main", "Tell tool about initial permissions\n");
2262 tl_assert(addr2dihandle);
2264 /* Mark the main thread as running while we tell the tool about
2265 the client memory so that the tool can associate that memory
2266 with the main thread. */
2267 tl_assert(VG_(running_tid) == VG_INVALID_THREADID);
2268 VG_(running_tid) = tid_main;
2270 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
2271 vg_assert(seg_starts && n_seg_starts >= 0);
2273 /* show interesting ones to the tool */
2274 for (i = 0; i < n_seg_starts; i++) {
2277 = VG_(am_find_nsegment)( seg_starts[i] );
2279 if (seg->kind == SkFileC || seg->kind == SkAnonC) {
2280 /* This next assertion is tricky. If it is placed
2281 immediately before this 'if', it very occasionally fails.
2282 Why? Because previous iterations of the loop may have
2283 caused tools (via the new_mem_startup calls) to do
2284 dynamic memory allocation, and that may affect the mapped
2285 segments; in particular it may cause segment merging to
2286 happen. Hence we cannot assume that seg_starts[i], which
2287 reflects the state of the world before we started this
2288 loop, is the same as seg->start, as the latter reflects
2289 the state of the world (viz, mappings) at this particular
2290 iteration of the loop.
2292 Why does moving it inside the 'if' make it safe? Because
2293 any dynamic memory allocation done by the tools will
2294 affect only the state of Valgrind-owned segments, not of
2295 Client-owned segments. And the 'if' guards against that
2296 -- we only get in here for Client-owned segments.
2298 In other words: the loop may change the state of
2299 Valgrind-owned segments as it proceeds. But it should
2300 not cause the Client-owned segments to change. */
2301 vg_assert(seg->start == seg_starts[i]);
2302 VG_(debugLog)(2, "main",
2303 "tell tool about %010lx-%010lx %c%c%c\n",
2304 seg->start, seg->end,
2305 seg->hasR ? 'r' : '-',
2306 seg->hasW ? 'w' : '-',
2307 seg->hasX ? 'x' : '-' );
2308 /* search addr2dihandle to see if we have an entry
2309 matching seg->start. */
2310 n = VG_(sizeXA)( addr2dihandle );
2311 for (j = 0; j < n; j++) {
2312 Addr_n_ULong* anl = VG_(indexXA)( addr2dihandle, j );
2313 if (anl->a == seg->start) {
2314 tl_assert(anl->ull > 0); /* check it's a valid handle */
2318 vg_assert(j >= 0 && j <= n);
2319 VG_TRACK( new_mem_startup, seg->start, seg->end+1-seg->start,
2320 seg->hasR, seg->hasW, seg->hasX,
2321 /* and the retrieved debuginfo handle, if any */
2323 ? ((Addr_n_ULong*)VG_(indexXA)( addr2dihandle, j ))->ull
2328 VG_(free)( seg_starts );
2329 VG_(deleteXA)( addr2dihandle );
2331 /* Also do the initial stack permissions. */
2333 SSizeT inaccessible_len;
2335 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
2337 vg_assert(seg->kind == SkAnonC);
2338 vg_assert(the_iifii.initial_client_SP >= seg->start);
2339 vg_assert(the_iifii.initial_client_SP <= seg->end);
2340 # if defined(VGO_aix5)
2341 VG_(clstk_base) = seg->start;
2342 VG_(clstk_end) = seg->end;
2345 /* Stuff below the initial SP is unaddressable. Take into
2346 account any ABI-mandated space below the stack pointer that
2347 is required (VG_STACK_REDZONE_SZB). setup_client_stack()
2348 will have allocated an extra page if a red zone is required,
2349 to be on the safe side. */
2350 inaccessible_len = the_iifii.initial_client_SP - VG_STACK_REDZONE_SZB
2352 vg_assert(inaccessible_len >= 0);
2353 if (inaccessible_len > 0)
2354 VG_TRACK( die_mem_stack,
2357 VG_(debugLog)(2, "main", "mark stack inaccessible %010lx-%010lx\n",
2359 the_iifii.initial_client_SP-1 - VG_STACK_REDZONE_SZB);
2362 /* Also the assembly helpers. */
2363 VG_TRACK( new_mem_startup,
2364 (Addr)&VG_(trampoline_stuff_start),
2365 (Addr)&VG_(trampoline_stuff_end)
2366 - (Addr)&VG_(trampoline_stuff_start),
2367 False, /* readable? */
2368 False, /* writable? */
2369 True /* executable? */,
2370 0 /* di_handle: no associated debug info */ );
2372 /* Clear the running thread indicator */
2373 VG_(running_tid) = VG_INVALID_THREADID;
2374 tl_assert(VG_(running_tid) == VG_INVALID_THREADID);
2377 #if defined(VGO_l4re)
2378 VG_TRACK( new_mem_startup, (Addr) client_env, client_env_size, 1, 1, 1, 0 );
2380 //--------------------------------------------------------------
2381 // Initialise the scheduler (phase 2)
2382 // p: Initialise the scheduler (phase 1) [for tid_main]
2383 // p: setup_file_descriptors() [else VG_(safe_fd)() breaks]
2384 // p: setup_client_stack
2385 //--------------------------------------------------------------
2386 VG_(debugLog)(1, "main", "Initialise scheduler (phase 2)\n");
2387 { NSegment const* seg
2388 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
2390 vg_assert(seg->kind == SkAnonC);
2391 vg_assert(the_iifii.initial_client_SP >= seg->start);
2392 vg_assert(the_iifii.initial_client_SP <= seg->end);
2393 VG_(scheduler_init_phase2)( tid_main,
2394 seg->end, the_iifii.clstack_max_size );
2397 //--------------------------------------------------------------
2398 // Set up state for the root thread
2400 // setup_scheduler() [for sched-specific thread 1 stuff]
2401 // VG_(ii_create_image) [for 'the_iicii' initial info]
2402 //--------------------------------------------------------------
2403 VG_(debugLog)(1, "main", "Finalise initial image\n");
2404 VG_(ii_finalise_image)( the_iifii );
2406 //--------------------------------------------------------------
2407 // Initialise the signal handling subsystem
2409 //--------------------------------------------------------------
2410 // NO signals on L4Re
2411 #if !defined(VGO_l4re)
2412 // Nb: temporarily parks the saved blocking-mask in saved_sigmask.
2413 VG_(debugLog)(1, "main", "Initialise signal management\n");
2414 /* Check that the kernel-interface signal definitions look sane */
2415 VG_(vki_do_initial_consistency_checks)();
2416 /* .. and go on to use them. */
2417 VG_(sigstartup_actions)();
2420 //--------------------------------------------------------------
2421 // Read suppression file
2422 // p: main_process_cmd_line_options() [for VG_(clo_suppressions)]
2423 //--------------------------------------------------------------
2424 if (VG_(needs).core_errors || VG_(needs).tool_errors) {
2425 VG_(debugLog)(1, "main", "Load suppressions\n");
2426 VG_(load_suppressions)();
2429 //--------------------------------------------------------------
2430 // register client stack
2431 //--------------------------------------------------------------
2432 VG_(clstk_id) = VG_(register_stack)(VG_(clstk_base), VG_(clstk_end));
2434 //--------------------------------------------------------------
2435 // Show the address space state so far
2436 //--------------------------------------------------------------
2437 VG_(debugLog)(1, "main", "\n");
2438 VG_(debugLog)(1, "main", "\n");
2439 VG_(am_show_nsegments)(1,"Memory layout at client startup");
2440 VG_(debugLog)(1, "main", "\n");
2441 VG_(debugLog)(1, "main", "\n");
2443 //--------------------------------------------------------------
2445 //--------------------------------------------------------------
2448 VG_(elapsed_wallclock_time)(buf);
2449 VG_(printf_xml_no_f_c)( "<status>\n"
2450 " <state>RUNNING</state>\n"
2451 " <time>%t</time>\n"
2454 VG_(printf_xml_no_f_c)( "\n" );
2457 VG_(debugLog)(1, "main", "Running thread 1\n");
2459 /* As a result of the following call, the last thread standing
2460 eventually winds up running shutdown_actions_NORETURN
2461 just below. Unfortunately, simply exporting said function
2462 causes m_main to be part of a module cycle, which is pretty
2463 nonsensical. So instead of doing that, the address of said
2464 function is stored in a global variable 'owned' by m_syswrap,
2465 and it uses that function pointer to get back here when it needs
2468 /* Set continuation address. */
2469 VG_(address_of_m_main_shutdown_actions_NORETURN)
2470 = & shutdown_actions_NORETURN;
2472 /* Run the first thread, eventually ending up at the continuation
2474 VG_(main_thread_wrapper_NORETURN)(1);
2480 /* Do everything which needs doing when the last thread exits or when
2481 a thread exits requesting a complete process exit (exit on AIX).
2483 We enter here holding The Lock. For the case VgSrc_ExitProcess we
2484 must never release it, because to do so would allow other threads
2485 to continue after the system is ostensibly shut down. So we must
2486 go to our grave, so to speak, holding the lock.
2488 In fact, there is never any point in releasing the lock at this
2489 point - we have it, we're shutting down the entire system, and
2490 for the case VgSrc_ExitProcess doing so positively causes trouble.
2493 The final_tidyup call makes a bit of a nonsense of the ExitProcess
2494 case, since it will run the libc_freeres function, thus allowing
2495 other lurking threads to run again. Hmm. */
2498 void shutdown_actions_NORETURN( ThreadId tid,
2499 VgSchedReturnCode tids_schedretcode )
2501 VG_(debugLog)(1, "main", "entering VG_(shutdown_actions_NORETURN)\n");
2502 VG_(am_show_nsegments)(1,"Memory layout at client shutdown");
2504 vg_assert(VG_(is_running_thread)(tid));
2506 vg_assert(tids_schedretcode == VgSrc_ExitThread
2507 || tids_schedretcode == VgSrc_ExitProcess
2508 || tids_schedretcode == VgSrc_FatalSig );
2510 if (tids_schedretcode == VgSrc_ExitThread) {
2512 // We are the last surviving thread. Right?
2513 vg_assert( VG_(count_living_threads)() == 1 );
2515 // Wait for all other threads to exit.
2516 // jrs: Huh? but they surely are already gone
2517 VG_(reap_threads)(tid);
2519 // Clean the client up before the final report
2520 // this causes the libc_freeres function to run
2524 vg_assert(VG_(is_running_thread)(tid));
2525 vg_assert(VG_(count_living_threads)() == 1);
2529 // We may not be the last surviving thread. However, we
2530 // want to shut down the entire process. We hold the lock
2531 // and we need to keep hold of it all the way out, in order
2532 // that none of the other threads ever run again.
2533 vg_assert( VG_(count_living_threads)() >= 1 );
2535 // Clean the client up before the final report
2536 // this causes the libc_freeres function to run
2537 // perhaps this is unsafe, as per comment above
2541 vg_assert(VG_(is_running_thread)(tid));
2542 vg_assert(VG_(count_living_threads)() >= 1);
2545 VG_(threads)[tid].status = VgTs_Empty;
2546 //--------------------------------------------------------------
2547 // Finalisation: cleanup, messages, etc. Order not so important, only
2548 // affects what order the messages come.
2549 //--------------------------------------------------------------
2550 // First thing in the post-amble is a blank line.
2552 VG_(printf_xml)("\n");
2553 else if (VG_(clo_verbosity) > 0)
2554 VG_(message)(Vg_UserMsg, "\n");
2558 VG_(elapsed_wallclock_time)(buf);
2559 VG_(printf_xml_no_f_c)( "<status>\n"
2560 " <state>FINISHED</state>\n"
2561 " <time>%t</time>\n"
2567 /* Print out file descriptor summary and stats. */
2568 if (VG_(clo_track_fds))
2569 VG_(show_open_fds)();
2571 /* Call the tool's finalisation function. This makes Memcheck's
2572 leak checker run, and possibly chuck a bunch of leak errors into
2573 the error management machinery. */
2574 VG_TDICT_CALL(tool_fini, 0/*exitcode*/);
2576 /* Show the error counts. */
2578 && (VG_(needs).core_errors || VG_(needs).tool_errors)) {
2579 VG_(show_error_counts_as_XML)();
2582 /* In XML mode, this merely prints the used suppressions. */
2583 if (VG_(needs).core_errors || VG_(needs).tool_errors)
2584 VG_(show_all_errors)(VG_(clo_verbosity), VG_(clo_xml));
2587 VG_(printf_xml)("\n");
2588 VG_(printf_xml)("</valgrindoutput>\n");
2589 VG_(printf_xml)("\n");
2592 VG_(sanity_check_general)( True /*include expensive checks*/ );
2597 /* Show a profile of the heap(s) at shutdown. Optionally, first
2598 throw away all the debug info, as that makes it easy to spot
2599 leaks in the debuginfo reader. */
2600 if (VG_(clo_profile_heap)) {
2601 if (0) VG_(di_discard_ALL_debuginfo)();
2602 VG_(print_arena_cc_analysis)();
2605 if (VG_(clo_profile_flags) > 0) {
2607 BBProfEntry tops[N_MAX];
2608 ULong score_total = VG_(get_BB_profile) (tops, N_MAX);
2609 show_BB_profile(tops, N_MAX, score_total);
2612 /* Print Vex storage stats */
2614 LibVEX_ShowAllocStats();
2616 /* Flush any output cached by previous calls to VG_(message). */
2617 VG_(message_flush)();
2619 /* terminate gdbserver if ever it was started. We terminate it here so that it get
2620 the output above if output was redirected to gdb */
2623 /* Ok, finally exit in the os-specific way, according to the scheduler's
2624 return code. In short, if the (last) thread exited by calling
2625 sys_exit, do likewise; if the (last) thread stopped due to a fatal
2626 signal, terminate the entire system with that same fatal signal. */
2627 VG_(debugLog)(1, "core_os",
2628 "VG_(terminate_NORETURN)(tid=%lld)\n", (ULong)tid);
2630 switch (tids_schedretcode) {
2631 case VgSrc_ExitThread: /* the normal way out (Linux) */
2632 case VgSrc_ExitProcess: /* the normal way out (AIX) */
2633 /* Change the application return code to user's return code,
2634 if an error was found */
2635 if (VG_(clo_error_exitcode) > 0
2636 && VG_(get_n_errs_found)() > 0) {
2637 VG_(exit)( VG_(clo_error_exitcode) );
2639 /* otherwise, return the client's exit code, in the normal
2641 VG_(exit)( VG_(threads)[tid].os_state.exitcode );
2643 /* NOT ALIVE HERE! */
2644 VG_(core_panic)("entered the afterlife in main() -- ExitT/P");
2645 break; /* what the hell :) */
2647 case VgSrc_FatalSig:
2648 /* We were killed by a fatal signal, so replicate the effect */
2649 vg_assert(VG_(threads)[tid].os_state.fatalsig != 0);
2650 VG_(kill_self)(VG_(threads)[tid].os_state.fatalsig);
2651 /* we shouldn't be alive at this point. But VG_(kill_self)
2652 sometimes fails with EPERM on Darwin, for unclear reasons. */
2653 # if defined(VGO_darwin)
2654 VG_(debugLog)(0, "main", "VG_(kill_self) failed. Exiting normally.\n");
2655 VG_(exit)(0); /* bogus, but we really need to exit now */
2656 /* fall through .. */
2658 VG_(core_panic)("main(): signal was supposed to be fatal");
2662 VG_(core_panic)("main(): unexpected scheduler return code");
2666 /* -------------------- */
2668 /* Final clean-up before terminating the process.
2669 Clean up the client by calling __libc_freeres() (if requested)
2670 This is Linux-specific?
2671 GrP fixme glibc-specific, anyway
2673 static void final_tidyup(ThreadId tid)
2675 #if !defined(VGO_darwin) && !defined(VGO_l4re)
2676 # if defined(VGP_ppc64_linux)
2679 Addr __libc_freeres_wrapper = VG_(client___libc_freeres_wrapper);
2681 vg_assert(VG_(is_running_thread)(tid));
2683 if ( !VG_(needs).libc_freeres ||
2684 !VG_(clo_run_libc_freeres) ||
2685 0 == __libc_freeres_wrapper )
2686 return; /* can't/won't do it */
2687 # if defined(VGO_aix5)
2688 return; /* inapplicable on non-Linux platforms */
2691 # if defined(VGP_ppc64_linux)
2692 r2 = VG_(get_tocptr)( __libc_freeres_wrapper );
2694 VG_(message)(Vg_UserMsg,
2695 "Caught __NR_exit, but can't run __libc_freeres()\n");
2696 VG_(message)(Vg_UserMsg,
2697 " since cannot establish TOC pointer for it.\n");
2702 if (VG_(clo_verbosity) > 2 ||
2703 VG_(clo_trace_syscalls) ||
2704 VG_(clo_trace_sched))
2705 VG_(message)(Vg_DebugMsg,
2706 "Caught __NR_exit; running __libc_freeres()\n");
2708 /* set thread context to point to libc_freeres_wrapper */
2709 /* ppc64-linux note: __libc_freeres_wrapper gives us the real
2710 function entry point, not a fn descriptor, so can use it
2711 directly. However, we need to set R2 (the toc pointer)
2713 VG_(set_IP)(tid, __libc_freeres_wrapper);
2714 # if defined(VGP_ppc64_linux)
2715 VG_(threads)[tid].arch.vex.guest_GPR2 = r2;
2718 /* Block all blockable signals by copying the real block state into
2719 the thread's block state*/
2720 VG_(sigprocmask)(VKI_SIG_BLOCK, NULL, &VG_(threads)[tid].sig_mask);
2721 VG_(threads)[tid].tmp_sig_mask = VG_(threads)[tid].sig_mask;
2723 /* and restore handlers to default */
2724 VG_(set_default_handler)(VKI_SIGSEGV);
2725 VG_(set_default_handler)(VKI_SIGBUS);
2726 VG_(set_default_handler)(VKI_SIGILL);
2727 VG_(set_default_handler)(VKI_SIGFPE);
2729 // We were exiting, so assert that...
2730 vg_assert(VG_(is_exiting)(tid));
2731 // ...but now we're not again
2732 VG_(threads)[tid].exitreason = VgSrc_None;
2734 // run until client thread exits - ideally with LIBC_FREERES_DONE,
2735 // but exit/exitgroup/signal will do
2736 VG_(scheduler)(tid);
2738 vg_assert(VG_(is_exiting)(tid));
2743 /*====================================================================*/
2744 /*=== Getting to main() alive: LINUX ===*/
2745 /*====================================================================*/
2747 #if defined(VGO_linux)
2749 /* If linking of the final executables is done with glibc present,
2750 then Valgrind starts at main() above as usual, and all of the
2751 following code is irrelevant.
2753 However, this is not the intended mode of use. The plan is to
2754 avoid linking against glibc, by giving gcc the flags
2755 -nodefaultlibs -lgcc -nostartfiles at startup.
2757 From this derive two requirements:
2759 1. gcc may emit calls to memcpy and memset to deal with structure
2760 assignments etc. Since we have chosen to ignore all the
2761 "normal" supporting libraries, we have to provide our own
2762 implementations of them. No problem.
2764 2. We have to provide a symbol "_start", to which the kernel
2765 hands control at startup. Hence the code below.
2768 /* ---------------- Requirement 1 ---------------- */
2770 void* memcpy(void *dest, const void *src, SizeT n);
2771 void* memcpy(void *dest, const void *src, SizeT n) {
2772 return VG_(memcpy)(dest,src,n);
2774 void* memset(void *s, int c, SizeT n);
2775 void* memset(void *s, int c, SizeT n) {
2776 return VG_(memset)(s,c,n);
2779 /* BVA: abort() for those platforms that need it (PPC and ARM). */
2782 VG_(printf)("Something called raise().\n");
2786 /* EAZG: ARM's EABI will call floating point exception handlers in
2787 libgcc which boil down to an abort or raise, that's usually defined
2788 in libc. Instead, define them here. */
2789 #if defined(VGP_arm_linux)
2792 VG_(printf)("Something called raise().\n");
2796 void __aeabi_unwind_cpp_pr0(void);
2797 void __aeabi_unwind_cpp_pr0(void){
2798 VG_(printf)("Something called __aeabi_unwind_cpp_pr0()\n");
2802 void __aeabi_unwind_cpp_pr1(void);
2803 void __aeabi_unwind_cpp_pr1(void){
2804 VG_(printf)("Something called __aeabi_unwind_cpp_pr1()\n");
2809 /* ---------------- Requirement 2 ---------------- */
2811 /* Glibc's sysdeps/i386/elf/start.S has the following gem of a
2812 comment, which explains how the stack looks right at process start
2813 (when _start is jumped to). Hence _start passes %esp to
2814 _start_in_C_linux, which extracts argc/argv/envp and starts up
2817 /* This is the canonical entry point, usually the first thing in the text
2818 segment. The SVR4/i386 ABI (pages 3-31, 3-32) says that when the entry
2819 point runs, most registers' values are unspecified, except for:
2821 %edx Contains a function pointer to be registered with `atexit'.
2822 This is how the dynamic linker arranges to have DT_FINI
2823 functions called for shared libraries that have been loaded
2824 before this code runs.
2826 %esp The stack contains the arguments and environment:
2831 (4*(argc+1))(%esp) envp[0]
2836 /* The kernel hands control to _start, which extracts the initial
2837 stack pointer and calls onwards to _start_in_C_linux. This also switches
2839 #if defined(VGP_x86_linux)
2843 "\t.type _start,@function\n"
2845 /* set up the new stack in %eax */
2846 "\tmovl $vgPlain_interim_stack, %eax\n"
2847 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
2848 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
2849 "\tsubl $16, %eax\n"
2850 "\tandl $~15, %eax\n"
2851 /* install it, and collect the original one */
2852 "\txchgl %eax, %esp\n"
2853 /* call _start_in_C_linux, passing it the startup %esp */
2855 "\tcall _start_in_C_linux\n"
2859 #elif defined(VGP_amd64_linux)
2863 "\t.type _start,@function\n"
2865 /* set up the new stack in %rdi */
2866 "\tmovq $vgPlain_interim_stack, %rdi\n"
2867 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
2868 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
2869 "\tandq $~15, %rdi\n"
2870 /* install it, and collect the original one */
2871 "\txchgq %rdi, %rsp\n"
2872 /* call _start_in_C_linux, passing it the startup %rsp */
2873 "\tcall _start_in_C_linux\n"
2877 #elif defined(VGP_ppc32_linux)
2881 "\t.type _start,@function\n"
2883 /* set up the new stack in r16 */
2884 "\tlis 16,vgPlain_interim_stack@ha\n"
2885 "\tla 16,vgPlain_interim_stack@l(16)\n"
2886 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2887 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2888 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2889 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2892 "\trlwinm 16,16,0,0,27\n"
2893 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2894 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2895 boundary. And r1 is the original SP. Set the SP to r16 and
2896 call _start_in_C_linux, passing it the initial SP. */
2899 "\tbl _start_in_C_linux\n"
2903 #elif defined(VGP_ppc64_linux)
2905 /* PPC64 ELF ABI says '_start' points to a function descriptor.
2906 So we must have one, and that is what goes into the .opd section. */
2908 "\t.global _start\n"
2909 "\t.section \".opd\",\"aw\"\n"
2912 "\t.quad ._start,.TOC.@tocbase,0\n"
2914 "\t.type ._start,@function\n"
2915 "\t.global ._start\n"
2917 /* set up the new stack in r16 */
2918 "\tlis 16, vgPlain_interim_stack@highest\n"
2919 "\tori 16,16,vgPlain_interim_stack@higher\n"
2921 "\toris 16,16,vgPlain_interim_stack@h\n"
2922 "\tori 16,16,vgPlain_interim_stack@l\n"
2924 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2925 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2927 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2928 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2931 "\trldicr 16,16,0,59\n"
2932 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2933 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2934 boundary. And r1 is the original SP. Set the SP to r16 and
2935 call _start_in_C_linux, passing it the initial SP. */
2938 "\tbl ._start_in_C_linux\n"
2942 #elif defined(VGP_s390x_linux)
2944 This is the canonical entry point, usually the first thing in the text
2945 segment. Most registers' values are unspecified, except for:
2947 %r14 Contains a function pointer to be registered with `atexit'.
2948 This is how the dynamic linker arranges to have DT_FINI
2949 functions called for shared libraries that have been loaded
2950 before this code runs.
2952 %r15 The stack contains the arguments and environment:
2957 (8*(argc+1))(%r15) envp[0]
2964 ".type _start,@function\n\t"
2966 /* set up the new stack in %r1 */
2967 "larl %r1, vgPlain_interim_stack\n\t"
2969 "ag %r1, 0(%r5)\n\t"
2970 "ag %r1, 2f-1f(%r5)\n\t"
2971 "nill %r1, 0xFFF0\n\t"
2972 /* install it, and collect the original one */
2975 /* call _start_in_C_linux, passing it the startup %r15 */
2976 "brasl %r14, _start_in_C_linux\n\t"
2977 /* trigger execution of an invalid opcode -> halt machine */
2979 "1: .quad "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n\t"
2980 "2: .quad "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n\t"
2983 #elif defined(VGP_arm_linux)
2987 "\t.type _start,#function\n"
2988 "\t.global _start\n"
2990 "\tldr r0, [pc, #36]\n"
2991 "\tldr r1, [pc, #36]\n"
2992 "\tadd r0, r1, r0\n"
2993 "\tldr r1, [pc, #32]\n"
2994 "\tadd r0, r1, r0\n"
2996 "\tand r0, r0, r1\n"
3000 "\tb _start_in_C_linux\n"
3001 "\t.word vgPlain_interim_stack\n"
3002 "\t.word "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
3003 "\t.word "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
3006 # error "Unknown linux platform"
3009 /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
3011 #define _FILE_OFFSET_BITS 64
3012 /* This is in order to get AT_NULL and AT_PAGESIZE. */
3014 /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
3016 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3017 'static' causes gcc to complain it isn't. */
3018 void _start_in_C_linux ( UWord* pArgc );
3019 void _start_in_C_linux ( UWord* pArgc )
3022 Word argc = pArgc[0];
3023 HChar** argv = (HChar**)&pArgc[1];
3024 HChar** envp = (HChar**)&pArgc[1+argc+1];
3026 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3027 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3029 the_iicii.sp_at_startup = (Addr)pArgc;
3031 # if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux)
3033 /* ppc/ppc64 can be configured with different page sizes.
3034 Determine this early. This is an ugly hack and really should
3035 be moved into valgrind_main. */
3036 UWord *sp = &pArgc[1+argc+1];
3039 for (; *sp != AT_NULL && *sp != AT_PAGESZ; sp += 2);
3040 if (*sp == AT_PAGESZ) {
3041 VKI_PAGE_SIZE = sp[1];
3042 for (VKI_PAGE_SHIFT = 12;
3043 VKI_PAGE_SHIFT <= VKI_MAX_PAGE_SHIFT; VKI_PAGE_SHIFT++)
3044 if (VKI_PAGE_SIZE == (1UL << VKI_PAGE_SHIFT))
3050 r = valgrind_main( (Int)argc, argv, envp );
3056 /*====================================================================*/
3057 /*=== Getting to main() alive: AIX5 ===*/
3058 /*====================================================================*/
3060 #elif defined(VGO_aix5)
3062 /* This is somewhat simpler than the Linux case. _start_valgrind
3063 receives control from the magic piece of code created in this
3064 process' address space by the launcher, via use of ptrace(). At
3067 - the initial client process image is in memory and ready to roll,
3068 except that we've partially trashed its integer register state
3069 in order to get this far. So ..
3071 - intregs37 holds the client's initial integer register state, so
3072 we can restore it before starting the client on the VCPU.
3074 - we're on the client's stack. This is not good; therefore the
3075 first order of business is to switch to our temporary stack.
3077 - the client's initial argc/v/envp is in r3/r4/r5 (32 bit mode) or
3078 r14/r15/r16 (64 bit mode). They are pulled out of the stashed
3079 integer register state and passed to our main().
3081 The launcher will have played some games with argv. If the launcher
3082 ($prefix/bin/valgrind) was started like this
3084 valgrind [args-for-V] app [args-for-app]
3086 then the launcher will have started the client as
3088 app [args-for-V] app [args-for-app]
3090 m_initimg will have to mess with the client's initial r4/r5
3091 (32-bit) or r15/r16 (64-bit) so that it believes it was execd as
3092 "app [args-for-app]". Well, that's no big deal.
3095 #include "launcher-aix5-bootblock.h"
3097 void _start_in_C_aix5 ( AIX5Bootblock* bootblock );
3098 void _start_in_C_aix5 ( AIX5Bootblock* bootblock )
3102 UWord argc, argv, envp;
3103 __NR_getpid = bootblock->__NR_getpid;
3104 __NR_write = bootblock->__NR_write;
3105 __NR_exit = bootblock->__NR_exit;
3106 __NR_open = bootblock->__NR_open;
3107 __NR_read = bootblock->__NR_read;
3108 __NR_close = bootblock->__NR_close;
3110 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3111 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3113 intregs37 = &bootblock->iregs_pc_cr_lr_ctr_xer[0];
3114 the_iicii.intregs37 = intregs37;
3115 the_iicii.bootblock = (void*)bootblock;
3116 the_iicii.adler32_exp = bootblock->adler32;
3118 /* Not important on AIX. */
3119 the_iicii.sp_at_startup = (Addr)0x31415927ULL;
3121 # if defined(VGP_ppc32_aix5)
3122 argc = (UWord)intregs37[3]; /* client's r3 == argc */
3123 argv = (UWord)intregs37[4];
3124 envp = (UWord)intregs37[5];
3125 # else /* defined(VGP_ppc64_aix5) */
3126 argc = (UWord)intregs37[14]; /* client's r14 == argc */
3127 argv = (UWord)intregs37[15];
3128 envp = (UWord)intregs37[16];
3131 r = valgrind_main( (Int)argc, (HChar**)argv, (HChar**)envp );
3137 /* THE ENTRY POINT */
3138 void _start_valgrind ( AIX5Bootblock* bootblock );
3139 void _start_valgrind ( AIX5Bootblock* bootblock )
3141 /* Switch immediately to our temporary stack, and continue. This
3142 is pretty dodgy in that it assumes that gcc does not place on
3143 the stack, anything needed to form the _start_in_C_aix5 call,
3144 since it will be on the old stack. */
3145 register UWord new_r1;
3146 new_r1 = (UWord)&VG_(interim_stack);
3147 new_r1 += VG_STACK_GUARD_SZB; /* step over lower guard page */
3148 new_r1 += VG_STACK_ACTIVE_SZB; /* step to top of active area */
3149 new_r1 -= 512; /* paranoia */
3150 __asm__ __volatile__("mr 1,%0" :/*wr*/
3152 :/*trash*/"r1","memory");
3153 _start_in_C_aix5(bootblock);
3158 /* At some point in Oct 2008, static linking appeared to stop working
3159 on AIX 5.3. This breaks the build since we link statically. The
3160 linking fails citing absence of the following five symbols as the
3161 reason. In the absence of a better solution, here are stand-ins
3162 for them. Kludge appears to work; presumably said functions,
3163 assuming they are indeed functions, are never called. */
3164 void encrypted_pw_passlen ( void ) { vg_assert(0); }
3165 void crypt_r ( void ) { vg_assert(0); }
3166 void max_history_size ( void ) { vg_assert(0); }
3167 void getpass_auto ( void ) { vg_assert(0); }
3168 void max_pw_passlen ( void ) { vg_assert(0); }
3171 /*====================================================================*/
3172 /*=== Getting to main() alive: darwin ===*/
3173 /*====================================================================*/
3175 #elif defined(VGO_darwin)
3178 Memory layout established by kernel:
3189 executable name (presumably, a pointer to it)
3192 Ditto in the 64-bit case, except all offsets from SP are obviously
3196 /* The kernel hands control to _start, which extracts the initial
3197 stack pointer and calls onwards to _start_in_C_darwin. This also
3198 switches to the new stack. */
3199 #if defined(VGP_x86_darwin)
3203 "\t.globl __start\n"
3205 /* set up the new stack in %eax */
3206 "\tmovl $_vgPlain_interim_stack, %eax\n"
3207 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
3208 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
3209 "\tsubl $16, %eax\n"
3210 "\tandl $~15, %eax\n"
3211 /* install it, and collect the original one */
3212 "\txchgl %eax, %esp\n"
3213 /* call _start_in_C_darwin, passing it the startup %esp */
3215 "\tcall __start_in_C_darwin\n"
3219 #elif defined(VGP_amd64_darwin)
3222 "\t.globl __start\n"
3225 /* set up the new stack in %rdi */
3226 "\tmovabsq $_vgPlain_interim_stack, %rdi\n"
3227 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
3228 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
3229 "\tandq $~15, %rdi\n"
3230 /* install it, and collect the original one */
3231 "\txchgq %rdi, %rsp\n"
3232 /* call _start_in_C_darwin, passing it the startup %rsp */
3233 "\tcall __start_in_C_darwin\n"
3239 void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2);
3240 void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2) {
3242 return VG_(memcpy)(dest,src,n);
3244 void* __memset_chk(void *s, int c, SizeT n, SizeT n2);
3245 void* __memset_chk(void *s, int c, SizeT n, SizeT n2) {
3247 return VG_(memset)(s,c,n);
3249 void bzero(void *s, SizeT n);
3250 void bzero(void *s, SizeT n) {
3254 void* memcpy(void *dest, const void *src, SizeT n);
3255 void* memcpy(void *dest, const void *src, SizeT n) {
3256 return VG_(memcpy)(dest,src,n);
3258 void* memset(void *s, int c, SizeT n);
3259 void* memset(void *s, int c, SizeT n) {
3260 return VG_(memset)(s,c,n);
3263 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3264 'static' causes gcc to complain it isn't. */
3265 void _start_in_C_darwin ( UWord* pArgc );
3266 void _start_in_C_darwin ( UWord* pArgc )
3269 Int argc = *(Int *)pArgc; // not pArgc[0] on LP64
3270 HChar** argv = (HChar**)&pArgc[1];
3271 HChar** envp = (HChar**)&pArgc[1+argc+1];
3273 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3274 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3276 the_iicii.sp_at_startup = (Addr)pArgc;
3278 r = valgrind_main( (Int)argc, argv, envp );
3283 #elif defined(VGO_l4re)
3285 /* If linking of the final executables is done with a libc present,
3286 then Valgrind starts at main() above as usual, and all of the
3287 following code is irrelevant.
3289 However, this is not the intended mode of use. The plan is to
3290 avoid linking against a libc, by giving gcc the flags
3291 -nodefaultlibs -lgcc -nostartfiles at startup.
3293 From this derive two requirements:
3295 1. gcc may emit calls to memcpy and memset to deal with structure
3296 assignments etc. Since we have chosen to ignore all the
3297 "normal" supporting libraries, we have to provide our own
3298 implementations of them. No problem.
3300 2. We have to provide a symbol "_start", to which the kernel
3301 hands control at startup. Hence the code below.
3304 /* ---------------- Requirement 1 ---------------- */
3306 void* memcpy(void *dest, const void *src, SizeT n);
3307 void* memcpy(void *dest, const void *src, SizeT n) {
3308 return VG_(memcpy)(dest,src,n);
3310 void* memset(void *s, int c, SizeT n);
3311 void* memset(void *s, int c, SizeT n) {
3312 return VG_(memset)(s,c,n);
3315 /* ---------------- Requirement 2 ---------------- */
3317 /* The kernel hands control to _start, which extracts the initial
3318 stack pointer and calls onwards to __c_main. This switches to
3319 the new stack and calls then _start_in_C_l4re. */
3320 /* _start is implemented in coregrind/l4re/__c_main.c */
3322 /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
3327 #define _FILE_OFFSET_BITS 64
3328 /* This is in order to get AT_NULL and AT_PAGESIZE. */
3330 /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
3332 #include <l4/re/env.h>
3334 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3335 'static' causes gcc to complain it isn't. */
3336 void _start_in_C_l4re ( int argc, char **argv, char **envp ,int esp);
3338 void _start_in_C_l4re ( int argc, char **argv, char **envp ,int esp)
3342 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3343 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3344 // the_iicii.sp_at_startup = 0x20000;
3346 the_iicii.sp_at_startup = (Addr)&argc;
3347 r = _valgrind_main( (Int)argc, argv, envp );
3354 # error "Unknown OS"
3358 /*====================================================================*/
3359 /*=== {u,}{div,mod}di3 replacements ===*/
3360 /*====================================================================*/
3362 /* For static linking on x86-darwin, we need to supply our own 64-bit
3363 integer division code, else the link dies thusly:
3365 ld_classic: Undefined symbols:
3369 #if defined(VGP_x86_darwin)
3371 /* Routines for doing signed/unsigned 64 x 64 ==> 64 div and mod
3372 (udivdi3, umoddi3, divdi3, moddi3) using only 32 x 32 ==> 32
3373 division. Cobbled together from
3375 http://www.hackersdelight.org/HDcode/divlu.c
3376 http://www.hackersdelight.org/HDcode/divls.c
3377 http://www.hackersdelight.org/HDcode/newCode/divDouble.c
3379 The code from those three files is covered by the following license,
3382 http://www.hackersdelight.org/permissions.htm
3384 You are free to use, copy, and distribute any of the code on
3385 this web site, whether modified by you or not. You need not give
3386 attribution. This includes the algorithms (some of which appear
3387 in Hacker's Delight), the Hacker's Assistant, and any code
3388 submitted by readers. Submitters implicitly agree to this.
3391 /* Long division, unsigned (64/32 ==> 32).
3392 This procedure performs unsigned "long division" i.e., division of a
3393 64-bit unsigned dividend by a 32-bit unsigned divisor, producing a
3394 32-bit quotient. In the overflow cases (divide by 0, or quotient
3395 exceeds 32 bits), it returns a remainder of 0xFFFFFFFF (an impossible
3397 The dividend is u1 and u0, with u1 being the most significant word.
3398 The divisor is parameter v. The value returned is the quotient.
3399 Max line length is 57, to fit in hacker.book. */
3401 static Int nlz32(UInt x)
3404 if (x == 0) return(32);
3406 if (x <= 0x0000FFFF) {n = n +16; x = x <<16;}
3407 if (x <= 0x00FFFFFF) {n = n + 8; x = x << 8;}
3408 if (x <= 0x0FFFFFFF) {n = n + 4; x = x << 4;}
3409 if (x <= 0x3FFFFFFF) {n = n + 2; x = x << 2;}
3410 if (x <= 0x7FFFFFFF) {n = n + 1;}
3414 /* 64 x 32 ==> 32 unsigned division, using only 32 x 32 ==> 32
3415 division as a primitive. */
3416 static UInt divlu2(UInt u1, UInt u0, UInt v, UInt *r)
3418 const UInt b = 65536; // Number base (16 bits).
3419 UInt un1, un0, // Norm. dividend LSD's.
3420 vn1, vn0, // Norm. divisor digits.
3421 q1, q0, // Quotient digits.
3422 un32, un21, un10, // Dividend digit pairs.
3423 rhat; // A remainder.
3424 Int s; // Shift amount for norm.
3426 if (u1 >= v) { // If overflow, set rem.
3427 if (r != NULL) // to an impossible value,
3428 *r = 0xFFFFFFFF; // and return the largest
3429 return 0xFFFFFFFF;} // possible quotient.
3431 s = nlz32(v); // 0 <= s <= 31.
3432 v = v << s; // Normalize divisor.
3433 vn1 = v >> 16; // Break divisor up into
3434 vn0 = v & 0xFFFF; // two 16-bit digits.
3436 un32 = (u1 << s) | ((u0 >> (32 - s)) & (-s >> 31));
3437 un10 = u0 << s; // Shift dividend left.
3439 un1 = un10 >> 16; // Break right half of
3440 un0 = un10 & 0xFFFF; // dividend into two digits.
3442 q1 = un32/vn1; // Compute the first
3443 rhat = un32 - q1*vn1; // quotient digit, q1.
3445 if (q1 >= b || q1*vn0 > b*rhat + un1) {
3448 if (rhat < b) goto again1;}
3450 un21 = un32*b + un1 - q1*v; // Multiply and subtract.
3452 q0 = un21/vn1; // Compute the second
3453 rhat = un21 - q0*vn1; // quotient digit, q0.
3455 if (q0 >= b || q0*vn0 > b*rhat + un0) {
3458 if (rhat < b) goto again2;}
3460 if (r != NULL) // If remainder is wanted,
3461 *r = (un21*b + un0 - q0*v) >> s; // return it.
3466 /* 64 x 32 ==> 32 signed division, using only 32 x 32 ==> 32 division
3468 static Int divls(Int u1, UInt u0, Int v, Int *r)
3470 Int q, uneg, vneg, diff, borrow;
3472 uneg = u1 >> 31; // -1 if u < 0.
3473 if (uneg) { // Compute the absolute
3474 u0 = -u0; // value of the dividend u.
3478 vneg = v >> 31; // -1 if v < 0.
3479 v = (v ^ vneg) - vneg; // Absolute value of v.
3481 if ((UInt)u1 >= (UInt)v) goto overflow;
3483 q = divlu2(u1, u0, v, (UInt *)r);
3485 diff = uneg ^ vneg; // Negate q if signs of
3486 q = (q ^ diff) - diff; // u and v differed.
3487 if (uneg && r != NULL)
3490 if ((diff ^ q) < 0 && q != 0) { // If overflow,
3491 overflow: // set remainder
3492 if (r != NULL) // to an impossible value,
3493 *r = 0x80000000; // and return the largest
3494 q = 0x80000000;} // possible neg. quotient.
3500 /* This file contains a program for doing 64/64 ==> 64 division, on a
3501 machine that does not have that instruction but that does have
3502 instructions for "long division" (64/32 ==> 32). Code for unsigned
3503 division is given first, followed by a simple program for doing the
3504 signed version by using the unsigned version.
3505 These programs are useful in implementing "long long" (64-bit)
3506 arithmetic on a machine that has the long division instruction. It will
3507 work on 64- and 32-bit machines, provided the compiler implements long
3508 long's (64-bit integers). It is desirable that the machine have the
3509 Count Leading Zeros instruction.
3510 In the GNU world, these programs are known as __divdi3 and __udivdi3,
3511 and similar names are used here.
3512 This material is not in HD, but may be in a future edition.
3513 Max line length is 57, to fit in hacker.book. */
3516 static Int nlz64(ULong x)
3519 if (x == 0) return(64);
3521 if (x <= 0x00000000FFFFFFFFULL) {n = n + 32; x = x << 32;}
3522 if (x <= 0x0000FFFFFFFFFFFFULL) {n = n + 16; x = x << 16;}
3523 if (x <= 0x00FFFFFFFFFFFFFFULL) {n = n + 8; x = x << 8;}
3524 if (x <= 0x0FFFFFFFFFFFFFFFULL) {n = n + 4; x = x << 4;}
3525 if (x <= 0x3FFFFFFFFFFFFFFFULL) {n = n + 2; x = x << 2;}
3526 if (x <= 0x7FFFFFFFFFFFFFFFULL) {n = n + 1;}
3530 // ---------------------------- udivdi3 --------------------------------
3532 /* The variables u0, u1, etc. take on only 32-bit values, but they
3533 are declared long long to avoid some compiler warning messages and to
3534 avoid some unnecessary EXTRs that the compiler would put in, to
3535 convert long longs to ints.
3537 First the procedure takes care of the case in which the divisor is a
3538 32-bit quantity. There are two subcases: (1) If the left half of the
3539 dividend is less than the divisor, one execution of DIVU is all that
3540 is required (overflow is not possible). (2) Otherwise it does two
3541 divisions, using the grade school method, with variables used as
3551 /* These macros must be used with arguments of the appropriate type
3552 (unsigned long long for DIVU and long long for DIVS. They are
3553 simulations of the presumed machines ops. I.e., they look at only the
3554 low-order 32 bits of the divisor, they return garbage if the division
3555 overflows, and they return garbage in the high-order half of the
3556 quotient doubleword.
3557 In practice, these would be replaced with uses of the machine's DIVU
3558 and DIVS instructions (e.g., by using the GNU "asm" facility). */
3560 static UInt DIVU ( ULong u, UInt v )
3562 UInt uHi = (UInt)(u >> 32);
3564 return divlu2(uHi, uLo, v, NULL);
3567 static Int DIVS ( Long u, Int v )
3569 Int uHi = (Int)(u >> 32);
3571 return divls(uHi, uLo, v, NULL);
3574 /* 64 x 64 ==> 64 unsigned division, using only 32 x 32 ==> 32
3575 division as a primitive. */
3576 static ULong udivdi3(ULong u, ULong v)
3578 ULong u0, u1, v1, q0, q1, k, n;
3580 if (v >> 32 == 0) { // If v < 2**32:
3581 if (u >> 32 < v) // If u/v cannot overflow,
3582 return DIVU(u, v) // just do one division.
3584 else { // If u/v would overflow:
3585 u1 = u >> 32; // Break u up into two
3586 u0 = u & 0xFFFFFFFF; // halves.
3587 q1 = DIVU(u1, v) // First quotient digit.
3589 k = u1 - q1*v; // First remainder, < v.
3590 q0 = DIVU((k << 32) + u0, v) // 2nd quot. digit.
3592 return (q1 << 32) + q0;
3596 n = nlz64(v); // 0 <= n <= 31.
3597 v1 = (v << n) >> 32; // Normalize the divisor
3599 u1 = u >> 1; // To ensure no overflow.
3600 q1 = DIVU(u1, v1) // Get quotient from
3601 & 0xFFFFFFFF; // divide unsigned insn.
3602 q0 = (q1 << n) >> 31; // Undo normalization and
3603 // division of u by 2.
3604 if (q0 != 0) // Make q0 correct or
3605 q0 = q0 - 1; // too small by 1.
3606 if ((u - q0*v) >= v)
3607 q0 = q0 + 1; // Now q0 is correct.
3612 // ----------------------------- divdi3 --------------------------------
3614 /* This routine presumes that smallish cases (those which can be done in
3615 one execution of DIVS) are common. If this is not the case, the test for
3616 this case should be deleted.
3617 Note that the test for when DIVS can be used is not entirely
3618 accurate. For example, DIVS is not used if v = 0xFFFFFFFF8000000,
3619 whereas if could be (if u is sufficiently small in magnitude). */
3621 // ------------------------------ cut ----------------------------------
3623 static ULong my_llabs ( Long x )
3629 /* 64 x 64 ==> 64 signed division, using only 32 x 32 ==> 32 division
3631 static Long divdi3(Long u, Long v)
3637 if (av >> 31 == 0) { // If |v| < 2**31 and
3638 // if (v << 32 >> 32 == v) { // If v is in range and
3639 if (au < av << 31) { // |u|/|v| cannot
3640 q = DIVS(u, v); // overflow, use DIVS.
3641 return (q << 32) >> 32;
3644 q = udivdi3(au,av); // Invoke udivdi3.
3645 t = (u ^ v) >> 63; // If u, v have different
3646 return (q ^ t) - t; // signs, negate q.
3649 // ---------------------------- end cut --------------------------------
3651 ULong __udivdi3 (ULong u, ULong v);
3652 ULong __udivdi3 (ULong u, ULong v)
3654 return udivdi3(u,v);
3657 Long __divdi3 (Long u, Long v);
3658 Long __divdi3 (Long u, Long v)
3663 ULong __umoddi3 (ULong u, ULong v);
3664 ULong __umoddi3 (ULong u, ULong v)
3666 ULong q = __udivdi3(u, v);
3667 ULong r = u - q * v;
3671 Long __moddi3 (Long u, Long v);
3672 Long __moddi3 (Long u, Long v)
3674 Long q = __divdi3(u, v);
3682 /*--------------------------------------------------------------------*/
3684 /*--------------------------------------------------------------------*/