configure.ac: Sort AC_CHECK_FUNCS() arguments alphabetically
[valgrind.git] / coregrind / m_main.c
blob68edc4d4997372bc55ad695715492fa78b664f2d
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-2017 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, see <http://www.gnu.org/licenses/>.
26 The GNU General Public License is contained in the file COPYING.
29 #include "vgversion.h"
30 #include "pub_core_basics.h"
31 #include "pub_core_vki.h"
32 #include "pub_core_threadstate.h"
33 #include "pub_core_xarray.h"
34 #include "pub_core_clientstate.h"
35 #include "pub_core_aspacemgr.h"
36 #include "pub_core_aspacehl.h"
37 #include "pub_core_clreq.h"
38 #include "pub_core_commandline.h"
39 #include "pub_core_debuglog.h"
40 #include "pub_core_errormgr.h"
41 #include "pub_core_execontext.h"
42 #include "pub_core_gdbserver.h"
43 #include "pub_core_initimg.h"
44 #include "pub_core_libcbase.h"
45 #include "pub_core_libcassert.h"
46 #include "pub_core_libcfile.h"
47 #include "pub_core_libcprint.h"
48 #include "pub_core_libcproc.h"
49 #include "pub_core_libcsignal.h"
50 #include "pub_core_sbprofile.h"
51 #include "pub_core_mach.h"
52 #include "pub_core_machine.h"
53 #include "pub_core_mallocfree.h"
54 #include "pub_core_options.h"
55 #include "pub_core_debuginfo.h"
56 #include "pub_core_redir.h"
57 #include "pub_core_scheduler.h"
58 #include "pub_core_seqmatch.h" // For VG_(string_match)
59 #include "pub_core_signals.h"
60 #include "pub_core_stacks.h" // For VG_(register_stack)
61 #include "pub_core_syswrap.h"
62 #include "pub_core_tooliface.h"
63 #include "pub_core_translate.h" // For VG_(translate)
64 #include "pub_core_trampoline.h"
65 #include "pub_core_transtab.h"
66 #include "pub_core_inner.h"
67 #if defined(ENABLE_INNER_CLIENT_REQUEST)
68 #include "pub_core_clreq.h"
69 #endif
72 /*====================================================================*/
73 /*=== Command-line: variables, processing, etc ===*/
74 /*====================================================================*/
76 // See pub_{core,tool}_options.h for explanations of all these.
78 // need_help: 0 = no, 1 = --help-dyn-options, 2 = --help 3 = --help-debug
79 static void usage_NORETURN ( int need_help )
81 /* 'usage1' contains a %s
82 - for the name of the GDB executable
83 - for the name of vgdb's path prefix
84 which must be supplied when they are VG_(printf)'d. */
85 const HChar usage1[] =
86 "usage: valgrind [options] prog-and-args\n"
87 "\n"
88 " tool-selection option, with default in [ ]:\n"
89 " --tool=<name> use the Valgrind tool named <name> [memcheck]\n"
90 "\n"
91 " basic user options for all Valgrind tools, with defaults in [ ]:\n"
92 " -h --help show this message\n"
93 " --help-debug show this message, plus debugging options\n"
94 " --help-dyn-options show the dynamically changeable options\n"
95 " --version show version\n"
96 " -q --quiet run silently; only print error msgs\n"
97 " -v --verbose be more verbose -- show misc extra info\n"
98 " --trace-children=no|yes Valgrind-ise child processes (follow execve)? [no]\n"
99 " --trace-children-skip=patt1,patt2,... specifies a list of executables\n"
100 " that --trace-children=yes should not trace into\n"
101 " --trace-children-skip-by-arg=patt1,patt2,... same as --trace-children-skip=\n"
102 " but check the argv[] entries for children, rather\n"
103 " than the exe name, to make a follow/no-follow decision\n"
104 " --child-silent-after-fork=no|yes omit child output between fork & exec? [no]\n"
105 " --vgdb=no|yes|full activate gdbserver? [yes]\n"
106 " full is slower but provides precise watchpoint/step\n"
107 " --vgdb-error=<number> invoke gdbserver after <number> errors [%d]\n"
108 " to get started quickly, use --vgdb-error=0\n"
109 " and follow the on-screen directions\n"
110 " --vgdb-stop-at=event1,event2,... invoke gdbserver for given events [none]\n"
111 " where event is one of:\n"
112 " startup exit valgrindabexit all none\n"
113 " --track-fds=no|yes|all track open file descriptors? [no]\n"
114 " all includes reporting stdin, stdout and stderr\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 " --exit-on-first-error=no|yes exit code on the first error found? [no]\n"
130 " --error-exitcode=<number> exit code to return if errors found [0=disable]\n"
131 " --error-markers=<begin>,<end> add lines with begin/end markers before/after\n"
132 " each error output in plain text mode [none]\n"
133 " --show-error-list=no|yes show detected errors list and\n"
134 " suppression counts at exit [no]\n"
135 " -s same as --show-error-list=yes\n"
136 " --keep-debuginfo=no|yes Keep symbols etc for unloaded code [no]\n"
137 " This allows saved stack traces (e.g. memory leaks)\n"
138 " to include file/line info for code that has been\n"
139 " dlclose'd (or similar)\n"
140 " --show-below-main=no|yes continue stack traces below main() [no]\n"
141 " --default-suppressions=yes|no\n"
142 " load default suppressions [yes]\n"
143 " --suppressions=<filename> suppress errors described in <filename>\n"
144 " --gen-suppressions=no|yes|all print suppressions for errors? [no]\n"
145 " --input-fd=<number> file descriptor for input [0=stdin]\n"
146 " --dsymutil=no|yes run dsymutil on Mac OS X when helpful? [yes]\n"
147 " --max-stackframe=<number> assume stack switch for SP changes larger\n"
148 " than <number> bytes [2000000]\n"
149 " --main-stacksize=<number> set size of main thread's stack (in bytes)\n"
150 " [min(max(current 'ulimit' value,1MB),16MB)]\n"
151 "\n"
152 " user options for Valgrind tools that replace malloc:\n"
153 " --alignment=<number> set minimum alignment of heap allocations [%s]\n"
154 " --redzone-size=<number> set minimum size of redzones added before/after\n"
155 " heap blocks (in bytes). [%s]\n"
156 " --xtree-memory=none|allocs|full profile heap memory in an xtree [none]\n"
157 " and produces a report at the end of the execution\n"
158 " none: no profiling, allocs: current allocated\n"
159 " size/blocks, full: profile current and cumulative\n"
160 " allocated size/blocks and freed size/blocks.\n"
161 " --xtree-memory-file=<file> xtree memory report file [xtmemory.kcg.%%p]\n"
162 "\n"
163 " uncommon user options for all Valgrind tools:\n"
164 " --fullpath-after= (with nothing after the '=')\n"
165 " show full source paths in call stacks\n"
166 " --fullpath-after=string like --fullpath-after=, but only show the\n"
167 " part of the path after 'string'. Allows removal\n"
168 " of path prefixes. Use this flag multiple times\n"
169 " to specify a set of prefixes to remove.\n"
170 " --extra-debuginfo-path=path absolute path to search for additional\n"
171 " debug symbols, in addition to existing default\n"
172 " well known search paths.\n"
173 " --debuginfo-server=ipaddr:port also query this server\n"
174 " (valgrind-di-server) for debug symbols\n"
175 " --allow-mismatched-debuginfo=no|yes [no]\n"
176 " for the above two flags only, accept debuginfo\n"
177 " objects that don't \"match\" the main object\n"
178 " --smc-check=none|stack|all|all-non-file [all-non-file]\n"
179 " checks for self-modifying code: none, only for\n"
180 " code found in stacks, for all code, or for all\n"
181 " code except that from file-backed mappings\n"
182 " --read-inline-info=yes|no read debug info about inlined function calls\n"
183 " and use it to do better stack traces.\n"
184 " [yes] on Linux/Android/Solaris for the tools\n"
185 " Memcheck/Massif/Helgrind/DRD only.\n"
186 " [no] for all other tools and platforms.\n"
187 " --read-var-info=yes|no read debug info on stack and global variables\n"
188 " and use it to print better error messages in\n"
189 " tools that make use of it (Memcheck, Helgrind,\n"
190 " DRD) [no]\n"
191 " --vgdb-poll=<number> gdbserver poll max every <number> basic blocks [%d] \n"
192 " --vgdb-shadow-registers=no|yes let gdb see the shadow registers [no]\n"
193 " --vgdb-prefix=<prefix> prefix for vgdb FIFOs [%s]\n"
194 " --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]\n"
195 " --run-cxx-freeres=no|yes free up libstdc++ memory at exit on Linux\n"
196 " and Solaris? [yes]\n"
197 " --sim-hints=hint1,hint2,... activate unusual sim behaviours [none] \n"
198 " where hint is one of:\n"
199 " lax-ioctls lax-doors fuse-compatible enable-outer\n"
200 " no-inner-prefix no-nptl-pthread-stackcache fallback-llsc none\n"
201 " --fair-sched=no|yes|try schedule threads fairly on multicore systems [no]\n"
202 " --kernel-variant=variant1,variant2,...\n"
203 " handle non-standard kernel variants [none]\n"
204 " where variant is one of:\n"
205 " bproc android-no-hw-tls\n"
206 " android-gpu-sgx5xx android-gpu-adreno3xx none\n"
207 " --merge-recursive-frames=<number> merge frames between identical\n"
208 " program counters in max <number> frames) [0]\n"
209 " --num-transtab-sectors=<number> size of translated code cache [%d]\n"
210 " more sectors may increase performance, but use more memory.\n"
211 " --avg-transtab-entry-size=<number> avg size in bytes of a translated\n"
212 " basic block [0, meaning use tool provided default]\n"
213 " --aspace-minaddr=0xPP avoid mapping memory below 0xPP [guessed]\n"
214 " --valgrind-stacksize=<number> size of valgrind (host) thread's stack\n"
215 " (in bytes) ["
216 VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)
217 "]\n"
218 " --show-emwarns=no|yes show warnings about emulation limits? [no]\n"
219 " --require-text-symbol=:sonamepattern:symbolpattern abort run if the\n"
220 " stated shared object doesn't have the stated\n"
221 " text symbol. Patterns can contain ? and *.\n"
222 " --soname-synonyms=syn1=pattern1,syn2=pattern2,... synonym soname\n"
223 " specify patterns for function wrapping or replacement.\n"
224 " To use a non-libc malloc library that is\n"
225 " in the main exe: --soname-synonyms=somalloc=NONE\n"
226 " in libxyzzy.so: --soname-synonyms=somalloc=libxyzzy.so\n"
227 " --sigill-diagnostics=yes|no warn about illegal instructions? [yes]\n"
228 " --unw-stack-scan-thresh=<number> Enable stack-scan unwind if fewer\n"
229 " than <number> good frames found [0, meaning \"disabled\"]\n"
230 " NOTE: stack scanning is only available on arm-linux.\n"
231 " --unw-stack-scan-frames=<number> Max number of frames that can be\n"
232 " recovered by stack scanning [5]\n"
233 " --resync-filter=no|yes|verbose [yes on MacOS, no on other OSes]\n"
234 " attempt to avoid expensive address-space-resync operations\n"
235 " --max-threads=<number> maximum number of threads that valgrind can\n"
236 " handle [%d]\n"
237 "\n";
239 const HChar usage2[] =
240 "\n"
241 " debugging options for all Valgrind tools:\n"
242 " -d show verbose debugging output\n"
243 " --stats=no|yes show tool and core statistics [no]\n"
244 " --sanity-level=<number> level of sanity checking to do [1]\n"
245 " --trace-flags=<XXXXXXXX> show generated code? (X = 0|1) [00000000]\n"
246 " --profile-flags=<XXXXXXXX> ditto, but for profiling (X = 0|1) [00000000]\n"
247 " --profile-interval=<number> show profile every <number> event checks\n"
248 " [0, meaning only at the end of the run]\n"
249 " --trace-notbelow=<number> only show BBs above <number> [999999999]\n"
250 " --trace-notabove=<number> only show BBs below <number> [0]\n"
251 " --trace-syscalls=no|yes show all system calls? [no]\n"
252 " --trace-signals=no|yes show signal handling details? [no]\n"
253 " --trace-symtab=no|yes show symbol table details? [no]\n"
254 " --trace-symtab-patt=<patt> limit debuginfo tracing to obj name <patt>\n"
255 " --trace-cfi=no|yes show call-frame-info details? [no]\n"
256 " --debug-dump=syms mimic /usr/bin/readelf --syms\n"
257 " --debug-dump=line mimic /usr/bin/readelf --debug-dump=line\n"
258 " --debug-dump=frames mimic /usr/bin/readelf --debug-dump=frames\n"
259 " --trace-redir=no|yes show redirection details? [no]\n"
260 " --trace-sched=no|yes show thread scheduler details? [no]\n"
261 " --profile-heap=no|yes profile Valgrind's own space use\n"
262 " --core-redzone-size=<number> set minimum size of redzones added before/after\n"
263 " heap blocks allocated for Valgrind internal use (in bytes) [4]\n"
264 " --wait-for-gdb=yes|no pause on startup to wait for gdb attach\n"
265 " --sym-offsets=yes|no show syms in form 'name+offset'? [no]\n"
266 " --progress-interval=<number> report progress every <number>\n"
267 " CPU seconds [0, meaning disabled]\n"
268 " --command-line-only=no|yes only use command line options [no]\n"
269 "\n"
270 " Vex options for all Valgrind tools:\n"
271 " --vex-iropt-verbosity=<0..9> [0]\n"
272 " --vex-iropt-level=<0..2> [2]\n"
273 " --vex-iropt-unroll-thresh=<0..400> [120]\n"
274 " --vex-guest-max-insns=<1..100> [50]\n"
275 " --vex-guest-chase=no|yes [yes]\n"
276 " Precise exception control. Possible values for 'mode' are as follows\n"
277 " and specify the minimum set of registers guaranteed to be correct\n"
278 " immediately prior to memory access instructions:\n"
279 " sp-at-mem-access stack pointer only\n"
280 " unwindregs-at-mem-access registers needed for stack unwinding\n"
281 " allregs-at-mem-access all registers\n"
282 " allregs-at-each-insn all registers are always correct\n"
283 " Default value for all 3 following flags is [unwindregs-at-mem-access].\n"
284 " --vex-iropt-register-updates=mode setting to use by default\n"
285 " --px-default=mode synonym for --vex-iropt-register-updates\n"
286 " --px-file-backed=mode optional setting for file-backed (non-JIT) code\n"
287 " Tracing and profile control:\n"
288 " --trace-flags and --profile-flags values (omit the middle space):\n"
289 " 1000 0000 show conversion into IR\n"
290 " 0100 0000 show after initial opt\n"
291 " 0010 0000 show after instrumentation\n"
292 " 0001 0000 show after second opt\n"
293 " 0000 1000 show after tree building\n"
294 " 0000 0100 show selecting insns\n"
295 " 0000 0010 show after reg-alloc\n"
296 " 0000 0001 show final assembly\n"
297 " 0000 0000 show summary profile only\n"
298 " (Nb: you need --trace-notbelow and/or --trace-notabove\n"
299 " with --trace-flags for full details)\n"
300 " --vex-regalloc-version=2|3 [3]\n"
301 "\n"
302 " debugging options for Valgrind tools that report errors\n"
303 " --dump-error=<number> show translation for basic block associated\n"
304 " with <number>'th error context [0=show none]\n"
305 "\n"
306 " debugging options for Valgrind tools that replace malloc:\n"
307 " --trace-malloc=no|yes show client malloc details? [no]\n"
308 " --xtree-compress-strings=no|yes compress strings in xtree callgrind format [yes]\n"
309 "\n";
311 const HChar usage3[] =
312 "\n"
313 " Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc\n"
314 "\n"
315 " %s is %s\n"
316 " Valgrind is Copyright (C) 2000-2017, and GNU GPL'd, by Julian Seward et al.\n"
317 " LibVEX is Copyright (C) 2004-2017, and GNU GPL'd, by OpenWorks LLP et al.\n"
318 "\n"
319 " Bug reports, feedback, admiration, abuse, etc, to: %s.\n"
320 "\n";
322 const HChar dyn_usage[] =
323 "Some command line settings are \"dynamic\", meaning they can be changed\n"
324 "while Valgrind is running, like this:\n"
325 " From the shell, using vgdb. Example:\n"
326 " $ vgdb \"v.clo --trace-children=yes --child-silent-after-fork=no\"\n"
327 " From a gdb attached to the valgrind gdbserver. Example:\n"
328 " (gdb) monitor v.clo --trace-children=yes --child-silent-after-fork=no\"\n"
329 " From your program, using a client request. Example:\n"
330 " #include <valgrind/valgrind.h>\n"
331 " VALGRIND_CLO_CHANGE(\"--trace-children=yes\");\n"
332 " VALGRIND_CLO_CHANGE(\"--child-silent-after-fork=no\");\n\n";
335 HChar default_alignment[30]; // large enough
336 HChar default_redzone_size[30]; // large enough
338 // Ensure the message goes to stdout
339 VG_(log_output_sink).fd = 1;
340 VG_(log_output_sink).type = VgLogTo_Fd;
342 if (VG_(needs).malloc_replacement) {
343 VG_(sprintf)(default_alignment, "%d", VG_MIN_MALLOC_SZB);
344 VG_(sprintf)(default_redzone_size, "%lu", VG_(tdict).tool_client_redzone_szB);
345 } else {
346 VG_(strcpy)(default_alignment, "not used by this tool");
347 VG_(strcpy)(default_redzone_size, "not used by this tool");
349 if (need_help > 1)
350 /* 'usage1' a type as described after each arg. */
351 VG_(printf)(usage1,
352 VG_(clo_vgdb_error) /* int */,
353 default_alignment /* char* */,
354 default_redzone_size /* char* */,
355 VG_(clo_vgdb_poll) /* int */,
356 VG_(vgdb_prefix_default)() /* char* */,
357 N_SECTORS_DEFAULT /* int */,
358 MAX_THREADS_DEFAULT /* int */
360 if (need_help > 1 && VG_(details).name) {
361 VG_(printf)(" user options for %s:\n", VG_(details).name);
362 if (VG_(needs).command_line_options)
363 VG_TDICT_CALL(tool_print_usage);
364 else
365 VG_(printf)(" (none)\n");
367 if (need_help == 1) {
368 VG_(printf)(dyn_usage);
369 VG_(list_dynamic_options) ();
370 VG_(printf)("valgrind: Use --help for more information.\n");
373 if (need_help > 2) {
374 VG_(printf)("%s", usage2);
376 if (VG_(details).name) {
377 VG_(printf)(" debugging options for %s:\n", VG_(details).name);
379 if (VG_(needs).command_line_options)
380 VG_TDICT_CALL(tool_print_debug_usage);
381 else
382 VG_(printf)(" (none)\n");
385 if (need_help > 1)
386 VG_(printf)(usage3, VG_(details).name, VG_(details).copyright_author,
387 VG_BUGS_TO);
388 VG_(exit)(0);
392 struct process_option_state {
393 /* Whether the user has asked for --version/--help. */
394 Int need_version;
395 Int need_help;
397 /* Whether the user has explicitly provided --sigill-diagnostics
398 or --show-error-list.
399 If not explicitly given depends on general verbosity setting. */
400 Bool sigill_diag_set;
401 Bool show_error_list_set;
403 /* Log to stderr by default, but usage message goes to stdout. XML
404 output is initially disabled. */
405 VgLogTo log_to; // Where is logging output to be sent?
406 VgLogTo xml_to; // Where is XML output to be sent?
407 Int tmp_log_fd;
408 Int tmp_xml_fd;
411 static void process_option (Clo_Mode mode,
412 HChar *arg, struct process_option_state *pos)
414 const HChar* tmp_str; // Used in a couple of places.
415 Int toolname_len = VG_(strlen)(VG_(clo_toolname));
416 HChar* colon = arg;
417 UInt ix = 0;
419 /* Constants for parsing PX control flags. */
420 const HChar* pxStrings[5]
421 = { "sp-at-mem-access", "unwindregs-at-mem-access",
422 "allregs-at-mem-access", "allregs-at-each-insn", NULL };
423 const VexRegisterUpdates pxVals[5]
424 = { VexRegUpdSpAtMemAccess, VexRegUpdUnwindregsAtMemAccess,
425 VexRegUpdAllregsAtMemAccess, VexRegUpdAllregsAtEachInsn, 0/*inval*/ };
427 VG_(set_Clo_Mode) (mode);
429 // Look for a colon in the option name.
430 while (*colon && *colon != ':' && *colon != '=')
431 colon++;
433 // Does it have the form "--toolname:foo"? We have to do it at the start
434 // in case someone has combined a prefix with a core-specific option,
435 // eg. "--memcheck:verbose".
436 if (*colon == ':') {
437 if (VG_STREQN(2, arg, "--") &&
438 VG_STREQN(toolname_len, arg+2, VG_(clo_toolname)) &&
439 VG_STREQN(1, arg+2+toolname_len, ":")) {
440 // Prefix matches, convert "--toolname:foo" to "--foo".
441 // Two things to note:
442 // - We cannot modify the option in-place. If we did, and then
443 // a child was spawned with --trace-children=yes, the
444 // now-non-prefixed option would be passed and could screw up
445 // the child.
446 // - We create copies, and never free them. Why? Non-prefixed
447 // options hang around forever, so tools need not make copies
448 // of strings within them. We need to have the same behaviour
449 // for prefixed options. The pointer to the copy will be lost
450 // once we leave this function (although a tool may keep a
451 // pointer into it), but the space wasted is insignificant.
452 // (In bug #142197, the copies were being freed, which caused
453 // problems for tools that reasonably assumed that arguments
454 // wouldn't disappear on them.)
455 if (0)
456 VG_(printf)("tool-specific arg: %s\n", arg);
457 arg = VG_(strdup)("main.mpclo.1", arg + toolname_len + 1);
458 arg[0] = '-';
459 arg[1] = '-';
461 } else {
462 // prefix doesn't match, declare it as recognised and skip this arg
463 VG_(set_Clo_Recognised) ();
464 return;
468 if VG_XACT_CLOM(cloE, arg, "--version", pos->need_version, 1) {}
469 else if (VG_STREQ_CLOM(cloED, arg, "-v") ||
470 VG_STREQ_CLOM(cloED, arg, "--verbose"))
471 VG_(clo_verbosity)++;
472 else if (VG_STREQ_CLOM(cloED, arg, "-q") ||
473 VG_STREQ_CLOM(cloED, arg, "--quiet"))
474 VG_(clo_verbosity)--;
475 else if VG_XACT_CLOM(cloE, arg, "--help-dyn-options", pos->need_help, 1) {}
476 else if VG_XACT_CLOM(cloE, arg, "-h", pos->need_help, 2) {}
477 else if VG_XACT_CLOM(cloE, arg, "--help", pos->need_help, 2) {}
478 else if VG_XACT_CLOM(cloE, arg, "--help-debug", pos->need_help, 3) {}
480 // The tool has already been determined, but we need to know the name
481 // here.
482 else if VG_STR_CLOM(cloE, arg, "--tool", VG_(clo_toolname)) {}
484 // Set up VG_(clo_max_stackframe) and VG_(clo_main_stacksize).
485 // These are needed by VG_(ii_create_image), which happens
486 // before main_process_cmd_line_options().
487 else if VG_INT_CLOM(cloE, arg, "--max-stackframe", VG_(clo_max_stackframe)) {}
488 else if VG_INT_CLOM(cloE, arg, "--main-stacksize", VG_(clo_main_stacksize)) {}
490 // Set up VG_(clo_max_threads); needed for VG_(tl_pre_clo_init)
491 else if VG_INT_CLOM(cloE, arg, "--max-threads", VG_(clo_max_threads)) {}
493 // Set up VG_(clo_sim_hints). This is needed a.o. for an inner
494 // running in an outer, to have "no-inner-prefix" enabled
495 // as early as possible.
496 else if VG_USETX_CLOM (cloE, arg, "--sim-hints",
497 "lax-ioctls,lax-doors,fuse-compatible,"
498 "enable-outer,no-inner-prefix,"
499 "no-nptl-pthread-stackcache,fallback-llsc",
500 VG_(clo_sim_hints)) {}
502 else if VG_STREQN_CLOM(0, 20, arg, "--command-line-only=") {} // m_commandline.c
503 else if VG_STREQ(arg, "--") {}
504 else if VG_STREQ_CLOM(cloD, arg, "-d") // pre-early + Dynamic
505 VG_(debugLog_startup) (VG_(debugLog_getLevel)() + 1,
506 "dynamic option change");
507 else if VG_STREQN_CLOM(0, 15, arg, "--profile-heap=") {} // pre-early
508 else if VG_STREQN_CLOM(0, 20, arg, "--core-redzone-size=") {} // pre-early
509 else if VG_STREQN_CLOM(0, 15, arg, "--redzone-size=") {} // pre-early
510 else if VG_STREQN_CLOM(0, 17, arg, "--aspace-minaddr=") {} // pre-early
512 else if VG_BINT_CLOM(cloE, arg, "--valgrind-stacksize",
513 VG_(clo_valgrind_stacksize),
514 2*VKI_PAGE_SIZE, 10*VG_DEFAULT_STACK_ACTIVE_SZB)
515 VG_(clo_valgrind_stacksize) = VG_PGROUNDUP(VG_(clo_valgrind_stacksize));
517 /* Obsolete options. Report an error and exit */
518 else if VG_STREQN(34, arg, "--vex-iropt-precise-memory-exns=no") {
519 VG_(fmsg_bad_option)
520 (arg,
521 "--vex-iropt-precise-memory-exns is obsolete\n"
522 "Use --vex-iropt-register-updates=unwindregs-at-mem-access instead\n");
524 else if VG_STREQN(35, arg, "--vex-iropt-precise-memory-exns=yes") {
525 VG_(fmsg_bad_option)
526 (arg,
527 "--vex-iropt-precise-memory-exns is obsolete\n"
528 "Use --vex-iropt-register-updates=allregs-at-mem-access instead\n"
529 " (or --vex-iropt-register-updates=allregs-at-each-insn)\n");
532 /* These options are new, not yet handled by
533 early_process_cmd_line_options. */
534 else if VG_BOOL_CLO(arg, "--sigill-diagnostics", VG_(clo_sigill_diag))
535 pos->sigill_diag_set = True;
537 else if VG_BOOL_CLOM(cloPD, arg, "--stats", VG_(clo_stats)) {}
538 else if VG_BOOL_CLO(arg, "--xml", VG_(clo_xml))
539 VG_(debugLog_setXml)(VG_(clo_xml));
541 else if VG_XACT_CLOM(cloPD, arg, "--vgdb=no", VG_(clo_vgdb), Vg_VgdbNo) {}
542 else if VG_XACT_CLOM(cloPD, arg, "--vgdb=yes", VG_(clo_vgdb), Vg_VgdbYes) {}
543 else if VG_XACT_CLOM(cloPD, arg, "--vgdb=full", VG_(clo_vgdb), Vg_VgdbFull) {
544 /* automatically updates register values at each insn
545 with --vgdb=full */
546 VG_(clo_vex_control).iropt_register_updates_default
547 = VG_(clo_px_file_backed)
548 = VexRegUpdAllregsAtEachInsn;
550 else if VG_INT_CLOM (cloPD, arg, "--vgdb-poll", VG_(clo_vgdb_poll)) {}
551 else if VG_INT_CLOM (cloPD, arg, "--vgdb-error", VG_(clo_vgdb_error)) {}
552 else if VG_USET_CLOM (cloPD, arg, "--vgdb-stop-at",
553 "startup,exit,valgrindabexit",
554 VG_(clo_vgdb_stop_at)) {}
555 else if VG_STR_CLO (arg, "--vgdb-prefix", VG_(clo_vgdb_prefix)) {
556 VG_(arg_vgdb_prefix) = arg;
558 else if VG_BOOL_CLO(arg, "--vgdb-shadow-registers",
559 VG_(clo_vgdb_shadow_registers)) {}
560 else if VG_BOOL_CLO(arg, "--demangle", VG_(clo_demangle)) {}
561 else if VG_STR_CLO (arg, "--soname-synonyms",VG_(clo_soname_synonyms)) {}
562 else if VG_BOOL_CLO(arg, "--error-limit", VG_(clo_error_limit)) {}
563 else if VG_BOOL_CLO(arg, "--exit-on-first-error", VG_(clo_exit_on_first_error)) {}
564 else if VG_INT_CLO (arg, "--error-exitcode", VG_(clo_error_exitcode)) {}
565 else if VG_STR_CLOM (cloPD, arg, "--error-markers", tmp_str) {
566 Int m;
567 const HChar *startpos = tmp_str;
568 const HChar *nextpos;
569 for (m = 0;
570 VG_(Clo_Mode)() != cloE
571 && m < sizeof(VG_(clo_error_markers))
572 /sizeof(VG_(clo_error_markers)[0]);
573 m++) {
574 /* Release previous value if clo given multiple times. */
575 VG_(free)(VG_(clo_error_markers)[m]);
576 VG_(clo_error_markers)[m] = NULL;
578 nextpos = VG_(strchr)(startpos, ',');
579 if (!nextpos)
580 nextpos = startpos + VG_(strlen)(startpos);
581 if (startpos != nextpos) {
582 VG_(clo_error_markers)[m]
583 = VG_(malloc)("main.mpclo.2", nextpos - startpos + 1);
584 VG_(memcpy)(VG_(clo_error_markers)[m], startpos,
585 nextpos - startpos);
586 VG_(clo_error_markers)[m][nextpos - startpos] = '\0';
588 startpos = *nextpos ? nextpos + 1 : nextpos;
591 else if VG_BOOL_CLOM(cloPD, arg, "--show-error-list", VG_(clo_show_error_list)) {
592 pos->show_error_list_set = True; }
593 else if (VG_STREQ_CLOM(cloPD, arg, "-s")) {
594 VG_(clo_show_error_list) = True;
595 pos->show_error_list_set = True;
597 else if VG_BOOL_CLO(arg, "--show-emwarns", VG_(clo_show_emwarns)) {}
599 else if VG_BOOL_CLO(arg, "--run-libc-freeres", VG_(clo_run_libc_freeres)) {}
600 else if VG_BOOL_CLO(arg, "--run-cxx-freeres", VG_(clo_run_cxx_freeres)) {}
601 else if VG_BOOL_CLOM(cloPD, arg, "--show-below-main", VG_(clo_show_below_main)) {}
602 else if VG_BOOL_CLO(arg, "--keep-debuginfo", VG_(clo_keep_debuginfo)) {}
603 else if VG_BOOL_CLOM(cloPD, arg, "--time-stamp", VG_(clo_time_stamp)) {}
604 else if VG_STR_CLO(arg, "--track-fds", tmp_str) {
605 if (VG_(strcmp)(tmp_str, "yes") == 0)
606 VG_(clo_track_fds) = 1;
607 else if (VG_(strcmp)(tmp_str, "all") == 0)
608 VG_(clo_track_fds) = 2;
609 else if (VG_(strcmp)(tmp_str, "no") == 0)
610 VG_(clo_track_fds) = 0;
611 else
612 VG_(fmsg_bad_option)(arg,
613 "Bad argument, should be 'yes', 'all' or 'no'\n");
615 else if VG_BOOL_CLOM(cloPD, arg, "--trace-children", VG_(clo_trace_children)) {}
616 else if VG_BOOL_CLOM(cloPD, arg, "--child-silent-after-fork",
617 VG_(clo_child_silent_after_fork)) {}
618 else if VG_STR_CLO(arg, "--fair-sched", tmp_str) {
619 if (VG_(Clo_Mode)() != cloP)
621 else if (VG_(strcmp)(tmp_str, "yes") == 0)
622 VG_(clo_fair_sched) = enable_fair_sched;
623 else if (VG_(strcmp)(tmp_str, "try") == 0)
624 VG_(clo_fair_sched) = try_fair_sched;
625 else if (VG_(strcmp)(tmp_str, "no") == 0)
626 VG_(clo_fair_sched) = disable_fair_sched;
627 else
628 VG_(fmsg_bad_option)(arg,
629 "Bad argument, should be 'yes', 'try' or 'no'\n");
631 else if VG_BOOL_CLOM(cloPD, arg, "--trace-sched", VG_(clo_trace_sched)) {}
632 else if VG_BOOL_CLOM(cloPD, arg, "--trace-signals", VG_(clo_trace_signals)) {}
633 else if VG_BOOL_CLOM(cloPD, arg, "--trace-symtab", VG_(clo_trace_symtab)) {}
634 else if VG_STR_CLO (arg, "--trace-symtab-patt", VG_(clo_trace_symtab_patt)) {}
635 else if VG_BOOL_CLOM(cloPD, arg, "--trace-cfi", VG_(clo_trace_cfi)) {}
636 else if VG_XACT_CLOM(cloPD, arg, "--debug-dump=syms", VG_(clo_debug_dump_syms),
637 True) {}
638 else if VG_XACT_CLOM(cloPD, arg, "--debug-dump=line", VG_(clo_debug_dump_line),
639 True) {}
640 else if VG_XACT_CLOM(cloPD, arg, "--debug-dump=frames",
641 VG_(clo_debug_dump_frames), True) {}
642 else if VG_BOOL_CLOM(cloPD, arg, "--trace-redir", VG_(clo_trace_redir)) {}
644 else if VG_BOOL_CLOM(cloPD, arg, "--trace-syscalls", VG_(clo_trace_syscalls)) {}
645 else if VG_BOOL_CLOM(cloE, arg, "--wait-for-gdb", VG_(clo_wait_for_gdb)) {
646 //--------------------------------------------------------------
647 // Allow GDB attach
648 // p: logging
649 //--------------------------------------------------------------
650 /* Hook to delay things long enough so we can get the pid and
651 attach GDB in another shell. */
652 if (VG_(clo_wait_for_gdb)) {
653 const int ms = 8000; // milliseconds
654 VG_(debugLog)(1, "main", "Wait for GDB during %d ms\n", ms);
655 VG_(printf)("pid=%d, entering delay %d ms loop\n", VG_(getpid)(), ms);
656 VG_(poll)(NULL, 0, ms);
660 else if VG_BOOL_CLOM(cloPD, arg, "--sym-offsets", VG_(clo_sym_offsets)) {}
661 else if VG_BINT_CLOM(cloPD, arg, "--progress-interval",
662 VG_(clo_progress_interval), 0, 3600) {}
663 else if VG_BOOL_CLO(arg, "--read-inline-info", VG_(clo_read_inline_info)) {}
664 else if VG_BOOL_CLO(arg, "--read-var-info", VG_(clo_read_var_info)) {}
666 else if VG_INT_CLO (arg, "--dump-error", VG_(clo_dump_error)) {}
667 else if VG_INT_CLO (arg, "--input-fd", VG_(clo_input_fd)) {}
668 else if VG_INT_CLO (arg, "--sanity-level", VG_(clo_sanity_level)) {}
669 else if VG_BINT_CLO(arg, "--num-callers", VG_(clo_backtrace_size), 1,
670 VG_DEEPEST_BACKTRACE) {}
671 else if VG_BINT_CLO(arg, "--num-transtab-sectors",
672 VG_(clo_num_transtab_sectors),
673 MIN_N_SECTORS, MAX_N_SECTORS) {}
674 else if VG_BINT_CLO(arg, "--avg-transtab-entry-size",
675 VG_(clo_avg_transtab_entry_size),
676 50, 5000) {}
677 else if VG_BINT_CLOM(cloPD, arg, "--merge-recursive-frames",
678 VG_(clo_merge_recursive_frames), 0,
679 VG_DEEPEST_BACKTRACE) {}
681 else if VG_XACT_CLO(arg, "--smc-check=none",
682 VG_(clo_smc_check), Vg_SmcNone) {}
683 else if VG_XACT_CLO(arg, "--smc-check=stack",
684 VG_(clo_smc_check), Vg_SmcStack) {}
685 else if VG_XACT_CLO(arg, "--smc-check=all",
686 VG_(clo_smc_check), Vg_SmcAll) {}
687 else if VG_XACT_CLO(arg, "--smc-check=all-non-file",
688 VG_(clo_smc_check), Vg_SmcAllNonFile) {}
690 else if VG_USETX_CLO (arg, "--kernel-variant",
691 "bproc,"
692 "android-no-hw-tls,"
693 "android-gpu-sgx5xx,"
694 "android-gpu-adreno3xx",
695 VG_(clo_kernel_variant)) {}
697 else if VG_BOOL_CLO(arg, "--dsymutil", VG_(clo_dsymutil)) {}
699 else if VG_STR_CLO (arg, "--trace-children-skip",
700 VG_(clo_trace_children_skip)) {}
701 else if VG_STR_CLO (arg, "--trace-children-skip-by-arg",
702 VG_(clo_trace_children_skip_by_arg)) {}
704 else if VG_BINT_CLOM(cloPD, arg, "--vex-iropt-verbosity",
705 VG_(clo_vex_control).iropt_verbosity, 0, 10) {}
706 else if VG_BINT_CLO(arg, "--vex-iropt-level",
707 VG_(clo_vex_control).iropt_level, 0, 2) {}
708 else if VG_BINT_CLO(arg, "--vex-regalloc-version",
709 VG_(clo_vex_control).regalloc_version, 2, 3) {}
711 else if (VG_STRINDEX_CLO(arg, "--vex-iropt-register-updates",
712 pxStrings, ix)
713 || VG_STRINDEX_CLO(arg, "--px-default", pxStrings, ix))
714 // NB: --px-default is an alias for the hard-to-remember
715 // --vex-iropt-register-updates, hence the same logic.
717 vg_assert(ix < 4);
718 vg_assert(pxVals[ix] >= VexRegUpdSpAtMemAccess);
719 vg_assert(pxVals[ix] <= VexRegUpdAllregsAtEachInsn);
720 VG_(clo_vex_control).iropt_register_updates_default = pxVals[ix];
723 else if VG_STRINDEX_CLO(arg, "--px-file-backed", pxStrings, ix) {
724 // Whereas --px-file-backed isn't
725 // the same flag as --vex-iropt-register-updates.
726 vg_assert(ix < 4);
727 vg_assert(pxVals[ix] >= VexRegUpdSpAtMemAccess);
728 vg_assert(pxVals[ix] <= VexRegUpdAllregsAtEachInsn);
729 VG_(clo_px_file_backed) = pxVals[ix];
732 else if VG_BINT_CLO(arg, "--vex-iropt-unroll-thresh",
733 VG_(clo_vex_control).iropt_unroll_thresh, 0, 400) {}
734 else if VG_BINT_CLO(arg, "--vex-guest-max-insns",
735 VG_(clo_vex_control).guest_max_insns, 1, 100) {}
736 else if VG_BOOL_CLO(arg, "--vex-guest-chase",
737 VG_(clo_vex_control).guest_chase) {}
739 else if VG_INT_CLO(arg, "--log-fd", pos->tmp_log_fd) {
740 pos->log_to = VgLogTo_Fd;
741 VG_(clo_log_fname_unexpanded) = NULL;
743 else if VG_INT_CLO(arg, "--xml-fd", pos->tmp_xml_fd) {
744 pos->xml_to = VgLogTo_Fd;
745 VG_(clo_xml_fname_unexpanded) = NULL;
748 else if VG_STR_CLO(arg, "--log-file", VG_(clo_log_fname_unexpanded)) {
749 pos->log_to = VgLogTo_File;
751 else if VG_STR_CLO(arg, "--xml-file", VG_(clo_xml_fname_unexpanded)) {
752 pos->xml_to = VgLogTo_File;
755 else if VG_STR_CLO(arg, "--log-socket", VG_(clo_log_fname_unexpanded)) {
756 pos->log_to = VgLogTo_Socket;
758 else if VG_STR_CLO(arg, "--xml-socket", VG_(clo_xml_fname_unexpanded)) {
759 pos->xml_to = VgLogTo_Socket;
762 else if VG_STR_CLO(arg, "--debuginfo-server",
763 VG_(clo_debuginfo_server)) {}
765 else if VG_BOOL_CLO(arg, "--allow-mismatched-debuginfo",
766 VG_(clo_allow_mismatched_debuginfo)) {}
768 else if VG_STR_CLO(arg, "--xml-user-comment",
769 VG_(clo_xml_user_comment)) {}
771 else if VG_BOOL_CLO(arg, "--default-suppressions",
772 VG_(clo_default_supp)) {}
774 else if VG_STR_CLOM(cloPD, arg, "--suppressions", tmp_str) {
775 VG_(add_suppression_file)(tmp_str);
778 else if VG_STR_CLO (arg, "--fullpath-after", tmp_str) {
779 VG_(addToXA)(VG_(clo_fullpath_after), &tmp_str);
782 else if VG_STR_CLO (arg, "--extra-debuginfo-path",
783 VG_(clo_extra_debuginfo_path)) {}
785 else if VG_STR_CLO(arg, "--require-text-symbol", tmp_str) {
786 /* String needs to be of the form C?*C?*, where C is any
787 character, but is the same both times. Having it in this
788 form facilitates finding the boundary between the sopatt
789 and the fnpatt just by looking for the second occurrence
790 of C, without hardwiring any assumption about what C
791 is. */
792 HChar patt[7];
793 Bool ok = True;
794 ok = tmp_str && VG_(strlen)(tmp_str) > 0;
795 if (ok) {
796 patt[0] = patt[3] = tmp_str[0];
797 patt[1] = patt[4] = '?';
798 patt[2] = patt[5] = '*';
799 patt[6] = 0;
800 ok = VG_(string_match)(patt, tmp_str);
802 if (!ok) {
803 VG_(fmsg_bad_option)(arg,
804 "Invalid --require-text-symbol= specification.\n");
806 VG_(addToXA)(VG_(clo_req_tsyms), &tmp_str);
809 /* "stuvwxyz" --> stuvwxyz (binary) */
810 else if VG_STR_CLOM(cloPD, arg, "--trace-flags", tmp_str) {
811 Int j;
812 if (8 != VG_(strlen)(tmp_str)) {
813 VG_(fmsg_bad_option)(arg,
814 "--trace-flags argument must have 8 digits\n");
816 for (j = 0; j < 8; j++) {
817 if ('0' == tmp_str[j]) { /* do nothing */ }
818 else if ('1' == tmp_str[j]) VG_(clo_trace_flags) |= (1 << (7-j));
819 else {
820 VG_(fmsg_bad_option)(arg,
821 "--trace-flags argument can only contain 0s and 1s\n");
826 else if VG_INT_CLOM (cloPD, arg, "--trace-notbelow", VG_(clo_trace_notbelow)) {}
828 else if VG_INT_CLOM (cloPD, arg, "--trace-notabove", VG_(clo_trace_notabove)) {}
830 /* "stuvwxyz" --> stuvwxyz (binary) */
831 else if VG_STR_CLOM(cloPD, arg, "--profile-flags", tmp_str) {
832 Int j;
833 if (8 != VG_(strlen)(tmp_str)) {
834 VG_(fmsg_bad_option)(arg,
835 "--profile-flags argument must have 8 digits\n");
837 for (j = 0; j < 8; j++) {
838 if ('0' == tmp_str[j]) { /* do nothing */ }
839 else if ('1' == tmp_str[j]) VG_(clo_profyle_flags) |= (1 << (7-j));
840 else {
841 VG_(fmsg_bad_option)(arg,
842 "--profile-flags argument can only contain 0s and 1s\n");
845 VG_(clo_profyle_sbs) = True;
848 else if VG_INT_CLO (arg, "--profile-interval",
849 VG_(clo_profyle_interval)) {}
851 else if VG_XACT_CLOM(cloPD, arg, "--gen-suppressions=no",
852 VG_(clo_gen_suppressions), 0) {}
853 else if VG_XACT_CLOM(cloPD, arg, "--gen-suppressions=yes",
854 VG_(clo_gen_suppressions), 1) {}
855 else if VG_XACT_CLOM(cloPD, arg, "--gen-suppressions=all",
856 VG_(clo_gen_suppressions), 2) {}
858 else if VG_BINT_CLO(arg, "--unw-stack-scan-thresh",
859 VG_(clo_unw_stack_scan_thresh), 0, 100) {}
860 else if VG_BINT_CLO(arg, "--unw-stack-scan-frames",
861 VG_(clo_unw_stack_scan_frames), 0, 32) {}
863 else if VG_XACT_CLO(arg, "--resync-filter=no",
864 VG_(clo_resync_filter), 0) {}
865 else if VG_XACT_CLO(arg, "--resync-filter=yes",
866 VG_(clo_resync_filter), 1) {}
867 else if VG_XACT_CLO(arg, "--resync-filter=verbose",
868 VG_(clo_resync_filter), 2) {}
870 else if ( VG_(Clo_Mode)() != cloE // tool does not have Early options
871 && !VG_(Clo_Recognised) ()
872 && (! VG_(needs).command_line_options
873 || ! VG_TDICT_CALL(tool_process_cmd_line_option, arg) )) {
874 if (VG_(Clo_Mode)() == cloH)
876 else if (VG_(Clo_Mode)() == cloP && !VG_(Clo_Recognised) ())
877 VG_(fmsg_unknown_option)(arg);
878 else if (VG_(Clo_Mode)() == cloD && !VG_(Clo_Recognised) ())
879 VG_(umsg)("Ignoring dynamic change to unrecognised option %s\n", arg);
883 void VG_(process_dynamic_option) (Clo_Mode mode, HChar *value)
885 process_option (mode, value, NULL);
886 // This is not supposed to change values in process_option_state,
887 // so we can give a NULL.
890 /* Peer at previously set up VG_(args_for_valgrind) and do some
891 minimal command line processing that must happen early on:
893 - show the version string, if requested (-v)
894 - extract any request for help (-h --help, --help-dyn-options, --help-debug)
895 - set VG_(toolname) (--tool=)
896 - set VG_(clo_max_stackframe) (--max-stackframe=)
897 - set VG_(clo_main_stacksize) (--main-stacksize=)
898 - set VG_(clo_sim_hints) (--sim-hints=)
899 - set VG_(clo_max_threads) (--max-threads)
901 That's all it does. The main command line processing is done below
902 by main_process_cmd_line_options. Note that
903 main_process_cmd_line_options has to handle but ignore the ones we
904 have handled here.
906 static void early_process_cmd_line_options ( /*OUT*/Int* need_help )
908 UInt i;
909 HChar* str;
910 struct process_option_state pos
911 = {0, 0, False, False, VgLogTo_Fd, VgLogTo_Fd, 2, -1};
913 vg_assert( VG_(args_for_valgrind) );
915 /* parse the options we have (only the options we care about now) */
916 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
918 str = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
919 vg_assert(str);
920 process_option (cloE, str, &pos);
923 if (pos.need_version) {
924 // Nb: the version string goes to stdout.
925 VG_(log_output_sink).fd = 1;
926 VG_(log_output_sink).type = VgLogTo_Fd;
927 if (VG_(clo_verbosity) <= 1)
928 VG_(printf)("valgrind-" VERSION "\n");
929 else
930 VG_(printf)("valgrind-" VERSION "-" VGGIT "\n");
931 VG_(exit)(0);
934 *need_help = pos.need_help;
936 /* For convenience */
937 VG_N_THREADS = VG_(clo_max_threads);
939 # if defined(VGO_solaris) || defined(VGO_darwin)
940 /* Sim hint no-nptl-pthread-stackcache should be ignored. */
941 VG_(clo_sim_hints) &= ~SimHint2S(SimHint_no_nptl_pthread_stackcache);
942 # endif
945 /* The main processing for command line options. See comments above
946 on early_process_cmd_line_options. */
947 static
948 void main_process_cmd_line_options( void )
950 Int i;
951 struct process_option_state pos
952 = {0, 0, False, False, VgLogTo_Fd, VgLogTo_Fd, 2, -1};
954 /* Check for sane path in ./configure --prefix=... */
955 if (VG_LIBDIR[0] != '/')
956 VG_(err_config_error)("Please use absolute paths in "
957 "./configure --prefix=... or --libdir=...\n");
959 vg_assert( VG_(args_for_valgrind) );
961 VG_(clo_suppressions) = VG_(newXA)(VG_(malloc), "main.mpclo.4",
962 VG_(free), sizeof(HChar *));
963 VG_(clo_fullpath_after) = VG_(newXA)(VG_(malloc), "main.mpclo.5",
964 VG_(free), sizeof(HChar *));
965 VG_(clo_req_tsyms) = VG_(newXA)(VG_(malloc), "main.mpclo.6",
966 VG_(free), sizeof(HChar *));
968 /* BEGIN command-line processing loop */
970 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
971 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
972 process_option (cloP, arg, &pos);
975 /* END command-line processing loop. From now on, only dynamically
976 changeable options will have an effect. */
977 VG_(set_Clo_Mode)(cloD);
979 /* Notify about deprecated features here. */
981 /* Determine the path prefix for vgdb */
982 if (VG_(clo_vgdb_prefix) == NULL)
983 VG_(clo_vgdb_prefix) = VG_(vgdb_prefix_default)();
985 /* Check various option values */
987 if (VG_(clo_verbosity) < 0)
988 VG_(clo_verbosity) = 0;
990 if (!pos.sigill_diag_set)
991 VG_(clo_sigill_diag) = (VG_(clo_verbosity) > 0);
993 if (!pos.show_error_list_set) {
994 if (VG_(clo_xml))
995 VG_(clo_show_error_list) = VG_(clo_verbosity) >= 1;
996 else
997 VG_(clo_show_error_list) = VG_(clo_verbosity) >= 2;
1000 if (VG_(clo_trace_notbelow) == -1) {
1001 if (VG_(clo_trace_notabove) == -1) {
1002 /* [] */
1003 VG_(clo_trace_notbelow) = 2147483647;
1004 VG_(clo_trace_notabove) = 0;
1005 } else {
1006 /* [0 .. notabove] */
1007 VG_(clo_trace_notbelow) = 0;
1009 } else {
1010 if (VG_(clo_trace_notabove) == -1) {
1011 /* [notbelow .. ] */
1012 VG_(clo_trace_notabove) = 2147483647;
1013 } else {
1014 /* [notbelow .. notabove] */
1018 if (VG_(clo_gen_suppressions) > 0 &&
1019 !VG_(needs).core_errors && !VG_(needs).tool_errors) {
1020 VG_(fmsg_bad_option)("--gen-suppressions=yes",
1021 "Can't use --gen-suppressions= with %s\n"
1022 "because it doesn't generate errors.\n", VG_(details).name);
1024 if ((VG_(clo_exit_on_first_error)) &&
1025 (VG_(clo_error_exitcode)==0)) {
1026 VG_(fmsg_bad_option)("--exit-on-first-error=yes",
1027 "You must define a non nul exit error code, with --error-exitcode=...\n");
1030 # if !defined(VGO_darwin)
1031 if (VG_(clo_resync_filter) != 0) {
1032 VG_(fmsg_bad_option)("--resync-filter=yes or =verbose",
1033 "--resync-filter= is only available on MacOS X.\n");
1034 /*NOTREACHED*/
1036 # endif
1038 /* If XML output is requested, check that the tool actually
1039 supports it. */
1040 if (VG_(clo_xml) && !VG_(needs).xml_output) {
1041 VG_(clo_xml) = False;
1042 VG_(fmsg_bad_option)("--xml=yes",
1043 "%s does not support XML output.\n", VG_(details).name);
1044 /*NOTREACHED*/
1047 vg_assert( VG_(clo_gen_suppressions) >= 0 );
1048 vg_assert( VG_(clo_gen_suppressions) <= 2 );
1050 /* If we've been asked to emit XML, mash around various other
1051 options so as to constrain the output somewhat, and to remove
1052 any need for user input during the run.
1054 if (VG_(clo_xml)) {
1056 /* We can't allow --gen-suppressions=yes, since that requires us
1057 to print the error and then ask the user if she wants a
1058 suppression for it, but in XML mode we won't print it until
1059 we know whether we also need to print a suppression. Hence a
1060 circular dependency. So disallow this.
1061 (--gen-suppressions=all is still OK since we don't need any
1062 user interaction in this case.) */
1063 if (VG_(clo_gen_suppressions) == 1) {
1064 VG_(fmsg_bad_option)(
1065 "--xml=yes together with --gen-suppressions=yes",
1066 "When --xml=yes is specified, --gen-suppressions=no\n"
1067 "or --gen-suppressions=all is allowed, but not "
1068 "--gen-suppressions=yes.\n");
1071 /* Disallow dump_error in XML mode; sounds like a recipe for
1072 chaos. No big deal; dump_error is a flag for debugging V
1073 itself. */
1074 if (VG_(clo_dump_error) > 0) {
1075 VG_(fmsg_bad_option)("--xml=yes",
1076 "Cannot be used together with --dump-error");
1079 /* Disable error limits (this might be a bad idea!) */
1080 VG_(clo_error_limit) = False;
1081 /* Disable emulation warnings */
1083 /* Also, we want to set options for the leak checker, but that
1084 will have to be done in Memcheck's flag-handling code, not
1085 here. */
1088 /* All non-logging-related options have been checked. If the logging
1089 option specified is ok, we can switch to it, as we know we won't
1090 have to generate any other command-line-related error messages.
1091 (So far we should be still attached to stderr, so we can show on
1092 the terminal any problems to do with processing command line
1093 opts.) */
1094 VG_(init_log_xml_sinks)(pos.log_to, pos.xml_to,
1095 pos.tmp_log_fd, pos.tmp_xml_fd);
1097 /* Register child at-fork handler which will take care of handling
1098 --child-silent-after-fork clo and also reopening output sinks for forked
1099 children, if requested via --log|xml-file= options. */
1100 VG_(atfork)(NULL, NULL, VG_(logging_atfork_child));
1102 // Suppressions related stuff
1104 if (VG_(clo_default_supp) &&
1105 (VG_(needs).core_errors || VG_(needs).tool_errors)) {
1106 /* If loading default is enabled, add it to the supp list. */
1107 static const HChar default_supp[] = "default.supp";
1108 Int len = VG_(strlen)(VG_(libdir)) + 1 + sizeof(default_supp);
1109 HChar *buf = VG_(malloc)("main.mpclo.3", len);
1110 VG_(sprintf)(buf, "%s/%s", VG_(libdir), default_supp);
1111 VG_(add_suppression_file)(buf);
1112 VG_(free)(buf);
1117 /*====================================================================*/
1118 /*=== File descriptor setup ===*/
1119 /*====================================================================*/
1121 /* Number of file descriptors that Valgrind tries to reserve for
1122 its own use - just a small constant. */
1123 #define N_RESERVED_FDS (12)
1125 static void setup_file_descriptors(void)
1127 struct vki_rlimit rl;
1128 Bool show = False;
1130 /* Get the current file descriptor limits. */
1131 if (VG_(getrlimit)(VKI_RLIMIT_NOFILE, &rl) < 0) {
1132 rl.rlim_cur = 1024;
1133 rl.rlim_max = 1024;
1136 # if defined(VGO_darwin)
1137 /* Darwin lies. It reports file max as RLIM_INFINITY but
1138 silently disallows anything bigger than 10240. */
1139 if (rl.rlim_cur >= 10240 && rl.rlim_max == 0x7fffffffffffffffULL) {
1140 rl.rlim_max = 10240;
1142 # endif
1144 if (show)
1145 VG_(printf)("fd limits: host, before: cur %llu max %llu\n",
1146 (ULong)rl.rlim_cur, (ULong)rl.rlim_max);
1148 /* Work out where to move the soft limit to. */
1149 if (rl.rlim_cur + N_RESERVED_FDS <= rl.rlim_max) {
1150 rl.rlim_cur = rl.rlim_cur + N_RESERVED_FDS;
1151 } else {
1152 rl.rlim_cur = rl.rlim_max;
1155 /* Reserve some file descriptors for our use. */
1156 VG_(fd_soft_limit) = rl.rlim_cur - N_RESERVED_FDS;
1157 VG_(fd_hard_limit) = rl.rlim_cur - N_RESERVED_FDS;
1159 /* Update the soft limit. */
1160 VG_(setrlimit)(VKI_RLIMIT_NOFILE, &rl);
1162 if (show) {
1163 VG_(printf)("fd limits: host, after: cur %lu max %lu\n",
1164 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
1165 VG_(printf)("fd limits: guest : cur %d max %d\n",
1166 VG_(fd_soft_limit), VG_(fd_hard_limit));
1169 if (VG_(cl_exec_fd) != -1)
1170 VG_(cl_exec_fd) = VG_(safe_fd)( VG_(cl_exec_fd) );
1174 /*====================================================================*/
1175 /*=== main() ===*/
1176 /*====================================================================*/
1178 /* When main() is entered, we should be on the following stack, not
1179 the one the kernel gave us. We will run on this stack until
1180 simulation of the root thread is started, at which point a transfer
1181 is made to a dynamically allocated stack. This is for the sake of
1182 uniform overflow detection for all Valgrind threads. This is
1183 marked global even though it isn't, because assembly code below
1184 needs to reference the name. */
1186 /*static*/ struct {
1187 HChar bytes [VG_STACK_GUARD_SZB + VG_DEFAULT_STACK_ACTIVE_SZB + VG_STACK_GUARD_SZB];
1188 } VG_(interim_stack);
1190 /* These are the structures used to hold info for creating the initial
1191 client image.
1193 'iicii' mostly holds important register state present at system
1194 startup (_start_valgrind). valgrind_main() then fills in the rest
1195 of it and passes it to VG_(ii_create_image)(). That produces
1196 'iifii', which is later handed to VG_(ii_finalise_image). */
1198 /* In all OS-instantiations, the_iicii has a field .sp_at_startup.
1199 This should get some address inside the stack on which we gained
1200 control (eg, it could be the SP at startup). It doesn't matter
1201 exactly where in the stack it is. This value is passed to the
1202 address space manager at startup. On Linux, aspacem then uses it
1203 to identify the initial stack segment and hence the upper end of
1204 the usable address space. */
1206 static IICreateImageInfo the_iicii;
1207 static IIFinaliseImageInfo the_iifii;
1210 /* A simple pair structure, used for conveying debuginfo handles to
1211 calls to VG_TRACK(new_mem_startup, ...). */
1212 typedef struct { Addr a; ULong ull; } Addr_n_ULong;
1215 /* --- Forwards decls to do with shutdown --- */
1217 static void final_tidyup(ThreadId tid);
1219 /* Do everything which needs doing when the last thread exits */
1220 static
1221 void shutdown_actions_NORETURN( ThreadId tid,
1222 VgSchedReturnCode tids_schedretcode );
1224 /* --- end of Forwards decls to do with shutdown --- */
1227 /* By the time we get to valgrind_main, the_iicii should already have
1228 been filled in with any important details as required by whatever
1229 OS we have been built for.
1231 static
1232 Int valgrind_main ( Int argc, HChar **argv, HChar **envp )
1234 Int need_help;
1235 ThreadId tid_main = VG_INVALID_THREADID;
1236 Int loglevel, i;
1237 XArray* addr2dihandle = NULL;
1239 //============================================================
1241 // Nb: startup is complex. Prerequisites are shown at every step.
1242 // *** Be very careful when messing with the order ***
1244 // The first order of business is to get debug logging, the address
1245 // space manager and the dynamic memory manager up and running.
1246 // Once that's done, we can relax a bit.
1248 //============================================================
1250 /* This is needed to make VG_(getenv) usable early. */
1251 VG_(client_envp) = (HChar**)envp;
1253 //--------------------------------------------------------------
1254 // Start up Mach kernel interface, if any
1255 // p: none
1256 //--------------------------------------------------------------
1257 # if defined(VGO_darwin)
1258 VG_(mach_init)();
1259 # endif
1261 //--------------------------------------------------------------
1262 // Start up the logging mechanism
1263 // p: none
1264 //--------------------------------------------------------------
1265 /* Start the debugging-log system ASAP. First find out how many
1266 "-d"s were specified. This is a pre-scan of the command line. Also
1267 get --profile-heap=yes, --core-redzone-size, --redzone-size
1268 --aspace-minaddr which are needed by the time we start up dynamic
1269 memory management. */
1270 loglevel = 0;
1271 for (i = 1; i < argc; i++) {
1272 const HChar* tmp_str;
1273 if (argv[i][0] != '-') break;
1274 if VG_STREQ(argv[i], "--") break;
1275 if VG_STREQ(argv[i], "-d") loglevel++;
1276 if VG_BOOL_CLOM(cloE, argv[i], "--profile-heap", VG_(clo_profile_heap)) {}
1277 if VG_BINT_CLOM(cloE, argv[i], "--core-redzone-size", VG_(clo_core_redzone_size),
1278 0, MAX_CLO_REDZONE_SZB) {}
1279 if VG_BINT_CLOM(cloE, argv[i], "--redzone-size", VG_(clo_redzone_size),
1280 0, MAX_CLO_REDZONE_SZB) {}
1281 if VG_STR_CLOM(cloE, argv[i], "--aspace-minaddr", tmp_str) {
1282 Bool ok = VG_(parse_Addr) (&tmp_str, &VG_(clo_aspacem_minAddr));
1283 if (!ok)
1284 VG_(fmsg_bad_option)(argv[i], "Invalid address\n");
1285 const HChar *errmsg;
1286 if (!VG_(am_is_valid_for_aspacem_minAddr)(VG_(clo_aspacem_minAddr),
1287 &errmsg))
1288 VG_(fmsg_bad_option)(argv[i], "%s\n", errmsg);
1292 /* ... and start the debug logger. Now we can safely emit logging
1293 messages all through startup. */
1294 VG_(debugLog_startup)(loglevel, "Stage 2 (main)");
1295 VG_(debugLog)(1, "main", "Welcome to Valgrind version "
1296 VERSION " debug logging\n");
1298 //--------------------------------------------------------------
1299 // Ensure we're on a plausible stack.
1300 // p: logging
1301 //--------------------------------------------------------------
1302 VG_(debugLog)(1, "main", "Checking current stack is plausible\n");
1303 { HChar* limLo = (HChar*)(&VG_(interim_stack).bytes[0]);
1304 HChar* limHi = limLo + sizeof(VG_(interim_stack));
1305 HChar* volatile
1306 aLocal = (HChar*)&limLo; /* any auto local will do */
1307 /* Re "volatile": Apple clang version 4.0
1308 (tags/Apple/clang-421.0.57) (based on LLVM 3.1svn)" appeared
1309 to miscompile the following check, causing run to abort at
1310 this point (in 64-bit mode) even though aLocal is within limLo
1311 .. limHi. But in fact clang is within its rights to do
1312 strange things here. "The reason is that the comparisons
1313 aLocal < limLo and aLocal >= limHi cause undefined behaviour
1314 (according to c99 6.5.8) because they compare pointers that do
1315 not point into the same aggregate." Adding "volatile" appears
1316 to fix it because "The compiler would have to prove that there
1317 is undefined behavior in order to exploit it. But as a
1318 volatile variable can change its value in ways invisible to
1319 the compiler, the compiler must make the conservative
1320 assumption that it points into the same aggregate as the other
1321 pointer its compared against. I.e. the behaviour is possibly
1322 defined." (Analysis by Florian Krohm). */
1323 if (aLocal < limLo || aLocal >= limHi) {
1324 /* something's wrong. Stop. */
1325 VG_(debugLog)(0, "main", "Root stack %p to %p, a local %p\n",
1326 limLo, limHi, aLocal );
1327 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1328 "Initial stack switched failed.\n");
1329 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1330 VG_(exit)(1);
1334 //--------------------------------------------------------------
1335 // Ensure we have a plausible pointer to the stack on which
1336 // we gained control (not the current stack!)
1337 // p: logging
1338 //--------------------------------------------------------------
1339 VG_(debugLog)(1, "main", "Checking initial stack was noted\n");
1340 if (the_iicii.sp_at_startup == 0) {
1341 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1342 "Initial stack was not noted.\n");
1343 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1344 VG_(exit)(1);
1347 //--------------------------------------------------------------
1348 // Start up the address space manager, and determine the
1349 // approximate location of the client's stack
1350 // p: logging, plausible-stack
1351 //--------------------------------------------------------------
1352 VG_(debugLog)(1, "main", "Starting the address space manager\n");
1353 vg_assert(VKI_PAGE_SIZE == 4096 || VKI_PAGE_SIZE == 8192
1354 || VKI_PAGE_SIZE == 16384 || VKI_PAGE_SIZE == 32768
1355 || VKI_PAGE_SIZE == 65536);
1356 vg_assert(VKI_MAX_PAGE_SIZE == 4096 || VKI_MAX_PAGE_SIZE == 8192
1357 || VKI_MAX_PAGE_SIZE == 16384 || VKI_MAX_PAGE_SIZE == 32768
1358 || VKI_MAX_PAGE_SIZE == 65536);
1359 vg_assert(VKI_PAGE_SIZE <= VKI_MAX_PAGE_SIZE);
1360 vg_assert(VKI_PAGE_SIZE == (1 << VKI_PAGE_SHIFT));
1361 vg_assert(VKI_MAX_PAGE_SIZE == (1 << VKI_MAX_PAGE_SHIFT));
1362 the_iicii.clstack_end = VG_(am_startup)( the_iicii.sp_at_startup );
1363 VG_(debugLog)(1, "main", "Address space manager is running\n");
1365 //--------------------------------------------------------------
1366 // Start up the dynamic memory manager
1367 // p: address space management
1368 // p: getting --profile-heap,--core-redzone-size,--redzone-size
1369 // In fact m_mallocfree is self-initialising, so there's no
1370 // initialisation call to do. Instead, try a simple malloc/
1371 // free pair right now to check that nothing is broken.
1372 //--------------------------------------------------------------
1373 VG_(debugLog)(1, "main", "Starting the dynamic memory manager\n");
1374 { void* p = VG_(malloc)( "main.vm.1", 12345 );
1375 VG_(free)( p );
1377 VG_(debugLog)(1, "main", "Dynamic memory manager is running\n");
1379 //============================================================
1381 // Dynamic memory management is now available.
1383 //============================================================
1385 //--------------------------------------------------------------
1386 // Initialise m_debuginfo
1387 // p: dynamic memory allocation
1388 VG_(debugLog)(1, "main", "Initialise m_debuginfo\n");
1389 VG_(di_initialise)();
1391 //--------------------------------------------------------------
1392 // Look for alternative libdir
1393 { HChar *cp = VG_(getenv)(VALGRIND_LIB);
1394 if (cp != NULL)
1395 VG_(libdir) = cp;
1396 VG_(debugLog)(1, "main", "VG_(libdir) = %s\n", VG_(libdir));
1399 //--------------------------------------------------------------
1400 // Extract the launcher name from the environment.
1401 VG_(debugLog)(1, "main", "Getting launcher's name ...\n");
1402 VG_(name_of_launcher) = VG_(getenv)(VALGRIND_LAUNCHER);
1403 if (VG_(name_of_launcher) == NULL) {
1404 VG_(printf)("valgrind: You cannot run '%s' directly.\n", argv[0]);
1405 VG_(printf)("valgrind: You should use $prefix/bin/valgrind.\n");
1406 VG_(exit)(1);
1408 VG_(debugLog)(1, "main", "... %s\n", VG_(name_of_launcher));
1410 //--------------------------------------------------------------
1411 // We used to set the process datasize rlimit to zero to prevent
1412 // any internal use of brk() from having any effect. But later
1413 // linux kernels redefine RLIMIT_DATA as the size of any data
1414 // areas, including some dynamic mmap memory allocations.
1415 // See bug #357833 for the commit that went into linux 4.5
1416 // changing the definition of RLIMIT_DATA. So don't mess with
1417 // RLIMIT_DATA here now anymore. Just remember it for use in
1418 // the syscall wrappers.
1419 VG_(getrlimit)(VKI_RLIMIT_DATA, &VG_(client_rlimit_data));
1421 // Get the current process stack rlimit.
1422 VG_(getrlimit)(VKI_RLIMIT_STACK, &VG_(client_rlimit_stack));
1424 //--------------------------------------------------------------
1425 // Figure out what sort of CPU we're on, and whether it is
1426 // able to run V.
1427 /* The vex_archinfo structure is passed down later to the client
1428 * to verify the HW info settings are consistent.
1430 VexArchInfo vex_archinfo;
1431 VG_(debugLog)(1, "main", "Get hardware capabilities ...\n");
1432 { VexArch vex_arch;
1433 Bool ok = VG_(machine_get_hwcaps)();
1434 if (!ok) {
1435 VG_(printf)("\n");
1436 VG_(printf)("valgrind: fatal error: unsupported CPU.\n");
1437 VG_(printf)(" Supported CPUs are:\n");
1438 VG_(printf)(" * x86 (practically any; Pentium-I or above), "
1439 "AMD Athlon or above)\n");
1440 VG_(printf)(" * AMD Athlon64/Opteron\n");
1441 VG_(printf)(" * ARM (armv7)\n");
1442 VG_(printf)(" * MIPS (mips32 and above; mips64 and above)\n");
1443 VG_(printf)(" * PowerPC (most; ppc405 and above)\n");
1444 VG_(printf)(" * System z (64bit only - s390x; z990 and above)\n");
1445 VG_(printf)("\n");
1446 VG_(exit)(1);
1448 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
1449 VG_(debugLog)(
1450 1, "main", "... arch = %s, hwcaps = %s\n",
1451 LibVEX_ppVexArch ( vex_arch ),
1452 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1456 //--------------------------------------------------------------
1457 // Record the working directory at startup
1458 // p: none
1459 VG_(debugLog)(1, "main", "Getting the working directory at startup\n");
1460 VG_(record_startup_wd)();
1461 const HChar *wd = VG_(get_startup_wd)();
1462 VG_(debugLog)(1, "main", "... %s\n", wd != NULL ? wd : "<NO CWD>" );
1464 //============================================================
1465 // Command line argument handling order:
1466 // * If --help/--help-debug are present, show usage message
1467 // (including the tool-specific usage)
1468 // * (If no --tool option given, default to Memcheck)
1469 // * Then, if client is missing, abort with error msg
1470 // * Then, if any cmdline args are bad, abort with error msg
1471 //============================================================
1473 //--------------------------------------------------------------
1474 // Split up argv into: C args, V args, V extra args, and exename.
1475 // p: dynamic memory allocation
1476 //--------------------------------------------------------------
1477 VG_(debugLog)(1, "main", "Split up command line\n");
1478 VG_(split_up_argv)( argc, argv );
1479 vg_assert( VG_(args_for_valgrind) );
1480 vg_assert( VG_(args_for_client) );
1481 if (0) {
1482 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++)
1483 VG_(printf)(
1484 "varg %s\n",
1485 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1487 VG_(printf)(" exe %s\n", VG_(args_the_exename));
1488 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++)
1489 VG_(printf)(
1490 "carg %s\n",
1491 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1495 //--------------------------------------------------------------
1496 // Extract tool name and whether help has been requested.
1497 // Note we can't print the help message yet, even if requested,
1498 // because the tool has not been initialised.
1499 // p: split_up_argv [for VG_(args_for_valgrind)]
1500 //--------------------------------------------------------------
1501 VG_(debugLog)(1, "main",
1502 "(early_) Process Valgrind's command line options\n");
1503 early_process_cmd_line_options(&need_help);
1505 // BEGIN HACK
1506 // When changing the logic for the VG_(clo_read_inline_info) default,
1507 // the manual and --help output have to be changed accordingly.
1508 vg_assert(VG_(clo_toolname) != NULL);
1509 vg_assert(VG_(clo_read_inline_info) == False);
1510 # if !defined(VGO_darwin)
1511 if (0 == VG_(strcmp)(VG_(clo_toolname), "memcheck")
1512 || 0 == VG_(strcmp)(VG_(clo_toolname), "helgrind")
1513 || 0 == VG_(strcmp)(VG_(clo_toolname), "drd")
1514 || 0 == VG_(strcmp)(VG_(clo_toolname), "massif")
1515 || 0 == VG_(strcmp)(VG_(clo_toolname), "dhat")) {
1516 /* Change the default setting. Later on (just below)
1517 main_process_cmd_line_options should pick up any
1518 user-supplied setting for it and will override the default
1519 set here. */
1520 VG_(clo_read_inline_info) = True;
1522 # endif
1523 // END HACK
1525 // Set default vex control params.
1526 LibVEX_default_VexControl(& VG_(clo_vex_control));
1528 //--------------------------------------------------------------
1529 // Load client executable, finding in $PATH if necessary
1530 // p: early_process_cmd_line_options() [for 'exec', 'need_help',
1531 // clo_max_stackframe,
1532 // clo_main_stacksize]
1533 // p: layout_remaining_space [so there's space]
1535 // Set up client's environment
1536 // p: set-libdir [for VG_(libdir)]
1537 // p: early_process_cmd_line_options [for VG_(clo_toolname)]
1539 // Setup client stack, eip, and VG_(client_arg[cv])
1540 // p: load_client() [for 'info']
1541 // p: fix_environment() [for 'env']
1543 // Setup client data (brk) segment. Initially a 1-page segment
1544 // which abuts a shrinkable reservation.
1545 // p: load_client() [for 'info' and hence VG_(brk_base)]
1547 // p: _start_in_C (for zeroing out the_iicii and putting some
1548 // initial values into it)
1549 //--------------------------------------------------------------
1550 if (!need_help) {
1551 VG_(debugLog)(1, "main", "Create initial image\n");
1553 # if defined(VGO_linux) || defined(VGO_darwin) || defined(VGO_solaris)
1554 the_iicii.argv = argv;
1555 the_iicii.envp = envp;
1556 the_iicii.toolname = VG_(clo_toolname);
1557 # else
1558 # error "Unknown platform"
1559 # endif
1561 /* NOTE: this call reads VG_(clo_main_stacksize). */
1562 the_iifii = VG_(ii_create_image)( the_iicii, &vex_archinfo );
1565 //==============================================================
1567 // Finished loading/setting up the client address space.
1569 //==============================================================
1571 //--------------------------------------------------------------
1572 // setup file descriptors
1573 // p: n/a
1574 //--------------------------------------------------------------
1575 VG_(debugLog)(1, "main", "Setup file descriptors\n");
1576 setup_file_descriptors();
1578 //--------------------------------------------------------------
1579 // create fake /proc/<pid>/cmdline and /proc/<pid>/auxv files
1580 // and then unlink them, but hold onto the fds, so we can handr
1581 // them out to the client when it tries to open
1582 // /proc/<pid>/cmdline or /proc/<pid>/auxv for itself.
1583 // p: setup file descriptors
1584 // p: ii_create_image for VG_(client_auxv) setup.
1585 //--------------------------------------------------------------
1586 VG_(cl_cmdline_fd) = -1;
1587 VG_(cl_auxv_fd) = -1;
1588 #if defined(VGO_solaris)
1589 VG_(cl_psinfo_fd) = -1;
1590 #endif
1592 #if defined(VGO_linux) || defined(VGO_solaris)
1593 if (!need_help) {
1594 HChar buf[50]; // large enough
1595 HChar buf2[VG_(mkstemp_fullname_bufsz)(sizeof buf - 1)];
1596 Int fd, r;
1598 #if defined(VGO_linux) || defined(SOLARIS_PROC_CMDLINE)
1599 /* Fake /proc/<pid>/cmdline only on Linux and Solaris if supported. */
1600 HChar nul[1];
1601 const HChar* exename;
1603 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/cmdline\n");
1605 VG_(sprintf)(buf, "proc_%d_cmdline", VG_(getpid)());
1606 fd = VG_(mkstemp)( buf, buf2 );
1607 if (fd == -1)
1608 VG_(err_config_error)("Can't create client cmdline file in %s\n", buf2);
1610 nul[0] = 0;
1611 exename = VG_(args_the_exename);
1612 VG_(write)(fd, exename, VG_(strlen)( exename ));
1613 VG_(write)(fd, nul, 1);
1615 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1616 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i );
1617 VG_(write)(fd, arg, VG_(strlen)( arg ));
1618 VG_(write)(fd, nul, 1);
1621 /* Don't bother to seek the file back to the start; instead do
1622 it every time a copy of it is given out (by PRE(sys_open) or
1623 PRE(sys_openat)). That is probably more robust across fork() etc. */
1625 /* Now delete it, but hang on to the fd. */
1626 r = VG_(unlink)( buf2 );
1627 if (r)
1628 VG_(err_config_error)("Can't delete client cmdline file in %s\n", buf2);
1630 VG_(cl_cmdline_fd) = fd;
1631 #endif // defined(VGO_linux) || defined(SOLARIS_PROC_CMDLINE)
1633 /* Fake /proc/<pid>/auxv on both Linux and Solaris. */
1634 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/auxv\n");
1636 VG_(sprintf)(buf, "proc_%d_auxv", VG_(getpid)());
1637 fd = VG_(mkstemp)( buf, buf2 );
1638 if (fd == -1)
1639 VG_(err_config_error)("Can't create client auxv file in %s\n", buf2);
1641 UWord *client_auxv = VG_(client_auxv);
1642 unsigned int client_auxv_len = 0;
1643 while (*client_auxv != 0) {
1644 client_auxv++;
1645 client_auxv++;
1646 client_auxv_len += 2 * sizeof(UWord);
1648 client_auxv_len += 2 * sizeof(UWord);
1650 VG_(write)(fd, VG_(client_auxv), client_auxv_len);
1652 /* Don't bother to seek the file back to the start; instead do
1653 it every time a copy of it is given out (by PRE(sys_open)).
1654 That is probably more robust across fork() etc. */
1656 /* Now delete it, but hang on to the fd. */
1657 r = VG_(unlink)( buf2 );
1658 if (r)
1659 VG_(err_config_error)("Can't delete client auxv file in %s\n", buf2);
1661 VG_(cl_auxv_fd) = fd;
1663 #if defined(VGO_solaris)
1664 /* Fake /proc/<pid>/psinfo on Solaris.
1665 * Contents will be fetched and partially faked later on the fly. */
1666 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/psinfo\n");
1668 VG_(sprintf)(buf, "proc_%d_psinfo", VG_(getpid)());
1669 fd = VG_(mkstemp)( buf, buf2 );
1670 if (fd == -1)
1671 VG_(err_config_error)("Can't create client psinfo file in %s\n", buf2);
1673 /* Now delete it, but hang on to the fd. */
1674 r = VG_(unlink)( buf2 );
1675 if (r)
1676 VG_(err_config_error)("Can't delete client psinfo file in %s\n", buf2);
1678 VG_(cl_psinfo_fd) = fd;
1679 #endif /* VGO_solaris */
1681 #endif
1683 //--------------------------------------------------------------
1684 // Init tool part 1: pre_clo_init
1685 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1686 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1687 //--------------------------------------------------------------
1688 VG_(debugLog)(1, "main", "Initialise the tool part 1 (pre_clo_init)\n");
1689 VG_(tl_pre_clo_init)();
1690 // Activate var info readers, if the tool asked for it:
1691 if (VG_(needs).var_info)
1692 VG_(clo_read_var_info) = True;
1694 //--------------------------------------------------------------
1695 // If --tool and --help/--help-debug was given, now give the core+tool
1696 // help message
1697 // p: early_process_cmd_line_options() [for 'need_help']
1698 // p: tl_pre_clo_init [for 'VG_(tdict).usage']
1699 //--------------------------------------------------------------
1700 VG_(debugLog)(1, "main", "Print help and quit, if requested\n");
1701 if (need_help) {
1702 usage_NORETURN(need_help);
1705 //--------------------------------------------------------------
1706 // Process command line options to Valgrind + tool
1707 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1708 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1709 //--------------------------------------------------------------
1710 VG_(debugLog)(1, "main",
1711 "(main_) Process Valgrind's command line options, "
1712 "setup logging\n");
1713 main_process_cmd_line_options();
1715 //--------------------------------------------------------------
1716 // Zeroise the millisecond counter by doing a first read of it.
1717 // p: none
1718 //--------------------------------------------------------------
1719 (void) VG_(read_millisecond_timer)();
1721 //--------------------------------------------------------------
1722 // Print the preamble
1723 // p: tl_pre_clo_init [for 'VG_(details).name' and friends]
1724 // p: main_process_cmd_line_options()
1725 // [for VG_(clo_verbosity), VG_(clo_xml)]
1726 //--------------------------------------------------------------
1727 VG_(debugLog)(1, "main", "Print the preamble...\n");
1728 VG_(print_preamble)(VG_(log_output_sink).type != VgLogTo_File);
1729 VG_(debugLog)(1, "main", "...finished the preamble\n");
1731 //--------------------------------------------------------------
1732 // Init tool part 2: post_clo_init
1733 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1734 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1735 // p: print_preamble() [so any warnings printed in post_clo_init
1736 // are shown after the preamble]
1737 //--------------------------------------------------------------
1738 VG_(debugLog)(1, "main", "Initialise the tool part 2 (post_clo_init)\n");
1739 VG_TDICT_CALL(tool_post_clo_init);
1741 /* The tool's "needs" will by now be finalised, since it has no
1742 further opportunity to specify them. So now sanity check
1743 and finish initialising the needs. */
1744 const HChar* s;
1745 Bool ok;
1746 ok = VG_(finish_needs_init)( &s );
1747 if (!ok) {
1748 VG_(core_panic)(s);
1752 //--------------------------------------------------------------
1753 // Initialise translation table and translation cache
1754 // p: aspacem [??]
1755 // p: tl_pre_clo_init [for 'VG_(details).avg_translation_sizeB']
1756 //--------------------------------------------------------------
1757 VG_(debugLog)(1, "main", "Initialise TT/TC\n");
1758 VG_(init_tt_tc)();
1760 //--------------------------------------------------------------
1761 // Initialise the redirect table.
1762 // p: init_tt_tc [so it can call VG_(search_transtab) safely]
1763 // p: aspacem [so can change ownership of sysinfo pages]
1764 //--------------------------------------------------------------
1765 VG_(debugLog)(1, "main", "Initialise redirects\n");
1766 VG_(redir_initialise)();
1768 //--------------------------------------------------------------
1769 // Search for file descriptors that are inherited from our parent
1770 // p: main_process_cmd_line_options [for VG_(clo_track_fds)]
1771 //--------------------------------------------------------------
1772 if (VG_(clo_track_fds)) {
1773 VG_(debugLog)(1, "main", "Init preopened fds\n");
1774 VG_(init_preopened_fds)();
1777 #if defined(VGO_solaris)
1778 VG_(syswrap_init)();
1779 #endif
1781 //--------------------------------------------------------------
1782 // Load debug info for the existing segments.
1783 // p: setup_code_redirect_table [so that redirs can be recorded]
1784 // p: mallocfree
1785 // p: probably: setup fds and process CLOs, so that logging works
1786 // p: initialise m_debuginfo
1788 // While doing this, make a note of the debuginfo-handles that
1789 // come back from VG_(di_notify_mmap).
1790 // Later, in "Tell the tool about the initial client memory permissions"
1791 // (just below) we can then hand these handles off to the tool in
1792 // calls to VG_TRACK(new_mem_startup, ...). This gives the tool the
1793 // opportunity to make further queries to m_debuginfo before the
1794 // client is started, if it wants. We put this information into an
1795 // XArray, each handle along with the associated segment start address,
1796 // and search the XArray for the handles later, when calling
1797 // VG_TRACK(new_mem_startup, ...).
1798 //--------------------------------------------------------------
1799 VG_(debugLog)(1, "main", "Load initial debug info\n");
1801 vg_assert(!addr2dihandle);
1802 addr2dihandle = VG_(newXA)( VG_(malloc), "main.vm.2",
1803 VG_(free), sizeof(Addr_n_ULong) );
1805 # if defined(VGO_linux) || defined(VGO_solaris)
1806 { Addr* seg_starts;
1807 Int n_seg_starts;
1808 Addr_n_ULong anu;
1810 seg_starts = VG_(get_segment_starts)( SkFileC | SkFileV, &n_seg_starts );
1811 vg_assert(seg_starts && n_seg_starts >= 0);
1813 /* show them all to the debug info reader. allow_SkFileV has to
1814 be True here so that we read info from the valgrind executable
1815 itself. */
1816 for (i = 0; i < n_seg_starts; i++) {
1817 anu.ull = VG_(di_notify_mmap)( seg_starts[i], True/*allow_SkFileV*/,
1818 -1/*Don't use_fd*/);
1819 /* anu.ull holds the debuginfo handle returned by di_notify_mmap,
1820 if any. */
1821 if (anu.ull > 0) {
1822 anu.a = seg_starts[i];
1823 VG_(addToXA)( addr2dihandle, &anu );
1827 VG_(free)( seg_starts );
1829 # elif defined(VGO_darwin)
1830 { Addr* seg_starts;
1831 Int n_seg_starts;
1832 seg_starts = VG_(get_segment_starts)( SkFileC, &n_seg_starts );
1833 vg_assert(seg_starts && n_seg_starts >= 0);
1835 /* show them all to the debug info reader.
1836 Don't read from V segments (unlike Linux) */
1837 // GrP fixme really?
1838 for (i = 0; i < n_seg_starts; i++) {
1839 VG_(di_notify_mmap)( seg_starts[i], False/*don't allow_SkFileV*/,
1840 -1/*don't use_fd*/);
1843 VG_(free)( seg_starts );
1845 # else
1846 # error Unknown OS
1847 # endif
1849 //--------------------------------------------------------------
1850 // Tell aspacem of ownership change of the asm helpers, so that
1851 // m_translate allows them to be translated. However, only do this
1852 // after the initial debug info read, since making a hole in the
1853 // address range for the stage2 binary confuses the debug info reader.
1854 // p: aspacem
1855 //--------------------------------------------------------------
1856 { Bool change_ownership_v_c_OK;
1857 Addr co_start = VG_PGROUNDDN( (Addr)&VG_(trampoline_stuff_start) );
1858 Addr co_endPlus = VG_PGROUNDUP( (Addr)&VG_(trampoline_stuff_end) );
1859 VG_(debugLog)(1,"redir",
1860 "transfer ownership V -> C of 0x%llx .. 0x%llx\n",
1861 (ULong)co_start, (ULong)co_endPlus-1 );
1863 change_ownership_v_c_OK
1864 = VG_(am_change_ownership_v_to_c)( co_start, co_endPlus - co_start );
1865 vg_assert(change_ownership_v_c_OK);
1868 if (VG_(clo_xml)) {
1869 HChar buf[50]; // large enough
1870 VG_(elapsed_wallclock_time)(buf, sizeof buf);
1871 VG_(printf_xml)( "<status>\n"
1872 " <state>RUNNING</state>\n"
1873 " <time>%pS</time>\n"
1874 "</status>\n",
1875 buf );
1876 VG_(printf_xml)( "\n" );
1879 VG_(init_Threads)();
1881 //--------------------------------------------------------------
1882 // Initialise the scheduler (phase 1) [generates tid_main]
1883 // p: none, afaics
1884 //--------------------------------------------------------------
1885 VG_(debugLog)(1, "main", "Initialise scheduler (phase 1)\n");
1886 tid_main = VG_(scheduler_init_phase1)();
1887 vg_assert(tid_main >= 0 && tid_main < VG_N_THREADS
1888 && tid_main != VG_INVALID_THREADID);
1889 /* Tell the tool about tid_main */
1890 VG_TRACK( pre_thread_ll_create, VG_INVALID_THREADID, tid_main );
1892 //--------------------------------------------------------------
1893 // Tell the tool about the initial client memory permissions
1894 // p: aspacem
1895 // p: mallocfree
1896 // p: setup_client_stack
1897 // p: setup_client_dataseg
1899 // For each segment we tell the client about, look up in
1900 // addr2dihandle as created above, to see if there's a debuginfo
1901 // handle associated with the segment, that we can hand along
1902 // to the tool, to be helpful.
1903 //--------------------------------------------------------------
1904 VG_(debugLog)(1, "main", "Tell tool about initial permissions\n");
1905 { Addr* seg_starts;
1906 Int n_seg_starts;
1908 vg_assert(addr2dihandle);
1910 /* Mark the main thread as running while we tell the tool about
1911 the client memory so that the tool can associate that memory
1912 with the main thread. */
1913 vg_assert(VG_(running_tid) == VG_INVALID_THREADID);
1914 VG_(running_tid) = tid_main;
1916 seg_starts = VG_(get_segment_starts)( SkFileC | SkAnonC | SkShmC,
1917 &n_seg_starts );
1918 vg_assert(seg_starts && n_seg_starts >= 0);
1920 /* Show client segments to the tool */
1921 for (i = 0; i < n_seg_starts; i++) {
1922 Word j, n;
1923 NSegment const* seg
1924 = VG_(am_find_nsegment)( seg_starts[i] );
1925 vg_assert(seg);
1926 vg_assert(seg->kind == SkFileC || seg->kind == SkAnonC ||
1927 seg->kind == SkShmC);
1928 vg_assert(seg->start == seg_starts[i]);
1930 VG_(debugLog)(2, "main",
1931 "tell tool about %010lx-%010lx %c%c%c\n",
1932 seg->start, seg->end,
1933 seg->hasR ? 'r' : '-',
1934 seg->hasW ? 'w' : '-',
1935 seg->hasX ? 'x' : '-' );
1936 /* search addr2dihandle to see if we have an entry
1937 matching seg->start. */
1938 n = VG_(sizeXA)( addr2dihandle );
1939 for (j = 0; j < n; j++) {
1940 Addr_n_ULong* anl = VG_(indexXA)( addr2dihandle, j );
1941 if (anl->a == seg->start) {
1942 vg_assert(anl->ull > 0); /* check it's a valid handle */
1943 break;
1946 vg_assert(j >= 0 && j <= n);
1947 VG_TRACK( new_mem_startup, seg->start, seg->end+1-seg->start,
1948 seg->hasR, seg->hasW, seg->hasX,
1949 /* and the retrieved debuginfo handle, if any */
1950 j < n
1951 ? ((Addr_n_ULong*)VG_(indexXA)( addr2dihandle, j ))->ull
1952 : 0 );
1956 VG_(free)( seg_starts );
1957 VG_(deleteXA)( addr2dihandle );
1959 /* Also do the initial stack permissions. */
1961 SSizeT inaccessible_len;
1962 NSegment const* seg
1963 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
1964 vg_assert(seg);
1965 vg_assert(seg->kind == SkAnonC);
1966 vg_assert(the_iifii.initial_client_SP >= seg->start);
1967 vg_assert(the_iifii.initial_client_SP <= seg->end);
1969 /* Stuff below the initial SP is unaddressable. Take into
1970 account any ABI-mandated space below the stack pointer that
1971 is required (VG_STACK_REDZONE_SZB). setup_client_stack()
1972 will have allocated an extra page if a red zone is required,
1973 to be on the safe side. */
1974 inaccessible_len = the_iifii.initial_client_SP - VG_STACK_REDZONE_SZB
1975 - seg->start;
1976 vg_assert(inaccessible_len >= 0);
1977 if (inaccessible_len > 0)
1978 VG_TRACK( die_mem_stack,
1979 seg->start,
1980 inaccessible_len );
1981 VG_(debugLog)(2, "main", "mark stack inaccessible %010lx-%010lx\n",
1982 seg->start,
1983 the_iifii.initial_client_SP-1 - VG_STACK_REDZONE_SZB);
1986 /* Also the assembly helpers. */
1987 VG_TRACK( new_mem_startup,
1988 (Addr)&VG_(trampoline_stuff_start),
1989 (Addr)&VG_(trampoline_stuff_end)
1990 - (Addr)&VG_(trampoline_stuff_start),
1991 False, /* readable? */
1992 False, /* writable? */
1993 True /* executable? */,
1994 0 /* di_handle: no associated debug info */ );
1996 /* Clear the running thread indicator */
1997 VG_(running_tid) = VG_INVALID_THREADID;
1998 vg_assert(VG_(running_tid) == VG_INVALID_THREADID);
2000 /* Darwin only: tell the tools where the client's kernel commpage
2001 is. It would be better to do this by telling aspacemgr about
2002 it -- see the now disused record_system_memory() in
2003 initimg-darwin.c -- but that causes the sync checker to fail,
2004 since the mapping doesn't appear in the kernel-supplied
2005 process map. So do it here instead. */
2006 # if defined(VGP_amd64_darwin)
2007 VG_TRACK( new_mem_startup,
2008 0x7fffffe00000, 0x7ffffffff000-0x7fffffe00000,
2009 True, False, True, /* r-x */
2010 0 /* di_handle: no associated debug info */ );
2011 # elif defined(VGP_x86_darwin)
2012 VG_TRACK( new_mem_startup,
2013 0xfffec000, 0xfffff000-0xfffec000,
2014 True, False, True, /* r-x */
2015 0 /* di_handle: no associated debug info */ );
2016 # endif
2019 //--------------------------------------------------------------
2020 // Initialise the scheduler (phase 2)
2021 // p: Initialise the scheduler (phase 1) [for tid_main]
2022 // p: setup_file_descriptors() [else VG_(safe_fd)() breaks]
2023 // p: setup_client_stack
2024 //--------------------------------------------------------------
2025 VG_(debugLog)(1, "main", "Initialise scheduler (phase 2)\n");
2026 { NSegment const* seg
2027 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
2028 vg_assert(seg);
2029 vg_assert(seg->kind == SkAnonC);
2030 vg_assert(the_iifii.initial_client_SP >= seg->start);
2031 vg_assert(the_iifii.initial_client_SP <= seg->end);
2032 VG_(scheduler_init_phase2)( tid_main,
2033 seg->end, the_iifii.clstack_max_size );
2036 //--------------------------------------------------------------
2037 // Set up state for the root thread
2038 // p: ?
2039 // setup_scheduler() [for sched-specific thread 1 stuff]
2040 // VG_(ii_create_image) [for 'the_iicii' initial info]
2041 //--------------------------------------------------------------
2042 VG_(debugLog)(1, "main", "Finalise initial image\n");
2043 { /* Mark the main thread as running while we tell the tool about
2044 the client memory which could be tracked during initial image
2045 finalisation. So the tool can associate that memory with the
2046 main thread. */
2047 vg_assert(VG_(running_tid) == VG_INVALID_THREADID);
2048 VG_(running_tid) = tid_main;
2050 VG_(ii_finalise_image)( the_iifii );
2052 /* Clear the running thread indicator */
2053 VG_(running_tid) = VG_INVALID_THREADID;
2054 vg_assert(VG_(running_tid) == VG_INVALID_THREADID);
2057 //--------------------------------------------------------------
2058 // Initialise the signal handling subsystem
2059 // p: n/a
2060 //--------------------------------------------------------------
2061 // Nb: temporarily parks the saved blocking-mask in saved_sigmask.
2062 VG_(debugLog)(1, "main", "Initialise signal management\n");
2063 /* Check that the kernel-interface signal definitions look sane */
2064 VG_(vki_do_initial_consistency_checks)();
2065 /* .. and go on to use them. */
2066 VG_(sigstartup_actions)();
2068 //--------------------------------------------------------------
2069 // Read suppression file
2070 // p: main_process_cmd_line_options() [for VG_(clo_suppressions)]
2071 //--------------------------------------------------------------
2072 if (VG_(needs).core_errors || VG_(needs).tool_errors) {
2073 VG_(debugLog)(1, "main", "Load suppressions\n");
2074 VG_(load_suppressions)();
2077 //--------------------------------------------------------------
2078 // register client stack
2079 //--------------------------------------------------------------
2080 VG_(clstk_id) = VG_(register_stack)(VG_(clstk_start_base), VG_(clstk_end));
2082 //--------------------------------------------------------------
2083 // Show the address space state so far
2084 //--------------------------------------------------------------
2085 VG_(debugLog)(1, "main", "\n");
2086 VG_(debugLog)(1, "main", "\n");
2087 VG_(am_show_nsegments)(1,"Memory layout at client startup");
2088 VG_(debugLog)(1, "main", "\n");
2089 VG_(debugLog)(1, "main", "\n");
2091 //--------------------------------------------------------------
2092 // Run!
2093 //--------------------------------------------------------------
2094 VG_(debugLog)(1, "main", "Running thread 1\n");
2096 /* As a result of the following call, the last thread standing
2097 eventually winds up running shutdown_actions_NORETURN
2098 just below. Unfortunately, simply exporting said function
2099 causes m_main to be part of a module cycle, which is pretty
2100 nonsensical. So instead of doing that, the address of said
2101 function is stored in a global variable 'owned' by m_syswrap,
2102 and it uses that function pointer to get back here when it needs
2103 to. */
2105 /* Set continuation address. */
2106 VG_(address_of_m_main_shutdown_actions_NORETURN)
2107 = & shutdown_actions_NORETURN;
2109 /* Run the first thread, eventually ending up at the continuation
2110 address. */
2111 VG_(main_thread_wrapper_NORETURN)(1);
2113 /*NOTREACHED*/
2114 vg_assert(0);
2117 /* Do everything which needs doing when the last thread exits or when
2118 a thread exits requesting a complete process exit.
2120 We enter here holding The Lock. For the case VgSrc_ExitProcess we
2121 must never release it, because to do so would allow other threads
2122 to continue after the system is ostensibly shut down. So we must
2123 go to our grave, so to speak, holding the lock.
2125 In fact, there is never any point in releasing the lock at this
2126 point - we have it, we're shutting down the entire system, and
2127 for the case VgSrc_ExitProcess doing so positively causes trouble.
2128 So don't.
2130 The final_tidyup call makes a bit of a nonsense of the ExitProcess
2131 case, since it will run __gnu_cxx::__freeres and libc_freeres functions,
2132 thus allowing other lurking threads to run again. Hmm. */
2134 static
2135 void shutdown_actions_NORETURN( ThreadId tid,
2136 VgSchedReturnCode tids_schedretcode )
2138 VG_(debugLog)(1, "main", "entering VG_(shutdown_actions_NORETURN)\n");
2139 VG_(am_show_nsegments)(1,"Memory layout at client shutdown");
2141 vg_assert(VG_(is_running_thread)(tid));
2142 vg_assert(tids_schedretcode == VgSrc_ExitThread
2143 || tids_schedretcode == VgSrc_ExitProcess
2144 || tids_schedretcode == VgSrc_FatalSig );
2146 if (tids_schedretcode == VgSrc_ExitThread) {
2148 // We are the last surviving thread. Right?
2149 vg_assert( VG_(count_living_threads)() == 1 );
2151 // Wait for all other threads to exit.
2152 // jrs: Huh? but they surely are already gone
2153 VG_(reap_threads)(tid);
2155 // Clean the client up before the final report.
2156 // This causes __gnu_cxx::__freeres and libc_freeres functions to run.
2157 final_tidyup(tid);
2159 /* be paranoid */
2160 vg_assert(VG_(is_running_thread)(tid));
2161 vg_assert(VG_(count_living_threads)() == 1);
2163 } else {
2165 // We may not be the last surviving thread. However, we
2166 // want to shut down the entire process. We hold the lock
2167 // and we need to keep hold of it all the way out, in order
2168 // that none of the other threads ever run again.
2169 vg_assert( VG_(count_living_threads)() >= 1 );
2171 // Clean the client up before the final report.
2172 // This causes __gnu_cxx::__freeres and libc_freeres functions to run.
2173 // Perhaps this is unsafe, as per comment above.
2174 final_tidyup(tid);
2176 /* be paranoid */
2177 vg_assert(VG_(is_running_thread)(tid));
2178 vg_assert(VG_(count_living_threads)() >= 1);
2181 /* Final call to gdbserver, if requested. */
2182 if (VG_(gdbserver_stop_at) (VgdbStopAt_Exit)) {
2183 VG_(umsg)("(action at exit) vgdb me ... \n");
2184 VG_(gdbserver) (tid);
2186 VG_(threads)[tid].status = VgTs_Empty;
2188 //--------------------------------------------------------------
2189 // Finalisation: cleanup, messages, etc. Order not so important, only
2190 // affects what order the messages come.
2191 //--------------------------------------------------------------
2192 // First thing in the post-amble is a blank line.
2193 if (VG_(clo_xml))
2194 VG_(printf_xml)("\n");
2195 else if (VG_(clo_verbosity) > 0)
2196 VG_(message)(Vg_UserMsg, "\n");
2198 if (VG_(clo_xml)) {
2199 HChar buf[50]; // large enough
2200 VG_(elapsed_wallclock_time)(buf, sizeof buf);
2201 VG_(printf_xml)( "<status>\n"
2202 " <state>FINISHED</state>\n"
2203 " <time>%pS</time>\n"
2204 "</status>\n"
2205 "\n",
2206 buf);
2209 /* Print out file descriptor summary and stats. */
2210 if (VG_(clo_track_fds))
2211 VG_(show_open_fds)("at exit");
2213 /* Call the tool's finalisation function. This makes Memcheck's
2214 leak checker run, and possibly chuck a bunch of leak errors into
2215 the error management machinery. */
2216 VG_TDICT_CALL(tool_fini, 0/*exitcode*/);
2218 if (VG_(needs).core_errors || VG_(needs).tool_errors) {
2219 if (VG_(clo_verbosity) == 1
2220 && !VG_(clo_xml)
2221 && !VG_(clo_show_error_list))
2222 VG_(message)(Vg_UserMsg,
2223 "For lists of detected and suppressed errors,"
2224 " rerun with: -s\n");
2226 /* Show the error counts. */
2227 if (VG_(clo_xml)) {
2228 VG_(show_error_counts_as_XML)();
2231 /* In XML mode, this merely prints the used suppressions. */
2232 VG_(show_all_errors)(VG_(clo_verbosity), VG_(clo_xml));
2235 if (VG_(clo_xml)) {
2236 VG_(printf_xml)("\n");
2237 VG_(printf_xml)("</valgrindoutput>\n");
2238 VG_(printf_xml)("\n");
2241 VG_(sanity_check_general)( True /*include expensive checks*/ );
2243 if (VG_(clo_stats))
2244 VG_(print_all_stats)(VG_(clo_verbosity) >= 1, /* Memory stats */
2245 False /* tool prints stats in the tool fini */);
2247 /* Show a profile of the heap(s) at shutdown. Optionally, first
2248 throw away all the debug info, as that makes it easy to spot
2249 leaks in the debuginfo reader. */
2250 if (VG_(clo_profile_heap)) {
2251 if (0) VG_(di_discard_ALL_debuginfo)();
2252 VG_(print_arena_cc_analysis)();
2255 /* If profiling has been requested, but with zero interval, it
2256 means "profile at the end of the run only". In which case we
2257 need to dump the profile now. */
2258 if (VG_(clo_profyle_sbs) && VG_(clo_profyle_interval) == 0) {
2259 VG_(get_and_show_SB_profile)(0/*denoting end-of-run*/);
2262 /* Print Vex storage stats */
2263 if (0)
2264 LibVEX_ShowAllocStats();
2266 /* Flush any output cached by previous calls to VG_(message). */
2267 VG_(message_flush)();
2269 /* Terminate gdbserver if ever it was started. We terminate it here
2270 so that it get the output above if output was redirected to
2271 gdb */
2272 VG_(gdbserver_exit) (tid, tids_schedretcode);
2274 /* Ok, finally exit in the os-specific way, according to the scheduler's
2275 return code. In short, if the (last) thread exited by calling
2276 sys_exit, do likewise; if the (last) thread stopped due to a fatal
2277 signal, terminate the entire system with that same fatal signal. */
2278 VG_(debugLog)(1, "core_os",
2279 "VG_(terminate_NORETURN)(tid=%u) schedretcode %s"
2280 " os_state.exit_code %ld fatalsig %d\n",
2281 tid, VG_(name_of_VgSchedReturnCode)(tids_schedretcode),
2282 VG_(threads)[tid].os_state.exitcode,
2283 VG_(threads)[tid].os_state.fatalsig);
2285 switch (tids_schedretcode) {
2286 case VgSrc_ExitThread: /* the normal way out (Linux, Solaris) */
2287 case VgSrc_ExitProcess: /* the normal way out (Darwin) */
2288 /* Change the application return code to user's return code,
2289 if an error was found */
2290 if (VG_(clo_error_exitcode) > 0
2291 && VG_(get_n_errs_found)() > 0) {
2292 VG_(client_exit)( VG_(clo_error_exitcode) );
2293 } else {
2294 /* otherwise, return the client's exit code, in the normal
2295 way. */
2296 VG_(client_exit)( VG_(threads)[tid].os_state.exitcode );
2298 /* NOT ALIVE HERE! */
2299 VG_(core_panic)("entered the afterlife in main() -- ExitT/P");
2300 break; /* what the hell :) */
2302 case VgSrc_FatalSig:
2303 /* We were killed by a fatal signal, so replicate the effect */
2304 vg_assert(VG_(threads)[tid].os_state.fatalsig != 0);
2305 VG_(kill_self)(VG_(threads)[tid].os_state.fatalsig);
2306 /* we shouldn't be alive at this point. But VG_(kill_self)
2307 sometimes fails with EPERM on Darwin, for unclear reasons. */
2308 # if defined(VGO_darwin)
2309 VG_(debugLog)(0, "main", "VG_(kill_self) failed. Exiting normally.\n");
2310 VG_(exit)(0); /* bogus, but we really need to exit now */
2311 /* fall through .. */
2312 # endif
2313 VG_(core_panic)("main(): signal was supposed to be fatal");
2314 break;
2316 default:
2317 VG_(core_panic)("main(): unexpected scheduler return code");
2321 /* -------------------- */
2323 /* Final clean-up before terminating the process.
2324 Clean up the client by calling __gnu_cxx::__freeres() (if requested)
2325 and __libc_freeres() (if requested).
2327 static void final_tidyup(ThreadId tid)
2329 #if defined(VGO_linux) || defined(VGO_solaris)
2330 Addr freeres_wrapper = VG_(client_freeres_wrapper);
2332 vg_assert(VG_(is_running_thread)(tid));
2334 if (freeres_wrapper == 0) {
2335 return; /* can't do it */
2338 Vg_FreeresToRun to_run = 0;
2339 if (VG_(needs).cxx_freeres && VG_(clo_run_cxx_freeres)) {
2340 to_run |= VG_RUN__GNU_CXX__FREERES;
2343 if (VG_(needs).libc_freeres && VG_(clo_run_libc_freeres)) {
2344 to_run |= VG_RUN__LIBC_FREERES;
2347 if (to_run == 0) {
2348 return; /* won't do it */
2351 # if defined(VGP_ppc64be_linux)
2352 Addr r2 = VG_(get_tocptr)(VG_(current_DiEpoch)(),
2353 freeres_wrapper);
2354 if (r2 == 0) {
2355 VG_(message)(Vg_UserMsg,
2356 "Caught __NR_exit, but can't run __gnu_cxx::__freeres()\n");
2357 VG_(message)(Vg_UserMsg,
2358 " or __libc_freeres() since cannot establish TOC pointer "
2359 "for it.\n");
2360 return;
2362 # endif
2364 if (VG_(clo_verbosity) > 2 ||
2365 VG_(clo_trace_syscalls) ||
2366 VG_(clo_trace_sched)) {
2368 vg_assert(to_run > 0);
2369 vg_assert(to_run <= (VG_RUN__GNU_CXX__FREERES | VG_RUN__LIBC_FREERES));
2371 const HChar *msgs[] = {"__gnu_cxx::__freeres()", "__libc_freeres()",
2372 "__gnu_cxx::__freeres and __libc_freeres()"};
2373 VG_(message)(Vg_DebugMsg,
2374 "Caught __NR_exit; running %s wrapper\n", msgs[to_run - 1]);
2377 /* Set thread context to point to freeres_wrapper.
2378 ppc64be-linux note: freeres_wrapper gives us the real
2379 function entry point, not a fn descriptor, so can use it
2380 directly. However, we need to set R2 (the toc pointer)
2381 appropriately. */
2382 VG_(set_IP)(tid, freeres_wrapper);
2384 # if defined(VGP_ppc64be_linux)
2385 VG_(threads)[tid].arch.vex.guest_GPR2 = r2;
2386 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2387 offsetof(VexGuestPPC64State, guest_GPR2),
2388 sizeof(VG_(threads)[tid].arch.vex.guest_GPR2));
2389 # elif defined(VGP_ppc64le_linux)
2390 /* setting GPR2 but not really needed, GPR12 is needed */
2391 VG_(threads)[tid].arch.vex.guest_GPR2 = freeres_wrapper;
2392 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2393 offsetof(VexGuestPPC64State, guest_GPR2),
2394 sizeof(VG_(threads)[tid].arch.vex.guest_GPR2));
2395 VG_(threads)[tid].arch.vex.guest_GPR12 = freeres_wrapper;
2396 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2397 offsetof(VexGuestPPC64State, guest_GPR12),
2398 sizeof(VG_(threads)[tid].arch.vex.guest_GPR12));
2399 # endif
2400 /* mips-linux note: we need to set t9 */
2401 # if defined(VGP_mips32_linux) || defined(VGP_nanomips_linux)
2402 VG_(threads)[tid].arch.vex.guest_r25 = freeres_wrapper;
2403 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2404 offsetof(VexGuestMIPS32State, guest_r25),
2405 sizeof(VG_(threads)[tid].arch.vex.guest_r25));
2406 # elif defined(VGP_mips64_linux)
2407 VG_(threads)[tid].arch.vex.guest_r25 = freeres_wrapper;
2408 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2409 offsetof(VexGuestMIPS64State, guest_r25),
2410 sizeof(VG_(threads)[tid].arch.vex.guest_r25));
2411 # endif
2413 /* Pass a parameter to freeres_wrapper(). */
2414 # if defined(VGA_x86)
2415 Addr sp = VG_(threads)[tid].arch.vex.guest_ESP;
2416 *((UWord *) sp) = to_run;
2417 VG_TRACK(post_mem_write, Vg_CoreClientReq, tid, sp, sizeof(UWord));
2418 sp = sp - sizeof(UWord);
2419 VG_(threads)[tid].arch.vex.guest_ESP = sp;
2420 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2421 offsetof(VexGuestX86State, guest_ESP),
2422 sizeof(VG_(threads)[tid].arch.vex.guest_ESP));
2423 # elif defined(VGA_amd64)
2424 VG_(threads)[tid].arch.vex.guest_RDI = to_run;
2425 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2426 offsetof(VexGuestAMD64State, guest_RDI),
2427 sizeof(VG_(threads)[tid].arch.vex.guest_RDI));
2428 # elif defined(VGA_arm)
2429 VG_(threads)[tid].arch.vex.guest_R0 = to_run;
2430 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2431 offsetof(VexGuestARMState, guest_R0),
2432 sizeof(VG_(threads)[tid].arch.vex.guest_R0));
2433 # elif defined(VGA_arm64)
2434 VG_(threads)[tid].arch.vex.guest_X0 = to_run;
2435 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2436 offsetof(VexGuestARM64State, guest_X0),
2437 sizeof(VG_(threads)[tid].arch.vex.guest_X0));
2438 # elif defined(VGA_mips32) || defined(VGA_nanomips)
2439 VG_(threads)[tid].arch.vex.guest_r4 = to_run;
2440 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2441 offsetof(VexGuestMIPS32State, guest_r4),
2442 sizeof(VG_(threads)[tid].arch.vex.guest_r4));
2443 # elif defined(VGA_mips64)
2444 VG_(threads)[tid].arch.vex.guest_r4 = to_run;
2445 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2446 offsetof(VexGuestMIPS64State, guest_r4),
2447 sizeof(VG_(threads)[tid].arch.vex.guest_r4));
2448 # elif defined(VGA_ppc32)
2449 VG_(threads)[tid].arch.vex.guest_GPR3 = to_run;
2450 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2451 offsetof(VexGuestPPC32State, guest_GPR3),
2452 sizeof(VG_(threads)[tid].arch.vex.guest_GPR3));
2453 # elif defined(VGA_ppc64be) || defined(VGA_ppc64le)
2454 VG_(threads)[tid].arch.vex.guest_GPR3 = to_run;
2455 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2456 offsetof(VexGuestPPC64State, guest_GPR3),
2457 sizeof(VG_(threads)[tid].arch.vex.guest_GPR3));
2458 # elif defined(VGA_s390x)
2459 VG_(threads)[tid].arch.vex.guest_r2 = to_run;
2460 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2461 offsetof(VexGuestS390XState, guest_r2),
2462 sizeof(VG_(threads)[tid].arch.vex.guest_r2));
2463 #else
2464 I_die_here : architecture missing in m_main.c
2465 #endif
2467 /* Block all blockable signals by copying the real block state into
2468 the thread's block state */
2469 VG_(sigprocmask)(VKI_SIG_BLOCK, NULL, &VG_(threads)[tid].sig_mask);
2470 VG_(threads)[tid].tmp_sig_mask = VG_(threads)[tid].sig_mask;
2472 /* and restore handlers to default. */
2473 VG_(set_default_handler)(VKI_SIGSEGV);
2474 VG_(set_default_handler)(VKI_SIGBUS);
2475 VG_(set_default_handler)(VKI_SIGILL);
2476 VG_(set_default_handler)(VKI_SIGFPE);
2478 // We were exiting, so assert that...
2479 vg_assert(VG_(is_exiting)(tid));
2480 // ...but now we're not again.
2481 VG_(threads)[tid].exitreason = VgSrc_None;
2483 // Run until client thread exits - ideally with FREERES_DONE,
2484 // but exit/exitgroup/signal will do.
2485 VG_(scheduler)(tid);
2487 vg_assert(VG_(is_exiting)(tid));
2488 #endif
2492 /*====================================================================*/
2493 /*=== Getting to main() alive: LINUX ===*/
2494 /*====================================================================*/
2496 #if defined(VGO_linux)
2498 /* If linking of the final executables is done with glibc present,
2499 then Valgrind starts at main() above as usual, and all of the
2500 following code is irrelevant.
2502 However, this is not the intended mode of use. The plan is to
2503 avoid linking against glibc, by giving gcc the flags
2504 -nodefaultlibs -lgcc -nostartfiles at startup.
2506 From this derive two requirements:
2508 1. gcc may emit calls to memcpy, memmove and memset to deal with
2509 structure assignments etc. Since we have chosen to ignore all the
2510 "normal" supporting libraries, we have to provide our own
2511 implementations of them. No problem.
2513 2. We have to provide a symbol "_start", to which the kernel
2514 hands control at startup. Hence the code below.
2517 /* ---------------- Requirement 1 ---------------- */
2519 void* memcpy(void *dest, const void *src, SizeT n);
2520 void* memcpy(void *dest, const void *src, SizeT n) {
2521 return VG_(memcpy)(dest,src,n);
2523 void* memmove(void *dest, const void *src, SizeT n);
2524 void* memmove(void *dest, const void *src, SizeT n) {
2525 return VG_(memmove)(dest,src,n);
2527 void* memset(void *s, int c, SizeT n);
2528 void* memset(void *s, int c, SizeT n) {
2529 return VG_(memset)(s,c,n);
2532 /* BVA: abort() for those platforms that need it (PPC and ARM). */
2533 void abort(void);
2534 void abort(void){
2535 VG_(printf)("Something called raise().\n");
2536 vg_assert(0);
2539 /* EAZG: ARM's EABI will call floating point exception handlers in
2540 libgcc which boil down to an abort or raise, that's usually defined
2541 in libc. Instead, define them here. */
2542 #if defined(VGP_arm_linux)
2544 void raise(void);
2545 void raise(void){
2546 VG_(printf)("Something called raise().\n");
2547 vg_assert(0);
2550 void __aeabi_unwind_cpp_pr0(void);
2551 void __aeabi_unwind_cpp_pr0(void){
2552 VG_(printf)("Something called __aeabi_unwind_cpp_pr0()\n");
2553 vg_assert(0);
2556 void __aeabi_unwind_cpp_pr1(void);
2557 void __aeabi_unwind_cpp_pr1(void){
2558 VG_(printf)("Something called __aeabi_unwind_cpp_pr1()\n");
2559 vg_assert(0);
2562 #endif /* defined(VGP_arm_linux) */
2564 /* Some Android helpers. See bug 368529. */
2565 #if defined(__clang__) \
2566 && (defined(VGPV_arm_linux_android) \
2567 || defined(VGPV_x86_linux_android) \
2568 || defined(VGPV_mips32_linux_android) \
2569 || defined(VGPV_arm64_linux_android))
2571 /* Replace __aeabi_memcpy* functions with vgPlain_memcpy. */
2572 void *__aeabi_memcpy(void *dest, const void *src, SizeT n);
2573 void *__aeabi_memcpy(void *dest, const void *src, SizeT n)
2575 return VG_(memcpy)(dest, src, n);
2578 void *__aeabi_memcpy4(void *dest, const void *src, SizeT n);
2579 void *__aeabi_memcpy4(void *dest, const void *src, SizeT n)
2581 return VG_(memcpy)(dest, src, n);
2584 void *__aeabi_memcpy8(void *dest, const void *src, SizeT n);
2585 void *__aeabi_memcpy8(void *dest, const void *src, SizeT n)
2587 return VG_(memcpy)(dest, src, n);
2590 /* Replace __aeabi_memclr* functions with vgPlain_memset. */
2591 void *__aeabi_memclr(void *dest, SizeT n);
2592 void *__aeabi_memclr(void *dest, SizeT n)
2594 return VG_(memset)(dest, 0, n);
2597 void *__aeabi_memclr4(void *dest, SizeT n);
2598 void *__aeabi_memclr4(void *dest, SizeT n)
2600 return VG_(memset)(dest, 0, n);
2603 void *__aeabi_memclr8(void *dest, SizeT n);
2604 void *__aeabi_memclr8(void *dest, SizeT n)
2606 return VG_(memset)(dest, 0, n);
2608 #endif /* clang and android, basically */
2610 /* ---------------- Requirement 2 ---------------- */
2612 /* Glibc's sysdeps/i386/elf/start.S has the following gem of a
2613 comment, which explains how the stack looks right at process start
2614 (when _start is jumped to). Hence _start passes %esp to
2615 _start_in_C_linux, which extracts argc/argv/envp and starts up
2616 correctly. */
2618 /* This is the canonical entry point, usually the first thing in the text
2619 segment. The SVR4/i386 ABI (pages 3-31, 3-32) says that when the entry
2620 point runs, most registers' values are unspecified, except for:
2622 %edx Contains a function pointer to be registered with `atexit'.
2623 This is how the dynamic linker arranges to have DT_FINI
2624 functions called for shared libraries that have been loaded
2625 before this code runs.
2627 %esp The stack contains the arguments and environment:
2628 0(%esp) argc
2629 4(%esp) argv[0]
2631 (4*argc)(%esp) NULL
2632 (4*(argc+1))(%esp) envp[0]
2634 NULL
2637 /* The kernel hands control to _start, which extracts the initial
2638 stack pointer and calls onwards to _start_in_C_linux. This also switches
2639 the new stack. */
2640 #if defined(VGP_x86_linux)
2641 asm("\n"
2642 ".text\n"
2643 "\t.globl _start\n"
2644 "\t.type _start,@function\n"
2645 "_start:\n"
2646 /* set up the new stack in %eax */
2647 "\tmovl $vgPlain_interim_stack, %eax\n"
2648 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
2649 "\taddl $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %eax\n"
2650 /* allocate at least 16 bytes on the new stack, and aligned */
2651 "\tsubl $16, %eax\n"
2652 "\tandl $~15, %eax\n"
2653 /* install it, and collect the original one */
2654 "\txchgl %eax, %esp\n"
2655 /* call _start_in_C_linux, passing it the startup %esp */
2656 "\tmovl %eax, (%esp)\n"
2657 "\tcall _start_in_C_linux\n"
2658 "\thlt\n"
2659 ".previous\n"
2661 #elif defined(VGP_amd64_linux)
2662 asm("\n"
2663 ".text\n"
2664 "\t.globl _start\n"
2665 "\t.type _start,@function\n"
2666 "_start:\n"
2667 /* set up the new stack in %rdi */
2668 "\tmovq $vgPlain_interim_stack, %rdi\n"
2669 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
2670 "\taddq $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %rdi\n"
2671 "\tandq $~15, %rdi\n"
2672 /* install it, and collect the original one */
2673 "\txchgq %rdi, %rsp\n"
2674 /* call _start_in_C_linux, passing it the startup %rsp */
2675 "\tcall _start_in_C_linux\n"
2676 "\thlt\n"
2677 ".previous\n"
2679 #elif defined(VGP_ppc32_linux)
2680 asm("\n"
2681 ".text\n"
2682 "\t.globl _start\n"
2683 "\t.type _start,@function\n"
2684 "_start:\n"
2685 /* set up the new stack in r16 */
2686 "\tlis 16,vgPlain_interim_stack@ha\n"
2687 "\tla 16,vgPlain_interim_stack@l(16)\n"
2688 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2689 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2690 "\tlis 18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" >> 16)\n"
2691 "\tori 18,18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2692 "\tadd 16,17,16\n"
2693 "\tadd 16,18,16\n"
2694 "\trlwinm 16,16,0,0,27\n"
2695 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2696 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2697 boundary. And r1 is the original SP. Set the SP to r16 and
2698 call _start_in_C_linux, passing it the initial SP. */
2699 "\tmr 3,1\n"
2700 "\tmr 1,16\n"
2701 "\tbl _start_in_C_linux\n"
2702 "\ttrap\n"
2703 ".previous\n"
2705 #elif defined(VGP_ppc64be_linux)
2706 asm("\n"
2707 /* PPC64 ELF ABI says '_start' points to a function descriptor.
2708 So we must have one, and that is what goes into the .opd section. */
2709 "\t.align 2\n"
2710 "\t.global _start\n"
2711 "\t.section \".opd\",\"aw\"\n"
2712 "\t.align 3\n"
2713 "_start:\n"
2714 "\t.quad ._start,.TOC.@tocbase,0\n"
2715 "\t.previous\n"
2716 "\t.type ._start,@function\n"
2717 "\t.global ._start\n"
2718 "._start:\n"
2719 /* set up the new stack in r16 */
2720 "\tlis 16, vgPlain_interim_stack@highest\n"
2721 "\tori 16,16,vgPlain_interim_stack@higher\n"
2722 "\tsldi 16,16,32\n"
2723 "\toris 16,16,vgPlain_interim_stack@h\n"
2724 "\tori 16,16,vgPlain_interim_stack@l\n"
2725 "\txor 17,17,17\n"
2726 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2727 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2728 "\txor 18,18,18\n"
2729 "\tlis 18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" >> 16)\n"
2730 "\tori 18,18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2731 "\tadd 16,17,16\n"
2732 "\tadd 16,18,16\n"
2733 "\trldicr 16,16,0,59\n"
2734 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2735 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2736 boundary. And r1 is the original SP. Set the SP to r16 and
2737 call _start_in_C_linux, passing it the initial SP. */
2738 "\tmr 3,1\n"
2739 "\tmr 1,16\n"
2740 "\tlis 14, _start_in_C_linux@highest\n"
2741 "\tori 14,14,_start_in_C_linux@higher\n"
2742 "\tsldi 14,14,32\n"
2743 "\toris 14,14,_start_in_C_linux@h\n"
2744 "\tori 14,14,_start_in_C_linux@l\n"
2745 "\tld 14,0(14)\n"
2746 "\tmtctr 14\n"
2747 "\tbctrl\n"
2748 "\tnop\n"
2749 "\ttrap\n"
2751 #elif defined(VGP_ppc64le_linux)
2752 /* Little Endian uses ELF version 2 but in the future may also
2753 * support other ELF versions.
2755 asm("\n"
2756 "\t.align 2\n"
2757 "\t.global _start\n"
2758 "\t.type _start,@function\n"
2759 "_start:\n"
2760 "#if _CALL_ELF == 2 \n"
2761 "0: addis 2,12,.TOC.-0b@ha\n"
2762 " addi 2,2,.TOC.-0b@l\n"
2763 " .localentry _start, .-_start\n"
2764 "#endif \n"
2765 /* set up the new stack in r16 */
2766 "\tlis 16, vgPlain_interim_stack@highest\n"
2767 "\tori 16,16,vgPlain_interim_stack@higher\n"
2768 "\tsldi 16,16,32\n"
2769 "\toris 16,16,vgPlain_interim_stack@h\n"
2770 "\tori 16,16,vgPlain_interim_stack@l\n"
2771 "\txor 17,17,17\n"
2772 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2773 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2774 "\txor 18,18,18\n"
2775 "\tlis 18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" >> 16)\n"
2776 "\tori 18,18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2777 "\tadd 16,17,16\n"
2778 "\tadd 16,18,16\n"
2779 "\trldicr 16,16,0,59\n"
2780 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2781 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2782 boundary. And r1 is the original SP. Set the SP to r16 and
2783 call _start_in_C_linux, passing it the initial SP. */
2784 "\tmr 3,1\n"
2785 "\tmr 1,16\n"
2786 "\tlis 14, _start_in_C_linux@highest\n"
2787 "\tori 14,14,_start_in_C_linux@higher\n"
2788 "\tsldi 14,14,32\n"
2789 "\toris 14,14,_start_in_C_linux@h\n"
2790 "\tori 14,14,_start_in_C_linux@l\n"
2791 "\tmtctr 14\n"
2792 "\tbctrl\n"
2793 "\tnop\n"
2794 "\ttrap\n"
2796 #elif defined(VGP_s390x_linux)
2798 This is the canonical entry point, usually the first thing in the text
2799 segment. Most registers' values are unspecified, except for:
2801 %r14 Contains a function pointer to be registered with `atexit'.
2802 This is how the dynamic linker arranges to have DT_FINI
2803 functions called for shared libraries that have been loaded
2804 before this code runs.
2806 %r15 The stack contains the arguments and environment:
2807 0(%r15) argc
2808 8(%r15) argv[0]
2810 (8*argc)(%r15) NULL
2811 (8*(argc+1))(%r15) envp[0]
2813 NULL
2815 asm("\n\t"
2816 ".text\n\t"
2817 ".globl _start\n\t"
2818 ".type _start,@function\n\t"
2819 "_start:\n\t"
2820 /* set up the new stack in %r1 */
2821 "larl %r1, vgPlain_interim_stack\n\t"
2822 "larl %r5, 1f\n\t"
2823 "ag %r1, 0(%r5)\n\t"
2824 "ag %r1, 2f-1f(%r5)\n\t"
2825 "nill %r1, 0xFFF0\n\t"
2826 /* install it, and collect the original one */
2827 "lgr %r2, %r15\n\t"
2828 "lgr %r15, %r1\n\t"
2829 /* call _start_in_C_linux, passing it the startup %r15 */
2830 "brasl %r14, _start_in_C_linux\n\t"
2831 /* trigger execution of an invalid opcode -> halt machine */
2832 "j .+2\n\t"
2833 "1: .quad "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n\t"
2834 "2: .quad "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)"\n\t"
2835 ".previous\n"
2837 #elif defined(VGP_arm_linux)
2838 asm("\n"
2839 "\t.text\n"
2840 "\t.align 4\n"
2841 "\t.type _start,#function\n"
2842 "\t.global _start\n"
2843 "_start:\n"
2844 "\tldr r0, [pc, #36]\n"
2845 "\tldr r1, [pc, #36]\n"
2846 "\tadd r0, r1, r0\n"
2847 "\tldr r1, [pc, #32]\n"
2848 "\tadd r0, r1, r0\n"
2849 "\tmvn r1, #15\n"
2850 "\tand r0, r0, r1\n"
2851 "\tmov r1, sp\n"
2852 "\tmov sp, r0\n"
2853 "\tmov r0, r1\n"
2854 "\tb _start_in_C_linux\n"
2855 "\t.word vgPlain_interim_stack\n"
2856 "\t.word "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
2857 "\t.word "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)"\n"
2859 #elif defined(VGP_arm64_linux)
2860 asm("\n"
2861 "\t.text\n"
2862 "\t.align 2\n"
2863 "\t.type _start,#function\n"
2864 "\t.global _start\n"
2865 "_start:\n"
2866 "\tadrp x0, vgPlain_interim_stack\n"
2867 "\tadd x0, x0, :lo12:vgPlain_interim_stack\n"
2868 // The next 2 assume that VG_STACK_GUARD_SZB fits in 32 bits
2869 "\tmov x1, (("VG_STRINGIFY(VG_STACK_GUARD_SZB)") >> 0) & 0xFFFF\n"
2870 "\tmovk x1, (("VG_STRINGIFY(VG_STACK_GUARD_SZB)") >> 16) & 0xFFFF,"
2871 " lsl 16\n"
2872 "\tadd x0, x0, x1\n"
2873 // The next 2 assume that VG_DEFAULT_STACK_ACTIVE_SZB fits in 32 bits
2874 "\tmov x1, (("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)") >> 0) & 0xFFFF\n"
2875 "\tmovk x1, (("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)") >> 16) & 0xFFFF,"
2876 " lsl 16\n"
2877 "\tadd x0, x0, x1\n"
2878 "\tand x0, x0, -16\n"
2879 "\tmov x1, sp\n"
2880 "\tmov sp, x0\n"
2881 "\tmov x0, x1\n"
2882 "\tb _start_in_C_linux\n"
2884 #elif defined(VGP_mips32_linux)
2885 asm("\n"
2886 "\t.type _gp_disp,@object\n"
2887 ".text\n"
2888 "\t.globl __start\n"
2889 "\t.type __start,@function\n"
2890 "__start:\n"
2892 "\tbal 1f\n"
2893 "\tnop\n"
2895 "1:\n"
2897 "\tlui $28, %hi(_gp_disp)\n"
2898 "\taddiu $28, $28, %lo(_gp_disp)\n"
2899 "\taddu $28, $28, $31\n"
2900 /* t1/$9 <- Addr(interim_stack) */
2901 "\tlui $9, %hi(vgPlain_interim_stack)\n"
2902 /* t1/$9 <- Addr(interim_stack) */
2903 "\taddiu $9, %lo(vgPlain_interim_stack)\n"
2906 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
2907 "\tli $11, "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)"\n"
2909 "\taddu $9, $9, $10\n"
2910 "\taddu $9, $9, $11\n"
2911 "\tli $12, 0xFFFFFFF0\n"
2912 "\tand $9, $9, $12\n"
2913 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2914 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2915 boundary. And $29 is the original SP. Set the SP to t1 and
2916 call _start_in_C, passing it the initial SP. */
2918 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
2919 "\tmove $29, $9\n" // $sp <- t1 (new sp)
2921 "\tlui $25, %hi(_start_in_C_linux)\n"
2922 "\taddiu $25, %lo(_start_in_C_linux)\n"
2924 "\tbal _start_in_C_linux\n"
2925 "\tbreak 0x7\n"
2926 ".previous\n"
2928 #elif defined(VGP_mips64_linux)
2929 asm(
2930 ".text\n"
2931 ".globl __start\n"
2932 ".type __start,@function\n"
2933 "__start:\n"
2934 "\t.set noreorder\n"
2935 "\t.cpload $25\n"
2936 "\t.set reorder\n"
2937 "\t.cprestore 16\n"
2938 "\tlui $9, %hi(vgPlain_interim_stack)\n"
2939 /* t1/$9 <- Addr(interim_stack) */
2940 "\tdaddiu $9, %lo(vgPlain_interim_stack)\n"
2942 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
2943 "\tli $11, "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)"\n"
2945 "\tdaddu $9, $9, $10\n"
2946 "\tdaddu $9, $9, $11\n"
2947 "\tli $12, 0xFFFFFF00\n"
2948 "\tand $9, $9, $12\n"
2949 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2950 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2951 boundary. And $29 is the original SP. Set the SP to t1 and
2952 call _start_in_C, passing it the initial SP. */
2954 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
2955 "\tmove $29, $9\n" // $sp <- t1 (new sp)
2957 "\tlui $9, %highest(_start_in_C_linux)\n"
2958 "\tori $9, %higher(_start_in_C_linux)\n"
2959 "\tdsll32 $9, $9, 0x0\n"
2960 "\tlui $10, %hi(_start_in_C_linux)\n"
2961 "\tdaddiu $10, %lo(_start_in_C_linux)\n"
2962 "\tdaddu $25, $9, $10\n"
2963 "\tjalr $25\n"
2964 "\tnop\n"
2965 ".previous\n"
2967 #elif defined(VGP_nanomips_linux)
2968 asm(
2969 ".text \n\t"
2970 ".globl __start \n\t"
2971 ".type __start,@function \n\t"
2972 "__start: \n\t"
2973 ".set push \n\t"
2974 ".set noreorder \n\t"
2975 "li $t1, vgPlain_interim_stack \n\t"
2976 "li $t0, "VG_STRINGIFY(VG_STACK_GUARD_SZB)" \n\t"
2977 "addu $t1, $t1, $t0 \n\t"
2978 "li $t0, "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)"\n\t"
2979 "addu $t1, $t1, $t0 \n\t"
2980 "li $t0, 0xFFFFFF00 \n\t"
2981 "and $t1, $t1, $t0 \n\t"
2982 "move $a0, $sp \n\t"
2983 "move $sp, $t1 \n\t"
2984 "li $t0, _start_in_C_linux \n\t"
2985 "jrc $t0 \n\t"
2986 "break \n\t"
2987 ".set pop \n\t"
2988 ".previous \n\t"
2990 #else
2991 # error "Unknown linux platform"
2992 #endif
2994 /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
2995 #define _GNU_SOURCE
2996 #define _FILE_OFFSET_BITS 64
2997 /* This is in order to get AT_NULL and AT_PAGESIZE. */
2998 #include <elf.h>
2999 /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
3001 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3002 'static' causes gcc to complain it isn't.
3003 attribute 'used' also ensures the code is not eliminated at link
3004 time */
3005 __attribute__ ((used))
3006 void _start_in_C_linux ( UWord* pArgc );
3007 __attribute__ ((used))
3008 void _start_in_C_linux ( UWord* pArgc )
3010 Int r;
3011 Word argc = pArgc[0];
3012 HChar** argv = (HChar**)&pArgc[1];
3013 HChar** envp = (HChar**)&pArgc[1+argc+1];
3015 // For an inner Valgrind, register the interim stack asap.
3016 // This is needed to allow the outer valgrind to do stacktraces during init.
3017 // Note that this stack is not unregistered when the main thread
3018 // is switching to the (real) stack. Unregistering this would imply
3019 // to save the stack id in a global variable, and have a "if"
3020 // in run_a_thread_NORETURN to do the unregistration only for the
3021 // main thread. This unregistration is not worth this complexity.
3022 INNER_REQUEST
3023 ((void) VALGRIND_STACK_REGISTER
3024 (&VG_(interim_stack).bytes[0],
3025 &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack))));
3027 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3028 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3030 the_iicii.sp_at_startup = (Addr)pArgc;
3032 # if defined(VGP_ppc32_linux) || defined(VGP_ppc64be_linux) \
3033 || defined(VGP_ppc64le_linux) || defined(VGP_arm64_linux) \
3034 || defined(VGP_mips32_linux) || defined(VGP_mips64_linux) \
3035 || defined(VGP_nanomips_linux)
3037 /* ppc32/ppc64, arm64, mips32/64 can be configured with different
3038 page sizes. Determine this early. This is an ugly hack and really
3039 should be moved into valgrind_main. */
3040 UWord *sp = &pArgc[1+argc+1];
3041 while (*sp++ != 0)
3043 for (; *sp != AT_NULL && *sp != AT_PAGESZ; sp += 2);
3044 if (*sp == AT_PAGESZ) {
3045 VKI_PAGE_SIZE = sp[1];
3046 for (VKI_PAGE_SHIFT = 12;
3047 VKI_PAGE_SHIFT <= VKI_MAX_PAGE_SHIFT; VKI_PAGE_SHIFT++)
3048 if (VKI_PAGE_SIZE == (1UL << VKI_PAGE_SHIFT))
3049 break;
3052 # endif
3054 r = valgrind_main( (Int)argc, argv, envp );
3055 /* NOTREACHED */
3056 VG_(exit)(r);
3060 /*====================================================================*/
3061 /*=== Getting to main() alive: darwin ===*/
3062 /*====================================================================*/
3064 #elif defined(VGO_darwin)
3067 Memory layout established by kernel:
3069 0(%esp) argc
3070 4(%esp) argv[0]
3072 argv[argc-1]
3073 NULL
3074 envp[0]
3076 envp[n]
3077 NULL
3078 executable name (presumably, a pointer to it)
3079 NULL
3081 Ditto in the 64-bit case, except all offsets from SP are obviously
3082 twice as large.
3085 /* The kernel hands control to _start, which extracts the initial
3086 stack pointer and calls onwards to _start_in_C_darwin. This also
3087 switches to the new stack. */
3088 #if defined(VGP_x86_darwin)
3089 asm("\n"
3090 ".text\n"
3091 ".align 2,0x90\n"
3092 "\t.globl __start\n"
3093 "__start:\n"
3094 /* set up the new stack in %eax */
3095 "\tmovl $_vgPlain_interim_stack, %eax\n"
3096 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
3097 "\taddl $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %eax\n"
3098 "\tsubl $16, %eax\n"
3099 "\tandl $~15, %eax\n"
3100 /* install it, and collect the original one */
3101 "\txchgl %eax, %esp\n"
3102 "\tsubl $12, %esp\n" // keep stack 16 aligned; see #295428
3103 /* call _start_in_C_darwin, passing it the startup %esp */
3104 "\tpushl %eax\n"
3105 "\tcall __start_in_C_darwin\n"
3106 "\tint $3\n"
3107 "\tint $3\n"
3109 #elif defined(VGP_amd64_darwin)
3110 asm("\n"
3111 ".text\n"
3112 "\t.globl __start\n"
3113 ".align 3,0x90\n"
3114 "__start:\n"
3115 /* set up the new stack in %rdi */
3116 "\tmovabsq $_vgPlain_interim_stack, %rdi\n"
3117 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
3118 "\taddq $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %rdi\n"
3119 "\tandq $~15, %rdi\n"
3120 /* install it, and collect the original one */
3121 "\txchgq %rdi, %rsp\n"
3122 /* call _start_in_C_darwin, passing it the startup %rsp */
3123 "\tcall __start_in_C_darwin\n"
3124 "\tint $3\n"
3125 "\tint $3\n"
3127 #endif
3129 void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2);
3130 void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2) {
3131 // skip check
3132 return VG_(memcpy)(dest,src,n);
3134 void* __memset_chk(void *s, int c, SizeT n, SizeT n2);
3135 void* __memset_chk(void *s, int c, SizeT n, SizeT n2) {
3136 // skip check
3137 return VG_(memset)(s,c,n);
3139 void __bzero(void* s, UWord n);
3140 void __bzero(void* s, UWord n) {
3141 (void)VG_(memset)(s,0,n);
3143 void bzero(void *s, SizeT n);
3144 void bzero(void *s, SizeT n) {
3145 VG_(memset)(s,0,n);
3148 void* memcpy(void *dest, const void *src, SizeT n);
3149 void* memcpy(void *dest, const void *src, SizeT n) {
3150 return VG_(memcpy)(dest,src,n);
3152 void* memset(void *s, int c, SizeT n);
3153 void* memset(void *s, int c, SizeT n) {
3154 return VG_(memset)(s,c,n);
3157 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3158 'static' causes gcc to complain it isn't. */
3159 void _start_in_C_darwin ( UWord* pArgc );
3160 void _start_in_C_darwin ( UWord* pArgc )
3162 Int r;
3163 Int argc = *(Int *)pArgc; // not pArgc[0] on LP64
3164 HChar** argv = (HChar**)&pArgc[1];
3165 HChar** envp = (HChar**)&pArgc[1+argc+1];
3167 // See _start_in_C_linux
3168 INNER_REQUEST
3169 ((void) VALGRIND_STACK_REGISTER
3170 (&VG_(interim_stack).bytes[0],
3171 &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack))));
3173 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3174 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3176 the_iicii.sp_at_startup = (Addr)pArgc;
3178 r = valgrind_main( (Int)argc, argv, envp );
3179 /* NOTREACHED */
3180 VG_(exit)(r);
3183 /*====================================================================*/
3184 /*=== Getting to main() alive: Solaris ===*/
3185 /*====================================================================*/
3186 #elif defined(VGO_solaris)
3187 #if defined(VGP_x86_solaris)
3188 /* The kernel hands control to _start, which extracts the initial stack
3189 pointer and calls onwards to _start_in_C_solaris. This also switches to
3190 the new stack. */
3191 asm("\n"
3192 "\t.text\n"
3193 "\t.globl _start\n"
3194 "\t.type _start, @function\n"
3195 "_start:\n"
3196 /* Set up the new stack in %eax. */
3197 "\tmovl $vgPlain_interim_stack, %eax\n"
3198 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
3199 "\taddl $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %eax\n"
3200 "\tandl $~15, %eax\n"
3201 /* Install it, and collect the original one. */
3202 "\txchgl %eax, %esp\n"
3203 "\tsubl $12, %esp\n" /* Keep stack 16-byte aligned. */
3204 /* Call _start_in_C_solaris, passing it the startup %esp. */
3205 "\tpushl %eax\n"
3206 "\tcall _start_in_C_solaris\n"
3207 /* NOTREACHED */
3208 "\thlt\n"
3209 "\t.previous\n"
3211 #elif defined(VGP_amd64_solaris)
3212 asm("\n"
3213 ".text\n"
3214 "\t.globl _start\n"
3215 "\t.type _start, @function\n"
3216 "_start:\n"
3217 /* Set up the new stack in %rdi. */
3218 "\tmovq $vgPlain_interim_stack, %rdi\n"
3219 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
3220 "\taddq $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %rdi\n"
3221 "\tandq $~15, %rdi\n"
3222 /* Install it, and collect the original one. */
3223 "\txchgq %rdi, %rsp\n"
3224 /* Call _start_in_C_solaris, passing it the startup %rsp. */
3225 "\tcall _start_in_C_solaris\n"
3226 /* NOTREACHED */
3227 "\thlt\n"
3228 ".previous\n"
3230 #else
3231 # error "Unknown Solaris platform"
3232 #endif
3234 void *memcpy(void *dest, const void *src, size_t n);
3235 void *memcpy(void *dest, const void *src, size_t n) {
3236 return VG_(memcpy)(dest, src, n);
3239 __attribute__ ((used))
3240 void _start_in_C_solaris ( UWord* pArgc );
3241 __attribute__ ((used))
3242 void _start_in_C_solaris ( UWord* pArgc )
3244 Int r;
3245 Word argc = pArgc[0];
3246 HChar** argv = (HChar**)&pArgc[1];
3247 HChar** envp = (HChar**)&pArgc[1 + argc + 1];
3249 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3250 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3252 the_iicii.sp_at_startup = (Addr)pArgc;
3254 r = valgrind_main((Int)argc, argv, envp);
3255 /* NOTREACHED */
3256 VG_(exit)(r);
3259 #else
3260 # error "Unknown OS"
3261 #endif
3264 Addr VG_(get_initial_client_SP)( void )
3266 return the_iifii.initial_client_SP;
3269 /*====================================================================*/
3270 /*=== {u,}{div,mod}di3 replacements ===*/
3271 /*====================================================================*/
3273 /* For static linking on x86-darwin, we need to supply our own 64-bit
3274 integer division code, else the link dies thusly:
3276 ld_classic: Undefined symbols:
3277 ___udivdi3
3278 ___umoddi3
3280 #if defined(VGP_x86_darwin)
3282 /* Routines for doing signed/unsigned 64 x 64 ==> 64 div and mod
3283 (udivdi3, umoddi3, divdi3, moddi3) using only 32 x 32 ==> 32
3284 division. Cobbled together from
3286 http://www.hackersdelight.org/HDcode/divlu.c
3287 http://www.hackersdelight.org/HDcode/divls.c
3288 http://www.hackersdelight.org/HDcode/newCode/divDouble.c
3290 The code from those three files is covered by the following license,
3291 as it appears at:
3293 http://www.hackersdelight.org/permissions.htm
3295 You are free to use, copy, and distribute any of the code on
3296 this web site, whether modified by you or not. You need not give
3297 attribution. This includes the algorithms (some of which appear
3298 in Hacker's Delight), the Hacker's Assistant, and any code
3299 submitted by readers. Submitters implicitly agree to this.
3302 /* Long division, unsigned (64/32 ==> 32).
3303 This procedure performs unsigned "long division" i.e., division of a
3304 64-bit unsigned dividend by a 32-bit unsigned divisor, producing a
3305 32-bit quotient. In the overflow cases (divide by 0, or quotient
3306 exceeds 32 bits), it returns a remainder of 0xFFFFFFFF (an impossible
3307 value).
3308 The dividend is u1 and u0, with u1 being the most significant word.
3309 The divisor is parameter v. The value returned is the quotient.
3310 Max line length is 57, to fit in hacker.book. */
3312 static Int nlz32(UInt x)
3314 Int n;
3315 if (x == 0) return(32);
3316 n = 0;
3317 if (x <= 0x0000FFFF) {n = n +16; x = x <<16;}
3318 if (x <= 0x00FFFFFF) {n = n + 8; x = x << 8;}
3319 if (x <= 0x0FFFFFFF) {n = n + 4; x = x << 4;}
3320 if (x <= 0x3FFFFFFF) {n = n + 2; x = x << 2;}
3321 if (x <= 0x7FFFFFFF) {n = n + 1;}
3322 return n;
3325 /* 64 x 32 ==> 32 unsigned division, using only 32 x 32 ==> 32
3326 division as a primitive. */
3327 static UInt divlu2(UInt u1, UInt u0, UInt v, UInt *r)
3329 const UInt b = 65536; // Number base (16 bits).
3330 UInt un1, un0, // Norm. dividend LSD's.
3331 vn1, vn0, // Norm. divisor digits.
3332 q1, q0, // Quotient digits.
3333 un32, un21, un10, // Dividend digit pairs.
3334 rhat; // A remainder.
3335 Int s; // Shift amount for norm.
3337 if (u1 >= v) { // If overflow, set rem.
3338 if (r != NULL) // to an impossible value,
3339 *r = 0xFFFFFFFF; // and return the largest
3340 return 0xFFFFFFFF;} // possible quotient.
3342 s = nlz32(v); // 0 <= s <= 31.
3343 v = v << s; // Normalize divisor.
3344 vn1 = v >> 16; // Break divisor up into
3345 vn0 = v & 0xFFFF; // two 16-bit digits.
3347 un32 = (u1 << s) | ((u0 >> (32 - s)) & (-s >> 31));
3348 un10 = u0 << s; // Shift dividend left.
3350 un1 = un10 >> 16; // Break right half of
3351 un0 = un10 & 0xFFFF; // dividend into two digits.
3353 q1 = un32/vn1; // Compute the first
3354 rhat = un32 - q1*vn1; // quotient digit, q1.
3355 again1:
3356 if (q1 >= b || q1*vn0 > b*rhat + un1) {
3357 q1 = q1 - 1;
3358 rhat = rhat + vn1;
3359 if (rhat < b) goto again1;}
3361 un21 = un32*b + un1 - q1*v; // Multiply and subtract.
3363 q0 = un21/vn1; // Compute the second
3364 rhat = un21 - q0*vn1; // quotient digit, q0.
3365 again2:
3366 if (q0 >= b || q0*vn0 > b*rhat + un0) {
3367 q0 = q0 - 1;
3368 rhat = rhat + vn1;
3369 if (rhat < b) goto again2;}
3371 if (r != NULL) // If remainder is wanted,
3372 *r = (un21*b + un0 - q0*v) >> s; // return it.
3373 return q1*b + q0;
3377 /* 64 x 32 ==> 32 signed division, using only 32 x 32 ==> 32 division
3378 as a primitive. */
3379 static Int divls(Int u1, UInt u0, Int v, Int *r)
3381 Int q, uneg, vneg, diff, borrow;
3383 uneg = u1 >> 31; // -1 if u < 0.
3384 if (uneg) { // Compute the absolute
3385 u0 = -u0; // value of the dividend u.
3386 borrow = (u0 != 0);
3387 u1 = -u1 - borrow;}
3389 vneg = v >> 31; // -1 if v < 0.
3390 v = (v ^ vneg) - vneg; // Absolute value of v.
3392 if ((UInt)u1 >= (UInt)v) goto overflow;
3394 q = divlu2(u1, u0, v, (UInt *)r);
3396 diff = uneg ^ vneg; // Negate q if signs of
3397 q = (q ^ diff) - diff; // u and v differed.
3398 if (uneg && r != NULL)
3399 *r = -*r;
3401 if ((diff ^ q) < 0 && q != 0) { // If overflow,
3402 overflow: // set remainder
3403 if (r != NULL) // to an impossible value,
3404 *r = 0x80000000; // and return the largest
3405 q = 0x80000000;} // possible neg. quotient.
3406 return q;
3411 /* This file contains a program for doing 64/64 ==> 64 division, on a
3412 machine that does not have that instruction but that does have
3413 instructions for "long division" (64/32 ==> 32). Code for unsigned
3414 division is given first, followed by a simple program for doing the
3415 signed version by using the unsigned version.
3416 These programs are useful in implementing "long long" (64-bit)
3417 arithmetic on a machine that has the long division instruction. It will
3418 work on 64- and 32-bit machines, provided the compiler implements long
3419 long's (64-bit integers). It is desirable that the machine have the
3420 Count Leading Zeros instruction.
3421 In the GNU world, these programs are known as __divdi3 and __udivdi3,
3422 and similar names are used here.
3423 This material is not in HD, but may be in a future edition.
3424 Max line length is 57, to fit in hacker.book. */
3427 static Int nlz64(ULong x)
3429 Int n;
3430 if (x == 0) return(64);
3431 n = 0;
3432 if (x <= 0x00000000FFFFFFFFULL) {n = n + 32; x = x << 32;}
3433 if (x <= 0x0000FFFFFFFFFFFFULL) {n = n + 16; x = x << 16;}
3434 if (x <= 0x00FFFFFFFFFFFFFFULL) {n = n + 8; x = x << 8;}
3435 if (x <= 0x0FFFFFFFFFFFFFFFULL) {n = n + 4; x = x << 4;}
3436 if (x <= 0x3FFFFFFFFFFFFFFFULL) {n = n + 2; x = x << 2;}
3437 if (x <= 0x7FFFFFFFFFFFFFFFULL) {n = n + 1;}
3438 return n;
3441 // ---------------------------- udivdi3 --------------------------------
3443 /* The variables u0, u1, etc. take on only 32-bit values, but they
3444 are declared long long to avoid some compiler warning messages and to
3445 avoid some unnecessary EXTRs that the compiler would put in, to
3446 convert long longs to ints.
3448 First the procedure takes care of the case in which the divisor is a
3449 32-bit quantity. There are two subcases: (1) If the left half of the
3450 dividend is less than the divisor, one execution of DIVU is all that
3451 is required (overflow is not possible). (2) Otherwise it does two
3452 divisions, using the grade school method, with variables used as
3453 suggested below.
3455 q1 q0
3456 ________
3457 v) u1 u0
3458 q1*v
3459 ____
3460 k u0 */
3462 /* These macros must be used with arguments of the appropriate type
3463 (unsigned long long for DIVU and long long for DIVS. They are
3464 simulations of the presumed machines ops. I.e., they look at only the
3465 low-order 32 bits of the divisor, they return garbage if the division
3466 overflows, and they return garbage in the high-order half of the
3467 quotient doubleword.
3468 In practice, these would be replaced with uses of the machine's DIVU
3469 and DIVS instructions (e.g., by using the GNU "asm" facility). */
3471 static UInt DIVU ( ULong u, UInt v )
3473 UInt uHi = (UInt)(u >> 32);
3474 UInt uLo = (UInt)u;
3475 return divlu2(uHi, uLo, v, NULL);
3478 static Int DIVS ( Long u, Int v )
3480 Int uHi = (Int)(u >> 32);
3481 UInt uLo = (UInt)u;
3482 return divls(uHi, uLo, v, NULL);
3485 /* 64 x 64 ==> 64 unsigned division, using only 32 x 32 ==> 32
3486 division as a primitive. */
3487 static ULong udivdi3(ULong u, ULong v)
3489 ULong u0, u1, v1, q0, q1, k, n;
3491 if (v >> 32 == 0) { // If v < 2**32:
3492 if (u >> 32 < v) // If u/v cannot overflow,
3493 return DIVU(u, v) // just do one division.
3494 & 0xFFFFFFFF;
3495 else { // If u/v would overflow:
3496 u1 = u >> 32; // Break u up into two
3497 u0 = u & 0xFFFFFFFF; // halves.
3498 q1 = DIVU(u1, v) // First quotient digit.
3499 & 0xFFFFFFFF;
3500 k = u1 - q1*v; // First remainder, < v.
3501 q0 = DIVU((k << 32) + u0, v) // 2nd quot. digit.
3502 & 0xFFFFFFFF;
3503 return (q1 << 32) + q0;
3506 // Here v >= 2**32.
3507 n = nlz64(v); // 0 <= n <= 31.
3508 v1 = (v << n) >> 32; // Normalize the divisor
3509 // so its MSB is 1.
3510 u1 = u >> 1; // To ensure no overflow.
3511 q1 = DIVU(u1, v1) // Get quotient from
3512 & 0xFFFFFFFF; // divide unsigned insn.
3513 q0 = (q1 << n) >> 31; // Undo normalization and
3514 // division of u by 2.
3515 if (q0 != 0) // Make q0 correct or
3516 q0 = q0 - 1; // too small by 1.
3517 if ((u - q0*v) >= v)
3518 q0 = q0 + 1; // Now q0 is correct.
3519 return q0;
3523 // ----------------------------- divdi3 --------------------------------
3525 /* This routine presumes that smallish cases (those which can be done in
3526 one execution of DIVS) are common. If this is not the case, the test for
3527 this case should be deleted.
3528 Note that the test for when DIVS can be used is not entirely
3529 accurate. For example, DIVS is not used if v = 0xFFFFFFFF8000000,
3530 whereas if could be (if u is sufficiently small in magnitude). */
3532 // ------------------------------ cut ----------------------------------
3534 static ULong my_llabs ( Long x )
3536 ULong t = x >> 63;
3537 return (x ^ t) - t;
3540 /* 64 x 64 ==> 64 signed division, using only 32 x 32 ==> 32 division
3541 as a primitive. */
3542 static Long divdi3(Long u, Long v)
3544 ULong au, av;
3545 Long q, t;
3546 au = my_llabs(u);
3547 av = my_llabs(v);
3548 if (av >> 31 == 0) { // If |v| < 2**31 and
3549 // if (v << 32 >> 32 == v) { // If v is in range and
3550 if (au < av << 31) { // |u|/|v| cannot
3551 q = DIVS(u, v); // overflow, use DIVS.
3552 return (q << 32) >> 32;
3555 q = udivdi3(au,av); // Invoke udivdi3.
3556 t = (u ^ v) >> 63; // If u, v have different
3557 return (q ^ t) - t; // signs, negate q.
3560 // ---------------------------- end cut --------------------------------
3562 ULong __udivdi3 (ULong u, ULong v);
3563 ULong __udivdi3 (ULong u, ULong v)
3565 return udivdi3(u,v);
3568 Long __divdi3 (Long u, Long v);
3569 Long __divdi3 (Long u, Long v)
3571 return divdi3(u,v);
3574 ULong __umoddi3 (ULong u, ULong v);
3575 ULong __umoddi3 (ULong u, ULong v)
3577 ULong q = __udivdi3(u, v);
3578 ULong r = u - q * v;
3579 return r;
3582 Long __moddi3 (Long u, Long v);
3583 Long __moddi3 (Long u, Long v)
3585 Long q = __divdi3(u, v);
3586 Long r = u - q * v;
3587 return r;
3590 /* ------------------------------------------------
3591 ld_classic: Undefined symbols:
3592 ___fixunsdfdi
3593 ------------------------------------------------
3596 /* ===-- fixunsdfdi.c - Implement __fixunsdfdi -----------------------------===
3598 * The LLVM Compiler Infrastructure
3600 * This file is dual licensed under the MIT and the University of Illinois Open
3601 * Source Licenses. See LICENSE.TXT for details.
3603 * ===----------------------------------------------------------------------===
3605 * This file implements __fixunsdfdi for the compiler_rt library.
3607 * ===----------------------------------------------------------------------===
3610 /* As per http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses,
3612 the "NCSA/University of Illinois Open Source License" is compatible
3613 with the GPL (both version 2 and 3). What is claimed to be
3614 compatible is this
3616 http://www.opensource.org/licenses/UoI-NCSA.php
3618 and the LLVM documentation at
3620 http://www.llvm.org/docs/DeveloperPolicy.html#license
3622 says all the code in LLVM is available under the University of
3623 Illinois/NCSA Open Source License, at this URL
3625 http://www.opensource.org/licenses/UoI-NCSA.php
3627 viz, the same one that the FSF pages claim is compatible. So I
3628 think it's OK to include it.
3631 /* Returns: convert a to a unsigned long long, rounding toward zero.
3632 * Negative values all become zero.
3635 /* Assumption: double is a IEEE 64 bit floating point type
3636 * du_int is a 64 bit integral type
3637 * value in double is representable in du_int or is negative
3638 * (no range checking performed)
3641 /* seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm */
3643 typedef unsigned long long du_int;
3644 typedef unsigned su_int;
3646 typedef union
3648 du_int all;
3649 struct
3651 #if VG_LITTLEENDIAN
3652 su_int low;
3653 su_int high;
3654 #else
3655 su_int high;
3656 su_int low;
3657 #endif /* VG_LITTLEENDIAN */
3659 } udwords;
3661 typedef union
3663 udwords u;
3664 double f;
3665 } double_bits;
3667 du_int __fixunsdfdi(double a);
3669 du_int
3670 __fixunsdfdi(double a)
3672 double_bits fb;
3673 fb.f = a;
3674 int e = ((fb.u.s.high & 0x7FF00000) >> 20) - 1023;
3675 if (e < 0 || (fb.u.s.high & 0x80000000))
3676 return 0;
3677 udwords r;
3678 r.s.high = (fb.u.s.high & 0x000FFFFF) | 0x00100000;
3679 r.s.low = fb.u.s.low;
3680 if (e > 52)
3681 r.all <<= (e - 52);
3682 else
3683 r.all >>= (52 - e);
3684 return r.all;
3688 #endif
3691 /*====================================================================*/
3692 /*=== Dummy _voucher_mach_msg_set for OSX 10.10 ===*/
3693 /*====================================================================*/
3695 #if defined(VGO_darwin) && DARWIN_VERS >= DARWIN_10_10
3697 /* Builds on MacOSX 10.10+ seem to need this for some reason. */
3698 /* extern boolean_t voucher_mach_msg_set(mach_msg_header_t *msg)
3699 __attribute__((weak_import));
3700 I haven't a clue what the return value means, so just return 0.
3701 Looks like none of the generated uses in the tree look at the
3702 return value anyway.
3704 UWord voucher_mach_msg_set ( UWord arg1 );
3705 UWord voucher_mach_msg_set ( UWord arg1 )
3707 return 0;
3710 #endif
3713 /*--------------------------------------------------------------------*/
3714 /*--- end ---*/
3715 /*--------------------------------------------------------------------*/