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-2013 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 "pub_core_basics.h"
32 #include "pub_core_vki.h"
33 #include "pub_core_vkiscnums.h"
34 #include "pub_core_libcsetjmp.h" // to keep _threadstate.h happy
35 #include "pub_core_threadstate.h"
36 #include "pub_core_xarray.h"
37 #include "pub_core_clientstate.h"
38 #include "pub_core_aspacemgr.h"
39 #include "pub_core_aspacehl.h"
40 #include "pub_core_commandline.h"
41 #include "pub_core_debuglog.h"
42 #include "pub_core_errormgr.h"
43 #include "pub_core_execontext.h"
44 #include "pub_core_gdbserver.h"
45 #include "pub_core_initimg.h"
46 #include "pub_core_libcbase.h"
47 #include "pub_core_libcassert.h"
48 #include "pub_core_libcfile.h"
49 #include "pub_core_libcprint.h"
50 #include "pub_core_libcproc.h"
51 #include "pub_core_libcsignal.h"
52 #include "pub_core_sbprofile.h"
53 #include "pub_core_syscall.h" // VG_(strerror)
54 #include "pub_core_mach.h"
55 #include "pub_core_machine.h"
56 #include "pub_core_mallocfree.h"
57 #include "pub_core_options.h"
58 #include "pub_core_debuginfo.h"
59 #include "pub_core_redir.h"
60 #include "pub_core_scheduler.h"
61 #include "pub_core_seqmatch.h" // For VG_(string_match)
62 #include "pub_core_signals.h"
63 #include "pub_core_stacks.h" // For VG_(register_stack)
64 #include "pub_core_syswrap.h"
65 #include "pub_core_tooliface.h"
66 #include "pub_core_translate.h" // For VG_(translate)
67 #include "pub_core_trampoline.h"
68 #include "pub_core_transtab.h"
69 #include "pub_core_inner.h"
70 #if defined(ENABLE_INNER_CLIENT_REQUEST)
71 #include "pub_core_clreq.h"
75 /*====================================================================*/
76 /*=== Command-line: variables, processing, etc ===*/
77 /*====================================================================*/
79 // See pub_{core,tool}_options.h for explanations of all these.
81 static void usage_NORETURN ( Bool debug_help
)
83 /* 'usage1' contains a %s
84 - for the name of the GDB executable
85 - for the name of vgdb's path prefix
86 which must be supplied when they are VG_(printf)'d. */
87 const HChar usage1
[] =
88 "usage: valgrind [options] prog-and-args\n"
90 " tool-selection option, with default in [ ]:\n"
91 " --tool=<name> use the Valgrind tool named <name> [memcheck]\n"
93 " basic user options for all Valgrind tools, with defaults in [ ]:\n"
94 " -h --help show this message\n"
95 " --help-debug show this message, plus debugging options\n"
96 " --version show version\n"
97 " -q --quiet run silently; only print error msgs\n"
98 " -v --verbose be more verbose -- show misc extra info\n"
99 " --trace-children=no|yes Valgrind-ise child processes (follow execve)? [no]\n"
100 " --trace-children-skip=patt1,patt2,... specifies a list of executables\n"
101 " that --trace-children=yes should not trace into\n"
102 " --trace-children-skip-by-arg=patt1,patt2,... same as --trace-children-skip=\n"
103 " but check the argv[] entries for children, rather\n"
104 " than the exe name, to make a follow/no-follow decision\n"
105 " --child-silent-after-fork=no|yes omit child output between fork & exec? [no]\n"
106 " --vgdb=no|yes|full activate gdbserver? [yes]\n"
107 " full is slower but provides precise watchpoint/step\n"
108 " --vgdb-error=<number> invoke gdbserver after <number> errors [%d]\n"
109 " to get started quickly, use --vgdb-error=0\n"
110 " and follow the on-screen directions\n"
111 " --vgdb-stop-at=event1,event2,... invoke gdbserver for given events [none]\n"
112 " where event is one of 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 " --error-exitcode=<number> exit code to return if errors found [0=disable]\n"
129 " --show-below-main=no|yes continue stack traces below main() [no]\n"
130 " --default-suppressions=yes|no\n"
131 " load default suppressions [yes]\n"
132 " --suppressions=<filename> suppress errors described in <filename>\n"
133 " --gen-suppressions=no|yes|all print suppressions for errors? [no]\n"
134 " --db-attach=no|yes start debugger when errors detected? [no]\n"
135 " --db-command=<command> command to start debugger [%s -nw %%f %%p]\n"
136 " --input-fd=<number> file descriptor for input [0=stdin]\n"
137 " --dsymutil=no|yes run dsymutil on Mac OS X when helpful? [no]\n"
138 " --max-stackframe=<number> assume stack switch for SP changes larger\n"
139 " than <number> bytes [2000000]\n"
140 " --main-stacksize=<number> set size of main thread's stack (in bytes)\n"
141 " [min(max(current 'ulimit' value,1MB),16MB)]\n"
143 " user options for Valgrind tools that replace malloc:\n"
144 " --alignment=<number> set minimum alignment of heap allocations [%s]\n"
145 " --redzone-size=<number> set minimum size of redzones added before/after\n"
146 " heap blocks (in bytes). [%s]\n"
148 " uncommon user options for all Valgrind tools:\n"
149 " --fullpath-after= (with nothing after the '=')\n"
150 " show full source paths in call stacks\n"
151 " --fullpath-after=string like --fullpath-after=, but only show the\n"
152 " part of the path after 'string'. Allows removal\n"
153 " of path prefixes. Use this flag multiple times\n"
154 " to specify a set of prefixes to remove.\n"
155 " --extra-debuginfo-path=path absolute path to search for additional\n"
156 " debug symbols, in addition to existing default\n"
157 " well known search paths.\n"
158 " --debuginfo-server=ipaddr:port also query this server\n"
159 " (valgrind-di-server) for debug symbols\n"
160 " --allow-mismatched-debuginfo=no|yes [no]\n"
161 " for the above two flags only, accept debuginfo\n"
162 " objects that don't \"match\" the main object\n"
163 " --smc-check=none|stack|all|all-non-file [stack]\n"
164 " checks for self-modifying code: none, only for\n"
165 " code found in stacks, for all code, or for all\n"
166 " code except that from file-backed mappings\n"
167 " --read-inline-info=yes|no read debug info about inlined function calls\n"
168 " and use it to do better stack traces [no]\n"
169 " --read-var-info=yes|no read debug info on stack and global variables\n"
170 " and use it to print better error messages in\n"
171 " tools that make use of it (Memcheck, Helgrind,\n"
173 " --vgdb-poll=<number> gdbserver poll max every <number> basic blocks [%d] \n"
174 " --vgdb-shadow-registers=no|yes let gdb see the shadow registers [no]\n"
175 " --vgdb-prefix=<prefix> prefix for vgdb FIFOs [%s]\n"
176 " --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]\n"
177 " --sim-hints=hint1,hint2,... activate unusual sim behaviours [none] \n"
178 " where hint is one of lax-ioctls fuse-compatible enable-outer\n"
179 " no-inner-prefix no-nptl-pthread-stackcache none\n"
180 " --fair-sched=no|yes|try schedule threads fairly on multicore systems [no]\n"
181 " --kernel-variant=variant1,variant2,... handle non-standard kernel"
183 " where variant is one of bproc none\n"
184 " --merge-recursive-frames=<number> merge frames between identical\n"
185 " program counters in max <number> frames) [0]\n"
186 " --num-transtab-sectors=<number> size of translated code cache [%d]\n"
187 " more sectors may increase performance, but use more memory.\n"
188 " --aspace-minaddr=0xPP avoid mapping memory below 0xPP [guessed]\n"
189 " --show-emwarns=no|yes show warnings about emulation limits? [no]\n"
190 " --require-text-symbol=:sonamepattern:symbolpattern abort run if the\n"
191 " stated shared object doesn't have the stated\n"
192 " text symbol. Patterns can contain ? and *.\n"
193 " --soname-synonyms=syn1=pattern1,syn2=pattern2,... synonym soname\n"
194 " specify patterns for function wrapping or replacement.\n"
195 " To use a non-libc malloc library that is\n"
196 " in the main exe: --soname-synonyms=somalloc=NONE\n"
197 " in libxyzzy.so: --soname-synonyms=somalloc=libxyzzy.so\n"
198 " --sigill-diagnostics=yes|no warn about illegal instructions? [yes]\n"
199 " --unw-stack-scan-thresh=<number> Enable stack-scan unwind if fewer\n"
200 " than <number> good frames found [0, meaning \"disabled\"]\n"
201 " NOTE: stack scanning is only available on arm-linux.\n"
202 " --unw-stack-scan-frames=<number> Max number of frames that can be\n"
203 " recovered by stack scanning [5]\n"
206 const HChar usage2
[] =
208 " debugging options for all Valgrind tools:\n"
209 " -d show verbose debugging output\n"
210 " --stats=no|yes show tool and core statistics [no]\n"
211 " --sanity-level=<number> level of sanity checking to do [1]\n"
212 " --trace-flags=<XXXXXXXX> show generated code? (X = 0|1) [00000000]\n"
213 " --profile-flags=<XXXXXXXX> ditto, but for profiling (X = 0|1) [00000000]\n"
214 " --profile-interval=<number> show profile every <number> event checks\n"
215 " [0, meaning only at the end of the run]\n"
216 " --trace-notbelow=<number> only show BBs above <number> [999999999]\n"
217 " --trace-notabove=<number> only show BBs below <number> [0]\n"
218 " --trace-syscalls=no|yes show all system calls? [no]\n"
219 " --trace-signals=no|yes show signal handling details? [no]\n"
220 " --trace-symtab=no|yes show symbol table details? [no]\n"
221 " --trace-symtab-patt=<patt> limit debuginfo tracing to obj name <patt>\n"
222 " --trace-cfi=no|yes show call-frame-info details? [no]\n"
223 " --debug-dump=syms mimic /usr/bin/readelf --syms\n"
224 " --debug-dump=line mimic /usr/bin/readelf --debug-dump=line\n"
225 " --debug-dump=frames mimic /usr/bin/readelf --debug-dump=frames\n"
226 " --trace-redir=no|yes show redirection details? [no]\n"
227 " --trace-sched=no|yes show thread scheduler details? [no]\n"
228 " --profile-heap=no|yes profile Valgrind's own space use\n"
229 " --core-redzone-size=<number> set minimum size of redzones added before/after\n"
230 " heap blocks allocated for Valgrind internal use (in bytes) [4]\n"
231 " --wait-for-gdb=yes|no pause on startup to wait for gdb attach\n"
232 " --sym-offsets=yes|no show syms in form 'name+offset' ? [no]\n"
233 " --command-line-only=no|yes only use command line options [no]\n"
235 " Vex options for all Valgrind tools:\n"
236 " --vex-iropt-verbosity=<0..9> [0]\n"
237 " --vex-iropt-level=<0..2> [2]\n"
238 " --vex-iropt-register-updates=sp-at-mem-access\n"
239 " |unwindregs-at-mem-access\n"
240 " |allregs-at-mem-access\n"
241 " |allregs-at-each-insn [unwindregs-at-mem-access]\n"
242 " --vex-iropt-unroll-thresh=<0..400> [120]\n"
243 " --vex-guest-max-insns=<1..100> [50]\n"
244 " --vex-guest-chase-thresh=<0..99> [10]\n"
245 " --vex-guest-chase-cond=no|yes [no]\n"
246 " --trace-flags and --profile-flags values (omit the middle space):\n"
247 " 1000 0000 show conversion into IR\n"
248 " 0100 0000 show after initial opt\n"
249 " 0010 0000 show after instrumentation\n"
250 " 0001 0000 show after second opt\n"
251 " 0000 1000 show after tree building\n"
252 " 0000 0100 show selecting insns\n"
253 " 0000 0010 show after reg-alloc\n"
254 " 0000 0001 show final assembly\n"
255 " 0000 0000 show summary profile only\n"
256 " (Nb: you need --trace-notbelow and/or --trace-notabove\n"
257 " with --trace-flags for full details)\n"
259 " debugging options for Valgrind tools that report errors\n"
260 " --dump-error=<number> show translation for basic block associated\n"
261 " with <number>'th error context [0=show none]\n"
263 " debugging options for Valgrind tools that replace malloc:\n"
264 " --trace-malloc=no|yes show client malloc details? [no]\n"
267 const HChar usage3
[] =
269 " Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc\n"
272 " Valgrind is Copyright (C) 2000-2013, and GNU GPL'd, by Julian Seward et al.\n"
273 " LibVEX is Copyright (C) 2004-2013, and GNU GPL'd, by OpenWorks LLP et al.\n"
275 " Bug reports, feedback, admiration, abuse, etc, to: %s.\n"
278 const HChar
* gdb_path
= GDB_PATH
;
279 HChar default_alignment
[30];
280 HChar default_redzone_size
[30];
282 // Ensure the message goes to stdout
283 VG_(log_output_sink
).fd
= 1;
284 VG_(log_output_sink
).is_socket
= False
;
286 if (VG_(needs
).malloc_replacement
) {
287 VG_(sprintf
)(default_alignment
, "%d", VG_MIN_MALLOC_SZB
);
288 VG_(sprintf
)(default_redzone_size
, "%lu", VG_(tdict
).tool_client_redzone_szB
);
290 VG_(strcpy
)(default_alignment
, "not used by this tool");
291 VG_(strcpy
)(default_redzone_size
, "not used by this tool");
293 /* 'usage1' a type as described after each arg. */
295 VG_(clo_vgdb_error
) /* int */,
296 gdb_path
/* char* */,
297 default_alignment
/* char* */,
298 default_redzone_size
/* char* */,
299 VG_(clo_vgdb_poll
) /* int */,
300 VG_(vgdb_prefix_default
)() /* char* */,
301 N_SECTORS_DEFAULT
/* int */
303 if (VG_(details
).name
) {
304 VG_(printf
)(" user options for %s:\n", VG_(details
).name
);
305 if (VG_(needs
).command_line_options
)
306 VG_TDICT_CALL(tool_print_usage
);
308 VG_(printf
)(" (none)\n");
311 VG_(printf
)("%s", usage2
);
313 if (VG_(details
).name
) {
314 VG_(printf
)(" debugging options for %s:\n", VG_(details
).name
);
316 if (VG_(needs
).command_line_options
)
317 VG_TDICT_CALL(tool_print_debug_usage
);
319 VG_(printf
)(" (none)\n");
322 VG_(printf
)(usage3
, VG_(details
).name
, VG_(details
).copyright_author
,
328 /* Peer at previously set up VG_(args_for_valgrind) and do some
329 minimal command line processing that must happen early on:
331 - show the version string, if requested (-v)
332 - extract any request for help (--help, -h, --help-debug)
333 - get the toolname (--tool=)
334 - set VG_(clo_max_stackframe) (--max-stackframe=)
335 - set VG_(clo_main_stacksize) (--main-stacksize=)
336 - set VG_(clo_sim_hints) (--sim-hints=)
338 That's all it does. The main command line processing is done below
339 by main_process_cmd_line_options. Note that
340 main_process_cmd_line_options has to handle but ignore the ones we
343 static void early_process_cmd_line_options ( /*OUT*/Int
* need_help
,
344 /*OUT*/const HChar
** tool
)
349 vg_assert( VG_(args_for_valgrind
) );
351 /* parse the options we have (only the options we care about now) */
352 for (i
= 0; i
< VG_(sizeXA
)( VG_(args_for_valgrind
) ); i
++) {
354 str
= * (HChar
**) VG_(indexXA
)( VG_(args_for_valgrind
), i
);
357 // Nb: the version string goes to stdout.
358 if VG_XACT_CLO(str
, "--version", VG_(log_output_sink
).fd
, 1) {
359 VG_(log_output_sink
).is_socket
= False
;
360 VG_(printf
)("valgrind-" VERSION
"\n");
363 else if VG_XACT_CLO(str
, "--help", *need_help
, *need_help
+1) {}
364 else if VG_XACT_CLO(str
, "-h", *need_help
, *need_help
+1) {}
366 else if VG_XACT_CLO(str
, "--help-debug", *need_help
, *need_help
+2) {}
368 // The tool has already been determined, but we need to know the name
370 else if VG_STR_CLO(str
, "--tool", *tool
) {}
372 // Set up VG_(clo_max_stackframe) and VG_(clo_main_stacksize).
373 // These are needed by VG_(ii_create_image), which happens
374 // before main_process_cmd_line_options().
375 else if VG_INT_CLO(str
, "--max-stackframe", VG_(clo_max_stackframe
)) {}
376 else if VG_INT_CLO(str
, "--main-stacksize", VG_(clo_main_stacksize
)) {}
378 // Set up VG_(clo_sim_hints). This is needed a.o. for an inner
379 // running in an outer, to have "no-inner-prefix" enabled
380 // as early as possible.
381 else if VG_USETX_CLO (str
, "--sim-hints",
382 "no-inner-prefix,fuse-compatible,"
383 "lax-ioctls,enable-outer,"
384 "no-nptl-pthread-stackcache",
385 VG_(clo_sim_hints
)) {}
389 /* The main processing for command line options. See comments above
390 on early_process_cmd_line_options.
392 Comments on how the logging options are handled:
395 --log-fd= for a fd to write to (default setting, fd = 2)
396 --log-file= for a file name to write to
397 --log-socket= for a socket to write to
399 As a result of examining these and doing relevant socket/file
400 opening, a final fd is established. This is stored in
401 VG_(log_output_sink) in m_libcprint. Also, if --log-file=STR was
402 specified, then STR, after expansion of %p and %q templates within
403 it, is stored in VG_(clo_log_fname_expanded), in m_options, just in
404 case anybody wants to know what it is.
406 When printing, VG_(log_output_sink) is consulted to find the
407 fd to send output to.
409 Exactly analogous actions are undertaken for the XML output
410 channel, with the one difference that the default fd is -1, meaning
411 the channel is disabled by default.
414 void main_process_cmd_line_options ( /*OUT*/Bool
* logging_to_fd
,
415 /*OUT*/HChar
** xml_fname_unexpanded
,
416 const HChar
* toolname
)
418 // VG_(clo_log_fd) is used by all the messaging. It starts as 2 (stderr)
419 // and we cannot change it until we know what we are changing it to is
420 // ok. So we have tmp_log_fd to hold the tmp fd prior to that point.
422 Int i
, tmp_log_fd
, tmp_xml_fd
;
423 Int toolname_len
= VG_(strlen
)(toolname
);
424 const HChar
* tmp_str
; // Used in a couple of places.
429 } log_to
= VgLogTo_Fd
, // Where is logging output to be sent?
430 xml_to
= VgLogTo_Fd
; // Where is XML output to be sent?
432 /* Temporarily holds the string STR specified with
433 --{log,xml}-{name,socket}=STR. 'fs' stands for
435 const HChar
* log_fsname_unexpanded
= NULL
;
436 const HChar
* xml_fsname_unexpanded
= NULL
;
438 /* Whether the user has explicitly provided --sigill-diagnostics.
439 If not explicitly given depends on general verbosity setting. */
440 Bool sigill_diag_set
= False
;
442 /* Log to stderr by default, but usage message goes to stdout. XML
443 output is initially disabled. */
447 /* Check for sane path in ./configure --prefix=... */
448 if (VG_LIBDIR
[0] != '/')
449 VG_(err_config_error
)("Please use absolute paths in "
450 "./configure --prefix=... or --libdir=...\n");
452 vg_assert( VG_(args_for_valgrind
) );
454 /* BEGIN command-line processing loop */
456 for (i
= 0; i
< VG_(sizeXA
)( VG_(args_for_valgrind
) ); i
++) {
458 HChar
* arg
= * (HChar
**) VG_(indexXA
)( VG_(args_for_valgrind
), i
);
461 // Look for a colon in the option name.
462 while (*colon
&& *colon
!= ':' && *colon
!= '=')
465 // Does it have the form "--toolname:foo"? We have to do it at the start
466 // in case someone has combined a prefix with a core-specific option,
467 // eg. "--memcheck:verbose".
469 if (VG_STREQN(2, arg
, "--") &&
470 VG_STREQN(toolname_len
, arg
+2, toolname
) &&
471 VG_STREQN(1, arg
+2+toolname_len
, ":"))
473 // Prefix matches, convert "--toolname:foo" to "--foo".
474 // Two things to note:
475 // - We cannot modify the option in-place. If we did, and then
476 // a child was spawned with --trace-children=yes, the
477 // now-non-prefixed option would be passed and could screw up
479 // - We create copies, and never free them. Why? Non-prefixed
480 // options hang around forever, so tools need not make copies
481 // of strings within them. We need to have the same behaviour
482 // for prefixed options. The pointer to the copy will be lost
483 // once we leave this function (although a tool may keep a
484 // pointer into it), but the space wasted is insignificant.
485 // (In bug #142197, the copies were being freed, which caused
486 // problems for tools that reasonably assumed that arguments
487 // wouldn't disappear on them.)
489 VG_(printf
)("tool-specific arg: %s\n", arg
);
490 arg
= VG_(strdup
)("main.mpclo.1", arg
+ toolname_len
+ 1);
495 // prefix doesn't match, skip to next arg
500 /* Ignore these options - they've already been handled */
501 if VG_STREQN( 7, arg
, "--tool=") {}
502 else if VG_STREQN(20, arg
, "--command-line-only=") {}
503 else if VG_STREQ( arg
, "--") {}
504 else if VG_STREQ( arg
, "-d") {}
505 else if VG_STREQN(17, arg
, "--max-stackframe=") {}
506 else if VG_STREQN(17, arg
, "--main-stacksize=") {}
507 else if VG_STREQN(12, arg
, "--sim-hints=") {}
508 else if VG_STREQN(15, arg
, "--profile-heap=") {}
509 else if VG_STREQN(20, arg
, "--core-redzone-size=") {}
510 else if VG_STREQN(15, arg
, "--redzone-size=") {}
511 else if VG_STREQN(17, arg
, "--aspace-minaddr=") {}
513 /* Obsolete options. Report an error and exit */
514 else if VG_STREQN(34, arg
, "--vex-iropt-precise-memory-exns=no") {
517 "--vex-iropt-precise-memory-exns is obsolete\n"
518 "Use --vex-iropt-register-updates=unwindregs-at-mem-access instead\n");
520 else if VG_STREQN(35, arg
, "--vex-iropt-precise-memory-exns=yes") {
523 "--vex-iropt-precise-memory-exns is obsolete\n"
524 "Use --vex-iropt-register-updates=allregs-at-mem-access instead\n"
525 " (or --vex-iropt-register-updates=allregs-at-each-insn)\n");
528 // These options are new.
529 else if (VG_STREQ(arg
, "-v") ||
530 VG_STREQ(arg
, "--verbose"))
531 VG_(clo_verbosity
)++;
533 else if (VG_STREQ(arg
, "-q") ||
534 VG_STREQ(arg
, "--quiet"))
535 VG_(clo_verbosity
)--;
537 else if VG_BOOL_CLO(arg
, "--sigill-diagnostics", VG_(clo_sigill_diag
))
538 sigill_diag_set
= True
;
540 else if VG_BOOL_CLO(arg
, "--stats", VG_(clo_stats
)) {}
541 else if VG_BOOL_CLO(arg
, "--xml", VG_(clo_xml
))
542 VG_(debugLog_setXml
)(VG_(clo_xml
));
544 else if VG_XACT_CLO(arg
, "--vgdb=no", VG_(clo_vgdb
), Vg_VgdbNo
) {}
545 else if VG_XACT_CLO(arg
, "--vgdb=yes", VG_(clo_vgdb
), Vg_VgdbYes
) {}
546 else if VG_XACT_CLO(arg
, "--vgdb=full", VG_(clo_vgdb
), Vg_VgdbFull
) {
547 /* automatically updates register values at each insn
549 VG_(clo_vex_control
).iropt_register_updates
550 = VexRegUpdAllregsAtEachInsn
;
552 else if VG_INT_CLO (arg
, "--vgdb-poll", VG_(clo_vgdb_poll
)) {}
553 else if VG_INT_CLO (arg
, "--vgdb-error", VG_(clo_vgdb_error
)) {}
554 else if VG_USET_CLO (arg
, "--vgdb-stop-at",
555 "startup,exit,valgrindabexit",
556 VG_(clo_vgdb_stop_at
)) {}
557 else if VG_STR_CLO (arg
, "--vgdb-prefix", VG_(clo_vgdb_prefix
)) {
558 VG_(arg_vgdb_prefix
) = arg
;
560 else if VG_BOOL_CLO(arg
, "--vgdb-shadow-registers",
561 VG_(clo_vgdb_shadow_registers
)) {}
562 else if VG_BOOL_CLO(arg
, "--db-attach", VG_(clo_db_attach
)) {}
563 else if VG_BOOL_CLO(arg
, "--demangle", VG_(clo_demangle
)) {}
564 else if VG_STR_CLO (arg
, "--soname-synonyms",VG_(clo_soname_synonyms
)) {}
565 else if VG_BOOL_CLO(arg
, "--error-limit", VG_(clo_error_limit
)) {}
566 else if VG_INT_CLO (arg
, "--error-exitcode", VG_(clo_error_exitcode
)) {}
567 else if VG_BOOL_CLO(arg
, "--show-emwarns", VG_(clo_show_emwarns
)) {}
569 else if VG_BOOL_CLO(arg
, "--run-libc-freeres", VG_(clo_run_libc_freeres
)) {}
570 else if VG_BOOL_CLO(arg
, "--show-below-main", VG_(clo_show_below_main
)) {}
571 else if VG_BOOL_CLO(arg
, "--time-stamp", VG_(clo_time_stamp
)) {}
572 else if VG_BOOL_CLO(arg
, "--track-fds", VG_(clo_track_fds
)) {}
573 else if VG_BOOL_CLO(arg
, "--trace-children", VG_(clo_trace_children
)) {}
574 else if VG_BOOL_CLO(arg
, "--child-silent-after-fork",
575 VG_(clo_child_silent_after_fork
)) {}
576 else if VG_STR_CLO(arg
, "--fair-sched", tmp_str
) {
577 if (VG_(strcmp
)(tmp_str
, "yes") == 0)
578 VG_(clo_fair_sched
) = enable_fair_sched
;
579 else if (VG_(strcmp
)(tmp_str
, "try") == 0)
580 VG_(clo_fair_sched
) = try_fair_sched
;
581 else if (VG_(strcmp
)(tmp_str
, "no") == 0)
582 VG_(clo_fair_sched
) = disable_fair_sched
;
584 VG_(fmsg_bad_option
)(arg
, "");
587 else if VG_BOOL_CLO(arg
, "--trace-sched", VG_(clo_trace_sched
)) {}
588 else if VG_BOOL_CLO(arg
, "--trace-signals", VG_(clo_trace_signals
)) {}
589 else if VG_BOOL_CLO(arg
, "--trace-symtab", VG_(clo_trace_symtab
)) {}
590 else if VG_STR_CLO (arg
, "--trace-symtab-patt", VG_(clo_trace_symtab_patt
)) {}
591 else if VG_BOOL_CLO(arg
, "--trace-cfi", VG_(clo_trace_cfi
)) {}
592 else if VG_XACT_CLO(arg
, "--debug-dump=syms", VG_(clo_debug_dump_syms
),
594 else if VG_XACT_CLO(arg
, "--debug-dump=line", VG_(clo_debug_dump_line
),
596 else if VG_XACT_CLO(arg
, "--debug-dump=frames",
597 VG_(clo_debug_dump_frames
), True
) {}
598 else if VG_BOOL_CLO(arg
, "--trace-redir", VG_(clo_trace_redir
)) {}
600 else if VG_BOOL_CLO(arg
, "--trace-syscalls", VG_(clo_trace_syscalls
)) {}
601 else if VG_BOOL_CLO(arg
, "--wait-for-gdb", VG_(clo_wait_for_gdb
)) {}
602 else if VG_STR_CLO (arg
, "--db-command", VG_(clo_db_command
)) {}
603 else if VG_BOOL_CLO(arg
, "--sym-offsets", VG_(clo_sym_offsets
)) {}
604 else if VG_BOOL_CLO(arg
, "--read-inline-info", VG_(clo_read_inline_info
)) {}
605 else if VG_BOOL_CLO(arg
, "--read-var-info", VG_(clo_read_var_info
)) {}
607 else if VG_INT_CLO (arg
, "--dump-error", VG_(clo_dump_error
)) {}
608 else if VG_INT_CLO (arg
, "--input-fd", VG_(clo_input_fd
)) {}
609 else if VG_INT_CLO (arg
, "--sanity-level", VG_(clo_sanity_level
)) {}
610 else if VG_BINT_CLO(arg
, "--num-callers", VG_(clo_backtrace_size
), 1,
611 VG_DEEPEST_BACKTRACE
) {}
612 else if VG_BINT_CLO(arg
, "--num-transtab-sectors",
613 VG_(clo_num_transtab_sectors
),
614 MIN_N_SECTORS
, MAX_N_SECTORS
) {}
615 else if VG_BINT_CLO(arg
, "--merge-recursive-frames",
616 VG_(clo_merge_recursive_frames
), 0,
617 VG_DEEPEST_BACKTRACE
) {}
619 else if VG_XACT_CLO(arg
, "--smc-check=none", VG_(clo_smc_check
),
621 else if VG_XACT_CLO(arg
, "--smc-check=stack", VG_(clo_smc_check
),
623 else if VG_XACT_CLO(arg
, "--smc-check=all", VG_(clo_smc_check
),
625 else if VG_XACT_CLO(arg
, "--smc-check=all-non-file",
629 else if VG_USETX_CLO (arg
, "--kernel-variant", "bproc",
630 VG_(clo_kernel_variant
)) {}
632 else if VG_BOOL_CLO(arg
, "--dsymutil", VG_(clo_dsymutil
)) {}
634 else if VG_STR_CLO (arg
, "--trace-children-skip",
635 VG_(clo_trace_children_skip
)) {}
636 else if VG_STR_CLO (arg
, "--trace-children-skip-by-arg",
637 VG_(clo_trace_children_skip_by_arg
)) {}
639 else if VG_BINT_CLO(arg
, "--vex-iropt-verbosity",
640 VG_(clo_vex_control
).iropt_verbosity
, 0, 10) {}
641 else if VG_BINT_CLO(arg
, "--vex-iropt-level",
642 VG_(clo_vex_control
).iropt_level
, 0, 2) {}
643 else if VG_XACT_CLO(arg
,
644 "--vex-iropt-register-updates=sp-at-mem-access",
645 VG_(clo_vex_control
).iropt_register_updates
,
646 VexRegUpdSpAtMemAccess
);
647 else if VG_XACT_CLO(arg
,
648 "--vex-iropt-register-updates=unwindregs-at-mem-access",
649 VG_(clo_vex_control
).iropt_register_updates
,
650 VexRegUpdUnwindregsAtMemAccess
);
651 else if VG_XACT_CLO(arg
,
652 "--vex-iropt-register-updates=allregs-at-mem-access",
653 VG_(clo_vex_control
).iropt_register_updates
,
654 VexRegUpdAllregsAtMemAccess
);
655 else if VG_XACT_CLO(arg
,
656 "--vex-iropt-register-updates=allregs-at-each-insn",
657 VG_(clo_vex_control
).iropt_register_updates
,
658 VexRegUpdAllregsAtEachInsn
);
659 else if VG_BINT_CLO(arg
, "--vex-iropt-unroll-thresh",
660 VG_(clo_vex_control
).iropt_unroll_thresh
, 0, 400) {}
661 else if VG_BINT_CLO(arg
, "--vex-guest-max-insns",
662 VG_(clo_vex_control
).guest_max_insns
, 1, 100) {}
663 else if VG_BINT_CLO(arg
, "--vex-guest-chase-thresh",
664 VG_(clo_vex_control
).guest_chase_thresh
, 0, 99) {}
665 else if VG_BOOL_CLO(arg
, "--vex-guest-chase-cond",
666 VG_(clo_vex_control
).guest_chase_cond
) {}
668 else if VG_INT_CLO(arg
, "--log-fd", tmp_log_fd
) {
670 log_fsname_unexpanded
= NULL
;
672 else if VG_INT_CLO(arg
, "--xml-fd", tmp_xml_fd
) {
674 xml_fsname_unexpanded
= NULL
;
677 else if VG_STR_CLO(arg
, "--log-file", log_fsname_unexpanded
) {
678 log_to
= VgLogTo_File
;
680 else if VG_STR_CLO(arg
, "--xml-file", xml_fsname_unexpanded
) {
681 xml_to
= VgLogTo_File
;
684 else if VG_STR_CLO(arg
, "--log-socket", log_fsname_unexpanded
) {
685 log_to
= VgLogTo_Socket
;
687 else if VG_STR_CLO(arg
, "--xml-socket", xml_fsname_unexpanded
) {
688 xml_to
= VgLogTo_Socket
;
691 else if VG_STR_CLO(arg
, "--debuginfo-server",
692 VG_(clo_debuginfo_server
)) {}
694 else if VG_BOOL_CLO(arg
, "--allow-mismatched-debuginfo",
695 VG_(clo_allow_mismatched_debuginfo
)) {}
697 else if VG_STR_CLO(arg
, "--xml-user-comment",
698 VG_(clo_xml_user_comment
)) {}
700 else if VG_BOOL_CLO(arg
, "--default-suppressions",
701 VG_(clo_default_supp
)) { }
703 else if VG_STR_CLO(arg
, "--suppressions", tmp_str
) {
704 if (VG_(clo_n_suppressions
) >= VG_CLO_MAX_SFILES
) {
705 VG_(fmsg_bad_option
)(arg
,
706 "Too many suppression files specified.\n"
707 "Increase VG_CLO_MAX_SFILES and recompile.\n");
709 VG_(clo_suppressions
)[VG_(clo_n_suppressions
)] = tmp_str
;
710 VG_(clo_n_suppressions
)++;
713 else if VG_STR_CLO (arg
, "--fullpath-after", tmp_str
) {
714 if (VG_(clo_n_fullpath_after
) >= VG_CLO_MAX_FULLPATH_AFTER
) {
715 VG_(fmsg_bad_option
)(arg
,
716 "Too many --fullpath-after= specifications.\n"
717 "Increase VG_CLO_MAX_FULLPATH_AFTER and recompile.\n");
719 VG_(clo_fullpath_after
)[VG_(clo_n_fullpath_after
)] = tmp_str
;
720 VG_(clo_n_fullpath_after
)++;
723 else if VG_STR_CLO (arg
, "--extra-debuginfo-path",
724 VG_(clo_extra_debuginfo_path
)) {}
726 else if VG_STR_CLO(arg
, "--require-text-symbol", tmp_str
) {
727 if (VG_(clo_n_req_tsyms
) >= VG_CLO_MAX_REQ_TSYMS
) {
728 VG_(fmsg_bad_option
)(arg
,
729 "Too many --require-text-symbol= specifications.\n"
730 "Increase VG_CLO_MAX_REQ_TSYMS and recompile.\n");
732 /* String needs to be of the form C?*C?*, where C is any
733 character, but is the same both times. Having it in this
734 form facilitates finding the boundary between the sopatt
735 and the fnpatt just by looking for the second occurrence
736 of C, without hardwiring any assumption about what C
740 ok
= tmp_str
&& VG_(strlen
)(tmp_str
) > 0;
742 patt
[0] = patt
[3] = tmp_str
[0];
743 patt
[1] = patt
[4] = '?';
744 patt
[2] = patt
[5] = '*';
746 ok
= VG_(string_match
)(patt
, tmp_str
);
749 VG_(fmsg_bad_option
)(arg
,
750 "Invalid --require-text-symbol= specification.\n");
752 VG_(clo_req_tsyms
)[VG_(clo_n_req_tsyms
)] = tmp_str
;
753 VG_(clo_n_req_tsyms
)++;
756 /* "stuvwxyz" --> stuvwxyz (binary) */
757 else if VG_STR_CLO(arg
, "--trace-flags", tmp_str
) {
759 if (8 != VG_(strlen
)(tmp_str
)) {
760 VG_(fmsg_bad_option
)(arg
,
761 "--trace-flags argument must have 8 digits\n");
763 for (j
= 0; j
< 8; j
++) {
764 if ('0' == tmp_str
[j
]) { /* do nothing */ }
765 else if ('1' == tmp_str
[j
]) VG_(clo_trace_flags
) |= (1 << (7-j
));
767 VG_(fmsg_bad_option
)(arg
,
768 "--trace-flags argument can only contain 0s and 1s\n");
773 else if VG_INT_CLO (arg
, "--trace-notbelow", VG_(clo_trace_notbelow
)) {}
775 else if VG_INT_CLO (arg
, "--trace-notabove", VG_(clo_trace_notabove
)) {}
777 /* "stuvwxyz" --> stuvwxyz (binary) */
778 else if VG_STR_CLO(arg
, "--profile-flags", tmp_str
) {
780 if (8 != VG_(strlen
)(tmp_str
)) {
781 VG_(fmsg_bad_option
)(arg
,
782 "--profile-flags argument must have 8 digits\n");
784 for (j
= 0; j
< 8; j
++) {
785 if ('0' == tmp_str
[j
]) { /* do nothing */ }
786 else if ('1' == tmp_str
[j
]) VG_(clo_profyle_flags
) |= (1 << (7-j
));
788 VG_(fmsg_bad_option
)(arg
,
789 "--profile-flags argument can only contain 0s and 1s\n");
792 VG_(clo_profyle_sbs
) = True
;
795 else if VG_INT_CLO (arg
, "--profile-interval",
796 VG_(clo_profyle_interval
)) {}
798 else if VG_XACT_CLO(arg
, "--gen-suppressions=no",
799 VG_(clo_gen_suppressions
), 0) {}
800 else if VG_XACT_CLO(arg
, "--gen-suppressions=yes",
801 VG_(clo_gen_suppressions
), 1) {}
802 else if VG_XACT_CLO(arg
, "--gen-suppressions=all",
803 VG_(clo_gen_suppressions
), 2) {}
805 else if VG_BINT_CLO(arg
, "--unw-stack-scan-thresh",
806 VG_(clo_unw_stack_scan_thresh
), 0, 100) {}
807 else if VG_BINT_CLO(arg
, "--unw-stack-scan-frames",
808 VG_(clo_unw_stack_scan_frames
), 0, 32) {}
810 else if ( ! VG_(needs
).command_line_options
811 || ! VG_TDICT_CALL(tool_process_cmd_line_option
, arg
) ) {
812 VG_(fmsg_bad_option
)(arg
, "");
816 /* END command-line processing loop */
818 /* Determine the path prefix for vgdb */
819 if (VG_(clo_vgdb_prefix
) == NULL
)
820 VG_(clo_vgdb_prefix
) = VG_(vgdb_prefix_default
)();
822 /* Make VEX control parameters sane */
824 if (VG_(clo_vex_control
).guest_chase_thresh
825 >= VG_(clo_vex_control
).guest_max_insns
)
826 VG_(clo_vex_control
).guest_chase_thresh
827 = VG_(clo_vex_control
).guest_max_insns
- 1;
829 if (VG_(clo_vex_control
).guest_chase_thresh
< 0)
830 VG_(clo_vex_control
).guest_chase_thresh
= 0;
832 /* Check various option values */
834 if (VG_(clo_verbosity
) < 0)
835 VG_(clo_verbosity
) = 0;
837 if (!sigill_diag_set
)
838 VG_(clo_sigill_diag
) = (VG_(clo_verbosity
) > 0);
840 if (VG_(clo_trace_notbelow
) == -1) {
841 if (VG_(clo_trace_notabove
) == -1) {
843 VG_(clo_trace_notbelow
) = 2147483647;
844 VG_(clo_trace_notabove
) = 0;
846 /* [0 .. notabove] */
847 VG_(clo_trace_notbelow
) = 0;
850 if (VG_(clo_trace_notabove
) == -1) {
852 VG_(clo_trace_notabove
) = 2147483647;
854 /* [notbelow .. notabove] */
858 VG_(dyn_vgdb_error
) = VG_(clo_vgdb_error
);
860 if (VG_(clo_gen_suppressions
) > 0 &&
861 !VG_(needs
).core_errors
&& !VG_(needs
).tool_errors
) {
862 VG_(fmsg_bad_option
)("--gen-suppressions=yes",
863 "Can't use --gen-suppressions= with %s\n"
864 "because it doesn't generate errors.\n", VG_(details
).name
);
867 /* If XML output is requested, check that the tool actually
869 if (VG_(clo_xml
) && !VG_(needs
).xml_output
) {
870 VG_(clo_xml
) = False
;
871 VG_(fmsg_bad_option
)("--xml=yes",
872 "%s does not support XML output.\n", VG_(details
).name
);
876 vg_assert( VG_(clo_gen_suppressions
) >= 0 );
877 vg_assert( VG_(clo_gen_suppressions
) <= 2 );
879 /* If we've been asked to emit XML, mash around various other
880 options so as to constrain the output somewhat, and to remove
881 any need for user input during the run.
885 /* We can't allow --gen-suppressions=yes, since that requires us
886 to print the error and then ask the user if she wants a
887 suppression for it, but in XML mode we won't print it until
888 we know whether we also need to print a suppression. Hence a
889 circular dependency. So disallow this.
890 (--gen-suppressions=all is still OK since we don't need any
891 user interaction in this case.) */
892 if (VG_(clo_gen_suppressions
) == 1) {
893 VG_(fmsg_bad_option
)(
894 "--xml=yes together with --gen-suppressions=yes",
895 "When --xml=yes is specified, --gen-suppressions=no\n"
896 "or --gen-suppressions=all is allowed, but not "
897 "--gen-suppressions=yes.\n");
900 /* We can't allow DB attaching (or we maybe could, but results
901 could be chaotic ..) since it requires user input. Hence
903 if (VG_(clo_db_attach
)) {
904 VG_(fmsg_bad_option
)(
905 "--xml=yes together with --db-attach=yes",
906 "--db-attach=yes is not allowed with --xml=yes\n"
907 "because it would require user input.\n");
910 /* Disallow dump_error in XML mode; sounds like a recipe for
911 chaos. No big deal; dump_error is a flag for debugging V
913 if (VG_(clo_dump_error
) > 0) {
914 VG_(fmsg_bad_option
)("--xml=yes together with --dump-error", "");
917 /* Disable error limits (this might be a bad idea!) */
918 VG_(clo_error_limit
) = False
;
919 /* Disable emulation warnings */
921 /* Also, we want to set options for the leak checker, but that
922 will have to be done in Memcheck's flag-handling code, not
926 /* All non-logging-related options have been checked. If the logging
927 option specified is ok, we can switch to it, as we know we won't
928 have to generate any other command-line-related error messages.
929 (So far we should be still attached to stderr, so we can show on
930 the terminal any problems to do with processing command line
933 So set up logging now. After this is done, VG_(log_output_sink)
934 and (if relevant) VG_(xml_output_sink) should be connected to
935 whatever sink has been selected, and we indiscriminately chuck
936 stuff into it without worrying what the nature of it is. Oh the
937 wonder of Unix streams. */
939 vg_assert(VG_(log_output_sink
).fd
== 2 /* stderr */);
940 vg_assert(VG_(log_output_sink
).is_socket
== False
);
941 vg_assert(VG_(clo_log_fname_expanded
) == NULL
);
943 vg_assert(VG_(xml_output_sink
).fd
== -1 /* disabled */);
944 vg_assert(VG_(xml_output_sink
).is_socket
== False
);
945 vg_assert(VG_(clo_xml_fname_expanded
) == NULL
);
947 /* --- set up the normal text output channel --- */
952 vg_assert(log_fsname_unexpanded
== NULL
);
958 vg_assert(log_fsname_unexpanded
!= NULL
);
959 vg_assert(VG_(strlen
)(log_fsname_unexpanded
) <= 900); /* paranoia */
961 // Nb: we overwrite an existing file of this name without asking
963 logfilename
= VG_(expand_file_name
)("--log-file",
964 log_fsname_unexpanded
);
965 sres
= VG_(open
)(logfilename
,
966 VKI_O_CREAT
|VKI_O_WRONLY
|VKI_O_TRUNC
,
967 VKI_S_IRUSR
|VKI_S_IWUSR
);
968 if (!sr_isError(sres
)) {
969 tmp_log_fd
= sr_Res(sres
);
970 VG_(clo_log_fname_expanded
) = logfilename
;
972 VG_(fmsg
)("can't create log file '%s': %s\n",
973 logfilename
, VG_(strerror
)(sr_Err(sres
)));
980 case VgLogTo_Socket
: {
981 vg_assert(log_fsname_unexpanded
!= NULL
);
982 vg_assert(VG_(strlen
)(log_fsname_unexpanded
) <= 900); /* paranoia */
983 tmp_log_fd
= VG_(connect_via_socket
)( log_fsname_unexpanded
);
984 if (tmp_log_fd
== -1) {
985 VG_(fmsg
)("Invalid --log-socket spec of '%s'\n",
986 log_fsname_unexpanded
);
990 if (tmp_log_fd
== -2) {
991 VG_(umsg
)("failed to connect to logging server '%s'.\n"
992 "Log messages will sent to stderr instead.\n",
993 log_fsname_unexpanded
);
995 /* We don't change anything here. */
996 vg_assert(VG_(log_output_sink
).fd
== 2);
999 vg_assert(tmp_log_fd
> 0);
1000 VG_(log_output_sink
).is_socket
= True
;
1006 /* --- set up the XML output channel --- */
1011 vg_assert(xml_fsname_unexpanded
== NULL
);
1014 case VgLogTo_File
: {
1017 vg_assert(xml_fsname_unexpanded
!= NULL
);
1018 vg_assert(VG_(strlen
)(xml_fsname_unexpanded
) <= 900); /* paranoia */
1020 // Nb: we overwrite an existing file of this name without asking
1022 xmlfilename
= VG_(expand_file_name
)("--xml-file",
1023 xml_fsname_unexpanded
);
1024 sres
= VG_(open
)(xmlfilename
,
1025 VKI_O_CREAT
|VKI_O_WRONLY
|VKI_O_TRUNC
,
1026 VKI_S_IRUSR
|VKI_S_IWUSR
);
1027 if (!sr_isError(sres
)) {
1028 tmp_xml_fd
= sr_Res(sres
);
1029 VG_(clo_xml_fname_expanded
) = xmlfilename
;
1030 /* strdup here is probably paranoid overkill, but ... */
1031 *xml_fname_unexpanded
= VG_(strdup
)( "main.mpclo.2",
1032 xml_fsname_unexpanded
);
1034 VG_(fmsg
)("can't create XML file '%s': %s\n",
1035 xmlfilename
, VG_(strerror
)(sr_Err(sres
)));
1042 case VgLogTo_Socket
: {
1043 vg_assert(xml_fsname_unexpanded
!= NULL
);
1044 vg_assert(VG_(strlen
)(xml_fsname_unexpanded
) <= 900); /* paranoia */
1045 tmp_xml_fd
= VG_(connect_via_socket
)( xml_fsname_unexpanded
);
1046 if (tmp_xml_fd
== -1) {
1047 VG_(fmsg
)("Invalid --xml-socket spec of '%s'\n",
1048 xml_fsname_unexpanded
);
1052 if (tmp_xml_fd
== -2) {
1053 VG_(umsg
)("failed to connect to XML logging server '%s'.\n"
1054 "XML output will sent to stderr instead.\n",
1055 xml_fsname_unexpanded
);
1056 /* We don't change anything here. */
1057 vg_assert(VG_(xml_output_sink
).fd
== 2);
1060 vg_assert(tmp_xml_fd
> 0);
1061 VG_(xml_output_sink
).is_socket
= True
;
1067 /* If we've got this far, and XML mode was requested, but no XML
1068 output channel appears to have been specified, just stop. We
1069 could continue, and XML output will simply vanish into nowhere,
1070 but that is likely to confuse the hell out of users, which is
1071 distinctly Ungood. */
1072 if (VG_(clo_xml
) && tmp_xml_fd
== -1) {
1073 VG_(fmsg_bad_option
)(
1074 "--xml=yes, but no XML destination specified",
1075 "--xml=yes has been specified, but there is no XML output\n"
1076 "destination. You must specify an XML output destination\n"
1077 "using --xml-fd, --xml-file or --xml-socket.\n"
1081 // Finalise the output fds: the log fd ..
1083 if (tmp_log_fd
>= 0) {
1084 // Move log_fd into the safe range, so it doesn't conflict with
1086 tmp_log_fd
= VG_(fcntl
)(tmp_log_fd
, VKI_F_DUPFD
, VG_(fd_hard_limit
));
1087 if (tmp_log_fd
< 0) {
1088 VG_(message
)(Vg_UserMsg
, "valgrind: failed to move logfile fd "
1089 "into safe range, using stderr\n");
1090 VG_(log_output_sink
).fd
= 2; // stderr
1091 VG_(log_output_sink
).is_socket
= False
;
1093 VG_(log_output_sink
).fd
= tmp_log_fd
;
1094 VG_(fcntl
)(VG_(log_output_sink
).fd
, VKI_F_SETFD
, VKI_FD_CLOEXEC
);
1097 // If they said --log-fd=-1, don't print anything. Plausible for use in
1098 // regression testing suites that use client requests to count errors.
1099 VG_(log_output_sink
).fd
= -1;
1100 VG_(log_output_sink
).is_socket
= False
;
1103 // Finalise the output fds: and the XML fd ..
1105 if (tmp_xml_fd
>= 0) {
1106 // Move xml_fd into the safe range, so it doesn't conflict with
1108 tmp_xml_fd
= VG_(fcntl
)(tmp_xml_fd
, VKI_F_DUPFD
, VG_(fd_hard_limit
));
1109 if (tmp_xml_fd
< 0) {
1110 VG_(message
)(Vg_UserMsg
, "valgrind: failed to move XML file fd "
1111 "into safe range, using stderr\n");
1112 VG_(xml_output_sink
).fd
= 2; // stderr
1113 VG_(xml_output_sink
).is_socket
= False
;
1115 VG_(xml_output_sink
).fd
= tmp_xml_fd
;
1116 VG_(fcntl
)(VG_(xml_output_sink
).fd
, VKI_F_SETFD
, VKI_FD_CLOEXEC
);
1119 // If they said --xml-fd=-1, don't print anything. Plausible for use in
1120 // regression testing suites that use client requests to count errors.
1121 VG_(xml_output_sink
).fd
= -1;
1122 VG_(xml_output_sink
).is_socket
= False
;
1125 // Suppressions related stuff
1127 if (VG_(clo_default_supp
) &&
1128 VG_(clo_n_suppressions
) < VG_CLO_MAX_SFILES
-1 &&
1129 (VG_(needs
).core_errors
|| VG_(needs
).tool_errors
)) {
1130 /* If we haven't reached the max number of suppressions, load
1132 static const HChar default_supp
[] = "default.supp";
1133 Int len
= VG_(strlen
)(VG_(libdir
)) + 1 + sizeof(default_supp
);
1134 HChar
*buf
= VG_(arena_malloc
)(VG_AR_CORE
, "main.mpclo.3", len
);
1135 VG_(sprintf
)(buf
, "%s/%s", VG_(libdir
), default_supp
);
1136 VG_(clo_suppressions
)[VG_(clo_n_suppressions
)] = buf
;
1137 VG_(clo_n_suppressions
)++;
1140 *logging_to_fd
= log_to
== VgLogTo_Fd
|| log_to
== VgLogTo_Socket
;
1143 // Write the name and value of log file qualifiers to the xml file.
1144 static void print_file_vars(HChar
* format
)
1149 if (format
[i
] == '%') {
1150 // We saw a '%'. What's next...
1152 if ('q' == format
[i
]) {
1154 if ('{' == format
[i
]) {
1155 // Get the env var name, print its contents.
1159 qualname
= &format
[i
];
1161 if ('}' == format
[i
]) {
1162 // Temporarily replace the '}' with NUL to extract var
1165 qual
= VG_(getenv
)(qualname
);
1172 "<logfilequalifier> <var>%pS</var> "
1173 "<value>%pS</value> </logfilequalifier>\n",
1187 /*====================================================================*/
1188 /*=== Printing the preamble ===*/
1189 /*====================================================================*/
1191 // Print the argument, escaping any chars that require it.
1192 static void umsg_arg(const HChar
* arg
)
1194 SizeT len
= VG_(strlen
)(arg
);
1195 const HChar
* special
= " \\<>";
1197 for (i
= 0; i
< len
; i
++) {
1198 if (VG_(strchr
)(special
, arg
[i
])) {
1199 VG_(umsg
)("\\"); // escape with a backslash if necessary
1201 VG_(umsg
)("%c", arg
[i
]);
1205 // Send output to the XML-stream and escape any XML meta-characters.
1206 static void xml_arg(const HChar
* arg
)
1208 VG_(printf_xml
)("%pS", arg
);
1211 /* Ok, the logging sink is running now. Print a suitable preamble.
1212 If logging to file or a socket, write details of parent PID and
1213 command line args, to help people trying to interpret the
1214 results of a run which encompasses multiple processes. */
1215 static void print_preamble ( Bool logging_to_fd
,
1216 HChar
* xml_fname_unexpanded
,
1217 const HChar
* toolname
)
1220 const HChar
* xpre
= VG_(clo_xml
) ? " <line>" : "";
1221 const HChar
* xpost
= VG_(clo_xml
) ? "</line>" : "";
1222 UInt (*umsg_or_xml
)( const HChar
*, ... )
1223 = VG_(clo_xml
) ? VG_(printf_xml
) : VG_(umsg
);
1225 void (*umsg_or_xml_arg
)( const HChar
* )
1226 = VG_(clo_xml
) ? xml_arg
: umsg_arg
;
1228 vg_assert( VG_(args_for_client
) );
1229 vg_assert( VG_(args_for_valgrind
) );
1230 vg_assert( toolname
);
1233 VG_(printf_xml
)("<?xml version=\"1.0\"?>\n");
1234 VG_(printf_xml
)("\n");
1235 VG_(printf_xml
)("<valgrindoutput>\n");
1236 VG_(printf_xml
)("\n");
1237 VG_(printf_xml
)("<protocolversion>4</protocolversion>\n");
1238 VG_(printf_xml
)("<protocoltool>%s</protocoltool>\n", toolname
);
1239 VG_(printf_xml
)("\n");
1242 if (VG_(clo_xml
) || VG_(clo_verbosity
> 0)) {
1245 VG_(printf_xml
)("<preamble>\n");
1248 umsg_or_xml( VG_(clo_xml
) ? "%s%pS%pS%pS, %pS%s\n" : "%s%s%s%s, %s%s\n",
1251 NULL
== VG_(details
).version
? "" : "-",
1252 NULL
== VG_(details
).version
1253 ? "" : VG_(details
).version
,
1254 VG_(details
).description
,
1257 if (VG_(strlen
)(toolname
) >= 4 && VG_STREQN(4, toolname
, "exp-")) {
1259 "%sNOTE: This is an Experimental-Class Valgrind Tool%s\n",
1264 umsg_or_xml( VG_(clo_xml
) ? "%s%pS%s\n" : "%s%s%s\n",
1265 xpre
, VG_(details
).copyright_author
, xpost
);
1269 "%sUsing Valgrind-%s and LibVEX; rerun with -h for copyright info%s\n",
1270 xpre
, VERSION
, xpost
1273 // Print the command line. At one point we wrapped at 80 chars and
1274 // printed a '\' as a line joiner, but that makes it hard to cut and
1275 // paste the command line (because of the "==pid==" prefixes), so we now
1276 // favour utility and simplicity over aesthetics.
1277 umsg_or_xml("%sCommand: ", xpre
);
1278 umsg_or_xml_arg(VG_(args_the_exename
));
1280 for (i
= 0; i
< VG_(sizeXA
)( VG_(args_for_client
) ); i
++) {
1281 HChar
* s
= *(HChar
**)VG_(indexXA
)( VG_(args_for_client
), i
);
1285 umsg_or_xml("%s\n", xpost
);
1288 VG_(printf_xml
)("</preamble>\n");
1291 // Print the parent PID, and other stuff, if necessary.
1292 if (!VG_(clo_xml
) && VG_(clo_verbosity
) > 0 && !logging_to_fd
) {
1293 VG_(umsg
)("Parent PID: %d\n", VG_(getppid
)());
1297 VG_(printf_xml
)("\n");
1298 VG_(printf_xml
)("<pid>%d</pid>\n", VG_(getpid
)());
1299 VG_(printf_xml
)("<ppid>%d</ppid>\n", VG_(getppid
)());
1300 VG_(printf_xml
)("<tool>%pS</tool>\n", toolname
);
1301 if (xml_fname_unexpanded
)
1302 print_file_vars(xml_fname_unexpanded
);
1303 if (VG_(clo_xml_user_comment
)) {
1304 /* Note: the user comment itself is XML and is therefore to
1305 be passed through verbatim (%s) rather than escaped
1307 VG_(printf_xml
)("<usercomment>%s</usercomment>\n",
1308 VG_(clo_xml_user_comment
));
1310 VG_(printf_xml
)("\n");
1311 VG_(printf_xml
)("<args>\n");
1313 VG_(printf_xml
)(" <vargv>\n");
1314 if (VG_(name_of_launcher
))
1315 VG_(printf_xml
)(" <exe>%pS</exe>\n",
1316 VG_(name_of_launcher
));
1318 VG_(printf_xml
)(" <exe>%pS</exe>\n",
1319 "(launcher name unknown)");
1320 for (i
= 0; i
< VG_(sizeXA
)( VG_(args_for_valgrind
) ); i
++) {
1322 " <arg>%pS</arg>\n",
1323 * (HChar
**) VG_(indexXA
)( VG_(args_for_valgrind
), i
)
1326 VG_(printf_xml
)(" </vargv>\n");
1328 VG_(printf_xml
)(" <argv>\n");
1329 VG_(printf_xml
)(" <exe>%pS</exe>\n",
1330 VG_(args_the_exename
));
1331 for (i
= 0; i
< VG_(sizeXA
)( VG_(args_for_client
) ); i
++) {
1333 " <arg>%pS</arg>\n",
1334 * (HChar
**) VG_(indexXA
)( VG_(args_for_client
), i
)
1337 VG_(printf_xml
)(" </argv>\n");
1339 VG_(printf_xml
)("</args>\n");
1342 // Last thing in the preamble is a blank line.
1344 VG_(printf_xml
)("\n");
1345 else if (VG_(clo_verbosity
) > 0)
1348 if (VG_(clo_verbosity
) > 1) {
1351 VexArchInfo vex_archinfo
;
1353 VG_(message
)(Vg_DebugMsg
, "\n");
1354 VG_(message
)(Vg_DebugMsg
, "Valgrind options:\n");
1355 for (i
= 0; i
< VG_(sizeXA
)( VG_(args_for_valgrind
) ); i
++) {
1356 VG_(message
)(Vg_DebugMsg
,
1358 * (HChar
**) VG_(indexXA
)( VG_(args_for_valgrind
), i
));
1361 VG_(message
)(Vg_DebugMsg
, "Contents of /proc/version:\n");
1362 fd
= VG_(open
) ( "/proc/version", VKI_O_RDONLY
, 0 );
1363 if (sr_isError(fd
)) {
1364 VG_(message
)(Vg_DebugMsg
, " can't open /proc/version\n");
1366 # define BUF_LEN 256
1367 HChar version_buf
[BUF_LEN
];
1368 Int n
= VG_(read
) ( sr_Res(fd
), version_buf
, BUF_LEN
);
1369 vg_assert(n
<= BUF_LEN
);
1371 version_buf
[n
-1] = '\0';
1372 VG_(message
)(Vg_DebugMsg
, " %s\n", version_buf
);
1374 VG_(message
)(Vg_DebugMsg
, " (empty?)\n");
1376 VG_(close
)(sr_Res(fd
));
1380 VG_(machine_get_VexArchInfo
)( &vex_arch
, &vex_archinfo
);
1383 "Arch and hwcaps: %s, %s, %s\n",
1384 LibVEX_ppVexArch ( vex_arch
),
1385 LibVEX_ppVexEndness ( vex_archinfo
.endness
),
1386 LibVEX_ppVexHwCaps ( vex_arch
, vex_archinfo
.hwcaps
)
1390 "Page sizes: currently %d, max supported %d\n",
1391 (Int
)VKI_PAGE_SIZE
, (Int
)VKI_MAX_PAGE_SIZE
1393 VG_(message
)(Vg_DebugMsg
,
1394 "Valgrind library directory: %s\n", VG_(libdir
));
1399 /*====================================================================*/
1400 /*=== File descriptor setup ===*/
1401 /*====================================================================*/
1403 /* Number of file descriptors that Valgrind tries to reserve for
1404 it's own use - just a small constant. */
1405 #define N_RESERVED_FDS (10)
1407 static void setup_file_descriptors(void)
1409 struct vki_rlimit rl
;
1412 /* Get the current file descriptor limits. */
1413 if (VG_(getrlimit
)(VKI_RLIMIT_NOFILE
, &rl
) < 0) {
1418 # if defined(VGO_darwin)
1419 /* Darwin lies. It reports file max as RLIM_INFINITY but
1420 silently disallows anything bigger than 10240. */
1421 if (rl
.rlim_cur
>= 10240 && rl
.rlim_max
== 0x7fffffffffffffffULL
) {
1422 rl
.rlim_max
= 10240;
1427 VG_(printf
)("fd limits: host, before: cur %lu max %lu\n",
1428 (UWord
)rl
.rlim_cur
, (UWord
)rl
.rlim_max
);
1430 /* Work out where to move the soft limit to. */
1431 if (rl
.rlim_cur
+ N_RESERVED_FDS
<= rl
.rlim_max
) {
1432 rl
.rlim_cur
= rl
.rlim_cur
+ N_RESERVED_FDS
;
1434 rl
.rlim_cur
= rl
.rlim_max
;
1437 /* Reserve some file descriptors for our use. */
1438 VG_(fd_soft_limit
) = rl
.rlim_cur
- N_RESERVED_FDS
;
1439 VG_(fd_hard_limit
) = rl
.rlim_cur
- N_RESERVED_FDS
;
1441 /* Update the soft limit. */
1442 VG_(setrlimit
)(VKI_RLIMIT_NOFILE
, &rl
);
1445 VG_(printf
)("fd limits: host, after: cur %lu max %lu\n",
1446 (UWord
)rl
.rlim_cur
, (UWord
)rl
.rlim_max
);
1447 VG_(printf
)("fd limits: guest : cur %u max %u\n",
1448 VG_(fd_soft_limit
), VG_(fd_hard_limit
));
1451 if (VG_(cl_exec_fd
) != -1)
1452 VG_(cl_exec_fd
) = VG_(safe_fd
)( VG_(cl_exec_fd
) );
1456 /*====================================================================*/
1458 /*====================================================================*/
1460 /* When main() is entered, we should be on the following stack, not
1461 the one the kernel gave us. We will run on this stack until
1462 simulation of the root thread is started, at which point a transfer
1463 is made to a dynamically allocated stack. This is for the sake of
1464 uniform overflow detection for all Valgrind threads. This is
1465 marked global even though it isn't, because assembly code below
1466 needs to reference the name. */
1468 /*static*/ VgStack
VG_(interim_stack
);
1470 /* These are the structures used to hold info for creating the initial
1473 'iicii' mostly holds important register state present at system
1474 startup (_start_valgrind). valgrind_main() then fills in the rest
1475 of it and passes it to VG_(ii_create_image)(). That produces
1476 'iifii', which is later handed to VG_(ii_finalise_image). */
1478 /* In all OS-instantiations, the_iicii has a field .sp_at_startup.
1479 This should get some address inside the stack on which we gained
1480 control (eg, it could be the SP at startup). It doesn't matter
1481 exactly where in the stack it is. This value is passed to the
1482 address space manager at startup. On Linux, aspacem then uses it
1483 to identify the initial stack segment and hence the upper end of
1484 the usable address space. */
1486 static IICreateImageInfo the_iicii
;
1487 static IIFinaliseImageInfo the_iifii
;
1490 /* A simple pair structure, used for conveying debuginfo handles to
1491 calls to VG_TRACK(new_mem_startup, ...). */
1492 typedef struct { Addr a
; ULong ull
; } Addr_n_ULong
;
1495 /* --- Forwards decls to do with shutdown --- */
1497 static void final_tidyup(ThreadId tid
);
1499 /* Do everything which needs doing when the last thread exits */
1501 void shutdown_actions_NORETURN( ThreadId tid
,
1502 VgSchedReturnCode tids_schedretcode
);
1504 /* --- end of Forwards decls to do with shutdown --- */
1507 /* By the time we get to valgrind_main, the_iicii should already have
1508 been filled in with any important details as required by whatever
1509 OS we have been built for.
1512 Int
valgrind_main ( Int argc
, HChar
**argv
, HChar
**envp
)
1514 const HChar
* toolname
= "memcheck"; // default to Memcheck
1515 Int need_help
= 0; // 0 = no, 1 = --help, 2 = --help-debug
1516 ThreadId tid_main
= VG_INVALID_THREADID
;
1517 Bool logging_to_fd
= False
;
1518 HChar
* xml_fname_unexpanded
= NULL
;
1520 struct vki_rlimit zero
= { 0, 0 };
1521 XArray
* addr2dihandle
= NULL
;
1523 //============================================================
1525 // Nb: startup is complex. Prerequisites are shown at every step.
1526 // *** Be very careful when messing with the order ***
1528 // The first order of business is to get debug logging, the address
1529 // space manager and the dynamic memory manager up and running.
1530 // Once that's done, we can relax a bit.
1532 //============================================================
1534 /* This is needed to make VG_(getenv) usable early. */
1535 VG_(client_envp
) = (HChar
**)envp
;
1537 //--------------------------------------------------------------
1538 // Start up Mach kernel interface, if any
1540 //--------------------------------------------------------------
1541 # if defined(VGO_darwin)
1545 //--------------------------------------------------------------
1546 // Start up the logging mechanism
1548 //--------------------------------------------------------------
1549 /* Start the debugging-log system ASAP. First find out how many
1550 "-d"s were specified. This is a pre-scan of the command line. Also
1551 get --profile-heap=yes, --core-redzone-size, --redzone-size
1552 --aspace-minaddr which are needed by the time we start up dynamic
1553 memory management. */
1555 for (i
= 1; i
< argc
; i
++) {
1556 const HChar
* tmp_str
;
1557 if (argv
[i
][0] != '-') break;
1558 if VG_STREQ(argv
[i
], "--") break;
1559 if VG_STREQ(argv
[i
], "-d") loglevel
++;
1560 if VG_BOOL_CLO(argv
[i
], "--profile-heap", VG_(clo_profile_heap
)) {}
1561 if VG_BINT_CLO(argv
[i
], "--core-redzone-size", VG_(clo_core_redzone_size
),
1562 0, MAX_CLO_REDZONE_SZB
) {}
1563 if VG_BINT_CLO(argv
[i
], "--redzone-size", VG_(clo_redzone_size
),
1564 0, MAX_CLO_REDZONE_SZB
) {}
1565 if VG_STR_CLO(argv
[i
], "--aspace-minaddr", tmp_str
) {
1566 # if VG_WORDSIZE == 4
1567 const Addr max
= (Addr
) 0x40000000; // 1Gb
1569 const Addr max
= (Addr
) 0x200000000; // 8Gb
1571 Bool ok
= VG_(parse_Addr
) (&tmp_str
, &VG_(clo_aspacem_minAddr
));
1573 VG_(fmsg_bad_option
)(argv
[i
], "Invalid address\n");
1575 if (!VG_IS_PAGE_ALIGNED(VG_(clo_aspacem_minAddr
))
1576 || VG_(clo_aspacem_minAddr
) < (Addr
) 0x1000
1577 || VG_(clo_aspacem_minAddr
) > max
) // 1Gb
1578 VG_(fmsg_bad_option
)(argv
[i
],
1579 "Must be a page aligned address between "
1580 "0x1000 and 0x%lx\n", max
);
1584 /* ... and start the debug logger. Now we can safely emit logging
1585 messages all through startup. */
1586 VG_(debugLog_startup
)(loglevel
, "Stage 2 (main)");
1587 VG_(debugLog
)(1, "main", "Welcome to Valgrind version "
1588 VERSION
" debug logging\n");
1590 //--------------------------------------------------------------
1591 // Ensure we're on a plausible stack.
1593 //--------------------------------------------------------------
1594 VG_(debugLog
)(1, "main", "Checking current stack is plausible\n");
1595 { HChar
* limLo
= (HChar
*)(&VG_(interim_stack
).bytes
[0]);
1596 HChar
* limHi
= limLo
+ sizeof(VG_(interim_stack
));
1598 aLocal
= (HChar
*)&limLo
; /* any auto local will do */
1599 /* Re "volatile": Apple clang version 4.0
1600 (tags/Apple/clang-421.0.57) (based on LLVM 3.1svn)" appeared
1601 to miscompile the following check, causing run to abort at
1602 this point (in 64-bit mode) even though aLocal is within limLo
1603 .. limHi. But in fact clang is within its rights to do
1604 strange things here. "The reason is that the comparisons
1605 aLocal < limLo and aLocal >= limHi cause undefined behaviour
1606 (according to c99 6.5.8) because they compare pointers that do
1607 not point into the same aggregate." Adding "volatile" appears
1608 to fix it because "The compiler would have to prove that there
1609 is undefined behavior in order to exploit it. But as a
1610 volatile variable can change its value in ways invisible to
1611 the compiler, the compiler must make the conservative
1612 assumption that it points into the same aggregate as the other
1613 pointer its compared against. I.e. the behaviour is possibly
1614 defined." (Analysis by Florian Krohm). */
1615 if (aLocal
< limLo
|| aLocal
>= limHi
) {
1616 /* something's wrong. Stop. */
1617 VG_(debugLog
)(0, "main", "Root stack %p to %p, a local %p\n",
1618 limLo
, limHi
, aLocal
);
1619 VG_(debugLog
)(0, "main", "Valgrind: FATAL: "
1620 "Initial stack switched failed.\n");
1621 VG_(debugLog
)(0, "main", " Cannot continue. Sorry.\n");
1626 //--------------------------------------------------------------
1627 // Ensure we have a plausible pointer to the stack on which
1628 // we gained control (not the current stack!)
1630 //--------------------------------------------------------------
1631 VG_(debugLog
)(1, "main", "Checking initial stack was noted\n");
1632 if (the_iicii
.sp_at_startup
== 0) {
1633 VG_(debugLog
)(0, "main", "Valgrind: FATAL: "
1634 "Initial stack was not noted.\n");
1635 VG_(debugLog
)(0, "main", " Cannot continue. Sorry.\n");
1639 //--------------------------------------------------------------
1640 // Start up the address space manager, and determine the
1641 // approximate location of the client's stack
1642 // p: logging, plausible-stack
1643 //--------------------------------------------------------------
1644 VG_(debugLog
)(1, "main", "Starting the address space manager\n");
1645 vg_assert(VKI_PAGE_SIZE
== 4096 || VKI_PAGE_SIZE
== 65536
1646 || VKI_PAGE_SIZE
== 16384);
1647 vg_assert(VKI_MAX_PAGE_SIZE
== 4096 || VKI_MAX_PAGE_SIZE
== 65536
1648 || VKI_MAX_PAGE_SIZE
== 16384);
1649 vg_assert(VKI_PAGE_SIZE
<= VKI_MAX_PAGE_SIZE
);
1650 vg_assert(VKI_PAGE_SIZE
== (1 << VKI_PAGE_SHIFT
));
1651 vg_assert(VKI_MAX_PAGE_SIZE
== (1 << VKI_MAX_PAGE_SHIFT
));
1652 the_iicii
.clstack_top
= VG_(am_startup
)( the_iicii
.sp_at_startup
);
1653 VG_(debugLog
)(1, "main", "Address space manager is running\n");
1655 //--------------------------------------------------------------
1656 // Start up the dynamic memory manager
1657 // p: address space management
1658 // p: getting --profile-heap,--core-redzone-size,--redzone-size
1659 // In fact m_mallocfree is self-initialising, so there's no
1660 // initialisation call to do. Instead, try a simple malloc/
1661 // free pair right now to check that nothing is broken.
1662 //--------------------------------------------------------------
1663 VG_(debugLog
)(1, "main", "Starting the dynamic memory manager\n");
1664 { void* p
= VG_(malloc
)( "main.vm.1", 12345 );
1665 if (p
) VG_(free
)( p
);
1667 VG_(debugLog
)(1, "main", "Dynamic memory manager is running\n");
1669 //============================================================
1671 // Dynamic memory management is now available.
1673 //============================================================
1675 //--------------------------------------------------------------
1676 // Initialise m_debuginfo
1677 // p: dynamic memory allocation
1678 VG_(debugLog
)(1, "main", "Initialise m_debuginfo\n");
1679 VG_(di_initialise
)();
1681 //--------------------------------------------------------------
1682 // Look for alternative libdir
1683 { HChar
*cp
= VG_(getenv
)(VALGRIND_LIB
);
1686 VG_(debugLog
)(1, "main", "VG_(libdir) = %s\n", VG_(libdir
));
1689 //--------------------------------------------------------------
1690 // Extract the launcher name from the environment.
1691 VG_(debugLog
)(1, "main", "Getting launcher's name ...\n");
1692 VG_(name_of_launcher
) = VG_(getenv
)(VALGRIND_LAUNCHER
);
1693 if (VG_(name_of_launcher
) == NULL
) {
1694 VG_(printf
)("valgrind: You cannot run '%s' directly.\n", argv
[0]);
1695 VG_(printf
)("valgrind: You should use $prefix/bin/valgrind.\n");
1698 VG_(debugLog
)(1, "main", "... %s\n", VG_(name_of_launcher
));
1700 //--------------------------------------------------------------
1701 // Get the current process datasize rlimit, and set it to zero.
1702 // This prevents any internal uses of brk() from having any effect.
1703 // We remember the old value so we can restore it on exec, so that
1704 // child processes will have a reasonable brk value.
1705 VG_(getrlimit
)(VKI_RLIMIT_DATA
, &VG_(client_rlimit_data
));
1706 zero
.rlim_max
= VG_(client_rlimit_data
).rlim_max
;
1707 VG_(setrlimit
)(VKI_RLIMIT_DATA
, &zero
);
1709 // Get the current process stack rlimit.
1710 VG_(getrlimit
)(VKI_RLIMIT_STACK
, &VG_(client_rlimit_stack
));
1712 //--------------------------------------------------------------
1713 // Figure out what sort of CPU we're on, and whether it is
1715 VG_(debugLog
)(1, "main", "Get hardware capabilities ...\n");
1717 VexArchInfo vex_archinfo
;
1718 Bool ok
= VG_(machine_get_hwcaps
)();
1721 VG_(printf
)("valgrind: fatal error: unsupported CPU.\n");
1722 VG_(printf
)(" Supported CPUs are:\n");
1723 VG_(printf
)(" * x86 (practically any; Pentium-I or above), "
1724 "AMD Athlon or above)\n");
1725 VG_(printf
)(" * AMD Athlon64/Opteron\n");
1726 VG_(printf
)(" * ARM (armv7)\n");
1727 VG_(printf
)(" * PowerPC (most; ppc405 and above)\n");
1728 VG_(printf
)(" * System z (64bit only - s390x; z900 and above)\n");
1732 VG_(machine_get_VexArchInfo
)( &vex_arch
, &vex_archinfo
);
1734 1, "main", "... arch = %s, hwcaps = %s\n",
1735 LibVEX_ppVexArch ( vex_arch
),
1736 LibVEX_ppVexHwCaps ( vex_arch
, vex_archinfo
.hwcaps
)
1740 //--------------------------------------------------------------
1741 // Record the working directory at startup
1743 VG_(debugLog
)(1, "main", "Getting the working directory at startup\n");
1744 { Bool ok
= VG_(record_startup_wd
)();
1746 VG_(err_config_error
)( "Can't establish current working "
1747 "directory at startup\n");
1749 { HChar buf
[VKI_PATH_MAX
+1];
1750 Bool ok
= VG_(get_startup_wd
)( buf
, sizeof(buf
) );
1752 buf
[VKI_PATH_MAX
] = 0;
1753 VG_(debugLog
)(1, "main", "... %s\n", buf
);
1756 //============================================================
1757 // Command line argument handling order:
1758 // * If --help/--help-debug are present, show usage message
1759 // (including the tool-specific usage)
1760 // * (If no --tool option given, default to Memcheck)
1761 // * Then, if client is missing, abort with error msg
1762 // * Then, if any cmdline args are bad, abort with error msg
1763 //============================================================
1765 //--------------------------------------------------------------
1766 // Split up argv into: C args, V args, V extra args, and exename.
1767 // p: dynamic memory allocation
1768 //--------------------------------------------------------------
1769 VG_(debugLog
)(1, "main", "Split up command line\n");
1770 VG_(split_up_argv
)( argc
, argv
);
1771 vg_assert( VG_(args_for_valgrind
) );
1772 vg_assert( VG_(args_for_client
) );
1774 for (i
= 0; i
< VG_(sizeXA
)( VG_(args_for_valgrind
) ); i
++)
1777 * (HChar
**) VG_(indexXA
)( VG_(args_for_valgrind
), i
)
1779 VG_(printf
)(" exe %s\n", VG_(args_the_exename
));
1780 for (i
= 0; i
< VG_(sizeXA
)( VG_(args_for_client
) ); i
++)
1783 * (HChar
**) VG_(indexXA
)( VG_(args_for_client
), i
)
1787 //--------------------------------------------------------------
1788 // Extract tool name and whether help has been requested.
1789 // Note we can't print the help message yet, even if requested,
1790 // because the tool has not been initialised.
1791 // p: split_up_argv [for VG_(args_for_valgrind)]
1792 //--------------------------------------------------------------
1793 VG_(debugLog
)(1, "main",
1794 "(early_) Process Valgrind's command line options\n");
1795 early_process_cmd_line_options(&need_help
, &toolname
);
1797 // Set default vex control params
1798 LibVEX_default_VexControl(& VG_(clo_vex_control
));
1800 //--------------------------------------------------------------
1801 // Load client executable, finding in $PATH if necessary
1802 // p: early_process_cmd_line_options() [for 'exec', 'need_help',
1803 // clo_max_stackframe,
1804 // clo_main_stacksize]
1805 // p: layout_remaining_space [so there's space]
1807 // Set up client's environment
1808 // p: set-libdir [for VG_(libdir)]
1809 // p: early_process_cmd_line_options [for toolname]
1811 // Setup client stack, eip, and VG_(client_arg[cv])
1812 // p: load_client() [for 'info']
1813 // p: fix_environment() [for 'env']
1815 // Setup client data (brk) segment. Initially a 1-page segment
1816 // which abuts a shrinkable reservation.
1817 // p: load_client() [for 'info' and hence VG_(brk_base)]
1819 // p: _start_in_C (for zeroing out the_iicii and putting some
1820 // initial values into it)
1821 //--------------------------------------------------------------
1823 VG_(debugLog
)(1, "main", "Create initial image\n");
1825 # if defined(VGO_linux) || defined(VGO_darwin)
1826 the_iicii
.argv
= argv
;
1827 the_iicii
.envp
= envp
;
1828 the_iicii
.toolname
= toolname
;
1830 # error "Unknown platform"
1833 /* NOTE: this call reads VG_(clo_main_stacksize). */
1834 the_iifii
= VG_(ii_create_image
)( the_iicii
);
1837 //==============================================================
1839 // Finished loading/setting up the client address space.
1841 //==============================================================
1843 //--------------------------------------------------------------
1844 // setup file descriptors
1846 //--------------------------------------------------------------
1847 VG_(debugLog
)(1, "main", "Setup file descriptors\n");
1848 setup_file_descriptors();
1850 //--------------------------------------------------------------
1851 // create fake /proc/<pid>/cmdline and /proc/<pid>/auxv files
1852 // and then unlink them, but hold onto the fds, so we can handr
1853 // them out to the client when it tries to open
1854 // /proc/<pid>/cmdline or /proc/<pid>/auxv for itself.
1855 // p: setup file descriptors
1856 // p: ii_create_image for VG_(client_auxv) setup.
1857 //--------------------------------------------------------------
1858 #if !defined(VGO_linux)
1859 // client shouldn't be using /proc!
1860 VG_(cl_cmdline_fd
) = -1;
1861 VG_(cl_auxv_fd
) = -1;
1864 HChar buf
[50], buf2
[VG_(mkstemp_fullname_bufsz
)(50-1)];
1867 const HChar
* exename
;
1869 VG_(debugLog
)(1, "main", "Create fake /proc/<pid>/cmdline\n");
1871 VG_(sprintf
)(buf
, "proc_%d_cmdline", VG_(getpid
)());
1872 fd
= VG_(mkstemp
)( buf
, buf2
);
1874 VG_(err_config_error
)("Can't create client cmdline file in %s\n", buf2
);
1877 exename
= VG_(args_the_exename
);
1878 VG_(write
)(fd
, exename
, VG_(strlen
)( exename
));
1879 VG_(write
)(fd
, nul
, 1);
1881 for (i
= 0; i
< VG_(sizeXA
)( VG_(args_for_client
) ); i
++) {
1882 HChar
* arg
= * (HChar
**) VG_(indexXA
)( VG_(args_for_client
), i
);
1883 VG_(write
)(fd
, arg
, VG_(strlen
)( arg
));
1884 VG_(write
)(fd
, nul
, 1);
1887 /* Don't bother to seek the file back to the start; instead do
1888 it every time a copy of it is given out (by PRE(sys_open)).
1889 That is probably more robust across fork() etc. */
1891 /* Now delete it, but hang on to the fd. */
1892 r
= VG_(unlink
)( buf2
);
1894 VG_(err_config_error
)("Can't delete client cmdline file in %s\n", buf2
);
1896 VG_(cl_cmdline_fd
) = fd
;
1898 VG_(debugLog
)(1, "main", "Create fake /proc/<pid>/auxv\n");
1900 VG_(sprintf
)(buf
, "proc_%d_auxv", VG_(getpid
)());
1901 fd
= VG_(mkstemp
)( buf
, buf2
);
1903 VG_(err_config_error
)("Can't create client auxv file in %s\n", buf2
);
1905 UWord
*client_auxv
= VG_(client_auxv
);
1906 unsigned int client_auxv_len
= 0;
1907 while (*client_auxv
!= 0) {
1910 client_auxv_len
+= 2 * sizeof(UWord
);
1912 client_auxv_len
+= 2 * sizeof(UWord
);
1914 VG_(write
)(fd
, VG_(client_auxv
), client_auxv_len
);
1916 /* Don't bother to seek the file back to the start; instead do
1917 it every time a copy of it is given out (by PRE(sys_open)).
1918 That is probably more robust across fork() etc. */
1920 /* Now delete it, but hang on to the fd. */
1921 r
= VG_(unlink
)( buf2
);
1923 VG_(err_config_error
)("Can't delete client auxv file in %s\n", buf2
);
1925 VG_(cl_auxv_fd
) = fd
;
1929 //--------------------------------------------------------------
1930 // Init tool part 1: pre_clo_init
1931 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1932 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1933 //--------------------------------------------------------------
1934 VG_(debugLog
)(1, "main", "Initialise the tool part 1 (pre_clo_init)\n");
1935 VG_(tl_pre_clo_init
)();
1936 // Activate var info readers, if the tool asked for it:
1937 if (VG_(needs
).var_info
)
1938 VG_(clo_read_var_info
) = True
;
1940 //--------------------------------------------------------------
1941 // If --tool and --help/--help-debug was given, now give the core+tool
1943 // p: early_process_cmd_line_options() [for 'need_help']
1944 // p: tl_pre_clo_init [for 'VG_(tdict).usage']
1945 //--------------------------------------------------------------
1946 VG_(debugLog
)(1, "main", "Print help and quit, if requested\n");
1948 usage_NORETURN(/*--help-debug?*/need_help
>= 2);
1951 //--------------------------------------------------------------
1952 // Process command line options to Valgrind + tool
1953 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1954 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1955 //--------------------------------------------------------------
1956 VG_(debugLog
)(1, "main",
1957 "(main_) Process Valgrind's command line options, "
1959 main_process_cmd_line_options ( &logging_to_fd
, &xml_fname_unexpanded
,
1962 //--------------------------------------------------------------
1963 // Zeroise the millisecond counter by doing a first read of it.
1965 //--------------------------------------------------------------
1966 (void) VG_(read_millisecond_timer
)();
1968 //--------------------------------------------------------------
1969 // Print the preamble
1970 // p: tl_pre_clo_init [for 'VG_(details).name' and friends]
1971 // p: main_process_cmd_line_options()
1972 // [for VG_(clo_verbosity), VG_(clo_xml),
1973 // logging_to_fd, xml_fname_unexpanded]
1974 //--------------------------------------------------------------
1975 VG_(debugLog
)(1, "main", "Print the preamble...\n");
1976 print_preamble(logging_to_fd
, xml_fname_unexpanded
, toolname
);
1977 VG_(debugLog
)(1, "main", "...finished the preamble\n");
1979 //--------------------------------------------------------------
1980 // Init tool part 2: post_clo_init
1981 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1982 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1983 // p: print_preamble() [so any warnings printed in post_clo_init
1984 // are shown after the preamble]
1985 //--------------------------------------------------------------
1986 VG_(debugLog
)(1, "main", "Initialise the tool part 2 (post_clo_init)\n");
1987 VG_TDICT_CALL(tool_post_clo_init
);
1989 /* The tool's "needs" will by now be finalised, since it has no
1990 further opportunity to specify them. So now sanity check
1994 ok
= VG_(sanity_check_needs
)( &s
);
2000 //--------------------------------------------------------------
2001 // Initialise translation table and translation cache
2003 // p: tl_pre_clo_init [for 'VG_(details).avg_translation_sizeB']
2004 //--------------------------------------------------------------
2005 VG_(debugLog
)(1, "main", "Initialise TT/TC\n");
2008 //--------------------------------------------------------------
2009 // Initialise the redirect table.
2010 // p: init_tt_tc [so it can call VG_(search_transtab) safely]
2011 // p: aspacem [so can change ownership of sysinfo pages]
2012 //--------------------------------------------------------------
2013 VG_(debugLog
)(1, "main", "Initialise redirects\n");
2014 VG_(redir_initialise
)();
2016 //--------------------------------------------------------------
2018 // p: main_process_cmd_line_options() [for VG_(clo_wait_for_gdb)]
2019 //--------------------------------------------------------------
2020 /* Hook to delay things long enough so we can get the pid and
2021 attach GDB in another shell. */
2022 if (VG_(clo_wait_for_gdb
)) {
2024 VG_(debugLog
)(1, "main", "Wait for GDB\n");
2025 VG_(printf
)("pid=%d, entering delay loop\n", VG_(getpid
)());
2027 # if defined(VGP_x86_linux)
2029 # elif defined(VGP_amd64_linux) || defined(VGP_ppc64be_linux) \
2030 || defined(VGP_ppc64le_linux)
2032 # elif defined(VGP_ppc32_linux)
2034 # elif defined(VGP_arm_linux)
2036 # elif defined(VGP_arm64_linux)
2038 # elif defined(VGP_s390x_linux)
2040 # elif defined(VGP_mips32_linux) || defined(VGP_mips64_linux)
2042 # elif defined(VGO_darwin)
2045 # error "Unknown plat"
2048 iters
*= 1000ULL * 1000 * 1000;
2049 for (q
= 0; q
< iters
; q
++)
2050 __asm__
__volatile__("" ::: "memory","cc");
2053 //--------------------------------------------------------------
2054 // Search for file descriptors that are inherited from our parent
2055 // p: main_process_cmd_line_options [for VG_(clo_track_fds)]
2056 //--------------------------------------------------------------
2057 if (VG_(clo_track_fds
)) {
2058 VG_(debugLog
)(1, "main", "Init preopened fds\n");
2059 VG_(init_preopened_fds
)();
2062 //--------------------------------------------------------------
2063 // Load debug info for the existing segments.
2064 // p: setup_code_redirect_table [so that redirs can be recorded]
2066 // p: probably: setup fds and process CLOs, so that logging works
2067 // p: initialise m_debuginfo
2069 // While doing this, make a note of the debuginfo-handles that
2070 // come back from VG_(di_notify_mmap).
2071 // Later, in "Tell the tool about the initial client memory permissions"
2072 // (just below) we can then hand these handles off to the tool in
2073 // calls to VG_TRACK(new_mem_startup, ...). This gives the tool the
2074 // opportunity to make further queries to m_debuginfo before the
2075 // client is started, if it wants. We put this information into an
2076 // XArray, each handle along with the associated segment start address,
2077 // and search the XArray for the handles later, when calling
2078 // VG_TRACK(new_mem_startup, ...).
2079 //--------------------------------------------------------------
2080 VG_(debugLog
)(1, "main", "Load initial debug info\n");
2082 tl_assert(!addr2dihandle
);
2083 addr2dihandle
= VG_(newXA
)( VG_(malloc
), "main.vm.2",
2084 VG_(free
), sizeof(Addr_n_ULong
) );
2085 tl_assert(addr2dihandle
);
2087 # if defined(VGO_linux)
2092 seg_starts
= VG_(get_segment_starts
)( &n_seg_starts
);
2093 vg_assert(seg_starts
&& n_seg_starts
>= 0);
2095 /* show them all to the debug info reader. allow_SkFileV has to
2096 be True here so that we read info from the valgrind executable
2098 for (i
= 0; i
< n_seg_starts
; i
++) {
2099 anu
.ull
= VG_(di_notify_mmap
)( seg_starts
[i
], True
/*allow_SkFileV*/,
2100 -1/*Don't use_fd*/);
2101 /* anu.ull holds the debuginfo handle returned by di_notify_mmap,
2104 anu
.a
= seg_starts
[i
];
2105 VG_(addToXA
)( addr2dihandle
, &anu
);
2109 VG_(free
)( seg_starts
);
2111 # elif defined(VGO_darwin)
2114 seg_starts
= VG_(get_segment_starts
)( &n_seg_starts
);
2115 vg_assert(seg_starts
&& n_seg_starts
>= 0);
2117 /* show them all to the debug info reader.
2118 Don't read from V segments (unlike Linux) */
2119 // GrP fixme really?
2120 for (i
= 0; i
< n_seg_starts
; i
++) {
2121 VG_(di_notify_mmap
)( seg_starts
[i
], False
/*don't allow_SkFileV*/,
2122 -1/*don't use_fd*/);
2125 VG_(free
)( seg_starts
);
2131 //--------------------------------------------------------------
2132 // Tell aspacem of ownership change of the asm helpers, so that
2133 // m_translate allows them to be translated. However, only do this
2134 // after the initial debug info read, since making a hole in the
2135 // address range for the stage2 binary confuses the debug info reader.
2137 //--------------------------------------------------------------
2138 { Bool change_ownership_v_c_OK
;
2139 Addr co_start
= VG_PGROUNDDN( (Addr
)&VG_(trampoline_stuff_start
) );
2140 Addr co_endPlus
= VG_PGROUNDUP( (Addr
)&VG_(trampoline_stuff_end
) );
2141 VG_(debugLog
)(1,"redir",
2142 "transfer ownership V -> C of 0x%llx .. 0x%llx\n",
2143 (ULong
)co_start
, (ULong
)co_endPlus
-1 );
2145 change_ownership_v_c_OK
2146 = VG_(am_change_ownership_v_to_c
)( co_start
, co_endPlus
- co_start
);
2147 vg_assert(change_ownership_v_c_OK
);
2152 VG_(elapsed_wallclock_time
)(buf
);
2153 VG_(printf_xml
)( "<status>\n"
2154 " <state>RUNNING</state>\n"
2155 " <time>%pS</time>\n"
2158 VG_(printf_xml
)( "\n" );
2161 VG_(init_Threads
)();
2163 //--------------------------------------------------------------
2164 // Initialise the scheduler (phase 1) [generates tid_main]
2166 //--------------------------------------------------------------
2167 VG_(debugLog
)(1, "main", "Initialise scheduler (phase 1)\n");
2168 tid_main
= VG_(scheduler_init_phase1
)();
2169 vg_assert(tid_main
>= 0 && tid_main
< VG_N_THREADS
2170 && tid_main
!= VG_INVALID_THREADID
);
2171 /* Tell the tool about tid_main */
2172 VG_TRACK( pre_thread_ll_create
, VG_INVALID_THREADID
, tid_main
);
2174 //--------------------------------------------------------------
2175 // Tell the tool about the initial client memory permissions
2178 // p: setup_client_stack
2179 // p: setup_client_dataseg
2181 // For each segment we tell the client about, look up in
2182 // addr2dihandle as created above, to see if there's a debuginfo
2183 // handle associated with the segment, that we can hand along
2184 // to the tool, to be helpful.
2185 //--------------------------------------------------------------
2186 VG_(debugLog
)(1, "main", "Tell tool about initial permissions\n");
2190 tl_assert(addr2dihandle
);
2192 /* Mark the main thread as running while we tell the tool about
2193 the client memory so that the tool can associate that memory
2194 with the main thread. */
2195 tl_assert(VG_(running_tid
) == VG_INVALID_THREADID
);
2196 VG_(running_tid
) = tid_main
;
2198 seg_starts
= VG_(get_segment_starts
)( &n_seg_starts
);
2199 vg_assert(seg_starts
&& n_seg_starts
>= 0);
2201 /* show interesting ones to the tool */
2202 for (i
= 0; i
< n_seg_starts
; i
++) {
2205 = VG_(am_find_nsegment
)( seg_starts
[i
] );
2207 if (seg
->kind
== SkFileC
|| seg
->kind
== SkAnonC
) {
2208 /* This next assertion is tricky. If it is placed
2209 immediately before this 'if', it very occasionally fails.
2210 Why? Because previous iterations of the loop may have
2211 caused tools (via the new_mem_startup calls) to do
2212 dynamic memory allocation, and that may affect the mapped
2213 segments; in particular it may cause segment merging to
2214 happen. Hence we cannot assume that seg_starts[i], which
2215 reflects the state of the world before we started this
2216 loop, is the same as seg->start, as the latter reflects
2217 the state of the world (viz, mappings) at this particular
2218 iteration of the loop.
2220 Why does moving it inside the 'if' make it safe? Because
2221 any dynamic memory allocation done by the tools will
2222 affect only the state of Valgrind-owned segments, not of
2223 Client-owned segments. And the 'if' guards against that
2224 -- we only get in here for Client-owned segments.
2226 In other words: the loop may change the state of
2227 Valgrind-owned segments as it proceeds. But it should
2228 not cause the Client-owned segments to change. */
2229 vg_assert(seg
->start
== seg_starts
[i
]);
2230 VG_(debugLog
)(2, "main",
2231 "tell tool about %010lx-%010lx %c%c%c\n",
2232 seg
->start
, seg
->end
,
2233 seg
->hasR
? 'r' : '-',
2234 seg
->hasW
? 'w' : '-',
2235 seg
->hasX
? 'x' : '-' );
2236 /* search addr2dihandle to see if we have an entry
2237 matching seg->start. */
2238 n
= VG_(sizeXA
)( addr2dihandle
);
2239 for (j
= 0; j
< n
; j
++) {
2240 Addr_n_ULong
* anl
= VG_(indexXA
)( addr2dihandle
, j
);
2241 if (anl
->a
== seg
->start
) {
2242 tl_assert(anl
->ull
> 0); /* check it's a valid handle */
2246 vg_assert(j
>= 0 && j
<= n
);
2247 VG_TRACK( new_mem_startup
, seg
->start
, seg
->end
+1-seg
->start
,
2248 seg
->hasR
, seg
->hasW
, seg
->hasX
,
2249 /* and the retrieved debuginfo handle, if any */
2251 ? ((Addr_n_ULong
*)VG_(indexXA
)( addr2dihandle
, j
))->ull
2256 VG_(free
)( seg_starts
);
2257 VG_(deleteXA
)( addr2dihandle
);
2259 /* Also do the initial stack permissions. */
2261 SSizeT inaccessible_len
;
2263 = VG_(am_find_nsegment
)( the_iifii
.initial_client_SP
);
2265 vg_assert(seg
->kind
== SkAnonC
);
2266 vg_assert(the_iifii
.initial_client_SP
>= seg
->start
);
2267 vg_assert(the_iifii
.initial_client_SP
<= seg
->end
);
2269 /* Stuff below the initial SP is unaddressable. Take into
2270 account any ABI-mandated space below the stack pointer that
2271 is required (VG_STACK_REDZONE_SZB). setup_client_stack()
2272 will have allocated an extra page if a red zone is required,
2273 to be on the safe side. */
2274 inaccessible_len
= the_iifii
.initial_client_SP
- VG_STACK_REDZONE_SZB
2276 vg_assert(inaccessible_len
>= 0);
2277 if (inaccessible_len
> 0)
2278 VG_TRACK( die_mem_stack
,
2281 VG_(debugLog
)(2, "main", "mark stack inaccessible %010lx-%010lx\n",
2283 the_iifii
.initial_client_SP
-1 - VG_STACK_REDZONE_SZB
);
2286 /* Also the assembly helpers. */
2287 VG_TRACK( new_mem_startup
,
2288 (Addr
)&VG_(trampoline_stuff_start
),
2289 (Addr
)&VG_(trampoline_stuff_end
)
2290 - (Addr
)&VG_(trampoline_stuff_start
),
2291 False
, /* readable? */
2292 False
, /* writable? */
2293 True
/* executable? */,
2294 0 /* di_handle: no associated debug info */ );
2296 /* Clear the running thread indicator */
2297 VG_(running_tid
) = VG_INVALID_THREADID
;
2298 tl_assert(VG_(running_tid
) == VG_INVALID_THREADID
);
2300 /* Darwin only: tell the tools where the client's kernel commpage
2301 is. It would be better to do this by telling aspacemgr about
2302 it -- see the now disused record_system_memory() in
2303 initimg-darwin.c -- but that causes the sync checker to fail,
2304 since the mapping doesn't appear in the kernel-supplied
2305 process map. So do it here instead. */
2306 # if defined(VGP_amd64_darwin)
2307 VG_TRACK( new_mem_startup
,
2308 0x7fffffe00000, 0x7ffffffff000-0x7fffffe00000,
2309 True
, False
, True
, /* r-x */
2310 0 /* di_handle: no associated debug info */ );
2311 # elif defined(VGP_x86_darwin)
2312 VG_TRACK( new_mem_startup
,
2313 0xfffec000, 0xfffff000-0xfffec000,
2314 True
, False
, True
, /* r-x */
2315 0 /* di_handle: no associated debug info */ );
2319 //--------------------------------------------------------------
2320 // Initialise the scheduler (phase 2)
2321 // p: Initialise the scheduler (phase 1) [for tid_main]
2322 // p: setup_file_descriptors() [else VG_(safe_fd)() breaks]
2323 // p: setup_client_stack
2324 //--------------------------------------------------------------
2325 VG_(debugLog
)(1, "main", "Initialise scheduler (phase 2)\n");
2326 { NSegment
const* seg
2327 = VG_(am_find_nsegment
)( the_iifii
.initial_client_SP
);
2329 vg_assert(seg
->kind
== SkAnonC
);
2330 vg_assert(the_iifii
.initial_client_SP
>= seg
->start
);
2331 vg_assert(the_iifii
.initial_client_SP
<= seg
->end
);
2332 VG_(scheduler_init_phase2
)( tid_main
,
2333 seg
->end
, the_iifii
.clstack_max_size
);
2336 //--------------------------------------------------------------
2337 // Set up state for the root thread
2339 // setup_scheduler() [for sched-specific thread 1 stuff]
2340 // VG_(ii_create_image) [for 'the_iicii' initial info]
2341 //--------------------------------------------------------------
2342 VG_(debugLog
)(1, "main", "Finalise initial image\n");
2343 VG_(ii_finalise_image
)( the_iifii
);
2345 //--------------------------------------------------------------
2346 // Initialise the signal handling subsystem
2348 //--------------------------------------------------------------
2349 // Nb: temporarily parks the saved blocking-mask in saved_sigmask.
2350 VG_(debugLog
)(1, "main", "Initialise signal management\n");
2351 /* Check that the kernel-interface signal definitions look sane */
2352 VG_(vki_do_initial_consistency_checks
)();
2353 /* .. and go on to use them. */
2354 VG_(sigstartup_actions
)();
2356 //--------------------------------------------------------------
2357 // Read suppression file
2358 // p: main_process_cmd_line_options() [for VG_(clo_suppressions)]
2359 //--------------------------------------------------------------
2360 if (VG_(needs
).core_errors
|| VG_(needs
).tool_errors
) {
2361 VG_(debugLog
)(1, "main", "Load suppressions\n");
2362 VG_(load_suppressions
)();
2365 //--------------------------------------------------------------
2366 // register client stack
2367 //--------------------------------------------------------------
2368 VG_(clstk_id
) = VG_(register_stack
)(VG_(clstk_base
), VG_(clstk_end
));
2370 //--------------------------------------------------------------
2371 // Show the address space state so far
2372 //--------------------------------------------------------------
2373 VG_(debugLog
)(1, "main", "\n");
2374 VG_(debugLog
)(1, "main", "\n");
2375 VG_(am_show_nsegments
)(1,"Memory layout at client startup");
2376 VG_(debugLog
)(1, "main", "\n");
2377 VG_(debugLog
)(1, "main", "\n");
2379 //--------------------------------------------------------------
2381 //--------------------------------------------------------------
2382 VG_(debugLog
)(1, "main", "Running thread 1\n");
2384 /* As a result of the following call, the last thread standing
2385 eventually winds up running shutdown_actions_NORETURN
2386 just below. Unfortunately, simply exporting said function
2387 causes m_main to be part of a module cycle, which is pretty
2388 nonsensical. So instead of doing that, the address of said
2389 function is stored in a global variable 'owned' by m_syswrap,
2390 and it uses that function pointer to get back here when it needs
2393 /* Set continuation address. */
2394 VG_(address_of_m_main_shutdown_actions_NORETURN
)
2395 = & shutdown_actions_NORETURN
;
2397 /* Run the first thread, eventually ending up at the continuation
2399 VG_(main_thread_wrapper_NORETURN
)(1);
2405 /* Do everything which needs doing when the last thread exits or when
2406 a thread exits requesting a complete process exit.
2408 We enter here holding The Lock. For the case VgSrc_ExitProcess we
2409 must never release it, because to do so would allow other threads
2410 to continue after the system is ostensibly shut down. So we must
2411 go to our grave, so to speak, holding the lock.
2413 In fact, there is never any point in releasing the lock at this
2414 point - we have it, we're shutting down the entire system, and
2415 for the case VgSrc_ExitProcess doing so positively causes trouble.
2418 The final_tidyup call makes a bit of a nonsense of the ExitProcess
2419 case, since it will run the libc_freeres function, thus allowing
2420 other lurking threads to run again. Hmm. */
2423 void shutdown_actions_NORETURN( ThreadId tid
,
2424 VgSchedReturnCode tids_schedretcode
)
2426 VG_(debugLog
)(1, "main", "entering VG_(shutdown_actions_NORETURN)\n");
2427 VG_(am_show_nsegments
)(1,"Memory layout at client shutdown");
2429 vg_assert(VG_(is_running_thread
)(tid
));
2431 vg_assert(tids_schedretcode
== VgSrc_ExitThread
2432 || tids_schedretcode
== VgSrc_ExitProcess
2433 || tids_schedretcode
== VgSrc_FatalSig
);
2435 if (tids_schedretcode
== VgSrc_ExitThread
) {
2437 // We are the last surviving thread. Right?
2438 vg_assert( VG_(count_living_threads
)() == 1 );
2440 // Wait for all other threads to exit.
2441 // jrs: Huh? but they surely are already gone
2442 VG_(reap_threads
)(tid
);
2444 // Clean the client up before the final report
2445 // this causes the libc_freeres function to run
2449 vg_assert(VG_(is_running_thread
)(tid
));
2450 vg_assert(VG_(count_living_threads
)() == 1);
2454 // We may not be the last surviving thread. However, we
2455 // want to shut down the entire process. We hold the lock
2456 // and we need to keep hold of it all the way out, in order
2457 // that none of the other threads ever run again.
2458 vg_assert( VG_(count_living_threads
)() >= 1 );
2460 // Clean the client up before the final report
2461 // this causes the libc_freeres function to run
2462 // perhaps this is unsafe, as per comment above
2466 vg_assert(VG_(is_running_thread
)(tid
));
2467 vg_assert(VG_(count_living_threads
)() >= 1);
2470 /* Final call to gdbserver, if requested. */
2471 if (VG_(gdbserver_stop_at
) (VgdbStopAt_Exit
)) {
2472 VG_(umsg
)("(action at exit) vgdb me ... \n");
2473 VG_(gdbserver
) (tid
);
2475 VG_(threads
)[tid
].status
= VgTs_Empty
;
2477 //--------------------------------------------------------------
2478 // Finalisation: cleanup, messages, etc. Order not so important, only
2479 // affects what order the messages come.
2480 //--------------------------------------------------------------
2481 // First thing in the post-amble is a blank line.
2483 VG_(printf_xml
)("\n");
2484 else if (VG_(clo_verbosity
) > 0)
2485 VG_(message
)(Vg_UserMsg
, "\n");
2489 VG_(elapsed_wallclock_time
)(buf
);
2490 VG_(printf_xml
)( "<status>\n"
2491 " <state>FINISHED</state>\n"
2492 " <time>%pS</time>\n"
2498 /* Print out file descriptor summary and stats. */
2499 if (VG_(clo_track_fds
))
2500 VG_(show_open_fds
)("at exit");
2502 /* Call the tool's finalisation function. This makes Memcheck's
2503 leak checker run, and possibly chuck a bunch of leak errors into
2504 the error management machinery. */
2505 VG_TDICT_CALL(tool_fini
, 0/*exitcode*/);
2507 /* Show the error counts. */
2509 && (VG_(needs
).core_errors
|| VG_(needs
).tool_errors
)) {
2510 VG_(show_error_counts_as_XML
)();
2513 /* In XML mode, this merely prints the used suppressions. */
2514 if (VG_(needs
).core_errors
|| VG_(needs
).tool_errors
)
2515 VG_(show_all_errors
)(VG_(clo_verbosity
), VG_(clo_xml
));
2518 VG_(printf_xml
)("\n");
2519 VG_(printf_xml
)("</valgrindoutput>\n");
2520 VG_(printf_xml
)("\n");
2523 VG_(sanity_check_general
)( True
/*include expensive checks*/ );
2526 VG_(print_all_stats
)(VG_(clo_verbosity
) > 2, /* Memory stats */
2527 False
/* tool prints stats in the tool fini */);
2529 /* Show a profile of the heap(s) at shutdown. Optionally, first
2530 throw away all the debug info, as that makes it easy to spot
2531 leaks in the debuginfo reader. */
2532 if (VG_(clo_profile_heap
)) {
2533 if (0) VG_(di_discard_ALL_debuginfo
)();
2534 VG_(print_arena_cc_analysis
)();
2537 /* If profiling has been requested, but with zero interval, it
2538 means "profile at the end of the run only". In which case we
2539 need to dump the profile now. */
2540 if (VG_(clo_profyle_sbs
) && VG_(clo_profyle_interval
) == 0) {
2541 VG_(get_and_show_SB_profile
)(0/*denoting end-of-run*/);
2544 /* Print Vex storage stats */
2546 LibVEX_ShowAllocStats();
2548 /* Flush any output cached by previous calls to VG_(message). */
2549 VG_(message_flush
)();
2551 /* Terminate gdbserver if ever it was started. We terminate it here
2552 so that it get the output above if output was redirected to
2554 VG_(gdbserver_exit
) (tid
, tids_schedretcode
);
2556 /* Ok, finally exit in the os-specific way, according to the scheduler's
2557 return code. In short, if the (last) thread exited by calling
2558 sys_exit, do likewise; if the (last) thread stopped due to a fatal
2559 signal, terminate the entire system with that same fatal signal. */
2560 VG_(debugLog
)(1, "core_os",
2561 "VG_(terminate_NORETURN)(tid=%lld)\n", (ULong
)tid
);
2563 switch (tids_schedretcode
) {
2564 case VgSrc_ExitThread
: /* the normal way out (Linux) */
2565 case VgSrc_ExitProcess
: /* the normal way out (AIX) -- still needed? */
2566 /* Change the application return code to user's return code,
2567 if an error was found */
2568 if (VG_(clo_error_exitcode
) > 0
2569 && VG_(get_n_errs_found
)() > 0) {
2570 VG_(client_exit
)( VG_(clo_error_exitcode
) );
2572 /* otherwise, return the client's exit code, in the normal
2574 VG_(client_exit
)( VG_(threads
)[tid
].os_state
.exitcode
);
2576 /* NOT ALIVE HERE! */
2577 VG_(core_panic
)("entered the afterlife in main() -- ExitT/P");
2578 break; /* what the hell :) */
2580 case VgSrc_FatalSig
:
2581 /* We were killed by a fatal signal, so replicate the effect */
2582 vg_assert(VG_(threads
)[tid
].os_state
.fatalsig
!= 0);
2583 VG_(kill_self
)(VG_(threads
)[tid
].os_state
.fatalsig
);
2584 /* we shouldn't be alive at this point. But VG_(kill_self)
2585 sometimes fails with EPERM on Darwin, for unclear reasons. */
2586 # if defined(VGO_darwin)
2587 VG_(debugLog
)(0, "main", "VG_(kill_self) failed. Exiting normally.\n");
2588 VG_(exit
)(0); /* bogus, but we really need to exit now */
2589 /* fall through .. */
2591 VG_(core_panic
)("main(): signal was supposed to be fatal");
2595 VG_(core_panic
)("main(): unexpected scheduler return code");
2599 /* -------------------- */
2601 /* Final clean-up before terminating the process.
2602 Clean up the client by calling __libc_freeres() (if requested)
2603 This is Linux-specific?
2604 GrP fixme glibc-specific, anyway
2606 static void final_tidyup(ThreadId tid
)
2608 #if !defined(VGO_darwin)
2609 # if defined(VGP_ppc64be_linux)
2612 Addr __libc_freeres_wrapper
= VG_(client___libc_freeres_wrapper
);
2614 vg_assert(VG_(is_running_thread
)(tid
));
2616 if ( !VG_(needs
).libc_freeres
||
2617 !VG_(clo_run_libc_freeres
) ||
2618 0 == __libc_freeres_wrapper
)
2619 return; /* can't/won't do it */
2621 # if defined(VGP_ppc64be_linux)
2622 r2
= VG_(get_tocptr
)( __libc_freeres_wrapper
);
2624 VG_(message
)(Vg_UserMsg
,
2625 "Caught __NR_exit, but can't run __libc_freeres()\n");
2626 VG_(message
)(Vg_UserMsg
,
2627 " since cannot establish TOC pointer for it.\n");
2632 if (VG_(clo_verbosity
) > 2 ||
2633 VG_(clo_trace_syscalls
) ||
2634 VG_(clo_trace_sched
))
2635 VG_(message
)(Vg_DebugMsg
,
2636 "Caught __NR_exit; running __libc_freeres()\n");
2638 /* set thread context to point to libc_freeres_wrapper */
2639 /* ppc64be-linux note: __libc_freeres_wrapper gives us the real
2640 function entry point, not a fn descriptor, so can use it
2641 directly. However, we need to set R2 (the toc pointer)
2643 VG_(set_IP
)(tid
, __libc_freeres_wrapper
);
2644 # if defined(VGP_ppc64be_linux)
2645 VG_(threads
)[tid
].arch
.vex
.guest_GPR2
= r2
;
2646 # elif defined(VGP_ppc64le_linux)
2647 /* setting GPR2 but not really needed, GPR12 is needed */
2648 VG_(threads
)[tid
].arch
.vex
.guest_GPR2
= __libc_freeres_wrapper
;
2649 VG_(threads
)[tid
].arch
.vex
.guest_GPR12
= __libc_freeres_wrapper
;
2651 /* mips-linux note: we need to set t9 */
2652 # if defined(VGP_mips32_linux) || defined(VGP_mips64_linux)
2653 VG_(threads
)[tid
].arch
.vex
.guest_r25
= __libc_freeres_wrapper
;
2656 /* Block all blockable signals by copying the real block state into
2657 the thread's block state*/
2658 VG_(sigprocmask
)(VKI_SIG_BLOCK
, NULL
, &VG_(threads
)[tid
].sig_mask
);
2659 VG_(threads
)[tid
].tmp_sig_mask
= VG_(threads
)[tid
].sig_mask
;
2661 /* and restore handlers to default */
2662 VG_(set_default_handler
)(VKI_SIGSEGV
);
2663 VG_(set_default_handler
)(VKI_SIGBUS
);
2664 VG_(set_default_handler
)(VKI_SIGILL
);
2665 VG_(set_default_handler
)(VKI_SIGFPE
);
2667 // We were exiting, so assert that...
2668 vg_assert(VG_(is_exiting
)(tid
));
2669 // ...but now we're not again
2670 VG_(threads
)[tid
].exitreason
= VgSrc_None
;
2672 // run until client thread exits - ideally with LIBC_FREERES_DONE,
2673 // but exit/exitgroup/signal will do
2674 VG_(scheduler
)(tid
);
2676 vg_assert(VG_(is_exiting
)(tid
));
2681 /*====================================================================*/
2682 /*=== Getting to main() alive: LINUX ===*/
2683 /*====================================================================*/
2685 #if defined(VGO_linux)
2687 /* If linking of the final executables is done with glibc present,
2688 then Valgrind starts at main() above as usual, and all of the
2689 following code is irrelevant.
2691 However, this is not the intended mode of use. The plan is to
2692 avoid linking against glibc, by giving gcc the flags
2693 -nodefaultlibs -lgcc -nostartfiles at startup.
2695 From this derive two requirements:
2697 1. gcc may emit calls to memcpy, memmove and memset to deal with
2698 structure assignments etc. Since we have chosen to ignore all the
2699 "normal" supporting libraries, we have to provide our own
2700 implementations of them. No problem.
2702 2. We have to provide a symbol "_start", to which the kernel
2703 hands control at startup. Hence the code below.
2706 /* ---------------- Requirement 1 ---------------- */
2708 void* memcpy(void *dest
, const void *src
, SizeT n
);
2709 void* memcpy(void *dest
, const void *src
, SizeT n
) {
2710 return VG_(memcpy
)(dest
,src
,n
);
2712 void* memmove(void *dest
, const void *src
, SizeT n
);
2713 void* memmove(void *dest
, const void *src
, SizeT n
) {
2714 return VG_(memmove
)(dest
,src
,n
);
2716 void* memset(void *s
, int c
, SizeT n
);
2717 void* memset(void *s
, int c
, SizeT n
) {
2718 return VG_(memset
)(s
,c
,n
);
2721 /* BVA: abort() for those platforms that need it (PPC and ARM). */
2724 VG_(printf
)("Something called raise().\n");
2728 /* EAZG: ARM's EABI will call floating point exception handlers in
2729 libgcc which boil down to an abort or raise, that's usually defined
2730 in libc. Instead, define them here. */
2731 #if defined(VGP_arm_linux)
2734 VG_(printf
)("Something called raise().\n");
2738 void __aeabi_unwind_cpp_pr0(void);
2739 void __aeabi_unwind_cpp_pr0(void){
2740 VG_(printf
)("Something called __aeabi_unwind_cpp_pr0()\n");
2744 void __aeabi_unwind_cpp_pr1(void);
2745 void __aeabi_unwind_cpp_pr1(void){
2746 VG_(printf
)("Something called __aeabi_unwind_cpp_pr1()\n");
2751 /* ---------------- Requirement 2 ---------------- */
2753 /* Glibc's sysdeps/i386/elf/start.S has the following gem of a
2754 comment, which explains how the stack looks right at process start
2755 (when _start is jumped to). Hence _start passes %esp to
2756 _start_in_C_linux, which extracts argc/argv/envp and starts up
2759 /* This is the canonical entry point, usually the first thing in the text
2760 segment. The SVR4/i386 ABI (pages 3-31, 3-32) says that when the entry
2761 point runs, most registers' values are unspecified, except for:
2763 %edx Contains a function pointer to be registered with `atexit'.
2764 This is how the dynamic linker arranges to have DT_FINI
2765 functions called for shared libraries that have been loaded
2766 before this code runs.
2768 %esp The stack contains the arguments and environment:
2773 (4*(argc+1))(%esp) envp[0]
2778 /* The kernel hands control to _start, which extracts the initial
2779 stack pointer and calls onwards to _start_in_C_linux. This also switches
2781 #if defined(VGP_x86_linux)
2785 "\t.type _start,@function\n"
2787 /* set up the new stack in %eax */
2788 "\tmovl $vgPlain_interim_stack, %eax\n"
2789 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB
)", %eax\n"
2790 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)", %eax\n"
2791 "\tsubl $16, %eax\n"
2792 "\tandl $~15, %eax\n"
2793 /* install it, and collect the original one */
2794 "\txchgl %eax, %esp\n"
2795 /* call _start_in_C_linux, passing it the startup %esp */
2797 "\tcall _start_in_C_linux\n"
2801 #elif defined(VGP_amd64_linux)
2805 "\t.type _start,@function\n"
2807 /* set up the new stack in %rdi */
2808 "\tmovq $vgPlain_interim_stack, %rdi\n"
2809 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB
)", %rdi\n"
2810 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)", %rdi\n"
2811 "\tandq $~15, %rdi\n"
2812 /* install it, and collect the original one */
2813 "\txchgq %rdi, %rsp\n"
2814 /* call _start_in_C_linux, passing it the startup %rsp */
2815 "\tcall _start_in_C_linux\n"
2819 #elif defined(VGP_ppc32_linux)
2823 "\t.type _start,@function\n"
2825 /* set up the new stack in r16 */
2826 "\tlis 16,vgPlain_interim_stack@ha\n"
2827 "\tla 16,vgPlain_interim_stack@l(16)\n"
2828 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB
)" >> 16)\n"
2829 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB
)" & 0xFFFF)\n"
2830 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)" >> 16)\n"
2831 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)" & 0xFFFF)\n"
2834 "\trlwinm 16,16,0,0,27\n"
2835 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2836 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2837 boundary. And r1 is the original SP. Set the SP to r16 and
2838 call _start_in_C_linux, passing it the initial SP. */
2841 "\tbl _start_in_C_linux\n"
2845 #elif defined(VGP_ppc64be_linux)
2847 /* PPC64 ELF ABI says '_start' points to a function descriptor.
2848 So we must have one, and that is what goes into the .opd section. */
2850 "\t.global _start\n"
2851 "\t.section \".opd\",\"aw\"\n"
2854 "\t.quad ._start,.TOC.@tocbase,0\n"
2856 "\t.type ._start,@function\n"
2857 "\t.global ._start\n"
2859 /* set up the new stack in r16 */
2860 "\tlis 16, vgPlain_interim_stack@highest\n"
2861 "\tori 16,16,vgPlain_interim_stack@higher\n"
2863 "\toris 16,16,vgPlain_interim_stack@h\n"
2864 "\tori 16,16,vgPlain_interim_stack@l\n"
2866 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB
)" >> 16)\n"
2867 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB
)" & 0xFFFF)\n"
2869 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)" >> 16)\n"
2870 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)" & 0xFFFF)\n"
2873 "\trldicr 16,16,0,59\n"
2874 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2875 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2876 boundary. And r1 is the original SP. Set the SP to r16 and
2877 call _start_in_C_linux, passing it the initial SP. */
2880 "\tlis 14, _start_in_C_linux@highest\n"
2881 "\tori 14,14,_start_in_C_linux@higher\n"
2883 "\toris 14,14,_start_in_C_linux@h\n"
2884 "\tori 14,14,_start_in_C_linux@l\n"
2891 #elif defined(VGP_ppc64le_linux)
2892 /* Little Endian uses ELF version 2 but in the future may also
2893 * support other ELF versions.
2897 "\t.global _start\n"
2898 "\t.type _start,@function\n"
2900 "#if _CALL_ELF == 2 \n"
2901 "0: addis 2,12,.TOC.-0b@ha\n"
2902 " addi 2,2,.TOC.-0b@l\n"
2903 " .localentry _start, .-_start\n"
2905 /* set up the new stack in r16 */
2906 "\tlis 16, vgPlain_interim_stack@highest\n"
2907 "\tori 16,16,vgPlain_interim_stack@higher\n"
2909 "\toris 16,16,vgPlain_interim_stack@h\n"
2910 "\tori 16,16,vgPlain_interim_stack@l\n"
2912 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB
)" >> 16)\n"
2913 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB
)" & 0xFFFF)\n"
2915 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)" >> 16)\n"
2916 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)" & 0xFFFF)\n"
2919 "\trldicr 16,16,0,59\n"
2920 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2921 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2922 boundary. And r1 is the original SP. Set the SP to r16 and
2923 call _start_in_C_linux, passing it the initial SP. */
2926 "\tlis 14, _start_in_C_linux@highest\n"
2927 "\tori 14,14,_start_in_C_linux@higher\n"
2929 "\toris 14,14,_start_in_C_linux@h\n"
2930 "\tori 14,14,_start_in_C_linux@l\n"
2936 #elif defined(VGP_s390x_linux)
2938 This is the canonical entry point, usually the first thing in the text
2939 segment. Most registers' values are unspecified, except for:
2941 %r14 Contains a function pointer to be registered with `atexit'.
2942 This is how the dynamic linker arranges to have DT_FINI
2943 functions called for shared libraries that have been loaded
2944 before this code runs.
2946 %r15 The stack contains the arguments and environment:
2951 (8*(argc+1))(%r15) envp[0]
2958 ".type _start,@function\n\t"
2960 /* set up the new stack in %r1 */
2961 "larl %r1, vgPlain_interim_stack\n\t"
2963 "ag %r1, 0(%r5)\n\t"
2964 "ag %r1, 2f-1f(%r5)\n\t"
2965 "nill %r1, 0xFFF0\n\t"
2966 /* install it, and collect the original one */
2969 /* call _start_in_C_linux, passing it the startup %r15 */
2970 "brasl %r14, _start_in_C_linux\n\t"
2971 /* trigger execution of an invalid opcode -> halt machine */
2973 "1: .quad "VG_STRINGIFY(VG_STACK_GUARD_SZB
)"\n\t"
2974 "2: .quad "VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)"\n\t"
2977 #elif defined(VGP_arm_linux)
2981 "\t.type _start,#function\n"
2982 "\t.global _start\n"
2984 "\tldr r0, [pc, #36]\n"
2985 "\tldr r1, [pc, #36]\n"
2986 "\tadd r0, r1, r0\n"
2987 "\tldr r1, [pc, #32]\n"
2988 "\tadd r0, r1, r0\n"
2990 "\tand r0, r0, r1\n"
2994 "\tb _start_in_C_linux\n"
2995 "\t.word vgPlain_interim_stack\n"
2996 "\t.word "VG_STRINGIFY(VG_STACK_GUARD_SZB
)"\n"
2997 "\t.word "VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)"\n"
2999 #elif defined(VGP_arm64_linux)
3003 "\t.type _start,#function\n"
3004 "\t.global _start\n"
3006 "\tadrp x0, vgPlain_interim_stack\n"
3007 "\tadd x0, x0, :lo12:vgPlain_interim_stack\n"
3008 // The next 2 assume that VG_STACK_GUARD_SZB fits in 32 bits
3009 "\tmov x1, (("VG_STRINGIFY(VG_STACK_GUARD_SZB
)") >> 0) & 0xFFFF\n"
3010 "\tmovk x1, (("VG_STRINGIFY(VG_STACK_GUARD_SZB
)") >> 16) & 0xFFFF,"
3012 "\tadd x0, x0, x1\n"
3013 // The next 2 assume that VG_STACK_ACTIVE_SZB fits in 32 bits
3014 "\tmov x1, (("VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)") >> 0) & 0xFFFF\n"
3015 "\tmovk x1, (("VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)") >> 16) & 0xFFFF,"
3017 "\tadd x0, x0, x1\n"
3018 "\tand x0, x0, -16\n"
3022 "\tb _start_in_C_linux\n"
3024 #elif defined(VGP_mips32_linux)
3026 "\t.type _gp_disp,@object\n"
3028 "\t.globl __start\n"
3029 "\t.type __start,@function\n"
3037 "\tlui $28, %hi(_gp_disp)\n"
3038 "\taddiu $28, $28, %lo(_gp_disp)\n"
3039 "\taddu $28, $28, $31\n"
3040 /* t1/$9 <- Addr(interim_stack) */
3041 "\tlui $9, %hi(vgPlain_interim_stack)\n"
3042 /* t1/$9 <- Addr(interim_stack) */
3043 "\taddiu $9, %lo(vgPlain_interim_stack)\n"
3046 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB
)"\n"
3047 "\tli $11, "VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)"\n"
3049 "\taddu $9, $9, $10\n"
3050 "\taddu $9, $9, $11\n"
3051 "\tli $12, 0xFFFFFFF0\n"
3052 "\tand $9, $9, $12\n"
3053 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
3054 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
3055 boundary. And $29 is the original SP. Set the SP to t1 and
3056 call _start_in_C, passing it the initial SP. */
3058 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
3059 "\tmove $29, $9\n" // $sp <- t1 (new sp)
3061 "\tlui $25, %hi(_start_in_C_linux)\n"
3062 "\taddiu $25, %lo(_start_in_C_linux)\n"
3064 "\tbal _start_in_C_linux\n"
3068 #elif defined(VGP_mips64_linux)
3072 ".type __start,@function\n"
3074 "\t.set noreorder\n"
3078 "\tlui $9, %hi(vgPlain_interim_stack)\n"
3079 /* t1/$9 <- Addr(interim_stack) */
3080 "\tdaddiu $9, %lo(vgPlain_interim_stack)\n"
3082 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB
)"\n"
3083 "\tli $11, "VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)"\n"
3085 "\tdaddu $9, $9, $10\n"
3086 "\tdaddu $9, $9, $11\n"
3087 "\tli $12, 0xFFFFFF00\n"
3088 "\tand $9, $9, $12\n"
3089 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
3090 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
3091 boundary. And $29 is the original SP. Set the SP to t1 and
3092 call _start_in_C, passing it the initial SP. */
3094 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
3095 "\tmove $29, $9\n" // $sp <- t1 (new sp)
3097 "\tlui $9, %highest(_start_in_C_linux)\n"
3098 "\tori $9, %higher(_start_in_C_linux)\n"
3099 "\tdsll32 $9, $9, 0x0\n"
3100 "\tlui $10, %hi(_start_in_C_linux)\n"
3101 "\tdaddiu $10, %lo(_start_in_C_linux)\n"
3102 "\tdaddu $25, $9, $10\n"
3108 # error "Unknown linux platform"
3111 /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
3113 #define _FILE_OFFSET_BITS 64
3114 /* This is in order to get AT_NULL and AT_PAGESIZE. */
3116 /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
3118 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3119 'static' causes gcc to complain it isn't.
3120 attribute 'used' also ensures the code is not eliminated at link
3122 __attribute__ ((used
))
3123 void _start_in_C_linux ( UWord
* pArgc
);
3124 __attribute__ ((used
))
3125 void _start_in_C_linux ( UWord
* pArgc
)
3128 Word argc
= pArgc
[0];
3129 HChar
** argv
= (HChar
**)&pArgc
[1];
3130 HChar
** envp
= (HChar
**)&pArgc
[1+argc
+1];
3132 // For an inner Valgrind, register the interim stack asap.
3133 // This is needed to allow the outer valgrind to do stacktraces during init.
3134 // Note that this stack is not unregistered when the main thread
3135 // is switching to the (real) stack. Unregistering this would imply
3136 // to save the stack id in a global variable, and have a "if"
3137 // in run_a_thread_NORETURN to do the unregistration only for the
3138 // main thread. This unregistration is not worth this complexity.
3140 ((void) VALGRIND_STACK_REGISTER
3141 (&VG_(interim_stack
).bytes
[0],
3142 &VG_(interim_stack
).bytes
[0] + sizeof(VG_(interim_stack
))));
3144 VG_(memset
)( &the_iicii
, 0, sizeof(the_iicii
) );
3145 VG_(memset
)( &the_iifii
, 0, sizeof(the_iifii
) );
3147 the_iicii
.sp_at_startup
= (Addr
)pArgc
;
3149 # if defined(VGP_ppc32_linux) || defined(VGP_ppc64be_linux) \
3150 || defined(VGP_ppc64le_linux) || defined(VGP_arm64_linux)
3152 /* ppc32/ppc64 can be configured with different page sizes.
3153 Determine this early. This is an ugly hack and really should
3154 be moved into valgrind_main. */
3155 UWord
*sp
= &pArgc
[1+argc
+1];
3158 for (; *sp
!= AT_NULL
&& *sp
!= AT_PAGESZ
; sp
+= 2);
3159 if (*sp
== AT_PAGESZ
) {
3160 VKI_PAGE_SIZE
= sp
[1];
3161 for (VKI_PAGE_SHIFT
= 12;
3162 VKI_PAGE_SHIFT
<= VKI_MAX_PAGE_SHIFT
; VKI_PAGE_SHIFT
++)
3163 if (VKI_PAGE_SIZE
== (1UL << VKI_PAGE_SHIFT
))
3169 r
= valgrind_main( (Int
)argc
, argv
, envp
);
3175 /*====================================================================*/
3176 /*=== Getting to main() alive: darwin ===*/
3177 /*====================================================================*/
3179 #elif defined(VGO_darwin)
3182 Memory layout established by kernel:
3193 executable name (presumably, a pointer to it)
3196 Ditto in the 64-bit case, except all offsets from SP are obviously
3200 /* The kernel hands control to _start, which extracts the initial
3201 stack pointer and calls onwards to _start_in_C_darwin. This also
3202 switches to the new stack. */
3203 #if defined(VGP_x86_darwin)
3207 "\t.globl __start\n"
3209 /* set up the new stack in %eax */
3210 "\tmovl $_vgPlain_interim_stack, %eax\n"
3211 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB
)", %eax\n"
3212 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)", %eax\n"
3213 "\tsubl $16, %eax\n"
3214 "\tandl $~15, %eax\n"
3215 /* install it, and collect the original one */
3216 "\txchgl %eax, %esp\n"
3217 "\tsubl $12, %esp\n" // keep stack 16 aligned; see #295428
3218 /* call _start_in_C_darwin, passing it the startup %esp */
3220 "\tcall __start_in_C_darwin\n"
3224 #elif defined(VGP_amd64_darwin)
3227 "\t.globl __start\n"
3230 /* set up the new stack in %rdi */
3231 "\tmovabsq $_vgPlain_interim_stack, %rdi\n"
3232 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB
)", %rdi\n"
3233 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB
)", %rdi\n"
3234 "\tandq $~15, %rdi\n"
3235 /* install it, and collect the original one */
3236 "\txchgq %rdi, %rsp\n"
3237 /* call _start_in_C_darwin, passing it the startup %rsp */
3238 "\tcall __start_in_C_darwin\n"
3244 void* __memcpy_chk(void *dest
, const void *src
, SizeT n
, SizeT n2
);
3245 void* __memcpy_chk(void *dest
, const void *src
, SizeT n
, SizeT n2
) {
3247 return VG_(memcpy
)(dest
,src
,n
);
3249 void* __memset_chk(void *s
, int c
, SizeT n
, SizeT n2
);
3250 void* __memset_chk(void *s
, int c
, SizeT n
, SizeT n2
) {
3252 return VG_(memset
)(s
,c
,n
);
3254 void bzero(void *s
, SizeT n
);
3255 void bzero(void *s
, SizeT n
) {
3259 void* memcpy(void *dest
, const void *src
, SizeT n
);
3260 void* memcpy(void *dest
, const void *src
, SizeT n
) {
3261 return VG_(memcpy
)(dest
,src
,n
);
3263 void* memset(void *s
, int c
, SizeT n
);
3264 void* memset(void *s
, int c
, SizeT n
) {
3265 return VG_(memset
)(s
,c
,n
);
3268 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3269 'static' causes gcc to complain it isn't. */
3270 void _start_in_C_darwin ( UWord
* pArgc
);
3271 void _start_in_C_darwin ( UWord
* pArgc
)
3274 Int argc
= *(Int
*)pArgc
; // not pArgc[0] on LP64
3275 HChar
** argv
= (HChar
**)&pArgc
[1];
3276 HChar
** envp
= (HChar
**)&pArgc
[1+argc
+1];
3278 // See _start_in_C_linux
3280 ((void) VALGRIND_STACK_REGISTER
3281 (&VG_(interim_stack
).bytes
[0],
3282 &VG_(interim_stack
).bytes
[0] + sizeof(VG_(interim_stack
))));
3284 VG_(memset
)( &the_iicii
, 0, sizeof(the_iicii
) );
3285 VG_(memset
)( &the_iifii
, 0, sizeof(the_iifii
) );
3287 the_iicii
.sp_at_startup
= (Addr
)pArgc
;
3289 r
= valgrind_main( (Int
)argc
, argv
, envp
);
3297 # error "Unknown OS"
3301 /*====================================================================*/
3302 /*=== {u,}{div,mod}di3 replacements ===*/
3303 /*====================================================================*/
3305 /* For static linking on x86-darwin, we need to supply our own 64-bit
3306 integer division code, else the link dies thusly:
3308 ld_classic: Undefined symbols:
3312 #if defined(VGP_x86_darwin)
3314 /* Routines for doing signed/unsigned 64 x 64 ==> 64 div and mod
3315 (udivdi3, umoddi3, divdi3, moddi3) using only 32 x 32 ==> 32
3316 division. Cobbled together from
3318 http://www.hackersdelight.org/HDcode/divlu.c
3319 http://www.hackersdelight.org/HDcode/divls.c
3320 http://www.hackersdelight.org/HDcode/newCode/divDouble.c
3322 The code from those three files is covered by the following license,
3325 http://www.hackersdelight.org/permissions.htm
3327 You are free to use, copy, and distribute any of the code on
3328 this web site, whether modified by you or not. You need not give
3329 attribution. This includes the algorithms (some of which appear
3330 in Hacker's Delight), the Hacker's Assistant, and any code
3331 submitted by readers. Submitters implicitly agree to this.
3334 /* Long division, unsigned (64/32 ==> 32).
3335 This procedure performs unsigned "long division" i.e., division of a
3336 64-bit unsigned dividend by a 32-bit unsigned divisor, producing a
3337 32-bit quotient. In the overflow cases (divide by 0, or quotient
3338 exceeds 32 bits), it returns a remainder of 0xFFFFFFFF (an impossible
3340 The dividend is u1 and u0, with u1 being the most significant word.
3341 The divisor is parameter v. The value returned is the quotient.
3342 Max line length is 57, to fit in hacker.book. */
3344 static Int
nlz32(UInt x
)
3347 if (x
== 0) return(32);
3349 if (x
<= 0x0000FFFF) {n
= n
+16; x
= x
<<16;}
3350 if (x
<= 0x00FFFFFF) {n
= n
+ 8; x
= x
<< 8;}
3351 if (x
<= 0x0FFFFFFF) {n
= n
+ 4; x
= x
<< 4;}
3352 if (x
<= 0x3FFFFFFF) {n
= n
+ 2; x
= x
<< 2;}
3353 if (x
<= 0x7FFFFFFF) {n
= n
+ 1;}
3357 /* 64 x 32 ==> 32 unsigned division, using only 32 x 32 ==> 32
3358 division as a primitive. */
3359 static UInt
divlu2(UInt u1
, UInt u0
, UInt v
, UInt
*r
)
3361 const UInt b
= 65536; // Number base (16 bits).
3362 UInt un1
, un0
, // Norm. dividend LSD's.
3363 vn1
, vn0
, // Norm. divisor digits.
3364 q1
, q0
, // Quotient digits.
3365 un32
, un21
, un10
, // Dividend digit pairs.
3366 rhat
; // A remainder.
3367 Int s
; // Shift amount for norm.
3369 if (u1
>= v
) { // If overflow, set rem.
3370 if (r
!= NULL
) // to an impossible value,
3371 *r
= 0xFFFFFFFF; // and return the largest
3372 return 0xFFFFFFFF;} // possible quotient.
3374 s
= nlz32(v
); // 0 <= s <= 31.
3375 v
= v
<< s
; // Normalize divisor.
3376 vn1
= v
>> 16; // Break divisor up into
3377 vn0
= v
& 0xFFFF; // two 16-bit digits.
3379 un32
= (u1
<< s
) | ((u0
>> (32 - s
)) & (-s
>> 31));
3380 un10
= u0
<< s
; // Shift dividend left.
3382 un1
= un10
>> 16; // Break right half of
3383 un0
= un10
& 0xFFFF; // dividend into two digits.
3385 q1
= un32
/vn1
; // Compute the first
3386 rhat
= un32
- q1
*vn1
; // quotient digit, q1.
3388 if (q1
>= b
|| q1
*vn0
> b
*rhat
+ un1
) {
3391 if (rhat
< b
) goto again1
;}
3393 un21
= un32
*b
+ un1
- q1
*v
; // Multiply and subtract.
3395 q0
= un21
/vn1
; // Compute the second
3396 rhat
= un21
- q0
*vn1
; // quotient digit, q0.
3398 if (q0
>= b
|| q0
*vn0
> b
*rhat
+ un0
) {
3401 if (rhat
< b
) goto again2
;}
3403 if (r
!= NULL
) // If remainder is wanted,
3404 *r
= (un21
*b
+ un0
- q0
*v
) >> s
; // return it.
3409 /* 64 x 32 ==> 32 signed division, using only 32 x 32 ==> 32 division
3411 static Int
divls(Int u1
, UInt u0
, Int v
, Int
*r
)
3413 Int q
, uneg
, vneg
, diff
, borrow
;
3415 uneg
= u1
>> 31; // -1 if u < 0.
3416 if (uneg
) { // Compute the absolute
3417 u0
= -u0
; // value of the dividend u.
3421 vneg
= v
>> 31; // -1 if v < 0.
3422 v
= (v
^ vneg
) - vneg
; // Absolute value of v.
3424 if ((UInt
)u1
>= (UInt
)v
) goto overflow
;
3426 q
= divlu2(u1
, u0
, v
, (UInt
*)r
);
3428 diff
= uneg
^ vneg
; // Negate q if signs of
3429 q
= (q
^ diff
) - diff
; // u and v differed.
3430 if (uneg
&& r
!= NULL
)
3433 if ((diff
^ q
) < 0 && q
!= 0) { // If overflow,
3434 overflow
: // set remainder
3435 if (r
!= NULL
) // to an impossible value,
3436 *r
= 0x80000000; // and return the largest
3437 q
= 0x80000000;} // possible neg. quotient.
3443 /* This file contains a program for doing 64/64 ==> 64 division, on a
3444 machine that does not have that instruction but that does have
3445 instructions for "long division" (64/32 ==> 32). Code for unsigned
3446 division is given first, followed by a simple program for doing the
3447 signed version by using the unsigned version.
3448 These programs are useful in implementing "long long" (64-bit)
3449 arithmetic on a machine that has the long division instruction. It will
3450 work on 64- and 32-bit machines, provided the compiler implements long
3451 long's (64-bit integers). It is desirable that the machine have the
3452 Count Leading Zeros instruction.
3453 In the GNU world, these programs are known as __divdi3 and __udivdi3,
3454 and similar names are used here.
3455 This material is not in HD, but may be in a future edition.
3456 Max line length is 57, to fit in hacker.book. */
3459 static Int
nlz64(ULong x
)
3462 if (x
== 0) return(64);
3464 if (x
<= 0x00000000FFFFFFFFULL
) {n
= n
+ 32; x
= x
<< 32;}
3465 if (x
<= 0x0000FFFFFFFFFFFFULL
) {n
= n
+ 16; x
= x
<< 16;}
3466 if (x
<= 0x00FFFFFFFFFFFFFFULL
) {n
= n
+ 8; x
= x
<< 8;}
3467 if (x
<= 0x0FFFFFFFFFFFFFFFULL
) {n
= n
+ 4; x
= x
<< 4;}
3468 if (x
<= 0x3FFFFFFFFFFFFFFFULL
) {n
= n
+ 2; x
= x
<< 2;}
3469 if (x
<= 0x7FFFFFFFFFFFFFFFULL
) {n
= n
+ 1;}
3473 // ---------------------------- udivdi3 --------------------------------
3475 /* The variables u0, u1, etc. take on only 32-bit values, but they
3476 are declared long long to avoid some compiler warning messages and to
3477 avoid some unnecessary EXTRs that the compiler would put in, to
3478 convert long longs to ints.
3480 First the procedure takes care of the case in which the divisor is a
3481 32-bit quantity. There are two subcases: (1) If the left half of the
3482 dividend is less than the divisor, one execution of DIVU is all that
3483 is required (overflow is not possible). (2) Otherwise it does two
3484 divisions, using the grade school method, with variables used as
3494 /* These macros must be used with arguments of the appropriate type
3495 (unsigned long long for DIVU and long long for DIVS. They are
3496 simulations of the presumed machines ops. I.e., they look at only the
3497 low-order 32 bits of the divisor, they return garbage if the division
3498 overflows, and they return garbage in the high-order half of the
3499 quotient doubleword.
3500 In practice, these would be replaced with uses of the machine's DIVU
3501 and DIVS instructions (e.g., by using the GNU "asm" facility). */
3503 static UInt
DIVU ( ULong u
, UInt v
)
3505 UInt uHi
= (UInt
)(u
>> 32);
3507 return divlu2(uHi
, uLo
, v
, NULL
);
3510 static Int
DIVS ( Long u
, Int v
)
3512 Int uHi
= (Int
)(u
>> 32);
3514 return divls(uHi
, uLo
, v
, NULL
);
3517 /* 64 x 64 ==> 64 unsigned division, using only 32 x 32 ==> 32
3518 division as a primitive. */
3519 static ULong
udivdi3(ULong u
, ULong v
)
3521 ULong u0
, u1
, v1
, q0
, q1
, k
, n
;
3523 if (v
>> 32 == 0) { // If v < 2**32:
3524 if (u
>> 32 < v
) // If u/v cannot overflow,
3525 return DIVU(u
, v
) // just do one division.
3527 else { // If u/v would overflow:
3528 u1
= u
>> 32; // Break u up into two
3529 u0
= u
& 0xFFFFFFFF; // halves.
3530 q1
= DIVU(u1
, v
) // First quotient digit.
3532 k
= u1
- q1
*v
; // First remainder, < v.
3533 q0
= DIVU((k
<< 32) + u0
, v
) // 2nd quot. digit.
3535 return (q1
<< 32) + q0
;
3539 n
= nlz64(v
); // 0 <= n <= 31.
3540 v1
= (v
<< n
) >> 32; // Normalize the divisor
3542 u1
= u
>> 1; // To ensure no overflow.
3543 q1
= DIVU(u1
, v1
) // Get quotient from
3544 & 0xFFFFFFFF; // divide unsigned insn.
3545 q0
= (q1
<< n
) >> 31; // Undo normalization and
3546 // division of u by 2.
3547 if (q0
!= 0) // Make q0 correct or
3548 q0
= q0
- 1; // too small by 1.
3549 if ((u
- q0
*v
) >= v
)
3550 q0
= q0
+ 1; // Now q0 is correct.
3555 // ----------------------------- divdi3 --------------------------------
3557 /* This routine presumes that smallish cases (those which can be done in
3558 one execution of DIVS) are common. If this is not the case, the test for
3559 this case should be deleted.
3560 Note that the test for when DIVS can be used is not entirely
3561 accurate. For example, DIVS is not used if v = 0xFFFFFFFF8000000,
3562 whereas if could be (if u is sufficiently small in magnitude). */
3564 // ------------------------------ cut ----------------------------------
3566 static ULong
my_llabs ( Long x
)
3572 /* 64 x 64 ==> 64 signed division, using only 32 x 32 ==> 32 division
3574 static Long
divdi3(Long u
, Long v
)
3580 if (av
>> 31 == 0) { // If |v| < 2**31 and
3581 // if (v << 32 >> 32 == v) { // If v is in range and
3582 if (au
< av
<< 31) { // |u|/|v| cannot
3583 q
= DIVS(u
, v
); // overflow, use DIVS.
3584 return (q
<< 32) >> 32;
3587 q
= udivdi3(au
,av
); // Invoke udivdi3.
3588 t
= (u
^ v
) >> 63; // If u, v have different
3589 return (q
^ t
) - t
; // signs, negate q.
3592 // ---------------------------- end cut --------------------------------
3594 ULong
__udivdi3 (ULong u
, ULong v
);
3595 ULong
__udivdi3 (ULong u
, ULong v
)
3597 return udivdi3(u
,v
);
3600 Long
__divdi3 (Long u
, Long v
);
3601 Long
__divdi3 (Long u
, Long v
)
3606 ULong
__umoddi3 (ULong u
, ULong v
);
3607 ULong
__umoddi3 (ULong u
, ULong v
)
3609 ULong q
= __udivdi3(u
, v
);
3610 ULong r
= u
- q
* v
;
3614 Long
__moddi3 (Long u
, Long v
);
3615 Long
__moddi3 (Long u
, Long v
)
3617 Long q
= __divdi3(u
, v
);
3622 /* ------------------------------------------------
3623 ld_classic: Undefined symbols:
3625 ------------------------------------------------
3628 /* ===-- fixunsdfdi.c - Implement __fixunsdfdi -----------------------------===
3630 * The LLVM Compiler Infrastructure
3632 * This file is dual licensed under the MIT and the University of Illinois Open
3633 * Source Licenses. See LICENSE.TXT for details.
3635 * ===----------------------------------------------------------------------===
3637 * This file implements __fixunsdfdi for the compiler_rt library.
3639 * ===----------------------------------------------------------------------===
3642 /* As per http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses,
3644 the "NCSA/University of Illinois Open Source License" is compatible
3645 with the GPL (both version 2 and 3). What is claimed to be
3648 http://www.opensource.org/licenses/UoI-NCSA.php
3650 and the LLVM documentation at
3652 http://www.llvm.org/docs/DeveloperPolicy.html#license
3654 says all the code in LLVM is available under the University of
3655 Illinois/NCSA Open Source License, at this URL
3657 http://www.opensource.org/licenses/UoI-NCSA.php
3659 viz, the same one that the FSF pages claim is compatible. So I
3660 think it's OK to include it.
3663 /* Returns: convert a to a unsigned long long, rounding toward zero.
3664 * Negative values all become zero.
3667 /* Assumption: double is a IEEE 64 bit floating point type
3668 * du_int is a 64 bit integral type
3669 * value in double is representable in du_int or is negative
3670 * (no range checking performed)
3673 /* seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm */
3675 typedef unsigned long long du_int
;
3676 typedef unsigned su_int
;
3689 #endif /* VG_LITTLEENDIAN */
3699 du_int
__fixunsdfdi(double a
);
3702 __fixunsdfdi(double a
)
3706 int e
= ((fb
.u
.s
.high
& 0x7FF00000) >> 20) - 1023;
3707 if (e
< 0 || (fb
.u
.s
.high
& 0x80000000))
3710 r
.s
.high
= (fb
.u
.s
.high
& 0x000FFFFF) | 0x00100000;
3711 r
.s
.low
= fb
.u
.s
.low
;
3723 /*--------------------------------------------------------------------*/
3725 /*--------------------------------------------------------------------*/