blob: e5871c42c6b949ec324bec01643a2dae3acb35fd [file] [log] [blame]
sewardjde4a1d02002-03-22 01:27:54 +00001
2/*--------------------------------------------------------------------*/
njn04e16982005-05-31 00:23:43 +00003/*--- Startup: the real stuff m_main.c ---*/
sewardjde4a1d02002-03-22 01:27:54 +00004/*--------------------------------------------------------------------*/
5
6/*
njnb9c427c2004-12-01 14:14:42 +00007 This file is part of Valgrind, a dynamic binary instrumentation
8 framework.
sewardjde4a1d02002-03-22 01:27:54 +00009
sewardj9eecbbb2010-05-03 21:37:12 +000010 Copyright (C) 2000-2010 Julian Seward
sewardjde4a1d02002-03-22 01:27:54 +000011 jseward@acm.org
sewardjde4a1d02002-03-22 01:27:54 +000012
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
njn25e49d8e72002-09-23 09:36:25 +000028 The GNU General Public License is contained in the file COPYING.
sewardjde4a1d02002-03-22 01:27:54 +000029*/
30
njnc7561b92005-06-19 01:24:32 +000031#include "pub_core_basics.h"
sewardj4cfea4f2006-10-14 19:26:10 +000032#include "pub_core_vki.h"
sewardj17c11042006-10-15 01:26:40 +000033#include "pub_core_vkiscnums.h"
njnc7561b92005-06-19 01:24:32 +000034#include "pub_core_threadstate.h"
sewardj14c7cc52007-02-25 15:08:24 +000035#include "pub_core_xarray.h"
sewardj45f4e7c2005-09-27 19:20:21 +000036#include "pub_core_clientstate.h"
sewardj55f9d1a2005-04-25 11:11:44 +000037#include "pub_core_aspacemgr.h"
njnac1e0332009-05-08 00:39:31 +000038#include "pub_core_aspacehl.h"
sewardj45f4e7c2005-09-27 19:20:21 +000039#include "pub_core_commandline.h"
njn2521d322005-05-08 14:45:13 +000040#include "pub_core_debuglog.h"
41#include "pub_core_errormgr.h"
42#include "pub_core_execontext.h"
sewardj17c11042006-10-15 01:26:40 +000043#include "pub_core_initimg.h"
njn97405b22005-06-02 03:39:33 +000044#include "pub_core_libcbase.h"
njn132bfcc2005-06-04 19:16:06 +000045#include "pub_core_libcassert.h"
njneb8896b2005-06-04 20:03:55 +000046#include "pub_core_libcfile.h"
njn36a20fa2005-06-03 03:08:39 +000047#include "pub_core_libcprint.h"
njnf39e9a32005-06-12 02:43:17 +000048#include "pub_core_libcproc.h"
njnde62cbf2005-06-10 22:08:14 +000049#include "pub_core_libcsignal.h"
sewardj45f4e7c2005-09-27 19:20:21 +000050#include "pub_core_syscall.h" // VG_(strerror)
njnf76d27a2009-05-28 01:53:07 +000051#include "pub_core_mach.h"
njnf536bbb2005-06-13 04:21:38 +000052#include "pub_core_machine.h"
njnaf1d7df2005-06-11 01:31:52 +000053#include "pub_core_mallocfree.h"
njn20242342005-05-16 23:31:24 +000054#include "pub_core_options.h"
sewardjfdf91b42005-09-28 00:53:09 +000055#include "pub_core_debuginfo.h"
njnd1af0032005-05-29 17:01:48 +000056#include "pub_core_redir.h"
njnc7561b92005-06-19 01:24:32 +000057#include "pub_core_scheduler.h"
sewardjf9ebc392010-05-09 22:30:43 +000058#include "pub_core_seqmatch.h" // For VG_(string_match)
njn0c246472005-05-31 01:00:08 +000059#include "pub_core_signals.h"
njn2025cf92005-06-26 20:44:48 +000060#include "pub_core_stacks.h" // For VG_(register_stack)
njnc1b01812005-06-17 22:19:06 +000061#include "pub_core_syswrap.h"
njn43b9a8a2005-05-10 04:37:01 +000062#include "pub_core_tooliface.h"
sewardj17c11042006-10-15 01:26:40 +000063#include "pub_core_translate.h" // For VG_(translate)
njna7598f62005-06-18 03:27:58 +000064#include "pub_core_trampoline.h"
njn8bddf582005-05-13 23:40:55 +000065#include "pub_core_transtab.h"
sewardj17c11042006-10-15 01:26:40 +000066
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
nethercote71980f02004-01-24 18:18:54 +000075
sewardjb5f6f512005-03-10 23:59:00 +000076
nethercote71980f02004-01-24 18:18:54 +000077/*====================================================================*/
78/*=== Counters, for profiling purposes only ===*/
79/*====================================================================*/
sewardjde4a1d02002-03-22 01:27:54 +000080
nethercote3a42fb82004-08-03 18:08:50 +000081static void print_all_stats ( void )
nethercote71980f02004-01-24 18:18:54 +000082{
njn42c83552005-12-05 20:45:59 +000083 VG_(print_translation_stats)();
nethercote92e7b7f2004-08-07 17:52:25 +000084 VG_(print_tt_tc_stats)();
nethercote844e7122004-08-02 15:27:22 +000085 VG_(print_scheduler_stats)();
njn9271cbc2005-03-13 05:38:25 +000086 VG_(print_ExeContext_stats)();
sewardj12ab7652006-10-17 02:10:42 +000087 VG_(print_errormgr_stats)();
njn9271cbc2005-03-13 05:38:25 +000088
nethercote3a42fb82004-08-03 18:08:50 +000089 // Memory stats
nethercote885dd912004-08-03 23:14:00 +000090 if (VG_(clo_verbosity) > 2) {
sewardj738856f2009-07-15 14:48:32 +000091 VG_(message)(Vg_DebugMsg, "\n");
nethercote3a42fb82004-08-03 18:08:50 +000092 VG_(message)(Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +000093 "------ Valgrind's internal memory use stats follow ------\n" );
nethercote885dd912004-08-03 23:14:00 +000094 VG_(sanity_check_malloc_all)();
sewardj738856f2009-07-15 14:48:32 +000095 VG_(message)(Vg_DebugMsg, "------\n" );
nethercote3a42fb82004-08-03 18:08:50 +000096 VG_(print_all_arena_stats)();
sewardj738856f2009-07-15 14:48:32 +000097 VG_(message)(Vg_DebugMsg, "\n");
nethercote3a42fb82004-08-03 18:08:50 +000098 }
nethercote71980f02004-01-24 18:18:54 +000099}
100
101
102/*====================================================================*/
sewardj71bc3cb2005-05-19 00:25:45 +0000103/*=== Command-line: variables, processing, etc ===*/
104/*====================================================================*/
105
106// See pub_{core,tool}_options.h for explanations of all these.
107
sewardj45f4e7c2005-09-27 19:20:21 +0000108static void usage_NORETURN ( Bool debug_help )
njn7cf0bd32002-06-08 13:36:03 +0000109{
sewardj7839d112007-11-20 19:45:03 +0000110 /* 'usage1' contains a %s for the name of the GDB executable, which
111 must be supplied when it is VG_(printf)'d. */
njn25e49d8e72002-09-23 09:36:25 +0000112 Char* usage1 =
njn00cfcfc2005-11-12 18:53:50 +0000113"usage: valgrind [options] prog-and-args\n"
njn25e49d8e72002-09-23 09:36:25 +0000114"\n"
njn97db7612009-08-04 02:32:55 +0000115" tool-selection option, with default in [ ]:\n"
sewardjb5f6f512005-03-10 23:59:00 +0000116" --tool=<name> use the Valgrind tool named <name> [memcheck]\n"
njn97db7612009-08-04 02:32:55 +0000117"\n"
118" basic user options for all Valgrind tools, with defaults in [ ]:\n"
nethercotea76368b2004-06-16 11:56:29 +0000119" -h --help show this message\n"
nethercote6c999f22004-01-31 22:55:15 +0000120" --help-debug show this message, plus debugging options\n"
njn25e49d8e72002-09-23 09:36:25 +0000121" --version show version\n"
njn25e49d8e72002-09-23 09:36:25 +0000122" -q --quiet run silently; only print error msgs\n"
sewardj2d9e8742009-08-07 15:46:56 +0000123" -v --verbose be more verbose -- show misc extra info\n"
sewardj6e31f802007-11-17 22:29:25 +0000124" --trace-children=no|yes Valgrind-ise child processes (follow execve)? [no]\n"
sewardj06421272009-11-05 08:55:13 +0000125" --trace-children-skip=patt1,patt2,... specifies a list of executables\n"
126" that --trace-children=yes should not trace into\n"
njn97db7612009-08-04 02:32:55 +0000127" --child-silent-after-fork=no|yes omit child output between fork & exec? [no]\n"
nethercote0d588502004-06-21 13:27:11 +0000128" --track-fds=no|yes track open file descriptors? [no]\n"
thughes6233a382004-08-21 11:10:44 +0000129" --time-stamp=no|yes add timestamps to log messages? [no]\n"
njnce545552005-07-25 22:36:52 +0000130" --log-fd=<number> log messages to file descriptor [2=stderr]\n"
njn374a36d2007-11-23 01:41:32 +0000131" --log-file=<file> log messages to <file>\n"
njnce545552005-07-25 22:36:52 +0000132" --log-socket=ipaddr:port log messages to socket ipaddr:port\n"
nethercote2b0793f2003-12-02 10:41:18 +0000133"\n"
nethercote2b0793f2003-12-02 10:41:18 +0000134" user options for Valgrind tools that report errors:\n"
sewardj738856f2009-07-15 14:48:32 +0000135" --xml=yes emit error output in XML (some tools only)\n"
136" --xml-fd=<number> XML output to file descriptor\n"
137" --xml-file=<file> XML output to <file>\n"
138" --xml-socket=ipaddr:port XML output to socket ipaddr:port\n"
139" --xml-user-comment=STR copy STR verbatim into XML output\n"
nethercote2b0793f2003-12-02 10:41:18 +0000140" --demangle=no|yes automatically demangle C++ names? [yes]\n"
njn20b4a152005-10-19 22:39:40 +0000141" --num-callers=<number> show <number> callers in stack traces [12]\n"
nethercote2b0793f2003-12-02 10:41:18 +0000142" --error-limit=no|yes stop showing new errors if too many? [yes]\n"
sewardjb9779082006-05-12 23:50:15 +0000143" --error-exitcode=<number> exit code to return if errors found [0=disable]\n"
nethercote2b0793f2003-12-02 10:41:18 +0000144" --show-below-main=no|yes continue stack traces below main() [no]\n"
145" --suppressions=<filename> suppress errors described in <filename>\n"
sewardjd153fae2005-01-10 17:24:47 +0000146" --gen-suppressions=no|yes|all print suppressions for errors? [no]\n"
nethercote04d0fbc2004-01-26 16:48:06 +0000147" --db-attach=no|yes start debugger when errors detected? [no]\n"
sewardj7839d112007-11-20 19:45:03 +0000148" --db-command=<command> command to start debugger [%s -nw %%f %%p]\n"
nethercote04d0fbc2004-01-26 16:48:06 +0000149" --input-fd=<number> file descriptor for input [0=stdin]\n"
njn97db7612009-08-04 02:32:55 +0000150" --dsymutil=no|yes run dsymutil on Mac OS X when helpful? [no]\n"
sewardj97724e52005-04-02 23:40:59 +0000151" --max-stackframe=<number> assume stack switch for SP changes larger\n"
152" than <number> bytes [2000000]\n"
sewardj95d86c02007-12-18 01:49:23 +0000153" --main-stacksize=<number> set size of main thread's stack (in bytes)\n"
154" [use current 'ulimit' value]\n"
njn97db7612009-08-04 02:32:55 +0000155"\n"
156" user options for Valgrind tools that replace malloc:\n"
157" --alignment=<number> set minimum alignment of heap allocations [%ld]\n"
158"\n"
159" uncommon user options for all Valgrind tools:\n"
sewardj14cdbf82010-10-12 00:44:05 +0000160" --fullpath-after= (with nothing after the '=')\n"
161" show full source paths in call stacks\n"
162" --fullpath-after=string like --fullpath-after=, but only show the\n"
163" part of the path after 'string'. Allows removal\n"
164" of path prefixes. Use this flag multiple times\n"
165" to specify a set of prefixes to remove.\n"
njn97db7612009-08-04 02:32:55 +0000166" --smc-check=none|stack|all checks for self-modifying code: none,\n"
167" only for code found in stacks, or all [stack]\n"
168" --read-var-info=yes|no read debug info on stack and global variables\n"
169" and use it to print better error messages in\n"
170" tools that make use of it (Memcheck, Helgrind,\n"
bartf6122a02010-03-27 07:38:39 +0000171" DRD) [no]\n"
njn97db7612009-08-04 02:32:55 +0000172" --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]\n"
173" --sim-hints=hint1,hint2,... known hints:\n"
174" lax-ioctls, enable-outer [none]\n"
175" --kernel-variant=variant1,variant2,... known variants: bproc [none]\n"
176" handle non-standard kernel variants\n"
177" --show-emwarns=no|yes show warnings about emulation limits? [no]\n"
sewardjf9ebc392010-05-09 22:30:43 +0000178" --require-text-symbol=:sonamepattern:symbolpattern abort run if the\n"
179" stated shared object doesn't have the stated\n"
180" text symbol. Patterns can contain ? and *.\n"
fitzhardinge98abfc72003-12-16 02:05:15 +0000181"\n";
njn7cf0bd32002-06-08 13:36:03 +0000182
njn25e49d8e72002-09-23 09:36:25 +0000183 Char* usage2 =
184"\n"
nethercote2b0793f2003-12-02 10:41:18 +0000185" debugging options for all Valgrind tools:\n"
njn97db7612009-08-04 02:32:55 +0000186" -d show verbose debugging output\n"
njnb1cc5d62010-07-06 04:05:23 +0000187" --stats=no|yes show tool and core statistics [no]\n"
njn25e49d8e72002-09-23 09:36:25 +0000188" --sanity-level=<number> level of sanity checking to do [1]\n"
sewardjfa8ec112005-01-19 11:55:34 +0000189" --trace-flags=<XXXXXXXX> show generated code? (X = 0|1) [00000000]\n"
190" --profile-flags=<XXXXXXXX> ditto, but for profiling (X = 0|1) [00000000]\n"
sewardj33afdb52006-01-17 02:36:40 +0000191" --trace-notbelow=<number> only show BBs above <number> [999999999]\n"
njn25e49d8e72002-09-23 09:36:25 +0000192" --trace-syscalls=no|yes show all system calls? [no]\n"
193" --trace-signals=no|yes show signal handling details? [no]\n"
194" --trace-symtab=no|yes show symbol table details? [no]\n"
sewardjf767d962007-02-12 17:47:14 +0000195" --trace-symtab-patt=<patt> limit debuginfo tracing to obj name <patt>\n"
sewardjce058b02005-05-01 08:55:38 +0000196" --trace-cfi=no|yes show call-frame-info details? [no]\n"
sewardjf767d962007-02-12 17:47:14 +0000197" --debug-dump=syms mimic /usr/bin/readelf --syms\n"
198" --debug-dump=line mimic /usr/bin/readelf --debug-dump=line\n"
199" --debug-dump=frames mimic /usr/bin/readelf --debug-dump=frames\n"
sewardj0ec07f32006-01-12 12:32:32 +0000200" --trace-redir=no|yes show redirection details? [no]\n"
njn25e49d8e72002-09-23 09:36:25 +0000201" --trace-sched=no|yes show thread scheduler details? [no]\n"
sewardj9c606bd2008-09-18 18:12:50 +0000202" --profile-heap=no|yes profile Valgrind's own space use\n"
jsgf855d93d2003-10-13 22:26:55 +0000203" --wait-for-gdb=yes|no pause on startup to wait for gdb attach\n"
sewardj17c11042006-10-15 01:26:40 +0000204" --sym-offsets=yes|no show syms in form 'name+offset' ? [no]\n"
sewardjb5f6f512005-03-10 23:59:00 +0000205" --command-line-only=no|yes only use command line options [no]\n"
njn613812e2005-03-11 04:57:30 +0000206"\n"
njn97db7612009-08-04 02:32:55 +0000207" Vex options for all Valgrind tools:\n"
208" --vex-iropt-verbosity=<0..9> [0]\n"
209" --vex-iropt-level=<0..2> [2]\n"
210" --vex-iropt-precise-memory-exns=no|yes [no]\n"
211" --vex-iropt-unroll-thresh=<0..400> [120]\n"
212" --vex-guest-max-insns=<1..100> [50]\n"
213" --vex-guest-chase-thresh=<0..99> [10]\n"
sewardj540cc4a2010-01-15 10:57:57 +0000214" --vex-guest-chase-cond=no|yes [no]\n"
sewardjfa8ec112005-01-19 11:55:34 +0000215" --trace-flags and --profile-flags values (omit the middle space):\n"
sewardj2a99cf62004-11-24 10:44:19 +0000216" 1000 0000 show conversion into IR\n"
217" 0100 0000 show after initial opt\n"
218" 0010 0000 show after instrumentation\n"
219" 0001 0000 show after second opt\n"
220" 0000 1000 show after tree building\n"
221" 0000 0100 show selecting insns\n"
222" 0000 0010 show after reg-alloc\n"
223" 0000 0001 show final assembly\n"
njn33dbfce2006-06-02 22:58:34 +0000224" (Nb: you need --trace-notbelow with --trace-flags for full details)\n"
sewardj2a99cf62004-11-24 10:44:19 +0000225"\n"
nethercote2b0793f2003-12-02 10:41:18 +0000226" debugging options for Valgrind tools that report errors\n"
227" --dump-error=<number> show translation for basic block associated\n"
228" with <number>'th error context [0=show none]\n"
njn97db7612009-08-04 02:32:55 +0000229"\n"
230" debugging options for Valgrind tools that replace malloc:\n"
231" --trace-malloc=no|yes show client malloc details? [no]\n"
fitzhardinge98abfc72003-12-16 02:05:15 +0000232"\n";
njn3e884182003-04-15 13:03:23 +0000233
234 Char* usage3 =
235"\n"
nethercote71980f02004-01-24 18:18:54 +0000236" Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc\n"
njn25e49d8e72002-09-23 09:36:25 +0000237"\n"
njn10b9aea2009-07-14 06:55:05 +0000238" %s is %s\n"
sewardj9eecbbb2010-05-03 21:37:12 +0000239" Valgrind is Copyright (C) 2000-2010, and GNU GPL'd, by Julian Seward et al.\n"
sewardje089f012010-10-13 21:47:29 +0000240" LibVEX is Copyright (C) 2004-2010, and GNU GPL'd, by OpenWorks LLP et al.\n"
njnd04b7c62002-10-03 14:05:52 +0000241"\n"
njn10b9aea2009-07-14 06:55:05 +0000242" Bug reports, feedback, admiration, abuse, etc, to: %s.\n"
njn25e49d8e72002-09-23 09:36:25 +0000243"\n";
njn7cf0bd32002-06-08 13:36:03 +0000244
sewardj12373b12007-11-20 21:38:14 +0000245 Char* gdb_path = GDB_PATH;
sewardj12373b12007-11-20 21:38:14 +0000246
njnbe9b47b2005-05-15 16:22:58 +0000247 // Ensure the message goes to stdout
sewardj738856f2009-07-15 14:48:32 +0000248 VG_(log_output_sink).fd = 1;
249 VG_(log_output_sink).is_socket = False;
njnbe9b47b2005-05-15 16:22:58 +0000250
njn97db7612009-08-04 02:32:55 +0000251 /* 'usage1' expects one char* argument and one SizeT argument. */
252 VG_(printf)(usage1, gdb_path, VG_MIN_MALLOC_SZB);
fitzhardinge98abfc72003-12-16 02:05:15 +0000253 if (VG_(details).name) {
254 VG_(printf)(" user options for %s:\n", VG_(details).name);
fitzhardinge98abfc72003-12-16 02:05:15 +0000255 if (VG_(needs).command_line_options)
njn51d827b2005-05-09 01:02:08 +0000256 VG_TDICT_CALL(tool_print_usage);
fitzhardinge98abfc72003-12-16 02:05:15 +0000257 else
258 VG_(printf)(" (none)\n");
259 }
nethercote6c999f22004-01-31 22:55:15 +0000260 if (debug_help) {
sewardjbbaef872008-11-01 23:55:32 +0000261 VG_(printf)("%s", usage2);
fitzhardinge98abfc72003-12-16 02:05:15 +0000262
nethercote6c999f22004-01-31 22:55:15 +0000263 if (VG_(details).name) {
264 VG_(printf)(" debugging options for %s:\n", VG_(details).name);
265
266 if (VG_(needs).command_line_options)
njn51d827b2005-05-09 01:02:08 +0000267 VG_TDICT_CALL(tool_print_debug_usage);
nethercote6c999f22004-01-31 22:55:15 +0000268 else
269 VG_(printf)(" (none)\n");
270 }
fitzhardinge98abfc72003-12-16 02:05:15 +0000271 }
njn10b9aea2009-07-14 06:55:05 +0000272 VG_(printf)(usage3, VG_(details).name, VG_(details).copyright_author,
273 VG_BUGS_TO);
nethercotef4928da2004-06-15 10:54:40 +0000274 VG_(exit)(0);
njn7cf0bd32002-06-08 13:36:03 +0000275}
sewardjde4a1d02002-03-22 01:27:54 +0000276
sewardjde4a1d02002-03-22 01:27:54 +0000277
sewardj95d86c02007-12-18 01:49:23 +0000278/* Peer at previously set up VG_(args_for_valgrind) and do some
279 minimal command line processing that must happen early on:
sewardj45f4e7c2005-09-27 19:20:21 +0000280
sewardj95d86c02007-12-18 01:49:23 +0000281 - show the version string, if requested (-v)
282 - extract any request for help (--help, -h, --help-debug)
283 - get the toolname (--tool=)
284 - set VG_(clo_max_stackframe) (--max-stackframe=)
285 - set VG_(clo_main_stacksize) (--main-stacksize=)
286
287 That's all it does. The main command line processing is done below
288 by main_process_cmd_line_options. Note that
289 main_process_cmd_line_options has to handle but ignore the ones we
290 have handled here.
291*/
292static void early_process_cmd_line_options ( /*OUT*/Int* need_help,
293 /*OUT*/HChar** tool )
sewardj45f4e7c2005-09-27 19:20:21 +0000294{
295 UInt i;
296 HChar* str;
sewardj8b635a42004-11-22 19:01:47 +0000297
sewardj14c7cc52007-02-25 15:08:24 +0000298 vg_assert( VG_(args_for_valgrind) );
nethercote71980f02004-01-24 18:18:54 +0000299
sewardj14c7cc52007-02-25 15:08:24 +0000300 /* parse the options we have (only the options we care about now) */
301 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
302
303 str = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
sewardj45f4e7c2005-09-27 19:20:21 +0000304 vg_assert(str);
nethercote71980f02004-01-24 18:18:54 +0000305
njn83df0b62009-02-25 01:01:05 +0000306 // Nb: the version string goes to stdout.
sewardj738856f2009-07-15 14:48:32 +0000307 if VG_XACT_CLO(str, "--version", VG_(log_output_sink).fd, 1) {
308 VG_(log_output_sink).is_socket = False;
sewardj45f4e7c2005-09-27 19:20:21 +0000309 VG_(printf)("valgrind-" VERSION "\n");
310 VG_(exit)(0);
njn83df0b62009-02-25 01:01:05 +0000311 }
njncce38e62010-07-06 04:25:12 +0000312 else if VG_XACT_CLO(str, "--help", *need_help, *need_help+1) {}
313 else if VG_XACT_CLO(str, "-h", *need_help, *need_help+1) {}
sewardj45f4e7c2005-09-27 19:20:21 +0000314
njncce38e62010-07-06 04:25:12 +0000315 else if VG_XACT_CLO(str, "--help-debug", *need_help, *need_help+2) {}
nethercote71980f02004-01-24 18:18:54 +0000316
sewardj45f4e7c2005-09-27 19:20:21 +0000317 // The tool has already been determined, but we need to know the name
318 // here.
njn83df0b62009-02-25 01:01:05 +0000319 else if VG_STR_CLO(str, "--tool", *tool) {}
sewardj5bdfbd22007-12-15 22:13:05 +0000320
sewardj95d86c02007-12-18 01:49:23 +0000321 // Set up VG_(clo_max_stackframe) and VG_(clo_main_stacksize).
322 // These are needed by VG_(ii_create_image), which happens
323 // before main_process_cmd_line_options().
njn83df0b62009-02-25 01:01:05 +0000324 else if VG_INT_CLO(str, "--max-stackframe", VG_(clo_max_stackframe)) {}
325 else if VG_INT_CLO(str, "--main-stacksize", VG_(clo_main_stacksize)) {}
nethercote71980f02004-01-24 18:18:54 +0000326 }
nethercote71980f02004-01-24 18:18:54 +0000327}
328
sewardj95d86c02007-12-18 01:49:23 +0000329/* The main processing for command line options. See comments above
sewardj738856f2009-07-15 14:48:32 +0000330 on early_process_cmd_line_options.
331
332 Comments on how the logging options are handled:
333
334 User can specify:
335 --log-fd= for a fd to write to (default setting, fd = 2)
336 --log-file= for a file name to write to
337 --log-socket= for a socket to write to
338
339 As a result of examining these and doing relevant socket/file
340 opening, a final fd is established. This is stored in
341 VG_(log_output_sink) in m_libcprint. Also, if --log-file=STR was
342 specified, then STR, after expansion of %p and %q templates within
343 it, is stored in VG_(clo_log_fname_expanded), in m_options, just in
344 case anybody wants to know what it is.
345
346 When printing, VG_(log_output_sink) is consulted to find the
347 fd to send output to.
348
349 Exactly analogous actions are undertaken for the XML output
350 channel, with the one difference that the default fd is -1, meaning
351 the channel is disabled by default.
sewardj95d86c02007-12-18 01:49:23 +0000352*/
sewardj738856f2009-07-15 14:48:32 +0000353static
354void main_process_cmd_line_options ( /*OUT*/Bool* logging_to_fd,
355 /*OUT*/Char** xml_fname_unexpanded,
356 const HChar* toolname )
nethercote71980f02004-01-24 18:18:54 +0000357{
njnda033f52005-12-19 21:27:58 +0000358 // VG_(clo_log_fd) is used by all the messaging. It starts as 2 (stderr)
359 // and we cannot change it until we know what we are changing it to is
360 // ok. So we have tmp_log_fd to hold the tmp fd prior to that point.
sewardj92645592005-07-23 09:18:34 +0000361 SysRes sres;
sewardj738856f2009-07-15 14:48:32 +0000362 Int i, tmp_log_fd, tmp_xml_fd;
sewardj92645592005-07-23 09:18:34 +0000363 Int toolname_len = VG_(strlen)(toolname);
njn83df0b62009-02-25 01:01:05 +0000364 Char* tmp_str; // Used in a couple of places.
njnbe9b47b2005-05-15 16:22:58 +0000365 enum {
366 VgLogTo_Fd,
367 VgLogTo_File,
njnbe9b47b2005-05-15 16:22:58 +0000368 VgLogTo_Socket
sewardj738856f2009-07-15 14:48:32 +0000369 } log_to = VgLogTo_Fd, // Where is logging output to be sent?
370 xml_to = VgLogTo_Fd; // Where is XML output to be sent?
sewardjde4a1d02002-03-22 01:27:54 +0000371
sewardj738856f2009-07-15 14:48:32 +0000372 /* Temporarily holds the string STR specified with
373 --{log,xml}-{name,socket}=STR. 'fs' stands for
374 file-or-socket. */
375 Char* log_fsname_unexpanded = NULL;
376 Char* xml_fsname_unexpanded = NULL;
377
378 /* Log to stderr by default, but usage message goes to stdout. XML
379 output is initially disabled. */
njnda033f52005-12-19 21:27:58 +0000380 tmp_log_fd = 2;
sewardj738856f2009-07-15 14:48:32 +0000381 tmp_xml_fd = -1;
382
sewardj19d81412002-06-03 01:10:40 +0000383 /* Check for sane path in ./configure --prefix=... */
fitzhardinge98abfc72003-12-16 02:05:15 +0000384 if (VG_LIBDIR[0] != '/')
sewardj17c11042006-10-15 01:26:40 +0000385 VG_(err_config_error)("Please use absolute paths in "
386 "./configure --prefix=... or --libdir=...");
sewardj38170912002-05-10 21:07:22 +0000387
sewardj14c7cc52007-02-25 15:08:24 +0000388 vg_assert( VG_(args_for_valgrind) );
nethercote71980f02004-01-24 18:18:54 +0000389
sewardj738856f2009-07-15 14:48:32 +0000390 /* BEGIN command-line processing loop */
391
sewardj14c7cc52007-02-25 15:08:24 +0000392 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
393
394 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
sewardj45f4e7c2005-09-27 19:20:21 +0000395 HChar* colon = arg;
nethercote71980f02004-01-24 18:18:54 +0000396
njn1274d242007-03-26 23:38:42 +0000397 // Look for a colon in the option name.
thughes3bfd5a02004-07-18 08:05:44 +0000398 while (*colon && *colon != ':' && *colon != '=')
399 colon++;
nethercote71980f02004-01-24 18:18:54 +0000400
njn1274d242007-03-26 23:38:42 +0000401 // Does it have the form "--toolname:foo"? We have to do it at the start
402 // in case someone has combined a prefix with a core-specific option,
403 // eg. "--memcheck:verbose".
thughes3bfd5a02004-07-18 08:05:44 +0000404 if (*colon == ':') {
njn83df0b62009-02-25 01:01:05 +0000405 if (VG_STREQN(2, arg, "--") &&
406 VG_STREQN(toolname_len, arg+2, toolname) &&
407 VG_STREQN(1, arg+2+toolname_len, ":"))
nethercote71980f02004-01-24 18:18:54 +0000408 {
njn1274d242007-03-26 23:38:42 +0000409 // Prefix matches, convert "--toolname:foo" to "--foo".
410 // Two things to note:
411 // - We cannot modify the option in-place. If we did, and then
412 // a child was spawned with --trace-children=yes, the
413 // now-non-prefixed option would be passed and could screw up
414 // the child.
415 // - We create copies, and never free them. Why? Non-prefixed
416 // options hang around forever, so tools need not make copies
417 // of strings within them. We need to have the same behaviour
418 // for prefixed options. The pointer to the copy will be lost
419 // once we leave this function (although a tool may keep a
420 // pointer into it), but the space wasted is insignificant.
421 // (In bug #142197, the copies were being freed, which caused
422 // problems for tools that reasonably assumed that arguments
423 // wouldn't disappear on them.)
nethercote71980f02004-01-24 18:18:54 +0000424 if (0)
425 VG_(printf)("tool-specific arg: %s\n", arg);
sewardj9c606bd2008-09-18 18:12:50 +0000426 arg = VG_(strdup)("main.mpclo.1", arg + toolname_len + 1);
nethercote71980f02004-01-24 18:18:54 +0000427 arg[0] = '-';
428 arg[1] = '-';
429
430 } else {
431 // prefix doesn't match, skip to next arg
432 continue;
433 }
434 }
435
fitzhardinge98abfc72003-12-16 02:05:15 +0000436 /* Ignore these options - they've already been handled */
njn83df0b62009-02-25 01:01:05 +0000437 if VG_STREQN( 7, arg, "--tool=") {}
438 else if VG_STREQN(20, arg, "--command-line-only=") {}
439 else if VG_STREQ( arg, "--") {}
440 else if VG_STREQ( arg, "-d") {}
441 else if VG_STREQN(16, arg, "--max-stackframe") {}
442 else if VG_STREQN(16, arg, "--main-stacksize") {}
443 else if VG_STREQN(14, arg, "--profile-heap") {}
nethercote27fec902004-06-16 21:26:32 +0000444
njn83df0b62009-02-25 01:01:05 +0000445 // These options are new.
446 else if (VG_STREQ(arg, "-v") ||
447 VG_STREQ(arg, "--verbose"))
sewardjde4a1d02002-03-22 01:27:54 +0000448 VG_(clo_verbosity)++;
nethercote27fec902004-06-16 21:26:32 +0000449
njn83df0b62009-02-25 01:01:05 +0000450 else if (VG_STREQ(arg, "-q") ||
451 VG_STREQ(arg, "--quiet"))
sewardjde4a1d02002-03-22 01:27:54 +0000452 VG_(clo_verbosity)--;
453
sewardj2d9e8742009-08-07 15:46:56 +0000454 else if VG_BOOL_CLO(arg, "--stats", VG_(clo_stats)) {}
njn83df0b62009-02-25 01:01:05 +0000455 else if VG_BOOL_CLO(arg, "--xml", VG_(clo_xml)) {}
456 else if VG_BOOL_CLO(arg, "--db-attach", VG_(clo_db_attach)) {}
457 else if VG_BOOL_CLO(arg, "--demangle", VG_(clo_demangle)) {}
458 else if VG_BOOL_CLO(arg, "--error-limit", VG_(clo_error_limit)) {}
459 else if VG_INT_CLO (arg, "--error-exitcode", VG_(clo_error_exitcode)) {}
460 else if VG_BOOL_CLO(arg, "--show-emwarns", VG_(clo_show_emwarns)) {}
sewardj95d86c02007-12-18 01:49:23 +0000461
njn83df0b62009-02-25 01:01:05 +0000462 else if VG_BOOL_CLO(arg, "--run-libc-freeres", VG_(clo_run_libc_freeres)) {}
463 else if VG_BOOL_CLO(arg, "--show-below-main", VG_(clo_show_below_main)) {}
464 else if VG_BOOL_CLO(arg, "--time-stamp", VG_(clo_time_stamp)) {}
465 else if VG_BOOL_CLO(arg, "--track-fds", VG_(clo_track_fds)) {}
466 else if VG_BOOL_CLO(arg, "--trace-children", VG_(clo_trace_children)) {}
467 else if VG_BOOL_CLO(arg, "--child-silent-after-fork",
468 VG_(clo_child_silent_after_fork)) {}
469 else if VG_BOOL_CLO(arg, "--trace-sched", VG_(clo_trace_sched)) {}
470 else if VG_BOOL_CLO(arg, "--trace-signals", VG_(clo_trace_signals)) {}
471 else if VG_BOOL_CLO(arg, "--trace-symtab", VG_(clo_trace_symtab)) {}
472 else if VG_STR_CLO (arg, "--trace-symtab-patt", VG_(clo_trace_symtab_patt)) {}
473 else if VG_BOOL_CLO(arg, "--trace-cfi", VG_(clo_trace_cfi)) {}
474 else if VG_XACT_CLO(arg, "--debug-dump=syms", VG_(clo_debug_dump_syms),
475 True) {}
476 else if VG_XACT_CLO(arg, "--debug-dump=line", VG_(clo_debug_dump_line),
477 True) {}
478 else if VG_XACT_CLO(arg, "--debug-dump=frames",
479 VG_(clo_debug_dump_frames), True) {}
480 else if VG_BOOL_CLO(arg, "--trace-redir", VG_(clo_trace_redir)) {}
sewardj95d86c02007-12-18 01:49:23 +0000481
njn83df0b62009-02-25 01:01:05 +0000482 else if VG_BOOL_CLO(arg, "--trace-syscalls", VG_(clo_trace_syscalls)) {}
483 else if VG_BOOL_CLO(arg, "--wait-for-gdb", VG_(clo_wait_for_gdb)) {}
484 else if VG_STR_CLO (arg, "--db-command", VG_(clo_db_command)) {}
485 else if VG_STR_CLO (arg, "--sim-hints", VG_(clo_sim_hints)) {}
486 else if VG_BOOL_CLO(arg, "--sym-offsets", VG_(clo_sym_offsets)) {}
487 else if VG_BOOL_CLO(arg, "--read-var-info", VG_(clo_read_var_info)) {}
sewardjf767d962007-02-12 17:47:14 +0000488
njn83df0b62009-02-25 01:01:05 +0000489 else if VG_INT_CLO (arg, "--dump-error", VG_(clo_dump_error)) {}
490 else if VG_INT_CLO (arg, "--input-fd", VG_(clo_input_fd)) {}
491 else if VG_INT_CLO (arg, "--sanity-level", VG_(clo_sanity_level)) {}
492 else if VG_BINT_CLO(arg, "--num-callers", VG_(clo_backtrace_size), 1,
493 VG_DEEPEST_BACKTRACE) {}
sewardjde4a1d02002-03-22 01:27:54 +0000494
njn83df0b62009-02-25 01:01:05 +0000495 else if VG_XACT_CLO(arg, "--smc-check=none", VG_(clo_smc_check),
496 Vg_SmcNone);
497 else if VG_XACT_CLO(arg, "--smc-check=stack", VG_(clo_smc_check),
498 Vg_SmcStack);
499 else if VG_XACT_CLO(arg, "--smc-check=all", VG_(clo_smc_check),
500 Vg_SmcAll);
sewardjde4a1d02002-03-22 01:27:54 +0000501
njn97db7612009-08-04 02:32:55 +0000502 else if VG_STR_CLO (arg, "--kernel-variant", VG_(clo_kernel_variant)) {}
sewardj26412bd2005-07-07 10:05:05 +0000503
njn97db7612009-08-04 02:32:55 +0000504 else if VG_BOOL_CLO(arg, "--dsymutil", VG_(clo_dsymutil)) {}
njnf76d27a2009-05-28 01:53:07 +0000505
sewardj06421272009-11-05 08:55:13 +0000506 else if VG_STR_CLO (arg, "--trace-children-skip", VG_(clo_trace_children_skip)) {}
507
njn83df0b62009-02-25 01:01:05 +0000508 else if VG_BINT_CLO(arg, "--vex-iropt-verbosity",
509 VG_(clo_vex_control).iropt_verbosity, 0, 10) {}
510 else if VG_BINT_CLO(arg, "--vex-iropt-level",
511 VG_(clo_vex_control).iropt_level, 0, 2) {}
512 else if VG_BOOL_CLO(arg, "--vex-iropt-precise-memory-exns",
513 VG_(clo_vex_control).iropt_precise_memory_exns) {}
514 else if VG_BINT_CLO(arg, "--vex-iropt-unroll-thresh",
515 VG_(clo_vex_control).iropt_unroll_thresh, 0, 400) {}
516 else if VG_BINT_CLO(arg, "--vex-guest-max-insns",
517 VG_(clo_vex_control).guest_max_insns, 1, 100) {}
518 else if VG_BINT_CLO(arg, "--vex-guest-chase-thresh",
519 VG_(clo_vex_control).guest_chase_thresh, 0, 99) {}
sewardj540cc4a2010-01-15 10:57:57 +0000520 else if VG_BOOL_CLO(arg, "--vex-guest-chase-cond",
521 VG_(clo_vex_control).guest_chase_cond) {}
sewardj94c8eb42008-09-19 20:13:39 +0000522
njn83df0b62009-02-25 01:01:05 +0000523 else if VG_INT_CLO(arg, "--log-fd", tmp_log_fd) {
524 log_to = VgLogTo_Fd;
sewardj738856f2009-07-15 14:48:32 +0000525 log_fsname_unexpanded = NULL;
526 }
527 else if VG_INT_CLO(arg, "--xml-fd", tmp_xml_fd) {
528 xml_to = VgLogTo_Fd;
529 xml_fsname_unexpanded = NULL;
sewardj4cf05692002-10-27 20:28:29 +0000530 }
531
sewardj738856f2009-07-15 14:48:32 +0000532 else if VG_STR_CLO(arg, "--log-file", log_fsname_unexpanded) {
njn83df0b62009-02-25 01:01:05 +0000533 log_to = VgLogTo_File;
sewardj4cf05692002-10-27 20:28:29 +0000534 }
sewardj738856f2009-07-15 14:48:32 +0000535 else if VG_STR_CLO(arg, "--xml-file", xml_fsname_unexpanded) {
536 xml_to = VgLogTo_File;
537 }
538
539 else if VG_STR_CLO(arg, "--log-socket", log_fsname_unexpanded) {
njn83df0b62009-02-25 01:01:05 +0000540 log_to = VgLogTo_Socket;
sewardj73cf3bc2002-11-03 03:20:15 +0000541 }
sewardj738856f2009-07-15 14:48:32 +0000542 else if VG_STR_CLO(arg, "--xml-socket", xml_fsname_unexpanded) {
543 xml_to = VgLogTo_Socket;
544 }
sewardj73cf3bc2002-11-03 03:20:15 +0000545
njn83df0b62009-02-25 01:01:05 +0000546 else if VG_STR_CLO(arg, "--xml-user-comment",
547 VG_(clo_xml_user_comment)) {}
sewardj768db0e2005-07-19 14:18:56 +0000548
njn83df0b62009-02-25 01:01:05 +0000549 else if VG_STR_CLO(arg, "--suppressions", tmp_str) {
sewardjde4a1d02002-03-22 01:27:54 +0000550 if (VG_(clo_n_suppressions) >= VG_CLO_MAX_SFILES) {
njnb1cc5d62010-07-06 04:05:23 +0000551 VG_(fmsg_bad_option)(arg,
552 "Too many suppression files specified.\n"
553 "Increase VG_CLO_MAX_SFILES and recompile.\n");
sewardjde4a1d02002-03-22 01:27:54 +0000554 }
njn83df0b62009-02-25 01:01:05 +0000555 VG_(clo_suppressions)[VG_(clo_n_suppressions)] = tmp_str;
sewardjde4a1d02002-03-22 01:27:54 +0000556 VG_(clo_n_suppressions)++;
557 }
sewardjde4a1d02002-03-22 01:27:54 +0000558
sewardj14cdbf82010-10-12 00:44:05 +0000559 else if VG_STR_CLO (arg, "--fullpath-after", tmp_str) {
560 if (VG_(clo_n_fullpath_after) >= VG_CLO_MAX_FULLPATH_AFTER) {
561 VG_(fmsg_bad_option)(arg,
562 "Too many --fullpath-after= specifications.\n"
563 "Increase VG_CLO_MAX_FULLPATH_AFTER and recompile.\n");
564 }
565 VG_(clo_fullpath_after)[VG_(clo_n_fullpath_after)] = tmp_str;
566 VG_(clo_n_fullpath_after)++;
567 }
568
sewardjf9ebc392010-05-09 22:30:43 +0000569 else if VG_STR_CLO(arg, "--require-text-symbol", tmp_str) {
570 if (VG_(clo_n_req_tsyms) >= VG_CLO_MAX_REQ_TSYMS) {
njnb1cc5d62010-07-06 04:05:23 +0000571 VG_(fmsg_bad_option)(arg,
572 "Too many --require-text-symbol= specifications.\n"
573 "Increase VG_CLO_MAX_REQ_TSYMS and recompile.\n");
sewardjf9ebc392010-05-09 22:30:43 +0000574 }
575 /* String needs to be of the form C?*C?*, where C is any
576 character, but is the same both times. Having it in this
577 form facilitates finding the boundary between the sopatt
578 and the fnpatt just by looking for the second occurrence
579 of C, without hardwiring any assumption about what C
580 is. */
581 Char patt[7];
582 Bool ok = True;
583 ok = tmp_str && VG_(strlen)(tmp_str) > 0;
584 if (ok) {
585 patt[0] = patt[3] = tmp_str[0];
586 patt[1] = patt[4] = '?';
587 patt[2] = patt[5] = '*';
588 patt[6] = 0;
589 ok = VG_(string_match)(patt, tmp_str);
590 }
591 if (!ok) {
njnb1cc5d62010-07-06 04:05:23 +0000592 VG_(fmsg_bad_option)(arg,
593 "Invalid --require-text-symbol= specification.\n");
sewardjf9ebc392010-05-09 22:30:43 +0000594 }
595 VG_(clo_req_tsyms)[VG_(clo_n_req_tsyms)] = tmp_str;
596 VG_(clo_n_req_tsyms)++;
597 }
598
sewardjfa8ec112005-01-19 11:55:34 +0000599 /* "stuvwxyz" --> stuvwxyz (binary) */
njn83df0b62009-02-25 01:01:05 +0000600 else if VG_STR_CLO(arg, "--trace-flags", tmp_str) {
sewardjfa8ec112005-01-19 11:55:34 +0000601 Int j;
sewardjfa8ec112005-01-19 11:55:34 +0000602
njn83df0b62009-02-25 01:01:05 +0000603 if (8 != VG_(strlen)(tmp_str)) {
njnb1cc5d62010-07-06 04:05:23 +0000604 VG_(fmsg_bad_option)(arg,
605 "--trace-flags argument must have 8 digits\n");
sewardjfa8ec112005-01-19 11:55:34 +0000606 }
607 for (j = 0; j < 8; j++) {
njn83df0b62009-02-25 01:01:05 +0000608 if ('0' == tmp_str[j]) { /* do nothing */ }
609 else if ('1' == tmp_str[j]) VG_(clo_trace_flags) |= (1 << (7-j));
sewardjfa8ec112005-01-19 11:55:34 +0000610 else {
njnb1cc5d62010-07-06 04:05:23 +0000611 VG_(fmsg_bad_option)(arg,
612 "--trace-flags argument can only contain 0s and 1s\n");
sewardjfa8ec112005-01-19 11:55:34 +0000613 }
614 }
615 }
616
617 /* "stuvwxyz" --> stuvwxyz (binary) */
njn83df0b62009-02-25 01:01:05 +0000618 else if VG_STR_CLO(arg, "--profile-flags", tmp_str) {
njn25e49d8e72002-09-23 09:36:25 +0000619 Int j;
njn25e49d8e72002-09-23 09:36:25 +0000620
njn83df0b62009-02-25 01:01:05 +0000621 if (8 != VG_(strlen)(tmp_str)) {
njnb1cc5d62010-07-06 04:05:23 +0000622 VG_(fmsg_bad_option)(arg,
623 "--profile-flags argument must have 8 digits\n");
njn25e49d8e72002-09-23 09:36:25 +0000624 }
sewardj8b635a42004-11-22 19:01:47 +0000625 for (j = 0; j < 8; j++) {
njn83df0b62009-02-25 01:01:05 +0000626 if ('0' == tmp_str[j]) { /* do nothing */ }
627 else if ('1' == tmp_str[j]) VG_(clo_profile_flags) |= (1 << (7-j));
njn25e49d8e72002-09-23 09:36:25 +0000628 else {
njnb1cc5d62010-07-06 04:05:23 +0000629 VG_(fmsg_bad_option)(arg,
630 "--profile-flags argument can only contain 0s and 1s\n");
njn25e49d8e72002-09-23 09:36:25 +0000631 }
632 }
633 }
sewardjde4a1d02002-03-22 01:27:54 +0000634
njn83df0b62009-02-25 01:01:05 +0000635 else if VG_INT_CLO (arg, "--trace-notbelow", VG_(clo_trace_notbelow)) {}
sewardjc771b292004-11-30 18:55:21 +0000636
njn83df0b62009-02-25 01:01:05 +0000637 else if VG_XACT_CLO(arg, "--gen-suppressions=no",
638 VG_(clo_gen_suppressions), 0) {}
639 else if VG_XACT_CLO(arg, "--gen-suppressions=yes",
640 VG_(clo_gen_suppressions), 1) {}
641 else if VG_XACT_CLO(arg, "--gen-suppressions=all",
642 VG_(clo_gen_suppressions), 2) {}
sewardjd153fae2005-01-10 17:24:47 +0000643
nethercote71980f02004-01-24 18:18:54 +0000644 else if ( ! VG_(needs).command_line_options
njn51d827b2005-05-09 01:02:08 +0000645 || ! VG_TDICT_CALL(tool_process_cmd_line_option, arg) ) {
njnb1cc5d62010-07-06 04:05:23 +0000646 VG_(fmsg_bad_option)(arg, "");
njn25e49d8e72002-09-23 09:36:25 +0000647 }
sewardjde4a1d02002-03-22 01:27:54 +0000648 }
649
sewardj738856f2009-07-15 14:48:32 +0000650 /* END command-line processing loop */
651
sewardj998d40d2004-12-06 14:24:52 +0000652 /* Make VEX control parameters sane */
653
654 if (VG_(clo_vex_control).guest_chase_thresh
655 >= VG_(clo_vex_control).guest_max_insns)
656 VG_(clo_vex_control).guest_chase_thresh
657 = VG_(clo_vex_control).guest_max_insns - 1;
658
659 if (VG_(clo_vex_control).guest_chase_thresh < 0)
660 VG_(clo_vex_control).guest_chase_thresh = 0;
661
662 /* Check various option values */
nethercote27fec902004-06-16 21:26:32 +0000663
njnf9ebf672003-05-12 21:41:30 +0000664 if (VG_(clo_verbosity) < 0)
sewardjde4a1d02002-03-22 01:27:54 +0000665 VG_(clo_verbosity) = 0;
666
njnbe9b47b2005-05-15 16:22:58 +0000667 if (VG_(clo_gen_suppressions) > 0 &&
668 !VG_(needs).core_errors && !VG_(needs).tool_errors) {
njnb1cc5d62010-07-06 04:05:23 +0000669 VG_(fmsg_bad_option)("--gen-suppressions=yes",
670 "Can't use --gen-suppressions= with %s\n"
671 "because it doesn't generate errors.\n", VG_(details).name);
njnbe9b47b2005-05-15 16:22:58 +0000672 }
673
sewardj738856f2009-07-15 14:48:32 +0000674 /* If XML output is requested, check that the tool actually
675 supports it. */
676 if (VG_(clo_xml) && !VG_(needs).xml_output) {
677 VG_(clo_xml) = False;
njnb1cc5d62010-07-06 04:05:23 +0000678 VG_(fmsg_bad_option)("--xml=yes",
sewardj738856f2009-07-15 14:48:32 +0000679 "%s does not support XML output.\n", VG_(details).name);
sewardj738856f2009-07-15 14:48:32 +0000680 /*NOTREACHED*/
681 }
682
683 vg_assert( VG_(clo_gen_suppressions) >= 0 );
684 vg_assert( VG_(clo_gen_suppressions) <= 2 );
685
sewardj71bc3cb2005-05-19 00:25:45 +0000686 /* If we've been asked to emit XML, mash around various other
687 options so as to constrain the output somewhat, and to remove
sewardj738856f2009-07-15 14:48:32 +0000688 any need for user input during the run.
689 */
sewardj71bc3cb2005-05-19 00:25:45 +0000690 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +0000691
692 /* We can't allow --gen-suppressions=yes, since that requires us
693 to print the error and then ask the user if she wants a
694 suppression for it, but in XML mode we won't print it until
695 we know whether we also need to print a suppression. Hence a
696 circular dependency. So disallow this.
697 (--gen-suppressions=all is still OK since we don't need any
698 user interaction in this case.) */
699 if (VG_(clo_gen_suppressions) == 1) {
njnb1cc5d62010-07-06 04:05:23 +0000700 VG_(fmsg_bad_option)(
701 "--xml=yes together with --gen-suppressions=yes",
702 "When --xml=yes is specified, --gen-suppressions=no\n"
703 "or --gen-suppressions=all is allowed, but not "
sewardj738856f2009-07-15 14:48:32 +0000704 "--gen-suppressions=yes.\n");
sewardj738856f2009-07-15 14:48:32 +0000705 }
706
707 /* We can't allow DB attaching (or we maybe could, but results
708 could be chaotic ..) since it requires user input. Hence
709 disallow. */
710 if (VG_(clo_db_attach)) {
njnb1cc5d62010-07-06 04:05:23 +0000711 VG_(fmsg_bad_option)(
712 "--xml=yes together with --db-attach=yes",
713 "--db-attach=yes is not allowed with --xml=yes\n"
714 "because it would require user input.\n");
sewardj738856f2009-07-15 14:48:32 +0000715 }
716
717 /* Disallow dump_error in XML mode; sounds like a recipe for
718 chaos. No big deal; dump_error is a flag for debugging V
719 itself. */
720 if (VG_(clo_dump_error) > 0) {
njnb1cc5d62010-07-06 04:05:23 +0000721 VG_(fmsg_bad_option)("--xml=yes together with --dump-error", "");
sewardj738856f2009-07-15 14:48:32 +0000722 }
723
sewardj71bc3cb2005-05-19 00:25:45 +0000724 /* Disable error limits (this might be a bad idea!) */
725 VG_(clo_error_limit) = False;
726 /* Disable emulation warnings */
sewardj738856f2009-07-15 14:48:32 +0000727
sewardj71bc3cb2005-05-19 00:25:45 +0000728 /* Also, we want to set options for the leak checker, but that
729 will have to be done in Memcheck's flag-handling code, not
730 here. */
731 }
732
njnbe9b47b2005-05-15 16:22:58 +0000733 /* All non-logging-related options have been checked. If the logging
734 option specified is ok, we can switch to it, as we know we won't
735 have to generate any other command-line-related error messages.
736 (So far we should be still attached to stderr, so we can show on
737 the terminal any problems to do with processing command line
738 opts.)
739
sewardj738856f2009-07-15 14:48:32 +0000740 So set up logging now. After this is done, VG_(log_output_sink)
741 and (if relevant) VG_(xml_output_sink) should be connected to
742 whatever sink has been selected, and we indiscriminately chuck
743 stuff into it without worrying what the nature of it is. Oh the
744 wonder of Unix streams. */
sewardj4cf05692002-10-27 20:28:29 +0000745
sewardj738856f2009-07-15 14:48:32 +0000746 vg_assert(VG_(log_output_sink).fd == 2 /* stderr */);
747 vg_assert(VG_(log_output_sink).is_socket == False);
748 vg_assert(VG_(clo_log_fname_expanded) == NULL);
749
750 vg_assert(VG_(xml_output_sink).fd == -1 /* disabled */);
751 vg_assert(VG_(xml_output_sink).is_socket == False);
752 vg_assert(VG_(clo_xml_fname_expanded) == NULL);
753
754 /* --- set up the normal text output channel --- */
sewardj4cf05692002-10-27 20:28:29 +0000755
njnbe9b47b2005-05-15 16:22:58 +0000756 switch (log_to) {
sewardj73cf3bc2002-11-03 03:20:15 +0000757
sewardj4cf05692002-10-27 20:28:29 +0000758 case VgLogTo_Fd:
sewardj738856f2009-07-15 14:48:32 +0000759 vg_assert(log_fsname_unexpanded == NULL);
sewardj4cf05692002-10-27 20:28:29 +0000760 break;
sewardj73cf3bc2002-11-03 03:20:15 +0000761
sewardj4cf05692002-10-27 20:28:29 +0000762 case VgLogTo_File: {
njn374a36d2007-11-23 01:41:32 +0000763 Char* logfilename;
jsgff3c3f1a2003-10-14 22:13:28 +0000764
sewardj738856f2009-07-15 14:48:32 +0000765 vg_assert(log_fsname_unexpanded != NULL);
766 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
jsgff3c3f1a2003-10-14 22:13:28 +0000767
njn374a36d2007-11-23 01:41:32 +0000768 // Nb: we overwrite an existing file of this name without asking
769 // any questions.
sewardj738856f2009-07-15 14:48:32 +0000770 logfilename = VG_(expand_file_name)("--log-file",
771 log_fsname_unexpanded);
njn374a36d2007-11-23 01:41:32 +0000772 sres = VG_(open)(logfilename,
njnda033f52005-12-19 21:27:58 +0000773 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
774 VKI_S_IRUSR|VKI_S_IWUSR);
njncda2f0f2009-05-18 02:12:08 +0000775 if (!sr_isError(sres)) {
776 tmp_log_fd = sr_Res(sres);
sewardj738856f2009-07-15 14:48:32 +0000777 VG_(clo_log_fname_expanded) = logfilename;
njnbe9b47b2005-05-15 16:22:58 +0000778 } else {
njnb1cc5d62010-07-06 04:05:23 +0000779 VG_(fmsg)("can't create log file '%s': %s\n",
780 logfilename, VG_(strerror)(sr_Err(sres)));
781 VG_(exit)(1);
sewardj603d4102005-01-11 14:01:02 +0000782 /*NOTREACHED*/
njn374a36d2007-11-23 01:41:32 +0000783 }
sewardj738856f2009-07-15 14:48:32 +0000784 break;
sewardj73cf3bc2002-11-03 03:20:15 +0000785 }
786
787 case VgLogTo_Socket: {
sewardj738856f2009-07-15 14:48:32 +0000788 vg_assert(log_fsname_unexpanded != NULL);
789 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
790 tmp_log_fd = VG_(connect_via_socket)( log_fsname_unexpanded );
njnda033f52005-12-19 21:27:58 +0000791 if (tmp_log_fd == -1) {
njnb1cc5d62010-07-06 04:05:23 +0000792 VG_(fmsg)("Invalid --log-socket spec of '%s'\n",
793 log_fsname_unexpanded);
794 VG_(exit)(1);
njnbe9b47b2005-05-15 16:22:58 +0000795 /*NOTREACHED*/
sewardj4cf05692002-10-27 20:28:29 +0000796 }
njnda033f52005-12-19 21:27:58 +0000797 if (tmp_log_fd == -2) {
njnb1cc5d62010-07-06 04:05:23 +0000798 VG_(umsg)("failed to connect to logging server '%s'.\n"
799 "Log messages will sent to stderr instead.\n",
800 log_fsname_unexpanded );
801
sewardj570f8902002-11-03 11:44:36 +0000802 /* We don't change anything here. */
sewardj738856f2009-07-15 14:48:32 +0000803 vg_assert(VG_(log_output_sink).fd == 2);
njnda033f52005-12-19 21:27:58 +0000804 tmp_log_fd = 2;
sewardj570f8902002-11-03 11:44:36 +0000805 } else {
njnda033f52005-12-19 21:27:58 +0000806 vg_assert(tmp_log_fd > 0);
sewardj738856f2009-07-15 14:48:32 +0000807 VG_(log_output_sink).is_socket = True;
sewardj570f8902002-11-03 11:44:36 +0000808 }
sewardj73cf3bc2002-11-03 03:20:15 +0000809 break;
810 }
sewardj4cf05692002-10-27 20:28:29 +0000811 }
812
sewardj738856f2009-07-15 14:48:32 +0000813 /* --- set up the XML output channel --- */
sewardj71bc3cb2005-05-19 00:25:45 +0000814
sewardj738856f2009-07-15 14:48:32 +0000815 switch (xml_to) {
816
817 case VgLogTo_Fd:
818 vg_assert(xml_fsname_unexpanded == NULL);
819 break;
820
821 case VgLogTo_File: {
822 Char* xmlfilename;
823
824 vg_assert(xml_fsname_unexpanded != NULL);
825 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
826
827 // Nb: we overwrite an existing file of this name without asking
828 // any questions.
829 xmlfilename = VG_(expand_file_name)("--xml-file",
830 xml_fsname_unexpanded);
831 sres = VG_(open)(xmlfilename,
832 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
833 VKI_S_IRUSR|VKI_S_IWUSR);
834 if (!sr_isError(sres)) {
835 tmp_xml_fd = sr_Res(sres);
836 VG_(clo_xml_fname_expanded) = xmlfilename;
837 /* strdup here is probably paranoid overkill, but ... */
838 *xml_fname_unexpanded = VG_(strdup)( "main.mpclo.2",
839 xml_fsname_unexpanded );
840 } else {
njnb1cc5d62010-07-06 04:05:23 +0000841 VG_(fmsg)("can't create XML file '%s': %s\n",
842 xmlfilename, VG_(strerror)(sr_Err(sres)));
843 VG_(exit)(1);
sewardj738856f2009-07-15 14:48:32 +0000844 /*NOTREACHED*/
845 }
846 break;
847 }
848
849 case VgLogTo_Socket: {
850 vg_assert(xml_fsname_unexpanded != NULL);
851 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
852 tmp_xml_fd = VG_(connect_via_socket)( xml_fsname_unexpanded );
853 if (tmp_xml_fd == -1) {
njnb1cc5d62010-07-06 04:05:23 +0000854 VG_(fmsg)("Invalid --xml-socket spec of '%s'\n",
855 xml_fsname_unexpanded );
856 VG_(exit)(1);
sewardj738856f2009-07-15 14:48:32 +0000857 /*NOTREACHED*/
858 }
859 if (tmp_xml_fd == -2) {
njnb1cc5d62010-07-06 04:05:23 +0000860 VG_(umsg)("failed to connect to XML logging server '%s'.\n"
861 "XML output will sent to stderr instead.\n",
862 xml_fsname_unexpanded);
sewardj738856f2009-07-15 14:48:32 +0000863 /* We don't change anything here. */
864 vg_assert(VG_(xml_output_sink).fd == 2);
865 tmp_xml_fd = 2;
866 } else {
867 vg_assert(tmp_xml_fd > 0);
868 VG_(xml_output_sink).is_socket = True;
869 }
870 break;
871 }
sewardj71bc3cb2005-05-19 00:25:45 +0000872 }
873
sewardj738856f2009-07-15 14:48:32 +0000874 /* If we've got this far, and XML mode was requested, but no XML
875 output channel appears to have been specified, just stop. We
876 could continue, and XML output will simply vanish into nowhere,
877 but that is likely to confuse the hell out of users, which is
878 distinctly Ungood. */
879 if (VG_(clo_xml) && tmp_xml_fd == -1) {
njnb1cc5d62010-07-06 04:05:23 +0000880 VG_(fmsg_bad_option)(
881 "--xml=yes, but no XML destination specified",
sewardj738856f2009-07-15 14:48:32 +0000882 "--xml=yes has been specified, but there is no XML output\n"
883 "destination. You must specify an XML output destination\n"
njnb1cc5d62010-07-06 04:05:23 +0000884 "using --xml-fd, --xml-file or --xml-socket.\n"
885 );
sewardj738856f2009-07-15 14:48:32 +0000886 }
887
888 // Finalise the output fds: the log fd ..
889
njnda033f52005-12-19 21:27:58 +0000890 if (tmp_log_fd >= 0) {
sewardj738856f2009-07-15 14:48:32 +0000891 // Move log_fd into the safe range, so it doesn't conflict with
892 // any app fds.
njnda033f52005-12-19 21:27:58 +0000893 tmp_log_fd = VG_(fcntl)(tmp_log_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
894 if (tmp_log_fd < 0) {
sewardj738856f2009-07-15 14:48:32 +0000895 VG_(message)(Vg_UserMsg, "valgrind: failed to move logfile fd "
896 "into safe range, using stderr\n");
897 VG_(log_output_sink).fd = 2; // stderr
898 VG_(log_output_sink).is_socket = False;
njnda033f52005-12-19 21:27:58 +0000899 } else {
sewardj738856f2009-07-15 14:48:32 +0000900 VG_(log_output_sink).fd = tmp_log_fd;
901 VG_(fcntl)(VG_(log_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
njnda033f52005-12-19 21:27:58 +0000902 }
903 } else {
904 // If they said --log-fd=-1, don't print anything. Plausible for use in
905 // regression testing suites that use client requests to count errors.
sewardj738856f2009-07-15 14:48:32 +0000906 VG_(log_output_sink).fd = -1;
907 VG_(log_output_sink).is_socket = False;
jsgf855d93d2003-10-13 22:26:55 +0000908 }
909
sewardj738856f2009-07-15 14:48:32 +0000910 // Finalise the output fds: and the XML fd ..
911
912 if (tmp_xml_fd >= 0) {
913 // Move xml_fd into the safe range, so it doesn't conflict with
914 // any app fds.
915 tmp_xml_fd = VG_(fcntl)(tmp_xml_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
916 if (tmp_xml_fd < 0) {
917 VG_(message)(Vg_UserMsg, "valgrind: failed to move XML file fd "
918 "into safe range, using stderr\n");
919 VG_(xml_output_sink).fd = 2; // stderr
920 VG_(xml_output_sink).is_socket = False;
921 } else {
922 VG_(xml_output_sink).fd = tmp_xml_fd;
923 VG_(fcntl)(VG_(xml_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
924 }
925 } else {
926 // If they said --xml-fd=-1, don't print anything. Plausible for use in
927 // regression testing suites that use client requests to count errors.
928 VG_(xml_output_sink).fd = -1;
929 VG_(xml_output_sink).is_socket = False;
930 }
931
932 // Suppressions related stuff
933
sewardj45f4e7c2005-09-27 19:20:21 +0000934 if (VG_(clo_n_suppressions) < VG_CLO_MAX_SFILES-1 &&
935 (VG_(needs).core_errors || VG_(needs).tool_errors)) {
936 /* If we haven't reached the max number of suppressions, load
937 the default one. */
938 static const Char default_supp[] = "default.supp";
939 Int len = VG_(strlen)(VG_(libdir)) + 1 + sizeof(default_supp);
sewardj738856f2009-07-15 14:48:32 +0000940 Char *buf = VG_(arena_malloc)(VG_AR_CORE, "main.mpclo.3", len);
sewardj45f4e7c2005-09-27 19:20:21 +0000941 VG_(sprintf)(buf, "%s/%s", VG_(libdir), default_supp);
942 VG_(clo_suppressions)[VG_(clo_n_suppressions)] = buf;
943 VG_(clo_n_suppressions)++;
944 }
sewardjde4a1d02002-03-22 01:27:54 +0000945
sewardj738856f2009-07-15 14:48:32 +0000946 *logging_to_fd = log_to == VgLogTo_Fd || log_to == VgLogTo_Socket;
sewardj45f4e7c2005-09-27 19:20:21 +0000947}
948
sewardj4efbaa72008-06-04 06:51:58 +0000949// Write the name and value of log file qualifiers to the xml file.
950static void print_file_vars(Char* format)
951{
952 Int i = 0;
953
954 while (format[i]) {
955 if (format[i] == '%') {
956 // We saw a '%'. What's next...
957 i++;
958 if ('q' == format[i]) {
959 i++;
960 if ('{' == format[i]) {
961 // Get the env var name, print its contents.
962 Char* qualname;
963 Char* qual;
964 i++;
965 qualname = &format[i];
966 while (True) {
967 if ('}' == format[i]) {
968 // Temporarily replace the '}' with NUL to extract var
969 // name.
970 format[i] = 0;
971 qual = VG_(getenv)(qualname);
972 break;
973 }
974 i++;
975 }
976
sewardj7ca100d2009-08-15 23:05:34 +0000977 VG_(printf_xml_no_f_c)(
978 "<logfilequalifier> <var>%t</var> "
979 "<value>%t</value> </logfilequalifier>\n",
980 qualname,qual
981 );
sewardj4efbaa72008-06-04 06:51:58 +0000982 format[i] = '}';
983 i++;
984 }
985 }
986 } else {
987 i++;
988 }
989 }
990}
991
sewardj45f4e7c2005-09-27 19:20:21 +0000992
993/*====================================================================*/
994/*=== Printing the preamble ===*/
995/*====================================================================*/
996
njnf8a11cf2009-08-02 23:03:06 +0000997// Print the command, escaping any chars that require it.
barta3054f52010-06-14 18:12:56 +0000998static void umsg_or_xml_arg(const Char* arg,
njnf8a11cf2009-08-02 23:03:06 +0000999 UInt (*umsg_or_xml)( const HChar*, ... ) )
1000{
1001 SizeT len = VG_(strlen)(arg);
1002 Char* special = " \\<>";
1003 Int i;
1004 for (i = 0; i < len; i++) {
1005 if (VG_(strchr)(special, arg[i])) {
1006 umsg_or_xml("\\"); // escape with a backslash if necessary
1007 }
1008 umsg_or_xml("%c", arg[i]);
1009 }
1010}
1011
sewardj45f4e7c2005-09-27 19:20:21 +00001012/* Ok, the logging sink is running now. Print a suitable preamble.
1013 If logging to file or a socket, write details of parent PID and
1014 command line args, to help people trying to interpret the
1015 results of a run which encompasses multiple processes. */
sewardj738856f2009-07-15 14:48:32 +00001016static void print_preamble ( Bool logging_to_fd,
1017 Char* xml_fname_unexpanded,
1018 const HChar* toolname )
sewardj45f4e7c2005-09-27 19:20:21 +00001019{
sewardj738856f2009-07-15 14:48:32 +00001020 Int i;
tom60a4b0b2005-10-12 10:45:27 +00001021 HChar* xpre = VG_(clo_xml) ? " <line>" : "";
1022 HChar* xpost = VG_(clo_xml) ? "</line>" : "";
sewardj738856f2009-07-15 14:48:32 +00001023 UInt (*umsg_or_xml)( const HChar*, ... )
1024 = VG_(clo_xml) ? VG_(printf_xml) : VG_(umsg);
tom60a4b0b2005-10-12 10:45:27 +00001025
sewardj14c7cc52007-02-25 15:08:24 +00001026 vg_assert( VG_(args_for_client) );
1027 vg_assert( VG_(args_for_valgrind) );
sewardj99a2ceb2007-11-09 12:30:36 +00001028 vg_assert( toolname );
sewardj14c7cc52007-02-25 15:08:24 +00001029
sewardj71bc3cb2005-05-19 00:25:45 +00001030 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +00001031 VG_(printf_xml)("<?xml version=\"1.0\"?>\n");
1032 VG_(printf_xml)("\n");
1033 VG_(printf_xml)("<valgrindoutput>\n");
1034 VG_(printf_xml)("\n");
1035 VG_(printf_xml)("<protocolversion>4</protocolversion>\n");
1036 VG_(printf_xml)("<protocoltool>%s</protocoltool>\n", toolname);
1037 VG_(printf_xml)("\n");
sewardj71bc3cb2005-05-19 00:25:45 +00001038 }
1039
sewardj738856f2009-07-15 14:48:32 +00001040 if (VG_(clo_xml) || VG_(clo_verbosity > 0)) {
sewardjd7bddad2005-06-13 16:48:32 +00001041
1042 if (VG_(clo_xml))
sewardj738856f2009-07-15 14:48:32 +00001043 VG_(printf_xml)("<preamble>\n");
sewardjd7bddad2005-06-13 16:48:32 +00001044
nethercote996901a2004-08-03 13:29:09 +00001045 /* Tool details */
sewardj743a2082010-07-23 17:03:22 +00001046 umsg_or_xml( VG_(clo_xml) ? "%s%t%t%t, %t%s\n" : "%s%s%s%s, %s%s\n",
sewardj71bc3cb2005-05-19 00:25:45 +00001047 xpre,
njnd04b7c62002-10-03 14:05:52 +00001048 VG_(details).name,
njnb9c427c2004-12-01 14:14:42 +00001049 NULL == VG_(details).version ? "" : "-",
njnd04b7c62002-10-03 14:05:52 +00001050 NULL == VG_(details).version
1051 ? (Char*)"" : VG_(details).version,
sewardj71bc3cb2005-05-19 00:25:45 +00001052 VG_(details).description,
sewardj738856f2009-07-15 14:48:32 +00001053 xpost );
sewardj99a2ceb2007-11-09 12:30:36 +00001054
njn10b9aea2009-07-14 06:55:05 +00001055 if (VG_(strlen)(toolname) >= 4 && VG_STREQN(4, toolname, "exp-")) {
sewardj738856f2009-07-15 14:48:32 +00001056 umsg_or_xml(
njnb6267bd2009-08-12 00:14:16 +00001057 "%sNOTE: This is an Experimental-Class Valgrind Tool%s\n",
sewardj99a2ceb2007-11-09 12:30:36 +00001058 xpre, xpost
1059 );
1060 }
1061
sewardj743a2082010-07-23 17:03:22 +00001062 umsg_or_xml( VG_(clo_xml) ? "%s%t%s\n" : "%s%s%s\n",
1063 xpre, VG_(details).copyright_author, xpost );
sewardj3b2736a2002-03-24 12:18:35 +00001064
njnd04b7c62002-10-03 14:05:52 +00001065 /* Core details */
sewardj738856f2009-07-15 14:48:32 +00001066 umsg_or_xml(
njnf73d87f2009-07-24 04:47:04 +00001067 "%sUsing Valgrind-%s and LibVEX; rerun with -h for copyright info%s\n",
1068 xpre, VERSION, xpost
sewardj738856f2009-07-15 14:48:32 +00001069 );
sewardj45f4e7c2005-09-27 19:20:21 +00001070
njnf3977a32009-08-04 00:27:56 +00001071 // Print the command line. At one point we wrapped at 80 chars and
1072 // printed a '\' as a line joiner, but that makes it hard to cut and
1073 // paste the command line (because of the "==pid==" prefixes), so we now
1074 // favour utility and simplicity over aesthetics.
1075 umsg_or_xml("%sCommand: ", xpre);
njn53162bf2009-07-29 23:34:49 +00001076 if (VG_(args_the_exename))
njnf8a11cf2009-08-02 23:03:06 +00001077 umsg_or_xml_arg(VG_(args_the_exename), umsg_or_xml);
njn53162bf2009-07-29 23:34:49 +00001078 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1079 HChar* s = *(HChar**)VG_(indexXA)( VG_(args_for_client), i );
njnf8a11cf2009-08-02 23:03:06 +00001080 umsg_or_xml(" ");
1081 umsg_or_xml_arg(s, umsg_or_xml);
njn53162bf2009-07-29 23:34:49 +00001082 }
njnf3977a32009-08-04 00:27:56 +00001083 umsg_or_xml("%s\n", xpost);
njn53162bf2009-07-29 23:34:49 +00001084
sewardjd7bddad2005-06-13 16:48:32 +00001085 if (VG_(clo_xml))
sewardj738856f2009-07-15 14:48:32 +00001086 VG_(printf_xml)("</preamble>\n");
njnd04b7c62002-10-03 14:05:52 +00001087 }
1088
njnb6267bd2009-08-12 00:14:16 +00001089 // Print the parent PID, and other stuff, if necessary.
sewardj45f4e7c2005-09-27 19:20:21 +00001090 if (!VG_(clo_xml) && VG_(clo_verbosity) > 0 && !logging_to_fd) {
njn305dc002009-07-30 23:36:43 +00001091 VG_(umsg)("Parent PID: %d\n", VG_(getppid)());
sewardj4cf05692002-10-27 20:28:29 +00001092 }
sewardj71bc3cb2005-05-19 00:25:45 +00001093 else
1094 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +00001095 VG_(printf_xml)("\n");
1096 VG_(printf_xml)("<pid>%d</pid>\n", VG_(getpid)());
1097 VG_(printf_xml)("<ppid>%d</ppid>\n", VG_(getppid)());
1098 VG_(printf_xml_no_f_c)("<tool>%t</tool>\n", toolname);
1099 if (xml_fname_unexpanded)
1100 print_file_vars(xml_fname_unexpanded);
sewardj768db0e2005-07-19 14:18:56 +00001101 if (VG_(clo_xml_user_comment)) {
1102 /* Note: the user comment itself is XML and is therefore to
1103 be passed through verbatim (%s) rather than escaped
1104 (%t). */
sewardj738856f2009-07-15 14:48:32 +00001105 VG_(printf_xml)("<usercomment>%s</usercomment>\n",
1106 VG_(clo_xml_user_comment));
sewardj768db0e2005-07-19 14:18:56 +00001107 }
sewardj738856f2009-07-15 14:48:32 +00001108 VG_(printf_xml)("\n");
1109 VG_(printf_xml)("<args>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001110
sewardj738856f2009-07-15 14:48:32 +00001111 VG_(printf_xml)(" <vargv>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001112 if (VG_(name_of_launcher))
sewardj738856f2009-07-15 14:48:32 +00001113 VG_(printf_xml_no_f_c)(" <exe>%t</exe>\n",
1114 VG_(name_of_launcher));
sewardj125fd4f2007-03-08 19:56:14 +00001115 else
njnb1cc5d62010-07-06 04:05:23 +00001116 VG_(printf_xml_no_f_c)(" <exe>%t</exe>\n",
1117 "(launcher name unknown)");
sewardj14c7cc52007-02-25 15:08:24 +00001118 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
sewardj738856f2009-07-15 14:48:32 +00001119 VG_(printf_xml_no_f_c)(
1120 " <arg>%t</arg>\n",
1121 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1122 );
sewardjb8a3dac2005-07-19 12:39:11 +00001123 }
sewardj738856f2009-07-15 14:48:32 +00001124 VG_(printf_xml)(" </vargv>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001125
sewardj738856f2009-07-15 14:48:32 +00001126 VG_(printf_xml)(" <argv>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001127 if (VG_(args_the_exename))
sewardj738856f2009-07-15 14:48:32 +00001128 VG_(printf_xml_no_f_c)(" <exe>%t</exe>\n",
1129 VG_(args_the_exename));
sewardj14c7cc52007-02-25 15:08:24 +00001130 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
sewardj738856f2009-07-15 14:48:32 +00001131 VG_(printf_xml_no_f_c)(
1132 " <arg>%t</arg>\n",
1133 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1134 );
sewardj8665d8e2005-06-01 17:35:23 +00001135 }
sewardj738856f2009-07-15 14:48:32 +00001136 VG_(printf_xml)(" </argv>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001137
sewardj738856f2009-07-15 14:48:32 +00001138 VG_(printf_xml)("</args>\n");
sewardj71bc3cb2005-05-19 00:25:45 +00001139 }
sewardj4cf05692002-10-27 20:28:29 +00001140
njnb6267bd2009-08-12 00:14:16 +00001141 // Last thing in the preamble is a blank line.
sewardj738856f2009-07-15 14:48:32 +00001142 if (VG_(clo_xml))
1143 VG_(printf_xml)("\n");
njnb6267bd2009-08-12 00:14:16 +00001144 else if (VG_(clo_verbosity) > 0)
1145 VG_(umsg)("\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001146
sewardjde4a1d02002-03-22 01:27:54 +00001147 if (VG_(clo_verbosity) > 1) {
sewardj92645592005-07-23 09:18:34 +00001148 SysRes fd;
sewardj1f0bbc72005-11-16 03:51:02 +00001149 VexArch vex_arch;
1150 VexArchInfo vex_archinfo;
sewardj45f4e7c2005-09-27 19:20:21 +00001151 if (!logging_to_fd)
sewardj738856f2009-07-15 14:48:32 +00001152 VG_(message)(Vg_DebugMsg, "\n");
njna3311642009-08-10 01:29:14 +00001153 VG_(message)(Vg_DebugMsg, "Valgrind options:\n");
sewardj14c7cc52007-02-25 15:08:24 +00001154 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
1155 VG_(message)(Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +00001156 " %s\n",
sewardj14c7cc52007-02-25 15:08:24 +00001157 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ));
sewardjde4a1d02002-03-22 01:27:54 +00001158 }
nethercotea70f7352004-04-18 12:08:46 +00001159
sewardj738856f2009-07-15 14:48:32 +00001160 VG_(message)(Vg_DebugMsg, "Contents of /proc/version:\n");
nethercotea70f7352004-04-18 12:08:46 +00001161 fd = VG_(open) ( "/proc/version", VKI_O_RDONLY, 0 );
njncda2f0f2009-05-18 02:12:08 +00001162 if (sr_isError(fd)) {
sewardj738856f2009-07-15 14:48:32 +00001163 VG_(message)(Vg_DebugMsg, " can't open /proc/version\n");
nethercotea70f7352004-04-18 12:08:46 +00001164 } else {
sewardj71bc3cb2005-05-19 00:25:45 +00001165# define BUF_LEN 256
nethercotea70f7352004-04-18 12:08:46 +00001166 Char version_buf[BUF_LEN];
njnf3977a32009-08-04 00:27:56 +00001167 Int n = VG_(read) ( sr_Res(fd), version_buf, BUF_LEN );
1168 vg_assert(n <= BUF_LEN);
1169 if (n > 0) {
1170 version_buf[n-1] = '\0';
sewardj738856f2009-07-15 14:48:32 +00001171 VG_(message)(Vg_DebugMsg, " %s\n", version_buf);
nethercotea70f7352004-04-18 12:08:46 +00001172 } else {
sewardj738856f2009-07-15 14:48:32 +00001173 VG_(message)(Vg_DebugMsg, " (empty?)\n");
nethercotea70f7352004-04-18 12:08:46 +00001174 }
njncda2f0f2009-05-18 02:12:08 +00001175 VG_(close)(sr_Res(fd));
sewardj71bc3cb2005-05-19 00:25:45 +00001176# undef BUF_LEN
nethercotea70f7352004-04-18 12:08:46 +00001177 }
sewardj1f0bbc72005-11-16 03:51:02 +00001178
1179 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
sewardje3121f32006-01-27 21:23:23 +00001180 VG_(message)(
1181 Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +00001182 "Arch and hwcaps: %s, %s\n",
sewardje3121f32006-01-27 21:23:23 +00001183 LibVEX_ppVexArch ( vex_arch ),
1184 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1185 );
sewardje66f2e02006-12-30 17:45:08 +00001186 VG_(message)(
1187 Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +00001188 "Page sizes: currently %d, max supported %d\n",
sewardje66f2e02006-12-30 17:45:08 +00001189 (Int)VKI_PAGE_SIZE, (Int)VKI_MAX_PAGE_SIZE
1190 );
sewardj738856f2009-07-15 14:48:32 +00001191 VG_(message)(Vg_DebugMsg,
1192 "Valgrind library directory: %s\n", VG_(libdir));
sewardjde4a1d02002-03-22 01:27:54 +00001193 }
nethercotef6a1d502004-08-09 12:21:57 +00001194}
1195
sewardjde4a1d02002-03-22 01:27:54 +00001196
nethercote71980f02004-01-24 18:18:54 +00001197/*====================================================================*/
1198/*=== File descriptor setup ===*/
1199/*====================================================================*/
1200
sewardj5f229e22005-09-28 01:36:01 +00001201/* Number of file descriptors that Valgrind tries to reserve for
1202 it's own use - just a small constant. */
1203#define N_RESERVED_FDS (10)
1204
nethercote71980f02004-01-24 18:18:54 +00001205static void setup_file_descriptors(void)
1206{
1207 struct vki_rlimit rl;
sewardj17c11042006-10-15 01:26:40 +00001208 Bool show = False;
nethercote71980f02004-01-24 18:18:54 +00001209
1210 /* Get the current file descriptor limits. */
1211 if (VG_(getrlimit)(VKI_RLIMIT_NOFILE, &rl) < 0) {
1212 rl.rlim_cur = 1024;
1213 rl.rlim_max = 1024;
1214 }
1215
njnf76d27a2009-05-28 01:53:07 +00001216# if defined(VGO_darwin)
1217 /* Darwin lies. It reports file max as RLIM_INFINITY but
1218 silently disallows anything bigger than 10240. */
1219 if (rl.rlim_cur >= 10240 && rl.rlim_max == 0x7fffffffffffffffULL) {
1220 rl.rlim_max = 10240;
1221 }
1222# endif
1223
sewardj17c11042006-10-15 01:26:40 +00001224 if (show)
njn8a7b41b2007-09-23 00:51:24 +00001225 VG_(printf)("fd limits: host, before: cur %lu max %lu\n",
sewardja8ffda62008-07-18 18:23:24 +00001226 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
sewardj17c11042006-10-15 01:26:40 +00001227
1228# if defined(VGP_ppc32_aix5) || defined(VGP_ppc64_aix5)
1229 /* I don't know why this kludge is needed; however if rl.rlim_cur
1230 is RLIM_INFINITY, then VG_(safe_fd)'s attempts using VG_(fcntl)
1231 to lift V's file descriptors above the threshold RLIM_INFINITY -
1232 N_RESERVED_FDS fail. So just use a relatively conservative
1233 value in this case. */
1234 if (rl.rlim_cur > 1024)
1235 rl.rlim_cur = 1024;
1236# endif
1237
nethercote71980f02004-01-24 18:18:54 +00001238 /* Work out where to move the soft limit to. */
njn14319cc2005-03-13 06:26:22 +00001239 if (rl.rlim_cur + N_RESERVED_FDS <= rl.rlim_max) {
1240 rl.rlim_cur = rl.rlim_cur + N_RESERVED_FDS;
nethercote71980f02004-01-24 18:18:54 +00001241 } else {
1242 rl.rlim_cur = rl.rlim_max;
1243 }
1244
1245 /* Reserve some file descriptors for our use. */
njn14319cc2005-03-13 06:26:22 +00001246 VG_(fd_soft_limit) = rl.rlim_cur - N_RESERVED_FDS;
1247 VG_(fd_hard_limit) = rl.rlim_cur - N_RESERVED_FDS;
nethercote71980f02004-01-24 18:18:54 +00001248
1249 /* Update the soft limit. */
1250 VG_(setrlimit)(VKI_RLIMIT_NOFILE, &rl);
1251
sewardj17c11042006-10-15 01:26:40 +00001252 if (show) {
njn8a7b41b2007-09-23 00:51:24 +00001253 VG_(printf)("fd limits: host, after: cur %lu max %lu\n",
sewardja8ffda62008-07-18 18:23:24 +00001254 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
sewardj17c11042006-10-15 01:26:40 +00001255 VG_(printf)("fd limits: guest : cur %u max %u\n",
1256 VG_(fd_soft_limit), VG_(fd_hard_limit));
1257 }
1258
sewardj45f4e7c2005-09-27 19:20:21 +00001259 if (VG_(cl_exec_fd) != -1)
1260 VG_(cl_exec_fd) = VG_(safe_fd)( VG_(cl_exec_fd) );
nethercote71980f02004-01-24 18:18:54 +00001261}
1262
sewardjde4a1d02002-03-22 01:27:54 +00001263
njn2da73352005-06-18 01:35:16 +00001264/*====================================================================*/
njn2025cf92005-06-26 20:44:48 +00001265/*=== BB profiling ===*/
1266/*====================================================================*/
1267
1268static
1269void show_BB_profile ( BBProfEntry tops[], UInt n_tops, ULong score_total )
1270{
1271 ULong score_cumul, score_here;
1272 Char buf_cumul[10], buf_here[10];
1273 Char name[64];
1274 Int r;
1275
1276 VG_(printf)("\n");
1277 VG_(printf)("-----------------------------------------------------------\n");
1278 VG_(printf)("--- BEGIN BB Profile (summary of scores) ---\n");
1279 VG_(printf)("-----------------------------------------------------------\n");
1280 VG_(printf)("\n");
1281
1282 VG_(printf)("Total score = %lld\n\n", score_total);
1283
1284 score_cumul = 0;
1285 for (r = 0; r < n_tops; r++) {
1286 if (tops[r].addr == 0)
1287 continue;
1288 name[0] = 0;
1289 VG_(get_fnname_w_offset)(tops[r].addr, name, 64);
1290 name[63] = 0;
1291 score_here = tops[r].score;
1292 score_cumul += score_here;
1293 VG_(percentify)(score_cumul, score_total, 2, 6, buf_cumul);
1294 VG_(percentify)(score_here, score_total, 2, 6, buf_here);
1295 VG_(printf)("%3d: (%9lld %s) %9lld %s 0x%llx %s\n",
1296 r,
1297 score_cumul, buf_cumul,
1298 score_here, buf_here, tops[r].addr, name );
1299 }
1300
1301 VG_(printf)("\n");
1302 VG_(printf)("-----------------------------------------------------------\n");
1303 VG_(printf)("--- BB Profile (BB details) ---\n");
1304 VG_(printf)("-----------------------------------------------------------\n");
1305 VG_(printf)("\n");
1306
1307 score_cumul = 0;
1308 for (r = 0; r < n_tops; r++) {
1309 if (tops[r].addr == 0)
1310 continue;
1311 name[0] = 0;
1312 VG_(get_fnname_w_offset)(tops[r].addr, name, 64);
1313 name[63] = 0;
1314 score_here = tops[r].score;
1315 score_cumul += score_here;
1316 VG_(percentify)(score_cumul, score_total, 2, 6, buf_cumul);
1317 VG_(percentify)(score_here, score_total, 2, 6, buf_here);
1318 VG_(printf)("\n");
1319 VG_(printf)("=-=-=-=-=-=-=-=-=-=-=-=-=-= begin BB rank %d "
1320 "=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n", r);
1321 VG_(printf)("%3d: (%9lld %s) %9lld %s 0x%llx %s\n",
1322 r,
1323 score_cumul, buf_cumul,
1324 score_here, buf_here, tops[r].addr, name );
1325 VG_(printf)("\n");
sewardjbcccbc02007-04-09 22:24:57 +00001326 VG_(discard_translations)(tops[r].addr, 1, "bb profile");
sewardj0ec07f32006-01-12 12:32:32 +00001327 VG_(translate)(0, tops[r].addr, True, VG_(clo_profile_flags), 0, True);
njn2025cf92005-06-26 20:44:48 +00001328 VG_(printf)("=-=-=-=-=-=-=-=-=-=-=-=-=-= end BB rank %d "
1329 "=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n", r);
1330 }
1331
1332 VG_(printf)("\n");
1333 VG_(printf)("-----------------------------------------------------------\n");
1334 VG_(printf)("--- END BB Profile ---\n");
1335 VG_(printf)("-----------------------------------------------------------\n");
1336 VG_(printf)("\n");
1337}
1338
1339
1340/*====================================================================*/
nethercote71980f02004-01-24 18:18:54 +00001341/*=== main() ===*/
1342/*====================================================================*/
1343
sewardjfdf91b42005-09-28 00:53:09 +00001344/* When main() is entered, we should be on the following stack, not
1345 the one the kernel gave us. We will run on this stack until
1346 simulation of the root thread is started, at which point a transfer
1347 is made to a dynamically allocated stack. This is for the sake of
1348 uniform overflow detection for all Valgrind threads. This is
1349 marked global even though it isn't, because assembly code below
1350 needs to reference the name. */
1351
1352/*static*/ VgStack VG_(interim_stack);
1353
sewardjf9d2f9b2006-11-17 20:00:57 +00001354/* These are the structures used to hold info for creating the initial
1355 client image.
1356
1357 'iicii' mostly holds important register state present at system
1358 startup (_start_valgrind). valgrind_main() then fills in the rest
1359 of it and passes it to VG_(ii_create_image)(). That produces
1360 'iifii', which is later handed to VG_(ii_finalise_image). */
1361
1362/* In all OS-instantiations, the_iicii has a field .sp_at_startup.
1363 This should get some address inside the stack on which we gained
sewardjfdf91b42005-09-28 00:53:09 +00001364 control (eg, it could be the SP at startup). It doesn't matter
1365 exactly where in the stack it is. This value is passed to the
sewardjf9d2f9b2006-11-17 20:00:57 +00001366 address space manager at startup. On Linux, aspacem then uses it
1367 to identify the initial stack segment and hence the upper end of
1368 the usable address space. */
sewardjfdf91b42005-09-28 00:53:09 +00001369
sewardjf9d2f9b2006-11-17 20:00:57 +00001370static IICreateImageInfo the_iicii;
1371static IIFinaliseImageInfo the_iifii;
1372
sewardjfdf91b42005-09-28 00:53:09 +00001373
sewardj9c606bd2008-09-18 18:12:50 +00001374/* A simple pair structure, used for conveying debuginfo handles to
1375 calls to VG_TRACK(new_mem_startup, ...). */
1376typedef struct { Addr a; ULong ull; } Addr_n_ULong;
1377
1378
sewardj1ae3f3a2005-09-28 10:47:38 +00001379/* --- Forwards decls to do with shutdown --- */
1380
1381static void final_tidyup(ThreadId tid);
1382
1383/* Do everything which needs doing when the last thread exits */
1384static
1385void shutdown_actions_NORETURN( ThreadId tid,
1386 VgSchedReturnCode tids_schedretcode );
1387
1388/* --- end of Forwards decls to do with shutdown --- */
sewardjfdf91b42005-09-28 00:53:09 +00001389
1390
sewardjf9d2f9b2006-11-17 20:00:57 +00001391/* By the time we get to valgrind_main, the_iicii should already have
1392 been filled in with any important details as required by whatever
1393 OS we have been built for.
1394*/
sewardj17c11042006-10-15 01:26:40 +00001395static
sewardjf9d2f9b2006-11-17 20:00:57 +00001396Int valgrind_main ( Int argc, HChar **argv, HChar **envp )
nethercote71980f02004-01-24 18:18:54 +00001397{
sewardj13247ca2005-12-30 22:52:20 +00001398 HChar* toolname = "memcheck"; // default to Memcheck
sewardj13247ca2005-12-30 22:52:20 +00001399 Int need_help = 0; // 0 = no, 1 = --help, 2 = --help-debug
sewardjde764e82007-11-09 23:13:22 +00001400 ThreadId tid_main = VG_INVALID_THREADID;
sewardj738856f2009-07-15 14:48:32 +00001401 Bool logging_to_fd = False;
1402 Char* xml_fname_unexpanded = NULL;
sewardj45f4e7c2005-09-27 19:20:21 +00001403 Int loglevel, i;
nethercote73b526f2004-10-31 18:48:21 +00001404 struct vki_rlimit zero = { 0, 0 };
sewardj9c606bd2008-09-18 18:12:50 +00001405 XArray* addr2dihandle = NULL;
sewardj17c11042006-10-15 01:26:40 +00001406
nethercote71980f02004-01-24 18:18:54 +00001407 //============================================================
nethercote71980f02004-01-24 18:18:54 +00001408 //
sewardj45f4e7c2005-09-27 19:20:21 +00001409 // Nb: startup is complex. Prerequisites are shown at every step.
nethercote71980f02004-01-24 18:18:54 +00001410 // *** Be very careful when messing with the order ***
sewardj45f4e7c2005-09-27 19:20:21 +00001411 //
1412 // The first order of business is to get debug logging, the address
1413 // space manager and the dynamic memory manager up and running.
1414 // Once that's done, we can relax a bit.
1415 //
nethercote71980f02004-01-24 18:18:54 +00001416 //============================================================
sewardj45f4e7c2005-09-27 19:20:21 +00001417
1418 /* This is needed to make VG_(getenv) usable early. */
1419 VG_(client_envp) = (Char**)envp;
nethercote71980f02004-01-24 18:18:54 +00001420
sewardj1cf558c2005-04-25 01:36:56 +00001421 //--------------------------------------------------------------
njnf76d27a2009-05-28 01:53:07 +00001422 // Start up Mach kernel interface, if any
1423 // p: none
1424 //--------------------------------------------------------------
1425# if defined(VGO_darwin)
1426 VG_(mach_init)();
1427# endif
1428
1429 //--------------------------------------------------------------
sewardj1cf558c2005-04-25 01:36:56 +00001430 // Start up the logging mechanism
1431 // p: none
1432 //--------------------------------------------------------------
1433 /* Start the debugging-log system ASAP. First find out how many
njn83df0b62009-02-25 01:01:05 +00001434 "-d"s were specified. This is a pre-scan of the command line. Also
1435 get --profile-heap=yes which is needed by the time we start up dynamic
1436 memory management. */
sewardj1cf558c2005-04-25 01:36:56 +00001437 loglevel = 0;
1438 for (i = 1; i < argc; i++) {
njn83df0b62009-02-25 01:01:05 +00001439 if (argv[i][0] != '-') break;
1440 if VG_STREQ(argv[i], "--") break;
1441 if VG_STREQ(argv[i], "-d") loglevel++;
1442 if VG_BOOL_CLO(argv[i], "--profile-heap", VG_(clo_profile_heap)) {}
sewardj1cf558c2005-04-25 01:36:56 +00001443 }
1444
1445 /* ... and start the debug logger. Now we can safely emit logging
1446 messages all through startup. */
sewardj10759312005-05-30 23:52:47 +00001447 VG_(debugLog_startup)(loglevel, "Stage 2 (main)");
sewardj45f4e7c2005-09-27 19:20:21 +00001448 VG_(debugLog)(1, "main", "Welcome to Valgrind version "
1449 VERSION " debug logging\n");
1450
1451 //--------------------------------------------------------------
sewardj17c11042006-10-15 01:26:40 +00001452 // AIX5 only: register the system call numbers
1453 // p: logging
1454 // p: that the initial few syscall numbers stated in the
1455 // bootblock have been installed (else we can't
1456 // open/read/close).
1457 //--------------------------------------------------------------
1458# if defined(VGO_aix5)
1459 VG_(debugLog)(1, "main", "aix5: registering syscalls ..\n");
1460 { UChar sysent_name[50];
1461 SysRes fd;
1462 Bool ok;
1463 Int n_unregd, sysent_used = 0;
1464 prsysent_t* sysent_hdr;
1465
1466 VG_(sprintf)(sysent_name, "/proc/%d/sysent", VG_(getpid)());
1467 fd = VG_(open)(sysent_name, VKI_O_RDONLY, 0);
1468 if (fd.isError)
1469 VG_(err_config_error)("aix5: can't open /proc/<pid>/sysent");
1470
1471 sysent_used = VG_(read)(fd.res, aix5_sysent_buf, VG_AIX5_SYSENT_SIZE);
1472 if (sysent_used < 0)
1473 VG_(err_config_error)("aix5: error reading /proc/<pid>/sysent");
1474 if (sysent_used >= VG_AIX5_SYSENT_SIZE)
1475 VG_(err_config_error)("aix5: VG_AIX5_SYSENT_SIZE is too low; "
1476 "increase and recompile");
1477 VG_(close)(fd.res);
1478
1479 vg_assert(sysent_used > 0 && sysent_used < VG_AIX5_SYSENT_SIZE);
1480
1481 sysent_hdr = (prsysent_t*)&aix5_sysent_buf[0];
1482
1483 n_unregd = 0;
1484 for (i = 0; i < sysent_hdr->pr_nsyscalls; i++) {
1485 UChar* name = &aix5_sysent_buf[ sysent_hdr
1486 ->pr_syscall[i].pr_nameoff ];
1487 UInt nmbr = sysent_hdr->pr_syscall[i].pr_number;
1488 VG_(debugLog)(3, "main", "aix5: bind syscall %d to \"%s\"\n",
1489 nmbr, name);
1490 ok = VG_(aix5_register_syscall)(nmbr, name);
1491 if (!ok)
1492 n_unregd++;
1493 if (!ok)
1494 VG_(debugLog)(3, "main",
1495 "aix5: bind FAILED: %d to \"%s\"\n",
1496 nmbr, name);
1497 }
1498 VG_(debugLog)(1, "main", "aix5: .. %d syscalls known, %d unknown\n",
1499 sysent_hdr->pr_nsyscalls - n_unregd, n_unregd );
1500 VG_(debugLog)(1, "main", "aix5: __NR_AIX5_FAKE_SIGRETURN = %d\n",
1501 __NR_AIX5_FAKE_SIGRETURN );
1502 }
1503# endif
1504
1505 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001506 // Ensure we're on a plausible stack.
1507 // p: logging
1508 //--------------------------------------------------------------
1509 VG_(debugLog)(1, "main", "Checking current stack is plausible\n");
sewardjfdf91b42005-09-28 00:53:09 +00001510 { HChar* limLo = (HChar*)(&VG_(interim_stack).bytes[0]);
1511 HChar* limHi = limLo + sizeof(VG_(interim_stack));
sewardj45f4e7c2005-09-27 19:20:21 +00001512 HChar* aLocal = (HChar*)&zero; /* any auto local will do */
1513 if (aLocal < limLo || aLocal >= limHi) {
1514 /* something's wrong. Stop. */
1515 VG_(debugLog)(0, "main", "Root stack %p to %p, a local %p\n",
1516 limLo, limHi, aLocal );
1517 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1518 "Initial stack switched failed.\n");
1519 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1520 VG_(exit)(1);
1521 }
1522 }
1523
1524 //--------------------------------------------------------------
1525 // Ensure we have a plausible pointer to the stack on which
1526 // we gained control (not the current stack!)
1527 // p: logging
1528 //--------------------------------------------------------------
1529 VG_(debugLog)(1, "main", "Checking initial stack was noted\n");
sewardjf9d2f9b2006-11-17 20:00:57 +00001530 if (the_iicii.sp_at_startup == 0) {
sewardj45f4e7c2005-09-27 19:20:21 +00001531 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1532 "Initial stack was not noted.\n");
1533 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1534 VG_(exit)(1);
1535 }
1536
1537 //--------------------------------------------------------------
1538 // Start up the address space manager, and determine the
1539 // approximate location of the client's stack
njnea2d6fd2010-07-01 00:20:20 +00001540 // p: logging, plausible-stack
sewardj45f4e7c2005-09-27 19:20:21 +00001541 //--------------------------------------------------------------
1542 VG_(debugLog)(1, "main", "Starting the address space manager\n");
sewardje66f2e02006-12-30 17:45:08 +00001543 vg_assert(VKI_PAGE_SIZE == 4096 || VKI_PAGE_SIZE == 65536);
1544 vg_assert(VKI_MAX_PAGE_SIZE == 4096 || VKI_MAX_PAGE_SIZE == 65536);
1545 vg_assert(VKI_PAGE_SIZE <= VKI_MAX_PAGE_SIZE);
1546 vg_assert(VKI_PAGE_SIZE == (1 << VKI_PAGE_SHIFT));
1547 vg_assert(VKI_MAX_PAGE_SIZE == (1 << VKI_MAX_PAGE_SHIFT));
sewardjf9d2f9b2006-11-17 20:00:57 +00001548 the_iicii.clstack_top = VG_(am_startup)( the_iicii.sp_at_startup );
sewardj45f4e7c2005-09-27 19:20:21 +00001549 VG_(debugLog)(1, "main", "Address space manager is running\n");
1550
1551 //--------------------------------------------------------------
1552 // Start up the dynamic memory manager
1553 // p: address space management
njn83df0b62009-02-25 01:01:05 +00001554 // p: getting --profile-heap
sewardj45f4e7c2005-09-27 19:20:21 +00001555 // In fact m_mallocfree is self-initialising, so there's no
1556 // initialisation call to do. Instead, try a simple malloc/
1557 // free pair right now to check that nothing is broken.
1558 //--------------------------------------------------------------
1559 VG_(debugLog)(1, "main", "Starting the dynamic memory manager\n");
sewardj9c606bd2008-09-18 18:12:50 +00001560 { void* p = VG_(malloc)( "main.vm.1", 12345 );
sewardj45f4e7c2005-09-27 19:20:21 +00001561 if (p) VG_(free)( p );
1562 }
1563 VG_(debugLog)(1, "main", "Dynamic memory manager is running\n");
sewardj1cf558c2005-04-25 01:36:56 +00001564
nethercotef4928da2004-06-15 10:54:40 +00001565 //============================================================
sewardj45f4e7c2005-09-27 19:20:21 +00001566 //
1567 // Dynamic memory management is now available.
1568 //
nethercotef4928da2004-06-15 10:54:40 +00001569 //============================================================
1570
sewardj45f4e7c2005-09-27 19:20:21 +00001571 //--------------------------------------------------------------
sewardjf98e1c02008-10-25 16:22:41 +00001572 // Initialise m_debuginfo
1573 // p: dynamic memory allocation
1574 VG_(debugLog)(1, "main", "Initialise m_debuginfo\n");
1575 VG_(di_initialise)();
1576
1577 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001578 // Look for alternative libdir
1579 { HChar *cp = VG_(getenv)(VALGRIND_LIB);
1580 if (cp != NULL)
1581 VG_(libdir) = cp;
njncde90d32009-07-22 22:41:38 +00001582 VG_(debugLog)(1, "main", "VG_(libdir) = %s\n", VG_(libdir));
sewardj45f4e7c2005-09-27 19:20:21 +00001583 }
1584
1585 //--------------------------------------------------------------
1586 // Extract the launcher name from the environment.
njna842d792009-05-21 01:15:18 +00001587 VG_(debugLog)(1, "main", "Getting launcher's name ...\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001588 VG_(name_of_launcher) = VG_(getenv)(VALGRIND_LAUNCHER);
1589 if (VG_(name_of_launcher) == NULL) {
1590 VG_(printf)("valgrind: You cannot run '%s' directly.\n", argv[0]);
1591 VG_(printf)("valgrind: You should use $prefix/bin/valgrind.\n");
1592 VG_(exit)(1);
1593 }
njna842d792009-05-21 01:15:18 +00001594 VG_(debugLog)(1, "main", "... %s\n", VG_(name_of_launcher));
sewardj45f4e7c2005-09-27 19:20:21 +00001595
1596 //--------------------------------------------------------------
fitzhardingeb50068f2004-02-24 23:42:55 +00001597 // Get the current process datasize rlimit, and set it to zero.
1598 // This prevents any internal uses of brk() from having any effect.
1599 // We remember the old value so we can restore it on exec, so that
1600 // child processes will have a reasonable brk value.
1601 VG_(getrlimit)(VKI_RLIMIT_DATA, &VG_(client_rlimit_data));
1602 zero.rlim_max = VG_(client_rlimit_data).rlim_max;
1603 VG_(setrlimit)(VKI_RLIMIT_DATA, &zero);
thughesc37184f2004-09-11 14:16:57 +00001604
1605 // Get the current process stack rlimit.
1606 VG_(getrlimit)(VKI_RLIMIT_STACK, &VG_(client_rlimit_stack));
1607
sewardje2d1e672005-11-12 23:10:48 +00001608 //--------------------------------------------------------------
1609 // Figure out what sort of CPU we're on, and whether it is
1610 // able to run V.
1611 VG_(debugLog)(1, "main", "Get hardware capabilities ...\n");
1612 { VexArch vex_arch;
1613 VexArchInfo vex_archinfo;
1614 Bool ok = VG_(machine_get_hwcaps)();
1615 if (!ok) {
1616 VG_(printf)("\n");
1617 VG_(printf)("valgrind: fatal error: unsupported CPU.\n");
1618 VG_(printf)(" Supported CPUs are:\n");
1619 VG_(printf)(" * x86 (practically any; Pentium-I or above), "
1620 "AMD Athlon or above)\n");
1621 VG_(printf)(" * AMD Athlon64/Opteron\n");
1622 VG_(printf)(" * PowerPC (most; ppc405 and above)\n");
1623 VG_(printf)("\n");
1624 VG_(exit)(1);
1625 }
1626 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
sewardje3121f32006-01-27 21:23:23 +00001627 VG_(debugLog)(
1628 1, "main", "... arch = %s, hwcaps = %s\n",
1629 LibVEX_ppVexArch ( vex_arch ),
1630 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1631 );
sewardje2d1e672005-11-12 23:10:48 +00001632 }
1633
sewardj198f34f2007-07-09 23:13:07 +00001634 //--------------------------------------------------------------
1635 // Record the working directory at startup
1636 // p: none (Linux), getenv and sys_getpid work (AIX)
1637 VG_(debugLog)(1, "main", "Getting the working directory at startup\n");
1638 { Bool ok = VG_(record_startup_wd)();
1639 if (!ok)
1640 VG_(err_config_error)( "Can't establish current working "
1641 "directory at startup");
1642 }
1643 { Char buf[VKI_PATH_MAX+1];
1644 Bool ok = VG_(get_startup_wd)( buf, sizeof(buf) );
1645 vg_assert(ok);
1646 buf[VKI_PATH_MAX] = 0;
1647 VG_(debugLog)(1, "main", "... %s\n", buf );
1648 }
1649
sewardj45f4e7c2005-09-27 19:20:21 +00001650 //============================================================
1651 // Command line argument handling order:
1652 // * If --help/--help-debug are present, show usage message
1653 // (including the tool-specific usage)
1654 // * (If no --tool option given, default to Memcheck)
1655 // * Then, if client is missing, abort with error msg
1656 // * Then, if any cmdline args are bad, abort with error msg
1657 //============================================================
1658
1659 //--------------------------------------------------------------
1660 // Split up argv into: C args, V args, V extra args, and exename.
1661 // p: dynamic memory allocation
1662 //--------------------------------------------------------------
1663 VG_(debugLog)(1, "main", "Split up command line\n");
1664 VG_(split_up_argv)( argc, argv );
sewardj14c7cc52007-02-25 15:08:24 +00001665 vg_assert( VG_(args_for_valgrind) );
1666 vg_assert( VG_(args_for_client) );
sewardj45f4e7c2005-09-27 19:20:21 +00001667 if (0) {
sewardj14c7cc52007-02-25 15:08:24 +00001668 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++)
1669 VG_(printf)(
1670 "varg %s\n",
1671 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1672 );
sewardj45f4e7c2005-09-27 19:20:21 +00001673 VG_(printf)(" exe %s\n", VG_(args_the_exename));
sewardj14c7cc52007-02-25 15:08:24 +00001674 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++)
1675 VG_(printf)(
1676 "carg %s\n",
1677 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1678 );
nethercote71980f02004-01-24 18:18:54 +00001679 }
1680
sewardj948a6fc2007-03-19 18:38:55 +00001681# if defined(VGO_aix5)
1682 /* Tolerate ptraced-based launchers. They can't run 'no program'
1683 if the user types "valgrind --help", so they run a do-nothing
1684 program $prefix/bin/no_op_client_for_valgrind, and we catch that
1685 here and turn it the exe name back into NULL. Then --help,
1686 --version etc work as they should. */
1687 if (VG_(args_the_exename)
1688 && VG_(strstr)( VG_(args_the_exename), "/no_op_client_for_valgrind" )) {
1689 VG_(args_the_exename) = NULL;
1690 }
1691# endif
1692
nethercote71980f02004-01-24 18:18:54 +00001693 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001694 // Extract tool name and whether help has been requested.
1695 // Note we can't print the help message yet, even if requested,
1696 // because the tool has not been initialised.
1697 // p: split_up_argv [for VG_(args_for_valgrind)]
nethercote71980f02004-01-24 18:18:54 +00001698 //--------------------------------------------------------------
sewardj95d86c02007-12-18 01:49:23 +00001699 VG_(debugLog)(1, "main",
1700 "(early_) Process Valgrind's command line options\n");
1701 early_process_cmd_line_options(&need_help, &toolname);
nethercote71980f02004-01-24 18:18:54 +00001702
sewardj45f4e7c2005-09-27 19:20:21 +00001703 // Set default vex control params
1704 LibVEX_default_VexControl(& VG_(clo_vex_control));
nethercote71980f02004-01-24 18:18:54 +00001705
1706 //--------------------------------------------------------------
1707 // Load client executable, finding in $PATH if necessary
njn83df0b62009-02-25 01:01:05 +00001708 // p: early_process_cmd_line_options() [for 'exec', 'need_help',
1709 // clo_max_stackframe,
1710 // clo_main_stacksize]
sewardj95d86c02007-12-18 01:49:23 +00001711 // p: layout_remaining_space [so there's space]
sewardj17c11042006-10-15 01:26:40 +00001712 //
nethercote71980f02004-01-24 18:18:54 +00001713 // Set up client's environment
sewardj95d86c02007-12-18 01:49:23 +00001714 // p: set-libdir [for VG_(libdir)]
1715 // p: early_process_cmd_line_options [for toolname]
sewardj17c11042006-10-15 01:26:40 +00001716 //
nethercote5ee67ca2004-06-22 14:00:09 +00001717 // Setup client stack, eip, and VG_(client_arg[cv])
nethercote71980f02004-01-24 18:18:54 +00001718 // p: load_client() [for 'info']
1719 // p: fix_environment() [for 'env']
sewardj17c11042006-10-15 01:26:40 +00001720 //
sewardj45f4e7c2005-09-27 19:20:21 +00001721 // Setup client data (brk) segment. Initially a 1-page segment
1722 // which abuts a shrinkable reservation.
1723 // p: load_client() [for 'info' and hence VG_(brk_base)]
sewardjf9d2f9b2006-11-17 20:00:57 +00001724 //
1725 // p: _start_in_C (for zeroing out the_iicii and putting some
1726 // initial values into it)
sewardj45f4e7c2005-09-27 19:20:21 +00001727 //--------------------------------------------------------------
sewardj17c11042006-10-15 01:26:40 +00001728 if (!need_help) {
sewardjf9d2f9b2006-11-17 20:00:57 +00001729 VG_(debugLog)(1, "main", "Create initial image\n");
1730
njnf76d27a2009-05-28 01:53:07 +00001731# if defined(VGO_linux) || defined(VGO_darwin)
sewardjf9d2f9b2006-11-17 20:00:57 +00001732 the_iicii.argv = argv;
1733 the_iicii.envp = envp;
1734 the_iicii.toolname = toolname;
1735# elif defined(VGO_aix5)
1736 /* the_iicii.intregs37 already set up */
1737 /* the_iicii.bootblock already set up */
1738 /* the_iicii.adler32_exp already set up */
1739 /* the_iicii.sp_at_startup is irrelevant */
1740 /* the_iicii.clstack_top is irrelevant */
1741 the_iicii.toolname = toolname;
1742# else
njna842d792009-05-21 01:15:18 +00001743# error "Unknown platform"
sewardjf9d2f9b2006-11-17 20:00:57 +00001744# endif
1745
sewardjdc2f79e2007-12-22 14:14:04 +00001746 /* NOTE: this call reads VG_(clo_main_stacksize). */
sewardjf9d2f9b2006-11-17 20:00:57 +00001747 the_iifii = VG_(ii_create_image)( the_iicii );
1748
sewardj17c11042006-10-15 01:26:40 +00001749# if defined(VGO_aix5)
sewardj17c11042006-10-15 01:26:40 +00001750 /* Tell aspacem where the initial client stack is, so that it
1751 can later produce a faked-up NSegment in response to
1752 VG_(am_find_nsegment) for that address range, if asked. */
sewardjdc2f79e2007-12-22 14:14:04 +00001753 /* NOTE: this call reads VG_(clo_main_stacksize). */
sewardjf9d2f9b2006-11-17 20:00:57 +00001754 VG_(am_aix5_set_initial_client_sp)( the_iifii.initial_client_SP );
1755 /* Now have a look at said fake segment, so we can find out
1756 the size of it. */
1757 { SizeT sz;
1758 NSegment const* seg
1759 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
1760 vg_assert(seg);
1761 sz = seg->end - seg->start + 1;
sewardjc9d33832007-12-22 14:12:42 +00001762 vg_assert(sz >= 0 && sz <= (256+1)*1024*1024); /* stay sane */
sewardjf9d2f9b2006-11-17 20:00:57 +00001763 the_iifii.clstack_max_size = sz;
1764 }
sewardj17c11042006-10-15 01:26:40 +00001765# endif
sewardj45f4e7c2005-09-27 19:20:21 +00001766 }
nethercote71980f02004-01-24 18:18:54 +00001767
1768 //==============================================================
sewardj45f4e7c2005-09-27 19:20:21 +00001769 //
1770 // Finished loading/setting up the client address space.
1771 //
nethercote71980f02004-01-24 18:18:54 +00001772 //==============================================================
1773
1774 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00001775 // setup file descriptors
1776 // p: n/a
1777 //--------------------------------------------------------------
sewardj1fbc1a52005-04-25 02:05:54 +00001778 VG_(debugLog)(1, "main", "Setup file descriptors\n");
nethercote71980f02004-01-24 18:18:54 +00001779 setup_file_descriptors();
1780
1781 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001782 // create the fake /proc/<pid>/cmdline file and then unlink it,
1783 // but hold onto the fd, so we can hand it out to the client
1784 // when it tries to open /proc/<pid>/cmdline for itself.
1785 // p: setup file descriptors
nethercotec314eba2004-07-15 12:59:41 +00001786 //--------------------------------------------------------------
bart9b533f82009-08-25 20:15:41 +00001787#if !defined(VGO_linux)
1788 // client shouldn't be using /proc!
1789 VG_(cl_cmdline_fd) = -1;
1790#else
1791 if (!need_help) {
1792 HChar buf[50], buf2[50+64];
1793 HChar nul[1];
1794 Int fd, r;
barta3054f52010-06-14 18:12:56 +00001795 const HChar* exename;
nethercotec314eba2004-07-15 12:59:41 +00001796
bart9b533f82009-08-25 20:15:41 +00001797 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/cmdline\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001798
bart9b533f82009-08-25 20:15:41 +00001799 VG_(sprintf)(buf, "proc_%d_cmdline", VG_(getpid)());
1800 fd = VG_(mkstemp)( buf, buf2 );
1801 if (fd == -1)
1802 VG_(err_config_error)("Can't create client cmdline file in /tmp.");
sewardj45f4e7c2005-09-27 19:20:21 +00001803
bart9b533f82009-08-25 20:15:41 +00001804 nul[0] = 0;
1805 exename = VG_(args_the_exename) ? VG_(args_the_exename)
1806 : "unknown_exename";
1807 VG_(write)(fd, VG_(args_the_exename),
1808 VG_(strlen)( VG_(args_the_exename) ));
1809 VG_(write)(fd, nul, 1);
1810
1811 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1812 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i );
1813 VG_(write)(fd, arg, VG_(strlen)( arg ));
sewardj45f4e7c2005-09-27 19:20:21 +00001814 VG_(write)(fd, nul, 1);
1815 }
bart9b533f82009-08-25 20:15:41 +00001816
1817 /* Don't bother to seek the file back to the start; instead do
1818 it every time a copy of it is given out (by PRE(sys_open)).
1819 That is probably more robust across fork() etc. */
1820
1821 /* Now delete it, but hang on to the fd. */
1822 r = VG_(unlink)( buf2 );
1823 if (r)
1824 VG_(err_config_error)("Can't delete client cmdline file in /tmp.");
1825
1826 VG_(cl_cmdline_fd) = fd;
sewardj45f4e7c2005-09-27 19:20:21 +00001827 }
bart9b533f82009-08-25 20:15:41 +00001828#endif
nethercotec314eba2004-07-15 12:59:41 +00001829
1830 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001831 // Init tool part 1: pre_clo_init
nethercotec314eba2004-07-15 12:59:41 +00001832 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
nethercotec314eba2004-07-15 12:59:41 +00001833 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
nethercote71980f02004-01-24 18:18:54 +00001834 //--------------------------------------------------------------
sewardj7cf4e6b2008-05-01 20:24:26 +00001835 VG_(debugLog)(1, "main", "Initialise the tool part 1 (pre_clo_init)\n");
njn08ce7b32009-02-27 03:38:28 +00001836 VG_(tl_pre_clo_init)();
nethercote71980f02004-01-24 18:18:54 +00001837
sewardj45f4e7c2005-09-27 19:20:21 +00001838 //--------------------------------------------------------------
nethercotef4928da2004-06-15 10:54:40 +00001839 // If --tool and --help/--help-debug was given, now give the core+tool
1840 // help message
sewardj95d86c02007-12-18 01:49:23 +00001841 // p: early_process_cmd_line_options() [for 'need_help']
1842 // p: tl_pre_clo_init [for 'VG_(tdict).usage']
sewardj45f4e7c2005-09-27 19:20:21 +00001843 //--------------------------------------------------------------
1844 VG_(debugLog)(1, "main", "Print help and quit, if requested\n");
nethercotef4928da2004-06-15 10:54:40 +00001845 if (need_help) {
njncce38e62010-07-06 04:25:12 +00001846 usage_NORETURN(/*--help-debug?*/need_help >= 2);
nethercotef4928da2004-06-15 10:54:40 +00001847 }
nethercotec314eba2004-07-15 12:59:41 +00001848
sewardj45f4e7c2005-09-27 19:20:21 +00001849 //--------------------------------------------------------------
1850 // Process command line options to Valgrind + tool
1851 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1852 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1853 //--------------------------------------------------------------
sewardj95d86c02007-12-18 01:49:23 +00001854 VG_(debugLog)(1, "main",
1855 "(main_) Process Valgrind's command line options, "
1856 "setup logging\n");
sewardj738856f2009-07-15 14:48:32 +00001857 main_process_cmd_line_options ( &logging_to_fd, &xml_fname_unexpanded,
1858 toolname );
sewardj45f4e7c2005-09-27 19:20:21 +00001859
1860 //--------------------------------------------------------------
sewardj592ae092005-11-08 19:01:44 +00001861 // Zeroise the millisecond counter by doing a first read of it.
1862 // p: none
1863 //--------------------------------------------------------------
1864 (void) VG_(read_millisecond_timer)();
1865
1866 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001867 // Print the preamble
1868 // p: tl_pre_clo_init [for 'VG_(details).name' and friends]
sewardj738856f2009-07-15 14:48:32 +00001869 // p: main_process_cmd_line_options()
1870 // [for VG_(clo_verbosity), VG_(clo_xml),
1871 // logging_to_fd, xml_fname_unexpanded]
sewardj45f4e7c2005-09-27 19:20:21 +00001872 //--------------------------------------------------------------
1873 VG_(debugLog)(1, "main", "Print the preamble...\n");
sewardj738856f2009-07-15 14:48:32 +00001874 print_preamble(logging_to_fd, xml_fname_unexpanded, toolname);
sewardj45f4e7c2005-09-27 19:20:21 +00001875 VG_(debugLog)(1, "main", "...finished the preamble\n");
1876
1877 //--------------------------------------------------------------
1878 // Init tool part 2: post_clo_init
1879 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1880 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1881 // p: print_preamble() [so any warnings printed in post_clo_init
1882 // are shown after the preamble]
1883 //--------------------------------------------------------------
1884 VG_(debugLog)(1, "main", "Initialise the tool part 2 (post_clo_init)\n");
njn51d827b2005-05-09 01:02:08 +00001885 VG_TDICT_CALL(tool_post_clo_init);
sewardj7cf4e6b2008-05-01 20:24:26 +00001886 {
1887 /* The tool's "needs" will by now be finalised, since it has no
1888 further opportunity to specify them. So now sanity check
1889 them. */
1890 Char* s;
1891 Bool ok;
1892 ok = VG_(sanity_check_needs)( &s );
1893 if (!ok) {
1894 VG_(tool_panic)(s);
1895 }
1896 }
nethercotef4928da2004-06-15 10:54:40 +00001897
1898 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001899 // Initialise translation table and translation cache
1900 // p: aspacem [??]
1901 // p: tl_pre_clo_init [for 'VG_(details).avg_translation_sizeB']
nethercote71980f02004-01-24 18:18:54 +00001902 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001903 VG_(debugLog)(1, "main", "Initialise TT/TC\n");
1904 VG_(init_tt_tc)();
sewardjb5f6f512005-03-10 23:59:00 +00001905
sewardj45f4e7c2005-09-27 19:20:21 +00001906 //--------------------------------------------------------------
1907 // Initialise the redirect table.
1908 // p: init_tt_tc [so it can call VG_(search_transtab) safely]
1909 // p: aspacem [so can change ownership of sysinfo pages]
1910 //--------------------------------------------------------------
1911 VG_(debugLog)(1, "main", "Initialise redirects\n");
sewardj0ec07f32006-01-12 12:32:32 +00001912 VG_(redir_initialise)();
nethercote71980f02004-01-24 18:18:54 +00001913
1914 //--------------------------------------------------------------
1915 // Allow GDB attach
sewardj95d86c02007-12-18 01:49:23 +00001916 // p: main_process_cmd_line_options() [for VG_(clo_wait_for_gdb)]
nethercote71980f02004-01-24 18:18:54 +00001917 //--------------------------------------------------------------
1918 /* Hook to delay things long enough so we can get the pid and
1919 attach GDB in another shell. */
1920 if (VG_(clo_wait_for_gdb)) {
sewardj95611ff2007-02-16 13:57:07 +00001921 Long iters;
1922 volatile Long q;
sewardj1fbc1a52005-04-25 02:05:54 +00001923 VG_(debugLog)(1, "main", "Wait for GDB\n");
sewardj93ab8572005-02-06 14:10:40 +00001924 VG_(printf)("pid=%d, entering delay loop\n", VG_(getpid)());
sewardj8211a572005-06-23 21:37:47 +00001925
1926# if defined(VGP_x86_linux)
1927 iters = 5;
sewardj2c48c7b2005-11-29 13:05:56 +00001928# elif defined(VGP_amd64_linux) || defined(VGP_ppc64_linux)
sewardj8211a572005-06-23 21:37:47 +00001929 iters = 10;
1930# elif defined(VGP_ppc32_linux)
sewardjd714d2e2005-07-08 18:24:04 +00001931 iters = 5;
sewardj59570ff2010-01-01 11:59:33 +00001932# elif defined(VGP_arm_linux)
1933 iters = 1;
sewardj17c11042006-10-15 01:26:40 +00001934# elif defined(VGP_ppc32_aix5) || defined(VGP_ppc64_aix5)
1935 iters = 4;
njnf76d27a2009-05-28 01:53:07 +00001936# elif defined(VGO_darwin)
1937 iters = 3;
sewardj8211a572005-06-23 21:37:47 +00001938# else
sewardj17c11042006-10-15 01:26:40 +00001939# error "Unknown plat"
sewardj8211a572005-06-23 21:37:47 +00001940# endif
1941
1942 iters *= 1000*1000*1000;
1943 for (q = 0; q < iters; q++)
1944 ;
nethercote71980f02004-01-24 18:18:54 +00001945 }
1946
sewardjb5d320c2005-03-13 18:57:15 +00001947 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00001948 // Search for file descriptors that are inherited from our parent
sewardj95d86c02007-12-18 01:49:23 +00001949 // p: main_process_cmd_line_options [for VG_(clo_track_fds)]
nethercote71980f02004-01-24 18:18:54 +00001950 //--------------------------------------------------------------
sewardj1fbc1a52005-04-25 02:05:54 +00001951 if (VG_(clo_track_fds)) {
1952 VG_(debugLog)(1, "main", "Init preopened fds\n");
nethercote71980f02004-01-24 18:18:54 +00001953 VG_(init_preopened_fds)();
sewardj1fbc1a52005-04-25 02:05:54 +00001954 }
nethercote71980f02004-01-24 18:18:54 +00001955
1956 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001957 // Load debug info for the existing segments.
1958 // p: setup_code_redirect_table [so that redirs can be recorded]
1959 // p: mallocfree
1960 // p: probably: setup fds and process CLOs, so that logging works
sewardjf98e1c02008-10-25 16:22:41 +00001961 // p: initialise m_debuginfo
sewardj9c606bd2008-09-18 18:12:50 +00001962 //
1963 // While doing this, make a note of the debuginfo-handles that
1964 // come back from VG_(di_notify_mmap)/VG_(di_aix5_notify_segchange).
1965 // Later, in "Tell the tool about the initial client memory permissions"
1966 // (just below) we can then hand these handles off to the tool in
1967 // calls to VG_TRACK(new_mem_startup, ...). This gives the tool the
1968 // opportunity to make further queries to m_debuginfo before the
1969 // client is started, if it wants. We put this information into an
1970 // XArray, each handle along with the associated segment start address,
1971 // and search the XArray for the handles later, when calling
1972 // VG_TRACK(new_mem_startup, ...).
sewardj45f4e7c2005-09-27 19:20:21 +00001973 //--------------------------------------------------------------
1974 VG_(debugLog)(1, "main", "Load initial debug info\n");
sewardj9c606bd2008-09-18 18:12:50 +00001975
1976 tl_assert(!addr2dihandle);
1977 addr2dihandle = VG_(newXA)( VG_(malloc), "main.vm.2",
1978 VG_(free), sizeof(Addr_n_ULong) );
1979 tl_assert(addr2dihandle);
1980
sewardj17c11042006-10-15 01:26:40 +00001981# if defined(VGO_linux)
sewardj45f4e7c2005-09-27 19:20:21 +00001982 { Addr* seg_starts;
1983 Int n_seg_starts;
sewardj9c606bd2008-09-18 18:12:50 +00001984 Addr_n_ULong anu;
sewardj45f4e7c2005-09-27 19:20:21 +00001985
njnac1e0332009-05-08 00:39:31 +00001986 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
sewardj17c11042006-10-15 01:26:40 +00001987 vg_assert(seg_starts && n_seg_starts >= 0);
sewardj45f4e7c2005-09-27 19:20:21 +00001988
sewardjf72cced2005-11-08 00:45:47 +00001989 /* show them all to the debug info reader. allow_SkFileV has to
1990 be True here so that we read info from the valgrind executable
1991 itself. */
sewardj9c606bd2008-09-18 18:12:50 +00001992 for (i = 0; i < n_seg_starts; i++) {
1993 anu.ull = VG_(di_notify_mmap)( seg_starts[i], True/*allow_SkFileV*/ );
1994 /* anu.ull holds the debuginfo handle returned by di_notify_mmap,
1995 if any. */
1996 if (anu.ull > 0) {
1997 anu.a = seg_starts[i];
1998 VG_(addToXA)( addr2dihandle, &anu );
1999 }
2000 }
sewardj45f4e7c2005-09-27 19:20:21 +00002001
2002 VG_(free)( seg_starts );
2003 }
sewardj17c11042006-10-15 01:26:40 +00002004# elif defined(VGO_aix5)
2005 { AixCodeSegChange* changes;
2006 Int changes_size, changes_used;
sewardj9c606bd2008-09-18 18:12:50 +00002007 Addr_n_ULong anu;
sewardj17c11042006-10-15 01:26:40 +00002008
2009 /* Find out how many AixCodeSegChange records we will need,
2010 and acquire them. */
2011 changes_size = VG_(am_aix5_reread_procmap_howmany_directives)();
sewardj9c606bd2008-09-18 18:12:50 +00002012 changes = VG_(malloc)("main.vm.3", changes_size * sizeof(AixCodeSegChange));
sewardj17c11042006-10-15 01:26:40 +00002013 vg_assert(changes);
2014
2015 /* Now re-read /proc/<pid>/map and acquire a change set */
2016 VG_(am_aix5_reread_procmap)( changes, &changes_used );
2017 vg_assert(changes_used >= 0 && changes_used <= changes_size);
2018
2019 /* And notify m_debuginfo of the changes. */
sewardj9c606bd2008-09-18 18:12:50 +00002020 for (i = 0; i < changes_used; i++) {
2021 anu.ull = VG_(di_aix5_notify_segchange)(
2022 changes[i].code_start,
2023 changes[i].code_len,
2024 changes[i].data_start,
2025 changes[i].data_len,
2026 changes[i].file_name,
2027 changes[i].mem_name,
2028 changes[i].is_mainexe,
2029 changes[i].acquire
2030 );
2031 if (anu.ull > 0) {
2032 tl_assert(changes[i].acquire);
2033 anu.a = changes[i].code_start; /* is this correct? */
2034 VG_(addToXA)( addr2dihandle, &anu );
2035 }
2036 }
sewardj17c11042006-10-15 01:26:40 +00002037
2038 VG_(free)(changes);
2039 }
njnf76d27a2009-05-28 01:53:07 +00002040# elif defined(VGO_darwin)
2041 { Addr* seg_starts;
2042 Int n_seg_starts;
2043 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
2044 vg_assert(seg_starts && n_seg_starts >= 0);
2045
2046 /* show them all to the debug info reader.
2047 Don't read from V segments (unlike Linux) */
2048 // GrP fixme really?
2049 for (i = 0; i < n_seg_starts; i++)
2050 VG_(di_notify_mmap)( seg_starts[i], False/*don't allow_SkFileV*/ );
2051
2052 VG_(free)( seg_starts );
2053 }
sewardj17c11042006-10-15 01:26:40 +00002054# else
2055# error Unknown OS
2056# endif
sewardj45f4e7c2005-09-27 19:20:21 +00002057
2058 //--------------------------------------------------------------
2059 // Tell aspacem of ownership change of the asm helpers, so that
2060 // m_translate allows them to be translated. However, only do this
2061 // after the initial debug info read, since making a hole in the
2062 // address range for the stage2 binary confuses the debug info reader.
2063 // p: aspacem
2064 //--------------------------------------------------------------
2065 { Bool change_ownership_v_c_OK;
sewardj1a85f4f2006-01-12 21:15:35 +00002066 Addr co_start = VG_PGROUNDDN( (Addr)&VG_(trampoline_stuff_start) );
2067 Addr co_endPlus = VG_PGROUNDUP( (Addr)&VG_(trampoline_stuff_end) );
sewardj45f4e7c2005-09-27 19:20:21 +00002068 VG_(debugLog)(1,"redir",
2069 "transfer ownership V -> C of 0x%llx .. 0x%llx\n",
2070 (ULong)co_start, (ULong)co_endPlus-1 );
2071
2072 change_ownership_v_c_OK
2073 = VG_(am_change_ownership_v_to_c)( co_start, co_endPlus - co_start );
2074 vg_assert(change_ownership_v_c_OK);
2075 }
2076
2077 //--------------------------------------------------------------
sewardjde764e82007-11-09 23:13:22 +00002078 // Initialise the scheduler (phase 1) [generates tid_main]
2079 // p: none, afaics
2080 //--------------------------------------------------------------
2081 VG_(debugLog)(1, "main", "Initialise scheduler (phase 1)\n");
2082 tid_main = VG_(scheduler_init_phase1)();
2083 vg_assert(tid_main >= 0 && tid_main < VG_N_THREADS
2084 && tid_main != VG_INVALID_THREADID);
2085 /* Tell the tool about tid_main */
2086 VG_TRACK( pre_thread_ll_create, VG_INVALID_THREADID, tid_main );
2087
2088 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00002089 // Tell the tool about the initial client memory permissions
2090 // p: aspacem
2091 // p: mallocfree
2092 // p: setup_client_stack
2093 // p: setup_client_dataseg
sewardj9c606bd2008-09-18 18:12:50 +00002094 //
2095 // For each segment we tell the client about, look up in
2096 // addr2dihandle as created above, to see if there's a debuginfo
2097 // handle associated with the segment, that we can hand along
2098 // to the tool, to be helpful.
sewardj45f4e7c2005-09-27 19:20:21 +00002099 //--------------------------------------------------------------
2100 VG_(debugLog)(1, "main", "Tell tool about initial permissions\n");
2101 { Addr* seg_starts;
2102 Int n_seg_starts;
sewardj45f4e7c2005-09-27 19:20:21 +00002103
sewardj9c606bd2008-09-18 18:12:50 +00002104 tl_assert(addr2dihandle);
2105
tom7c1a19a2008-01-02 10:13:04 +00002106 /* Mark the main thread as running while we tell the tool about
2107 the client memory so that the tool can associate that memory
2108 with the main thread. */
2109 tl_assert(VG_(running_tid) == VG_INVALID_THREADID);
2110 VG_(running_tid) = tid_main;
2111
njnac1e0332009-05-08 00:39:31 +00002112 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
sewardj17c11042006-10-15 01:26:40 +00002113 vg_assert(seg_starts && n_seg_starts >= 0);
sewardj45f4e7c2005-09-27 19:20:21 +00002114
2115 /* show interesting ones to the tool */
2116 for (i = 0; i < n_seg_starts; i++) {
sewardj9c606bd2008-09-18 18:12:50 +00002117 Word j, n;
sewardj12ab7652006-10-17 02:10:42 +00002118 NSegment const* seg
sewardj17c11042006-10-15 01:26:40 +00002119 = VG_(am_find_nsegment)( seg_starts[i] );
sewardj45f4e7c2005-09-27 19:20:21 +00002120 vg_assert(seg);
2121 if (seg->kind == SkFileC || seg->kind == SkAnonC) {
sewardjc6d86a32009-01-31 15:08:08 +00002122 /* This next assertion is tricky. If it is placed
2123 immediately before this 'if', it very occasionally fails.
2124 Why? Because previous iterations of the loop may have
2125 caused tools (via the new_mem_startup calls) to do
2126 dynamic memory allocation, and that may affect the mapped
2127 segments; in particular it may cause segment merging to
2128 happen. Hence we cannot assume that seg_starts[i], which
2129 reflects the state of the world before we started this
2130 loop, is the same as seg->start, as the latter reflects
2131 the state of the world (viz, mappings) at this particular
2132 iteration of the loop.
2133
2134 Why does moving it inside the 'if' make it safe? Because
2135 any dynamic memory allocation done by the tools will
2136 affect only the state of Valgrind-owned segments, not of
2137 Client-owned segments. And the 'if' guards against that
2138 -- we only get in here for Client-owned segments.
2139
2140 In other words: the loop may change the state of
2141 Valgrind-owned segments as it proceeds. But it should
2142 not cause the Client-owned segments to change. */
2143 vg_assert(seg->start == seg_starts[i]);
sewardj45f4e7c2005-09-27 19:20:21 +00002144 VG_(debugLog)(2, "main",
2145 "tell tool about %010lx-%010lx %c%c%c\n",
2146 seg->start, seg->end,
2147 seg->hasR ? 'r' : '-',
2148 seg->hasW ? 'w' : '-',
2149 seg->hasX ? 'x' : '-' );
sewardj9c606bd2008-09-18 18:12:50 +00002150 /* search addr2dihandle to see if we have an entry
2151 matching seg->start. */
2152 n = VG_(sizeXA)( addr2dihandle );
2153 for (j = 0; j < n; j++) {
2154 Addr_n_ULong* anl = VG_(indexXA)( addr2dihandle, j );
2155 if (anl->a == seg->start) {
2156 tl_assert(anl->ull > 0); /* check it's a valid handle */
2157 break;
2158 }
2159 }
2160 vg_assert(j >= 0 && j <= n);
sewardj45f4e7c2005-09-27 19:20:21 +00002161 VG_TRACK( new_mem_startup, seg->start, seg->end+1-seg->start,
sewardj9c606bd2008-09-18 18:12:50 +00002162 seg->hasR, seg->hasW, seg->hasX,
2163 /* and the retrieved debuginfo handle, if any */
2164 j < n
2165 ? ((Addr_n_ULong*)VG_(indexXA)( addr2dihandle, j ))->ull
2166 : 0 );
sewardj45f4e7c2005-09-27 19:20:21 +00002167 }
2168 }
2169
2170 VG_(free)( seg_starts );
sewardj9c606bd2008-09-18 18:12:50 +00002171 VG_(deleteXA)( addr2dihandle );
sewardj45f4e7c2005-09-27 19:20:21 +00002172
2173 /* Also do the initial stack permissions. */
barte05b3a42010-09-07 16:32:53 +00002174 {
2175 SSizeT inaccessible_len;
2176 NSegment const* seg
sewardjf9d2f9b2006-11-17 20:00:57 +00002177 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
sewardj17c11042006-10-15 01:26:40 +00002178 vg_assert(seg);
2179 vg_assert(seg->kind == SkAnonC);
sewardjf9d2f9b2006-11-17 20:00:57 +00002180 vg_assert(the_iifii.initial_client_SP >= seg->start);
2181 vg_assert(the_iifii.initial_client_SP <= seg->end);
sewardj17c11042006-10-15 01:26:40 +00002182# if defined(VGO_aix5)
2183 VG_(clstk_base) = seg->start;
2184 VG_(clstk_end) = seg->end;
2185# endif
sewardj45f4e7c2005-09-27 19:20:21 +00002186
sewardj17c11042006-10-15 01:26:40 +00002187 /* Stuff below the initial SP is unaddressable. Take into
2188 account any ABI-mandated space below the stack pointer that
2189 is required (VG_STACK_REDZONE_SZB). setup_client_stack()
2190 will have allocated an extra page if a red zone is required,
2191 to be on the safe side. */
barte05b3a42010-09-07 16:32:53 +00002192 inaccessible_len = the_iifii.initial_client_SP - VG_STACK_REDZONE_SZB
2193 - seg->start;
2194 vg_assert(inaccessible_len >= 0);
2195 if (inaccessible_len > 0)
2196 VG_TRACK( die_mem_stack,
2197 seg->start,
2198 inaccessible_len );
sewardj17c11042006-10-15 01:26:40 +00002199 VG_(debugLog)(2, "main", "mark stack inaccessible %010lx-%010lx\n",
2200 seg->start,
sewardjf9d2f9b2006-11-17 20:00:57 +00002201 the_iifii.initial_client_SP-1 - VG_STACK_REDZONE_SZB);
sewardj17c11042006-10-15 01:26:40 +00002202 }
sewardj45f4e7c2005-09-27 19:20:21 +00002203
2204 /* Also the assembly helpers. */
2205 VG_TRACK( new_mem_startup,
2206 (Addr)&VG_(trampoline_stuff_start),
sewardjc6527d62006-02-13 17:54:31 +00002207 (Addr)&VG_(trampoline_stuff_end)
2208 - (Addr)&VG_(trampoline_stuff_start),
sewardj45f4e7c2005-09-27 19:20:21 +00002209 False, /* readable? */
2210 False, /* writable? */
sewardj9c606bd2008-09-18 18:12:50 +00002211 True /* executable? */,
2212 0 /* di_handle: no associated debug info */ );
tom7c1a19a2008-01-02 10:13:04 +00002213
2214 /* Clear the running thread indicator */
2215 VG_(running_tid) = VG_INVALID_THREADID;
2216 tl_assert(VG_(running_tid) == VG_INVALID_THREADID);
sewardj45f4e7c2005-09-27 19:20:21 +00002217 }
2218
2219 //--------------------------------------------------------------
sewardjde764e82007-11-09 23:13:22 +00002220 // Initialise the scheduler (phase 2)
2221 // p: Initialise the scheduler (phase 1) [for tid_main]
nethercote71980f02004-01-24 18:18:54 +00002222 // p: setup_file_descriptors() [else VG_(safe_fd)() breaks]
sewardj45f4e7c2005-09-27 19:20:21 +00002223 // p: setup_client_stack
nethercote71980f02004-01-24 18:18:54 +00002224 //--------------------------------------------------------------
sewardjde764e82007-11-09 23:13:22 +00002225 VG_(debugLog)(1, "main", "Initialise scheduler (phase 2)\n");
sewardj12ab7652006-10-17 02:10:42 +00002226 { NSegment const* seg
sewardjf9d2f9b2006-11-17 20:00:57 +00002227 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
sewardj45f4e7c2005-09-27 19:20:21 +00002228 vg_assert(seg);
2229 vg_assert(seg->kind == SkAnonC);
sewardjf9d2f9b2006-11-17 20:00:57 +00002230 vg_assert(the_iifii.initial_client_SP >= seg->start);
2231 vg_assert(the_iifii.initial_client_SP <= seg->end);
sewardjde764e82007-11-09 23:13:22 +00002232 VG_(scheduler_init_phase2)( tid_main,
2233 seg->end, the_iifii.clstack_max_size );
sewardj45f4e7c2005-09-27 19:20:21 +00002234 }
nethercote71980f02004-01-24 18:18:54 +00002235
2236 //--------------------------------------------------------------
sewardj17c11042006-10-15 01:26:40 +00002237 // Set up state for the root thread
sewardjb5f6f512005-03-10 23:59:00 +00002238 // p: ?
sewardj17c11042006-10-15 01:26:40 +00002239 // setup_scheduler() [for sched-specific thread 1 stuff]
sewardjf9d2f9b2006-11-17 20:00:57 +00002240 // VG_(ii_create_image) [for 'the_iicii' initial info]
sewardj2a99cf62004-11-24 10:44:19 +00002241 //--------------------------------------------------------------
sewardjf9d2f9b2006-11-17 20:00:57 +00002242 VG_(debugLog)(1, "main", "Finalise initial image\n");
2243 VG_(ii_finalise_image)( the_iifii );
njnea4b28c2004-11-30 16:04:58 +00002244
sewardj2a99cf62004-11-24 10:44:19 +00002245 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00002246 // Initialise the signal handling subsystem
sewardjb5f6f512005-03-10 23:59:00 +00002247 // p: n/a
nethercote71980f02004-01-24 18:18:54 +00002248 //--------------------------------------------------------------
2249 // Nb: temporarily parks the saved blocking-mask in saved_sigmask.
sewardj1fbc1a52005-04-25 02:05:54 +00002250 VG_(debugLog)(1, "main", "Initialise signal management\n");
njncda2f0f2009-05-18 02:12:08 +00002251 /* Check that the kernel-interface signal definitions look sane */
2252 VG_(vki_do_initial_consistency_checks)();
2253 /* .. and go on to use them. */
nethercote71980f02004-01-24 18:18:54 +00002254 VG_(sigstartup_actions)();
2255
2256 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00002257 // Read suppression file
sewardj95d86c02007-12-18 01:49:23 +00002258 // p: main_process_cmd_line_options() [for VG_(clo_suppressions)]
nethercote71980f02004-01-24 18:18:54 +00002259 //--------------------------------------------------------------
sewardj1fbc1a52005-04-25 02:05:54 +00002260 if (VG_(needs).core_errors || VG_(needs).tool_errors) {
2261 VG_(debugLog)(1, "main", "Load suppressions\n");
nethercote71980f02004-01-24 18:18:54 +00002262 VG_(load_suppressions)();
sewardj1fbc1a52005-04-25 02:05:54 +00002263 }
nethercote71980f02004-01-24 18:18:54 +00002264
2265 //--------------------------------------------------------------
rjwalsh0140af52005-06-04 20:42:33 +00002266 // register client stack
2267 //--------------------------------------------------------------
njn945ed2e2005-06-24 03:28:30 +00002268 VG_(clstk_id) = VG_(register_stack)(VG_(clstk_base), VG_(clstk_end));
rjwalsh0140af52005-06-04 20:42:33 +00002269
2270 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00002271 // Show the address space state so far
2272 //--------------------------------------------------------------
2273 VG_(debugLog)(1, "main", "\n");
2274 VG_(debugLog)(1, "main", "\n");
2275 VG_(am_show_nsegments)(1,"Memory layout at client startup");
2276 VG_(debugLog)(1, "main", "\n");
2277 VG_(debugLog)(1, "main", "\n");
2278
2279 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00002280 // Run!
2281 //--------------------------------------------------------------
sewardj71bc3cb2005-05-19 00:25:45 +00002282 if (VG_(clo_xml)) {
sewardj68cde6f2005-07-19 12:17:51 +00002283 HChar buf[50];
sewardj592ae092005-11-08 19:01:44 +00002284 VG_(elapsed_wallclock_time)(buf);
sewardj738856f2009-07-15 14:48:32 +00002285 VG_(printf_xml_no_f_c)( "<status>\n"
2286 " <state>RUNNING</state>\n"
2287 " <time>%t</time>\n"
2288 "</status>\n",
2289 buf );
2290 VG_(printf_xml_no_f_c)( "\n" );
sewardj71bc3cb2005-05-19 00:25:45 +00002291 }
2292
sewardj1fbc1a52005-04-25 02:05:54 +00002293 VG_(debugLog)(1, "main", "Running thread 1\n");
sewardj1ae3f3a2005-09-28 10:47:38 +00002294
sewardj1d887112005-05-30 21:44:08 +00002295 /* As a result of the following call, the last thread standing
sewardj1ae3f3a2005-09-28 10:47:38 +00002296 eventually winds up running shutdown_actions_NORETURN
2297 just below. Unfortunately, simply exporting said function
2298 causes m_main to be part of a module cycle, which is pretty
2299 nonsensical. So instead of doing that, the address of said
2300 function is stored in a global variable 'owned' by m_syswrap,
2301 and it uses that function pointer to get back here when it needs
2302 to. */
2303
2304 /* Set continuation address. */
2305 VG_(address_of_m_main_shutdown_actions_NORETURN)
2306 = & shutdown_actions_NORETURN;
2307
2308 /* Run the first thread, eventually ending up at the continuation
2309 address. */
njnaf839f52005-06-23 03:27:57 +00002310 VG_(main_thread_wrapper_NORETURN)(1);
nethercote71980f02004-01-24 18:18:54 +00002311
sewardj1d887112005-05-30 21:44:08 +00002312 /*NOTREACHED*/
2313 vg_assert(0);
sewardjb5f6f512005-03-10 23:59:00 +00002314}
2315
sewardj17c11042006-10-15 01:26:40 +00002316/* Do everything which needs doing when the last thread exits or when
2317 a thread exits requesting a complete process exit (exit on AIX).
2318
2319 We enter here holding The Lock. For the case VgSrc_ExitProcess we
2320 must never release it, because to do so would allow other threads
2321 to continue after the system is ostensibly shut down. So we must
2322 go to our grave, so to speak, holding the lock.
2323
2324 In fact, there is never any point in releasing the lock at this
2325 point - we have it, we're shutting down the entire system, and
2326 for the case VgSrc_ExitProcess doing so positively causes trouble.
2327 So don't.
2328
2329 The final_tidyup call makes a bit of a nonsense of the ExitProcess
2330 case, since it will run the libc_freeres function, thus allowing
2331 other lurking threads to run again. Hmm. */
sewardjb5f6f512005-03-10 23:59:00 +00002332
sewardj1ae3f3a2005-09-28 10:47:38 +00002333static
2334void shutdown_actions_NORETURN( ThreadId tid,
2335 VgSchedReturnCode tids_schedretcode )
sewardjb5f6f512005-03-10 23:59:00 +00002336{
sewardj1d887112005-05-30 21:44:08 +00002337 VG_(debugLog)(1, "main", "entering VG_(shutdown_actions_NORETURN)\n");
sewardj17c11042006-10-15 01:26:40 +00002338 VG_(am_show_nsegments)(1,"Memory layout at client shutdown");
sewardj1d887112005-05-30 21:44:08 +00002339
sewardjb5f6f512005-03-10 23:59:00 +00002340 vg_assert(VG_(is_running_thread)(tid));
2341
sewardj12ab7652006-10-17 02:10:42 +00002342 vg_assert(tids_schedretcode == VgSrc_ExitThread
2343 || tids_schedretcode == VgSrc_ExitProcess
2344 || tids_schedretcode == VgSrc_FatalSig );
sewardjb5f6f512005-03-10 23:59:00 +00002345
sewardj12ab7652006-10-17 02:10:42 +00002346 if (tids_schedretcode == VgSrc_ExitThread) {
sewardjb5f6f512005-03-10 23:59:00 +00002347
sewardj17c11042006-10-15 01:26:40 +00002348 // We are the last surviving thread. Right?
2349 vg_assert( VG_(count_living_threads)() == 1 );
sewardjb5f6f512005-03-10 23:59:00 +00002350
sewardj17c11042006-10-15 01:26:40 +00002351 // Wait for all other threads to exit.
2352 // jrs: Huh? but they surely are already gone
2353 VG_(reap_threads)(tid);
sewardjb5f6f512005-03-10 23:59:00 +00002354
sewardj17c11042006-10-15 01:26:40 +00002355 // Clean the client up before the final report
2356 // this causes the libc_freeres function to run
2357 final_tidyup(tid);
2358
2359 /* be paranoid */
2360 vg_assert(VG_(is_running_thread)(tid));
2361 vg_assert(VG_(count_living_threads)() == 1);
2362
2363 } else {
2364
2365 // We may not be the last surviving thread. However, we
2366 // want to shut down the entire process. We hold the lock
2367 // and we need to keep hold of it all the way out, in order
2368 // that none of the other threads ever run again.
2369 vg_assert( VG_(count_living_threads)() >= 1 );
2370
sewardj17c11042006-10-15 01:26:40 +00002371 // Clean the client up before the final report
2372 // this causes the libc_freeres function to run
2373 // perhaps this is unsafe, as per comment above
2374 final_tidyup(tid);
2375
2376 /* be paranoid */
2377 vg_assert(VG_(is_running_thread)(tid));
2378 vg_assert(VG_(count_living_threads)() >= 1);
2379 }
sewardjb5f6f512005-03-10 23:59:00 +00002380
2381 VG_(threads)[tid].status = VgTs_Empty;
nethercote71980f02004-01-24 18:18:54 +00002382 //--------------------------------------------------------------
sewardj738856f2009-07-15 14:48:32 +00002383 // Finalisation: cleanup, messages, etc. Order not so important, only
nethercote71980f02004-01-24 18:18:54 +00002384 // affects what order the messages come.
2385 //--------------------------------------------------------------
njnb6267bd2009-08-12 00:14:16 +00002386 // First thing in the post-amble is a blank line.
sewardj738856f2009-07-15 14:48:32 +00002387 if (VG_(clo_xml))
2388 VG_(printf_xml)("\n");
njnb6267bd2009-08-12 00:14:16 +00002389 else if (VG_(clo_verbosity) > 0)
2390 VG_(message)(Vg_UserMsg, "\n");
nethercote71980f02004-01-24 18:18:54 +00002391
sewardj71bc3cb2005-05-19 00:25:45 +00002392 if (VG_(clo_xml)) {
sewardj68cde6f2005-07-19 12:17:51 +00002393 HChar buf[50];
sewardj592ae092005-11-08 19:01:44 +00002394 VG_(elapsed_wallclock_time)(buf);
sewardj738856f2009-07-15 14:48:32 +00002395 VG_(printf_xml_no_f_c)( "<status>\n"
2396 " <state>FINISHED</state>\n"
2397 " <time>%t</time>\n"
njnb6267bd2009-08-12 00:14:16 +00002398 "</status>\n"
2399 "\n",
sewardj738856f2009-07-15 14:48:32 +00002400 buf);
sewardj71bc3cb2005-05-19 00:25:45 +00002401 }
2402
nethercote71980f02004-01-24 18:18:54 +00002403 /* Print out file descriptor summary and stats. */
2404 if (VG_(clo_track_fds))
nethercote3a42fb82004-08-03 18:08:50 +00002405 VG_(show_open_fds)();
nethercote71980f02004-01-24 18:18:54 +00002406
sewardj2d9e8742009-08-07 15:46:56 +00002407 /* Call the tool's finalisation function. This makes Memcheck's
2408 leak checker run, and possibly chuck a bunch of leak errors into
2409 the error management machinery. */
2410 VG_TDICT_CALL(tool_fini, 0/*exitcode*/);
nethercote71980f02004-01-24 18:18:54 +00002411
sewardj2d9e8742009-08-07 15:46:56 +00002412 /* Show the error counts. */
sewardj7ca100d2009-08-15 23:05:34 +00002413 if (VG_(clo_xml)
2414 && (VG_(needs).core_errors || VG_(needs).tool_errors)) {
sewardj2d9e8742009-08-07 15:46:56 +00002415 VG_(show_error_counts_as_XML)();
sewardj738856f2009-07-15 14:48:32 +00002416 }
sewardj2d9e8742009-08-07 15:46:56 +00002417
2418 /* In XML mode, this merely prints the used suppressions. */
2419 if (VG_(needs).core_errors || VG_(needs).tool_errors)
2420 VG_(show_all_errors)();
nethercote71980f02004-01-24 18:18:54 +00002421
sewardj71bc3cb2005-05-19 00:25:45 +00002422 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +00002423 VG_(printf_xml)("\n");
2424 VG_(printf_xml)("</valgrindoutput>\n");
2425 VG_(printf_xml)("\n");
sewardj71bc3cb2005-05-19 00:25:45 +00002426 }
2427
nethercote885dd912004-08-03 23:14:00 +00002428 VG_(sanity_check_general)( True /*include expensive checks*/ );
nethercote71980f02004-01-24 18:18:54 +00002429
sewardj2d9e8742009-08-07 15:46:56 +00002430 if (VG_(clo_stats))
nethercote3a42fb82004-08-03 18:08:50 +00002431 print_all_stats();
nethercote71980f02004-01-24 18:18:54 +00002432
sewardj9c606bd2008-09-18 18:12:50 +00002433 /* Show a profile of the heap(s) at shutdown. Optionally, first
2434 throw away all the debug info, as that makes it easy to spot
2435 leaks in the debuginfo reader. */
2436 if (VG_(clo_profile_heap)) {
2437 if (0) VG_(di_discard_ALL_debuginfo)();
2438 VG_(print_arena_cc_analysis)();
2439 }
2440
njn2025cf92005-06-26 20:44:48 +00002441 if (VG_(clo_profile_flags) > 0) {
sewardj5471ec62006-10-17 13:58:17 +00002442 #define N_MAX 200
njn2025cf92005-06-26 20:44:48 +00002443 BBProfEntry tops[N_MAX];
2444 ULong score_total = VG_(get_BB_profile) (tops, N_MAX);
2445 show_BB_profile(tops, N_MAX, score_total);
2446 }
sewardjfa8ec112005-01-19 11:55:34 +00002447
sewardj8b635a42004-11-22 19:01:47 +00002448 /* Print Vex storage stats */
sewardjbf426512005-01-17 18:35:30 +00002449 if (0)
2450 LibVEX_ShowAllocStats();
sewardj1d887112005-05-30 21:44:08 +00002451
sewardj738856f2009-07-15 14:48:32 +00002452 /* Flush any output cached by previous calls to VG_(message). */
2453 VG_(message_flush)();
2454
njn8aa35852005-06-10 22:59:56 +00002455 /* Ok, finally exit in the os-specific way, according to the scheduler's
2456 return code. In short, if the (last) thread exited by calling
2457 sys_exit, do likewise; if the (last) thread stopped due to a fatal
2458 signal, terminate the entire system with that same fatal signal. */
2459 VG_(debugLog)(1, "core_os",
njn7b85dd52005-06-12 17:26:29 +00002460 "VG_(terminate_NORETURN)(tid=%lld)\n", (ULong)tid);
njn8aa35852005-06-10 22:59:56 +00002461
njn8aa35852005-06-10 22:59:56 +00002462 switch (tids_schedretcode) {
sewardj12ab7652006-10-17 02:10:42 +00002463 case VgSrc_ExitThread: /* the normal way out (Linux) */
2464 case VgSrc_ExitProcess: /* the normal way out (AIX) */
sewardjb9779082006-05-12 23:50:15 +00002465 /* Change the application return code to user's return code,
2466 if an error was found */
2467 if (VG_(clo_error_exitcode) > 0
2468 && VG_(get_n_errs_found)() > 0) {
2469 VG_(exit)( VG_(clo_error_exitcode) );
2470 } else {
2471 /* otherwise, return the client's exit code, in the normal
2472 way. */
2473 VG_(exit)( VG_(threads)[tid].os_state.exitcode );
2474 }
njn8aa35852005-06-10 22:59:56 +00002475 /* NOT ALIVE HERE! */
sewardj17c11042006-10-15 01:26:40 +00002476 VG_(core_panic)("entered the afterlife in main() -- ExitT/P");
njn8aa35852005-06-10 22:59:56 +00002477 break; /* what the hell :) */
2478
2479 case VgSrc_FatalSig:
2480 /* We were killed by a fatal signal, so replicate the effect */
2481 vg_assert(VG_(threads)[tid].os_state.fatalsig != 0);
2482 VG_(kill_self)(VG_(threads)[tid].os_state.fatalsig);
njnf76d27a2009-05-28 01:53:07 +00002483 /* we shouldn't be alive at this point. But VG_(kill_self)
2484 sometimes fails with EPERM on Darwin, for unclear reasons. */
2485# if defined(VGO_darwin)
2486 VG_(debugLog)(0, "main", "VG_(kill_self) failed. Exiting normally.\n");
2487 VG_(exit)(0); /* bogus, but we really need to exit now */
2488 /* fall through .. */
2489# endif
njn8aa35852005-06-10 22:59:56 +00002490 VG_(core_panic)("main(): signal was supposed to be fatal");
2491 break;
2492
2493 default:
2494 VG_(core_panic)("main(): unexpected scheduler return code");
2495 }
njne96be672005-05-08 19:08:54 +00002496}
sewardj8b635a42004-11-22 19:01:47 +00002497
sewardj1ae3f3a2005-09-28 10:47:38 +00002498/* -------------------- */
2499
2500/* Final clean-up before terminating the process.
2501 Clean up the client by calling __libc_freeres() (if requested)
2502 This is Linux-specific?
njnf76d27a2009-05-28 01:53:07 +00002503 GrP fixme glibc-specific, anyway
sewardj1ae3f3a2005-09-28 10:47:38 +00002504*/
2505static void final_tidyup(ThreadId tid)
2506{
njnf76d27a2009-05-28 01:53:07 +00002507#if !defined(VGO_darwin)
sewardjcf951812006-01-17 02:22:21 +00002508# if defined(VGP_ppc64_linux)
2509 Addr r2;
2510# endif
sewardj0ec07f32006-01-12 12:32:32 +00002511 Addr __libc_freeres_wrapper = VG_(client___libc_freeres_wrapper);
sewardj1ae3f3a2005-09-28 10:47:38 +00002512
2513 vg_assert(VG_(is_running_thread)(tid));
2514
2515 if ( !VG_(needs).libc_freeres ||
2516 !VG_(clo_run_libc_freeres) ||
sewardj0ec07f32006-01-12 12:32:32 +00002517 0 == __libc_freeres_wrapper )
sewardj1ae3f3a2005-09-28 10:47:38 +00002518 return; /* can't/won't do it */
sewardj17c11042006-10-15 01:26:40 +00002519# if defined(VGO_aix5)
2520 return; /* inapplicable on non-Linux platforms */
2521# endif
sewardj1ae3f3a2005-09-28 10:47:38 +00002522
sewardjcf951812006-01-17 02:22:21 +00002523# if defined(VGP_ppc64_linux)
2524 r2 = VG_(get_tocptr)( __libc_freeres_wrapper );
2525 if (r2 == 0) {
2526 VG_(message)(Vg_UserMsg,
sewardj738856f2009-07-15 14:48:32 +00002527 "Caught __NR_exit, but can't run __libc_freeres()\n");
sewardjcf951812006-01-17 02:22:21 +00002528 VG_(message)(Vg_UserMsg,
sewardj738856f2009-07-15 14:48:32 +00002529 " since cannot establish TOC pointer for it.\n");
sewardjcf951812006-01-17 02:22:21 +00002530 return;
2531 }
2532# endif
2533
sewardj1ae3f3a2005-09-28 10:47:38 +00002534 if (VG_(clo_verbosity) > 2 ||
2535 VG_(clo_trace_syscalls) ||
2536 VG_(clo_trace_sched))
2537 VG_(message)(Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +00002538 "Caught __NR_exit; running __libc_freeres()\n");
sewardj1ae3f3a2005-09-28 10:47:38 +00002539
sewardj0ec07f32006-01-12 12:32:32 +00002540 /* set thread context to point to libc_freeres_wrapper */
sewardj1a85f4f2006-01-12 21:15:35 +00002541 /* ppc64-linux note: __libc_freeres_wrapper gives us the real
2542 function entry point, not a fn descriptor, so can use it
2543 directly. However, we need to set R2 (the toc pointer)
2544 appropriately. */
sewardj1ae3f3a2005-09-28 10:47:38 +00002545 VG_(set_IP)(tid, __libc_freeres_wrapper);
sewardjcf951812006-01-17 02:22:21 +00002546# if defined(VGP_ppc64_linux)
2547 VG_(threads)[tid].arch.vex.guest_GPR2 = r2;
2548# endif
sewardj1ae3f3a2005-09-28 10:47:38 +00002549
2550 /* Block all blockable signals by copying the real block state into
2551 the thread's block state*/
2552 VG_(sigprocmask)(VKI_SIG_BLOCK, NULL, &VG_(threads)[tid].sig_mask);
2553 VG_(threads)[tid].tmp_sig_mask = VG_(threads)[tid].sig_mask;
2554
2555 /* and restore handlers to default */
2556 VG_(set_default_handler)(VKI_SIGSEGV);
2557 VG_(set_default_handler)(VKI_SIGBUS);
2558 VG_(set_default_handler)(VKI_SIGILL);
2559 VG_(set_default_handler)(VKI_SIGFPE);
2560
2561 // We were exiting, so assert that...
2562 vg_assert(VG_(is_exiting)(tid));
2563 // ...but now we're not again
2564 VG_(threads)[tid].exitreason = VgSrc_None;
2565
2566 // run until client thread exits - ideally with LIBC_FREERES_DONE,
2567 // but exit/exitgroup/signal will do
2568 VG_(scheduler)(tid);
2569
2570 vg_assert(VG_(is_exiting)(tid));
njnf76d27a2009-05-28 01:53:07 +00002571#endif
sewardj1ae3f3a2005-09-28 10:47:38 +00002572}
2573
sewardj45f4e7c2005-09-27 19:20:21 +00002574
2575/*====================================================================*/
njn49f80e82009-05-21 01:25:43 +00002576/*=== Getting to main() alive: LINUX ===*/
sewardj45f4e7c2005-09-27 19:20:21 +00002577/*====================================================================*/
2578
sewardj17c11042006-10-15 01:26:40 +00002579#if defined(VGO_linux)
2580
sewardj45f4e7c2005-09-27 19:20:21 +00002581/* If linking of the final executables is done with glibc present,
2582 then Valgrind starts at main() above as usual, and all of the
2583 following code is irrelevant.
2584
2585 However, this is not the intended mode of use. The plan is to
2586 avoid linking against glibc, by giving gcc the flags
2587 -nodefaultlibs -lgcc -nostartfiles at startup.
2588
2589 From this derive two requirements:
2590
2591 1. gcc may emit calls to memcpy and memset to deal with structure
2592 assignments etc. Since we have chosen to ignore all the
2593 "normal" supporting libraries, we have to provide our own
2594 implementations of them. No problem.
2595
2596 2. We have to provide a symbol "_start", to which the kernel
2597 hands control at startup. Hence the code below.
2598*/
2599
2600/* ---------------- Requirement 1 ---------------- */
2601
sewardj17c11042006-10-15 01:26:40 +00002602void* memcpy(void *dest, const void *src, SizeT n);
2603void* memcpy(void *dest, const void *src, SizeT n) {
sewardj45f4e7c2005-09-27 19:20:21 +00002604 return VG_(memcpy)(dest,src,n);
2605}
sewardj17c11042006-10-15 01:26:40 +00002606void* memset(void *s, int c, SizeT n);
2607void* memset(void *s, int c, SizeT n) {
sewardj45f4e7c2005-09-27 19:20:21 +00002608 return VG_(memset)(s,c,n);
2609}
2610
bart82616e12010-06-13 13:46:24 +00002611/* BVA: abort() for those platforms that need it (PPC and ARM). */
2612void abort(void);
2613void abort(void){
2614 VG_(printf)("Something called raise().\n");
2615 vg_assert(0);
2616}
2617
sewardj59570ff2010-01-01 11:59:33 +00002618/* EAZG: ARM's EABI will call floating point exception handlers in
2619 libgcc which boil down to an abort or raise, that's usually defined
2620 in libc. Instead, define them here. */
2621#if defined(VGP_arm_linux)
2622void raise(void);
2623void raise(void){
2624 VG_(printf)("Something called raise().\n");
2625 vg_assert(0);
2626}
2627
sewardj59570ff2010-01-01 11:59:33 +00002628void __aeabi_unwind_cpp_pr0(void);
2629void __aeabi_unwind_cpp_pr0(void){
2630 VG_(printf)("Something called __aeabi_unwind_cpp_pr0()\n");
2631 vg_assert(0);
2632}
sewardj38efe4b2010-08-22 12:23:01 +00002633
2634void __aeabi_unwind_cpp_pr1(void);
2635void __aeabi_unwind_cpp_pr1(void){
2636 VG_(printf)("Something called __aeabi_unwind_cpp_pr1()\n");
2637 vg_assert(0);
2638}
sewardj59570ff2010-01-01 11:59:33 +00002639#endif
2640
sewardj45f4e7c2005-09-27 19:20:21 +00002641/* ---------------- Requirement 2 ---------------- */
2642
2643/* Glibc's sysdeps/i386/elf/start.S has the following gem of a
2644 comment, which explains how the stack looks right at process start
2645 (when _start is jumped to). Hence _start passes %esp to
sewardj17c11042006-10-15 01:26:40 +00002646 _start_in_C_linux, which extracts argc/argv/envp and starts up
sewardj45f4e7c2005-09-27 19:20:21 +00002647 correctly. */
2648
2649/* This is the canonical entry point, usually the first thing in the text
2650 segment. The SVR4/i386 ABI (pages 3-31, 3-32) says that when the entry
2651 point runs, most registers' values are unspecified, except for:
2652
2653 %edx Contains a function pointer to be registered with `atexit'.
2654 This is how the dynamic linker arranges to have DT_FINI
2655 functions called for shared libraries that have been loaded
2656 before this code runs.
2657
2658 %esp The stack contains the arguments and environment:
2659 0(%esp) argc
2660 4(%esp) argv[0]
2661 ...
2662 (4*argc)(%esp) NULL
2663 (4*(argc+1))(%esp) envp[0]
2664 ...
2665 NULL
2666*/
2667
2668/* The kernel hands control to _start, which extracts the initial
sewardj17c11042006-10-15 01:26:40 +00002669 stack pointer and calls onwards to _start_in_C_linux. This also switches
sewardja48a4932005-09-29 11:09:56 +00002670 the new stack. */
sewardj45f4e7c2005-09-27 19:20:21 +00002671#if defined(VGP_x86_linux)
2672asm("\n"
sewardjd9fc3822005-11-18 23:50:43 +00002673 ".text\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002674 "\t.globl _start\n"
2675 "\t.type _start,@function\n"
2676 "_start:\n"
2677 /* set up the new stack in %eax */
sewardjfdf91b42005-09-28 00:53:09 +00002678 "\tmovl $vgPlain_interim_stack, %eax\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002679 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
2680 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
2681 "\tsubl $16, %eax\n"
2682 "\tandl $~15, %eax\n"
2683 /* install it, and collect the original one */
2684 "\txchgl %eax, %esp\n"
sewardj17c11042006-10-15 01:26:40 +00002685 /* call _start_in_C_linux, passing it the startup %esp */
sewardj45f4e7c2005-09-27 19:20:21 +00002686 "\tpushl %eax\n"
sewardj17c11042006-10-15 01:26:40 +00002687 "\tcall _start_in_C_linux\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002688 "\thlt\n"
sewardj2fedc642005-11-19 02:02:57 +00002689 ".previous\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002690);
2691#elif defined(VGP_amd64_linux)
2692asm("\n"
sewardjd9fc3822005-11-18 23:50:43 +00002693 ".text\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002694 "\t.globl _start\n"
2695 "\t.type _start,@function\n"
2696 "_start:\n"
2697 /* set up the new stack in %rdi */
sewardjfdf91b42005-09-28 00:53:09 +00002698 "\tmovq $vgPlain_interim_stack, %rdi\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002699 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
2700 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
2701 "\tandq $~15, %rdi\n"
2702 /* install it, and collect the original one */
2703 "\txchgq %rdi, %rsp\n"
sewardj17c11042006-10-15 01:26:40 +00002704 /* call _start_in_C_linux, passing it the startup %rsp */
2705 "\tcall _start_in_C_linux\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002706 "\thlt\n"
sewardj2fedc642005-11-19 02:02:57 +00002707 ".previous\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002708);
sewardja48a4932005-09-29 11:09:56 +00002709#elif defined(VGP_ppc32_linux)
2710asm("\n"
sewardjd9fc3822005-11-18 23:50:43 +00002711 ".text\n"
sewardja48a4932005-09-29 11:09:56 +00002712 "\t.globl _start\n"
2713 "\t.type _start,@function\n"
2714 "_start:\n"
2715 /* set up the new stack in r16 */
2716 "\tlis 16,vgPlain_interim_stack@ha\n"
2717 "\tla 16,vgPlain_interim_stack@l(16)\n"
2718 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2719 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2720 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2721 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2722 "\tadd 16,17,16\n"
2723 "\tadd 16,18,16\n"
2724 "\trlwinm 16,16,0,0,27\n"
2725 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2726 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2727 boundary. And r1 is the original SP. Set the SP to r16 and
sewardj17c11042006-10-15 01:26:40 +00002728 call _start_in_C_linux, passing it the initial SP. */
sewardja48a4932005-09-29 11:09:56 +00002729 "\tmr 3,1\n"
2730 "\tmr 1,16\n"
sewardj17c11042006-10-15 01:26:40 +00002731 "\tbl _start_in_C_linux\n"
sewardja48a4932005-09-29 11:09:56 +00002732 "\ttrap\n"
sewardj2fedc642005-11-19 02:02:57 +00002733 ".previous\n"
sewardja48a4932005-09-29 11:09:56 +00002734);
sewardj2c48c7b2005-11-29 13:05:56 +00002735#elif defined(VGP_ppc64_linux)
2736asm("\n"
cerion21082042005-12-06 19:07:08 +00002737 /* PPC64 ELF ABI says '_start' points to a function descriptor.
2738 So we must have one, and that is what goes into the .opd section. */
cerion297c88f2005-12-22 15:53:12 +00002739 "\t.align 2\n"
cerion21082042005-12-06 19:07:08 +00002740 "\t.global _start\n"
2741 "\t.section \".opd\",\"aw\"\n"
2742 "\t.align 3\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002743 "_start:\n"
cerion21082042005-12-06 19:07:08 +00002744 "\t.quad ._start,.TOC.@tocbase,0\n"
2745 "\t.previous\n"
2746 "\t.type ._start,@function\n"
2747 "\t.global ._start\n"
2748 "._start:\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002749 /* set up the new stack in r16 */
2750 "\tlis 16, vgPlain_interim_stack@highest\n"
2751 "\tori 16,16,vgPlain_interim_stack@higher\n"
2752 "\tsldi 16,16,32\n"
2753 "\toris 16,16,vgPlain_interim_stack@h\n"
2754 "\tori 16,16,vgPlain_interim_stack@l\n"
2755 "\txor 17,17,17\n"
2756 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2757 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2758 "\txor 18,18,18\n"
2759 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2760 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2761 "\tadd 16,17,16\n"
2762 "\tadd 16,18,16\n"
2763 "\trldicr 16,16,0,59\n"
2764 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2765 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2766 boundary. And r1 is the original SP. Set the SP to r16 and
sewardj17c11042006-10-15 01:26:40 +00002767 call _start_in_C_linux, passing it the initial SP. */
sewardj2c48c7b2005-11-29 13:05:56 +00002768 "\tmr 3,1\n"
2769 "\tmr 1,16\n"
sewardj17c11042006-10-15 01:26:40 +00002770 "\tbl ._start_in_C_linux\n"
cerion21082042005-12-06 19:07:08 +00002771 "\tnop\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002772 "\ttrap\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002773);
sewardj59570ff2010-01-01 11:59:33 +00002774#elif defined(VGP_arm_linux)
2775asm("\n"
2776 "\t.align 2\n"
2777 "\t.global _start\n"
2778 "_start:\n"
2779 "\tldr r0, [pc, #36]\n"
2780 "\tldr r1, [pc, #36]\n"
2781 "\tadd r0, r1, r0\n"
2782 "\tldr r1, [pc, #32]\n"
2783 "\tadd r0, r1, r0\n"
2784 "\tmvn r1, #15\n"
2785 "\tand r0, r0, r1\n"
2786 "\tmov r1, sp\n"
2787 "\tmov sp, r0\n"
2788 "\tmov r0, r1\n"
2789 "\tb _start_in_C_linux\n"
2790 "\t.word vgPlain_interim_stack\n"
2791 "\t.word "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
2792 "\t.word "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
2793);
sewardj45f4e7c2005-09-27 19:20:21 +00002794#else
njn49f80e82009-05-21 01:25:43 +00002795# error "Unknown linux platform"
sewardj45f4e7c2005-09-27 19:20:21 +00002796#endif
2797
sewardje66f2e02006-12-30 17:45:08 +00002798/* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
2799#define _GNU_SOURCE
2800#define _FILE_OFFSET_BITS 64
2801/* This is in order to get AT_NULL and AT_PAGESIZE. */
2802#include <elf.h>
2803/* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
2804
sewardj45f4e7c2005-09-27 19:20:21 +00002805/* Avoid compiler warnings: this fn _is_ used, but labelling it
2806 'static' causes gcc to complain it isn't. */
sewardj17c11042006-10-15 01:26:40 +00002807void _start_in_C_linux ( UWord* pArgc );
2808void _start_in_C_linux ( UWord* pArgc )
sewardj45f4e7c2005-09-27 19:20:21 +00002809{
2810 Int r;
2811 Word argc = pArgc[0];
2812 HChar** argv = (HChar**)&pArgc[1];
2813 HChar** envp = (HChar**)&pArgc[1+argc+1];
sewardjf9d2f9b2006-11-17 20:00:57 +00002814
2815 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
2816 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
2817
2818 the_iicii.sp_at_startup = (Addr)pArgc;
2819
sewardje66f2e02006-12-30 17:45:08 +00002820# if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux)
2821 {
2822 /* ppc/ppc64 can be configured with different page sizes.
2823 Determine this early. This is an ugly hack and really should
2824 be moved into valgrind_main. */
2825 UWord *sp = &pArgc[1+argc+1];
2826 while (*sp++ != 0)
2827 ;
2828 for (; *sp != AT_NULL && *sp != AT_PAGESZ; sp += 2);
2829 if (*sp == AT_PAGESZ) {
2830 VKI_PAGE_SIZE = sp[1];
2831 for (VKI_PAGE_SHIFT = 12;
2832 VKI_PAGE_SHIFT <= VKI_MAX_PAGE_SHIFT; VKI_PAGE_SHIFT++)
2833 if (VKI_PAGE_SIZE == (1UL << VKI_PAGE_SHIFT))
2834 break;
2835 }
2836 }
2837# endif
2838
sewardjf9d2f9b2006-11-17 20:00:57 +00002839 r = valgrind_main( (Int)argc, argv, envp );
sewardj17c11042006-10-15 01:26:40 +00002840 /* NOTREACHED */
sewardj45f4e7c2005-09-27 19:20:21 +00002841 VG_(exit)(r);
2842}
2843
sewardj17c11042006-10-15 01:26:40 +00002844
2845/*====================================================================*/
2846/*=== Getting to main() alive: AIX5 ===*/
2847/*====================================================================*/
2848
njn49f80e82009-05-21 01:25:43 +00002849#elif defined(VGO_aix5)
sewardj17c11042006-10-15 01:26:40 +00002850
2851/* This is somewhat simpler than the Linux case. _start_valgrind
2852 receives control from the magic piece of code created in this
2853 process' address space by the launcher, via use of ptrace(). At
2854 the point of entry:
2855
2856 - the initial client process image is in memory and ready to roll,
2857 except that we've partially trashed its integer register state
2858 in order to get this far. So ..
2859
2860 - intregs37 holds the client's initial integer register state, so
2861 we can restore it before starting the client on the VCPU.
2862
2863 - we're on the client's stack. This is not good; therefore the
2864 first order of business is to switch to our temporary stack.
2865
2866 - the client's initial argc/v/envp is in r3/r4/r5 (32 bit mode) or
2867 r14/r15/r16 (64 bit mode). They are pulled out of the stashed
2868 integer register state and passed to our main().
2869
2870 The launcher will have played some games with argv. If the launcher
2871 ($prefix/bin/valgrind) was started like this
2872
2873 valgrind [args-for-V] app [args-for-app]
2874
2875 then the launcher will have started the client as
2876
2877 app [args-for-V] app [args-for-app]
2878
2879 m_initimg will have to mess with the client's initial r4/r5
2880 (32-bit) or r15/r16 (64-bit) so that it believes it was execd as
2881 "app [args-for-app]". Well, that's no big deal.
2882*/
2883
2884#include "launcher-aix5-bootblock.h"
2885
2886void _start_in_C_aix5 ( AIX5Bootblock* bootblock );
2887void _start_in_C_aix5 ( AIX5Bootblock* bootblock )
2888{
2889 Int r;
2890 ULong* intregs37;
2891 UWord argc, argv, envp;
2892 __NR_getpid = bootblock->__NR_getpid;
2893 __NR_write = bootblock->__NR_write;
2894 __NR_exit = bootblock->__NR_exit;
2895 __NR_open = bootblock->__NR_open;
2896 __NR_read = bootblock->__NR_read;
2897 __NR_close = bootblock->__NR_close;
sewardjf9d2f9b2006-11-17 20:00:57 +00002898
2899 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
2900 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
2901
sewardj17c11042006-10-15 01:26:40 +00002902 intregs37 = &bootblock->iregs_pc_cr_lr_ctr_xer[0];
sewardjf9d2f9b2006-11-17 20:00:57 +00002903 the_iicii.intregs37 = intregs37;
2904 the_iicii.bootblock = (void*)bootblock;
2905 the_iicii.adler32_exp = bootblock->adler32;
2906
2907 /* Not important on AIX. */
2908 the_iicii.sp_at_startup = (Addr)0x31415927ULL;
2909
sewardj17c11042006-10-15 01:26:40 +00002910# if defined(VGP_ppc32_aix5)
2911 argc = (UWord)intregs37[3]; /* client's r3 == argc */
2912 argv = (UWord)intregs37[4];
2913 envp = (UWord)intregs37[5];
2914# else /* defined(VGP_ppc64_aix5) */
2915 argc = (UWord)intregs37[14]; /* client's r14 == argc */
2916 argv = (UWord)intregs37[15];
2917 envp = (UWord)intregs37[16];
2918# endif
sewardjf9d2f9b2006-11-17 20:00:57 +00002919
2920 r = valgrind_main( (Int)argc, (HChar**)argv, (HChar**)envp );
2921
sewardj17c11042006-10-15 01:26:40 +00002922 /* NOTREACHED */
2923 VG_(exit)(r);
2924}
2925
2926/* THE ENTRY POINT */
2927void _start_valgrind ( AIX5Bootblock* bootblock );
2928void _start_valgrind ( AIX5Bootblock* bootblock )
2929{
2930 /* Switch immediately to our temporary stack, and continue. This
2931 is pretty dodgy in that it assumes that gcc does not place on
2932 the stack, anything needed to form the _start_in_C_aix5 call,
2933 since it will be on the old stack. */
2934 register UWord new_r1;
2935 new_r1 = (UWord)&VG_(interim_stack);
2936 new_r1 += VG_STACK_GUARD_SZB; /* step over lower guard page */
2937 new_r1 += VG_STACK_ACTIVE_SZB; /* step to top of active area */
2938 new_r1 -= 512; /* paranoia */
2939 __asm__ __volatile__("mr 1,%0" :/*wr*/
2940 :/*rd*/ "b"(new_r1)
2941 :/*trash*/"r1","memory");
2942 _start_in_C_aix5(bootblock);
2943 /*NOTREACHED*/
2944 VG_(exit)(0);
2945}
2946
sewardj61a1b052008-10-22 00:56:53 +00002947/* At some point in Oct 2008, static linking appeared to stop working
2948 on AIX 5.3. This breaks the build since we link statically. The
2949 linking fails citing absence of the following five symbols as the
2950 reason. In the absence of a better solution, here are stand-ins
2951 for them. Kludge appears to work; presumably said functions,
2952 assuming they are indeed functions, are never called. */
2953void encrypted_pw_passlen ( void ) { vg_assert(0); }
2954void crypt_r ( void ) { vg_assert(0); }
2955void max_history_size ( void ) { vg_assert(0); }
2956void getpass_auto ( void ) { vg_assert(0); }
2957void max_pw_passlen ( void ) { vg_assert(0); }
2958
njn49f80e82009-05-21 01:25:43 +00002959
njnf76d27a2009-05-28 01:53:07 +00002960/*====================================================================*/
2961/*=== Getting to main() alive: darwin ===*/
2962/*====================================================================*/
2963
2964#elif defined(VGO_darwin)
2965
njnea2d6fd2010-07-01 00:20:20 +00002966/*
2967 Memory layout established by kernel:
2968
2969 0(%esp) argc
2970 4(%esp) argv[0]
2971 ...
2972 argv[argc-1]
2973 NULL
2974 envp[0]
2975 ...
2976 envp[n]
2977 NULL
2978 executable name (presumably, a pointer to it)
2979 NULL
2980
2981 Ditto in the 64-bit case, except all offsets from SP are obviously
2982 twice as large.
2983*/
2984
2985/* The kernel hands control to _start, which extracts the initial
2986 stack pointer and calls onwards to _start_in_C_darwin. This also
2987 switches to the new stack. */
2988#if defined(VGP_x86_darwin)
2989asm("\n"
2990 ".text\n"
2991 ".align 2,0x90\n"
2992 "\t.globl __start\n"
2993 "__start:\n"
2994 /* set up the new stack in %eax */
2995 "\tmovl $_vgPlain_interim_stack, %eax\n"
2996 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
2997 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
2998 "\tsubl $16, %eax\n"
2999 "\tandl $~15, %eax\n"
3000 /* install it, and collect the original one */
3001 "\txchgl %eax, %esp\n"
3002 /* call _start_in_C_darwin, passing it the startup %esp */
3003 "\tpushl %eax\n"
3004 "\tcall __start_in_C_darwin\n"
3005 "\tint $3\n"
3006 "\tint $3\n"
3007);
3008#elif defined(VGP_amd64_darwin)
3009asm("\n"
3010 ".text\n"
3011 "\t.globl __start\n"
3012 ".align 3,0x90\n"
3013 "__start:\n"
3014 /* set up the new stack in %rdi */
3015 "\tmovabsq $_vgPlain_interim_stack, %rdi\n"
3016 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
3017 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
3018 "\tandq $~15, %rdi\n"
3019 /* install it, and collect the original one */
3020 "\txchgq %rdi, %rsp\n"
3021 /* call _start_in_C_darwin, passing it the startup %rsp */
3022 "\tcall __start_in_C_darwin\n"
3023 "\tint $3\n"
3024 "\tint $3\n"
3025);
3026#endif
3027
njnf76d27a2009-05-28 01:53:07 +00003028void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2);
3029void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2) {
3030 // skip check
3031 return VG_(memcpy)(dest,src,n);
3032}
3033void* __memset_chk(void *s, int c, SizeT n, SizeT n2);
3034void* __memset_chk(void *s, int c, SizeT n, SizeT n2) {
3035 // skip check
3036 return VG_(memset)(s,c,n);
3037}
3038void bzero(void *s, SizeT n);
3039void bzero(void *s, SizeT n) {
3040 VG_(memset)(s,0,n);
3041}
3042
3043void* memcpy(void *dest, const void *src, SizeT n);
3044void* memcpy(void *dest, const void *src, SizeT n) {
3045 return VG_(memcpy)(dest,src,n);
3046}
3047void* memset(void *s, int c, SizeT n);
3048void* memset(void *s, int c, SizeT n) {
3049 return VG_(memset)(s,c,n);
3050}
3051
njnf76d27a2009-05-28 01:53:07 +00003052/* Avoid compiler warnings: this fn _is_ used, but labelling it
3053 'static' causes gcc to complain it isn't. */
3054void _start_in_C_darwin ( UWord* pArgc );
3055void _start_in_C_darwin ( UWord* pArgc )
3056{
3057 Int r;
njnea2d6fd2010-07-01 00:20:20 +00003058 Int argc = *(Int *)pArgc; // not pArgc[0] on LP64
njnf76d27a2009-05-28 01:53:07 +00003059 HChar** argv = (HChar**)&pArgc[1];
3060 HChar** envp = (HChar**)&pArgc[1+argc+1];
3061
3062 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3063 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3064
3065 the_iicii.sp_at_startup = (Addr)pArgc;
3066
3067 r = valgrind_main( (Int)argc, argv, envp );
3068 /* NOTREACHED */
3069 VG_(exit)(r);
3070}
3071
3072
njn49f80e82009-05-21 01:25:43 +00003073#else
3074
3075# error "Unknown OS"
3076#endif
sewardj17c11042006-10-15 01:26:40 +00003077
3078
sewardj0af71bb2010-07-01 14:50:30 +00003079/*====================================================================*/
3080/*=== {u,}{div,mod}di3 replacements ===*/
3081/*====================================================================*/
njnea2d6fd2010-07-01 00:20:20 +00003082
3083/* For static linking on x86-darwin, we need to supply our own 64-bit
3084 integer division code, else the link dies thusly:
3085
3086 ld_classic: Undefined symbols:
3087 ___udivdi3
3088 ___umoddi3
3089*/
3090#if defined(VGP_x86_darwin)
3091
3092/* Routines for doing signed/unsigned 64 x 64 ==> 64 div and mod
3093 (udivdi3, umoddi3, divdi3, moddi3) using only 32 x 32 ==> 32
3094 division. Cobbled together from
3095
3096 http://www.hackersdelight.org/HDcode/divlu.c
3097 http://www.hackersdelight.org/HDcode/divls.c
3098 http://www.hackersdelight.org/HDcode/newCode/divDouble.c
3099
3100 The code from those three files is covered by the following license,
3101 as it appears at:
3102
3103 http://www.hackersdelight.org/permissions.htm
3104
3105 You are free to use, copy, and distribute any of the code on
3106 this web site, whether modified by you or not. You need not give
3107 attribution. This includes the algorithms (some of which appear
3108 in Hacker's Delight), the Hacker's Assistant, and any code
3109 submitted by readers. Submitters implicitly agree to this.
3110*/
3111
3112/* Long division, unsigned (64/32 ==> 32).
3113 This procedure performs unsigned "long division" i.e., division of a
311464-bit unsigned dividend by a 32-bit unsigned divisor, producing a
311532-bit quotient. In the overflow cases (divide by 0, or quotient
3116exceeds 32 bits), it returns a remainder of 0xFFFFFFFF (an impossible
3117value).
3118 The dividend is u1 and u0, with u1 being the most significant word.
3119The divisor is parameter v. The value returned is the quotient.
3120 Max line length is 57, to fit in hacker.book. */
3121
3122static Int nlz32(UInt x)
3123{
3124 Int n;
3125 if (x == 0) return(32);
3126 n = 0;
3127 if (x <= 0x0000FFFF) {n = n +16; x = x <<16;}
3128 if (x <= 0x00FFFFFF) {n = n + 8; x = x << 8;}
3129 if (x <= 0x0FFFFFFF) {n = n + 4; x = x << 4;}
3130 if (x <= 0x3FFFFFFF) {n = n + 2; x = x << 2;}
3131 if (x <= 0x7FFFFFFF) {n = n + 1;}
3132 return n;
3133}
3134
3135/* 64 x 32 ==> 32 unsigned division, using only 32 x 32 ==> 32
3136 division as a primitive. */
3137static UInt divlu2(UInt u1, UInt u0, UInt v, UInt *r)
3138{
3139 const UInt b = 65536; // Number base (16 bits).
3140 UInt un1, un0, // Norm. dividend LSD's.
3141 vn1, vn0, // Norm. divisor digits.
3142 q1, q0, // Quotient digits.
3143 un32, un21, un10, // Dividend digit pairs.
3144 rhat; // A remainder.
3145 Int s; // Shift amount for norm.
3146
3147 if (u1 >= v) { // If overflow, set rem.
3148 if (r != NULL) // to an impossible value,
3149 *r = 0xFFFFFFFF; // and return the largest
3150 return 0xFFFFFFFF;} // possible quotient.
3151
3152 s = nlz32(v); // 0 <= s <= 31.
3153 v = v << s; // Normalize divisor.
3154 vn1 = v >> 16; // Break divisor up into
3155 vn0 = v & 0xFFFF; // two 16-bit digits.
3156
3157 un32 = (u1 << s) | ((u0 >> (32 - s)) & (-s >> 31));
3158 un10 = u0 << s; // Shift dividend left.
3159
3160 un1 = un10 >> 16; // Break right half of
3161 un0 = un10 & 0xFFFF; // dividend into two digits.
3162
3163 q1 = un32/vn1; // Compute the first
3164 rhat = un32 - q1*vn1; // quotient digit, q1.
3165 again1:
3166 if (q1 >= b || q1*vn0 > b*rhat + un1) {
3167 q1 = q1 - 1;
3168 rhat = rhat + vn1;
3169 if (rhat < b) goto again1;}
3170
3171 un21 = un32*b + un1 - q1*v; // Multiply and subtract.
3172
3173 q0 = un21/vn1; // Compute the second
3174 rhat = un21 - q0*vn1; // quotient digit, q0.
3175 again2:
3176 if (q0 >= b || q0*vn0 > b*rhat + un0) {
3177 q0 = q0 - 1;
3178 rhat = rhat + vn1;
3179 if (rhat < b) goto again2;}
3180
3181 if (r != NULL) // If remainder is wanted,
3182 *r = (un21*b + un0 - q0*v) >> s; // return it.
3183 return q1*b + q0;
3184}
3185
3186
3187/* 64 x 32 ==> 32 signed division, using only 32 x 32 ==> 32 division
3188 as a primitive. */
3189static Int divls(Int u1, UInt u0, Int v, Int *r)
3190{
3191 Int q, uneg, vneg, diff, borrow;
3192
3193 uneg = u1 >> 31; // -1 if u < 0.
3194 if (uneg) { // Compute the absolute
3195 u0 = -u0; // value of the dividend u.
3196 borrow = (u0 != 0);
3197 u1 = -u1 - borrow;}
3198
3199 vneg = v >> 31; // -1 if v < 0.
3200 v = (v ^ vneg) - vneg; // Absolute value of v.
3201
3202 if ((UInt)u1 >= (UInt)v) goto overflow;
3203
3204 q = divlu2(u1, u0, v, (UInt *)r);
3205
3206 diff = uneg ^ vneg; // Negate q if signs of
3207 q = (q ^ diff) - diff; // u and v differed.
3208 if (uneg && r != NULL)
3209 *r = -*r;
3210
3211 if ((diff ^ q) < 0 && q != 0) { // If overflow,
3212 overflow: // set remainder
3213 if (r != NULL) // to an impossible value,
3214 *r = 0x80000000; // and return the largest
3215 q = 0x80000000;} // possible neg. quotient.
3216 return q;
3217}
3218
3219
3220
3221/* This file contains a program for doing 64/64 ==> 64 division, on a
3222machine that does not have that instruction but that does have
3223instructions for "long division" (64/32 ==> 32). Code for unsigned
3224division is given first, followed by a simple program for doing the
3225signed version by using the unsigned version.
3226 These programs are useful in implementing "long long" (64-bit)
3227arithmetic on a machine that has the long division instruction. It will
3228work on 64- and 32-bit machines, provided the compiler implements long
3229long's (64-bit integers). It is desirable that the machine have the
3230Count Leading Zeros instruction.
3231 In the GNU world, these programs are known as __divdi3 and __udivdi3,
3232and similar names are used here.
3233 This material is not in HD, but may be in a future edition.
3234Max line length is 57, to fit in hacker.book. */
3235
3236
3237static Int nlz64(ULong x)
3238{
3239 Int n;
3240 if (x == 0) return(64);
3241 n = 0;
3242 if (x <= 0x00000000FFFFFFFFULL) {n = n + 32; x = x << 32;}
3243 if (x <= 0x0000FFFFFFFFFFFFULL) {n = n + 16; x = x << 16;}
3244 if (x <= 0x00FFFFFFFFFFFFFFULL) {n = n + 8; x = x << 8;}
3245 if (x <= 0x0FFFFFFFFFFFFFFFULL) {n = n + 4; x = x << 4;}
3246 if (x <= 0x3FFFFFFFFFFFFFFFULL) {n = n + 2; x = x << 2;}
3247 if (x <= 0x7FFFFFFFFFFFFFFFULL) {n = n + 1;}
3248 return n;
3249}
3250
3251// ---------------------------- udivdi3 --------------------------------
3252
3253 /* The variables u0, u1, etc. take on only 32-bit values, but they
3254 are declared long long to avoid some compiler warning messages and to
3255 avoid some unnecessary EXTRs that the compiler would put in, to
3256 convert long longs to ints.
3257
3258 First the procedure takes care of the case in which the divisor is a
3259 32-bit quantity. There are two subcases: (1) If the left half of the
3260 dividend is less than the divisor, one execution of DIVU is all that
3261 is required (overflow is not possible). (2) Otherwise it does two
3262 divisions, using the grade school method, with variables used as
3263 suggested below.
3264
3265 q1 q0
3266 ________
3267 v) u1 u0
3268 q1*v
3269 ____
3270 k u0 */
3271
3272/* These macros must be used with arguments of the appropriate type
3273(unsigned long long for DIVU and long long for DIVS. They are
3274simulations of the presumed machines ops. I.e., they look at only the
3275low-order 32 bits of the divisor, they return garbage if the division
3276overflows, and they return garbage in the high-order half of the
3277quotient doubleword.
3278 In practice, these would be replaced with uses of the machine's DIVU
3279and DIVS instructions (e.g., by using the GNU "asm" facility). */
3280
3281static UInt DIVU ( ULong u, UInt v )
3282{
3283 UInt uHi = (UInt)(u >> 32);
3284 UInt uLo = (UInt)u;
3285 return divlu2(uHi, uLo, v, NULL);
3286}
3287
3288static Int DIVS ( Long u, Int v )
3289{
3290 Int uHi = (Int)(u >> 32);
3291 UInt uLo = (UInt)u;
3292 return divls(uHi, uLo, v, NULL);
3293}
3294
3295/* 64 x 64 ==> 64 unsigned division, using only 32 x 32 ==> 32
3296 division as a primitive. */
3297static ULong udivdi3(ULong u, ULong v)
3298{
3299 ULong u0, u1, v1, q0, q1, k, n;
3300
3301 if (v >> 32 == 0) { // If v < 2**32:
3302 if (u >> 32 < v) // If u/v cannot overflow,
3303 return DIVU(u, v) // just do one division.
3304 & 0xFFFFFFFF;
3305 else { // If u/v would overflow:
3306 u1 = u >> 32; // Break u up into two
3307 u0 = u & 0xFFFFFFFF; // halves.
3308 q1 = DIVU(u1, v) // First quotient digit.
3309 & 0xFFFFFFFF;
3310 k = u1 - q1*v; // First remainder, < v.
3311 q0 = DIVU((k << 32) + u0, v) // 2nd quot. digit.
3312 & 0xFFFFFFFF;
3313 return (q1 << 32) + q0;
3314 }
3315 }
3316 // Here v >= 2**32.
3317 n = nlz64(v); // 0 <= n <= 31.
3318 v1 = (v << n) >> 32; // Normalize the divisor
3319 // so its MSB is 1.
3320 u1 = u >> 1; // To ensure no overflow.
3321 q1 = DIVU(u1, v1) // Get quotient from
3322 & 0xFFFFFFFF; // divide unsigned insn.
3323 q0 = (q1 << n) >> 31; // Undo normalization and
3324 // division of u by 2.
3325 if (q0 != 0) // Make q0 correct or
3326 q0 = q0 - 1; // too small by 1.
3327 if ((u - q0*v) >= v)
3328 q0 = q0 + 1; // Now q0 is correct.
3329 return q0;
3330}
3331
3332
3333// ----------------------------- divdi3 --------------------------------
3334
3335/* This routine presumes that smallish cases (those which can be done in
3336one execution of DIVS) are common. If this is not the case, the test for
3337this case should be deleted.
3338 Note that the test for when DIVS can be used is not entirely
3339accurate. For example, DIVS is not used if v = 0xFFFFFFFF8000000,
3340whereas if could be (if u is sufficiently small in magnitude). */
3341
3342// ------------------------------ cut ----------------------------------
3343
3344static ULong my_llabs ( Long x )
3345{
3346 ULong t = x >> 63;
3347 return (x ^ t) - t;
3348}
3349
3350/* 64 x 64 ==> 64 signed division, using only 32 x 32 ==> 32 division
3351 as a primitive. */
3352static Long divdi3(Long u, Long v)
3353{
3354 ULong au, av;
3355 Long q, t;
3356 au = my_llabs(u);
3357 av = my_llabs(v);
3358 if (av >> 31 == 0) { // If |v| < 2**31 and
3359 // if (v << 32 >> 32 == v) { // If v is in range and
3360 if (au < av << 31) { // |u|/|v| cannot
3361 q = DIVS(u, v); // overflow, use DIVS.
3362 return (q << 32) >> 32;
3363 }
3364 }
3365 q = udivdi3(au,av); // Invoke udivdi3.
3366 t = (u ^ v) >> 63; // If u, v have different
3367 return (q ^ t) - t; // signs, negate q.
3368}
3369
3370// ---------------------------- end cut --------------------------------
3371
sewardj0af71bb2010-07-01 14:50:30 +00003372ULong __udivdi3 (ULong u, ULong v);
njnea2d6fd2010-07-01 00:20:20 +00003373ULong __udivdi3 (ULong u, ULong v)
3374{
3375 return udivdi3(u,v);
3376}
3377
sewardj0af71bb2010-07-01 14:50:30 +00003378Long __divdi3 (Long u, Long v);
njnea2d6fd2010-07-01 00:20:20 +00003379Long __divdi3 (Long u, Long v)
3380{
3381 return divdi3(u,v);
3382}
3383
sewardj0af71bb2010-07-01 14:50:30 +00003384ULong __umoddi3 (ULong u, ULong v);
njnea2d6fd2010-07-01 00:20:20 +00003385ULong __umoddi3 (ULong u, ULong v)
3386{
3387 ULong q = __udivdi3(u, v);
3388 ULong r = u - q * v;
3389 return r;
3390}
3391
sewardj0af71bb2010-07-01 14:50:30 +00003392Long __moddi3 (Long u, Long v);
njnea2d6fd2010-07-01 00:20:20 +00003393Long __moddi3 (Long u, Long v)
3394{
3395 Long q = __divdi3(u, v);
3396 Long r = u - q * v;
3397 return r;
3398}
3399
3400#endif
3401
3402
sewardjde4a1d02002-03-22 01:27:54 +00003403/*--------------------------------------------------------------------*/
njn04e16982005-05-31 00:23:43 +00003404/*--- end ---*/
sewardjde4a1d02002-03-22 01:27:54 +00003405/*--------------------------------------------------------------------*/