Fix 308644 vgdb command for having the info for the track-fds option
[ambi/valgrind.git] / coregrind / m_main.c
1
2 /*--------------------------------------------------------------------*/
3 /*--- Startup: the real stuff                             m_main.c ---*/
4 /*--------------------------------------------------------------------*/
5
6 /*
7    This file is part of Valgrind, a dynamic binary instrumentation
8    framework.
9
10    Copyright (C) 2000-2012 Julian Seward 
11       jseward@acm.org
12
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.
17
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.
22
23    You should have received a copy of the GNU General Public License
24    along with this program; if not, write to the Free Software
25    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
26    02111-1307, USA.
27
28    The GNU General Public License is contained in the file COPYING.
29 */
30
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_syscall.h"       // VG_(strerror)
53 #include "pub_core_mach.h"
54 #include "pub_core_machine.h"
55 #include "pub_core_mallocfree.h"
56 #include "pub_core_options.h"
57 #include "pub_core_debuginfo.h"
58 #include "pub_core_redir.h"
59 #include "pub_core_scheduler.h"
60 #include "pub_core_seqmatch.h"      // For VG_(string_match)
61 #include "pub_core_signals.h"
62 #include "pub_core_stacks.h"        // For VG_(register_stack)
63 #include "pub_core_syswrap.h"
64 #include "pub_core_tooliface.h"
65 #include "pub_core_translate.h"     // For VG_(translate)
66 #include "pub_core_trampoline.h"
67 #include "pub_core_transtab.h"
68 #include "pub_tool_inner.h"
69 #if defined(ENABLE_INNER_CLIENT_REQUEST)
70 #include "valgrind.h"
71 #endif 
72
73
74 /*====================================================================*/
75 /*=== Counters, for profiling purposes only                        ===*/
76 /*====================================================================*/
77
78 static void print_all_stats ( void )
79 {
80    VG_(print_translation_stats)();
81    VG_(print_tt_tc_stats)();
82    VG_(print_scheduler_stats)();
83    VG_(print_ExeContext_stats)();
84    VG_(print_errormgr_stats)();
85
86    // Memory stats
87    if (VG_(clo_verbosity) > 2) {
88       VG_(message)(Vg_DebugMsg, "\n");
89       VG_(message)(Vg_DebugMsg, 
90          "------ Valgrind's internal memory use stats follow ------\n" );
91       VG_(sanity_check_malloc_all)();
92       VG_(message)(Vg_DebugMsg, "------\n" );
93       VG_(print_all_arena_stats)();
94       VG_(message)(Vg_DebugMsg, "\n");
95    }
96 }
97
98
99 /*====================================================================*/
100 /*=== Command-line: variables, processing, etc                     ===*/
101 /*====================================================================*/
102
103 // See pub_{core,tool}_options.h for explanations of all these.
104
105 static void usage_NORETURN ( Bool debug_help )
106 {
107    /* 'usage1' contains a %s 
108       - for the name of the GDB executable
109       - for the name of vgdb's path prefix
110       which must be supplied when they are VG_(printf)'d. */
111    const HChar* usage1 = 
112 "usage: valgrind [options] prog-and-args\n"
113 "\n"
114 "  tool-selection option, with default in [ ]:\n"
115 "    --tool=<name>             use the Valgrind tool named <name> [memcheck]\n"
116 "\n"
117 "  basic user options for all Valgrind tools, with defaults in [ ]:\n"
118 "    -h --help                 show this message\n"
119 "    --help-debug              show this message, plus debugging options\n"
120 "    --version                 show version\n"
121 "    -q --quiet                run silently; only print error msgs\n"
122 "    -v --verbose              be more verbose -- show misc extra info\n"
123 "    --trace-children=no|yes   Valgrind-ise child processes (follow execve)? [no]\n"
124 "    --trace-children-skip=patt1,patt2,...    specifies a list of executables\n"
125 "                              that --trace-children=yes should not trace into\n"
126 "    --trace-children-skip-by-arg=patt1,patt2,...   same as --trace-children-skip=\n"
127 "                              but check the argv[] entries for children, rather\n"
128 "                              than the exe name, to make a follow/no-follow decision\n"
129 "    --child-silent-after-fork=no|yes omit child output between fork & exec? [no]\n"
130 "    --vgdb=no|yes|full        activate gdbserver? [yes]\n"
131 "                              full is slower but provides precise watchpoint/step\n"
132 "    --vgdb-error=<number>     invoke gdbserver after <number> errors [%d]\n"
133 "                              to get started quickly, use --vgdb-error=0\n"
134 "                              and follow the on-screen directions\n"
135 "    --track-fds=no|yes        track open file descriptors? [no]\n"
136 "    --time-stamp=no|yes       add timestamps to log messages? [no]\n"
137 "    --log-fd=<number>         log messages to file descriptor [2=stderr]\n"
138 "    --log-file=<file>         log messages to <file>\n"
139 "    --log-socket=ipaddr:port  log messages to socket ipaddr:port\n"
140 "\n"
141 "  user options for Valgrind tools that report errors:\n"
142 "    --xml=yes                 emit error output in XML (some tools only)\n"
143 "    --xml-fd=<number>         XML output to file descriptor\n"
144 "    --xml-file=<file>         XML output to <file>\n"
145 "    --xml-socket=ipaddr:port  XML output to socket ipaddr:port\n"
146 "    --xml-user-comment=STR    copy STR verbatim into XML output\n"
147 "    --demangle=no|yes         automatically demangle C++ names? [yes]\n"
148 "    --num-callers=<number>    show <number> callers in stack traces [12]\n"
149 "    --error-limit=no|yes      stop showing new errors if too many? [yes]\n"
150 "    --error-exitcode=<number> exit code to return if errors found [0=disable]\n"
151 "    --show-below-main=no|yes  continue stack traces below main() [no]\n"
152 "    --suppressions=<filename> suppress errors described in <filename>\n"
153 "    --gen-suppressions=no|yes|all    print suppressions for errors? [no]\n"
154 "    --db-attach=no|yes        start debugger when errors detected? [no]\n"
155 "    --db-command=<command>    command to start debugger [%s -nw %%f %%p]\n"
156 "    --input-fd=<number>       file descriptor for input [0=stdin]\n"
157 "    --dsymutil=no|yes         run dsymutil on Mac OS X when helpful? [no]\n"
158 "    --max-stackframe=<number> assume stack switch for SP changes larger\n"
159 "                              than <number> bytes [2000000]\n"
160 "    --main-stacksize=<number> set size of main thread's stack (in bytes)\n"
161 "                              [use current 'ulimit' value]\n"
162 "\n"
163 "  user options for Valgrind tools that replace malloc:\n"
164 "    --alignment=<number>      set minimum alignment of heap allocations [%s]\n"
165 "    --redzone-size=<number>   set minimum size of redzones added before/after\n"
166 "                              heap blocks (in bytes). [%s]\n"
167 "\n"
168 "  uncommon user options for all Valgrind tools:\n"
169 "    --fullpath-after=         (with nothing after the '=')\n"
170 "                              show full source paths in call stacks\n"
171 "    --fullpath-after=string   like --fullpath-after=, but only show the\n"
172 "                              part of the path after 'string'.  Allows removal\n"
173 "                              of path prefixes.  Use this flag multiple times\n"
174 "                              to specify a set of prefixes to remove.\n"
175 "    --smc-check=none|stack|all|all-non-file [stack]\n"
176 "                              checks for self-modifying code: none, only for\n"
177 "                              code found in stacks, for all code, or for all\n"
178 "                              code except that from file-backed mappings\n"
179 "    --read-var-info=yes|no    read debug info on stack and global variables\n"
180 "                              and use it to print better error messages in\n"
181 "                              tools that make use of it (Memcheck, Helgrind,\n"
182 "                              DRD) [no]\n"
183 "    --vgdb-poll=<number>      gdbserver poll max every <number> basic blocks [%d] \n"
184 "    --vgdb-shadow-registers=no|yes   let gdb see the shadow registers [no]\n"
185 "    --vgdb-prefix=<prefix>    prefix for vgdb FIFOs [%s]\n"
186 "    --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]\n"
187 "    --sim-hints=hint1,hint2,...  known hints:\n"
188 "                                 lax-ioctls, enable-outer, fuse-compatible [none]\n"
189 "    --fair-sched=no|yes|try   schedule threads fairly on multicore systems [no]\n"
190 "    --kernel-variant=variant1,variant2,...  known variants: bproc [none]\n"
191 "                              handle non-standard kernel variants\n"
192 "    --show-emwarns=no|yes     show warnings about emulation limits? [no]\n"
193 "    --require-text-symbol=:sonamepattern:symbolpattern    abort run if the\n"
194 "                              stated shared object doesn't have the stated\n"
195 "                              text symbol.  Patterns can contain ? and *.\n"
196 "    --soname-synonyms=syn1=pattern1,syn2=pattern2,... synonym soname\n"
197 "              specify patterns for function wrapping or replacement.\n"
198 "              To use a non-libc malloc library that is\n"
199 "                  in the main exe:  --soname-synonyms=somalloc=NONE\n"
200 "                  in libxyzzy.so:   --soname-synonyms=somalloc=libxyzzy.so\n"
201 "\n";
202
203    const HChar* usage2 = 
204 "\n"
205 "  debugging options for all Valgrind tools:\n"
206 "    -d                        show verbose debugging output\n"
207 "    --stats=no|yes            show tool and core statistics [no]\n"
208 "    --sanity-level=<number>   level of sanity checking to do [1]\n"
209 "    --trace-flags=<XXXXXXXX>   show generated code? (X = 0|1) [00000000]\n"
210 "    --profile-flags=<XXXXXXXX> ditto, but for profiling (X = 0|1) [00000000]\n"
211 "    --trace-notbelow=<number> only show BBs above <number> [999999999]\n"
212 "    --trace-notabove=<number> only show BBs below <number> [0]\n"
213 "    --trace-syscalls=no|yes   show all system calls? [no]\n"
214 "    --trace-signals=no|yes    show signal handling details? [no]\n"
215 "    --trace-symtab=no|yes     show symbol table details? [no]\n"
216 "    --trace-symtab-patt=<patt> limit debuginfo tracing to obj name <patt>\n"
217 "    --trace-cfi=no|yes        show call-frame-info details? [no]\n"
218 "    --debug-dump=syms         mimic /usr/bin/readelf --syms\n"
219 "    --debug-dump=line         mimic /usr/bin/readelf --debug-dump=line\n"
220 "    --debug-dump=frames       mimic /usr/bin/readelf --debug-dump=frames\n"
221 "    --trace-redir=no|yes      show redirection details? [no]\n"
222 "    --trace-sched=no|yes      show thread scheduler details? [no]\n"
223 "    --profile-heap=no|yes     profile Valgrind's own space use\n"
224 "    --core-redzone-size=<number>  set minimum size of redzones added before/after\n"
225 "                              heap blocks allocated for Valgrind internal use (in bytes) [4]\n"
226 "    --wait-for-gdb=yes|no     pause on startup to wait for gdb attach\n"
227 "    --sym-offsets=yes|no      show syms in form 'name+offset' ? [no]\n"
228 "    --command-line-only=no|yes  only use command line options [no]\n"
229 "\n"
230 "  Vex options for all Valgrind tools:\n"
231 "    --vex-iropt-verbosity=<0..9>           [0]\n"
232 "    --vex-iropt-level=<0..2>               [2]\n"
233 "    --vex-iropt-register-updates=sp-at-mem-access\n"
234 "                                |unwindregs-at-mem-access\n"
235 "                                |allregs-at-mem-access\n"
236 "                                |allregs-at-each-insn  [unwindregs-at-mem-access]\n"
237 "    --vex-iropt-unroll-thresh=<0..400>     [120]\n"
238 "    --vex-guest-max-insns=<1..100>         [50]\n"
239 "    --vex-guest-chase-thresh=<0..99>       [10]\n"
240 "    --vex-guest-chase-cond=no|yes          [no]\n"
241 "    --trace-flags and --profile-flags values (omit the middle space):\n"
242 "       1000 0000   show conversion into IR\n"
243 "       0100 0000   show after initial opt\n"
244 "       0010 0000   show after instrumentation\n"
245 "       0001 0000   show after second opt\n"
246 "       0000 1000   show after tree building\n"
247 "       0000 0100   show selecting insns\n"
248 "       0000 0010   show after reg-alloc\n"
249 "       0000 0001   show final assembly\n"
250 "      (Nb: you need --trace-notbelow and/or --trace-notabove with --trace-flags for full details)\n"
251 "\n"
252 "  debugging options for Valgrind tools that report errors\n"
253 "    --dump-error=<number>     show translation for basic block associated\n"
254 "                              with <number>'th error context [0=show none]\n"
255 "\n"
256 "  debugging options for Valgrind tools that replace malloc:\n"
257 "    --trace-malloc=no|yes     show client malloc details? [no]\n"
258 "\n";
259
260    const HChar* usage3 =
261 "\n"
262 "  Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc\n"
263 "\n"
264 "  %s is %s\n"
265 "  Valgrind is Copyright (C) 2000-2012, and GNU GPL'd, by Julian Seward et al.\n"
266 "  LibVEX is Copyright (C) 2004-2012, and GNU GPL'd, by OpenWorks LLP et al.\n"
267 "\n"
268 "  Bug reports, feedback, admiration, abuse, etc, to: %s.\n"
269 "\n";
270
271    const HChar* gdb_path = GDB_PATH;
272    Char default_alignment[30];
273    Char default_redzone_size[30];
274
275    // Ensure the message goes to stdout
276    VG_(log_output_sink).fd = 1;
277    VG_(log_output_sink).is_socket = False;
278
279    if (VG_(needs).malloc_replacement) {
280       VG_(sprintf)(default_alignment,    "%d",  VG_MIN_MALLOC_SZB);
281       VG_(sprintf)(default_redzone_size, "%lu", VG_(tdict).tool_client_redzone_szB);
282    } else {
283       VG_(strcpy)(default_alignment,    "not used by this tool");
284       VG_(strcpy)(default_redzone_size, "not used by this tool");
285    }
286    /* 'usage1' a type as described after each arg. */
287    VG_(printf)(usage1, 
288                VG_(clo_vgdb_error)        /* int */,
289                gdb_path                   /* char* */,
290                default_alignment          /* char* */,
291                default_redzone_size       /* char* */,
292                VG_(clo_vgdb_poll)         /* int */,
293                VG_(vgdb_prefix_default)() /* char* */
294                ); 
295    if (VG_(details).name) {
296       VG_(printf)("  user options for %s:\n", VG_(details).name);
297       if (VG_(needs).command_line_options)
298          VG_TDICT_CALL(tool_print_usage);
299       else
300          VG_(printf)("    (none)\n");
301    }
302    if (debug_help) {
303       VG_(printf)("%s", usage2);
304
305       if (VG_(details).name) {
306          VG_(printf)("  debugging options for %s:\n", VG_(details).name);
307       
308          if (VG_(needs).command_line_options)
309             VG_TDICT_CALL(tool_print_debug_usage);
310          else
311             VG_(printf)("    (none)\n");
312       }
313    }
314    VG_(printf)(usage3, VG_(details).name, VG_(details).copyright_author,
315                VG_BUGS_TO);
316    VG_(exit)(0);
317 }
318
319
320 /* Peer at previously set up VG_(args_for_valgrind) and do some
321    minimal command line processing that must happen early on:
322
323    - show the version string, if requested (-v)
324    - extract any request for help (--help, -h, --help-debug)
325    - get the toolname (--tool=)
326    - set VG_(clo_max_stackframe) (--max-stackframe=)
327    - set VG_(clo_main_stacksize) (--main-stacksize=)
328    - set VG_(clo_sim_hints) (--sim-hints=)
329
330    That's all it does.  The main command line processing is done below
331    by main_process_cmd_line_options.  Note that
332    main_process_cmd_line_options has to handle but ignore the ones we
333    have handled here.
334 */
335 static void early_process_cmd_line_options ( /*OUT*/Int* need_help,
336                                              /*OUT*/HChar** tool )
337 {
338    UInt   i;
339    HChar* str;
340
341    vg_assert( VG_(args_for_valgrind) );
342
343    /* parse the options we have (only the options we care about now) */
344    for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
345
346       str = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
347       vg_assert(str);
348
349       // Nb: the version string goes to stdout.
350       if VG_XACT_CLO(str, "--version", VG_(log_output_sink).fd, 1) {
351          VG_(log_output_sink).is_socket = False;
352          VG_(printf)("valgrind-" VERSION "\n");
353          VG_(exit)(0);
354       }
355       else if VG_XACT_CLO(str, "--help", *need_help, *need_help+1) {}
356       else if VG_XACT_CLO(str, "-h",     *need_help, *need_help+1) {}
357
358       else if VG_XACT_CLO(str, "--help-debug", *need_help, *need_help+2) {}
359
360       // The tool has already been determined, but we need to know the name
361       // here.
362       else if VG_STR_CLO(str, "--tool", *tool) {} 
363
364       // Set up VG_(clo_max_stackframe) and VG_(clo_main_stacksize).
365       // These are needed by VG_(ii_create_image), which happens
366       // before main_process_cmd_line_options().
367       else if VG_INT_CLO(str, "--max-stackframe", VG_(clo_max_stackframe)) {}
368       else if VG_INT_CLO(str, "--main-stacksize", VG_(clo_main_stacksize)) {}
369
370       // Set up VG_(clo_sim_hints). This is needed a.o. for an inner
371       // running in an outer, to have "no-inner-prefix" enabled
372       // as early as possible.
373       else if VG_STR_CLO (str, "--sim-hints",     VG_(clo_sim_hints)) {}
374    }
375 }
376
377 /* The main processing for command line options.  See comments above
378    on early_process_cmd_line_options.
379
380    Comments on how the logging options are handled:
381
382    User can specify:
383       --log-fd=      for a fd to write to (default setting, fd = 2)
384       --log-file=    for a file name to write to
385       --log-socket=  for a socket to write to
386
387    As a result of examining these and doing relevant socket/file
388    opening, a final fd is established.  This is stored in
389    VG_(log_output_sink) in m_libcprint.  Also, if --log-file=STR was
390    specified, then STR, after expansion of %p and %q templates within
391    it, is stored in VG_(clo_log_fname_expanded), in m_options, just in
392    case anybody wants to know what it is.
393
394    When printing, VG_(log_output_sink) is consulted to find the
395    fd to send output to.
396
397    Exactly analogous actions are undertaken for the XML output
398    channel, with the one difference that the default fd is -1, meaning
399    the channel is disabled by default.
400 */
401 static
402 void main_process_cmd_line_options ( /*OUT*/Bool* logging_to_fd,
403                                      /*OUT*/Char** xml_fname_unexpanded,
404                                      const HChar* toolname )
405 {
406    // VG_(clo_log_fd) is used by all the messaging.  It starts as 2 (stderr)
407    // and we cannot change it until we know what we are changing it to is
408    // ok.  So we have tmp_log_fd to hold the tmp fd prior to that point.
409    SysRes sres;
410    Int    i, tmp_log_fd, tmp_xml_fd;
411    Int    toolname_len = VG_(strlen)(toolname);
412    Char*  tmp_str;         // Used in a couple of places.
413    enum {
414       VgLogTo_Fd,
415       VgLogTo_File,
416       VgLogTo_Socket
417    } log_to = VgLogTo_Fd,   // Where is logging output to be sent?
418      xml_to = VgLogTo_Fd;   // Where is XML output to be sent?
419
420    /* Temporarily holds the string STR specified with
421       --{log,xml}-{name,socket}=STR.  'fs' stands for
422       file-or-socket. */
423    Char* log_fsname_unexpanded = NULL;
424    Char* xml_fsname_unexpanded = NULL;
425
426    /* Log to stderr by default, but usage message goes to stdout.  XML
427       output is initially disabled. */
428    tmp_log_fd = 2; 
429    tmp_xml_fd = -1;
430  
431    /* Check for sane path in ./configure --prefix=... */
432    if (VG_LIBDIR[0] != '/') 
433       VG_(err_config_error)("Please use absolute paths in "
434                             "./configure --prefix=... or --libdir=...\n");
435
436    vg_assert( VG_(args_for_valgrind) );
437
438    /* BEGIN command-line processing loop */
439
440    for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
441
442       HChar* arg   = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
443       HChar* colon = arg;
444
445       // Look for a colon in the option name.
446       while (*colon && *colon != ':' && *colon != '=')
447          colon++;
448
449       // Does it have the form "--toolname:foo"?  We have to do it at the start
450       // in case someone has combined a prefix with a core-specific option,
451       // eg.  "--memcheck:verbose".
452       if (*colon == ':') {
453          if (VG_STREQN(2,            arg,                "--") && 
454              VG_STREQN(toolname_len, arg+2,              toolname) &&
455              VG_STREQN(1,            arg+2+toolname_len, ":"))
456          {
457             // Prefix matches, convert "--toolname:foo" to "--foo".
458             // Two things to note:
459             // - We cannot modify the option in-place.  If we did, and then
460             //   a child was spawned with --trace-children=yes, the
461             //   now-non-prefixed option would be passed and could screw up
462             //   the child.
463             // - We create copies, and never free them.  Why?  Non-prefixed
464             //   options hang around forever, so tools need not make copies
465             //   of strings within them.  We need to have the same behaviour
466             //   for prefixed options.  The pointer to the copy will be lost
467             //   once we leave this function (although a tool may keep a
468             //   pointer into it), but the space wasted is insignificant.
469             //   (In bug #142197, the copies were being freed, which caused
470             //   problems for tools that reasonably assumed that arguments
471             //   wouldn't disappear on them.)
472             if (0)
473                VG_(printf)("tool-specific arg: %s\n", arg);
474             arg = VG_(strdup)("main.mpclo.1", arg + toolname_len + 1);
475             arg[0] = '-';
476             arg[1] = '-';
477
478          } else {
479             // prefix doesn't match, skip to next arg
480             continue;
481          }
482       }
483       
484       /* Ignore these options - they've already been handled */
485       if      VG_STREQN( 7, arg, "--tool=")              {}
486       else if VG_STREQN(20, arg, "--command-line-only=") {}
487       else if VG_STREQ(     arg, "--")                   {}
488       else if VG_STREQ(     arg, "-d")                   {}
489       else if VG_STREQN(17, arg, "--max-stackframe=")    {}
490       else if VG_STREQN(17, arg, "--main-stacksize=")    {}
491       else if VG_STREQN(12, arg,  "--sim-hints=")        {}
492       else if VG_STREQN(15, arg, "--profile-heap=")      {}
493       else if VG_STREQN(20, arg, "--core-redzone-size=") {}
494       else if VG_STREQN(15, arg, "--redzone-size=")      {}
495
496       /* Obsolete options. Report an error and exit */
497       else if VG_STREQN(34, arg, "--vex-iropt-precise-memory-exns=no") {
498          VG_(fmsg_bad_option)
499             (arg,
500              "--vex-iropt-precise-memory-exns is obsolete\n"
501              "Use --vex-iropt-register-updates=unwindregs-at-mem-access instead\n");
502       }
503       else if VG_STREQN(35, arg, "--vex-iropt-precise-memory-exns=yes") {
504          VG_(fmsg_bad_option)
505             (arg,
506              "--vex-iropt-precise-memory-exns is obsolete\n"
507              "Use --vex-iropt-register-updates=allregs-at-mem-access instead\n"
508              " (or --vex-iropt-register-updates=allregs-at-each-insn)\n");
509       }
510
511       // These options are new.
512       else if (VG_STREQ(arg, "-v") ||
513                VG_STREQ(arg, "--verbose"))
514          VG_(clo_verbosity)++;
515
516       else if (VG_STREQ(arg, "-q") ||
517                VG_STREQ(arg, "--quiet"))
518          VG_(clo_verbosity)--;
519
520       else if VG_BOOL_CLO(arg, "--stats",          VG_(clo_stats)) {}
521       else if VG_BOOL_CLO(arg, "--xml",            VG_(clo_xml))
522          VG_(debugLog_setXml)(VG_(clo_xml));
523
524       else if VG_XACT_CLO(arg, "--vgdb=no",        VG_(clo_vgdb), Vg_VgdbNo) {}
525       else if VG_XACT_CLO(arg, "--vgdb=yes",       VG_(clo_vgdb), Vg_VgdbYes) {}
526       else if VG_XACT_CLO(arg, "--vgdb=full",      VG_(clo_vgdb), Vg_VgdbFull) {
527          /* automatically updates register values at each insn
528             with --vgdb=full */
529          VG_(clo_vex_control).iropt_register_updates 
530             = VexRegUpdAllregsAtEachInsn;
531       }
532       else if VG_INT_CLO (arg, "--vgdb-poll",      VG_(clo_vgdb_poll)) {}
533       else if VG_INT_CLO (arg, "--vgdb-error",     VG_(clo_vgdb_error)) {}
534       else if VG_STR_CLO (arg, "--vgdb-prefix",    VG_(clo_vgdb_prefix)) {}
535       else if VG_BOOL_CLO(arg, "--vgdb-shadow-registers",
536                             VG_(clo_vgdb_shadow_registers)) {}
537       else if VG_BOOL_CLO(arg, "--db-attach",      VG_(clo_db_attach)) {}
538       else if VG_BOOL_CLO(arg, "--demangle",       VG_(clo_demangle)) {}
539       else if VG_STR_CLO (arg, "--soname-synonyms",VG_(clo_soname_synonyms)) {}
540       else if VG_BOOL_CLO(arg, "--error-limit",    VG_(clo_error_limit)) {}
541       else if VG_INT_CLO (arg, "--error-exitcode", VG_(clo_error_exitcode)) {}
542       else if VG_BOOL_CLO(arg, "--show-emwarns",   VG_(clo_show_emwarns)) {}
543
544       else if VG_BOOL_CLO(arg, "--run-libc-freeres", VG_(clo_run_libc_freeres)) {}
545       else if VG_BOOL_CLO(arg, "--show-below-main",  VG_(clo_show_below_main)) {}
546       else if VG_BOOL_CLO(arg, "--time-stamp",       VG_(clo_time_stamp)) {}
547       else if VG_BOOL_CLO(arg, "--track-fds",        VG_(clo_track_fds)) {}
548       else if VG_BOOL_CLO(arg, "--trace-children",   VG_(clo_trace_children)) {}
549       else if VG_BOOL_CLO(arg, "--child-silent-after-fork",
550                             VG_(clo_child_silent_after_fork)) {}
551       else if VG_STR_CLO(arg, "--fair-sched",        tmp_str) {
552          if (VG_(strcmp)(tmp_str, "yes") == 0)
553             VG_(clo_fair_sched) = enable_fair_sched;
554          else if (VG_(strcmp)(tmp_str, "try") == 0)
555             VG_(clo_fair_sched) = try_fair_sched;
556          else if (VG_(strcmp)(tmp_str, "no") == 0)
557             VG_(clo_fair_sched) = disable_fair_sched;
558          else
559             VG_(fmsg_bad_option)(arg, "");
560
561       }
562       else if VG_BOOL_CLO(arg, "--trace-sched",      VG_(clo_trace_sched)) {}
563       else if VG_BOOL_CLO(arg, "--trace-signals",    VG_(clo_trace_signals)) {}
564       else if VG_BOOL_CLO(arg, "--trace-symtab",     VG_(clo_trace_symtab)) {}
565       else if VG_STR_CLO (arg, "--trace-symtab-patt", VG_(clo_trace_symtab_patt)) {}
566       else if VG_BOOL_CLO(arg, "--trace-cfi",        VG_(clo_trace_cfi)) {}
567       else if VG_XACT_CLO(arg, "--debug-dump=syms",  VG_(clo_debug_dump_syms),
568                                                      True) {}
569       else if VG_XACT_CLO(arg, "--debug-dump=line",  VG_(clo_debug_dump_line),
570                                                      True) {}
571       else if VG_XACT_CLO(arg, "--debug-dump=frames",
572                                VG_(clo_debug_dump_frames), True) {}
573       else if VG_BOOL_CLO(arg, "--trace-redir",      VG_(clo_trace_redir)) {}
574
575       else if VG_BOOL_CLO(arg, "--trace-syscalls",   VG_(clo_trace_syscalls)) {}
576       else if VG_BOOL_CLO(arg, "--wait-for-gdb",     VG_(clo_wait_for_gdb)) {}
577       else if VG_STR_CLO (arg, "--db-command",       VG_(clo_db_command)) {}
578       else if VG_BOOL_CLO(arg, "--sym-offsets",      VG_(clo_sym_offsets)) {}
579       else if VG_BOOL_CLO(arg, "--read-var-info",    VG_(clo_read_var_info)) {}
580
581       else if VG_INT_CLO (arg, "--dump-error",       VG_(clo_dump_error))   {}
582       else if VG_INT_CLO (arg, "--input-fd",         VG_(clo_input_fd))     {}
583       else if VG_INT_CLO (arg, "--sanity-level",     VG_(clo_sanity_level)) {}
584       else if VG_BINT_CLO(arg, "--num-callers",      VG_(clo_backtrace_size), 1,
585                                                      VG_DEEPEST_BACKTRACE) {}
586
587       else if VG_XACT_CLO(arg, "--smc-check=none",  VG_(clo_smc_check),
588                                                     Vg_SmcNone);
589       else if VG_XACT_CLO(arg, "--smc-check=stack", VG_(clo_smc_check),
590                                                     Vg_SmcStack);
591       else if VG_XACT_CLO(arg, "--smc-check=all",   VG_(clo_smc_check),
592                                                     Vg_SmcAll);
593       else if VG_XACT_CLO(arg, "--smc-check=all-non-file",
594                                                     VG_(clo_smc_check),
595                                                     Vg_SmcAllNonFile);
596
597       else if VG_STR_CLO (arg, "--kernel-variant",  VG_(clo_kernel_variant)) {}
598
599       else if VG_BOOL_CLO(arg, "--dsymutil",        VG_(clo_dsymutil)) {}
600
601       else if VG_STR_CLO (arg, "--trace-children-skip",
602                                VG_(clo_trace_children_skip)) {}
603       else if VG_STR_CLO (arg, "--trace-children-skip-by-arg",
604                                VG_(clo_trace_children_skip_by_arg)) {}
605
606       else if VG_BINT_CLO(arg, "--vex-iropt-verbosity",
607                        VG_(clo_vex_control).iropt_verbosity, 0, 10) {}
608       else if VG_BINT_CLO(arg, "--vex-iropt-level",
609                        VG_(clo_vex_control).iropt_level, 0, 2) {}
610       else if VG_XACT_CLO(arg, 
611                        "--vex-iropt-register-updates=sp-at-mem-access",
612                        VG_(clo_vex_control).iropt_register_updates,
613                        VexRegUpdSpAtMemAccess);
614       else if VG_XACT_CLO(arg, 
615                        "--vex-iropt-register-updates=unwindregs-at-mem-access",
616                        VG_(clo_vex_control).iropt_register_updates,
617                        VexRegUpdUnwindregsAtMemAccess);
618       else if VG_XACT_CLO(arg, 
619                        "--vex-iropt-register-updates=allregs-at-mem-access",
620                        VG_(clo_vex_control).iropt_register_updates,
621                        VexRegUpdAllregsAtMemAccess);
622       else if VG_XACT_CLO(arg, 
623                        "--vex-iropt-register-updates=allregs-at-each-insn",
624                        VG_(clo_vex_control).iropt_register_updates,
625                        VexRegUpdAllregsAtEachInsn);
626       else if VG_BINT_CLO(arg, "--vex-iropt-unroll-thresh",
627                        VG_(clo_vex_control).iropt_unroll_thresh, 0, 400) {}
628       else if VG_BINT_CLO(arg, "--vex-guest-max-insns",
629                        VG_(clo_vex_control).guest_max_insns, 1, 100) {}
630       else if VG_BINT_CLO(arg, "--vex-guest-chase-thresh",
631                        VG_(clo_vex_control).guest_chase_thresh, 0, 99) {}
632       else if VG_BOOL_CLO(arg, "--vex-guest-chase-cond",
633                        VG_(clo_vex_control).guest_chase_cond) {}
634
635       else if VG_INT_CLO(arg, "--log-fd", tmp_log_fd) {
636          log_to = VgLogTo_Fd;
637          log_fsname_unexpanded = NULL;
638       }
639       else if VG_INT_CLO(arg, "--xml-fd", tmp_xml_fd) {
640          xml_to = VgLogTo_Fd;
641          xml_fsname_unexpanded = NULL;
642       }
643
644       else if VG_STR_CLO(arg, "--log-file", log_fsname_unexpanded) {
645          log_to = VgLogTo_File;
646       }
647       else if VG_STR_CLO(arg, "--xml-file", xml_fsname_unexpanded) {
648          xml_to = VgLogTo_File;
649       }
650  
651       else if VG_STR_CLO(arg, "--log-socket", log_fsname_unexpanded) {
652          log_to = VgLogTo_Socket;
653       }
654       else if VG_STR_CLO(arg, "--xml-socket", xml_fsname_unexpanded) {
655          xml_to = VgLogTo_Socket;
656       }
657
658       else if VG_STR_CLO(arg, "--xml-user-comment",
659                               VG_(clo_xml_user_comment)) {}
660
661       else if VG_STR_CLO(arg, "--suppressions", tmp_str) {
662          if (VG_(clo_n_suppressions) >= VG_CLO_MAX_SFILES) {
663             VG_(fmsg_bad_option)(arg,
664                "Too many suppression files specified.\n"
665                "Increase VG_CLO_MAX_SFILES and recompile.\n");
666          }
667          VG_(clo_suppressions)[VG_(clo_n_suppressions)] = tmp_str;
668          VG_(clo_n_suppressions)++;
669       }
670
671       else if VG_STR_CLO (arg, "--fullpath-after", tmp_str) {
672          if (VG_(clo_n_fullpath_after) >= VG_CLO_MAX_FULLPATH_AFTER) {
673             VG_(fmsg_bad_option)(arg,
674                "Too many --fullpath-after= specifications.\n"
675                "Increase VG_CLO_MAX_FULLPATH_AFTER and recompile.\n");
676          }
677          VG_(clo_fullpath_after)[VG_(clo_n_fullpath_after)] = tmp_str;
678          VG_(clo_n_fullpath_after)++;
679       }
680
681       else if VG_STR_CLO(arg, "--require-text-symbol", tmp_str) {
682          if (VG_(clo_n_req_tsyms) >= VG_CLO_MAX_REQ_TSYMS) {
683             VG_(fmsg_bad_option)(arg,
684                "Too many --require-text-symbol= specifications.\n"
685                "Increase VG_CLO_MAX_REQ_TSYMS and recompile.\n");
686          }
687          /* String needs to be of the form C?*C?*, where C is any
688             character, but is the same both times.  Having it in this
689             form facilitates finding the boundary between the sopatt
690             and the fnpatt just by looking for the second occurrence
691             of C, without hardwiring any assumption about what C
692             is. */
693          Char patt[7];
694          Bool ok = True;
695          ok = tmp_str && VG_(strlen)(tmp_str) > 0;
696          if (ok) {
697            patt[0] = patt[3] = tmp_str[0];
698            patt[1] = patt[4] = '?';
699            patt[2] = patt[5] = '*';
700            patt[6] = 0;
701            ok = VG_(string_match)(patt, tmp_str);
702          }
703          if (!ok) {
704             VG_(fmsg_bad_option)(arg,
705                "Invalid --require-text-symbol= specification.\n");
706          }
707          VG_(clo_req_tsyms)[VG_(clo_n_req_tsyms)] = tmp_str;
708          VG_(clo_n_req_tsyms)++;
709       }
710
711       /* "stuvwxyz" --> stuvwxyz (binary) */
712       else if VG_STR_CLO(arg, "--trace-flags", tmp_str) {
713          Int j;
714    
715          if (8 != VG_(strlen)(tmp_str)) {
716             VG_(fmsg_bad_option)(arg,
717                "--trace-flags argument must have 8 digits\n");
718          }
719          for (j = 0; j < 8; j++) {
720             if      ('0' == tmp_str[j]) { /* do nothing */ }
721             else if ('1' == tmp_str[j]) VG_(clo_trace_flags) |= (1 << (7-j));
722             else {
723                VG_(fmsg_bad_option)(arg,
724                   "--trace-flags argument can only contain 0s and 1s\n");
725             }
726          }
727       }
728
729       /* "stuvwxyz" --> stuvwxyz (binary) */
730       else if VG_STR_CLO(arg, "--profile-flags", tmp_str) {
731          Int j;
732    
733          if (8 != VG_(strlen)(tmp_str)) {
734             VG_(fmsg_bad_option)(arg, 
735                "--profile-flags argument must have 8 digits\n");
736          }
737          for (j = 0; j < 8; j++) {
738             if      ('0' == tmp_str[j]) { /* do nothing */ }
739             else if ('1' == tmp_str[j]) VG_(clo_profile_flags) |= (1 << (7-j));
740             else {
741                VG_(fmsg_bad_option)(arg,
742                   "--profile-flags argument can only contain 0s and 1s\n");
743             }
744          }
745       }
746
747       else if VG_INT_CLO (arg, "--trace-notbelow", VG_(clo_trace_notbelow)) {}
748
749       else if VG_INT_CLO (arg, "--trace-notabove", VG_(clo_trace_notabove)) {}
750
751       else if VG_XACT_CLO(arg, "--gen-suppressions=no",
752                                VG_(clo_gen_suppressions), 0) {}
753       else if VG_XACT_CLO(arg, "--gen-suppressions=yes",
754                                VG_(clo_gen_suppressions), 1) {}
755       else if VG_XACT_CLO(arg, "--gen-suppressions=all",
756                                VG_(clo_gen_suppressions), 2) {}
757
758       else if ( ! VG_(needs).command_line_options
759              || ! VG_TDICT_CALL(tool_process_cmd_line_option, arg) ) {
760          VG_(fmsg_bad_option)(arg, "");
761       }
762    }
763
764    /* END command-line processing loop */
765
766    /* Determine the path prefix for vgdb */
767    if (VG_(clo_vgdb_prefix) == NULL)
768      VG_(clo_vgdb_prefix) = VG_(vgdb_prefix_default)();
769
770    /* Make VEX control parameters sane */
771
772    if (VG_(clo_vex_control).guest_chase_thresh
773        >= VG_(clo_vex_control).guest_max_insns)
774       VG_(clo_vex_control).guest_chase_thresh
775          = VG_(clo_vex_control).guest_max_insns - 1;
776
777    if (VG_(clo_vex_control).guest_chase_thresh < 0)
778       VG_(clo_vex_control).guest_chase_thresh = 0;
779
780    /* Check various option values */
781
782    if (VG_(clo_verbosity) < 0)
783       VG_(clo_verbosity) = 0;
784
785    if (VG_(clo_trace_notbelow) == -1) {
786      if (VG_(clo_trace_notabove) == -1) {
787        /* [] */
788        VG_(clo_trace_notbelow) = 2147483647;
789        VG_(clo_trace_notabove) = 0;
790      } else {
791        /* [0 .. notabove] */
792        VG_(clo_trace_notbelow) = 0;
793      }
794    } else {
795      if (VG_(clo_trace_notabove) == -1) {
796        /* [notbelow .. ]  */
797        VG_(clo_trace_notabove) = 2147483647;
798      } else {
799        /* [notbelow .. notabove]  */
800      }
801    }
802
803    VG_(dyn_vgdb_error) = VG_(clo_vgdb_error);
804
805    if (VG_(clo_gen_suppressions) > 0 && 
806        !VG_(needs).core_errors && !VG_(needs).tool_errors) {
807       VG_(fmsg_bad_option)("--gen-suppressions=yes",
808          "Can't use --gen-suppressions= with %s\n"
809          "because it doesn't generate errors.\n", VG_(details).name);
810    }
811
812    /* If XML output is requested, check that the tool actually
813       supports it. */
814    if (VG_(clo_xml) && !VG_(needs).xml_output) {
815       VG_(clo_xml) = False;
816       VG_(fmsg_bad_option)("--xml=yes",
817          "%s does not support XML output.\n", VG_(details).name); 
818       /*NOTREACHED*/
819    }
820
821    vg_assert( VG_(clo_gen_suppressions) >= 0 );
822    vg_assert( VG_(clo_gen_suppressions) <= 2 );
823
824    /* If we've been asked to emit XML, mash around various other
825       options so as to constrain the output somewhat, and to remove
826       any need for user input during the run. 
827    */
828    if (VG_(clo_xml)) {
829
830       /* We can't allow --gen-suppressions=yes, since that requires us
831          to print the error and then ask the user if she wants a
832          suppression for it, but in XML mode we won't print it until
833          we know whether we also need to print a suppression.  Hence a
834          circular dependency.  So disallow this.
835          (--gen-suppressions=all is still OK since we don't need any
836          user interaction in this case.) */
837       if (VG_(clo_gen_suppressions) == 1) {
838          VG_(fmsg_bad_option)(
839             "--xml=yes together with --gen-suppressions=yes",
840             "When --xml=yes is specified, --gen-suppressions=no\n"
841             "or --gen-suppressions=all is allowed, but not "
842             "--gen-suppressions=yes.\n");
843       }
844
845       /* We can't allow DB attaching (or we maybe could, but results
846          could be chaotic ..) since it requires user input.  Hence
847          disallow. */
848       if (VG_(clo_db_attach)) {
849          VG_(fmsg_bad_option)(
850             "--xml=yes together with --db-attach=yes",
851             "--db-attach=yes is not allowed with --xml=yes\n"
852             "because it would require user input.\n");
853       }
854
855       /* Disallow dump_error in XML mode; sounds like a recipe for
856          chaos.  No big deal; dump_error is a flag for debugging V
857          itself. */
858       if (VG_(clo_dump_error) > 0) {
859          VG_(fmsg_bad_option)("--xml=yes together with --dump-error", "");
860       }
861
862       /* Disable error limits (this might be a bad idea!) */
863       VG_(clo_error_limit) = False;
864       /* Disable emulation warnings */
865
866       /* Also, we want to set options for the leak checker, but that
867          will have to be done in Memcheck's flag-handling code, not
868          here. */
869    }
870
871    /* All non-logging-related options have been checked.  If the logging
872       option specified is ok, we can switch to it, as we know we won't
873       have to generate any other command-line-related error messages.
874       (So far we should be still attached to stderr, so we can show on
875       the terminal any problems to do with processing command line
876       opts.)
877    
878       So set up logging now.  After this is done, VG_(log_output_sink)
879       and (if relevant) VG_(xml_output_sink) should be connected to
880       whatever sink has been selected, and we indiscriminately chuck
881       stuff into it without worrying what the nature of it is.  Oh the
882       wonder of Unix streams. */
883
884    vg_assert(VG_(log_output_sink).fd == 2 /* stderr */);
885    vg_assert(VG_(log_output_sink).is_socket == False);
886    vg_assert(VG_(clo_log_fname_expanded) == NULL);
887
888    vg_assert(VG_(xml_output_sink).fd == -1 /* disabled */);
889    vg_assert(VG_(xml_output_sink).is_socket == False);
890    vg_assert(VG_(clo_xml_fname_expanded) == NULL);
891
892    /* --- set up the normal text output channel --- */
893
894    switch (log_to) {
895
896       case VgLogTo_Fd: 
897          vg_assert(log_fsname_unexpanded == NULL);
898          break;
899
900       case VgLogTo_File: {
901          Char* logfilename;
902
903          vg_assert(log_fsname_unexpanded != NULL);
904          vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
905
906          // Nb: we overwrite an existing file of this name without asking
907          // any questions.
908          logfilename = VG_(expand_file_name)("--log-file",
909                                              log_fsname_unexpanded);
910          sres = VG_(open)(logfilename, 
911                           VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC, 
912                           VKI_S_IRUSR|VKI_S_IWUSR);
913          if (!sr_isError(sres)) {
914             tmp_log_fd = sr_Res(sres);
915             VG_(clo_log_fname_expanded) = logfilename;
916          } else {
917             VG_(fmsg)("can't create log file '%s': %s\n", 
918                       logfilename, VG_(strerror)(sr_Err(sres)));
919             VG_(exit)(1);
920             /*NOTREACHED*/
921          }
922          break;
923       }
924
925       case VgLogTo_Socket: {
926          vg_assert(log_fsname_unexpanded != NULL);
927          vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
928          tmp_log_fd = VG_(connect_via_socket)( log_fsname_unexpanded );
929          if (tmp_log_fd == -1) {
930             VG_(fmsg)("Invalid --log-socket spec of '%s'\n",
931                       log_fsname_unexpanded);
932             VG_(exit)(1);
933             /*NOTREACHED*/
934          }
935          if (tmp_log_fd == -2) {
936             VG_(umsg)("failed to connect to logging server '%s'.\n"
937                       "Log messages will sent to stderr instead.\n",
938                       log_fsname_unexpanded ); 
939
940             /* We don't change anything here. */
941             vg_assert(VG_(log_output_sink).fd == 2);
942             tmp_log_fd = 2;
943          } else {
944             vg_assert(tmp_log_fd > 0);
945             VG_(log_output_sink).is_socket = True;
946          }
947          break;
948       }
949    }
950
951    /* --- set up the XML output channel --- */
952
953    switch (xml_to) {
954
955       case VgLogTo_Fd: 
956          vg_assert(xml_fsname_unexpanded == NULL);
957          break;
958
959       case VgLogTo_File: {
960          Char* xmlfilename;
961
962          vg_assert(xml_fsname_unexpanded != NULL);
963          vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
964
965          // Nb: we overwrite an existing file of this name without asking
966          // any questions.
967          xmlfilename = VG_(expand_file_name)("--xml-file",
968                                              xml_fsname_unexpanded);
969          sres = VG_(open)(xmlfilename, 
970                           VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC, 
971                           VKI_S_IRUSR|VKI_S_IWUSR);
972          if (!sr_isError(sres)) {
973             tmp_xml_fd = sr_Res(sres);
974             VG_(clo_xml_fname_expanded) = xmlfilename;
975             /* strdup here is probably paranoid overkill, but ... */
976             *xml_fname_unexpanded = VG_(strdup)( "main.mpclo.2",
977                                                  xml_fsname_unexpanded );
978          } else {
979             VG_(fmsg)("can't create XML file '%s': %s\n", 
980                       xmlfilename, VG_(strerror)(sr_Err(sres)));
981             VG_(exit)(1);
982             /*NOTREACHED*/
983          }
984          break;
985       }
986
987       case VgLogTo_Socket: {
988          vg_assert(xml_fsname_unexpanded != NULL);
989          vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
990          tmp_xml_fd = VG_(connect_via_socket)( xml_fsname_unexpanded );
991          if (tmp_xml_fd == -1) {
992             VG_(fmsg)("Invalid --xml-socket spec of '%s'\n",
993                       xml_fsname_unexpanded );
994             VG_(exit)(1);
995             /*NOTREACHED*/
996          }
997          if (tmp_xml_fd == -2) {
998             VG_(umsg)("failed to connect to XML logging server '%s'.\n"
999                       "XML output will sent to stderr instead.\n",
1000                       xml_fsname_unexpanded); 
1001             /* We don't change anything here. */
1002             vg_assert(VG_(xml_output_sink).fd == 2);
1003             tmp_xml_fd = 2;
1004          } else {
1005             vg_assert(tmp_xml_fd > 0);
1006             VG_(xml_output_sink).is_socket = True;
1007          }
1008          break;
1009       }
1010    }
1011
1012    /* If we've got this far, and XML mode was requested, but no XML
1013       output channel appears to have been specified, just stop.  We
1014       could continue, and XML output will simply vanish into nowhere,
1015       but that is likely to confuse the hell out of users, which is
1016       distinctly Ungood. */
1017    if (VG_(clo_xml) && tmp_xml_fd == -1) {
1018       VG_(fmsg_bad_option)(
1019           "--xml=yes, but no XML destination specified",
1020           "--xml=yes has been specified, but there is no XML output\n"
1021           "destination.  You must specify an XML output destination\n"
1022           "using --xml-fd, --xml-file or --xml-socket.\n"
1023       );
1024    }
1025
1026    // Finalise the output fds: the log fd ..
1027
1028    if (tmp_log_fd >= 0) {
1029       // Move log_fd into the safe range, so it doesn't conflict with
1030       // any app fds.
1031       tmp_log_fd = VG_(fcntl)(tmp_log_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
1032       if (tmp_log_fd < 0) {
1033          VG_(message)(Vg_UserMsg, "valgrind: failed to move logfile fd "
1034                                   "into safe range, using stderr\n");
1035          VG_(log_output_sink).fd = 2;   // stderr
1036          VG_(log_output_sink).is_socket = False;
1037       } else {
1038          VG_(log_output_sink).fd = tmp_log_fd;
1039          VG_(fcntl)(VG_(log_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
1040       }
1041    } else {
1042       // If they said --log-fd=-1, don't print anything.  Plausible for use in
1043       // regression testing suites that use client requests to count errors.
1044       VG_(log_output_sink).fd = -1;
1045       VG_(log_output_sink).is_socket = False;
1046    }
1047
1048    // Finalise the output fds: and the XML fd ..
1049
1050    if (tmp_xml_fd >= 0) {
1051       // Move xml_fd into the safe range, so it doesn't conflict with
1052       // any app fds.
1053       tmp_xml_fd = VG_(fcntl)(tmp_xml_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
1054       if (tmp_xml_fd < 0) {
1055          VG_(message)(Vg_UserMsg, "valgrind: failed to move XML file fd "
1056                                   "into safe range, using stderr\n");
1057          VG_(xml_output_sink).fd = 2;   // stderr
1058          VG_(xml_output_sink).is_socket = False;
1059       } else {
1060          VG_(xml_output_sink).fd = tmp_xml_fd;
1061          VG_(fcntl)(VG_(xml_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
1062       }
1063    } else {
1064       // If they said --xml-fd=-1, don't print anything.  Plausible for use in
1065       // regression testing suites that use client requests to count errors.
1066       VG_(xml_output_sink).fd = -1;
1067       VG_(xml_output_sink).is_socket = False;
1068    }
1069
1070    // Suppressions related stuff
1071
1072    if (VG_(clo_n_suppressions) < VG_CLO_MAX_SFILES-1 &&
1073        (VG_(needs).core_errors || VG_(needs).tool_errors)) {
1074       /* If we haven't reached the max number of suppressions, load
1075          the default one. */
1076       static const HChar default_supp[] = "default.supp";
1077       Int len = VG_(strlen)(VG_(libdir)) + 1 + sizeof(default_supp);
1078       Char *buf = VG_(arena_malloc)(VG_AR_CORE, "main.mpclo.3", len);
1079       VG_(sprintf)(buf, "%s/%s", VG_(libdir), default_supp);
1080       VG_(clo_suppressions)[VG_(clo_n_suppressions)] = buf;
1081       VG_(clo_n_suppressions)++;
1082    }
1083
1084    *logging_to_fd = log_to == VgLogTo_Fd || log_to == VgLogTo_Socket;
1085 }
1086
1087 // Write the name and value of log file qualifiers to the xml file.
1088 static void print_file_vars(Char* format)
1089 {
1090    Int i = 0;
1091    
1092    while (format[i]) {
1093       if (format[i] == '%') {
1094          // We saw a '%'.  What's next...
1095          i++;
1096          if ('q' == format[i]) {
1097             i++;
1098             if ('{' == format[i]) {
1099                // Get the env var name, print its contents.
1100                Char* qualname;
1101                Char* qual;
1102                i++;
1103                qualname = &format[i];
1104                while (True) {
1105                   if ('}' == format[i]) {
1106                      // Temporarily replace the '}' with NUL to extract var
1107                      // name.
1108                      format[i] = 0;
1109                      qual = VG_(getenv)(qualname);
1110                      break;
1111                   }
1112                   i++;
1113                }
1114
1115                VG_(printf_xml)(
1116                   "<logfilequalifier> <var>%pS</var> "
1117                   "<value>%pS</value> </logfilequalifier>\n",
1118                   qualname,qual
1119                );
1120                format[i] = '}';
1121                i++;
1122             }
1123          }
1124       } else {
1125          i++;
1126       }
1127    }
1128 }
1129
1130
1131 /*====================================================================*/
1132 /*=== Printing the preamble                                        ===*/
1133 /*====================================================================*/
1134
1135 // Print the argument, escaping any chars that require it.
1136 static void umsg_arg(const Char* arg)
1137 {
1138    SizeT len = VG_(strlen)(arg);
1139    const HChar* special = " \\<>";
1140    Int i;
1141    for (i = 0; i < len; i++) {
1142       if (VG_(strchr)(special, arg[i])) {
1143          VG_(umsg)("\\");   // escape with a backslash if necessary
1144       }
1145       VG_(umsg)("%c", arg[i]);
1146    }
1147 }
1148
1149 // Send output to the XML-stream and escape any XML meta-characters.
1150 static void xml_arg(const Char* arg)
1151 {
1152    VG_(printf_xml)("%pS", arg);
1153 }
1154
1155 /* Ok, the logging sink is running now.  Print a suitable preamble.
1156    If logging to file or a socket, write details of parent PID and
1157    command line args, to help people trying to interpret the
1158    results of a run which encompasses multiple processes. */
1159 static void print_preamble ( Bool logging_to_fd, 
1160                              Char* xml_fname_unexpanded,
1161                              const HChar* toolname )
1162 {
1163    Int    i;
1164    HChar* xpre  = VG_(clo_xml) ? "  <line>" : "";
1165    HChar* xpost = VG_(clo_xml) ? "</line>" : "";
1166    UInt (*umsg_or_xml)( const HChar*, ... )
1167       = VG_(clo_xml) ? VG_(printf_xml) : VG_(umsg);
1168
1169    void (*umsg_or_xml_arg)( const Char* )
1170       = VG_(clo_xml) ? xml_arg : umsg_arg;
1171
1172    vg_assert( VG_(args_for_client) );
1173    vg_assert( VG_(args_for_valgrind) );
1174    vg_assert( toolname );
1175
1176    if (VG_(clo_xml)) {
1177       VG_(printf_xml)("<?xml version=\"1.0\"?>\n");
1178       VG_(printf_xml)("\n");
1179       VG_(printf_xml)("<valgrindoutput>\n");
1180       VG_(printf_xml)("\n");
1181       VG_(printf_xml)("<protocolversion>4</protocolversion>\n");
1182       VG_(printf_xml)("<protocoltool>%s</protocoltool>\n", toolname);
1183       VG_(printf_xml)("\n");
1184    }
1185
1186    if (VG_(clo_xml) || VG_(clo_verbosity > 0)) {
1187
1188       if (VG_(clo_xml))
1189          VG_(printf_xml)("<preamble>\n");
1190
1191       /* Tool details */
1192       umsg_or_xml( VG_(clo_xml) ? "%s%pS%pS%pS, %pS%s\n" : "%s%s%s%s, %s%s\n",
1193                    xpre,
1194                    VG_(details).name, 
1195                    NULL == VG_(details).version ? "" : "-",
1196                    NULL == VG_(details).version 
1197                       ? "" : VG_(details).version,
1198                    VG_(details).description,
1199                    xpost );
1200
1201       if (VG_(strlen)(toolname) >= 4 && VG_STREQN(4, toolname, "exp-")) {
1202          umsg_or_xml(
1203             "%sNOTE: This is an Experimental-Class Valgrind Tool%s\n",
1204             xpre, xpost
1205          );
1206       }
1207
1208       umsg_or_xml( VG_(clo_xml) ? "%s%pS%s\n" : "%s%s%s\n",
1209                    xpre, VG_(details).copyright_author, xpost );
1210
1211       /* Core details */
1212       umsg_or_xml(
1213          "%sUsing Valgrind-%s and LibVEX; rerun with -h for copyright info%s\n",
1214          xpre, VERSION, xpost
1215       );
1216
1217       // Print the command line.  At one point we wrapped at 80 chars and
1218       // printed a '\' as a line joiner, but that makes it hard to cut and
1219       // paste the command line (because of the "==pid==" prefixes), so we now
1220       // favour utility and simplicity over aesthetics.
1221       umsg_or_xml("%sCommand: ", xpre);
1222       if (VG_(args_the_exename))
1223          umsg_or_xml_arg(VG_(args_the_exename));
1224           
1225       for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1226          HChar* s = *(HChar**)VG_(indexXA)( VG_(args_for_client), i );
1227          umsg_or_xml(" ");
1228          umsg_or_xml_arg(s);
1229       }
1230       umsg_or_xml("%s\n", xpost);
1231
1232       if (VG_(clo_xml))
1233          VG_(printf_xml)("</preamble>\n");
1234    }
1235
1236    // Print the parent PID, and other stuff, if necessary.
1237    if (!VG_(clo_xml) && VG_(clo_verbosity) > 0 && !logging_to_fd) {
1238       VG_(umsg)("Parent PID: %d\n", VG_(getppid)());
1239    }
1240    else
1241    if (VG_(clo_xml)) {
1242       VG_(printf_xml)("\n");
1243       VG_(printf_xml)("<pid>%d</pid>\n", VG_(getpid)());
1244       VG_(printf_xml)("<ppid>%d</ppid>\n", VG_(getppid)());
1245       VG_(printf_xml)("<tool>%pS</tool>\n", toolname);
1246       if (xml_fname_unexpanded)
1247          print_file_vars(xml_fname_unexpanded);
1248       if (VG_(clo_xml_user_comment)) {
1249          /* Note: the user comment itself is XML and is therefore to
1250             be passed through verbatim (%s) rather than escaped
1251             (%pS). */
1252          VG_(printf_xml)("<usercomment>%s</usercomment>\n",
1253                          VG_(clo_xml_user_comment));
1254       }
1255       VG_(printf_xml)("\n");
1256       VG_(printf_xml)("<args>\n");
1257
1258       VG_(printf_xml)("  <vargv>\n");
1259       if (VG_(name_of_launcher))
1260          VG_(printf_xml)("    <exe>%pS</exe>\n",
1261                                 VG_(name_of_launcher));
1262       else
1263          VG_(printf_xml)("    <exe>%pS</exe>\n",
1264                                 "(launcher name unknown)");
1265       for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
1266          VG_(printf_xml)(
1267             "    <arg>%pS</arg>\n",
1268             * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1269          );
1270       }
1271       VG_(printf_xml)("  </vargv>\n");
1272
1273       VG_(printf_xml)("  <argv>\n");
1274       if (VG_(args_the_exename))
1275          VG_(printf_xml)("    <exe>%pS</exe>\n",
1276                                 VG_(args_the_exename));
1277       for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1278          VG_(printf_xml)(
1279             "    <arg>%pS</arg>\n",
1280             * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1281          );
1282       }
1283       VG_(printf_xml)("  </argv>\n");
1284
1285       VG_(printf_xml)("</args>\n");
1286    }
1287
1288    // Last thing in the preamble is a blank line.
1289    if (VG_(clo_xml))
1290       VG_(printf_xml)("\n");
1291    else if (VG_(clo_verbosity) > 0)
1292       VG_(umsg)("\n");
1293
1294 #  if defined(VGO_darwin) && DARWIN_VERS == DARWIN_10_8
1295    /* Uh, this doesn't play nice with XML output. */
1296    umsg_or_xml( "WARNING: Support on MacOS 10.8 is experimental and mostly broken.\n");
1297    umsg_or_xml( "WARNING: Expect incorrect results, assertions and crashes.\n");
1298    umsg_or_xml( "WARNING: In particular, Memcheck on 32-bit programs will fail to\n");
1299    umsg_or_xml( "WARNING: detect any errors associated with heap-allocated data.\n");
1300    umsg_or_xml( "\n" );
1301 #  endif
1302
1303    if (VG_(clo_verbosity) > 1) {
1304       SysRes fd;
1305       VexArch vex_arch;
1306       VexArchInfo vex_archinfo;
1307       if (!logging_to_fd)
1308          VG_(message)(Vg_DebugMsg, "\n");
1309       VG_(message)(Vg_DebugMsg, "Valgrind options:\n");
1310       for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
1311          VG_(message)(Vg_DebugMsg, 
1312                      "   %s\n", 
1313                      * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ));
1314       }
1315
1316       VG_(message)(Vg_DebugMsg, "Contents of /proc/version:\n");
1317       fd = VG_(open) ( "/proc/version", VKI_O_RDONLY, 0 );
1318       if (sr_isError(fd)) {
1319          VG_(message)(Vg_DebugMsg, "  can't open /proc/version\n");
1320       } else {
1321 #        define BUF_LEN    256
1322          Char version_buf[BUF_LEN];
1323          Int n = VG_(read) ( sr_Res(fd), version_buf, BUF_LEN );
1324          vg_assert(n <= BUF_LEN);
1325          if (n > 0) {
1326             version_buf[n-1] = '\0';
1327             VG_(message)(Vg_DebugMsg, "  %s\n", version_buf);
1328          } else {
1329             VG_(message)(Vg_DebugMsg, "  (empty?)\n");
1330          }
1331          VG_(close)(sr_Res(fd));
1332 #        undef BUF_LEN
1333       }
1334
1335       VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
1336       VG_(message)(
1337          Vg_DebugMsg, 
1338          "Arch and hwcaps: %s, %s\n",
1339          LibVEX_ppVexArch   ( vex_arch ),
1340          LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1341       );
1342       VG_(message)(
1343          Vg_DebugMsg, 
1344          "Page sizes: currently %d, max supported %d\n", 
1345          (Int)VKI_PAGE_SIZE, (Int)VKI_MAX_PAGE_SIZE
1346       );
1347       VG_(message)(Vg_DebugMsg,
1348                    "Valgrind library directory: %s\n", VG_(libdir));
1349    }
1350 }
1351
1352
1353 /*====================================================================*/
1354 /*=== File descriptor setup                                        ===*/
1355 /*====================================================================*/
1356
1357 /* Number of file descriptors that Valgrind tries to reserve for
1358    it's own use - just a small constant. */
1359 #define N_RESERVED_FDS (10)
1360
1361 static void setup_file_descriptors(void)
1362 {
1363    struct vki_rlimit rl;
1364    Bool show = False;
1365
1366    /* Get the current file descriptor limits. */
1367    if (VG_(getrlimit)(VKI_RLIMIT_NOFILE, &rl) < 0) {
1368       rl.rlim_cur = 1024;
1369       rl.rlim_max = 1024;
1370    }
1371
1372 #  if defined(VGO_darwin)
1373    /* Darwin lies. It reports file max as RLIM_INFINITY but
1374       silently disallows anything bigger than 10240. */
1375    if (rl.rlim_cur >= 10240  &&  rl.rlim_max == 0x7fffffffffffffffULL) {
1376       rl.rlim_max = 10240;
1377    }
1378 #  endif
1379
1380    if (show)
1381       VG_(printf)("fd limits: host, before: cur %lu max %lu\n", 
1382                   (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
1383
1384    /* Work out where to move the soft limit to. */
1385    if (rl.rlim_cur + N_RESERVED_FDS <= rl.rlim_max) {
1386       rl.rlim_cur = rl.rlim_cur + N_RESERVED_FDS;
1387    } else {
1388       rl.rlim_cur = rl.rlim_max;
1389    }
1390
1391    /* Reserve some file descriptors for our use. */
1392    VG_(fd_soft_limit) = rl.rlim_cur - N_RESERVED_FDS;
1393    VG_(fd_hard_limit) = rl.rlim_cur - N_RESERVED_FDS;
1394
1395    /* Update the soft limit. */
1396    VG_(setrlimit)(VKI_RLIMIT_NOFILE, &rl);
1397
1398    if (show) {
1399       VG_(printf)("fd limits: host,  after: cur %lu max %lu\n",
1400                   (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
1401       VG_(printf)("fd limits: guest       : cur %u max %u\n",
1402                   VG_(fd_soft_limit), VG_(fd_hard_limit));
1403    }
1404
1405    if (VG_(cl_exec_fd) != -1)
1406       VG_(cl_exec_fd) = VG_(safe_fd)( VG_(cl_exec_fd) );
1407 }
1408
1409
1410 /*====================================================================*/
1411 /*=== BB profiling                                                 ===*/
1412 /*====================================================================*/
1413
1414 static 
1415 void show_BB_profile ( BBProfEntry tops[], UInt n_tops, ULong score_total )
1416 {
1417    ULong score_cumul,   score_here;
1418    Char  buf_cumul[10], buf_here[10];
1419    Char  name[64];
1420    Int   r;
1421
1422    VG_(printf)("\n");
1423    VG_(printf)("-----------------------------------------------------------\n");
1424    VG_(printf)("--- BEGIN BB Profile (summary of scores)                ---\n");
1425    VG_(printf)("-----------------------------------------------------------\n");
1426    VG_(printf)("\n");
1427
1428    VG_(printf)("Total score = %lld\n\n", score_total);
1429
1430    score_cumul = 0;
1431    for (r = 0; r < n_tops; r++) {
1432       if (tops[r].addr == 0)
1433          continue;
1434       name[0] = 0;
1435       VG_(get_fnname_w_offset)(tops[r].addr, name, 64);
1436       name[63] = 0;
1437       score_here = tops[r].score;
1438       score_cumul += score_here;
1439       VG_(percentify)(score_cumul, score_total, 2, 6, buf_cumul);
1440       VG_(percentify)(score_here,  score_total, 2, 6, buf_here);
1441       VG_(printf)("%3d: (%9lld %s)   %9lld %s      0x%llx %s\n",
1442                   r,
1443                   score_cumul, buf_cumul,
1444                   score_here,  buf_here, tops[r].addr, name );
1445    }
1446
1447    VG_(printf)("\n");
1448    VG_(printf)("-----------------------------------------------------------\n");
1449    VG_(printf)("--- BB Profile (BB details)                             ---\n");
1450    VG_(printf)("-----------------------------------------------------------\n");
1451    VG_(printf)("\n");
1452
1453    score_cumul = 0;
1454    for (r = 0; r < n_tops; r++) {
1455       if (tops[r].addr == 0)
1456          continue;
1457       name[0] = 0;
1458       VG_(get_fnname_w_offset)(tops[r].addr, name, 64);
1459       name[63] = 0;
1460       score_here = tops[r].score;
1461       score_cumul += score_here;
1462       VG_(percentify)(score_cumul, score_total, 2, 6, buf_cumul);
1463       VG_(percentify)(score_here,  score_total, 2, 6, buf_here);
1464       VG_(printf)("\n");
1465       VG_(printf)("=-=-=-=-=-=-=-=-=-=-=-=-=-= begin BB rank %d "
1466                   "=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n", r);
1467       VG_(printf)("%3d: (%9lld %s)   %9lld %s      0x%llx %s\n",
1468                   r,
1469                   score_cumul, buf_cumul,
1470                   score_here,  buf_here, tops[r].addr, name );
1471       VG_(printf)("\n");
1472       VG_(discard_translations)(tops[r].addr, 1, "bb profile");
1473       VG_(translate)(0, tops[r].addr, True, VG_(clo_profile_flags), 0, True);
1474       VG_(printf)("=-=-=-=-=-=-=-=-=-=-=-=-=-=  end BB rank %d  "
1475                   "=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n", r);
1476    }
1477
1478    VG_(printf)("\n");
1479    VG_(printf)("-----------------------------------------------------------\n");
1480    VG_(printf)("--- END BB Profile                                      ---\n");
1481    VG_(printf)("-----------------------------------------------------------\n");
1482    VG_(printf)("\n");
1483 }
1484
1485
1486 /*====================================================================*/
1487 /*=== main()                                                       ===*/
1488 /*====================================================================*/
1489
1490 /* When main() is entered, we should be on the following stack, not
1491    the one the kernel gave us.  We will run on this stack until
1492    simulation of the root thread is started, at which point a transfer
1493    is made to a dynamically allocated stack.  This is for the sake of
1494    uniform overflow detection for all Valgrind threads.  This is
1495    marked global even though it isn't, because assembly code below
1496    needs to reference the name. */
1497
1498 /*static*/ VgStack VG_(interim_stack);
1499
1500 /* These are the structures used to hold info for creating the initial
1501    client image.
1502
1503    'iicii' mostly holds important register state present at system
1504    startup (_start_valgrind).  valgrind_main() then fills in the rest
1505    of it and passes it to VG_(ii_create_image)().  That produces
1506    'iifii', which is later handed to VG_(ii_finalise_image). */
1507
1508 /* In all OS-instantiations, the_iicii has a field .sp_at_startup.
1509    This should get some address inside the stack on which we gained
1510    control (eg, it could be the SP at startup).  It doesn't matter
1511    exactly where in the stack it is.  This value is passed to the
1512    address space manager at startup.  On Linux, aspacem then uses it
1513    to identify the initial stack segment and hence the upper end of
1514    the usable address space. */
1515
1516 static IICreateImageInfo   the_iicii;
1517 static IIFinaliseImageInfo the_iifii;
1518
1519
1520 /* A simple pair structure, used for conveying debuginfo handles to
1521    calls to VG_TRACK(new_mem_startup, ...). */
1522 typedef  struct { Addr a; ULong ull; }  Addr_n_ULong;
1523
1524
1525 /* --- Forwards decls to do with shutdown --- */
1526
1527 static void final_tidyup(ThreadId tid); 
1528
1529 /* Do everything which needs doing when the last thread exits */
1530 static 
1531 void shutdown_actions_NORETURN( ThreadId tid, 
1532                                 VgSchedReturnCode tids_schedretcode );
1533
1534 /* --- end of Forwards decls to do with shutdown --- */
1535
1536
1537 /* By the time we get to valgrind_main, the_iicii should already have
1538    been filled in with any important details as required by whatever
1539    OS we have been built for.
1540 */
1541 static
1542 Int valgrind_main ( Int argc, HChar **argv, HChar **envp )
1543 {
1544    HChar*  toolname           = "memcheck";    // default to Memcheck
1545    Int     need_help          = 0; // 0 = no, 1 = --help, 2 = --help-debug
1546    ThreadId tid_main          = VG_INVALID_THREADID;
1547    Bool    logging_to_fd      = False;
1548    Char* xml_fname_unexpanded = NULL;
1549    Int     loglevel, i;
1550    struct vki_rlimit zero = { 0, 0 };
1551    XArray* addr2dihandle = NULL;
1552
1553    // For an inner Valgrind, register the interim stack asap.
1554    // This is needed to allow the outer valgrind to do stacktraces during init.
1555    // Note that this stack is not unregistered when the main thread
1556    // is switching to the (real) stack. Unregistering this would imply
1557    // to save the stack id in a global variable, and have a "if"
1558    // in run_a_thread_NORETURN to do the unregistration only for the
1559    // main thread. This unregistration is not worth this complexity.
1560    INNER_REQUEST
1561       ((void) VALGRIND_STACK_REGISTER
1562        (&VG_(interim_stack).bytes[0],
1563         &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack))));
1564
1565
1566    //============================================================
1567    //
1568    // Nb: startup is complex.  Prerequisites are shown at every step.
1569    // *** Be very careful when messing with the order ***
1570    //
1571    // The first order of business is to get debug logging, the address
1572    // space manager and the dynamic memory manager up and running.
1573    // Once that's done, we can relax a bit.
1574    //
1575    //============================================================
1576    
1577    /* This is needed to make VG_(getenv) usable early. */
1578    VG_(client_envp) = (Char**)envp;
1579
1580    //--------------------------------------------------------------
1581    // Start up Mach kernel interface, if any
1582    //   p: none
1583    //--------------------------------------------------------------
1584 #  if defined(VGO_darwin)
1585    VG_(mach_init)();
1586 #  endif
1587
1588    //--------------------------------------------------------------
1589    // Start up the logging mechanism
1590    //   p: none
1591    //--------------------------------------------------------------
1592    /* Start the debugging-log system ASAP.  First find out how many 
1593       "-d"s were specified.  This is a pre-scan of the command line.  Also
1594       get --profile-heap=yes, --core-redzone-size, --redzone-size which are
1595       needed by the time we start up dynamic memory management.  */
1596    loglevel = 0;
1597    for (i = 1; i < argc; i++) {
1598       if (argv[i][0] != '-') break;
1599       if VG_STREQ(argv[i], "--") break;
1600       if VG_STREQ(argv[i], "-d") loglevel++;
1601       if VG_BOOL_CLO(argv[i], "--profile-heap", VG_(clo_profile_heap)) {}
1602       if VG_BINT_CLO(argv[i], "--core-redzone-size", VG_(clo_core_redzone_size),
1603                      0, MAX_CLO_REDZONE_SZB) {}
1604       if VG_BINT_CLO(argv[i], "--redzone-size", VG_(clo_redzone_size),
1605                      0, MAX_CLO_REDZONE_SZB) {}
1606    }
1607
1608    /* ... and start the debug logger.  Now we can safely emit logging
1609       messages all through startup. */
1610    VG_(debugLog_startup)(loglevel, "Stage 2 (main)");
1611    VG_(debugLog)(1, "main", "Welcome to Valgrind version " 
1612                             VERSION " debug logging\n");
1613
1614    //--------------------------------------------------------------
1615    // Ensure we're on a plausible stack.
1616    //   p: logging
1617    //--------------------------------------------------------------
1618    VG_(debugLog)(1, "main", "Checking current stack is plausible\n");
1619    { HChar* limLo  = (HChar*)(&VG_(interim_stack).bytes[0]);
1620      HChar* limHi  = limLo + sizeof(VG_(interim_stack));
1621      HChar* volatile 
1622             aLocal = (HChar*)&limLo; /* any auto local will do */
1623      /* Re "volatile": Apple clang version 4.0
1624         (tags/Apple/clang-421.0.57) (based on LLVM 3.1svn)" appeared
1625         to miscompile the following check, causing run to abort at
1626         this point (in 64-bit mode) even though aLocal is within limLo
1627         .. limHi.  But in fact clang is within its rights to do
1628         strange things here.  "The reason is that the comparisons
1629         aLocal < limLo and aLocal >= limHi cause undefined behaviour
1630         (according to c99 6.5.8) because they compare pointers that do
1631         not point into the same aggregate."  Adding "volatile" appears
1632         to fix it because "The compiler would have to prove that there
1633         is undefined behavior in order to exploit it.  But as a
1634         volatile variable can change its value in ways invisible to
1635         the compiler, the compiler must make the conservative
1636         assumption that it points into the same aggregate as the other
1637         pointer its compared against.  I.e. the behaviour is possibly
1638         defined." (Analysis by Florian Krohm). */
1639      if (aLocal < limLo || aLocal >= limHi) {
1640         /* something's wrong.  Stop. */
1641         VG_(debugLog)(0, "main", "Root stack %p to %p, a local %p\n",
1642                           limLo, limHi, aLocal );
1643         VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1644                                  "Initial stack switched failed.\n");
1645         VG_(debugLog)(0, "main", "   Cannot continue.  Sorry.\n");
1646         VG_(exit)(1);
1647      }
1648    }
1649
1650    //--------------------------------------------------------------
1651    // Ensure we have a plausible pointer to the stack on which
1652    // we gained control (not the current stack!)
1653    //   p: logging
1654    //--------------------------------------------------------------
1655    VG_(debugLog)(1, "main", "Checking initial stack was noted\n");
1656    if (the_iicii.sp_at_startup == 0) {
1657       VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1658                                "Initial stack was not noted.\n");
1659       VG_(debugLog)(0, "main", "   Cannot continue.  Sorry.\n");
1660       VG_(exit)(1);
1661    }
1662
1663    //--------------------------------------------------------------
1664    // Start up the address space manager, and determine the
1665    // approximate location of the client's stack
1666    //   p: logging, plausible-stack
1667    //--------------------------------------------------------------
1668    VG_(debugLog)(1, "main", "Starting the address space manager\n");
1669    vg_assert(VKI_PAGE_SIZE     == 4096 || VKI_PAGE_SIZE     == 65536
1670              || VKI_PAGE_SIZE     == 16384);
1671    vg_assert(VKI_MAX_PAGE_SIZE == 4096 || VKI_MAX_PAGE_SIZE == 65536
1672              || VKI_MAX_PAGE_SIZE == 16384);
1673    vg_assert(VKI_PAGE_SIZE <= VKI_MAX_PAGE_SIZE);
1674    vg_assert(VKI_PAGE_SIZE     == (1 << VKI_PAGE_SHIFT));
1675    vg_assert(VKI_MAX_PAGE_SIZE == (1 << VKI_MAX_PAGE_SHIFT));
1676    the_iicii.clstack_top = VG_(am_startup)( the_iicii.sp_at_startup );
1677    VG_(debugLog)(1, "main", "Address space manager is running\n");
1678
1679    //--------------------------------------------------------------
1680    // Start up the dynamic memory manager
1681    //   p: address space management
1682    //   p: getting --profile-heap,--core-redzone-size,--redzone-size
1683    //   In fact m_mallocfree is self-initialising, so there's no
1684    //   initialisation call to do.  Instead, try a simple malloc/
1685    //   free pair right now to check that nothing is broken.
1686    //--------------------------------------------------------------
1687    VG_(debugLog)(1, "main", "Starting the dynamic memory manager\n");
1688    { void* p = VG_(malloc)( "main.vm.1", 12345 );
1689      if (p) VG_(free)( p );
1690    }
1691    VG_(debugLog)(1, "main", "Dynamic memory manager is running\n");
1692
1693    //============================================================
1694    //
1695    // Dynamic memory management is now available.
1696    //
1697    //============================================================
1698
1699    //--------------------------------------------------------------
1700    // Initialise m_debuginfo
1701    //  p: dynamic memory allocation
1702    VG_(debugLog)(1, "main", "Initialise m_debuginfo\n");
1703    VG_(di_initialise)();
1704
1705    //--------------------------------------------------------------
1706    // Look for alternative libdir                                  
1707    { HChar *cp = VG_(getenv)(VALGRIND_LIB);
1708      if (cp != NULL)
1709         VG_(libdir) = cp;
1710      VG_(debugLog)(1, "main", "VG_(libdir) = %s\n", VG_(libdir));
1711    }
1712
1713    //--------------------------------------------------------------
1714    // Extract the launcher name from the environment.
1715    VG_(debugLog)(1, "main", "Getting launcher's name ...\n");
1716    VG_(name_of_launcher) = VG_(getenv)(VALGRIND_LAUNCHER);
1717    if (VG_(name_of_launcher) == NULL) {
1718       VG_(printf)("valgrind: You cannot run '%s' directly.\n", argv[0]);
1719       VG_(printf)("valgrind: You should use $prefix/bin/valgrind.\n");
1720       VG_(exit)(1);
1721    }
1722    VG_(debugLog)(1, "main", "... %s\n", VG_(name_of_launcher));
1723
1724    //--------------------------------------------------------------
1725    // Get the current process datasize rlimit, and set it to zero.
1726    // This prevents any internal uses of brk() from having any effect.
1727    // We remember the old value so we can restore it on exec, so that
1728    // child processes will have a reasonable brk value.
1729    VG_(getrlimit)(VKI_RLIMIT_DATA, &VG_(client_rlimit_data));
1730    zero.rlim_max = VG_(client_rlimit_data).rlim_max;
1731    VG_(setrlimit)(VKI_RLIMIT_DATA, &zero);
1732
1733    // Get the current process stack rlimit.
1734    VG_(getrlimit)(VKI_RLIMIT_STACK, &VG_(client_rlimit_stack));
1735
1736    //--------------------------------------------------------------
1737    // Figure out what sort of CPU we're on, and whether it is 
1738    // able to run V.
1739    VG_(debugLog)(1, "main", "Get hardware capabilities ...\n");
1740    { VexArch     vex_arch;
1741      VexArchInfo vex_archinfo;
1742      Bool ok = VG_(machine_get_hwcaps)();
1743      if (!ok) {
1744         VG_(printf)("\n");
1745         VG_(printf)("valgrind: fatal error: unsupported CPU.\n");
1746         VG_(printf)("   Supported CPUs are:\n");
1747         VG_(printf)("   * x86 (practically any; Pentium-I or above), "
1748                     "AMD Athlon or above)\n");
1749         VG_(printf)("   * AMD Athlon64/Opteron\n");
1750         VG_(printf)("   * PowerPC (most; ppc405 and above)\n");
1751         VG_(printf)("   * System z (64bit only - s390x; z900 and above)\n");
1752         VG_(printf)("\n");
1753         VG_(exit)(1);
1754      }
1755      VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
1756      VG_(debugLog)(
1757         1, "main", "... arch = %s, hwcaps = %s\n",
1758            LibVEX_ppVexArch   ( vex_arch ),
1759            LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps ) 
1760      );
1761    }
1762
1763    //--------------------------------------------------------------
1764    // Record the working directory at startup
1765    //   p: none
1766    VG_(debugLog)(1, "main", "Getting the working directory at startup\n");
1767    { Bool ok = VG_(record_startup_wd)();
1768      if (!ok) 
1769         VG_(err_config_error)( "Can't establish current working "
1770                                "directory at startup\n");
1771    }
1772    { Char buf[VKI_PATH_MAX+1];
1773      Bool ok = VG_(get_startup_wd)( buf, sizeof(buf) );
1774      vg_assert(ok);
1775      buf[VKI_PATH_MAX] = 0;
1776      VG_(debugLog)(1, "main", "... %s\n", buf );
1777    }
1778
1779    //============================================================
1780    // Command line argument handling order:
1781    // * If --help/--help-debug are present, show usage message 
1782    //   (including the tool-specific usage)
1783    // * (If no --tool option given, default to Memcheck)
1784    // * Then, if client is missing, abort with error msg
1785    // * Then, if any cmdline args are bad, abort with error msg
1786    //============================================================
1787
1788    //--------------------------------------------------------------
1789    // Split up argv into: C args, V args, V extra args, and exename.
1790    //   p: dynamic memory allocation
1791    //--------------------------------------------------------------
1792    VG_(debugLog)(1, "main", "Split up command line\n");
1793    VG_(split_up_argv)( argc, argv );
1794    vg_assert( VG_(args_for_valgrind) );
1795    vg_assert( VG_(args_for_client) );
1796    if (0) {
1797       for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++)
1798          VG_(printf)(
1799             "varg %s\n", 
1800             * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1801          );
1802       VG_(printf)(" exe %s\n", VG_(args_the_exename));
1803       for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++)
1804          VG_(printf)(
1805             "carg %s\n", 
1806             * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1807          );
1808    }
1809
1810    //--------------------------------------------------------------
1811    // Extract tool name and whether help has been requested.
1812    // Note we can't print the help message yet, even if requested,
1813    // because the tool has not been initialised.
1814    //   p: split_up_argv [for VG_(args_for_valgrind)]
1815    //--------------------------------------------------------------
1816    VG_(debugLog)(1, "main",
1817                     "(early_) Process Valgrind's command line options\n");
1818    early_process_cmd_line_options(&need_help, &toolname);
1819
1820    // Set default vex control params
1821    LibVEX_default_VexControl(& VG_(clo_vex_control));
1822
1823    //--------------------------------------------------------------
1824    // Load client executable, finding in $PATH if necessary
1825    //   p: early_process_cmd_line_options()  [for 'exec', 'need_help',
1826    //                                         clo_max_stackframe,
1827    //                                         clo_main_stacksize]
1828    //   p: layout_remaining_space            [so there's space]
1829    //
1830    // Set up client's environment
1831    //   p: set-libdir                     [for VG_(libdir)]
1832    //   p: early_process_cmd_line_options [for toolname]
1833    //
1834    // Setup client stack, eip, and VG_(client_arg[cv])
1835    //   p: load_client()     [for 'info']
1836    //   p: fix_environment() [for 'env']
1837    //
1838    // Setup client data (brk) segment.  Initially a 1-page segment
1839    // which abuts a shrinkable reservation. 
1840    //     p: load_client()     [for 'info' and hence VG_(brk_base)]
1841    //
1842    // p: _start_in_C (for zeroing out the_iicii and putting some
1843    //    initial values into it)
1844    //--------------------------------------------------------------
1845    if (!need_help) {
1846       VG_(debugLog)(1, "main", "Create initial image\n");
1847
1848 #     if defined(VGO_linux) || defined(VGO_darwin)
1849       the_iicii.argv              = argv;
1850       the_iicii.envp              = envp;
1851       the_iicii.toolname          = toolname;
1852 #     else
1853 #       error "Unknown platform"
1854 #     endif
1855
1856       /* NOTE: this call reads VG_(clo_main_stacksize). */
1857       the_iifii = VG_(ii_create_image)( the_iicii );
1858    }
1859
1860    //==============================================================
1861    //
1862    // Finished loading/setting up the client address space.
1863    //
1864    //==============================================================
1865
1866    //--------------------------------------------------------------
1867    // setup file descriptors
1868    //   p: n/a
1869    //--------------------------------------------------------------
1870    VG_(debugLog)(1, "main", "Setup file descriptors\n");
1871    setup_file_descriptors();
1872
1873    //--------------------------------------------------------------
1874    // create fake /proc/<pid>/cmdline and /proc/<pid>/auxv files
1875    // and then unlink them, but hold onto the fds, so we can handr
1876    // them out to the client when it tries to open
1877    // /proc/<pid>/cmdline or /proc/<pid>/auxv for itself.
1878    //   p: setup file descriptors
1879    //   p: ii_create_image for VG_(client_auxv) setup.
1880    //--------------------------------------------------------------
1881 #if !defined(VGO_linux)
1882    // client shouldn't be using /proc!
1883    VG_(cl_cmdline_fd) = -1;
1884    VG_(cl_auxv_fd) = -1;
1885 #else
1886    if (!need_help) {
1887       HChar  buf[50], buf2[50+64];
1888       HChar  nul[1];
1889       Int    fd, r;
1890       const HChar* exename;
1891
1892       VG_(debugLog)(1, "main", "Create fake /proc/<pid>/cmdline\n");
1893
1894       VG_(sprintf)(buf, "proc_%d_cmdline", VG_(getpid)());
1895       fd = VG_(mkstemp)( buf, buf2 );
1896       if (fd == -1)
1897          VG_(err_config_error)("Can't create client cmdline file in %s\n", buf2);
1898
1899       nul[0] = 0;
1900       exename = VG_(args_the_exename) ? VG_(args_the_exename)
1901                                       : "unknown_exename";
1902       VG_(write)(fd, exename, VG_(strlen)( exename ));
1903       VG_(write)(fd, nul, 1);
1904
1905       for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1906          HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i );
1907          VG_(write)(fd, arg, VG_(strlen)( arg ));
1908          VG_(write)(fd, nul, 1);
1909       }
1910
1911       /* Don't bother to seek the file back to the start; instead do
1912          it every time a copy of it is given out (by PRE(sys_open)). 
1913          That is probably more robust across fork() etc. */
1914
1915       /* Now delete it, but hang on to the fd. */
1916       r = VG_(unlink)( buf2 );
1917       if (r)
1918          VG_(err_config_error)("Can't delete client cmdline file in %s\n", buf2);
1919
1920       VG_(cl_cmdline_fd) = fd;
1921
1922       VG_(debugLog)(1, "main", "Create fake /proc/<pid>/auxv\n");
1923
1924       VG_(sprintf)(buf, "proc_%d_auxv", VG_(getpid)());
1925       fd = VG_(mkstemp)( buf, buf2 );
1926       if (fd == -1)
1927          VG_(err_config_error)("Can't create client auxv file in %s\n", buf2);
1928
1929       UWord *client_auxv = VG_(client_auxv);
1930       unsigned int client_auxv_len = 0;
1931       while (*client_auxv != 0) {
1932          client_auxv++;
1933          client_auxv++;
1934          client_auxv_len += 2 * sizeof(UWord);
1935       }
1936       client_auxv_len += 2 * sizeof(UWord);
1937
1938       VG_(write)(fd, VG_(client_auxv), client_auxv_len);
1939
1940       /* Don't bother to seek the file back to the start; instead do
1941          it every time a copy of it is given out (by PRE(sys_open)). 
1942          That is probably more robust across fork() etc. */
1943
1944       /* Now delete it, but hang on to the fd. */
1945       r = VG_(unlink)( buf2 );
1946       if (r)
1947          VG_(err_config_error)("Can't delete client auxv file in %s\n", buf2);
1948
1949       VG_(cl_auxv_fd) = fd;
1950    }
1951 #endif
1952
1953    //--------------------------------------------------------------
1954    // Init tool part 1: pre_clo_init
1955    //   p: setup_client_stack()      [for 'VG_(client_arg[cv]']
1956    //   p: setup_file_descriptors()  [for 'VG_(fd_xxx_limit)']
1957    //--------------------------------------------------------------
1958    VG_(debugLog)(1, "main", "Initialise the tool part 1 (pre_clo_init)\n");
1959    VG_(tl_pre_clo_init)();
1960
1961    //--------------------------------------------------------------
1962    // If --tool and --help/--help-debug was given, now give the core+tool
1963    // help message
1964    //   p: early_process_cmd_line_options() [for 'need_help']
1965    //   p: tl_pre_clo_init                  [for 'VG_(tdict).usage']
1966    //--------------------------------------------------------------
1967    VG_(debugLog)(1, "main", "Print help and quit, if requested\n");
1968    if (need_help) {
1969       usage_NORETURN(/*--help-debug?*/need_help >= 2);
1970    }
1971
1972    //--------------------------------------------------------------
1973    // Process command line options to Valgrind + tool
1974    //   p: setup_client_stack()      [for 'VG_(client_arg[cv]']
1975    //   p: setup_file_descriptors()  [for 'VG_(fd_xxx_limit)']
1976    //--------------------------------------------------------------
1977    VG_(debugLog)(1, "main",
1978                     "(main_) Process Valgrind's command line options, "
1979                     "setup logging\n");
1980    main_process_cmd_line_options ( &logging_to_fd, &xml_fname_unexpanded,
1981                                    toolname );
1982
1983    //--------------------------------------------------------------
1984    // Zeroise the millisecond counter by doing a first read of it.
1985    //   p: none
1986    //--------------------------------------------------------------
1987    (void) VG_(read_millisecond_timer)();
1988
1989    //--------------------------------------------------------------
1990    // Print the preamble
1991    //   p: tl_pre_clo_init            [for 'VG_(details).name' and friends]
1992    //   p: main_process_cmd_line_options()
1993    //         [for VG_(clo_verbosity), VG_(clo_xml),
1994    //          logging_to_fd, xml_fname_unexpanded]
1995    //--------------------------------------------------------------
1996    VG_(debugLog)(1, "main", "Print the preamble...\n");
1997    print_preamble(logging_to_fd, xml_fname_unexpanded, toolname);
1998    VG_(debugLog)(1, "main", "...finished the preamble\n");
1999
2000    //--------------------------------------------------------------
2001    // Init tool part 2: post_clo_init
2002    //   p: setup_client_stack()      [for 'VG_(client_arg[cv]']
2003    //   p: setup_file_descriptors()  [for 'VG_(fd_xxx_limit)']
2004    //   p: print_preamble()          [so any warnings printed in post_clo_init
2005    //                                 are shown after the preamble]
2006    //--------------------------------------------------------------
2007    VG_(debugLog)(1, "main", "Initialise the tool part 2 (post_clo_init)\n");
2008    VG_TDICT_CALL(tool_post_clo_init);
2009    {
2010       /* The tool's "needs" will by now be finalised, since it has no
2011          further opportunity to specify them.  So now sanity check
2012          them. */
2013       const HChar* s;
2014       Bool  ok;
2015       ok = VG_(sanity_check_needs)( &s );
2016       if (!ok) {
2017          VG_(tool_panic)(s);
2018       }
2019    }
2020
2021    //--------------------------------------------------------------
2022    // Initialise translation table and translation cache
2023    //   p: aspacem         [??]
2024    //   p: tl_pre_clo_init [for 'VG_(details).avg_translation_sizeB']
2025    //--------------------------------------------------------------
2026    VG_(debugLog)(1, "main", "Initialise TT/TC\n");
2027    VG_(init_tt_tc)();
2028
2029    //--------------------------------------------------------------
2030    // Initialise the redirect table.
2031    //   p: init_tt_tc [so it can call VG_(search_transtab) safely]
2032    //   p: aspacem [so can change ownership of sysinfo pages]
2033    //--------------------------------------------------------------
2034    VG_(debugLog)(1, "main", "Initialise redirects\n");
2035    VG_(redir_initialise)();
2036
2037    //--------------------------------------------------------------
2038    // Allow GDB attach
2039    //   p: main_process_cmd_line_options()  [for VG_(clo_wait_for_gdb)]
2040    //--------------------------------------------------------------
2041    /* Hook to delay things long enough so we can get the pid and
2042       attach GDB in another shell. */
2043    if (VG_(clo_wait_for_gdb)) {
2044       ULong iters, q;
2045       VG_(debugLog)(1, "main", "Wait for GDB\n");
2046       VG_(printf)("pid=%d, entering delay loop\n", VG_(getpid)());
2047
2048 #     if defined(VGP_x86_linux)
2049       iters = 10;
2050 #     elif defined(VGP_amd64_linux) || defined(VGP_ppc64_linux)
2051       iters = 10;
2052 #     elif defined(VGP_ppc32_linux)
2053       iters = 5;
2054 #     elif defined(VGP_arm_linux)
2055       iters = 5;
2056 #     elif defined(VGP_s390x_linux)
2057       iters = 10;
2058 #     elif defined(VGP_mips32_linux)
2059       iters = 10;
2060 #     elif defined(VGO_darwin)
2061       iters = 3;
2062 #     else
2063 #       error "Unknown plat"
2064 #     endif
2065
2066       iters *= 1000ULL * 1000 * 1000;
2067       for (q = 0; q < iters; q++) 
2068          __asm__ __volatile__("" ::: "memory","cc");
2069    }
2070
2071    //--------------------------------------------------------------
2072    // Search for file descriptors that are inherited from our parent
2073    //   p: main_process_cmd_line_options  [for VG_(clo_track_fds)]
2074    //--------------------------------------------------------------
2075    if (VG_(clo_track_fds)) {
2076       VG_(debugLog)(1, "main", "Init preopened fds\n");
2077       VG_(init_preopened_fds)();
2078    }
2079
2080    //--------------------------------------------------------------
2081    // Load debug info for the existing segments.
2082    //   p: setup_code_redirect_table [so that redirs can be recorded]
2083    //   p: mallocfree
2084    //   p: probably: setup fds and process CLOs, so that logging works
2085    //   p: initialise m_debuginfo
2086    //
2087    // While doing this, make a note of the debuginfo-handles that
2088    // come back from VG_(di_notify_mmap).
2089    // Later, in "Tell the tool about the initial client memory permissions"
2090    // (just below) we can then hand these handles off to the tool in
2091    // calls to VG_TRACK(new_mem_startup, ...).  This gives the tool the
2092    // opportunity to make further queries to m_debuginfo before the
2093    // client is started, if it wants.  We put this information into an
2094    // XArray, each handle along with the associated segment start address,
2095    // and search the XArray for the handles later, when calling
2096    // VG_TRACK(new_mem_startup, ...).
2097    //--------------------------------------------------------------
2098    VG_(debugLog)(1, "main", "Load initial debug info\n");
2099
2100    tl_assert(!addr2dihandle);
2101    addr2dihandle = VG_(newXA)( VG_(malloc), "main.vm.2",
2102                                VG_(free), sizeof(Addr_n_ULong) );
2103    tl_assert(addr2dihandle);
2104
2105 #  if defined(VGO_linux)
2106    { Addr* seg_starts;
2107      Int   n_seg_starts;
2108      Addr_n_ULong anu;
2109
2110      seg_starts = VG_(get_segment_starts)( &n_seg_starts );
2111      vg_assert(seg_starts && n_seg_starts >= 0);
2112
2113      /* show them all to the debug info reader.  allow_SkFileV has to
2114         be True here so that we read info from the valgrind executable
2115         itself. */
2116      for (i = 0; i < n_seg_starts; i++) {
2117         anu.ull = VG_(di_notify_mmap)( seg_starts[i], True/*allow_SkFileV*/,
2118                                        -1/*Don't use_fd*/);
2119         /* anu.ull holds the debuginfo handle returned by di_notify_mmap,
2120            if any. */
2121         if (anu.ull > 0) {
2122            anu.a = seg_starts[i];
2123            VG_(addToXA)( addr2dihandle, &anu );
2124         }
2125      }
2126
2127      VG_(free)( seg_starts );
2128    }
2129 #  elif defined(VGO_darwin)
2130    { Addr* seg_starts;
2131      Int   n_seg_starts;
2132      seg_starts = VG_(get_segment_starts)( &n_seg_starts );
2133      vg_assert(seg_starts && n_seg_starts >= 0);
2134
2135      /* show them all to the debug info reader.  
2136         Don't read from V segments (unlike Linux) */
2137      // GrP fixme really?
2138      for (i = 0; i < n_seg_starts; i++) {
2139         VG_(di_notify_mmap)( seg_starts[i], False/*don't allow_SkFileV*/,
2140                              -1/*don't use_fd*/);
2141      }
2142
2143      VG_(free)( seg_starts );
2144    }
2145 #  else
2146 #    error Unknown OS
2147 #  endif
2148
2149    //--------------------------------------------------------------
2150    // Tell aspacem of ownership change of the asm helpers, so that
2151    // m_translate allows them to be translated.  However, only do this
2152    // after the initial debug info read, since making a hole in the
2153    // address range for the stage2 binary confuses the debug info reader.
2154    //   p: aspacem
2155    //--------------------------------------------------------------
2156    { Bool change_ownership_v_c_OK;
2157      Addr co_start   = VG_PGROUNDDN( (Addr)&VG_(trampoline_stuff_start) );
2158      Addr co_endPlus = VG_PGROUNDUP( (Addr)&VG_(trampoline_stuff_end) );
2159      VG_(debugLog)(1,"redir",
2160                      "transfer ownership V -> C of 0x%llx .. 0x%llx\n",
2161                      (ULong)co_start, (ULong)co_endPlus-1 );
2162
2163      change_ownership_v_c_OK 
2164         = VG_(am_change_ownership_v_to_c)( co_start, co_endPlus - co_start );
2165      vg_assert(change_ownership_v_c_OK);
2166    }
2167
2168    if (VG_(clo_xml)) {
2169       HChar buf[50];
2170       VG_(elapsed_wallclock_time)(buf);
2171       VG_(printf_xml)( "<status>\n"
2172                        "  <state>RUNNING</state>\n"
2173                        "  <time>%pS</time>\n"
2174                        "</status>\n",
2175                        buf );
2176       VG_(printf_xml)( "\n" );
2177    }
2178
2179    VG_(init_Threads)();
2180
2181    //--------------------------------------------------------------
2182    // Initialise the scheduler (phase 1) [generates tid_main]
2183    //   p: none, afaics
2184    //--------------------------------------------------------------
2185    VG_(debugLog)(1, "main", "Initialise scheduler (phase 1)\n");
2186    tid_main = VG_(scheduler_init_phase1)();
2187    vg_assert(tid_main >= 0 && tid_main < VG_N_THREADS
2188              && tid_main != VG_INVALID_THREADID);
2189    /* Tell the tool about tid_main */
2190    VG_TRACK( pre_thread_ll_create, VG_INVALID_THREADID, tid_main );
2191    
2192    //--------------------------------------------------------------
2193    // Tell the tool about the initial client memory permissions
2194    //   p: aspacem
2195    //   p: mallocfree
2196    //   p: setup_client_stack
2197    //   p: setup_client_dataseg
2198    //
2199    // For each segment we tell the client about, look up in 
2200    // addr2dihandle as created above, to see if there's a debuginfo
2201    // handle associated with the segment, that we can hand along
2202    // to the tool, to be helpful.
2203    //--------------------------------------------------------------
2204    VG_(debugLog)(1, "main", "Tell tool about initial permissions\n");
2205    { Addr*     seg_starts;
2206      Int       n_seg_starts;
2207
2208      tl_assert(addr2dihandle);
2209
2210      /* Mark the main thread as running while we tell the tool about
2211         the client memory so that the tool can associate that memory
2212         with the main thread. */
2213      tl_assert(VG_(running_tid) == VG_INVALID_THREADID);
2214      VG_(running_tid) = tid_main;
2215
2216      seg_starts = VG_(get_segment_starts)( &n_seg_starts );
2217      vg_assert(seg_starts && n_seg_starts >= 0);
2218
2219      /* show interesting ones to the tool */
2220      for (i = 0; i < n_seg_starts; i++) {
2221         Word j, n;
2222         NSegment const* seg 
2223            = VG_(am_find_nsegment)( seg_starts[i] );
2224         vg_assert(seg);
2225         if (seg->kind == SkFileC || seg->kind == SkAnonC) {
2226           /* This next assertion is tricky.  If it is placed
2227              immediately before this 'if', it very occasionally fails.
2228              Why?  Because previous iterations of the loop may have
2229              caused tools (via the new_mem_startup calls) to do
2230              dynamic memory allocation, and that may affect the mapped
2231              segments; in particular it may cause segment merging to
2232              happen.  Hence we cannot assume that seg_starts[i], which
2233              reflects the state of the world before we started this
2234              loop, is the same as seg->start, as the latter reflects
2235              the state of the world (viz, mappings) at this particular
2236              iteration of the loop.
2237
2238              Why does moving it inside the 'if' make it safe?  Because
2239              any dynamic memory allocation done by the tools will
2240              affect only the state of Valgrind-owned segments, not of
2241              Client-owned segments.  And the 'if' guards against that
2242              -- we only get in here for Client-owned segments.
2243
2244              In other words: the loop may change the state of
2245              Valgrind-owned segments as it proceeds.  But it should
2246              not cause the Client-owned segments to change. */
2247            vg_assert(seg->start == seg_starts[i]);
2248            VG_(debugLog)(2, "main", 
2249                             "tell tool about %010lx-%010lx %c%c%c\n",
2250                              seg->start, seg->end,
2251                              seg->hasR ? 'r' : '-',
2252                              seg->hasW ? 'w' : '-',
2253                              seg->hasX ? 'x' : '-' );
2254            /* search addr2dihandle to see if we have an entry
2255               matching seg->start. */
2256            n = VG_(sizeXA)( addr2dihandle );
2257            for (j = 0; j < n; j++) {
2258               Addr_n_ULong* anl = VG_(indexXA)( addr2dihandle, j );
2259               if (anl->a == seg->start) {
2260                   tl_assert(anl->ull > 0); /* check it's a valid handle */
2261                   break;
2262               }
2263            }
2264            vg_assert(j >= 0 && j <= n);
2265            VG_TRACK( new_mem_startup, seg->start, seg->end+1-seg->start, 
2266                      seg->hasR, seg->hasW, seg->hasX,
2267                      /* and the retrieved debuginfo handle, if any */
2268                      j < n
2269                      ? ((Addr_n_ULong*)VG_(indexXA)( addr2dihandle, j ))->ull
2270                         : 0 );
2271         }
2272      }
2273
2274      VG_(free)( seg_starts );
2275      VG_(deleteXA)( addr2dihandle );
2276
2277      /* Also do the initial stack permissions. */
2278      {
2279        SSizeT inaccessible_len;
2280        NSegment const* seg 
2281           = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
2282        vg_assert(seg);
2283        vg_assert(seg->kind == SkAnonC);
2284        vg_assert(the_iifii.initial_client_SP >= seg->start);
2285        vg_assert(the_iifii.initial_client_SP <= seg->end);
2286
2287        /* Stuff below the initial SP is unaddressable.  Take into
2288           account any ABI-mandated space below the stack pointer that
2289           is required (VG_STACK_REDZONE_SZB).  setup_client_stack()
2290           will have allocated an extra page if a red zone is required,
2291           to be on the safe side. */
2292        inaccessible_len = the_iifii.initial_client_SP - VG_STACK_REDZONE_SZB 
2293                           - seg->start;
2294        vg_assert(inaccessible_len >= 0);
2295        if (inaccessible_len > 0)
2296           VG_TRACK( die_mem_stack, 
2297                     seg->start, 
2298                     inaccessible_len );
2299        VG_(debugLog)(2, "main", "mark stack inaccessible %010lx-%010lx\n",
2300                         seg->start, 
2301                         the_iifii.initial_client_SP-1 - VG_STACK_REDZONE_SZB);
2302      }
2303
2304      /* Also the assembly helpers. */
2305      VG_TRACK( new_mem_startup,
2306                (Addr)&VG_(trampoline_stuff_start),
2307                (Addr)&VG_(trampoline_stuff_end) 
2308                   - (Addr)&VG_(trampoline_stuff_start),
2309                False, /* readable? */
2310                False, /* writable? */
2311                True   /* executable? */,
2312                0 /* di_handle: no associated debug info */ );
2313
2314      /* Clear the running thread indicator */
2315      VG_(running_tid) = VG_INVALID_THREADID;
2316      tl_assert(VG_(running_tid) == VG_INVALID_THREADID);
2317    }
2318
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 );
2328      vg_assert(seg);
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 );
2334    }
2335
2336    //--------------------------------------------------------------
2337    // Set up state for the root thread
2338    //   p: ?
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 );
2344
2345    //--------------------------------------------------------------
2346    // Initialise the signal handling subsystem
2347    //   p: n/a
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)();
2355
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)();
2363    }
2364
2365    //--------------------------------------------------------------
2366    // register client stack
2367    //--------------------------------------------------------------
2368    VG_(clstk_id) = VG_(register_stack)(VG_(clstk_base), VG_(clstk_end));
2369
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");
2378
2379    //--------------------------------------------------------------
2380    // Run!
2381    //--------------------------------------------------------------
2382    VG_(debugLog)(1, "main", "Running thread 1\n");
2383
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
2391       to. */
2392
2393    /* Set continuation address. */
2394    VG_(address_of_m_main_shutdown_actions_NORETURN)
2395       = & shutdown_actions_NORETURN;
2396
2397    /* Run the first thread, eventually ending up at the continuation
2398       address. */
2399    VG_(main_thread_wrapper_NORETURN)(1);
2400
2401    /*NOTREACHED*/
2402    vg_assert(0);
2403 }
2404
2405 /* Do everything which needs doing when the last thread exits or when
2406    a thread exits requesting a complete process exit.
2407
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. 
2412
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.
2416    So don't. 
2417
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. */
2421
2422 static 
2423 void shutdown_actions_NORETURN( ThreadId tid, 
2424                                 VgSchedReturnCode tids_schedretcode )
2425 {
2426    VG_(debugLog)(1, "main", "entering VG_(shutdown_actions_NORETURN)\n");
2427    VG_(am_show_nsegments)(1,"Memory layout at client shutdown");
2428
2429    vg_assert(VG_(is_running_thread)(tid));
2430
2431    vg_assert(tids_schedretcode == VgSrc_ExitThread
2432              || tids_schedretcode == VgSrc_ExitProcess
2433              || tids_schedretcode == VgSrc_FatalSig );
2434
2435    if (tids_schedretcode == VgSrc_ExitThread) {
2436
2437       // We are the last surviving thread.  Right?
2438       vg_assert( VG_(count_living_threads)() == 1 );
2439
2440       // Wait for all other threads to exit.
2441       // jrs: Huh?  but they surely are already gone
2442       VG_(reap_threads)(tid);
2443
2444       // Clean the client up before the final report
2445       // this causes the libc_freeres function to run
2446       final_tidyup(tid);
2447
2448       /* be paranoid */
2449       vg_assert(VG_(is_running_thread)(tid));
2450       vg_assert(VG_(count_living_threads)() == 1);
2451
2452    } else {
2453
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 );
2459
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
2463       final_tidyup(tid);
2464
2465       /* be paranoid */
2466       vg_assert(VG_(is_running_thread)(tid));
2467       vg_assert(VG_(count_living_threads)() >= 1);
2468    }
2469
2470    VG_(threads)[tid].status = VgTs_Empty;
2471    //--------------------------------------------------------------
2472    // Finalisation: cleanup, messages, etc.  Order not so important, only
2473    // affects what order the messages come.
2474    //--------------------------------------------------------------
2475    // First thing in the post-amble is a blank line.
2476    if (VG_(clo_xml))
2477       VG_(printf_xml)("\n");
2478    else if (VG_(clo_verbosity) > 0)
2479       VG_(message)(Vg_UserMsg, "\n");
2480
2481    if (VG_(clo_xml)) {
2482       HChar buf[50];
2483       VG_(elapsed_wallclock_time)(buf);
2484       VG_(printf_xml)( "<status>\n"
2485                               "  <state>FINISHED</state>\n"
2486                               "  <time>%pS</time>\n"
2487                               "</status>\n"
2488                               "\n",
2489                               buf);
2490    }
2491
2492    /* Print out file descriptor summary and stats. */
2493    if (VG_(clo_track_fds))
2494       VG_(show_open_fds)("at exit");
2495
2496    /* Call the tool's finalisation function.  This makes Memcheck's
2497       leak checker run, and possibly chuck a bunch of leak errors into
2498       the error management machinery. */
2499    VG_TDICT_CALL(tool_fini, 0/*exitcode*/);
2500
2501    /* Show the error counts. */
2502    if (VG_(clo_xml)
2503        && (VG_(needs).core_errors || VG_(needs).tool_errors)) {
2504       VG_(show_error_counts_as_XML)();
2505    }
2506
2507    /* In XML mode, this merely prints the used suppressions. */
2508    if (VG_(needs).core_errors || VG_(needs).tool_errors)
2509       VG_(show_all_errors)(VG_(clo_verbosity), VG_(clo_xml));
2510
2511    if (VG_(clo_xml)) {
2512       VG_(printf_xml)("\n");
2513       VG_(printf_xml)("</valgrindoutput>\n");
2514       VG_(printf_xml)("\n");
2515    }
2516
2517    VG_(sanity_check_general)( True /*include expensive checks*/ );
2518
2519    if (VG_(clo_stats))
2520       print_all_stats();
2521
2522    /* Show a profile of the heap(s) at shutdown.  Optionally, first
2523       throw away all the debug info, as that makes it easy to spot
2524       leaks in the debuginfo reader. */
2525    if (VG_(clo_profile_heap)) {
2526       if (0) VG_(di_discard_ALL_debuginfo)();
2527       VG_(print_arena_cc_analysis)();
2528    }
2529
2530    if (VG_(clo_profile_flags) > 0) {
2531       #define N_MAX 200
2532       BBProfEntry tops[N_MAX];
2533       ULong score_total = VG_(get_BB_profile) (tops, N_MAX);
2534       show_BB_profile(tops, N_MAX, score_total);
2535    }
2536
2537    /* Print Vex storage stats */
2538    if (0)
2539        LibVEX_ShowAllocStats();
2540
2541    /* Flush any output cached by previous calls to VG_(message). */
2542    VG_(message_flush)();
2543
2544    /* terminate gdbserver if ever it was started. We terminate it here so that it get
2545       the output above if output was redirected to gdb */
2546    VG_(gdbserver_exit) (tid, tids_schedretcode);
2547
2548    /* Ok, finally exit in the os-specific way, according to the scheduler's
2549       return code.  In short, if the (last) thread exited by calling
2550       sys_exit, do likewise; if the (last) thread stopped due to a fatal
2551       signal, terminate the entire system with that same fatal signal. */
2552    VG_(debugLog)(1, "core_os", 
2553                     "VG_(terminate_NORETURN)(tid=%lld)\n", (ULong)tid);
2554
2555    switch (tids_schedretcode) {
2556    case VgSrc_ExitThread:  /* the normal way out (Linux) */
2557    case VgSrc_ExitProcess: /* the normal way out (AIX) -- still needed? */
2558       /* Change the application return code to user's return code,
2559          if an error was found */
2560       if (VG_(clo_error_exitcode) > 0 
2561           && VG_(get_n_errs_found)() > 0) {
2562          VG_(exit)( VG_(clo_error_exitcode) );
2563       } else {
2564          /* otherwise, return the client's exit code, in the normal
2565             way. */
2566          VG_(exit)( VG_(threads)[tid].os_state.exitcode );
2567       }
2568       /* NOT ALIVE HERE! */
2569       VG_(core_panic)("entered the afterlife in main() -- ExitT/P");
2570       break; /* what the hell :) */
2571
2572    case VgSrc_FatalSig:
2573       /* We were killed by a fatal signal, so replicate the effect */
2574       vg_assert(VG_(threads)[tid].os_state.fatalsig != 0);
2575       VG_(kill_self)(VG_(threads)[tid].os_state.fatalsig);
2576       /* we shouldn't be alive at this point.  But VG_(kill_self)
2577          sometimes fails with EPERM on Darwin, for unclear reasons. */
2578 #     if defined(VGO_darwin)
2579       VG_(debugLog)(0, "main", "VG_(kill_self) failed.  Exiting normally.\n");
2580       VG_(exit)(0); /* bogus, but we really need to exit now */
2581       /* fall through .. */
2582 #     endif
2583       VG_(core_panic)("main(): signal was supposed to be fatal");
2584       break;
2585
2586    default:
2587       VG_(core_panic)("main(): unexpected scheduler return code");
2588    }
2589 }
2590
2591 /* -------------------- */
2592
2593 /* Final clean-up before terminating the process.  
2594    Clean up the client by calling __libc_freeres() (if requested) 
2595    This is Linux-specific?
2596    GrP fixme glibc-specific, anyway
2597 */
2598 static void final_tidyup(ThreadId tid)
2599 {
2600 #if !defined(VGO_darwin)
2601 #  if defined(VGP_ppc64_linux)
2602    Addr r2;
2603 #  endif
2604    Addr __libc_freeres_wrapper = VG_(client___libc_freeres_wrapper);
2605
2606    vg_assert(VG_(is_running_thread)(tid));
2607    
2608    if ( !VG_(needs).libc_freeres ||
2609         !VG_(clo_run_libc_freeres) ||
2610         0 == __libc_freeres_wrapper )
2611       return;                   /* can't/won't do it */
2612
2613 #  if defined(VGP_ppc64_linux)
2614    r2 = VG_(get_tocptr)( __libc_freeres_wrapper );
2615    if (r2 == 0) {
2616       VG_(message)(Vg_UserMsg, 
2617                    "Caught __NR_exit, but can't run __libc_freeres()\n");
2618       VG_(message)(Vg_UserMsg, 
2619                    "   since cannot establish TOC pointer for it.\n");
2620       return;
2621    }
2622 #  endif
2623
2624    if (VG_(clo_verbosity) > 2  ||
2625        VG_(clo_trace_syscalls) ||
2626        VG_(clo_trace_sched))
2627       VG_(message)(Vg_DebugMsg, 
2628                    "Caught __NR_exit; running __libc_freeres()\n");
2629       
2630    /* set thread context to point to libc_freeres_wrapper */
2631    /* ppc64-linux note: __libc_freeres_wrapper gives us the real
2632       function entry point, not a fn descriptor, so can use it
2633       directly.  However, we need to set R2 (the toc pointer)
2634       appropriately. */
2635    VG_(set_IP)(tid, __libc_freeres_wrapper);
2636 #  if defined(VGP_ppc64_linux)
2637    VG_(threads)[tid].arch.vex.guest_GPR2 = r2;
2638 #  endif
2639    /* mips-linux note: we need to set t9 */
2640 #  if defined(VGP_mips32_linux)
2641    VG_(threads)[tid].arch.vex.guest_r25 = __libc_freeres_wrapper;
2642 #  endif
2643
2644    /* Block all blockable signals by copying the real block state into
2645       the thread's block state*/
2646    VG_(sigprocmask)(VKI_SIG_BLOCK, NULL, &VG_(threads)[tid].sig_mask);
2647    VG_(threads)[tid].tmp_sig_mask = VG_(threads)[tid].sig_mask;
2648
2649    /* and restore handlers to default */
2650    VG_(set_default_handler)(VKI_SIGSEGV);
2651    VG_(set_default_handler)(VKI_SIGBUS);
2652    VG_(set_default_handler)(VKI_SIGILL);
2653    VG_(set_default_handler)(VKI_SIGFPE);
2654
2655    // We were exiting, so assert that...
2656    vg_assert(VG_(is_exiting)(tid));
2657    // ...but now we're not again
2658    VG_(threads)[tid].exitreason = VgSrc_None;
2659
2660    // run until client thread exits - ideally with LIBC_FREERES_DONE,
2661    // but exit/exitgroup/signal will do
2662    VG_(scheduler)(tid);
2663
2664    vg_assert(VG_(is_exiting)(tid));
2665 #endif
2666 }
2667
2668
2669 /*====================================================================*/
2670 /*=== Getting to main() alive: LINUX                               ===*/
2671 /*====================================================================*/
2672
2673 #if defined(VGO_linux)
2674
2675 /* If linking of the final executables is done with glibc present,
2676    then Valgrind starts at main() above as usual, and all of the
2677    following code is irrelevant.
2678
2679    However, this is not the intended mode of use.  The plan is to
2680    avoid linking against glibc, by giving gcc the flags 
2681    -nodefaultlibs -lgcc -nostartfiles at startup.
2682
2683    From this derive two requirements:
2684
2685    1. gcc may emit calls to memcpy and memset to deal with structure
2686       assignments etc.  Since we have chosen to ignore all the
2687       "normal" supporting libraries, we have to provide our own
2688       implementations of them.  No problem.
2689
2690    2. We have to provide a symbol "_start", to which the kernel
2691       hands control at startup.  Hence the code below.
2692 */
2693
2694 /* ---------------- Requirement 1 ---------------- */
2695
2696 void* memcpy(void *dest, const void *src, SizeT n);
2697 void* memcpy(void *dest, const void *src, SizeT n) {
2698    return VG_(memcpy)(dest,src,n);
2699 }
2700 void* memset(void *s, int c, SizeT n);
2701 void* memset(void *s, int c, SizeT n) {
2702   return VG_(memset)(s,c,n);
2703 }
2704
2705 /* BVA: abort() for those platforms that need it (PPC and ARM). */
2706 void abort(void);
2707 void abort(void){
2708    VG_(printf)("Something called raise().\n");
2709    vg_assert(0);
2710 }
2711
2712 /* EAZG: ARM's EABI will call floating point exception handlers in
2713    libgcc which boil down to an abort or raise, that's usually defined
2714    in libc. Instead, define them here. */
2715 #if defined(VGP_arm_linux)
2716 void raise(void);
2717 void raise(void){
2718    VG_(printf)("Something called raise().\n");
2719    vg_assert(0);
2720 }
2721
2722 void __aeabi_unwind_cpp_pr0(void);
2723 void __aeabi_unwind_cpp_pr0(void){
2724    VG_(printf)("Something called __aeabi_unwind_cpp_pr0()\n");
2725    vg_assert(0);
2726 }
2727
2728 void __aeabi_unwind_cpp_pr1(void);
2729 void __aeabi_unwind_cpp_pr1(void){
2730    VG_(printf)("Something called __aeabi_unwind_cpp_pr1()\n");
2731    vg_assert(0);
2732 }
2733 #endif
2734
2735 /* ---------------- Requirement 2 ---------------- */
2736
2737 /* Glibc's sysdeps/i386/elf/start.S has the following gem of a
2738    comment, which explains how the stack looks right at process start
2739    (when _start is jumped to).  Hence _start passes %esp to
2740    _start_in_C_linux, which extracts argc/argv/envp and starts up
2741    correctly. */
2742
2743 /* This is the canonical entry point, usually the first thing in the text
2744    segment.  The SVR4/i386 ABI (pages 3-31, 3-32) says that when the entry
2745    point runs, most registers' values are unspecified, except for:
2746
2747    %edx         Contains a function pointer to be registered with `atexit'.
2748                 This is how the dynamic linker arranges to have DT_FINI
2749                 functions called for shared libraries that have been loaded
2750                 before this code runs.
2751
2752    %esp         The stack contains the arguments and environment:
2753                 0(%esp)                 argc
2754                 4(%esp)                 argv[0]
2755                 ...
2756                 (4*argc)(%esp)          NULL
2757                 (4*(argc+1))(%esp)      envp[0]
2758                 ...
2759                                         NULL
2760 */
2761
2762 /* The kernel hands control to _start, which extracts the initial
2763    stack pointer and calls onwards to _start_in_C_linux.  This also switches
2764    the new stack.  */
2765 #if defined(VGP_x86_linux)
2766 asm("\n"
2767     ".text\n"
2768     "\t.globl _start\n"
2769     "\t.type _start,@function\n"
2770     "_start:\n"
2771     /* set up the new stack in %eax */
2772     "\tmovl  $vgPlain_interim_stack, %eax\n"
2773     "\taddl  $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
2774     "\taddl  $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
2775     "\tsubl  $16, %eax\n"
2776     "\tandl  $~15, %eax\n"
2777     /* install it, and collect the original one */
2778     "\txchgl %eax, %esp\n"
2779     /* call _start_in_C_linux, passing it the startup %esp */
2780     "\tpushl %eax\n"
2781     "\tcall  _start_in_C_linux\n"
2782     "\thlt\n"
2783     ".previous\n"
2784 );
2785 #elif defined(VGP_amd64_linux)
2786 asm("\n"
2787     ".text\n"
2788     "\t.globl _start\n"
2789     "\t.type _start,@function\n"
2790     "_start:\n"
2791     /* set up the new stack in %rdi */
2792     "\tmovq  $vgPlain_interim_stack, %rdi\n"
2793     "\taddq  $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
2794     "\taddq  $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
2795     "\tandq  $~15, %rdi\n"
2796     /* install it, and collect the original one */
2797     "\txchgq %rdi, %rsp\n"
2798     /* call _start_in_C_linux, passing it the startup %rsp */
2799     "\tcall  _start_in_C_linux\n"
2800     "\thlt\n"
2801     ".previous\n"
2802 );
2803 #elif defined(VGP_ppc32_linux)
2804 asm("\n"
2805     ".text\n"
2806     "\t.globl _start\n"
2807     "\t.type _start,@function\n"
2808     "_start:\n"
2809     /* set up the new stack in r16 */
2810     "\tlis 16,vgPlain_interim_stack@ha\n"
2811     "\tla  16,vgPlain_interim_stack@l(16)\n"
2812     "\tlis    17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2813     "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2814     "\tlis    18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2815     "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2816     "\tadd 16,17,16\n"
2817     "\tadd 16,18,16\n"
2818     "\trlwinm 16,16,0,0,27\n"
2819     /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2820        VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2821        boundary.  And r1 is the original SP.  Set the SP to r16 and
2822        call _start_in_C_linux, passing it the initial SP. */
2823     "\tmr 3,1\n"
2824     "\tmr 1,16\n"
2825     "\tbl _start_in_C_linux\n"
2826     "\ttrap\n"
2827     ".previous\n"
2828 );
2829 #elif defined(VGP_ppc64_linux)
2830 asm("\n"
2831     /* PPC64 ELF ABI says '_start' points to a function descriptor.
2832        So we must have one, and that is what goes into the .opd section. */
2833     "\t.align 2\n"
2834     "\t.global _start\n"
2835     "\t.section \".opd\",\"aw\"\n"
2836     "\t.align 3\n"
2837     "_start:\n"
2838     "\t.quad ._start,.TOC.@tocbase,0\n"
2839     "\t.previous\n"
2840     "\t.type ._start,@function\n"
2841     "\t.global  ._start\n"
2842     "._start:\n"
2843     /* set up the new stack in r16 */
2844     "\tlis  16,   vgPlain_interim_stack@highest\n"
2845     "\tori  16,16,vgPlain_interim_stack@higher\n"
2846     "\tsldi 16,16,32\n"
2847     "\toris 16,16,vgPlain_interim_stack@h\n"
2848     "\tori  16,16,vgPlain_interim_stack@l\n"
2849     "\txor  17,17,17\n"
2850     "\tlis    17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2851     "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2852     "\txor 18,18,18\n"
2853     "\tlis    18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2854     "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2855     "\tadd 16,17,16\n"
2856     "\tadd 16,18,16\n"
2857     "\trldicr 16,16,0,59\n"
2858     /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2859        VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2860        boundary.  And r1 is the original SP.  Set the SP to r16 and
2861        call _start_in_C_linux, passing it the initial SP. */
2862     "\tmr 3,1\n"
2863     "\tmr 1,16\n"
2864     "\tlis  14,   _start_in_C_linux@highest\n"
2865     "\tori  14,14,_start_in_C_linux@higher\n"
2866     "\tsldi 14,14,32\n"
2867     "\toris 14,14,_start_in_C_linux@h\n"
2868     "\tori  14,14,_start_in_C_linux@l\n"
2869     "\tld 14,0(14)\n"
2870     "\tmtctr 14\n"
2871     "\tbctrl\n"
2872     "\tnop\n"
2873     "\ttrap\n"
2874 );
2875 #elif defined(VGP_s390x_linux)
2876 /*
2877     This is the canonical entry point, usually the first thing in the text
2878     segment. Most registers' values are unspecified, except for:
2879
2880     %r14         Contains a function pointer to be registered with `atexit'.
2881                  This is how the dynamic linker arranges to have DT_FINI
2882                  functions called for shared libraries that have been loaded
2883                  before this code runs.
2884
2885     %r15         The stack contains the arguments and environment:
2886                  0(%r15)              argc
2887                  8(%r15)              argv[0]
2888                  ...
2889                  (8*argc)(%r15)       NULL
2890                  (8*(argc+1))(%r15)   envp[0]
2891                  ...
2892                                       NULL
2893 */
2894 asm("\n\t"
2895     ".text\n\t"
2896     ".globl _start\n\t"
2897     ".type  _start,@function\n\t"
2898     "_start:\n\t"
2899     /* set up the new stack in %r1 */
2900     "larl   %r1,  vgPlain_interim_stack\n\t"
2901     "larl   %r5,  1f\n\t"
2902     "ag     %r1,  0(%r5)\n\t"
2903     "ag     %r1,  2f-1f(%r5)\n\t"
2904     "nill   %r1,  0xFFF0\n\t"
2905     /* install it, and collect the original one */
2906     "lgr    %r2,  %r15\n\t"
2907     "lgr    %r15, %r1\n\t"
2908     /* call _start_in_C_linux, passing it the startup %r15 */
2909     "brasl  %r14, _start_in_C_linux\n\t"
2910     /* trigger execution of an invalid opcode -> halt machine */
2911     "j      .+2\n\t"
2912     "1:   .quad "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n\t"
2913     "2:   .quad "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n\t"
2914     ".previous\n"
2915 );
2916 #elif defined(VGP_arm_linux)
2917 asm("\n"
2918     "\t.text\n"
2919     "\t.align 4\n"
2920     "\t.type _start,#function\n"
2921     "\t.global _start\n"
2922     "_start:\n"
2923     "\tldr  r0, [pc, #36]\n"
2924     "\tldr  r1, [pc, #36]\n"
2925     "\tadd  r0, r1, r0\n"
2926     "\tldr  r1, [pc, #32]\n"
2927     "\tadd  r0, r1, r0\n"
2928     "\tmvn  r1, #15\n"
2929     "\tand  r0, r0, r1\n"
2930     "\tmov  r1, sp\n"
2931     "\tmov  sp, r0\n"
2932     "\tmov  r0, r1\n"
2933     "\tb _start_in_C_linux\n"
2934     "\t.word vgPlain_interim_stack\n"
2935     "\t.word "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
2936     "\t.word "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
2937 );
2938 #elif defined(VGP_mips32_linux)
2939 asm("\n"
2940     "\t.type _gp_disp,@object\n"
2941     ".text\n"
2942     "\t.globl __start\n"
2943     "\t.type __start,@function\n"
2944     "__start:\n"
2945
2946     "\tbal 1f\n"
2947     "\tnop\n"
2948     
2949     "1:\n"    
2950
2951     "\tlui      $28, %hi(_gp_disp)\n"
2952     "\taddiu    $28, $28, %lo(_gp_disp)\n"
2953     "\taddu     $28, $28, $31\n"
2954     /* t1/$9 <- Addr(interim_stack) */
2955     "\tlui      $9, %hi(vgPlain_interim_stack)\n"
2956     /* t1/$9 <- Addr(interim_stack) */
2957     "\taddiu    $9, %lo(vgPlain_interim_stack)\n"
2958
2959
2960     "\tli    $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
2961     "\tli    $11, "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
2962     
2963     "\taddu     $9, $9, $10\n"
2964     "\taddu     $9, $9, $11\n"
2965     "\tli       $12, 0xFFFFFFF0\n"
2966     "\tand      $9, $9, $12\n"
2967     /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2968        VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2969        boundary.  And $29 is the original SP.  Set the SP to t1 and
2970        call _start_in_C, passing it the initial SP. */
2971        
2972     "\tmove    $4, $29\n"     // a0 <- $sp (_start_in_C first arg)
2973     "\tmove    $29, $9\n"     // $sp <- t1 (new sp)
2974     
2975     "\tlui     $25, %hi(_start_in_C_linux)\n"
2976     "\taddiu   $25, %lo(_start_in_C_linux)\n"
2977     
2978     "\tbal  _start_in_C_linux\n"
2979     "\tbreak  0x7\n"
2980     ".previous\n"
2981 );
2982 #else
2983 #  error "Unknown linux platform"
2984 #endif
2985
2986 /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
2987 #define _GNU_SOURCE
2988 #define _FILE_OFFSET_BITS 64
2989 /* This is in order to get AT_NULL and AT_PAGESIZE. */
2990 #include <elf.h>
2991 /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
2992
2993 /* Avoid compiler warnings: this fn _is_ used, but labelling it
2994    'static' causes gcc to complain it isn't.
2995    attribute 'used' also ensures the code is not eliminated at link
2996    time */
2997 __attribute__ ((used))
2998 void _start_in_C_linux ( UWord* pArgc );
2999 __attribute__ ((used))
3000 void _start_in_C_linux ( UWord* pArgc )
3001 {
3002    Int     r;
3003    Word    argc = pArgc[0];
3004    HChar** argv = (HChar**)&pArgc[1];
3005    HChar** envp = (HChar**)&pArgc[1+argc+1];
3006
3007    VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3008    VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3009
3010    the_iicii.sp_at_startup = (Addr)pArgc;
3011
3012 #  if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux)
3013    {
3014       /* ppc/ppc64 can be configured with different page sizes.
3015          Determine this early.  This is an ugly hack and really should
3016          be moved into valgrind_main. */
3017       UWord *sp = &pArgc[1+argc+1];
3018       while (*sp++ != 0)
3019          ;
3020       for (; *sp != AT_NULL && *sp != AT_PAGESZ; sp += 2);
3021       if (*sp == AT_PAGESZ) {
3022          VKI_PAGE_SIZE = sp[1];
3023          for (VKI_PAGE_SHIFT = 12;
3024               VKI_PAGE_SHIFT <= VKI_MAX_PAGE_SHIFT; VKI_PAGE_SHIFT++)
3025             if (VKI_PAGE_SIZE == (1UL << VKI_PAGE_SHIFT))
3026          break;
3027       }
3028    }
3029 #  endif
3030
3031    r = valgrind_main( (Int)argc, argv, envp );
3032    /* NOTREACHED */
3033    VG_(exit)(r);
3034 }
3035
3036
3037 /*====================================================================*/
3038 /*=== Getting to main() alive: darwin                              ===*/
3039 /*====================================================================*/
3040
3041 #elif defined(VGO_darwin)
3042
3043 /*
3044    Memory layout established by kernel:
3045
3046    0(%esp)   argc
3047    4(%esp)   argv[0]
3048              ...
3049              argv[argc-1]
3050              NULL
3051              envp[0]
3052              ...
3053              envp[n]
3054              NULL
3055              executable name (presumably, a pointer to it)
3056              NULL
3057
3058    Ditto in the 64-bit case, except all offsets from SP are obviously
3059    twice as large.
3060 */
3061
3062 /* The kernel hands control to _start, which extracts the initial
3063    stack pointer and calls onwards to _start_in_C_darwin.  This also
3064    switches to the new stack.  */
3065 #if defined(VGP_x86_darwin)
3066 asm("\n"
3067     ".text\n"
3068     ".align 2,0x90\n"
3069     "\t.globl __start\n"
3070     "__start:\n"
3071     /* set up the new stack in %eax */
3072     "\tmovl  $_vgPlain_interim_stack, %eax\n"
3073     "\taddl  $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
3074     "\taddl  $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
3075     "\tsubl  $16, %eax\n"
3076     "\tandl  $~15, %eax\n"
3077     /* install it, and collect the original one */
3078     "\txchgl %eax, %esp\n"
3079     "\tsubl  $12, %esp\n"  // keep stack 16 aligned; see #295428
3080     /* call _start_in_C_darwin, passing it the startup %esp */
3081     "\tpushl %eax\n"
3082     "\tcall  __start_in_C_darwin\n"
3083     "\tint $3\n"
3084     "\tint $3\n"
3085 );
3086 #elif defined(VGP_amd64_darwin)
3087 asm("\n"
3088     ".text\n"
3089     "\t.globl __start\n"
3090     ".align 3,0x90\n"
3091     "__start:\n"
3092     /* set up the new stack in %rdi */
3093     "\tmovabsq $_vgPlain_interim_stack, %rdi\n"
3094     "\taddq    $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
3095     "\taddq    $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
3096     "\tandq    $~15, %rdi\n"
3097     /* install it, and collect the original one */
3098     "\txchgq %rdi, %rsp\n"
3099     /* call _start_in_C_darwin, passing it the startup %rsp */
3100     "\tcall  __start_in_C_darwin\n"
3101     "\tint $3\n"
3102     "\tint $3\n"
3103 );
3104 #endif
3105
3106 void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2);
3107 void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2) {
3108     // skip check
3109    return VG_(memcpy)(dest,src,n);
3110 }
3111 void* __memset_chk(void *s, int c, SizeT n, SizeT n2);
3112 void* __memset_chk(void *s, int c, SizeT n, SizeT n2) {
3113     // skip check
3114   return VG_(memset)(s,c,n);
3115 }
3116 void bzero(void *s, SizeT n);
3117 void bzero(void *s, SizeT n) {
3118     VG_(memset)(s,0,n);
3119 }
3120
3121 void* memcpy(void *dest, const void *src, SizeT n);
3122 void* memcpy(void *dest, const void *src, SizeT n) {
3123    return VG_(memcpy)(dest,src,n);
3124 }
3125 void* memset(void *s, int c, SizeT n);
3126 void* memset(void *s, int c, SizeT n) {
3127   return VG_(memset)(s,c,n);
3128 }
3129
3130 /* Avoid compiler warnings: this fn _is_ used, but labelling it
3131    'static' causes gcc to complain it isn't. */
3132 void _start_in_C_darwin ( UWord* pArgc );
3133 void _start_in_C_darwin ( UWord* pArgc )
3134 {
3135    Int     r;
3136    Int     argc = *(Int *)pArgc;  // not pArgc[0] on LP64
3137    HChar** argv = (HChar**)&pArgc[1];
3138    HChar** envp = (HChar**)&pArgc[1+argc+1];
3139
3140    VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3141    VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3142
3143    the_iicii.sp_at_startup = (Addr)pArgc;
3144
3145    r = valgrind_main( (Int)argc, argv, envp );
3146    /* NOTREACHED */
3147    VG_(exit)(r);
3148 }
3149
3150
3151 #else
3152
3153 #  error "Unknown OS"
3154 #endif
3155
3156
3157 /*====================================================================*/
3158 /*=== {u,}{div,mod}di3 replacements                                ===*/
3159 /*====================================================================*/
3160
3161 /* For static linking on x86-darwin, we need to supply our own 64-bit
3162    integer division code, else the link dies thusly:
3163
3164    ld_classic: Undefined symbols:
3165      ___udivdi3
3166      ___umoddi3
3167 */
3168 #if defined(VGP_x86_darwin)
3169
3170 /* Routines for doing signed/unsigned 64 x 64 ==> 64 div and mod
3171    (udivdi3, umoddi3, divdi3, moddi3) using only 32 x 32 ==> 32
3172    division.  Cobbled together from
3173
3174    http://www.hackersdelight.org/HDcode/divlu.c
3175    http://www.hackersdelight.org/HDcode/divls.c
3176    http://www.hackersdelight.org/HDcode/newCode/divDouble.c
3177
3178    The code from those three files is covered by the following license,
3179    as it appears at:
3180
3181    http://www.hackersdelight.org/permissions.htm
3182
3183       You are free to use, copy, and distribute any of the code on
3184       this web site, whether modified by you or not. You need not give
3185       attribution. This includes the algorithms (some of which appear
3186       in Hacker's Delight), the Hacker's Assistant, and any code
3187       submitted by readers. Submitters implicitly agree to this.
3188 */
3189
3190 /* Long division, unsigned (64/32 ==> 32).
3191    This procedure performs unsigned "long division" i.e., division of a
3192 64-bit unsigned dividend by a 32-bit unsigned divisor, producing a
3193 32-bit quotient.  In the overflow cases (divide by 0, or quotient
3194 exceeds 32 bits), it returns a remainder of 0xFFFFFFFF (an impossible
3195 value).
3196    The dividend is u1 and u0, with u1 being the most significant word.
3197 The divisor is parameter v. The value returned is the quotient.
3198    Max line length is 57, to fit in hacker.book. */
3199
3200 static Int nlz32(UInt x) 
3201 {
3202    Int n;
3203    if (x == 0) return(32);
3204    n = 0;
3205    if (x <= 0x0000FFFF) {n = n +16; x = x <<16;}
3206    if (x <= 0x00FFFFFF) {n = n + 8; x = x << 8;}
3207    if (x <= 0x0FFFFFFF) {n = n + 4; x = x << 4;}
3208    if (x <= 0x3FFFFFFF) {n = n + 2; x = x << 2;}
3209    if (x <= 0x7FFFFFFF) {n = n + 1;}
3210    return n;
3211 }
3212
3213 /* 64 x 32 ==> 32 unsigned division, using only 32 x 32 ==> 32
3214    division as a primitive. */
3215 static UInt divlu2(UInt u1, UInt u0, UInt v, UInt *r)
3216 {
3217    const UInt b = 65536;     // Number base (16 bits).
3218    UInt un1, un0,            // Norm. dividend LSD's.
3219         vn1, vn0,            // Norm. divisor digits.
3220         q1, q0,              // Quotient digits.
3221         un32, un21, un10,    // Dividend digit pairs.
3222         rhat;                // A remainder.
3223    Int s;                    // Shift amount for norm.
3224
3225    if (u1 >= v) {            // If overflow, set rem.
3226       if (r != NULL)         // to an impossible value,
3227          *r = 0xFFFFFFFF;    // and return the largest
3228       return 0xFFFFFFFF;}    // possible quotient.
3229
3230    s = nlz32(v);             // 0 <= s <= 31.
3231    v = v << s;               // Normalize divisor.
3232    vn1 = v >> 16;            // Break divisor up into
3233    vn0 = v & 0xFFFF;         // two 16-bit digits.
3234
3235    un32 = (u1 << s) | ((u0 >> (32 - s)) & (-s >> 31));
3236    un10 = u0 << s;           // Shift dividend left.
3237
3238    un1 = un10 >> 16;         // Break right half of
3239    un0 = un10 & 0xFFFF;      // dividend into two digits.
3240
3241    q1 = un32/vn1;            // Compute the first
3242    rhat = un32 - q1*vn1;     // quotient digit, q1.
3243  again1:
3244    if (q1 >= b || q1*vn0 > b*rhat + un1) {
3245      q1 = q1 - 1;
3246      rhat = rhat + vn1;
3247      if (rhat < b) goto again1;}
3248
3249    un21 = un32*b + un1 - q1*v;  // Multiply and subtract.
3250
3251    q0 = un21/vn1;            // Compute the second
3252    rhat = un21 - q0*vn1;     // quotient digit, q0.
3253  again2:
3254    if (q0 >= b || q0*vn0 > b*rhat + un0) {
3255      q0 = q0 - 1;
3256      rhat = rhat + vn1;
3257      if (rhat < b) goto again2;}
3258
3259    if (r != NULL)            // If remainder is wanted,
3260       *r = (un21*b + un0 - q0*v) >> s;     // return it.
3261    return q1*b + q0;
3262 }
3263
3264
3265 /* 64 x 32 ==> 32 signed division, using only 32 x 32 ==> 32 division
3266    as a primitive. */
3267 static Int divls(Int u1, UInt u0, Int v, Int *r)
3268 {
3269    Int q, uneg, vneg, diff, borrow;
3270
3271    uneg = u1 >> 31;          // -1 if u < 0.
3272    if (uneg) {               // Compute the absolute
3273       u0 = -u0;              // value of the dividend u.
3274       borrow = (u0 != 0);
3275       u1 = -u1 - borrow;}
3276
3277    vneg = v >> 31;           // -1 if v < 0.
3278    v = (v ^ vneg) - vneg;    // Absolute value of v.
3279
3280    if ((UInt)u1 >= (UInt)v) goto overflow;
3281
3282    q = divlu2(u1, u0, v, (UInt *)r);
3283
3284    diff = uneg ^ vneg;       // Negate q if signs of
3285    q = (q ^ diff) - diff;    // u and v differed.
3286    if (uneg && r != NULL)
3287       *r = -*r;
3288
3289    if ((diff ^ q) < 0 && q != 0) {  // If overflow,
3290  overflow:                    // set remainder
3291       if (r != NULL)         // to an impossible value,
3292          *r = 0x80000000;    // and return the largest
3293       q = 0x80000000;}       // possible neg. quotient.
3294    return q;
3295 }
3296
3297
3298
3299 /* This file contains a program for doing 64/64 ==> 64 division, on a
3300 machine that does not have that instruction but that does have
3301 instructions for "long division" (64/32 ==> 32). Code for unsigned
3302 division is given first, followed by a simple program for doing the
3303 signed version by using the unsigned version.
3304    These programs are useful in implementing "long long" (64-bit)
3305 arithmetic on a machine that has the long division instruction. It will
3306 work on 64- and 32-bit machines, provided the compiler implements long
3307 long's (64-bit integers). It is desirable that the machine have the
3308 Count Leading Zeros instruction.
3309    In the GNU world, these programs are known as __divdi3 and __udivdi3,
3310 and similar names are used here.
3311    This material is not in HD, but may be in a future edition.
3312 Max line length is 57, to fit in hacker.book. */
3313
3314
3315 static Int nlz64(ULong x) 
3316 {
3317    Int n;
3318    if (x == 0) return(64);
3319    n = 0;
3320    if (x <= 0x00000000FFFFFFFFULL) {n = n + 32; x = x << 32;}
3321    if (x <= 0x0000FFFFFFFFFFFFULL) {n = n + 16; x = x << 16;}
3322    if (x <= 0x00FFFFFFFFFFFFFFULL) {n = n +  8; x = x <<  8;}
3323    if (x <= 0x0FFFFFFFFFFFFFFFULL) {n = n +  4; x = x <<  4;}
3324    if (x <= 0x3FFFFFFFFFFFFFFFULL) {n = n +  2; x = x <<  2;}
3325    if (x <= 0x7FFFFFFFFFFFFFFFULL) {n = n +  1;}
3326    return n;
3327 }
3328
3329 // ---------------------------- udivdi3 --------------------------------
3330
3331    /* The variables u0, u1, etc. take on only 32-bit values, but they
3332    are declared long long to avoid some compiler warning messages and to
3333    avoid some unnecessary EXTRs that the compiler would put in, to
3334    convert long longs to ints.
3335
3336    First the procedure takes care of the case in which the divisor is a
3337    32-bit quantity. There are two subcases: (1) If the left half of the
3338    dividend is less than the divisor, one execution of DIVU is all that
3339    is required (overflow is not possible). (2) Otherwise it does two
3340    divisions, using the grade school method, with variables used as
3341    suggested below.
3342
3343        q1 q0
3344     ________
3345    v)  u1 u0
3346      q1*v
3347      ____
3348         k u0   */
3349
3350 /* These macros must be used with arguments of the appropriate type
3351 (unsigned long long for DIVU and long long for DIVS. They are
3352 simulations of the presumed machines ops. I.e., they look at only the
3353 low-order 32 bits of the divisor, they return garbage if the division
3354 overflows, and they return garbage in the high-order half of the
3355 quotient doubleword.
3356    In practice, these would be replaced with uses of the machine's DIVU
3357 and DIVS instructions (e.g., by using the GNU "asm" facility). */
3358
3359 static UInt DIVU ( ULong u, UInt v )
3360 {
3361   UInt uHi = (UInt)(u >> 32);
3362   UInt uLo = (UInt)u;
3363   return divlu2(uHi, uLo, v, NULL);
3364 }
3365
3366 static Int DIVS ( Long u, Int v )
3367 {
3368   Int  uHi = (Int)(u >> 32);
3369   UInt uLo = (UInt)u;
3370   return divls(uHi, uLo, v, NULL);
3371 }
3372
3373 /* 64 x 64 ==> 64 unsigned division, using only 32 x 32 ==> 32
3374    division as a primitive. */
3375 static ULong udivdi3(ULong u, ULong v)
3376 {
3377    ULong u0, u1, v1, q0, q1, k, n;
3378
3379    if (v >> 32 == 0) {          // If v < 2**32:
3380       if (u >> 32 < v)          // If u/v cannot overflow,
3381          return DIVU(u, v)      // just do one division.
3382             & 0xFFFFFFFF;
3383       else {                    // If u/v would overflow:
3384          u1 = u >> 32;          // Break u up into two
3385          u0 = u & 0xFFFFFFFF;   // halves.
3386          q1 = DIVU(u1, v)       // First quotient digit.
3387             & 0xFFFFFFFF;
3388          k = u1 - q1*v;         // First remainder, < v.
3389          q0 = DIVU((k << 32) + u0, v) // 2nd quot. digit.
3390             & 0xFFFFFFFF;
3391          return (q1 << 32) + q0;
3392       }
3393    }
3394                                 // Here v >= 2**32.
3395    n = nlz64(v);                // 0 <= n <= 31.
3396    v1 = (v << n) >> 32;         // Normalize the divisor
3397                                 // so its MSB is 1.
3398    u1 = u >> 1;                 // To ensure no overflow.
3399    q1 = DIVU(u1, v1)            // Get quotient from
3400        & 0xFFFFFFFF;            // divide unsigned insn.
3401    q0 = (q1 << n) >> 31;        // Undo normalization and
3402                                 // division of u by 2.
3403    if (q0 != 0)                 // Make q0 correct or
3404       q0 = q0 - 1;              // too small by 1.
3405    if ((u - q0*v) >= v)
3406       q0 = q0 + 1;              // Now q0 is correct.
3407    return q0;
3408 }
3409
3410
3411 // ----------------------------- divdi3 --------------------------------
3412
3413 /* This routine presumes that smallish cases (those which can be done in
3414 one execution of DIVS) are common. If this is not the case, the test for
3415 this case should be deleted.
3416    Note that the test for when DIVS can be used is not entirely
3417 accurate. For example, DIVS is not used if v = 0xFFFFFFFF8000000,
3418 whereas if could be (if u is sufficiently small in magnitude). */
3419
3420 // ------------------------------ cut ----------------------------------
3421
3422 static ULong my_llabs ( Long x )
3423 {
3424    ULong t = x >> 63;
3425    return (x ^ t) - t;
3426 }
3427
3428 /* 64 x 64 ==> 64 signed division, using only 32 x 32 ==> 32 division
3429    as a primitive. */
3430 static Long divdi3(Long u, Long v)
3431 {
3432    ULong au, av;
3433    Long q, t;
3434    au = my_llabs(u);
3435    av = my_llabs(v);
3436    if (av >> 31 == 0) {         // If |v| < 2**31 and
3437    // if (v << 32 >> 32 == v) { // If v is in range and
3438       if (au < av << 31) {      // |u|/|v| cannot
3439          q = DIVS(u, v);        // overflow, use DIVS.
3440          return (q << 32) >> 32;
3441       }
3442    }
3443    q = udivdi3(au,av);          // Invoke udivdi3.
3444    t = (u ^ v) >> 63;           // If u, v have different
3445    return (q ^ t) - t;          // signs, negate q.
3446 }
3447
3448 // ---------------------------- end cut --------------------------------
3449
3450 ULong __udivdi3 (ULong u, ULong v);
3451 ULong __udivdi3 (ULong u, ULong v)
3452 {
3453   return udivdi3(u,v);
3454 }
3455
3456 Long __divdi3 (Long u, Long v);
3457 Long __divdi3 (Long u, Long v)
3458 {
3459   return divdi3(u,v);
3460 }
3461
3462 ULong __umoddi3 (ULong u, ULong v);
3463 ULong __umoddi3 (ULong u, ULong v)
3464 {
3465   ULong q = __udivdi3(u, v);
3466   ULong r = u - q * v;
3467   return r;
3468 }
3469
3470 Long __moddi3 (Long u, Long v);
3471 Long __moddi3 (Long u, Long v)
3472 {
3473   Long q = __divdi3(u, v);
3474   Long r = u - q * v;
3475   return r;
3476 }
3477
3478 /* ------------------------------------------------
3479    ld_classic: Undefined symbols:
3480       ___fixunsdfdi
3481    ------------------------------------------------
3482 */
3483
3484 /* ===-- fixunsdfdi.c - Implement __fixunsdfdi -----------------------------===
3485  *
3486  *                     The LLVM Compiler Infrastructure
3487  *
3488  * This file is dual licensed under the MIT and the University of Illinois Open
3489  * Source Licenses. See LICENSE.TXT for details.
3490  *
3491  * ===----------------------------------------------------------------------===
3492  *
3493  * This file implements __fixunsdfdi for the compiler_rt library.
3494  *
3495  * ===----------------------------------------------------------------------===
3496  */
3497
3498 /* As per http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses,
3499
3500    the "NCSA/University of Illinois Open Source License" is compatible
3501    with the GPL (both version 2 and 3).  What is claimed to be
3502    compatible is this
3503
3504    http://www.opensource.org/licenses/UoI-NCSA.php
3505
3506    and the LLVM documentation at
3507
3508    http://www.llvm.org/docs/DeveloperPolicy.html#license
3509
3510    says all the code in LLVM is available under the University of
3511    Illinois/NCSA Open Source License, at this URL
3512
3513    http://www.opensource.org/licenses/UoI-NCSA.php
3514
3515    viz, the same one that the FSF pages claim is compatible.  So I
3516    think it's OK to include it.
3517 */
3518
3519 /* Returns: convert a to a unsigned long long, rounding toward zero.
3520  *          Negative values all become zero.
3521  */
3522
3523 /* Assumption: double is a IEEE 64 bit floating point type 
3524  *             du_int is a 64 bit integral type
3525  *             value in double is representable in du_int or is negative 
3526  *                 (no range checking performed)
3527  */
3528
3529 /* seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm */
3530
3531 typedef unsigned long long du_int;
3532 typedef unsigned su_int;
3533
3534 typedef union
3535 {
3536     du_int all;
3537     struct
3538     {
3539 #if VG_LITTLEENDIAN
3540         su_int low;
3541         su_int high;
3542 #else
3543         su_int high;
3544         su_int low;
3545 #endif /* VG_LITTLEENDIAN */
3546     }s;
3547 } udwords;
3548
3549 typedef union
3550 {
3551     udwords u;
3552     double  f;
3553 } double_bits;
3554
3555 du_int __fixunsdfdi(double a);
3556
3557 du_int
3558 __fixunsdfdi(double a)
3559 {
3560     double_bits fb;
3561     fb.f = a;
3562     int e = ((fb.u.s.high & 0x7FF00000) >> 20) - 1023;
3563     if (e < 0 || (fb.u.s.high & 0x80000000))
3564         return 0;
3565     udwords r;
3566     r.s.high = (fb.u.s.high & 0x000FFFFF) | 0x00100000;
3567     r.s.low = fb.u.s.low;
3568     if (e > 52)
3569         r.all <<= (e - 52);
3570     else
3571         r.all >>= (52 - e);
3572     return r.all;
3573 }
3574
3575
3576 #endif
3577
3578
3579 /*--------------------------------------------------------------------*/
3580 /*--- end                                                          ---*/
3581 /*--------------------------------------------------------------------*/