syswrap openat2 for all linux arches
[valgrind.git] / coregrind / m_main.c
blobbb4a0ca96e4ef33907ca5eee2b0a3a032bb349b0
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 " available tools are:\n"
91 " memcheck cachegrind callgrind helgrind drd\n"
92 " massif dhat lackey none exp-bbv\n"
93 "\n"
94 " basic user options for all Valgrind tools, with defaults in [ ]:\n"
95 " -h --help show this message\n"
96 " --help-debug show this message, plus debugging options\n"
97 " --help-dyn-options show the dynamically changeable options\n"
98 " --version show version\n"
99 " -q --quiet run silently; only print error msgs\n"
100 " -v --verbose be more verbose -- show misc extra info\n"
101 " --trace-children=no|yes Valgrind-ise child processes (follow execve)? [no]\n"
102 " --trace-children-skip=patt1,patt2,... specifies a list of executables\n"
103 " that --trace-children=yes should not trace into\n"
104 " --trace-children-skip-by-arg=patt1,patt2,... same as --trace-children-skip=\n"
105 " but check the argv[] entries for children, rather\n"
106 " than the exe name, to make a follow/no-follow decision\n"
107 " --child-silent-after-fork=no|yes omit child output between fork & exec? [no]\n"
108 " --vgdb=no|yes|full activate gdbserver? [yes]\n"
109 " full is slower but provides precise watchpoint/step\n"
110 " --vgdb-error=<number> invoke gdbserver after <number> errors [%d]\n"
111 " to get started quickly, use --vgdb-error=0\n"
112 " and follow the on-screen directions\n"
113 " --vgdb-stop-at=event1,event2,... invoke gdbserver for given events [none]\n"
114 " where event is one of:\n"
115 " startup exit abexit valgrindabexit all none\n"
116 " --track-fds=no|yes|all track open file descriptors? [no]\n"
117 " all includes reporting stdin, stdout and stderr\n"
118 " --time-stamp=no|yes add timestamps to log messages? [no]\n"
119 " --log-fd=<number> log messages to file descriptor [2=stderr]\n"
120 " --log-file=<file> log messages to <file>\n"
121 " --log-socket=ipaddr:port log messages to socket ipaddr:port\n"
122 #if defined(VGO_linux)
123 " --enable-debuginfod=no|yes query debuginfod servers for missing\n"
124 " debuginfo [yes]\n"
125 #endif
126 "\n"
127 " user options for Valgrind tools that report errors:\n"
128 " --xml=yes emit error output in XML (some tools only)\n"
129 " --xml-fd=<number> XML output to file descriptor\n"
130 " --xml-file=<file> XML output to <file>\n"
131 " --xml-socket=ipaddr:port XML output to socket ipaddr:port\n"
132 " --xml-user-comment=STR copy STR verbatim into XML output\n"
133 " --demangle=no|yes automatically demangle C++ names? [yes]\n"
134 " --num-callers=<number> show <number> callers in stack traces [12]\n"
135 " --error-limit=no|yes stop showing new errors if too many? [yes]\n"
136 " --exit-on-first-error=no|yes exit code on the first error found? [no]\n"
137 " --error-exitcode=<number> exit code to return if errors found [0=disable]\n"
138 " --error-markers=<begin>,<end> add lines with begin/end markers before/after\n"
139 " each error output in plain text mode [none]\n"
140 " --show-error-list=no|yes show detected errors list and\n"
141 " suppression counts at exit [no]\n"
142 " -s same as --show-error-list=yes\n"
143 " --keep-debuginfo=no|yes Keep symbols etc for unloaded code [no]\n"
144 " This allows saved stack traces (e.g. memory leaks)\n"
145 " to include file/line info for code that has been\n"
146 " dlclose'd (or similar)\n"
147 " --show-below-main=no|yes continue stack traces below main() [no]\n"
148 " --default-suppressions=yes|no\n"
149 " load default suppressions [yes]\n"
150 " --suppressions=<filename> suppress errors described in <filename>\n"
151 " --gen-suppressions=no|yes|all print suppressions for errors? [no]\n"
152 " --input-fd=<number> file descriptor for input [0=stdin]\n"
153 " --dsymutil=no|yes run dsymutil on Mac OS X when helpful? [yes]\n"
154 " --max-stackframe=<number> assume stack switch for SP changes larger\n"
155 " than <number> bytes [2000000]\n"
156 " --main-stacksize=<number> set size of main thread's stack (in bytes)\n"
157 " [min(max(current 'ulimit' value,1MB),16MB)]\n"
158 "\n"
159 " user options for Valgrind tools that replace malloc:\n"
160 " --alignment=<number> set minimum alignment of heap allocations [%s]\n"
161 " --redzone-size=<number> set minimum size of redzones added before/after\n"
162 " heap blocks (in bytes). [%s]\n"
163 " --xtree-memory=none|allocs|full profile heap memory in an xtree [none]\n"
164 " and produces a report at the end of the execution\n"
165 " none: no profiling, allocs: current allocated\n"
166 " size/blocks, full: profile current and cumulative\n"
167 " allocated size/blocks and freed size/blocks.\n"
168 " --xtree-memory-file=<file> xtree memory report file [xtmemory.kcg.%%p]\n"
169 "\n"
170 " uncommon user options for all Valgrind tools:\n"
171 " --fullpath-after= (with nothing after the '=')\n"
172 " show full source paths in call stacks\n"
173 " --fullpath-after=string like --fullpath-after=, but only show the\n"
174 " part of the path after 'string'. Allows removal\n"
175 " of path prefixes. Use this flag multiple times\n"
176 " to specify a set of prefixes to remove.\n"
177 " --extra-debuginfo-path=path absolute path to search for additional\n"
178 " debug symbols, in addition to existing default\n"
179 " well known search paths.\n"
180 " --debuginfo-server=ipaddr:port also query this server\n"
181 " (valgrind-di-server) for debug symbols\n"
182 " --allow-mismatched-debuginfo=no|yes [no]\n"
183 " for the above two flags only, accept debuginfo\n"
184 " objects that don't \"match\" the main object\n"
185 " --smc-check=none|stack|all|all-non-file [all-non-file]\n"
186 " checks for self-modifying code: none, only for\n"
187 " code found in stacks, for all code, or for all\n"
188 " code except that from file-backed mappings\n"
189 " --read-inline-info=yes|no read debug info about inlined function calls\n"
190 " and use it to do better stack traces.\n"
191 " [yes] on Linux/Android/Solaris for the tools\n"
192 " Memcheck/Massif/Helgrind/DRD only.\n"
193 " [no] for all other tools and platforms.\n"
194 " --read-var-info=yes|no read debug info on stack and global variables\n"
195 " and use it to print better error messages in\n"
196 " tools that make use of it (Memcheck, Helgrind,\n"
197 " DRD) [no]\n"
198 " --vgdb-poll=<number> gdbserver poll max every <number> basic blocks [%d] \n"
199 " --vgdb-shadow-registers=no|yes let gdb see the shadow registers [no]\n"
200 " --vgdb-prefix=<prefix> prefix for vgdb FIFOs [%s]\n"
201 " --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]\n"
202 " --run-cxx-freeres=no|yes free up libstdc++ memory at exit on Linux\n"
203 " and Solaris? [yes]\n"
204 " --sim-hints=hint1,hint2,... activate unusual sim behaviours [none] \n"
205 " where hint is one of:\n"
206 " lax-ioctls lax-doors fuse-compatible enable-outer\n"
207 " no-inner-prefix no-nptl-pthread-stackcache fallback-llsc none\n"
208 " --scheduling-quantum=<number> thread-scheduling timeslice in number of\n"
209 " basic blocks [100000]\n"
210 " --fair-sched=no|yes|try schedule threads fairly on multicore systems [no]\n"
211 " --kernel-variant=variant1,variant2,...\n"
212 " handle non-standard kernel variants [none]\n"
213 " where variant is one of:\n"
214 " bproc android-no-hw-tls\n"
215 " android-gpu-sgx5xx android-gpu-adreno3xx none\n"
216 " --merge-recursive-frames=<number> merge frames between identical\n"
217 " program counters in max <number> frames) [0]\n"
218 " --num-transtab-sectors=<number> size of translated code cache [%d]\n"
219 " more sectors may increase performance, but use more memory.\n"
220 " --avg-transtab-entry-size=<number> avg size in bytes of a translated\n"
221 " basic block [0, meaning use tool provided default]\n"
222 " --aspace-minaddr=0xPP avoid mapping memory below 0xPP [guessed]\n"
223 " --valgrind-stacksize=<number> size of valgrind (host) thread's stack\n"
224 " (in bytes) ["
225 VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)
226 "]\n"
227 " --show-emwarns=no|yes show warnings about emulation limits? [no]\n"
228 " --require-text-symbol=:sonamepattern:symbolpattern abort run if the\n"
229 " stated shared object doesn't have the stated\n"
230 " text symbol. Patterns can contain ? and *.\n"
231 " --soname-synonyms=syn1=pattern1,syn2=pattern2,... synonym soname\n"
232 " specify patterns for function wrapping or replacement.\n"
233 " To use a non-libc malloc library that is\n"
234 " in the main exe: --soname-synonyms=somalloc=NONE\n"
235 " in libxyzzy.so: --soname-synonyms=somalloc=libxyzzy.so\n"
236 " --sigill-diagnostics=yes|no warn about illegal instructions? [yes]\n"
237 " --unw-stack-scan-thresh=<number> Enable stack-scan unwind if fewer\n"
238 " than <number> good frames found [0, meaning \"disabled\"]\n"
239 " NOTE: stack scanning is only available on arm-linux.\n"
240 " --unw-stack-scan-frames=<number> Max number of frames that can be\n"
241 " recovered by stack scanning [5]\n"
242 " --resync-filter=no|yes|verbose [yes on MacOS, no on other OSes]\n"
243 " attempt to avoid expensive address-space-resync operations\n"
244 " --max-threads=<number> maximum number of threads that valgrind can\n"
245 " handle [%d]\n"
246 " --realloc-zero-bytes-frees=yes|no [yes on Linux glibc, no otherwise]\n"
247 " should calls to realloc with a size of 0\n"
248 " free memory and return NULL or\n"
249 " allocate/resize and return non-NULL\n"
250 "\n";
252 const HChar usage2[] =
253 "\n"
254 " debugging options for all Valgrind tools:\n"
255 " -d show verbose debugging output\n"
256 " --stats=no|yes show tool and core statistics [no]\n"
257 " --sanity-level=<number> level of sanity checking to do [1]\n"
258 " --trace-flags=<XXXXXXXX> show generated code? (X = 0|1) [00000000]\n"
259 " --profile-flags=<XXXXXXXX> ditto, but for profiling (X = 0|1) [00000000]\n"
260 " --profile-interval=<number> show profile every <number> event checks\n"
261 " [0, meaning only at the end of the run]\n"
262 " --trace-notbelow=<number> only show BBs above <number> [999999999]\n"
263 " --trace-notabove=<number> only show BBs below <number> [0]\n"
264 " --trace-syscalls=no|yes show all system calls? [no]\n"
265 " --trace-signals=no|yes show signal handling details? [no]\n"
266 " --trace-symtab=no|yes show symbol table details? [no]\n"
267 " --trace-symtab-patt=<patt> limit debuginfo tracing to obj name <patt>\n"
268 " --trace-cfi=no|yes show call-frame-info details? [no]\n"
269 " --debug-dump=syms mimic /usr/bin/readelf --syms\n"
270 " --debug-dump=line mimic /usr/bin/readelf --debug-dump=line\n"
271 " --debug-dump=frames mimic /usr/bin/readelf --debug-dump=frames\n"
272 " --trace-redir=no|yes show redirection details? [no]\n"
273 " --trace-sched=no|yes show thread scheduler details? [no]\n"
274 " --profile-heap=no|yes profile Valgrind's own space use\n"
275 " --core-redzone-size=<number> set minimum size of redzones added before/after\n"
276 " heap blocks allocated for Valgrind internal use (in bytes) [4]\n"
277 " --wait-for-gdb=yes|no pause on startup to wait for gdb attach\n"
278 " --sym-offsets=yes|no show syms in form 'name+offset'? [no]\n"
279 " --progress-interval=<number> report progress every <number>\n"
280 " CPU seconds [0, meaning disabled]\n"
281 " --command-line-only=no|yes only use command line options [no]\n\n"
282 " Vex options for all Valgrind tools:\n"
283 " --vex-iropt-verbosity=<0..9> [0]\n"
284 " --vex-iropt-level=<0..2> [2]\n"
285 " --vex-iropt-unroll-thresh=<0..400> [120]\n"
286 " --vex-guest-max-insns=<1..100> [50]\n"
287 " --vex-guest-chase=no|yes [yes]\n"
288 " Precise exception control. Possible values for 'mode' are as follows\n"
289 " and specify the minimum set of registers guaranteed to be correct\n"
290 " immediately prior to memory access instructions:\n"
291 " sp-at-mem-access stack pointer only\n"
292 " unwindregs-at-mem-access registers needed for stack unwinding\n"
293 " allregs-at-mem-access all registers\n"
294 " allregs-at-each-insn all registers are always correct\n"
295 " Default value for all 3 following flags is [unwindregs-at-mem-access].\n"
296 " --vex-iropt-register-updates=mode setting to use by default\n"
297 " --px-default=mode synonym for --vex-iropt-register-updates\n"
298 " --px-file-backed=mode optional setting for file-backed (non-JIT) code\n"
299 " Tracing and profile control:\n"
300 " --trace-flags and --profile-flags values (omit the middle space):\n"
301 " 1000 0000 show conversion into IR\n"
302 " 0100 0000 show after initial opt\n"
303 " 0010 0000 show after instrumentation\n"
304 " 0001 0000 show after second opt\n"
305 " 0000 1000 show after tree building\n"
306 " 0000 0100 show selecting insns\n"
307 " 0000 0010 show after reg-alloc\n"
308 " 0000 0001 show final assembly\n"
309 " 0000 0000 show summary profile only\n"
310 " (Nb: you need --trace-notbelow and/or --trace-notabove\n"
311 " with --trace-flags for full details)\n"
312 " --vex-regalloc-version=2|3 [3]\n"
313 "\n"
314 " debugging options for Valgrind tools that report errors\n"
315 " --dump-error=<number> show translation for basic block associated\n"
316 " with <number>'th error context [0=show none]\n"
317 "\n"
318 " debugging options for Valgrind tools that replace malloc:\n"
319 " --trace-malloc=no|yes show client malloc details? [no]\n"
320 " --xtree-compress-strings=no|yes compress strings in xtree callgrind format [yes]\n"
321 "\n";
323 const HChar usage3[] =
324 "\n"
325 " Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc\n"
326 "\n"
327 " %s is %s\n"
328 " Valgrind is Copyright (C) 2000-2017, and GNU GPL'd, by Julian Seward et al.\n"
329 " LibVEX is Copyright (C) 2004-2017, and GNU GPL'd, by OpenWorks LLP et al.\n"
330 "\n"
331 " Bug reports, feedback, admiration, abuse, etc, to: %s.\n"
332 "\n";
334 const HChar dyn_usage[] =
335 "Some command line settings are \"dynamic\", meaning they can be changed\n"
336 "while Valgrind is running, like this:\n"
337 " From the shell, using vgdb. Example:\n"
338 " $ vgdb \"v.clo --trace-children=yes --child-silent-after-fork=no\"\n"
339 " From a gdb attached to the valgrind gdbserver. Example:\n"
340 " (gdb) monitor v.clo --trace-children=yes --child-silent-after-fork=no\"\n"
341 " From your program, using a client request. Example:\n"
342 " #include <valgrind/valgrind.h>\n"
343 " VALGRIND_CLO_CHANGE(\"--trace-children=yes\");\n"
344 " VALGRIND_CLO_CHANGE(\"--child-silent-after-fork=no\");\n\n";
347 HChar default_alignment[30]; // large enough
348 HChar default_redzone_size[30]; // large enough
350 // Ensure the message goes to stdout
351 VG_(log_output_sink).fd = 1;
352 VG_(log_output_sink).type = VgLogTo_Fd;
354 if (VG_(needs).malloc_replacement) {
355 VG_(sprintf)(default_alignment, "%d", VG_MIN_MALLOC_SZB);
356 VG_(sprintf)(default_redzone_size, "%lu", VG_(tdict).tool_client_redzone_szB);
357 } else {
358 VG_(strcpy)(default_alignment, "not used by this tool");
359 VG_(strcpy)(default_redzone_size, "not used by this tool");
361 if (need_help > 1)
362 /* 'usage1' a type as described after each arg. */
363 VG_(printf)(usage1,
364 VG_(clo_vgdb_error) /* int */,
365 default_alignment /* char* */,
366 default_redzone_size /* char* */,
367 VG_(clo_vgdb_poll) /* int */,
368 VG_(vgdb_prefix_default)() /* char* */,
369 N_SECTORS_DEFAULT /* int */,
370 MAX_THREADS_DEFAULT /* int */
372 if (need_help > 1 && VG_(details).name) {
373 VG_(printf)(" user options for %s:\n", VG_(details).name);
374 if (VG_(needs).command_line_options)
375 VG_TDICT_CALL(tool_print_usage);
376 else
377 VG_(printf)(" (none)\n");
379 if (need_help == 1) {
380 VG_(printf)(dyn_usage);
381 VG_(list_dynamic_options) ();
382 VG_(printf)("valgrind: Use --help for more information.\n");
385 if (need_help > 2) {
386 VG_(printf)("%s", usage2);
388 if (VG_(details).name) {
389 VG_(printf)(" debugging options for %s:\n", VG_(details).name);
391 if (VG_(needs).command_line_options)
392 VG_TDICT_CALL(tool_print_debug_usage);
393 else
394 VG_(printf)(" (none)\n");
397 if (need_help > 1)
398 VG_(printf)(usage3, VG_(details).name, VG_(details).copyright_author,
399 VG_BUGS_TO);
400 VG_(exit)(0);
404 struct process_option_state {
405 /* Whether the user has asked for --version/--help. */
406 Int need_version;
407 Int need_help;
409 /* Whether the user has explicitly provided --sigill-diagnostics
410 or --show-error-list.
411 If not explicitly given depends on general verbosity setting. */
412 Bool sigill_diag_set;
413 Bool show_error_list_set;
415 /* Log to stderr by default, but usage message goes to stdout. XML
416 output is initially disabled. */
417 VgLogTo log_to; // Where is logging output to be sent?
418 VgLogTo xml_to; // Where is XML output to be sent?
419 Int tmp_log_fd;
420 Int tmp_xml_fd;
423 static void process_option (Clo_Mode mode,
424 HChar *arg, struct process_option_state *pos)
426 const HChar* tmp_str; // Used in a couple of places.
427 Int toolname_len = VG_(strlen)(VG_(clo_toolname));
428 HChar* colon = arg;
429 UInt ix = 0;
431 /* Constants for parsing PX control flags. */
432 const HChar* pxStrings[5]
433 = { "sp-at-mem-access", "unwindregs-at-mem-access",
434 "allregs-at-mem-access", "allregs-at-each-insn", NULL };
435 const VexRegisterUpdates pxVals[5]
436 = { VexRegUpdSpAtMemAccess, VexRegUpdUnwindregsAtMemAccess,
437 VexRegUpdAllregsAtMemAccess, VexRegUpdAllregsAtEachInsn, 0/*inval*/ };
439 VG_(set_Clo_Mode) (mode);
441 // Look for a colon in the option name.
442 while (*colon && *colon != ':' && *colon != '=')
443 colon++;
445 // Does it have the form "--toolname:foo"? We have to do it at the start
446 // in case someone has combined a prefix with a core-specific option,
447 // eg. "--memcheck:verbose".
448 if (*colon == ':') {
449 if (VG_STREQN(2, arg, "--") &&
450 VG_STREQN(toolname_len, arg+2, VG_(clo_toolname)) &&
451 VG_STREQN(1, arg+2+toolname_len, ":")) {
452 // Prefix matches, convert "--toolname:foo" to "--foo".
453 // Two things to note:
454 // - We cannot modify the option in-place. If we did, and then
455 // a child was spawned with --trace-children=yes, the
456 // now-non-prefixed option would be passed and could screw up
457 // the child.
458 // - We create copies, and never free them. Why? Non-prefixed
459 // options hang around forever, so tools need not make copies
460 // of strings within them. We need to have the same behaviour
461 // for prefixed options. The pointer to the copy will be lost
462 // once we leave this function (although a tool may keep a
463 // pointer into it), but the space wasted is insignificant.
464 // (In bug #142197, the copies were being freed, which caused
465 // problems for tools that reasonably assumed that arguments
466 // wouldn't disappear on them.)
467 if (0)
468 VG_(printf)("tool-specific arg: %s\n", arg);
469 arg = VG_(strdup)("main.mpclo.1", arg + toolname_len + 1);
470 arg[0] = '-';
471 arg[1] = '-';
473 } else {
474 // prefix doesn't match, declare it as recognised and skip this arg
475 VG_(set_Clo_Recognised) ();
476 return;
480 if VG_XACT_CLOM(cloE, arg, "--version", pos->need_version, 1) {}
481 else if (VG_STREQ_CLOM(cloED, arg, "-v") ||
482 VG_STREQ_CLOM(cloED, arg, "--verbose"))
483 VG_(clo_verbosity)++;
484 else if (VG_STREQ_CLOM(cloED, arg, "-q") ||
485 VG_STREQ_CLOM(cloED, arg, "--quiet"))
486 VG_(clo_verbosity)--;
487 else if VG_XACT_CLOM(cloE, arg, "--help-dyn-options", pos->need_help, 1) {}
488 else if VG_XACT_CLOM(cloE, arg, "-h", pos->need_help, 2) {}
489 else if VG_XACT_CLOM(cloE, arg, "--help", pos->need_help, 2) {}
490 else if VG_XACT_CLOM(cloE, arg, "--help-debug", pos->need_help, 3) {}
492 // The tool has already been determined, but we need to know the name
493 // here.
494 else if VG_STR_CLOM(cloE, arg, "--tool", VG_(clo_toolname)) {}
496 // Set up VG_(clo_max_stackframe) and VG_(clo_main_stacksize).
497 // These are needed by VG_(ii_create_image), which happens
498 // before main_process_cmd_line_options().
499 else if VG_INT_CLOM(cloE, arg, "--max-stackframe", VG_(clo_max_stackframe)) {}
500 else if VG_INT_CLOM(cloE, arg, "--main-stacksize", VG_(clo_main_stacksize)) {}
502 // Set up VG_(clo_max_threads); needed for VG_(tl_pre_clo_init)
503 else if VG_INT_CLOM(cloE, arg, "--max-threads", VG_(clo_max_threads)) {}
505 // Set up VG_(clo_sim_hints). This is needed a.o. for an inner
506 // running in an outer, to have "no-inner-prefix" enabled
507 // as early as possible.
508 else if VG_USETX_CLOM (cloE, arg, "--sim-hints",
509 "lax-ioctls,lax-doors,fuse-compatible,"
510 "enable-outer,no-inner-prefix,"
511 "no-nptl-pthread-stackcache,fallback-llsc",
512 VG_(clo_sim_hints)) {}
514 else if VG_STREQN_CLOM(0, 20, arg, "--command-line-only=") {} // m_commandline.c
515 else if VG_STREQ(arg, "--") {}
516 else if VG_STREQ_CLOM(cloD, arg, "-d") // pre-early + Dynamic
517 VG_(debugLog_startup) (VG_(debugLog_getLevel)() + 1,
518 "dynamic option change");
519 else if VG_STREQN_CLOM(0, 15, arg, "--profile-heap=") {} // pre-early
520 else if VG_STREQN_CLOM(0, 20, arg, "--core-redzone-size=") {} // pre-early
521 else if VG_STREQN_CLOM(0, 15, arg, "--redzone-size=") {} // pre-early
522 else if VG_STREQN_CLOM(0, 17, arg, "--aspace-minaddr=") {} // pre-early
524 else if VG_BINT_CLOM(cloE, arg, "--valgrind-stacksize",
525 VG_(clo_valgrind_stacksize),
526 2*VKI_PAGE_SIZE, 10*VG_DEFAULT_STACK_ACTIVE_SZB)
527 VG_(clo_valgrind_stacksize) = VG_PGROUNDUP(VG_(clo_valgrind_stacksize));
529 /* Obsolete options. Report an error and exit */
530 else if VG_STREQN(34, arg, "--vex-iropt-precise-memory-exns=no") {
531 VG_(fmsg_bad_option)
532 (arg,
533 "--vex-iropt-precise-memory-exns is obsolete\n"
534 "Use --vex-iropt-register-updates=unwindregs-at-mem-access instead\n");
536 else if VG_STREQN(35, arg, "--vex-iropt-precise-memory-exns=yes") {
537 VG_(fmsg_bad_option)
538 (arg,
539 "--vex-iropt-precise-memory-exns is obsolete\n"
540 "Use --vex-iropt-register-updates=allregs-at-mem-access instead\n"
541 " (or --vex-iropt-register-updates=allregs-at-each-insn)\n");
544 /* These options are new, not yet handled by
545 early_process_cmd_line_options. */
546 else if VG_BOOL_CLO(arg, "--sigill-diagnostics", VG_(clo_sigill_diag))
547 pos->sigill_diag_set = True;
549 else if VG_BOOL_CLOM(cloPD, arg, "--stats", VG_(clo_stats)) {}
550 else if VG_BOOL_CLO(arg, "--xml", VG_(clo_xml))
551 VG_(debugLog_setXml)(VG_(clo_xml));
553 else if VG_XACT_CLOM(cloPD, arg, "--vgdb=no", VG_(clo_vgdb), Vg_VgdbNo) {}
554 else if VG_XACT_CLOM(cloPD, arg, "--vgdb=yes", VG_(clo_vgdb), Vg_VgdbYes) {}
555 else if VG_XACT_CLOM(cloPD, arg, "--vgdb=full", VG_(clo_vgdb), Vg_VgdbFull) {
556 /* automatically updates register values at each insn
557 with --vgdb=full */
558 VG_(clo_vex_control).iropt_register_updates_default
559 = VG_(clo_px_file_backed)
560 = VexRegUpdAllregsAtEachInsn;
562 else if VG_INT_CLOM (cloPD, arg, "--vgdb-poll", VG_(clo_vgdb_poll)) {}
563 else if VG_INT_CLOM (cloPD, arg, "--vgdb-error", VG_(clo_vgdb_error)) {}
564 /* --launched-with-multi is an internal option used by vgdb to suppress
565 some output that valgrind normally shows when using --vgdb-error. */
566 else if VG_BOOL_CLO (arg, "--launched-with-multi",
567 VG_(clo_launched_with_multi)) {}
568 else if VG_USET_CLOM (cloPD, arg, "--vgdb-stop-at",
569 "startup,exit,abexit,valgrindabexit",
570 VG_(clo_vgdb_stop_at)) {}
571 else if VG_STR_CLO (arg, "--vgdb-prefix", VG_(clo_vgdb_prefix)) {
572 VG_(arg_vgdb_prefix) = arg;
574 else if VG_BOOL_CLO(arg, "--vgdb-shadow-registers",
575 VG_(clo_vgdb_shadow_registers)) {}
576 else if VG_BOOL_CLO(arg, "--demangle", VG_(clo_demangle)) {}
577 else if VG_STR_CLO (arg, "--soname-synonyms",VG_(clo_soname_synonyms)) {}
578 else if VG_BOOL_CLO(arg, "--error-limit", VG_(clo_error_limit)) {}
579 else if VG_BOOL_CLO(arg, "--exit-on-first-error", VG_(clo_exit_on_first_error)) {}
580 else if VG_INT_CLO (arg, "--error-exitcode", VG_(clo_error_exitcode)) {}
581 else if VG_STR_CLOM (cloPD, arg, "--error-markers", tmp_str) {
582 Int m;
583 const HChar *startpos = tmp_str;
584 const HChar *nextpos;
585 for (m = 0;
586 VG_(Clo_Mode)() != cloE
587 && m < sizeof(VG_(clo_error_markers))
588 /sizeof(VG_(clo_error_markers)[0]);
589 m++) {
590 /* Release previous value if clo given multiple times. */
591 VG_(free)(VG_(clo_error_markers)[m]);
592 VG_(clo_error_markers)[m] = NULL;
594 nextpos = VG_(strchr)(startpos, ',');
595 if (!nextpos)
596 nextpos = startpos + VG_(strlen)(startpos);
597 if (startpos != nextpos) {
598 VG_(clo_error_markers)[m]
599 = VG_(malloc)("main.mpclo.2", nextpos - startpos + 1);
600 VG_(memcpy)(VG_(clo_error_markers)[m], startpos,
601 nextpos - startpos);
602 VG_(clo_error_markers)[m][nextpos - startpos] = '\0';
604 startpos = *nextpos ? nextpos + 1 : nextpos;
607 else if VG_BOOL_CLOM(cloPD, arg, "--show-error-list", VG_(clo_show_error_list)) {
608 pos->show_error_list_set = True; }
609 else if (VG_STREQ_CLOM(cloPD, arg, "-s")) {
610 VG_(clo_show_error_list) = True;
611 pos->show_error_list_set = True;
613 else if VG_BOOL_CLO(arg, "--show-emwarns", VG_(clo_show_emwarns)) {}
615 else if VG_BOOL_CLO(arg, "--run-libc-freeres", VG_(clo_run_libc_freeres)) {}
616 else if VG_BOOL_CLO(arg, "--run-cxx-freeres", VG_(clo_run_cxx_freeres)) {}
617 else if VG_BOOL_CLOM(cloPD, arg, "--show-below-main", VG_(clo_show_below_main)) {}
618 else if VG_BOOL_CLO(arg, "--keep-debuginfo", VG_(clo_keep_debuginfo)) {}
619 #if defined(VGO_linux)
620 else if VG_BOOL_CLO(arg, "--enable-debuginfod", VG_(clo_enable_debuginfod)) {}
621 #endif
622 else if VG_BOOL_CLOM(cloPD, arg, "--time-stamp", VG_(clo_time_stamp)) {}
623 else if VG_STR_CLO(arg, "--track-fds", tmp_str) {
624 if (VG_(strcmp)(tmp_str, "yes") == 0)
625 VG_(clo_track_fds) = 1;
626 else if (VG_(strcmp)(tmp_str, "all") == 0)
627 VG_(clo_track_fds) = 2;
628 else if (VG_(strcmp)(tmp_str, "no") == 0)
629 VG_(clo_track_fds) = 0;
630 else
631 VG_(fmsg_bad_option)(arg,
632 "Bad argument, should be 'yes', 'all' or 'no'\n");
634 else if VG_BOOL_CLOM(cloPD, arg, "--trace-children", VG_(clo_trace_children)) {}
635 else if VG_BOOL_CLOM(cloPD, arg, "--child-silent-after-fork",
636 VG_(clo_child_silent_after_fork)) {}
637 else if VG_INT_CLOM(cloPD, arg, "--scheduling-quantum",
638 VG_(clo_scheduling_quantum)) {}
639 else if VG_STR_CLO(arg, "--fair-sched", tmp_str) {
640 if (VG_(Clo_Mode)() != cloP)
642 else if (VG_(strcmp)(tmp_str, "yes") == 0)
643 VG_(clo_fair_sched) = enable_fair_sched;
644 else if (VG_(strcmp)(tmp_str, "try") == 0)
645 VG_(clo_fair_sched) = try_fair_sched;
646 else if (VG_(strcmp)(tmp_str, "no") == 0)
647 VG_(clo_fair_sched) = disable_fair_sched;
648 else
649 VG_(fmsg_bad_option)(arg,
650 "Bad argument, should be 'yes', 'try' or 'no'\n");
652 else if VG_BOOL_CLOM(cloPD, arg, "--trace-sched", VG_(clo_trace_sched)) {}
653 else if VG_BOOL_CLOM(cloPD, arg, "--trace-signals", VG_(clo_trace_signals)) {}
654 else if VG_BOOL_CLOM(cloPD, arg, "--trace-symtab", VG_(clo_trace_symtab)) {}
655 else if VG_STR_CLO (arg, "--trace-symtab-patt", VG_(clo_trace_symtab_patt)) {}
656 else if VG_BOOL_CLOM(cloPD, arg, "--trace-cfi", VG_(clo_trace_cfi)) {}
657 else if VG_XACT_CLOM(cloPD, arg, "--debug-dump=syms", VG_(clo_debug_dump_syms),
658 True) {}
659 else if VG_XACT_CLOM(cloPD, arg, "--debug-dump=line", VG_(clo_debug_dump_line),
660 True) {}
661 else if VG_XACT_CLOM(cloPD, arg, "--debug-dump=frames",
662 VG_(clo_debug_dump_frames), True) {}
663 else if VG_BOOL_CLOM(cloPD, arg, "--trace-redir", VG_(clo_trace_redir)) {}
665 else if VG_BOOL_CLOM(cloPD, arg, "--trace-syscalls", VG_(clo_trace_syscalls)) {}
666 else if VG_BOOL_CLOM(cloE, arg, "--wait-for-gdb", VG_(clo_wait_for_gdb)) {
667 //--------------------------------------------------------------
668 // Allow GDB attach
669 // p: logging
670 //--------------------------------------------------------------
671 /* Hook to delay things long enough so we can get the pid and
672 attach GDB in another shell. */
673 if (VG_(clo_wait_for_gdb)) {
674 const int ms = 8000; // milliseconds
675 VG_(debugLog)(1, "main", "Wait for GDB during %d ms\n", ms);
676 VG_(printf)("pid=%d, entering delay %d ms loop\n", VG_(getpid)(), ms);
677 VG_(poll)(NULL, 0, ms);
681 else if VG_BOOL_CLOM(cloPD, arg, "--sym-offsets", VG_(clo_sym_offsets)) {}
682 else if VG_BUINT_CLOM(cloPD, arg, "--progress-interval",
683 VG_(clo_progress_interval), 3600) {}
684 else if VG_BOOL_CLO(arg, "--read-inline-info", VG_(clo_read_inline_info)) {}
685 else if VG_BOOL_CLO(arg, "--read-var-info", VG_(clo_read_var_info)) {}
687 else if VG_INT_CLO (arg, "--dump-error", VG_(clo_dump_error)) {}
688 else if VG_INT_CLO (arg, "--input-fd", VG_(clo_input_fd)) {}
689 else if VG_INT_CLO (arg, "--sanity-level", VG_(clo_sanity_level)) {}
690 else if VG_BINT_CLO(arg, "--num-callers", VG_(clo_backtrace_size), 1,
691 VG_DEEPEST_BACKTRACE) {}
692 else if VG_BINT_CLO(arg, "--num-transtab-sectors",
693 VG_(clo_num_transtab_sectors),
694 MIN_N_SECTORS, MAX_N_SECTORS) {}
695 else if VG_BINT_CLO(arg, "--avg-transtab-entry-size",
696 VG_(clo_avg_transtab_entry_size),
697 50, 5000) {}
698 else if VG_BINT_CLOM(cloPD, arg, "--merge-recursive-frames",
699 VG_(clo_merge_recursive_frames), 0,
700 VG_DEEPEST_BACKTRACE) {}
702 else if VG_XACT_CLO(arg, "--smc-check=none",
703 VG_(clo_smc_check), Vg_SmcNone) {}
704 else if VG_XACT_CLO(arg, "--smc-check=stack",
705 VG_(clo_smc_check), Vg_SmcStack) {}
706 else if VG_XACT_CLO(arg, "--smc-check=all",
707 VG_(clo_smc_check), Vg_SmcAll) {}
708 else if VG_XACT_CLO(arg, "--smc-check=all-non-file",
709 VG_(clo_smc_check), Vg_SmcAllNonFile) {}
711 else if VG_USETX_CLO (arg, "--kernel-variant",
712 "bproc,"
713 "android-no-hw-tls,"
714 "android-gpu-sgx5xx,"
715 "android-gpu-adreno3xx",
716 VG_(clo_kernel_variant)) {}
718 else if VG_BOOL_CLO(arg, "--dsymutil", VG_(clo_dsymutil)) {}
720 else if VG_STR_CLO (arg, "--trace-children-skip",
721 VG_(clo_trace_children_skip)) {}
722 else if VG_STR_CLO (arg, "--trace-children-skip-by-arg",
723 VG_(clo_trace_children_skip_by_arg)) {}
725 else if VG_BINT_CLOM(cloPD, arg, "--vex-iropt-verbosity",
726 VG_(clo_vex_control).iropt_verbosity, 0, 10) {}
727 else if VG_BINT_CLO(arg, "--vex-iropt-level",
728 VG_(clo_vex_control).iropt_level, 0, 2) {}
729 else if VG_BINT_CLO(arg, "--vex-regalloc-version",
730 VG_(clo_vex_control).regalloc_version, 2, 3) {}
732 else if (VG_STRINDEX_CLO(arg, "--vex-iropt-register-updates",
733 pxStrings, ix)
734 || VG_STRINDEX_CLO(arg, "--px-default", pxStrings, ix))
735 // NB: --px-default is an alias for the hard-to-remember
736 // --vex-iropt-register-updates, hence the same logic.
738 vg_assert(ix < 4);
739 vg_assert(pxVals[ix] >= VexRegUpdSpAtMemAccess);
740 vg_assert(pxVals[ix] <= VexRegUpdAllregsAtEachInsn);
741 VG_(clo_vex_control).iropt_register_updates_default = pxVals[ix];
744 else if VG_STRINDEX_CLO(arg, "--px-file-backed", pxStrings, ix) {
745 // Whereas --px-file-backed isn't
746 // the same flag as --vex-iropt-register-updates.
747 vg_assert(ix < 4);
748 vg_assert(pxVals[ix] >= VexRegUpdSpAtMemAccess);
749 vg_assert(pxVals[ix] <= VexRegUpdAllregsAtEachInsn);
750 VG_(clo_px_file_backed) = pxVals[ix];
753 else if VG_BINT_CLO(arg, "--vex-iropt-unroll-thresh",
754 VG_(clo_vex_control).iropt_unroll_thresh, 0, 400) {}
755 else if VG_BINT_CLO(arg, "--vex-guest-max-insns",
756 VG_(clo_vex_control).guest_max_insns, 1, 100) {}
757 else if VG_BOOL_CLO(arg, "--vex-guest-chase",
758 VG_(clo_vex_control).guest_chase) {}
760 else if VG_INT_CLO(arg, "--log-fd", pos->tmp_log_fd) {
761 pos->log_to = VgLogTo_Fd;
762 VG_(clo_log_fname_unexpanded) = NULL;
764 else if VG_INT_CLO(arg, "--xml-fd", pos->tmp_xml_fd) {
765 pos->xml_to = VgLogTo_Fd;
766 VG_(clo_xml_fname_unexpanded) = NULL;
769 else if VG_STR_CLO(arg, "--log-file", VG_(clo_log_fname_unexpanded)) {
770 pos->log_to = VgLogTo_File;
772 else if VG_STR_CLO(arg, "--xml-file", VG_(clo_xml_fname_unexpanded)) {
773 pos->xml_to = VgLogTo_File;
776 else if VG_STR_CLO(arg, "--log-socket", VG_(clo_log_fname_unexpanded)) {
777 pos->log_to = VgLogTo_Socket;
779 else if VG_STR_CLO(arg, "--xml-socket", VG_(clo_xml_fname_unexpanded)) {
780 pos->xml_to = VgLogTo_Socket;
783 else if VG_STR_CLO(arg, "--debuginfo-server",
784 VG_(clo_debuginfo_server)) {}
786 else if VG_BOOL_CLO(arg, "--allow-mismatched-debuginfo",
787 VG_(clo_allow_mismatched_debuginfo)) {}
789 else if VG_STR_CLO(arg, "--xml-user-comment",
790 VG_(clo_xml_user_comment)) {}
792 else if VG_BOOL_CLO(arg, "--default-suppressions",
793 VG_(clo_default_supp)) {}
795 else if VG_STR_CLOM(cloPD, arg, "--suppressions", tmp_str) {
796 VG_(add_suppression_file)(tmp_str);
799 else if VG_STR_CLO (arg, "--fullpath-after", tmp_str) {
800 VG_(addToXA)(VG_(clo_fullpath_after), &tmp_str);
803 else if VG_STR_CLO (arg, "--extra-debuginfo-path",
804 VG_(clo_extra_debuginfo_path)) {}
806 else if VG_STR_CLO(arg, "--require-text-symbol", tmp_str) {
807 /* String needs to be of the form C?*C?*, where C is any
808 character, but is the same both times. Having it in this
809 form facilitates finding the boundary between the sopatt
810 and the fnpatt just by looking for the second occurrence
811 of C, without hardwiring any assumption about what C
812 is. */
813 HChar patt[7];
814 Bool ok = True;
815 ok = tmp_str && VG_(strlen)(tmp_str) > 0;
816 if (ok) {
817 patt[0] = patt[3] = tmp_str[0];
818 patt[1] = patt[4] = '?';
819 patt[2] = patt[5] = '*';
820 patt[6] = 0;
821 ok = VG_(string_match)(patt, tmp_str);
823 if (!ok) {
824 VG_(fmsg_bad_option)(arg,
825 "Invalid --require-text-symbol= specification.\n");
827 VG_(addToXA)(VG_(clo_req_tsyms), &tmp_str);
830 /* "stuvwxyz" --> stuvwxyz (binary) */
831 else if VG_STR_CLOM(cloPD, arg, "--trace-flags", tmp_str) {
832 Int j;
833 if (8 != VG_(strlen)(tmp_str)) {
834 VG_(fmsg_bad_option)(arg,
835 "--trace-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_trace_flags) |= (1 << (7-j));
840 else {
841 VG_(fmsg_bad_option)(arg,
842 "--trace-flags argument can only contain 0s and 1s\n");
847 else if VG_INT_CLOM (cloPD, arg, "--trace-notbelow", VG_(clo_trace_notbelow)) {}
849 else if VG_INT_CLOM (cloPD, arg, "--trace-notabove", VG_(clo_trace_notabove)) {}
851 /* "stuvwxyz" --> stuvwxyz (binary) */
852 else if VG_STR_CLOM(cloPD, arg, "--profile-flags", tmp_str) {
853 Int j;
854 if (8 != VG_(strlen)(tmp_str)) {
855 VG_(fmsg_bad_option)(arg,
856 "--profile-flags argument must have 8 digits\n");
858 for (j = 0; j < 8; j++) {
859 if ('0' == tmp_str[j]) { /* do nothing */ }
860 else if ('1' == tmp_str[j]) VG_(clo_profyle_flags) |= (1 << (7-j));
861 else {
862 VG_(fmsg_bad_option)(arg,
863 "--profile-flags argument can only contain 0s and 1s\n");
866 VG_(clo_profyle_sbs) = True;
869 else if VG_INT_CLO (arg, "--profile-interval",
870 VG_(clo_profyle_interval)) {}
872 else if VG_XACT_CLOM(cloPD, arg, "--gen-suppressions=no",
873 VG_(clo_gen_suppressions), 0) {}
874 else if VG_XACT_CLOM(cloPD, arg, "--gen-suppressions=yes",
875 VG_(clo_gen_suppressions), 1) {}
876 else if VG_XACT_CLOM(cloPD, arg, "--gen-suppressions=all",
877 VG_(clo_gen_suppressions), 2) {}
879 else if VG_BINT_CLO(arg, "--unw-stack-scan-thresh",
880 VG_(clo_unw_stack_scan_thresh), 0, 100) {}
881 else if VG_BINT_CLO(arg, "--unw-stack-scan-frames",
882 VG_(clo_unw_stack_scan_frames), 0, 32) {}
884 else if VG_XACT_CLO(arg, "--resync-filter=no",
885 VG_(clo_resync_filter), 0) {}
886 else if VG_XACT_CLO(arg, "--resync-filter=yes",
887 VG_(clo_resync_filter), 1) {}
888 else if VG_XACT_CLO(arg, "--resync-filter=verbose",
889 VG_(clo_resync_filter), 2) {}
891 else if ( VG_(Clo_Mode)() != cloE // tool does not have Early options
892 && !VG_(Clo_Recognised) ()
893 && (! VG_(needs).command_line_options
894 || ! VG_TDICT_CALL(tool_process_cmd_line_option, arg) )) {
895 if (VG_(Clo_Mode)() == cloH)
897 else if (VG_(Clo_Mode)() == cloP && !VG_(Clo_Recognised) ())
898 VG_(fmsg_unknown_option)(arg);
899 else if (VG_(Clo_Mode)() == cloD && !VG_(Clo_Recognised) ())
900 VG_(umsg)("Ignoring dynamic change to unrecognised option %s\n", arg);
904 void VG_(process_dynamic_option) (Clo_Mode mode, HChar *value)
906 struct process_option_state dummy;
907 process_option (mode, value, &dummy);
908 // No need to handle a process_option_state once valgrind has started.
911 /* Peer at previously set up VG_(args_for_valgrind) and do some
912 minimal command line processing that must happen early on:
914 - show the version string, if requested (-v)
915 - extract any request for help (-h --help, --help-dyn-options, --help-debug)
916 - set VG_(toolname) (--tool=)
917 - set VG_(clo_max_stackframe) (--max-stackframe=)
918 - set VG_(clo_main_stacksize) (--main-stacksize=)
919 - set VG_(clo_sim_hints) (--sim-hints=)
920 - set VG_(clo_max_threads) (--max-threads)
922 That's all it does. The main command line processing is done below
923 by main_process_cmd_line_options. Note that
924 main_process_cmd_line_options has to handle but ignore the ones we
925 have handled here.
927 static void early_process_cmd_line_options ( /*OUT*/Int* need_help )
929 UInt i;
930 HChar* str;
931 struct process_option_state pos
932 = {0, 0, False, False, VgLogTo_Fd, VgLogTo_Fd, 2, -1};
934 vg_assert( VG_(args_for_valgrind) );
936 /* parse the options we have (only the options we care about now) */
937 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
939 str = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
940 vg_assert(str);
941 process_option (cloE, str, &pos);
944 if (pos.need_version) {
945 // Nb: the version string goes to stdout.
946 VG_(log_output_sink).fd = 1;
947 VG_(log_output_sink).type = VgLogTo_Fd;
948 if (VG_(clo_verbosity) <= 1)
949 VG_(printf)("valgrind-" VERSION "\n");
950 else
951 VG_(printf)("valgrind-" VERSION "-" VGGIT "\n");
952 VG_(exit)(0);
955 *need_help = pos.need_help;
957 /* For convenience */
958 VG_N_THREADS = VG_(clo_max_threads);
960 # if defined(VGO_solaris) || defined(VGO_darwin)
961 /* Sim hint no-nptl-pthread-stackcache should be ignored. */
962 VG_(clo_sim_hints) &= ~SimHint2S(SimHint_no_nptl_pthread_stackcache);
963 # endif
966 /* The main processing for command line options. See comments above
967 on early_process_cmd_line_options. */
968 static
969 void main_process_cmd_line_options( void )
971 Int i;
972 struct process_option_state pos
973 = {0, 0, False, False, VgLogTo_Fd, VgLogTo_Fd, 2, -1};
975 /* Check for sane path in ./configure --prefix=... */
976 if (VG_LIBDIR[0] != '/')
977 VG_(err_config_error)("Please use absolute paths in "
978 "./configure --prefix=... or --libdir=...\n");
980 vg_assert( VG_(args_for_valgrind) );
982 VG_(clo_suppressions) = VG_(newXA)(VG_(malloc), "main.mpclo.4",
983 VG_(free), sizeof(HChar *));
984 VG_(clo_fullpath_after) = VG_(newXA)(VG_(malloc), "main.mpclo.5",
985 VG_(free), sizeof(HChar *));
986 VG_(clo_req_tsyms) = VG_(newXA)(VG_(malloc), "main.mpclo.6",
987 VG_(free), sizeof(HChar *));
989 /* BEGIN command-line processing loop */
991 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
992 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
993 process_option (cloP, arg, &pos);
996 /* END command-line processing loop. From now on, only dynamically
997 changeable options will have an effect. */
998 VG_(set_Clo_Mode)(cloD);
1000 /* Notify about deprecated features here. */
1002 /* Determine the path prefix for vgdb */
1003 if (VG_(clo_vgdb_prefix) == NULL)
1004 VG_(clo_vgdb_prefix) = VG_(vgdb_prefix_default)();
1006 /* Check various option values */
1008 if (VG_(clo_verbosity) < 0)
1009 VG_(clo_verbosity) = 0;
1011 if (!pos.sigill_diag_set)
1012 VG_(clo_sigill_diag) = (VG_(clo_verbosity) > 0);
1014 if (!pos.show_error_list_set) {
1015 if (VG_(clo_xml))
1016 VG_(clo_show_error_list) = VG_(clo_verbosity) >= 1;
1017 else
1018 VG_(clo_show_error_list) = VG_(clo_verbosity) >= 2;
1021 if (VG_(clo_trace_notbelow) == -1) {
1022 if (VG_(clo_trace_notabove) == -1) {
1023 /* [] */
1024 VG_(clo_trace_notbelow) = 2147483647;
1025 VG_(clo_trace_notabove) = 0;
1026 } else {
1027 /* [0 .. notabove] */
1028 VG_(clo_trace_notbelow) = 0;
1030 } else {
1031 if (VG_(clo_trace_notabove) == -1) {
1032 /* [notbelow .. ] */
1033 VG_(clo_trace_notabove) = 2147483647;
1034 } else {
1035 /* [notbelow .. notabove] */
1039 if (VG_(clo_gen_suppressions) > 0 &&
1040 !VG_(needs).core_errors && !VG_(needs).tool_errors) {
1041 VG_(fmsg_bad_option)("--gen-suppressions=yes",
1042 "Can't use --gen-suppressions= with %s\n"
1043 "because it doesn't generate errors.\n", VG_(details).name);
1045 if ((VG_(clo_exit_on_first_error)) &&
1046 (VG_(clo_error_exitcode)==0)) {
1047 VG_(fmsg_bad_option)("--exit-on-first-error=yes",
1048 "You must define a non nul exit error code, with --error-exitcode=...\n");
1051 # if !defined(VGO_darwin)
1052 if (VG_(clo_resync_filter) != 0) {
1053 VG_(fmsg_bad_option)("--resync-filter=yes or =verbose",
1054 "--resync-filter= is only available on MacOS X.\n");
1055 /*NOTREACHED*/
1057 # endif
1059 /* If XML output is requested, check that the tool actually
1060 supports it. */
1061 if (VG_(clo_xml) && !VG_(needs).xml_output) {
1062 VG_(clo_xml) = False;
1063 VG_(fmsg_bad_option)("--xml=yes",
1064 "%s does not support XML output.\n", VG_(details).name);
1065 /*NOTREACHED*/
1068 vg_assert( VG_(clo_gen_suppressions) >= 0 );
1069 vg_assert( VG_(clo_gen_suppressions) <= 2 );
1071 /* If we've been asked to emit XML, mash around various other
1072 options so as to constrain the output somewhat, and to remove
1073 any need for user input during the run.
1075 if (VG_(clo_xml)) {
1077 /* We can't allow --gen-suppressions=yes, since that requires us
1078 to print the error and then ask the user if she wants a
1079 suppression for it, but in XML mode we won't print it until
1080 we know whether we also need to print a suppression. Hence a
1081 circular dependency. So disallow this.
1082 (--gen-suppressions=all is still OK since we don't need any
1083 user interaction in this case.) */
1084 if (VG_(clo_gen_suppressions) == 1) {
1085 VG_(fmsg_bad_option)(
1086 "--xml=yes together with --gen-suppressions=yes",
1087 "When --xml=yes is specified, --gen-suppressions=no\n"
1088 "or --gen-suppressions=all is allowed, but not "
1089 "--gen-suppressions=yes.\n");
1092 /* Disallow dump_error in XML mode; sounds like a recipe for
1093 chaos. No big deal; dump_error is a flag for debugging V
1094 itself. */
1095 if (VG_(clo_dump_error) > 0) {
1096 VG_(fmsg_bad_option)("--xml=yes",
1097 "Cannot be used together with --dump-error");
1100 /* Disable error limits (this might be a bad idea!) */
1101 VG_(clo_error_limit) = False;
1102 /* Disable emulation warnings */
1104 /* Also, we want to set options for the leak checker, but that
1105 will have to be done in Memcheck's flag-handling code, not
1106 here. */
1109 /* All non-logging-related options have been checked. If the logging
1110 option specified is ok, we can switch to it, as we know we won't
1111 have to generate any other command-line-related error messages.
1112 (So far we should be still attached to stderr, so we can show on
1113 the terminal any problems to do with processing command line
1114 opts.) */
1115 VG_(init_log_xml_sinks)(pos.log_to, pos.xml_to,
1116 pos.tmp_log_fd, pos.tmp_xml_fd);
1118 /* Register child at-fork handler which will take care of handling
1119 --child-silent-after-fork clo and also reopening output sinks for forked
1120 children, if requested via --log|xml-file= options. */
1121 VG_(atfork)(NULL, NULL, VG_(logging_atfork_child));
1123 // Suppressions related stuff
1125 if (VG_(clo_default_supp) &&
1126 (VG_(needs).core_errors || VG_(needs).tool_errors)) {
1127 /* If loading default is enabled, add it to the supp list. */
1128 static const HChar default_supp[] = "default.supp";
1129 Int len = VG_(strlen)(VG_(libdir)) + 1 + sizeof(default_supp);
1130 HChar *buf = VG_(malloc)("main.mpclo.3", len);
1131 VG_(sprintf)(buf, "%s/%s", VG_(libdir), default_supp);
1132 VG_(add_suppression_file)(buf);
1133 VG_(free)(buf);
1138 /*====================================================================*/
1139 /*=== File descriptor setup ===*/
1140 /*====================================================================*/
1142 /* Number of file descriptors that Valgrind tries to reserve for
1143 its own use - just a small constant. */
1144 #define N_RESERVED_FDS (12)
1146 static void setup_file_descriptors(void)
1148 struct vki_rlimit rl;
1149 Bool show = False;
1151 /* Get the current file descriptor limits. */
1152 if (VG_(getrlimit)(VKI_RLIMIT_NOFILE, &rl) < 0) {
1153 rl.rlim_cur = 1024;
1154 rl.rlim_max = 1024;
1157 # if defined(VGO_darwin)
1158 /* Darwin lies. It reports file max as RLIM_INFINITY but
1159 silently disallows anything bigger than 10240. */
1160 if (rl.rlim_cur >= 10240 && rl.rlim_max == 0x7fffffffffffffffULL) {
1161 rl.rlim_max = 10240;
1163 # endif
1165 if (show)
1166 VG_(printf)("fd limits: host, before: cur %llu max %llu\n",
1167 (ULong)rl.rlim_cur, (ULong)rl.rlim_max);
1169 /* Work out where to move the soft limit to. */
1170 if (rl.rlim_cur + N_RESERVED_FDS <= rl.rlim_max) {
1171 rl.rlim_cur = rl.rlim_cur + N_RESERVED_FDS;
1172 } else {
1173 rl.rlim_cur = rl.rlim_max;
1176 /* Reserve some file descriptors for our use. */
1177 VG_(fd_soft_limit) = rl.rlim_cur - N_RESERVED_FDS;
1178 VG_(fd_hard_limit) = rl.rlim_cur - N_RESERVED_FDS;
1180 /* Update the soft limit. */
1181 VG_(setrlimit)(VKI_RLIMIT_NOFILE, &rl);
1183 if (show) {
1184 VG_(printf)("fd limits: host, after: cur %lu max %lu\n",
1185 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
1186 VG_(printf)("fd limits: guest : cur %d max %d\n",
1187 VG_(fd_soft_limit), VG_(fd_hard_limit));
1190 if (VG_(cl_exec_fd) != -1)
1191 VG_(cl_exec_fd) = VG_(safe_fd)( VG_(cl_exec_fd) );
1195 /*====================================================================*/
1196 /*=== main() ===*/
1197 /*====================================================================*/
1199 /* When main() is entered, we should be on the following stack, not
1200 the one the kernel gave us. We will run on this stack until
1201 simulation of the root thread is started, at which point a transfer
1202 is made to a dynamically allocated stack. This is for the sake of
1203 uniform overflow detection for all Valgrind threads. This is
1204 marked global even though it isn't, because assembly code below
1205 needs to reference the name. */
1207 /*static*/ struct {
1208 HChar bytes [VG_STACK_GUARD_SZB + VG_DEFAULT_STACK_ACTIVE_SZB + VG_STACK_GUARD_SZB];
1209 } VG_(interim_stack);
1211 /* These are the structures used to hold info for creating the initial
1212 client image.
1214 'iicii' mostly holds important register state present at system
1215 startup (_start_valgrind). valgrind_main() then fills in the rest
1216 of it and passes it to VG_(ii_create_image)(). That produces
1217 'iifii', which is later handed to VG_(ii_finalise_image). */
1219 /* In all OS-instantiations, the_iicii has a field .sp_at_startup.
1220 This should get some address inside the stack on which we gained
1221 control (eg, it could be the SP at startup). It doesn't matter
1222 exactly where in the stack it is. This value is passed to the
1223 address space manager at startup. On Linux, aspacem then uses it
1224 to identify the initial stack segment and hence the upper end of
1225 the usable address space. */
1227 static IICreateImageInfo the_iicii;
1228 static IIFinaliseImageInfo the_iifii;
1231 /* A simple pair structure, used for conveying debuginfo handles to
1232 calls to VG_TRACK(new_mem_startup, ...). */
1233 typedef struct { Addr a; ULong ull; } Addr_n_ULong;
1236 /* --- Forwards decls to do with shutdown --- */
1238 static void final_tidyup(ThreadId tid);
1240 /* Do everything which needs doing when the last thread exits */
1241 static
1242 void shutdown_actions_NORETURN( ThreadId tid,
1243 VgSchedReturnCode tids_schedretcode );
1245 /* --- end of Forwards decls to do with shutdown --- */
1248 /* By the time we get to valgrind_main, the_iicii should already have
1249 been filled in with any important details as required by whatever
1250 OS we have been built for.
1252 static
1253 Int valgrind_main ( Int argc, HChar **argv, HChar **envp )
1255 Int need_help;
1256 ThreadId tid_main = VG_INVALID_THREADID;
1257 Int loglevel, i;
1258 XArray* addr2dihandle = NULL;
1260 //============================================================
1262 // Nb: startup is complex. Prerequisites are shown at every step.
1263 // *** Be very careful when messing with the order ***
1265 // The first order of business is to get debug logging, the address
1266 // space manager and the dynamic memory manager up and running.
1267 // Once that's done, we can relax a bit.
1269 //============================================================
1271 /* This is needed to make VG_(getenv) usable early. */
1272 VG_(client_envp) = (HChar**)envp;
1274 //--------------------------------------------------------------
1275 // Start up Mach kernel interface, if any
1276 // p: none
1277 //--------------------------------------------------------------
1278 # if defined(VGO_darwin)
1279 VG_(mach_init)();
1280 # endif
1282 //--------------------------------------------------------------
1283 // Start up the logging mechanism
1284 // p: none
1285 //--------------------------------------------------------------
1286 /* Start the debugging-log system ASAP. First find out how many
1287 "-d"s were specified. This is a pre-scan of the command line. Also
1288 get --profile-heap=yes, --core-redzone-size, --redzone-size
1289 --aspace-minaddr which are needed by the time we start up dynamic
1290 memory management. */
1291 loglevel = 0;
1292 for (i = 1; i < argc; i++) {
1293 const HChar* tmp_str;
1294 if (argv[i][0] != '-') break;
1295 if VG_STREQ(argv[i], "--") break;
1296 if VG_STREQ(argv[i], "-d") loglevel++;
1297 if VG_BOOL_CLOM(cloE, argv[i], "--profile-heap", VG_(clo_profile_heap)) {}
1298 if VG_BINT_CLOM(cloE, argv[i], "--core-redzone-size", VG_(clo_core_redzone_size),
1299 0, MAX_CLO_REDZONE_SZB) {}
1300 if VG_BINT_CLOM(cloE, argv[i], "--redzone-size", VG_(clo_redzone_size),
1301 0, MAX_CLO_REDZONE_SZB) {}
1302 if VG_STR_CLOM(cloE, argv[i], "--aspace-minaddr", tmp_str) {
1303 Bool ok = VG_(parse_Addr) (&tmp_str, &VG_(clo_aspacem_minAddr));
1304 if (!ok)
1305 VG_(fmsg_bad_option)(argv[i], "Invalid address\n");
1306 const HChar *errmsg;
1307 if (!VG_(am_is_valid_for_aspacem_minAddr)(VG_(clo_aspacem_minAddr),
1308 &errmsg))
1309 VG_(fmsg_bad_option)(argv[i], "%s\n", errmsg);
1313 /* ... and start the debug logger. Now we can safely emit logging
1314 messages all through startup. */
1315 VG_(debugLog_startup)(loglevel, "Stage 2 (main)");
1316 VG_(debugLog)(1, "main", "Welcome to Valgrind version "
1317 VERSION " debug logging\n");
1319 //--------------------------------------------------------------
1320 // Ensure we're on a plausible stack.
1321 // p: logging
1322 //--------------------------------------------------------------
1323 VG_(debugLog)(1, "main", "Checking current stack is plausible\n");
1324 { HChar* limLo = (HChar*)(&VG_(interim_stack).bytes[0]);
1325 HChar* limHi = limLo + sizeof(VG_(interim_stack));
1326 HChar* volatile
1327 aLocal = (HChar*)&limLo; /* any auto local will do */
1328 /* Re "volatile": Apple clang version 4.0
1329 (tags/Apple/clang-421.0.57) (based on LLVM 3.1svn)" appeared
1330 to miscompile the following check, causing run to abort at
1331 this point (in 64-bit mode) even though aLocal is within limLo
1332 .. limHi. But in fact clang is within its rights to do
1333 strange things here. "The reason is that the comparisons
1334 aLocal < limLo and aLocal >= limHi cause undefined behaviour
1335 (according to c99 6.5.8) because they compare pointers that do
1336 not point into the same aggregate." Adding "volatile" appears
1337 to fix it because "The compiler would have to prove that there
1338 is undefined behavior in order to exploit it. But as a
1339 volatile variable can change its value in ways invisible to
1340 the compiler, the compiler must make the conservative
1341 assumption that it points into the same aggregate as the other
1342 pointer its compared against. I.e. the behaviour is possibly
1343 defined." (Analysis by Florian Krohm). */
1344 if (aLocal < limLo || aLocal >= limHi) {
1345 /* something's wrong. Stop. */
1346 VG_(debugLog)(0, "main", "Root stack %p to %p, a local %p\n",
1347 limLo, limHi, aLocal );
1348 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1349 "Initial stack switched failed.\n");
1350 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1351 VG_(exit)(1);
1355 //--------------------------------------------------------------
1356 // Ensure we have a plausible pointer to the stack on which
1357 // we gained control (not the current stack!)
1358 // p: logging
1359 //--------------------------------------------------------------
1360 VG_(debugLog)(1, "main", "Checking initial stack was noted\n");
1361 if (the_iicii.sp_at_startup == 0) {
1362 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1363 "Initial stack was not noted.\n");
1364 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1365 VG_(exit)(1);
1368 #if defined(VGO_freebsd)
1369 Int val;
1370 SizeT len = sizeof(val);
1371 //--------------------------------------------------------------
1372 // FreeBSD check security.bsd.unprivileged_proc_debug sysctl
1373 // This needs to be done before aspacemgr starts, otherwise that
1374 // will fail with mysterious error codes
1375 //--------------------------------------------------------------
1376 Int error = VG_(sysctlbyname)("security.bsd.unprivileged_proc_debug", &val, &len, 0, 0);
1377 if (error != -1 && val != 1) {
1378 VG_(debugLog)(0, "main", "Valgrind: FATAL:\n");
1379 VG_(debugLog)(0, "main", "security.bsd.unprivileged_proc_debug sysctl is 0.\n");
1380 VG_(debugLog)(0, "main", " Set this sysctl with\n");
1381 VG_(debugLog)(0, "main", " 'sysctl security.bsd.unprivileged_proc_debug=1'.\n");
1382 VG_(debugLog)(0, "main", " Cannot continue.\n");
1384 VG_(exit)(1);
1386 #endif
1389 //--------------------------------------------------------------
1390 // Start up the address space manager, and determine the
1391 // approximate location of the client's stack
1392 // p: logging, plausible-stack
1393 //--------------------------------------------------------------
1394 VG_(debugLog)(1, "main", "Starting the address space manager\n");
1395 vg_assert(VKI_PAGE_SIZE == 4096 || VKI_PAGE_SIZE == 8192
1396 || VKI_PAGE_SIZE == 16384 || VKI_PAGE_SIZE == 32768
1397 || VKI_PAGE_SIZE == 65536);
1398 vg_assert(VKI_MAX_PAGE_SIZE == 4096 || VKI_MAX_PAGE_SIZE == 8192
1399 || VKI_MAX_PAGE_SIZE == 16384 || VKI_MAX_PAGE_SIZE == 32768
1400 || VKI_MAX_PAGE_SIZE == 65536);
1401 vg_assert(VKI_PAGE_SIZE <= VKI_MAX_PAGE_SIZE);
1402 vg_assert(VKI_PAGE_SIZE == (1 << VKI_PAGE_SHIFT));
1403 vg_assert(VKI_MAX_PAGE_SIZE == (1 << VKI_MAX_PAGE_SHIFT));
1404 the_iicii.clstack_end = VG_(am_startup)( the_iicii.sp_at_startup );
1405 VG_(debugLog)(1, "main", "Address space manager is running\n");
1407 //--------------------------------------------------------------
1408 // Start up the dynamic memory manager
1409 // p: address space management
1410 // p: getting --profile-heap,--core-redzone-size,--redzone-size
1411 // In fact m_mallocfree is self-initialising, so there's no
1412 // initialisation call to do. Instead, try a simple malloc/
1413 // free pair right now to check that nothing is broken.
1414 //--------------------------------------------------------------
1415 VG_(debugLog)(1, "main", "Starting the dynamic memory manager\n");
1416 { void* p = VG_(malloc)( "main.vm.1", 12345 );
1417 VG_(free)( p );
1419 VG_(debugLog)(1, "main", "Dynamic memory manager is running\n");
1421 //============================================================
1423 // Dynamic memory management is now available.
1425 //============================================================
1427 //--------------------------------------------------------------
1428 // Initialise m_debuginfo
1429 // p: dynamic memory allocation
1430 VG_(debugLog)(1, "main", "Initialise m_debuginfo\n");
1431 VG_(di_initialise)();
1433 //--------------------------------------------------------------
1434 // Look for alternative libdir
1435 { HChar *cp = VG_(getenv)(VALGRIND_LIB);
1436 if (cp != NULL)
1437 VG_(libdir) = cp;
1438 VG_(debugLog)(1, "main", "VG_(libdir) = %s\n", VG_(libdir));
1441 //--------------------------------------------------------------
1442 // Extract the launcher name from the environment.
1443 VG_(debugLog)(1, "main", "Getting launcher's name ...\n");
1444 VG_(name_of_launcher) = VG_(getenv)(VALGRIND_LAUNCHER);
1445 if (VG_(name_of_launcher) == NULL) {
1446 VG_(printf)("valgrind: You cannot run '%s' directly.\n", argv[0]);
1447 VG_(printf)("valgrind: You should use $prefix/bin/valgrind.\n");
1448 VG_(exit)(1);
1450 VG_(debugLog)(1, "main", "... %s\n", VG_(name_of_launcher));
1452 //--------------------------------------------------------------
1453 // We used to set the process datasize rlimit to zero to prevent
1454 // any internal use of brk() from having any effect. But later
1455 // linux kernels redefine RLIMIT_DATA as the size of any data
1456 // areas, including some dynamic mmap memory allocations.
1457 // See bug #357833 for the commit that went into linux 4.5
1458 // changing the definition of RLIMIT_DATA. So don't mess with
1459 // RLIMIT_DATA here now anymore. Just remember it for use in
1460 // the syscall wrappers.
1461 VG_(getrlimit)(VKI_RLIMIT_DATA, &VG_(client_rlimit_data));
1463 // Get the current process stack rlimit.
1464 VG_(getrlimit)(VKI_RLIMIT_STACK, &VG_(client_rlimit_stack));
1466 //--------------------------------------------------------------
1467 // Figure out what sort of CPU we're on, and whether it is
1468 // able to run V.
1469 /* The vex_archinfo structure is passed down later to the client
1470 * to verify the HW info settings are consistent.
1472 VexArchInfo vex_archinfo;
1473 VG_(debugLog)(1, "main", "Get hardware capabilities ...\n");
1474 { VexArch vex_arch;
1475 Bool ok = VG_(machine_get_hwcaps)();
1476 if (!ok) {
1477 VG_(printf)("\n");
1478 VG_(printf)("valgrind: fatal error: unsupported CPU.\n");
1479 VG_(printf)(" Supported CPUs are:\n");
1480 VG_(printf)(" * x86 (practically any; Pentium-I or above), "
1481 "AMD Athlon or above)\n");
1482 VG_(printf)(" * AMD Athlon64/Opteron\n");
1483 VG_(printf)(" * ARM (armv7)\n");
1484 VG_(printf)(" * MIPS (mips32 and above; mips64 and above)\n");
1485 VG_(printf)(" * PowerPC (most; ppc405 and above)\n");
1486 VG_(printf)(" * System z (64bit only - s390x; z990 and above)\n");
1487 VG_(printf)("\n");
1488 VG_(exit)(1);
1490 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
1491 VG_(debugLog)(
1492 1, "main", "... arch = %s, hwcaps = %s\n",
1493 LibVEX_ppVexArch ( vex_arch ),
1494 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1498 //--------------------------------------------------------------
1499 // Record the working directory at startup
1500 // p: none
1501 VG_(debugLog)(1, "main", "Getting the working directory at startup\n");
1502 VG_(record_startup_wd)();
1503 const HChar *wd = VG_(get_startup_wd)();
1504 VG_(debugLog)(1, "main", "... %s\n", wd != NULL ? wd : "<NO CWD>" );
1506 //============================================================
1507 // Command line argument handling order:
1508 // * If --help/--help-debug are present, show usage message
1509 // (including the tool-specific usage)
1510 // * (If no --tool option given, default to Memcheck)
1511 // * Then, if client is missing, abort with error msg
1512 // * Then, if any cmdline args are bad, abort with error msg
1513 //============================================================
1515 //--------------------------------------------------------------
1516 // Split up argv into: C args, V args, V extra args, and exename.
1517 // p: dynamic memory allocation
1518 //--------------------------------------------------------------
1519 VG_(debugLog)(1, "main", "Split up command line\n");
1520 VG_(split_up_argv)( argc, argv );
1521 vg_assert( VG_(args_for_valgrind) );
1522 vg_assert( VG_(args_for_client) );
1523 if (0) {
1524 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++)
1525 VG_(printf)(
1526 "varg %s\n",
1527 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1529 VG_(printf)(" exe %s\n", VG_(args_the_exename));
1530 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++)
1531 VG_(printf)(
1532 "carg %s\n",
1533 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1537 //--------------------------------------------------------------
1538 // Extract tool name and whether help has been requested.
1539 // Note we can't print the help message yet, even if requested,
1540 // because the tool has not been initialised.
1541 // p: split_up_argv [for VG_(args_for_valgrind)]
1542 //--------------------------------------------------------------
1543 VG_(debugLog)(1, "main",
1544 "(early_) Process Valgrind's command line options\n");
1545 early_process_cmd_line_options(&need_help);
1547 // BEGIN HACK
1548 // When changing the logic for the VG_(clo_read_inline_info) default,
1549 // the manual and --help output have to be changed accordingly.
1550 vg_assert(VG_(clo_toolname) != NULL);
1551 vg_assert(VG_(clo_read_inline_info) == False);
1552 # if !defined(VGO_darwin)
1553 if (0 == VG_(strcmp)(VG_(clo_toolname), "memcheck")
1554 || 0 == VG_(strcmp)(VG_(clo_toolname), "helgrind")
1555 || 0 == VG_(strcmp)(VG_(clo_toolname), "drd")
1556 || 0 == VG_(strcmp)(VG_(clo_toolname), "massif")
1557 || 0 == VG_(strcmp)(VG_(clo_toolname), "dhat")) {
1558 /* Change the default setting. Later on (just below)
1559 main_process_cmd_line_options should pick up any
1560 user-supplied setting for it and will override the default
1561 set here. */
1562 VG_(clo_read_inline_info) = True;
1564 # endif
1565 // END HACK
1567 // Set default vex control params.
1568 LibVEX_default_VexControl(& VG_(clo_vex_control));
1570 //--------------------------------------------------------------
1571 // Load client executable, finding in $PATH if necessary
1572 // p: early_process_cmd_line_options() [for 'exec', 'need_help',
1573 // clo_max_stackframe,
1574 // clo_main_stacksize]
1575 // p: layout_remaining_space [so there's space]
1577 // Set up client's environment
1578 // p: set-libdir [for VG_(libdir)]
1579 // p: early_process_cmd_line_options [for VG_(clo_toolname)]
1581 // Setup client stack, eip, and VG_(client_arg[cv])
1582 // p: load_client() [for 'info']
1583 // p: fix_environment() [for 'env']
1585 // Setup client data (brk) segment. Initially a 1-page segment
1586 // which abuts a shrinkable reservation.
1587 // p: load_client() [for 'info' and hence VG_(brk_base)]
1589 // p: _start_in_C (for zeroing out the_iicii and putting some
1590 // initial values into it)
1591 //--------------------------------------------------------------
1592 if (!need_help) {
1593 VG_(debugLog)(1, "main", "Create initial image\n");
1595 # if defined(VGO_linux) || defined(VGO_darwin) || defined(VGO_solaris) || defined(VGO_freebsd)
1596 the_iicii.argv = argv;
1597 the_iicii.envp = envp;
1598 the_iicii.toolname = VG_(clo_toolname);
1599 # else
1600 # error "Unknown platform"
1601 # endif
1603 /* NOTE: this call reads VG_(clo_main_stacksize). */
1604 the_iifii = VG_(ii_create_image)( the_iicii, &vex_archinfo );
1607 //==============================================================
1609 // Finished loading/setting up the client address space.
1611 //==============================================================
1613 //--------------------------------------------------------------
1614 // setup file descriptors
1615 // p: n/a
1616 //--------------------------------------------------------------
1617 VG_(debugLog)(1, "main", "Setup file descriptors\n");
1618 setup_file_descriptors();
1620 //--------------------------------------------------------------
1621 // create fake /proc/<pid>/cmdline and /proc/<pid>/auxv files
1622 // and then unlink them, but hold onto the fds, so we can handr
1623 // them out to the client when it tries to open
1624 // /proc/<pid>/cmdline or /proc/<pid>/auxv for itself.
1625 // p: setup file descriptors
1626 // p: ii_create_image for VG_(client_auxv) setup.
1627 //--------------------------------------------------------------
1628 VG_(cl_cmdline_fd) = -1;
1629 VG_(cl_auxv_fd) = -1;
1630 #if defined(VGO_solaris)
1631 VG_(cl_psinfo_fd) = -1;
1632 #endif
1634 #if defined(VGO_linux) || defined(VGO_solaris)
1635 if (!need_help) {
1636 HChar buf[50]; // large enough
1637 HChar buf2[VG_(mkstemp_fullname_bufsz)(sizeof buf - 1)];
1638 Int fd, r;
1640 #if defined(VGO_linux) || defined(SOLARIS_PROC_CMDLINE)
1641 /* Fake /proc/<pid>/cmdline only on Linux and Solaris if supported. */
1642 HChar nul[1];
1643 const HChar* exename;
1645 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/cmdline\n");
1647 VG_(sprintf)(buf, "proc_%d_cmdline", VG_(getpid)());
1648 fd = VG_(mkstemp)( buf, buf2 );
1649 if (fd == -1)
1650 VG_(err_config_error)("Can't create client cmdline file in %s\n", buf2);
1652 nul[0] = 0;
1653 exename = VG_(args_the_exename);
1654 VG_(write)(fd, exename, VG_(strlen)( exename ));
1655 VG_(write)(fd, nul, 1);
1657 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1658 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i );
1659 VG_(write)(fd, arg, VG_(strlen)( arg ));
1660 VG_(write)(fd, nul, 1);
1663 /* Don't bother to seek the file back to the start; instead do
1664 it every time a copy of it is given out (by PRE(sys_open) or
1665 PRE(sys_openat)). That is probably more robust across fork() etc. */
1667 /* Now delete it, but hang on to the fd. */
1668 r = VG_(unlink)( buf2 );
1669 if (r)
1670 VG_(err_config_error)("Can't delete client cmdline file in %s\n", buf2);
1672 VG_(cl_cmdline_fd) = fd;
1673 #endif // defined(VGO_linux) || defined(SOLARIS_PROC_CMDLINE)
1675 /* Fake /proc/<pid>/auxv on both Linux and Solaris. */
1676 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/auxv\n");
1678 VG_(sprintf)(buf, "proc_%d_auxv", VG_(getpid)());
1679 fd = VG_(mkstemp)( buf, buf2 );
1680 if (fd == -1)
1681 VG_(err_config_error)("Can't create client auxv file in %s\n", buf2);
1683 UWord *client_auxv = VG_(client_auxv);
1684 unsigned int client_auxv_len = 0;
1685 while (*client_auxv != 0) {
1686 client_auxv++;
1687 client_auxv++;
1688 client_auxv_len += 2 * sizeof(UWord);
1690 client_auxv_len += 2 * sizeof(UWord);
1692 VG_(write)(fd, VG_(client_auxv), client_auxv_len);
1694 /* Don't bother to seek the file back to the start; instead do
1695 it every time a copy of it is given out (by PRE(sys_open)).
1696 That is probably more robust across fork() etc. */
1698 /* Now delete it, but hang on to the fd. */
1699 r = VG_(unlink)( buf2 );
1700 if (r)
1701 VG_(err_config_error)("Can't delete client auxv file in %s\n", buf2);
1703 VG_(cl_auxv_fd) = fd;
1705 #if defined(VGO_solaris)
1706 /* Fake /proc/<pid>/psinfo on Solaris.
1707 * Contents will be fetched and partially faked later on the fly. */
1708 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/psinfo\n");
1710 VG_(sprintf)(buf, "proc_%d_psinfo", VG_(getpid)());
1711 fd = VG_(mkstemp)( buf, buf2 );
1712 if (fd == -1)
1713 VG_(err_config_error)("Can't create client psinfo file in %s\n", buf2);
1715 /* Now delete it, but hang on to the fd. */
1716 r = VG_(unlink)( buf2 );
1717 if (r)
1718 VG_(err_config_error)("Can't delete client psinfo file in %s\n", buf2);
1720 VG_(cl_psinfo_fd) = fd;
1721 #endif /* VGO_solaris */
1723 #endif
1725 #if defined(VGO_freebsd)
1726 /* On FreeBSD /proc is optional
1727 * Most functionality is accessed through sysctl instead */
1728 if (!need_help) {
1729 struct vg_stat statbuf;
1730 SysRes statres = VG_(stat)("/proc", &statbuf);
1731 if (!sr_isError(statres) || VKI_S_ISLNK(statbuf.mode)) {
1732 VG_(have_slash_proc) = True;
1734 // each directory contains the following that might get read
1735 // file - a symlink to the exe
1736 // cmdline - null separate command line
1737 // etype - the executable type e.g., FreeBSD ELF64 (same for guest and host)
1738 // map - a memory map, tricky to synthesize
1739 // rlimit - list of process limits
1740 // status - process, pid, ppid pts cty uid gid and some other stuff
1742 #endif
1744 //--------------------------------------------------------------
1745 // Init tool part 1: pre_clo_init
1746 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1747 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1748 //--------------------------------------------------------------
1749 VG_(debugLog)(1, "main", "Initialise the tool part 1 (pre_clo_init)\n");
1750 VG_(tl_pre_clo_init)();
1751 // Activate var info readers, if the tool asked for it:
1752 if (VG_(needs).var_info)
1753 VG_(clo_read_var_info) = True;
1755 //--------------------------------------------------------------
1756 // If --tool and --help/--help-debug was given, now give the core+tool
1757 // help message
1758 // p: early_process_cmd_line_options() [for 'need_help']
1759 // p: tl_pre_clo_init [for 'VG_(tdict).usage']
1760 //--------------------------------------------------------------
1761 VG_(debugLog)(1, "main", "Print help and quit, if requested\n");
1762 if (need_help) {
1763 usage_NORETURN(need_help);
1766 //--------------------------------------------------------------
1767 // Process command line options to Valgrind + tool
1768 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1769 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1770 //--------------------------------------------------------------
1771 VG_(debugLog)(1, "main",
1772 "(main_) Process Valgrind's command line options, "
1773 "setup logging\n");
1774 main_process_cmd_line_options();
1776 //--------------------------------------------------------------
1777 // Zeroise the millisecond counter by doing a first read of it.
1778 // p: none
1779 //--------------------------------------------------------------
1780 (void) VG_(read_millisecond_timer)();
1782 //--------------------------------------------------------------
1783 // Print the preamble
1784 // p: tl_pre_clo_init [for 'VG_(details).name' and friends]
1785 // p: main_process_cmd_line_options()
1786 // [for VG_(clo_verbosity), VG_(clo_xml)]
1787 //--------------------------------------------------------------
1788 VG_(debugLog)(1, "main", "Print the preamble...\n");
1789 VG_(print_preamble)(VG_(log_output_sink).type != VgLogTo_File);
1790 VG_(debugLog)(1, "main", "...finished the preamble\n");
1792 //--------------------------------------------------------------
1793 // Init tool part 2: post_clo_init
1794 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1795 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1796 // p: print_preamble() [so any warnings printed in post_clo_init
1797 // are shown after the preamble]
1798 //--------------------------------------------------------------
1799 VG_(debugLog)(1, "main", "Initialise the tool part 2 (post_clo_init)\n");
1800 VG_TDICT_CALL(tool_post_clo_init);
1802 /* The tool's "needs" will by now be finalised, since it has no
1803 further opportunity to specify them. So now sanity check
1804 and finish initialising the needs. */
1805 const HChar* s;
1806 Bool ok;
1807 ok = VG_(finish_needs_init)( &s );
1808 if (!ok) {
1809 VG_(core_panic)(s);
1813 //--------------------------------------------------------------
1814 // Initialise translation table and translation cache
1815 // p: aspacem [??]
1816 // p: tl_pre_clo_init [for 'VG_(details).avg_translation_sizeB']
1817 //--------------------------------------------------------------
1818 VG_(debugLog)(1, "main", "Initialise TT/TC\n");
1819 VG_(init_tt_tc)();
1821 //--------------------------------------------------------------
1822 // Initialise the redirect table.
1823 // p: init_tt_tc [so it can call VG_(search_transtab) safely]
1824 // p: aspacem [so can change ownership of sysinfo pages]
1825 //--------------------------------------------------------------
1826 VG_(debugLog)(1, "main", "Initialise redirects\n");
1827 VG_(redir_initialise)();
1829 //--------------------------------------------------------------
1830 // Search for file descriptors that are inherited from our parent
1831 // p: main_process_cmd_line_options [for VG_(clo_track_fds)]
1832 //--------------------------------------------------------------
1833 if (VG_(clo_track_fds)) {
1834 VG_(debugLog)(1, "main", "Init preopened fds\n");
1835 VG_(init_preopened_fds)();
1838 #if defined(VGO_solaris)
1839 VG_(syswrap_init)();
1840 #endif
1842 //--------------------------------------------------------------
1843 // Load debug info for the existing segments.
1844 // p: setup_code_redirect_table [so that redirs can be recorded]
1845 // p: mallocfree
1846 // p: probably: setup fds and process CLOs, so that logging works
1847 // p: initialise m_debuginfo
1849 // While doing this, make a note of the debuginfo-handles that
1850 // come back from VG_(di_notify_mmap).
1851 // Later, in "Tell the tool about the initial client memory permissions"
1852 // (just below) we can then hand these handles off to the tool in
1853 // calls to VG_TRACK(new_mem_startup, ...). This gives the tool the
1854 // opportunity to make further queries to m_debuginfo before the
1855 // client is started, if it wants. We put this information into an
1856 // XArray, each handle along with the associated segment start address,
1857 // and search the XArray for the handles later, when calling
1858 // VG_TRACK(new_mem_startup, ...).
1859 //--------------------------------------------------------------
1860 VG_(debugLog)(1, "main", "Load initial debug info\n");
1862 vg_assert(!addr2dihandle);
1863 addr2dihandle = VG_(newXA)( VG_(malloc), "main.vm.2",
1864 VG_(free), sizeof(Addr_n_ULong) );
1866 # if defined(VGO_linux) || defined(VGO_solaris) || defined(VGO_freebsd)
1867 { Addr* seg_starts;
1868 Int n_seg_starts;
1869 Addr_n_ULong anu;
1871 seg_starts = VG_(get_segment_starts)( SkFileC | SkFileV, &n_seg_starts );
1872 vg_assert(seg_starts && n_seg_starts >= 0);
1874 /* show them all to the debug info reader. allow_SkFileV has to
1875 be True here so that we read info from the valgrind executable
1876 itself. */
1877 for (i = 0; i < n_seg_starts; i++) {
1878 anu.ull = VG_(di_notify_mmap)( seg_starts[i], True/*allow_SkFileV*/,
1879 -1/*Don't use_fd*/);
1880 /* anu.ull holds the debuginfo handle returned by di_notify_mmap,
1881 if any. */
1882 if (anu.ull > 0) {
1883 anu.a = seg_starts[i];
1884 VG_(addToXA)( addr2dihandle, &anu );
1888 VG_(free)( seg_starts );
1890 # elif defined(VGO_darwin)
1891 { Addr* seg_starts;
1892 Int n_seg_starts;
1893 seg_starts = VG_(get_segment_starts)( SkFileC, &n_seg_starts );
1894 vg_assert(seg_starts && n_seg_starts >= 0);
1896 /* show them all to the debug info reader.
1897 Don't read from V segments (unlike Linux) */
1898 // GrP fixme really?
1899 for (i = 0; i < n_seg_starts; i++) {
1900 VG_(di_notify_mmap)( seg_starts[i], False/*don't allow_SkFileV*/,
1901 -1/*don't use_fd*/);
1904 VG_(free)( seg_starts );
1906 # else
1907 # error Unknown OS
1908 # endif
1910 //--------------------------------------------------------------
1911 // Tell aspacem of ownership change of the asm helpers, so that
1912 // m_translate allows them to be translated. However, only do this
1913 // after the initial debug info read, since making a hole in the
1914 // address range for the stage2 binary confuses the debug info reader.
1915 // p: aspacem
1916 //--------------------------------------------------------------
1917 { Bool change_ownership_v_c_OK;
1918 Addr co_start = VG_PGROUNDDN( (Addr)&VG_(trampoline_stuff_start) );
1919 Addr co_endPlus = VG_PGROUNDUP( (Addr)&VG_(trampoline_stuff_end) );
1920 VG_(debugLog)(1,"redir",
1921 "transfer ownership V -> C of 0x%llx .. 0x%llx\n",
1922 (ULong)co_start, (ULong)co_endPlus-1 );
1924 change_ownership_v_c_OK
1925 = VG_(am_change_ownership_v_to_c)( co_start, co_endPlus - co_start );
1926 vg_assert(change_ownership_v_c_OK);
1929 if (VG_(clo_xml)) {
1930 HChar buf[50]; // large enough
1931 VG_(elapsed_wallclock_time)(buf, sizeof buf);
1932 VG_(printf_xml)( "<status>\n"
1933 " <state>RUNNING</state>\n"
1934 " <time>%pS</time>\n"
1935 "</status>\n",
1936 buf );
1937 VG_(printf_xml)( "\n" );
1940 VG_(init_Threads)();
1942 //--------------------------------------------------------------
1943 // Initialise the scheduler (phase 1) [generates tid_main]
1944 // p: none, afaics
1945 //--------------------------------------------------------------
1946 VG_(debugLog)(1, "main", "Initialise scheduler (phase 1)\n");
1947 tid_main = VG_(scheduler_init_phase1)();
1948 vg_assert(tid_main < VG_N_THREADS
1949 && tid_main != VG_INVALID_THREADID);
1950 /* Tell the tool about tid_main */
1951 VG_TRACK( pre_thread_ll_create, VG_INVALID_THREADID, tid_main );
1953 //--------------------------------------------------------------
1954 // Tell the tool about the initial client memory permissions
1955 // p: aspacem
1956 // p: mallocfree
1957 // p: setup_client_stack
1958 // p: setup_client_dataseg
1960 // For each segment we tell the client about, look up in
1961 // addr2dihandle as created above, to see if there's a debuginfo
1962 // handle associated with the segment, that we can hand along
1963 // to the tool, to be helpful.
1964 //--------------------------------------------------------------
1965 VG_(debugLog)(1, "main", "Tell tool about initial permissions\n");
1966 { Addr* seg_starts;
1967 Int n_seg_starts;
1969 vg_assert(addr2dihandle);
1971 /* Mark the main thread as running while we tell the tool about
1972 the client memory so that the tool can associate that memory
1973 with the main thread. */
1974 vg_assert(VG_(running_tid) == VG_INVALID_THREADID);
1975 VG_(running_tid) = tid_main;
1977 seg_starts = VG_(get_segment_starts)( SkFileC | SkAnonC | SkShmC,
1978 &n_seg_starts );
1979 vg_assert(seg_starts && n_seg_starts >= 0);
1981 /* Show client segments to the tool */
1982 for (i = 0; i < n_seg_starts; i++) {
1983 Word j, n;
1984 NSegment const* seg
1985 = VG_(am_find_nsegment)( seg_starts[i] );
1986 vg_assert(seg);
1987 vg_assert(seg->kind == SkFileC || seg->kind == SkAnonC ||
1988 seg->kind == SkShmC);
1989 vg_assert(seg->start == seg_starts[i]);
1991 VG_(debugLog)(2, "main",
1992 "tell tool about %010lx-%010lx %c%c%c\n",
1993 seg->start, seg->end,
1994 seg->hasR ? 'r' : '-',
1995 seg->hasW ? 'w' : '-',
1996 seg->hasX ? 'x' : '-' );
1997 /* search addr2dihandle to see if we have an entry
1998 matching seg->start. */
1999 n = VG_(sizeXA)( addr2dihandle );
2000 for (j = 0; j < n; j++) {
2001 Addr_n_ULong* anl = VG_(indexXA)( addr2dihandle, j );
2002 if (anl->a == seg->start) {
2003 vg_assert(anl->ull > 0); /* check it's a valid handle */
2004 break;
2007 vg_assert(j >= 0 && j <= n);
2008 VG_TRACK( new_mem_startup, seg->start, seg->end+1-seg->start,
2009 seg->hasR, seg->hasW, seg->hasX,
2010 /* and the retrieved debuginfo handle, if any */
2011 j < n
2012 ? ((Addr_n_ULong*)VG_(indexXA)( addr2dihandle, j ))->ull
2013 : 0 );
2017 VG_(free)( seg_starts );
2018 VG_(deleteXA)( addr2dihandle );
2020 /* Also do the initial stack permissions. */
2022 SSizeT inaccessible_len;
2023 NSegment const* seg
2024 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
2025 vg_assert(seg);
2026 vg_assert(seg->kind == SkAnonC);
2027 vg_assert(the_iifii.initial_client_SP >= seg->start);
2028 vg_assert(the_iifii.initial_client_SP <= seg->end);
2030 /* Stuff below the initial SP is unaddressable. Take into
2031 account any ABI-mandated space below the stack pointer that
2032 is required (VG_STACK_REDZONE_SZB). setup_client_stack()
2033 will have allocated an extra page if a red zone is required,
2034 to be on the safe side. */
2035 inaccessible_len = the_iifii.initial_client_SP - VG_STACK_REDZONE_SZB
2036 - seg->start;
2037 vg_assert(inaccessible_len >= 0);
2038 if (inaccessible_len > 0)
2039 VG_TRACK( die_mem_stack,
2040 seg->start,
2041 inaccessible_len );
2042 VG_(debugLog)(2, "main", "mark stack inaccessible %010lx-%010lx\n",
2043 seg->start,
2044 the_iifii.initial_client_SP-1 - VG_STACK_REDZONE_SZB);
2047 /* Also the assembly helpers. */
2048 VG_TRACK( new_mem_startup,
2049 (Addr)&VG_(trampoline_stuff_start),
2050 (Addr)&VG_(trampoline_stuff_end)
2051 - (Addr)&VG_(trampoline_stuff_start),
2052 False, /* readable? */
2053 False, /* writable? */
2054 True /* executable? */,
2055 0 /* di_handle: no associated debug info */ );
2057 /* Darwin only: tell the tools where the client's kernel commpage
2058 is. It would be better to do this by telling aspacemgr about
2059 it -- see the now disused record_system_memory() in
2060 initimg-darwin.c -- but that causes the sync checker to fail,
2061 since the mapping doesn't appear in the kernel-supplied
2062 process map. So do it here instead. */
2063 # if defined(VGP_amd64_darwin)
2064 VG_TRACK( new_mem_startup,
2065 0x7fffffe00000, 0x7ffffffff000-0x7fffffe00000,
2066 True, False, True, /* r-x */
2067 0 /* di_handle: no associated debug info */ );
2068 # elif defined(VGP_x86_darwin)
2069 VG_TRACK( new_mem_startup,
2070 0xfffec000, 0xfffff000-0xfffec000,
2071 True, False, True, /* r-x */
2072 0 /* di_handle: no associated debug info */ );
2073 # endif
2075 /* Clear the running thread indicator */
2076 VG_(running_tid) = VG_INVALID_THREADID;
2077 vg_assert(VG_(running_tid) == VG_INVALID_THREADID);
2080 //--------------------------------------------------------------
2081 // Initialise the scheduler (phase 2)
2082 // p: Initialise the scheduler (phase 1) [for tid_main]
2083 // p: setup_file_descriptors() [else VG_(safe_fd)() breaks]
2084 // p: setup_client_stack
2085 //--------------------------------------------------------------
2086 VG_(debugLog)(1, "main", "Initialise scheduler (phase 2)\n");
2087 { NSegment const* seg
2088 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
2089 vg_assert(seg);
2090 vg_assert(seg->kind == SkAnonC);
2091 vg_assert(the_iifii.initial_client_SP >= seg->start);
2092 vg_assert(the_iifii.initial_client_SP <= seg->end);
2093 VG_(scheduler_init_phase2)( tid_main,
2094 seg->end, the_iifii.clstack_max_size );
2097 //--------------------------------------------------------------
2098 // Set up state for the root thread
2099 // p: ?
2100 // setup_scheduler() [for sched-specific thread 1 stuff]
2101 // VG_(ii_create_image) [for 'the_iicii' initial info]
2102 //--------------------------------------------------------------
2103 VG_(debugLog)(1, "main", "Finalise initial image\n");
2104 { /* Mark the main thread as running while we tell the tool about
2105 the client memory which could be tracked during initial image
2106 finalisation. So the tool can associate that memory with the
2107 main thread. */
2108 vg_assert(VG_(running_tid) == VG_INVALID_THREADID);
2109 VG_(running_tid) = tid_main;
2111 VG_(ii_finalise_image)( the_iifii );
2113 /* Clear the running thread indicator */
2114 VG_(running_tid) = VG_INVALID_THREADID;
2115 vg_assert(VG_(running_tid) == VG_INVALID_THREADID);
2118 //--------------------------------------------------------------
2119 // Initialise the signal handling subsystem
2120 // p: n/a
2121 //--------------------------------------------------------------
2122 // Nb: temporarily parks the saved blocking-mask in saved_sigmask.
2123 VG_(debugLog)(1, "main", "Initialise signal management\n");
2124 /* Check that the kernel-interface signal definitions look sane */
2125 VG_(vki_do_initial_consistency_checks)();
2126 /* .. and go on to use them. */
2127 VG_(sigstartup_actions)();
2129 //--------------------------------------------------------------
2130 // Read suppression file
2131 // p: main_process_cmd_line_options() [for VG_(clo_suppressions)]
2132 //--------------------------------------------------------------
2133 if (VG_(needs).core_errors || VG_(needs).tool_errors) {
2134 VG_(debugLog)(1, "main", "Load suppressions\n");
2135 VG_(load_suppressions)();
2138 //--------------------------------------------------------------
2139 // register client stack
2140 //--------------------------------------------------------------
2141 VG_(clstk_id) = VG_(register_stack)(VG_(clstk_start_base), VG_(clstk_end));
2143 //--------------------------------------------------------------
2144 // Show the address space state so far
2145 //--------------------------------------------------------------
2146 VG_(debugLog)(1, "main", "\n");
2147 VG_(debugLog)(1, "main", "\n");
2148 VG_(am_show_nsegments)(1,"Memory layout at client startup");
2149 VG_(debugLog)(1, "main", "\n");
2150 VG_(debugLog)(1, "main", "\n");
2152 //--------------------------------------------------------------
2153 // Run!
2154 //--------------------------------------------------------------
2155 VG_(debugLog)(1, "main", "Running thread 1\n");
2157 /* As a result of the following call, the last thread standing
2158 eventually winds up running shutdown_actions_NORETURN
2159 just below. Unfortunately, simply exporting said function
2160 causes m_main to be part of a module cycle, which is pretty
2161 nonsensical. So instead of doing that, the address of said
2162 function is stored in a global variable 'owned' by m_syswrap,
2163 and it uses that function pointer to get back here when it needs
2164 to. */
2166 /* Set continuation address. */
2167 VG_(address_of_m_main_shutdown_actions_NORETURN)
2168 = & shutdown_actions_NORETURN;
2170 /* Run the first thread, eventually ending up at the continuation
2171 address. */
2172 VG_(main_thread_wrapper_NORETURN)(1);
2174 /*NOTREACHED*/
2175 vg_assert(0);
2178 /* Return the exit code to use when tid exits, depending on the tid os_state
2179 exit code and the clo options controlling valgrind exit code. */
2180 static
2181 Int tid_exit_code (ThreadId tid)
2183 if (VG_(clo_error_exitcode) > 0 && VG_(get_n_errs_found)() > 0)
2184 /* Change the application return code to user's return code,
2185 if an error was found */
2186 return VG_(clo_error_exitcode);
2187 else
2188 /* otherwise, return the client's exit code, in the normal
2189 way. */
2190 return VG_(threads)[tid].os_state.exitcode;
2193 /* Do everything which needs doing when the last thread exits or when
2194 a thread exits requesting a complete process exit.
2196 We enter here holding The Lock. For the case VgSrc_ExitProcess we
2197 must never release it, because to do so would allow other threads
2198 to continue after the system is ostensibly shut down. So we must
2199 go to our grave, so to speak, holding the lock.
2201 In fact, there is never any point in releasing the lock at this
2202 point - we have it, we're shutting down the entire system, and
2203 for the case VgSrc_ExitProcess doing so positively causes trouble.
2204 So don't.
2206 The final_tidyup call makes a bit of a nonsense of the ExitProcess
2207 case, since it will run __gnu_cxx::__freeres and libc_freeres functions,
2208 thus allowing other lurking threads to run again. Hmm. */
2210 static
2211 void shutdown_actions_NORETURN( ThreadId tid,
2212 VgSchedReturnCode tids_schedretcode )
2214 VG_(debugLog)(1, "main", "entering VG_(shutdown_actions_NORETURN)\n");
2215 VG_(am_show_nsegments)(1,"Memory layout at client shutdown");
2217 vg_assert(VG_(is_running_thread)(tid));
2218 vg_assert(tids_schedretcode == VgSrc_ExitThread
2219 || tids_schedretcode == VgSrc_ExitProcess
2220 || tids_schedretcode == VgSrc_FatalSig );
2222 /* Try to do final tidyup on "normal" exit, not on FatalSig. */
2223 if (tids_schedretcode == VgSrc_ExitThread) {
2225 // We are the last surviving thread. Right?
2226 vg_assert( VG_(count_living_threads)() == 1 );
2228 // Wait for all other threads to exit.
2229 // jrs: Huh? but they surely are already gone
2230 VG_(reap_threads)(tid);
2232 // Clean the client up before the final report.
2233 // This causes __gnu_cxx::__freeres and libc_freeres functions to run.
2234 final_tidyup(tid);
2236 /* be paranoid */
2237 vg_assert(VG_(is_running_thread)(tid));
2238 vg_assert(VG_(count_living_threads)() == 1);
2240 } else if (tids_schedretcode == VgSrc_ExitProcess) {
2242 // We may not be the last surviving thread. However, we
2243 // want to shut down the entire process. We hold the lock
2244 // and we need to keep hold of it all the way out, in order
2245 // that none of the other threads ever run again.
2246 vg_assert( VG_(count_living_threads)() >= 1 );
2248 // Clean the client up before the final report.
2249 // This causes __gnu_cxx::__freeres and libc_freeres functions to run.
2250 // Perhaps this is unsafe, as per comment above.
2251 final_tidyup(tid);
2253 /* be paranoid */
2254 vg_assert(VG_(is_running_thread)(tid));
2255 vg_assert(VG_(count_living_threads)() >= 1);
2258 /* Final call to gdbserver, if requested. */
2259 if (VG_(gdbserver_stop_at) (VgdbStopAt_Abexit)
2260 && tid_exit_code (tid) != 0) {
2261 if (!(VG_(clo_launched_with_multi)))
2262 VG_(umsg)("(action at abexit, exit code %d) vgdb me ... \n",
2263 tid_exit_code (tid));
2264 VG_(gdbserver) (tid);
2265 } else if (VG_(gdbserver_stop_at) (VgdbStopAt_Exit)) {
2266 if (!(VG_(clo_launched_with_multi)))
2267 VG_(umsg)("(action at exit, exit code %d) vgdb me ... \n",
2268 tid_exit_code (tid));
2269 VG_(gdbserver) (tid);
2271 VG_(threads)[tid].status = VgTs_Empty;
2273 //--------------------------------------------------------------
2274 // Finalisation: cleanup, messages, etc. Order not so important, only
2275 // affects what order the messages come.
2276 //--------------------------------------------------------------
2277 // First thing in the post-amble is a blank line.
2278 if (VG_(clo_xml))
2279 VG_(printf_xml)("\n");
2280 else if (VG_(clo_verbosity) > 0)
2281 VG_(message)(Vg_UserMsg, "\n");
2283 if (VG_(clo_xml)) {
2284 HChar buf[50]; // large enough
2285 VG_(elapsed_wallclock_time)(buf, sizeof buf);
2286 VG_(printf_xml)( "<status>\n"
2287 " <state>FINISHED</state>\n"
2288 " <time>%pS</time>\n"
2289 "</status>\n"
2290 "\n",
2291 buf);
2294 /* Print out file descriptor summary and stats. */
2295 if (VG_(clo_track_fds))
2296 VG_(show_open_fds)("at exit");
2298 /* Call the tool's finalisation function. This makes Memcheck's
2299 leak checker run, and possibly chuck a bunch of leak errors into
2300 the error management machinery. */
2301 VG_TDICT_CALL(tool_fini, 0/*exitcode*/);
2303 if (VG_(needs).core_errors || VG_(needs).tool_errors) {
2304 if (VG_(clo_verbosity) == 1
2305 && !VG_(clo_xml)
2306 && !VG_(clo_show_error_list))
2307 VG_(message)(Vg_UserMsg,
2308 "For lists of detected and suppressed errors,"
2309 " rerun with: -s\n");
2311 /* Show the error counts. */
2312 if (VG_(clo_xml)) {
2313 VG_(show_error_counts_as_XML)();
2316 /* In XML mode, this merely prints the used suppressions. */
2317 VG_(show_all_errors)(VG_(clo_verbosity), VG_(clo_xml));
2320 if (VG_(clo_xml)) {
2321 VG_(printf_xml)("\n");
2322 VG_(printf_xml)("</valgrindoutput>\n");
2323 VG_(printf_xml)("\n");
2326 VG_(sanity_check_general)( True /*include expensive checks*/ );
2328 if (VG_(clo_stats))
2329 VG_(print_all_stats)(VG_(clo_verbosity) >= 1, /* Memory stats */
2330 False /* tool prints stats in the tool fini */);
2332 /* Show a profile of the heap(s) at shutdown. Optionally, first
2333 throw away all the debug info, as that makes it easy to spot
2334 leaks in the debuginfo reader. */
2335 if (VG_(clo_profile_heap)) {
2336 if (0) VG_(di_discard_ALL_debuginfo)();
2337 VG_(print_arena_cc_analysis)();
2340 /* If profiling has been requested, but with zero interval, it
2341 means "profile at the end of the run only". In which case we
2342 need to dump the profile now. */
2343 if (VG_(clo_profyle_sbs) && VG_(clo_profyle_interval) == 0) {
2344 VG_(get_and_show_SB_profile)(0/*denoting end-of-run*/);
2347 /* Print Vex storage stats */
2348 if (0)
2349 LibVEX_ShowAllocStats();
2351 /* Flush any output cached by previous calls to VG_(message). */
2352 VG_(message_flush)();
2354 /* Terminate gdbserver if ever it was started. We terminate it here
2355 so that it get the output above if output was redirected to
2356 gdb */
2357 VG_(gdbserver_exit) (tid, tids_schedretcode);
2359 /* Ok, finally exit in the os-specific way, according to the scheduler's
2360 return code. In short, if the (last) thread exited by calling
2361 sys_exit, do likewise; if the (last) thread stopped due to a fatal
2362 signal, terminate the entire system with that same fatal signal. */
2363 VG_(debugLog)(1, "core_os",
2364 "VG_(terminate_NORETURN)(tid=%u) schedretcode %s"
2365 " os_state.exit_code %ld fatalsig %d\n",
2366 tid, VG_(name_of_VgSchedReturnCode)(tids_schedretcode),
2367 VG_(threads)[tid].os_state.exitcode,
2368 VG_(threads)[tid].os_state.fatalsig);
2370 switch (tids_schedretcode) {
2371 case VgSrc_ExitThread: /* the normal way out (Linux, Solaris) */
2372 case VgSrc_ExitProcess: /* the normal way out (Darwin) */
2373 VG_(client_exit)(tid_exit_code (tid));
2374 /* NOT ALIVE HERE! */
2375 VG_(core_panic)("entered the afterlife in main() -- ExitT/P");
2376 break; /* what the hell :) */
2378 case VgSrc_FatalSig:
2379 /* We were killed by a fatal signal, so replicate the effect */
2380 vg_assert(VG_(threads)[tid].os_state.fatalsig != 0);
2381 VG_(kill_self)(VG_(threads)[tid].os_state.fatalsig);
2382 /* we shouldn't be alive at this point. But VG_(kill_self)
2383 sometimes fails with EPERM on Darwin, for unclear reasons. */
2384 # if defined(VGO_darwin)
2385 VG_(debugLog)(0, "main", "VG_(kill_self) failed. Exiting normally.\n");
2386 VG_(exit)(0); /* bogus, but we really need to exit now */
2387 /* fall through .. */
2388 # endif
2389 VG_(core_panic)("main(): signal was supposed to be fatal");
2390 break;
2392 default:
2393 VG_(core_panic)("main(): unexpected scheduler return code");
2397 /* -------------------- */
2399 /* Final clean-up before terminating the process.
2400 Clean up the client by calling __gnu_cxx::__freeres() (if requested)
2401 and __libc_freeres() (if requested).
2403 static void final_tidyup(ThreadId tid)
2405 #if defined(VGO_linux) || defined(VGO_solaris) || defined(VGO_freebsd)
2406 Addr freeres_wrapper = VG_(client_freeres_wrapper);
2408 vg_assert(VG_(is_running_thread)(tid));
2410 if (freeres_wrapper == 0) {
2411 return; /* can't do it */
2414 Vg_FreeresToRun to_run = 0;
2415 if (VG_(needs).cxx_freeres && VG_(clo_run_cxx_freeres)) {
2416 to_run |= VG_RUN__GNU_CXX__FREERES;
2419 if (VG_(needs).libc_freeres && VG_(clo_run_libc_freeres)) {
2420 to_run |= VG_RUN__LIBC_FREERES;
2423 if (to_run == 0) {
2424 return; /* won't do it */
2427 # if defined(VGP_ppc64be_linux)
2428 Addr r2 = VG_(get_tocptr)(VG_(current_DiEpoch)(),
2429 freeres_wrapper);
2430 if (r2 == 0) {
2431 VG_(message)(Vg_UserMsg,
2432 "Caught __NR_exit, but can't run __gnu_cxx::__freeres()\n");
2433 VG_(message)(Vg_UserMsg,
2434 " or __libc_freeres() since cannot establish TOC pointer "
2435 "for it.\n");
2436 return;
2438 # endif
2440 if (VG_(clo_verbosity) > 2 ||
2441 VG_(clo_trace_syscalls) ||
2442 VG_(clo_trace_sched)) {
2444 vg_assert(to_run > 0);
2445 vg_assert(to_run <= (VG_RUN__GNU_CXX__FREERES | VG_RUN__LIBC_FREERES));
2447 const HChar *msgs[] = {"__gnu_cxx::__freeres()", "__libc_freeres()",
2448 "__gnu_cxx::__freeres and __libc_freeres()"};
2449 VG_(message)(Vg_DebugMsg,
2450 "Caught __NR_exit; running %s wrapper\n", msgs[to_run - 1]);
2453 /* Set thread context to point to freeres_wrapper.
2454 ppc64be-linux note: freeres_wrapper gives us the real
2455 function entry point, not a fn descriptor, so can use it
2456 directly. However, we need to set R2 (the toc pointer)
2457 appropriately. */
2458 VG_(set_IP)(tid, freeres_wrapper);
2460 # if defined(VGP_ppc64be_linux)
2461 VG_(threads)[tid].arch.vex.guest_GPR2 = r2;
2462 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2463 offsetof(VexGuestPPC64State, guest_GPR2),
2464 sizeof(VG_(threads)[tid].arch.vex.guest_GPR2));
2465 # elif defined(VGP_ppc64le_linux)
2466 /* setting GPR2 but not really needed, GPR12 is needed */
2467 VG_(threads)[tid].arch.vex.guest_GPR2 = freeres_wrapper;
2468 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2469 offsetof(VexGuestPPC64State, guest_GPR2),
2470 sizeof(VG_(threads)[tid].arch.vex.guest_GPR2));
2471 VG_(threads)[tid].arch.vex.guest_GPR12 = freeres_wrapper;
2472 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2473 offsetof(VexGuestPPC64State, guest_GPR12),
2474 sizeof(VG_(threads)[tid].arch.vex.guest_GPR12));
2475 # endif
2476 /* mips-linux note: we need to set t9 */
2477 # if defined(VGP_mips32_linux) || defined(VGP_nanomips_linux)
2478 VG_(threads)[tid].arch.vex.guest_r25 = freeres_wrapper;
2479 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2480 offsetof(VexGuestMIPS32State, guest_r25),
2481 sizeof(VG_(threads)[tid].arch.vex.guest_r25));
2482 # elif defined(VGP_mips64_linux)
2483 VG_(threads)[tid].arch.vex.guest_r25 = freeres_wrapper;
2484 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2485 offsetof(VexGuestMIPS64State, guest_r25),
2486 sizeof(VG_(threads)[tid].arch.vex.guest_r25));
2487 # endif
2489 /* Pass a parameter to freeres_wrapper(). */
2490 # if defined(VGA_x86)
2491 Addr sp = VG_(threads)[tid].arch.vex.guest_ESP;
2492 *((UWord *) sp) = to_run;
2493 VG_TRACK(post_mem_write, Vg_CoreClientReq, tid, sp, sizeof(UWord));
2494 sp = sp - sizeof(UWord);
2495 VG_(threads)[tid].arch.vex.guest_ESP = sp;
2496 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2497 offsetof(VexGuestX86State, guest_ESP),
2498 sizeof(VG_(threads)[tid].arch.vex.guest_ESP));
2499 # elif defined(VGA_amd64)
2500 VG_(threads)[tid].arch.vex.guest_RDI = to_run;
2501 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2502 offsetof(VexGuestAMD64State, guest_RDI),
2503 sizeof(VG_(threads)[tid].arch.vex.guest_RDI));
2504 # elif defined(VGA_arm)
2505 VG_(threads)[tid].arch.vex.guest_R0 = to_run;
2506 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2507 offsetof(VexGuestARMState, guest_R0),
2508 sizeof(VG_(threads)[tid].arch.vex.guest_R0));
2509 # elif defined(VGA_arm64)
2510 VG_(threads)[tid].arch.vex.guest_X0 = to_run;
2511 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2512 offsetof(VexGuestARM64State, guest_X0),
2513 sizeof(VG_(threads)[tid].arch.vex.guest_X0));
2514 # elif defined(VGA_mips32) || defined(VGA_nanomips)
2515 VG_(threads)[tid].arch.vex.guest_r4 = to_run;
2516 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2517 offsetof(VexGuestMIPS32State, guest_r4),
2518 sizeof(VG_(threads)[tid].arch.vex.guest_r4));
2519 # elif defined(VGA_mips64)
2520 VG_(threads)[tid].arch.vex.guest_r4 = to_run;
2521 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2522 offsetof(VexGuestMIPS64State, guest_r4),
2523 sizeof(VG_(threads)[tid].arch.vex.guest_r4));
2524 # elif defined(VGA_ppc32)
2525 VG_(threads)[tid].arch.vex.guest_GPR3 = to_run;
2526 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2527 offsetof(VexGuestPPC32State, guest_GPR3),
2528 sizeof(VG_(threads)[tid].arch.vex.guest_GPR3));
2529 # elif defined(VGA_ppc64be) || defined(VGA_ppc64le)
2530 VG_(threads)[tid].arch.vex.guest_GPR3 = to_run;
2531 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2532 offsetof(VexGuestPPC64State, guest_GPR3),
2533 sizeof(VG_(threads)[tid].arch.vex.guest_GPR3));
2534 # elif defined(VGA_s390x)
2535 VG_(threads)[tid].arch.vex.guest_r2 = to_run;
2536 VG_TRACK(post_reg_write, Vg_CoreClientReq, tid,
2537 offsetof(VexGuestS390XState, guest_r2),
2538 sizeof(VG_(threads)[tid].arch.vex.guest_r2));
2539 #else
2540 I_die_here : architecture missing in m_main.c
2541 #endif
2543 /* Block all blockable signals by copying the real block state into
2544 the thread's block state */
2545 VG_(sigprocmask)(VKI_SIG_BLOCK, NULL, &VG_(threads)[tid].sig_mask);
2546 VG_(threads)[tid].tmp_sig_mask = VG_(threads)[tid].sig_mask;
2548 /* and restore handlers to default. */
2549 VG_(set_default_handler)(VKI_SIGSEGV);
2550 VG_(set_default_handler)(VKI_SIGBUS);
2551 VG_(set_default_handler)(VKI_SIGILL);
2552 VG_(set_default_handler)(VKI_SIGFPE);
2553 VG_(set_default_handler)(VKI_SIGSYS);
2555 // We were exiting, so assert that...
2556 vg_assert(VG_(is_exiting)(tid));
2557 // ...but now we're not again.
2558 VG_(threads)[tid].exitreason = VgSrc_None;
2560 // Run until client thread exits - ideally with FREERES_DONE,
2561 // but exit/exitgroup/signal will do.
2562 VG_(scheduler)(tid);
2564 vg_assert(VG_(is_exiting)(tid));
2565 #endif
2569 /*====================================================================*/
2570 /*=== Getting to main() alive: LINUX ===*/
2571 /*====================================================================*/
2573 #if defined(VGO_linux)
2575 /* If linking of the final executables is done with glibc present,
2576 then Valgrind starts at main() above as usual, and all of the
2577 following code is irrelevant.
2579 However, this is not the intended mode of use. The plan is to
2580 avoid linking against glibc, by giving gcc the flags
2581 -nodefaultlibs -lgcc -nostartfiles at startup.
2583 From this derive two requirements:
2585 1. gcc may emit calls to memcpy, memmove and memset to deal with
2586 structure assignments etc. Since we have chosen to ignore all the
2587 "normal" supporting libraries, we have to provide our own
2588 implementations of them. No problem.
2590 2. We have to provide a symbol "_start", to which the kernel
2591 hands control at startup. Hence the code below.
2594 /* ---------------- Requirement 1 ---------------- */
2596 void* memcpy(void *dest, const void *src, SizeT n);
2597 void* memcpy(void *dest, const void *src, SizeT n) {
2598 return VG_(memcpy)(dest,src,n);
2600 void* memmove(void *dest, const void *src, SizeT n);
2601 void* memmove(void *dest, const void *src, SizeT n) {
2602 return VG_(memmove)(dest,src,n);
2604 void* memset(void *s, int c, SizeT n);
2605 void* memset(void *s, int c, SizeT n) {
2606 return VG_(memset)(s,c,n);
2609 /* BVA: abort() for those platforms that need it (PPC and ARM). */
2610 void abort(void);
2611 void abort(void){
2612 VG_(printf)("Something called raise().\n");
2613 vg_assert(0);
2616 /* EAZG: ARM's EABI will call floating point exception handlers in
2617 libgcc which boil down to an abort or raise, that's usually defined
2618 in libc. Instead, define them here. */
2619 #if defined(VGP_arm_linux)
2621 void raise(void);
2622 void raise(void){
2623 VG_(printf)("Something called raise().\n");
2624 vg_assert(0);
2627 void __aeabi_unwind_cpp_pr0(void);
2628 void __aeabi_unwind_cpp_pr0(void){
2629 VG_(printf)("Something called __aeabi_unwind_cpp_pr0()\n");
2630 vg_assert(0);
2633 void __aeabi_unwind_cpp_pr1(void);
2634 void __aeabi_unwind_cpp_pr1(void){
2635 VG_(printf)("Something called __aeabi_unwind_cpp_pr1()\n");
2636 vg_assert(0);
2639 #endif /* defined(VGP_arm_linux) */
2641 /* Some Android helpers. See bug 368529. */
2642 #if defined(__clang__) \
2643 && (defined(VGPV_arm_linux_android) \
2644 || defined(VGPV_x86_linux_android) \
2645 || defined(VGPV_mips32_linux_android) \
2646 || defined(VGPV_arm64_linux_android))
2648 /* Replace __aeabi_memcpy* functions with vgPlain_memcpy. */
2649 void *__aeabi_memcpy(void *dest, const void *src, SizeT n);
2650 void *__aeabi_memcpy(void *dest, const void *src, SizeT n)
2652 return VG_(memcpy)(dest, src, n);
2655 void *__aeabi_memcpy4(void *dest, const void *src, SizeT n);
2656 void *__aeabi_memcpy4(void *dest, const void *src, SizeT n)
2658 return VG_(memcpy)(dest, src, n);
2661 void *__aeabi_memcpy8(void *dest, const void *src, SizeT n);
2662 void *__aeabi_memcpy8(void *dest, const void *src, SizeT n)
2664 return VG_(memcpy)(dest, src, n);
2667 /* Replace __aeabi_memclr* functions with vgPlain_memset. */
2668 void *__aeabi_memclr(void *dest, SizeT n);
2669 void *__aeabi_memclr(void *dest, SizeT n)
2671 return VG_(memset)(dest, 0, n);
2674 void *__aeabi_memclr4(void *dest, SizeT n);
2675 void *__aeabi_memclr4(void *dest, SizeT n)
2677 return VG_(memset)(dest, 0, n);
2680 void *__aeabi_memclr8(void *dest, SizeT n);
2681 void *__aeabi_memclr8(void *dest, SizeT n)
2683 return VG_(memset)(dest, 0, n);
2685 #endif /* clang and android, basically */
2687 /* ---------------- Requirement 2 ---------------- */
2689 /* Glibc's sysdeps/i386/elf/start.S has the following gem of a
2690 comment, which explains how the stack looks right at process start
2691 (when _start is jumped to). Hence _start passes %esp to
2692 _start_in_C_linux, which extracts argc/argv/envp and starts up
2693 correctly. */
2695 /* This is the canonical entry point, usually the first thing in the text
2696 segment. The SVR4/i386 ABI (pages 3-31, 3-32) says that when the entry
2697 point runs, most registers' values are unspecified, except for:
2699 %edx Contains a function pointer to be registered with `atexit'.
2700 This is how the dynamic linker arranges to have DT_FINI
2701 functions called for shared libraries that have been loaded
2702 before this code runs.
2704 %esp The stack contains the arguments and environment:
2705 0(%esp) argc
2706 4(%esp) argv[0]
2708 (4*argc)(%esp) NULL
2709 (4*(argc+1))(%esp) envp[0]
2711 NULL
2714 /* The kernel hands control to _start, which extracts the initial
2715 stack pointer and calls onwards to _start_in_C_linux. This also switches
2716 the new stack. */
2717 #if defined(VGP_x86_linux)
2718 asm("\n"
2719 ".text\n"
2720 "\t.globl _start\n"
2721 "\t.type _start,@function\n"
2722 "_start:\n"
2723 /* set up the new stack in %eax */
2724 "\tmovl $vgPlain_interim_stack, %eax\n"
2725 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
2726 "\taddl $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %eax\n"
2727 /* allocate at least 16 bytes on the new stack, and aligned */
2728 "\tsubl $16, %eax\n"
2729 "\tandl $~15, %eax\n"
2730 /* install it, and collect the original one */
2731 "\txchgl %eax, %esp\n"
2732 /* call _start_in_C_linux, passing it the startup %esp */
2733 "\tmovl %eax, (%esp)\n"
2734 "\tcall _start_in_C_linux\n"
2735 "\thlt\n"
2736 ".previous\n"
2738 #elif defined(VGP_amd64_linux)
2739 asm("\n"
2740 ".text\n"
2741 "\t.globl _start\n"
2742 "\t.type _start,@function\n"
2743 "_start:\n"
2744 /* set up the new stack in %rdi */
2745 "\tmovq $vgPlain_interim_stack, %rdi\n"
2746 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
2747 "\taddq $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %rdi\n"
2748 "\tandq $~15, %rdi\n"
2749 /* install it, and collect the original one */
2750 "\txchgq %rdi, %rsp\n"
2751 /* call _start_in_C_linux, passing it the startup %rsp */
2752 "\tcall _start_in_C_linux\n"
2753 "\thlt\n"
2754 ".previous\n"
2756 #elif defined(VGP_ppc32_linux)
2757 asm("\n"
2758 ".text\n"
2759 "\t.globl _start\n"
2760 "\t.type _start,@function\n"
2761 "_start:\n"
2762 /* set up the new stack in r16 */
2763 "\tlis 16,vgPlain_interim_stack@ha\n"
2764 "\tla 16,vgPlain_interim_stack@l(16)\n"
2765 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2766 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2767 "\tlis 18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" >> 16)\n"
2768 "\tori 18,18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2769 "\tadd 16,17,16\n"
2770 "\tadd 16,18,16\n"
2771 "\trlwinm 16,16,0,0,27\n"
2772 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2773 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2774 boundary. And r1 is the original SP. Set the SP to r16 and
2775 call _start_in_C_linux, passing it the initial SP. */
2776 "\tmr 3,1\n"
2777 "\tmr 1,16\n"
2778 "\tbl _start_in_C_linux\n"
2779 "\ttrap\n"
2780 ".previous\n"
2782 #elif defined(VGP_ppc64be_linux)
2783 asm("\n"
2784 /* PPC64 ELF ABI says '_start' points to a function descriptor.
2785 So we must have one, and that is what goes into the .opd section. */
2786 "\t.align 2\n"
2787 "\t.global _start\n"
2788 "\t.section \".opd\",\"aw\"\n"
2789 "\t.align 3\n"
2790 "_start:\n"
2791 "\t.quad ._start,.TOC.@tocbase,0\n"
2792 "\t.previous\n"
2793 "\t.type ._start,@function\n"
2794 "\t.global ._start\n"
2795 "._start:\n"
2796 /* set up the new stack in r16 */
2797 "\tlis 16, vgPlain_interim_stack@highest\n"
2798 "\tori 16,16,vgPlain_interim_stack@higher\n"
2799 "\tsldi 16,16,32\n"
2800 "\toris 16,16,vgPlain_interim_stack@h\n"
2801 "\tori 16,16,vgPlain_interim_stack@l\n"
2802 "\txor 17,17,17\n"
2803 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2804 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2805 "\txor 18,18,18\n"
2806 "\tlis 18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" >> 16)\n"
2807 "\tori 18,18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2808 "\tadd 16,17,16\n"
2809 "\tadd 16,18,16\n"
2810 "\trldicr 16,16,0,59\n"
2811 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2812 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2813 boundary. And r1 is the original SP. Set the SP to r16 and
2814 call _start_in_C_linux, passing it the initial SP. */
2815 "\tmr 3,1\n"
2816 "\tmr 1,16\n"
2817 "\tlis 14, _start_in_C_linux@highest\n"
2818 "\tori 14,14,_start_in_C_linux@higher\n"
2819 "\tsldi 14,14,32\n"
2820 "\toris 14,14,_start_in_C_linux@h\n"
2821 "\tori 14,14,_start_in_C_linux@l\n"
2822 "\tld 14,0(14)\n"
2823 "\tmtctr 14\n"
2824 "\tbctrl\n"
2825 "\tnop\n"
2826 "\ttrap\n"
2828 #elif defined(VGP_ppc64le_linux)
2829 /* Little Endian uses ELF version 2 but in the future may also
2830 * support other ELF versions.
2832 asm("\n"
2833 "\t.align 2\n"
2834 "\t.global _start\n"
2835 "\t.type _start,@function\n"
2836 "_start:\n"
2837 "#if _CALL_ELF == 2 \n"
2838 "0: addis 2,12,.TOC.-0b@ha\n"
2839 " addi 2,2,.TOC.-0b@l\n"
2840 " .localentry _start, .-_start\n"
2841 "#endif \n"
2842 /* set up the new stack in r16 */
2843 "\tlis 16, vgPlain_interim_stack@highest\n"
2844 "\tori 16,16,vgPlain_interim_stack@higher\n"
2845 "\tsldi 16,16,32\n"
2846 "\toris 16,16,vgPlain_interim_stack@h\n"
2847 "\tori 16,16,vgPlain_interim_stack@l\n"
2848 "\txor 17,17,17\n"
2849 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2850 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2851 "\txor 18,18,18\n"
2852 "\tlis 18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" >> 16)\n"
2853 "\tori 18,18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2854 "\tadd 16,17,16\n"
2855 "\tadd 16,18,16\n"
2856 "\trldicr 16,16,0,59\n"
2857 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2858 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2859 boundary. And r1 is the original SP. Set the SP to r16 and
2860 call _start_in_C_linux, passing it the initial SP. */
2861 "\tmr 3,1\n"
2862 "\tmr 1,16\n"
2863 "\tlis 14, _start_in_C_linux@highest\n"
2864 "\tori 14,14,_start_in_C_linux@higher\n"
2865 "\tsldi 14,14,32\n"
2866 "\toris 14,14,_start_in_C_linux@h\n"
2867 "\tori 14,14,_start_in_C_linux@l\n"
2868 "\tmtctr 14\n"
2869 "\tbctrl\n"
2870 "\tnop\n"
2871 "\ttrap\n"
2873 #elif defined(VGP_s390x_linux)
2875 This is the canonical entry point, usually the first thing in the text
2876 segment. Most registers' values are unspecified, except for:
2878 %r14 Contains a function pointer to be registered with `atexit'.
2879 This is how the dynamic linker arranges to have DT_FINI
2880 functions called for shared libraries that have been loaded
2881 before this code runs.
2883 %r15 The stack contains the arguments and environment:
2884 0(%r15) argc
2885 8(%r15) argv[0]
2887 (8*argc)(%r15) NULL
2888 (8*(argc+1))(%r15) envp[0]
2890 NULL
2892 asm("\n\t"
2893 ".text\n\t"
2894 ".globl _start\n\t"
2895 ".type _start,@function\n\t"
2896 "_start:\n\t"
2897 /* set up the new stack in %r1 */
2898 "larl %r1, vgPlain_interim_stack\n\t"
2899 "larl %r5, 1f\n\t"
2900 "ag %r1, 0(%r5)\n\t"
2901 "ag %r1, 2f-1f(%r5)\n\t"
2902 "nill %r1, 0xFFF0\n\t"
2903 /* install it, and collect the original one */
2904 "lgr %r2, %r15\n\t"
2905 "lgr %r15, %r1\n\t"
2906 /* call _start_in_C_linux, passing it the startup %r15 */
2907 "brasl %r14, _start_in_C_linux\n\t"
2908 /* trigger execution of an invalid opcode -> halt machine */
2909 "j .+2\n\t"
2910 "1: .quad "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n\t"
2911 "2: .quad "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)"\n\t"
2912 ".previous\n"
2914 #elif defined(VGP_arm_linux)
2915 asm("\n"
2916 "\t.text\n"
2917 "\t.align 4\n"
2918 "\t.type _start,#function\n"
2919 "\t.global _start\n"
2920 "_start:\n"
2921 "\tldr r0, [pc, #36]\n"
2922 "\tldr r1, [pc, #36]\n"
2923 "\tadd r0, r1, r0\n"
2924 "\tldr r1, [pc, #32]\n"
2925 "\tadd r0, r1, r0\n"
2926 "\tmvn r1, #15\n"
2927 "\tand r0, r0, r1\n"
2928 "\tmov r1, sp\n"
2929 "\tmov sp, r0\n"
2930 "\tmov r0, r1\n"
2931 "\tb _start_in_C_linux\n"
2932 "\t.word vgPlain_interim_stack\n"
2933 "\t.word "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
2934 "\t.word "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)"\n"
2936 #elif defined(VGP_arm64_linux)
2937 asm("\n"
2938 "\t.text\n"
2939 "\t.align 2\n"
2940 "\t.type _start,#function\n"
2941 "\t.global _start\n"
2942 "_start:\n"
2943 "\tadrp x0, vgPlain_interim_stack\n"
2944 "\tadd x0, x0, :lo12:vgPlain_interim_stack\n"
2945 // The next 2 assume that VG_STACK_GUARD_SZB fits in 32 bits
2946 "\tmov x1, (("VG_STRINGIFY(VG_STACK_GUARD_SZB)") >> 0) & 0xFFFF\n"
2947 "\tmovk x1, (("VG_STRINGIFY(VG_STACK_GUARD_SZB)") >> 16) & 0xFFFF,"
2948 " lsl 16\n"
2949 "\tadd x0, x0, x1\n"
2950 // The next 2 assume that VG_DEFAULT_STACK_ACTIVE_SZB fits in 32 bits
2951 "\tmov x1, (("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)") >> 0) & 0xFFFF\n"
2952 "\tmovk x1, (("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)") >> 16) & 0xFFFF,"
2953 " lsl 16\n"
2954 "\tadd x0, x0, x1\n"
2955 "\tand x0, x0, -16\n"
2956 "\tmov x1, sp\n"
2957 "\tmov sp, x0\n"
2958 "\tmov x0, x1\n"
2959 "\tb _start_in_C_linux\n"
2961 #elif defined(VGP_mips32_linux)
2962 asm("\n"
2963 "\t.type _gp_disp,@object\n"
2964 ".text\n"
2965 "\t.globl __start\n"
2966 "\t.type __start,@function\n"
2967 "__start:\n"
2969 "\tbal 1f\n"
2970 "\tnop\n"
2972 "1:\n"
2974 "\tlui $28, %hi(_gp_disp)\n"
2975 "\taddiu $28, $28, %lo(_gp_disp)\n"
2976 "\taddu $28, $28, $31\n"
2977 /* t1/$9 <- Addr(interim_stack) */
2978 "\tlui $9, %hi(vgPlain_interim_stack)\n"
2979 /* t1/$9 <- Addr(interim_stack) */
2980 "\taddiu $9, %lo(vgPlain_interim_stack)\n"
2983 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
2984 "\tli $11, "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)"\n"
2986 "\taddu $9, $9, $10\n"
2987 "\taddu $9, $9, $11\n"
2988 "\tli $12, 0xFFFFFFF0\n"
2989 "\tand $9, $9, $12\n"
2990 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2991 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2992 boundary. And $29 is the original SP. Set the SP to t1 and
2993 call _start_in_C, passing it the initial SP. */
2995 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
2996 "\tmove $29, $9\n" // $sp <- t1 (new sp)
2998 "\tlui $25, %hi(_start_in_C_linux)\n"
2999 "\taddiu $25, %lo(_start_in_C_linux)\n"
3001 "\tbal _start_in_C_linux\n"
3002 "\tbreak 0x7\n"
3003 ".previous\n"
3005 #elif defined(VGP_mips64_linux)
3006 asm(
3007 ".text\n"
3008 ".globl __start\n"
3009 ".type __start,@function\n"
3010 "__start:\n"
3011 "\t.set noreorder\n"
3012 "\t.cpload $25\n"
3013 "\t.set reorder\n"
3014 "\t.cprestore 16\n"
3015 "\tlui $9, %hi(vgPlain_interim_stack)\n"
3016 /* t1/$9 <- Addr(interim_stack) */
3017 "\tdaddiu $9, %lo(vgPlain_interim_stack)\n"
3019 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
3020 "\tli $11, "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)"\n"
3022 "\tdaddu $9, $9, $10\n"
3023 "\tdaddu $9, $9, $11\n"
3024 "\tli $12, 0xFFFFFF00\n"
3025 "\tand $9, $9, $12\n"
3026 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
3027 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
3028 boundary. And $29 is the original SP. Set the SP to t1 and
3029 call _start_in_C, passing it the initial SP. */
3031 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
3032 "\tmove $29, $9\n" // $sp <- t1 (new sp)
3034 "\tlui $9, %highest(_start_in_C_linux)\n"
3035 "\tori $9, %higher(_start_in_C_linux)\n"
3036 "\tdsll32 $9, $9, 0x0\n"
3037 "\tlui $10, %hi(_start_in_C_linux)\n"
3038 "\tdaddiu $10, %lo(_start_in_C_linux)\n"
3039 "\tdaddu $25, $9, $10\n"
3040 "\tjalr $25\n"
3041 "\tnop\n"
3042 ".previous\n"
3044 #elif defined(VGP_nanomips_linux)
3045 asm(
3046 ".text \n\t"
3047 ".globl __start \n\t"
3048 ".type __start,@function \n\t"
3049 "__start: \n\t"
3050 ".set push \n\t"
3051 ".set noreorder \n\t"
3052 "li $t1, vgPlain_interim_stack \n\t"
3053 "li $t0, "VG_STRINGIFY(VG_STACK_GUARD_SZB)" \n\t"
3054 "addu $t1, $t1, $t0 \n\t"
3055 "li $t0, "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)"\n\t"
3056 "addu $t1, $t1, $t0 \n\t"
3057 "li $t0, 0xFFFFFF00 \n\t"
3058 "and $t1, $t1, $t0 \n\t"
3059 "move $a0, $sp \n\t"
3060 "move $sp, $t1 \n\t"
3061 "li $t0, _start_in_C_linux \n\t"
3062 "jrc $t0 \n\t"
3063 "break \n\t"
3064 ".set pop \n\t"
3065 ".previous \n\t"
3067 #else
3068 # error "Unknown platform"
3069 #endif
3071 /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
3072 #define _GNU_SOURCE
3073 #define _FILE_OFFSET_BITS 64
3074 /* This is in order to get AT_NULL and AT_PAGESIZE. */
3075 #include <elf.h>
3076 /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
3078 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3079 'static' causes gcc to complain it isn't.
3080 attribute 'used' also ensures the code is not eliminated at link
3081 time */
3082 __attribute__ ((used))
3083 void _start_in_C_linux ( UWord* pArgc );
3084 __attribute__ ((used))
3085 void _start_in_C_linux ( UWord* pArgc )
3087 Int r;
3088 Word argc = pArgc[0];
3089 HChar** argv = (HChar**)&pArgc[1];
3090 HChar** envp = (HChar**)&pArgc[1+argc+1];
3092 // For an inner Valgrind, register the interim stack asap.
3093 // This is needed to allow the outer valgrind to do stacktraces during init.
3094 // Note that this stack is not unregistered when the main thread
3095 // is switching to the (real) stack. Unregistering this would imply
3096 // to save the stack id in a global variable, and have a "if"
3097 // in run_a_thread_NORETURN to do the unregistration only for the
3098 // main thread. This unregistration is not worth this complexity.
3099 INNER_REQUEST
3100 ((void) VALGRIND_STACK_REGISTER
3101 (&VG_(interim_stack).bytes[0],
3102 &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack))));
3104 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3105 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3107 the_iicii.sp_at_startup = (Addr)pArgc;
3109 # if defined(VGP_ppc32_linux) || defined(VGP_ppc64be_linux) \
3110 || defined(VGP_ppc64le_linux) || defined(VGP_arm64_linux) \
3111 || defined(VGP_mips32_linux) || defined(VGP_mips64_linux) \
3112 || defined(VGP_nanomips_linux)
3114 /* ppc32/ppc64, arm64, mips32/64 can be configured with different
3115 page sizes. Determine this early. This is an ugly hack and really
3116 should be moved into valgrind_main. */
3117 UWord *sp = &pArgc[1+argc+1];
3118 while (*sp++ != 0)
3120 for (; *sp != AT_NULL && *sp != AT_PAGESZ; sp += 2);
3121 if (*sp == AT_PAGESZ) {
3122 VKI_PAGE_SIZE = sp[1];
3123 for (VKI_PAGE_SHIFT = 12;
3124 VKI_PAGE_SHIFT <= VKI_MAX_PAGE_SHIFT; VKI_PAGE_SHIFT++)
3125 if (VKI_PAGE_SIZE == (1UL << VKI_PAGE_SHIFT))
3126 break;
3129 # endif
3131 r = valgrind_main( (Int)argc, argv, envp );
3132 /* NOTREACHED */
3133 VG_(exit)(r);
3137 /*====================================================================*/
3138 /*=== Getting to main() alive: darwin ===*/
3139 /*====================================================================*/
3141 #elif defined(VGO_darwin)
3144 Memory layout established by kernel:
3146 0(%esp) argc
3147 4(%esp) argv[0]
3149 argv[argc-1]
3150 NULL
3151 envp[0]
3153 envp[n]
3154 NULL
3155 executable name (presumably, a pointer to it)
3156 NULL
3158 Ditto in the 64-bit case, except all offsets from SP are obviously
3159 twice as large.
3162 /* The kernel hands control to _start, which extracts the initial
3163 stack pointer and calls onwards to _start_in_C_darwin. This also
3164 switches to the new stack. */
3165 #if defined(VGP_x86_darwin)
3166 asm("\n"
3167 ".text\n"
3168 ".align 2,0x90\n"
3169 "\t.globl __start\n"
3170 "__start:\n"
3171 /* set up the new stack in %eax */
3172 "\tmovl $_vgPlain_interim_stack, %eax\n"
3173 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
3174 "\taddl $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %eax\n"
3175 "\tsubl $16, %eax\n"
3176 "\tandl $~15, %eax\n"
3177 /* install it, and collect the original one */
3178 "\txchgl %eax, %esp\n"
3179 "\tsubl $12, %esp\n" // keep stack 16 aligned; see #295428
3180 /* call _start_in_C_darwin, passing it the startup %esp */
3181 "\tpushl %eax\n"
3182 "\tcall __start_in_C_darwin\n"
3183 "\tint $3\n"
3184 "\tint $3\n"
3186 #elif defined(VGP_amd64_darwin)
3187 asm("\n"
3188 ".text\n"
3189 "\t.globl __start\n"
3190 ".align 3,0x90\n"
3191 "__start:\n"
3192 /* set up the new stack in %rdi */
3193 "\tmovabsq $_vgPlain_interim_stack, %rdi\n"
3194 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
3195 "\taddq $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %rdi\n"
3196 "\tandq $~15, %rdi\n"
3197 /* install it, and collect the original one */
3198 "\txchgq %rdi, %rsp\n"
3199 /* call _start_in_C_darwin, passing it the startup %rsp */
3200 "\tcall __start_in_C_darwin\n"
3201 "\tint $3\n"
3202 "\tint $3\n"
3204 #endif
3206 void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2);
3207 void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2) {
3208 // skip check
3209 return VG_(memcpy)(dest,src,n);
3211 void* __memset_chk(void *s, int c, SizeT n, SizeT n2);
3212 void* __memset_chk(void *s, int c, SizeT n, SizeT n2) {
3213 // skip check
3214 return VG_(memset)(s,c,n);
3216 void __bzero(void* s, UWord n);
3217 void __bzero(void* s, UWord n) {
3218 (void)VG_(memset)(s,0,n);
3220 void bzero(void *s, SizeT n);
3221 void bzero(void *s, SizeT n) {
3222 VG_(memset)(s,0,n);
3225 void* memcpy(void *dest, const void *src, SizeT n);
3226 void* memcpy(void *dest, const void *src, SizeT n) {
3227 return VG_(memcpy)(dest,src,n);
3229 void* memset(void *s, int c, SizeT n);
3230 void* memset(void *s, int c, SizeT n) {
3231 return VG_(memset)(s,c,n);
3234 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3235 'static' causes gcc to complain it isn't. */
3236 void _start_in_C_darwin ( UWord* pArgc );
3237 void _start_in_C_darwin ( UWord* pArgc )
3239 Int r;
3240 Int argc = *(Int *)pArgc; // not pArgc[0] on LP64
3241 HChar** argv = (HChar**)&pArgc[1];
3242 HChar** envp = (HChar**)&pArgc[1+argc+1];
3244 // See _start_in_C_linux
3245 INNER_REQUEST
3246 ((void) VALGRIND_STACK_REGISTER
3247 (&VG_(interim_stack).bytes[0],
3248 &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack))));
3250 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3251 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3253 the_iicii.sp_at_startup = (Addr)pArgc;
3255 r = valgrind_main( (Int)argc, argv, envp );
3256 /* NOTREACHED */
3257 VG_(exit)(r);
3260 /*====================================================================*/
3261 /*=== Getting to main() alive: Solaris ===*/
3262 /*====================================================================*/
3263 #elif defined(VGO_solaris)
3264 #if defined(VGP_x86_solaris)
3265 /* The kernel hands control to _start, which extracts the initial stack
3266 pointer and calls onwards to _start_in_C_solaris. This also switches to
3267 the new stack. */
3268 asm("\n"
3269 "\t.text\n"
3270 "\t.globl _start\n"
3271 "\t.type _start, @function\n"
3272 "_start:\n"
3273 /* Set up the new stack in %eax. */
3274 "\tmovl $vgPlain_interim_stack, %eax\n"
3275 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
3276 "\taddl $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %eax\n"
3277 "\tandl $~15, %eax\n"
3278 /* Install it, and collect the original one. */
3279 "\txchgl %eax, %esp\n"
3280 "\tsubl $12, %esp\n" /* Keep stack 16-byte aligned. */
3281 /* Call _start_in_C_solaris, passing it the startup %esp. */
3282 "\tpushl %eax\n"
3283 "\tcall _start_in_C_solaris\n"
3284 /* NOTREACHED */
3285 "\thlt\n"
3286 "\t.previous\n"
3288 #elif defined(VGP_amd64_solaris)
3289 asm("\n"
3290 ".text\n"
3291 "\t.globl _start\n"
3292 "\t.type _start, @function\n"
3293 "_start:\n"
3294 /* Set up the new stack in %rdi. */
3295 "\tmovq $vgPlain_interim_stack, %rdi\n"
3296 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
3297 "\taddq $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %rdi\n"
3298 "\tandq $~15, %rdi\n"
3299 /* Install it, and collect the original one. */
3300 "\txchgq %rdi, %rsp\n"
3301 /* Call _start_in_C_solaris, passing it the startup %rsp. */
3302 "\tcall _start_in_C_solaris\n"
3303 /* NOTREACHED */
3304 "\thlt\n"
3305 ".previous\n"
3307 #else
3308 # error "Unknown Solaris platform"
3309 #endif
3311 void *memcpy(void *dest, const void *src, size_t n);
3312 void *memcpy(void *dest, const void *src, size_t n) {
3313 return VG_(memcpy)(dest, src, n);
3316 __attribute__ ((used))
3317 void _start_in_C_solaris ( UWord* pArgc );
3318 __attribute__ ((used))
3319 void _start_in_C_solaris ( UWord* pArgc )
3321 Int r;
3322 Word argc = pArgc[0];
3323 HChar** argv = (HChar**)&pArgc[1];
3324 HChar** envp = (HChar**)&pArgc[1 + argc + 1];
3326 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3327 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3329 the_iicii.sp_at_startup = (Addr)pArgc;
3331 r = valgrind_main((Int)argc, argv, envp);
3332 /* NOTREACHED */
3333 VG_(exit)(r);
3336 /*====================================================================*/
3337 /*=== Getting to main() alive: FreeBSD ===*/
3338 /*====================================================================*/
3339 #elif defined(VGO_freebsd)
3342 * Could probably extract __FreeBSD_version at configure time
3344 /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
3345 #include <sys/param.h> /* __FreeBSD_version */
3346 /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
3349 * We need to add two elf notes in order for image activator to parse
3350 * additional binary properites.
3351 * First note declares the ABI, second is the feature note.
3352 * This is primarly used to turn off W^X policy for all valgrind tools,
3353 * as they don't work with it enabled.
3356 /* Based on FreeBSD sources: lib/csu/common/crtbrand.S */
3357 asm("\n"
3358 ".section .note.tag,\"aG\",%note,.freebsd.noteG,comdat\n"
3359 ".p2align 2\n"
3360 ".4byte 2f-1f\n"
3361 ".4byte 4f-3f\n"
3362 ".4byte "VG_STRINGIFY(VKI_NT_FREEBSD_ABI_TAG)"\n"
3363 "1: .asciz \"FreeBSD\"\n"
3364 "2: .p2align 2\n"
3365 "3: .4byte "VG_STRINGIFY(__FreeBSD_version)"\n"
3366 "4: .previous\n"
3369 /* Based on FreeBSD sources: lib/csu/common/feature_note.S */
3370 asm("\n"
3371 ".section .note.tag,\"a\",%note\n"
3372 ".p2align 2\n"
3373 ".4byte 2f-1f\n"
3374 ".4byte 4f-3f\n"
3375 ".4byte "VG_STRINGIFY(VKI_NT_FREEBSD_FEATURE_CTL)"\n"
3376 "1: .asciz \"FreeBSD\"\n"
3377 "2: .p2align 2\n"
3378 "3: .4byte "VG_STRINGIFY(VKI_NT_FREEBSD_FCTL_WXNEEDED)"\n"
3379 "4: .previous\n"
3382 #if defined(VGP_x86_freebsd)
3383 asm("\n"
3384 ".text\n"
3385 "\t.globl _start\n"
3386 "\t.type _start,@function\n"
3387 "_start:\n"
3388 /* set up the new stack in %eax */
3389 "\tmovl $vgPlain_interim_stack, %eax\n"
3390 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
3391 "\taddl $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %eax\n"
3392 /* allocate at least 16 bytes on the new stack, and aligned */
3393 "\tsubl $16, %eax\n"
3394 "\tandl $~15, %eax\n"
3395 /* install it, and collect the original one */
3396 "\txchgl %eax, %esp\n"
3397 "\tsubl $12, %esp\n" /* Keep stack 16-byte aligned. */
3398 /* call _start_in_C_freebsd, passing it the startup %esp */
3399 "\tpushl %eax\n"
3400 "\tcall _start_in_C_freebsd\n"
3401 "\thlt\n"
3402 ".previous\n"
3404 #elif defined(VGP_amd64_freebsd)
3406 // @todo PJF I don't really understand why this is done this way
3407 // other amd64 platforms just put the new stack address in rdi
3408 // then do an exchange so that the stack pointer points to the
3409 // new stack and rdi (which is the 1st argument in the amd64 sysv abi)
3410 // contains the old stack
3412 // instead for amd64 the same thing is done for rsi, the second
3413 // function argument and rdi is unchanged
3415 // In gdb I see the initial rdp is 8+rsp
3416 // e.g.
3417 // rdi 0x7fffffffe3b0
3418 // rsp 0x7fffffffe3a8
3420 // Maybe on FreeBSD the pointer to argc is 16byte aligned and can be 8 bytes above the
3421 // start of the stack?
3423 // Some answers to this mystery here
3424 // https://forums.freebsd.org/threads/stack-alignment-argc-location-in-assembled-binaries.89302/#post-613119
3425 // and here
3426 // https://github.com/freebsd/freebsd-src/blob/releng/5.1/sys/amd64/amd64/machdep.c#LL487C1-L488C42
3428 asm("\n"
3429 ".text\n"
3430 "\t.globl _start\n"
3431 "\t.type _start,@function\n"
3432 "_start:\n"
3433 /* set up the new stack in %rsi */
3434 "\tmovq $vgPlain_interim_stack, %rsi\n"
3435 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rsi\n"
3436 "\taddq $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB)", %rsi\n"
3437 "\tandq $~15, %rsi\n"
3438 /* install it, and collect the original one */
3439 "\txchgq %rsi, %rsp\n"
3440 /* call _start_in_C_freebsd, passing it the startup %rsp */
3441 "\tcall _start_in_C_freebsd\n"
3442 "\thlt\n"
3443 ".previous\n"
3445 #endif
3447 void *memcpy(void *dest, const void *src, size_t n);
3448 void *memcpy(void *dest, const void *src, size_t n) {
3449 return VG_(memcpy)(dest, src, n);
3451 void* memmove(void *dest, const void *src, SizeT n);
3452 void* memmove(void *dest, const void *src, SizeT n) {
3453 return VG_(memmove)(dest,src,n);
3455 void* memset(void *s, int c, SizeT n);
3456 void* memset(void *s, int c, SizeT n) {
3457 return VG_(memset)(s,c,n);
3460 __attribute__ ((used))
3461 void _start_in_C_freebsd ( UWord* pArgc, UWord *initial_sp );
3462 __attribute__ ((used))
3463 void _start_in_C_freebsd ( UWord* pArgc, UWord *initial_sp )
3465 Int r;
3466 Word argc = pArgc[0];
3467 HChar** argv = (HChar**)&pArgc[1];
3468 HChar** envp = (HChar**)&pArgc[1+argc+1];
3470 INNER_REQUEST
3471 ((void) VALGRIND_STACK_REGISTER
3472 (&VG_(interim_stack).bytes[0],
3473 &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack))));
3475 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3476 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3478 #if defined(VGP_amd64_freebsd)
3479 the_iicii.sp_at_startup = (Addr)initial_sp;
3480 #else
3481 the_iicii.sp_at_startup = (Addr)pArgc;
3482 #endif
3484 r = valgrind_main( (Int)argc, argv, envp );
3485 /* NOTREACHED */
3486 VG_(exit)(r);
3489 #else
3490 # error "Unknown OS"
3491 #endif
3494 Addr VG_(get_initial_client_SP)( void )
3496 return the_iifii.initial_client_SP;
3499 /*====================================================================*/
3500 /*=== {u,}{div,mod}di3 replacements ===*/
3501 /*====================================================================*/
3503 /* For static linking on x86-darwin, we need to supply our own 64-bit
3504 integer division code, else the link dies thusly:
3506 ld_classic: Undefined symbols:
3507 ___udivdi3
3508 ___umoddi3
3510 #if defined(VGP_x86_darwin)
3512 /* Routines for doing signed/unsigned 64 x 64 ==> 64 div and mod
3513 (udivdi3, umoddi3, divdi3, moddi3) using only 32 x 32 ==> 32
3514 division. Cobbled together from
3516 http://www.hackersdelight.org/HDcode/divlu.c
3517 http://www.hackersdelight.org/HDcode/divls.c
3518 http://www.hackersdelight.org/HDcode/newCode/divDouble.c
3520 The code from those three files is covered by the following license,
3521 as it appears at:
3523 http://www.hackersdelight.org/permissions.htm
3525 You are free to use, copy, and distribute any of the code on
3526 this web site, whether modified by you or not. You need not give
3527 attribution. This includes the algorithms (some of which appear
3528 in Hacker's Delight), the Hacker's Assistant, and any code
3529 submitted by readers. Submitters implicitly agree to this.
3532 /* Long division, unsigned (64/32 ==> 32).
3533 This procedure performs unsigned "long division" i.e., division of a
3534 64-bit unsigned dividend by a 32-bit unsigned divisor, producing a
3535 32-bit quotient. In the overflow cases (divide by 0, or quotient
3536 exceeds 32 bits), it returns a remainder of 0xFFFFFFFF (an impossible
3537 value).
3538 The dividend is u1 and u0, with u1 being the most significant word.
3539 The divisor is parameter v. The value returned is the quotient.
3540 Max line length is 57, to fit in hacker.book. */
3542 static Int nlz32(UInt x)
3544 Int n;
3545 if (x == 0) return(32);
3546 n = 0;
3547 if (x <= 0x0000FFFF) {n = n +16; x = x <<16;}
3548 if (x <= 0x00FFFFFF) {n = n + 8; x = x << 8;}
3549 if (x <= 0x0FFFFFFF) {n = n + 4; x = x << 4;}
3550 if (x <= 0x3FFFFFFF) {n = n + 2; x = x << 2;}
3551 if (x <= 0x7FFFFFFF) {n = n + 1;}
3552 return n;
3555 /* 64 x 32 ==> 32 unsigned division, using only 32 x 32 ==> 32
3556 division as a primitive. */
3557 static UInt divlu2(UInt u1, UInt u0, UInt v, UInt *r)
3559 const UInt b = 65536; // Number base (16 bits).
3560 UInt un1, un0, // Norm. dividend LSD's.
3561 vn1, vn0, // Norm. divisor digits.
3562 q1, q0, // Quotient digits.
3563 un32, un21, un10, // Dividend digit pairs.
3564 rhat; // A remainder.
3565 Int s; // Shift amount for norm.
3567 if (u1 >= v) { // If overflow, set rem.
3568 if (r != NULL) // to an impossible value,
3569 *r = 0xFFFFFFFF; // and return the largest
3570 return 0xFFFFFFFF;} // possible quotient.
3572 s = nlz32(v); // 0 <= s <= 31.
3573 v = v << s; // Normalize divisor.
3574 vn1 = v >> 16; // Break divisor up into
3575 vn0 = v & 0xFFFF; // two 16-bit digits.
3577 un32 = (u1 << s) | ((u0 >> (32 - s)) & (-s >> 31));
3578 un10 = u0 << s; // Shift dividend left.
3580 un1 = un10 >> 16; // Break right half of
3581 un0 = un10 & 0xFFFF; // dividend into two digits.
3583 q1 = un32/vn1; // Compute the first
3584 rhat = un32 - q1*vn1; // quotient digit, q1.
3585 again1:
3586 if (q1 >= b || q1*vn0 > b*rhat + un1) {
3587 q1 = q1 - 1;
3588 rhat = rhat + vn1;
3589 if (rhat < b) goto again1;}
3591 un21 = un32*b + un1 - q1*v; // Multiply and subtract.
3593 q0 = un21/vn1; // Compute the second
3594 rhat = un21 - q0*vn1; // quotient digit, q0.
3595 again2:
3596 if (q0 >= b || q0*vn0 > b*rhat + un0) {
3597 q0 = q0 - 1;
3598 rhat = rhat + vn1;
3599 if (rhat < b) goto again2;}
3601 if (r != NULL) // If remainder is wanted,
3602 *r = (un21*b + un0 - q0*v) >> s; // return it.
3603 return q1*b + q0;
3607 /* 64 x 32 ==> 32 signed division, using only 32 x 32 ==> 32 division
3608 as a primitive. */
3609 static Int divls(Int u1, UInt u0, Int v, Int *r)
3611 Int q, uneg, vneg, diff, borrow;
3613 uneg = u1 >> 31; // -1 if u < 0.
3614 if (uneg) { // Compute the absolute
3615 u0 = -u0; // value of the dividend u.
3616 borrow = (u0 != 0);
3617 u1 = -u1 - borrow;}
3619 vneg = v >> 31; // -1 if v < 0.
3620 v = (v ^ vneg) - vneg; // Absolute value of v.
3622 if ((UInt)u1 >= (UInt)v) goto overflow;
3624 q = divlu2(u1, u0, v, (UInt *)r);
3626 diff = uneg ^ vneg; // Negate q if signs of
3627 q = (q ^ diff) - diff; // u and v differed.
3628 if (uneg && r != NULL)
3629 *r = -*r;
3631 if ((diff ^ q) < 0 && q != 0) { // If overflow,
3632 overflow: // set remainder
3633 if (r != NULL) // to an impossible value,
3634 *r = 0x80000000; // and return the largest
3635 q = 0x80000000;} // possible neg. quotient.
3636 return q;
3641 /* This file contains a program for doing 64/64 ==> 64 division, on a
3642 machine that does not have that instruction but that does have
3643 instructions for "long division" (64/32 ==> 32). Code for unsigned
3644 division is given first, followed by a simple program for doing the
3645 signed version by using the unsigned version.
3646 These programs are useful in implementing "long long" (64-bit)
3647 arithmetic on a machine that has the long division instruction. It will
3648 work on 64- and 32-bit machines, provided the compiler implements long
3649 long's (64-bit integers). It is desirable that the machine have the
3650 Count Leading Zeros instruction.
3651 In the GNU world, these programs are known as __divdi3 and __udivdi3,
3652 and similar names are used here.
3653 This material is not in HD, but may be in a future edition.
3654 Max line length is 57, to fit in hacker.book. */
3657 static Int nlz64(ULong x)
3659 Int n;
3660 if (x == 0) return(64);
3661 n = 0;
3662 if (x <= 0x00000000FFFFFFFFULL) {n = n + 32; x = x << 32;}
3663 if (x <= 0x0000FFFFFFFFFFFFULL) {n = n + 16; x = x << 16;}
3664 if (x <= 0x00FFFFFFFFFFFFFFULL) {n = n + 8; x = x << 8;}
3665 if (x <= 0x0FFFFFFFFFFFFFFFULL) {n = n + 4; x = x << 4;}
3666 if (x <= 0x3FFFFFFFFFFFFFFFULL) {n = n + 2; x = x << 2;}
3667 if (x <= 0x7FFFFFFFFFFFFFFFULL) {n = n + 1;}
3668 return n;
3671 // ---------------------------- udivdi3 --------------------------------
3673 /* The variables u0, u1, etc. take on only 32-bit values, but they
3674 are declared long long to avoid some compiler warning messages and to
3675 avoid some unnecessary EXTRs that the compiler would put in, to
3676 convert long longs to ints.
3678 First the procedure takes care of the case in which the divisor is a
3679 32-bit quantity. There are two subcases: (1) If the left half of the
3680 dividend is less than the divisor, one execution of DIVU is all that
3681 is required (overflow is not possible). (2) Otherwise it does two
3682 divisions, using the grade school method, with variables used as
3683 suggested below.
3685 q1 q0
3686 ________
3687 v) u1 u0
3688 q1*v
3689 ____
3690 k u0 */
3692 /* These macros must be used with arguments of the appropriate type
3693 (unsigned long long for DIVU and long long for DIVS. They are
3694 simulations of the presumed machines ops. I.e., they look at only the
3695 low-order 32 bits of the divisor, they return garbage if the division
3696 overflows, and they return garbage in the high-order half of the
3697 quotient doubleword.
3698 In practice, these would be replaced with uses of the machine's DIVU
3699 and DIVS instructions (e.g., by using the GNU "asm" facility). */
3701 static UInt DIVU ( ULong u, UInt v )
3703 UInt uHi = (UInt)(u >> 32);
3704 UInt uLo = (UInt)u;
3705 return divlu2(uHi, uLo, v, NULL);
3708 static Int DIVS ( Long u, Int v )
3710 Int uHi = (Int)(u >> 32);
3711 UInt uLo = (UInt)u;
3712 return divls(uHi, uLo, v, NULL);
3715 /* 64 x 64 ==> 64 unsigned division, using only 32 x 32 ==> 32
3716 division as a primitive. */
3717 static ULong udivdi3(ULong u, ULong v)
3719 ULong u0, u1, v1, q0, q1, k, n;
3721 if (v >> 32 == 0) { // If v < 2**32:
3722 if (u >> 32 < v) // If u/v cannot overflow,
3723 return DIVU(u, v) // just do one division.
3724 & 0xFFFFFFFF;
3725 else { // If u/v would overflow:
3726 u1 = u >> 32; // Break u up into two
3727 u0 = u & 0xFFFFFFFF; // halves.
3728 q1 = DIVU(u1, v) // First quotient digit.
3729 & 0xFFFFFFFF;
3730 k = u1 - q1*v; // First remainder, < v.
3731 q0 = DIVU((k << 32) + u0, v) // 2nd quot. digit.
3732 & 0xFFFFFFFF;
3733 return (q1 << 32) + q0;
3736 // Here v >= 2**32.
3737 n = nlz64(v); // 0 <= n <= 31.
3738 v1 = (v << n) >> 32; // Normalize the divisor
3739 // so its MSB is 1.
3740 u1 = u >> 1; // To ensure no overflow.
3741 q1 = DIVU(u1, v1) // Get quotient from
3742 & 0xFFFFFFFF; // divide unsigned insn.
3743 q0 = (q1 << n) >> 31; // Undo normalization and
3744 // division of u by 2.
3745 if (q0 != 0) // Make q0 correct or
3746 q0 = q0 - 1; // too small by 1.
3747 if ((u - q0*v) >= v)
3748 q0 = q0 + 1; // Now q0 is correct.
3749 return q0;
3753 // ----------------------------- divdi3 --------------------------------
3755 /* This routine presumes that smallish cases (those which can be done in
3756 one execution of DIVS) are common. If this is not the case, the test for
3757 this case should be deleted.
3758 Note that the test for when DIVS can be used is not entirely
3759 accurate. For example, DIVS is not used if v = 0xFFFFFFFF8000000,
3760 whereas if could be (if u is sufficiently small in magnitude). */
3762 // ------------------------------ cut ----------------------------------
3764 static ULong my_llabs ( Long x )
3766 ULong t = x >> 63;
3767 return (x ^ t) - t;
3770 /* 64 x 64 ==> 64 signed division, using only 32 x 32 ==> 32 division
3771 as a primitive. */
3772 static Long divdi3(Long u, Long v)
3774 ULong au, av;
3775 Long q, t;
3776 au = my_llabs(u);
3777 av = my_llabs(v);
3778 if (av >> 31 == 0) { // If |v| < 2**31 and
3779 // if (v << 32 >> 32 == v) { // If v is in range and
3780 if (au < av << 31) { // |u|/|v| cannot
3781 q = DIVS(u, v); // overflow, use DIVS.
3782 return (q << 32) >> 32;
3785 q = udivdi3(au,av); // Invoke udivdi3.
3786 t = (u ^ v) >> 63; // If u, v have different
3787 return (q ^ t) - t; // signs, negate q.
3790 // ---------------------------- end cut --------------------------------
3792 ULong __udivdi3 (ULong u, ULong v);
3793 ULong __udivdi3 (ULong u, ULong v)
3795 return udivdi3(u,v);
3798 Long __divdi3 (Long u, Long v);
3799 Long __divdi3 (Long u, Long v)
3801 return divdi3(u,v);
3804 ULong __umoddi3 (ULong u, ULong v);
3805 ULong __umoddi3 (ULong u, ULong v)
3807 ULong q = __udivdi3(u, v);
3808 ULong r = u - q * v;
3809 return r;
3812 Long __moddi3 (Long u, Long v);
3813 Long __moddi3 (Long u, Long v)
3815 Long q = __divdi3(u, v);
3816 Long r = u - q * v;
3817 return r;
3820 /* ------------------------------------------------
3821 ld_classic: Undefined symbols:
3822 ___fixunsdfdi
3823 ------------------------------------------------
3826 /* ===-- fixunsdfdi.c - Implement __fixunsdfdi -----------------------------===
3828 * The LLVM Compiler Infrastructure
3830 * This file is dual licensed under the MIT and the University of Illinois Open
3831 * Source Licenses. See LICENSE.TXT for details.
3833 * ===----------------------------------------------------------------------===
3835 * This file implements __fixunsdfdi for the compiler_rt library.
3837 * ===----------------------------------------------------------------------===
3840 /* As per http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses,
3842 the "NCSA/University of Illinois Open Source License" is compatible
3843 with the GPL (both version 2 and 3). What is claimed to be
3844 compatible is this
3846 http://www.opensource.org/licenses/UoI-NCSA.php
3848 and the LLVM documentation at
3850 http://www.llvm.org/docs/DeveloperPolicy.html#license
3852 says all the code in LLVM is available under the University of
3853 Illinois/NCSA Open Source License, at this URL
3855 http://www.opensource.org/licenses/UoI-NCSA.php
3857 viz, the same one that the FSF pages claim is compatible. So I
3858 think it's OK to include it.
3861 /* Returns: convert a to a unsigned long long, rounding toward zero.
3862 * Negative values all become zero.
3865 /* Assumption: double is a IEEE 64 bit floating point type
3866 * du_int is a 64 bit integral type
3867 * value in double is representable in du_int or is negative
3868 * (no range checking performed)
3871 /* seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm */
3873 typedef unsigned long long du_int;
3874 typedef unsigned su_int;
3876 typedef union
3878 du_int all;
3879 struct
3881 #if VG_LITTLEENDIAN
3882 su_int low;
3883 su_int high;
3884 #else
3885 su_int high;
3886 su_int low;
3887 #endif /* VG_LITTLEENDIAN */
3889 } udwords;
3891 typedef union
3893 udwords u;
3894 double f;
3895 } double_bits;
3897 du_int __fixunsdfdi(double a);
3899 du_int
3900 __fixunsdfdi(double a)
3902 double_bits fb;
3903 fb.f = a;
3904 int e = ((fb.u.s.high & 0x7FF00000) >> 20) - 1023;
3905 if (e < 0 || (fb.u.s.high & 0x80000000))
3906 return 0;
3907 udwords r;
3908 r.s.high = (fb.u.s.high & 0x000FFFFF) | 0x00100000;
3909 r.s.low = fb.u.s.low;
3910 if (e > 52)
3911 r.all <<= (e - 52);
3912 else
3913 r.all >>= (52 - e);
3914 return r.all;
3918 #endif
3921 /*====================================================================*/
3922 /*=== Dummy _voucher_mach_msg_set for OSX 10.10 ===*/
3923 /*====================================================================*/
3925 #if defined(VGO_darwin) && DARWIN_VERS >= DARWIN_10_10
3927 /* Builds on MacOSX 10.10+ seem to need this for some reason. */
3928 /* extern boolean_t voucher_mach_msg_set(mach_msg_header_t *msg)
3929 __attribute__((weak_import));
3930 I haven't a clue what the return value means, so just return 0.
3931 Looks like none of the generated uses in the tree look at the
3932 return value anyway.
3934 UWord voucher_mach_msg_set ( UWord arg1 );
3935 UWord voucher_mach_msg_set ( UWord arg1 )
3937 return 0;
3940 #endif
3942 #if defined(VGO_freebsd)
3943 Word VG_(get_usrstack)(void)
3945 return VG_PGROUNDDN(the_iicii.clstack_end) + VKI_PAGE_SIZE;
3947 #endif
3951 /*--------------------------------------------------------------------*/
3952 /*--- end ---*/
3953 /*--------------------------------------------------------------------*/