2 /*--------------------------------------------------------------------*/
3 /*--- Startup: the real stuff m_main.c ---*/
4 /*--------------------------------------------------------------------*/
7 This file is part of Valgrind, a dynamic binary instrumentation
10 Copyright (C) 2000-2017 Julian Seward
13 This program is free software; you can redistribute it and/or
14 modify it under the terms of the GNU General Public License as
15 published by the Free Software Foundation; either version 2 of the
16 License, or (at your option) any later version.
18 This program is distributed in the hope that it will be useful, but
19 WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 General Public License for more details.
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
28 The GNU General Public License is contained in the file COPYING.
31 #include "vgversion.h"
32 #include "pub_core_basics.h"
33 #include "pub_core_vki.h"
34 #include "pub_core_threadstate.h"
35 #include "pub_core_xarray.h"
36 #include "pub_core_clientstate.h"
37 #include "pub_core_aspacemgr.h"
38 #include "pub_core_aspacehl.h"
39 #include "pub_core_clreq.h"
40 #include "pub_core_commandline.h"
41 #include "pub_core_debuglog.h"
42 #include "pub_core_errormgr.h"
43 #include "pub_core_execontext.h"
44 #include "pub_core_gdbserver.h"
45 #include "pub_core_initimg.h"
46 #include "pub_core_libcbase.h"
47 #include "pub_core_libcassert.h"
48 #include "pub_core_libcfile.h"
49 #include "pub_core_libcprint.h"
50 #include "pub_core_libcproc.h"
51 #include "pub_core_libcsignal.h"
52 #include "pub_core_sbprofile.h"
53 #include "pub_core_mach.h"
54 #include "pub_core_machine.h"
55 #include "pub_core_mallocfree.h"
56 #include "pub_core_options.h"
57 #include "pub_core_debuginfo.h"
58 #include "pub_core_redir.h"
59 #include "pub_core_scheduler.h"
60 #include "pub_core_seqmatch.h" // For VG_(string_match)
61 #include "pub_core_signals.h"
62 #include "pub_core_stacks.h" // For VG_(register_stack)
63 #include "pub_core_syswrap.h"
64 #include "pub_core_tooliface.h"
65 #include "pub_core_translate.h" // For VG_(translate)
66 #include "pub_core_trampoline.h"
67 #include "pub_core_transtab.h"
68 #include "pub_core_inner.h"
69 #if defined(ENABLE_INNER_CLIENT_REQUEST)
70 #include "pub_core_clreq.h"
74 /*====================================================================*/
75 /*=== Command-line: variables, processing, etc ===*/
76 /*====================================================================*/
78 // See pub_{core,tool}_options.h for explanations of all these.
80 static void usage_NORETURN ( Bool debug_help
)
82 /* 'usage1' contains a %s
83 - for the name of the GDB executable
84 - for the name of vgdb's path prefix
85 which must be supplied when they are VG_(printf)'d. */
86 const HChar usage1
[] =
87 "usage: valgrind [options] prog-and-args\n"
89 " tool-selection option, with default in [ ]:\n"
90 " --tool=<name> use the Valgrind tool named <name> [memcheck]\n"
92 " basic user options for all Valgrind tools, with defaults in [ ]:\n"
93 " -h --help show this message\n"
94 " --help-debug show this message, plus debugging options\n"
95 " --version show version\n"
96 " -q --quiet run silently; only print error msgs\n"
97 " -v --verbose be more verbose -- show misc extra info\n"
98 " --trace-children=no|yes Valgrind-ise child processes (follow execve)? [no]\n"
99 " --trace-children-skip=patt1,patt2,... specifies a list of executables\n"
100 " that --trace-children=yes should not trace into\n"
101 " --trace-children-skip-by-arg=patt1,patt2,... same as --trace-children-skip=\n"
102 " but check the argv[] entries for children, rather\n"
103 " than the exe name, to make a follow/no-follow decision\n"
104 " --child-silent-after-fork=no|yes omit child output between fork & exec? [no]\n"
105 " --vgdb=no|yes|full activate gdbserver? [yes]\n"
106 " full is slower but provides precise watchpoint/step\n"
107 " --vgdb-error=<number> invoke gdbserver after <number> errors [%d]\n"
108 " to get started quickly, use --vgdb-error=0\n"
109 " and follow the on-screen directions\n"
110 " --vgdb-stop-at=event1,event2,... invoke gdbserver for given events [none]\n"
111 " where event is one of:\n"
112 " startup exit valgrindabexit all none\n"
113 " --track-fds=no|yes track open file descriptors? [no]\n"
114 " --time-stamp=no|yes add timestamps to log messages? [no]\n"
115 " --log-fd=<number> log messages to file descriptor [2=stderr]\n"
116 " --log-file=<file> log messages to <file>\n"
117 " --log-socket=ipaddr:port log messages to socket ipaddr:port\n"
119 " user options for Valgrind tools that report errors:\n"
120 " --xml=yes emit error output in XML (some tools only)\n"
121 " --xml-fd=<number> XML output to file descriptor\n"
122 " --xml-file=<file> XML output to <file>\n"
123 " --xml-socket=ipaddr:port XML output to socket ipaddr:port\n"
124 " --xml-user-comment=STR copy STR verbatim into XML output\n"
125 " --demangle=no|yes automatically demangle C++ names? [yes]\n"
126 " --num-callers=<number> show <number> callers in stack traces [12]\n"
127 " --error-limit=no|yes stop showing new errors if too many? [yes]\n"
128 " --exit-on-first-error=no|yes exit code on the first error found? [no]\n"
129 " --error-exitcode=<number> exit code to return if errors found [0=disable]\n"
130 " --error-markers=<begin>,<end> add lines with begin/end markers before/after\n"
131 " each error output in plain text mode [none]\n"
132 " --keep-debuginfo=no|yes Keep symbols etc for unloaded code [no]\n"
133 " This allows saved stack traces (e.g. memory leaks)\n"
134 " to include file/line info for code that has been\n"
135 " dlclose'd (or similar)\n"
136 " --show-below-main=no|yes continue stack traces below main() [no]\n"
137 " --default-suppressions=yes|no\n"
138 " load default suppressions [yes]\n"
139 " --suppressions=<filename> suppress errors described in <filename>\n"
140 " --gen-suppressions=no|yes|all print suppressions for errors? [no]\n"
141 " --input-fd=<number> file descriptor for input [0=stdin]\n"
142 " --dsymutil=no|yes run dsymutil on Mac OS X when helpful? [yes]\n"
143 " --max-stackframe=<number> assume stack switch for SP changes larger\n"
144 " than <number> bytes [2000000]\n"
145 " --main-stacksize=<number> set size of main thread's stack (in bytes)\n"
146 " [min(max(current 'ulimit' value,1MB),16MB)]\n"
148 " user options for Valgrind tools that replace malloc:\n"
149 " --alignment=<number> set minimum alignment of heap allocations [%s]\n"
150 " --redzone-size=<number> set minimum size of redzones added before/after\n"
151 " heap blocks (in bytes). [%s]\n"
152 " --xtree-memory=none|allocs|full profile heap memory in an xtree [none]\n"
153 " and produces a report at the end of the execution\n"
154 " none: no profiling, allocs: current allocated\n"
155 " size/blocks, full: profile current and cumulative\n"
156 " allocated size/blocks and freed size/blocks.\n"
157 " --xtree-memory-file=<file> xtree memory report file [xtmemory.kcg.%%p]\n"
159 " uncommon user options for all Valgrind tools:\n"
160 " --fullpath-after= (with nothing after the '=')\n"
161 " show full source paths in call stacks\n"
162 " --fullpath-after=string like --fullpath-after=, but only show the\n"
163 " part of the path after 'string'. Allows removal\n"
164 " of path prefixes. Use this flag multiple times\n"
165 " to specify a set of prefixes to remove.\n"
166 " --extra-debuginfo-path=path absolute path to search for additional\n"
167 " debug symbols, in addition to existing default\n"
168 " well known search paths.\n"
169 " --debuginfo-server=ipaddr:port also query this server\n"
170 " (valgrind-di-server) for debug symbols\n"
171 " --allow-mismatched-debuginfo=no|yes [no]\n"
172 " for the above two flags only, accept debuginfo\n"
173 " objects that don't \"match\" the main object\n"
174 " --smc-check=none|stack|all|all-non-file [all-non-file]\n"
175 " checks for self-modifying code: none, only for\n"
176 " code found in stacks, for all code, or for all\n"
177 " code except that from file-backed mappings\n"
178 " --read-inline-info=yes|no read debug info about inlined function calls\n"
179 " and use it to do better stack traces. [yes]\n"
180 " on Linux/Android/Solaris for Memcheck/Helgrind/DRD\n"
181 " only. [no] for all other tools and platforms.\n"
182 " --read-var-info=yes|no read debug info on stack and global variables\n"
183 " and use it to print better error messages in\n"
184 " tools that make use of it (Memcheck, Helgrind,\n"
186 " --vgdb-poll=<number> gdbserver poll max every <number> basic blocks [%d] \n"
187 " --vgdb-shadow-registers=no|yes let gdb see the shadow registers [no]\n"
188 " --vgdb-prefix=<prefix> prefix for vgdb FIFOs [%s]\n"
189 " --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]\n"
190 " --run-cxx-freeres=no|yes free up libstdc++ memory at exit on Linux\n"
191 " and Solaris? [yes]\n"
192 " --sim-hints=hint1,hint2,... activate unusual sim behaviours [none] \n"
193 " where hint is one of:\n"
194 " lax-ioctls lax-doors fuse-compatible enable-outer\n"
195 " no-inner-prefix no-nptl-pthread-stackcache fallback-llsc none\n"
196 " --fair-sched=no|yes|try schedule threads fairly on multicore systems [no]\n"
197 " --kernel-variant=variant1,variant2,...\n"
198 " handle non-standard kernel variants [none]\n"
199 " where variant is one of:\n"
200 " bproc android-no-hw-tls\n"
201 " android-gpu-sgx5xx android-gpu-adreno3xx none\n"
202 " --merge-recursive-frames=<number> merge frames between identical\n"
203 " program counters in max <number> frames) [0]\n"
204 " --num-transtab-sectors=<number> size of translated code cache [%d]\n"
205 " more sectors may increase performance, but use more memory.\n"
206 " --avg-transtab-entry-size=<number> avg size in bytes of a translated\n"
207 " basic block [0, meaning use tool provided default]\n"
208 " --aspace-minaddr=0xPP avoid mapping memory below 0xPP [guessed]\n"
209 " --valgrind-stacksize=<number> size of valgrind (host) thread's stack\n"
211 VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)
213 " --show-emwarns=no|yes show warnings about emulation limits? [no]\n"
214 " --require-text-symbol=:sonamepattern:symbolpattern abort run if the\n"
215 " stated shared object doesn't have the stated\n"
216 " text symbol. Patterns can contain ? and *.\n"
217 " --soname-synonyms=syn1=pattern1,syn2=pattern2,... synonym soname\n"
218 " specify patterns for function wrapping or replacement.\n"
219 " To use a non-libc malloc library that is\n"
220 " in the main exe: --soname-synonyms=somalloc=NONE\n"
221 " in libxyzzy.so: --soname-synonyms=somalloc=libxyzzy.so\n"
222 " --sigill-diagnostics=yes|no warn about illegal instructions? [yes]\n"
223 " --unw-stack-scan-thresh=<number> Enable stack-scan unwind if fewer\n"
224 " than <number> good frames found [0, meaning \"disabled\"]\n"
225 " NOTE: stack scanning is only available on arm-linux.\n"
226 " --unw-stack-scan-frames=<number> Max number of frames that can be\n"
227 " recovered by stack scanning [5]\n"
228 " --resync-filter=no|yes|verbose [yes on MacOS, no on other OSes]\n"
229 " attempt to avoid expensive address-space-resync operations\n"
230 " --max-threads=<number> maximum number of threads that valgrind can\n"
234 const HChar usage2
[] =
236 " debugging options for all Valgrind tools:\n"
237 " -d show verbose debugging output\n"
238 " --stats=no|yes show tool and core statistics [no]\n"
239 " --sanity-level=<number> level of sanity checking to do [1]\n"
240 " --trace-flags=<XXXXXXXX> show generated code? (X = 0|1) [00000000]\n"
241 " --profile-flags=<XXXXXXXX> ditto, but for profiling (X = 0|1) [00000000]\n"
242 " --profile-interval=<number> show profile every <number> event checks\n"
243 " [0, meaning only at the end of the run]\n"
244 " --trace-notbelow=<number> only show BBs above <number> [999999999]\n"
245 " --trace-notabove=<number> only show BBs below <number> [0]\n"
246 " --trace-syscalls=no|yes show all system calls? [no]\n"
247 " --trace-signals=no|yes show signal handling details? [no]\n"
248 " --trace-symtab=no|yes show symbol table details? [no]\n"
249 " --trace-symtab-patt=<patt> limit debuginfo tracing to obj name <patt>\n"
250 " --trace-cfi=no|yes show call-frame-info details? [no]\n"
251 " --debug-dump=syms mimic /usr/bin/readelf --syms\n"
252 " --debug-dump=line mimic /usr/bin/readelf --debug-dump=line\n"
253 " --debug-dump=frames mimic /usr/bin/readelf --debug-dump=frames\n"
254 " --trace-redir=no|yes show redirection details? [no]\n"
255 " --trace-sched=no|yes show thread scheduler details? [no]\n"
256 " --profile-heap=no|yes profile Valgrind's own space use\n"
257 " --core-redzone-size=<number> set minimum size of redzones added before/after\n"
258 " heap blocks allocated for Valgrind internal use (in bytes) [4]\n"
259 " --wait-for-gdb=yes|no pause on startup to wait for gdb attach\n"
260 " --sym-offsets=yes|no show syms in form 'name+offset'? [no]\n"
261 " --progress-interval=<number> report progress every <number>\n"
262 " CPU seconds [0, meaning disabled]\n"
263 " --command-line-only=no|yes only use command line options [no]\n"
265 " Vex options for all Valgrind tools:\n"
266 " --vex-iropt-verbosity=<0..9> [0]\n"
267 " --vex-iropt-level=<0..2> [2]\n"
268 " --vex-iropt-unroll-thresh=<0..400> [120]\n"
269 " --vex-guest-max-insns=<1..100> [50]\n"
270 " --vex-guest-chase-thresh=<0..99> [10]\n"
271 " --vex-guest-chase-cond=no|yes [no]\n"
272 " Precise exception control. Possible values for 'mode' are as follows\n"
273 " and specify the minimum set of registers guaranteed to be correct\n"
274 " immediately prior to memory access instructions:\n"
275 " sp-at-mem-access stack pointer only\n"
276 " unwindregs-at-mem-access registers needed for stack unwinding\n"
277 " allregs-at-mem-access all registers\n"
278 " allregs-at-each-insn all registers are always correct\n"
279 " Default value for all 3 following flags is [unwindregs-at-mem-access].\n"
280 " --vex-iropt-register-updates=mode setting to use by default\n"
281 " --px-default=mode synonym for --vex-iropt-register-updates\n"
282 " --px-file-backed=mode optional setting for file-backed (non-JIT) code\n"
283 " Tracing and profile control:\n"
284 " --trace-flags and --profile-flags values (omit the middle space):\n"
285 " 1000 0000 show conversion into IR\n"
286 " 0100 0000 show after initial opt\n"
287 " 0010 0000 show after instrumentation\n"
288 " 0001 0000 show after second opt\n"
289 " 0000 1000 show after tree building\n"
290 " 0000 0100 show selecting insns\n"
291 " 0000 0010 show after reg-alloc\n"
292 " 0000 0001 show final assembly\n"
293 " 0000 0000 show summary profile only\n"
294 " (Nb: you need --trace-notbelow and/or --trace-notabove\n"
295 " with --trace-flags for full details)\n"
296 " --vex-regalloc-version=2|3 [3]\n"
298 " debugging options for Valgrind tools that report errors\n"
299 " --dump-error=<number> show translation for basic block associated\n"
300 " with <number>'th error context [0=show none]\n"
302 " debugging options for Valgrind tools that replace malloc:\n"
303 " --trace-malloc=no|yes show client malloc details? [no]\n"
304 " --xtree-compress-strings=no|yes compress strings in xtree callgrind format [yes]\n"
307 const HChar usage3
[] =
309 " Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc\n"
312 " Valgrind is Copyright (C) 2000-2017, and GNU GPL'd, by Julian Seward et al.\n"
313 " LibVEX is Copyright (C) 2004-2017, and GNU GPL'd, by OpenWorks LLP et al.\n"
315 " Bug reports, feedback, admiration, abuse, etc, to: %s.\n"
318 HChar default_alignment
[30]; // large enough
319 HChar default_redzone_size
[30]; // large enough
321 // Ensure the message goes to stdout
322 VG_(log_output_sink
).fd
= 1;
323 VG_(log_output_sink
).type
= VgLogTo_Fd
;
325 if (VG_(needs
).malloc_replacement
) {
326 VG_(sprintf
)(default_alignment
, "%d", VG_MIN_MALLOC_SZB
);
327 VG_(sprintf
)(default_redzone_size
, "%lu", VG_(tdict
).tool_client_redzone_szB
);
329 VG_(strcpy
)(default_alignment
, "not used by this tool");
330 VG_(strcpy
)(default_redzone_size
, "not used by this tool");
332 /* 'usage1' a type as described after each arg. */
334 VG_(clo_vgdb_error
) /* int */,
335 default_alignment
/* char* */,
336 default_redzone_size
/* char* */,
337 VG_(clo_vgdb_poll
) /* int */,
338 VG_(vgdb_prefix_default
)() /* char* */,
339 N_SECTORS_DEFAULT
/* int */,
340 MAX_THREADS_DEFAULT
/* int */
342 if (VG_(details
).name
) {
343 VG_(printf
)(" user options for %s:\n", VG_(details
).name
);
344 if (VG_(needs
).command_line_options
)
345 VG_TDICT_CALL(tool_print_usage
);
347 VG_(printf
)(" (none)\n");
350 VG_(printf
)("%s", usage2
);
352 if (VG_(details
).name
) {
353 VG_(printf
)(" debugging options for %s:\n", VG_(details
).name
);
355 if (VG_(needs
).command_line_options
)
356 VG_TDICT_CALL(tool_print_debug_usage
);
358 VG_(printf
)(" (none)\n");
361 VG_(printf
)(usage3
, VG_(details
).name
, VG_(details
).copyright_author
,
367 /* Peer at previously set up VG_(args_for_valgrind) and do some
368 minimal command line processing that must happen early on:
370 - show the version string, if requested (-v)
371 - extract any request for help (--help, -h, --help-debug)
372 - set VG_(toolname) (--tool=)
373 - set VG_(clo_max_stackframe) (--max-stackframe=)
374 - set VG_(clo_main_stacksize) (--main-stacksize=)
375 - set VG_(clo_sim_hints) (--sim-hints=)
376 - set VG_(clo_max_threads) (--max-threads)
378 That's all it does. The main command line processing is done below
379 by main_process_cmd_line_options. Note that
380 main_process_cmd_line_options has to handle but ignore the ones we
383 static void early_process_cmd_line_options ( /*OUT*/Int
* need_help
)
387 Int need_version
= 0;
389 vg_assert( VG_(args_for_valgrind
) );
391 /* parse the options we have (only the options we care about now) */
392 for (i
= 0; i
< VG_(sizeXA
)( VG_(args_for_valgrind
) ); i
++) {
394 str
= * (HChar
**) VG_(indexXA
)( VG_(args_for_valgrind
), i
);
397 if VG_XACT_CLO(str
, "--version", need_version
, 1) {}
398 else if (VG_STREQ(str
, "-v") ||
399 VG_STREQ(str
, "--verbose"))
400 VG_(clo_verbosity
)++;
401 else if (VG_STREQ(str
, "-q") ||
402 VG_STREQ(str
, "--quiet"))
403 VG_(clo_verbosity
)--;
404 else if VG_XACT_CLO(str
, "--help", *need_help
, *need_help
+1) {}
405 else if VG_XACT_CLO(str
, "-h", *need_help
, *need_help
+1) {}
407 else if VG_XACT_CLO(str
, "--help-debug", *need_help
, *need_help
+2) {}
409 // The tool has already been determined, but we need to know the name
411 else if VG_STR_CLO(str
, "--tool", VG_(clo_toolname
)) {}
413 // Set up VG_(clo_max_stackframe) and VG_(clo_main_stacksize).
414 // These are needed by VG_(ii_create_image), which happens
415 // before main_process_cmd_line_options().
416 else if VG_INT_CLO(str
, "--max-stackframe", VG_(clo_max_stackframe
)) {}
417 else if VG_INT_CLO(str
, "--main-stacksize", VG_(clo_main_stacksize
)) {}
419 // Set up VG_(clo_max_threads); needed for VG_(tl_pre_clo_init)
420 else if VG_INT_CLO(str
, "--max-threads", VG_(clo_max_threads
)) {}
422 // Set up VG_(clo_sim_hints). This is needed a.o. for an inner
423 // running in an outer, to have "no-inner-prefix" enabled
424 // as early as possible.
425 else if VG_USETX_CLO (str
, "--sim-hints",
426 "lax-ioctls,lax-doors,fuse-compatible,"
427 "enable-outer,no-inner-prefix,"
428 "no-nptl-pthread-stackcache,fallback-llsc",
429 VG_(clo_sim_hints
)) {}
433 // Nb: the version string goes to stdout.
434 VG_(log_output_sink
).fd
= 1;
435 VG_(log_output_sink
).type
= VgLogTo_Fd
;
436 if (VG_(clo_verbosity
) <= 1)
437 VG_(printf
)("valgrind-" VERSION
"\n");
439 VG_(printf
)("valgrind-" VERSION
"-" VGGIT
"\n");
443 /* For convenience */
444 VG_N_THREADS
= VG_(clo_max_threads
);
446 # if defined(VGO_solaris) || defined(VGO_darwin)
447 /* Sim hint no-nptl-pthread-stackcache should be ignored. */
448 VG_(clo_sim_hints
) &= ~SimHint2S(SimHint_no_nptl_pthread_stackcache
);
452 /* The main processing for command line options. See comments above
453 on early_process_cmd_line_options. */
455 void main_process_cmd_line_options( void )
458 Int toolname_len
= VG_(strlen
)(VG_(clo_toolname
));
459 const HChar
* tmp_str
; // Used in a couple of places.
461 /* Whether the user has explicitly provided --sigill-diagnostics.
462 If not explicitly given depends on general verbosity setting. */
463 Bool sigill_diag_set
= False
;
465 /* Log to stderr by default, but usage message goes to stdout. XML
466 output is initially disabled. */
467 VgLogTo log_to
= VgLogTo_Fd
; // Where is logging output to be sent?
468 VgLogTo xml_to
= VgLogTo_Fd
; // Where is XML output to be sent?
472 /* Check for sane path in ./configure --prefix=... */
473 if (VG_LIBDIR
[0] != '/')
474 VG_(err_config_error
)("Please use absolute paths in "
475 "./configure --prefix=... or --libdir=...\n");
477 vg_assert( VG_(args_for_valgrind
) );
479 VG_(clo_suppressions
) = VG_(newXA
)(VG_(malloc
), "main.mpclo.4",
480 VG_(free
), sizeof(HChar
*));
481 VG_(clo_fullpath_after
) = VG_(newXA
)(VG_(malloc
), "main.mpclo.5",
482 VG_(free
), sizeof(HChar
*));
483 VG_(clo_req_tsyms
) = VG_(newXA
)(VG_(malloc
), "main.mpclo.6",
484 VG_(free
), sizeof(HChar
*));
486 /* Constants for parsing PX control flags. */
487 const HChar
* pxStrings
[5]
488 = { "sp-at-mem-access", "unwindregs-at-mem-access",
489 "allregs-at-mem-access", "allregs-at-each-insn", NULL
};
490 const VexRegisterUpdates pxVals
[5]
491 = { VexRegUpdSpAtMemAccess
, VexRegUpdUnwindregsAtMemAccess
,
492 VexRegUpdAllregsAtMemAccess
, VexRegUpdAllregsAtEachInsn
, 0/*inval*/ };
494 /* BEGIN command-line processing loop */
496 for (i
= 0; i
< VG_(sizeXA
)( VG_(args_for_valgrind
) ); i
++) {
498 HChar
* arg
= * (HChar
**) VG_(indexXA
)( VG_(args_for_valgrind
), i
);
502 // Look for a colon in the option name.
503 while (*colon
&& *colon
!= ':' && *colon
!= '=')
506 // Does it have the form "--toolname:foo"? We have to do it at the start
507 // in case someone has combined a prefix with a core-specific option,
508 // eg. "--memcheck:verbose".
510 if (VG_STREQN(2, arg
, "--") &&
511 VG_STREQN(toolname_len
, arg
+2, VG_(clo_toolname
)) &&
512 VG_STREQN(1, arg
+2+toolname_len
, ":"))
514 // Prefix matches, convert "--toolname:foo" to "--foo".
515 // Two things to note:
516 // - We cannot modify the option in-place. If we did, and then
517 // a child was spawned with --trace-children=yes, the
518 // now-non-prefixed option would be passed and could screw up
520 // - We create copies, and never free them. Why? Non-prefixed
521 // options hang around forever, so tools need not make copies
522 // of strings within them. We need to have the same behaviour
523 // for prefixed options. The pointer to the copy will be lost
524 // once we leave this function (although a tool may keep a
525 // pointer into it), but the space wasted is insignificant.
526 // (In bug #142197, the copies were being freed, which caused
527 // problems for tools that reasonably assumed that arguments
528 // wouldn't disappear on them.)
530 VG_(printf
)("tool-specific arg: %s\n", arg
);
531 arg
= VG_(strdup
)("main.mpclo.1", arg
+ toolname_len
+ 1);
536 // prefix doesn't match, skip to next arg
541 /* Ignore these options - they've already been handled */
542 if VG_STREQN( 7, arg
, "--tool=") {}
543 else if VG_STREQN(20, arg
, "--command-line-only=") {}
544 else if VG_STREQ( arg
, "--") {}
545 else if VG_STREQ( arg
, "-d") {}
546 else if VG_STREQ( arg
, "-q") {}
547 else if VG_STREQ( arg
, "--quiet") {}
548 else if VG_STREQ( arg
, "-v") {}
549 else if VG_STREQ( arg
, "--verbose") {}
550 else if VG_STREQN(17, arg
, "--max-stackframe=") {}
551 else if VG_STREQN(17, arg
, "--main-stacksize=") {}
552 else if VG_STREQN(14, arg
, "--max-threads=") {}
553 else if VG_STREQN(12, arg
, "--sim-hints=") {}
554 else if VG_STREQN(15, arg
, "--profile-heap=") {}
555 else if VG_STREQN(20, arg
, "--core-redzone-size=") {}
556 else if VG_STREQN(15, arg
, "--redzone-size=") {}
557 else if VG_STREQN(17, arg
, "--aspace-minaddr=") {}
559 else if VG_BINT_CLO(arg
, "--valgrind-stacksize",
560 VG_(clo_valgrind_stacksize
),
561 2*VKI_PAGE_SIZE
, 10*VG_DEFAULT_STACK_ACTIVE_SZB
)
562 {VG_(clo_valgrind_stacksize
)
563 = VG_PGROUNDUP(VG_(clo_valgrind_stacksize
));}
565 /* Obsolete options. Report an error and exit */
566 else if VG_STREQN(34, arg
, "--vex-iropt-precise-memory-exns=no") {
569 "--vex-iropt-precise-memory-exns is obsolete\n"
570 "Use --vex-iropt-register-updates=unwindregs-at-mem-access instead\n");
572 else if VG_STREQN(35, arg
, "--vex-iropt-precise-memory-exns=yes") {
575 "--vex-iropt-precise-memory-exns is obsolete\n"
576 "Use --vex-iropt-register-updates=allregs-at-mem-access instead\n"
577 " (or --vex-iropt-register-updates=allregs-at-each-insn)\n");
580 /* These options are new, not yet handled by
581 early_process_cmd_line_options. */
582 else if VG_BOOL_CLO(arg
, "--sigill-diagnostics", VG_(clo_sigill_diag
))
583 sigill_diag_set
= True
;
585 else if VG_BOOL_CLO(arg
, "--stats", VG_(clo_stats
)) {}
586 else if VG_BOOL_CLO(arg
, "--xml", VG_(clo_xml
))
587 VG_(debugLog_setXml
)(VG_(clo_xml
));
589 else if VG_XACT_CLO(arg
, "--vgdb=no", VG_(clo_vgdb
), Vg_VgdbNo
) {}
590 else if VG_XACT_CLO(arg
, "--vgdb=yes", VG_(clo_vgdb
), Vg_VgdbYes
) {}
591 else if VG_XACT_CLO(arg
, "--vgdb=full", VG_(clo_vgdb
), Vg_VgdbFull
) {
592 /* automatically updates register values at each insn
594 VG_(clo_vex_control
).iropt_register_updates_default
595 = VG_(clo_px_file_backed
)
596 = VexRegUpdAllregsAtEachInsn
;
598 else if VG_INT_CLO (arg
, "--vgdb-poll", VG_(clo_vgdb_poll
)) {}
599 else if VG_INT_CLO (arg
, "--vgdb-error", VG_(clo_vgdb_error
)) {}
600 else if VG_USET_CLO (arg
, "--vgdb-stop-at",
601 "startup,exit,valgrindabexit",
602 VG_(clo_vgdb_stop_at
)) {}
603 else if VG_STR_CLO (arg
, "--vgdb-prefix", VG_(clo_vgdb_prefix
)) {
604 VG_(arg_vgdb_prefix
) = arg
;
606 else if VG_BOOL_CLO(arg
, "--vgdb-shadow-registers",
607 VG_(clo_vgdb_shadow_registers
)) {}
608 else if VG_BOOL_CLO(arg
, "--demangle", VG_(clo_demangle
)) {}
609 else if VG_STR_CLO (arg
, "--soname-synonyms",VG_(clo_soname_synonyms
)) {}
610 else if VG_BOOL_CLO(arg
, "--error-limit", VG_(clo_error_limit
)) {}
611 else if VG_BOOL_CLO(arg
, "--exit-on-first-error", VG_(clo_exit_on_first_error
)) {}
612 else if VG_INT_CLO (arg
, "--error-exitcode", VG_(clo_error_exitcode
)) {}
613 else if VG_STR_CLO (arg
, "--error-markers", tmp_str
) {
615 const HChar
*startpos
= tmp_str
;
616 const HChar
*nextpos
;
618 m
< sizeof(VG_(clo_error_markers
))
619 /sizeof(VG_(clo_error_markers
)[0]);
621 /* Release previous value if clo given multiple times. */
622 VG_(free
)(VG_(clo_error_markers
)[m
]);
623 VG_(clo_error_markers
)[m
] = NULL
;
625 nextpos
= VG_(strchr
)(startpos
, ',');
627 nextpos
= startpos
+ VG_(strlen
)(startpos
);
628 if (startpos
!= nextpos
) {
629 VG_(clo_error_markers
)[m
]
630 = VG_(malloc
)("main.mpclo.2", nextpos
- startpos
+ 1);
631 VG_(memcpy
)(VG_(clo_error_markers
)[m
], startpos
,
633 VG_(clo_error_markers
)[m
][nextpos
- startpos
] = '\0';
635 startpos
= *nextpos
? nextpos
+ 1 : nextpos
;
638 else if VG_BOOL_CLO(arg
, "--show-emwarns", VG_(clo_show_emwarns
)) {}
640 else if VG_BOOL_CLO(arg
, "--run-libc-freeres", VG_(clo_run_libc_freeres
)) {}
641 else if VG_BOOL_CLO(arg
, "--run-cxx-freeres", VG_(clo_run_cxx_freeres
)) {}
642 else if VG_BOOL_CLO(arg
, "--show-below-main", VG_(clo_show_below_main
)) {}
643 else if VG_BOOL_CLO(arg
, "--keep-debuginfo", VG_(clo_keep_debuginfo
)) {}
644 else if VG_BOOL_CLO(arg
, "--time-stamp", VG_(clo_time_stamp
)) {}
645 else if VG_BOOL_CLO(arg
, "--track-fds", VG_(clo_track_fds
)) {}
646 else if VG_BOOL_CLO(arg
, "--trace-children", VG_(clo_trace_children
)) {}
647 else if VG_BOOL_CLO(arg
, "--child-silent-after-fork",
648 VG_(clo_child_silent_after_fork
)) {}
649 else if VG_STR_CLO(arg
, "--fair-sched", tmp_str
) {
650 if (VG_(strcmp
)(tmp_str
, "yes") == 0)
651 VG_(clo_fair_sched
) = enable_fair_sched
;
652 else if (VG_(strcmp
)(tmp_str
, "try") == 0)
653 VG_(clo_fair_sched
) = try_fair_sched
;
654 else if (VG_(strcmp
)(tmp_str
, "no") == 0)
655 VG_(clo_fair_sched
) = disable_fair_sched
;
657 VG_(fmsg_bad_option
)(arg
,
658 "Bad argument, should be 'yes', 'try' or 'no'\n");
660 else if VG_BOOL_CLO(arg
, "--trace-sched", VG_(clo_trace_sched
)) {}
661 else if VG_BOOL_CLO(arg
, "--trace-signals", VG_(clo_trace_signals
)) {}
662 else if VG_BOOL_CLO(arg
, "--trace-symtab", VG_(clo_trace_symtab
)) {}
663 else if VG_STR_CLO (arg
, "--trace-symtab-patt", VG_(clo_trace_symtab_patt
)) {}
664 else if VG_BOOL_CLO(arg
, "--trace-cfi", VG_(clo_trace_cfi
)) {}
665 else if VG_XACT_CLO(arg
, "--debug-dump=syms", VG_(clo_debug_dump_syms
),
667 else if VG_XACT_CLO(arg
, "--debug-dump=line", VG_(clo_debug_dump_line
),
669 else if VG_XACT_CLO(arg
, "--debug-dump=frames",
670 VG_(clo_debug_dump_frames
), True
) {}
671 else if VG_BOOL_CLO(arg
, "--trace-redir", VG_(clo_trace_redir
)) {}
673 else if VG_BOOL_CLO(arg
, "--trace-syscalls", VG_(clo_trace_syscalls
)) {}
674 else if VG_BOOL_CLO(arg
, "--wait-for-gdb", VG_(clo_wait_for_gdb
)) {}
675 else if VG_BOOL_CLO(arg
, "--sym-offsets", VG_(clo_sym_offsets
)) {}
676 else if VG_BINT_CLO(arg
, "--progress-interval",
677 VG_(clo_progress_interval
), 0, 3600) {}
678 else if VG_BOOL_CLO(arg
, "--read-inline-info", VG_(clo_read_inline_info
)) {}
679 else if VG_BOOL_CLO(arg
, "--read-var-info", VG_(clo_read_var_info
)) {}
681 else if VG_INT_CLO (arg
, "--dump-error", VG_(clo_dump_error
)) {}
682 else if VG_INT_CLO (arg
, "--input-fd", VG_(clo_input_fd
)) {}
683 else if VG_INT_CLO (arg
, "--sanity-level", VG_(clo_sanity_level
)) {}
684 else if VG_BINT_CLO(arg
, "--num-callers", VG_(clo_backtrace_size
), 1,
685 VG_DEEPEST_BACKTRACE
) {}
686 else if VG_BINT_CLO(arg
, "--num-transtab-sectors",
687 VG_(clo_num_transtab_sectors
),
688 MIN_N_SECTORS
, MAX_N_SECTORS
) {}
689 else if VG_BINT_CLO(arg
, "--avg-transtab-entry-size",
690 VG_(clo_avg_transtab_entry_size
),
692 else if VG_BINT_CLO(arg
, "--merge-recursive-frames",
693 VG_(clo_merge_recursive_frames
), 0,
694 VG_DEEPEST_BACKTRACE
) {}
696 else if VG_XACT_CLO(arg
, "--smc-check=none",
697 VG_(clo_smc_check
), Vg_SmcNone
) {}
698 else if VG_XACT_CLO(arg
, "--smc-check=stack",
699 VG_(clo_smc_check
), Vg_SmcStack
) {}
700 else if VG_XACT_CLO(arg
, "--smc-check=all",
701 VG_(clo_smc_check
), Vg_SmcAll
) {}
702 else if VG_XACT_CLO(arg
, "--smc-check=all-non-file",
703 VG_(clo_smc_check
), Vg_SmcAllNonFile
) {}
705 else if VG_USETX_CLO (arg
, "--kernel-variant",
708 "android-gpu-sgx5xx,"
709 "android-gpu-adreno3xx",
710 VG_(clo_kernel_variant
)) {}
712 else if VG_BOOL_CLO(arg
, "--dsymutil", VG_(clo_dsymutil
)) {}
714 else if VG_STR_CLO (arg
, "--trace-children-skip",
715 VG_(clo_trace_children_skip
)) {}
716 else if VG_STR_CLO (arg
, "--trace-children-skip-by-arg",
717 VG_(clo_trace_children_skip_by_arg
)) {}
719 else if VG_BINT_CLO(arg
, "--vex-iropt-verbosity",
720 VG_(clo_vex_control
).iropt_verbosity
, 0, 10) {}
721 else if VG_BINT_CLO(arg
, "--vex-iropt-level",
722 VG_(clo_vex_control
).iropt_level
, 0, 2) {}
723 else if VG_BINT_CLO(arg
, "--vex-regalloc-version",
724 VG_(clo_vex_control
).regalloc_version
, 2, 3) {}
726 else if VG_STRINDEX_CLO(arg
, "--vex-iropt-register-updates",
729 vg_assert(pxVals
[ix
] >= VexRegUpdSpAtMemAccess
);
730 vg_assert(pxVals
[ix
] <= VexRegUpdAllregsAtEachInsn
);
731 VG_(clo_vex_control
).iropt_register_updates_default
= pxVals
[ix
];
733 else if VG_STRINDEX_CLO(arg
, "--px-default", pxStrings
, ix
) {
734 // NB: --px-default is an alias for the hard-to-remember
735 // --vex-iropt-register-updates, hence the same logic.
737 vg_assert(pxVals
[ix
] >= VexRegUpdSpAtMemAccess
);
738 vg_assert(pxVals
[ix
] <= VexRegUpdAllregsAtEachInsn
);
739 VG_(clo_vex_control
).iropt_register_updates_default
= pxVals
[ix
];
741 else if VG_STRINDEX_CLO(arg
, "--px-file-backed", pxStrings
, ix
) {
742 // Whereas --px-file-backed isn't
743 // the same flag as --vex-iropt-register-updates.
745 vg_assert(pxVals
[ix
] >= VexRegUpdSpAtMemAccess
);
746 vg_assert(pxVals
[ix
] <= VexRegUpdAllregsAtEachInsn
);
747 VG_(clo_px_file_backed
) = pxVals
[ix
];
750 else if VG_BINT_CLO(arg
, "--vex-iropt-unroll-thresh",
751 VG_(clo_vex_control
).iropt_unroll_thresh
, 0, 400) {}
752 else if VG_BINT_CLO(arg
, "--vex-guest-max-insns",
753 VG_(clo_vex_control
).guest_max_insns
, 1, 100) {}
754 else if VG_BINT_CLO(arg
, "--vex-guest-chase-thresh",
755 VG_(clo_vex_control
).guest_chase_thresh
, 0, 99) {}
756 else if VG_BOOL_CLO(arg
, "--vex-guest-chase-cond",
757 VG_(clo_vex_control
).guest_chase_cond
) {}
759 else if VG_INT_CLO(arg
, "--log-fd", tmp_log_fd
) {
761 VG_(clo_log_fname_unexpanded
) = NULL
;
763 else if VG_INT_CLO(arg
, "--xml-fd", tmp_xml_fd
) {
765 VG_(clo_xml_fname_unexpanded
) = NULL
;
768 else if VG_STR_CLO(arg
, "--log-file", VG_(clo_log_fname_unexpanded
)) {
769 log_to
= VgLogTo_File
;
771 else if VG_STR_CLO(arg
, "--xml-file", VG_(clo_xml_fname_unexpanded
)) {
772 xml_to
= VgLogTo_File
;
775 else if VG_STR_CLO(arg
, "--log-socket", VG_(clo_log_fname_unexpanded
)) {
776 log_to
= VgLogTo_Socket
;
778 else if VG_STR_CLO(arg
, "--xml-socket", VG_(clo_xml_fname_unexpanded
)) {
779 xml_to
= VgLogTo_Socket
;
782 else if VG_STR_CLO(arg
, "--debuginfo-server",
783 VG_(clo_debuginfo_server
)) {}
785 else if VG_BOOL_CLO(arg
, "--allow-mismatched-debuginfo",
786 VG_(clo_allow_mismatched_debuginfo
)) {}
788 else if VG_STR_CLO(arg
, "--xml-user-comment",
789 VG_(clo_xml_user_comment
)) {}
791 else if VG_BOOL_CLO(arg
, "--default-suppressions",
792 VG_(clo_default_supp
)) {}
794 else if VG_STR_CLO(arg
, "--suppressions", tmp_str
) {
795 VG_(addToXA
)(VG_(clo_suppressions
), &tmp_str
);
798 else if VG_STR_CLO (arg
, "--fullpath-after", tmp_str
) {
799 VG_(addToXA
)(VG_(clo_fullpath_after
), &tmp_str
);
802 else if VG_STR_CLO (arg
, "--extra-debuginfo-path",
803 VG_(clo_extra_debuginfo_path
)) {}
805 else if VG_STR_CLO(arg
, "--require-text-symbol", tmp_str
) {
806 /* String needs to be of the form C?*C?*, where C is any
807 character, but is the same both times. Having it in this
808 form facilitates finding the boundary between the sopatt
809 and the fnpatt just by looking for the second occurrence
810 of C, without hardwiring any assumption about what C
814 ok
= tmp_str
&& VG_(strlen
)(tmp_str
) > 0;
816 patt
[0] = patt
[3] = tmp_str
[0];
817 patt
[1] = patt
[4] = '?';
818 patt
[2] = patt
[5] = '*';
820 ok
= VG_(string_match
)(patt
, tmp_str
);
823 VG_(fmsg_bad_option
)(arg
,
824 "Invalid --require-text-symbol= specification.\n");
826 VG_(addToXA
)(VG_(clo_req_tsyms
), &tmp_str
);
829 /* "stuvwxyz" --> stuvwxyz (binary) */
830 else if VG_STR_CLO(arg
, "--trace-flags", tmp_str
) {
832 if (8 != VG_(strlen
)(tmp_str
)) {
833 VG_(fmsg_bad_option
)(arg
,
834 "--trace-flags argument must have 8 digits\n");
836 for (j
= 0; j
< 8; j
++) {
837 if ('0' == tmp_str
[j
]) { /* do nothing */ }
838 else if ('1' == tmp_str
[j
]) VG_(clo_trace_flags
) |= (1 << (7-j
));
840 VG_(fmsg_bad_option
)(arg
,
841 "--trace-flags argument can only contain 0s and 1s\n");
846 else if VG_INT_CLO (arg
, "--trace-notbelow", VG_(clo_trace_notbelow
)) {}
848 else if VG_INT_CLO (arg
, "--trace-notabove", VG_(clo_trace_notabove
)) {}
850 /* "stuvwxyz" --> stuvwxyz (binary) */
851 else if VG_STR_CLO(arg
, "--profile-flags", tmp_str
) {
853 if (8 != VG_(strlen
)(tmp_str
)) {
854 VG_(fmsg_bad_option
)(arg
,
855 "--profile-flags argument must have 8 digits\n");
857 for (j
= 0; j
< 8; j
++) {
858 if ('0' == tmp_str
[j
]) { /* do nothing */ }
859 else if ('1' == tmp_str
[j
]) VG_(clo_profyle_flags
) |= (1 << (7-j
));
861 VG_(fmsg_bad_option
)(arg
,
862 "--profile-flags argument can only contain 0s and 1s\n");
865 VG_(clo_profyle_sbs
) = True
;
868 else if VG_INT_CLO (arg
, "--profile-interval",
869 VG_(clo_profyle_interval
)) {}
871 else if VG_XACT_CLO(arg
, "--gen-suppressions=no",
872 VG_(clo_gen_suppressions
), 0) {}
873 else if VG_XACT_CLO(arg
, "--gen-suppressions=yes",
874 VG_(clo_gen_suppressions
), 1) {}
875 else if VG_XACT_CLO(arg
, "--gen-suppressions=all",
876 VG_(clo_gen_suppressions
), 2) {}
878 else if VG_BINT_CLO(arg
, "--unw-stack-scan-thresh",
879 VG_(clo_unw_stack_scan_thresh
), 0, 100) {}
880 else if VG_BINT_CLO(arg
, "--unw-stack-scan-frames",
881 VG_(clo_unw_stack_scan_frames
), 0, 32) {}
883 else if VG_XACT_CLO(arg
, "--resync-filter=no",
884 VG_(clo_resync_filter
), 0) {}
885 else if VG_XACT_CLO(arg
, "--resync-filter=yes",
886 VG_(clo_resync_filter
), 1) {}
887 else if VG_XACT_CLO(arg
, "--resync-filter=verbose",
888 VG_(clo_resync_filter
), 2) {}
890 else if ( ! VG_(needs
).command_line_options
891 || ! VG_TDICT_CALL(tool_process_cmd_line_option
, arg
) ) {
892 VG_(fmsg_unknown_option
)(arg
);
896 /* END command-line processing loop */
898 /* Notify about deprecated features here. */
900 /* Determine the path prefix for vgdb */
901 if (VG_(clo_vgdb_prefix
) == NULL
)
902 VG_(clo_vgdb_prefix
) = VG_(vgdb_prefix_default
)();
904 /* Make VEX control parameters sane */
906 if (VG_(clo_vex_control
).guest_chase_thresh
907 >= VG_(clo_vex_control
).guest_max_insns
)
908 VG_(clo_vex_control
).guest_chase_thresh
909 = VG_(clo_vex_control
).guest_max_insns
- 1;
911 if (VG_(clo_vex_control
).guest_chase_thresh
< 0)
912 VG_(clo_vex_control
).guest_chase_thresh
= 0;
914 /* Check various option values */
916 if (VG_(clo_verbosity
) < 0)
917 VG_(clo_verbosity
) = 0;
919 if (!sigill_diag_set
)
920 VG_(clo_sigill_diag
) = (VG_(clo_verbosity
) > 0);
922 if (VG_(clo_trace_notbelow
) == -1) {
923 if (VG_(clo_trace_notabove
) == -1) {
925 VG_(clo_trace_notbelow
) = 2147483647;
926 VG_(clo_trace_notabove
) = 0;
928 /* [0 .. notabove] */
929 VG_(clo_trace_notbelow
) = 0;
932 if (VG_(clo_trace_notabove
) == -1) {
934 VG_(clo_trace_notabove
) = 2147483647;
936 /* [notbelow .. notabove] */
940 VG_(dyn_vgdb_error
) = VG_(clo_vgdb_error
);
942 if (VG_(clo_gen_suppressions
) > 0 &&
943 !VG_(needs
).core_errors
&& !VG_(needs
).tool_errors
) {
944 VG_(fmsg_bad_option
)("--gen-suppressions=yes",
945 "Can't use --gen-suppressions= with %s\n"
946 "because it doesn't generate errors.\n", VG_(details
).name
);
948 if ((VG_(clo_exit_on_first_error
)) &&
949 (VG_(clo_error_exitcode
)==0)) {
950 VG_(fmsg_bad_option
)("--exit-on-first-error=yes",
951 "You must define a non nul exit error code, with --error-exitcode=...\n");
954 # if !defined(VGO_darwin)
955 if (VG_(clo_resync_filter
) != 0) {
956 VG_(fmsg_bad_option
)("--resync-filter=yes or =verbose",
957 "--resync-filter= is only available on MacOS X.\n");
962 /* If XML output is requested, check that the tool actually
964 if (VG_(clo_xml
) && !VG_(needs
).xml_output
) {
965 VG_(clo_xml
) = False
;
966 VG_(fmsg_bad_option
)("--xml=yes",
967 "%s does not support XML output.\n", VG_(details
).name
);
971 vg_assert( VG_(clo_gen_suppressions
) >= 0 );
972 vg_assert( VG_(clo_gen_suppressions
) <= 2 );
974 /* If we've been asked to emit XML, mash around various other
975 options so as to constrain the output somewhat, and to remove
976 any need for user input during the run.
980 /* We can't allow --gen-suppressions=yes, since that requires us
981 to print the error and then ask the user if she wants a
982 suppression for it, but in XML mode we won't print it until
983 we know whether we also need to print a suppression. Hence a
984 circular dependency. So disallow this.
985 (--gen-suppressions=all is still OK since we don't need any
986 user interaction in this case.) */
987 if (VG_(clo_gen_suppressions
) == 1) {
988 VG_(fmsg_bad_option
)(
989 "--xml=yes together with --gen-suppressions=yes",
990 "When --xml=yes is specified, --gen-suppressions=no\n"
991 "or --gen-suppressions=all is allowed, but not "
992 "--gen-suppressions=yes.\n");
995 /* Disallow dump_error in XML mode; sounds like a recipe for
996 chaos. No big deal; dump_error is a flag for debugging V
998 if (VG_(clo_dump_error
) > 0) {
999 VG_(fmsg_bad_option
)("--xml=yes",
1000 "Cannot be used together with --dump-error");
1003 /* Disable error limits (this might be a bad idea!) */
1004 VG_(clo_error_limit
) = False
;
1005 /* Disable emulation warnings */
1007 /* Also, we want to set options for the leak checker, but that
1008 will have to be done in Memcheck's flag-handling code, not
1012 /* All non-logging-related options have been checked. If the logging
1013 option specified is ok, we can switch to it, as we know we won't
1014 have to generate any other command-line-related error messages.
1015 (So far we should be still attached to stderr, so we can show on
1016 the terminal any problems to do with processing command line
1018 VG_(init_log_xml_sinks
)(log_to
, xml_to
, tmp_log_fd
, tmp_xml_fd
);
1020 /* Register child at-fork handler which will take care of handling
1021 --child-silent-after-fork clo and also reopening output sinks for forked
1022 children, if requested via --log|xml-file= options. */
1023 VG_(atfork
)(NULL
, NULL
, VG_(logging_atfork_child
));
1025 // Suppressions related stuff
1027 if (VG_(clo_default_supp
) &&
1028 (VG_(needs
).core_errors
|| VG_(needs
).tool_errors
)) {
1029 /* If we haven't reached the max number of suppressions, load
1031 static const HChar default_supp
[] = "default.supp";
1032 Int len
= VG_(strlen
)(VG_(libdir
)) + 1 + sizeof(default_supp
);
1033 HChar
*buf
= VG_(malloc
)("main.mpclo.3", len
);
1034 VG_(sprintf
)(buf
, "%s/%s", VG_(libdir
), default_supp
);
1035 VG_(addToXA
)(VG_(clo_suppressions
), &buf
);
1040 /*====================================================================*/
1041 /*=== File descriptor setup ===*/
1042 /*====================================================================*/
1044 /* Number of file descriptors that Valgrind tries to reserve for
1045 its own use - just a small constant. */
1046 #define N_RESERVED_FDS (12)
1048 static void setup_file_descriptors(void)
1050 struct vki_rlimit rl
;
1053 /* Get the current file descriptor limits. */
1054 if (VG_(getrlimit
)(VKI_RLIMIT_NOFILE
, &rl
) < 0) {
1059 # if defined(VGO_darwin)
1060 /* Darwin lies. It reports file max as RLIM_INFINITY but
1061 silently disallows anything bigger than 10240. */
1062 if (rl
.rlim_cur
>= 10240 && rl
.rlim_max
== 0x7fffffffffffffffULL
) {
1063 rl
.rlim_max
= 10240;
1068 VG_(printf
)("fd limits: host, before: cur %llu max %llu\n",
1069 (ULong
)rl
.rlim_cur
, (ULong
)rl
.rlim_max
);
1071 /* Work out where to move the soft limit to. */
1072 if (rl
.rlim_cur
+ N_RESERVED_FDS
<= rl
.rlim_max
) {
1073 rl
.rlim_cur
= rl
.rlim_cur
+ N_RESERVED_FDS
;
1075 rl
.rlim_cur
= rl
.rlim_max
;
1078 /* Reserve some file descriptors for our use. */
1079 VG_(fd_soft_limit
) = rl
.rlim_cur
- N_RESERVED_FDS
;
1080 VG_(fd_hard_limit
) = rl
.rlim_cur
- N_RESERVED_FDS
;
1082 /* Update the soft limit. */
1083 VG_(setrlimit
)(VKI_RLIMIT_NOFILE
, &rl
);
1086 VG_(printf
)("fd limits: host, after: cur %lu max %lu\n",
1087 (UWord
)rl
.rlim_cur
, (UWord
)rl
.rlim_max
);
1088 VG_(printf
)("fd limits: guest : cur %d max %d\n",
1089 VG_(fd_soft_limit
), VG_(fd_hard_limit
));
1092 if (VG_(cl_exec_fd
) != -1)
1093 VG_(cl_exec_fd
) = VG_(safe_fd
)( VG_(cl_exec_fd
) );
1097 /*====================================================================*/
1099 /*====================================================================*/
1101 /* When main() is entered, we should be on the following stack, not
1102 the one the kernel gave us. We will run on this stack until
1103 simulation of the root thread is started, at which point a transfer
1104 is made to a dynamically allocated stack. This is for the sake of
1105 uniform overflow detection for all Valgrind threads. This is
1106 marked global even though it isn't, because assembly code below
1107 needs to reference the name. */
1110 HChar bytes
[VG_STACK_GUARD_SZB
+ VG_DEFAULT_STACK_ACTIVE_SZB
+ VG_STACK_GUARD_SZB
];
1111 } VG_(interim_stack
);
1113 /* These are the structures used to hold info for creating the initial
1116 'iicii' mostly holds important register state present at system
1117 startup (_start_valgrind). valgrind_main() then fills in the rest
1118 of it and passes it to VG_(ii_create_image)(). That produces
1119 'iifii', which is later handed to VG_(ii_finalise_image). */
1121 /* In all OS-instantiations, the_iicii has a field .sp_at_startup.
1122 This should get some address inside the stack on which we gained
1123 control (eg, it could be the SP at startup). It doesn't matter
1124 exactly where in the stack it is. This value is passed to the
1125 address space manager at startup. On Linux, aspacem then uses it
1126 to identify the initial stack segment and hence the upper end of
1127 the usable address space. */
1129 static IICreateImageInfo the_iicii
;
1130 static IIFinaliseImageInfo the_iifii
;
1133 /* A simple pair structure, used for conveying debuginfo handles to
1134 calls to VG_TRACK(new_mem_startup, ...). */
1135 typedef struct { Addr a
; ULong ull
; } Addr_n_ULong
;
1138 /* --- Forwards decls to do with shutdown --- */
1140 static void final_tidyup(ThreadId tid
);
1142 /* Do everything which needs doing when the last thread exits */
1144 void shutdown_actions_NORETURN( ThreadId tid
,
1145 VgSchedReturnCode tids_schedretcode
);
1147 /* --- end of Forwards decls to do with shutdown --- */
1150 /* By the time we get to valgrind_main, the_iicii should already have
1151 been filled in with any important details as required by whatever
1152 OS we have been built for.
1155 Int
valgrind_main ( Int argc
, HChar
**argv
, HChar
**envp
)
1157 Int need_help
= 0; // 0 = no, 1 = --help, 2 = --help-debug
1158 ThreadId tid_main
= VG_INVALID_THREADID
;
1160 XArray
* addr2dihandle
= NULL
;
1162 //============================================================
1164 // Nb: startup is complex. Prerequisites are shown at every step.
1165 // *** Be very careful when messing with the order ***
1167 // The first order of business is to get debug logging, the address
1168 // space manager and the dynamic memory manager up and running.
1169 // Once that's done, we can relax a bit.
1171 //============================================================
1173 /* This is needed to make VG_(getenv) usable early. */
1174 VG_(client_envp
) = (HChar
**)envp
;
1176 //--------------------------------------------------------------
1177 // Start up Mach kernel interface, if any
1179 //--------------------------------------------------------------
1180 # if defined(VGO_darwin)
1184 //--------------------------------------------------------------
1185 // Start up the logging mechanism
1187 //--------------------------------------------------------------
1188 /* Start the debugging-log system ASAP. First find out how many
1189 "-d"s were specified. This is a pre-scan of the command line. Also
1190 get --profile-heap=yes, --core-redzone-size, --redzone-size
1191 --aspace-minaddr which are needed by the time we start up dynamic
1192 memory management. */
1194 for (i
= 1; i
< argc
; i
++) {
1195 const HChar
* tmp_str
;
1196 if (argv
[i
][0] != '-') break;
1197 if VG_STREQ(argv
[i
], "--") break;
1198 if VG_STREQ(argv
[i
], "-d") loglevel
++;
1199 if VG_BOOL_CLO(argv
[i
], "--profile-heap", VG_(clo_profile_heap
)) {}
1200 if VG_BINT_CLO(argv
[i
], "--core-redzone-size", VG_(clo_core_redzone_size
),
1201 0, MAX_CLO_REDZONE_SZB
) {}
1202 if VG_BINT_CLO(argv
[i
], "--redzone-size", VG_(clo_redzone_size
),
1203 0, MAX_CLO_REDZONE_SZB
) {}
1204 if VG_STR_CLO(argv
[i
], "--aspace-minaddr", tmp_str
) {
1205 Bool ok
= VG_(parse_Addr
) (&tmp_str
, &VG_(clo_aspacem_minAddr
));
1207 VG_(fmsg_bad_option
)(argv
[i
], "Invalid address\n");
1208 const HChar
*errmsg
;
1209 if (!VG_(am_is_valid_for_aspacem_minAddr
)(VG_(clo_aspacem_minAddr
),
1211 VG_(fmsg_bad_option
)(argv
[i
], "%s\n", errmsg
);
1215 /* ... and start the debug logger. Now we can safely emit logging
1216 messages all through startup. */
1217 VG_(debugLog_startup
)(loglevel
, "Stage 2 (main)");
1218 VG_(debugLog
)(1, "main", "Welcome to Valgrind version "
1219 VERSION
" debug logging\n");
1221 //--------------------------------------------------------------
1222 // Ensure we're on a plausible stack.
1224 //--------------------------------------------------------------
1225 VG_(debugLog
)(1, "main", "Checking current stack is plausible\n");
1226 { HChar
* limLo
= (HChar
*)(&VG_(interim_stack
).bytes
[0]);
1227 HChar
* limHi
= limLo
+ sizeof(VG_(interim_stack
));
1229 aLocal
= (HChar
*)&limLo
; /* any auto local will do */
1230 /* Re "volatile": Apple clang version 4.0
1231 (tags/Apple/clang-421.0.57) (based on LLVM 3.1svn)" appeared
1232 to miscompile the following check, causing run to abort at
1233 this point (in 64-bit mode) even though aLocal is within limLo
1234 .. limHi. But in fact clang is within its rights to do
1235 strange things here. "The reason is that the comparisons
1236 aLocal < limLo and aLocal >= limHi cause undefined behaviour
1237 (according to c99 6.5.8) because they compare pointers that do
1238 not point into the same aggregate." Adding "volatile" appears
1239 to fix it because "The compiler would have to prove that there
1240 is undefined behavior in order to exploit it. But as a
1241 volatile variable can change its value in ways invisible to
1242 the compiler, the compiler must make the conservative
1243 assumption that it points into the same aggregate as the other
1244 pointer its compared against. I.e. the behaviour is possibly
1245 defined." (Analysis by Florian Krohm). */
1246 if (aLocal
< limLo
|| aLocal
>= limHi
) {
1247 /* something's wrong. Stop. */
1248 VG_(debugLog
)(0, "main", "Root stack %p to %p, a local %p\n",
1249 limLo
, limHi
, aLocal
);
1250 VG_(debugLog
)(0, "main", "Valgrind: FATAL: "
1251 "Initial stack switched failed.\n");
1252 VG_(debugLog
)(0, "main", " Cannot continue. Sorry.\n");
1257 //--------------------------------------------------------------
1258 // Ensure we have a plausible pointer to the stack on which
1259 // we gained control (not the current stack!)
1261 //--------------------------------------------------------------
1262 VG_(debugLog
)(1, "main", "Checking initial stack was noted\n");
1263 if (the_iicii
.sp_at_startup
== 0) {
1264 VG_(debugLog
)(0, "main", "Valgrind: FATAL: "
1265 "Initial stack was not noted.\n");
1266 VG_(debugLog
)(0, "main", " Cannot continue. Sorry.\n");
1270 //--------------------------------------------------------------
1271 // Start up the address space manager, and determine the
1272 // approximate location of the client's stack
1273 // p: logging, plausible-stack
1274 //--------------------------------------------------------------
1275 VG_(debugLog
)(1, "main", "Starting the address space manager\n");
1276 vg_assert(VKI_PAGE_SIZE
== 4096 || VKI_PAGE_SIZE
== 8192
1277 || VKI_PAGE_SIZE
== 16384 || VKI_PAGE_SIZE
== 32768
1278 || VKI_PAGE_SIZE
== 65536);
1279 vg_assert(VKI_MAX_PAGE_SIZE
== 4096 || VKI_MAX_PAGE_SIZE
== 8192
1280 || VKI_MAX_PAGE_SIZE
== 16384 || VKI_MAX_PAGE_SIZE
== 32768
1281 || VKI_MAX_PAGE_SIZE
== 65536);
1282 vg_assert(VKI_PAGE_SIZE
<= VKI_MAX_PAGE_SIZE
);
1283 vg_assert(VKI_PAGE_SIZE
== (1 << VKI_PAGE_SHIFT
));
1284 vg_assert(VKI_MAX_PAGE_SIZE
== (1 << VKI_MAX_PAGE_SHIFT
));
1285 the_iicii
.clstack_end
= VG_(am_startup
)( the_iicii
.sp_at_startup
);
1286 VG_(debugLog
)(1, "main", "Address space manager is running\n");
1288 //--------------------------------------------------------------
1289 // Start up the dynamic memory manager
1290 // p: address space management
1291 // p: getting --profile-heap,--core-redzone-size,--redzone-size
1292 // In fact m_mallocfree is self-initialising, so there's no
1293 // initialisation call to do. Instead, try a simple malloc/
1294 // free pair right now to check that nothing is broken.
1295 //--------------------------------------------------------------
1296 VG_(debugLog
)(1, "main", "Starting the dynamic memory manager\n");
1297 { void* p
= VG_(malloc
)( "main.vm.1", 12345 );
1300 VG_(debugLog
)(1, "main", "Dynamic memory manager is running\n");
1302 //============================================================
1304 // Dynamic memory management is now available.
1306 //============================================================
1308 //--------------------------------------------------------------
1309 // Initialise m_debuginfo
1310 // p: dynamic memory allocation
1311 VG_(debugLog
)(1, "main", "Initialise m_debuginfo\n");
1312 VG_(di_initialise
)();
1314 //--------------------------------------------------------------
1315 // Look for alternative libdir
1316 { HChar
*cp
= VG_(getenv
)(VALGRIND_LIB
);
1319 VG_(debugLog
)(1, "main", "VG_(libdir) = %s\n", VG_(libdir
));
1322 //--------------------------------------------------------------
1323 // Extract the launcher name from the environment.
1324 VG_(debugLog
)(1, "main", "Getting launcher's name ...\n");
1325 VG_(name_of_launcher
) = VG_(getenv
)(VALGRIND_LAUNCHER
);
1326 if (VG_(name_of_launcher
) == NULL
) {
1327 VG_(printf
)("valgrind: You cannot run '%s' directly.\n", argv
[0]);
1328 VG_(printf
)("valgrind: You should use $prefix/bin/valgrind.\n");
1331 VG_(debugLog
)(1, "main", "... %s\n", VG_(name_of_launcher
));
1333 //--------------------------------------------------------------
1334 // We used to set the process datasize rlimit to zero to prevent
1335 // any internal use of brk() from having any effect. But later
1336 // linux kernels redefine RLIMIT_DATA as the size of any data
1337 // areas, including some dynamic mmap memory allocations.
1338 // See bug #357833 for the commit that went into linux 4.5
1339 // changing the definition of RLIMIT_DATA. So don't mess with
1340 // RLIMIT_DATA here now anymore. Just remember it for use in
1341 // the syscall wrappers.
1342 VG_(getrlimit
)(VKI_RLIMIT_DATA
, &VG_(client_rlimit_data
));
1344 // Get the current process stack rlimit.
1345 VG_(getrlimit
)(VKI_RLIMIT_STACK
, &VG_(client_rlimit_stack
));
1347 //--------------------------------------------------------------
1348 // Figure out what sort of CPU we're on, and whether it is
1350 /* The vex_archinfo structure is passed down later to the client
1351 * to verify the HW info settings are consistent.
1353 VexArchInfo vex_archinfo
;
1354 VG_(debugLog
)(1, "main", "Get hardware capabilities ...\n");
1356 Bool ok
= VG_(machine_get_hwcaps
)();
1359 VG_(printf
)("valgrind: fatal error: unsupported CPU.\n");
1360 VG_(printf
)(" Supported CPUs are:\n");
1361 VG_(printf
)(" * x86 (practically any; Pentium-I or above), "
1362 "AMD Athlon or above)\n");
1363 VG_(printf
)(" * AMD Athlon64/Opteron\n");
1364 VG_(printf
)(" * ARM (armv7)\n");
1365 VG_(printf
)(" * MIPS (mips32 and above; mips64 and above)\n");
1366 VG_(printf
)(" * PowerPC (most; ppc405 and above)\n");
1367 VG_(printf
)(" * System z (64bit only - s390x; z990 and above)\n");
1371 VG_(machine_get_VexArchInfo
)( &vex_arch
, &vex_archinfo
);
1373 1, "main", "... arch = %s, hwcaps = %s\n",
1374 LibVEX_ppVexArch ( vex_arch
),
1375 LibVEX_ppVexHwCaps ( vex_arch
, vex_archinfo
.hwcaps
)
1379 //--------------------------------------------------------------
1380 // Record the working directory at startup
1382 VG_(debugLog
)(1, "main", "Getting the working directory at startup\n");
1383 VG_(record_startup_wd
)();
1384 const HChar
*wd
= VG_(get_startup_wd
)();
1385 VG_(debugLog
)(1, "main", "... %s\n", wd
!= NULL
? wd
: "<NO CWD>" );
1387 //============================================================
1388 // Command line argument handling order:
1389 // * If --help/--help-debug are present, show usage message
1390 // (including the tool-specific usage)
1391 // * (If no --tool option given, default to Memcheck)
1392 // * Then, if client is missing, abort with error msg
1393 // * Then, if any cmdline args are bad, abort with error msg
1394 //============================================================
1396 //--------------------------------------------------------------
1397 // Split up argv into: C args, V args, V extra args, and exename.
1398 // p: dynamic memory allocation
1399 //--------------------------------------------------------------
1400 VG_(debugLog
)(1, "main", "Split up command line\n");
1401 VG_(split_up_argv
)( argc
, argv
);
1402 vg_assert( VG_(args_for_valgrind
) );
1403 vg_assert( VG_(args_for_client
) );
1405 for (i
= 0; i
< VG_(sizeXA
)( VG_(args_for_valgrind
) ); i
++)
1408 * (HChar
**) VG_(indexXA
)( VG_(args_for_valgrind
), i
)
1410 VG_(printf
)(" exe %s\n", VG_(args_the_exename
));
1411 for (i
= 0; i
< VG_(sizeXA
)( VG_(args_for_client
) ); i
++)
1414 * (HChar
**) VG_(indexXA
)( VG_(args_for_client
), i
)
1418 //--------------------------------------------------------------
1419 // Extract tool name and whether help has been requested.
1420 // Note we can't print the help message yet, even if requested,
1421 // because the tool has not been initialised.
1422 // p: split_up_argv [for VG_(args_for_valgrind)]
1423 //--------------------------------------------------------------
1424 VG_(debugLog
)(1, "main",
1425 "(early_) Process Valgrind's command line options\n");
1426 early_process_cmd_line_options(&need_help
);
1429 vg_assert(VG_(clo_toolname
) != NULL
);
1430 vg_assert(VG_(clo_read_inline_info
) == False
);
1431 # if !defined(VGO_darwin)
1432 if (0 == VG_(strcmp
)(VG_(clo_toolname
), "memcheck")
1433 || 0 == VG_(strcmp
)(VG_(clo_toolname
), "helgrind")
1434 || 0 == VG_(strcmp
)(VG_(clo_toolname
), "drd")
1435 || 0 == VG_(strcmp
)(VG_(clo_toolname
), "exp-dhat")) {
1436 /* Change the default setting. Later on (just below)
1437 main_process_cmd_line_options should pick up any
1438 user-supplied setting for it and will override the default
1440 VG_(clo_read_inline_info
) = True
;
1445 // Set default vex control params.
1446 LibVEX_default_VexControl(& VG_(clo_vex_control
));
1448 //--------------------------------------------------------------
1449 // Load client executable, finding in $PATH if necessary
1450 // p: early_process_cmd_line_options() [for 'exec', 'need_help',
1451 // clo_max_stackframe,
1452 // clo_main_stacksize]
1453 // p: layout_remaining_space [so there's space]
1455 // Set up client's environment
1456 // p: set-libdir [for VG_(libdir)]
1457 // p: early_process_cmd_line_options [for VG_(clo_toolname)]
1459 // Setup client stack, eip, and VG_(client_arg[cv])
1460 // p: load_client() [for 'info']
1461 // p: fix_environment() [for 'env']
1463 // Setup client data (brk) segment. Initially a 1-page segment
1464 // which abuts a shrinkable reservation.
1465 // p: load_client() [for 'info' and hence VG_(brk_base)]
1467 // p: _start_in_C (for zeroing out the_iicii and putting some
1468 // initial values into it)
1469 //--------------------------------------------------------------
1471 VG_(debugLog
)(1, "main", "Create initial image\n");
1473 # if defined(VGO_linux) || defined(VGO_darwin) || defined(VGO_solaris)
1474 the_iicii
.argv
= argv
;
1475 the_iicii
.envp
= envp
;
1476 the_iicii
.toolname
= VG_(clo_toolname
);
1478 # error "Unknown platform"
1481 /* NOTE: this call reads VG_(clo_main_stacksize). */
1482 the_iifii
= VG_(ii_create_image
)( the_iicii
, &vex_archinfo
);
1485 //==============================================================
1487 // Finished loading/setting up the client address space.
1489 //==============================================================
1491 //--------------------------------------------------------------
1492 // setup file descriptors
1494 //--------------------------------------------------------------
1495 VG_(debugLog
)(1, "main", "Setup file descriptors\n");
1496 setup_file_descriptors();
1498 //--------------------------------------------------------------
1499 // create fake /proc/<pid>/cmdline and /proc/<pid>/auxv files
1500 // and then unlink them, but hold onto the fds, so we can handr
1501 // them out to the client when it tries to open
1502 // /proc/<pid>/cmdline or /proc/<pid>/auxv for itself.
1503 // p: setup file descriptors
1504 // p: ii_create_image for VG_(client_auxv) setup.
1505 //--------------------------------------------------------------
1506 VG_(cl_cmdline_fd
) = -1;
1507 VG_(cl_auxv_fd
) = -1;
1508 #if defined(VGO_solaris)
1509 VG_(cl_psinfo_fd
) = -1;
1512 #if defined(VGO_linux) || defined(VGO_solaris)
1514 HChar buf
[50]; // large enough
1515 HChar buf2
[VG_(mkstemp_fullname_bufsz
)(sizeof buf
- 1)];
1518 #if defined(VGO_linux) || defined(SOLARIS_PROC_CMDLINE)
1519 /* Fake /proc/<pid>/cmdline only on Linux and Solaris if supported. */
1521 const HChar
* exename
;
1523 VG_(debugLog
)(1, "main", "Create fake /proc/<pid>/cmdline\n");
1525 VG_(sprintf
)(buf
, "proc_%d_cmdline", VG_(getpid
)());
1526 fd
= VG_(mkstemp
)( buf
, buf2
);
1528 VG_(err_config_error
)("Can't create client cmdline file in %s\n", buf2
);
1531 exename
= VG_(args_the_exename
);
1532 VG_(write
)(fd
, exename
, VG_(strlen
)( exename
));
1533 VG_(write
)(fd
, nul
, 1);
1535 for (i
= 0; i
< VG_(sizeXA
)( VG_(args_for_client
) ); i
++) {
1536 HChar
* arg
= * (HChar
**) VG_(indexXA
)( VG_(args_for_client
), i
);
1537 VG_(write
)(fd
, arg
, VG_(strlen
)( arg
));
1538 VG_(write
)(fd
, nul
, 1);
1541 /* Don't bother to seek the file back to the start; instead do
1542 it every time a copy of it is given out (by PRE(sys_open) or
1543 PRE(sys_openat)). That is probably more robust across fork() etc. */
1545 /* Now delete it, but hang on to the fd. */
1546 r
= VG_(unlink
)( buf2
);
1548 VG_(err_config_error
)("Can't delete client cmdline file in %s\n", buf2
);
1550 VG_(cl_cmdline_fd
) = fd
;
1551 #endif // defined(VGO_linux) || defined(SOLARIS_PROC_CMDLINE)
1553 /* Fake /proc/<pid>/auxv on both Linux and Solaris. */
1554 VG_(debugLog
)(1, "main", "Create fake /proc/<pid>/auxv\n");
1556 VG_(sprintf
)(buf
, "proc_%d_auxv", VG_(getpid
)());
1557 fd
= VG_(mkstemp
)( buf
, buf2
);
1559 VG_(err_config_error
)("Can't create client auxv file in %s\n", buf2
);
1561 UWord
*client_auxv
= VG_(client_auxv
);
1562 unsigned int client_auxv_len
= 0;
1563 while (*client_auxv
!= 0) {
1566 client_auxv_len
+= 2 * sizeof(UWord
);
1568 client_auxv_len
+= 2 * sizeof(UWord
);
1570 VG_(write
)(fd
, VG_(client_auxv
), client_auxv_len
);
1572 /* Don't bother to seek the file back to the start; instead do
1573 it every time a copy of it is given out (by PRE(sys_open)).
1574 That is probably more robust across fork() etc. */
1576 /* Now delete it, but hang on to the fd. */
1577 r
= VG_(unlink
)( buf2
);
1579 VG_(err_config_error
)("Can't delete client auxv file in %s\n", buf2
);
1581 VG_(cl_auxv_fd
) = fd
;
1583 #if defined(VGO_solaris)
1584 /* Fake /proc/<pid>/psinfo on Solaris.
1585 * Contents will be fetched and partially faked later on the fly. */
1586 VG_(debugLog
)(1, "main", "Create fake /proc/<pid>/psinfo\n");
1588 VG_(sprintf
)(buf
, "proc_%d_psinfo", VG_(getpid
)());
1589 fd
= VG_(mkstemp
)( buf
, buf2
);
1591 VG_(err_config_error
)("Can't create client psinfo file in %s\n", buf2
);
1593 /* Now delete it, but hang on to the fd. */
1594 r
= VG_(unlink
)( buf2
);
1596 VG_(err_config_error
)("Can't delete client psinfo file in %s\n", buf2
);
1598 VG_(cl_psinfo_fd
) = fd
;
1599 #endif /* VGO_solaris */
1603 //--------------------------------------------------------------
1604 // Init tool part 1: pre_clo_init
1605 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1606 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1607 //--------------------------------------------------------------
1608 VG_(debugLog
)(1, "main", "Initialise the tool part 1 (pre_clo_init)\n");
1609 VG_(tl_pre_clo_init
)();
1610 // Activate var info readers, if the tool asked for it:
1611 if (VG_(needs
).var_info
)
1612 VG_(clo_read_var_info
) = True
;
1614 //--------------------------------------------------------------
1615 // If --tool and --help/--help-debug was given, now give the core+tool
1617 // p: early_process_cmd_line_options() [for 'need_help']
1618 // p: tl_pre_clo_init [for 'VG_(tdict).usage']
1619 //--------------------------------------------------------------
1620 VG_(debugLog
)(1, "main", "Print help and quit, if requested\n");
1622 usage_NORETURN(/*--help-debug?*/need_help
>= 2);
1625 //--------------------------------------------------------------
1626 // Process command line options to Valgrind + tool
1627 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1628 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1629 //--------------------------------------------------------------
1630 VG_(debugLog
)(1, "main",
1631 "(main_) Process Valgrind's command line options, "
1633 main_process_cmd_line_options();
1635 //--------------------------------------------------------------
1636 // Zeroise the millisecond counter by doing a first read of it.
1638 //--------------------------------------------------------------
1639 (void) VG_(read_millisecond_timer
)();
1641 //--------------------------------------------------------------
1642 // Print the preamble
1643 // p: tl_pre_clo_init [for 'VG_(details).name' and friends]
1644 // p: main_process_cmd_line_options()
1645 // [for VG_(clo_verbosity), VG_(clo_xml)]
1646 //--------------------------------------------------------------
1647 VG_(debugLog
)(1, "main", "Print the preamble...\n");
1648 VG_(print_preamble
)(VG_(log_output_sink
).type
!= VgLogTo_File
);
1649 VG_(debugLog
)(1, "main", "...finished the preamble\n");
1651 //--------------------------------------------------------------
1652 // Init tool part 2: post_clo_init
1653 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1654 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1655 // p: print_preamble() [so any warnings printed in post_clo_init
1656 // are shown after the preamble]
1657 //--------------------------------------------------------------
1658 VG_(debugLog
)(1, "main", "Initialise the tool part 2 (post_clo_init)\n");
1659 VG_TDICT_CALL(tool_post_clo_init
);
1661 /* The tool's "needs" will by now be finalised, since it has no
1662 further opportunity to specify them. So now sanity check
1663 and finish initialising the needs. */
1666 ok
= VG_(finish_needs_init
)( &s
);
1672 //--------------------------------------------------------------
1673 // Initialise translation table and translation cache
1675 // p: tl_pre_clo_init [for 'VG_(details).avg_translation_sizeB']
1676 //--------------------------------------------------------------
1677 VG_(debugLog
)(1, "main", "Initialise TT/TC\n");
1680 //--------------------------------------------------------------
1681 // Initialise the redirect table.
1682 // p: init_tt_tc [so it can call VG_(search_transtab) safely]
1683 // p: aspacem [so can change ownership of sysinfo pages]
1684 //--------------------------------------------------------------
1685 VG_(debugLog
)(1, "main", "Initialise redirects\n");
1686 VG_(redir_initialise
)();
1688 //--------------------------------------------------------------
1690 // p: main_process_cmd_line_options() [for VG_(clo_wait_for_gdb)]
1691 //--------------------------------------------------------------
1692 /* Hook to delay things long enough so we can get the pid and
1693 attach GDB in another shell. */
1694 if (VG_(clo_wait_for_gdb
)) {
1695 const int ms
= 8000; // milliseconds
1696 VG_(debugLog
)(1, "main", "Wait for GDB during %d ms\n", ms
);
1697 VG_(printf
)("pid=%d, entering delay %d ms loop\n", VG_(getpid
)(), ms
);
1698 VG_(poll
)(NULL
, 0, ms
);
1701 //--------------------------------------------------------------
1702 // Search for file descriptors that are inherited from our parent
1703 // p: main_process_cmd_line_options [for VG_(clo_track_fds)]
1704 //--------------------------------------------------------------
1705 if (VG_(clo_track_fds
)) {
1706 VG_(debugLog
)(1, "main", "Init preopened fds\n");
1707 VG_(init_preopened_fds
)();
1710 #if defined(VGO_solaris)
1711 VG_(syswrap_init
)();
1714 //--------------------------------------------------------------
1715 // Load debug info for the existing segments.
1716 // p: setup_code_redirect_table [so that redirs can be recorded]
1718 // p: probably: setup fds and process CLOs, so that logging works
1719 // p: initialise m_debuginfo
1721 // While doing this, make a note of the debuginfo-handles that
1722 // come back from VG_(di_notify_mmap).
1723 // Later, in "Tell the tool about the initial client memory permissions"
1724 // (just below) we can then hand these handles off to the tool in
1725 // calls to VG_TRACK(new_mem_startup, ...). This gives the tool the
1726 // opportunity to make further queries to m_debuginfo before the
1727 // client is started, if it wants. We put this information into an
1728 // XArray, each handle along with the associated segment start address,
1729 // and search the XArray for the handles later, when calling
1730 // VG_TRACK(new_mem_startup, ...).
1731 //--------------------------------------------------------------
1732 VG_(debugLog
)(1, "main", "Load initial debug info\n");
1734 vg_assert(!addr2dihandle
);
1735 addr2dihandle
= VG_(newXA
)( VG_(malloc
), "main.vm.2",
1736 VG_(free
), sizeof(Addr_n_ULong
) );
1738 # if defined(VGO_linux) || defined(VGO_solaris)
1743 seg_starts
= VG_(get_segment_starts
)( SkFileC
| SkFileV
, &n_seg_starts
);
1744 vg_assert(seg_starts
&& n_seg_starts
>= 0);
1746 /* show them all to the debug info reader. allow_SkFileV has to
1747 be True here so that we read info from the valgrind executable
1749 for (i
= 0; i
< n_seg_starts
; i
++) {
1750 anu
.ull
= VG_(di_notify_mmap
)( seg_starts
[i
], True
/*allow_SkFileV*/,
1751 -1/*Don't use_fd*/);
1752 /* anu.ull holds the debuginfo handle returned by di_notify_mmap,
1755 anu
.a
= seg_starts
[i
];
1756 VG_(addToXA
)( addr2dihandle
, &anu
);
1760 VG_(free
)( seg_starts
);
1762 # elif defined(VGO_darwin)
1765 seg_starts
= VG_(get_segment_starts
)( SkFileC
, &n_seg_starts
);
1766 vg_assert(seg_starts
&& n_seg_starts
>= 0);
1768 /* show them all to the debug info reader.
1769 Don't read from V segments (unlike Linux) */
1770 // GrP fixme really?
1771 for (i
= 0; i
< n_seg_starts
; i
++) {
1772 VG_(di_notify_mmap
)( seg_starts
[i
], False
/*don't allow_SkFileV*/,
1773 -1/*don't use_fd*/);
1776 VG_(free
)( seg_starts
);
1782 //--------------------------------------------------------------
1783 // Tell aspacem of ownership change of the asm helpers, so that
1784 // m_translate allows them to be translated. However, only do this
1785 // after the initial debug info read, since making a hole in the
1786 // address range for the stage2 binary confuses the debug info reader.
1788 //--------------------------------------------------------------
1789 { Bool change_ownership_v_c_OK
;
1790 Addr co_start
= VG_PGROUNDDN( (Addr
)&VG_(trampoline_stuff_start
) );
1791 Addr co_endPlus
= VG_PGROUNDUP( (Addr
)&VG_(trampoline_stuff_end
) );
1792 VG_(debugLog
)(1,"redir",
1793 "transfer ownership V -> C of 0x%llx .. 0x%llx\n",
1794 (ULong
)co_start
, (ULong
)co_endPlus
-1 );
1796 change_ownership_v_c_OK
1797 = VG_(am_change_ownership_v_to_c
)( co_start
, co_endPlus
- co_start
);
1798 vg_assert(change_ownership_v_c_OK
);
1802 HChar buf
[50]; // large enough
1803 VG_(elapsed_wallclock_time
)(buf
, sizeof buf
);
1804 VG_(printf_xml
)( "<status>\n"
1805 " <state>RUNNING</state>\n"
1806 " <time>%pS</time>\n"
1809 VG_(printf_xml
)( "\n" );
1812 VG_(init_Threads
)();
1814 //--------------------------------------------------------------
1815 // Initialise the scheduler (phase 1) [generates tid_main]
1817 //--------------------------------------------------------------
1818 VG_(debugLog
)(1, "main", "Initialise scheduler (phase 1)\n");
1819 tid_main
= VG_(scheduler_init_phase1
)();
1820 vg_assert(tid_main
>= 0 && tid_main
< VG_N_THREADS
1821 && tid_main
!= VG_INVALID_THREADID
);
1822 /* Tell the tool about tid_main */
1823 VG_TRACK( pre_thread_ll_create
, VG_INVALID_THREADID
, tid_main
);
1825 //--------------------------------------------------------------
1826 // Tell the tool about the initial client memory permissions
1829 // p: setup_client_stack
1830 // p: setup_client_dataseg
1832 // For each segment we tell the client about, look up in
1833 // addr2dihandle as created above, to see if there's a debuginfo
1834 // handle associated with the segment, that we can hand along
1835 // to the tool, to be helpful.
1836 //--------------------------------------------------------------
1837 VG_(debugLog
)(1, "main", "Tell tool about initial permissions\n");
1841 vg_assert(addr2dihandle
);
1843 /* Mark the main thread as running while we tell the tool about
1844 the client memory so that the tool can associate that memory
1845 with the main thread. */
1846 vg_assert(VG_(running_tid
) == VG_INVALID_THREADID
);
1847 VG_(running_tid
) = tid_main
;
1849 seg_starts
= VG_(get_segment_starts
)( SkFileC
| SkAnonC
| SkShmC
,
1851 vg_assert(seg_starts
&& n_seg_starts
>= 0);
1853 /* Show client segments to the tool */
1854 for (i
= 0; i
< n_seg_starts
; i
++) {
1857 = VG_(am_find_nsegment
)( seg_starts
[i
] );
1859 vg_assert(seg
->kind
== SkFileC
|| seg
->kind
== SkAnonC
||
1860 seg
->kind
== SkShmC
);
1861 vg_assert(seg
->start
== seg_starts
[i
]);
1863 VG_(debugLog
)(2, "main",
1864 "tell tool about %010lx-%010lx %c%c%c\n",
1865 seg
->start
, seg
->end
,
1866 seg
->hasR
? 'r' : '-',
1867 seg
->hasW
? 'w' : '-',
1868 seg
->hasX
? 'x' : '-' );
1869 /* search addr2dihandle to see if we have an entry
1870 matching seg->start. */
1871 n
= VG_(sizeXA
)( addr2dihandle
);
1872 for (j
= 0; j
< n
; j
++) {
1873 Addr_n_ULong
* anl
= VG_(indexXA
)( addr2dihandle
, j
);
1874 if (anl
->a
== seg
->start
) {
1875 vg_assert(anl
->ull
> 0); /* check it's a valid handle */
1879 vg_assert(j
>= 0 && j
<= n
);
1880 VG_TRACK( new_mem_startup
, seg
->start
, seg
->end
+1-seg
->start
,
1881 seg
->hasR
, seg
->hasW
, seg
->hasX
,
1882 /* and the retrieved debuginfo handle, if any */
1884 ? ((Addr_n_ULong
*)VG_(indexXA
)( addr2dihandle
, j
))->ull
1889 VG_(free
)( seg_starts
);
1890 VG_(deleteXA
)( addr2dihandle
);
1892 /* Also do the initial stack permissions. */
1894 SSizeT inaccessible_len
;
1896 = VG_(am_find_nsegment
)( the_iifii
.initial_client_SP
);
1898 vg_assert(seg
->kind
== SkAnonC
);
1899 vg_assert(the_iifii
.initial_client_SP
>= seg
->start
);
1900 vg_assert(the_iifii
.initial_client_SP
<= seg
->end
);
1902 /* Stuff below the initial SP is unaddressable. Take into
1903 account any ABI-mandated space below the stack pointer that
1904 is required (VG_STACK_REDZONE_SZB). setup_client_stack()
1905 will have allocated an extra page if a red zone is required,
1906 to be on the safe side. */
1907 inaccessible_len
= the_iifii
.initial_client_SP
- VG_STACK_REDZONE_SZB
1909 vg_assert(inaccessible_len
>= 0);
1910 if (inaccessible_len
> 0)
1911 VG_TRACK( die_mem_stack
,
1914 VG_(debugLog
)(2, "main", "mark stack inaccessible %010lx-%010lx\n",
1916 the_iifii
.initial_client_SP
-1 - VG_STACK_REDZONE_SZB
);
1919 /* Also the assembly helpers. */
1920 VG_TRACK( new_mem_startup
,
1921 (Addr
)&VG_(trampoline_stuff_start
),
1922 (Addr
)&VG_(trampoline_stuff_end
)
1923 - (Addr
)&VG_(trampoline_stuff_start
),
1924 False
, /* readable? */
1925 False
, /* writable? */
1926 True
/* executable? */,
1927 0 /* di_handle: no associated debug info */ );
1929 /* Clear the running thread indicator */
1930 VG_(running_tid
) = VG_INVALID_THREADID
;
1931 vg_assert(VG_(running_tid
) == VG_INVALID_THREADID
);
1933 /* Darwin only: tell the tools where the client's kernel commpage
1934 is. It would be better to do this by telling aspacemgr about
1935 it -- see the now disused record_system_memory() in
1936 initimg-darwin.c -- but that causes the sync checker to fail,
1937 since the mapping doesn't appear in the kernel-supplied
1938 process map. So do it here instead. */
1939 # if defined(VGP_amd64_darwin)
1940 VG_TRACK( new_mem_startup
,
1941 0x7fffffe00000, 0x7ffffffff000-0x7fffffe00000,
1942 True
, False
, True
, /* r-x */
1943 0 /* di_handle: no associated debug info */ );
1944 # elif defined(VGP_x86_darwin)
1945 VG_TRACK( new_mem_startup
,
1946 0xfffec000, 0xfffff000-0xfffec000,
1947 True
, False
, True
, /* r-x */
1948 0 /* di_handle: no associated debug info */ );
1952 //--------------------------------------------------------------
1953 // Initialise the scheduler (phase 2)
1954 // p: Initialise the scheduler (phase 1) [for tid_main]
1955 // p: setup_file_descriptors() [else VG_(safe_fd)() breaks]
1956 // p: setup_client_stack
1957 //--------------------------------------------------------------
1958 VG_(debugLog
)(1, "main", "Initialise scheduler (phase 2)\n");
1959 { NSegment
const* seg
1960 = VG_(am_find_nsegment
)( the_iifii
.initial_client_SP
);
1962 vg_assert(seg
->kind
== SkAnonC
);
1963 vg_assert(the_iifii
.initial_client_SP
>= seg
->start
);
1964 vg_assert(the_iifii
.initial_client_SP
<= seg
->end
);
1965 VG_(scheduler_init_phase2
)( tid_main
,
1966 seg
->end
, the_iifii
.clstack_max_size
);
1969 //--------------------------------------------------------------
1970 // Set up state for the root thread
1972 // setup_scheduler() [for sched-specific thread 1 stuff]
1973 // VG_(ii_create_image) [for 'the_iicii' initial info]
1974 //--------------------------------------------------------------
1975 VG_(debugLog
)(1, "main", "Finalise initial image\n");
1976 { /* Mark the main thread as running while we tell the tool about
1977 the client memory which could be tracked during initial image
1978 finalisation. So the tool can associate that memory with the
1980 vg_assert(VG_(running_tid
) == VG_INVALID_THREADID
);
1981 VG_(running_tid
) = tid_main
;
1983 VG_(ii_finalise_image
)( the_iifii
);
1985 /* Clear the running thread indicator */
1986 VG_(running_tid
) = VG_INVALID_THREADID
;
1987 vg_assert(VG_(running_tid
) == VG_INVALID_THREADID
);
1990 //--------------------------------------------------------------
1991 // Initialise the signal handling subsystem
1993 //--------------------------------------------------------------
1994 // Nb: temporarily parks the saved blocking-mask in saved_sigmask.
1995 VG_(debugLog
)(1, "main", "Initialise signal management\n");
1996 /* Check that the kernel-interface signal definitions look sane */
1997 VG_(vki_do_initial_consistency_checks
)();
1998 /* .. and go on to use them. */
1999 VG_(sigstartup_actions
)();
2001 //--------------------------------------------------------------
2002 // Read suppression file
2003 // p: main_process_cmd_line_options() [for VG_(clo_suppressions)]
2004 //--------------------------------------------------------------
2005 if (VG_(needs
).core_errors
|| VG_(needs
).tool_errors
) {
2006 VG_(debugLog
)(1, "main", "Load suppressions\n");
2007 VG_(load_suppressions
)();
2010 //--------------------------------------------------------------
2011 // register client stack
2012 //--------------------------------------------------------------
2013 VG_(clstk_id
) = VG_(register_stack
)(VG_(clstk_start_base
), VG_(clstk_end
));
2015 //--------------------------------------------------------------
2016 // Show the address space state so far
2017 //--------------------------------------------------------------
2018 VG_(debugLog
)(1, "main", "\n");
2019 VG_(debugLog
)(1, "main", "\n");
2020 VG_(am_show_nsegments
)(1,"Memory layout at client startup");
2021 VG_(debugLog
)(1, "main", "\n");
2022 VG_(debugLog
)(1, "main", "\n");
2024 //--------------------------------------------------------------
2026 //--------------------------------------------------------------
2027 VG_(debugLog
)(1, "main", "Running thread 1\n");
2029 /* As a result of the following call, the last thread standing
2030 eventually winds up running shutdown_actions_NORETURN
2031 just below. Unfortunately, simply exporting said function
2032 causes m_main to be part of a module cycle, which is pretty
2033 nonsensical. So instead of doing that, the address of said
2034 function is stored in a global variable 'owned' by m_syswrap,
2035 and it uses that function pointer to get back here when it needs
2038 /* Set continuation address. */
2039 VG_(address_of_m_main_shutdown_actions_NORETURN
)
2040 = & shutdown_actions_NORETURN
;
2042 /* Run the first thread, eventually ending up at the continuation
2044 VG_(main_thread_wrapper_NORETURN
)(1);
2050 /* Do everything which needs doing when the last thread exits or when
2051 a thread exits requesting a complete process exit.
2053 We enter here holding The Lock. For the case VgSrc_ExitProcess we
2054 must never release it, because to do so would allow other threads
2055 to continue after the system is ostensibly shut down. So we must
2056 go to our grave, so to speak, holding the lock.
2058 In fact, there is never any point in releasing the lock at this
2059 point - we have it, we're shutting down the entire system, and
2060 for the case VgSrc_ExitProcess doing so positively causes trouble.
2063 The final_tidyup call makes a bit of a nonsense of the ExitProcess
2064 case, since it will run __gnu_cxx::__freeres and libc_freeres functions,
2065 thus allowing other lurking threads to run again. Hmm. */
2068 void shutdown_actions_NORETURN( ThreadId tid
,
2069 VgSchedReturnCode tids_schedretcode
)
2071 VG_(debugLog
)(1, "main", "entering VG_(shutdown_actions_NORETURN)\n");
2072 VG_(am_show_nsegments
)(1,"Memory layout at client shutdown");
2074 vg_assert(VG_(is_running_thread
)(tid
));
2075 vg_assert(tids_schedretcode
== VgSrc_ExitThread
2076 || tids_schedretcode
== VgSrc_ExitProcess
2077 || tids_schedretcode
== VgSrc_FatalSig
);
2079 if (tids_schedretcode
== VgSrc_ExitThread
) {
2081 // We are the last surviving thread. Right?
2082 vg_assert( VG_(count_living_threads
)() == 1 );
2084 // Wait for all other threads to exit.
2085 // jrs: Huh? but they surely are already gone
2086 VG_(reap_threads
)(tid
);
2088 // Clean the client up before the final report.
2089 // This causes __gnu_cxx::__freeres and libc_freeres functions to run.
2093 vg_assert(VG_(is_running_thread
)(tid
));
2094 vg_assert(VG_(count_living_threads
)() == 1);
2098 // We may not be the last surviving thread. However, we
2099 // want to shut down the entire process. We hold the lock
2100 // and we need to keep hold of it all the way out, in order
2101 // that none of the other threads ever run again.
2102 vg_assert( VG_(count_living_threads
)() >= 1 );
2104 // Clean the client up before the final report.
2105 // This causes __gnu_cxx::__freeres and libc_freeres functions to run.
2106 // Perhaps this is unsafe, as per comment above.
2110 vg_assert(VG_(is_running_thread
)(tid
));
2111 vg_assert(VG_(count_living_threads
)() >= 1);
2114 /* Final call to gdbserver, if requested. */
2115 if (VG_(gdbserver_stop_at
) (VgdbStopAt_Exit
)) {
2116 VG_(umsg
)("(action at exit) vgdb me ... \n");
2117 VG_(gdbserver
) (tid
);
2119 VG_(threads
)[tid
].status
= VgTs_Empty
;
2121 //--------------------------------------------------------------
2122 // Finalisation: cleanup, messages, etc. Order not so important, only
2123 // affects what order the messages come.
2124 //--------------------------------------------------------------
2125 // First thing in the post-amble is a blank line.
2127 VG_(printf_xml
)("\n");
2128 else if (VG_(clo_verbosity
) > 0)
2129 VG_(message
)(Vg_UserMsg
, "\n");
2132 HChar buf
[50]; // large enough
2133 VG_(elapsed_wallclock_time
)(buf
, sizeof buf
);
2134 VG_(printf_xml
)( "<status>\n"
2135 " <state>FINISHED</state>\n"
2136 " <time>%pS</time>\n"
2142 /* Print out file descriptor summary and stats. */
2143 if (VG_(clo_track_fds
))
2144 VG_(show_open_fds
)("at exit");
2146 /* Call the tool's finalisation function. This makes Memcheck's
2147 leak checker run, and possibly chuck a bunch of leak errors into
2148 the error management machinery. */
2149 VG_TDICT_CALL(tool_fini
, 0/*exitcode*/);
2151 /* Show the error counts. */
2153 && (VG_(needs
).core_errors
|| VG_(needs
).tool_errors
)) {
2154 VG_(show_error_counts_as_XML
)();
2157 /* In XML mode, this merely prints the used suppressions. */
2158 if (VG_(needs
).core_errors
|| VG_(needs
).tool_errors
)
2159 VG_(show_all_errors
)(VG_(clo_verbosity
), VG_(clo_xml
));
2162 VG_(printf_xml
)("\n");
2163 VG_(printf_xml
)("</valgrindoutput>\n");
2164 VG_(printf_xml
)("\n");
2167 VG_(sanity_check_general
)( True
/*include expensive checks*/ );
2170 VG_(print_all_stats
)(VG_(clo_verbosity
) >= 1, /* Memory stats */
2171 False
/* tool prints stats in the tool fini */);
2173 /* Show a profile of the heap(s) at shutdown. Optionally, first
2174 throw away all the debug info, as that makes it easy to spot
2175 leaks in the debuginfo reader. */
2176 if (VG_(clo_profile_heap
)) {
2177 if (0) VG_(di_discard_ALL_debuginfo
)();
2178 VG_(print_arena_cc_analysis
)();
2181 /* If profiling has been requested, but with zero interval, it
2182 means "profile at the end of the run only". In which case we
2183 need to dump the profile now. */
2184 if (VG_(clo_profyle_sbs
) && VG_(clo_profyle_interval
) == 0) {
2185 VG_(get_and_show_SB_profile
)(0/*denoting end-of-run*/);
2188 /* Print Vex storage stats */
2190 LibVEX_ShowAllocStats();
2192 /* Flush any output cached by previous calls to VG_(message). */
2193 VG_(message_flush
)();
2195 /* Terminate gdbserver if ever it was started. We terminate it here
2196 so that it get the output above if output was redirected to
2198 VG_(gdbserver_exit
) (tid
, tids_schedretcode
);
2200 /* Ok, finally exit in the os-specific way, according to the scheduler's
2201 return code. In short, if the (last) thread exited by calling
2202 sys_exit, do likewise; if the (last) thread stopped due to a fatal
2203 signal, terminate the entire system with that same fatal signal. */
2204 VG_(debugLog
)(1, "core_os",
2205 "VG_(terminate_NORETURN)(tid=%u) schedretcode %s"
2206 " os_state.exit_code %ld fatalsig %d\n",
2207 tid
, VG_(name_of_VgSchedReturnCode
)(tids_schedretcode
),
2208 VG_(threads
)[tid
].os_state
.exitcode
,
2209 VG_(threads
)[tid
].os_state
.fatalsig
);
2211 switch (tids_schedretcode
) {
2212 case VgSrc_ExitThread
: /* the normal way out (Linux, Solaris) */
2213 case VgSrc_ExitProcess
: /* the normal way out (Darwin) */
2214 /* Change the application return code to user's return code,
2215 if an error was found */
2216 if (VG_(clo_error_exitcode
) > 0
2217 && VG_(get_n_errs_found
)() > 0) {
2218 VG_(client_exit
)( VG_(clo_error_exitcode
) );
2220 /* otherwise, return the client's exit code, in the normal
2222 VG_(client_exit
)( VG_(threads
)[tid
].os_state
.exitcode
);
2224 /* NOT ALIVE HERE! */
2225 VG_(core_panic
)("entered the afterlife in main() -- ExitT/P");
2226 break; /* what the hell :) */
2228 case VgSrc_FatalSig
:
2229 /* We were killed by a fatal signal, so replicate the effect */
2230 vg_assert(VG_(threads
)[tid
].os_state
.fatalsig
!= 0);
2231 VG_(kill_self
)(VG_(threads
)[tid
].os_state
.fatalsig
);
2232 /* we shouldn't be alive at this point. But VG_(kill_self)
2233 sometimes fails with EPERM on Darwin, for unclear reasons. */
2234 # if defined(VGO_darwin)
2235 VG_(debugLog
)(0, "main", "VG_(kill_self) failed. Exiting normally.\n");
2236 VG_(exit
)(0); /* bogus, but we really need to exit now */
2237 /* fall through .. */
2239 VG_(core_panic
)("main(): signal was supposed to be fatal");
2243 VG_(core_panic
)("main(): unexpected scheduler return code");
2247 /* -------------------- */
2249 /* Final clean-up before terminating the process.
2250 Clean up the client by calling __gnu_cxx::__freeres() (if requested)
2251 and __libc_freeres() (if requested).
2253 static void final_tidyup(ThreadId tid
)
2255 #if defined(VGO_linux) || defined(VGO_solaris)
2256 Addr freeres_wrapper
= VG_(client_freeres_wrapper
);
2258 vg_assert(VG_(is_running_thread
)(tid
));
2260 if (freeres_wrapper
== 0) {
2261 return; /* can't do it */
2264 Vg_FreeresToRun to_run
= 0;
2265 if (VG_(needs
).cxx_freeres
&& VG_(clo_run_cxx_freeres
)) {
2266 to_run
|= VG_RUN__GNU_CXX__FREERES
;
2269 if (VG_(needs
).libc_freeres
&& VG_(clo_run_libc_freeres
)) {
2270 to_run
|= VG_RUN__LIBC_FREERES
;
2274 return; /* won't do it */
2277 # if defined(VGP_ppc64be_linux)
2278 Addr r2
= VG_(get_tocptr
)(VG_(current_DiEpoch
)(),
2281 VG_(message
)(Vg_UserMsg
,
2282 "Caught __NR_exit, but can't run __gnu_cxx::__freeres()\n");
2283 VG_(message
)(Vg_UserMsg
,
2284 " or __libc_freeres() since cannot establish TOC pointer "
2290 if (VG_(clo_verbosity
) > 2 ||
2291 VG_(clo_trace_syscalls
) ||
2292 VG_(clo_trace_sched
)) {
2294 vg_assert(to_run
> 0);
2295 vg_assert(to_run
<= (VG_RUN__GNU_CXX__FREERES
| VG_RUN__LIBC_FREERES
));
2297 const HChar
*msgs
[] = {"__gnu_cxx::__freeres()", "__libc_freeres()",
2298 "__gnu_cxx::__freeres and __libc_freeres()"};
2299 VG_(message
)(Vg_DebugMsg
,
2300 "Caught __NR_exit; running %s wrapper\n", msgs
[to_run
- 1]);
2303 /* set thread context to point to freeres_wrapper */
2304 /* ppc64be-linux note: freeres_wrapper gives us the real
2305 function entry point, not a fn descriptor, so can use it
2306 directly. However, we need to set R2 (the toc pointer)
2308 VG_(set_IP
)(tid
, freeres_wrapper
);
2309 # if defined(VGP_ppc64be_linux)
2310 VG_(threads
)[tid
].arch
.vex
.guest_GPR2
= r2
;
2311 # elif defined(VGP_ppc64le_linux)
2312 /* setting GPR2 but not really needed, GPR12 is needed */
2313 VG_(threads
)[tid
].arch
.vex
.guest_GPR2
= freeres_wrapper
;
2314 VG_(threads
)[tid
].arch
.vex
.guest_GPR12
= freeres_wrapper
;
2316 /* mips-linux note: we need to set t9 */
2317 # if defined(VGP_mips32_linux) || defined(VGP_mips64_linux)
2318 VG_(threads
)[tid
].arch
.vex
.guest_r25
= freeres_wrapper
;
2321 /* Pass a parameter to freeres_wrapper(). */
2322 # if defined(VGA_x86)
2323 Addr sp
= VG_(threads
)[tid
].arch
.vex
.guest_ESP
;
2324 *((UWord
*) sp
) = to_run
;
2325 VG_TRACK(post_mem_write
, Vg_CoreClientReq
, tid
, sp
, sizeof(UWord
));
2326 sp
= sp
- sizeof(UWord
);
2327 VG_(threads
)[tid
].arch
.vex
.guest_ESP
= sp
;
2328 VG_TRACK(post_reg_write
, Vg_CoreClientReq
, tid
,
2329 offsetof(VexGuestX86State
, guest_ESP
),
2330 sizeof(VG_(threads
)[tid
].arch
.vex
.guest_ESP
));
2331 # elif defined(VGA_amd64)
2332 VG_(threads
)[tid
].arch
.vex
.guest_RDI
= to_run
;
2333 VG_TRACK(post_reg_write
, Vg_CoreClientReq
, tid
,
2334 offsetof(VexGuestAMD64State
, guest_RDI
),
2335 sizeof(VG_(threads
)[tid
].arch
.vex
.guest_RDI
));
2336 # elif defined(VGA_arm)
2337 VG_(threads
)[tid
].arch
.vex
.guest_R0
= to_run
;
2338 VG_TRACK(post_reg_write
, Vg_CoreClientReq
, tid
,
2339 offsetof(VexGuestARMState
, guest_R0
),
2340 sizeof(VG_(threads
)[tid
].arch
.vex
.guest_R0
));
2341 # elif defined(VGA_arm64)
2342 VG_(threads
)[tid
].arch
.vex
.guest_X0
= to_run
;
2343 VG_TRACK(post_reg_write
, Vg_CoreClientReq
, tid
,
2344 offsetof(VexGuestARM64State
, guest_X0
),
2345 sizeof(VG_(threads
)[tid
].arch
.vex
.guest_X0
));
2346 # elif defined(VGA_mips32)
2347 VG_(threads
)[tid
].arch
.vex
.guest_r4
= to_run
;
2348 VG_TRACK(post_reg_write
, Vg_CoreClientReq
, tid
,
2349 offsetof(VexGuestMIPS32State
, guest_r4
),
2350 sizeof(VG_(threads
)[tid
].arch
.vex
.guest_r4
));
2351 # elif defined(VGA_mips64)
2352 VG_(threads
)[tid
].arch
.vex
.guest_r4
= to_run
;
2353 VG_TRACK(post_reg_write
, Vg_CoreClientReq
, tid
,
2354 offsetof(VexGuestMIPS64State
, guest_r4
),
2355 sizeof(VG_(threads
)[tid
].arch
.vex
.guest_r4
));
2356 # elif defined(VGA_ppc32)
2357 VG_(threads
)[tid
].arch
.vex
.guest_GPR3
= to_run
;
2358 VG_TRACK(post_reg_write
, Vg_CoreClientReq
, tid
,
2359 offsetof(VexGuestPPC32State
, guest_GPR3
),
2360 sizeof(VG_(threads
)[tid
].arch
.vex
.guest_GPR3
));
2361 # elif defined(VGA_ppc64be) || defined(VGA_ppc64le)
2362 VG_(threads
)[tid
].arch
.vex
.guest_GPR3
= to_run
;
2363 VG_TRACK(post_reg_write
, Vg_CoreClientReq
, tid
,
2364 offsetof(VexGuestPPC64State
, guest_GPR3
),
2365 sizeof(VG_(threads
)[tid
].arch
.vex
.guest_GPR3
));
2366 # elif defined(VGA_s390x)
2367 VG_(threads
)[tid
].arch
.vex
.guest_r2
= to_run
;
2368 VG_TRACK(post_reg_write
, Vg_CoreClientReq
, tid
,
2369 offsetof(VexGuestS390XState
, guest_r2
),
2370 sizeof(VG_(threads
)[tid
].arch
.vex
.guest_r2
));
2372 I_die_here
: architecture missing in m_main
.c
2375 /* Block all blockable signals by copying the real block state into
2376 the thread's block state */
2377 VG_(sigprocmask
)(VKI_SIG_BLOCK
, NULL
, &VG_(threads
)[tid
].sig_mask
);
2378 VG_(threads
)[tid
].tmp_sig_mask
= VG_(threads
)[tid
].sig_mask
;
2380 /* and restore handlers to default. */
2381 VG_(set_default_handler
)(VKI_SIGSEGV
);
2382 VG_(set_default_handler
)(VKI_SIGBUS
);
2383 VG_(set_default_handler
)(VKI_SIGILL
);
2384 VG_(set_default_handler
)(VKI_SIGFPE
);
2386 // We were exiting, so assert that...
2387 vg_assert(VG_(is_exiting
)(tid
));
2388 // ...but now we're not again.
2389 VG_(threads
)[tid
].exitreason
= VgSrc_None
;
2391 // Run until client thread exits - ideally with FREERES_DONE,
2392 // but exit/exitgroup/signal will do.
2393 VG_(scheduler
)(tid
);
2395 vg_assert(VG_(is_exiting
)(tid
));
2400 /*====================================================================*/
2401 /*=== Getting to main() alive: LINUX ===*/
2402 /*====================================================================*/
2404 #if defined(VGO_linux)
2406 /* If linking of the final executables is done with glibc present,
2407 then Valgrind starts at main() above as usual, and all of the
2408 following code is irrelevant.
2410 However, this is not the intended mode of use. The plan is to
2411 avoid linking against glibc, by giving gcc the flags
2412 -nodefaultlibs -lgcc -nostartfiles at startup.
2414 From this derive two requirements:
2416 1. gcc may emit calls to memcpy, memmove and memset to deal with
2417 structure assignments etc. Since we have chosen to ignore all the
2418 "normal" supporting libraries, we have to provide our own
2419 implementations of them. No problem.
2421 2. We have to provide a symbol "_start", to which the kernel
2422 hands control at startup. Hence the code below.
2425 /* ---------------- Requirement 1 ---------------- */
2427 void* memcpy(void *dest
, const void *src
, SizeT n
);
2428 void* memcpy(void *dest
, const void *src
, SizeT n
) {
2429 return VG_(memcpy
)(dest
,src
,n
);
2431 void* memmove(void *dest
, const void *src
, SizeT n
);
2432 void* memmove(void *dest
, const void *src
, SizeT n
) {
2433 return VG_(memmove
)(dest
,src
,n
);
2435 void* memset(void *s
, int c
, SizeT n
);
2436 void* memset(void *s
, int c
, SizeT n
) {
2437 return VG_(memset
)(s
,c
,n
);
2440 /* BVA: abort() for those platforms that need it (PPC and ARM). */
2443 VG_(printf
)("Something called raise().\n");
2447 /* EAZG: ARM's EABI will call floating point exception handlers in
2448 libgcc which boil down to an abort or raise, that's usually defined
2449 in libc. Instead, define them here. */
2450 #if defined(VGP_arm_linux)
2454 VG_(printf
)("Something called raise().\n");
2458 void __aeabi_unwind_cpp_pr0(void);
2459 void __aeabi_unwind_cpp_pr0(void){
2460 VG_(printf
)("Something called __aeabi_unwind_cpp_pr0()\n");
2464 void __aeabi_unwind_cpp_pr1(void);
2465 void __aeabi_unwind_cpp_pr1(void){
2466 VG_(printf
)("Something called __aeabi_unwind_cpp_pr1()\n");
2470 #endif /* defined(VGP_arm_linux) */
2472 /* Some Android helpers. See bug 368529. */
2473 #if defined(__clang__) \
2474 && (defined(VGPV_arm_linux_android) \
2475 || defined(VGPV_x86_linux_android) \
2476 || defined(VGPV_mips32_linux_android) \
2477 || defined(VGPV_arm64_linux_android))
2479 /* Replace __aeabi_memcpy* functions with vgPlain_memcpy. */
2480 void *__aeabi_memcpy(void *dest
, const void *src
, SizeT n
);
2481 void *__aeabi_memcpy(void *dest
, const void *src
, SizeT n
)
2483 return VG_(memcpy
)(dest
, src
, n
);
2486 void *__aeabi_memcpy4(void *dest
, const void *src
, SizeT n
);
2487 void *__aeabi_memcpy4(void *dest
, const void *src
, SizeT n
)
2489 return VG_(memcpy
)(dest
, src
, n
);
2492 void *__aeabi_memcpy8(void *dest
, const void *src
, SizeT n
);
2493 void *__aeabi_memcpy8(void *dest
, const void *src
, SizeT n
)
2495 return VG_(memcpy
)(dest
, src
, n
);
2498 /* Replace __aeabi_memclr* functions with vgPlain_memset. */
2499 void *__aeabi_memclr(void *dest
, SizeT n
);
2500 void *__aeabi_memclr(void *dest
, SizeT n
)
2502 return VG_(memset
)(dest
, 0, n
);
2505 void *__aeabi_memclr4(void *dest
, SizeT n
);
2506 void *__aeabi_memclr4(void *dest
, SizeT n
)
2508 return VG_(memset
)(dest
, 0, n
);
2511 void *__aeabi_memclr8(void *dest
, SizeT n
);
2512 void *__aeabi_memclr8(void *dest
, SizeT n
)
2514 return VG_(memset
)(dest
, 0, n
);
2516 #endif /* clang and android, basically */
2518 /* ---------------- Requirement 2 ---------------- */
2520 /* Glibc's sysdeps/i386/elf/start.S has the following gem of a
2521 comment, which explains how the stack looks right at process start
2522 (when _start is jumped to). Hence _start passes %esp to
2523 _start_in_C_linux, which extracts argc/argv/envp and starts up
2526 /* This is the canonical entry point, usually the first thing in the text
2527 segment. The SVR4/i386 ABI (pages 3-31, 3-32) says that when the entry
2528 point runs, most registers' values are unspecified, except for:
2530 %edx Contains a function pointer to be registered with `atexit'.
2531 This is how the dynamic linker arranges to have DT_FINI
2532 functions called for shared libraries that have been loaded
2533 before this code runs.
2535 %esp The stack contains the arguments and environment:
2540 (4*(argc+1))(%esp) envp[0]
2545 /* The kernel hands control to _start, which extracts the initial
2546 stack pointer and calls onwards to _start_in_C_linux. This also switches
2548 #if defined(VGP_x86_linux)
2552 "\t.type _start,@function\n"
2554 /* set up the new stack in %eax */
2555 "\tmovl $vgPlain_interim_stack, %eax\n"
2556 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB
)", %eax\n"
2557 "\taddl $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)", %eax\n"
2558 /* allocate at least 16 bytes on the new stack, and aligned */
2559 "\tsubl $16, %eax\n"
2560 "\tandl $~15, %eax\n"
2561 /* install it, and collect the original one */
2562 "\txchgl %eax, %esp\n"
2563 /* call _start_in_C_linux, passing it the startup %esp */
2564 "\tmovl %eax, (%esp)\n"
2565 "\tcall _start_in_C_linux\n"
2569 #elif defined(VGP_amd64_linux)
2573 "\t.type _start,@function\n"
2575 /* set up the new stack in %rdi */
2576 "\tmovq $vgPlain_interim_stack, %rdi\n"
2577 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB
)", %rdi\n"
2578 "\taddq $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)", %rdi\n"
2579 "\tandq $~15, %rdi\n"
2580 /* install it, and collect the original one */
2581 "\txchgq %rdi, %rsp\n"
2582 /* call _start_in_C_linux, passing it the startup %rsp */
2583 "\tcall _start_in_C_linux\n"
2587 #elif defined(VGP_ppc32_linux)
2591 "\t.type _start,@function\n"
2593 /* set up the new stack in r16 */
2594 "\tlis 16,vgPlain_interim_stack@ha\n"
2595 "\tla 16,vgPlain_interim_stack@l(16)\n"
2596 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB
)" >> 16)\n"
2597 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB
)" & 0xFFFF)\n"
2598 "\tlis 18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)" >> 16)\n"
2599 "\tori 18,18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)" & 0xFFFF)\n"
2602 "\trlwinm 16,16,0,0,27\n"
2603 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2604 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2605 boundary. And r1 is the original SP. Set the SP to r16 and
2606 call _start_in_C_linux, passing it the initial SP. */
2609 "\tbl _start_in_C_linux\n"
2613 #elif defined(VGP_ppc64be_linux)
2615 /* PPC64 ELF ABI says '_start' points to a function descriptor.
2616 So we must have one, and that is what goes into the .opd section. */
2618 "\t.global _start\n"
2619 "\t.section \".opd\",\"aw\"\n"
2622 "\t.quad ._start,.TOC.@tocbase,0\n"
2624 "\t.type ._start,@function\n"
2625 "\t.global ._start\n"
2627 /* set up the new stack in r16 */
2628 "\tlis 16, vgPlain_interim_stack@highest\n"
2629 "\tori 16,16,vgPlain_interim_stack@higher\n"
2631 "\toris 16,16,vgPlain_interim_stack@h\n"
2632 "\tori 16,16,vgPlain_interim_stack@l\n"
2634 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB
)" >> 16)\n"
2635 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB
)" & 0xFFFF)\n"
2637 "\tlis 18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)" >> 16)\n"
2638 "\tori 18,18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)" & 0xFFFF)\n"
2641 "\trldicr 16,16,0,59\n"
2642 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2643 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2644 boundary. And r1 is the original SP. Set the SP to r16 and
2645 call _start_in_C_linux, passing it the initial SP. */
2648 "\tlis 14, _start_in_C_linux@highest\n"
2649 "\tori 14,14,_start_in_C_linux@higher\n"
2651 "\toris 14,14,_start_in_C_linux@h\n"
2652 "\tori 14,14,_start_in_C_linux@l\n"
2659 #elif defined(VGP_ppc64le_linux)
2660 /* Little Endian uses ELF version 2 but in the future may also
2661 * support other ELF versions.
2665 "\t.global _start\n"
2666 "\t.type _start,@function\n"
2668 "#if _CALL_ELF == 2 \n"
2669 "0: addis 2,12,.TOC.-0b@ha\n"
2670 " addi 2,2,.TOC.-0b@l\n"
2671 " .localentry _start, .-_start\n"
2673 /* set up the new stack in r16 */
2674 "\tlis 16, vgPlain_interim_stack@highest\n"
2675 "\tori 16,16,vgPlain_interim_stack@higher\n"
2677 "\toris 16,16,vgPlain_interim_stack@h\n"
2678 "\tori 16,16,vgPlain_interim_stack@l\n"
2680 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB
)" >> 16)\n"
2681 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB
)" & 0xFFFF)\n"
2683 "\tlis 18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)" >> 16)\n"
2684 "\tori 18,18,("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)" & 0xFFFF)\n"
2687 "\trldicr 16,16,0,59\n"
2688 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2689 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2690 boundary. And r1 is the original SP. Set the SP to r16 and
2691 call _start_in_C_linux, passing it the initial SP. */
2694 "\tlis 14, _start_in_C_linux@highest\n"
2695 "\tori 14,14,_start_in_C_linux@higher\n"
2697 "\toris 14,14,_start_in_C_linux@h\n"
2698 "\tori 14,14,_start_in_C_linux@l\n"
2704 #elif defined(VGP_s390x_linux)
2706 This is the canonical entry point, usually the first thing in the text
2707 segment. Most registers' values are unspecified, except for:
2709 %r14 Contains a function pointer to be registered with `atexit'.
2710 This is how the dynamic linker arranges to have DT_FINI
2711 functions called for shared libraries that have been loaded
2712 before this code runs.
2714 %r15 The stack contains the arguments and environment:
2719 (8*(argc+1))(%r15) envp[0]
2726 ".type _start,@function\n\t"
2728 /* set up the new stack in %r1 */
2729 "larl %r1, vgPlain_interim_stack\n\t"
2731 "ag %r1, 0(%r5)\n\t"
2732 "ag %r1, 2f-1f(%r5)\n\t"
2733 "nill %r1, 0xFFF0\n\t"
2734 /* install it, and collect the original one */
2737 /* call _start_in_C_linux, passing it the startup %r15 */
2738 "brasl %r14, _start_in_C_linux\n\t"
2739 /* trigger execution of an invalid opcode -> halt machine */
2741 "1: .quad "VG_STRINGIFY(VG_STACK_GUARD_SZB
)"\n\t"
2742 "2: .quad "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)"\n\t"
2745 #elif defined(VGP_arm_linux)
2749 "\t.type _start,#function\n"
2750 "\t.global _start\n"
2752 "\tldr r0, [pc, #36]\n"
2753 "\tldr r1, [pc, #36]\n"
2754 "\tadd r0, r1, r0\n"
2755 "\tldr r1, [pc, #32]\n"
2756 "\tadd r0, r1, r0\n"
2758 "\tand r0, r0, r1\n"
2762 "\tb _start_in_C_linux\n"
2763 "\t.word vgPlain_interim_stack\n"
2764 "\t.word "VG_STRINGIFY(VG_STACK_GUARD_SZB
)"\n"
2765 "\t.word "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)"\n"
2767 #elif defined(VGP_arm64_linux)
2771 "\t.type _start,#function\n"
2772 "\t.global _start\n"
2774 "\tadrp x0, vgPlain_interim_stack\n"
2775 "\tadd x0, x0, :lo12:vgPlain_interim_stack\n"
2776 // The next 2 assume that VG_STACK_GUARD_SZB fits in 32 bits
2777 "\tmov x1, (("VG_STRINGIFY(VG_STACK_GUARD_SZB
)") >> 0) & 0xFFFF\n"
2778 "\tmovk x1, (("VG_STRINGIFY(VG_STACK_GUARD_SZB
)") >> 16) & 0xFFFF,"
2780 "\tadd x0, x0, x1\n"
2781 // The next 2 assume that VG_DEFAULT_STACK_ACTIVE_SZB fits in 32 bits
2782 "\tmov x1, (("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)") >> 0) & 0xFFFF\n"
2783 "\tmovk x1, (("VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)") >> 16) & 0xFFFF,"
2785 "\tadd x0, x0, x1\n"
2786 "\tand x0, x0, -16\n"
2790 "\tb _start_in_C_linux\n"
2792 #elif defined(VGP_mips32_linux)
2794 "\t.type _gp_disp,@object\n"
2796 "\t.globl __start\n"
2797 "\t.type __start,@function\n"
2805 "\tlui $28, %hi(_gp_disp)\n"
2806 "\taddiu $28, $28, %lo(_gp_disp)\n"
2807 "\taddu $28, $28, $31\n"
2808 /* t1/$9 <- Addr(interim_stack) */
2809 "\tlui $9, %hi(vgPlain_interim_stack)\n"
2810 /* t1/$9 <- Addr(interim_stack) */
2811 "\taddiu $9, %lo(vgPlain_interim_stack)\n"
2814 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB
)"\n"
2815 "\tli $11, "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)"\n"
2817 "\taddu $9, $9, $10\n"
2818 "\taddu $9, $9, $11\n"
2819 "\tli $12, 0xFFFFFFF0\n"
2820 "\tand $9, $9, $12\n"
2821 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2822 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2823 boundary. And $29 is the original SP. Set the SP to t1 and
2824 call _start_in_C, passing it the initial SP. */
2826 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
2827 "\tmove $29, $9\n" // $sp <- t1 (new sp)
2829 "\tlui $25, %hi(_start_in_C_linux)\n"
2830 "\taddiu $25, %lo(_start_in_C_linux)\n"
2832 "\tbal _start_in_C_linux\n"
2836 #elif defined(VGP_mips64_linux)
2840 ".type __start,@function\n"
2842 "\t.set noreorder\n"
2846 "\tlui $9, %hi(vgPlain_interim_stack)\n"
2847 /* t1/$9 <- Addr(interim_stack) */
2848 "\tdaddiu $9, %lo(vgPlain_interim_stack)\n"
2850 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB
)"\n"
2851 "\tli $11, "VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)"\n"
2853 "\tdaddu $9, $9, $10\n"
2854 "\tdaddu $9, $9, $11\n"
2855 "\tli $12, 0xFFFFFF00\n"
2856 "\tand $9, $9, $12\n"
2857 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2858 VG_DEFAULT_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2859 boundary. And $29 is the original SP. Set the SP to t1 and
2860 call _start_in_C, passing it the initial SP. */
2862 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
2863 "\tmove $29, $9\n" // $sp <- t1 (new sp)
2865 "\tlui $9, %highest(_start_in_C_linux)\n"
2866 "\tori $9, %higher(_start_in_C_linux)\n"
2867 "\tdsll32 $9, $9, 0x0\n"
2868 "\tlui $10, %hi(_start_in_C_linux)\n"
2869 "\tdaddiu $10, %lo(_start_in_C_linux)\n"
2870 "\tdaddu $25, $9, $10\n"
2876 # error "Unknown linux platform"
2879 /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
2881 #define _FILE_OFFSET_BITS 64
2882 /* This is in order to get AT_NULL and AT_PAGESIZE. */
2884 /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
2886 /* Avoid compiler warnings: this fn _is_ used, but labelling it
2887 'static' causes gcc to complain it isn't.
2888 attribute 'used' also ensures the code is not eliminated at link
2890 __attribute__ ((used
))
2891 void _start_in_C_linux ( UWord
* pArgc
);
2892 __attribute__ ((used
))
2893 void _start_in_C_linux ( UWord
* pArgc
)
2896 Word argc
= pArgc
[0];
2897 HChar
** argv
= (HChar
**)&pArgc
[1];
2898 HChar
** envp
= (HChar
**)&pArgc
[1+argc
+1];
2900 // For an inner Valgrind, register the interim stack asap.
2901 // This is needed to allow the outer valgrind to do stacktraces during init.
2902 // Note that this stack is not unregistered when the main thread
2903 // is switching to the (real) stack. Unregistering this would imply
2904 // to save the stack id in a global variable, and have a "if"
2905 // in run_a_thread_NORETURN to do the unregistration only for the
2906 // main thread. This unregistration is not worth this complexity.
2908 ((void) VALGRIND_STACK_REGISTER
2909 (&VG_(interim_stack
).bytes
[0],
2910 &VG_(interim_stack
).bytes
[0] + sizeof(VG_(interim_stack
))));
2912 VG_(memset
)( &the_iicii
, 0, sizeof(the_iicii
) );
2913 VG_(memset
)( &the_iifii
, 0, sizeof(the_iifii
) );
2915 the_iicii
.sp_at_startup
= (Addr
)pArgc
;
2917 # if defined(VGP_ppc32_linux) || defined(VGP_ppc64be_linux) \
2918 || defined(VGP_ppc64le_linux) || defined(VGP_arm64_linux) \
2919 || defined(VGP_mips32_linux) || defined(VGP_mips64_linux)
2921 /* ppc32/ppc64, arm64, mips32/64 can be configured with different
2922 page sizes. Determine this early. This is an ugly hack and really
2923 should be moved into valgrind_main. */
2924 UWord
*sp
= &pArgc
[1+argc
+1];
2927 for (; *sp
!= AT_NULL
&& *sp
!= AT_PAGESZ
; sp
+= 2);
2928 if (*sp
== AT_PAGESZ
) {
2929 VKI_PAGE_SIZE
= sp
[1];
2930 for (VKI_PAGE_SHIFT
= 12;
2931 VKI_PAGE_SHIFT
<= VKI_MAX_PAGE_SHIFT
; VKI_PAGE_SHIFT
++)
2932 if (VKI_PAGE_SIZE
== (1UL << VKI_PAGE_SHIFT
))
2938 r
= valgrind_main( (Int
)argc
, argv
, envp
);
2944 /*====================================================================*/
2945 /*=== Getting to main() alive: darwin ===*/
2946 /*====================================================================*/
2948 #elif defined(VGO_darwin)
2951 Memory layout established by kernel:
2962 executable name (presumably, a pointer to it)
2965 Ditto in the 64-bit case, except all offsets from SP are obviously
2969 /* The kernel hands control to _start, which extracts the initial
2970 stack pointer and calls onwards to _start_in_C_darwin. This also
2971 switches to the new stack. */
2972 #if defined(VGP_x86_darwin)
2976 "\t.globl __start\n"
2978 /* set up the new stack in %eax */
2979 "\tmovl $_vgPlain_interim_stack, %eax\n"
2980 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB
)", %eax\n"
2981 "\taddl $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)", %eax\n"
2982 "\tsubl $16, %eax\n"
2983 "\tandl $~15, %eax\n"
2984 /* install it, and collect the original one */
2985 "\txchgl %eax, %esp\n"
2986 "\tsubl $12, %esp\n" // keep stack 16 aligned; see #295428
2987 /* call _start_in_C_darwin, passing it the startup %esp */
2989 "\tcall __start_in_C_darwin\n"
2993 #elif defined(VGP_amd64_darwin)
2996 "\t.globl __start\n"
2999 /* set up the new stack in %rdi */
3000 "\tmovabsq $_vgPlain_interim_stack, %rdi\n"
3001 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB
)", %rdi\n"
3002 "\taddq $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)", %rdi\n"
3003 "\tandq $~15, %rdi\n"
3004 /* install it, and collect the original one */
3005 "\txchgq %rdi, %rsp\n"
3006 /* call _start_in_C_darwin, passing it the startup %rsp */
3007 "\tcall __start_in_C_darwin\n"
3013 void* __memcpy_chk(void *dest
, const void *src
, SizeT n
, SizeT n2
);
3014 void* __memcpy_chk(void *dest
, const void *src
, SizeT n
, SizeT n2
) {
3016 return VG_(memcpy
)(dest
,src
,n
);
3018 void* __memset_chk(void *s
, int c
, SizeT n
, SizeT n2
);
3019 void* __memset_chk(void *s
, int c
, SizeT n
, SizeT n2
) {
3021 return VG_(memset
)(s
,c
,n
);
3023 void __bzero(void* s
, UWord n
);
3024 void __bzero(void* s
, UWord n
) {
3025 (void)VG_(memset
)(s
,0,n
);
3027 void bzero(void *s
, SizeT n
);
3028 void bzero(void *s
, SizeT n
) {
3032 void* memcpy(void *dest
, const void *src
, SizeT n
);
3033 void* memcpy(void *dest
, const void *src
, SizeT n
) {
3034 return VG_(memcpy
)(dest
,src
,n
);
3036 void* memset(void *s
, int c
, SizeT n
);
3037 void* memset(void *s
, int c
, SizeT n
) {
3038 return VG_(memset
)(s
,c
,n
);
3041 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3042 'static' causes gcc to complain it isn't. */
3043 void _start_in_C_darwin ( UWord
* pArgc
);
3044 void _start_in_C_darwin ( UWord
* pArgc
)
3047 Int argc
= *(Int
*)pArgc
; // not pArgc[0] on LP64
3048 HChar
** argv
= (HChar
**)&pArgc
[1];
3049 HChar
** envp
= (HChar
**)&pArgc
[1+argc
+1];
3051 // See _start_in_C_linux
3053 ((void) VALGRIND_STACK_REGISTER
3054 (&VG_(interim_stack
).bytes
[0],
3055 &VG_(interim_stack
).bytes
[0] + sizeof(VG_(interim_stack
))));
3057 VG_(memset
)( &the_iicii
, 0, sizeof(the_iicii
) );
3058 VG_(memset
)( &the_iifii
, 0, sizeof(the_iifii
) );
3060 the_iicii
.sp_at_startup
= (Addr
)pArgc
;
3062 r
= valgrind_main( (Int
)argc
, argv
, envp
);
3067 /*====================================================================*/
3068 /*=== Getting to main() alive: Solaris ===*/
3069 /*====================================================================*/
3070 #elif defined(VGO_solaris)
3071 #if defined(VGP_x86_solaris)
3072 /* The kernel hands control to _start, which extracts the initial stack
3073 pointer and calls onwards to _start_in_C_solaris. This also switches to
3078 "\t.type _start, @function\n"
3080 /* Set up the new stack in %eax. */
3081 "\tmovl $vgPlain_interim_stack, %eax\n"
3082 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB
)", %eax\n"
3083 "\taddl $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)", %eax\n"
3084 "\tandl $~15, %eax\n"
3085 /* Install it, and collect the original one. */
3086 "\txchgl %eax, %esp\n"
3087 "\tsubl $12, %esp\n" /* Keep stack 16-byte aligned. */
3088 /* Call _start_in_C_solaris, passing it the startup %esp. */
3090 "\tcall _start_in_C_solaris\n"
3095 #elif defined(VGP_amd64_solaris)
3099 "\t.type _start, @function\n"
3101 /* Set up the new stack in %rdi. */
3102 "\tmovq $vgPlain_interim_stack, %rdi\n"
3103 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB
)", %rdi\n"
3104 "\taddq $"VG_STRINGIFY(VG_DEFAULT_STACK_ACTIVE_SZB
)", %rdi\n"
3105 "\tandq $~15, %rdi\n"
3106 /* Install it, and collect the original one. */
3107 "\txchgq %rdi, %rsp\n"
3108 /* Call _start_in_C_solaris, passing it the startup %rsp. */
3109 "\tcall _start_in_C_solaris\n"
3115 # error "Unknown Solaris platform"
3118 void *memcpy(void *dest
, const void *src
, size_t n
);
3119 void *memcpy(void *dest
, const void *src
, size_t n
) {
3120 return VG_(memcpy
)(dest
, src
, n
);
3123 __attribute__ ((used
))
3124 void _start_in_C_solaris ( UWord
* pArgc
);
3125 __attribute__ ((used
))
3126 void _start_in_C_solaris ( UWord
* pArgc
)
3129 Word argc
= pArgc
[0];
3130 HChar
** argv
= (HChar
**)&pArgc
[1];
3131 HChar
** envp
= (HChar
**)&pArgc
[1 + argc
+ 1];
3133 VG_(memset
)( &the_iicii
, 0, sizeof(the_iicii
) );
3134 VG_(memset
)( &the_iifii
, 0, sizeof(the_iifii
) );
3136 the_iicii
.sp_at_startup
= (Addr
)pArgc
;
3138 r
= valgrind_main((Int
)argc
, argv
, envp
);
3144 # error "Unknown OS"
3148 Addr
VG_(get_initial_client_SP
)( void )
3150 return the_iifii
.initial_client_SP
;
3153 /*====================================================================*/
3154 /*=== {u,}{div,mod}di3 replacements ===*/
3155 /*====================================================================*/
3157 /* For static linking on x86-darwin, we need to supply our own 64-bit
3158 integer division code, else the link dies thusly:
3160 ld_classic: Undefined symbols:
3164 #if defined(VGP_x86_darwin)
3166 /* Routines for doing signed/unsigned 64 x 64 ==> 64 div and mod
3167 (udivdi3, umoddi3, divdi3, moddi3) using only 32 x 32 ==> 32
3168 division. Cobbled together from
3170 http://www.hackersdelight.org/HDcode/divlu.c
3171 http://www.hackersdelight.org/HDcode/divls.c
3172 http://www.hackersdelight.org/HDcode/newCode/divDouble.c
3174 The code from those three files is covered by the following license,
3177 http://www.hackersdelight.org/permissions.htm
3179 You are free to use, copy, and distribute any of the code on
3180 this web site, whether modified by you or not. You need not give
3181 attribution. This includes the algorithms (some of which appear
3182 in Hacker's Delight), the Hacker's Assistant, and any code
3183 submitted by readers. Submitters implicitly agree to this.
3186 /* Long division, unsigned (64/32 ==> 32).
3187 This procedure performs unsigned "long division" i.e., division of a
3188 64-bit unsigned dividend by a 32-bit unsigned divisor, producing a
3189 32-bit quotient. In the overflow cases (divide by 0, or quotient
3190 exceeds 32 bits), it returns a remainder of 0xFFFFFFFF (an impossible
3192 The dividend is u1 and u0, with u1 being the most significant word.
3193 The divisor is parameter v. The value returned is the quotient.
3194 Max line length is 57, to fit in hacker.book. */
3196 static Int
nlz32(UInt x
)
3199 if (x
== 0) return(32);
3201 if (x
<= 0x0000FFFF) {n
= n
+16; x
= x
<<16;}
3202 if (x
<= 0x00FFFFFF) {n
= n
+ 8; x
= x
<< 8;}
3203 if (x
<= 0x0FFFFFFF) {n
= n
+ 4; x
= x
<< 4;}
3204 if (x
<= 0x3FFFFFFF) {n
= n
+ 2; x
= x
<< 2;}
3205 if (x
<= 0x7FFFFFFF) {n
= n
+ 1;}
3209 /* 64 x 32 ==> 32 unsigned division, using only 32 x 32 ==> 32
3210 division as a primitive. */
3211 static UInt
divlu2(UInt u1
, UInt u0
, UInt v
, UInt
*r
)
3213 const UInt b
= 65536; // Number base (16 bits).
3214 UInt un1
, un0
, // Norm. dividend LSD's.
3215 vn1
, vn0
, // Norm. divisor digits.
3216 q1
, q0
, // Quotient digits.
3217 un32
, un21
, un10
, // Dividend digit pairs.
3218 rhat
; // A remainder.
3219 Int s
; // Shift amount for norm.
3221 if (u1
>= v
) { // If overflow, set rem.
3222 if (r
!= NULL
) // to an impossible value,
3223 *r
= 0xFFFFFFFF; // and return the largest
3224 return 0xFFFFFFFF;} // possible quotient.
3226 s
= nlz32(v
); // 0 <= s <= 31.
3227 v
= v
<< s
; // Normalize divisor.
3228 vn1
= v
>> 16; // Break divisor up into
3229 vn0
= v
& 0xFFFF; // two 16-bit digits.
3231 un32
= (u1
<< s
) | ((u0
>> (32 - s
)) & (-s
>> 31));
3232 un10
= u0
<< s
; // Shift dividend left.
3234 un1
= un10
>> 16; // Break right half of
3235 un0
= un10
& 0xFFFF; // dividend into two digits.
3237 q1
= un32
/vn1
; // Compute the first
3238 rhat
= un32
- q1
*vn1
; // quotient digit, q1.
3240 if (q1
>= b
|| q1
*vn0
> b
*rhat
+ un1
) {
3243 if (rhat
< b
) goto again1
;}
3245 un21
= un32
*b
+ un1
- q1
*v
; // Multiply and subtract.
3247 q0
= un21
/vn1
; // Compute the second
3248 rhat
= un21
- q0
*vn1
; // quotient digit, q0.
3250 if (q0
>= b
|| q0
*vn0
> b
*rhat
+ un0
) {
3253 if (rhat
< b
) goto again2
;}
3255 if (r
!= NULL
) // If remainder is wanted,
3256 *r
= (un21
*b
+ un0
- q0
*v
) >> s
; // return it.
3261 /* 64 x 32 ==> 32 signed division, using only 32 x 32 ==> 32 division
3263 static Int
divls(Int u1
, UInt u0
, Int v
, Int
*r
)
3265 Int q
, uneg
, vneg
, diff
, borrow
;
3267 uneg
= u1
>> 31; // -1 if u < 0.
3268 if (uneg
) { // Compute the absolute
3269 u0
= -u0
; // value of the dividend u.
3273 vneg
= v
>> 31; // -1 if v < 0.
3274 v
= (v
^ vneg
) - vneg
; // Absolute value of v.
3276 if ((UInt
)u1
>= (UInt
)v
) goto overflow
;
3278 q
= divlu2(u1
, u0
, v
, (UInt
*)r
);
3280 diff
= uneg
^ vneg
; // Negate q if signs of
3281 q
= (q
^ diff
) - diff
; // u and v differed.
3282 if (uneg
&& r
!= NULL
)
3285 if ((diff
^ q
) < 0 && q
!= 0) { // If overflow,
3286 overflow
: // set remainder
3287 if (r
!= NULL
) // to an impossible value,
3288 *r
= 0x80000000; // and return the largest
3289 q
= 0x80000000;} // possible neg. quotient.
3295 /* This file contains a program for doing 64/64 ==> 64 division, on a
3296 machine that does not have that instruction but that does have
3297 instructions for "long division" (64/32 ==> 32). Code for unsigned
3298 division is given first, followed by a simple program for doing the
3299 signed version by using the unsigned version.
3300 These programs are useful in implementing "long long" (64-bit)
3301 arithmetic on a machine that has the long division instruction. It will
3302 work on 64- and 32-bit machines, provided the compiler implements long
3303 long's (64-bit integers). It is desirable that the machine have the
3304 Count Leading Zeros instruction.
3305 In the GNU world, these programs are known as __divdi3 and __udivdi3,
3306 and similar names are used here.
3307 This material is not in HD, but may be in a future edition.
3308 Max line length is 57, to fit in hacker.book. */
3311 static Int
nlz64(ULong x
)
3314 if (x
== 0) return(64);
3316 if (x
<= 0x00000000FFFFFFFFULL
) {n
= n
+ 32; x
= x
<< 32;}
3317 if (x
<= 0x0000FFFFFFFFFFFFULL
) {n
= n
+ 16; x
= x
<< 16;}
3318 if (x
<= 0x00FFFFFFFFFFFFFFULL
) {n
= n
+ 8; x
= x
<< 8;}
3319 if (x
<= 0x0FFFFFFFFFFFFFFFULL
) {n
= n
+ 4; x
= x
<< 4;}
3320 if (x
<= 0x3FFFFFFFFFFFFFFFULL
) {n
= n
+ 2; x
= x
<< 2;}
3321 if (x
<= 0x7FFFFFFFFFFFFFFFULL
) {n
= n
+ 1;}
3325 // ---------------------------- udivdi3 --------------------------------
3327 /* The variables u0, u1, etc. take on only 32-bit values, but they
3328 are declared long long to avoid some compiler warning messages and to
3329 avoid some unnecessary EXTRs that the compiler would put in, to
3330 convert long longs to ints.
3332 First the procedure takes care of the case in which the divisor is a
3333 32-bit quantity. There are two subcases: (1) If the left half of the
3334 dividend is less than the divisor, one execution of DIVU is all that
3335 is required (overflow is not possible). (2) Otherwise it does two
3336 divisions, using the grade school method, with variables used as
3346 /* These macros must be used with arguments of the appropriate type
3347 (unsigned long long for DIVU and long long for DIVS. They are
3348 simulations of the presumed machines ops. I.e., they look at only the
3349 low-order 32 bits of the divisor, they return garbage if the division
3350 overflows, and they return garbage in the high-order half of the
3351 quotient doubleword.
3352 In practice, these would be replaced with uses of the machine's DIVU
3353 and DIVS instructions (e.g., by using the GNU "asm" facility). */
3355 static UInt
DIVU ( ULong u
, UInt v
)
3357 UInt uHi
= (UInt
)(u
>> 32);
3359 return divlu2(uHi
, uLo
, v
, NULL
);
3362 static Int
DIVS ( Long u
, Int v
)
3364 Int uHi
= (Int
)(u
>> 32);
3366 return divls(uHi
, uLo
, v
, NULL
);
3369 /* 64 x 64 ==> 64 unsigned division, using only 32 x 32 ==> 32
3370 division as a primitive. */
3371 static ULong
udivdi3(ULong u
, ULong v
)
3373 ULong u0
, u1
, v1
, q0
, q1
, k
, n
;
3375 if (v
>> 32 == 0) { // If v < 2**32:
3376 if (u
>> 32 < v
) // If u/v cannot overflow,
3377 return DIVU(u
, v
) // just do one division.
3379 else { // If u/v would overflow:
3380 u1
= u
>> 32; // Break u up into two
3381 u0
= u
& 0xFFFFFFFF; // halves.
3382 q1
= DIVU(u1
, v
) // First quotient digit.
3384 k
= u1
- q1
*v
; // First remainder, < v.
3385 q0
= DIVU((k
<< 32) + u0
, v
) // 2nd quot. digit.
3387 return (q1
<< 32) + q0
;
3391 n
= nlz64(v
); // 0 <= n <= 31.
3392 v1
= (v
<< n
) >> 32; // Normalize the divisor
3394 u1
= u
>> 1; // To ensure no overflow.
3395 q1
= DIVU(u1
, v1
) // Get quotient from
3396 & 0xFFFFFFFF; // divide unsigned insn.
3397 q0
= (q1
<< n
) >> 31; // Undo normalization and
3398 // division of u by 2.
3399 if (q0
!= 0) // Make q0 correct or
3400 q0
= q0
- 1; // too small by 1.
3401 if ((u
- q0
*v
) >= v
)
3402 q0
= q0
+ 1; // Now q0 is correct.
3407 // ----------------------------- divdi3 --------------------------------
3409 /* This routine presumes that smallish cases (those which can be done in
3410 one execution of DIVS) are common. If this is not the case, the test for
3411 this case should be deleted.
3412 Note that the test for when DIVS can be used is not entirely
3413 accurate. For example, DIVS is not used if v = 0xFFFFFFFF8000000,
3414 whereas if could be (if u is sufficiently small in magnitude). */
3416 // ------------------------------ cut ----------------------------------
3418 static ULong
my_llabs ( Long x
)
3424 /* 64 x 64 ==> 64 signed division, using only 32 x 32 ==> 32 division
3426 static Long
divdi3(Long u
, Long v
)
3432 if (av
>> 31 == 0) { // If |v| < 2**31 and
3433 // if (v << 32 >> 32 == v) { // If v is in range and
3434 if (au
< av
<< 31) { // |u|/|v| cannot
3435 q
= DIVS(u
, v
); // overflow, use DIVS.
3436 return (q
<< 32) >> 32;
3439 q
= udivdi3(au
,av
); // Invoke udivdi3.
3440 t
= (u
^ v
) >> 63; // If u, v have different
3441 return (q
^ t
) - t
; // signs, negate q.
3444 // ---------------------------- end cut --------------------------------
3446 ULong
__udivdi3 (ULong u
, ULong v
);
3447 ULong
__udivdi3 (ULong u
, ULong v
)
3449 return udivdi3(u
,v
);
3452 Long
__divdi3 (Long u
, Long v
);
3453 Long
__divdi3 (Long u
, Long v
)
3458 ULong
__umoddi3 (ULong u
, ULong v
);
3459 ULong
__umoddi3 (ULong u
, ULong v
)
3461 ULong q
= __udivdi3(u
, v
);
3462 ULong r
= u
- q
* v
;
3466 Long
__moddi3 (Long u
, Long v
);
3467 Long
__moddi3 (Long u
, Long v
)
3469 Long q
= __divdi3(u
, v
);
3474 /* ------------------------------------------------
3475 ld_classic: Undefined symbols:
3477 ------------------------------------------------
3480 /* ===-- fixunsdfdi.c - Implement __fixunsdfdi -----------------------------===
3482 * The LLVM Compiler Infrastructure
3484 * This file is dual licensed under the MIT and the University of Illinois Open
3485 * Source Licenses. See LICENSE.TXT for details.
3487 * ===----------------------------------------------------------------------===
3489 * This file implements __fixunsdfdi for the compiler_rt library.
3491 * ===----------------------------------------------------------------------===
3494 /* As per http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses,
3496 the "NCSA/University of Illinois Open Source License" is compatible
3497 with the GPL (both version 2 and 3). What is claimed to be
3500 http://www.opensource.org/licenses/UoI-NCSA.php
3502 and the LLVM documentation at
3504 http://www.llvm.org/docs/DeveloperPolicy.html#license
3506 says all the code in LLVM is available under the University of
3507 Illinois/NCSA Open Source License, at this URL
3509 http://www.opensource.org/licenses/UoI-NCSA.php
3511 viz, the same one that the FSF pages claim is compatible. So I
3512 think it's OK to include it.
3515 /* Returns: convert a to a unsigned long long, rounding toward zero.
3516 * Negative values all become zero.
3519 /* Assumption: double is a IEEE 64 bit floating point type
3520 * du_int is a 64 bit integral type
3521 * value in double is representable in du_int or is negative
3522 * (no range checking performed)
3525 /* seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm */
3527 typedef unsigned long long du_int
;
3528 typedef unsigned su_int
;
3541 #endif /* VG_LITTLEENDIAN */
3551 du_int
__fixunsdfdi(double a
);
3554 __fixunsdfdi(double a
)
3558 int e
= ((fb
.u
.s
.high
& 0x7FF00000) >> 20) - 1023;
3559 if (e
< 0 || (fb
.u
.s
.high
& 0x80000000))
3562 r
.s
.high
= (fb
.u
.s
.high
& 0x000FFFFF) | 0x00100000;
3563 r
.s
.low
= fb
.u
.s
.low
;
3575 /*====================================================================*/
3576 /*=== Dummy _voucher_mach_msg_set for OSX 10.10 ===*/
3577 /*====================================================================*/
3579 #if defined(VGO_darwin) && DARWIN_VERS >= DARWIN_10_10
3581 /* Builds on MacOSX 10.10+ seem to need this for some reason. */
3582 /* extern boolean_t voucher_mach_msg_set(mach_msg_header_t *msg)
3583 __attribute__((weak_import));
3584 I haven't a clue what the return value means, so just return 0.
3585 Looks like none of the generated uses in the tree look at the
3586 return value anyway.
3588 UWord
voucher_mach_msg_set ( UWord arg1
);
3589 UWord
voucher_mach_msg_set ( UWord arg1
)
3597 /*--------------------------------------------------------------------*/
3599 /*--------------------------------------------------------------------*/