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