Fix non portability spotted by Florian:
[valgrind.git] / coregrind / m_main.c
bloba1de69c7c724be4f5e98144ca91af2ebd6ade1c5
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 " --valgrind-stacksize=<number> size of valgrind (host) thread's stack\n"
199 " (in bytes) ["
200 VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)
201 "]\n"
202 " --show-emwarns=no|yes show warnings about emulation limits? [no]\n"
203 " --require-text-symbol=:sonamepattern:symbolpattern abort run if the\n"
204 " stated shared object doesn't have the stated\n"
205 " text symbol. Patterns can contain ? and *.\n"
206 " --soname-synonyms=syn1=pattern1,syn2=pattern2,... synonym soname\n"
207 " specify patterns for function wrapping or replacement.\n"
208 " To use a non-libc malloc library that is\n"
209 " in the main exe: --soname-synonyms=somalloc=NONE\n"
210 " in libxyzzy.so: --soname-synonyms=somalloc=libxyzzy.so\n"
211 " --sigill-diagnostics=yes|no warn about illegal instructions? [yes]\n"
212 " --unw-stack-scan-thresh=<number> Enable stack-scan unwind if fewer\n"
213 " than <number> good frames found [0, meaning \"disabled\"]\n"
214 " NOTE: stack scanning is only available on arm-linux.\n"
215 " --unw-stack-scan-frames=<number> Max number of frames that can be\n"
216 " recovered by stack scanning [5]\n"
217 " --resync-filter=no|yes|verbose [yes on MacOS, no on other OSes]\n"
218 " attempt to avoid expensive address-space-resync operations\n"
219 " --max-threads=<number> maximum number of threads that valgrind can\n"
220 " handle [%d]\n"
221 "\n";
223 const HChar usage2[] =
224 "\n"
225 " debugging options for all Valgrind tools:\n"
226 " -d show verbose debugging output\n"
227 " --stats=no|yes show tool and core statistics [no]\n"
228 " --sanity-level=<number> level of sanity checking to do [1]\n"
229 " --trace-flags=<XXXXXXXX> show generated code? (X = 0|1) [00000000]\n"
230 " --profile-flags=<XXXXXXXX> ditto, but for profiling (X = 0|1) [00000000]\n"
231 " --profile-interval=<number> show profile every <number> event checks\n"
232 " [0, meaning only at the end of the run]\n"
233 " --trace-notbelow=<number> only show BBs above <number> [999999999]\n"
234 " --trace-notabove=<number> only show BBs below <number> [0]\n"
235 " --trace-syscalls=no|yes show all system calls? [no]\n"
236 " --trace-signals=no|yes show signal handling details? [no]\n"
237 " --trace-symtab=no|yes show symbol table details? [no]\n"
238 " --trace-symtab-patt=<patt> limit debuginfo tracing to obj name <patt>\n"
239 " --trace-cfi=no|yes show call-frame-info details? [no]\n"
240 " --debug-dump=syms mimic /usr/bin/readelf --syms\n"
241 " --debug-dump=line mimic /usr/bin/readelf --debug-dump=line\n"
242 " --debug-dump=frames mimic /usr/bin/readelf --debug-dump=frames\n"
243 " --trace-redir=no|yes show redirection details? [no]\n"
244 " --trace-sched=no|yes show thread scheduler details? [no]\n"
245 " --profile-heap=no|yes profile Valgrind's own space use\n"
246 " --core-redzone-size=<number> set minimum size of redzones added before/after\n"
247 " heap blocks allocated for Valgrind internal use (in bytes) [4]\n"
248 " --wait-for-gdb=yes|no pause on startup to wait for gdb attach\n"
249 " --sym-offsets=yes|no show syms in form 'name+offset' ? [no]\n"
250 " --command-line-only=no|yes only use command line options [no]\n"
251 "\n"
252 " Vex options for all Valgrind tools:\n"
253 " --vex-iropt-verbosity=<0..9> [0]\n"
254 " --vex-iropt-level=<0..2> [2]\n"
255 " --vex-iropt-unroll-thresh=<0..400> [120]\n"
256 " --vex-guest-max-insns=<1..100> [50]\n"
257 " --vex-guest-chase-thresh=<0..99> [10]\n"
258 " --vex-guest-chase-cond=no|yes [no]\n"
259 " Precise exception control. Possible values for 'mode' are as follows\n"
260 " and specify the minimum set of registers guaranteed to be correct\n"
261 " immediately prior to memory access instructions:\n"
262 " sp-at-mem-access stack pointer only\n"
263 " unwindregs-at-mem-access registers needed for stack unwinding\n"
264 " allregs-at-mem-access all registers\n"
265 " allregs-at-each-insn all registers are always correct\n"
266 " Default value for all 3 following flags is [unwindregs-at-mem-access].\n"
267 " --vex-iropt-register-updates=mode setting to use by default\n"
268 " --px-default=mode synonym for --vex-iropt-register-updates\n"
269 " --px-file-backed=mode optional setting for file-backed (non-JIT) code\n"
270 " Tracing and profile control:\n"
271 " --trace-flags and --profile-flags values (omit the middle space):\n"
272 " 1000 0000 show conversion into IR\n"
273 " 0100 0000 show after initial opt\n"
274 " 0010 0000 show after instrumentation\n"
275 " 0001 0000 show after second opt\n"
276 " 0000 1000 show after tree building\n"
277 " 0000 0100 show selecting insns\n"
278 " 0000 0010 show after reg-alloc\n"
279 " 0000 0001 show final assembly\n"
280 " 0000 0000 show summary profile only\n"
281 " (Nb: you need --trace-notbelow and/or --trace-notabove\n"
282 " with --trace-flags for full details)\n"
283 "\n"
284 " debugging options for Valgrind tools that report errors\n"
285 " --dump-error=<number> show translation for basic block associated\n"
286 " with <number>'th error context [0=show none]\n"
287 "\n"
288 " debugging options for Valgrind tools that replace malloc:\n"
289 " --trace-malloc=no|yes show client malloc details? [no]\n"
290 "\n";
292 const HChar usage3[] =
293 "\n"
294 " Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc\n"
295 "\n"
296 " %s is %s\n"
297 " Valgrind is Copyright (C) 2000-2013, and GNU GPL'd, by Julian Seward et al.\n"
298 " LibVEX is Copyright (C) 2004-2013, and GNU GPL'd, by OpenWorks LLP et al.\n"
299 "\n"
300 " Bug reports, feedback, admiration, abuse, etc, to: %s.\n"
301 "\n";
303 const HChar* gdb_path = GDB_PATH;
304 HChar default_alignment[30]; // large enough
305 HChar default_redzone_size[30]; // large enough
307 // Ensure the message goes to stdout
308 VG_(log_output_sink).fd = 1;
309 VG_(log_output_sink).is_socket = False;
311 if (VG_(needs).malloc_replacement) {
312 VG_(sprintf)(default_alignment, "%d", VG_MIN_MALLOC_SZB);
313 VG_(sprintf)(default_redzone_size, "%lu", VG_(tdict).tool_client_redzone_szB);
314 } else {
315 VG_(strcpy)(default_alignment, "not used by this tool");
316 VG_(strcpy)(default_redzone_size, "not used by this tool");
318 /* 'usage1' a type as described after each arg. */
319 VG_(printf)(usage1,
320 VG_(clo_vgdb_error) /* int */,
321 gdb_path /* char* */,
322 default_alignment /* char* */,
323 default_redzone_size /* char* */,
324 VG_(clo_vgdb_poll) /* int */,
325 VG_(vgdb_prefix_default)() /* char* */,
326 N_SECTORS_DEFAULT /* int */,
327 MAX_THREADS_DEFAULT /* int */
329 if (VG_(details).name) {
330 VG_(printf)(" user options for %s:\n", VG_(details).name);
331 if (VG_(needs).command_line_options)
332 VG_TDICT_CALL(tool_print_usage);
333 else
334 VG_(printf)(" (none)\n");
336 if (debug_help) {
337 VG_(printf)("%s", usage2);
339 if (VG_(details).name) {
340 VG_(printf)(" debugging options for %s:\n", VG_(details).name);
342 if (VG_(needs).command_line_options)
343 VG_TDICT_CALL(tool_print_debug_usage);
344 else
345 VG_(printf)(" (none)\n");
348 VG_(printf)(usage3, VG_(details).name, VG_(details).copyright_author,
349 VG_BUGS_TO);
350 VG_(exit)(0);
354 /* Peer at previously set up VG_(args_for_valgrind) and do some
355 minimal command line processing that must happen early on:
357 - show the version string, if requested (-v)
358 - extract any request for help (--help, -h, --help-debug)
359 - get the toolname (--tool=)
360 - set VG_(clo_max_stackframe) (--max-stackframe=)
361 - set VG_(clo_main_stacksize) (--main-stacksize=)
362 - set VG_(clo_sim_hints) (--sim-hints=)
363 - set VG_(clo_max_threads) (--max-threads)
365 That's all it does. The main command line processing is done below
366 by main_process_cmd_line_options. Note that
367 main_process_cmd_line_options has to handle but ignore the ones we
368 have handled here.
370 static void early_process_cmd_line_options ( /*OUT*/Int* need_help,
371 /*OUT*/const HChar** tool )
373 UInt i;
374 HChar* str;
376 vg_assert( VG_(args_for_valgrind) );
378 /* parse the options we have (only the options we care about now) */
379 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
381 str = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
382 vg_assert(str);
384 // Nb: the version string goes to stdout.
385 if VG_XACT_CLO(str, "--version", VG_(log_output_sink).fd, 1) {
386 VG_(log_output_sink).is_socket = False;
387 VG_(printf)("valgrind-" VERSION "\n");
388 VG_(exit)(0);
390 else if VG_XACT_CLO(str, "--help", *need_help, *need_help+1) {}
391 else if VG_XACT_CLO(str, "-h", *need_help, *need_help+1) {}
393 else if VG_XACT_CLO(str, "--help-debug", *need_help, *need_help+2) {}
395 // The tool has already been determined, but we need to know the name
396 // here.
397 else if VG_STR_CLO(str, "--tool", *tool) {}
399 // Set up VG_(clo_max_stackframe) and VG_(clo_main_stacksize).
400 // These are needed by VG_(ii_create_image), which happens
401 // before main_process_cmd_line_options().
402 else if VG_INT_CLO(str, "--max-stackframe", VG_(clo_max_stackframe)) {}
403 else if VG_INT_CLO(str, "--main-stacksize", VG_(clo_main_stacksize)) {}
405 // Set up VG_(clo_max_threads); needed for VG_(tl_pre_clo_init)
406 else if VG_INT_CLO(str, "--max-threads", VG_(clo_max_threads)) {}
408 // Set up VG_(clo_sim_hints). This is needed a.o. for an inner
409 // running in an outer, to have "no-inner-prefix" enabled
410 // as early as possible.
411 else if VG_USETX_CLO (str, "--sim-hints",
412 "lax-ioctls,fuse-compatible,"
413 "enable-outer,no-inner-prefix,"
414 "no-nptl-pthread-stackcache",
415 VG_(clo_sim_hints)) {}
418 /* For convenience */
419 VG_N_THREADS = VG_(clo_max_threads);
422 /* The main processing for command line options. See comments above
423 on early_process_cmd_line_options.
425 Comments on how the logging options are handled:
427 User can specify:
428 --log-fd= for a fd to write to (default setting, fd = 2)
429 --log-file= for a file name to write to
430 --log-socket= for a socket to write to
432 As a result of examining these and doing relevant socket/file
433 opening, a final fd is established. This is stored in
434 VG_(log_output_sink) in m_libcprint. Also, if --log-file=STR was
435 specified, then STR, after expansion of %p and %q templates within
436 it, is stored in VG_(clo_log_fname_expanded), in m_options, just in
437 case anybody wants to know what it is.
439 When printing, VG_(log_output_sink) is consulted to find the
440 fd to send output to.
442 Exactly analogous actions are undertaken for the XML output
443 channel, with the one difference that the default fd is -1, meaning
444 the channel is disabled by default.
446 static
447 void main_process_cmd_line_options ( /*OUT*/Bool* logging_to_fd,
448 /*OUT*/const HChar** xml_fname_unexpanded,
449 const HChar* toolname )
451 // VG_(clo_log_fd) is used by all the messaging. It starts as 2 (stderr)
452 // and we cannot change it until we know what we are changing it to is
453 // ok. So we have tmp_log_fd to hold the tmp fd prior to that point.
454 SysRes sres;
455 Int i, tmp_log_fd, tmp_xml_fd;
456 Int toolname_len = VG_(strlen)(toolname);
457 const HChar* tmp_str; // Used in a couple of places.
458 enum {
459 VgLogTo_Fd,
460 VgLogTo_File,
461 VgLogTo_Socket
462 } log_to = VgLogTo_Fd, // Where is logging output to be sent?
463 xml_to = VgLogTo_Fd; // Where is XML output to be sent?
465 /* Temporarily holds the string STR specified with
466 --{log,xml}-{name,socket}=STR. 'fs' stands for
467 file-or-socket. */
468 const HChar* log_fsname_unexpanded = NULL;
469 const HChar* xml_fsname_unexpanded = NULL;
471 /* Whether the user has explicitly provided --sigill-diagnostics.
472 If not explicitly given depends on general verbosity setting. */
473 Bool sigill_diag_set = False;
475 /* Log to stderr by default, but usage message goes to stdout. XML
476 output is initially disabled. */
477 tmp_log_fd = 2;
478 tmp_xml_fd = -1;
480 /* Check for sane path in ./configure --prefix=... */
481 if (VG_LIBDIR[0] != '/')
482 VG_(err_config_error)("Please use absolute paths in "
483 "./configure --prefix=... or --libdir=...\n");
485 vg_assert( VG_(args_for_valgrind) );
487 VG_(clo_suppressions) = VG_(newXA)(VG_(malloc), "main.mpclo.4",
488 VG_(free), sizeof(HChar *));
489 VG_(clo_fullpath_after) = VG_(newXA)(VG_(malloc), "main.mpclo.5",
490 VG_(free), sizeof(HChar *));
491 VG_(clo_req_tsyms) = VG_(newXA)(VG_(malloc), "main.mpclo.6",
492 VG_(free), sizeof(HChar *));
494 /* Constants for parsing PX control flags. */
495 const HChar* pxStrings[5]
496 = { "sp-at-mem-access", "unwindregs-at-mem-access",
497 "allregs-at-mem-access", "allregs-at-each-insn", NULL };
498 const VexRegisterUpdates pxVals[5]
499 = { VexRegUpdSpAtMemAccess, VexRegUpdUnwindregsAtMemAccess,
500 VexRegUpdAllregsAtMemAccess, VexRegUpdAllregsAtEachInsn, 0/*inval*/ };
502 /* BEGIN command-line processing loop */
504 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
506 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
507 HChar* colon = arg;
508 UInt ix = 0;
510 // Look for a colon in the option name.
511 while (*colon && *colon != ':' && *colon != '=')
512 colon++;
514 // Does it have the form "--toolname:foo"? We have to do it at the start
515 // in case someone has combined a prefix with a core-specific option,
516 // eg. "--memcheck:verbose".
517 if (*colon == ':') {
518 if (VG_STREQN(2, arg, "--") &&
519 VG_STREQN(toolname_len, arg+2, toolname) &&
520 VG_STREQN(1, arg+2+toolname_len, ":"))
522 // Prefix matches, convert "--toolname:foo" to "--foo".
523 // Two things to note:
524 // - We cannot modify the option in-place. If we did, and then
525 // a child was spawned with --trace-children=yes, the
526 // now-non-prefixed option would be passed and could screw up
527 // the child.
528 // - We create copies, and never free them. Why? Non-prefixed
529 // options hang around forever, so tools need not make copies
530 // of strings within them. We need to have the same behaviour
531 // for prefixed options. The pointer to the copy will be lost
532 // once we leave this function (although a tool may keep a
533 // pointer into it), but the space wasted is insignificant.
534 // (In bug #142197, the copies were being freed, which caused
535 // problems for tools that reasonably assumed that arguments
536 // wouldn't disappear on them.)
537 if (0)
538 VG_(printf)("tool-specific arg: %s\n", arg);
539 arg = VG_(strdup)("main.mpclo.1", arg + toolname_len + 1);
540 arg[0] = '-';
541 arg[1] = '-';
543 } else {
544 // prefix doesn't match, skip to next arg
545 continue;
549 /* Ignore these options - they've already been handled */
550 if VG_STREQN( 7, arg, "--tool=") {}
551 else if VG_STREQN(20, arg, "--command-line-only=") {}
552 else if VG_STREQ( arg, "--") {}
553 else if VG_STREQ( arg, "-d") {}
554 else if VG_STREQN(17, arg, "--max-stackframe=") {}
555 else if VG_STREQN(17, arg, "--main-stacksize=") {}
556 else if VG_STREQN(14, arg, "--max-threads=") {}
557 else if VG_STREQN(12, arg, "--sim-hints=") {}
558 else if VG_STREQN(15, arg, "--profile-heap=") {}
559 else if VG_STREQN(20, arg, "--core-redzone-size=") {}
560 else if VG_STREQN(15, arg, "--redzone-size=") {}
561 else if VG_STREQN(17, arg, "--aspace-minaddr=") {}
563 else if VG_BINT_CLO(arg, "--valgrind-stacksize",
564 VG_(clo_valgrind_stacksize),
565 2*VKI_PAGE_SIZE, 10*VG_DEFAULT_STACK_ACTIVE_SZB)
566 {VG_(clo_valgrind_stacksize)
567 = VG_PGROUNDUP(VG_(clo_valgrind_stacksize));}
569 /* Obsolete options. Report an error and exit */
570 else if VG_STREQN(34, arg, "--vex-iropt-precise-memory-exns=no") {
571 VG_(fmsg_bad_option)
572 (arg,
573 "--vex-iropt-precise-memory-exns is obsolete\n"
574 "Use --vex-iropt-register-updates=unwindregs-at-mem-access instead\n");
576 else if VG_STREQN(35, arg, "--vex-iropt-precise-memory-exns=yes") {
577 VG_(fmsg_bad_option)
578 (arg,
579 "--vex-iropt-precise-memory-exns is obsolete\n"
580 "Use --vex-iropt-register-updates=allregs-at-mem-access instead\n"
581 " (or --vex-iropt-register-updates=allregs-at-each-insn)\n");
584 // These options are new.
585 else if (VG_STREQ(arg, "-v") ||
586 VG_STREQ(arg, "--verbose"))
587 VG_(clo_verbosity)++;
589 else if (VG_STREQ(arg, "-q") ||
590 VG_STREQ(arg, "--quiet"))
591 VG_(clo_verbosity)--;
593 else if VG_BOOL_CLO(arg, "--sigill-diagnostics", VG_(clo_sigill_diag))
594 sigill_diag_set = True;
596 else if VG_BOOL_CLO(arg, "--stats", VG_(clo_stats)) {}
597 else if VG_BOOL_CLO(arg, "--xml", VG_(clo_xml))
598 VG_(debugLog_setXml)(VG_(clo_xml));
600 else if VG_XACT_CLO(arg, "--vgdb=no", VG_(clo_vgdb), Vg_VgdbNo) {}
601 else if VG_XACT_CLO(arg, "--vgdb=yes", VG_(clo_vgdb), Vg_VgdbYes) {}
602 else if VG_XACT_CLO(arg, "--vgdb=full", VG_(clo_vgdb), Vg_VgdbFull) {
603 /* automatically updates register values at each insn
604 with --vgdb=full */
605 VG_(clo_vex_control).iropt_register_updates_default
606 = VG_(clo_px_file_backed)
607 = VexRegUpdAllregsAtEachInsn;
609 else if VG_INT_CLO (arg, "--vgdb-poll", VG_(clo_vgdb_poll)) {}
610 else if VG_INT_CLO (arg, "--vgdb-error", VG_(clo_vgdb_error)) {}
611 else if VG_USET_CLO (arg, "--vgdb-stop-at",
612 "startup,exit,valgrindabexit",
613 VG_(clo_vgdb_stop_at)) {}
614 else if VG_STR_CLO (arg, "--vgdb-prefix", VG_(clo_vgdb_prefix)) {
615 VG_(arg_vgdb_prefix) = arg;
617 else if VG_BOOL_CLO(arg, "--vgdb-shadow-registers",
618 VG_(clo_vgdb_shadow_registers)) {}
619 else if VG_BOOL_CLO(arg, "--db-attach", VG_(clo_db_attach)) {}
620 else if VG_BOOL_CLO(arg, "--demangle", VG_(clo_demangle)) {}
621 else if VG_STR_CLO (arg, "--soname-synonyms",VG_(clo_soname_synonyms)) {}
622 else if VG_BOOL_CLO(arg, "--error-limit", VG_(clo_error_limit)) {}
623 else if VG_INT_CLO (arg, "--error-exitcode", VG_(clo_error_exitcode)) {}
624 else if VG_STR_CLO (arg, "--error-markers", tmp_str) {
625 Int m;
626 const HChar *startpos = tmp_str;
627 const HChar *nextpos;
628 for (m = 0;
629 m < sizeof(VG_(clo_error_markers))
630 /sizeof(VG_(clo_error_markers)[0]);
631 m++) {
632 /* Release previous value if clo given multiple times. */
633 VG_(free)(VG_(clo_error_markers)[m]);
634 VG_(clo_error_markers)[m] = NULL;
636 nextpos = VG_(strchr)(startpos, ',');
637 if (!nextpos)
638 nextpos = startpos + VG_(strlen)(startpos);
639 if (startpos != nextpos) {
640 VG_(clo_error_markers)[m]
641 = VG_(malloc)("main.mpclo.2", nextpos - startpos + 1);
642 VG_(memcpy)(VG_(clo_error_markers)[m], startpos,
643 nextpos - startpos);
644 VG_(clo_error_markers)[m][nextpos - startpos] = '\0';
646 startpos = *nextpos ? nextpos + 1 : nextpos;
649 else if VG_BOOL_CLO(arg, "--show-emwarns", VG_(clo_show_emwarns)) {}
651 else if VG_BOOL_CLO(arg, "--run-libc-freeres", VG_(clo_run_libc_freeres)) {}
652 else if VG_BOOL_CLO(arg, "--show-below-main", VG_(clo_show_below_main)) {}
653 else if VG_BOOL_CLO(arg, "--time-stamp", VG_(clo_time_stamp)) {}
654 else if VG_BOOL_CLO(arg, "--track-fds", VG_(clo_track_fds)) {}
655 else if VG_BOOL_CLO(arg, "--trace-children", VG_(clo_trace_children)) {}
656 else if VG_BOOL_CLO(arg, "--child-silent-after-fork",
657 VG_(clo_child_silent_after_fork)) {}
658 else if VG_STR_CLO(arg, "--fair-sched", tmp_str) {
659 if (VG_(strcmp)(tmp_str, "yes") == 0)
660 VG_(clo_fair_sched) = enable_fair_sched;
661 else if (VG_(strcmp)(tmp_str, "try") == 0)
662 VG_(clo_fair_sched) = try_fair_sched;
663 else if (VG_(strcmp)(tmp_str, "no") == 0)
664 VG_(clo_fair_sched) = disable_fair_sched;
665 else
666 VG_(fmsg_bad_option)(arg,
667 "Bad argument, should be 'yes', 'try' or 'no'\n");
669 else if VG_BOOL_CLO(arg, "--trace-sched", VG_(clo_trace_sched)) {}
670 else if VG_BOOL_CLO(arg, "--trace-signals", VG_(clo_trace_signals)) {}
671 else if VG_BOOL_CLO(arg, "--trace-symtab", VG_(clo_trace_symtab)) {}
672 else if VG_STR_CLO (arg, "--trace-symtab-patt", VG_(clo_trace_symtab_patt)) {}
673 else if VG_BOOL_CLO(arg, "--trace-cfi", VG_(clo_trace_cfi)) {}
674 else if VG_XACT_CLO(arg, "--debug-dump=syms", VG_(clo_debug_dump_syms),
675 True) {}
676 else if VG_XACT_CLO(arg, "--debug-dump=line", VG_(clo_debug_dump_line),
677 True) {}
678 else if VG_XACT_CLO(arg, "--debug-dump=frames",
679 VG_(clo_debug_dump_frames), True) {}
680 else if VG_BOOL_CLO(arg, "--trace-redir", VG_(clo_trace_redir)) {}
682 else if VG_BOOL_CLO(arg, "--trace-syscalls", VG_(clo_trace_syscalls)) {}
683 else if VG_BOOL_CLO(arg, "--wait-for-gdb", VG_(clo_wait_for_gdb)) {}
684 else if VG_STR_CLO (arg, "--db-command", VG_(clo_db_command)) {}
685 else if VG_BOOL_CLO(arg, "--sym-offsets", VG_(clo_sym_offsets)) {}
686 else if VG_BOOL_CLO(arg, "--read-inline-info", VG_(clo_read_inline_info)) {}
687 else if VG_BOOL_CLO(arg, "--read-var-info", VG_(clo_read_var_info)) {}
689 else if VG_INT_CLO (arg, "--dump-error", VG_(clo_dump_error)) {}
690 else if VG_INT_CLO (arg, "--input-fd", VG_(clo_input_fd)) {}
691 else if VG_INT_CLO (arg, "--sanity-level", VG_(clo_sanity_level)) {}
692 else if VG_BINT_CLO(arg, "--num-callers", VG_(clo_backtrace_size), 1,
693 VG_DEEPEST_BACKTRACE) {}
694 else if VG_BINT_CLO(arg, "--num-transtab-sectors",
695 VG_(clo_num_transtab_sectors),
696 MIN_N_SECTORS, MAX_N_SECTORS) {}
697 else if VG_BINT_CLO(arg, "--merge-recursive-frames",
698 VG_(clo_merge_recursive_frames), 0,
699 VG_DEEPEST_BACKTRACE) {}
701 else if VG_XACT_CLO(arg, "--smc-check=none",
702 VG_(clo_smc_check), Vg_SmcNone) {}
703 else if VG_XACT_CLO(arg, "--smc-check=stack",
704 VG_(clo_smc_check), Vg_SmcStack) {}
705 else if VG_XACT_CLO(arg, "--smc-check=all",
706 VG_(clo_smc_check), Vg_SmcAll) {}
707 else if VG_XACT_CLO(arg, "--smc-check=all-non-file",
708 VG_(clo_smc_check), Vg_SmcAllNonFile) {}
710 else if VG_USETX_CLO (arg, "--kernel-variant",
711 "bproc,"
712 "android-no-hw-tls,"
713 "android-gpu-sgx5xx,"
714 "android-gpu-adreno3xx",
715 VG_(clo_kernel_variant)) {}
717 else if VG_BOOL_CLO(arg, "--dsymutil", VG_(clo_dsymutil)) {}
719 else if VG_STR_CLO (arg, "--trace-children-skip",
720 VG_(clo_trace_children_skip)) {}
721 else if VG_STR_CLO (arg, "--trace-children-skip-by-arg",
722 VG_(clo_trace_children_skip_by_arg)) {}
724 else if VG_BINT_CLO(arg, "--vex-iropt-verbosity",
725 VG_(clo_vex_control).iropt_verbosity, 0, 10) {}
726 else if VG_BINT_CLO(arg, "--vex-iropt-level",
727 VG_(clo_vex_control).iropt_level, 0, 2) {}
729 else if VG_STRINDEX_CLO(arg, "--vex-iropt-register-updates",
730 pxStrings, ix) {
731 vg_assert(ix < 4);
732 vg_assert(pxVals[ix] >= VexRegUpdSpAtMemAccess);
733 vg_assert(pxVals[ix] <= VexRegUpdAllregsAtEachInsn);
734 VG_(clo_vex_control).iropt_register_updates_default = pxVals[ix];
736 else if VG_STRINDEX_CLO(arg, "--px-default", pxStrings, ix) {
737 // NB: --px-default is an alias for the hard-to-remember
738 // --vex-iropt-register-updates, hence the same logic.
739 vg_assert(ix < 4);
740 vg_assert(pxVals[ix] >= VexRegUpdSpAtMemAccess);
741 vg_assert(pxVals[ix] <= VexRegUpdAllregsAtEachInsn);
742 VG_(clo_vex_control).iropt_register_updates_default = pxVals[ix];
744 else if VG_STRINDEX_CLO(arg, "--px-file-backed", pxStrings, ix) {
745 // Whereas --px-file-backed isn't
746 // the same flag as --vex-iropt-register-updates.
747 vg_assert(ix < 4);
748 vg_assert(pxVals[ix] >= VexRegUpdSpAtMemAccess);
749 vg_assert(pxVals[ix] <= VexRegUpdAllregsAtEachInsn);
750 VG_(clo_px_file_backed) = pxVals[ix];
753 else if VG_BINT_CLO(arg, "--vex-iropt-unroll-thresh",
754 VG_(clo_vex_control).iropt_unroll_thresh, 0, 400) {}
755 else if VG_BINT_CLO(arg, "--vex-guest-max-insns",
756 VG_(clo_vex_control).guest_max_insns, 1, 100) {}
757 else if VG_BINT_CLO(arg, "--vex-guest-chase-thresh",
758 VG_(clo_vex_control).guest_chase_thresh, 0, 99) {}
759 else if VG_BOOL_CLO(arg, "--vex-guest-chase-cond",
760 VG_(clo_vex_control).guest_chase_cond) {}
762 else if VG_INT_CLO(arg, "--log-fd", tmp_log_fd) {
763 log_to = VgLogTo_Fd;
764 log_fsname_unexpanded = NULL;
766 else if VG_INT_CLO(arg, "--xml-fd", tmp_xml_fd) {
767 xml_to = VgLogTo_Fd;
768 xml_fsname_unexpanded = NULL;
771 else if VG_STR_CLO(arg, "--log-file", log_fsname_unexpanded) {
772 log_to = VgLogTo_File;
774 else if VG_STR_CLO(arg, "--xml-file", xml_fsname_unexpanded) {
775 xml_to = VgLogTo_File;
778 else if VG_STR_CLO(arg, "--log-socket", log_fsname_unexpanded) {
779 log_to = VgLogTo_Socket;
781 else if VG_STR_CLO(arg, "--xml-socket", xml_fsname_unexpanded) {
782 xml_to = VgLogTo_Socket;
785 else if VG_STR_CLO(arg, "--debuginfo-server",
786 VG_(clo_debuginfo_server)) {}
788 else if VG_BOOL_CLO(arg, "--allow-mismatched-debuginfo",
789 VG_(clo_allow_mismatched_debuginfo)) {}
791 else if VG_STR_CLO(arg, "--xml-user-comment",
792 VG_(clo_xml_user_comment)) {}
794 else if VG_BOOL_CLO(arg, "--default-suppressions",
795 VG_(clo_default_supp)) {}
797 else if VG_STR_CLO(arg, "--suppressions", tmp_str) {
798 VG_(addToXA)(VG_(clo_suppressions), &tmp_str);
801 else if VG_STR_CLO (arg, "--fullpath-after", tmp_str) {
802 VG_(addToXA)(VG_(clo_fullpath_after), &tmp_str);
805 else if VG_STR_CLO (arg, "--extra-debuginfo-path",
806 VG_(clo_extra_debuginfo_path)) {}
808 else if VG_STR_CLO(arg, "--require-text-symbol", tmp_str) {
809 /* String needs to be of the form C?*C?*, where C is any
810 character, but is the same both times. Having it in this
811 form facilitates finding the boundary between the sopatt
812 and the fnpatt just by looking for the second occurrence
813 of C, without hardwiring any assumption about what C
814 is. */
815 HChar patt[7];
816 Bool ok = True;
817 ok = tmp_str && VG_(strlen)(tmp_str) > 0;
818 if (ok) {
819 patt[0] = patt[3] = tmp_str[0];
820 patt[1] = patt[4] = '?';
821 patt[2] = patt[5] = '*';
822 patt[6] = 0;
823 ok = VG_(string_match)(patt, tmp_str);
825 if (!ok) {
826 VG_(fmsg_bad_option)(arg,
827 "Invalid --require-text-symbol= specification.\n");
829 VG_(addToXA)(VG_(clo_req_tsyms), &tmp_str);
832 /* "stuvwxyz" --> stuvwxyz (binary) */
833 else if VG_STR_CLO(arg, "--trace-flags", tmp_str) {
834 Int j;
835 if (8 != VG_(strlen)(tmp_str)) {
836 VG_(fmsg_bad_option)(arg,
837 "--trace-flags argument must have 8 digits\n");
839 for (j = 0; j < 8; j++) {
840 if ('0' == tmp_str[j]) { /* do nothing */ }
841 else if ('1' == tmp_str[j]) VG_(clo_trace_flags) |= (1 << (7-j));
842 else {
843 VG_(fmsg_bad_option)(arg,
844 "--trace-flags argument can only contain 0s and 1s\n");
849 else if VG_INT_CLO (arg, "--trace-notbelow", VG_(clo_trace_notbelow)) {}
851 else if VG_INT_CLO (arg, "--trace-notabove", VG_(clo_trace_notabove)) {}
853 /* "stuvwxyz" --> stuvwxyz (binary) */
854 else if VG_STR_CLO(arg, "--profile-flags", tmp_str) {
855 Int j;
856 if (8 != VG_(strlen)(tmp_str)) {
857 VG_(fmsg_bad_option)(arg,
858 "--profile-flags argument must have 8 digits\n");
860 for (j = 0; j < 8; j++) {
861 if ('0' == tmp_str[j]) { /* do nothing */ }
862 else if ('1' == tmp_str[j]) VG_(clo_profyle_flags) |= (1 << (7-j));
863 else {
864 VG_(fmsg_bad_option)(arg,
865 "--profile-flags argument can only contain 0s and 1s\n");
868 VG_(clo_profyle_sbs) = True;
871 else if VG_INT_CLO (arg, "--profile-interval",
872 VG_(clo_profyle_interval)) {}
874 else if VG_XACT_CLO(arg, "--gen-suppressions=no",
875 VG_(clo_gen_suppressions), 0) {}
876 else if VG_XACT_CLO(arg, "--gen-suppressions=yes",
877 VG_(clo_gen_suppressions), 1) {}
878 else if VG_XACT_CLO(arg, "--gen-suppressions=all",
879 VG_(clo_gen_suppressions), 2) {}
881 else if VG_BINT_CLO(arg, "--unw-stack-scan-thresh",
882 VG_(clo_unw_stack_scan_thresh), 0, 100) {}
883 else if VG_BINT_CLO(arg, "--unw-stack-scan-frames",
884 VG_(clo_unw_stack_scan_frames), 0, 32) {}
886 else if VG_XACT_CLO(arg, "--resync-filter=no",
887 VG_(clo_resync_filter), 0) {}
888 else if VG_XACT_CLO(arg, "--resync-filter=yes",
889 VG_(clo_resync_filter), 1) {}
890 else if VG_XACT_CLO(arg, "--resync-filter=verbose",
891 VG_(clo_resync_filter), 2) {}
893 else if ( ! VG_(needs).command_line_options
894 || ! VG_TDICT_CALL(tool_process_cmd_line_option, arg) ) {
895 VG_(fmsg_unknown_option)(arg);
899 /* END command-line processing loop */
901 /* Notify about deprecated features */
902 if (VG_(clo_db_attach))
903 VG_(umsg)
904 ("\nWarning: --db-attach is a deprecated feature which will be\n"
905 " removed in the next release. Use --vgdb-error=1 instead\n\n");
907 /* Determine the path prefix for vgdb */
908 if (VG_(clo_vgdb_prefix) == NULL)
909 VG_(clo_vgdb_prefix) = VG_(vgdb_prefix_default)();
911 /* Make VEX control parameters sane */
913 if (VG_(clo_vex_control).guest_chase_thresh
914 >= VG_(clo_vex_control).guest_max_insns)
915 VG_(clo_vex_control).guest_chase_thresh
916 = VG_(clo_vex_control).guest_max_insns - 1;
918 if (VG_(clo_vex_control).guest_chase_thresh < 0)
919 VG_(clo_vex_control).guest_chase_thresh = 0;
921 /* Check various option values */
923 if (VG_(clo_verbosity) < 0)
924 VG_(clo_verbosity) = 0;
926 if (!sigill_diag_set)
927 VG_(clo_sigill_diag) = (VG_(clo_verbosity) > 0);
929 if (VG_(clo_trace_notbelow) == -1) {
930 if (VG_(clo_trace_notabove) == -1) {
931 /* [] */
932 VG_(clo_trace_notbelow) = 2147483647;
933 VG_(clo_trace_notabove) = 0;
934 } else {
935 /* [0 .. notabove] */
936 VG_(clo_trace_notbelow) = 0;
938 } else {
939 if (VG_(clo_trace_notabove) == -1) {
940 /* [notbelow .. ] */
941 VG_(clo_trace_notabove) = 2147483647;
942 } else {
943 /* [notbelow .. notabove] */
947 VG_(dyn_vgdb_error) = VG_(clo_vgdb_error);
949 if (VG_(clo_gen_suppressions) > 0 &&
950 !VG_(needs).core_errors && !VG_(needs).tool_errors) {
951 VG_(fmsg_bad_option)("--gen-suppressions=yes",
952 "Can't use --gen-suppressions= with %s\n"
953 "because it doesn't generate errors.\n", VG_(details).name);
956 # if !defined(VGO_darwin)
957 if (VG_(clo_resync_filter) != 0) {
958 VG_(fmsg_bad_option)("--resync-filter=yes or =verbose",
959 "--resync-filter= is only available on MacOS X.\n");
960 /*NOTREACHED*/
962 # endif
964 /* If XML output is requested, check that the tool actually
965 supports it. */
966 if (VG_(clo_xml) && !VG_(needs).xml_output) {
967 VG_(clo_xml) = False;
968 VG_(fmsg_bad_option)("--xml=yes",
969 "%s does not support XML output.\n", VG_(details).name);
970 /*NOTREACHED*/
973 vg_assert( VG_(clo_gen_suppressions) >= 0 );
974 vg_assert( VG_(clo_gen_suppressions) <= 2 );
976 /* If we've been asked to emit XML, mash around various other
977 options so as to constrain the output somewhat, and to remove
978 any need for user input during the run.
980 if (VG_(clo_xml)) {
982 /* We can't allow --gen-suppressions=yes, since that requires us
983 to print the error and then ask the user if she wants a
984 suppression for it, but in XML mode we won't print it until
985 we know whether we also need to print a suppression. Hence a
986 circular dependency. So disallow this.
987 (--gen-suppressions=all is still OK since we don't need any
988 user interaction in this case.) */
989 if (VG_(clo_gen_suppressions) == 1) {
990 VG_(fmsg_bad_option)(
991 "--xml=yes together with --gen-suppressions=yes",
992 "When --xml=yes is specified, --gen-suppressions=no\n"
993 "or --gen-suppressions=all is allowed, but not "
994 "--gen-suppressions=yes.\n");
997 /* We can't allow DB attaching (or we maybe could, but results
998 could be chaotic ..) since it requires user input. Hence
999 disallow. */
1000 if (VG_(clo_db_attach)) {
1001 VG_(fmsg_bad_option)(
1002 "--xml=yes together with --db-attach=yes",
1003 "--db-attach=yes is not allowed with --xml=yes\n"
1004 "because it would require user input.\n");
1007 /* Disallow dump_error in XML mode; sounds like a recipe for
1008 chaos. No big deal; dump_error is a flag for debugging V
1009 itself. */
1010 if (VG_(clo_dump_error) > 0) {
1011 VG_(fmsg_bad_option)("--xml=yes",
1012 "Cannot be used together with --dump-error");
1015 /* Disable error limits (this might be a bad idea!) */
1016 VG_(clo_error_limit) = False;
1017 /* Disable emulation warnings */
1019 /* Also, we want to set options for the leak checker, but that
1020 will have to be done in Memcheck's flag-handling code, not
1021 here. */
1024 /* All non-logging-related options have been checked. If the logging
1025 option specified is ok, we can switch to it, as we know we won't
1026 have to generate any other command-line-related error messages.
1027 (So far we should be still attached to stderr, so we can show on
1028 the terminal any problems to do with processing command line
1029 opts.)
1031 So set up logging now. After this is done, VG_(log_output_sink)
1032 and (if relevant) VG_(xml_output_sink) should be connected to
1033 whatever sink has been selected, and we indiscriminately chuck
1034 stuff into it without worrying what the nature of it is. Oh the
1035 wonder of Unix streams. */
1037 vg_assert(VG_(log_output_sink).fd == 2 /* stderr */);
1038 vg_assert(VG_(log_output_sink).is_socket == False);
1039 vg_assert(VG_(clo_log_fname_expanded) == NULL);
1041 vg_assert(VG_(xml_output_sink).fd == -1 /* disabled */);
1042 vg_assert(VG_(xml_output_sink).is_socket == False);
1043 vg_assert(VG_(clo_xml_fname_expanded) == NULL);
1045 /* --- set up the normal text output channel --- */
1047 switch (log_to) {
1049 case VgLogTo_Fd:
1050 vg_assert(log_fsname_unexpanded == NULL);
1051 break;
1053 case VgLogTo_File: {
1054 HChar* logfilename;
1056 vg_assert(log_fsname_unexpanded != NULL);
1057 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
1059 // Nb: we overwrite an existing file of this name without asking
1060 // any questions.
1061 logfilename = VG_(expand_file_name)("--log-file",
1062 log_fsname_unexpanded);
1063 sres = VG_(open)(logfilename,
1064 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
1065 VKI_S_IRUSR|VKI_S_IWUSR|VKI_S_IRGRP|VKI_S_IROTH);
1066 if (!sr_isError(sres)) {
1067 tmp_log_fd = sr_Res(sres);
1068 VG_(clo_log_fname_expanded) = logfilename;
1069 } else {
1070 VG_(fmsg)("can't create log file '%s': %s\n",
1071 logfilename, VG_(strerror)(sr_Err(sres)));
1072 VG_(exit)(1);
1073 /*NOTREACHED*/
1075 break;
1078 case VgLogTo_Socket: {
1079 vg_assert(log_fsname_unexpanded != NULL);
1080 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
1081 tmp_log_fd = VG_(connect_via_socket)( log_fsname_unexpanded );
1082 if (tmp_log_fd == -1) {
1083 VG_(fmsg)("Invalid --log-socket spec of '%s'\n",
1084 log_fsname_unexpanded);
1085 VG_(exit)(1);
1086 /*NOTREACHED*/
1088 if (tmp_log_fd == -2) {
1089 VG_(umsg)("failed to connect to logging server '%s'.\n"
1090 "Log messages will sent to stderr instead.\n",
1091 log_fsname_unexpanded );
1093 /* We don't change anything here. */
1094 vg_assert(VG_(log_output_sink).fd == 2);
1095 tmp_log_fd = 2;
1096 } else {
1097 vg_assert(tmp_log_fd > 0);
1098 VG_(log_output_sink).is_socket = True;
1100 break;
1104 /* --- set up the XML output channel --- */
1106 switch (xml_to) {
1108 case VgLogTo_Fd:
1109 vg_assert(xml_fsname_unexpanded == NULL);
1110 break;
1112 case VgLogTo_File: {
1113 HChar* xmlfilename;
1115 vg_assert(xml_fsname_unexpanded != NULL);
1116 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
1118 // Nb: we overwrite an existing file of this name without asking
1119 // any questions.
1120 xmlfilename = VG_(expand_file_name)("--xml-file",
1121 xml_fsname_unexpanded);
1122 sres = VG_(open)(xmlfilename,
1123 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
1124 VKI_S_IRUSR|VKI_S_IWUSR|VKI_S_IRGRP|VKI_S_IROTH);
1125 if (!sr_isError(sres)) {
1126 tmp_xml_fd = sr_Res(sres);
1127 VG_(clo_xml_fname_expanded) = xmlfilename;
1128 *xml_fname_unexpanded = xml_fsname_unexpanded;
1129 } else {
1130 VG_(fmsg)("can't create XML file '%s': %s\n",
1131 xmlfilename, VG_(strerror)(sr_Err(sres)));
1132 VG_(exit)(1);
1133 /*NOTREACHED*/
1135 break;
1138 case VgLogTo_Socket: {
1139 vg_assert(xml_fsname_unexpanded != NULL);
1140 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
1141 tmp_xml_fd = VG_(connect_via_socket)( xml_fsname_unexpanded );
1142 if (tmp_xml_fd == -1) {
1143 VG_(fmsg)("Invalid --xml-socket spec of '%s'\n",
1144 xml_fsname_unexpanded );
1145 VG_(exit)(1);
1146 /*NOTREACHED*/
1148 if (tmp_xml_fd == -2) {
1149 VG_(umsg)("failed to connect to XML logging server '%s'.\n"
1150 "XML output will sent to stderr instead.\n",
1151 xml_fsname_unexpanded);
1152 /* We don't change anything here. */
1153 vg_assert(VG_(xml_output_sink).fd == 2);
1154 tmp_xml_fd = 2;
1155 } else {
1156 vg_assert(tmp_xml_fd > 0);
1157 VG_(xml_output_sink).is_socket = True;
1159 break;
1163 /* If we've got this far, and XML mode was requested, but no XML
1164 output channel appears to have been specified, just stop. We
1165 could continue, and XML output will simply vanish into nowhere,
1166 but that is likely to confuse the hell out of users, which is
1167 distinctly Ungood. */
1168 if (VG_(clo_xml) && tmp_xml_fd == -1) {
1169 VG_(fmsg_bad_option)(
1170 "--xml=yes, but no XML destination specified",
1171 "--xml=yes has been specified, but there is no XML output\n"
1172 "destination. You must specify an XML output destination\n"
1173 "using --xml-fd, --xml-file or --xml-socket.\n"
1177 // Finalise the output fds: the log fd ..
1179 if (tmp_log_fd >= 0) {
1180 // Move log_fd into the safe range, so it doesn't conflict with
1181 // any app fds.
1182 tmp_log_fd = VG_(fcntl)(tmp_log_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
1183 if (tmp_log_fd < 0) {
1184 VG_(message)(Vg_UserMsg, "valgrind: failed to move logfile fd "
1185 "into safe range, using stderr\n");
1186 VG_(log_output_sink).fd = 2; // stderr
1187 VG_(log_output_sink).is_socket = False;
1188 } else {
1189 VG_(log_output_sink).fd = tmp_log_fd;
1190 VG_(fcntl)(VG_(log_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
1192 } else {
1193 // If they said --log-fd=-1, don't print anything. Plausible for use in
1194 // regression testing suites that use client requests to count errors.
1195 VG_(log_output_sink).fd = -1;
1196 VG_(log_output_sink).is_socket = False;
1199 // Finalise the output fds: and the XML fd ..
1201 if (tmp_xml_fd >= 0) {
1202 // Move xml_fd into the safe range, so it doesn't conflict with
1203 // any app fds.
1204 tmp_xml_fd = VG_(fcntl)(tmp_xml_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
1205 if (tmp_xml_fd < 0) {
1206 VG_(message)(Vg_UserMsg, "valgrind: failed to move XML file fd "
1207 "into safe range, using stderr\n");
1208 VG_(xml_output_sink).fd = 2; // stderr
1209 VG_(xml_output_sink).is_socket = False;
1210 } else {
1211 VG_(xml_output_sink).fd = tmp_xml_fd;
1212 VG_(fcntl)(VG_(xml_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
1214 } else {
1215 // If they said --xml-fd=-1, don't print anything. Plausible for use in
1216 // regression testing suites that use client requests to count errors.
1217 VG_(xml_output_sink).fd = -1;
1218 VG_(xml_output_sink).is_socket = False;
1221 // Suppressions related stuff
1223 if (VG_(clo_default_supp) &&
1224 (VG_(needs).core_errors || VG_(needs).tool_errors)) {
1225 /* If we haven't reached the max number of suppressions, load
1226 the default one. */
1227 static const HChar default_supp[] = "default.supp";
1228 Int len = VG_(strlen)(VG_(libdir)) + 1 + sizeof(default_supp);
1229 HChar *buf = VG_(malloc)("main.mpclo.3", len);
1230 VG_(sprintf)(buf, "%s/%s", VG_(libdir), default_supp);
1231 VG_(addToXA)(VG_(clo_suppressions), &buf);
1234 *logging_to_fd = log_to == VgLogTo_Fd || log_to == VgLogTo_Socket;
1237 // Write the name and value of log file qualifiers to the xml file.
1238 // We can safely assume here that the format string is well-formed.
1239 // It has been checked earlier in VG_(expand_file_name) when processing
1240 // command line options.
1241 static void print_file_vars(const HChar* format)
1243 Int i = 0;
1245 while (format[i]) {
1246 if (format[i] == '%') {
1247 // We saw a '%'. What's next...
1248 i++;
1249 if ('q' == format[i]) {
1250 i++;
1251 if ('{' == format[i]) {
1252 // Get the env var name, print its contents.
1253 HChar* qual;
1254 Int begin_qualname = ++i;
1255 while (True) {
1256 if ('}' == format[i]) {
1257 Int qualname_len = i - begin_qualname;
1258 HChar qualname[qualname_len + 1];
1259 VG_(strncpy)(qualname, format + begin_qualname,
1260 qualname_len);
1261 qualname[qualname_len] = '\0';
1262 qual = VG_(getenv)(qualname);
1263 i++;
1264 VG_(printf_xml)("<logfilequalifier> <var>%pS</var> "
1265 "<value>%pS</value> </logfilequalifier>\n",
1266 qualname, qual);
1267 break;
1269 i++;
1273 } else {
1274 i++;
1280 /*====================================================================*/
1281 /*=== Printing the preamble ===*/
1282 /*====================================================================*/
1284 // Print the argument, escaping any chars that require it.
1285 static void umsg_arg(const HChar* arg)
1287 SizeT len = VG_(strlen)(arg);
1288 const HChar* special = " \\<>";
1289 Int i;
1290 for (i = 0; i < len; i++) {
1291 if (VG_(strchr)(special, arg[i])) {
1292 VG_(umsg)("\\"); // escape with a backslash if necessary
1294 VG_(umsg)("%c", arg[i]);
1298 // Send output to the XML-stream and escape any XML meta-characters.
1299 static void xml_arg(const HChar* arg)
1301 VG_(printf_xml)("%pS", arg);
1304 /* Ok, the logging sink is running now. Print a suitable preamble.
1305 If logging to file or a socket, write details of parent PID and
1306 command line args, to help people trying to interpret the
1307 results of a run which encompasses multiple processes. */
1308 static void print_preamble ( Bool logging_to_fd,
1309 const HChar* xml_fname_unexpanded,
1310 const HChar* toolname )
1312 Int i;
1313 const HChar* xpre = VG_(clo_xml) ? " <line>" : "";
1314 const HChar* xpost = VG_(clo_xml) ? "</line>" : "";
1315 UInt (*umsg_or_xml)( const HChar*, ... )
1316 = VG_(clo_xml) ? VG_(printf_xml) : VG_(umsg);
1318 void (*umsg_or_xml_arg)( const HChar* )
1319 = VG_(clo_xml) ? xml_arg : umsg_arg;
1321 vg_assert( VG_(args_for_client) );
1322 vg_assert( VG_(args_for_valgrind) );
1323 vg_assert( toolname );
1325 if (VG_(clo_xml)) {
1326 VG_(printf_xml)("<?xml version=\"1.0\"?>\n");
1327 VG_(printf_xml)("\n");
1328 VG_(printf_xml)("<valgrindoutput>\n");
1329 VG_(printf_xml)("\n");
1330 VG_(printf_xml)("<protocolversion>4</protocolversion>\n");
1331 VG_(printf_xml)("<protocoltool>%s</protocoltool>\n", toolname);
1332 VG_(printf_xml)("\n");
1335 if (VG_(clo_xml) || VG_(clo_verbosity > 0)) {
1337 if (VG_(clo_xml))
1338 VG_(printf_xml)("<preamble>\n");
1340 /* Tool details */
1341 umsg_or_xml( VG_(clo_xml) ? "%s%pS%pS%pS, %pS%s\n" : "%s%s%s%s, %s%s\n",
1342 xpre,
1343 VG_(details).name,
1344 NULL == VG_(details).version ? "" : "-",
1345 NULL == VG_(details).version
1346 ? "" : VG_(details).version,
1347 VG_(details).description,
1348 xpost );
1350 if (VG_(strlen)(toolname) >= 4 && VG_STREQN(4, toolname, "exp-")) {
1351 umsg_or_xml(
1352 "%sNOTE: This is an Experimental-Class Valgrind Tool%s\n",
1353 xpre, xpost
1357 umsg_or_xml( VG_(clo_xml) ? "%s%pS%s\n" : "%s%s%s\n",
1358 xpre, VG_(details).copyright_author, xpost );
1360 /* Core details */
1361 umsg_or_xml(
1362 "%sUsing Valgrind-%s and LibVEX; rerun with -h for copyright info%s\n",
1363 xpre, VERSION, xpost
1366 // Print the command line. At one point we wrapped at 80 chars and
1367 // printed a '\' as a line joiner, but that makes it hard to cut and
1368 // paste the command line (because of the "==pid==" prefixes), so we now
1369 // favour utility and simplicity over aesthetics.
1370 umsg_or_xml("%sCommand: ", xpre);
1371 umsg_or_xml_arg(VG_(args_the_exename));
1373 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1374 HChar* s = *(HChar**)VG_(indexXA)( VG_(args_for_client), i );
1375 umsg_or_xml(" ");
1376 umsg_or_xml_arg(s);
1378 umsg_or_xml("%s\n", xpost);
1380 if (VG_(clo_xml))
1381 VG_(printf_xml)("</preamble>\n");
1384 // Print the parent PID, and other stuff, if necessary.
1385 if (!VG_(clo_xml) && VG_(clo_verbosity) > 0 && !logging_to_fd) {
1386 VG_(umsg)("Parent PID: %d\n", VG_(getppid)());
1388 else
1389 if (VG_(clo_xml)) {
1390 VG_(printf_xml)("\n");
1391 VG_(printf_xml)("<pid>%d</pid>\n", VG_(getpid)());
1392 VG_(printf_xml)("<ppid>%d</ppid>\n", VG_(getppid)());
1393 VG_(printf_xml)("<tool>%pS</tool>\n", toolname);
1394 if (xml_fname_unexpanded)
1395 print_file_vars(xml_fname_unexpanded);
1396 if (VG_(clo_xml_user_comment)) {
1397 /* Note: the user comment itself is XML and is therefore to
1398 be passed through verbatim (%s) rather than escaped
1399 (%pS). */
1400 VG_(printf_xml)("<usercomment>%s</usercomment>\n",
1401 VG_(clo_xml_user_comment));
1403 VG_(printf_xml)("\n");
1404 VG_(printf_xml)("<args>\n");
1406 VG_(printf_xml)(" <vargv>\n");
1407 if (VG_(name_of_launcher))
1408 VG_(printf_xml)(" <exe>%pS</exe>\n",
1409 VG_(name_of_launcher));
1410 else
1411 VG_(printf_xml)(" <exe>%pS</exe>\n",
1412 "(launcher name unknown)");
1413 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
1414 VG_(printf_xml)(
1415 " <arg>%pS</arg>\n",
1416 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1419 VG_(printf_xml)(" </vargv>\n");
1421 VG_(printf_xml)(" <argv>\n");
1422 VG_(printf_xml)(" <exe>%pS</exe>\n",
1423 VG_(args_the_exename));
1424 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1425 VG_(printf_xml)(
1426 " <arg>%pS</arg>\n",
1427 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1430 VG_(printf_xml)(" </argv>\n");
1432 VG_(printf_xml)("</args>\n");
1435 // Last thing in the preamble is a blank line.
1436 if (VG_(clo_xml))
1437 VG_(printf_xml)("\n");
1438 else if (VG_(clo_verbosity) > 0)
1439 VG_(umsg)("\n");
1441 if (VG_(clo_verbosity) > 1) {
1442 SysRes fd;
1443 VexArch vex_arch;
1444 VexArchInfo vex_archinfo;
1445 if (!logging_to_fd)
1446 VG_(message)(Vg_DebugMsg, "\n");
1447 VG_(message)(Vg_DebugMsg, "Valgrind options:\n");
1448 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
1449 VG_(message)(Vg_DebugMsg,
1450 " %s\n",
1451 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ));
1454 VG_(message)(Vg_DebugMsg, "Contents of /proc/version:\n");
1455 fd = VG_(open) ( "/proc/version", VKI_O_RDONLY, 0 );
1456 if (sr_isError(fd)) {
1457 VG_(message)(Vg_DebugMsg, " can't open /proc/version\n");
1458 } else {
1459 const SizeT bufsiz = 255;
1460 HChar version_buf[bufsiz+1];
1461 VG_(message)(Vg_DebugMsg, " ");
1462 Int n, fdno = sr_Res(fd);
1463 do {
1464 n = VG_(read)(fdno, version_buf, bufsiz);
1465 if (n < 0) {
1466 VG_(message)(Vg_DebugMsg, " error reading /proc/version\n");
1467 break;
1469 version_buf[n] = '\0';
1470 VG_(message)(Vg_DebugMsg, "%s", version_buf);
1471 } while (n == bufsiz);
1472 VG_(message)(Vg_DebugMsg, "\n");
1473 VG_(close)(fdno);
1476 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
1477 VG_(message)(
1478 Vg_DebugMsg,
1479 "Arch and hwcaps: %s, %s, %s\n",
1480 LibVEX_ppVexArch ( vex_arch ),
1481 LibVEX_ppVexEndness ( vex_archinfo.endness ),
1482 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1484 VG_(message)(
1485 Vg_DebugMsg,
1486 "Page sizes: currently %d, max supported %d\n",
1487 (Int)VKI_PAGE_SIZE, (Int)VKI_MAX_PAGE_SIZE
1489 VG_(message)(Vg_DebugMsg,
1490 "Valgrind library directory: %s\n", VG_(libdir));
1495 /*====================================================================*/
1496 /*=== File descriptor setup ===*/
1497 /*====================================================================*/
1499 /* Number of file descriptors that Valgrind tries to reserve for
1500 it's own use - just a small constant. */
1501 #define N_RESERVED_FDS (10)
1503 static void setup_file_descriptors(void)
1505 struct vki_rlimit rl;
1506 Bool show = False;
1508 /* Get the current file descriptor limits. */
1509 if (VG_(getrlimit)(VKI_RLIMIT_NOFILE, &rl) < 0) {
1510 rl.rlim_cur = 1024;
1511 rl.rlim_max = 1024;
1514 # if defined(VGO_darwin)
1515 /* Darwin lies. It reports file max as RLIM_INFINITY but
1516 silently disallows anything bigger than 10240. */
1517 if (rl.rlim_cur >= 10240 && rl.rlim_max == 0x7fffffffffffffffULL) {
1518 rl.rlim_max = 10240;
1520 # endif
1522 if (show)
1523 VG_(printf)("fd limits: host, before: cur %lu max %lu\n",
1524 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
1526 /* Work out where to move the soft limit to. */
1527 if (rl.rlim_cur + N_RESERVED_FDS <= rl.rlim_max) {
1528 rl.rlim_cur = rl.rlim_cur + N_RESERVED_FDS;
1529 } else {
1530 rl.rlim_cur = rl.rlim_max;
1533 /* Reserve some file descriptors for our use. */
1534 VG_(fd_soft_limit) = rl.rlim_cur - N_RESERVED_FDS;
1535 VG_(fd_hard_limit) = rl.rlim_cur - N_RESERVED_FDS;
1537 /* Update the soft limit. */
1538 VG_(setrlimit)(VKI_RLIMIT_NOFILE, &rl);
1540 if (show) {
1541 VG_(printf)("fd limits: host, after: cur %lu max %lu\n",
1542 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
1543 VG_(printf)("fd limits: guest : cur %u max %u\n",
1544 VG_(fd_soft_limit), VG_(fd_hard_limit));
1547 if (VG_(cl_exec_fd) != -1)
1548 VG_(cl_exec_fd) = VG_(safe_fd)( VG_(cl_exec_fd) );
1552 /*====================================================================*/
1553 /*=== main() ===*/
1554 /*====================================================================*/
1556 /* When main() is entered, we should be on the following stack, not
1557 the one the kernel gave us. We will run on this stack until
1558 simulation of the root thread is started, at which point a transfer
1559 is made to a dynamically allocated stack. This is for the sake of
1560 uniform overflow detection for all Valgrind threads. This is
1561 marked global even though it isn't, because assembly code below
1562 needs to reference the name. */
1564 /*static*/ struct {
1565 HChar bytes [VG_STACK_GUARD_SZB + VG_DEFAULT_STACK_ACTIVE_SZB + VG_STACK_GUARD_SZB];
1566 } VG_(interim_stack);
1568 /* These are the structures used to hold info for creating the initial
1569 client image.
1571 'iicii' mostly holds important register state present at system
1572 startup (_start_valgrind). valgrind_main() then fills in the rest
1573 of it and passes it to VG_(ii_create_image)(). That produces
1574 'iifii', which is later handed to VG_(ii_finalise_image). */
1576 /* In all OS-instantiations, the_iicii has a field .sp_at_startup.
1577 This should get some address inside the stack on which we gained
1578 control (eg, it could be the SP at startup). It doesn't matter
1579 exactly where in the stack it is. This value is passed to the
1580 address space manager at startup. On Linux, aspacem then uses it
1581 to identify the initial stack segment and hence the upper end of
1582 the usable address space. */
1584 static IICreateImageInfo the_iicii;
1585 static IIFinaliseImageInfo the_iifii;
1588 /* A simple pair structure, used for conveying debuginfo handles to
1589 calls to VG_TRACK(new_mem_startup, ...). */
1590 typedef struct { Addr a; ULong ull; } Addr_n_ULong;
1593 /* --- Forwards decls to do with shutdown --- */
1595 static void final_tidyup(ThreadId tid);
1597 /* Do everything which needs doing when the last thread exits */
1598 static
1599 void shutdown_actions_NORETURN( ThreadId tid,
1600 VgSchedReturnCode tids_schedretcode );
1602 /* --- end of Forwards decls to do with shutdown --- */
1605 /* By the time we get to valgrind_main, the_iicii should already have
1606 been filled in with any important details as required by whatever
1607 OS we have been built for.
1609 static
1610 Int valgrind_main ( Int argc, HChar **argv, HChar **envp )
1612 const HChar* toolname = "memcheck"; // default to Memcheck
1613 Int need_help = 0; // 0 = no, 1 = --help, 2 = --help-debug
1614 ThreadId tid_main = VG_INVALID_THREADID;
1615 Bool logging_to_fd = False;
1616 const HChar* xml_fname_unexpanded = NULL;
1617 Int loglevel, i;
1618 struct vki_rlimit zero = { 0, 0 };
1619 XArray* addr2dihandle = NULL;
1621 //============================================================
1623 // Nb: startup is complex. Prerequisites are shown at every step.
1624 // *** Be very careful when messing with the order ***
1626 // The first order of business is to get debug logging, the address
1627 // space manager and the dynamic memory manager up and running.
1628 // Once that's done, we can relax a bit.
1630 //============================================================
1632 /* This is needed to make VG_(getenv) usable early. */
1633 VG_(client_envp) = (HChar**)envp;
1635 //--------------------------------------------------------------
1636 // Start up Mach kernel interface, if any
1637 // p: none
1638 //--------------------------------------------------------------
1639 # if defined(VGO_darwin)
1640 VG_(mach_init)();
1641 # endif
1643 //--------------------------------------------------------------
1644 // Start up the logging mechanism
1645 // p: none
1646 //--------------------------------------------------------------
1647 /* Start the debugging-log system ASAP. First find out how many
1648 "-d"s were specified. This is a pre-scan of the command line. Also
1649 get --profile-heap=yes, --core-redzone-size, --redzone-size
1650 --aspace-minaddr which are needed by the time we start up dynamic
1651 memory management. */
1652 loglevel = 0;
1653 for (i = 1; i < argc; i++) {
1654 const HChar* tmp_str;
1655 if (argv[i][0] != '-') break;
1656 if VG_STREQ(argv[i], "--") break;
1657 if VG_STREQ(argv[i], "-d") loglevel++;
1658 if VG_BOOL_CLO(argv[i], "--profile-heap", VG_(clo_profile_heap)) {}
1659 if VG_BINT_CLO(argv[i], "--core-redzone-size", VG_(clo_core_redzone_size),
1660 0, MAX_CLO_REDZONE_SZB) {}
1661 if VG_BINT_CLO(argv[i], "--redzone-size", VG_(clo_redzone_size),
1662 0, MAX_CLO_REDZONE_SZB) {}
1663 if VG_STR_CLO(argv[i], "--aspace-minaddr", tmp_str) {
1664 # if VG_WORDSIZE == 4
1665 const Addr max = (Addr) 0x40000000; // 1Gb
1666 # else
1667 const Addr max = (Addr) 0x200000000; // 8Gb
1668 # endif
1669 Bool ok = VG_(parse_Addr) (&tmp_str, &VG_(clo_aspacem_minAddr));
1670 if (!ok)
1671 VG_(fmsg_bad_option)(argv[i], "Invalid address\n");
1673 if (!VG_IS_PAGE_ALIGNED(VG_(clo_aspacem_minAddr))
1674 || VG_(clo_aspacem_minAddr) < (Addr) 0x1000
1675 || VG_(clo_aspacem_minAddr) > max) // 1Gb
1676 VG_(fmsg_bad_option)(argv[i],
1677 "Must be a page aligned address between "
1678 "0x1000 and 0x%lx\n", max);
1682 /* ... and start the debug logger. Now we can safely emit logging
1683 messages all through startup. */
1684 VG_(debugLog_startup)(loglevel, "Stage 2 (main)");
1685 VG_(debugLog)(1, "main", "Welcome to Valgrind version "
1686 VERSION " debug logging\n");
1688 //--------------------------------------------------------------
1689 // Ensure we're on a plausible stack.
1690 // p: logging
1691 //--------------------------------------------------------------
1692 VG_(debugLog)(1, "main", "Checking current stack is plausible\n");
1693 { HChar* limLo = (HChar*)(&VG_(interim_stack).bytes[0]);
1694 HChar* limHi = limLo + sizeof(VG_(interim_stack));
1695 HChar* volatile
1696 aLocal = (HChar*)&limLo; /* any auto local will do */
1697 /* Re "volatile": Apple clang version 4.0
1698 (tags/Apple/clang-421.0.57) (based on LLVM 3.1svn)" appeared
1699 to miscompile the following check, causing run to abort at
1700 this point (in 64-bit mode) even though aLocal is within limLo
1701 .. limHi. But in fact clang is within its rights to do
1702 strange things here. "The reason is that the comparisons
1703 aLocal < limLo and aLocal >= limHi cause undefined behaviour
1704 (according to c99 6.5.8) because they compare pointers that do
1705 not point into the same aggregate." Adding "volatile" appears
1706 to fix it because "The compiler would have to prove that there
1707 is undefined behavior in order to exploit it. But as a
1708 volatile variable can change its value in ways invisible to
1709 the compiler, the compiler must make the conservative
1710 assumption that it points into the same aggregate as the other
1711 pointer its compared against. I.e. the behaviour is possibly
1712 defined." (Analysis by Florian Krohm). */
1713 if (aLocal < limLo || aLocal >= limHi) {
1714 /* something's wrong. Stop. */
1715 VG_(debugLog)(0, "main", "Root stack %p to %p, a local %p\n",
1716 limLo, limHi, aLocal );
1717 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1718 "Initial stack switched failed.\n");
1719 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1720 VG_(exit)(1);
1724 //--------------------------------------------------------------
1725 // Ensure we have a plausible pointer to the stack on which
1726 // we gained control (not the current stack!)
1727 // p: logging
1728 //--------------------------------------------------------------
1729 VG_(debugLog)(1, "main", "Checking initial stack was noted\n");
1730 if (the_iicii.sp_at_startup == 0) {
1731 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1732 "Initial stack was not noted.\n");
1733 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1734 VG_(exit)(1);
1737 //--------------------------------------------------------------
1738 // Start up the address space manager, and determine the
1739 // approximate location of the client's stack
1740 // p: logging, plausible-stack
1741 //--------------------------------------------------------------
1742 VG_(debugLog)(1, "main", "Starting the address space manager\n");
1743 vg_assert(VKI_PAGE_SIZE == 4096 || VKI_PAGE_SIZE == 65536
1744 || VKI_PAGE_SIZE == 16384);
1745 vg_assert(VKI_MAX_PAGE_SIZE == 4096 || VKI_MAX_PAGE_SIZE == 65536
1746 || VKI_MAX_PAGE_SIZE == 16384);
1747 vg_assert(VKI_PAGE_SIZE <= VKI_MAX_PAGE_SIZE);
1748 vg_assert(VKI_PAGE_SIZE == (1 << VKI_PAGE_SHIFT));
1749 vg_assert(VKI_MAX_PAGE_SIZE == (1 << VKI_MAX_PAGE_SHIFT));
1750 the_iicii.clstack_end = VG_(am_startup)( the_iicii.sp_at_startup );
1751 VG_(debugLog)(1, "main", "Address space manager is running\n");
1753 //--------------------------------------------------------------
1754 // Start up the dynamic memory manager
1755 // p: address space management
1756 // p: getting --profile-heap,--core-redzone-size,--redzone-size
1757 // In fact m_mallocfree is self-initialising, so there's no
1758 // initialisation call to do. Instead, try a simple malloc/
1759 // free pair right now to check that nothing is broken.
1760 //--------------------------------------------------------------
1761 VG_(debugLog)(1, "main", "Starting the dynamic memory manager\n");
1762 { void* p = VG_(malloc)( "main.vm.1", 12345 );
1763 VG_(free)( p );
1765 VG_(debugLog)(1, "main", "Dynamic memory manager is running\n");
1767 //============================================================
1769 // Dynamic memory management is now available.
1771 //============================================================
1773 //--------------------------------------------------------------
1774 // Initialise m_debuginfo
1775 // p: dynamic memory allocation
1776 VG_(debugLog)(1, "main", "Initialise m_debuginfo\n");
1777 VG_(di_initialise)();
1779 //--------------------------------------------------------------
1780 // Look for alternative libdir
1781 { HChar *cp = VG_(getenv)(VALGRIND_LIB);
1782 if (cp != NULL)
1783 VG_(libdir) = cp;
1784 VG_(debugLog)(1, "main", "VG_(libdir) = %s\n", VG_(libdir));
1787 //--------------------------------------------------------------
1788 // Extract the launcher name from the environment.
1789 VG_(debugLog)(1, "main", "Getting launcher's name ...\n");
1790 VG_(name_of_launcher) = VG_(getenv)(VALGRIND_LAUNCHER);
1791 if (VG_(name_of_launcher) == NULL) {
1792 VG_(printf)("valgrind: You cannot run '%s' directly.\n", argv[0]);
1793 VG_(printf)("valgrind: You should use $prefix/bin/valgrind.\n");
1794 VG_(exit)(1);
1796 VG_(debugLog)(1, "main", "... %s\n", VG_(name_of_launcher));
1798 //--------------------------------------------------------------
1799 // Get the current process datasize rlimit, and set it to zero.
1800 // This prevents any internal uses of brk() from having any effect.
1801 // We remember the old value so we can restore it on exec, so that
1802 // child processes will have a reasonable brk value.
1803 VG_(getrlimit)(VKI_RLIMIT_DATA, &VG_(client_rlimit_data));
1804 zero.rlim_max = VG_(client_rlimit_data).rlim_max;
1805 VG_(setrlimit)(VKI_RLIMIT_DATA, &zero);
1807 // Get the current process stack rlimit.
1808 VG_(getrlimit)(VKI_RLIMIT_STACK, &VG_(client_rlimit_stack));
1810 //--------------------------------------------------------------
1811 // Figure out what sort of CPU we're on, and whether it is
1812 // able to run V.
1813 VG_(debugLog)(1, "main", "Get hardware capabilities ...\n");
1814 { VexArch vex_arch;
1815 VexArchInfo vex_archinfo;
1816 Bool ok = VG_(machine_get_hwcaps)();
1817 if (!ok) {
1818 VG_(printf)("\n");
1819 VG_(printf)("valgrind: fatal error: unsupported CPU.\n");
1820 VG_(printf)(" Supported CPUs are:\n");
1821 VG_(printf)(" * x86 (practically any; Pentium-I or above), "
1822 "AMD Athlon or above)\n");
1823 VG_(printf)(" * AMD Athlon64/Opteron\n");
1824 VG_(printf)(" * ARM (armv7)\n");
1825 VG_(printf)(" * PowerPC (most; ppc405 and above)\n");
1826 VG_(printf)(" * System z (64bit only - s390x; z990 and above)\n");
1827 VG_(printf)("\n");
1828 VG_(exit)(1);
1830 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
1831 VG_(debugLog)(
1832 1, "main", "... arch = %s, hwcaps = %s\n",
1833 LibVEX_ppVexArch ( vex_arch ),
1834 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1838 //--------------------------------------------------------------
1839 // Record the working directory at startup
1840 // p: none
1841 VG_(debugLog)(1, "main", "Getting the working directory at startup\n");
1842 { Bool ok = VG_(record_startup_wd)();
1843 if (!ok)
1844 VG_(err_config_error)( "Can't establish current working "
1845 "directory at startup\n");
1847 VG_(debugLog)(1, "main", "... %s\n", VG_(get_startup_wd)() );
1849 //============================================================
1850 // Command line argument handling order:
1851 // * If --help/--help-debug are present, show usage message
1852 // (including the tool-specific usage)
1853 // * (If no --tool option given, default to Memcheck)
1854 // * Then, if client is missing, abort with error msg
1855 // * Then, if any cmdline args are bad, abort with error msg
1856 //============================================================
1858 //--------------------------------------------------------------
1859 // Split up argv into: C args, V args, V extra args, and exename.
1860 // p: dynamic memory allocation
1861 //--------------------------------------------------------------
1862 VG_(debugLog)(1, "main", "Split up command line\n");
1863 VG_(split_up_argv)( argc, argv );
1864 vg_assert( VG_(args_for_valgrind) );
1865 vg_assert( VG_(args_for_client) );
1866 if (0) {
1867 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++)
1868 VG_(printf)(
1869 "varg %s\n",
1870 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1872 VG_(printf)(" exe %s\n", VG_(args_the_exename));
1873 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++)
1874 VG_(printf)(
1875 "carg %s\n",
1876 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1880 //--------------------------------------------------------------
1881 // Extract tool name and whether help has been requested.
1882 // Note we can't print the help message yet, even if requested,
1883 // because the tool has not been initialised.
1884 // p: split_up_argv [for VG_(args_for_valgrind)]
1885 //--------------------------------------------------------------
1886 VG_(debugLog)(1, "main",
1887 "(early_) Process Valgrind's command line options\n");
1888 early_process_cmd_line_options(&need_help, &toolname);
1890 // BEGIN HACK
1891 vg_assert(toolname != NULL);
1892 vg_assert(VG_(clo_read_inline_info) == False);
1893 # if !defined(VGO_darwin)
1894 if (0 == VG_(strcmp)(toolname, "memcheck")
1895 || 0 == VG_(strcmp)(toolname, "helgrind")
1896 || 0 == VG_(strcmp)(toolname, "drd")) {
1897 /* Change the default setting. Later on (just below)
1898 main_process_cmd_line_options should pick up any
1899 user-supplied setting for it and will override the default
1900 set here. */
1901 VG_(clo_read_inline_info) = True;
1903 # endif
1904 // END HACK
1906 // Set default vex control params.
1907 LibVEX_default_VexControl(& VG_(clo_vex_control));
1909 //--------------------------------------------------------------
1910 // Load client executable, finding in $PATH if necessary
1911 // p: early_process_cmd_line_options() [for 'exec', 'need_help',
1912 // clo_max_stackframe,
1913 // clo_main_stacksize]
1914 // p: layout_remaining_space [so there's space]
1916 // Set up client's environment
1917 // p: set-libdir [for VG_(libdir)]
1918 // p: early_process_cmd_line_options [for toolname]
1920 // Setup client stack, eip, and VG_(client_arg[cv])
1921 // p: load_client() [for 'info']
1922 // p: fix_environment() [for 'env']
1924 // Setup client data (brk) segment. Initially a 1-page segment
1925 // which abuts a shrinkable reservation.
1926 // p: load_client() [for 'info' and hence VG_(brk_base)]
1928 // p: _start_in_C (for zeroing out the_iicii and putting some
1929 // initial values into it)
1930 //--------------------------------------------------------------
1931 if (!need_help) {
1932 VG_(debugLog)(1, "main", "Create initial image\n");
1934 # if defined(VGO_linux) || defined(VGO_darwin)
1935 the_iicii.argv = argv;
1936 the_iicii.envp = envp;
1937 the_iicii.toolname = toolname;
1938 # else
1939 # error "Unknown platform"
1940 # endif
1942 /* NOTE: this call reads VG_(clo_main_stacksize). */
1943 the_iifii = VG_(ii_create_image)( the_iicii );
1946 //==============================================================
1948 // Finished loading/setting up the client address space.
1950 //==============================================================
1952 //--------------------------------------------------------------
1953 // setup file descriptors
1954 // p: n/a
1955 //--------------------------------------------------------------
1956 VG_(debugLog)(1, "main", "Setup file descriptors\n");
1957 setup_file_descriptors();
1959 //--------------------------------------------------------------
1960 // create fake /proc/<pid>/cmdline and /proc/<pid>/auxv files
1961 // and then unlink them, but hold onto the fds, so we can handr
1962 // them out to the client when it tries to open
1963 // /proc/<pid>/cmdline or /proc/<pid>/auxv for itself.
1964 // p: setup file descriptors
1965 // p: ii_create_image for VG_(client_auxv) setup.
1966 //--------------------------------------------------------------
1967 #if !defined(VGO_linux)
1968 // client shouldn't be using /proc!
1969 VG_(cl_cmdline_fd) = -1;
1970 VG_(cl_auxv_fd) = -1;
1971 #else
1972 if (!need_help) {
1973 HChar buf[50]; // large enough
1974 HChar buf2[VG_(mkstemp_fullname_bufsz)(sizeof buf - 1)];
1975 HChar nul[1];
1976 Int fd, r;
1977 const HChar* exename;
1979 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/cmdline\n");
1981 VG_(sprintf)(buf, "proc_%d_cmdline", VG_(getpid)());
1982 fd = VG_(mkstemp)( buf, buf2 );
1983 if (fd == -1)
1984 VG_(err_config_error)("Can't create client cmdline file in %s\n", buf2);
1986 nul[0] = 0;
1987 exename = VG_(args_the_exename);
1988 VG_(write)(fd, exename, VG_(strlen)( exename ));
1989 VG_(write)(fd, nul, 1);
1991 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1992 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i );
1993 VG_(write)(fd, arg, VG_(strlen)( arg ));
1994 VG_(write)(fd, nul, 1);
1997 /* Don't bother to seek the file back to the start; instead do
1998 it every time a copy of it is given out (by PRE(sys_open)).
1999 That is probably more robust across fork() etc. */
2001 /* Now delete it, but hang on to the fd. */
2002 r = VG_(unlink)( buf2 );
2003 if (r)
2004 VG_(err_config_error)("Can't delete client cmdline file in %s\n", buf2);
2006 VG_(cl_cmdline_fd) = fd;
2008 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/auxv\n");
2010 VG_(sprintf)(buf, "proc_%d_auxv", VG_(getpid)());
2011 fd = VG_(mkstemp)( buf, buf2 );
2012 if (fd == -1)
2013 VG_(err_config_error)("Can't create client auxv file in %s\n", buf2);
2015 UWord *client_auxv = VG_(client_auxv);
2016 unsigned int client_auxv_len = 0;
2017 while (*client_auxv != 0) {
2018 client_auxv++;
2019 client_auxv++;
2020 client_auxv_len += 2 * sizeof(UWord);
2022 client_auxv_len += 2 * sizeof(UWord);
2024 VG_(write)(fd, VG_(client_auxv), client_auxv_len);
2026 /* Don't bother to seek the file back to the start; instead do
2027 it every time a copy of it is given out (by PRE(sys_open)).
2028 That is probably more robust across fork() etc. */
2030 /* Now delete it, but hang on to the fd. */
2031 r = VG_(unlink)( buf2 );
2032 if (r)
2033 VG_(err_config_error)("Can't delete client auxv file in %s\n", buf2);
2035 VG_(cl_auxv_fd) = fd;
2037 #endif
2039 //--------------------------------------------------------------
2040 // Init tool part 1: pre_clo_init
2041 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
2042 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
2043 //--------------------------------------------------------------
2044 VG_(debugLog)(1, "main", "Initialise the tool part 1 (pre_clo_init)\n");
2045 VG_(tl_pre_clo_init)();
2046 // Activate var info readers, if the tool asked for it:
2047 if (VG_(needs).var_info)
2048 VG_(clo_read_var_info) = True;
2050 //--------------------------------------------------------------
2051 // If --tool and --help/--help-debug was given, now give the core+tool
2052 // help message
2053 // p: early_process_cmd_line_options() [for 'need_help']
2054 // p: tl_pre_clo_init [for 'VG_(tdict).usage']
2055 //--------------------------------------------------------------
2056 VG_(debugLog)(1, "main", "Print help and quit, if requested\n");
2057 if (need_help) {
2058 usage_NORETURN(/*--help-debug?*/need_help >= 2);
2061 //--------------------------------------------------------------
2062 // Process command line options to Valgrind + tool
2063 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
2064 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
2065 //--------------------------------------------------------------
2066 VG_(debugLog)(1, "main",
2067 "(main_) Process Valgrind's command line options, "
2068 "setup logging\n");
2069 main_process_cmd_line_options ( &logging_to_fd, &xml_fname_unexpanded,
2070 toolname );
2072 //--------------------------------------------------------------
2073 // Zeroise the millisecond counter by doing a first read of it.
2074 // p: none
2075 //--------------------------------------------------------------
2076 (void) VG_(read_millisecond_timer)();
2078 //--------------------------------------------------------------
2079 // Print the preamble
2080 // p: tl_pre_clo_init [for 'VG_(details).name' and friends]
2081 // p: main_process_cmd_line_options()
2082 // [for VG_(clo_verbosity), VG_(clo_xml),
2083 // logging_to_fd, xml_fname_unexpanded]
2084 //--------------------------------------------------------------
2085 VG_(debugLog)(1, "main", "Print the preamble...\n");
2086 print_preamble(logging_to_fd, xml_fname_unexpanded, toolname);
2087 VG_(debugLog)(1, "main", "...finished the preamble\n");
2089 //--------------------------------------------------------------
2090 // Init tool part 2: post_clo_init
2091 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
2092 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
2093 // p: print_preamble() [so any warnings printed in post_clo_init
2094 // are shown after the preamble]
2095 //--------------------------------------------------------------
2096 VG_(debugLog)(1, "main", "Initialise the tool part 2 (post_clo_init)\n");
2097 VG_TDICT_CALL(tool_post_clo_init);
2099 /* The tool's "needs" will by now be finalised, since it has no
2100 further opportunity to specify them. So now sanity check
2101 them. */
2102 const HChar* s;
2103 Bool ok;
2104 ok = VG_(sanity_check_needs)( &s );
2105 if (!ok) {
2106 VG_(core_panic)(s);
2110 //--------------------------------------------------------------
2111 // Initialise translation table and translation cache
2112 // p: aspacem [??]
2113 // p: tl_pre_clo_init [for 'VG_(details).avg_translation_sizeB']
2114 //--------------------------------------------------------------
2115 VG_(debugLog)(1, "main", "Initialise TT/TC\n");
2116 VG_(init_tt_tc)();
2118 //--------------------------------------------------------------
2119 // Initialise the redirect table.
2120 // p: init_tt_tc [so it can call VG_(search_transtab) safely]
2121 // p: aspacem [so can change ownership of sysinfo pages]
2122 //--------------------------------------------------------------
2123 VG_(debugLog)(1, "main", "Initialise redirects\n");
2124 VG_(redir_initialise)();
2126 //--------------------------------------------------------------
2127 // Allow GDB attach
2128 // p: main_process_cmd_line_options() [for VG_(clo_wait_for_gdb)]
2129 //--------------------------------------------------------------
2130 /* Hook to delay things long enough so we can get the pid and
2131 attach GDB in another shell. */
2132 if (VG_(clo_wait_for_gdb)) {
2133 ULong iters, q;
2134 VG_(debugLog)(1, "main", "Wait for GDB\n");
2135 VG_(printf)("pid=%d, entering delay loop\n", VG_(getpid)());
2137 # if defined(VGP_x86_linux)
2138 iters = 10;
2139 # elif defined(VGP_amd64_linux) || defined(VGP_ppc64be_linux) \
2140 || defined(VGP_ppc64le_linux)
2141 iters = 10;
2142 # elif defined(VGP_ppc32_linux)
2143 iters = 5;
2144 # elif defined(VGP_arm_linux)
2145 iters = 5;
2146 # elif defined(VGP_arm64_linux)
2147 iters = 5;
2148 # elif defined(VGP_s390x_linux)
2149 iters = 10;
2150 # elif defined(VGP_mips32_linux) || defined(VGP_mips64_linux)
2151 iters = 10;
2152 # elif defined(VGO_darwin)
2153 iters = 3;
2154 # else
2155 # error "Unknown plat"
2156 # endif
2158 iters *= 1000ULL * 1000 * 1000;
2159 for (q = 0; q < iters; q++)
2160 __asm__ __volatile__("" ::: "memory","cc");
2163 //--------------------------------------------------------------
2164 // Search for file descriptors that are inherited from our parent
2165 // p: main_process_cmd_line_options [for VG_(clo_track_fds)]
2166 //--------------------------------------------------------------
2167 if (VG_(clo_track_fds)) {
2168 VG_(debugLog)(1, "main", "Init preopened fds\n");
2169 VG_(init_preopened_fds)();
2172 //--------------------------------------------------------------
2173 // Load debug info for the existing segments.
2174 // p: setup_code_redirect_table [so that redirs can be recorded]
2175 // p: mallocfree
2176 // p: probably: setup fds and process CLOs, so that logging works
2177 // p: initialise m_debuginfo
2179 // While doing this, make a note of the debuginfo-handles that
2180 // come back from VG_(di_notify_mmap).
2181 // Later, in "Tell the tool about the initial client memory permissions"
2182 // (just below) we can then hand these handles off to the tool in
2183 // calls to VG_TRACK(new_mem_startup, ...). This gives the tool the
2184 // opportunity to make further queries to m_debuginfo before the
2185 // client is started, if it wants. We put this information into an
2186 // XArray, each handle along with the associated segment start address,
2187 // and search the XArray for the handles later, when calling
2188 // VG_TRACK(new_mem_startup, ...).
2189 //--------------------------------------------------------------
2190 VG_(debugLog)(1, "main", "Load initial debug info\n");
2192 vg_assert(!addr2dihandle);
2193 addr2dihandle = VG_(newXA)( VG_(malloc), "main.vm.2",
2194 VG_(free), sizeof(Addr_n_ULong) );
2196 # if defined(VGO_linux)
2197 { Addr* seg_starts;
2198 Int n_seg_starts;
2199 Addr_n_ULong anu;
2201 seg_starts = VG_(get_segment_starts)( SkFileC | SkFileV, &n_seg_starts );
2202 vg_assert(seg_starts && n_seg_starts >= 0);
2204 /* show them all to the debug info reader. allow_SkFileV has to
2205 be True here so that we read info from the valgrind executable
2206 itself. */
2207 for (i = 0; i < n_seg_starts; i++) {
2208 anu.ull = VG_(di_notify_mmap)( seg_starts[i], True/*allow_SkFileV*/,
2209 -1/*Don't use_fd*/);
2210 /* anu.ull holds the debuginfo handle returned by di_notify_mmap,
2211 if any. */
2212 if (anu.ull > 0) {
2213 anu.a = seg_starts[i];
2214 VG_(addToXA)( addr2dihandle, &anu );
2218 VG_(free)( seg_starts );
2220 # elif defined(VGO_darwin)
2221 { Addr* seg_starts;
2222 Int n_seg_starts;
2223 seg_starts = VG_(get_segment_starts)( SkFileC, &n_seg_starts );
2224 vg_assert(seg_starts && n_seg_starts >= 0);
2226 /* show them all to the debug info reader.
2227 Don't read from V segments (unlike Linux) */
2228 // GrP fixme really?
2229 for (i = 0; i < n_seg_starts; i++) {
2230 VG_(di_notify_mmap)( seg_starts[i], False/*don't allow_SkFileV*/,
2231 -1/*don't use_fd*/);
2234 VG_(free)( seg_starts );
2236 # else
2237 # error Unknown OS
2238 # endif
2240 //--------------------------------------------------------------
2241 // Tell aspacem of ownership change of the asm helpers, so that
2242 // m_translate allows them to be translated. However, only do this
2243 // after the initial debug info read, since making a hole in the
2244 // address range for the stage2 binary confuses the debug info reader.
2245 // p: aspacem
2246 //--------------------------------------------------------------
2247 { Bool change_ownership_v_c_OK;
2248 Addr co_start = VG_PGROUNDDN( (Addr)&VG_(trampoline_stuff_start) );
2249 Addr co_endPlus = VG_PGROUNDUP( (Addr)&VG_(trampoline_stuff_end) );
2250 VG_(debugLog)(1,"redir",
2251 "transfer ownership V -> C of 0x%llx .. 0x%llx\n",
2252 (ULong)co_start, (ULong)co_endPlus-1 );
2254 change_ownership_v_c_OK
2255 = VG_(am_change_ownership_v_to_c)( co_start, co_endPlus - co_start );
2256 vg_assert(change_ownership_v_c_OK);
2259 if (VG_(clo_xml)) {
2260 HChar buf[50]; // large enough
2261 VG_(elapsed_wallclock_time)(buf, sizeof buf);
2262 VG_(printf_xml)( "<status>\n"
2263 " <state>RUNNING</state>\n"
2264 " <time>%pS</time>\n"
2265 "</status>\n",
2266 buf );
2267 VG_(printf_xml)( "\n" );
2270 VG_(init_Threads)();
2272 //--------------------------------------------------------------
2273 // Initialise the scheduler (phase 1) [generates tid_main]
2274 // p: none, afaics
2275 //--------------------------------------------------------------
2276 VG_(debugLog)(1, "main", "Initialise scheduler (phase 1)\n");
2277 tid_main = VG_(scheduler_init_phase1)();
2278 vg_assert(tid_main >= 0 && tid_main < VG_N_THREADS
2279 && tid_main != VG_INVALID_THREADID);
2280 /* Tell the tool about tid_main */
2281 VG_TRACK( pre_thread_ll_create, VG_INVALID_THREADID, tid_main );
2283 //--------------------------------------------------------------
2284 // Tell the tool about the initial client memory permissions
2285 // p: aspacem
2286 // p: mallocfree
2287 // p: setup_client_stack
2288 // p: setup_client_dataseg
2290 // For each segment we tell the client about, look up in
2291 // addr2dihandle as created above, to see if there's a debuginfo
2292 // handle associated with the segment, that we can hand along
2293 // to the tool, to be helpful.
2294 //--------------------------------------------------------------
2295 VG_(debugLog)(1, "main", "Tell tool about initial permissions\n");
2296 { Addr* seg_starts;
2297 Int n_seg_starts;
2299 vg_assert(addr2dihandle);
2301 /* Mark the main thread as running while we tell the tool about
2302 the client memory so that the tool can associate that memory
2303 with the main thread. */
2304 vg_assert(VG_(running_tid) == VG_INVALID_THREADID);
2305 VG_(running_tid) = tid_main;
2307 seg_starts = VG_(get_segment_starts)( SkFileC | SkAnonC | SkShmC,
2308 &n_seg_starts );
2309 vg_assert(seg_starts && n_seg_starts >= 0);
2311 /* Show client segments to the tool */
2312 for (i = 0; i < n_seg_starts; i++) {
2313 Word j, n;
2314 NSegment const* seg
2315 = VG_(am_find_nsegment)( seg_starts[i] );
2316 vg_assert(seg);
2317 vg_assert(seg->kind == SkFileC || seg->kind == SkAnonC ||
2318 seg->kind == SkShmC);
2319 vg_assert(seg->start == seg_starts[i]);
2321 VG_(debugLog)(2, "main",
2322 "tell tool about %010lx-%010lx %c%c%c\n",
2323 seg->start, seg->end,
2324 seg->hasR ? 'r' : '-',
2325 seg->hasW ? 'w' : '-',
2326 seg->hasX ? 'x' : '-' );
2327 /* search addr2dihandle to see if we have an entry
2328 matching seg->start. */
2329 n = VG_(sizeXA)( addr2dihandle );
2330 for (j = 0; j < n; j++) {
2331 Addr_n_ULong* anl = VG_(indexXA)( addr2dihandle, j );
2332 if (anl->a == seg->start) {
2333 vg_assert(anl->ull > 0); /* check it's a valid handle */
2334 break;
2337 vg_assert(j >= 0 && j <= n);
2338 VG_TRACK( new_mem_startup, seg->start, seg->end+1-seg->start,
2339 seg->hasR, seg->hasW, seg->hasX,
2340 /* and the retrieved debuginfo handle, if any */
2341 j < n
2342 ? ((Addr_n_ULong*)VG_(indexXA)( addr2dihandle, j ))->ull
2343 : 0 );
2347 VG_(free)( seg_starts );
2348 VG_(deleteXA)( addr2dihandle );
2350 /* Also do the initial stack permissions. */
2352 SSizeT inaccessible_len;
2353 NSegment const* seg
2354 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
2355 vg_assert(seg);
2356 vg_assert(seg->kind == SkAnonC);
2357 vg_assert(the_iifii.initial_client_SP >= seg->start);
2358 vg_assert(the_iifii.initial_client_SP <= seg->end);
2360 /* Stuff below the initial SP is unaddressable. Take into
2361 account any ABI-mandated space below the stack pointer that
2362 is required (VG_STACK_REDZONE_SZB). setup_client_stack()
2363 will have allocated an extra page if a red zone is required,
2364 to be on the safe side. */
2365 inaccessible_len = the_iifii.initial_client_SP - VG_STACK_REDZONE_SZB
2366 - seg->start;
2367 vg_assert(inaccessible_len >= 0);
2368 if (inaccessible_len > 0)
2369 VG_TRACK( die_mem_stack,
2370 seg->start,
2371 inaccessible_len );
2372 VG_(debugLog)(2, "main", "mark stack inaccessible %010lx-%010lx\n",
2373 seg->start,
2374 the_iifii.initial_client_SP-1 - VG_STACK_REDZONE_SZB);
2377 /* Also the assembly helpers. */
2378 VG_TRACK( new_mem_startup,
2379 (Addr)&VG_(trampoline_stuff_start),
2380 (Addr)&VG_(trampoline_stuff_end)
2381 - (Addr)&VG_(trampoline_stuff_start),
2382 False, /* readable? */
2383 False, /* writable? */
2384 True /* executable? */,
2385 0 /* di_handle: no associated debug info */ );
2387 /* Clear the running thread indicator */
2388 VG_(running_tid) = VG_INVALID_THREADID;
2389 vg_assert(VG_(running_tid) == VG_INVALID_THREADID);
2391 /* Darwin only: tell the tools where the client's kernel commpage
2392 is. It would be better to do this by telling aspacemgr about
2393 it -- see the now disused record_system_memory() in
2394 initimg-darwin.c -- but that causes the sync checker to fail,
2395 since the mapping doesn't appear in the kernel-supplied
2396 process map. So do it here instead. */
2397 # if defined(VGP_amd64_darwin)
2398 VG_TRACK( new_mem_startup,
2399 0x7fffffe00000, 0x7ffffffff000-0x7fffffe00000,
2400 True, False, True, /* r-x */
2401 0 /* di_handle: no associated debug info */ );
2402 # elif defined(VGP_x86_darwin)
2403 VG_TRACK( new_mem_startup,
2404 0xfffec000, 0xfffff000-0xfffec000,
2405 True, False, True, /* r-x */
2406 0 /* di_handle: no associated debug info */ );
2407 # endif
2410 //--------------------------------------------------------------
2411 // Initialise the scheduler (phase 2)
2412 // p: Initialise the scheduler (phase 1) [for tid_main]
2413 // p: setup_file_descriptors() [else VG_(safe_fd)() breaks]
2414 // p: setup_client_stack
2415 //--------------------------------------------------------------
2416 VG_(debugLog)(1, "main", "Initialise scheduler (phase 2)\n");
2417 { NSegment const* seg
2418 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
2419 vg_assert(seg);
2420 vg_assert(seg->kind == SkAnonC);
2421 vg_assert(the_iifii.initial_client_SP >= seg->start);
2422 vg_assert(the_iifii.initial_client_SP <= seg->end);
2423 VG_(scheduler_init_phase2)( tid_main,
2424 seg->end, the_iifii.clstack_max_size );
2427 //--------------------------------------------------------------
2428 // Set up state for the root thread
2429 // p: ?
2430 // setup_scheduler() [for sched-specific thread 1 stuff]
2431 // VG_(ii_create_image) [for 'the_iicii' initial info]
2432 //--------------------------------------------------------------
2433 VG_(debugLog)(1, "main", "Finalise initial image\n");
2434 VG_(ii_finalise_image)( the_iifii );
2436 //--------------------------------------------------------------
2437 // Initialise the signal handling subsystem
2438 // p: n/a
2439 //--------------------------------------------------------------
2440 // Nb: temporarily parks the saved blocking-mask in saved_sigmask.
2441 VG_(debugLog)(1, "main", "Initialise signal management\n");
2442 /* Check that the kernel-interface signal definitions look sane */
2443 VG_(vki_do_initial_consistency_checks)();
2444 /* .. and go on to use them. */
2445 VG_(sigstartup_actions)();
2447 //--------------------------------------------------------------
2448 // Read suppression file
2449 // p: main_process_cmd_line_options() [for VG_(clo_suppressions)]
2450 //--------------------------------------------------------------
2451 if (VG_(needs).core_errors || VG_(needs).tool_errors) {
2452 VG_(debugLog)(1, "main", "Load suppressions\n");
2453 VG_(load_suppressions)();
2456 //--------------------------------------------------------------
2457 // register client stack
2458 //--------------------------------------------------------------
2459 VG_(clstk_id) = VG_(register_stack)(VG_(clstk_start_base), VG_(clstk_end));
2461 //--------------------------------------------------------------
2462 // Show the address space state so far
2463 //--------------------------------------------------------------
2464 VG_(debugLog)(1, "main", "\n");
2465 VG_(debugLog)(1, "main", "\n");
2466 VG_(am_show_nsegments)(1,"Memory layout at client startup");
2467 VG_(debugLog)(1, "main", "\n");
2468 VG_(debugLog)(1, "main", "\n");
2470 //--------------------------------------------------------------
2471 // Run!
2472 //--------------------------------------------------------------
2473 VG_(debugLog)(1, "main", "Running thread 1\n");
2475 /* As a result of the following call, the last thread standing
2476 eventually winds up running shutdown_actions_NORETURN
2477 just below. Unfortunately, simply exporting said function
2478 causes m_main to be part of a module cycle, which is pretty
2479 nonsensical. So instead of doing that, the address of said
2480 function is stored in a global variable 'owned' by m_syswrap,
2481 and it uses that function pointer to get back here when it needs
2482 to. */
2484 /* Set continuation address. */
2485 VG_(address_of_m_main_shutdown_actions_NORETURN)
2486 = & shutdown_actions_NORETURN;
2488 /* Run the first thread, eventually ending up at the continuation
2489 address. */
2490 VG_(main_thread_wrapper_NORETURN)(1);
2492 /*NOTREACHED*/
2493 vg_assert(0);
2496 /* Do everything which needs doing when the last thread exits or when
2497 a thread exits requesting a complete process exit.
2499 We enter here holding The Lock. For the case VgSrc_ExitProcess we
2500 must never release it, because to do so would allow other threads
2501 to continue after the system is ostensibly shut down. So we must
2502 go to our grave, so to speak, holding the lock.
2504 In fact, there is never any point in releasing the lock at this
2505 point - we have it, we're shutting down the entire system, and
2506 for the case VgSrc_ExitProcess doing so positively causes trouble.
2507 So don't.
2509 The final_tidyup call makes a bit of a nonsense of the ExitProcess
2510 case, since it will run the libc_freeres function, thus allowing
2511 other lurking threads to run again. Hmm. */
2513 static
2514 void shutdown_actions_NORETURN( ThreadId tid,
2515 VgSchedReturnCode tids_schedretcode )
2517 VG_(debugLog)(1, "main", "entering VG_(shutdown_actions_NORETURN)\n");
2518 VG_(am_show_nsegments)(1,"Memory layout at client shutdown");
2520 vg_assert(VG_(is_running_thread)(tid));
2521 vg_assert(tids_schedretcode == VgSrc_ExitThread
2522 || tids_schedretcode == VgSrc_ExitProcess
2523 || tids_schedretcode == VgSrc_FatalSig );
2525 if (tids_schedretcode == VgSrc_ExitThread) {
2527 // We are the last surviving thread. Right?
2528 vg_assert( VG_(count_living_threads)() == 1 );
2530 // Wait for all other threads to exit.
2531 // jrs: Huh? but they surely are already gone
2532 VG_(reap_threads)(tid);
2534 // Clean the client up before the final report
2535 // this causes the libc_freeres function to run
2536 final_tidyup(tid);
2538 /* be paranoid */
2539 vg_assert(VG_(is_running_thread)(tid));
2540 vg_assert(VG_(count_living_threads)() == 1);
2542 } else {
2544 // We may not be the last surviving thread. However, we
2545 // want to shut down the entire process. We hold the lock
2546 // and we need to keep hold of it all the way out, in order
2547 // that none of the other threads ever run again.
2548 vg_assert( VG_(count_living_threads)() >= 1 );
2550 // Clean the client up before the final report
2551 // this causes the libc_freeres function to run
2552 // perhaps this is unsafe, as per comment above
2553 final_tidyup(tid);
2555 /* be paranoid */
2556 vg_assert(VG_(is_running_thread)(tid));
2557 vg_assert(VG_(count_living_threads)() >= 1);
2560 /* Final call to gdbserver, if requested. */
2561 if (VG_(gdbserver_stop_at) (VgdbStopAt_Exit)) {
2562 VG_(umsg)("(action at exit) vgdb me ... \n");
2563 VG_(gdbserver) (tid);
2565 VG_(threads)[tid].status = VgTs_Empty;
2567 //--------------------------------------------------------------
2568 // Finalisation: cleanup, messages, etc. Order not so important, only
2569 // affects what order the messages come.
2570 //--------------------------------------------------------------
2571 // First thing in the post-amble is a blank line.
2572 if (VG_(clo_xml))
2573 VG_(printf_xml)("\n");
2574 else if (VG_(clo_verbosity) > 0)
2575 VG_(message)(Vg_UserMsg, "\n");
2577 if (VG_(clo_xml)) {
2578 HChar buf[50]; // large enough
2579 VG_(elapsed_wallclock_time)(buf, sizeof buf);
2580 VG_(printf_xml)( "<status>\n"
2581 " <state>FINISHED</state>\n"
2582 " <time>%pS</time>\n"
2583 "</status>\n"
2584 "\n",
2585 buf);
2588 /* Print out file descriptor summary and stats. */
2589 if (VG_(clo_track_fds))
2590 VG_(show_open_fds)("at exit");
2592 /* Call the tool's finalisation function. This makes Memcheck's
2593 leak checker run, and possibly chuck a bunch of leak errors into
2594 the error management machinery. */
2595 VG_TDICT_CALL(tool_fini, 0/*exitcode*/);
2597 /* Show the error counts. */
2598 if (VG_(clo_xml)
2599 && (VG_(needs).core_errors || VG_(needs).tool_errors)) {
2600 VG_(show_error_counts_as_XML)();
2603 /* In XML mode, this merely prints the used suppressions. */
2604 if (VG_(needs).core_errors || VG_(needs).tool_errors)
2605 VG_(show_all_errors)(VG_(clo_verbosity), VG_(clo_xml));
2607 if (VG_(clo_xml)) {
2608 VG_(printf_xml)("\n");
2609 VG_(printf_xml)("</valgrindoutput>\n");
2610 VG_(printf_xml)("\n");
2613 VG_(sanity_check_general)( True /*include expensive checks*/ );
2615 if (VG_(clo_stats))
2616 VG_(print_all_stats)(VG_(clo_verbosity) > 2, /* Memory stats */
2617 False /* tool prints stats in the tool fini */);
2619 /* Show a profile of the heap(s) at shutdown. Optionally, first
2620 throw away all the debug info, as that makes it easy to spot
2621 leaks in the debuginfo reader. */
2622 if (VG_(clo_profile_heap)) {
2623 if (0) VG_(di_discard_ALL_debuginfo)();
2624 VG_(print_arena_cc_analysis)();
2627 /* If profiling has been requested, but with zero interval, it
2628 means "profile at the end of the run only". In which case we
2629 need to dump the profile now. */
2630 if (VG_(clo_profyle_sbs) && VG_(clo_profyle_interval) == 0) {
2631 VG_(get_and_show_SB_profile)(0/*denoting end-of-run*/);
2634 /* Print Vex storage stats */
2635 if (0)
2636 LibVEX_ShowAllocStats();
2638 /* Flush any output cached by previous calls to VG_(message). */
2639 VG_(message_flush)();
2641 /* Terminate gdbserver if ever it was started. We terminate it here
2642 so that it get the output above if output was redirected to
2643 gdb */
2644 VG_(gdbserver_exit) (tid, tids_schedretcode);
2646 /* Ok, finally exit in the os-specific way, according to the scheduler's
2647 return code. In short, if the (last) thread exited by calling
2648 sys_exit, do likewise; if the (last) thread stopped due to a fatal
2649 signal, terminate the entire system with that same fatal signal. */
2650 VG_(debugLog)(1, "core_os",
2651 "VG_(terminate_NORETURN)(tid=%lld)\n", (ULong)tid);
2653 switch (tids_schedretcode) {
2654 case VgSrc_ExitThread: /* the normal way out (Linux) */
2655 case VgSrc_ExitProcess: /* the normal way out (Darwin) */
2656 /* Change the application return code to user's return code,
2657 if an error was found */
2658 if (VG_(clo_error_exitcode) > 0
2659 && VG_(get_n_errs_found)() > 0) {
2660 VG_(client_exit)( VG_(clo_error_exitcode) );
2661 } else {
2662 /* otherwise, return the client's exit code, in the normal
2663 way. */
2664 VG_(client_exit)( VG_(threads)[tid].os_state.exitcode );
2666 /* NOT ALIVE HERE! */
2667 VG_(core_panic)("entered the afterlife in main() -- ExitT/P");
2668 break; /* what the hell :) */
2670 case VgSrc_FatalSig:
2671 /* We were killed by a fatal signal, so replicate the effect */
2672 vg_assert(VG_(threads)[tid].os_state.fatalsig != 0);
2673 VG_(kill_self)(VG_(threads)[tid].os_state.fatalsig);
2674 /* we shouldn't be alive at this point. But VG_(kill_self)
2675 sometimes fails with EPERM on Darwin, for unclear reasons. */
2676 # if defined(VGO_darwin)
2677 VG_(debugLog)(0, "main", "VG_(kill_self) failed. Exiting normally.\n");
2678 VG_(exit)(0); /* bogus, but we really need to exit now */
2679 /* fall through .. */
2680 # endif
2681 VG_(core_panic)("main(): signal was supposed to be fatal");
2682 break;
2684 default:
2685 VG_(core_panic)("main(): unexpected scheduler return code");
2689 /* -------------------- */
2691 /* Final clean-up before terminating the process.
2692 Clean up the client by calling __libc_freeres() (if requested)
2693 This is Linux-specific?
2694 GrP fixme glibc-specific, anyway
2696 static void final_tidyup(ThreadId tid)
2698 #if !defined(VGO_darwin)
2699 Addr __libc_freeres_wrapper = VG_(client___libc_freeres_wrapper);
2701 vg_assert(VG_(is_running_thread)(tid));
2703 if ( !VG_(needs).libc_freeres ||
2704 !VG_(clo_run_libc_freeres) ||
2705 0 == __libc_freeres_wrapper )
2706 return; /* can't/won't do it */
2708 # if defined(VGP_ppc64be_linux)
2709 Addr r2 = VG_(get_tocptr)( __libc_freeres_wrapper );
2710 if (r2 == 0) {
2711 VG_(message)(Vg_UserMsg,
2712 "Caught __NR_exit, but can't run __libc_freeres()\n");
2713 VG_(message)(Vg_UserMsg,
2714 " since cannot establish TOC pointer for it.\n");
2715 return;
2717 # endif
2719 if (VG_(clo_verbosity) > 2 ||
2720 VG_(clo_trace_syscalls) ||
2721 VG_(clo_trace_sched))
2722 VG_(message)(Vg_DebugMsg,
2723 "Caught __NR_exit; running __libc_freeres()\n");
2725 /* set thread context to point to libc_freeres_wrapper */
2726 /* ppc64be-linux note: __libc_freeres_wrapper gives us the real
2727 function entry point, not a fn descriptor, so can use it
2728 directly. However, we need to set R2 (the toc pointer)
2729 appropriately. */
2730 VG_(set_IP)(tid, __libc_freeres_wrapper);
2731 # if defined(VGP_ppc64be_linux)
2732 VG_(threads)[tid].arch.vex.guest_GPR2 = r2;
2733 # elif defined(VGP_ppc64le_linux)
2734 /* setting GPR2 but not really needed, GPR12 is needed */
2735 VG_(threads)[tid].arch.vex.guest_GPR2 = __libc_freeres_wrapper;
2736 VG_(threads)[tid].arch.vex.guest_GPR12 = __libc_freeres_wrapper;
2737 # endif
2738 /* mips-linux note: we need to set t9 */
2739 # if defined(VGP_mips32_linux) || defined(VGP_mips64_linux)
2740 VG_(threads)[tid].arch.vex.guest_r25 = __libc_freeres_wrapper;
2741 # endif
2743 /* Block all blockable signals by copying the real block state into
2744 the thread's block state*/
2745 VG_(sigprocmask)(VKI_SIG_BLOCK, NULL, &VG_(threads)[tid].sig_mask);
2746 VG_(threads)[tid].tmp_sig_mask = VG_(threads)[tid].sig_mask;
2748 /* and restore handlers to default */
2749 VG_(set_default_handler)(VKI_SIGSEGV);
2750 VG_(set_default_handler)(VKI_SIGBUS);
2751 VG_(set_default_handler)(VKI_SIGILL);
2752 VG_(set_default_handler)(VKI_SIGFPE);
2754 // We were exiting, so assert that...
2755 vg_assert(VG_(is_exiting)(tid));
2756 // ...but now we're not again
2757 VG_(threads)[tid].exitreason = VgSrc_None;
2759 // run until client thread exits - ideally with LIBC_FREERES_DONE,
2760 // but exit/exitgroup/signal will do
2761 VG_(scheduler)(tid);
2763 vg_assert(VG_(is_exiting)(tid));
2764 #endif
2768 /*====================================================================*/
2769 /*=== Getting to main() alive: LINUX ===*/
2770 /*====================================================================*/
2772 #if defined(VGO_linux)
2774 /* If linking of the final executables is done with glibc present,
2775 then Valgrind starts at main() above as usual, and all of the
2776 following code is irrelevant.
2778 However, this is not the intended mode of use. The plan is to
2779 avoid linking against glibc, by giving gcc the flags
2780 -nodefaultlibs -lgcc -nostartfiles at startup.
2782 From this derive two requirements:
2784 1. gcc may emit calls to memcpy, memmove and memset to deal with
2785 structure assignments etc. Since we have chosen to ignore all the
2786 "normal" supporting libraries, we have to provide our own
2787 implementations of them. No problem.
2789 2. We have to provide a symbol "_start", to which the kernel
2790 hands control at startup. Hence the code below.
2793 /* ---------------- Requirement 1 ---------------- */
2795 void* memcpy(void *dest, const void *src, SizeT n);
2796 void* memcpy(void *dest, const void *src, SizeT n) {
2797 return VG_(memcpy)(dest,src,n);
2799 void* memmove(void *dest, const void *src, SizeT n);
2800 void* memmove(void *dest, const void *src, SizeT n) {
2801 return VG_(memmove)(dest,src,n);
2803 void* memset(void *s, int c, SizeT n);
2804 void* memset(void *s, int c, SizeT n) {
2805 return VG_(memset)(s,c,n);
2808 /* BVA: abort() for those platforms that need it (PPC and ARM). */
2809 void abort(void);
2810 void abort(void){
2811 VG_(printf)("Something called raise().\n");
2812 vg_assert(0);
2815 /* EAZG: ARM's EABI will call floating point exception handlers in
2816 libgcc which boil down to an abort or raise, that's usually defined
2817 in libc. Instead, define them here. */
2818 #if defined(VGP_arm_linux)
2819 void raise(void);
2820 void raise(void){
2821 VG_(printf)("Something called raise().\n");
2822 vg_assert(0);
2825 void __aeabi_unwind_cpp_pr0(void);
2826 void __aeabi_unwind_cpp_pr0(void){
2827 VG_(printf)("Something called __aeabi_unwind_cpp_pr0()\n");
2828 vg_assert(0);
2831 void __aeabi_unwind_cpp_pr1(void);
2832 void __aeabi_unwind_cpp_pr1(void){
2833 VG_(printf)("Something called __aeabi_unwind_cpp_pr1()\n");
2834 vg_assert(0);
2836 #endif
2838 /* ---------------- Requirement 2 ---------------- */
2840 /* Glibc's sysdeps/i386/elf/start.S has the following gem of a
2841 comment, which explains how the stack looks right at process start
2842 (when _start is jumped to). Hence _start passes %esp to
2843 _start_in_C_linux, which extracts argc/argv/envp and starts up
2844 correctly. */
2846 /* This is the canonical entry point, usually the first thing in the text
2847 segment. The SVR4/i386 ABI (pages 3-31, 3-32) says that when the entry
2848 point runs, most registers' values are unspecified, except for:
2850 %edx Contains a function pointer to be registered with `atexit'.
2851 This is how the dynamic linker arranges to have DT_FINI
2852 functions called for shared libraries that have been loaded
2853 before this code runs.
2855 %esp The stack contains the arguments and environment:
2856 0(%esp) argc
2857 4(%esp) argv[0]
2859 (4*argc)(%esp) NULL
2860 (4*(argc+1))(%esp) envp[0]
2862 NULL
2865 /* The kernel hands control to _start, which extracts the initial
2866 stack pointer and calls onwards to _start_in_C_linux. This also switches
2867 the new stack. */
2868 #if defined(VGP_x86_linux)
2869 asm("\n"
2870 ".text\n"
2871 "\t.globl _start\n"
2872 "\t.type _start,@function\n"
2873 "_start:\n"
2874 /* set up the new stack in %eax */
2875 "\tmovl $vgPlain_interim_stack, %eax\n"
2876 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
2877 "\taddl $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %eax\n"
2878 "\tsubl $16, %eax\n"
2879 "\tandl $~15, %eax\n"
2880 /* install it, and collect the original one */
2881 "\txchgl %eax, %esp\n"
2882 /* call _start_in_C_linux, passing it the startup %esp */
2883 "\tpushl %eax\n"
2884 "\tcall _start_in_C_linux\n"
2885 "\thlt\n"
2886 ".previous\n"
2888 #elif defined(VGP_amd64_linux)
2889 asm("\n"
2890 ".text\n"
2891 "\t.globl _start\n"
2892 "\t.type _start,@function\n"
2893 "_start:\n"
2894 /* set up the new stack in %rdi */
2895 "\tmovq $vgPlain_interim_stack, %rdi\n"
2896 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
2897 "\taddq $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %rdi\n"
2898 "\tandq $~15, %rdi\n"
2899 /* install it, and collect the original one */
2900 "\txchgq %rdi, %rsp\n"
2901 /* call _start_in_C_linux, passing it the startup %rsp */
2902 "\tcall _start_in_C_linux\n"
2903 "\thlt\n"
2904 ".previous\n"
2906 #elif defined(VGP_ppc32_linux)
2907 asm("\n"
2908 ".text\n"
2909 "\t.globl _start\n"
2910 "\t.type _start,@function\n"
2911 "_start:\n"
2912 /* set up the new stack in r16 */
2913 "\tlis 16,vgPlain_interim_stack@ha\n"
2914 "\tla 16,vgPlain_interim_stack@l(16)\n"
2915 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2916 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2917 "\tlis 18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" >> 16)\n"
2918 "\tori 18,18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2919 "\tadd 16,17,16\n"
2920 "\tadd 16,18,16\n"
2921 "\trlwinm 16,16,0,0,27\n"
2922 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2923 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2924 boundary. And r1 is the original SP. Set the SP to r16 and
2925 call _start_in_C_linux, passing it the initial SP. */
2926 "\tmr 3,1\n"
2927 "\tmr 1,16\n"
2928 "\tbl _start_in_C_linux\n"
2929 "\ttrap\n"
2930 ".previous\n"
2932 #elif defined(VGP_ppc64be_linux)
2933 asm("\n"
2934 /* PPC64 ELF ABI says '_start' points to a function descriptor.
2935 So we must have one, and that is what goes into the .opd section. */
2936 "\t.align 2\n"
2937 "\t.global _start\n"
2938 "\t.section \".opd\",\"aw\"\n"
2939 "\t.align 3\n"
2940 "_start:\n"
2941 "\t.quad ._start,.TOC.@tocbase,0\n"
2942 "\t.previous\n"
2943 "\t.type ._start,@function\n"
2944 "\t.global ._start\n"
2945 "._start:\n"
2946 /* set up the new stack in r16 */
2947 "\tlis 16, vgPlain_interim_stack@highest\n"
2948 "\tori 16,16,vgPlain_interim_stack@higher\n"
2949 "\tsldi 16,16,32\n"
2950 "\toris 16,16,vgPlain_interim_stack@h\n"
2951 "\tori 16,16,vgPlain_interim_stack@l\n"
2952 "\txor 17,17,17\n"
2953 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2954 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2955 "\txor 18,18,18\n"
2956 "\tlis 18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" >> 16)\n"
2957 "\tori 18,18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2958 "\tadd 16,17,16\n"
2959 "\tadd 16,18,16\n"
2960 "\trldicr 16,16,0,59\n"
2961 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2962 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2963 boundary. And r1 is the original SP. Set the SP to r16 and
2964 call _start_in_C_linux, passing it the initial SP. */
2965 "\tmr 3,1\n"
2966 "\tmr 1,16\n"
2967 "\tlis 14, _start_in_C_linux@highest\n"
2968 "\tori 14,14,_start_in_C_linux@higher\n"
2969 "\tsldi 14,14,32\n"
2970 "\toris 14,14,_start_in_C_linux@h\n"
2971 "\tori 14,14,_start_in_C_linux@l\n"
2972 "\tld 14,0(14)\n"
2973 "\tmtctr 14\n"
2974 "\tbctrl\n"
2975 "\tnop\n"
2976 "\ttrap\n"
2978 #elif defined(VGP_ppc64le_linux)
2979 /* Little Endian uses ELF version 2 but in the future may also
2980 * support other ELF versions.
2982 asm("\n"
2983 "\t.align 2\n"
2984 "\t.global _start\n"
2985 "\t.type _start,@function\n"
2986 "_start:\n"
2987 "#if _CALL_ELF == 2 \n"
2988 "0: addis 2,12,.TOC.-0b@ha\n"
2989 " addi 2,2,.TOC.-0b@l\n"
2990 " .localentry _start, .-_start\n"
2991 "#endif \n"
2992 /* set up the new stack in r16 */
2993 "\tlis 16, vgPlain_interim_stack@highest\n"
2994 "\tori 16,16,vgPlain_interim_stack@higher\n"
2995 "\tsldi 16,16,32\n"
2996 "\toris 16,16,vgPlain_interim_stack@h\n"
2997 "\tori 16,16,vgPlain_interim_stack@l\n"
2998 "\txor 17,17,17\n"
2999 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
3000 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
3001 "\txor 18,18,18\n"
3002 "\tlis 18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" >> 16)\n"
3003 "\tori 18,18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
3004 "\tadd 16,17,16\n"
3005 "\tadd 16,18,16\n"
3006 "\trldicr 16,16,0,59\n"
3007 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
3008 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
3009 boundary. And r1 is the original SP. Set the SP to r16 and
3010 call _start_in_C_linux, passing it the initial SP. */
3011 "\tmr 3,1\n"
3012 "\tmr 1,16\n"
3013 "\tlis 14, _start_in_C_linux@highest\n"
3014 "\tori 14,14,_start_in_C_linux@higher\n"
3015 "\tsldi 14,14,32\n"
3016 "\toris 14,14,_start_in_C_linux@h\n"
3017 "\tori 14,14,_start_in_C_linux@l\n"
3018 "\tmtctr 14\n"
3019 "\tbctrl\n"
3020 "\tnop\n"
3021 "\ttrap\n"
3023 #elif defined(VGP_s390x_linux)
3025 This is the canonical entry point, usually the first thing in the text
3026 segment. Most registers' values are unspecified, except for:
3028 %r14 Contains a function pointer to be registered with `atexit'.
3029 This is how the dynamic linker arranges to have DT_FINI
3030 functions called for shared libraries that have been loaded
3031 before this code runs.
3033 %r15 The stack contains the arguments and environment:
3034 0(%r15) argc
3035 8(%r15) argv[0]
3037 (8*argc)(%r15) NULL
3038 (8*(argc+1))(%r15) envp[0]
3040 NULL
3042 asm("\n\t"
3043 ".text\n\t"
3044 ".globl _start\n\t"
3045 ".type _start,@function\n\t"
3046 "_start:\n\t"
3047 /* set up the new stack in %r1 */
3048 "larl %r1, vgPlain_interim_stack\n\t"
3049 "larl %r5, 1f\n\t"
3050 "ag %r1, 0(%r5)\n\t"
3051 "ag %r1, 2f-1f(%r5)\n\t"
3052 "nill %r1, 0xFFF0\n\t"
3053 /* install it, and collect the original one */
3054 "lgr %r2, %r15\n\t"
3055 "lgr %r15, %r1\n\t"
3056 /* call _start_in_C_linux, passing it the startup %r15 */
3057 "brasl %r14, _start_in_C_linux\n\t"
3058 /* trigger execution of an invalid opcode -> halt machine */
3059 "j .+2\n\t"
3060 "1: .quad "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n\t"
3061 "2: .quad "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)"\n\t"
3062 ".previous\n"
3064 #elif defined(VGP_arm_linux)
3065 asm("\n"
3066 "\t.text\n"
3067 "\t.align 4\n"
3068 "\t.type _start,#function\n"
3069 "\t.global _start\n"
3070 "_start:\n"
3071 "\tldr r0, [pc, #36]\n"
3072 "\tldr r1, [pc, #36]\n"
3073 "\tadd r0, r1, r0\n"
3074 "\tldr r1, [pc, #32]\n"
3075 "\tadd r0, r1, r0\n"
3076 "\tmvn r1, #15\n"
3077 "\tand r0, r0, r1\n"
3078 "\tmov r1, sp\n"
3079 "\tmov sp, r0\n"
3080 "\tmov r0, r1\n"
3081 "\tb _start_in_C_linux\n"
3082 "\t.word vgPlain_interim_stack\n"
3083 "\t.word "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
3084 "\t.word "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)"\n"
3086 #elif defined(VGP_arm64_linux)
3087 asm("\n"
3088 "\t.text\n"
3089 "\t.align 2\n"
3090 "\t.type _start,#function\n"
3091 "\t.global _start\n"
3092 "_start:\n"
3093 "\tadrp x0, vgPlain_interim_stack\n"
3094 "\tadd x0, x0, :lo12:vgPlain_interim_stack\n"
3095 // The next 2 assume that VG_STACK_GUARD_SZB fits in 32 bits
3096 "\tmov x1, (("VG_STRINGIFY(VG_STACK_GUARD_SZB)") >> 0) & 0xFFFF\n"
3097 "\tmovk x1, (("VG_STRINGIFY(VG_STACK_GUARD_SZB)") >> 16) & 0xFFFF,"
3098 " lsl 16\n"
3099 "\tadd x0, x0, x1\n"
3100 // The next 2 assume that VG_DEFAULT_STACK_ACTIVE_SZB fits in 32 bits
3101 "\tmov x1, (("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)") >> 0) & 0xFFFF\n"
3102 "\tmovk x1, (("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)") >> 16) & 0xFFFF,"
3103 " lsl 16\n"
3104 "\tadd x0, x0, x1\n"
3105 "\tand x0, x0, -16\n"
3106 "\tmov x1, sp\n"
3107 "\tmov sp, x0\n"
3108 "\tmov x0, x1\n"
3109 "\tb _start_in_C_linux\n"
3111 #elif defined(VGP_mips32_linux)
3112 asm("\n"
3113 "\t.type _gp_disp,@object\n"
3114 ".text\n"
3115 "\t.globl __start\n"
3116 "\t.type __start,@function\n"
3117 "__start:\n"
3119 "\tbal 1f\n"
3120 "\tnop\n"
3122 "1:\n"
3124 "\tlui $28, %hi(_gp_disp)\n"
3125 "\taddiu $28, $28, %lo(_gp_disp)\n"
3126 "\taddu $28, $28, $31\n"
3127 /* t1/$9 <- Addr(interim_stack) */
3128 "\tlui $9, %hi(vgPlain_interim_stack)\n"
3129 /* t1/$9 <- Addr(interim_stack) */
3130 "\taddiu $9, %lo(vgPlain_interim_stack)\n"
3133 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
3134 "\tli $11, "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)"\n"
3136 "\taddu $9, $9, $10\n"
3137 "\taddu $9, $9, $11\n"
3138 "\tli $12, 0xFFFFFFF0\n"
3139 "\tand $9, $9, $12\n"
3140 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
3141 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
3142 boundary. And $29 is the original SP. Set the SP to t1 and
3143 call _start_in_C, passing it the initial SP. */
3145 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
3146 "\tmove $29, $9\n" // $sp <- t1 (new sp)
3148 "\tlui $25, %hi(_start_in_C_linux)\n"
3149 "\taddiu $25, %lo(_start_in_C_linux)\n"
3151 "\tbal _start_in_C_linux\n"
3152 "\tbreak 0x7\n"
3153 ".previous\n"
3155 #elif defined(VGP_mips64_linux)
3156 asm(
3157 ".text\n"
3158 ".globl __start\n"
3159 ".type __start,@function\n"
3160 "__start:\n"
3161 "\t.set noreorder\n"
3162 "\t.cpload $25\n"
3163 "\t.set reorder\n"
3164 "\t.cprestore 16\n"
3165 "\tlui $9, %hi(vgPlain_interim_stack)\n"
3166 /* t1/$9 <- Addr(interim_stack) */
3167 "\tdaddiu $9, %lo(vgPlain_interim_stack)\n"
3169 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
3170 "\tli $11, "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)"\n"
3172 "\tdaddu $9, $9, $10\n"
3173 "\tdaddu $9, $9, $11\n"
3174 "\tli $12, 0xFFFFFF00\n"
3175 "\tand $9, $9, $12\n"
3176 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
3177 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
3178 boundary. And $29 is the original SP. Set the SP to t1 and
3179 call _start_in_C, passing it the initial SP. */
3181 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
3182 "\tmove $29, $9\n" // $sp <- t1 (new sp)
3184 "\tlui $9, %highest(_start_in_C_linux)\n"
3185 "\tori $9, %higher(_start_in_C_linux)\n"
3186 "\tdsll32 $9, $9, 0x0\n"
3187 "\tlui $10, %hi(_start_in_C_linux)\n"
3188 "\tdaddiu $10, %lo(_start_in_C_linux)\n"
3189 "\tdaddu $25, $9, $10\n"
3190 "\tjalr $25\n"
3191 "\tnop\n"
3192 ".previous\n"
3194 #else
3195 # error "Unknown linux platform"
3196 #endif
3198 /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
3199 #define _GNU_SOURCE
3200 #define _FILE_OFFSET_BITS 64
3201 /* This is in order to get AT_NULL and AT_PAGESIZE. */
3202 #include <elf.h>
3203 /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
3205 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3206 'static' causes gcc to complain it isn't.
3207 attribute 'used' also ensures the code is not eliminated at link
3208 time */
3209 __attribute__ ((used))
3210 void _start_in_C_linux ( UWord* pArgc );
3211 __attribute__ ((used))
3212 void _start_in_C_linux ( UWord* pArgc )
3214 Int r;
3215 Word argc = pArgc[0];
3216 HChar** argv = (HChar**)&pArgc[1];
3217 HChar** envp = (HChar**)&pArgc[1+argc+1];
3219 // For an inner Valgrind, register the interim stack asap.
3220 // This is needed to allow the outer valgrind to do stacktraces during init.
3221 // Note that this stack is not unregistered when the main thread
3222 // is switching to the (real) stack. Unregistering this would imply
3223 // to save the stack id in a global variable, and have a "if"
3224 // in run_a_thread_NORETURN to do the unregistration only for the
3225 // main thread. This unregistration is not worth this complexity.
3226 INNER_REQUEST
3227 ((void) VALGRIND_STACK_REGISTER
3228 (&VG_(interim_stack).bytes[0],
3229 &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack))));
3231 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3232 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3234 the_iicii.sp_at_startup = (Addr)pArgc;
3236 # if defined(VGP_ppc32_linux) || defined(VGP_ppc64be_linux) \
3237 || defined(VGP_ppc64le_linux) || defined(VGP_arm64_linux)
3239 /* ppc32/ppc64 can be configured with different page sizes.
3240 Determine this early. This is an ugly hack and really should
3241 be moved into valgrind_main. */
3242 UWord *sp = &pArgc[1+argc+1];
3243 while (*sp++ != 0)
3245 for (; *sp != AT_NULL && *sp != AT_PAGESZ; sp += 2);
3246 if (*sp == AT_PAGESZ) {
3247 VKI_PAGE_SIZE = sp[1];
3248 for (VKI_PAGE_SHIFT = 12;
3249 VKI_PAGE_SHIFT <= VKI_MAX_PAGE_SHIFT; VKI_PAGE_SHIFT++)
3250 if (VKI_PAGE_SIZE == (1UL << VKI_PAGE_SHIFT))
3251 break;
3254 # endif
3256 r = valgrind_main( (Int)argc, argv, envp );
3257 /* NOTREACHED */
3258 VG_(exit)(r);
3262 /*====================================================================*/
3263 /*=== Getting to main() alive: darwin ===*/
3264 /*====================================================================*/
3266 #elif defined(VGO_darwin)
3269 Memory layout established by kernel:
3271 0(%esp) argc
3272 4(%esp) argv[0]
3274 argv[argc-1]
3275 NULL
3276 envp[0]
3278 envp[n]
3279 NULL
3280 executable name (presumably, a pointer to it)
3281 NULL
3283 Ditto in the 64-bit case, except all offsets from SP are obviously
3284 twice as large.
3287 /* The kernel hands control to _start, which extracts the initial
3288 stack pointer and calls onwards to _start_in_C_darwin. This also
3289 switches to the new stack. */
3290 #if defined(VGP_x86_darwin)
3291 asm("\n"
3292 ".text\n"
3293 ".align 2,0x90\n"
3294 "\t.globl __start\n"
3295 "__start:\n"
3296 /* set up the new stack in %eax */
3297 "\tmovl $_vgPlain_interim_stack, %eax\n"
3298 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
3299 "\taddl $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %eax\n"
3300 "\tsubl $16, %eax\n"
3301 "\tandl $~15, %eax\n"
3302 /* install it, and collect the original one */
3303 "\txchgl %eax, %esp\n"
3304 "\tsubl $12, %esp\n" // keep stack 16 aligned; see #295428
3305 /* call _start_in_C_darwin, passing it the startup %esp */
3306 "\tpushl %eax\n"
3307 "\tcall __start_in_C_darwin\n"
3308 "\tint $3\n"
3309 "\tint $3\n"
3311 #elif defined(VGP_amd64_darwin)
3312 asm("\n"
3313 ".text\n"
3314 "\t.globl __start\n"
3315 ".align 3,0x90\n"
3316 "__start:\n"
3317 /* set up the new stack in %rdi */
3318 "\tmovabsq $_vgPlain_interim_stack, %rdi\n"
3319 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
3320 "\taddq $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %rdi\n"
3321 "\tandq $~15, %rdi\n"
3322 /* install it, and collect the original one */
3323 "\txchgq %rdi, %rsp\n"
3324 /* call _start_in_C_darwin, passing it the startup %rsp */
3325 "\tcall __start_in_C_darwin\n"
3326 "\tint $3\n"
3327 "\tint $3\n"
3329 #endif
3331 void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2);
3332 void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2) {
3333 // skip check
3334 return VG_(memcpy)(dest,src,n);
3336 void* __memset_chk(void *s, int c, SizeT n, SizeT n2);
3337 void* __memset_chk(void *s, int c, SizeT n, SizeT n2) {
3338 // skip check
3339 return VG_(memset)(s,c,n);
3341 void bzero(void *s, SizeT n);
3342 void bzero(void *s, SizeT n) {
3343 VG_(memset)(s,0,n);
3346 void* memcpy(void *dest, const void *src, SizeT n);
3347 void* memcpy(void *dest, const void *src, SizeT n) {
3348 return VG_(memcpy)(dest,src,n);
3350 void* memset(void *s, int c, SizeT n);
3351 void* memset(void *s, int c, SizeT n) {
3352 return VG_(memset)(s,c,n);
3355 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3356 'static' causes gcc to complain it isn't. */
3357 void _start_in_C_darwin ( UWord* pArgc );
3358 void _start_in_C_darwin ( UWord* pArgc )
3360 Int r;
3361 Int argc = *(Int *)pArgc; // not pArgc[0] on LP64
3362 HChar** argv = (HChar**)&pArgc[1];
3363 HChar** envp = (HChar**)&pArgc[1+argc+1];
3365 // See _start_in_C_linux
3366 INNER_REQUEST
3367 ((void) VALGRIND_STACK_REGISTER
3368 (&VG_(interim_stack).bytes[0],
3369 &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack))));
3371 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3372 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3374 the_iicii.sp_at_startup = (Addr)pArgc;
3376 r = valgrind_main( (Int)argc, argv, envp );
3377 /* NOTREACHED */
3378 VG_(exit)(r);
3382 #else
3384 # error "Unknown OS"
3385 #endif
3388 /*====================================================================*/
3389 /*=== {u,}{div,mod}di3 replacements ===*/
3390 /*====================================================================*/
3392 /* For static linking on x86-darwin, we need to supply our own 64-bit
3393 integer division code, else the link dies thusly:
3395 ld_classic: Undefined symbols:
3396 ___udivdi3
3397 ___umoddi3
3399 #if defined(VGP_x86_darwin)
3401 /* Routines for doing signed/unsigned 64 x 64 ==> 64 div and mod
3402 (udivdi3, umoddi3, divdi3, moddi3) using only 32 x 32 ==> 32
3403 division. Cobbled together from
3405 http://www.hackersdelight.org/HDcode/divlu.c
3406 http://www.hackersdelight.org/HDcode/divls.c
3407 http://www.hackersdelight.org/HDcode/newCode/divDouble.c
3409 The code from those three files is covered by the following license,
3410 as it appears at:
3412 http://www.hackersdelight.org/permissions.htm
3414 You are free to use, copy, and distribute any of the code on
3415 this web site, whether modified by you or not. You need not give
3416 attribution. This includes the algorithms (some of which appear
3417 in Hacker's Delight), the Hacker's Assistant, and any code
3418 submitted by readers. Submitters implicitly agree to this.
3421 /* Long division, unsigned (64/32 ==> 32).
3422 This procedure performs unsigned "long division" i.e., division of a
3423 64-bit unsigned dividend by a 32-bit unsigned divisor, producing a
3424 32-bit quotient. In the overflow cases (divide by 0, or quotient
3425 exceeds 32 bits), it returns a remainder of 0xFFFFFFFF (an impossible
3426 value).
3427 The dividend is u1 and u0, with u1 being the most significant word.
3428 The divisor is parameter v. The value returned is the quotient.
3429 Max line length is 57, to fit in hacker.book. */
3431 static Int nlz32(UInt x)
3433 Int n;
3434 if (x == 0) return(32);
3435 n = 0;
3436 if (x <= 0x0000FFFF) {n = n +16; x = x <<16;}
3437 if (x <= 0x00FFFFFF) {n = n + 8; x = x << 8;}
3438 if (x <= 0x0FFFFFFF) {n = n + 4; x = x << 4;}
3439 if (x <= 0x3FFFFFFF) {n = n + 2; x = x << 2;}
3440 if (x <= 0x7FFFFFFF) {n = n + 1;}
3441 return n;
3444 /* 64 x 32 ==> 32 unsigned division, using only 32 x 32 ==> 32
3445 division as a primitive. */
3446 static UInt divlu2(UInt u1, UInt u0, UInt v, UInt *r)
3448 const UInt b = 65536; // Number base (16 bits).
3449 UInt un1, un0, // Norm. dividend LSD's.
3450 vn1, vn0, // Norm. divisor digits.
3451 q1, q0, // Quotient digits.
3452 un32, un21, un10, // Dividend digit pairs.
3453 rhat; // A remainder.
3454 Int s; // Shift amount for norm.
3456 if (u1 >= v) { // If overflow, set rem.
3457 if (r != NULL) // to an impossible value,
3458 *r = 0xFFFFFFFF; // and return the largest
3459 return 0xFFFFFFFF;} // possible quotient.
3461 s = nlz32(v); // 0 <= s <= 31.
3462 v = v << s; // Normalize divisor.
3463 vn1 = v >> 16; // Break divisor up into
3464 vn0 = v & 0xFFFF; // two 16-bit digits.
3466 un32 = (u1 << s) | ((u0 >> (32 - s)) & (-s >> 31));
3467 un10 = u0 << s; // Shift dividend left.
3469 un1 = un10 >> 16; // Break right half of
3470 un0 = un10 & 0xFFFF; // dividend into two digits.
3472 q1 = un32/vn1; // Compute the first
3473 rhat = un32 - q1*vn1; // quotient digit, q1.
3474 again1:
3475 if (q1 >= b || q1*vn0 > b*rhat + un1) {
3476 q1 = q1 - 1;
3477 rhat = rhat + vn1;
3478 if (rhat < b) goto again1;}
3480 un21 = un32*b + un1 - q1*v; // Multiply and subtract.
3482 q0 = un21/vn1; // Compute the second
3483 rhat = un21 - q0*vn1; // quotient digit, q0.
3484 again2:
3485 if (q0 >= b || q0*vn0 > b*rhat + un0) {
3486 q0 = q0 - 1;
3487 rhat = rhat + vn1;
3488 if (rhat < b) goto again2;}
3490 if (r != NULL) // If remainder is wanted,
3491 *r = (un21*b + un0 - q0*v) >> s; // return it.
3492 return q1*b + q0;
3496 /* 64 x 32 ==> 32 signed division, using only 32 x 32 ==> 32 division
3497 as a primitive. */
3498 static Int divls(Int u1, UInt u0, Int v, Int *r)
3500 Int q, uneg, vneg, diff, borrow;
3502 uneg = u1 >> 31; // -1 if u < 0.
3503 if (uneg) { // Compute the absolute
3504 u0 = -u0; // value of the dividend u.
3505 borrow = (u0 != 0);
3506 u1 = -u1 - borrow;}
3508 vneg = v >> 31; // -1 if v < 0.
3509 v = (v ^ vneg) - vneg; // Absolute value of v.
3511 if ((UInt)u1 >= (UInt)v) goto overflow;
3513 q = divlu2(u1, u0, v, (UInt *)r);
3515 diff = uneg ^ vneg; // Negate q if signs of
3516 q = (q ^ diff) - diff; // u and v differed.
3517 if (uneg && r != NULL)
3518 *r = -*r;
3520 if ((diff ^ q) < 0 && q != 0) { // If overflow,
3521 overflow: // set remainder
3522 if (r != NULL) // to an impossible value,
3523 *r = 0x80000000; // and return the largest
3524 q = 0x80000000;} // possible neg. quotient.
3525 return q;
3530 /* This file contains a program for doing 64/64 ==> 64 division, on a
3531 machine that does not have that instruction but that does have
3532 instructions for "long division" (64/32 ==> 32). Code for unsigned
3533 division is given first, followed by a simple program for doing the
3534 signed version by using the unsigned version.
3535 These programs are useful in implementing "long long" (64-bit)
3536 arithmetic on a machine that has the long division instruction. It will
3537 work on 64- and 32-bit machines, provided the compiler implements long
3538 long's (64-bit integers). It is desirable that the machine have the
3539 Count Leading Zeros instruction.
3540 In the GNU world, these programs are known as __divdi3 and __udivdi3,
3541 and similar names are used here.
3542 This material is not in HD, but may be in a future edition.
3543 Max line length is 57, to fit in hacker.book. */
3546 static Int nlz64(ULong x)
3548 Int n;
3549 if (x == 0) return(64);
3550 n = 0;
3551 if (x <= 0x00000000FFFFFFFFULL) {n = n + 32; x = x << 32;}
3552 if (x <= 0x0000FFFFFFFFFFFFULL) {n = n + 16; x = x << 16;}
3553 if (x <= 0x00FFFFFFFFFFFFFFULL) {n = n + 8; x = x << 8;}
3554 if (x <= 0x0FFFFFFFFFFFFFFFULL) {n = n + 4; x = x << 4;}
3555 if (x <= 0x3FFFFFFFFFFFFFFFULL) {n = n + 2; x = x << 2;}
3556 if (x <= 0x7FFFFFFFFFFFFFFFULL) {n = n + 1;}
3557 return n;
3560 // ---------------------------- udivdi3 --------------------------------
3562 /* The variables u0, u1, etc. take on only 32-bit values, but they
3563 are declared long long to avoid some compiler warning messages and to
3564 avoid some unnecessary EXTRs that the compiler would put in, to
3565 convert long longs to ints.
3567 First the procedure takes care of the case in which the divisor is a
3568 32-bit quantity. There are two subcases: (1) If the left half of the
3569 dividend is less than the divisor, one execution of DIVU is all that
3570 is required (overflow is not possible). (2) Otherwise it does two
3571 divisions, using the grade school method, with variables used as
3572 suggested below.
3574 q1 q0
3575 ________
3576 v) u1 u0
3577 q1*v
3578 ____
3579 k u0 */
3581 /* These macros must be used with arguments of the appropriate type
3582 (unsigned long long for DIVU and long long for DIVS. They are
3583 simulations of the presumed machines ops. I.e., they look at only the
3584 low-order 32 bits of the divisor, they return garbage if the division
3585 overflows, and they return garbage in the high-order half of the
3586 quotient doubleword.
3587 In practice, these would be replaced with uses of the machine's DIVU
3588 and DIVS instructions (e.g., by using the GNU "asm" facility). */
3590 static UInt DIVU ( ULong u, UInt v )
3592 UInt uHi = (UInt)(u >> 32);
3593 UInt uLo = (UInt)u;
3594 return divlu2(uHi, uLo, v, NULL);
3597 static Int DIVS ( Long u, Int v )
3599 Int uHi = (Int)(u >> 32);
3600 UInt uLo = (UInt)u;
3601 return divls(uHi, uLo, v, NULL);
3604 /* 64 x 64 ==> 64 unsigned division, using only 32 x 32 ==> 32
3605 division as a primitive. */
3606 static ULong udivdi3(ULong u, ULong v)
3608 ULong u0, u1, v1, q0, q1, k, n;
3610 if (v >> 32 == 0) { // If v < 2**32:
3611 if (u >> 32 < v) // If u/v cannot overflow,
3612 return DIVU(u, v) // just do one division.
3613 & 0xFFFFFFFF;
3614 else { // If u/v would overflow:
3615 u1 = u >> 32; // Break u up into two
3616 u0 = u & 0xFFFFFFFF; // halves.
3617 q1 = DIVU(u1, v) // First quotient digit.
3618 & 0xFFFFFFFF;
3619 k = u1 - q1*v; // First remainder, < v.
3620 q0 = DIVU((k << 32) + u0, v) // 2nd quot. digit.
3621 & 0xFFFFFFFF;
3622 return (q1 << 32) + q0;
3625 // Here v >= 2**32.
3626 n = nlz64(v); // 0 <= n <= 31.
3627 v1 = (v << n) >> 32; // Normalize the divisor
3628 // so its MSB is 1.
3629 u1 = u >> 1; // To ensure no overflow.
3630 q1 = DIVU(u1, v1) // Get quotient from
3631 & 0xFFFFFFFF; // divide unsigned insn.
3632 q0 = (q1 << n) >> 31; // Undo normalization and
3633 // division of u by 2.
3634 if (q0 != 0) // Make q0 correct or
3635 q0 = q0 - 1; // too small by 1.
3636 if ((u - q0*v) >= v)
3637 q0 = q0 + 1; // Now q0 is correct.
3638 return q0;
3642 // ----------------------------- divdi3 --------------------------------
3644 /* This routine presumes that smallish cases (those which can be done in
3645 one execution of DIVS) are common. If this is not the case, the test for
3646 this case should be deleted.
3647 Note that the test for when DIVS can be used is not entirely
3648 accurate. For example, DIVS is not used if v = 0xFFFFFFFF8000000,
3649 whereas if could be (if u is sufficiently small in magnitude). */
3651 // ------------------------------ cut ----------------------------------
3653 static ULong my_llabs ( Long x )
3655 ULong t = x >> 63;
3656 return (x ^ t) - t;
3659 /* 64 x 64 ==> 64 signed division, using only 32 x 32 ==> 32 division
3660 as a primitive. */
3661 static Long divdi3(Long u, Long v)
3663 ULong au, av;
3664 Long q, t;
3665 au = my_llabs(u);
3666 av = my_llabs(v);
3667 if (av >> 31 == 0) { // If |v| < 2**31 and
3668 // if (v << 32 >> 32 == v) { // If v is in range and
3669 if (au < av << 31) { // |u|/|v| cannot
3670 q = DIVS(u, v); // overflow, use DIVS.
3671 return (q << 32) >> 32;
3674 q = udivdi3(au,av); // Invoke udivdi3.
3675 t = (u ^ v) >> 63; // If u, v have different
3676 return (q ^ t) - t; // signs, negate q.
3679 // ---------------------------- end cut --------------------------------
3681 ULong __udivdi3 (ULong u, ULong v);
3682 ULong __udivdi3 (ULong u, ULong v)
3684 return udivdi3(u,v);
3687 Long __divdi3 (Long u, Long v);
3688 Long __divdi3 (Long u, Long v)
3690 return divdi3(u,v);
3693 ULong __umoddi3 (ULong u, ULong v);
3694 ULong __umoddi3 (ULong u, ULong v)
3696 ULong q = __udivdi3(u, v);
3697 ULong r = u - q * v;
3698 return r;
3701 Long __moddi3 (Long u, Long v);
3702 Long __moddi3 (Long u, Long v)
3704 Long q = __divdi3(u, v);
3705 Long r = u - q * v;
3706 return r;
3709 /* ------------------------------------------------
3710 ld_classic: Undefined symbols:
3711 ___fixunsdfdi
3712 ------------------------------------------------
3715 /* ===-- fixunsdfdi.c - Implement __fixunsdfdi -----------------------------===
3717 * The LLVM Compiler Infrastructure
3719 * This file is dual licensed under the MIT and the University of Illinois Open
3720 * Source Licenses. See LICENSE.TXT for details.
3722 * ===----------------------------------------------------------------------===
3724 * This file implements __fixunsdfdi for the compiler_rt library.
3726 * ===----------------------------------------------------------------------===
3729 /* As per http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses,
3731 the "NCSA/University of Illinois Open Source License" is compatible
3732 with the GPL (both version 2 and 3). What is claimed to be
3733 compatible is this
3735 http://www.opensource.org/licenses/UoI-NCSA.php
3737 and the LLVM documentation at
3739 http://www.llvm.org/docs/DeveloperPolicy.html#license
3741 says all the code in LLVM is available under the University of
3742 Illinois/NCSA Open Source License, at this URL
3744 http://www.opensource.org/licenses/UoI-NCSA.php
3746 viz, the same one that the FSF pages claim is compatible. So I
3747 think it's OK to include it.
3750 /* Returns: convert a to a unsigned long long, rounding toward zero.
3751 * Negative values all become zero.
3754 /* Assumption: double is a IEEE 64 bit floating point type
3755 * du_int is a 64 bit integral type
3756 * value in double is representable in du_int or is negative
3757 * (no range checking performed)
3760 /* seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm */
3762 typedef unsigned long long du_int;
3763 typedef unsigned su_int;
3765 typedef union
3767 du_int all;
3768 struct
3770 #if VG_LITTLEENDIAN
3771 su_int low;
3772 su_int high;
3773 #else
3774 su_int high;
3775 su_int low;
3776 #endif /* VG_LITTLEENDIAN */
3778 } udwords;
3780 typedef union
3782 udwords u;
3783 double f;
3784 } double_bits;
3786 du_int __fixunsdfdi(double a);
3788 du_int
3789 __fixunsdfdi(double a)
3791 double_bits fb;
3792 fb.f = a;
3793 int e = ((fb.u.s.high & 0x7FF00000) >> 20) - 1023;
3794 if (e < 0 || (fb.u.s.high & 0x80000000))
3795 return 0;
3796 udwords r;
3797 r.s.high = (fb.u.s.high & 0x000FFFFF) | 0x00100000;
3798 r.s.low = fb.u.s.low;
3799 if (e > 52)
3800 r.all <<= (e - 52);
3801 else
3802 r.all >>= (52 - e);
3803 return r.all;
3807 #endif
3810 /*====================================================================*/
3811 /*=== Dummy _voucher_mach_msg_set for OSX 10.10 ===*/
3812 /*====================================================================*/
3814 #if defined(VGO_darwin) && DARWIN_VERS == DARWIN_10_10
3816 /* Builds on MacOSX 10.10 seem to need this for some reason. */
3817 /* extern boolean_t voucher_mach_msg_set(mach_msg_header_t *msg)
3818 __attribute__((weak_import));
3819 I haven't a clue what the return value means, so just return 0.
3820 Looks like none of the generated uses in the tree look at the
3821 return value anyway.
3823 UWord voucher_mach_msg_set ( UWord arg1 );
3824 UWord voucher_mach_msg_set ( UWord arg1 )
3826 return 0;
3829 #endif
3832 /*--------------------------------------------------------------------*/
3833 /*--- end ---*/
3834 /*--------------------------------------------------------------------*/