drd: Add a consistency check
[valgrind.git] / coregrind / m_main.c
blob2a0b2a67785a75afbeb10b5c8dbcf74bb4aa3c15
2 /*--------------------------------------------------------------------*/
3 /*--- Startup: the real stuff m_main.c ---*/
4 /*--------------------------------------------------------------------*/
6 /*
7 This file is part of Valgrind, a dynamic binary instrumentation
8 framework.
10 Copyright (C) 2000-2013 Julian Seward
11 jseward@acm.org
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
26 02111-1307, USA.
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_sbprofile.h"
53 #include "pub_core_syscall.h" // VG_(strerror)
54 #include "pub_core_mach.h"
55 #include "pub_core_machine.h"
56 #include "pub_core_mallocfree.h"
57 #include "pub_core_options.h"
58 #include "pub_core_debuginfo.h"
59 #include "pub_core_redir.h"
60 #include "pub_core_scheduler.h"
61 #include "pub_core_seqmatch.h" // For VG_(string_match)
62 #include "pub_core_signals.h"
63 #include "pub_core_stacks.h" // For VG_(register_stack)
64 #include "pub_core_syswrap.h"
65 #include "pub_core_tooliface.h"
66 #include "pub_core_translate.h" // For VG_(translate)
67 #include "pub_core_trampoline.h"
68 #include "pub_core_transtab.h"
69 #include "pub_core_inner.h"
70 #if defined(ENABLE_INNER_CLIENT_REQUEST)
71 #include "pub_core_clreq.h"
72 #endif
75 /*====================================================================*/
76 /*=== Command-line: variables, processing, etc ===*/
77 /*====================================================================*/
79 // See pub_{core,tool}_options.h for explanations of all these.
81 static void usage_NORETURN ( Bool debug_help )
83 /* 'usage1' contains a %s
84 - for the name of the GDB executable
85 - for the name of vgdb's path prefix
86 which must be supplied when they are VG_(printf)'d. */
87 const HChar usage1[] =
88 "usage: valgrind [options] prog-and-args\n"
89 "\n"
90 " tool-selection option, with default in [ ]:\n"
91 " --tool=<name> use the Valgrind tool named <name> [memcheck]\n"
92 "\n"
93 " basic user options for all Valgrind tools, with defaults in [ ]:\n"
94 " -h --help show this message\n"
95 " --help-debug show this message, plus debugging options\n"
96 " --version show version\n"
97 " -q --quiet run silently; only print error msgs\n"
98 " -v --verbose be more verbose -- show misc extra info\n"
99 " --trace-children=no|yes Valgrind-ise child processes (follow execve)? [no]\n"
100 " --trace-children-skip=patt1,patt2,... specifies a list of executables\n"
101 " that --trace-children=yes should not trace into\n"
102 " --trace-children-skip-by-arg=patt1,patt2,... same as --trace-children-skip=\n"
103 " but check the argv[] entries for children, rather\n"
104 " than the exe name, to make a follow/no-follow decision\n"
105 " --child-silent-after-fork=no|yes omit child output between fork & exec? [no]\n"
106 " --vgdb=no|yes|full activate gdbserver? [yes]\n"
107 " full is slower but provides precise watchpoint/step\n"
108 " --vgdb-error=<number> invoke gdbserver after <number> errors [%d]\n"
109 " to get started quickly, use --vgdb-error=0\n"
110 " and follow the on-screen directions\n"
111 " --vgdb-stop-at=event1,event2,... invoke gdbserver for given events [none]\n"
112 " where event is one of:\n"
113 " startup exit valgrindabexit all none\n"
114 " --track-fds=no|yes track open file descriptors? [no]\n"
115 " --time-stamp=no|yes add timestamps to log messages? [no]\n"
116 " --log-fd=<number> log messages to file descriptor [2=stderr]\n"
117 " --log-file=<file> log messages to <file>\n"
118 " --log-socket=ipaddr:port log messages to socket ipaddr:port\n"
119 "\n"
120 " user options for Valgrind tools that report errors:\n"
121 " --xml=yes emit error output in XML (some tools only)\n"
122 " --xml-fd=<number> XML output to file descriptor\n"
123 " --xml-file=<file> XML output to <file>\n"
124 " --xml-socket=ipaddr:port XML output to socket ipaddr:port\n"
125 " --xml-user-comment=STR copy STR verbatim into XML output\n"
126 " --demangle=no|yes automatically demangle C++ names? [yes]\n"
127 " --num-callers=<number> show <number> callers in stack traces [12]\n"
128 " --error-limit=no|yes stop showing new errors if too many? [yes]\n"
129 " --error-exitcode=<number> exit code to return if errors found [0=disable]\n"
130 " --error-markers=<begin>,<end> add lines with begin/end markers before/after\n"
131 " each error output in plain text mode [none]\n"
132 " --show-below-main=no|yes continue stack traces below main() [no]\n"
133 " --default-suppressions=yes|no\n"
134 " load default suppressions [yes]\n"
135 " --suppressions=<filename> suppress errors described in <filename>\n"
136 " --gen-suppressions=no|yes|all print suppressions for errors? [no]\n"
137 " --db-attach=no|yes start debugger when errors detected? [no]\n"
138 " Note: deprecated feature\n"
139 " --db-command=<command> command to start debugger [%s -nw %%f %%p]\n"
140 " --input-fd=<number> file descriptor for input [0=stdin]\n"
141 " --dsymutil=no|yes run dsymutil on Mac OS X when helpful? [no]\n"
142 " --max-stackframe=<number> assume stack switch for SP changes larger\n"
143 " than <number> bytes [2000000]\n"
144 " --main-stacksize=<number> set size of main thread's stack (in bytes)\n"
145 " [min(max(current 'ulimit' value,1MB),16MB)]\n"
146 "\n"
147 " user options for Valgrind tools that replace malloc:\n"
148 " --alignment=<number> set minimum alignment of heap allocations [%s]\n"
149 " --redzone-size=<number> set minimum size of redzones added before/after\n"
150 " heap blocks (in bytes). [%s]\n"
151 "\n"
152 " uncommon user options for all Valgrind tools:\n"
153 " --fullpath-after= (with nothing after the '=')\n"
154 " show full source paths in call stacks\n"
155 " --fullpath-after=string like --fullpath-after=, but only show the\n"
156 " part of the path after 'string'. Allows removal\n"
157 " of path prefixes. Use this flag multiple times\n"
158 " to specify a set of prefixes to remove.\n"
159 " --extra-debuginfo-path=path absolute path to search for additional\n"
160 " debug symbols, in addition to existing default\n"
161 " well known search paths.\n"
162 " --debuginfo-server=ipaddr:port also query this server\n"
163 " (valgrind-di-server) for debug symbols\n"
164 " --allow-mismatched-debuginfo=no|yes [no]\n"
165 " for the above two flags only, accept debuginfo\n"
166 " objects that don't \"match\" the main object\n"
167 " --smc-check=none|stack|all|all-non-file [stack]\n"
168 " checks for self-modifying code: none, only for\n"
169 " code found in stacks, for all code, or for all\n"
170 " code except that from file-backed mappings\n"
171 " --read-inline-info=yes|no read debug info about inlined function calls\n"
172 " and use it to do better stack traces. [yes]\n"
173 " on Linux/Android for Memcheck/Helgrind/DRD\n"
174 " only. [no] for all other tools and platforms.\n"
175 " --read-var-info=yes|no read debug info on stack and global variables\n"
176 " and use it to print better error messages in\n"
177 " tools that make use of it (Memcheck, Helgrind,\n"
178 " DRD) [no]\n"
179 " --vgdb-poll=<number> gdbserver poll max every <number> basic blocks [%d] \n"
180 " --vgdb-shadow-registers=no|yes let gdb see the shadow registers [no]\n"
181 " --vgdb-prefix=<prefix> prefix for vgdb FIFOs [%s]\n"
182 " --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]\n"
183 " --sim-hints=hint1,hint2,... activate unusual sim behaviours [none] \n"
184 " where hint is one of:\n"
185 " lax-ioctls fuse-compatible enable-outer\n"
186 " no-inner-prefix no-nptl-pthread-stackcache none\n"
187 " --fair-sched=no|yes|try schedule threads fairly on multicore systems [no]\n"
188 " --kernel-variant=variant1,variant2,...\n"
189 " handle non-standard kernel variants [none]\n"
190 " where variant is one of:\n"
191 " bproc android-no-hw-tls\n"
192 " android-gpu-sgx5xx android-gpu-adreno3xx none\n"
193 " --merge-recursive-frames=<number> merge frames between identical\n"
194 " program counters in max <number> frames) [0]\n"
195 " --num-transtab-sectors=<number> size of translated code cache [%d]\n"
196 " more sectors may increase performance, but use more memory.\n"
197 " --aspace-minaddr=0xPP avoid mapping memory below 0xPP [guessed]\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"
202 " --soname-synonyms=syn1=pattern1,syn2=pattern2,... synonym soname\n"
203 " specify patterns for function wrapping or replacement.\n"
204 " To use a non-libc malloc library that is\n"
205 " in the main exe: --soname-synonyms=somalloc=NONE\n"
206 " in libxyzzy.so: --soname-synonyms=somalloc=libxyzzy.so\n"
207 " --sigill-diagnostics=yes|no warn about illegal instructions? [yes]\n"
208 " --unw-stack-scan-thresh=<number> Enable stack-scan unwind if fewer\n"
209 " than <number> good frames found [0, meaning \"disabled\"]\n"
210 " NOTE: stack scanning is only available on arm-linux.\n"
211 " --unw-stack-scan-frames=<number> Max number of frames that can be\n"
212 " recovered by stack scanning [5]\n"
213 " --resync-filter=no|yes|verbose [yes on MacOS, no on other OSes]\n"
214 " attempt to avoid expensive address-space-resync operations\n"
215 "\n";
217 const HChar usage2[] =
218 "\n"
219 " debugging options for all Valgrind tools:\n"
220 " -d show verbose debugging output\n"
221 " --stats=no|yes show tool and core statistics [no]\n"
222 " --sanity-level=<number> level of sanity checking to do [1]\n"
223 " --trace-flags=<XXXXXXXX> show generated code? (X = 0|1) [00000000]\n"
224 " --profile-flags=<XXXXXXXX> ditto, but for profiling (X = 0|1) [00000000]\n"
225 " --profile-interval=<number> show profile every <number> event checks\n"
226 " [0, meaning only at the end of the run]\n"
227 " --trace-notbelow=<number> only show BBs above <number> [999999999]\n"
228 " --trace-notabove=<number> only show BBs below <number> [0]\n"
229 " --trace-syscalls=no|yes show all system calls? [no]\n"
230 " --trace-signals=no|yes show signal handling details? [no]\n"
231 " --trace-symtab=no|yes show symbol table details? [no]\n"
232 " --trace-symtab-patt=<patt> limit debuginfo tracing to obj name <patt>\n"
233 " --trace-cfi=no|yes show call-frame-info details? [no]\n"
234 " --debug-dump=syms mimic /usr/bin/readelf --syms\n"
235 " --debug-dump=line mimic /usr/bin/readelf --debug-dump=line\n"
236 " --debug-dump=frames mimic /usr/bin/readelf --debug-dump=frames\n"
237 " --trace-redir=no|yes show redirection details? [no]\n"
238 " --trace-sched=no|yes show thread scheduler details? [no]\n"
239 " --profile-heap=no|yes profile Valgrind's own space use\n"
240 " --core-redzone-size=<number> set minimum size of redzones added before/after\n"
241 " heap blocks allocated for Valgrind internal use (in bytes) [4]\n"
242 " --wait-for-gdb=yes|no pause on startup to wait for gdb attach\n"
243 " --sym-offsets=yes|no show syms in form 'name+offset' ? [no]\n"
244 " --command-line-only=no|yes only use command line options [no]\n"
245 "\n"
246 " Vex options for all Valgrind tools:\n"
247 " --vex-iropt-verbosity=<0..9> [0]\n"
248 " --vex-iropt-level=<0..2> [2]\n"
249 " --vex-iropt-register-updates=sp-at-mem-access\n"
250 " |unwindregs-at-mem-access\n"
251 " |allregs-at-mem-access\n"
252 " |allregs-at-each-insn [unwindregs-at-mem-access]\n"
253 " --vex-iropt-unroll-thresh=<0..400> [120]\n"
254 " --vex-guest-max-insns=<1..100> [50]\n"
255 " --vex-guest-chase-thresh=<0..99> [10]\n"
256 " --vex-guest-chase-cond=no|yes [no]\n"
257 " --trace-flags and --profile-flags values (omit the middle space):\n"
258 " 1000 0000 show conversion into IR\n"
259 " 0100 0000 show after initial opt\n"
260 " 0010 0000 show after instrumentation\n"
261 " 0001 0000 show after second opt\n"
262 " 0000 1000 show after tree building\n"
263 " 0000 0100 show selecting insns\n"
264 " 0000 0010 show after reg-alloc\n"
265 " 0000 0001 show final assembly\n"
266 " 0000 0000 show summary profile only\n"
267 " (Nb: you need --trace-notbelow and/or --trace-notabove\n"
268 " with --trace-flags for full details)\n"
269 "\n"
270 " debugging options for Valgrind tools that report errors\n"
271 " --dump-error=<number> show translation for basic block associated\n"
272 " with <number>'th error context [0=show none]\n"
273 "\n"
274 " debugging options for Valgrind tools that replace malloc:\n"
275 " --trace-malloc=no|yes show client malloc details? [no]\n"
276 "\n";
278 const HChar usage3[] =
279 "\n"
280 " Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc\n"
281 "\n"
282 " %s is %s\n"
283 " Valgrind is Copyright (C) 2000-2013, and GNU GPL'd, by Julian Seward et al.\n"
284 " LibVEX is Copyright (C) 2004-2013, and GNU GPL'd, by OpenWorks LLP et al.\n"
285 "\n"
286 " Bug reports, feedback, admiration, abuse, etc, to: %s.\n"
287 "\n";
289 const HChar* gdb_path = GDB_PATH;
290 HChar default_alignment[30];
291 HChar default_redzone_size[30];
293 // Ensure the message goes to stdout
294 VG_(log_output_sink).fd = 1;
295 VG_(log_output_sink).is_socket = False;
297 if (VG_(needs).malloc_replacement) {
298 VG_(sprintf)(default_alignment, "%d", VG_MIN_MALLOC_SZB);
299 VG_(sprintf)(default_redzone_size, "%lu", VG_(tdict).tool_client_redzone_szB);
300 } else {
301 VG_(strcpy)(default_alignment, "not used by this tool");
302 VG_(strcpy)(default_redzone_size, "not used by this tool");
304 /* 'usage1' a type as described after each arg. */
305 VG_(printf)(usage1,
306 VG_(clo_vgdb_error) /* int */,
307 gdb_path /* char* */,
308 default_alignment /* char* */,
309 default_redzone_size /* char* */,
310 VG_(clo_vgdb_poll) /* int */,
311 VG_(vgdb_prefix_default)() /* char* */,
312 N_SECTORS_DEFAULT /* int */
314 if (VG_(details).name) {
315 VG_(printf)(" user options for %s:\n", VG_(details).name);
316 if (VG_(needs).command_line_options)
317 VG_TDICT_CALL(tool_print_usage);
318 else
319 VG_(printf)(" (none)\n");
321 if (debug_help) {
322 VG_(printf)("%s", usage2);
324 if (VG_(details).name) {
325 VG_(printf)(" debugging options for %s:\n", VG_(details).name);
327 if (VG_(needs).command_line_options)
328 VG_TDICT_CALL(tool_print_debug_usage);
329 else
330 VG_(printf)(" (none)\n");
333 VG_(printf)(usage3, VG_(details).name, VG_(details).copyright_author,
334 VG_BUGS_TO);
335 VG_(exit)(0);
339 /* Peer at previously set up VG_(args_for_valgrind) and do some
340 minimal command line processing that must happen early on:
342 - show the version string, if requested (-v)
343 - extract any request for help (--help, -h, --help-debug)
344 - get the toolname (--tool=)
345 - set VG_(clo_max_stackframe) (--max-stackframe=)
346 - set VG_(clo_main_stacksize) (--main-stacksize=)
347 - set VG_(clo_sim_hints) (--sim-hints=)
349 That's all it does. The main command line processing is done below
350 by main_process_cmd_line_options. Note that
351 main_process_cmd_line_options has to handle but ignore the ones we
352 have handled here.
354 static void early_process_cmd_line_options ( /*OUT*/Int* need_help,
355 /*OUT*/const HChar** tool )
357 UInt i;
358 HChar* str;
360 vg_assert( VG_(args_for_valgrind) );
362 /* parse the options we have (only the options we care about now) */
363 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
365 str = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
366 vg_assert(str);
368 // Nb: the version string goes to stdout.
369 if VG_XACT_CLO(str, "--version", VG_(log_output_sink).fd, 1) {
370 VG_(log_output_sink).is_socket = False;
371 VG_(printf)("valgrind-" VERSION "\n");
372 VG_(exit)(0);
374 else if VG_XACT_CLO(str, "--help", *need_help, *need_help+1) {}
375 else if VG_XACT_CLO(str, "-h", *need_help, *need_help+1) {}
377 else if VG_XACT_CLO(str, "--help-debug", *need_help, *need_help+2) {}
379 // The tool has already been determined, but we need to know the name
380 // here.
381 else if VG_STR_CLO(str, "--tool", *tool) {}
383 // Set up VG_(clo_max_stackframe) and VG_(clo_main_stacksize).
384 // These are needed by VG_(ii_create_image), which happens
385 // before main_process_cmd_line_options().
386 else if VG_INT_CLO(str, "--max-stackframe", VG_(clo_max_stackframe)) {}
387 else if VG_INT_CLO(str, "--main-stacksize", VG_(clo_main_stacksize)) {}
389 // Set up VG_(clo_sim_hints). This is needed a.o. for an inner
390 // running in an outer, to have "no-inner-prefix" enabled
391 // as early as possible.
392 else if VG_USETX_CLO (str, "--sim-hints",
393 "lax-ioctls,fuse-compatible,"
394 "enable-outer,no-inner-prefix,"
395 "no-nptl-pthread-stackcache",
396 VG_(clo_sim_hints)) {}
400 /* The main processing for command line options. See comments above
401 on early_process_cmd_line_options.
403 Comments on how the logging options are handled:
405 User can specify:
406 --log-fd= for a fd to write to (default setting, fd = 2)
407 --log-file= for a file name to write to
408 --log-socket= for a socket to write to
410 As a result of examining these and doing relevant socket/file
411 opening, a final fd is established. This is stored in
412 VG_(log_output_sink) in m_libcprint. Also, if --log-file=STR was
413 specified, then STR, after expansion of %p and %q templates within
414 it, is stored in VG_(clo_log_fname_expanded), in m_options, just in
415 case anybody wants to know what it is.
417 When printing, VG_(log_output_sink) is consulted to find the
418 fd to send output to.
420 Exactly analogous actions are undertaken for the XML output
421 channel, with the one difference that the default fd is -1, meaning
422 the channel is disabled by default.
424 static
425 void main_process_cmd_line_options ( /*OUT*/Bool* logging_to_fd,
426 /*OUT*/const HChar** xml_fname_unexpanded,
427 const HChar* toolname )
429 // VG_(clo_log_fd) is used by all the messaging. It starts as 2 (stderr)
430 // and we cannot change it until we know what we are changing it to is
431 // ok. So we have tmp_log_fd to hold the tmp fd prior to that point.
432 SysRes sres;
433 Int i, tmp_log_fd, tmp_xml_fd;
434 Int toolname_len = VG_(strlen)(toolname);
435 const HChar* tmp_str; // Used in a couple of places.
436 enum {
437 VgLogTo_Fd,
438 VgLogTo_File,
439 VgLogTo_Socket
440 } log_to = VgLogTo_Fd, // Where is logging output to be sent?
441 xml_to = VgLogTo_Fd; // Where is XML output to be sent?
443 /* Temporarily holds the string STR specified with
444 --{log,xml}-{name,socket}=STR. 'fs' stands for
445 file-or-socket. */
446 const HChar* log_fsname_unexpanded = NULL;
447 const HChar* xml_fsname_unexpanded = NULL;
449 /* Whether the user has explicitly provided --sigill-diagnostics.
450 If not explicitly given depends on general verbosity setting. */
451 Bool sigill_diag_set = False;
453 /* Log to stderr by default, but usage message goes to stdout. XML
454 output is initially disabled. */
455 tmp_log_fd = 2;
456 tmp_xml_fd = -1;
458 /* Check for sane path in ./configure --prefix=... */
459 if (VG_LIBDIR[0] != '/')
460 VG_(err_config_error)("Please use absolute paths in "
461 "./configure --prefix=... or --libdir=...\n");
463 vg_assert( VG_(args_for_valgrind) );
465 VG_(clo_suppressions) = VG_(newXA)(VG_(malloc), "main.mpclo.4",
466 VG_(free), sizeof(HChar *));
467 VG_(clo_fullpath_after) = VG_(newXA)(VG_(malloc), "main.mpclo.5",
468 VG_(free), sizeof(HChar *));
469 VG_(clo_req_tsyms) = VG_(newXA)(VG_(malloc), "main.mpclo.6",
470 VG_(free), sizeof(HChar *));
472 /* BEGIN command-line processing loop */
474 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
476 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
477 HChar* colon = arg;
479 // Look for a colon in the option name.
480 while (*colon && *colon != ':' && *colon != '=')
481 colon++;
483 // Does it have the form "--toolname:foo"? We have to do it at the start
484 // in case someone has combined a prefix with a core-specific option,
485 // eg. "--memcheck:verbose".
486 if (*colon == ':') {
487 if (VG_STREQN(2, arg, "--") &&
488 VG_STREQN(toolname_len, arg+2, toolname) &&
489 VG_STREQN(1, arg+2+toolname_len, ":"))
491 // Prefix matches, convert "--toolname:foo" to "--foo".
492 // Two things to note:
493 // - We cannot modify the option in-place. If we did, and then
494 // a child was spawned with --trace-children=yes, the
495 // now-non-prefixed option would be passed and could screw up
496 // the child.
497 // - We create copies, and never free them. Why? Non-prefixed
498 // options hang around forever, so tools need not make copies
499 // of strings within them. We need to have the same behaviour
500 // for prefixed options. The pointer to the copy will be lost
501 // once we leave this function (although a tool may keep a
502 // pointer into it), but the space wasted is insignificant.
503 // (In bug #142197, the copies were being freed, which caused
504 // problems for tools that reasonably assumed that arguments
505 // wouldn't disappear on them.)
506 if (0)
507 VG_(printf)("tool-specific arg: %s\n", arg);
508 arg = VG_(strdup)("main.mpclo.1", arg + toolname_len + 1);
509 arg[0] = '-';
510 arg[1] = '-';
512 } else {
513 // prefix doesn't match, skip to next arg
514 continue;
518 /* Ignore these options - they've already been handled */
519 if VG_STREQN( 7, arg, "--tool=") {}
520 else if VG_STREQN(20, arg, "--command-line-only=") {}
521 else if VG_STREQ( arg, "--") {}
522 else if VG_STREQ( arg, "-d") {}
523 else if VG_STREQN(17, arg, "--max-stackframe=") {}
524 else if VG_STREQN(17, arg, "--main-stacksize=") {}
525 else if VG_STREQN(12, arg, "--sim-hints=") {}
526 else if VG_STREQN(15, arg, "--profile-heap=") {}
527 else if VG_STREQN(20, arg, "--core-redzone-size=") {}
528 else if VG_STREQN(15, arg, "--redzone-size=") {}
529 else if VG_STREQN(17, arg, "--aspace-minaddr=") {}
531 /* Obsolete options. Report an error and exit */
532 else if VG_STREQN(34, arg, "--vex-iropt-precise-memory-exns=no") {
533 VG_(fmsg_bad_option)
534 (arg,
535 "--vex-iropt-precise-memory-exns is obsolete\n"
536 "Use --vex-iropt-register-updates=unwindregs-at-mem-access instead\n");
538 else if VG_STREQN(35, arg, "--vex-iropt-precise-memory-exns=yes") {
539 VG_(fmsg_bad_option)
540 (arg,
541 "--vex-iropt-precise-memory-exns is obsolete\n"
542 "Use --vex-iropt-register-updates=allregs-at-mem-access instead\n"
543 " (or --vex-iropt-register-updates=allregs-at-each-insn)\n");
546 // These options are new.
547 else if (VG_STREQ(arg, "-v") ||
548 VG_STREQ(arg, "--verbose"))
549 VG_(clo_verbosity)++;
551 else if (VG_STREQ(arg, "-q") ||
552 VG_STREQ(arg, "--quiet"))
553 VG_(clo_verbosity)--;
555 else if VG_BOOL_CLO(arg, "--sigill-diagnostics", VG_(clo_sigill_diag))
556 sigill_diag_set = True;
558 else if VG_BOOL_CLO(arg, "--stats", VG_(clo_stats)) {}
559 else if VG_BOOL_CLO(arg, "--xml", VG_(clo_xml))
560 VG_(debugLog_setXml)(VG_(clo_xml));
562 else if VG_XACT_CLO(arg, "--vgdb=no", VG_(clo_vgdb), Vg_VgdbNo) {}
563 else if VG_XACT_CLO(arg, "--vgdb=yes", VG_(clo_vgdb), Vg_VgdbYes) {}
564 else if VG_XACT_CLO(arg, "--vgdb=full", VG_(clo_vgdb), Vg_VgdbFull) {
565 /* automatically updates register values at each insn
566 with --vgdb=full */
567 VG_(clo_vex_control).iropt_register_updates
568 = VexRegUpdAllregsAtEachInsn;
570 else if VG_INT_CLO (arg, "--vgdb-poll", VG_(clo_vgdb_poll)) {}
571 else if VG_INT_CLO (arg, "--vgdb-error", VG_(clo_vgdb_error)) {}
572 else if VG_USET_CLO (arg, "--vgdb-stop-at",
573 "startup,exit,valgrindabexit",
574 VG_(clo_vgdb_stop_at)) {}
575 else if VG_STR_CLO (arg, "--vgdb-prefix", VG_(clo_vgdb_prefix)) {
576 VG_(arg_vgdb_prefix) = arg;
578 else if VG_BOOL_CLO(arg, "--vgdb-shadow-registers",
579 VG_(clo_vgdb_shadow_registers)) {}
580 else if VG_BOOL_CLO(arg, "--db-attach", VG_(clo_db_attach)) {}
581 else if VG_BOOL_CLO(arg, "--demangle", VG_(clo_demangle)) {}
582 else if VG_STR_CLO (arg, "--soname-synonyms",VG_(clo_soname_synonyms)) {}
583 else if VG_BOOL_CLO(arg, "--error-limit", VG_(clo_error_limit)) {}
584 else if VG_INT_CLO (arg, "--error-exitcode", VG_(clo_error_exitcode)) {}
585 else if VG_STR_CLO (arg, "--error-markers", tmp_str) {
586 Int m;
587 const HChar *startpos = tmp_str;
588 const HChar *nextpos;
589 for (m = 0;
590 m < sizeof(VG_(clo_error_markers))
591 /sizeof(VG_(clo_error_markers)[0]);
592 m++) {
593 /* Release previous value if clo given multiple times. */
594 VG_(free)(VG_(clo_error_markers)[m]);
595 VG_(clo_error_markers)[m] = NULL;
597 nextpos = VG_(strchr)(startpos, ',');
598 if (!nextpos)
599 nextpos = startpos + VG_(strlen)(startpos);
600 if (startpos != nextpos) {
601 VG_(clo_error_markers)[m]
602 = VG_(malloc)("main.mpclo.2", nextpos - startpos + 1);
603 VG_(memcpy)(VG_(clo_error_markers)[m], startpos,
604 nextpos - startpos);
605 VG_(clo_error_markers)[m][nextpos - startpos] = '\0';
607 startpos = *nextpos ? nextpos + 1 : nextpos;
610 else if VG_BOOL_CLO(arg, "--show-emwarns", VG_(clo_show_emwarns)) {}
612 else if VG_BOOL_CLO(arg, "--run-libc-freeres", VG_(clo_run_libc_freeres)) {}
613 else if VG_BOOL_CLO(arg, "--show-below-main", VG_(clo_show_below_main)) {}
614 else if VG_BOOL_CLO(arg, "--time-stamp", VG_(clo_time_stamp)) {}
615 else if VG_BOOL_CLO(arg, "--track-fds", VG_(clo_track_fds)) {}
616 else if VG_BOOL_CLO(arg, "--trace-children", VG_(clo_trace_children)) {}
617 else if VG_BOOL_CLO(arg, "--child-silent-after-fork",
618 VG_(clo_child_silent_after_fork)) {}
619 else if VG_STR_CLO(arg, "--fair-sched", tmp_str) {
620 if (VG_(strcmp)(tmp_str, "yes") == 0)
621 VG_(clo_fair_sched) = enable_fair_sched;
622 else if (VG_(strcmp)(tmp_str, "try") == 0)
623 VG_(clo_fair_sched) = try_fair_sched;
624 else if (VG_(strcmp)(tmp_str, "no") == 0)
625 VG_(clo_fair_sched) = disable_fair_sched;
626 else
627 VG_(fmsg_bad_option)(arg, "");
630 else if VG_BOOL_CLO(arg, "--trace-sched", VG_(clo_trace_sched)) {}
631 else if VG_BOOL_CLO(arg, "--trace-signals", VG_(clo_trace_signals)) {}
632 else if VG_BOOL_CLO(arg, "--trace-symtab", VG_(clo_trace_symtab)) {}
633 else if VG_STR_CLO (arg, "--trace-symtab-patt", VG_(clo_trace_symtab_patt)) {}
634 else if VG_BOOL_CLO(arg, "--trace-cfi", VG_(clo_trace_cfi)) {}
635 else if VG_XACT_CLO(arg, "--debug-dump=syms", VG_(clo_debug_dump_syms),
636 True) {}
637 else if VG_XACT_CLO(arg, "--debug-dump=line", VG_(clo_debug_dump_line),
638 True) {}
639 else if VG_XACT_CLO(arg, "--debug-dump=frames",
640 VG_(clo_debug_dump_frames), True) {}
641 else if VG_BOOL_CLO(arg, "--trace-redir", VG_(clo_trace_redir)) {}
643 else if VG_BOOL_CLO(arg, "--trace-syscalls", VG_(clo_trace_syscalls)) {}
644 else if VG_BOOL_CLO(arg, "--wait-for-gdb", VG_(clo_wait_for_gdb)) {}
645 else if VG_STR_CLO (arg, "--db-command", VG_(clo_db_command)) {}
646 else if VG_BOOL_CLO(arg, "--sym-offsets", VG_(clo_sym_offsets)) {}
647 else if VG_BOOL_CLO(arg, "--read-inline-info", VG_(clo_read_inline_info)) {}
648 else if VG_BOOL_CLO(arg, "--read-var-info", VG_(clo_read_var_info)) {}
650 else if VG_INT_CLO (arg, "--dump-error", VG_(clo_dump_error)) {}
651 else if VG_INT_CLO (arg, "--input-fd", VG_(clo_input_fd)) {}
652 else if VG_INT_CLO (arg, "--sanity-level", VG_(clo_sanity_level)) {}
653 else if VG_BINT_CLO(arg, "--num-callers", VG_(clo_backtrace_size), 1,
654 VG_DEEPEST_BACKTRACE) {}
655 else if VG_BINT_CLO(arg, "--num-transtab-sectors",
656 VG_(clo_num_transtab_sectors),
657 MIN_N_SECTORS, MAX_N_SECTORS) {}
658 else if VG_BINT_CLO(arg, "--merge-recursive-frames",
659 VG_(clo_merge_recursive_frames), 0,
660 VG_DEEPEST_BACKTRACE) {}
662 else if VG_XACT_CLO(arg, "--smc-check=none", VG_(clo_smc_check),
663 Vg_SmcNone);
664 else if VG_XACT_CLO(arg, "--smc-check=stack", VG_(clo_smc_check),
665 Vg_SmcStack);
666 else if VG_XACT_CLO(arg, "--smc-check=all", VG_(clo_smc_check),
667 Vg_SmcAll);
668 else if VG_XACT_CLO(arg, "--smc-check=all-non-file",
669 VG_(clo_smc_check),
670 Vg_SmcAllNonFile);
672 else if VG_USETX_CLO (arg, "--kernel-variant",
673 "bproc,"
674 "android-no-hw-tls,"
675 "android-gpu-sgx5xx,"
676 "android-gpu-adreno3xx",
677 VG_(clo_kernel_variant)) {}
679 else if VG_BOOL_CLO(arg, "--dsymutil", VG_(clo_dsymutil)) {}
681 else if VG_STR_CLO (arg, "--trace-children-skip",
682 VG_(clo_trace_children_skip)) {}
683 else if VG_STR_CLO (arg, "--trace-children-skip-by-arg",
684 VG_(clo_trace_children_skip_by_arg)) {}
686 else if VG_BINT_CLO(arg, "--vex-iropt-verbosity",
687 VG_(clo_vex_control).iropt_verbosity, 0, 10) {}
688 else if VG_BINT_CLO(arg, "--vex-iropt-level",
689 VG_(clo_vex_control).iropt_level, 0, 2) {}
690 else if VG_XACT_CLO(arg,
691 "--vex-iropt-register-updates=sp-at-mem-access",
692 VG_(clo_vex_control).iropt_register_updates,
693 VexRegUpdSpAtMemAccess);
694 else if VG_XACT_CLO(arg,
695 "--vex-iropt-register-updates=unwindregs-at-mem-access",
696 VG_(clo_vex_control).iropt_register_updates,
697 VexRegUpdUnwindregsAtMemAccess);
698 else if VG_XACT_CLO(arg,
699 "--vex-iropt-register-updates=allregs-at-mem-access",
700 VG_(clo_vex_control).iropt_register_updates,
701 VexRegUpdAllregsAtMemAccess);
702 else if VG_XACT_CLO(arg,
703 "--vex-iropt-register-updates=allregs-at-each-insn",
704 VG_(clo_vex_control).iropt_register_updates,
705 VexRegUpdAllregsAtEachInsn);
706 else if VG_BINT_CLO(arg, "--vex-iropt-unroll-thresh",
707 VG_(clo_vex_control).iropt_unroll_thresh, 0, 400) {}
708 else if VG_BINT_CLO(arg, "--vex-guest-max-insns",
709 VG_(clo_vex_control).guest_max_insns, 1, 100) {}
710 else if VG_BINT_CLO(arg, "--vex-guest-chase-thresh",
711 VG_(clo_vex_control).guest_chase_thresh, 0, 99) {}
712 else if VG_BOOL_CLO(arg, "--vex-guest-chase-cond",
713 VG_(clo_vex_control).guest_chase_cond) {}
715 else if VG_INT_CLO(arg, "--log-fd", tmp_log_fd) {
716 log_to = VgLogTo_Fd;
717 log_fsname_unexpanded = NULL;
719 else if VG_INT_CLO(arg, "--xml-fd", tmp_xml_fd) {
720 xml_to = VgLogTo_Fd;
721 xml_fsname_unexpanded = NULL;
724 else if VG_STR_CLO(arg, "--log-file", log_fsname_unexpanded) {
725 log_to = VgLogTo_File;
727 else if VG_STR_CLO(arg, "--xml-file", xml_fsname_unexpanded) {
728 xml_to = VgLogTo_File;
731 else if VG_STR_CLO(arg, "--log-socket", log_fsname_unexpanded) {
732 log_to = VgLogTo_Socket;
734 else if VG_STR_CLO(arg, "--xml-socket", xml_fsname_unexpanded) {
735 xml_to = VgLogTo_Socket;
738 else if VG_STR_CLO(arg, "--debuginfo-server",
739 VG_(clo_debuginfo_server)) {}
741 else if VG_BOOL_CLO(arg, "--allow-mismatched-debuginfo",
742 VG_(clo_allow_mismatched_debuginfo)) {}
744 else if VG_STR_CLO(arg, "--xml-user-comment",
745 VG_(clo_xml_user_comment)) {}
747 else if VG_BOOL_CLO(arg, "--default-suppressions",
748 VG_(clo_default_supp)) { }
750 else if VG_STR_CLO(arg, "--suppressions", tmp_str) {
751 VG_(addToXA)(VG_(clo_suppressions), &tmp_str);
754 else if VG_STR_CLO (arg, "--fullpath-after", tmp_str) {
755 VG_(addToXA)(VG_(clo_fullpath_after), &tmp_str);
758 else if VG_STR_CLO (arg, "--extra-debuginfo-path",
759 VG_(clo_extra_debuginfo_path)) {}
761 else if VG_STR_CLO(arg, "--require-text-symbol", tmp_str) {
762 /* String needs to be of the form C?*C?*, where C is any
763 character, but is the same both times. Having it in this
764 form facilitates finding the boundary between the sopatt
765 and the fnpatt just by looking for the second occurrence
766 of C, without hardwiring any assumption about what C
767 is. */
768 HChar patt[7];
769 Bool ok = True;
770 ok = tmp_str && VG_(strlen)(tmp_str) > 0;
771 if (ok) {
772 patt[0] = patt[3] = tmp_str[0];
773 patt[1] = patt[4] = '?';
774 patt[2] = patt[5] = '*';
775 patt[6] = 0;
776 ok = VG_(string_match)(patt, tmp_str);
778 if (!ok) {
779 VG_(fmsg_bad_option)(arg,
780 "Invalid --require-text-symbol= specification.\n");
782 VG_(addToXA)(VG_(clo_req_tsyms), &tmp_str);
785 /* "stuvwxyz" --> stuvwxyz (binary) */
786 else if VG_STR_CLO(arg, "--trace-flags", tmp_str) {
787 Int j;
788 if (8 != VG_(strlen)(tmp_str)) {
789 VG_(fmsg_bad_option)(arg,
790 "--trace-flags argument must have 8 digits\n");
792 for (j = 0; j < 8; j++) {
793 if ('0' == tmp_str[j]) { /* do nothing */ }
794 else if ('1' == tmp_str[j]) VG_(clo_trace_flags) |= (1 << (7-j));
795 else {
796 VG_(fmsg_bad_option)(arg,
797 "--trace-flags argument can only contain 0s and 1s\n");
802 else if VG_INT_CLO (arg, "--trace-notbelow", VG_(clo_trace_notbelow)) {}
804 else if VG_INT_CLO (arg, "--trace-notabove", VG_(clo_trace_notabove)) {}
806 /* "stuvwxyz" --> stuvwxyz (binary) */
807 else if VG_STR_CLO(arg, "--profile-flags", tmp_str) {
808 Int j;
809 if (8 != VG_(strlen)(tmp_str)) {
810 VG_(fmsg_bad_option)(arg,
811 "--profile-flags argument must have 8 digits\n");
813 for (j = 0; j < 8; j++) {
814 if ('0' == tmp_str[j]) { /* do nothing */ }
815 else if ('1' == tmp_str[j]) VG_(clo_profyle_flags) |= (1 << (7-j));
816 else {
817 VG_(fmsg_bad_option)(arg,
818 "--profile-flags argument can only contain 0s and 1s\n");
821 VG_(clo_profyle_sbs) = True;
824 else if VG_INT_CLO (arg, "--profile-interval",
825 VG_(clo_profyle_interval)) {}
827 else if VG_XACT_CLO(arg, "--gen-suppressions=no",
828 VG_(clo_gen_suppressions), 0) {}
829 else if VG_XACT_CLO(arg, "--gen-suppressions=yes",
830 VG_(clo_gen_suppressions), 1) {}
831 else if VG_XACT_CLO(arg, "--gen-suppressions=all",
832 VG_(clo_gen_suppressions), 2) {}
834 else if VG_BINT_CLO(arg, "--unw-stack-scan-thresh",
835 VG_(clo_unw_stack_scan_thresh), 0, 100) {}
836 else if VG_BINT_CLO(arg, "--unw-stack-scan-frames",
837 VG_(clo_unw_stack_scan_frames), 0, 32) {}
839 else if VG_XACT_CLO(arg, "--resync-filter=no",
840 VG_(clo_resync_filter), 0) {}
841 else if VG_XACT_CLO(arg, "--resync-filter=yes",
842 VG_(clo_resync_filter), 1) {}
843 else if VG_XACT_CLO(arg, "--resync-filter=verbose",
844 VG_(clo_resync_filter), 2) {}
846 else if ( ! VG_(needs).command_line_options
847 || ! VG_TDICT_CALL(tool_process_cmd_line_option, arg) ) {
848 VG_(fmsg_bad_option)(arg, "");
852 /* END command-line processing loop */
854 /* Notify about deprecated features */
855 if (VG_(clo_db_attach))
856 VG_(umsg)
857 ("\nWarning: --db-attach is a deprecated feature which will be\n"
858 " removed in the next release. Use --vgdb-error=1 instead\n\n");
860 /* Determine the path prefix for vgdb */
861 if (VG_(clo_vgdb_prefix) == NULL)
862 VG_(clo_vgdb_prefix) = VG_(vgdb_prefix_default)();
864 /* Make VEX control parameters sane */
866 if (VG_(clo_vex_control).guest_chase_thresh
867 >= VG_(clo_vex_control).guest_max_insns)
868 VG_(clo_vex_control).guest_chase_thresh
869 = VG_(clo_vex_control).guest_max_insns - 1;
871 if (VG_(clo_vex_control).guest_chase_thresh < 0)
872 VG_(clo_vex_control).guest_chase_thresh = 0;
874 /* Check various option values */
876 if (VG_(clo_verbosity) < 0)
877 VG_(clo_verbosity) = 0;
879 if (!sigill_diag_set)
880 VG_(clo_sigill_diag) = (VG_(clo_verbosity) > 0);
882 if (VG_(clo_trace_notbelow) == -1) {
883 if (VG_(clo_trace_notabove) == -1) {
884 /* [] */
885 VG_(clo_trace_notbelow) = 2147483647;
886 VG_(clo_trace_notabove) = 0;
887 } else {
888 /* [0 .. notabove] */
889 VG_(clo_trace_notbelow) = 0;
891 } else {
892 if (VG_(clo_trace_notabove) == -1) {
893 /* [notbelow .. ] */
894 VG_(clo_trace_notabove) = 2147483647;
895 } else {
896 /* [notbelow .. notabove] */
900 VG_(dyn_vgdb_error) = VG_(clo_vgdb_error);
902 if (VG_(clo_gen_suppressions) > 0 &&
903 !VG_(needs).core_errors && !VG_(needs).tool_errors) {
904 VG_(fmsg_bad_option)("--gen-suppressions=yes",
905 "Can't use --gen-suppressions= with %s\n"
906 "because it doesn't generate errors.\n", VG_(details).name);
909 # if !defined(VGO_darwin)
910 if (VG_(clo_resync_filter) != 0) {
911 VG_(fmsg_bad_option)("--resync-filter=yes or =verbose",
912 "--resync-filter= is only available on MacOS X.\n");
913 /*NOTREACHED*/
915 # endif
917 /* If XML output is requested, check that the tool actually
918 supports it. */
919 if (VG_(clo_xml) && !VG_(needs).xml_output) {
920 VG_(clo_xml) = False;
921 VG_(fmsg_bad_option)("--xml=yes",
922 "%s does not support XML output.\n", VG_(details).name);
923 /*NOTREACHED*/
926 vg_assert( VG_(clo_gen_suppressions) >= 0 );
927 vg_assert( VG_(clo_gen_suppressions) <= 2 );
929 /* If we've been asked to emit XML, mash around various other
930 options so as to constrain the output somewhat, and to remove
931 any need for user input during the run.
933 if (VG_(clo_xml)) {
935 /* We can't allow --gen-suppressions=yes, since that requires us
936 to print the error and then ask the user if she wants a
937 suppression for it, but in XML mode we won't print it until
938 we know whether we also need to print a suppression. Hence a
939 circular dependency. So disallow this.
940 (--gen-suppressions=all is still OK since we don't need any
941 user interaction in this case.) */
942 if (VG_(clo_gen_suppressions) == 1) {
943 VG_(fmsg_bad_option)(
944 "--xml=yes together with --gen-suppressions=yes",
945 "When --xml=yes is specified, --gen-suppressions=no\n"
946 "or --gen-suppressions=all is allowed, but not "
947 "--gen-suppressions=yes.\n");
950 /* We can't allow DB attaching (or we maybe could, but results
951 could be chaotic ..) since it requires user input. Hence
952 disallow. */
953 if (VG_(clo_db_attach)) {
954 VG_(fmsg_bad_option)(
955 "--xml=yes together with --db-attach=yes",
956 "--db-attach=yes is not allowed with --xml=yes\n"
957 "because it would require user input.\n");
960 /* Disallow dump_error in XML mode; sounds like a recipe for
961 chaos. No big deal; dump_error is a flag for debugging V
962 itself. */
963 if (VG_(clo_dump_error) > 0) {
964 VG_(fmsg_bad_option)("--xml=yes together with --dump-error", "");
967 /* Disable error limits (this might be a bad idea!) */
968 VG_(clo_error_limit) = False;
969 /* Disable emulation warnings */
971 /* Also, we want to set options for the leak checker, but that
972 will have to be done in Memcheck's flag-handling code, not
973 here. */
976 /* All non-logging-related options have been checked. If the logging
977 option specified is ok, we can switch to it, as we know we won't
978 have to generate any other command-line-related error messages.
979 (So far we should be still attached to stderr, so we can show on
980 the terminal any problems to do with processing command line
981 opts.)
983 So set up logging now. After this is done, VG_(log_output_sink)
984 and (if relevant) VG_(xml_output_sink) should be connected to
985 whatever sink has been selected, and we indiscriminately chuck
986 stuff into it without worrying what the nature of it is. Oh the
987 wonder of Unix streams. */
989 vg_assert(VG_(log_output_sink).fd == 2 /* stderr */);
990 vg_assert(VG_(log_output_sink).is_socket == False);
991 vg_assert(VG_(clo_log_fname_expanded) == NULL);
993 vg_assert(VG_(xml_output_sink).fd == -1 /* disabled */);
994 vg_assert(VG_(xml_output_sink).is_socket == False);
995 vg_assert(VG_(clo_xml_fname_expanded) == NULL);
997 /* --- set up the normal text output channel --- */
999 switch (log_to) {
1001 case VgLogTo_Fd:
1002 vg_assert(log_fsname_unexpanded == NULL);
1003 break;
1005 case VgLogTo_File: {
1006 HChar* logfilename;
1008 vg_assert(log_fsname_unexpanded != NULL);
1009 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
1011 // Nb: we overwrite an existing file of this name without asking
1012 // any questions.
1013 logfilename = VG_(expand_file_name)("--log-file",
1014 log_fsname_unexpanded);
1015 sres = VG_(open)(logfilename,
1016 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
1017 VKI_S_IRUSR|VKI_S_IWUSR);
1018 if (!sr_isError(sres)) {
1019 tmp_log_fd = sr_Res(sres);
1020 VG_(clo_log_fname_expanded) = logfilename;
1021 } else {
1022 VG_(fmsg)("can't create log file '%s': %s\n",
1023 logfilename, VG_(strerror)(sr_Err(sres)));
1024 VG_(exit)(1);
1025 /*NOTREACHED*/
1027 break;
1030 case VgLogTo_Socket: {
1031 vg_assert(log_fsname_unexpanded != NULL);
1032 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
1033 tmp_log_fd = VG_(connect_via_socket)( log_fsname_unexpanded );
1034 if (tmp_log_fd == -1) {
1035 VG_(fmsg)("Invalid --log-socket spec of '%s'\n",
1036 log_fsname_unexpanded);
1037 VG_(exit)(1);
1038 /*NOTREACHED*/
1040 if (tmp_log_fd == -2) {
1041 VG_(umsg)("failed to connect to logging server '%s'.\n"
1042 "Log messages will sent to stderr instead.\n",
1043 log_fsname_unexpanded );
1045 /* We don't change anything here. */
1046 vg_assert(VG_(log_output_sink).fd == 2);
1047 tmp_log_fd = 2;
1048 } else {
1049 vg_assert(tmp_log_fd > 0);
1050 VG_(log_output_sink).is_socket = True;
1052 break;
1056 /* --- set up the XML output channel --- */
1058 switch (xml_to) {
1060 case VgLogTo_Fd:
1061 vg_assert(xml_fsname_unexpanded == NULL);
1062 break;
1064 case VgLogTo_File: {
1065 HChar* xmlfilename;
1067 vg_assert(xml_fsname_unexpanded != NULL);
1068 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
1070 // Nb: we overwrite an existing file of this name without asking
1071 // any questions.
1072 xmlfilename = VG_(expand_file_name)("--xml-file",
1073 xml_fsname_unexpanded);
1074 sres = VG_(open)(xmlfilename,
1075 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
1076 VKI_S_IRUSR|VKI_S_IWUSR);
1077 if (!sr_isError(sres)) {
1078 tmp_xml_fd = sr_Res(sres);
1079 VG_(clo_xml_fname_expanded) = xmlfilename;
1080 *xml_fname_unexpanded = xml_fsname_unexpanded;
1081 } else {
1082 VG_(fmsg)("can't create XML file '%s': %s\n",
1083 xmlfilename, VG_(strerror)(sr_Err(sres)));
1084 VG_(exit)(1);
1085 /*NOTREACHED*/
1087 break;
1090 case VgLogTo_Socket: {
1091 vg_assert(xml_fsname_unexpanded != NULL);
1092 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
1093 tmp_xml_fd = VG_(connect_via_socket)( xml_fsname_unexpanded );
1094 if (tmp_xml_fd == -1) {
1095 VG_(fmsg)("Invalid --xml-socket spec of '%s'\n",
1096 xml_fsname_unexpanded );
1097 VG_(exit)(1);
1098 /*NOTREACHED*/
1100 if (tmp_xml_fd == -2) {
1101 VG_(umsg)("failed to connect to XML logging server '%s'.\n"
1102 "XML output will sent to stderr instead.\n",
1103 xml_fsname_unexpanded);
1104 /* We don't change anything here. */
1105 vg_assert(VG_(xml_output_sink).fd == 2);
1106 tmp_xml_fd = 2;
1107 } else {
1108 vg_assert(tmp_xml_fd > 0);
1109 VG_(xml_output_sink).is_socket = True;
1111 break;
1115 /* If we've got this far, and XML mode was requested, but no XML
1116 output channel appears to have been specified, just stop. We
1117 could continue, and XML output will simply vanish into nowhere,
1118 but that is likely to confuse the hell out of users, which is
1119 distinctly Ungood. */
1120 if (VG_(clo_xml) && tmp_xml_fd == -1) {
1121 VG_(fmsg_bad_option)(
1122 "--xml=yes, but no XML destination specified",
1123 "--xml=yes has been specified, but there is no XML output\n"
1124 "destination. You must specify an XML output destination\n"
1125 "using --xml-fd, --xml-file or --xml-socket.\n"
1129 // Finalise the output fds: the log fd ..
1131 if (tmp_log_fd >= 0) {
1132 // Move log_fd into the safe range, so it doesn't conflict with
1133 // any app fds.
1134 tmp_log_fd = VG_(fcntl)(tmp_log_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
1135 if (tmp_log_fd < 0) {
1136 VG_(message)(Vg_UserMsg, "valgrind: failed to move logfile fd "
1137 "into safe range, using stderr\n");
1138 VG_(log_output_sink).fd = 2; // stderr
1139 VG_(log_output_sink).is_socket = False;
1140 } else {
1141 VG_(log_output_sink).fd = tmp_log_fd;
1142 VG_(fcntl)(VG_(log_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
1144 } else {
1145 // If they said --log-fd=-1, don't print anything. Plausible for use in
1146 // regression testing suites that use client requests to count errors.
1147 VG_(log_output_sink).fd = -1;
1148 VG_(log_output_sink).is_socket = False;
1151 // Finalise the output fds: and the XML fd ..
1153 if (tmp_xml_fd >= 0) {
1154 // Move xml_fd into the safe range, so it doesn't conflict with
1155 // any app fds.
1156 tmp_xml_fd = VG_(fcntl)(tmp_xml_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
1157 if (tmp_xml_fd < 0) {
1158 VG_(message)(Vg_UserMsg, "valgrind: failed to move XML file fd "
1159 "into safe range, using stderr\n");
1160 VG_(xml_output_sink).fd = 2; // stderr
1161 VG_(xml_output_sink).is_socket = False;
1162 } else {
1163 VG_(xml_output_sink).fd = tmp_xml_fd;
1164 VG_(fcntl)(VG_(xml_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
1166 } else {
1167 // If they said --xml-fd=-1, don't print anything. Plausible for use in
1168 // regression testing suites that use client requests to count errors.
1169 VG_(xml_output_sink).fd = -1;
1170 VG_(xml_output_sink).is_socket = False;
1173 // Suppressions related stuff
1175 if (VG_(clo_default_supp) &&
1176 (VG_(needs).core_errors || VG_(needs).tool_errors)) {
1177 /* If we haven't reached the max number of suppressions, load
1178 the default one. */
1179 static const HChar default_supp[] = "default.supp";
1180 Int len = VG_(strlen)(VG_(libdir)) + 1 + sizeof(default_supp);
1181 HChar *buf = VG_(malloc)("main.mpclo.3", len);
1182 VG_(sprintf)(buf, "%s/%s", VG_(libdir), default_supp);
1183 VG_(addToXA)(VG_(clo_suppressions), &buf);
1186 *logging_to_fd = log_to == VgLogTo_Fd || log_to == VgLogTo_Socket;
1189 // Write the name and value of log file qualifiers to the xml file.
1190 // We can safely assume here that the format string is well-formed.
1191 // It has been checked earlier in VG_(expand_file_name) when processing
1192 // command line options.
1193 static void print_file_vars(const HChar* format)
1195 Int i = 0;
1197 while (format[i]) {
1198 if (format[i] == '%') {
1199 // We saw a '%'. What's next...
1200 i++;
1201 if ('q' == format[i]) {
1202 i++;
1203 if ('{' == format[i]) {
1204 // Get the env var name, print its contents.
1205 HChar* qual;
1206 Int begin_qualname = ++i;
1207 while (True) {
1208 if ('}' == format[i]) {
1209 Int qualname_len = i - begin_qualname;
1210 HChar qualname[qualname_len + 1];
1211 VG_(strncpy)(qualname, format + begin_qualname,
1212 qualname_len);
1213 qualname[qualname_len] = '\0';
1214 qual = VG_(getenv)(qualname);
1215 i++;
1216 VG_(printf_xml)("<logfilequalifier> <var>%pS</var> "
1217 "<value>%pS</value> </logfilequalifier>\n",
1218 qualname, qual);
1219 break;
1221 i++;
1225 } else {
1226 i++;
1232 /*====================================================================*/
1233 /*=== Printing the preamble ===*/
1234 /*====================================================================*/
1236 // Print the argument, escaping any chars that require it.
1237 static void umsg_arg(const HChar* arg)
1239 SizeT len = VG_(strlen)(arg);
1240 const HChar* special = " \\<>";
1241 Int i;
1242 for (i = 0; i < len; i++) {
1243 if (VG_(strchr)(special, arg[i])) {
1244 VG_(umsg)("\\"); // escape with a backslash if necessary
1246 VG_(umsg)("%c", arg[i]);
1250 // Send output to the XML-stream and escape any XML meta-characters.
1251 static void xml_arg(const HChar* arg)
1253 VG_(printf_xml)("%pS", arg);
1256 /* Ok, the logging sink is running now. Print a suitable preamble.
1257 If logging to file or a socket, write details of parent PID and
1258 command line args, to help people trying to interpret the
1259 results of a run which encompasses multiple processes. */
1260 static void print_preamble ( Bool logging_to_fd,
1261 const HChar* xml_fname_unexpanded,
1262 const HChar* toolname )
1264 Int i;
1265 const HChar* xpre = VG_(clo_xml) ? " <line>" : "";
1266 const HChar* xpost = VG_(clo_xml) ? "</line>" : "";
1267 UInt (*umsg_or_xml)( const HChar*, ... )
1268 = VG_(clo_xml) ? VG_(printf_xml) : VG_(umsg);
1270 void (*umsg_or_xml_arg)( const HChar* )
1271 = VG_(clo_xml) ? xml_arg : umsg_arg;
1273 vg_assert( VG_(args_for_client) );
1274 vg_assert( VG_(args_for_valgrind) );
1275 vg_assert( toolname );
1277 if (VG_(clo_xml)) {
1278 VG_(printf_xml)("<?xml version=\"1.0\"?>\n");
1279 VG_(printf_xml)("\n");
1280 VG_(printf_xml)("<valgrindoutput>\n");
1281 VG_(printf_xml)("\n");
1282 VG_(printf_xml)("<protocolversion>4</protocolversion>\n");
1283 VG_(printf_xml)("<protocoltool>%s</protocoltool>\n", toolname);
1284 VG_(printf_xml)("\n");
1287 if (VG_(clo_xml) || VG_(clo_verbosity > 0)) {
1289 if (VG_(clo_xml))
1290 VG_(printf_xml)("<preamble>\n");
1292 /* Tool details */
1293 umsg_or_xml( VG_(clo_xml) ? "%s%pS%pS%pS, %pS%s\n" : "%s%s%s%s, %s%s\n",
1294 xpre,
1295 VG_(details).name,
1296 NULL == VG_(details).version ? "" : "-",
1297 NULL == VG_(details).version
1298 ? "" : VG_(details).version,
1299 VG_(details).description,
1300 xpost );
1302 if (VG_(strlen)(toolname) >= 4 && VG_STREQN(4, toolname, "exp-")) {
1303 umsg_or_xml(
1304 "%sNOTE: This is an Experimental-Class Valgrind Tool%s\n",
1305 xpre, xpost
1309 umsg_or_xml( VG_(clo_xml) ? "%s%pS%s\n" : "%s%s%s\n",
1310 xpre, VG_(details).copyright_author, xpost );
1312 /* Core details */
1313 umsg_or_xml(
1314 "%sUsing Valgrind-%s and LibVEX; rerun with -h for copyright info%s\n",
1315 xpre, VERSION, xpost
1318 // Print the command line. At one point we wrapped at 80 chars and
1319 // printed a '\' as a line joiner, but that makes it hard to cut and
1320 // paste the command line (because of the "==pid==" prefixes), so we now
1321 // favour utility and simplicity over aesthetics.
1322 umsg_or_xml("%sCommand: ", xpre);
1323 umsg_or_xml_arg(VG_(args_the_exename));
1325 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1326 HChar* s = *(HChar**)VG_(indexXA)( VG_(args_for_client), i );
1327 umsg_or_xml(" ");
1328 umsg_or_xml_arg(s);
1330 umsg_or_xml("%s\n", xpost);
1332 if (VG_(clo_xml))
1333 VG_(printf_xml)("</preamble>\n");
1336 // Print the parent PID, and other stuff, if necessary.
1337 if (!VG_(clo_xml) && VG_(clo_verbosity) > 0 && !logging_to_fd) {
1338 VG_(umsg)("Parent PID: %d\n", VG_(getppid)());
1340 else
1341 if (VG_(clo_xml)) {
1342 VG_(printf_xml)("\n");
1343 VG_(printf_xml)("<pid>%d</pid>\n", VG_(getpid)());
1344 VG_(printf_xml)("<ppid>%d</ppid>\n", VG_(getppid)());
1345 VG_(printf_xml)("<tool>%pS</tool>\n", toolname);
1346 if (xml_fname_unexpanded)
1347 print_file_vars(xml_fname_unexpanded);
1348 if (VG_(clo_xml_user_comment)) {
1349 /* Note: the user comment itself is XML and is therefore to
1350 be passed through verbatim (%s) rather than escaped
1351 (%pS). */
1352 VG_(printf_xml)("<usercomment>%s</usercomment>\n",
1353 VG_(clo_xml_user_comment));
1355 VG_(printf_xml)("\n");
1356 VG_(printf_xml)("<args>\n");
1358 VG_(printf_xml)(" <vargv>\n");
1359 if (VG_(name_of_launcher))
1360 VG_(printf_xml)(" <exe>%pS</exe>\n",
1361 VG_(name_of_launcher));
1362 else
1363 VG_(printf_xml)(" <exe>%pS</exe>\n",
1364 "(launcher name unknown)");
1365 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
1366 VG_(printf_xml)(
1367 " <arg>%pS</arg>\n",
1368 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1371 VG_(printf_xml)(" </vargv>\n");
1373 VG_(printf_xml)(" <argv>\n");
1374 VG_(printf_xml)(" <exe>%pS</exe>\n",
1375 VG_(args_the_exename));
1376 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1377 VG_(printf_xml)(
1378 " <arg>%pS</arg>\n",
1379 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1382 VG_(printf_xml)(" </argv>\n");
1384 VG_(printf_xml)("</args>\n");
1387 // Last thing in the preamble is a blank line.
1388 if (VG_(clo_xml))
1389 VG_(printf_xml)("\n");
1390 else if (VG_(clo_verbosity) > 0)
1391 VG_(umsg)("\n");
1393 if (VG_(clo_verbosity) > 1) {
1394 SysRes fd;
1395 VexArch vex_arch;
1396 VexArchInfo vex_archinfo;
1397 if (!logging_to_fd)
1398 VG_(message)(Vg_DebugMsg, "\n");
1399 VG_(message)(Vg_DebugMsg, "Valgrind options:\n");
1400 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
1401 VG_(message)(Vg_DebugMsg,
1402 " %s\n",
1403 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ));
1406 VG_(message)(Vg_DebugMsg, "Contents of /proc/version:\n");
1407 fd = VG_(open) ( "/proc/version", VKI_O_RDONLY, 0 );
1408 if (sr_isError(fd)) {
1409 VG_(message)(Vg_DebugMsg, " can't open /proc/version\n");
1410 } else {
1411 const SizeT bufsiz = 255;
1412 HChar version_buf[bufsiz+1];
1413 VG_(message)(Vg_DebugMsg, " ");
1414 Int n, fdno = sr_Res(fd);
1415 do {
1416 n = VG_(read)(fdno, version_buf, bufsiz);
1417 if (n < 0) {
1418 VG_(message)(Vg_DebugMsg, " error reading /proc/version\n");
1419 break;
1421 version_buf[n] = '\0';
1422 VG_(message)(Vg_DebugMsg, "%s", version_buf);
1423 } while (n == bufsiz);
1424 VG_(message)(Vg_DebugMsg, "\n");
1425 VG_(close)(fdno);
1428 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
1429 VG_(message)(
1430 Vg_DebugMsg,
1431 "Arch and hwcaps: %s, %s, %s\n",
1432 LibVEX_ppVexArch ( vex_arch ),
1433 LibVEX_ppVexEndness ( vex_archinfo.endness ),
1434 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1436 VG_(message)(
1437 Vg_DebugMsg,
1438 "Page sizes: currently %d, max supported %d\n",
1439 (Int)VKI_PAGE_SIZE, (Int)VKI_MAX_PAGE_SIZE
1441 VG_(message)(Vg_DebugMsg,
1442 "Valgrind library directory: %s\n", VG_(libdir));
1447 /*====================================================================*/
1448 /*=== File descriptor setup ===*/
1449 /*====================================================================*/
1451 /* Number of file descriptors that Valgrind tries to reserve for
1452 it's own use - just a small constant. */
1453 #define N_RESERVED_FDS (10)
1455 static void setup_file_descriptors(void)
1457 struct vki_rlimit rl;
1458 Bool show = False;
1460 /* Get the current file descriptor limits. */
1461 if (VG_(getrlimit)(VKI_RLIMIT_NOFILE, &rl) < 0) {
1462 rl.rlim_cur = 1024;
1463 rl.rlim_max = 1024;
1466 # if defined(VGO_darwin)
1467 /* Darwin lies. It reports file max as RLIM_INFINITY but
1468 silently disallows anything bigger than 10240. */
1469 if (rl.rlim_cur >= 10240 && rl.rlim_max == 0x7fffffffffffffffULL) {
1470 rl.rlim_max = 10240;
1472 # endif
1474 if (show)
1475 VG_(printf)("fd limits: host, before: cur %lu max %lu\n",
1476 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
1478 /* Work out where to move the soft limit to. */
1479 if (rl.rlim_cur + N_RESERVED_FDS <= rl.rlim_max) {
1480 rl.rlim_cur = rl.rlim_cur + N_RESERVED_FDS;
1481 } else {
1482 rl.rlim_cur = rl.rlim_max;
1485 /* Reserve some file descriptors for our use. */
1486 VG_(fd_soft_limit) = rl.rlim_cur - N_RESERVED_FDS;
1487 VG_(fd_hard_limit) = rl.rlim_cur - N_RESERVED_FDS;
1489 /* Update the soft limit. */
1490 VG_(setrlimit)(VKI_RLIMIT_NOFILE, &rl);
1492 if (show) {
1493 VG_(printf)("fd limits: host, after: cur %lu max %lu\n",
1494 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
1495 VG_(printf)("fd limits: guest : cur %u max %u\n",
1496 VG_(fd_soft_limit), VG_(fd_hard_limit));
1499 if (VG_(cl_exec_fd) != -1)
1500 VG_(cl_exec_fd) = VG_(safe_fd)( VG_(cl_exec_fd) );
1504 /*====================================================================*/
1505 /*=== main() ===*/
1506 /*====================================================================*/
1508 /* When main() is entered, we should be on the following stack, not
1509 the one the kernel gave us. We will run on this stack until
1510 simulation of the root thread is started, at which point a transfer
1511 is made to a dynamically allocated stack. This is for the sake of
1512 uniform overflow detection for all Valgrind threads. This is
1513 marked global even though it isn't, because assembly code below
1514 needs to reference the name. */
1516 /*static*/ VgStack VG_(interim_stack);
1518 /* These are the structures used to hold info for creating the initial
1519 client image.
1521 'iicii' mostly holds important register state present at system
1522 startup (_start_valgrind). valgrind_main() then fills in the rest
1523 of it and passes it to VG_(ii_create_image)(). That produces
1524 'iifii', which is later handed to VG_(ii_finalise_image). */
1526 /* In all OS-instantiations, the_iicii has a field .sp_at_startup.
1527 This should get some address inside the stack on which we gained
1528 control (eg, it could be the SP at startup). It doesn't matter
1529 exactly where in the stack it is. This value is passed to the
1530 address space manager at startup. On Linux, aspacem then uses it
1531 to identify the initial stack segment and hence the upper end of
1532 the usable address space. */
1534 static IICreateImageInfo the_iicii;
1535 static IIFinaliseImageInfo the_iifii;
1538 /* A simple pair structure, used for conveying debuginfo handles to
1539 calls to VG_TRACK(new_mem_startup, ...). */
1540 typedef struct { Addr a; ULong ull; } Addr_n_ULong;
1543 /* --- Forwards decls to do with shutdown --- */
1545 static void final_tidyup(ThreadId tid);
1547 /* Do everything which needs doing when the last thread exits */
1548 static
1549 void shutdown_actions_NORETURN( ThreadId tid,
1550 VgSchedReturnCode tids_schedretcode );
1552 /* --- end of Forwards decls to do with shutdown --- */
1555 /* By the time we get to valgrind_main, the_iicii should already have
1556 been filled in with any important details as required by whatever
1557 OS we have been built for.
1559 static
1560 Int valgrind_main ( Int argc, HChar **argv, HChar **envp )
1562 const HChar* toolname = "memcheck"; // default to Memcheck
1563 Int need_help = 0; // 0 = no, 1 = --help, 2 = --help-debug
1564 ThreadId tid_main = VG_INVALID_THREADID;
1565 Bool logging_to_fd = False;
1566 const HChar* xml_fname_unexpanded = NULL;
1567 Int loglevel, i;
1568 struct vki_rlimit zero = { 0, 0 };
1569 XArray* addr2dihandle = NULL;
1571 //============================================================
1573 // Nb: startup is complex. Prerequisites are shown at every step.
1574 // *** Be very careful when messing with the order ***
1576 // The first order of business is to get debug logging, the address
1577 // space manager and the dynamic memory manager up and running.
1578 // Once that's done, we can relax a bit.
1580 //============================================================
1582 /* This is needed to make VG_(getenv) usable early. */
1583 VG_(client_envp) = (HChar**)envp;
1585 //--------------------------------------------------------------
1586 // Start up Mach kernel interface, if any
1587 // p: none
1588 //--------------------------------------------------------------
1589 # if defined(VGO_darwin)
1590 VG_(mach_init)();
1591 # endif
1593 //--------------------------------------------------------------
1594 // Start up the logging mechanism
1595 // p: none
1596 //--------------------------------------------------------------
1597 /* Start the debugging-log system ASAP. First find out how many
1598 "-d"s were specified. This is a pre-scan of the command line. Also
1599 get --profile-heap=yes, --core-redzone-size, --redzone-size
1600 --aspace-minaddr which are needed by the time we start up dynamic
1601 memory management. */
1602 loglevel = 0;
1603 for (i = 1; i < argc; i++) {
1604 const HChar* tmp_str;
1605 if (argv[i][0] != '-') break;
1606 if VG_STREQ(argv[i], "--") break;
1607 if VG_STREQ(argv[i], "-d") loglevel++;
1608 if VG_BOOL_CLO(argv[i], "--profile-heap", VG_(clo_profile_heap)) {}
1609 if VG_BINT_CLO(argv[i], "--core-redzone-size", VG_(clo_core_redzone_size),
1610 0, MAX_CLO_REDZONE_SZB) {}
1611 if VG_BINT_CLO(argv[i], "--redzone-size", VG_(clo_redzone_size),
1612 0, MAX_CLO_REDZONE_SZB) {}
1613 if VG_STR_CLO(argv[i], "--aspace-minaddr", tmp_str) {
1614 # if VG_WORDSIZE == 4
1615 const Addr max = (Addr) 0x40000000; // 1Gb
1616 # else
1617 const Addr max = (Addr) 0x200000000; // 8Gb
1618 # endif
1619 Bool ok = VG_(parse_Addr) (&tmp_str, &VG_(clo_aspacem_minAddr));
1620 if (!ok)
1621 VG_(fmsg_bad_option)(argv[i], "Invalid address\n");
1623 if (!VG_IS_PAGE_ALIGNED(VG_(clo_aspacem_minAddr))
1624 || VG_(clo_aspacem_minAddr) < (Addr) 0x1000
1625 || VG_(clo_aspacem_minAddr) > max) // 1Gb
1626 VG_(fmsg_bad_option)(argv[i],
1627 "Must be a page aligned address between "
1628 "0x1000 and 0x%lx\n", max);
1632 /* ... and start the debug logger. Now we can safely emit logging
1633 messages all through startup. */
1634 VG_(debugLog_startup)(loglevel, "Stage 2 (main)");
1635 VG_(debugLog)(1, "main", "Welcome to Valgrind version "
1636 VERSION " debug logging\n");
1638 //--------------------------------------------------------------
1639 // Ensure we're on a plausible stack.
1640 // p: logging
1641 //--------------------------------------------------------------
1642 VG_(debugLog)(1, "main", "Checking current stack is plausible\n");
1643 { HChar* limLo = (HChar*)(&VG_(interim_stack).bytes[0]);
1644 HChar* limHi = limLo + sizeof(VG_(interim_stack));
1645 HChar* volatile
1646 aLocal = (HChar*)&limLo; /* any auto local will do */
1647 /* Re "volatile": Apple clang version 4.0
1648 (tags/Apple/clang-421.0.57) (based on LLVM 3.1svn)" appeared
1649 to miscompile the following check, causing run to abort at
1650 this point (in 64-bit mode) even though aLocal is within limLo
1651 .. limHi. But in fact clang is within its rights to do
1652 strange things here. "The reason is that the comparisons
1653 aLocal < limLo and aLocal >= limHi cause undefined behaviour
1654 (according to c99 6.5.8) because they compare pointers that do
1655 not point into the same aggregate." Adding "volatile" appears
1656 to fix it because "The compiler would have to prove that there
1657 is undefined behavior in order to exploit it. But as a
1658 volatile variable can change its value in ways invisible to
1659 the compiler, the compiler must make the conservative
1660 assumption that it points into the same aggregate as the other
1661 pointer its compared against. I.e. the behaviour is possibly
1662 defined." (Analysis by Florian Krohm). */
1663 if (aLocal < limLo || aLocal >= limHi) {
1664 /* something's wrong. Stop. */
1665 VG_(debugLog)(0, "main", "Root stack %p to %p, a local %p\n",
1666 limLo, limHi, aLocal );
1667 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1668 "Initial stack switched failed.\n");
1669 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1670 VG_(exit)(1);
1674 //--------------------------------------------------------------
1675 // Ensure we have a plausible pointer to the stack on which
1676 // we gained control (not the current stack!)
1677 // p: logging
1678 //--------------------------------------------------------------
1679 VG_(debugLog)(1, "main", "Checking initial stack was noted\n");
1680 if (the_iicii.sp_at_startup == 0) {
1681 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1682 "Initial stack was not noted.\n");
1683 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1684 VG_(exit)(1);
1687 //--------------------------------------------------------------
1688 // Start up the address space manager, and determine the
1689 // approximate location of the client's stack
1690 // p: logging, plausible-stack
1691 //--------------------------------------------------------------
1692 VG_(debugLog)(1, "main", "Starting the address space manager\n");
1693 vg_assert(VKI_PAGE_SIZE == 4096 || VKI_PAGE_SIZE == 65536
1694 || VKI_PAGE_SIZE == 16384);
1695 vg_assert(VKI_MAX_PAGE_SIZE == 4096 || VKI_MAX_PAGE_SIZE == 65536
1696 || VKI_MAX_PAGE_SIZE == 16384);
1697 vg_assert(VKI_PAGE_SIZE <= VKI_MAX_PAGE_SIZE);
1698 vg_assert(VKI_PAGE_SIZE == (1 << VKI_PAGE_SHIFT));
1699 vg_assert(VKI_MAX_PAGE_SIZE == (1 << VKI_MAX_PAGE_SHIFT));
1700 the_iicii.clstack_end = VG_(am_startup)( the_iicii.sp_at_startup );
1701 VG_(debugLog)(1, "main", "Address space manager is running\n");
1703 //--------------------------------------------------------------
1704 // Start up the dynamic memory manager
1705 // p: address space management
1706 // p: getting --profile-heap,--core-redzone-size,--redzone-size
1707 // In fact m_mallocfree is self-initialising, so there's no
1708 // initialisation call to do. Instead, try a simple malloc/
1709 // free pair right now to check that nothing is broken.
1710 //--------------------------------------------------------------
1711 VG_(debugLog)(1, "main", "Starting the dynamic memory manager\n");
1712 { void* p = VG_(malloc)( "main.vm.1", 12345 );
1713 VG_(free)( p );
1715 VG_(debugLog)(1, "main", "Dynamic memory manager is running\n");
1717 //============================================================
1719 // Dynamic memory management is now available.
1721 //============================================================
1723 //--------------------------------------------------------------
1724 // Initialise m_debuginfo
1725 // p: dynamic memory allocation
1726 VG_(debugLog)(1, "main", "Initialise m_debuginfo\n");
1727 VG_(di_initialise)();
1729 //--------------------------------------------------------------
1730 // Look for alternative libdir
1731 { HChar *cp = VG_(getenv)(VALGRIND_LIB);
1732 if (cp != NULL)
1733 VG_(libdir) = cp;
1734 VG_(debugLog)(1, "main", "VG_(libdir) = %s\n", VG_(libdir));
1737 //--------------------------------------------------------------
1738 // Extract the launcher name from the environment.
1739 VG_(debugLog)(1, "main", "Getting launcher's name ...\n");
1740 VG_(name_of_launcher) = VG_(getenv)(VALGRIND_LAUNCHER);
1741 if (VG_(name_of_launcher) == NULL) {
1742 VG_(printf)("valgrind: You cannot run '%s' directly.\n", argv[0]);
1743 VG_(printf)("valgrind: You should use $prefix/bin/valgrind.\n");
1744 VG_(exit)(1);
1746 VG_(debugLog)(1, "main", "... %s\n", VG_(name_of_launcher));
1748 //--------------------------------------------------------------
1749 // Get the current process datasize rlimit, and set it to zero.
1750 // This prevents any internal uses of brk() from having any effect.
1751 // We remember the old value so we can restore it on exec, so that
1752 // child processes will have a reasonable brk value.
1753 VG_(getrlimit)(VKI_RLIMIT_DATA, &VG_(client_rlimit_data));
1754 zero.rlim_max = VG_(client_rlimit_data).rlim_max;
1755 VG_(setrlimit)(VKI_RLIMIT_DATA, &zero);
1757 // Get the current process stack rlimit.
1758 VG_(getrlimit)(VKI_RLIMIT_STACK, &VG_(client_rlimit_stack));
1760 //--------------------------------------------------------------
1761 // Figure out what sort of CPU we're on, and whether it is
1762 // able to run V.
1763 VG_(debugLog)(1, "main", "Get hardware capabilities ...\n");
1764 { VexArch vex_arch;
1765 VexArchInfo vex_archinfo;
1766 Bool ok = VG_(machine_get_hwcaps)();
1767 if (!ok) {
1768 VG_(printf)("\n");
1769 VG_(printf)("valgrind: fatal error: unsupported CPU.\n");
1770 VG_(printf)(" Supported CPUs are:\n");
1771 VG_(printf)(" * x86 (practically any; Pentium-I or above), "
1772 "AMD Athlon or above)\n");
1773 VG_(printf)(" * AMD Athlon64/Opteron\n");
1774 VG_(printf)(" * ARM (armv7)\n");
1775 VG_(printf)(" * PowerPC (most; ppc405 and above)\n");
1776 VG_(printf)(" * System z (64bit only - s390x; z900 and above)\n");
1777 VG_(printf)("\n");
1778 VG_(exit)(1);
1780 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
1781 VG_(debugLog)(
1782 1, "main", "... arch = %s, hwcaps = %s\n",
1783 LibVEX_ppVexArch ( vex_arch ),
1784 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1788 //--------------------------------------------------------------
1789 // Record the working directory at startup
1790 // p: none
1791 VG_(debugLog)(1, "main", "Getting the working directory at startup\n");
1792 { Bool ok = VG_(record_startup_wd)();
1793 if (!ok)
1794 VG_(err_config_error)( "Can't establish current working "
1795 "directory at startup\n");
1797 VG_(debugLog)(1, "main", "... %s\n", VG_(get_startup_wd)() );
1799 //============================================================
1800 // Command line argument handling order:
1801 // * If --help/--help-debug are present, show usage message
1802 // (including the tool-specific usage)
1803 // * (If no --tool option given, default to Memcheck)
1804 // * Then, if client is missing, abort with error msg
1805 // * Then, if any cmdline args are bad, abort with error msg
1806 //============================================================
1808 //--------------------------------------------------------------
1809 // Split up argv into: C args, V args, V extra args, and exename.
1810 // p: dynamic memory allocation
1811 //--------------------------------------------------------------
1812 VG_(debugLog)(1, "main", "Split up command line\n");
1813 VG_(split_up_argv)( argc, argv );
1814 vg_assert( VG_(args_for_valgrind) );
1815 vg_assert( VG_(args_for_client) );
1816 if (0) {
1817 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++)
1818 VG_(printf)(
1819 "varg %s\n",
1820 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1822 VG_(printf)(" exe %s\n", VG_(args_the_exename));
1823 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++)
1824 VG_(printf)(
1825 "carg %s\n",
1826 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1830 //--------------------------------------------------------------
1831 // Extract tool name and whether help has been requested.
1832 // Note we can't print the help message yet, even if requested,
1833 // because the tool has not been initialised.
1834 // p: split_up_argv [for VG_(args_for_valgrind)]
1835 //--------------------------------------------------------------
1836 VG_(debugLog)(1, "main",
1837 "(early_) Process Valgrind's command line options\n");
1838 early_process_cmd_line_options(&need_help, &toolname);
1840 // BEGIN HACK
1841 vg_assert(toolname != NULL);
1842 vg_assert(VG_(clo_read_inline_info) == False);
1843 # if !defined(VGO_darwin)
1844 if (0 == VG_(strcmp)(toolname, "memcheck")
1845 || 0 == VG_(strcmp)(toolname, "helgrind")
1846 || 0 == VG_(strcmp)(toolname, "drd")) {
1847 /* Change the default setting. Later on (just below)
1848 main_process_cmd_line_options should pick up any
1849 user-supplied setting for it and will override the default
1850 set here. */
1851 VG_(clo_read_inline_info) = True;
1853 # endif
1854 // END HACK
1856 // Set default vex control params
1857 LibVEX_default_VexControl(& VG_(clo_vex_control));
1859 //--------------------------------------------------------------
1860 // Load client executable, finding in $PATH if necessary
1861 // p: early_process_cmd_line_options() [for 'exec', 'need_help',
1862 // clo_max_stackframe,
1863 // clo_main_stacksize]
1864 // p: layout_remaining_space [so there's space]
1866 // Set up client's environment
1867 // p: set-libdir [for VG_(libdir)]
1868 // p: early_process_cmd_line_options [for toolname]
1870 // Setup client stack, eip, and VG_(client_arg[cv])
1871 // p: load_client() [for 'info']
1872 // p: fix_environment() [for 'env']
1874 // Setup client data (brk) segment. Initially a 1-page segment
1875 // which abuts a shrinkable reservation.
1876 // p: load_client() [for 'info' and hence VG_(brk_base)]
1878 // p: _start_in_C (for zeroing out the_iicii and putting some
1879 // initial values into it)
1880 //--------------------------------------------------------------
1881 if (!need_help) {
1882 VG_(debugLog)(1, "main", "Create initial image\n");
1884 # if defined(VGO_linux) || defined(VGO_darwin)
1885 the_iicii.argv = argv;
1886 the_iicii.envp = envp;
1887 the_iicii.toolname = toolname;
1888 # else
1889 # error "Unknown platform"
1890 # endif
1892 /* NOTE: this call reads VG_(clo_main_stacksize). */
1893 the_iifii = VG_(ii_create_image)( the_iicii );
1896 //==============================================================
1898 // Finished loading/setting up the client address space.
1900 //==============================================================
1902 //--------------------------------------------------------------
1903 // setup file descriptors
1904 // p: n/a
1905 //--------------------------------------------------------------
1906 VG_(debugLog)(1, "main", "Setup file descriptors\n");
1907 setup_file_descriptors();
1909 //--------------------------------------------------------------
1910 // create fake /proc/<pid>/cmdline and /proc/<pid>/auxv files
1911 // and then unlink them, but hold onto the fds, so we can handr
1912 // them out to the client when it tries to open
1913 // /proc/<pid>/cmdline or /proc/<pid>/auxv for itself.
1914 // p: setup file descriptors
1915 // p: ii_create_image for VG_(client_auxv) setup.
1916 //--------------------------------------------------------------
1917 #if !defined(VGO_linux)
1918 // client shouldn't be using /proc!
1919 VG_(cl_cmdline_fd) = -1;
1920 VG_(cl_auxv_fd) = -1;
1921 #else
1922 if (!need_help) {
1923 HChar buf[50]; // large enough
1924 HChar buf2[VG_(mkstemp_fullname_bufsz)(sizeof buf - 1)];
1925 HChar nul[1];
1926 Int fd, r;
1927 const HChar* exename;
1929 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/cmdline\n");
1931 VG_(sprintf)(buf, "proc_%d_cmdline", VG_(getpid)());
1932 fd = VG_(mkstemp)( buf, buf2 );
1933 if (fd == -1)
1934 VG_(err_config_error)("Can't create client cmdline file in %s\n", buf2);
1936 nul[0] = 0;
1937 exename = VG_(args_the_exename);
1938 VG_(write)(fd, exename, VG_(strlen)( exename ));
1939 VG_(write)(fd, nul, 1);
1941 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1942 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i );
1943 VG_(write)(fd, arg, VG_(strlen)( arg ));
1944 VG_(write)(fd, nul, 1);
1947 /* Don't bother to seek the file back to the start; instead do
1948 it every time a copy of it is given out (by PRE(sys_open)).
1949 That is probably more robust across fork() etc. */
1951 /* Now delete it, but hang on to the fd. */
1952 r = VG_(unlink)( buf2 );
1953 if (r)
1954 VG_(err_config_error)("Can't delete client cmdline file in %s\n", buf2);
1956 VG_(cl_cmdline_fd) = fd;
1958 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/auxv\n");
1960 VG_(sprintf)(buf, "proc_%d_auxv", VG_(getpid)());
1961 fd = VG_(mkstemp)( buf, buf2 );
1962 if (fd == -1)
1963 VG_(err_config_error)("Can't create client auxv file in %s\n", buf2);
1965 UWord *client_auxv = VG_(client_auxv);
1966 unsigned int client_auxv_len = 0;
1967 while (*client_auxv != 0) {
1968 client_auxv++;
1969 client_auxv++;
1970 client_auxv_len += 2 * sizeof(UWord);
1972 client_auxv_len += 2 * sizeof(UWord);
1974 VG_(write)(fd, VG_(client_auxv), client_auxv_len);
1976 /* Don't bother to seek the file back to the start; instead do
1977 it every time a copy of it is given out (by PRE(sys_open)).
1978 That is probably more robust across fork() etc. */
1980 /* Now delete it, but hang on to the fd. */
1981 r = VG_(unlink)( buf2 );
1982 if (r)
1983 VG_(err_config_error)("Can't delete client auxv file in %s\n", buf2);
1985 VG_(cl_auxv_fd) = fd;
1987 #endif
1989 //--------------------------------------------------------------
1990 // Init tool part 1: pre_clo_init
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", "Initialise the tool part 1 (pre_clo_init)\n");
1995 VG_(tl_pre_clo_init)();
1996 // Activate var info readers, if the tool asked for it:
1997 if (VG_(needs).var_info)
1998 VG_(clo_read_var_info) = True;
2000 //--------------------------------------------------------------
2001 // If --tool and --help/--help-debug was given, now give the core+tool
2002 // help message
2003 // p: early_process_cmd_line_options() [for 'need_help']
2004 // p: tl_pre_clo_init [for 'VG_(tdict).usage']
2005 //--------------------------------------------------------------
2006 VG_(debugLog)(1, "main", "Print help and quit, if requested\n");
2007 if (need_help) {
2008 usage_NORETURN(/*--help-debug?*/need_help >= 2);
2011 //--------------------------------------------------------------
2012 // Process command line options to Valgrind + tool
2013 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
2014 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
2015 //--------------------------------------------------------------
2016 VG_(debugLog)(1, "main",
2017 "(main_) Process Valgrind's command line options, "
2018 "setup logging\n");
2019 main_process_cmd_line_options ( &logging_to_fd, &xml_fname_unexpanded,
2020 toolname );
2022 //--------------------------------------------------------------
2023 // Zeroise the millisecond counter by doing a first read of it.
2024 // p: none
2025 //--------------------------------------------------------------
2026 (void) VG_(read_millisecond_timer)();
2028 //--------------------------------------------------------------
2029 // Print the preamble
2030 // p: tl_pre_clo_init [for 'VG_(details).name' and friends]
2031 // p: main_process_cmd_line_options()
2032 // [for VG_(clo_verbosity), VG_(clo_xml),
2033 // logging_to_fd, xml_fname_unexpanded]
2034 //--------------------------------------------------------------
2035 VG_(debugLog)(1, "main", "Print the preamble...\n");
2036 print_preamble(logging_to_fd, xml_fname_unexpanded, toolname);
2037 VG_(debugLog)(1, "main", "...finished the preamble\n");
2039 //--------------------------------------------------------------
2040 // Init tool part 2: post_clo_init
2041 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
2042 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
2043 // p: print_preamble() [so any warnings printed in post_clo_init
2044 // are shown after the preamble]
2045 //--------------------------------------------------------------
2046 VG_(debugLog)(1, "main", "Initialise the tool part 2 (post_clo_init)\n");
2047 VG_TDICT_CALL(tool_post_clo_init);
2049 /* The tool's "needs" will by now be finalised, since it has no
2050 further opportunity to specify them. So now sanity check
2051 them. */
2052 const HChar* s;
2053 Bool ok;
2054 ok = VG_(sanity_check_needs)( &s );
2055 if (!ok) {
2056 VG_(core_panic)(s);
2060 //--------------------------------------------------------------
2061 // Initialise translation table and translation cache
2062 // p: aspacem [??]
2063 // p: tl_pre_clo_init [for 'VG_(details).avg_translation_sizeB']
2064 //--------------------------------------------------------------
2065 VG_(debugLog)(1, "main", "Initialise TT/TC\n");
2066 VG_(init_tt_tc)();
2068 //--------------------------------------------------------------
2069 // Initialise the redirect table.
2070 // p: init_tt_tc [so it can call VG_(search_transtab) safely]
2071 // p: aspacem [so can change ownership of sysinfo pages]
2072 //--------------------------------------------------------------
2073 VG_(debugLog)(1, "main", "Initialise redirects\n");
2074 VG_(redir_initialise)();
2076 //--------------------------------------------------------------
2077 // Allow GDB attach
2078 // p: main_process_cmd_line_options() [for VG_(clo_wait_for_gdb)]
2079 //--------------------------------------------------------------
2080 /* Hook to delay things long enough so we can get the pid and
2081 attach GDB in another shell. */
2082 if (VG_(clo_wait_for_gdb)) {
2083 ULong iters, q;
2084 VG_(debugLog)(1, "main", "Wait for GDB\n");
2085 VG_(printf)("pid=%d, entering delay loop\n", VG_(getpid)());
2087 # if defined(VGP_x86_linux)
2088 iters = 10;
2089 # elif defined(VGP_amd64_linux) || defined(VGP_ppc64be_linux) \
2090 || defined(VGP_ppc64le_linux)
2091 iters = 10;
2092 # elif defined(VGP_ppc32_linux)
2093 iters = 5;
2094 # elif defined(VGP_arm_linux)
2095 iters = 5;
2096 # elif defined(VGP_arm64_linux)
2097 iters = 5;
2098 # elif defined(VGP_s390x_linux)
2099 iters = 10;
2100 # elif defined(VGP_mips32_linux) || defined(VGP_mips64_linux)
2101 iters = 10;
2102 # elif defined(VGO_darwin)
2103 iters = 3;
2104 # else
2105 # error "Unknown plat"
2106 # endif
2108 iters *= 1000ULL * 1000 * 1000;
2109 for (q = 0; q < iters; q++)
2110 __asm__ __volatile__("" ::: "memory","cc");
2113 //--------------------------------------------------------------
2114 // Search for file descriptors that are inherited from our parent
2115 // p: main_process_cmd_line_options [for VG_(clo_track_fds)]
2116 //--------------------------------------------------------------
2117 if (VG_(clo_track_fds)) {
2118 VG_(debugLog)(1, "main", "Init preopened fds\n");
2119 VG_(init_preopened_fds)();
2122 //--------------------------------------------------------------
2123 // Load debug info for the existing segments.
2124 // p: setup_code_redirect_table [so that redirs can be recorded]
2125 // p: mallocfree
2126 // p: probably: setup fds and process CLOs, so that logging works
2127 // p: initialise m_debuginfo
2129 // While doing this, make a note of the debuginfo-handles that
2130 // come back from VG_(di_notify_mmap).
2131 // Later, in "Tell the tool about the initial client memory permissions"
2132 // (just below) we can then hand these handles off to the tool in
2133 // calls to VG_TRACK(new_mem_startup, ...). This gives the tool the
2134 // opportunity to make further queries to m_debuginfo before the
2135 // client is started, if it wants. We put this information into an
2136 // XArray, each handle along with the associated segment start address,
2137 // and search the XArray for the handles later, when calling
2138 // VG_TRACK(new_mem_startup, ...).
2139 //--------------------------------------------------------------
2140 VG_(debugLog)(1, "main", "Load initial debug info\n");
2142 vg_assert(!addr2dihandle);
2143 addr2dihandle = VG_(newXA)( VG_(malloc), "main.vm.2",
2144 VG_(free), sizeof(Addr_n_ULong) );
2146 # if defined(VGO_linux)
2147 { Addr* seg_starts;
2148 Int n_seg_starts;
2149 Addr_n_ULong anu;
2151 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
2152 vg_assert(seg_starts && n_seg_starts >= 0);
2154 /* show them all to the debug info reader. allow_SkFileV has to
2155 be True here so that we read info from the valgrind executable
2156 itself. */
2157 for (i = 0; i < n_seg_starts; i++) {
2158 anu.ull = VG_(di_notify_mmap)( seg_starts[i], True/*allow_SkFileV*/,
2159 -1/*Don't use_fd*/);
2160 /* anu.ull holds the debuginfo handle returned by di_notify_mmap,
2161 if any. */
2162 if (anu.ull > 0) {
2163 anu.a = seg_starts[i];
2164 VG_(addToXA)( addr2dihandle, &anu );
2168 VG_(free)( seg_starts );
2170 # elif defined(VGO_darwin)
2171 { Addr* seg_starts;
2172 Int n_seg_starts;
2173 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
2174 vg_assert(seg_starts && n_seg_starts >= 0);
2176 /* show them all to the debug info reader.
2177 Don't read from V segments (unlike Linux) */
2178 // GrP fixme really?
2179 for (i = 0; i < n_seg_starts; i++) {
2180 VG_(di_notify_mmap)( seg_starts[i], False/*don't allow_SkFileV*/,
2181 -1/*don't use_fd*/);
2184 VG_(free)( seg_starts );
2186 # else
2187 # error Unknown OS
2188 # endif
2190 //--------------------------------------------------------------
2191 // Tell aspacem of ownership change of the asm helpers, so that
2192 // m_translate allows them to be translated. However, only do this
2193 // after the initial debug info read, since making a hole in the
2194 // address range for the stage2 binary confuses the debug info reader.
2195 // p: aspacem
2196 //--------------------------------------------------------------
2197 { Bool change_ownership_v_c_OK;
2198 Addr co_start = VG_PGROUNDDN( (Addr)&VG_(trampoline_stuff_start) );
2199 Addr co_endPlus = VG_PGROUNDUP( (Addr)&VG_(trampoline_stuff_end) );
2200 VG_(debugLog)(1,"redir",
2201 "transfer ownership V -> C of 0x%llx .. 0x%llx\n",
2202 (ULong)co_start, (ULong)co_endPlus-1 );
2204 change_ownership_v_c_OK
2205 = VG_(am_change_ownership_v_to_c)( co_start, co_endPlus - co_start );
2206 vg_assert(change_ownership_v_c_OK);
2209 if (VG_(clo_xml)) {
2210 HChar buf[50];
2211 VG_(elapsed_wallclock_time)(buf, sizeof buf);
2212 VG_(printf_xml)( "<status>\n"
2213 " <state>RUNNING</state>\n"
2214 " <time>%pS</time>\n"
2215 "</status>\n",
2216 buf );
2217 VG_(printf_xml)( "\n" );
2220 VG_(init_Threads)();
2222 //--------------------------------------------------------------
2223 // Initialise the scheduler (phase 1) [generates tid_main]
2224 // p: none, afaics
2225 //--------------------------------------------------------------
2226 VG_(debugLog)(1, "main", "Initialise scheduler (phase 1)\n");
2227 tid_main = VG_(scheduler_init_phase1)();
2228 vg_assert(tid_main >= 0 && tid_main < VG_N_THREADS
2229 && tid_main != VG_INVALID_THREADID);
2230 /* Tell the tool about tid_main */
2231 VG_TRACK( pre_thread_ll_create, VG_INVALID_THREADID, tid_main );
2233 //--------------------------------------------------------------
2234 // Tell the tool about the initial client memory permissions
2235 // p: aspacem
2236 // p: mallocfree
2237 // p: setup_client_stack
2238 // p: setup_client_dataseg
2240 // For each segment we tell the client about, look up in
2241 // addr2dihandle as created above, to see if there's a debuginfo
2242 // handle associated with the segment, that we can hand along
2243 // to the tool, to be helpful.
2244 //--------------------------------------------------------------
2245 VG_(debugLog)(1, "main", "Tell tool about initial permissions\n");
2246 { Addr* seg_starts;
2247 Int n_seg_starts;
2249 vg_assert(addr2dihandle);
2251 /* Mark the main thread as running while we tell the tool about
2252 the client memory so that the tool can associate that memory
2253 with the main thread. */
2254 vg_assert(VG_(running_tid) == VG_INVALID_THREADID);
2255 VG_(running_tid) = tid_main;
2257 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
2258 vg_assert(seg_starts && n_seg_starts >= 0);
2260 /* show interesting ones to the tool */
2261 for (i = 0; i < n_seg_starts; i++) {
2262 Word j, n;
2263 NSegment const* seg
2264 = VG_(am_find_nsegment)( seg_starts[i] );
2265 vg_assert(seg);
2266 if (seg->kind == SkFileC || seg->kind == SkAnonC) {
2267 /* This next assertion is tricky. If it is placed
2268 immediately before this 'if', it very occasionally fails.
2269 Why? Because previous iterations of the loop may have
2270 caused tools (via the new_mem_startup calls) to do
2271 dynamic memory allocation, and that may affect the mapped
2272 segments; in particular it may cause segment merging to
2273 happen. Hence we cannot assume that seg_starts[i], which
2274 reflects the state of the world before we started this
2275 loop, is the same as seg->start, as the latter reflects
2276 the state of the world (viz, mappings) at this particular
2277 iteration of the loop.
2279 Why does moving it inside the 'if' make it safe? Because
2280 any dynamic memory allocation done by the tools will
2281 affect only the state of Valgrind-owned segments, not of
2282 Client-owned segments. And the 'if' guards against that
2283 -- we only get in here for Client-owned segments.
2285 In other words: the loop may change the state of
2286 Valgrind-owned segments as it proceeds. But it should
2287 not cause the Client-owned segments to change. */
2288 vg_assert(seg->start == seg_starts[i]);
2289 VG_(debugLog)(2, "main",
2290 "tell tool about %010lx-%010lx %c%c%c\n",
2291 seg->start, seg->end,
2292 seg->hasR ? 'r' : '-',
2293 seg->hasW ? 'w' : '-',
2294 seg->hasX ? 'x' : '-' );
2295 /* search addr2dihandle to see if we have an entry
2296 matching seg->start. */
2297 n = VG_(sizeXA)( addr2dihandle );
2298 for (j = 0; j < n; j++) {
2299 Addr_n_ULong* anl = VG_(indexXA)( addr2dihandle, j );
2300 if (anl->a == seg->start) {
2301 vg_assert(anl->ull > 0); /* check it's a valid handle */
2302 break;
2305 vg_assert(j >= 0 && j <= n);
2306 VG_TRACK( new_mem_startup, seg->start, seg->end+1-seg->start,
2307 seg->hasR, seg->hasW, seg->hasX,
2308 /* and the retrieved debuginfo handle, if any */
2309 j < n
2310 ? ((Addr_n_ULong*)VG_(indexXA)( addr2dihandle, j ))->ull
2311 : 0 );
2315 VG_(free)( seg_starts );
2316 VG_(deleteXA)( addr2dihandle );
2318 /* Also do the initial stack permissions. */
2320 SSizeT inaccessible_len;
2321 NSegment const* seg
2322 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
2323 vg_assert(seg);
2324 vg_assert(seg->kind == SkAnonC);
2325 vg_assert(the_iifii.initial_client_SP >= seg->start);
2326 vg_assert(the_iifii.initial_client_SP <= seg->end);
2328 /* Stuff below the initial SP is unaddressable. Take into
2329 account any ABI-mandated space below the stack pointer that
2330 is required (VG_STACK_REDZONE_SZB). setup_client_stack()
2331 will have allocated an extra page if a red zone is required,
2332 to be on the safe side. */
2333 inaccessible_len = the_iifii.initial_client_SP - VG_STACK_REDZONE_SZB
2334 - seg->start;
2335 vg_assert(inaccessible_len >= 0);
2336 if (inaccessible_len > 0)
2337 VG_TRACK( die_mem_stack,
2338 seg->start,
2339 inaccessible_len );
2340 VG_(debugLog)(2, "main", "mark stack inaccessible %010lx-%010lx\n",
2341 seg->start,
2342 the_iifii.initial_client_SP-1 - VG_STACK_REDZONE_SZB);
2345 /* Also the assembly helpers. */
2346 VG_TRACK( new_mem_startup,
2347 (Addr)&VG_(trampoline_stuff_start),
2348 (Addr)&VG_(trampoline_stuff_end)
2349 - (Addr)&VG_(trampoline_stuff_start),
2350 False, /* readable? */
2351 False, /* writable? */
2352 True /* executable? */,
2353 0 /* di_handle: no associated debug info */ );
2355 /* Clear the running thread indicator */
2356 VG_(running_tid) = VG_INVALID_THREADID;
2357 vg_assert(VG_(running_tid) == VG_INVALID_THREADID);
2359 /* Darwin only: tell the tools where the client's kernel commpage
2360 is. It would be better to do this by telling aspacemgr about
2361 it -- see the now disused record_system_memory() in
2362 initimg-darwin.c -- but that causes the sync checker to fail,
2363 since the mapping doesn't appear in the kernel-supplied
2364 process map. So do it here instead. */
2365 # if defined(VGP_amd64_darwin)
2366 VG_TRACK( new_mem_startup,
2367 0x7fffffe00000, 0x7ffffffff000-0x7fffffe00000,
2368 True, False, True, /* r-x */
2369 0 /* di_handle: no associated debug info */ );
2370 # elif defined(VGP_x86_darwin)
2371 VG_TRACK( new_mem_startup,
2372 0xfffec000, 0xfffff000-0xfffec000,
2373 True, False, True, /* r-x */
2374 0 /* di_handle: no associated debug info */ );
2375 # endif
2378 //--------------------------------------------------------------
2379 // Initialise the scheduler (phase 2)
2380 // p: Initialise the scheduler (phase 1) [for tid_main]
2381 // p: setup_file_descriptors() [else VG_(safe_fd)() breaks]
2382 // p: setup_client_stack
2383 //--------------------------------------------------------------
2384 VG_(debugLog)(1, "main", "Initialise scheduler (phase 2)\n");
2385 { NSegment const* seg
2386 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
2387 vg_assert(seg);
2388 vg_assert(seg->kind == SkAnonC);
2389 vg_assert(the_iifii.initial_client_SP >= seg->start);
2390 vg_assert(the_iifii.initial_client_SP <= seg->end);
2391 VG_(scheduler_init_phase2)( tid_main,
2392 seg->end, the_iifii.clstack_max_size );
2395 //--------------------------------------------------------------
2396 // Set up state for the root thread
2397 // p: ?
2398 // setup_scheduler() [for sched-specific thread 1 stuff]
2399 // VG_(ii_create_image) [for 'the_iicii' initial info]
2400 //--------------------------------------------------------------
2401 VG_(debugLog)(1, "main", "Finalise initial image\n");
2402 VG_(ii_finalise_image)( the_iifii );
2404 //--------------------------------------------------------------
2405 // Initialise the signal handling subsystem
2406 // p: n/a
2407 //--------------------------------------------------------------
2408 // Nb: temporarily parks the saved blocking-mask in saved_sigmask.
2409 VG_(debugLog)(1, "main", "Initialise signal management\n");
2410 /* Check that the kernel-interface signal definitions look sane */
2411 VG_(vki_do_initial_consistency_checks)();
2412 /* .. and go on to use them. */
2413 VG_(sigstartup_actions)();
2415 //--------------------------------------------------------------
2416 // Read suppression file
2417 // p: main_process_cmd_line_options() [for VG_(clo_suppressions)]
2418 //--------------------------------------------------------------
2419 if (VG_(needs).core_errors || VG_(needs).tool_errors) {
2420 VG_(debugLog)(1, "main", "Load suppressions\n");
2421 VG_(load_suppressions)();
2424 //--------------------------------------------------------------
2425 // register client stack
2426 //--------------------------------------------------------------
2427 VG_(clstk_id) = VG_(register_stack)(VG_(clstk_start_base), VG_(clstk_end));
2429 //--------------------------------------------------------------
2430 // Show the address space state so far
2431 //--------------------------------------------------------------
2432 VG_(debugLog)(1, "main", "\n");
2433 VG_(debugLog)(1, "main", "\n");
2434 VG_(am_show_nsegments)(1,"Memory layout at client startup");
2435 VG_(debugLog)(1, "main", "\n");
2436 VG_(debugLog)(1, "main", "\n");
2438 //--------------------------------------------------------------
2439 // Run!
2440 //--------------------------------------------------------------
2441 VG_(debugLog)(1, "main", "Running thread 1\n");
2443 /* As a result of the following call, the last thread standing
2444 eventually winds up running shutdown_actions_NORETURN
2445 just below. Unfortunately, simply exporting said function
2446 causes m_main to be part of a module cycle, which is pretty
2447 nonsensical. So instead of doing that, the address of said
2448 function is stored in a global variable 'owned' by m_syswrap,
2449 and it uses that function pointer to get back here when it needs
2450 to. */
2452 /* Set continuation address. */
2453 VG_(address_of_m_main_shutdown_actions_NORETURN)
2454 = & shutdown_actions_NORETURN;
2456 /* Run the first thread, eventually ending up at the continuation
2457 address. */
2458 VG_(main_thread_wrapper_NORETURN)(1);
2460 /*NOTREACHED*/
2461 vg_assert(0);
2464 /* Do everything which needs doing when the last thread exits or when
2465 a thread exits requesting a complete process exit.
2467 We enter here holding The Lock. For the case VgSrc_ExitProcess we
2468 must never release it, because to do so would allow other threads
2469 to continue after the system is ostensibly shut down. So we must
2470 go to our grave, so to speak, holding the lock.
2472 In fact, there is never any point in releasing the lock at this
2473 point - we have it, we're shutting down the entire system, and
2474 for the case VgSrc_ExitProcess doing so positively causes trouble.
2475 So don't.
2477 The final_tidyup call makes a bit of a nonsense of the ExitProcess
2478 case, since it will run the libc_freeres function, thus allowing
2479 other lurking threads to run again. Hmm. */
2481 static
2482 void shutdown_actions_NORETURN( ThreadId tid,
2483 VgSchedReturnCode tids_schedretcode )
2485 VG_(debugLog)(1, "main", "entering VG_(shutdown_actions_NORETURN)\n");
2486 VG_(am_show_nsegments)(1,"Memory layout at client shutdown");
2488 vg_assert(VG_(is_running_thread)(tid));
2490 vg_assert(tids_schedretcode == VgSrc_ExitThread
2491 || tids_schedretcode == VgSrc_ExitProcess
2492 || tids_schedretcode == VgSrc_FatalSig );
2494 if (tids_schedretcode == VgSrc_ExitThread) {
2496 // We are the last surviving thread. Right?
2497 vg_assert( VG_(count_living_threads)() == 1 );
2499 // Wait for all other threads to exit.
2500 // jrs: Huh? but they surely are already gone
2501 VG_(reap_threads)(tid);
2503 // Clean the client up before the final report
2504 // this causes the libc_freeres function to run
2505 final_tidyup(tid);
2507 /* be paranoid */
2508 vg_assert(VG_(is_running_thread)(tid));
2509 vg_assert(VG_(count_living_threads)() == 1);
2511 } else {
2513 // We may not be the last surviving thread. However, we
2514 // want to shut down the entire process. We hold the lock
2515 // and we need to keep hold of it all the way out, in order
2516 // that none of the other threads ever run again.
2517 vg_assert( VG_(count_living_threads)() >= 1 );
2519 // Clean the client up before the final report
2520 // this causes the libc_freeres function to run
2521 // perhaps this is unsafe, as per comment above
2522 final_tidyup(tid);
2524 /* be paranoid */
2525 vg_assert(VG_(is_running_thread)(tid));
2526 vg_assert(VG_(count_living_threads)() >= 1);
2529 /* Final call to gdbserver, if requested. */
2530 if (VG_(gdbserver_stop_at) (VgdbStopAt_Exit)) {
2531 VG_(umsg)("(action at exit) vgdb me ... \n");
2532 VG_(gdbserver) (tid);
2534 VG_(threads)[tid].status = VgTs_Empty;
2536 //--------------------------------------------------------------
2537 // Finalisation: cleanup, messages, etc. Order not so important, only
2538 // affects what order the messages come.
2539 //--------------------------------------------------------------
2540 // First thing in the post-amble is a blank line.
2541 if (VG_(clo_xml))
2542 VG_(printf_xml)("\n");
2543 else if (VG_(clo_verbosity) > 0)
2544 VG_(message)(Vg_UserMsg, "\n");
2546 if (VG_(clo_xml)) {
2547 HChar buf[50];
2548 VG_(elapsed_wallclock_time)(buf, sizeof buf);
2549 VG_(printf_xml)( "<status>\n"
2550 " <state>FINISHED</state>\n"
2551 " <time>%pS</time>\n"
2552 "</status>\n"
2553 "\n",
2554 buf);
2557 /* Print out file descriptor summary and stats. */
2558 if (VG_(clo_track_fds))
2559 VG_(show_open_fds)("at exit");
2561 /* Call the tool's finalisation function. This makes Memcheck's
2562 leak checker run, and possibly chuck a bunch of leak errors into
2563 the error management machinery. */
2564 VG_TDICT_CALL(tool_fini, 0/*exitcode*/);
2566 /* Show the error counts. */
2567 if (VG_(clo_xml)
2568 && (VG_(needs).core_errors || VG_(needs).tool_errors)) {
2569 VG_(show_error_counts_as_XML)();
2572 /* In XML mode, this merely prints the used suppressions. */
2573 if (VG_(needs).core_errors || VG_(needs).tool_errors)
2574 VG_(show_all_errors)(VG_(clo_verbosity), VG_(clo_xml));
2576 if (VG_(clo_xml)) {
2577 VG_(printf_xml)("\n");
2578 VG_(printf_xml)("</valgrindoutput>\n");
2579 VG_(printf_xml)("\n");
2582 VG_(sanity_check_general)( True /*include expensive checks*/ );
2584 if (VG_(clo_stats))
2585 VG_(print_all_stats)(VG_(clo_verbosity) > 2, /* Memory stats */
2586 False /* tool prints stats in the tool fini */);
2588 /* Show a profile of the heap(s) at shutdown. Optionally, first
2589 throw away all the debug info, as that makes it easy to spot
2590 leaks in the debuginfo reader. */
2591 if (VG_(clo_profile_heap)) {
2592 if (0) VG_(di_discard_ALL_debuginfo)();
2593 VG_(print_arena_cc_analysis)();
2596 /* If profiling has been requested, but with zero interval, it
2597 means "profile at the end of the run only". In which case we
2598 need to dump the profile now. */
2599 if (VG_(clo_profyle_sbs) && VG_(clo_profyle_interval) == 0) {
2600 VG_(get_and_show_SB_profile)(0/*denoting end-of-run*/);
2603 /* Print Vex storage stats */
2604 if (0)
2605 LibVEX_ShowAllocStats();
2607 /* Flush any output cached by previous calls to VG_(message). */
2608 VG_(message_flush)();
2610 /* Terminate gdbserver if ever it was started. We terminate it here
2611 so that it get the output above if output was redirected to
2612 gdb */
2613 VG_(gdbserver_exit) (tid, tids_schedretcode);
2615 /* Ok, finally exit in the os-specific way, according to the scheduler's
2616 return code. In short, if the (last) thread exited by calling
2617 sys_exit, do likewise; if the (last) thread stopped due to a fatal
2618 signal, terminate the entire system with that same fatal signal. */
2619 VG_(debugLog)(1, "core_os",
2620 "VG_(terminate_NORETURN)(tid=%lld)\n", (ULong)tid);
2622 switch (tids_schedretcode) {
2623 case VgSrc_ExitThread: /* the normal way out (Linux) */
2624 case VgSrc_ExitProcess: /* the normal way out (AIX) -- still needed? */
2625 /* Change the application return code to user's return code,
2626 if an error was found */
2627 if (VG_(clo_error_exitcode) > 0
2628 && VG_(get_n_errs_found)() > 0) {
2629 VG_(client_exit)( VG_(clo_error_exitcode) );
2630 } else {
2631 /* otherwise, return the client's exit code, in the normal
2632 way. */
2633 VG_(client_exit)( VG_(threads)[tid].os_state.exitcode );
2635 /* NOT ALIVE HERE! */
2636 VG_(core_panic)("entered the afterlife in main() -- ExitT/P");
2637 break; /* what the hell :) */
2639 case VgSrc_FatalSig:
2640 /* We were killed by a fatal signal, so replicate the effect */
2641 vg_assert(VG_(threads)[tid].os_state.fatalsig != 0);
2642 VG_(kill_self)(VG_(threads)[tid].os_state.fatalsig);
2643 /* we shouldn't be alive at this point. But VG_(kill_self)
2644 sometimes fails with EPERM on Darwin, for unclear reasons. */
2645 # if defined(VGO_darwin)
2646 VG_(debugLog)(0, "main", "VG_(kill_self) failed. Exiting normally.\n");
2647 VG_(exit)(0); /* bogus, but we really need to exit now */
2648 /* fall through .. */
2649 # endif
2650 VG_(core_panic)("main(): signal was supposed to be fatal");
2651 break;
2653 default:
2654 VG_(core_panic)("main(): unexpected scheduler return code");
2658 /* -------------------- */
2660 /* Final clean-up before terminating the process.
2661 Clean up the client by calling __libc_freeres() (if requested)
2662 This is Linux-specific?
2663 GrP fixme glibc-specific, anyway
2665 static void final_tidyup(ThreadId tid)
2667 #if !defined(VGO_darwin)
2668 # if defined(VGP_ppc64be_linux)
2669 Addr r2;
2670 # endif
2671 Addr __libc_freeres_wrapper = VG_(client___libc_freeres_wrapper);
2673 vg_assert(VG_(is_running_thread)(tid));
2675 if ( !VG_(needs).libc_freeres ||
2676 !VG_(clo_run_libc_freeres) ||
2677 0 == __libc_freeres_wrapper )
2678 return; /* can't/won't do it */
2680 # if defined(VGP_ppc64be_linux)
2681 r2 = VG_(get_tocptr)( __libc_freeres_wrapper );
2682 if (r2 == 0) {
2683 VG_(message)(Vg_UserMsg,
2684 "Caught __NR_exit, but can't run __libc_freeres()\n");
2685 VG_(message)(Vg_UserMsg,
2686 " since cannot establish TOC pointer for it.\n");
2687 return;
2689 # endif
2691 if (VG_(clo_verbosity) > 2 ||
2692 VG_(clo_trace_syscalls) ||
2693 VG_(clo_trace_sched))
2694 VG_(message)(Vg_DebugMsg,
2695 "Caught __NR_exit; running __libc_freeres()\n");
2697 /* set thread context to point to libc_freeres_wrapper */
2698 /* ppc64be-linux note: __libc_freeres_wrapper gives us the real
2699 function entry point, not a fn descriptor, so can use it
2700 directly. However, we need to set R2 (the toc pointer)
2701 appropriately. */
2702 VG_(set_IP)(tid, __libc_freeres_wrapper);
2703 # if defined(VGP_ppc64be_linux)
2704 VG_(threads)[tid].arch.vex.guest_GPR2 = r2;
2705 # elif defined(VGP_ppc64le_linux)
2706 /* setting GPR2 but not really needed, GPR12 is needed */
2707 VG_(threads)[tid].arch.vex.guest_GPR2 = __libc_freeres_wrapper;
2708 VG_(threads)[tid].arch.vex.guest_GPR12 = __libc_freeres_wrapper;
2709 # endif
2710 /* mips-linux note: we need to set t9 */
2711 # if defined(VGP_mips32_linux) || defined(VGP_mips64_linux)
2712 VG_(threads)[tid].arch.vex.guest_r25 = __libc_freeres_wrapper;
2713 # endif
2715 /* Block all blockable signals by copying the real block state into
2716 the thread's block state*/
2717 VG_(sigprocmask)(VKI_SIG_BLOCK, NULL, &VG_(threads)[tid].sig_mask);
2718 VG_(threads)[tid].tmp_sig_mask = VG_(threads)[tid].sig_mask;
2720 /* and restore handlers to default */
2721 VG_(set_default_handler)(VKI_SIGSEGV);
2722 VG_(set_default_handler)(VKI_SIGBUS);
2723 VG_(set_default_handler)(VKI_SIGILL);
2724 VG_(set_default_handler)(VKI_SIGFPE);
2726 // We were exiting, so assert that...
2727 vg_assert(VG_(is_exiting)(tid));
2728 // ...but now we're not again
2729 VG_(threads)[tid].exitreason = VgSrc_None;
2731 // run until client thread exits - ideally with LIBC_FREERES_DONE,
2732 // but exit/exitgroup/signal will do
2733 VG_(scheduler)(tid);
2735 vg_assert(VG_(is_exiting)(tid));
2736 #endif
2740 /*====================================================================*/
2741 /*=== Getting to main() alive: LINUX ===*/
2742 /*====================================================================*/
2744 #if defined(VGO_linux)
2746 /* If linking of the final executables is done with glibc present,
2747 then Valgrind starts at main() above as usual, and all of the
2748 following code is irrelevant.
2750 However, this is not the intended mode of use. The plan is to
2751 avoid linking against glibc, by giving gcc the flags
2752 -nodefaultlibs -lgcc -nostartfiles at startup.
2754 From this derive two requirements:
2756 1. gcc may emit calls to memcpy, memmove and memset to deal with
2757 structure assignments etc. Since we have chosen to ignore all the
2758 "normal" supporting libraries, we have to provide our own
2759 implementations of them. No problem.
2761 2. We have to provide a symbol "_start", to which the kernel
2762 hands control at startup. Hence the code below.
2765 /* ---------------- Requirement 1 ---------------- */
2767 void* memcpy(void *dest, const void *src, SizeT n);
2768 void* memcpy(void *dest, const void *src, SizeT n) {
2769 return VG_(memcpy)(dest,src,n);
2771 void* memmove(void *dest, const void *src, SizeT n);
2772 void* memmove(void *dest, const void *src, SizeT n) {
2773 return VG_(memmove)(dest,src,n);
2775 void* memset(void *s, int c, SizeT n);
2776 void* memset(void *s, int c, SizeT n) {
2777 return VG_(memset)(s,c,n);
2780 /* BVA: abort() for those platforms that need it (PPC and ARM). */
2781 void abort(void);
2782 void abort(void){
2783 VG_(printf)("Something called raise().\n");
2784 vg_assert(0);
2787 /* EAZG: ARM's EABI will call floating point exception handlers in
2788 libgcc which boil down to an abort or raise, that's usually defined
2789 in libc. Instead, define them here. */
2790 #if defined(VGP_arm_linux)
2791 void raise(void);
2792 void raise(void){
2793 VG_(printf)("Something called raise().\n");
2794 vg_assert(0);
2797 void __aeabi_unwind_cpp_pr0(void);
2798 void __aeabi_unwind_cpp_pr0(void){
2799 VG_(printf)("Something called __aeabi_unwind_cpp_pr0()\n");
2800 vg_assert(0);
2803 void __aeabi_unwind_cpp_pr1(void);
2804 void __aeabi_unwind_cpp_pr1(void){
2805 VG_(printf)("Something called __aeabi_unwind_cpp_pr1()\n");
2806 vg_assert(0);
2808 #endif
2810 /* ---------------- Requirement 2 ---------------- */
2812 /* Glibc's sysdeps/i386/elf/start.S has the following gem of a
2813 comment, which explains how the stack looks right at process start
2814 (when _start is jumped to). Hence _start passes %esp to
2815 _start_in_C_linux, which extracts argc/argv/envp and starts up
2816 correctly. */
2818 /* This is the canonical entry point, usually the first thing in the text
2819 segment. The SVR4/i386 ABI (pages 3-31, 3-32) says that when the entry
2820 point runs, most registers' values are unspecified, except for:
2822 %edx Contains a function pointer to be registered with `atexit'.
2823 This is how the dynamic linker arranges to have DT_FINI
2824 functions called for shared libraries that have been loaded
2825 before this code runs.
2827 %esp The stack contains the arguments and environment:
2828 0(%esp) argc
2829 4(%esp) argv[0]
2831 (4*argc)(%esp) NULL
2832 (4*(argc+1))(%esp) envp[0]
2834 NULL
2837 /* The kernel hands control to _start, which extracts the initial
2838 stack pointer and calls onwards to _start_in_C_linux. This also switches
2839 the new stack. */
2840 #if defined(VGP_x86_linux)
2841 asm("\n"
2842 ".text\n"
2843 "\t.globl _start\n"
2844 "\t.type _start,@function\n"
2845 "_start:\n"
2846 /* set up the new stack in %eax */
2847 "\tmovl $vgPlain_interim_stack, %eax\n"
2848 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
2849 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
2850 "\tsubl $16, %eax\n"
2851 "\tandl $~15, %eax\n"
2852 /* install it, and collect the original one */
2853 "\txchgl %eax, %esp\n"
2854 /* call _start_in_C_linux, passing it the startup %esp */
2855 "\tpushl %eax\n"
2856 "\tcall _start_in_C_linux\n"
2857 "\thlt\n"
2858 ".previous\n"
2860 #elif defined(VGP_amd64_linux)
2861 asm("\n"
2862 ".text\n"
2863 "\t.globl _start\n"
2864 "\t.type _start,@function\n"
2865 "_start:\n"
2866 /* set up the new stack in %rdi */
2867 "\tmovq $vgPlain_interim_stack, %rdi\n"
2868 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
2869 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
2870 "\tandq $~15, %rdi\n"
2871 /* install it, and collect the original one */
2872 "\txchgq %rdi, %rsp\n"
2873 /* call _start_in_C_linux, passing it the startup %rsp */
2874 "\tcall _start_in_C_linux\n"
2875 "\thlt\n"
2876 ".previous\n"
2878 #elif defined(VGP_ppc32_linux)
2879 asm("\n"
2880 ".text\n"
2881 "\t.globl _start\n"
2882 "\t.type _start,@function\n"
2883 "_start:\n"
2884 /* set up the new stack in r16 */
2885 "\tlis 16,vgPlain_interim_stack@ha\n"
2886 "\tla 16,vgPlain_interim_stack@l(16)\n"
2887 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2888 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2889 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2890 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2891 "\tadd 16,17,16\n"
2892 "\tadd 16,18,16\n"
2893 "\trlwinm 16,16,0,0,27\n"
2894 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2895 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2896 boundary. And r1 is the original SP. Set the SP to r16 and
2897 call _start_in_C_linux, passing it the initial SP. */
2898 "\tmr 3,1\n"
2899 "\tmr 1,16\n"
2900 "\tbl _start_in_C_linux\n"
2901 "\ttrap\n"
2902 ".previous\n"
2904 #elif defined(VGP_ppc64be_linux)
2905 asm("\n"
2906 /* PPC64 ELF ABI says '_start' points to a function descriptor.
2907 So we must have one, and that is what goes into the .opd section. */
2908 "\t.align 2\n"
2909 "\t.global _start\n"
2910 "\t.section \".opd\",\"aw\"\n"
2911 "\t.align 3\n"
2912 "_start:\n"
2913 "\t.quad ._start,.TOC.@tocbase,0\n"
2914 "\t.previous\n"
2915 "\t.type ._start,@function\n"
2916 "\t.global ._start\n"
2917 "._start:\n"
2918 /* set up the new stack in r16 */
2919 "\tlis 16, vgPlain_interim_stack@highest\n"
2920 "\tori 16,16,vgPlain_interim_stack@higher\n"
2921 "\tsldi 16,16,32\n"
2922 "\toris 16,16,vgPlain_interim_stack@h\n"
2923 "\tori 16,16,vgPlain_interim_stack@l\n"
2924 "\txor 17,17,17\n"
2925 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2926 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2927 "\txor 18,18,18\n"
2928 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2929 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2930 "\tadd 16,17,16\n"
2931 "\tadd 16,18,16\n"
2932 "\trldicr 16,16,0,59\n"
2933 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2934 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2935 boundary. And r1 is the original SP. Set the SP to r16 and
2936 call _start_in_C_linux, passing it the initial SP. */
2937 "\tmr 3,1\n"
2938 "\tmr 1,16\n"
2939 "\tlis 14, _start_in_C_linux@highest\n"
2940 "\tori 14,14,_start_in_C_linux@higher\n"
2941 "\tsldi 14,14,32\n"
2942 "\toris 14,14,_start_in_C_linux@h\n"
2943 "\tori 14,14,_start_in_C_linux@l\n"
2944 "\tld 14,0(14)\n"
2945 "\tmtctr 14\n"
2946 "\tbctrl\n"
2947 "\tnop\n"
2948 "\ttrap\n"
2950 #elif defined(VGP_ppc64le_linux)
2951 /* Little Endian uses ELF version 2 but in the future may also
2952 * support other ELF versions.
2954 asm("\n"
2955 "\t.align 2\n"
2956 "\t.global _start\n"
2957 "\t.type _start,@function\n"
2958 "_start:\n"
2959 "#if _CALL_ELF == 2 \n"
2960 "0: addis 2,12,.TOC.-0b@ha\n"
2961 " addi 2,2,.TOC.-0b@l\n"
2962 " .localentry _start, .-_start\n"
2963 "#endif \n"
2964 /* set up the new stack in r16 */
2965 "\tlis 16, vgPlain_interim_stack@highest\n"
2966 "\tori 16,16,vgPlain_interim_stack@higher\n"
2967 "\tsldi 16,16,32\n"
2968 "\toris 16,16,vgPlain_interim_stack@h\n"
2969 "\tori 16,16,vgPlain_interim_stack@l\n"
2970 "\txor 17,17,17\n"
2971 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2972 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2973 "\txor 18,18,18\n"
2974 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2975 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2976 "\tadd 16,17,16\n"
2977 "\tadd 16,18,16\n"
2978 "\trldicr 16,16,0,59\n"
2979 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2980 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2981 boundary. And r1 is the original SP. Set the SP to r16 and
2982 call _start_in_C_linux, passing it the initial SP. */
2983 "\tmr 3,1\n"
2984 "\tmr 1,16\n"
2985 "\tlis 14, _start_in_C_linux@highest\n"
2986 "\tori 14,14,_start_in_C_linux@higher\n"
2987 "\tsldi 14,14,32\n"
2988 "\toris 14,14,_start_in_C_linux@h\n"
2989 "\tori 14,14,_start_in_C_linux@l\n"
2990 "\tmtctr 14\n"
2991 "\tbctrl\n"
2992 "\tnop\n"
2993 "\ttrap\n"
2995 #elif defined(VGP_s390x_linux)
2997 This is the canonical entry point, usually the first thing in the text
2998 segment. Most registers' values are unspecified, except for:
3000 %r14 Contains a function pointer to be registered with `atexit'.
3001 This is how the dynamic linker arranges to have DT_FINI
3002 functions called for shared libraries that have been loaded
3003 before this code runs.
3005 %r15 The stack contains the arguments and environment:
3006 0(%r15) argc
3007 8(%r15) argv[0]
3009 (8*argc)(%r15) NULL
3010 (8*(argc+1))(%r15) envp[0]
3012 NULL
3014 asm("\n\t"
3015 ".text\n\t"
3016 ".globl _start\n\t"
3017 ".type _start,@function\n\t"
3018 "_start:\n\t"
3019 /* set up the new stack in %r1 */
3020 "larl %r1, vgPlain_interim_stack\n\t"
3021 "larl %r5, 1f\n\t"
3022 "ag %r1, 0(%r5)\n\t"
3023 "ag %r1, 2f-1f(%r5)\n\t"
3024 "nill %r1, 0xFFF0\n\t"
3025 /* install it, and collect the original one */
3026 "lgr %r2, %r15\n\t"
3027 "lgr %r15, %r1\n\t"
3028 /* call _start_in_C_linux, passing it the startup %r15 */
3029 "brasl %r14, _start_in_C_linux\n\t"
3030 /* trigger execution of an invalid opcode -> halt machine */
3031 "j .+2\n\t"
3032 "1: .quad "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n\t"
3033 "2: .quad "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n\t"
3034 ".previous\n"
3036 #elif defined(VGP_arm_linux)
3037 asm("\n"
3038 "\t.text\n"
3039 "\t.align 4\n"
3040 "\t.type _start,#function\n"
3041 "\t.global _start\n"
3042 "_start:\n"
3043 "\tldr r0, [pc, #36]\n"
3044 "\tldr r1, [pc, #36]\n"
3045 "\tadd r0, r1, r0\n"
3046 "\tldr r1, [pc, #32]\n"
3047 "\tadd r0, r1, r0\n"
3048 "\tmvn r1, #15\n"
3049 "\tand r0, r0, r1\n"
3050 "\tmov r1, sp\n"
3051 "\tmov sp, r0\n"
3052 "\tmov r0, r1\n"
3053 "\tb _start_in_C_linux\n"
3054 "\t.word vgPlain_interim_stack\n"
3055 "\t.word "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
3056 "\t.word "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
3058 #elif defined(VGP_arm64_linux)
3059 asm("\n"
3060 "\t.text\n"
3061 "\t.align 2\n"
3062 "\t.type _start,#function\n"
3063 "\t.global _start\n"
3064 "_start:\n"
3065 "\tadrp x0, vgPlain_interim_stack\n"
3066 "\tadd x0, x0, :lo12:vgPlain_interim_stack\n"
3067 // The next 2 assume that VG_STACK_GUARD_SZB fits in 32 bits
3068 "\tmov x1, (("VG_STRINGIFY(VG_STACK_GUARD_SZB)") >> 0) & 0xFFFF\n"
3069 "\tmovk x1, (("VG_STRINGIFY(VG_STACK_GUARD_SZB)") >> 16) & 0xFFFF,"
3070 " lsl 16\n"
3071 "\tadd x0, x0, x1\n"
3072 // The next 2 assume that VG_STACK_ACTIVE_SZB fits in 32 bits
3073 "\tmov x1, (("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)") >> 0) & 0xFFFF\n"
3074 "\tmovk x1, (("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)") >> 16) & 0xFFFF,"
3075 " lsl 16\n"
3076 "\tadd x0, x0, x1\n"
3077 "\tand x0, x0, -16\n"
3078 "\tmov x1, sp\n"
3079 "\tmov sp, x0\n"
3080 "\tmov x0, x1\n"
3081 "\tb _start_in_C_linux\n"
3083 #elif defined(VGP_mips32_linux)
3084 asm("\n"
3085 "\t.type _gp_disp,@object\n"
3086 ".text\n"
3087 "\t.globl __start\n"
3088 "\t.type __start,@function\n"
3089 "__start:\n"
3091 "\tbal 1f\n"
3092 "\tnop\n"
3094 "1:\n"
3096 "\tlui $28, %hi(_gp_disp)\n"
3097 "\taddiu $28, $28, %lo(_gp_disp)\n"
3098 "\taddu $28, $28, $31\n"
3099 /* t1/$9 <- Addr(interim_stack) */
3100 "\tlui $9, %hi(vgPlain_interim_stack)\n"
3101 /* t1/$9 <- Addr(interim_stack) */
3102 "\taddiu $9, %lo(vgPlain_interim_stack)\n"
3105 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
3106 "\tli $11, "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
3108 "\taddu $9, $9, $10\n"
3109 "\taddu $9, $9, $11\n"
3110 "\tli $12, 0xFFFFFFF0\n"
3111 "\tand $9, $9, $12\n"
3112 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
3113 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
3114 boundary. And $29 is the original SP. Set the SP to t1 and
3115 call _start_in_C, passing it the initial SP. */
3117 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
3118 "\tmove $29, $9\n" // $sp <- t1 (new sp)
3120 "\tlui $25, %hi(_start_in_C_linux)\n"
3121 "\taddiu $25, %lo(_start_in_C_linux)\n"
3123 "\tbal _start_in_C_linux\n"
3124 "\tbreak 0x7\n"
3125 ".previous\n"
3127 #elif defined(VGP_mips64_linux)
3128 asm(
3129 ".text\n"
3130 ".globl __start\n"
3131 ".type __start,@function\n"
3132 "__start:\n"
3133 "\t.set noreorder\n"
3134 "\t.cpload $25\n"
3135 "\t.set reorder\n"
3136 "\t.cprestore 16\n"
3137 "\tlui $9, %hi(vgPlain_interim_stack)\n"
3138 /* t1/$9 <- Addr(interim_stack) */
3139 "\tdaddiu $9, %lo(vgPlain_interim_stack)\n"
3141 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
3142 "\tli $11, "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
3144 "\tdaddu $9, $9, $10\n"
3145 "\tdaddu $9, $9, $11\n"
3146 "\tli $12, 0xFFFFFF00\n"
3147 "\tand $9, $9, $12\n"
3148 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
3149 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
3150 boundary. And $29 is the original SP. Set the SP to t1 and
3151 call _start_in_C, passing it the initial SP. */
3153 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
3154 "\tmove $29, $9\n" // $sp <- t1 (new sp)
3156 "\tlui $9, %highest(_start_in_C_linux)\n"
3157 "\tori $9, %higher(_start_in_C_linux)\n"
3158 "\tdsll32 $9, $9, 0x0\n"
3159 "\tlui $10, %hi(_start_in_C_linux)\n"
3160 "\tdaddiu $10, %lo(_start_in_C_linux)\n"
3161 "\tdaddu $25, $9, $10\n"
3162 "\tjalr $25\n"
3163 "\tnop\n"
3164 ".previous\n"
3166 #else
3167 # error "Unknown linux platform"
3168 #endif
3170 /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
3171 #define _GNU_SOURCE
3172 #define _FILE_OFFSET_BITS 64
3173 /* This is in order to get AT_NULL and AT_PAGESIZE. */
3174 #include <elf.h>
3175 /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
3177 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3178 'static' causes gcc to complain it isn't.
3179 attribute 'used' also ensures the code is not eliminated at link
3180 time */
3181 __attribute__ ((used))
3182 void _start_in_C_linux ( UWord* pArgc );
3183 __attribute__ ((used))
3184 void _start_in_C_linux ( UWord* pArgc )
3186 Int r;
3187 Word argc = pArgc[0];
3188 HChar** argv = (HChar**)&pArgc[1];
3189 HChar** envp = (HChar**)&pArgc[1+argc+1];
3191 // For an inner Valgrind, register the interim stack asap.
3192 // This is needed to allow the outer valgrind to do stacktraces during init.
3193 // Note that this stack is not unregistered when the main thread
3194 // is switching to the (real) stack. Unregistering this would imply
3195 // to save the stack id in a global variable, and have a "if"
3196 // in run_a_thread_NORETURN to do the unregistration only for the
3197 // main thread. This unregistration is not worth this complexity.
3198 INNER_REQUEST
3199 ((void) VALGRIND_STACK_REGISTER
3200 (&VG_(interim_stack).bytes[0],
3201 &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack))));
3203 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3204 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3206 the_iicii.sp_at_startup = (Addr)pArgc;
3208 # if defined(VGP_ppc32_linux) || defined(VGP_ppc64be_linux) \
3209 || defined(VGP_ppc64le_linux) || defined(VGP_arm64_linux)
3211 /* ppc32/ppc64 can be configured with different page sizes.
3212 Determine this early. This is an ugly hack and really should
3213 be moved into valgrind_main. */
3214 UWord *sp = &pArgc[1+argc+1];
3215 while (*sp++ != 0)
3217 for (; *sp != AT_NULL && *sp != AT_PAGESZ; sp += 2);
3218 if (*sp == AT_PAGESZ) {
3219 VKI_PAGE_SIZE = sp[1];
3220 for (VKI_PAGE_SHIFT = 12;
3221 VKI_PAGE_SHIFT <= VKI_MAX_PAGE_SHIFT; VKI_PAGE_SHIFT++)
3222 if (VKI_PAGE_SIZE == (1UL << VKI_PAGE_SHIFT))
3223 break;
3226 # endif
3228 r = valgrind_main( (Int)argc, argv, envp );
3229 /* NOTREACHED */
3230 VG_(exit)(r);
3234 /*====================================================================*/
3235 /*=== Getting to main() alive: darwin ===*/
3236 /*====================================================================*/
3238 #elif defined(VGO_darwin)
3241 Memory layout established by kernel:
3243 0(%esp) argc
3244 4(%esp) argv[0]
3246 argv[argc-1]
3247 NULL
3248 envp[0]
3250 envp[n]
3251 NULL
3252 executable name (presumably, a pointer to it)
3253 NULL
3255 Ditto in the 64-bit case, except all offsets from SP are obviously
3256 twice as large.
3259 /* The kernel hands control to _start, which extracts the initial
3260 stack pointer and calls onwards to _start_in_C_darwin. This also
3261 switches to the new stack. */
3262 #if defined(VGP_x86_darwin)
3263 asm("\n"
3264 ".text\n"
3265 ".align 2,0x90\n"
3266 "\t.globl __start\n"
3267 "__start:\n"
3268 /* set up the new stack in %eax */
3269 "\tmovl $_vgPlain_interim_stack, %eax\n"
3270 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
3271 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
3272 "\tsubl $16, %eax\n"
3273 "\tandl $~15, %eax\n"
3274 /* install it, and collect the original one */
3275 "\txchgl %eax, %esp\n"
3276 "\tsubl $12, %esp\n" // keep stack 16 aligned; see #295428
3277 /* call _start_in_C_darwin, passing it the startup %esp */
3278 "\tpushl %eax\n"
3279 "\tcall __start_in_C_darwin\n"
3280 "\tint $3\n"
3281 "\tint $3\n"
3283 #elif defined(VGP_amd64_darwin)
3284 asm("\n"
3285 ".text\n"
3286 "\t.globl __start\n"
3287 ".align 3,0x90\n"
3288 "__start:\n"
3289 /* set up the new stack in %rdi */
3290 "\tmovabsq $_vgPlain_interim_stack, %rdi\n"
3291 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
3292 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
3293 "\tandq $~15, %rdi\n"
3294 /* install it, and collect the original one */
3295 "\txchgq %rdi, %rsp\n"
3296 /* call _start_in_C_darwin, passing it the startup %rsp */
3297 "\tcall __start_in_C_darwin\n"
3298 "\tint $3\n"
3299 "\tint $3\n"
3301 #endif
3303 void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2);
3304 void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2) {
3305 // skip check
3306 return VG_(memcpy)(dest,src,n);
3308 void* __memset_chk(void *s, int c, SizeT n, SizeT n2);
3309 void* __memset_chk(void *s, int c, SizeT n, SizeT n2) {
3310 // skip check
3311 return VG_(memset)(s,c,n);
3313 void bzero(void *s, SizeT n);
3314 void bzero(void *s, SizeT n) {
3315 VG_(memset)(s,0,n);
3318 void* memcpy(void *dest, const void *src, SizeT n);
3319 void* memcpy(void *dest, const void *src, SizeT n) {
3320 return VG_(memcpy)(dest,src,n);
3322 void* memset(void *s, int c, SizeT n);
3323 void* memset(void *s, int c, SizeT n) {
3324 return VG_(memset)(s,c,n);
3327 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3328 'static' causes gcc to complain it isn't. */
3329 void _start_in_C_darwin ( UWord* pArgc );
3330 void _start_in_C_darwin ( UWord* pArgc )
3332 Int r;
3333 Int argc = *(Int *)pArgc; // not pArgc[0] on LP64
3334 HChar** argv = (HChar**)&pArgc[1];
3335 HChar** envp = (HChar**)&pArgc[1+argc+1];
3337 // See _start_in_C_linux
3338 INNER_REQUEST
3339 ((void) VALGRIND_STACK_REGISTER
3340 (&VG_(interim_stack).bytes[0],
3341 &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack))));
3343 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3344 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3346 the_iicii.sp_at_startup = (Addr)pArgc;
3348 r = valgrind_main( (Int)argc, argv, envp );
3349 /* NOTREACHED */
3350 VG_(exit)(r);
3354 #else
3356 # error "Unknown OS"
3357 #endif
3360 /*====================================================================*/
3361 /*=== {u,}{div,mod}di3 replacements ===*/
3362 /*====================================================================*/
3364 /* For static linking on x86-darwin, we need to supply our own 64-bit
3365 integer division code, else the link dies thusly:
3367 ld_classic: Undefined symbols:
3368 ___udivdi3
3369 ___umoddi3
3371 #if defined(VGP_x86_darwin)
3373 /* Routines for doing signed/unsigned 64 x 64 ==> 64 div and mod
3374 (udivdi3, umoddi3, divdi3, moddi3) using only 32 x 32 ==> 32
3375 division. Cobbled together from
3377 http://www.hackersdelight.org/HDcode/divlu.c
3378 http://www.hackersdelight.org/HDcode/divls.c
3379 http://www.hackersdelight.org/HDcode/newCode/divDouble.c
3381 The code from those three files is covered by the following license,
3382 as it appears at:
3384 http://www.hackersdelight.org/permissions.htm
3386 You are free to use, copy, and distribute any of the code on
3387 this web site, whether modified by you or not. You need not give
3388 attribution. This includes the algorithms (some of which appear
3389 in Hacker's Delight), the Hacker's Assistant, and any code
3390 submitted by readers. Submitters implicitly agree to this.
3393 /* Long division, unsigned (64/32 ==> 32).
3394 This procedure performs unsigned "long division" i.e., division of a
3395 64-bit unsigned dividend by a 32-bit unsigned divisor, producing a
3396 32-bit quotient. In the overflow cases (divide by 0, or quotient
3397 exceeds 32 bits), it returns a remainder of 0xFFFFFFFF (an impossible
3398 value).
3399 The dividend is u1 and u0, with u1 being the most significant word.
3400 The divisor is parameter v. The value returned is the quotient.
3401 Max line length is 57, to fit in hacker.book. */
3403 static Int nlz32(UInt x)
3405 Int n;
3406 if (x == 0) return(32);
3407 n = 0;
3408 if (x <= 0x0000FFFF) {n = n +16; x = x <<16;}
3409 if (x <= 0x00FFFFFF) {n = n + 8; x = x << 8;}
3410 if (x <= 0x0FFFFFFF) {n = n + 4; x = x << 4;}
3411 if (x <= 0x3FFFFFFF) {n = n + 2; x = x << 2;}
3412 if (x <= 0x7FFFFFFF) {n = n + 1;}
3413 return n;
3416 /* 64 x 32 ==> 32 unsigned division, using only 32 x 32 ==> 32
3417 division as a primitive. */
3418 static UInt divlu2(UInt u1, UInt u0, UInt v, UInt *r)
3420 const UInt b = 65536; // Number base (16 bits).
3421 UInt un1, un0, // Norm. dividend LSD's.
3422 vn1, vn0, // Norm. divisor digits.
3423 q1, q0, // Quotient digits.
3424 un32, un21, un10, // Dividend digit pairs.
3425 rhat; // A remainder.
3426 Int s; // Shift amount for norm.
3428 if (u1 >= v) { // If overflow, set rem.
3429 if (r != NULL) // to an impossible value,
3430 *r = 0xFFFFFFFF; // and return the largest
3431 return 0xFFFFFFFF;} // possible quotient.
3433 s = nlz32(v); // 0 <= s <= 31.
3434 v = v << s; // Normalize divisor.
3435 vn1 = v >> 16; // Break divisor up into
3436 vn0 = v & 0xFFFF; // two 16-bit digits.
3438 un32 = (u1 << s) | ((u0 >> (32 - s)) & (-s >> 31));
3439 un10 = u0 << s; // Shift dividend left.
3441 un1 = un10 >> 16; // Break right half of
3442 un0 = un10 & 0xFFFF; // dividend into two digits.
3444 q1 = un32/vn1; // Compute the first
3445 rhat = un32 - q1*vn1; // quotient digit, q1.
3446 again1:
3447 if (q1 >= b || q1*vn0 > b*rhat + un1) {
3448 q1 = q1 - 1;
3449 rhat = rhat + vn1;
3450 if (rhat < b) goto again1;}
3452 un21 = un32*b + un1 - q1*v; // Multiply and subtract.
3454 q0 = un21/vn1; // Compute the second
3455 rhat = un21 - q0*vn1; // quotient digit, q0.
3456 again2:
3457 if (q0 >= b || q0*vn0 > b*rhat + un0) {
3458 q0 = q0 - 1;
3459 rhat = rhat + vn1;
3460 if (rhat < b) goto again2;}
3462 if (r != NULL) // If remainder is wanted,
3463 *r = (un21*b + un0 - q0*v) >> s; // return it.
3464 return q1*b + q0;
3468 /* 64 x 32 ==> 32 signed division, using only 32 x 32 ==> 32 division
3469 as a primitive. */
3470 static Int divls(Int u1, UInt u0, Int v, Int *r)
3472 Int q, uneg, vneg, diff, borrow;
3474 uneg = u1 >> 31; // -1 if u < 0.
3475 if (uneg) { // Compute the absolute
3476 u0 = -u0; // value of the dividend u.
3477 borrow = (u0 != 0);
3478 u1 = -u1 - borrow;}
3480 vneg = v >> 31; // -1 if v < 0.
3481 v = (v ^ vneg) - vneg; // Absolute value of v.
3483 if ((UInt)u1 >= (UInt)v) goto overflow;
3485 q = divlu2(u1, u0, v, (UInt *)r);
3487 diff = uneg ^ vneg; // Negate q if signs of
3488 q = (q ^ diff) - diff; // u and v differed.
3489 if (uneg && r != NULL)
3490 *r = -*r;
3492 if ((diff ^ q) < 0 && q != 0) { // If overflow,
3493 overflow: // set remainder
3494 if (r != NULL) // to an impossible value,
3495 *r = 0x80000000; // and return the largest
3496 q = 0x80000000;} // possible neg. quotient.
3497 return q;
3502 /* This file contains a program for doing 64/64 ==> 64 division, on a
3503 machine that does not have that instruction but that does have
3504 instructions for "long division" (64/32 ==> 32). Code for unsigned
3505 division is given first, followed by a simple program for doing the
3506 signed version by using the unsigned version.
3507 These programs are useful in implementing "long long" (64-bit)
3508 arithmetic on a machine that has the long division instruction. It will
3509 work on 64- and 32-bit machines, provided the compiler implements long
3510 long's (64-bit integers). It is desirable that the machine have the
3511 Count Leading Zeros instruction.
3512 In the GNU world, these programs are known as __divdi3 and __udivdi3,
3513 and similar names are used here.
3514 This material is not in HD, but may be in a future edition.
3515 Max line length is 57, to fit in hacker.book. */
3518 static Int nlz64(ULong x)
3520 Int n;
3521 if (x == 0) return(64);
3522 n = 0;
3523 if (x <= 0x00000000FFFFFFFFULL) {n = n + 32; x = x << 32;}
3524 if (x <= 0x0000FFFFFFFFFFFFULL) {n = n + 16; x = x << 16;}
3525 if (x <= 0x00FFFFFFFFFFFFFFULL) {n = n + 8; x = x << 8;}
3526 if (x <= 0x0FFFFFFFFFFFFFFFULL) {n = n + 4; x = x << 4;}
3527 if (x <= 0x3FFFFFFFFFFFFFFFULL) {n = n + 2; x = x << 2;}
3528 if (x <= 0x7FFFFFFFFFFFFFFFULL) {n = n + 1;}
3529 return n;
3532 // ---------------------------- udivdi3 --------------------------------
3534 /* The variables u0, u1, etc. take on only 32-bit values, but they
3535 are declared long long to avoid some compiler warning messages and to
3536 avoid some unnecessary EXTRs that the compiler would put in, to
3537 convert long longs to ints.
3539 First the procedure takes care of the case in which the divisor is a
3540 32-bit quantity. There are two subcases: (1) If the left half of the
3541 dividend is less than the divisor, one execution of DIVU is all that
3542 is required (overflow is not possible). (2) Otherwise it does two
3543 divisions, using the grade school method, with variables used as
3544 suggested below.
3546 q1 q0
3547 ________
3548 v) u1 u0
3549 q1*v
3550 ____
3551 k u0 */
3553 /* These macros must be used with arguments of the appropriate type
3554 (unsigned long long for DIVU and long long for DIVS. They are
3555 simulations of the presumed machines ops. I.e., they look at only the
3556 low-order 32 bits of the divisor, they return garbage if the division
3557 overflows, and they return garbage in the high-order half of the
3558 quotient doubleword.
3559 In practice, these would be replaced with uses of the machine's DIVU
3560 and DIVS instructions (e.g., by using the GNU "asm" facility). */
3562 static UInt DIVU ( ULong u, UInt v )
3564 UInt uHi = (UInt)(u >> 32);
3565 UInt uLo = (UInt)u;
3566 return divlu2(uHi, uLo, v, NULL);
3569 static Int DIVS ( Long u, Int v )
3571 Int uHi = (Int)(u >> 32);
3572 UInt uLo = (UInt)u;
3573 return divls(uHi, uLo, v, NULL);
3576 /* 64 x 64 ==> 64 unsigned division, using only 32 x 32 ==> 32
3577 division as a primitive. */
3578 static ULong udivdi3(ULong u, ULong v)
3580 ULong u0, u1, v1, q0, q1, k, n;
3582 if (v >> 32 == 0) { // If v < 2**32:
3583 if (u >> 32 < v) // If u/v cannot overflow,
3584 return DIVU(u, v) // just do one division.
3585 & 0xFFFFFFFF;
3586 else { // If u/v would overflow:
3587 u1 = u >> 32; // Break u up into two
3588 u0 = u & 0xFFFFFFFF; // halves.
3589 q1 = DIVU(u1, v) // First quotient digit.
3590 & 0xFFFFFFFF;
3591 k = u1 - q1*v; // First remainder, < v.
3592 q0 = DIVU((k << 32) + u0, v) // 2nd quot. digit.
3593 & 0xFFFFFFFF;
3594 return (q1 << 32) + q0;
3597 // Here v >= 2**32.
3598 n = nlz64(v); // 0 <= n <= 31.
3599 v1 = (v << n) >> 32; // Normalize the divisor
3600 // so its MSB is 1.
3601 u1 = u >> 1; // To ensure no overflow.
3602 q1 = DIVU(u1, v1) // Get quotient from
3603 & 0xFFFFFFFF; // divide unsigned insn.
3604 q0 = (q1 << n) >> 31; // Undo normalization and
3605 // division of u by 2.
3606 if (q0 != 0) // Make q0 correct or
3607 q0 = q0 - 1; // too small by 1.
3608 if ((u - q0*v) >= v)
3609 q0 = q0 + 1; // Now q0 is correct.
3610 return q0;
3614 // ----------------------------- divdi3 --------------------------------
3616 /* This routine presumes that smallish cases (those which can be done in
3617 one execution of DIVS) are common. If this is not the case, the test for
3618 this case should be deleted.
3619 Note that the test for when DIVS can be used is not entirely
3620 accurate. For example, DIVS is not used if v = 0xFFFFFFFF8000000,
3621 whereas if could be (if u is sufficiently small in magnitude). */
3623 // ------------------------------ cut ----------------------------------
3625 static ULong my_llabs ( Long x )
3627 ULong t = x >> 63;
3628 return (x ^ t) - t;
3631 /* 64 x 64 ==> 64 signed division, using only 32 x 32 ==> 32 division
3632 as a primitive. */
3633 static Long divdi3(Long u, Long v)
3635 ULong au, av;
3636 Long q, t;
3637 au = my_llabs(u);
3638 av = my_llabs(v);
3639 if (av >> 31 == 0) { // If |v| < 2**31 and
3640 // if (v << 32 >> 32 == v) { // If v is in range and
3641 if (au < av << 31) { // |u|/|v| cannot
3642 q = DIVS(u, v); // overflow, use DIVS.
3643 return (q << 32) >> 32;
3646 q = udivdi3(au,av); // Invoke udivdi3.
3647 t = (u ^ v) >> 63; // If u, v have different
3648 return (q ^ t) - t; // signs, negate q.
3651 // ---------------------------- end cut --------------------------------
3653 ULong __udivdi3 (ULong u, ULong v);
3654 ULong __udivdi3 (ULong u, ULong v)
3656 return udivdi3(u,v);
3659 Long __divdi3 (Long u, Long v);
3660 Long __divdi3 (Long u, Long v)
3662 return divdi3(u,v);
3665 ULong __umoddi3 (ULong u, ULong v);
3666 ULong __umoddi3 (ULong u, ULong v)
3668 ULong q = __udivdi3(u, v);
3669 ULong r = u - q * v;
3670 return r;
3673 Long __moddi3 (Long u, Long v);
3674 Long __moddi3 (Long u, Long v)
3676 Long q = __divdi3(u, v);
3677 Long r = u - q * v;
3678 return r;
3681 /* ------------------------------------------------
3682 ld_classic: Undefined symbols:
3683 ___fixunsdfdi
3684 ------------------------------------------------
3687 /* ===-- fixunsdfdi.c - Implement __fixunsdfdi -----------------------------===
3689 * The LLVM Compiler Infrastructure
3691 * This file is dual licensed under the MIT and the University of Illinois Open
3692 * Source Licenses. See LICENSE.TXT for details.
3694 * ===----------------------------------------------------------------------===
3696 * This file implements __fixunsdfdi for the compiler_rt library.
3698 * ===----------------------------------------------------------------------===
3701 /* As per http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses,
3703 the "NCSA/University of Illinois Open Source License" is compatible
3704 with the GPL (both version 2 and 3). What is claimed to be
3705 compatible is this
3707 http://www.opensource.org/licenses/UoI-NCSA.php
3709 and the LLVM documentation at
3711 http://www.llvm.org/docs/DeveloperPolicy.html#license
3713 says all the code in LLVM is available under the University of
3714 Illinois/NCSA Open Source License, at this URL
3716 http://www.opensource.org/licenses/UoI-NCSA.php
3718 viz, the same one that the FSF pages claim is compatible. So I
3719 think it's OK to include it.
3722 /* Returns: convert a to a unsigned long long, rounding toward zero.
3723 * Negative values all become zero.
3726 /* Assumption: double is a IEEE 64 bit floating point type
3727 * du_int is a 64 bit integral type
3728 * value in double is representable in du_int or is negative
3729 * (no range checking performed)
3732 /* seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm */
3734 typedef unsigned long long du_int;
3735 typedef unsigned su_int;
3737 typedef union
3739 du_int all;
3740 struct
3742 #if VG_LITTLEENDIAN
3743 su_int low;
3744 su_int high;
3745 #else
3746 su_int high;
3747 su_int low;
3748 #endif /* VG_LITTLEENDIAN */
3750 } udwords;
3752 typedef union
3754 udwords u;
3755 double f;
3756 } double_bits;
3758 du_int __fixunsdfdi(double a);
3760 du_int
3761 __fixunsdfdi(double a)
3763 double_bits fb;
3764 fb.f = a;
3765 int e = ((fb.u.s.high & 0x7FF00000) >> 20) - 1023;
3766 if (e < 0 || (fb.u.s.high & 0x80000000))
3767 return 0;
3768 udwords r;
3769 r.s.high = (fb.u.s.high & 0x000FFFFF) | 0x00100000;
3770 r.s.low = fb.u.s.low;
3771 if (e > 52)
3772 r.all <<= (e - 52);
3773 else
3774 r.all >>= (52 - e);
3775 return r.all;
3779 #endif
3782 /*====================================================================*/
3783 /*=== Dummy _voucher_mach_msg_set for OSX 10.10 ===*/
3784 /*====================================================================*/
3786 #if defined(VGO_darwin) && DARWIN_VERS == DARWIN_10_10
3788 /* Builds on MacOSX 10.10 seem to need this for some reason. */
3789 /* extern boolean_t voucher_mach_msg_set(mach_msg_header_t *msg)
3790 __attribute__((weak_import));
3791 I haven't a clue what the return value means, so just return 0.
3792 Looks like none of the generated uses in the tree look at the
3793 return value anyway.
3795 UWord voucher_mach_msg_set ( UWord arg1 );
3796 UWord voucher_mach_msg_set ( UWord arg1 )
3798 return 0;
3801 #endif
3804 /*--------------------------------------------------------------------*/
3805 /*--- end ---*/
3806 /*--------------------------------------------------------------------*/