blob: d02e5a4b360c10c4c6eb91e0b612a9352586c61f [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
sewardjec062e82011-10-23 07:32:08 +000010 Copyright (C) 2000-2011 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"
sewardj6c591e12011-04-11 16:17:51 +000034#include "pub_core_libcsetjmp.h" // to keep _threadstate.h happy
njnc7561b92005-06-19 01:24:32 +000035#include "pub_core_threadstate.h"
sewardj14c7cc52007-02-25 15:08:24 +000036#include "pub_core_xarray.h"
sewardj45f4e7c2005-09-27 19:20:21 +000037#include "pub_core_clientstate.h"
sewardj55f9d1a2005-04-25 11:11:44 +000038#include "pub_core_aspacemgr.h"
njnac1e0332009-05-08 00:39:31 +000039#include "pub_core_aspacehl.h"
sewardj45f4e7c2005-09-27 19:20:21 +000040#include "pub_core_commandline.h"
njn2521d322005-05-08 14:45:13 +000041#include "pub_core_debuglog.h"
42#include "pub_core_errormgr.h"
43#include "pub_core_execontext.h"
sewardj3b290482011-05-06 21:02:55 +000044#include "pub_core_gdbserver.h"
sewardj17c11042006-10-15 01:26:40 +000045#include "pub_core_initimg.h"
njn97405b22005-06-02 03:39:33 +000046#include "pub_core_libcbase.h"
njn132bfcc2005-06-04 19:16:06 +000047#include "pub_core_libcassert.h"
njneb8896b2005-06-04 20:03:55 +000048#include "pub_core_libcfile.h"
njn36a20fa2005-06-03 03:08:39 +000049#include "pub_core_libcprint.h"
njnf39e9a32005-06-12 02:43:17 +000050#include "pub_core_libcproc.h"
njnde62cbf2005-06-10 22:08:14 +000051#include "pub_core_libcsignal.h"
sewardj45f4e7c2005-09-27 19:20:21 +000052#include "pub_core_syscall.h" // VG_(strerror)
njnf76d27a2009-05-28 01:53:07 +000053#include "pub_core_mach.h"
njnf536bbb2005-06-13 04:21:38 +000054#include "pub_core_machine.h"
njnaf1d7df2005-06-11 01:31:52 +000055#include "pub_core_mallocfree.h"
njn20242342005-05-16 23:31:24 +000056#include "pub_core_options.h"
sewardjfdf91b42005-09-28 00:53:09 +000057#include "pub_core_debuginfo.h"
njnd1af0032005-05-29 17:01:48 +000058#include "pub_core_redir.h"
njnc7561b92005-06-19 01:24:32 +000059#include "pub_core_scheduler.h"
sewardjf9ebc392010-05-09 22:30:43 +000060#include "pub_core_seqmatch.h" // For VG_(string_match)
njn0c246472005-05-31 01:00:08 +000061#include "pub_core_signals.h"
njn2025cf92005-06-26 20:44:48 +000062#include "pub_core_stacks.h" // For VG_(register_stack)
njnc1b01812005-06-17 22:19:06 +000063#include "pub_core_syswrap.h"
njn43b9a8a2005-05-10 04:37:01 +000064#include "pub_core_tooliface.h"
sewardj17c11042006-10-15 01:26:40 +000065#include "pub_core_translate.h" // For VG_(translate)
njna7598f62005-06-18 03:27:58 +000066#include "pub_core_trampoline.h"
njn8bddf582005-05-13 23:40:55 +000067#include "pub_core_transtab.h"
philippe14711e82012-06-14 22:18:50 +000068#include "pub_tool_inner.h"
69#if defined(ENABLE_INNER_CLIENT_REQUEST)
70#include "valgrind.h"
71#endif
sewardj17c11042006-10-15 01:26:40 +000072
sewardjb5f6f512005-03-10 23:59:00 +000073
nethercote71980f02004-01-24 18:18:54 +000074/*====================================================================*/
75/*=== Counters, for profiling purposes only ===*/
76/*====================================================================*/
sewardjde4a1d02002-03-22 01:27:54 +000077
nethercote3a42fb82004-08-03 18:08:50 +000078static void print_all_stats ( void )
nethercote71980f02004-01-24 18:18:54 +000079{
njn42c83552005-12-05 20:45:59 +000080 VG_(print_translation_stats)();
nethercote92e7b7f2004-08-07 17:52:25 +000081 VG_(print_tt_tc_stats)();
nethercote844e7122004-08-02 15:27:22 +000082 VG_(print_scheduler_stats)();
njn9271cbc2005-03-13 05:38:25 +000083 VG_(print_ExeContext_stats)();
sewardj12ab7652006-10-17 02:10:42 +000084 VG_(print_errormgr_stats)();
njn9271cbc2005-03-13 05:38:25 +000085
nethercote3a42fb82004-08-03 18:08:50 +000086 // Memory stats
nethercote885dd912004-08-03 23:14:00 +000087 if (VG_(clo_verbosity) > 2) {
sewardj738856f2009-07-15 14:48:32 +000088 VG_(message)(Vg_DebugMsg, "\n");
nethercote3a42fb82004-08-03 18:08:50 +000089 VG_(message)(Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +000090 "------ Valgrind's internal memory use stats follow ------\n" );
nethercote885dd912004-08-03 23:14:00 +000091 VG_(sanity_check_malloc_all)();
sewardj738856f2009-07-15 14:48:32 +000092 VG_(message)(Vg_DebugMsg, "------\n" );
nethercote3a42fb82004-08-03 18:08:50 +000093 VG_(print_all_arena_stats)();
sewardj738856f2009-07-15 14:48:32 +000094 VG_(message)(Vg_DebugMsg, "\n");
nethercote3a42fb82004-08-03 18:08:50 +000095 }
nethercote71980f02004-01-24 18:18:54 +000096}
97
98
99/*====================================================================*/
sewardj71bc3cb2005-05-19 00:25:45 +0000100/*=== Command-line: variables, processing, etc ===*/
101/*====================================================================*/
102
103// See pub_{core,tool}_options.h for explanations of all these.
104
sewardj45f4e7c2005-09-27 19:20:21 +0000105static void usage_NORETURN ( Bool debug_help )
njn7cf0bd32002-06-08 13:36:03 +0000106{
florian95a128b2011-09-29 14:26:38 +0000107 /* 'usage1' contains a %s
108 - for the name of the GDB executable
109 - for the name of vgdb's path prefix
110 which must be supplied when they are VG_(printf)'d. */
njn25e49d8e72002-09-23 09:36:25 +0000111 Char* usage1 =
njn00cfcfc2005-11-12 18:53:50 +0000112"usage: valgrind [options] prog-and-args\n"
njn25e49d8e72002-09-23 09:36:25 +0000113"\n"
njn97db7612009-08-04 02:32:55 +0000114" tool-selection option, with default in [ ]:\n"
sewardjb5f6f512005-03-10 23:59:00 +0000115" --tool=<name> use the Valgrind tool named <name> [memcheck]\n"
njn97db7612009-08-04 02:32:55 +0000116"\n"
117" basic user options for all Valgrind tools, with defaults in [ ]:\n"
nethercotea76368b2004-06-16 11:56:29 +0000118" -h --help show this message\n"
nethercote6c999f22004-01-31 22:55:15 +0000119" --help-debug show this message, plus debugging options\n"
njn25e49d8e72002-09-23 09:36:25 +0000120" --version show version\n"
njn25e49d8e72002-09-23 09:36:25 +0000121" -q --quiet run silently; only print error msgs\n"
sewardj2d9e8742009-08-07 15:46:56 +0000122" -v --verbose be more verbose -- show misc extra info\n"
sewardj6e31f802007-11-17 22:29:25 +0000123" --trace-children=no|yes Valgrind-ise child processes (follow execve)? [no]\n"
sewardj06421272009-11-05 08:55:13 +0000124" --trace-children-skip=patt1,patt2,... specifies a list of executables\n"
125" that --trace-children=yes should not trace into\n"
sewardj9ab64a42010-12-06 11:40:04 +0000126" --trace-children-skip-by-arg=patt1,patt2,... same as --trace-children-skip=\n"
127" but check the argv[] entries for children, rather\n"
128" than the exe name, to make a follow/no-follow decision\n"
njn97db7612009-08-04 02:32:55 +0000129" --child-silent-after-fork=no|yes omit child output between fork & exec? [no]\n"
sewardj3b290482011-05-06 21:02:55 +0000130" --vgdb=no|yes|full activate gdbserver? [yes]\n"
131" full is slower but provides precise watchpoint/step\n"
sewardj1568e172011-06-18 08:28:04 +0000132" --vgdb-error=<number> invoke gdbserver after <number> errors [%d]\n"
133" to get started quickly, use --vgdb-error=0\n"
134" and follow the on-screen directions\n"
nethercote0d588502004-06-21 13:27:11 +0000135" --track-fds=no|yes track open file descriptors? [no]\n"
thughes6233a382004-08-21 11:10:44 +0000136" --time-stamp=no|yes add timestamps to log messages? [no]\n"
njnce545552005-07-25 22:36:52 +0000137" --log-fd=<number> log messages to file descriptor [2=stderr]\n"
njn374a36d2007-11-23 01:41:32 +0000138" --log-file=<file> log messages to <file>\n"
njnce545552005-07-25 22:36:52 +0000139" --log-socket=ipaddr:port log messages to socket ipaddr:port\n"
nethercote2b0793f2003-12-02 10:41:18 +0000140"\n"
nethercote2b0793f2003-12-02 10:41:18 +0000141" user options for Valgrind tools that report errors:\n"
sewardj738856f2009-07-15 14:48:32 +0000142" --xml=yes emit error output in XML (some tools only)\n"
143" --xml-fd=<number> XML output to file descriptor\n"
144" --xml-file=<file> XML output to <file>\n"
145" --xml-socket=ipaddr:port XML output to socket ipaddr:port\n"
146" --xml-user-comment=STR copy STR verbatim into XML output\n"
nethercote2b0793f2003-12-02 10:41:18 +0000147" --demangle=no|yes automatically demangle C++ names? [yes]\n"
njn20b4a152005-10-19 22:39:40 +0000148" --num-callers=<number> show <number> callers in stack traces [12]\n"
nethercote2b0793f2003-12-02 10:41:18 +0000149" --error-limit=no|yes stop showing new errors if too many? [yes]\n"
sewardjb9779082006-05-12 23:50:15 +0000150" --error-exitcode=<number> exit code to return if errors found [0=disable]\n"
nethercote2b0793f2003-12-02 10:41:18 +0000151" --show-below-main=no|yes continue stack traces below main() [no]\n"
152" --suppressions=<filename> suppress errors described in <filename>\n"
sewardjd153fae2005-01-10 17:24:47 +0000153" --gen-suppressions=no|yes|all print suppressions for errors? [no]\n"
nethercote04d0fbc2004-01-26 16:48:06 +0000154" --db-attach=no|yes start debugger when errors detected? [no]\n"
sewardj7839d112007-11-20 19:45:03 +0000155" --db-command=<command> command to start debugger [%s -nw %%f %%p]\n"
nethercote04d0fbc2004-01-26 16:48:06 +0000156" --input-fd=<number> file descriptor for input [0=stdin]\n"
njn97db7612009-08-04 02:32:55 +0000157" --dsymutil=no|yes run dsymutil on Mac OS X when helpful? [no]\n"
sewardj97724e52005-04-02 23:40:59 +0000158" --max-stackframe=<number> assume stack switch for SP changes larger\n"
159" than <number> bytes [2000000]\n"
sewardj95d86c02007-12-18 01:49:23 +0000160" --main-stacksize=<number> set size of main thread's stack (in bytes)\n"
161" [use current 'ulimit' value]\n"
njn97db7612009-08-04 02:32:55 +0000162"\n"
163" user options for Valgrind tools that replace malloc:\n"
164" --alignment=<number> set minimum alignment of heap allocations [%ld]\n"
165"\n"
166" uncommon user options for all Valgrind tools:\n"
sewardj14cdbf82010-10-12 00:44:05 +0000167" --fullpath-after= (with nothing after the '=')\n"
168" show full source paths in call stacks\n"
169" --fullpath-after=string like --fullpath-after=, but only show the\n"
170" part of the path after 'string'. Allows removal\n"
171" of path prefixes. Use this flag multiple times\n"
172" to specify a set of prefixes to remove.\n"
sewardj6dbcc632011-06-07 21:39:28 +0000173" --smc-check=none|stack|all|all-non-file [stack]\n"
174" checks for self-modifying code: none, only for\n"
175" code found in stacks, for all code, or for all\n"
176" code except that from file-backed mappings\n"
njn97db7612009-08-04 02:32:55 +0000177" --read-var-info=yes|no read debug info on stack and global variables\n"
178" and use it to print better error messages in\n"
179" tools that make use of it (Memcheck, Helgrind,\n"
bartf6122a02010-03-27 07:38:39 +0000180" DRD) [no]\n"
sewardj3b290482011-05-06 21:02:55 +0000181" --vgdb-poll=<number> gdbserver poll max every <number> basic blocks [%d] \n"
182" --vgdb-shadow-registers=no|yes let gdb see the shadow registers [no]\n"
183" --vgdb-prefix=<prefix> prefix for vgdb FIFOs [%s]\n"
njn97db7612009-08-04 02:32:55 +0000184" --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]\n"
185" --sim-hints=hint1,hint2,... known hints:\n"
sewardjcc3de2d2011-08-18 15:08:20 +0000186" lax-ioctls, enable-outer, fuse-compatible [none]\n"
bart78bfc712011-12-08 16:14:59 +0000187" --fair-sched=no|yes|try schedule threads fairly on multicore systems [no]\n"
njn97db7612009-08-04 02:32:55 +0000188" --kernel-variant=variant1,variant2,... known variants: bproc [none]\n"
189" handle non-standard kernel variants\n"
190" --show-emwarns=no|yes show warnings about emulation limits? [no]\n"
sewardjf9ebc392010-05-09 22:30:43 +0000191" --require-text-symbol=:sonamepattern:symbolpattern abort run if the\n"
192" stated shared object doesn't have the stated\n"
193" text symbol. Patterns can contain ? and *.\n"
philippe1e470b52012-05-11 19:33:46 +0000194" --soname-synonyms=syn1=pattern1,syn2=pattern2,... synonym soname\n"
195" patterns for some Valgrind wrapping\n"
196" or replacement (such as malloc replacement)\n"
fitzhardinge98abfc72003-12-16 02:05:15 +0000197"\n";
njn7cf0bd32002-06-08 13:36:03 +0000198
njn25e49d8e72002-09-23 09:36:25 +0000199 Char* usage2 =
200"\n"
nethercote2b0793f2003-12-02 10:41:18 +0000201" debugging options for all Valgrind tools:\n"
njn97db7612009-08-04 02:32:55 +0000202" -d show verbose debugging output\n"
njnb1cc5d62010-07-06 04:05:23 +0000203" --stats=no|yes show tool and core statistics [no]\n"
njn25e49d8e72002-09-23 09:36:25 +0000204" --sanity-level=<number> level of sanity checking to do [1]\n"
sewardjfa8ec112005-01-19 11:55:34 +0000205" --trace-flags=<XXXXXXXX> show generated code? (X = 0|1) [00000000]\n"
206" --profile-flags=<XXXXXXXX> ditto, but for profiling (X = 0|1) [00000000]\n"
sewardj33afdb52006-01-17 02:36:40 +0000207" --trace-notbelow=<number> only show BBs above <number> [999999999]\n"
njn25e49d8e72002-09-23 09:36:25 +0000208" --trace-syscalls=no|yes show all system calls? [no]\n"
209" --trace-signals=no|yes show signal handling details? [no]\n"
210" --trace-symtab=no|yes show symbol table details? [no]\n"
sewardjf767d962007-02-12 17:47:14 +0000211" --trace-symtab-patt=<patt> limit debuginfo tracing to obj name <patt>\n"
sewardjce058b02005-05-01 08:55:38 +0000212" --trace-cfi=no|yes show call-frame-info details? [no]\n"
sewardjf767d962007-02-12 17:47:14 +0000213" --debug-dump=syms mimic /usr/bin/readelf --syms\n"
214" --debug-dump=line mimic /usr/bin/readelf --debug-dump=line\n"
215" --debug-dump=frames mimic /usr/bin/readelf --debug-dump=frames\n"
sewardj0ec07f32006-01-12 12:32:32 +0000216" --trace-redir=no|yes show redirection details? [no]\n"
njn25e49d8e72002-09-23 09:36:25 +0000217" --trace-sched=no|yes show thread scheduler details? [no]\n"
sewardj9c606bd2008-09-18 18:12:50 +0000218" --profile-heap=no|yes profile Valgrind's own space use\n"
jsgf855d93d2003-10-13 22:26:55 +0000219" --wait-for-gdb=yes|no pause on startup to wait for gdb attach\n"
sewardj17c11042006-10-15 01:26:40 +0000220" --sym-offsets=yes|no show syms in form 'name+offset' ? [no]\n"
sewardjb5f6f512005-03-10 23:59:00 +0000221" --command-line-only=no|yes only use command line options [no]\n"
njn613812e2005-03-11 04:57:30 +0000222"\n"
njn97db7612009-08-04 02:32:55 +0000223" Vex options for all Valgrind tools:\n"
224" --vex-iropt-verbosity=<0..9> [0]\n"
225" --vex-iropt-level=<0..2> [2]\n"
226" --vex-iropt-precise-memory-exns=no|yes [no]\n"
227" --vex-iropt-unroll-thresh=<0..400> [120]\n"
228" --vex-guest-max-insns=<1..100> [50]\n"
229" --vex-guest-chase-thresh=<0..99> [10]\n"
sewardj540cc4a2010-01-15 10:57:57 +0000230" --vex-guest-chase-cond=no|yes [no]\n"
sewardjfa8ec112005-01-19 11:55:34 +0000231" --trace-flags and --profile-flags values (omit the middle space):\n"
sewardj2a99cf62004-11-24 10:44:19 +0000232" 1000 0000 show conversion into IR\n"
233" 0100 0000 show after initial opt\n"
234" 0010 0000 show after instrumentation\n"
235" 0001 0000 show after second opt\n"
236" 0000 1000 show after tree building\n"
237" 0000 0100 show selecting insns\n"
238" 0000 0010 show after reg-alloc\n"
239" 0000 0001 show final assembly\n"
njn33dbfce2006-06-02 22:58:34 +0000240" (Nb: you need --trace-notbelow with --trace-flags for full details)\n"
sewardj2a99cf62004-11-24 10:44:19 +0000241"\n"
nethercote2b0793f2003-12-02 10:41:18 +0000242" debugging options for Valgrind tools that report errors\n"
243" --dump-error=<number> show translation for basic block associated\n"
244" with <number>'th error context [0=show none]\n"
njn97db7612009-08-04 02:32:55 +0000245"\n"
246" debugging options for Valgrind tools that replace malloc:\n"
247" --trace-malloc=no|yes show client malloc details? [no]\n"
fitzhardinge98abfc72003-12-16 02:05:15 +0000248"\n";
njn3e884182003-04-15 13:03:23 +0000249
250 Char* usage3 =
251"\n"
nethercote71980f02004-01-24 18:18:54 +0000252" Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc\n"
njn25e49d8e72002-09-23 09:36:25 +0000253"\n"
njn10b9aea2009-07-14 06:55:05 +0000254" %s is %s\n"
sewardjec062e82011-10-23 07:32:08 +0000255" Valgrind is Copyright (C) 2000-2011, and GNU GPL'd, by Julian Seward et al.\n"
256" LibVEX is Copyright (C) 2004-2011, and GNU GPL'd, by OpenWorks LLP et al.\n"
njnd04b7c62002-10-03 14:05:52 +0000257"\n"
njn10b9aea2009-07-14 06:55:05 +0000258" Bug reports, feedback, admiration, abuse, etc, to: %s.\n"
njn25e49d8e72002-09-23 09:36:25 +0000259"\n";
njn7cf0bd32002-06-08 13:36:03 +0000260
sewardj12373b12007-11-20 21:38:14 +0000261 Char* gdb_path = GDB_PATH;
sewardj12373b12007-11-20 21:38:14 +0000262
njnbe9b47b2005-05-15 16:22:58 +0000263 // Ensure the message goes to stdout
sewardj738856f2009-07-15 14:48:32 +0000264 VG_(log_output_sink).fd = 1;
265 VG_(log_output_sink).is_socket = False;
njnbe9b47b2005-05-15 16:22:58 +0000266
sewardj3b290482011-05-06 21:02:55 +0000267 /* 'usage1' expects two int, two char* argument, and one SizeT argument. */
268 VG_(printf)(usage1,
269 VG_(clo_vgdb_error), gdb_path, VG_MIN_MALLOC_SZB,
florian95a128b2011-09-29 14:26:38 +0000270 VG_(clo_vgdb_poll), VG_(vgdb_prefix_default)());
fitzhardinge98abfc72003-12-16 02:05:15 +0000271 if (VG_(details).name) {
272 VG_(printf)(" user options for %s:\n", VG_(details).name);
fitzhardinge98abfc72003-12-16 02:05:15 +0000273 if (VG_(needs).command_line_options)
njn51d827b2005-05-09 01:02:08 +0000274 VG_TDICT_CALL(tool_print_usage);
fitzhardinge98abfc72003-12-16 02:05:15 +0000275 else
276 VG_(printf)(" (none)\n");
277 }
nethercote6c999f22004-01-31 22:55:15 +0000278 if (debug_help) {
sewardjbbaef872008-11-01 23:55:32 +0000279 VG_(printf)("%s", usage2);
fitzhardinge98abfc72003-12-16 02:05:15 +0000280
nethercote6c999f22004-01-31 22:55:15 +0000281 if (VG_(details).name) {
282 VG_(printf)(" debugging options for %s:\n", VG_(details).name);
283
284 if (VG_(needs).command_line_options)
njn51d827b2005-05-09 01:02:08 +0000285 VG_TDICT_CALL(tool_print_debug_usage);
nethercote6c999f22004-01-31 22:55:15 +0000286 else
287 VG_(printf)(" (none)\n");
288 }
fitzhardinge98abfc72003-12-16 02:05:15 +0000289 }
njn10b9aea2009-07-14 06:55:05 +0000290 VG_(printf)(usage3, VG_(details).name, VG_(details).copyright_author,
291 VG_BUGS_TO);
nethercotef4928da2004-06-15 10:54:40 +0000292 VG_(exit)(0);
njn7cf0bd32002-06-08 13:36:03 +0000293}
sewardjde4a1d02002-03-22 01:27:54 +0000294
sewardjde4a1d02002-03-22 01:27:54 +0000295
sewardj95d86c02007-12-18 01:49:23 +0000296/* Peer at previously set up VG_(args_for_valgrind) and do some
297 minimal command line processing that must happen early on:
sewardj45f4e7c2005-09-27 19:20:21 +0000298
sewardj95d86c02007-12-18 01:49:23 +0000299 - show the version string, if requested (-v)
300 - extract any request for help (--help, -h, --help-debug)
301 - get the toolname (--tool=)
302 - set VG_(clo_max_stackframe) (--max-stackframe=)
303 - set VG_(clo_main_stacksize) (--main-stacksize=)
philippe72faf102012-03-11 22:24:03 +0000304 - set VG_(clo_sim_hints) (--sim-hints=)
sewardj95d86c02007-12-18 01:49:23 +0000305
306 That's all it does. The main command line processing is done below
307 by main_process_cmd_line_options. Note that
308 main_process_cmd_line_options has to handle but ignore the ones we
309 have handled here.
310*/
311static void early_process_cmd_line_options ( /*OUT*/Int* need_help,
312 /*OUT*/HChar** tool )
sewardj45f4e7c2005-09-27 19:20:21 +0000313{
314 UInt i;
315 HChar* str;
sewardj8b635a42004-11-22 19:01:47 +0000316
sewardj14c7cc52007-02-25 15:08:24 +0000317 vg_assert( VG_(args_for_valgrind) );
nethercote71980f02004-01-24 18:18:54 +0000318
sewardj14c7cc52007-02-25 15:08:24 +0000319 /* parse the options we have (only the options we care about now) */
320 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
321
322 str = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
sewardj45f4e7c2005-09-27 19:20:21 +0000323 vg_assert(str);
nethercote71980f02004-01-24 18:18:54 +0000324
njn83df0b62009-02-25 01:01:05 +0000325 // Nb: the version string goes to stdout.
sewardj738856f2009-07-15 14:48:32 +0000326 if VG_XACT_CLO(str, "--version", VG_(log_output_sink).fd, 1) {
327 VG_(log_output_sink).is_socket = False;
sewardj45f4e7c2005-09-27 19:20:21 +0000328 VG_(printf)("valgrind-" VERSION "\n");
329 VG_(exit)(0);
njn83df0b62009-02-25 01:01:05 +0000330 }
njncce38e62010-07-06 04:25:12 +0000331 else if VG_XACT_CLO(str, "--help", *need_help, *need_help+1) {}
332 else if VG_XACT_CLO(str, "-h", *need_help, *need_help+1) {}
sewardj45f4e7c2005-09-27 19:20:21 +0000333
njncce38e62010-07-06 04:25:12 +0000334 else if VG_XACT_CLO(str, "--help-debug", *need_help, *need_help+2) {}
nethercote71980f02004-01-24 18:18:54 +0000335
sewardj45f4e7c2005-09-27 19:20:21 +0000336 // The tool has already been determined, but we need to know the name
337 // here.
njn83df0b62009-02-25 01:01:05 +0000338 else if VG_STR_CLO(str, "--tool", *tool) {}
sewardj5bdfbd22007-12-15 22:13:05 +0000339
sewardj95d86c02007-12-18 01:49:23 +0000340 // Set up VG_(clo_max_stackframe) and VG_(clo_main_stacksize).
341 // These are needed by VG_(ii_create_image), which happens
342 // before main_process_cmd_line_options().
njn83df0b62009-02-25 01:01:05 +0000343 else if VG_INT_CLO(str, "--max-stackframe", VG_(clo_max_stackframe)) {}
344 else if VG_INT_CLO(str, "--main-stacksize", VG_(clo_main_stacksize)) {}
philippe72faf102012-03-11 22:24:03 +0000345
346 // Set up VG_(clo_sim_hints). This is needed a.o. for an inner
347 // running in an outer, to have "no-inner-prefix" enabled
348 // as early as possible.
349 else if VG_STR_CLO (str, "--sim-hints", VG_(clo_sim_hints)) {}
nethercote71980f02004-01-24 18:18:54 +0000350 }
nethercote71980f02004-01-24 18:18:54 +0000351}
352
sewardj95d86c02007-12-18 01:49:23 +0000353/* The main processing for command line options. See comments above
sewardj738856f2009-07-15 14:48:32 +0000354 on early_process_cmd_line_options.
355
356 Comments on how the logging options are handled:
357
358 User can specify:
359 --log-fd= for a fd to write to (default setting, fd = 2)
360 --log-file= for a file name to write to
361 --log-socket= for a socket to write to
362
363 As a result of examining these and doing relevant socket/file
364 opening, a final fd is established. This is stored in
365 VG_(log_output_sink) in m_libcprint. Also, if --log-file=STR was
366 specified, then STR, after expansion of %p and %q templates within
367 it, is stored in VG_(clo_log_fname_expanded), in m_options, just in
368 case anybody wants to know what it is.
369
370 When printing, VG_(log_output_sink) is consulted to find the
371 fd to send output to.
372
373 Exactly analogous actions are undertaken for the XML output
374 channel, with the one difference that the default fd is -1, meaning
375 the channel is disabled by default.
sewardj95d86c02007-12-18 01:49:23 +0000376*/
sewardj738856f2009-07-15 14:48:32 +0000377static
378void main_process_cmd_line_options ( /*OUT*/Bool* logging_to_fd,
379 /*OUT*/Char** xml_fname_unexpanded,
380 const HChar* toolname )
nethercote71980f02004-01-24 18:18:54 +0000381{
njnda033f52005-12-19 21:27:58 +0000382 // VG_(clo_log_fd) is used by all the messaging. It starts as 2 (stderr)
383 // and we cannot change it until we know what we are changing it to is
384 // ok. So we have tmp_log_fd to hold the tmp fd prior to that point.
sewardj92645592005-07-23 09:18:34 +0000385 SysRes sres;
sewardj738856f2009-07-15 14:48:32 +0000386 Int i, tmp_log_fd, tmp_xml_fd;
sewardj92645592005-07-23 09:18:34 +0000387 Int toolname_len = VG_(strlen)(toolname);
njn83df0b62009-02-25 01:01:05 +0000388 Char* tmp_str; // Used in a couple of places.
njnbe9b47b2005-05-15 16:22:58 +0000389 enum {
390 VgLogTo_Fd,
391 VgLogTo_File,
njnbe9b47b2005-05-15 16:22:58 +0000392 VgLogTo_Socket
sewardj738856f2009-07-15 14:48:32 +0000393 } log_to = VgLogTo_Fd, // Where is logging output to be sent?
394 xml_to = VgLogTo_Fd; // Where is XML output to be sent?
sewardjde4a1d02002-03-22 01:27:54 +0000395
sewardj738856f2009-07-15 14:48:32 +0000396 /* Temporarily holds the string STR specified with
397 --{log,xml}-{name,socket}=STR. 'fs' stands for
398 file-or-socket. */
399 Char* log_fsname_unexpanded = NULL;
400 Char* xml_fsname_unexpanded = NULL;
401
402 /* Log to stderr by default, but usage message goes to stdout. XML
403 output is initially disabled. */
njnda033f52005-12-19 21:27:58 +0000404 tmp_log_fd = 2;
sewardj738856f2009-07-15 14:48:32 +0000405 tmp_xml_fd = -1;
406
sewardj19d81412002-06-03 01:10:40 +0000407 /* Check for sane path in ./configure --prefix=... */
fitzhardinge98abfc72003-12-16 02:05:15 +0000408 if (VG_LIBDIR[0] != '/')
sewardj17c11042006-10-15 01:26:40 +0000409 VG_(err_config_error)("Please use absolute paths in "
florian1763e812011-07-12 19:07:05 +0000410 "./configure --prefix=... or --libdir=...\n");
sewardj38170912002-05-10 21:07:22 +0000411
sewardj14c7cc52007-02-25 15:08:24 +0000412 vg_assert( VG_(args_for_valgrind) );
nethercote71980f02004-01-24 18:18:54 +0000413
sewardj738856f2009-07-15 14:48:32 +0000414 /* BEGIN command-line processing loop */
415
sewardj14c7cc52007-02-25 15:08:24 +0000416 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
417
418 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
sewardj45f4e7c2005-09-27 19:20:21 +0000419 HChar* colon = arg;
nethercote71980f02004-01-24 18:18:54 +0000420
njn1274d242007-03-26 23:38:42 +0000421 // Look for a colon in the option name.
thughes3bfd5a02004-07-18 08:05:44 +0000422 while (*colon && *colon != ':' && *colon != '=')
423 colon++;
nethercote71980f02004-01-24 18:18:54 +0000424
njn1274d242007-03-26 23:38:42 +0000425 // Does it have the form "--toolname:foo"? We have to do it at the start
426 // in case someone has combined a prefix with a core-specific option,
427 // eg. "--memcheck:verbose".
thughes3bfd5a02004-07-18 08:05:44 +0000428 if (*colon == ':') {
njn83df0b62009-02-25 01:01:05 +0000429 if (VG_STREQN(2, arg, "--") &&
430 VG_STREQN(toolname_len, arg+2, toolname) &&
431 VG_STREQN(1, arg+2+toolname_len, ":"))
nethercote71980f02004-01-24 18:18:54 +0000432 {
njn1274d242007-03-26 23:38:42 +0000433 // Prefix matches, convert "--toolname:foo" to "--foo".
434 // Two things to note:
435 // - We cannot modify the option in-place. If we did, and then
436 // a child was spawned with --trace-children=yes, the
437 // now-non-prefixed option would be passed and could screw up
438 // the child.
439 // - We create copies, and never free them. Why? Non-prefixed
440 // options hang around forever, so tools need not make copies
441 // of strings within them. We need to have the same behaviour
442 // for prefixed options. The pointer to the copy will be lost
443 // once we leave this function (although a tool may keep a
444 // pointer into it), but the space wasted is insignificant.
445 // (In bug #142197, the copies were being freed, which caused
446 // problems for tools that reasonably assumed that arguments
447 // wouldn't disappear on them.)
nethercote71980f02004-01-24 18:18:54 +0000448 if (0)
449 VG_(printf)("tool-specific arg: %s\n", arg);
sewardj9c606bd2008-09-18 18:12:50 +0000450 arg = VG_(strdup)("main.mpclo.1", arg + toolname_len + 1);
nethercote71980f02004-01-24 18:18:54 +0000451 arg[0] = '-';
452 arg[1] = '-';
453
454 } else {
455 // prefix doesn't match, skip to next arg
456 continue;
457 }
458 }
459
fitzhardinge98abfc72003-12-16 02:05:15 +0000460 /* Ignore these options - they've already been handled */
njn83df0b62009-02-25 01:01:05 +0000461 if VG_STREQN( 7, arg, "--tool=") {}
462 else if VG_STREQN(20, arg, "--command-line-only=") {}
463 else if VG_STREQ( arg, "--") {}
464 else if VG_STREQ( arg, "-d") {}
465 else if VG_STREQN(16, arg, "--max-stackframe") {}
466 else if VG_STREQN(16, arg, "--main-stacksize") {}
philippe72faf102012-03-11 22:24:03 +0000467 else if VG_STREQN(11, arg, "--sim-hints") {}
njn83df0b62009-02-25 01:01:05 +0000468 else if VG_STREQN(14, arg, "--profile-heap") {}
nethercote27fec902004-06-16 21:26:32 +0000469
njn83df0b62009-02-25 01:01:05 +0000470 // These options are new.
471 else if (VG_STREQ(arg, "-v") ||
472 VG_STREQ(arg, "--verbose"))
sewardjde4a1d02002-03-22 01:27:54 +0000473 VG_(clo_verbosity)++;
nethercote27fec902004-06-16 21:26:32 +0000474
njn83df0b62009-02-25 01:01:05 +0000475 else if (VG_STREQ(arg, "-q") ||
476 VG_STREQ(arg, "--quiet"))
sewardjde4a1d02002-03-22 01:27:54 +0000477 VG_(clo_verbosity)--;
478
sewardj2d9e8742009-08-07 15:46:56 +0000479 else if VG_BOOL_CLO(arg, "--stats", VG_(clo_stats)) {}
bartdb4384e2011-10-11 18:49:35 +0000480 else if VG_BOOL_CLO(arg, "--xml", VG_(clo_xml))
481 VG_(debugLog_setXml)(VG_(clo_xml));
482
sewardj3b290482011-05-06 21:02:55 +0000483 else if VG_XACT_CLO(arg, "--vgdb=no", VG_(clo_vgdb), Vg_VgdbNo) {}
484 else if VG_XACT_CLO(arg, "--vgdb=yes", VG_(clo_vgdb), Vg_VgdbYes) {}
485 else if VG_XACT_CLO(arg, "--vgdb=full", VG_(clo_vgdb), Vg_VgdbFull) {}
486 else if VG_INT_CLO (arg, "--vgdb-poll", VG_(clo_vgdb_poll)) {}
487 else if VG_INT_CLO (arg, "--vgdb-error", VG_(clo_vgdb_error)) {}
488 else if VG_STR_CLO (arg, "--vgdb-prefix", VG_(clo_vgdb_prefix)) {}
489 else if VG_BOOL_CLO(arg, "--vgdb-shadow-registers",
490 VG_(clo_vgdb_shadow_registers)) {}
njn83df0b62009-02-25 01:01:05 +0000491 else if VG_BOOL_CLO(arg, "--db-attach", VG_(clo_db_attach)) {}
492 else if VG_BOOL_CLO(arg, "--demangle", VG_(clo_demangle)) {}
philippe1e470b52012-05-11 19:33:46 +0000493 else if VG_STR_CLO (arg, "--soname-synonyms",VG_(clo_soname_synonyms)) {}
njn83df0b62009-02-25 01:01:05 +0000494 else if VG_BOOL_CLO(arg, "--error-limit", VG_(clo_error_limit)) {}
495 else if VG_INT_CLO (arg, "--error-exitcode", VG_(clo_error_exitcode)) {}
496 else if VG_BOOL_CLO(arg, "--show-emwarns", VG_(clo_show_emwarns)) {}
sewardj95d86c02007-12-18 01:49:23 +0000497
njn83df0b62009-02-25 01:01:05 +0000498 else if VG_BOOL_CLO(arg, "--run-libc-freeres", VG_(clo_run_libc_freeres)) {}
499 else if VG_BOOL_CLO(arg, "--show-below-main", VG_(clo_show_below_main)) {}
500 else if VG_BOOL_CLO(arg, "--time-stamp", VG_(clo_time_stamp)) {}
501 else if VG_BOOL_CLO(arg, "--track-fds", VG_(clo_track_fds)) {}
502 else if VG_BOOL_CLO(arg, "--trace-children", VG_(clo_trace_children)) {}
503 else if VG_BOOL_CLO(arg, "--child-silent-after-fork",
504 VG_(clo_child_silent_after_fork)) {}
bart78bfc712011-12-08 16:14:59 +0000505 else if VG_STR_CLO(arg, "--fair-sched", tmp_str) {
506 if (VG_(strcmp)(tmp_str, "yes") == 0)
507 VG_(clo_fair_sched) = enable_fair_sched;
508 else if (VG_(strcmp)(tmp_str, "try") == 0)
509 VG_(clo_fair_sched) = try_fair_sched;
510 else if (VG_(strcmp)(tmp_str, "no") == 0)
511 VG_(clo_fair_sched) = disable_fair_sched;
512 else
513 VG_(fmsg_bad_option)(arg, "");
514
515 }
njn83df0b62009-02-25 01:01:05 +0000516 else if VG_BOOL_CLO(arg, "--trace-sched", VG_(clo_trace_sched)) {}
517 else if VG_BOOL_CLO(arg, "--trace-signals", VG_(clo_trace_signals)) {}
518 else if VG_BOOL_CLO(arg, "--trace-symtab", VG_(clo_trace_symtab)) {}
519 else if VG_STR_CLO (arg, "--trace-symtab-patt", VG_(clo_trace_symtab_patt)) {}
520 else if VG_BOOL_CLO(arg, "--trace-cfi", VG_(clo_trace_cfi)) {}
521 else if VG_XACT_CLO(arg, "--debug-dump=syms", VG_(clo_debug_dump_syms),
522 True) {}
523 else if VG_XACT_CLO(arg, "--debug-dump=line", VG_(clo_debug_dump_line),
524 True) {}
525 else if VG_XACT_CLO(arg, "--debug-dump=frames",
526 VG_(clo_debug_dump_frames), True) {}
527 else if VG_BOOL_CLO(arg, "--trace-redir", VG_(clo_trace_redir)) {}
sewardj95d86c02007-12-18 01:49:23 +0000528
njn83df0b62009-02-25 01:01:05 +0000529 else if VG_BOOL_CLO(arg, "--trace-syscalls", VG_(clo_trace_syscalls)) {}
530 else if VG_BOOL_CLO(arg, "--wait-for-gdb", VG_(clo_wait_for_gdb)) {}
531 else if VG_STR_CLO (arg, "--db-command", VG_(clo_db_command)) {}
njn83df0b62009-02-25 01:01:05 +0000532 else if VG_BOOL_CLO(arg, "--sym-offsets", VG_(clo_sym_offsets)) {}
533 else if VG_BOOL_CLO(arg, "--read-var-info", VG_(clo_read_var_info)) {}
sewardjf767d962007-02-12 17:47:14 +0000534
njn83df0b62009-02-25 01:01:05 +0000535 else if VG_INT_CLO (arg, "--dump-error", VG_(clo_dump_error)) {}
536 else if VG_INT_CLO (arg, "--input-fd", VG_(clo_input_fd)) {}
537 else if VG_INT_CLO (arg, "--sanity-level", VG_(clo_sanity_level)) {}
538 else if VG_BINT_CLO(arg, "--num-callers", VG_(clo_backtrace_size), 1,
539 VG_DEEPEST_BACKTRACE) {}
sewardjde4a1d02002-03-22 01:27:54 +0000540
njn83df0b62009-02-25 01:01:05 +0000541 else if VG_XACT_CLO(arg, "--smc-check=none", VG_(clo_smc_check),
542 Vg_SmcNone);
543 else if VG_XACT_CLO(arg, "--smc-check=stack", VG_(clo_smc_check),
544 Vg_SmcStack);
545 else if VG_XACT_CLO(arg, "--smc-check=all", VG_(clo_smc_check),
546 Vg_SmcAll);
sewardj6dbcc632011-06-07 21:39:28 +0000547 else if VG_XACT_CLO(arg, "--smc-check=all-non-file",
548 VG_(clo_smc_check),
549 Vg_SmcAllNonFile);
sewardjde4a1d02002-03-22 01:27:54 +0000550
njn97db7612009-08-04 02:32:55 +0000551 else if VG_STR_CLO (arg, "--kernel-variant", VG_(clo_kernel_variant)) {}
sewardj26412bd2005-07-07 10:05:05 +0000552
njn97db7612009-08-04 02:32:55 +0000553 else if VG_BOOL_CLO(arg, "--dsymutil", VG_(clo_dsymutil)) {}
njnf76d27a2009-05-28 01:53:07 +0000554
sewardj9ab64a42010-12-06 11:40:04 +0000555 else if VG_STR_CLO (arg, "--trace-children-skip",
556 VG_(clo_trace_children_skip)) {}
557 else if VG_STR_CLO (arg, "--trace-children-skip-by-arg",
558 VG_(clo_trace_children_skip_by_arg)) {}
sewardj06421272009-11-05 08:55:13 +0000559
njn83df0b62009-02-25 01:01:05 +0000560 else if VG_BINT_CLO(arg, "--vex-iropt-verbosity",
561 VG_(clo_vex_control).iropt_verbosity, 0, 10) {}
562 else if VG_BINT_CLO(arg, "--vex-iropt-level",
563 VG_(clo_vex_control).iropt_level, 0, 2) {}
564 else if VG_BOOL_CLO(arg, "--vex-iropt-precise-memory-exns",
565 VG_(clo_vex_control).iropt_precise_memory_exns) {}
566 else if VG_BINT_CLO(arg, "--vex-iropt-unroll-thresh",
567 VG_(clo_vex_control).iropt_unroll_thresh, 0, 400) {}
568 else if VG_BINT_CLO(arg, "--vex-guest-max-insns",
569 VG_(clo_vex_control).guest_max_insns, 1, 100) {}
570 else if VG_BINT_CLO(arg, "--vex-guest-chase-thresh",
571 VG_(clo_vex_control).guest_chase_thresh, 0, 99) {}
sewardj540cc4a2010-01-15 10:57:57 +0000572 else if VG_BOOL_CLO(arg, "--vex-guest-chase-cond",
573 VG_(clo_vex_control).guest_chase_cond) {}
sewardj94c8eb42008-09-19 20:13:39 +0000574
njn83df0b62009-02-25 01:01:05 +0000575 else if VG_INT_CLO(arg, "--log-fd", tmp_log_fd) {
576 log_to = VgLogTo_Fd;
sewardj738856f2009-07-15 14:48:32 +0000577 log_fsname_unexpanded = NULL;
578 }
579 else if VG_INT_CLO(arg, "--xml-fd", tmp_xml_fd) {
580 xml_to = VgLogTo_Fd;
581 xml_fsname_unexpanded = NULL;
sewardj4cf05692002-10-27 20:28:29 +0000582 }
583
sewardj738856f2009-07-15 14:48:32 +0000584 else if VG_STR_CLO(arg, "--log-file", log_fsname_unexpanded) {
njn83df0b62009-02-25 01:01:05 +0000585 log_to = VgLogTo_File;
sewardj4cf05692002-10-27 20:28:29 +0000586 }
sewardj738856f2009-07-15 14:48:32 +0000587 else if VG_STR_CLO(arg, "--xml-file", xml_fsname_unexpanded) {
588 xml_to = VgLogTo_File;
589 }
590
591 else if VG_STR_CLO(arg, "--log-socket", log_fsname_unexpanded) {
njn83df0b62009-02-25 01:01:05 +0000592 log_to = VgLogTo_Socket;
sewardj73cf3bc2002-11-03 03:20:15 +0000593 }
sewardj738856f2009-07-15 14:48:32 +0000594 else if VG_STR_CLO(arg, "--xml-socket", xml_fsname_unexpanded) {
595 xml_to = VgLogTo_Socket;
596 }
sewardj73cf3bc2002-11-03 03:20:15 +0000597
njn83df0b62009-02-25 01:01:05 +0000598 else if VG_STR_CLO(arg, "--xml-user-comment",
599 VG_(clo_xml_user_comment)) {}
sewardj768db0e2005-07-19 14:18:56 +0000600
njn83df0b62009-02-25 01:01:05 +0000601 else if VG_STR_CLO(arg, "--suppressions", tmp_str) {
sewardjde4a1d02002-03-22 01:27:54 +0000602 if (VG_(clo_n_suppressions) >= VG_CLO_MAX_SFILES) {
njnb1cc5d62010-07-06 04:05:23 +0000603 VG_(fmsg_bad_option)(arg,
604 "Too many suppression files specified.\n"
605 "Increase VG_CLO_MAX_SFILES and recompile.\n");
sewardjde4a1d02002-03-22 01:27:54 +0000606 }
njn83df0b62009-02-25 01:01:05 +0000607 VG_(clo_suppressions)[VG_(clo_n_suppressions)] = tmp_str;
sewardjde4a1d02002-03-22 01:27:54 +0000608 VG_(clo_n_suppressions)++;
609 }
sewardjde4a1d02002-03-22 01:27:54 +0000610
sewardj14cdbf82010-10-12 00:44:05 +0000611 else if VG_STR_CLO (arg, "--fullpath-after", tmp_str) {
612 if (VG_(clo_n_fullpath_after) >= VG_CLO_MAX_FULLPATH_AFTER) {
613 VG_(fmsg_bad_option)(arg,
614 "Too many --fullpath-after= specifications.\n"
615 "Increase VG_CLO_MAX_FULLPATH_AFTER and recompile.\n");
616 }
617 VG_(clo_fullpath_after)[VG_(clo_n_fullpath_after)] = tmp_str;
618 VG_(clo_n_fullpath_after)++;
619 }
620
sewardjf9ebc392010-05-09 22:30:43 +0000621 else if VG_STR_CLO(arg, "--require-text-symbol", tmp_str) {
622 if (VG_(clo_n_req_tsyms) >= VG_CLO_MAX_REQ_TSYMS) {
njnb1cc5d62010-07-06 04:05:23 +0000623 VG_(fmsg_bad_option)(arg,
624 "Too many --require-text-symbol= specifications.\n"
625 "Increase VG_CLO_MAX_REQ_TSYMS and recompile.\n");
sewardjf9ebc392010-05-09 22:30:43 +0000626 }
627 /* String needs to be of the form C?*C?*, where C is any
628 character, but is the same both times. Having it in this
629 form facilitates finding the boundary between the sopatt
630 and the fnpatt just by looking for the second occurrence
631 of C, without hardwiring any assumption about what C
632 is. */
633 Char patt[7];
634 Bool ok = True;
635 ok = tmp_str && VG_(strlen)(tmp_str) > 0;
636 if (ok) {
637 patt[0] = patt[3] = tmp_str[0];
638 patt[1] = patt[4] = '?';
639 patt[2] = patt[5] = '*';
640 patt[6] = 0;
641 ok = VG_(string_match)(patt, tmp_str);
642 }
643 if (!ok) {
njnb1cc5d62010-07-06 04:05:23 +0000644 VG_(fmsg_bad_option)(arg,
645 "Invalid --require-text-symbol= specification.\n");
sewardjf9ebc392010-05-09 22:30:43 +0000646 }
647 VG_(clo_req_tsyms)[VG_(clo_n_req_tsyms)] = tmp_str;
648 VG_(clo_n_req_tsyms)++;
649 }
650
sewardjfa8ec112005-01-19 11:55:34 +0000651 /* "stuvwxyz" --> stuvwxyz (binary) */
njn83df0b62009-02-25 01:01:05 +0000652 else if VG_STR_CLO(arg, "--trace-flags", tmp_str) {
sewardjfa8ec112005-01-19 11:55:34 +0000653 Int j;
sewardjfa8ec112005-01-19 11:55:34 +0000654
njn83df0b62009-02-25 01:01:05 +0000655 if (8 != VG_(strlen)(tmp_str)) {
njnb1cc5d62010-07-06 04:05:23 +0000656 VG_(fmsg_bad_option)(arg,
657 "--trace-flags argument must have 8 digits\n");
sewardjfa8ec112005-01-19 11:55:34 +0000658 }
659 for (j = 0; j < 8; j++) {
njn83df0b62009-02-25 01:01:05 +0000660 if ('0' == tmp_str[j]) { /* do nothing */ }
661 else if ('1' == tmp_str[j]) VG_(clo_trace_flags) |= (1 << (7-j));
sewardjfa8ec112005-01-19 11:55:34 +0000662 else {
njnb1cc5d62010-07-06 04:05:23 +0000663 VG_(fmsg_bad_option)(arg,
664 "--trace-flags argument can only contain 0s and 1s\n");
sewardjfa8ec112005-01-19 11:55:34 +0000665 }
666 }
667 }
668
669 /* "stuvwxyz" --> stuvwxyz (binary) */
njn83df0b62009-02-25 01:01:05 +0000670 else if VG_STR_CLO(arg, "--profile-flags", tmp_str) {
njn25e49d8e72002-09-23 09:36:25 +0000671 Int j;
njn25e49d8e72002-09-23 09:36:25 +0000672
njn83df0b62009-02-25 01:01:05 +0000673 if (8 != VG_(strlen)(tmp_str)) {
njnb1cc5d62010-07-06 04:05:23 +0000674 VG_(fmsg_bad_option)(arg,
675 "--profile-flags argument must have 8 digits\n");
njn25e49d8e72002-09-23 09:36:25 +0000676 }
sewardj8b635a42004-11-22 19:01:47 +0000677 for (j = 0; j < 8; j++) {
njn83df0b62009-02-25 01:01:05 +0000678 if ('0' == tmp_str[j]) { /* do nothing */ }
679 else if ('1' == tmp_str[j]) VG_(clo_profile_flags) |= (1 << (7-j));
njn25e49d8e72002-09-23 09:36:25 +0000680 else {
njnb1cc5d62010-07-06 04:05:23 +0000681 VG_(fmsg_bad_option)(arg,
682 "--profile-flags argument can only contain 0s and 1s\n");
njn25e49d8e72002-09-23 09:36:25 +0000683 }
684 }
685 }
sewardjde4a1d02002-03-22 01:27:54 +0000686
njn83df0b62009-02-25 01:01:05 +0000687 else if VG_INT_CLO (arg, "--trace-notbelow", VG_(clo_trace_notbelow)) {}
sewardjc771b292004-11-30 18:55:21 +0000688
njn83df0b62009-02-25 01:01:05 +0000689 else if VG_XACT_CLO(arg, "--gen-suppressions=no",
690 VG_(clo_gen_suppressions), 0) {}
691 else if VG_XACT_CLO(arg, "--gen-suppressions=yes",
692 VG_(clo_gen_suppressions), 1) {}
693 else if VG_XACT_CLO(arg, "--gen-suppressions=all",
694 VG_(clo_gen_suppressions), 2) {}
sewardjd153fae2005-01-10 17:24:47 +0000695
nethercote71980f02004-01-24 18:18:54 +0000696 else if ( ! VG_(needs).command_line_options
njn51d827b2005-05-09 01:02:08 +0000697 || ! VG_TDICT_CALL(tool_process_cmd_line_option, arg) ) {
njnb1cc5d62010-07-06 04:05:23 +0000698 VG_(fmsg_bad_option)(arg, "");
njn25e49d8e72002-09-23 09:36:25 +0000699 }
sewardjde4a1d02002-03-22 01:27:54 +0000700 }
701
sewardj738856f2009-07-15 14:48:32 +0000702 /* END command-line processing loop */
703
florianb985e2d2011-09-29 03:03:45 +0000704 /* Determine the path prefix for vgdb */
705 if (VG_(clo_vgdb_prefix) == NULL)
706 VG_(clo_vgdb_prefix) = VG_(vgdb_prefix_default)();
707
sewardj998d40d2004-12-06 14:24:52 +0000708 /* Make VEX control parameters sane */
709
710 if (VG_(clo_vex_control).guest_chase_thresh
711 >= VG_(clo_vex_control).guest_max_insns)
712 VG_(clo_vex_control).guest_chase_thresh
713 = VG_(clo_vex_control).guest_max_insns - 1;
714
715 if (VG_(clo_vex_control).guest_chase_thresh < 0)
716 VG_(clo_vex_control).guest_chase_thresh = 0;
717
718 /* Check various option values */
nethercote27fec902004-06-16 21:26:32 +0000719
njnf9ebf672003-05-12 21:41:30 +0000720 if (VG_(clo_verbosity) < 0)
sewardjde4a1d02002-03-22 01:27:54 +0000721 VG_(clo_verbosity) = 0;
722
sewardj3b290482011-05-06 21:02:55 +0000723 VG_(dyn_vgdb_error) = VG_(clo_vgdb_error);
724
njnbe9b47b2005-05-15 16:22:58 +0000725 if (VG_(clo_gen_suppressions) > 0 &&
726 !VG_(needs).core_errors && !VG_(needs).tool_errors) {
njnb1cc5d62010-07-06 04:05:23 +0000727 VG_(fmsg_bad_option)("--gen-suppressions=yes",
728 "Can't use --gen-suppressions= with %s\n"
729 "because it doesn't generate errors.\n", VG_(details).name);
njnbe9b47b2005-05-15 16:22:58 +0000730 }
731
sewardj738856f2009-07-15 14:48:32 +0000732 /* If XML output is requested, check that the tool actually
733 supports it. */
734 if (VG_(clo_xml) && !VG_(needs).xml_output) {
735 VG_(clo_xml) = False;
njnb1cc5d62010-07-06 04:05:23 +0000736 VG_(fmsg_bad_option)("--xml=yes",
sewardj738856f2009-07-15 14:48:32 +0000737 "%s does not support XML output.\n", VG_(details).name);
sewardj738856f2009-07-15 14:48:32 +0000738 /*NOTREACHED*/
739 }
740
741 vg_assert( VG_(clo_gen_suppressions) >= 0 );
742 vg_assert( VG_(clo_gen_suppressions) <= 2 );
743
sewardj71bc3cb2005-05-19 00:25:45 +0000744 /* If we've been asked to emit XML, mash around various other
745 options so as to constrain the output somewhat, and to remove
sewardj738856f2009-07-15 14:48:32 +0000746 any need for user input during the run.
747 */
sewardj71bc3cb2005-05-19 00:25:45 +0000748 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +0000749
750 /* We can't allow --gen-suppressions=yes, since that requires us
751 to print the error and then ask the user if she wants a
752 suppression for it, but in XML mode we won't print it until
753 we know whether we also need to print a suppression. Hence a
754 circular dependency. So disallow this.
755 (--gen-suppressions=all is still OK since we don't need any
756 user interaction in this case.) */
757 if (VG_(clo_gen_suppressions) == 1) {
njnb1cc5d62010-07-06 04:05:23 +0000758 VG_(fmsg_bad_option)(
759 "--xml=yes together with --gen-suppressions=yes",
760 "When --xml=yes is specified, --gen-suppressions=no\n"
761 "or --gen-suppressions=all is allowed, but not "
sewardj738856f2009-07-15 14:48:32 +0000762 "--gen-suppressions=yes.\n");
sewardj738856f2009-07-15 14:48:32 +0000763 }
764
765 /* We can't allow DB attaching (or we maybe could, but results
766 could be chaotic ..) since it requires user input. Hence
767 disallow. */
768 if (VG_(clo_db_attach)) {
njnb1cc5d62010-07-06 04:05:23 +0000769 VG_(fmsg_bad_option)(
770 "--xml=yes together with --db-attach=yes",
771 "--db-attach=yes is not allowed with --xml=yes\n"
772 "because it would require user input.\n");
sewardj738856f2009-07-15 14:48:32 +0000773 }
774
775 /* Disallow dump_error in XML mode; sounds like a recipe for
776 chaos. No big deal; dump_error is a flag for debugging V
777 itself. */
778 if (VG_(clo_dump_error) > 0) {
njnb1cc5d62010-07-06 04:05:23 +0000779 VG_(fmsg_bad_option)("--xml=yes together with --dump-error", "");
sewardj738856f2009-07-15 14:48:32 +0000780 }
781
sewardj71bc3cb2005-05-19 00:25:45 +0000782 /* Disable error limits (this might be a bad idea!) */
783 VG_(clo_error_limit) = False;
784 /* Disable emulation warnings */
sewardj738856f2009-07-15 14:48:32 +0000785
sewardj71bc3cb2005-05-19 00:25:45 +0000786 /* Also, we want to set options for the leak checker, but that
787 will have to be done in Memcheck's flag-handling code, not
788 here. */
789 }
790
njnbe9b47b2005-05-15 16:22:58 +0000791 /* All non-logging-related options have been checked. If the logging
792 option specified is ok, we can switch to it, as we know we won't
793 have to generate any other command-line-related error messages.
794 (So far we should be still attached to stderr, so we can show on
795 the terminal any problems to do with processing command line
796 opts.)
797
sewardj738856f2009-07-15 14:48:32 +0000798 So set up logging now. After this is done, VG_(log_output_sink)
799 and (if relevant) VG_(xml_output_sink) should be connected to
800 whatever sink has been selected, and we indiscriminately chuck
801 stuff into it without worrying what the nature of it is. Oh the
802 wonder of Unix streams. */
sewardj4cf05692002-10-27 20:28:29 +0000803
sewardj738856f2009-07-15 14:48:32 +0000804 vg_assert(VG_(log_output_sink).fd == 2 /* stderr */);
805 vg_assert(VG_(log_output_sink).is_socket == False);
806 vg_assert(VG_(clo_log_fname_expanded) == NULL);
807
808 vg_assert(VG_(xml_output_sink).fd == -1 /* disabled */);
809 vg_assert(VG_(xml_output_sink).is_socket == False);
810 vg_assert(VG_(clo_xml_fname_expanded) == NULL);
811
812 /* --- set up the normal text output channel --- */
sewardj4cf05692002-10-27 20:28:29 +0000813
njnbe9b47b2005-05-15 16:22:58 +0000814 switch (log_to) {
sewardj73cf3bc2002-11-03 03:20:15 +0000815
sewardj4cf05692002-10-27 20:28:29 +0000816 case VgLogTo_Fd:
sewardj738856f2009-07-15 14:48:32 +0000817 vg_assert(log_fsname_unexpanded == NULL);
sewardj4cf05692002-10-27 20:28:29 +0000818 break;
sewardj73cf3bc2002-11-03 03:20:15 +0000819
sewardj4cf05692002-10-27 20:28:29 +0000820 case VgLogTo_File: {
njn374a36d2007-11-23 01:41:32 +0000821 Char* logfilename;
jsgff3c3f1a2003-10-14 22:13:28 +0000822
sewardj738856f2009-07-15 14:48:32 +0000823 vg_assert(log_fsname_unexpanded != NULL);
824 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
jsgff3c3f1a2003-10-14 22:13:28 +0000825
njn374a36d2007-11-23 01:41:32 +0000826 // Nb: we overwrite an existing file of this name without asking
827 // any questions.
sewardj738856f2009-07-15 14:48:32 +0000828 logfilename = VG_(expand_file_name)("--log-file",
829 log_fsname_unexpanded);
njn374a36d2007-11-23 01:41:32 +0000830 sres = VG_(open)(logfilename,
njnda033f52005-12-19 21:27:58 +0000831 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
832 VKI_S_IRUSR|VKI_S_IWUSR);
njncda2f0f2009-05-18 02:12:08 +0000833 if (!sr_isError(sres)) {
834 tmp_log_fd = sr_Res(sres);
sewardj738856f2009-07-15 14:48:32 +0000835 VG_(clo_log_fname_expanded) = logfilename;
njnbe9b47b2005-05-15 16:22:58 +0000836 } else {
njnb1cc5d62010-07-06 04:05:23 +0000837 VG_(fmsg)("can't create log file '%s': %s\n",
838 logfilename, VG_(strerror)(sr_Err(sres)));
839 VG_(exit)(1);
sewardj603d4102005-01-11 14:01:02 +0000840 /*NOTREACHED*/
njn374a36d2007-11-23 01:41:32 +0000841 }
sewardj738856f2009-07-15 14:48:32 +0000842 break;
sewardj73cf3bc2002-11-03 03:20:15 +0000843 }
844
845 case VgLogTo_Socket: {
sewardj738856f2009-07-15 14:48:32 +0000846 vg_assert(log_fsname_unexpanded != NULL);
847 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
848 tmp_log_fd = VG_(connect_via_socket)( log_fsname_unexpanded );
njnda033f52005-12-19 21:27:58 +0000849 if (tmp_log_fd == -1) {
njnb1cc5d62010-07-06 04:05:23 +0000850 VG_(fmsg)("Invalid --log-socket spec of '%s'\n",
851 log_fsname_unexpanded);
852 VG_(exit)(1);
njnbe9b47b2005-05-15 16:22:58 +0000853 /*NOTREACHED*/
sewardj4cf05692002-10-27 20:28:29 +0000854 }
njnda033f52005-12-19 21:27:58 +0000855 if (tmp_log_fd == -2) {
njnb1cc5d62010-07-06 04:05:23 +0000856 VG_(umsg)("failed to connect to logging server '%s'.\n"
857 "Log messages will sent to stderr instead.\n",
858 log_fsname_unexpanded );
859
sewardj570f8902002-11-03 11:44:36 +0000860 /* We don't change anything here. */
sewardj738856f2009-07-15 14:48:32 +0000861 vg_assert(VG_(log_output_sink).fd == 2);
njnda033f52005-12-19 21:27:58 +0000862 tmp_log_fd = 2;
sewardj570f8902002-11-03 11:44:36 +0000863 } else {
njnda033f52005-12-19 21:27:58 +0000864 vg_assert(tmp_log_fd > 0);
sewardj738856f2009-07-15 14:48:32 +0000865 VG_(log_output_sink).is_socket = True;
sewardj570f8902002-11-03 11:44:36 +0000866 }
sewardj73cf3bc2002-11-03 03:20:15 +0000867 break;
868 }
sewardj4cf05692002-10-27 20:28:29 +0000869 }
870
sewardj738856f2009-07-15 14:48:32 +0000871 /* --- set up the XML output channel --- */
sewardj71bc3cb2005-05-19 00:25:45 +0000872
sewardj738856f2009-07-15 14:48:32 +0000873 switch (xml_to) {
874
875 case VgLogTo_Fd:
876 vg_assert(xml_fsname_unexpanded == NULL);
877 break;
878
879 case VgLogTo_File: {
880 Char* xmlfilename;
881
882 vg_assert(xml_fsname_unexpanded != NULL);
883 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
884
885 // Nb: we overwrite an existing file of this name without asking
886 // any questions.
887 xmlfilename = VG_(expand_file_name)("--xml-file",
888 xml_fsname_unexpanded);
889 sres = VG_(open)(xmlfilename,
890 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
891 VKI_S_IRUSR|VKI_S_IWUSR);
892 if (!sr_isError(sres)) {
893 tmp_xml_fd = sr_Res(sres);
894 VG_(clo_xml_fname_expanded) = xmlfilename;
895 /* strdup here is probably paranoid overkill, but ... */
896 *xml_fname_unexpanded = VG_(strdup)( "main.mpclo.2",
897 xml_fsname_unexpanded );
898 } else {
njnb1cc5d62010-07-06 04:05:23 +0000899 VG_(fmsg)("can't create XML file '%s': %s\n",
900 xmlfilename, VG_(strerror)(sr_Err(sres)));
901 VG_(exit)(1);
sewardj738856f2009-07-15 14:48:32 +0000902 /*NOTREACHED*/
903 }
904 break;
905 }
906
907 case VgLogTo_Socket: {
908 vg_assert(xml_fsname_unexpanded != NULL);
909 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
910 tmp_xml_fd = VG_(connect_via_socket)( xml_fsname_unexpanded );
911 if (tmp_xml_fd == -1) {
njnb1cc5d62010-07-06 04:05:23 +0000912 VG_(fmsg)("Invalid --xml-socket spec of '%s'\n",
913 xml_fsname_unexpanded );
914 VG_(exit)(1);
sewardj738856f2009-07-15 14:48:32 +0000915 /*NOTREACHED*/
916 }
917 if (tmp_xml_fd == -2) {
njnb1cc5d62010-07-06 04:05:23 +0000918 VG_(umsg)("failed to connect to XML logging server '%s'.\n"
919 "XML output will sent to stderr instead.\n",
920 xml_fsname_unexpanded);
sewardj738856f2009-07-15 14:48:32 +0000921 /* We don't change anything here. */
922 vg_assert(VG_(xml_output_sink).fd == 2);
923 tmp_xml_fd = 2;
924 } else {
925 vg_assert(tmp_xml_fd > 0);
926 VG_(xml_output_sink).is_socket = True;
927 }
928 break;
929 }
sewardj71bc3cb2005-05-19 00:25:45 +0000930 }
931
sewardj738856f2009-07-15 14:48:32 +0000932 /* If we've got this far, and XML mode was requested, but no XML
933 output channel appears to have been specified, just stop. We
934 could continue, and XML output will simply vanish into nowhere,
935 but that is likely to confuse the hell out of users, which is
936 distinctly Ungood. */
937 if (VG_(clo_xml) && tmp_xml_fd == -1) {
njnb1cc5d62010-07-06 04:05:23 +0000938 VG_(fmsg_bad_option)(
939 "--xml=yes, but no XML destination specified",
sewardj738856f2009-07-15 14:48:32 +0000940 "--xml=yes has been specified, but there is no XML output\n"
941 "destination. You must specify an XML output destination\n"
njnb1cc5d62010-07-06 04:05:23 +0000942 "using --xml-fd, --xml-file or --xml-socket.\n"
943 );
sewardj738856f2009-07-15 14:48:32 +0000944 }
945
946 // Finalise the output fds: the log fd ..
947
njnda033f52005-12-19 21:27:58 +0000948 if (tmp_log_fd >= 0) {
sewardj738856f2009-07-15 14:48:32 +0000949 // Move log_fd into the safe range, so it doesn't conflict with
950 // any app fds.
njnda033f52005-12-19 21:27:58 +0000951 tmp_log_fd = VG_(fcntl)(tmp_log_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
952 if (tmp_log_fd < 0) {
sewardj738856f2009-07-15 14:48:32 +0000953 VG_(message)(Vg_UserMsg, "valgrind: failed to move logfile fd "
954 "into safe range, using stderr\n");
955 VG_(log_output_sink).fd = 2; // stderr
956 VG_(log_output_sink).is_socket = False;
njnda033f52005-12-19 21:27:58 +0000957 } else {
sewardj738856f2009-07-15 14:48:32 +0000958 VG_(log_output_sink).fd = tmp_log_fd;
959 VG_(fcntl)(VG_(log_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
njnda033f52005-12-19 21:27:58 +0000960 }
961 } else {
962 // If they said --log-fd=-1, don't print anything. Plausible for use in
963 // regression testing suites that use client requests to count errors.
sewardj738856f2009-07-15 14:48:32 +0000964 VG_(log_output_sink).fd = -1;
965 VG_(log_output_sink).is_socket = False;
jsgf855d93d2003-10-13 22:26:55 +0000966 }
967
sewardj738856f2009-07-15 14:48:32 +0000968 // Finalise the output fds: and the XML fd ..
969
970 if (tmp_xml_fd >= 0) {
971 // Move xml_fd into the safe range, so it doesn't conflict with
972 // any app fds.
973 tmp_xml_fd = VG_(fcntl)(tmp_xml_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
974 if (tmp_xml_fd < 0) {
975 VG_(message)(Vg_UserMsg, "valgrind: failed to move XML file fd "
976 "into safe range, using stderr\n");
977 VG_(xml_output_sink).fd = 2; // stderr
978 VG_(xml_output_sink).is_socket = False;
979 } else {
980 VG_(xml_output_sink).fd = tmp_xml_fd;
981 VG_(fcntl)(VG_(xml_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
982 }
983 } else {
984 // If they said --xml-fd=-1, don't print anything. Plausible for use in
985 // regression testing suites that use client requests to count errors.
986 VG_(xml_output_sink).fd = -1;
987 VG_(xml_output_sink).is_socket = False;
988 }
989
990 // Suppressions related stuff
991
sewardj45f4e7c2005-09-27 19:20:21 +0000992 if (VG_(clo_n_suppressions) < VG_CLO_MAX_SFILES-1 &&
993 (VG_(needs).core_errors || VG_(needs).tool_errors)) {
994 /* If we haven't reached the max number of suppressions, load
995 the default one. */
996 static const Char default_supp[] = "default.supp";
997 Int len = VG_(strlen)(VG_(libdir)) + 1 + sizeof(default_supp);
sewardj738856f2009-07-15 14:48:32 +0000998 Char *buf = VG_(arena_malloc)(VG_AR_CORE, "main.mpclo.3", len);
sewardj45f4e7c2005-09-27 19:20:21 +0000999 VG_(sprintf)(buf, "%s/%s", VG_(libdir), default_supp);
1000 VG_(clo_suppressions)[VG_(clo_n_suppressions)] = buf;
1001 VG_(clo_n_suppressions)++;
1002 }
sewardjde4a1d02002-03-22 01:27:54 +00001003
sewardj738856f2009-07-15 14:48:32 +00001004 *logging_to_fd = log_to == VgLogTo_Fd || log_to == VgLogTo_Socket;
sewardj45f4e7c2005-09-27 19:20:21 +00001005}
1006
sewardj4efbaa72008-06-04 06:51:58 +00001007// Write the name and value of log file qualifiers to the xml file.
1008static void print_file_vars(Char* format)
1009{
1010 Int i = 0;
1011
1012 while (format[i]) {
1013 if (format[i] == '%') {
1014 // We saw a '%'. What's next...
1015 i++;
1016 if ('q' == format[i]) {
1017 i++;
1018 if ('{' == format[i]) {
1019 // Get the env var name, print its contents.
1020 Char* qualname;
1021 Char* qual;
1022 i++;
1023 qualname = &format[i];
1024 while (True) {
1025 if ('}' == format[i]) {
1026 // Temporarily replace the '}' with NUL to extract var
1027 // name.
1028 format[i] = 0;
1029 qual = VG_(getenv)(qualname);
1030 break;
1031 }
1032 i++;
1033 }
1034
bartb3af9cf2011-10-06 19:08:37 +00001035 VG_(printf_xml)(
1036 "<logfilequalifier> <var>%pS</var> "
1037 "<value>%pS</value> </logfilequalifier>\n",
sewardj7ca100d2009-08-15 23:05:34 +00001038 qualname,qual
1039 );
sewardj4efbaa72008-06-04 06:51:58 +00001040 format[i] = '}';
1041 i++;
1042 }
1043 }
1044 } else {
1045 i++;
1046 }
1047 }
1048}
1049
sewardj45f4e7c2005-09-27 19:20:21 +00001050
1051/*====================================================================*/
1052/*=== Printing the preamble ===*/
1053/*====================================================================*/
1054
barta92677a2011-10-22 08:24:32 +00001055// Print the argument, escaping any chars that require it.
1056static void umsg_arg(const Char* arg)
njnf8a11cf2009-08-02 23:03:06 +00001057{
1058 SizeT len = VG_(strlen)(arg);
1059 Char* special = " \\<>";
1060 Int i;
1061 for (i = 0; i < len; i++) {
1062 if (VG_(strchr)(special, arg[i])) {
barta92677a2011-10-22 08:24:32 +00001063 VG_(umsg)("\\"); // escape with a backslash if necessary
njnf8a11cf2009-08-02 23:03:06 +00001064 }
barta92677a2011-10-22 08:24:32 +00001065 VG_(umsg)("%c", arg[i]);
njnf8a11cf2009-08-02 23:03:06 +00001066 }
1067}
1068
barta92677a2011-10-22 08:24:32 +00001069// Send output to the XML-stream and escape any XML meta-characters.
1070static void xml_arg(const Char* arg)
1071{
1072 VG_(printf_xml)("%pS", arg);
1073}
1074
sewardj45f4e7c2005-09-27 19:20:21 +00001075/* Ok, the logging sink is running now. Print a suitable preamble.
1076 If logging to file or a socket, write details of parent PID and
1077 command line args, to help people trying to interpret the
1078 results of a run which encompasses multiple processes. */
sewardj738856f2009-07-15 14:48:32 +00001079static void print_preamble ( Bool logging_to_fd,
1080 Char* xml_fname_unexpanded,
1081 const HChar* toolname )
sewardj45f4e7c2005-09-27 19:20:21 +00001082{
sewardj738856f2009-07-15 14:48:32 +00001083 Int i;
tom60a4b0b2005-10-12 10:45:27 +00001084 HChar* xpre = VG_(clo_xml) ? " <line>" : "";
1085 HChar* xpost = VG_(clo_xml) ? "</line>" : "";
sewardj738856f2009-07-15 14:48:32 +00001086 UInt (*umsg_or_xml)( const HChar*, ... )
1087 = VG_(clo_xml) ? VG_(printf_xml) : VG_(umsg);
tom60a4b0b2005-10-12 10:45:27 +00001088
bart4d4b6442011-10-22 09:42:05 +00001089 void (*umsg_or_xml_arg)( const Char* )
barta92677a2011-10-22 08:24:32 +00001090 = VG_(clo_xml) ? xml_arg : umsg_arg;
1091
sewardj14c7cc52007-02-25 15:08:24 +00001092 vg_assert( VG_(args_for_client) );
1093 vg_assert( VG_(args_for_valgrind) );
sewardj99a2ceb2007-11-09 12:30:36 +00001094 vg_assert( toolname );
sewardj14c7cc52007-02-25 15:08:24 +00001095
sewardj71bc3cb2005-05-19 00:25:45 +00001096 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +00001097 VG_(printf_xml)("<?xml version=\"1.0\"?>\n");
1098 VG_(printf_xml)("\n");
1099 VG_(printf_xml)("<valgrindoutput>\n");
1100 VG_(printf_xml)("\n");
1101 VG_(printf_xml)("<protocolversion>4</protocolversion>\n");
1102 VG_(printf_xml)("<protocoltool>%s</protocoltool>\n", toolname);
1103 VG_(printf_xml)("\n");
sewardj71bc3cb2005-05-19 00:25:45 +00001104 }
1105
sewardj738856f2009-07-15 14:48:32 +00001106 if (VG_(clo_xml) || VG_(clo_verbosity > 0)) {
sewardjd7bddad2005-06-13 16:48:32 +00001107
1108 if (VG_(clo_xml))
sewardj738856f2009-07-15 14:48:32 +00001109 VG_(printf_xml)("<preamble>\n");
sewardjd7bddad2005-06-13 16:48:32 +00001110
nethercote996901a2004-08-03 13:29:09 +00001111 /* Tool details */
bartb3af9cf2011-10-06 19:08:37 +00001112 umsg_or_xml( VG_(clo_xml) ? "%s%pS%pS%pS, %pS%s\n" : "%s%s%s%s, %s%s\n",
sewardj71bc3cb2005-05-19 00:25:45 +00001113 xpre,
njnd04b7c62002-10-03 14:05:52 +00001114 VG_(details).name,
njnb9c427c2004-12-01 14:14:42 +00001115 NULL == VG_(details).version ? "" : "-",
njnd04b7c62002-10-03 14:05:52 +00001116 NULL == VG_(details).version
1117 ? (Char*)"" : VG_(details).version,
sewardj71bc3cb2005-05-19 00:25:45 +00001118 VG_(details).description,
sewardj738856f2009-07-15 14:48:32 +00001119 xpost );
sewardj99a2ceb2007-11-09 12:30:36 +00001120
njn10b9aea2009-07-14 06:55:05 +00001121 if (VG_(strlen)(toolname) >= 4 && VG_STREQN(4, toolname, "exp-")) {
sewardj738856f2009-07-15 14:48:32 +00001122 umsg_or_xml(
njnb6267bd2009-08-12 00:14:16 +00001123 "%sNOTE: This is an Experimental-Class Valgrind Tool%s\n",
sewardj99a2ceb2007-11-09 12:30:36 +00001124 xpre, xpost
1125 );
1126 }
1127
bartb3af9cf2011-10-06 19:08:37 +00001128 umsg_or_xml( VG_(clo_xml) ? "%s%pS%s\n" : "%s%s%s\n",
sewardj743a2082010-07-23 17:03:22 +00001129 xpre, VG_(details).copyright_author, xpost );
sewardj3b2736a2002-03-24 12:18:35 +00001130
njnd04b7c62002-10-03 14:05:52 +00001131 /* Core details */
sewardj738856f2009-07-15 14:48:32 +00001132 umsg_or_xml(
njnf73d87f2009-07-24 04:47:04 +00001133 "%sUsing Valgrind-%s and LibVEX; rerun with -h for copyright info%s\n",
1134 xpre, VERSION, xpost
sewardj738856f2009-07-15 14:48:32 +00001135 );
sewardj45f4e7c2005-09-27 19:20:21 +00001136
njnf3977a32009-08-04 00:27:56 +00001137 // Print the command line. At one point we wrapped at 80 chars and
1138 // printed a '\' as a line joiner, but that makes it hard to cut and
1139 // paste the command line (because of the "==pid==" prefixes), so we now
1140 // favour utility and simplicity over aesthetics.
1141 umsg_or_xml("%sCommand: ", xpre);
njn53162bf2009-07-29 23:34:49 +00001142 if (VG_(args_the_exename))
barta92677a2011-10-22 08:24:32 +00001143 umsg_or_xml_arg(VG_(args_the_exename));
1144
njn53162bf2009-07-29 23:34:49 +00001145 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1146 HChar* s = *(HChar**)VG_(indexXA)( VG_(args_for_client), i );
njnf8a11cf2009-08-02 23:03:06 +00001147 umsg_or_xml(" ");
barta92677a2011-10-22 08:24:32 +00001148 umsg_or_xml_arg(s);
njn53162bf2009-07-29 23:34:49 +00001149 }
njnf3977a32009-08-04 00:27:56 +00001150 umsg_or_xml("%s\n", xpost);
njn53162bf2009-07-29 23:34:49 +00001151
sewardjd7bddad2005-06-13 16:48:32 +00001152 if (VG_(clo_xml))
sewardj738856f2009-07-15 14:48:32 +00001153 VG_(printf_xml)("</preamble>\n");
njnd04b7c62002-10-03 14:05:52 +00001154 }
1155
njnb6267bd2009-08-12 00:14:16 +00001156 // Print the parent PID, and other stuff, if necessary.
sewardj45f4e7c2005-09-27 19:20:21 +00001157 if (!VG_(clo_xml) && VG_(clo_verbosity) > 0 && !logging_to_fd) {
njn305dc002009-07-30 23:36:43 +00001158 VG_(umsg)("Parent PID: %d\n", VG_(getppid)());
sewardj4cf05692002-10-27 20:28:29 +00001159 }
sewardj71bc3cb2005-05-19 00:25:45 +00001160 else
1161 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +00001162 VG_(printf_xml)("\n");
1163 VG_(printf_xml)("<pid>%d</pid>\n", VG_(getpid)());
1164 VG_(printf_xml)("<ppid>%d</ppid>\n", VG_(getppid)());
bartb3af9cf2011-10-06 19:08:37 +00001165 VG_(printf_xml)("<tool>%pS</tool>\n", toolname);
sewardj738856f2009-07-15 14:48:32 +00001166 if (xml_fname_unexpanded)
1167 print_file_vars(xml_fname_unexpanded);
sewardj768db0e2005-07-19 14:18:56 +00001168 if (VG_(clo_xml_user_comment)) {
1169 /* Note: the user comment itself is XML and is therefore to
1170 be passed through verbatim (%s) rather than escaped
bartb3af9cf2011-10-06 19:08:37 +00001171 (%pS). */
sewardj738856f2009-07-15 14:48:32 +00001172 VG_(printf_xml)("<usercomment>%s</usercomment>\n",
1173 VG_(clo_xml_user_comment));
sewardj768db0e2005-07-19 14:18:56 +00001174 }
sewardj738856f2009-07-15 14:48:32 +00001175 VG_(printf_xml)("\n");
1176 VG_(printf_xml)("<args>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001177
sewardj738856f2009-07-15 14:48:32 +00001178 VG_(printf_xml)(" <vargv>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001179 if (VG_(name_of_launcher))
bartb3af9cf2011-10-06 19:08:37 +00001180 VG_(printf_xml)(" <exe>%pS</exe>\n",
sewardj738856f2009-07-15 14:48:32 +00001181 VG_(name_of_launcher));
sewardj125fd4f2007-03-08 19:56:14 +00001182 else
bartb3af9cf2011-10-06 19:08:37 +00001183 VG_(printf_xml)(" <exe>%pS</exe>\n",
njnb1cc5d62010-07-06 04:05:23 +00001184 "(launcher name unknown)");
sewardj14c7cc52007-02-25 15:08:24 +00001185 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
bartb3af9cf2011-10-06 19:08:37 +00001186 VG_(printf_xml)(
1187 " <arg>%pS</arg>\n",
sewardj738856f2009-07-15 14:48:32 +00001188 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1189 );
sewardjb8a3dac2005-07-19 12:39:11 +00001190 }
sewardj738856f2009-07-15 14:48:32 +00001191 VG_(printf_xml)(" </vargv>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001192
sewardj738856f2009-07-15 14:48:32 +00001193 VG_(printf_xml)(" <argv>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001194 if (VG_(args_the_exename))
bartb3af9cf2011-10-06 19:08:37 +00001195 VG_(printf_xml)(" <exe>%pS</exe>\n",
sewardj738856f2009-07-15 14:48:32 +00001196 VG_(args_the_exename));
sewardj14c7cc52007-02-25 15:08:24 +00001197 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
bartb3af9cf2011-10-06 19:08:37 +00001198 VG_(printf_xml)(
1199 " <arg>%pS</arg>\n",
sewardj738856f2009-07-15 14:48:32 +00001200 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1201 );
sewardj8665d8e2005-06-01 17:35:23 +00001202 }
sewardj738856f2009-07-15 14:48:32 +00001203 VG_(printf_xml)(" </argv>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001204
sewardj738856f2009-07-15 14:48:32 +00001205 VG_(printf_xml)("</args>\n");
sewardj71bc3cb2005-05-19 00:25:45 +00001206 }
sewardj4cf05692002-10-27 20:28:29 +00001207
njnb6267bd2009-08-12 00:14:16 +00001208 // Last thing in the preamble is a blank line.
sewardj738856f2009-07-15 14:48:32 +00001209 if (VG_(clo_xml))
1210 VG_(printf_xml)("\n");
njnb6267bd2009-08-12 00:14:16 +00001211 else if (VG_(clo_verbosity) > 0)
1212 VG_(umsg)("\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001213
sewardjde4a1d02002-03-22 01:27:54 +00001214 if (VG_(clo_verbosity) > 1) {
sewardj92645592005-07-23 09:18:34 +00001215 SysRes fd;
sewardj1f0bbc72005-11-16 03:51:02 +00001216 VexArch vex_arch;
1217 VexArchInfo vex_archinfo;
sewardj45f4e7c2005-09-27 19:20:21 +00001218 if (!logging_to_fd)
sewardj738856f2009-07-15 14:48:32 +00001219 VG_(message)(Vg_DebugMsg, "\n");
njna3311642009-08-10 01:29:14 +00001220 VG_(message)(Vg_DebugMsg, "Valgrind options:\n");
sewardj14c7cc52007-02-25 15:08:24 +00001221 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
1222 VG_(message)(Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +00001223 " %s\n",
sewardj14c7cc52007-02-25 15:08:24 +00001224 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ));
sewardjde4a1d02002-03-22 01:27:54 +00001225 }
nethercotea70f7352004-04-18 12:08:46 +00001226
sewardj738856f2009-07-15 14:48:32 +00001227 VG_(message)(Vg_DebugMsg, "Contents of /proc/version:\n");
nethercotea70f7352004-04-18 12:08:46 +00001228 fd = VG_(open) ( "/proc/version", VKI_O_RDONLY, 0 );
njncda2f0f2009-05-18 02:12:08 +00001229 if (sr_isError(fd)) {
sewardj738856f2009-07-15 14:48:32 +00001230 VG_(message)(Vg_DebugMsg, " can't open /proc/version\n");
nethercotea70f7352004-04-18 12:08:46 +00001231 } else {
sewardj71bc3cb2005-05-19 00:25:45 +00001232# define BUF_LEN 256
nethercotea70f7352004-04-18 12:08:46 +00001233 Char version_buf[BUF_LEN];
njnf3977a32009-08-04 00:27:56 +00001234 Int n = VG_(read) ( sr_Res(fd), version_buf, BUF_LEN );
1235 vg_assert(n <= BUF_LEN);
1236 if (n > 0) {
1237 version_buf[n-1] = '\0';
sewardj738856f2009-07-15 14:48:32 +00001238 VG_(message)(Vg_DebugMsg, " %s\n", version_buf);
nethercotea70f7352004-04-18 12:08:46 +00001239 } else {
sewardj738856f2009-07-15 14:48:32 +00001240 VG_(message)(Vg_DebugMsg, " (empty?)\n");
nethercotea70f7352004-04-18 12:08:46 +00001241 }
njncda2f0f2009-05-18 02:12:08 +00001242 VG_(close)(sr_Res(fd));
sewardj71bc3cb2005-05-19 00:25:45 +00001243# undef BUF_LEN
nethercotea70f7352004-04-18 12:08:46 +00001244 }
sewardj1f0bbc72005-11-16 03:51:02 +00001245
1246 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
sewardje3121f32006-01-27 21:23:23 +00001247 VG_(message)(
1248 Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +00001249 "Arch and hwcaps: %s, %s\n",
sewardje3121f32006-01-27 21:23:23 +00001250 LibVEX_ppVexArch ( vex_arch ),
1251 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1252 );
sewardje66f2e02006-12-30 17:45:08 +00001253 VG_(message)(
1254 Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +00001255 "Page sizes: currently %d, max supported %d\n",
sewardje66f2e02006-12-30 17:45:08 +00001256 (Int)VKI_PAGE_SIZE, (Int)VKI_MAX_PAGE_SIZE
1257 );
sewardj738856f2009-07-15 14:48:32 +00001258 VG_(message)(Vg_DebugMsg,
1259 "Valgrind library directory: %s\n", VG_(libdir));
sewardjde4a1d02002-03-22 01:27:54 +00001260 }
nethercotef6a1d502004-08-09 12:21:57 +00001261}
1262
sewardjde4a1d02002-03-22 01:27:54 +00001263
nethercote71980f02004-01-24 18:18:54 +00001264/*====================================================================*/
1265/*=== File descriptor setup ===*/
1266/*====================================================================*/
1267
sewardj5f229e22005-09-28 01:36:01 +00001268/* Number of file descriptors that Valgrind tries to reserve for
1269 it's own use - just a small constant. */
1270#define N_RESERVED_FDS (10)
1271
nethercote71980f02004-01-24 18:18:54 +00001272static void setup_file_descriptors(void)
1273{
1274 struct vki_rlimit rl;
sewardj17c11042006-10-15 01:26:40 +00001275 Bool show = False;
nethercote71980f02004-01-24 18:18:54 +00001276
1277 /* Get the current file descriptor limits. */
1278 if (VG_(getrlimit)(VKI_RLIMIT_NOFILE, &rl) < 0) {
1279 rl.rlim_cur = 1024;
1280 rl.rlim_max = 1024;
1281 }
1282
njnf76d27a2009-05-28 01:53:07 +00001283# if defined(VGO_darwin)
1284 /* Darwin lies. It reports file max as RLIM_INFINITY but
1285 silently disallows anything bigger than 10240. */
1286 if (rl.rlim_cur >= 10240 && rl.rlim_max == 0x7fffffffffffffffULL) {
1287 rl.rlim_max = 10240;
1288 }
1289# endif
1290
sewardj17c11042006-10-15 01:26:40 +00001291 if (show)
njn8a7b41b2007-09-23 00:51:24 +00001292 VG_(printf)("fd limits: host, before: cur %lu max %lu\n",
sewardja8ffda62008-07-18 18:23:24 +00001293 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
sewardj17c11042006-10-15 01:26:40 +00001294
nethercote71980f02004-01-24 18:18:54 +00001295 /* Work out where to move the soft limit to. */
njn14319cc2005-03-13 06:26:22 +00001296 if (rl.rlim_cur + N_RESERVED_FDS <= rl.rlim_max) {
1297 rl.rlim_cur = rl.rlim_cur + N_RESERVED_FDS;
nethercote71980f02004-01-24 18:18:54 +00001298 } else {
1299 rl.rlim_cur = rl.rlim_max;
1300 }
1301
1302 /* Reserve some file descriptors for our use. */
njn14319cc2005-03-13 06:26:22 +00001303 VG_(fd_soft_limit) = rl.rlim_cur - N_RESERVED_FDS;
1304 VG_(fd_hard_limit) = rl.rlim_cur - N_RESERVED_FDS;
nethercote71980f02004-01-24 18:18:54 +00001305
1306 /* Update the soft limit. */
1307 VG_(setrlimit)(VKI_RLIMIT_NOFILE, &rl);
1308
sewardj17c11042006-10-15 01:26:40 +00001309 if (show) {
njn8a7b41b2007-09-23 00:51:24 +00001310 VG_(printf)("fd limits: host, after: cur %lu max %lu\n",
sewardja8ffda62008-07-18 18:23:24 +00001311 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
sewardj17c11042006-10-15 01:26:40 +00001312 VG_(printf)("fd limits: guest : cur %u max %u\n",
1313 VG_(fd_soft_limit), VG_(fd_hard_limit));
1314 }
1315
sewardj45f4e7c2005-09-27 19:20:21 +00001316 if (VG_(cl_exec_fd) != -1)
1317 VG_(cl_exec_fd) = VG_(safe_fd)( VG_(cl_exec_fd) );
nethercote71980f02004-01-24 18:18:54 +00001318}
1319
sewardjde4a1d02002-03-22 01:27:54 +00001320
njn2da73352005-06-18 01:35:16 +00001321/*====================================================================*/
njn2025cf92005-06-26 20:44:48 +00001322/*=== BB profiling ===*/
1323/*====================================================================*/
1324
1325static
1326void show_BB_profile ( BBProfEntry tops[], UInt n_tops, ULong score_total )
1327{
1328 ULong score_cumul, score_here;
1329 Char buf_cumul[10], buf_here[10];
1330 Char name[64];
1331 Int r;
1332
1333 VG_(printf)("\n");
1334 VG_(printf)("-----------------------------------------------------------\n");
1335 VG_(printf)("--- BEGIN BB Profile (summary of scores) ---\n");
1336 VG_(printf)("-----------------------------------------------------------\n");
1337 VG_(printf)("\n");
1338
1339 VG_(printf)("Total score = %lld\n\n", score_total);
1340
1341 score_cumul = 0;
1342 for (r = 0; r < n_tops; r++) {
1343 if (tops[r].addr == 0)
1344 continue;
1345 name[0] = 0;
1346 VG_(get_fnname_w_offset)(tops[r].addr, name, 64);
1347 name[63] = 0;
1348 score_here = tops[r].score;
1349 score_cumul += score_here;
1350 VG_(percentify)(score_cumul, score_total, 2, 6, buf_cumul);
1351 VG_(percentify)(score_here, score_total, 2, 6, buf_here);
1352 VG_(printf)("%3d: (%9lld %s) %9lld %s 0x%llx %s\n",
1353 r,
1354 score_cumul, buf_cumul,
1355 score_here, buf_here, tops[r].addr, name );
1356 }
1357
1358 VG_(printf)("\n");
1359 VG_(printf)("-----------------------------------------------------------\n");
1360 VG_(printf)("--- BB Profile (BB details) ---\n");
1361 VG_(printf)("-----------------------------------------------------------\n");
1362 VG_(printf)("\n");
1363
1364 score_cumul = 0;
1365 for (r = 0; r < n_tops; r++) {
1366 if (tops[r].addr == 0)
1367 continue;
1368 name[0] = 0;
1369 VG_(get_fnname_w_offset)(tops[r].addr, name, 64);
1370 name[63] = 0;
1371 score_here = tops[r].score;
1372 score_cumul += score_here;
1373 VG_(percentify)(score_cumul, score_total, 2, 6, buf_cumul);
1374 VG_(percentify)(score_here, score_total, 2, 6, buf_here);
1375 VG_(printf)("\n");
1376 VG_(printf)("=-=-=-=-=-=-=-=-=-=-=-=-=-= begin BB rank %d "
1377 "=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n", r);
1378 VG_(printf)("%3d: (%9lld %s) %9lld %s 0x%llx %s\n",
1379 r,
1380 score_cumul, buf_cumul,
1381 score_here, buf_here, tops[r].addr, name );
1382 VG_(printf)("\n");
sewardjbcccbc02007-04-09 22:24:57 +00001383 VG_(discard_translations)(tops[r].addr, 1, "bb profile");
sewardj0ec07f32006-01-12 12:32:32 +00001384 VG_(translate)(0, tops[r].addr, True, VG_(clo_profile_flags), 0, True);
njn2025cf92005-06-26 20:44:48 +00001385 VG_(printf)("=-=-=-=-=-=-=-=-=-=-=-=-=-= end BB rank %d "
1386 "=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n", r);
1387 }
1388
1389 VG_(printf)("\n");
1390 VG_(printf)("-----------------------------------------------------------\n");
1391 VG_(printf)("--- END BB Profile ---\n");
1392 VG_(printf)("-----------------------------------------------------------\n");
1393 VG_(printf)("\n");
1394}
1395
1396
1397/*====================================================================*/
nethercote71980f02004-01-24 18:18:54 +00001398/*=== main() ===*/
1399/*====================================================================*/
1400
sewardjfdf91b42005-09-28 00:53:09 +00001401/* When main() is entered, we should be on the following stack, not
1402 the one the kernel gave us. We will run on this stack until
1403 simulation of the root thread is started, at which point a transfer
1404 is made to a dynamically allocated stack. This is for the sake of
1405 uniform overflow detection for all Valgrind threads. This is
1406 marked global even though it isn't, because assembly code below
1407 needs to reference the name. */
1408
1409/*static*/ VgStack VG_(interim_stack);
1410
sewardjf9d2f9b2006-11-17 20:00:57 +00001411/* These are the structures used to hold info for creating the initial
1412 client image.
1413
1414 'iicii' mostly holds important register state present at system
1415 startup (_start_valgrind). valgrind_main() then fills in the rest
1416 of it and passes it to VG_(ii_create_image)(). That produces
1417 'iifii', which is later handed to VG_(ii_finalise_image). */
1418
1419/* In all OS-instantiations, the_iicii has a field .sp_at_startup.
1420 This should get some address inside the stack on which we gained
sewardjfdf91b42005-09-28 00:53:09 +00001421 control (eg, it could be the SP at startup). It doesn't matter
1422 exactly where in the stack it is. This value is passed to the
sewardjf9d2f9b2006-11-17 20:00:57 +00001423 address space manager at startup. On Linux, aspacem then uses it
1424 to identify the initial stack segment and hence the upper end of
1425 the usable address space. */
sewardjfdf91b42005-09-28 00:53:09 +00001426
sewardjf9d2f9b2006-11-17 20:00:57 +00001427static IICreateImageInfo the_iicii;
1428static IIFinaliseImageInfo the_iifii;
1429
sewardjfdf91b42005-09-28 00:53:09 +00001430
sewardj9c606bd2008-09-18 18:12:50 +00001431/* A simple pair structure, used for conveying debuginfo handles to
1432 calls to VG_TRACK(new_mem_startup, ...). */
1433typedef struct { Addr a; ULong ull; } Addr_n_ULong;
1434
1435
sewardj1ae3f3a2005-09-28 10:47:38 +00001436/* --- Forwards decls to do with shutdown --- */
1437
1438static void final_tidyup(ThreadId tid);
1439
1440/* Do everything which needs doing when the last thread exits */
1441static
1442void shutdown_actions_NORETURN( ThreadId tid,
1443 VgSchedReturnCode tids_schedretcode );
1444
1445/* --- end of Forwards decls to do with shutdown --- */
sewardjfdf91b42005-09-28 00:53:09 +00001446
1447
sewardjf9d2f9b2006-11-17 20:00:57 +00001448/* By the time we get to valgrind_main, the_iicii should already have
1449 been filled in with any important details as required by whatever
1450 OS we have been built for.
1451*/
sewardj17c11042006-10-15 01:26:40 +00001452static
sewardjf9d2f9b2006-11-17 20:00:57 +00001453Int valgrind_main ( Int argc, HChar **argv, HChar **envp )
nethercote71980f02004-01-24 18:18:54 +00001454{
sewardj13247ca2005-12-30 22:52:20 +00001455 HChar* toolname = "memcheck"; // default to Memcheck
sewardj13247ca2005-12-30 22:52:20 +00001456 Int need_help = 0; // 0 = no, 1 = --help, 2 = --help-debug
sewardjde764e82007-11-09 23:13:22 +00001457 ThreadId tid_main = VG_INVALID_THREADID;
sewardj738856f2009-07-15 14:48:32 +00001458 Bool logging_to_fd = False;
1459 Char* xml_fname_unexpanded = NULL;
sewardj45f4e7c2005-09-27 19:20:21 +00001460 Int loglevel, i;
nethercote73b526f2004-10-31 18:48:21 +00001461 struct vki_rlimit zero = { 0, 0 };
sewardj9c606bd2008-09-18 18:12:50 +00001462 XArray* addr2dihandle = NULL;
sewardj17c11042006-10-15 01:26:40 +00001463
philippe14711e82012-06-14 22:18:50 +00001464 // For an inner Valgrind, register the interim stack asap.
1465 // This is needed to allow the outer valgrind to do stacktraces during init.
1466 // Note that this stack is not unregistered when the main thread
1467 // is switching to the (real) stack. Unregistering this would imply
1468 // to save the stack id in a global variable, and have a "if"
1469 // in run_a_thread_NORETURN to do the unregistration only for the
1470 // main thread. This unregistration is not worth this complexity.
1471 INNER_REQUEST
1472 ((void) VALGRIND_STACK_REGISTER
1473 (&VG_(interim_stack).bytes[0],
1474 &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack))));
1475
1476
nethercote71980f02004-01-24 18:18:54 +00001477 //============================================================
nethercote71980f02004-01-24 18:18:54 +00001478 //
sewardj45f4e7c2005-09-27 19:20:21 +00001479 // Nb: startup is complex. Prerequisites are shown at every step.
nethercote71980f02004-01-24 18:18:54 +00001480 // *** Be very careful when messing with the order ***
sewardj45f4e7c2005-09-27 19:20:21 +00001481 //
1482 // The first order of business is to get debug logging, the address
1483 // space manager and the dynamic memory manager up and running.
1484 // Once that's done, we can relax a bit.
1485 //
nethercote71980f02004-01-24 18:18:54 +00001486 //============================================================
sewardj45f4e7c2005-09-27 19:20:21 +00001487
1488 /* This is needed to make VG_(getenv) usable early. */
1489 VG_(client_envp) = (Char**)envp;
nethercote71980f02004-01-24 18:18:54 +00001490
sewardj1cf558c2005-04-25 01:36:56 +00001491 //--------------------------------------------------------------
njnf76d27a2009-05-28 01:53:07 +00001492 // Start up Mach kernel interface, if any
1493 // p: none
1494 //--------------------------------------------------------------
1495# if defined(VGO_darwin)
1496 VG_(mach_init)();
1497# endif
1498
1499 //--------------------------------------------------------------
sewardj1cf558c2005-04-25 01:36:56 +00001500 // Start up the logging mechanism
1501 // p: none
1502 //--------------------------------------------------------------
1503 /* Start the debugging-log system ASAP. First find out how many
njn83df0b62009-02-25 01:01:05 +00001504 "-d"s were specified. This is a pre-scan of the command line. Also
1505 get --profile-heap=yes which is needed by the time we start up dynamic
1506 memory management. */
sewardj1cf558c2005-04-25 01:36:56 +00001507 loglevel = 0;
1508 for (i = 1; i < argc; i++) {
njn83df0b62009-02-25 01:01:05 +00001509 if (argv[i][0] != '-') break;
1510 if VG_STREQ(argv[i], "--") break;
1511 if VG_STREQ(argv[i], "-d") loglevel++;
1512 if VG_BOOL_CLO(argv[i], "--profile-heap", VG_(clo_profile_heap)) {}
sewardj1cf558c2005-04-25 01:36:56 +00001513 }
1514
1515 /* ... and start the debug logger. Now we can safely emit logging
1516 messages all through startup. */
sewardj10759312005-05-30 23:52:47 +00001517 VG_(debugLog_startup)(loglevel, "Stage 2 (main)");
sewardj45f4e7c2005-09-27 19:20:21 +00001518 VG_(debugLog)(1, "main", "Welcome to Valgrind version "
1519 VERSION " debug logging\n");
1520
1521 //--------------------------------------------------------------
1522 // Ensure we're on a plausible stack.
1523 // p: logging
1524 //--------------------------------------------------------------
1525 VG_(debugLog)(1, "main", "Checking current stack is plausible\n");
sewardjfdf91b42005-09-28 00:53:09 +00001526 { HChar* limLo = (HChar*)(&VG_(interim_stack).bytes[0]);
1527 HChar* limHi = limLo + sizeof(VG_(interim_stack));
sewardj45f4e7c2005-09-27 19:20:21 +00001528 HChar* aLocal = (HChar*)&zero; /* any auto local will do */
1529 if (aLocal < limLo || aLocal >= limHi) {
1530 /* something's wrong. Stop. */
1531 VG_(debugLog)(0, "main", "Root stack %p to %p, a local %p\n",
1532 limLo, limHi, aLocal );
1533 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1534 "Initial stack switched failed.\n");
1535 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1536 VG_(exit)(1);
1537 }
1538 }
1539
1540 //--------------------------------------------------------------
1541 // Ensure we have a plausible pointer to the stack on which
1542 // we gained control (not the current stack!)
1543 // p: logging
1544 //--------------------------------------------------------------
1545 VG_(debugLog)(1, "main", "Checking initial stack was noted\n");
sewardjf9d2f9b2006-11-17 20:00:57 +00001546 if (the_iicii.sp_at_startup == 0) {
sewardj45f4e7c2005-09-27 19:20:21 +00001547 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1548 "Initial stack was not noted.\n");
1549 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1550 VG_(exit)(1);
1551 }
1552
1553 //--------------------------------------------------------------
1554 // Start up the address space manager, and determine the
1555 // approximate location of the client's stack
njnea2d6fd2010-07-01 00:20:20 +00001556 // p: logging, plausible-stack
sewardj45f4e7c2005-09-27 19:20:21 +00001557 //--------------------------------------------------------------
1558 VG_(debugLog)(1, "main", "Starting the address space manager\n");
sewardj5db15402012-06-07 09:13:21 +00001559 vg_assert(VKI_PAGE_SIZE == 4096 || VKI_PAGE_SIZE == 65536
1560 || VKI_PAGE_SIZE == 16384);
1561 vg_assert(VKI_MAX_PAGE_SIZE == 4096 || VKI_MAX_PAGE_SIZE == 65536
1562 || VKI_MAX_PAGE_SIZE == 16384);
sewardje66f2e02006-12-30 17:45:08 +00001563 vg_assert(VKI_PAGE_SIZE <= VKI_MAX_PAGE_SIZE);
1564 vg_assert(VKI_PAGE_SIZE == (1 << VKI_PAGE_SHIFT));
1565 vg_assert(VKI_MAX_PAGE_SIZE == (1 << VKI_MAX_PAGE_SHIFT));
sewardjf9d2f9b2006-11-17 20:00:57 +00001566 the_iicii.clstack_top = VG_(am_startup)( the_iicii.sp_at_startup );
sewardj45f4e7c2005-09-27 19:20:21 +00001567 VG_(debugLog)(1, "main", "Address space manager is running\n");
1568
1569 //--------------------------------------------------------------
1570 // Start up the dynamic memory manager
1571 // p: address space management
njn83df0b62009-02-25 01:01:05 +00001572 // p: getting --profile-heap
sewardj45f4e7c2005-09-27 19:20:21 +00001573 // In fact m_mallocfree is self-initialising, so there's no
1574 // initialisation call to do. Instead, try a simple malloc/
1575 // free pair right now to check that nothing is broken.
1576 //--------------------------------------------------------------
1577 VG_(debugLog)(1, "main", "Starting the dynamic memory manager\n");
sewardj9c606bd2008-09-18 18:12:50 +00001578 { void* p = VG_(malloc)( "main.vm.1", 12345 );
sewardj45f4e7c2005-09-27 19:20:21 +00001579 if (p) VG_(free)( p );
1580 }
1581 VG_(debugLog)(1, "main", "Dynamic memory manager is running\n");
sewardj1cf558c2005-04-25 01:36:56 +00001582
nethercotef4928da2004-06-15 10:54:40 +00001583 //============================================================
sewardj45f4e7c2005-09-27 19:20:21 +00001584 //
1585 // Dynamic memory management is now available.
1586 //
nethercotef4928da2004-06-15 10:54:40 +00001587 //============================================================
1588
sewardj45f4e7c2005-09-27 19:20:21 +00001589 //--------------------------------------------------------------
sewardjf98e1c02008-10-25 16:22:41 +00001590 // Initialise m_debuginfo
1591 // p: dynamic memory allocation
1592 VG_(debugLog)(1, "main", "Initialise m_debuginfo\n");
1593 VG_(di_initialise)();
1594
1595 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001596 // Look for alternative libdir
1597 { HChar *cp = VG_(getenv)(VALGRIND_LIB);
1598 if (cp != NULL)
1599 VG_(libdir) = cp;
njncde90d32009-07-22 22:41:38 +00001600 VG_(debugLog)(1, "main", "VG_(libdir) = %s\n", VG_(libdir));
sewardj45f4e7c2005-09-27 19:20:21 +00001601 }
1602
1603 //--------------------------------------------------------------
1604 // Extract the launcher name from the environment.
njna842d792009-05-21 01:15:18 +00001605 VG_(debugLog)(1, "main", "Getting launcher's name ...\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001606 VG_(name_of_launcher) = VG_(getenv)(VALGRIND_LAUNCHER);
1607 if (VG_(name_of_launcher) == NULL) {
1608 VG_(printf)("valgrind: You cannot run '%s' directly.\n", argv[0]);
1609 VG_(printf)("valgrind: You should use $prefix/bin/valgrind.\n");
1610 VG_(exit)(1);
1611 }
njna842d792009-05-21 01:15:18 +00001612 VG_(debugLog)(1, "main", "... %s\n", VG_(name_of_launcher));
sewardj45f4e7c2005-09-27 19:20:21 +00001613
1614 //--------------------------------------------------------------
fitzhardingeb50068f2004-02-24 23:42:55 +00001615 // Get the current process datasize rlimit, and set it to zero.
1616 // This prevents any internal uses of brk() from having any effect.
1617 // We remember the old value so we can restore it on exec, so that
1618 // child processes will have a reasonable brk value.
1619 VG_(getrlimit)(VKI_RLIMIT_DATA, &VG_(client_rlimit_data));
1620 zero.rlim_max = VG_(client_rlimit_data).rlim_max;
1621 VG_(setrlimit)(VKI_RLIMIT_DATA, &zero);
thughesc37184f2004-09-11 14:16:57 +00001622
1623 // Get the current process stack rlimit.
1624 VG_(getrlimit)(VKI_RLIMIT_STACK, &VG_(client_rlimit_stack));
1625
sewardje2d1e672005-11-12 23:10:48 +00001626 //--------------------------------------------------------------
1627 // Figure out what sort of CPU we're on, and whether it is
1628 // able to run V.
1629 VG_(debugLog)(1, "main", "Get hardware capabilities ...\n");
1630 { VexArch vex_arch;
1631 VexArchInfo vex_archinfo;
1632 Bool ok = VG_(machine_get_hwcaps)();
1633 if (!ok) {
1634 VG_(printf)("\n");
1635 VG_(printf)("valgrind: fatal error: unsupported CPU.\n");
1636 VG_(printf)(" Supported CPUs are:\n");
1637 VG_(printf)(" * x86 (practically any; Pentium-I or above), "
1638 "AMD Athlon or above)\n");
1639 VG_(printf)(" * AMD Athlon64/Opteron\n");
1640 VG_(printf)(" * PowerPC (most; ppc405 and above)\n");
sewardjb5b87402011-03-07 16:05:35 +00001641 VG_(printf)(" * System z (64bit only - s390x; z900 and above)\n");
sewardje2d1e672005-11-12 23:10:48 +00001642 VG_(printf)("\n");
1643 VG_(exit)(1);
1644 }
1645 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
sewardje3121f32006-01-27 21:23:23 +00001646 VG_(debugLog)(
1647 1, "main", "... arch = %s, hwcaps = %s\n",
1648 LibVEX_ppVexArch ( vex_arch ),
1649 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1650 );
sewardje2d1e672005-11-12 23:10:48 +00001651 }
1652
sewardj198f34f2007-07-09 23:13:07 +00001653 //--------------------------------------------------------------
1654 // Record the working directory at startup
sewardj6e9de462011-06-28 07:25:29 +00001655 // p: none
sewardj198f34f2007-07-09 23:13:07 +00001656 VG_(debugLog)(1, "main", "Getting the working directory at startup\n");
1657 { Bool ok = VG_(record_startup_wd)();
1658 if (!ok)
1659 VG_(err_config_error)( "Can't establish current working "
florian1763e812011-07-12 19:07:05 +00001660 "directory at startup\n");
sewardj198f34f2007-07-09 23:13:07 +00001661 }
1662 { Char buf[VKI_PATH_MAX+1];
1663 Bool ok = VG_(get_startup_wd)( buf, sizeof(buf) );
1664 vg_assert(ok);
1665 buf[VKI_PATH_MAX] = 0;
1666 VG_(debugLog)(1, "main", "... %s\n", buf );
1667 }
1668
sewardj45f4e7c2005-09-27 19:20:21 +00001669 //============================================================
1670 // Command line argument handling order:
1671 // * If --help/--help-debug are present, show usage message
1672 // (including the tool-specific usage)
1673 // * (If no --tool option given, default to Memcheck)
1674 // * Then, if client is missing, abort with error msg
1675 // * Then, if any cmdline args are bad, abort with error msg
1676 //============================================================
1677
1678 //--------------------------------------------------------------
1679 // Split up argv into: C args, V args, V extra args, and exename.
1680 // p: dynamic memory allocation
1681 //--------------------------------------------------------------
1682 VG_(debugLog)(1, "main", "Split up command line\n");
1683 VG_(split_up_argv)( argc, argv );
sewardj14c7cc52007-02-25 15:08:24 +00001684 vg_assert( VG_(args_for_valgrind) );
1685 vg_assert( VG_(args_for_client) );
sewardj45f4e7c2005-09-27 19:20:21 +00001686 if (0) {
sewardj14c7cc52007-02-25 15:08:24 +00001687 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++)
1688 VG_(printf)(
1689 "varg %s\n",
1690 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1691 );
sewardj45f4e7c2005-09-27 19:20:21 +00001692 VG_(printf)(" exe %s\n", VG_(args_the_exename));
sewardj14c7cc52007-02-25 15:08:24 +00001693 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++)
1694 VG_(printf)(
1695 "carg %s\n",
1696 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1697 );
nethercote71980f02004-01-24 18:18:54 +00001698 }
1699
1700 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001701 // Extract tool name and whether help has been requested.
1702 // Note we can't print the help message yet, even if requested,
1703 // because the tool has not been initialised.
1704 // p: split_up_argv [for VG_(args_for_valgrind)]
nethercote71980f02004-01-24 18:18:54 +00001705 //--------------------------------------------------------------
sewardj95d86c02007-12-18 01:49:23 +00001706 VG_(debugLog)(1, "main",
1707 "(early_) Process Valgrind's command line options\n");
1708 early_process_cmd_line_options(&need_help, &toolname);
nethercote71980f02004-01-24 18:18:54 +00001709
sewardj45f4e7c2005-09-27 19:20:21 +00001710 // Set default vex control params
1711 LibVEX_default_VexControl(& VG_(clo_vex_control));
nethercote71980f02004-01-24 18:18:54 +00001712
1713 //--------------------------------------------------------------
1714 // Load client executable, finding in $PATH if necessary
njn83df0b62009-02-25 01:01:05 +00001715 // p: early_process_cmd_line_options() [for 'exec', 'need_help',
1716 // clo_max_stackframe,
1717 // clo_main_stacksize]
sewardj95d86c02007-12-18 01:49:23 +00001718 // p: layout_remaining_space [so there's space]
sewardj17c11042006-10-15 01:26:40 +00001719 //
nethercote71980f02004-01-24 18:18:54 +00001720 // Set up client's environment
sewardj95d86c02007-12-18 01:49:23 +00001721 // p: set-libdir [for VG_(libdir)]
1722 // p: early_process_cmd_line_options [for toolname]
sewardj17c11042006-10-15 01:26:40 +00001723 //
nethercote5ee67ca2004-06-22 14:00:09 +00001724 // Setup client stack, eip, and VG_(client_arg[cv])
nethercote71980f02004-01-24 18:18:54 +00001725 // p: load_client() [for 'info']
1726 // p: fix_environment() [for 'env']
sewardj17c11042006-10-15 01:26:40 +00001727 //
sewardj45f4e7c2005-09-27 19:20:21 +00001728 // Setup client data (brk) segment. Initially a 1-page segment
1729 // which abuts a shrinkable reservation.
1730 // p: load_client() [for 'info' and hence VG_(brk_base)]
sewardjf9d2f9b2006-11-17 20:00:57 +00001731 //
1732 // p: _start_in_C (for zeroing out the_iicii and putting some
1733 // initial values into it)
sewardj45f4e7c2005-09-27 19:20:21 +00001734 //--------------------------------------------------------------
sewardj17c11042006-10-15 01:26:40 +00001735 if (!need_help) {
sewardjf9d2f9b2006-11-17 20:00:57 +00001736 VG_(debugLog)(1, "main", "Create initial image\n");
1737
njnf76d27a2009-05-28 01:53:07 +00001738# if defined(VGO_linux) || defined(VGO_darwin)
sewardjf9d2f9b2006-11-17 20:00:57 +00001739 the_iicii.argv = argv;
1740 the_iicii.envp = envp;
1741 the_iicii.toolname = toolname;
sewardjf9d2f9b2006-11-17 20:00:57 +00001742# 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 );
sewardj45f4e7c2005-09-27 19:20:21 +00001748 }
nethercote71980f02004-01-24 18:18:54 +00001749
1750 //==============================================================
sewardj45f4e7c2005-09-27 19:20:21 +00001751 //
1752 // Finished loading/setting up the client address space.
1753 //
nethercote71980f02004-01-24 18:18:54 +00001754 //==============================================================
1755
1756 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00001757 // setup file descriptors
1758 // p: n/a
1759 //--------------------------------------------------------------
sewardj1fbc1a52005-04-25 02:05:54 +00001760 VG_(debugLog)(1, "main", "Setup file descriptors\n");
nethercote71980f02004-01-24 18:18:54 +00001761 setup_file_descriptors();
1762
1763 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001764 // create the fake /proc/<pid>/cmdline file and then unlink it,
1765 // but hold onto the fd, so we can hand it out to the client
1766 // when it tries to open /proc/<pid>/cmdline for itself.
1767 // p: setup file descriptors
nethercotec314eba2004-07-15 12:59:41 +00001768 //--------------------------------------------------------------
bart9b533f82009-08-25 20:15:41 +00001769#if !defined(VGO_linux)
1770 // client shouldn't be using /proc!
1771 VG_(cl_cmdline_fd) = -1;
1772#else
1773 if (!need_help) {
1774 HChar buf[50], buf2[50+64];
1775 HChar nul[1];
1776 Int fd, r;
barta3054f52010-06-14 18:12:56 +00001777 const HChar* exename;
nethercotec314eba2004-07-15 12:59:41 +00001778
bart9b533f82009-08-25 20:15:41 +00001779 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/cmdline\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001780
bart9b533f82009-08-25 20:15:41 +00001781 VG_(sprintf)(buf, "proc_%d_cmdline", VG_(getpid)());
1782 fd = VG_(mkstemp)( buf, buf2 );
1783 if (fd == -1)
florian1763e812011-07-12 19:07:05 +00001784 VG_(err_config_error)("Can't create client cmdline file in %s\n", buf2);
sewardj45f4e7c2005-09-27 19:20:21 +00001785
bart9b533f82009-08-25 20:15:41 +00001786 nul[0] = 0;
1787 exename = VG_(args_the_exename) ? VG_(args_the_exename)
1788 : "unknown_exename";
sewardjc7ffc942011-03-28 16:26:42 +00001789 VG_(write)(fd, exename, VG_(strlen)( exename ));
bart9b533f82009-08-25 20:15:41 +00001790 VG_(write)(fd, nul, 1);
1791
1792 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1793 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i );
1794 VG_(write)(fd, arg, VG_(strlen)( arg ));
sewardj45f4e7c2005-09-27 19:20:21 +00001795 VG_(write)(fd, nul, 1);
1796 }
bart9b533f82009-08-25 20:15:41 +00001797
1798 /* Don't bother to seek the file back to the start; instead do
1799 it every time a copy of it is given out (by PRE(sys_open)).
1800 That is probably more robust across fork() etc. */
1801
1802 /* Now delete it, but hang on to the fd. */
1803 r = VG_(unlink)( buf2 );
1804 if (r)
florian1763e812011-07-12 19:07:05 +00001805 VG_(err_config_error)("Can't delete client cmdline file in %s\n", buf2);
bart9b533f82009-08-25 20:15:41 +00001806
1807 VG_(cl_cmdline_fd) = fd;
sewardj45f4e7c2005-09-27 19:20:21 +00001808 }
bart9b533f82009-08-25 20:15:41 +00001809#endif
nethercotec314eba2004-07-15 12:59:41 +00001810
1811 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001812 // Init tool part 1: pre_clo_init
nethercotec314eba2004-07-15 12:59:41 +00001813 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
nethercotec314eba2004-07-15 12:59:41 +00001814 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
nethercote71980f02004-01-24 18:18:54 +00001815 //--------------------------------------------------------------
sewardj7cf4e6b2008-05-01 20:24:26 +00001816 VG_(debugLog)(1, "main", "Initialise the tool part 1 (pre_clo_init)\n");
njn08ce7b32009-02-27 03:38:28 +00001817 VG_(tl_pre_clo_init)();
nethercote71980f02004-01-24 18:18:54 +00001818
sewardj45f4e7c2005-09-27 19:20:21 +00001819 //--------------------------------------------------------------
nethercotef4928da2004-06-15 10:54:40 +00001820 // If --tool and --help/--help-debug was given, now give the core+tool
1821 // help message
sewardj95d86c02007-12-18 01:49:23 +00001822 // p: early_process_cmd_line_options() [for 'need_help']
1823 // p: tl_pre_clo_init [for 'VG_(tdict).usage']
sewardj45f4e7c2005-09-27 19:20:21 +00001824 //--------------------------------------------------------------
1825 VG_(debugLog)(1, "main", "Print help and quit, if requested\n");
nethercotef4928da2004-06-15 10:54:40 +00001826 if (need_help) {
njncce38e62010-07-06 04:25:12 +00001827 usage_NORETURN(/*--help-debug?*/need_help >= 2);
nethercotef4928da2004-06-15 10:54:40 +00001828 }
nethercotec314eba2004-07-15 12:59:41 +00001829
sewardj45f4e7c2005-09-27 19:20:21 +00001830 //--------------------------------------------------------------
1831 // Process command line options to Valgrind + tool
1832 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1833 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1834 //--------------------------------------------------------------
sewardj95d86c02007-12-18 01:49:23 +00001835 VG_(debugLog)(1, "main",
1836 "(main_) Process Valgrind's command line options, "
1837 "setup logging\n");
sewardj738856f2009-07-15 14:48:32 +00001838 main_process_cmd_line_options ( &logging_to_fd, &xml_fname_unexpanded,
1839 toolname );
sewardj45f4e7c2005-09-27 19:20:21 +00001840
1841 //--------------------------------------------------------------
sewardj592ae092005-11-08 19:01:44 +00001842 // Zeroise the millisecond counter by doing a first read of it.
1843 // p: none
1844 //--------------------------------------------------------------
1845 (void) VG_(read_millisecond_timer)();
1846
1847 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001848 // Print the preamble
1849 // p: tl_pre_clo_init [for 'VG_(details).name' and friends]
sewardj738856f2009-07-15 14:48:32 +00001850 // p: main_process_cmd_line_options()
1851 // [for VG_(clo_verbosity), VG_(clo_xml),
1852 // logging_to_fd, xml_fname_unexpanded]
sewardj45f4e7c2005-09-27 19:20:21 +00001853 //--------------------------------------------------------------
1854 VG_(debugLog)(1, "main", "Print the preamble...\n");
sewardj738856f2009-07-15 14:48:32 +00001855 print_preamble(logging_to_fd, xml_fname_unexpanded, toolname);
sewardj45f4e7c2005-09-27 19:20:21 +00001856 VG_(debugLog)(1, "main", "...finished the preamble\n");
1857
1858 //--------------------------------------------------------------
1859 // Init tool part 2: post_clo_init
1860 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1861 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1862 // p: print_preamble() [so any warnings printed in post_clo_init
1863 // are shown after the preamble]
1864 //--------------------------------------------------------------
1865 VG_(debugLog)(1, "main", "Initialise the tool part 2 (post_clo_init)\n");
njn51d827b2005-05-09 01:02:08 +00001866 VG_TDICT_CALL(tool_post_clo_init);
sewardj7cf4e6b2008-05-01 20:24:26 +00001867 {
1868 /* The tool's "needs" will by now be finalised, since it has no
1869 further opportunity to specify them. So now sanity check
1870 them. */
1871 Char* s;
1872 Bool ok;
1873 ok = VG_(sanity_check_needs)( &s );
1874 if (!ok) {
1875 VG_(tool_panic)(s);
1876 }
1877 }
nethercotef4928da2004-06-15 10:54:40 +00001878
1879 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001880 // Initialise translation table and translation cache
1881 // p: aspacem [??]
1882 // p: tl_pre_clo_init [for 'VG_(details).avg_translation_sizeB']
nethercote71980f02004-01-24 18:18:54 +00001883 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001884 VG_(debugLog)(1, "main", "Initialise TT/TC\n");
1885 VG_(init_tt_tc)();
sewardjb5f6f512005-03-10 23:59:00 +00001886
sewardj45f4e7c2005-09-27 19:20:21 +00001887 //--------------------------------------------------------------
1888 // Initialise the redirect table.
1889 // p: init_tt_tc [so it can call VG_(search_transtab) safely]
1890 // p: aspacem [so can change ownership of sysinfo pages]
1891 //--------------------------------------------------------------
1892 VG_(debugLog)(1, "main", "Initialise redirects\n");
sewardj0ec07f32006-01-12 12:32:32 +00001893 VG_(redir_initialise)();
nethercote71980f02004-01-24 18:18:54 +00001894
1895 //--------------------------------------------------------------
1896 // Allow GDB attach
sewardj95d86c02007-12-18 01:49:23 +00001897 // p: main_process_cmd_line_options() [for VG_(clo_wait_for_gdb)]
nethercote71980f02004-01-24 18:18:54 +00001898 //--------------------------------------------------------------
1899 /* Hook to delay things long enough so we can get the pid and
1900 attach GDB in another shell. */
1901 if (VG_(clo_wait_for_gdb)) {
sewardj87cd71c2011-07-05 09:13:41 +00001902 ULong iters, q;
sewardj1fbc1a52005-04-25 02:05:54 +00001903 VG_(debugLog)(1, "main", "Wait for GDB\n");
sewardj93ab8572005-02-06 14:10:40 +00001904 VG_(printf)("pid=%d, entering delay loop\n", VG_(getpid)());
sewardj8211a572005-06-23 21:37:47 +00001905
1906# if defined(VGP_x86_linux)
sewardj291849f2012-04-20 23:58:55 +00001907 iters = 10;
sewardj2c48c7b2005-11-29 13:05:56 +00001908# elif defined(VGP_amd64_linux) || defined(VGP_ppc64_linux)
sewardj8211a572005-06-23 21:37:47 +00001909 iters = 10;
1910# elif defined(VGP_ppc32_linux)
sewardjd714d2e2005-07-08 18:24:04 +00001911 iters = 5;
sewardj59570ff2010-01-01 11:59:33 +00001912# elif defined(VGP_arm_linux)
sewardj291849f2012-04-20 23:58:55 +00001913 iters = 5;
sewardjb5b87402011-03-07 16:05:35 +00001914# elif defined(VGP_s390x_linux)
1915 iters = 10;
sewardj5db15402012-06-07 09:13:21 +00001916# elif defined(VGP_mips32_linux)
1917 iters = 10;
njnf76d27a2009-05-28 01:53:07 +00001918# elif defined(VGO_darwin)
1919 iters = 3;
sewardj8211a572005-06-23 21:37:47 +00001920# else
sewardj17c11042006-10-15 01:26:40 +00001921# error "Unknown plat"
sewardj8211a572005-06-23 21:37:47 +00001922# endif
1923
sewardj87cd71c2011-07-05 09:13:41 +00001924 iters *= 1000ULL * 1000 * 1000;
sewardj8211a572005-06-23 21:37:47 +00001925 for (q = 0; q < iters; q++)
sewardj87cd71c2011-07-05 09:13:41 +00001926 __asm__ __volatile__("" ::: "memory","cc");
nethercote71980f02004-01-24 18:18:54 +00001927 }
1928
sewardjb5d320c2005-03-13 18:57:15 +00001929 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00001930 // Search for file descriptors that are inherited from our parent
sewardj95d86c02007-12-18 01:49:23 +00001931 // p: main_process_cmd_line_options [for VG_(clo_track_fds)]
nethercote71980f02004-01-24 18:18:54 +00001932 //--------------------------------------------------------------
sewardj1fbc1a52005-04-25 02:05:54 +00001933 if (VG_(clo_track_fds)) {
1934 VG_(debugLog)(1, "main", "Init preopened fds\n");
nethercote71980f02004-01-24 18:18:54 +00001935 VG_(init_preopened_fds)();
sewardj1fbc1a52005-04-25 02:05:54 +00001936 }
nethercote71980f02004-01-24 18:18:54 +00001937
1938 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001939 // Load debug info for the existing segments.
1940 // p: setup_code_redirect_table [so that redirs can be recorded]
1941 // p: mallocfree
1942 // p: probably: setup fds and process CLOs, so that logging works
sewardjf98e1c02008-10-25 16:22:41 +00001943 // p: initialise m_debuginfo
sewardj9c606bd2008-09-18 18:12:50 +00001944 //
1945 // While doing this, make a note of the debuginfo-handles that
sewardj6e9de462011-06-28 07:25:29 +00001946 // come back from VG_(di_notify_mmap).
sewardj9c606bd2008-09-18 18:12:50 +00001947 // Later, in "Tell the tool about the initial client memory permissions"
1948 // (just below) we can then hand these handles off to the tool in
1949 // calls to VG_TRACK(new_mem_startup, ...). This gives the tool the
1950 // opportunity to make further queries to m_debuginfo before the
1951 // client is started, if it wants. We put this information into an
1952 // XArray, each handle along with the associated segment start address,
1953 // and search the XArray for the handles later, when calling
1954 // VG_TRACK(new_mem_startup, ...).
sewardj45f4e7c2005-09-27 19:20:21 +00001955 //--------------------------------------------------------------
1956 VG_(debugLog)(1, "main", "Load initial debug info\n");
sewardj9c606bd2008-09-18 18:12:50 +00001957
1958 tl_assert(!addr2dihandle);
1959 addr2dihandle = VG_(newXA)( VG_(malloc), "main.vm.2",
1960 VG_(free), sizeof(Addr_n_ULong) );
1961 tl_assert(addr2dihandle);
1962
sewardj17c11042006-10-15 01:26:40 +00001963# if defined(VGO_linux)
sewardj45f4e7c2005-09-27 19:20:21 +00001964 { Addr* seg_starts;
1965 Int n_seg_starts;
sewardj9c606bd2008-09-18 18:12:50 +00001966 Addr_n_ULong anu;
sewardj45f4e7c2005-09-27 19:20:21 +00001967
njnac1e0332009-05-08 00:39:31 +00001968 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
sewardj17c11042006-10-15 01:26:40 +00001969 vg_assert(seg_starts && n_seg_starts >= 0);
sewardj45f4e7c2005-09-27 19:20:21 +00001970
sewardjf72cced2005-11-08 00:45:47 +00001971 /* show them all to the debug info reader. allow_SkFileV has to
1972 be True here so that we read info from the valgrind executable
1973 itself. */
sewardj9c606bd2008-09-18 18:12:50 +00001974 for (i = 0; i < n_seg_starts; i++) {
sewardj5f2dcad2011-10-24 08:53:03 +00001975 anu.ull = VG_(di_notify_mmap)( seg_starts[i], True/*allow_SkFileV*/,
1976 -1/*Don't use_fd*/);
sewardj9c606bd2008-09-18 18:12:50 +00001977 /* anu.ull holds the debuginfo handle returned by di_notify_mmap,
1978 if any. */
1979 if (anu.ull > 0) {
1980 anu.a = seg_starts[i];
1981 VG_(addToXA)( addr2dihandle, &anu );
1982 }
1983 }
sewardj45f4e7c2005-09-27 19:20:21 +00001984
1985 VG_(free)( seg_starts );
1986 }
njnf76d27a2009-05-28 01:53:07 +00001987# elif defined(VGO_darwin)
1988 { Addr* seg_starts;
1989 Int n_seg_starts;
1990 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
1991 vg_assert(seg_starts && n_seg_starts >= 0);
1992
1993 /* show them all to the debug info reader.
1994 Don't read from V segments (unlike Linux) */
1995 // GrP fixme really?
sewardj5f2dcad2011-10-24 08:53:03 +00001996 for (i = 0; i < n_seg_starts; i++) {
1997 VG_(di_notify_mmap)( seg_starts[i], False/*don't allow_SkFileV*/,
1998 -1/*don't use_fd*/);
1999 }
njnf76d27a2009-05-28 01:53:07 +00002000
2001 VG_(free)( seg_starts );
2002 }
sewardj17c11042006-10-15 01:26:40 +00002003# else
2004# error Unknown OS
2005# endif
sewardj45f4e7c2005-09-27 19:20:21 +00002006
2007 //--------------------------------------------------------------
2008 // Tell aspacem of ownership change of the asm helpers, so that
2009 // m_translate allows them to be translated. However, only do this
2010 // after the initial debug info read, since making a hole in the
2011 // address range for the stage2 binary confuses the debug info reader.
2012 // p: aspacem
2013 //--------------------------------------------------------------
2014 { Bool change_ownership_v_c_OK;
sewardj1a85f4f2006-01-12 21:15:35 +00002015 Addr co_start = VG_PGROUNDDN( (Addr)&VG_(trampoline_stuff_start) );
2016 Addr co_endPlus = VG_PGROUNDUP( (Addr)&VG_(trampoline_stuff_end) );
sewardj45f4e7c2005-09-27 19:20:21 +00002017 VG_(debugLog)(1,"redir",
2018 "transfer ownership V -> C of 0x%llx .. 0x%llx\n",
2019 (ULong)co_start, (ULong)co_endPlus-1 );
2020
2021 change_ownership_v_c_OK
2022 = VG_(am_change_ownership_v_to_c)( co_start, co_endPlus - co_start );
2023 vg_assert(change_ownership_v_c_OK);
2024 }
2025
bart6c63f5c2011-10-11 18:50:14 +00002026 if (VG_(clo_xml)) {
2027 HChar buf[50];
2028 VG_(elapsed_wallclock_time)(buf);
2029 VG_(printf_xml)( "<status>\n"
2030 " <state>RUNNING</state>\n"
2031 " <time>%pS</time>\n"
2032 "</status>\n",
2033 buf );
2034 VG_(printf_xml)( "\n" );
2035 }
2036
bart27233e92012-03-08 14:59:25 +00002037 VG_(init_Threads)();
2038
sewardj45f4e7c2005-09-27 19:20:21 +00002039 //--------------------------------------------------------------
sewardjde764e82007-11-09 23:13:22 +00002040 // Initialise the scheduler (phase 1) [generates tid_main]
2041 // p: none, afaics
2042 //--------------------------------------------------------------
2043 VG_(debugLog)(1, "main", "Initialise scheduler (phase 1)\n");
2044 tid_main = VG_(scheduler_init_phase1)();
2045 vg_assert(tid_main >= 0 && tid_main < VG_N_THREADS
2046 && tid_main != VG_INVALID_THREADID);
2047 /* Tell the tool about tid_main */
2048 VG_TRACK( pre_thread_ll_create, VG_INVALID_THREADID, tid_main );
2049
2050 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00002051 // Tell the tool about the initial client memory permissions
2052 // p: aspacem
2053 // p: mallocfree
2054 // p: setup_client_stack
2055 // p: setup_client_dataseg
sewardj9c606bd2008-09-18 18:12:50 +00002056 //
2057 // For each segment we tell the client about, look up in
2058 // addr2dihandle as created above, to see if there's a debuginfo
2059 // handle associated with the segment, that we can hand along
2060 // to the tool, to be helpful.
sewardj45f4e7c2005-09-27 19:20:21 +00002061 //--------------------------------------------------------------
2062 VG_(debugLog)(1, "main", "Tell tool about initial permissions\n");
2063 { Addr* seg_starts;
2064 Int n_seg_starts;
sewardj45f4e7c2005-09-27 19:20:21 +00002065
sewardj9c606bd2008-09-18 18:12:50 +00002066 tl_assert(addr2dihandle);
2067
tom7c1a19a2008-01-02 10:13:04 +00002068 /* Mark the main thread as running while we tell the tool about
2069 the client memory so that the tool can associate that memory
2070 with the main thread. */
2071 tl_assert(VG_(running_tid) == VG_INVALID_THREADID);
2072 VG_(running_tid) = tid_main;
2073
njnac1e0332009-05-08 00:39:31 +00002074 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
sewardj17c11042006-10-15 01:26:40 +00002075 vg_assert(seg_starts && n_seg_starts >= 0);
sewardj45f4e7c2005-09-27 19:20:21 +00002076
2077 /* show interesting ones to the tool */
2078 for (i = 0; i < n_seg_starts; i++) {
sewardj9c606bd2008-09-18 18:12:50 +00002079 Word j, n;
sewardj12ab7652006-10-17 02:10:42 +00002080 NSegment const* seg
sewardj17c11042006-10-15 01:26:40 +00002081 = VG_(am_find_nsegment)( seg_starts[i] );
sewardj45f4e7c2005-09-27 19:20:21 +00002082 vg_assert(seg);
2083 if (seg->kind == SkFileC || seg->kind == SkAnonC) {
sewardjc6d86a32009-01-31 15:08:08 +00002084 /* This next assertion is tricky. If it is placed
2085 immediately before this 'if', it very occasionally fails.
2086 Why? Because previous iterations of the loop may have
2087 caused tools (via the new_mem_startup calls) to do
2088 dynamic memory allocation, and that may affect the mapped
2089 segments; in particular it may cause segment merging to
2090 happen. Hence we cannot assume that seg_starts[i], which
2091 reflects the state of the world before we started this
2092 loop, is the same as seg->start, as the latter reflects
2093 the state of the world (viz, mappings) at this particular
2094 iteration of the loop.
2095
2096 Why does moving it inside the 'if' make it safe? Because
2097 any dynamic memory allocation done by the tools will
2098 affect only the state of Valgrind-owned segments, not of
2099 Client-owned segments. And the 'if' guards against that
2100 -- we only get in here for Client-owned segments.
2101
2102 In other words: the loop may change the state of
2103 Valgrind-owned segments as it proceeds. But it should
2104 not cause the Client-owned segments to change. */
2105 vg_assert(seg->start == seg_starts[i]);
sewardj45f4e7c2005-09-27 19:20:21 +00002106 VG_(debugLog)(2, "main",
2107 "tell tool about %010lx-%010lx %c%c%c\n",
2108 seg->start, seg->end,
2109 seg->hasR ? 'r' : '-',
2110 seg->hasW ? 'w' : '-',
2111 seg->hasX ? 'x' : '-' );
sewardj9c606bd2008-09-18 18:12:50 +00002112 /* search addr2dihandle to see if we have an entry
2113 matching seg->start. */
2114 n = VG_(sizeXA)( addr2dihandle );
2115 for (j = 0; j < n; j++) {
2116 Addr_n_ULong* anl = VG_(indexXA)( addr2dihandle, j );
2117 if (anl->a == seg->start) {
2118 tl_assert(anl->ull > 0); /* check it's a valid handle */
2119 break;
2120 }
2121 }
2122 vg_assert(j >= 0 && j <= n);
sewardj45f4e7c2005-09-27 19:20:21 +00002123 VG_TRACK( new_mem_startup, seg->start, seg->end+1-seg->start,
sewardj9c606bd2008-09-18 18:12:50 +00002124 seg->hasR, seg->hasW, seg->hasX,
2125 /* and the retrieved debuginfo handle, if any */
2126 j < n
2127 ? ((Addr_n_ULong*)VG_(indexXA)( addr2dihandle, j ))->ull
2128 : 0 );
sewardj45f4e7c2005-09-27 19:20:21 +00002129 }
2130 }
2131
2132 VG_(free)( seg_starts );
sewardj9c606bd2008-09-18 18:12:50 +00002133 VG_(deleteXA)( addr2dihandle );
sewardj45f4e7c2005-09-27 19:20:21 +00002134
2135 /* Also do the initial stack permissions. */
barte05b3a42010-09-07 16:32:53 +00002136 {
2137 SSizeT inaccessible_len;
2138 NSegment const* seg
sewardjf9d2f9b2006-11-17 20:00:57 +00002139 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
sewardj17c11042006-10-15 01:26:40 +00002140 vg_assert(seg);
2141 vg_assert(seg->kind == SkAnonC);
sewardjf9d2f9b2006-11-17 20:00:57 +00002142 vg_assert(the_iifii.initial_client_SP >= seg->start);
2143 vg_assert(the_iifii.initial_client_SP <= seg->end);
sewardj45f4e7c2005-09-27 19:20:21 +00002144
sewardj17c11042006-10-15 01:26:40 +00002145 /* Stuff below the initial SP is unaddressable. Take into
2146 account any ABI-mandated space below the stack pointer that
2147 is required (VG_STACK_REDZONE_SZB). setup_client_stack()
2148 will have allocated an extra page if a red zone is required,
2149 to be on the safe side. */
barte05b3a42010-09-07 16:32:53 +00002150 inaccessible_len = the_iifii.initial_client_SP - VG_STACK_REDZONE_SZB
2151 - seg->start;
2152 vg_assert(inaccessible_len >= 0);
2153 if (inaccessible_len > 0)
2154 VG_TRACK( die_mem_stack,
2155 seg->start,
2156 inaccessible_len );
sewardj17c11042006-10-15 01:26:40 +00002157 VG_(debugLog)(2, "main", "mark stack inaccessible %010lx-%010lx\n",
2158 seg->start,
sewardjf9d2f9b2006-11-17 20:00:57 +00002159 the_iifii.initial_client_SP-1 - VG_STACK_REDZONE_SZB);
sewardj17c11042006-10-15 01:26:40 +00002160 }
sewardj45f4e7c2005-09-27 19:20:21 +00002161
2162 /* Also the assembly helpers. */
2163 VG_TRACK( new_mem_startup,
2164 (Addr)&VG_(trampoline_stuff_start),
sewardjc6527d62006-02-13 17:54:31 +00002165 (Addr)&VG_(trampoline_stuff_end)
2166 - (Addr)&VG_(trampoline_stuff_start),
sewardj45f4e7c2005-09-27 19:20:21 +00002167 False, /* readable? */
2168 False, /* writable? */
sewardj9c606bd2008-09-18 18:12:50 +00002169 True /* executable? */,
2170 0 /* di_handle: no associated debug info */ );
tom7c1a19a2008-01-02 10:13:04 +00002171
2172 /* Clear the running thread indicator */
2173 VG_(running_tid) = VG_INVALID_THREADID;
2174 tl_assert(VG_(running_tid) == VG_INVALID_THREADID);
sewardj45f4e7c2005-09-27 19:20:21 +00002175 }
2176
2177 //--------------------------------------------------------------
sewardjde764e82007-11-09 23:13:22 +00002178 // Initialise the scheduler (phase 2)
2179 // p: Initialise the scheduler (phase 1) [for tid_main]
nethercote71980f02004-01-24 18:18:54 +00002180 // p: setup_file_descriptors() [else VG_(safe_fd)() breaks]
sewardj45f4e7c2005-09-27 19:20:21 +00002181 // p: setup_client_stack
nethercote71980f02004-01-24 18:18:54 +00002182 //--------------------------------------------------------------
sewardjde764e82007-11-09 23:13:22 +00002183 VG_(debugLog)(1, "main", "Initialise scheduler (phase 2)\n");
sewardj12ab7652006-10-17 02:10:42 +00002184 { NSegment const* seg
sewardjf9d2f9b2006-11-17 20:00:57 +00002185 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
sewardj45f4e7c2005-09-27 19:20:21 +00002186 vg_assert(seg);
2187 vg_assert(seg->kind == SkAnonC);
sewardjf9d2f9b2006-11-17 20:00:57 +00002188 vg_assert(the_iifii.initial_client_SP >= seg->start);
2189 vg_assert(the_iifii.initial_client_SP <= seg->end);
sewardjde764e82007-11-09 23:13:22 +00002190 VG_(scheduler_init_phase2)( tid_main,
2191 seg->end, the_iifii.clstack_max_size );
sewardj45f4e7c2005-09-27 19:20:21 +00002192 }
nethercote71980f02004-01-24 18:18:54 +00002193
2194 //--------------------------------------------------------------
sewardj17c11042006-10-15 01:26:40 +00002195 // Set up state for the root thread
sewardjb5f6f512005-03-10 23:59:00 +00002196 // p: ?
sewardj17c11042006-10-15 01:26:40 +00002197 // setup_scheduler() [for sched-specific thread 1 stuff]
sewardjf9d2f9b2006-11-17 20:00:57 +00002198 // VG_(ii_create_image) [for 'the_iicii' initial info]
sewardj2a99cf62004-11-24 10:44:19 +00002199 //--------------------------------------------------------------
sewardjf9d2f9b2006-11-17 20:00:57 +00002200 VG_(debugLog)(1, "main", "Finalise initial image\n");
2201 VG_(ii_finalise_image)( the_iifii );
njnea4b28c2004-11-30 16:04:58 +00002202
sewardj2a99cf62004-11-24 10:44:19 +00002203 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00002204 // Initialise the signal handling subsystem
sewardjb5f6f512005-03-10 23:59:00 +00002205 // p: n/a
nethercote71980f02004-01-24 18:18:54 +00002206 //--------------------------------------------------------------
2207 // Nb: temporarily parks the saved blocking-mask in saved_sigmask.
sewardj1fbc1a52005-04-25 02:05:54 +00002208 VG_(debugLog)(1, "main", "Initialise signal management\n");
njncda2f0f2009-05-18 02:12:08 +00002209 /* Check that the kernel-interface signal definitions look sane */
2210 VG_(vki_do_initial_consistency_checks)();
2211 /* .. and go on to use them. */
nethercote71980f02004-01-24 18:18:54 +00002212 VG_(sigstartup_actions)();
2213
2214 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00002215 // Read suppression file
sewardj95d86c02007-12-18 01:49:23 +00002216 // p: main_process_cmd_line_options() [for VG_(clo_suppressions)]
nethercote71980f02004-01-24 18:18:54 +00002217 //--------------------------------------------------------------
sewardj1fbc1a52005-04-25 02:05:54 +00002218 if (VG_(needs).core_errors || VG_(needs).tool_errors) {
2219 VG_(debugLog)(1, "main", "Load suppressions\n");
nethercote71980f02004-01-24 18:18:54 +00002220 VG_(load_suppressions)();
sewardj1fbc1a52005-04-25 02:05:54 +00002221 }
nethercote71980f02004-01-24 18:18:54 +00002222
2223 //--------------------------------------------------------------
rjwalsh0140af52005-06-04 20:42:33 +00002224 // register client stack
2225 //--------------------------------------------------------------
njn945ed2e2005-06-24 03:28:30 +00002226 VG_(clstk_id) = VG_(register_stack)(VG_(clstk_base), VG_(clstk_end));
rjwalsh0140af52005-06-04 20:42:33 +00002227
2228 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00002229 // Show the address space state so far
2230 //--------------------------------------------------------------
2231 VG_(debugLog)(1, "main", "\n");
2232 VG_(debugLog)(1, "main", "\n");
2233 VG_(am_show_nsegments)(1,"Memory layout at client startup");
2234 VG_(debugLog)(1, "main", "\n");
2235 VG_(debugLog)(1, "main", "\n");
2236
2237 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00002238 // Run!
2239 //--------------------------------------------------------------
sewardj1fbc1a52005-04-25 02:05:54 +00002240 VG_(debugLog)(1, "main", "Running thread 1\n");
sewardj1ae3f3a2005-09-28 10:47:38 +00002241
sewardj1d887112005-05-30 21:44:08 +00002242 /* As a result of the following call, the last thread standing
sewardj1ae3f3a2005-09-28 10:47:38 +00002243 eventually winds up running shutdown_actions_NORETURN
2244 just below. Unfortunately, simply exporting said function
2245 causes m_main to be part of a module cycle, which is pretty
2246 nonsensical. So instead of doing that, the address of said
2247 function is stored in a global variable 'owned' by m_syswrap,
2248 and it uses that function pointer to get back here when it needs
2249 to. */
2250
2251 /* Set continuation address. */
2252 VG_(address_of_m_main_shutdown_actions_NORETURN)
2253 = & shutdown_actions_NORETURN;
2254
2255 /* Run the first thread, eventually ending up at the continuation
2256 address. */
njnaf839f52005-06-23 03:27:57 +00002257 VG_(main_thread_wrapper_NORETURN)(1);
nethercote71980f02004-01-24 18:18:54 +00002258
sewardj1d887112005-05-30 21:44:08 +00002259 /*NOTREACHED*/
2260 vg_assert(0);
sewardjb5f6f512005-03-10 23:59:00 +00002261}
2262
sewardj17c11042006-10-15 01:26:40 +00002263/* Do everything which needs doing when the last thread exits or when
sewardj6e9de462011-06-28 07:25:29 +00002264 a thread exits requesting a complete process exit.
sewardj17c11042006-10-15 01:26:40 +00002265
2266 We enter here holding The Lock. For the case VgSrc_ExitProcess we
2267 must never release it, because to do so would allow other threads
2268 to continue after the system is ostensibly shut down. So we must
2269 go to our grave, so to speak, holding the lock.
2270
2271 In fact, there is never any point in releasing the lock at this
2272 point - we have it, we're shutting down the entire system, and
2273 for the case VgSrc_ExitProcess doing so positively causes trouble.
2274 So don't.
2275
2276 The final_tidyup call makes a bit of a nonsense of the ExitProcess
2277 case, since it will run the libc_freeres function, thus allowing
2278 other lurking threads to run again. Hmm. */
sewardjb5f6f512005-03-10 23:59:00 +00002279
sewardj1ae3f3a2005-09-28 10:47:38 +00002280static
2281void shutdown_actions_NORETURN( ThreadId tid,
2282 VgSchedReturnCode tids_schedretcode )
sewardjb5f6f512005-03-10 23:59:00 +00002283{
sewardj1d887112005-05-30 21:44:08 +00002284 VG_(debugLog)(1, "main", "entering VG_(shutdown_actions_NORETURN)\n");
sewardj17c11042006-10-15 01:26:40 +00002285 VG_(am_show_nsegments)(1,"Memory layout at client shutdown");
sewardj1d887112005-05-30 21:44:08 +00002286
sewardjb5f6f512005-03-10 23:59:00 +00002287 vg_assert(VG_(is_running_thread)(tid));
2288
sewardj12ab7652006-10-17 02:10:42 +00002289 vg_assert(tids_schedretcode == VgSrc_ExitThread
2290 || tids_schedretcode == VgSrc_ExitProcess
2291 || tids_schedretcode == VgSrc_FatalSig );
sewardjb5f6f512005-03-10 23:59:00 +00002292
sewardj12ab7652006-10-17 02:10:42 +00002293 if (tids_schedretcode == VgSrc_ExitThread) {
sewardjb5f6f512005-03-10 23:59:00 +00002294
sewardj17c11042006-10-15 01:26:40 +00002295 // We are the last surviving thread. Right?
2296 vg_assert( VG_(count_living_threads)() == 1 );
sewardjb5f6f512005-03-10 23:59:00 +00002297
sewardj17c11042006-10-15 01:26:40 +00002298 // Wait for all other threads to exit.
2299 // jrs: Huh? but they surely are already gone
2300 VG_(reap_threads)(tid);
sewardjb5f6f512005-03-10 23:59:00 +00002301
sewardj17c11042006-10-15 01:26:40 +00002302 // Clean the client up before the final report
2303 // this causes the libc_freeres function to run
2304 final_tidyup(tid);
2305
2306 /* be paranoid */
2307 vg_assert(VG_(is_running_thread)(tid));
2308 vg_assert(VG_(count_living_threads)() == 1);
2309
2310 } else {
2311
2312 // We may not be the last surviving thread. However, we
2313 // want to shut down the entire process. We hold the lock
2314 // and we need to keep hold of it all the way out, in order
2315 // that none of the other threads ever run again.
2316 vg_assert( VG_(count_living_threads)() >= 1 );
2317
sewardj17c11042006-10-15 01:26:40 +00002318 // Clean the client up before the final report
2319 // this causes the libc_freeres function to run
2320 // perhaps this is unsafe, as per comment above
2321 final_tidyup(tid);
2322
2323 /* be paranoid */
2324 vg_assert(VG_(is_running_thread)(tid));
2325 vg_assert(VG_(count_living_threads)() >= 1);
2326 }
sewardjb5f6f512005-03-10 23:59:00 +00002327
2328 VG_(threads)[tid].status = VgTs_Empty;
nethercote71980f02004-01-24 18:18:54 +00002329 //--------------------------------------------------------------
sewardj738856f2009-07-15 14:48:32 +00002330 // Finalisation: cleanup, messages, etc. Order not so important, only
nethercote71980f02004-01-24 18:18:54 +00002331 // affects what order the messages come.
2332 //--------------------------------------------------------------
njnb6267bd2009-08-12 00:14:16 +00002333 // First thing in the post-amble is a blank line.
sewardj738856f2009-07-15 14:48:32 +00002334 if (VG_(clo_xml))
2335 VG_(printf_xml)("\n");
njnb6267bd2009-08-12 00:14:16 +00002336 else if (VG_(clo_verbosity) > 0)
2337 VG_(message)(Vg_UserMsg, "\n");
nethercote71980f02004-01-24 18:18:54 +00002338
sewardj71bc3cb2005-05-19 00:25:45 +00002339 if (VG_(clo_xml)) {
sewardj68cde6f2005-07-19 12:17:51 +00002340 HChar buf[50];
sewardj592ae092005-11-08 19:01:44 +00002341 VG_(elapsed_wallclock_time)(buf);
bartb3af9cf2011-10-06 19:08:37 +00002342 VG_(printf_xml)( "<status>\n"
sewardj738856f2009-07-15 14:48:32 +00002343 " <state>FINISHED</state>\n"
bartb3af9cf2011-10-06 19:08:37 +00002344 " <time>%pS</time>\n"
njnb6267bd2009-08-12 00:14:16 +00002345 "</status>\n"
2346 "\n",
sewardj738856f2009-07-15 14:48:32 +00002347 buf);
sewardj71bc3cb2005-05-19 00:25:45 +00002348 }
2349
nethercote71980f02004-01-24 18:18:54 +00002350 /* Print out file descriptor summary and stats. */
2351 if (VG_(clo_track_fds))
nethercote3a42fb82004-08-03 18:08:50 +00002352 VG_(show_open_fds)();
nethercote71980f02004-01-24 18:18:54 +00002353
sewardj2d9e8742009-08-07 15:46:56 +00002354 /* Call the tool's finalisation function. This makes Memcheck's
2355 leak checker run, and possibly chuck a bunch of leak errors into
2356 the error management machinery. */
2357 VG_TDICT_CALL(tool_fini, 0/*exitcode*/);
nethercote71980f02004-01-24 18:18:54 +00002358
sewardj2d9e8742009-08-07 15:46:56 +00002359 /* Show the error counts. */
sewardj7ca100d2009-08-15 23:05:34 +00002360 if (VG_(clo_xml)
2361 && (VG_(needs).core_errors || VG_(needs).tool_errors)) {
sewardj2d9e8742009-08-07 15:46:56 +00002362 VG_(show_error_counts_as_XML)();
sewardj738856f2009-07-15 14:48:32 +00002363 }
sewardj2d9e8742009-08-07 15:46:56 +00002364
2365 /* In XML mode, this merely prints the used suppressions. */
2366 if (VG_(needs).core_errors || VG_(needs).tool_errors)
sewardj3b290482011-05-06 21:02:55 +00002367 VG_(show_all_errors)(VG_(clo_verbosity), VG_(clo_xml));
nethercote71980f02004-01-24 18:18:54 +00002368
sewardj71bc3cb2005-05-19 00:25:45 +00002369 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +00002370 VG_(printf_xml)("\n");
2371 VG_(printf_xml)("</valgrindoutput>\n");
2372 VG_(printf_xml)("\n");
sewardj71bc3cb2005-05-19 00:25:45 +00002373 }
2374
nethercote885dd912004-08-03 23:14:00 +00002375 VG_(sanity_check_general)( True /*include expensive checks*/ );
nethercote71980f02004-01-24 18:18:54 +00002376
sewardj2d9e8742009-08-07 15:46:56 +00002377 if (VG_(clo_stats))
nethercote3a42fb82004-08-03 18:08:50 +00002378 print_all_stats();
nethercote71980f02004-01-24 18:18:54 +00002379
sewardj9c606bd2008-09-18 18:12:50 +00002380 /* Show a profile of the heap(s) at shutdown. Optionally, first
2381 throw away all the debug info, as that makes it easy to spot
2382 leaks in the debuginfo reader. */
2383 if (VG_(clo_profile_heap)) {
2384 if (0) VG_(di_discard_ALL_debuginfo)();
2385 VG_(print_arena_cc_analysis)();
2386 }
2387
njn2025cf92005-06-26 20:44:48 +00002388 if (VG_(clo_profile_flags) > 0) {
sewardj5471ec62006-10-17 13:58:17 +00002389 #define N_MAX 200
njn2025cf92005-06-26 20:44:48 +00002390 BBProfEntry tops[N_MAX];
2391 ULong score_total = VG_(get_BB_profile) (tops, N_MAX);
2392 show_BB_profile(tops, N_MAX, score_total);
2393 }
sewardjfa8ec112005-01-19 11:55:34 +00002394
sewardj8b635a42004-11-22 19:01:47 +00002395 /* Print Vex storage stats */
sewardjbf426512005-01-17 18:35:30 +00002396 if (0)
2397 LibVEX_ShowAllocStats();
sewardj1d887112005-05-30 21:44:08 +00002398
sewardj738856f2009-07-15 14:48:32 +00002399 /* Flush any output cached by previous calls to VG_(message). */
2400 VG_(message_flush)();
2401
sewardj3b290482011-05-06 21:02:55 +00002402 /* terminate gdbserver if ever it was started. We terminate it here so that it get
2403 the output above if output was redirected to gdb */
2404 VG_(gdbserver) (0);
2405
njn8aa35852005-06-10 22:59:56 +00002406 /* Ok, finally exit in the os-specific way, according to the scheduler's
2407 return code. In short, if the (last) thread exited by calling
2408 sys_exit, do likewise; if the (last) thread stopped due to a fatal
2409 signal, terminate the entire system with that same fatal signal. */
2410 VG_(debugLog)(1, "core_os",
njn7b85dd52005-06-12 17:26:29 +00002411 "VG_(terminate_NORETURN)(tid=%lld)\n", (ULong)tid);
njn8aa35852005-06-10 22:59:56 +00002412
njn8aa35852005-06-10 22:59:56 +00002413 switch (tids_schedretcode) {
sewardj12ab7652006-10-17 02:10:42 +00002414 case VgSrc_ExitThread: /* the normal way out (Linux) */
sewardj6e9de462011-06-28 07:25:29 +00002415 case VgSrc_ExitProcess: /* the normal way out (AIX) -- still needed? */
sewardjb9779082006-05-12 23:50:15 +00002416 /* Change the application return code to user's return code,
2417 if an error was found */
2418 if (VG_(clo_error_exitcode) > 0
2419 && VG_(get_n_errs_found)() > 0) {
2420 VG_(exit)( VG_(clo_error_exitcode) );
2421 } else {
2422 /* otherwise, return the client's exit code, in the normal
2423 way. */
2424 VG_(exit)( VG_(threads)[tid].os_state.exitcode );
2425 }
njn8aa35852005-06-10 22:59:56 +00002426 /* NOT ALIVE HERE! */
sewardj17c11042006-10-15 01:26:40 +00002427 VG_(core_panic)("entered the afterlife in main() -- ExitT/P");
njn8aa35852005-06-10 22:59:56 +00002428 break; /* what the hell :) */
2429
2430 case VgSrc_FatalSig:
2431 /* We were killed by a fatal signal, so replicate the effect */
2432 vg_assert(VG_(threads)[tid].os_state.fatalsig != 0);
2433 VG_(kill_self)(VG_(threads)[tid].os_state.fatalsig);
njnf76d27a2009-05-28 01:53:07 +00002434 /* we shouldn't be alive at this point. But VG_(kill_self)
2435 sometimes fails with EPERM on Darwin, for unclear reasons. */
2436# if defined(VGO_darwin)
2437 VG_(debugLog)(0, "main", "VG_(kill_self) failed. Exiting normally.\n");
2438 VG_(exit)(0); /* bogus, but we really need to exit now */
2439 /* fall through .. */
2440# endif
njn8aa35852005-06-10 22:59:56 +00002441 VG_(core_panic)("main(): signal was supposed to be fatal");
2442 break;
2443
2444 default:
2445 VG_(core_panic)("main(): unexpected scheduler return code");
2446 }
njne96be672005-05-08 19:08:54 +00002447}
sewardj8b635a42004-11-22 19:01:47 +00002448
sewardj1ae3f3a2005-09-28 10:47:38 +00002449/* -------------------- */
2450
2451/* Final clean-up before terminating the process.
2452 Clean up the client by calling __libc_freeres() (if requested)
2453 This is Linux-specific?
njnf76d27a2009-05-28 01:53:07 +00002454 GrP fixme glibc-specific, anyway
sewardj1ae3f3a2005-09-28 10:47:38 +00002455*/
2456static void final_tidyup(ThreadId tid)
2457{
njnf76d27a2009-05-28 01:53:07 +00002458#if !defined(VGO_darwin)
sewardjcf951812006-01-17 02:22:21 +00002459# if defined(VGP_ppc64_linux)
2460 Addr r2;
2461# endif
sewardj0ec07f32006-01-12 12:32:32 +00002462 Addr __libc_freeres_wrapper = VG_(client___libc_freeres_wrapper);
sewardj1ae3f3a2005-09-28 10:47:38 +00002463
2464 vg_assert(VG_(is_running_thread)(tid));
2465
2466 if ( !VG_(needs).libc_freeres ||
2467 !VG_(clo_run_libc_freeres) ||
sewardj0ec07f32006-01-12 12:32:32 +00002468 0 == __libc_freeres_wrapper )
sewardj1ae3f3a2005-09-28 10:47:38 +00002469 return; /* can't/won't do it */
2470
sewardjcf951812006-01-17 02:22:21 +00002471# if defined(VGP_ppc64_linux)
2472 r2 = VG_(get_tocptr)( __libc_freeres_wrapper );
2473 if (r2 == 0) {
2474 VG_(message)(Vg_UserMsg,
sewardj738856f2009-07-15 14:48:32 +00002475 "Caught __NR_exit, but can't run __libc_freeres()\n");
sewardjcf951812006-01-17 02:22:21 +00002476 VG_(message)(Vg_UserMsg,
sewardj738856f2009-07-15 14:48:32 +00002477 " since cannot establish TOC pointer for it.\n");
sewardjcf951812006-01-17 02:22:21 +00002478 return;
2479 }
2480# endif
2481
sewardj1ae3f3a2005-09-28 10:47:38 +00002482 if (VG_(clo_verbosity) > 2 ||
2483 VG_(clo_trace_syscalls) ||
2484 VG_(clo_trace_sched))
2485 VG_(message)(Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +00002486 "Caught __NR_exit; running __libc_freeres()\n");
sewardj1ae3f3a2005-09-28 10:47:38 +00002487
sewardj0ec07f32006-01-12 12:32:32 +00002488 /* set thread context to point to libc_freeres_wrapper */
sewardj1a85f4f2006-01-12 21:15:35 +00002489 /* ppc64-linux note: __libc_freeres_wrapper gives us the real
2490 function entry point, not a fn descriptor, so can use it
2491 directly. However, we need to set R2 (the toc pointer)
2492 appropriately. */
sewardj1ae3f3a2005-09-28 10:47:38 +00002493 VG_(set_IP)(tid, __libc_freeres_wrapper);
sewardjcf951812006-01-17 02:22:21 +00002494# if defined(VGP_ppc64_linux)
2495 VG_(threads)[tid].arch.vex.guest_GPR2 = r2;
2496# endif
sewardj5db15402012-06-07 09:13:21 +00002497 /* mips-linux note: we need to set t9 */
2498# if defined(VGP_mips32_linux)
2499 VG_(threads)[tid].arch.vex.guest_r25 = __libc_freeres_wrapper;
2500# endif
sewardj1ae3f3a2005-09-28 10:47:38 +00002501
2502 /* Block all blockable signals by copying the real block state into
2503 the thread's block state*/
2504 VG_(sigprocmask)(VKI_SIG_BLOCK, NULL, &VG_(threads)[tid].sig_mask);
2505 VG_(threads)[tid].tmp_sig_mask = VG_(threads)[tid].sig_mask;
2506
2507 /* and restore handlers to default */
2508 VG_(set_default_handler)(VKI_SIGSEGV);
2509 VG_(set_default_handler)(VKI_SIGBUS);
2510 VG_(set_default_handler)(VKI_SIGILL);
2511 VG_(set_default_handler)(VKI_SIGFPE);
2512
2513 // We were exiting, so assert that...
2514 vg_assert(VG_(is_exiting)(tid));
2515 // ...but now we're not again
2516 VG_(threads)[tid].exitreason = VgSrc_None;
2517
2518 // run until client thread exits - ideally with LIBC_FREERES_DONE,
2519 // but exit/exitgroup/signal will do
2520 VG_(scheduler)(tid);
2521
2522 vg_assert(VG_(is_exiting)(tid));
njnf76d27a2009-05-28 01:53:07 +00002523#endif
sewardj1ae3f3a2005-09-28 10:47:38 +00002524}
2525
sewardj45f4e7c2005-09-27 19:20:21 +00002526
2527/*====================================================================*/
njn49f80e82009-05-21 01:25:43 +00002528/*=== Getting to main() alive: LINUX ===*/
sewardj45f4e7c2005-09-27 19:20:21 +00002529/*====================================================================*/
2530
sewardj17c11042006-10-15 01:26:40 +00002531#if defined(VGO_linux)
2532
sewardj45f4e7c2005-09-27 19:20:21 +00002533/* If linking of the final executables is done with glibc present,
2534 then Valgrind starts at main() above as usual, and all of the
2535 following code is irrelevant.
2536
2537 However, this is not the intended mode of use. The plan is to
2538 avoid linking against glibc, by giving gcc the flags
2539 -nodefaultlibs -lgcc -nostartfiles at startup.
2540
2541 From this derive two requirements:
2542
2543 1. gcc may emit calls to memcpy and memset to deal with structure
2544 assignments etc. Since we have chosen to ignore all the
2545 "normal" supporting libraries, we have to provide our own
2546 implementations of them. No problem.
2547
2548 2. We have to provide a symbol "_start", to which the kernel
2549 hands control at startup. Hence the code below.
2550*/
2551
2552/* ---------------- Requirement 1 ---------------- */
2553
sewardj17c11042006-10-15 01:26:40 +00002554void* memcpy(void *dest, const void *src, SizeT n);
2555void* memcpy(void *dest, const void *src, SizeT n) {
sewardj45f4e7c2005-09-27 19:20:21 +00002556 return VG_(memcpy)(dest,src,n);
2557}
sewardj17c11042006-10-15 01:26:40 +00002558void* memset(void *s, int c, SizeT n);
2559void* memset(void *s, int c, SizeT n) {
sewardj45f4e7c2005-09-27 19:20:21 +00002560 return VG_(memset)(s,c,n);
2561}
2562
bart82616e12010-06-13 13:46:24 +00002563/* BVA: abort() for those platforms that need it (PPC and ARM). */
2564void abort(void);
2565void abort(void){
2566 VG_(printf)("Something called raise().\n");
2567 vg_assert(0);
2568}
2569
sewardj59570ff2010-01-01 11:59:33 +00002570/* EAZG: ARM's EABI will call floating point exception handlers in
2571 libgcc which boil down to an abort or raise, that's usually defined
2572 in libc. Instead, define them here. */
2573#if defined(VGP_arm_linux)
2574void raise(void);
2575void raise(void){
2576 VG_(printf)("Something called raise().\n");
2577 vg_assert(0);
2578}
2579
sewardj59570ff2010-01-01 11:59:33 +00002580void __aeabi_unwind_cpp_pr0(void);
2581void __aeabi_unwind_cpp_pr0(void){
2582 VG_(printf)("Something called __aeabi_unwind_cpp_pr0()\n");
2583 vg_assert(0);
2584}
sewardj38efe4b2010-08-22 12:23:01 +00002585
2586void __aeabi_unwind_cpp_pr1(void);
2587void __aeabi_unwind_cpp_pr1(void){
2588 VG_(printf)("Something called __aeabi_unwind_cpp_pr1()\n");
2589 vg_assert(0);
2590}
sewardj59570ff2010-01-01 11:59:33 +00002591#endif
2592
sewardj45f4e7c2005-09-27 19:20:21 +00002593/* ---------------- Requirement 2 ---------------- */
2594
2595/* Glibc's sysdeps/i386/elf/start.S has the following gem of a
2596 comment, which explains how the stack looks right at process start
2597 (when _start is jumped to). Hence _start passes %esp to
sewardj17c11042006-10-15 01:26:40 +00002598 _start_in_C_linux, which extracts argc/argv/envp and starts up
sewardj45f4e7c2005-09-27 19:20:21 +00002599 correctly. */
2600
2601/* This is the canonical entry point, usually the first thing in the text
2602 segment. The SVR4/i386 ABI (pages 3-31, 3-32) says that when the entry
2603 point runs, most registers' values are unspecified, except for:
2604
2605 %edx Contains a function pointer to be registered with `atexit'.
2606 This is how the dynamic linker arranges to have DT_FINI
2607 functions called for shared libraries that have been loaded
2608 before this code runs.
2609
2610 %esp The stack contains the arguments and environment:
2611 0(%esp) argc
2612 4(%esp) argv[0]
2613 ...
2614 (4*argc)(%esp) NULL
2615 (4*(argc+1))(%esp) envp[0]
2616 ...
2617 NULL
2618*/
2619
2620/* The kernel hands control to _start, which extracts the initial
sewardj17c11042006-10-15 01:26:40 +00002621 stack pointer and calls onwards to _start_in_C_linux. This also switches
sewardja48a4932005-09-29 11:09:56 +00002622 the new stack. */
sewardj45f4e7c2005-09-27 19:20:21 +00002623#if defined(VGP_x86_linux)
2624asm("\n"
sewardjd9fc3822005-11-18 23:50:43 +00002625 ".text\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002626 "\t.globl _start\n"
2627 "\t.type _start,@function\n"
2628 "_start:\n"
2629 /* set up the new stack in %eax */
sewardjfdf91b42005-09-28 00:53:09 +00002630 "\tmovl $vgPlain_interim_stack, %eax\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002631 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
2632 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
2633 "\tsubl $16, %eax\n"
2634 "\tandl $~15, %eax\n"
2635 /* install it, and collect the original one */
2636 "\txchgl %eax, %esp\n"
sewardj17c11042006-10-15 01:26:40 +00002637 /* call _start_in_C_linux, passing it the startup %esp */
sewardj45f4e7c2005-09-27 19:20:21 +00002638 "\tpushl %eax\n"
sewardj17c11042006-10-15 01:26:40 +00002639 "\tcall _start_in_C_linux\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002640 "\thlt\n"
sewardj2fedc642005-11-19 02:02:57 +00002641 ".previous\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002642);
2643#elif defined(VGP_amd64_linux)
2644asm("\n"
sewardjd9fc3822005-11-18 23:50:43 +00002645 ".text\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002646 "\t.globl _start\n"
2647 "\t.type _start,@function\n"
2648 "_start:\n"
2649 /* set up the new stack in %rdi */
sewardjfdf91b42005-09-28 00:53:09 +00002650 "\tmovq $vgPlain_interim_stack, %rdi\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002651 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
2652 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
2653 "\tandq $~15, %rdi\n"
2654 /* install it, and collect the original one */
2655 "\txchgq %rdi, %rsp\n"
sewardj17c11042006-10-15 01:26:40 +00002656 /* call _start_in_C_linux, passing it the startup %rsp */
2657 "\tcall _start_in_C_linux\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002658 "\thlt\n"
sewardj2fedc642005-11-19 02:02:57 +00002659 ".previous\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002660);
sewardja48a4932005-09-29 11:09:56 +00002661#elif defined(VGP_ppc32_linux)
2662asm("\n"
sewardjd9fc3822005-11-18 23:50:43 +00002663 ".text\n"
sewardja48a4932005-09-29 11:09:56 +00002664 "\t.globl _start\n"
2665 "\t.type _start,@function\n"
2666 "_start:\n"
2667 /* set up the new stack in r16 */
2668 "\tlis 16,vgPlain_interim_stack@ha\n"
2669 "\tla 16,vgPlain_interim_stack@l(16)\n"
2670 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2671 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2672 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2673 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2674 "\tadd 16,17,16\n"
2675 "\tadd 16,18,16\n"
2676 "\trlwinm 16,16,0,0,27\n"
2677 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2678 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2679 boundary. And r1 is the original SP. Set the SP to r16 and
sewardj17c11042006-10-15 01:26:40 +00002680 call _start_in_C_linux, passing it the initial SP. */
sewardja48a4932005-09-29 11:09:56 +00002681 "\tmr 3,1\n"
2682 "\tmr 1,16\n"
sewardj17c11042006-10-15 01:26:40 +00002683 "\tbl _start_in_C_linux\n"
sewardja48a4932005-09-29 11:09:56 +00002684 "\ttrap\n"
sewardj2fedc642005-11-19 02:02:57 +00002685 ".previous\n"
sewardja48a4932005-09-29 11:09:56 +00002686);
sewardj2c48c7b2005-11-29 13:05:56 +00002687#elif defined(VGP_ppc64_linux)
2688asm("\n"
cerion21082042005-12-06 19:07:08 +00002689 /* PPC64 ELF ABI says '_start' points to a function descriptor.
2690 So we must have one, and that is what goes into the .opd section. */
cerion297c88f2005-12-22 15:53:12 +00002691 "\t.align 2\n"
cerion21082042005-12-06 19:07:08 +00002692 "\t.global _start\n"
2693 "\t.section \".opd\",\"aw\"\n"
2694 "\t.align 3\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002695 "_start:\n"
cerion21082042005-12-06 19:07:08 +00002696 "\t.quad ._start,.TOC.@tocbase,0\n"
2697 "\t.previous\n"
2698 "\t.type ._start,@function\n"
2699 "\t.global ._start\n"
2700 "._start:\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002701 /* set up the new stack in r16 */
2702 "\tlis 16, vgPlain_interim_stack@highest\n"
2703 "\tori 16,16,vgPlain_interim_stack@higher\n"
2704 "\tsldi 16,16,32\n"
2705 "\toris 16,16,vgPlain_interim_stack@h\n"
2706 "\tori 16,16,vgPlain_interim_stack@l\n"
2707 "\txor 17,17,17\n"
2708 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2709 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2710 "\txor 18,18,18\n"
2711 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2712 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2713 "\tadd 16,17,16\n"
2714 "\tadd 16,18,16\n"
2715 "\trldicr 16,16,0,59\n"
2716 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2717 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2718 boundary. And r1 is the original SP. Set the SP to r16 and
sewardj17c11042006-10-15 01:26:40 +00002719 call _start_in_C_linux, passing it the initial SP. */
sewardj2c48c7b2005-11-29 13:05:56 +00002720 "\tmr 3,1\n"
2721 "\tmr 1,16\n"
sewardj17c11042006-10-15 01:26:40 +00002722 "\tbl ._start_in_C_linux\n"
cerion21082042005-12-06 19:07:08 +00002723 "\tnop\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002724 "\ttrap\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002725);
sewardjb5b87402011-03-07 16:05:35 +00002726#elif defined(VGP_s390x_linux)
2727/*
2728 This is the canonical entry point, usually the first thing in the text
2729 segment. Most registers' values are unspecified, except for:
2730
2731 %r14 Contains a function pointer to be registered with `atexit'.
2732 This is how the dynamic linker arranges to have DT_FINI
2733 functions called for shared libraries that have been loaded
2734 before this code runs.
2735
2736 %r15 The stack contains the arguments and environment:
2737 0(%r15) argc
2738 8(%r15) argv[0]
2739 ...
2740 (8*argc)(%r15) NULL
2741 (8*(argc+1))(%r15) envp[0]
2742 ...
2743 NULL
2744*/
2745asm("\n\t"
2746 ".text\n\t"
2747 ".globl _start\n\t"
2748 ".type _start,@function\n\t"
2749 "_start:\n\t"
2750 /* set up the new stack in %r1 */
2751 "larl %r1, vgPlain_interim_stack\n\t"
2752 "larl %r5, 1f\n\t"
2753 "ag %r1, 0(%r5)\n\t"
2754 "ag %r1, 2f-1f(%r5)\n\t"
2755 "nill %r1, 0xFFF0\n\t"
2756 /* install it, and collect the original one */
2757 "lgr %r2, %r15\n\t"
2758 "lgr %r15, %r1\n\t"
2759 /* call _start_in_C_linux, passing it the startup %r15 */
2760 "brasl %r14, _start_in_C_linux\n\t"
2761 /* trigger execution of an invalid opcode -> halt machine */
2762 "j .+2\n\t"
2763 "1: .quad "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n\t"
2764 "2: .quad "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n\t"
2765 ".previous\n"
2766);
sewardj59570ff2010-01-01 11:59:33 +00002767#elif defined(VGP_arm_linux)
2768asm("\n"
sewardjb51c9262011-05-03 14:24:11 +00002769 "\t.text\n"
2770 "\t.align 4\n"
2771 "\t.type _start,#function\n"
sewardj59570ff2010-01-01 11:59:33 +00002772 "\t.global _start\n"
2773 "_start:\n"
2774 "\tldr r0, [pc, #36]\n"
2775 "\tldr r1, [pc, #36]\n"
2776 "\tadd r0, r1, r0\n"
2777 "\tldr r1, [pc, #32]\n"
2778 "\tadd r0, r1, r0\n"
2779 "\tmvn r1, #15\n"
2780 "\tand r0, r0, r1\n"
2781 "\tmov r1, sp\n"
2782 "\tmov sp, r0\n"
2783 "\tmov r0, r1\n"
2784 "\tb _start_in_C_linux\n"
2785 "\t.word vgPlain_interim_stack\n"
2786 "\t.word "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
2787 "\t.word "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
2788);
sewardj5db15402012-06-07 09:13:21 +00002789#elif defined(VGP_mips32_linux)
2790asm("\n"
2791 "\t.type _gp_disp,@object\n"
2792 ".text\n"
2793 "\t.globl __start\n"
2794 "\t.type __start,@function\n"
2795 "__start:\n"
2796
2797 "\tbal 1f\n"
2798 "\tnop\n"
2799
2800 "1:\n"
2801
2802 "\tlui $28, %hi(_gp_disp)\n"
2803 "\taddiu $28, $28, %lo(_gp_disp)\n"
2804 "\taddu $28, $28, $31\n"
2805 /* t1/$9 <- Addr(interim_stack) */
2806 "\tlui $9, %hi(vgPlain_interim_stack)\n"
2807 /* t1/$9 <- Addr(interim_stack) */
2808 "\taddiu $9, %lo(vgPlain_interim_stack)\n"
2809
2810
2811 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
2812 "\tli $11, "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
2813
2814 "\taddu $9, $9, $10\n"
2815 "\taddu $9, $9, $11\n"
2816 "\tli $12, 0xFFFFFFF0\n"
2817 "\tand $9, $9, $12\n"
2818 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2819 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2820 boundary. And $29 is the original SP. Set the SP to t1 and
2821 call _start_in_C, passing it the initial SP. */
2822
2823 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
2824 "\tmove $29, $9\n" // $sp <- t1 (new sp)
2825
2826 "\tlui $25, %hi(_start_in_C_linux)\n"
2827 "\taddiu $25, %lo(_start_in_C_linux)\n"
2828
2829 "\tbal _start_in_C_linux\n"
2830 "\tbreak 0x7\n"
2831 ".previous\n"
2832);
sewardj45f4e7c2005-09-27 19:20:21 +00002833#else
njn49f80e82009-05-21 01:25:43 +00002834# error "Unknown linux platform"
sewardj45f4e7c2005-09-27 19:20:21 +00002835#endif
2836
sewardje66f2e02006-12-30 17:45:08 +00002837/* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
2838#define _GNU_SOURCE
2839#define _FILE_OFFSET_BITS 64
2840/* This is in order to get AT_NULL and AT_PAGESIZE. */
2841#include <elf.h>
2842/* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
2843
sewardj45f4e7c2005-09-27 19:20:21 +00002844/* Avoid compiler warnings: this fn _is_ used, but labelling it
philippe9fdca562012-04-16 22:06:47 +00002845 'static' causes gcc to complain it isn't.
2846 attribute 'used' also ensures the code is not eliminated at link
2847 time */
2848__attribute__ ((used))
sewardj17c11042006-10-15 01:26:40 +00002849void _start_in_C_linux ( UWord* pArgc );
philippe9fdca562012-04-16 22:06:47 +00002850__attribute__ ((used))
sewardj17c11042006-10-15 01:26:40 +00002851void _start_in_C_linux ( UWord* pArgc )
sewardj45f4e7c2005-09-27 19:20:21 +00002852{
2853 Int r;
2854 Word argc = pArgc[0];
2855 HChar** argv = (HChar**)&pArgc[1];
2856 HChar** envp = (HChar**)&pArgc[1+argc+1];
sewardjf9d2f9b2006-11-17 20:00:57 +00002857
2858 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
2859 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
2860
2861 the_iicii.sp_at_startup = (Addr)pArgc;
2862
sewardje66f2e02006-12-30 17:45:08 +00002863# if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux)
2864 {
2865 /* ppc/ppc64 can be configured with different page sizes.
2866 Determine this early. This is an ugly hack and really should
2867 be moved into valgrind_main. */
2868 UWord *sp = &pArgc[1+argc+1];
2869 while (*sp++ != 0)
2870 ;
2871 for (; *sp != AT_NULL && *sp != AT_PAGESZ; sp += 2);
2872 if (*sp == AT_PAGESZ) {
2873 VKI_PAGE_SIZE = sp[1];
2874 for (VKI_PAGE_SHIFT = 12;
2875 VKI_PAGE_SHIFT <= VKI_MAX_PAGE_SHIFT; VKI_PAGE_SHIFT++)
2876 if (VKI_PAGE_SIZE == (1UL << VKI_PAGE_SHIFT))
2877 break;
2878 }
2879 }
2880# endif
2881
sewardjf9d2f9b2006-11-17 20:00:57 +00002882 r = valgrind_main( (Int)argc, argv, envp );
sewardj17c11042006-10-15 01:26:40 +00002883 /* NOTREACHED */
sewardj45f4e7c2005-09-27 19:20:21 +00002884 VG_(exit)(r);
2885}
2886
sewardj17c11042006-10-15 01:26:40 +00002887
2888/*====================================================================*/
njnf76d27a2009-05-28 01:53:07 +00002889/*=== Getting to main() alive: darwin ===*/
2890/*====================================================================*/
2891
2892#elif defined(VGO_darwin)
2893
njnea2d6fd2010-07-01 00:20:20 +00002894/*
2895 Memory layout established by kernel:
2896
2897 0(%esp) argc
2898 4(%esp) argv[0]
2899 ...
2900 argv[argc-1]
2901 NULL
2902 envp[0]
2903 ...
2904 envp[n]
2905 NULL
2906 executable name (presumably, a pointer to it)
2907 NULL
2908
2909 Ditto in the 64-bit case, except all offsets from SP are obviously
2910 twice as large.
2911*/
2912
2913/* The kernel hands control to _start, which extracts the initial
2914 stack pointer and calls onwards to _start_in_C_darwin. This also
2915 switches to the new stack. */
2916#if defined(VGP_x86_darwin)
2917asm("\n"
2918 ".text\n"
2919 ".align 2,0x90\n"
2920 "\t.globl __start\n"
2921 "__start:\n"
2922 /* set up the new stack in %eax */
2923 "\tmovl $_vgPlain_interim_stack, %eax\n"
2924 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
2925 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
2926 "\tsubl $16, %eax\n"
2927 "\tandl $~15, %eax\n"
2928 /* install it, and collect the original one */
2929 "\txchgl %eax, %esp\n"
sewardj69197362012-03-07 16:38:12 +00002930 "\tsubl $12, %esp\n" // keep stack 16 aligned; see #295428
njnea2d6fd2010-07-01 00:20:20 +00002931 /* call _start_in_C_darwin, passing it the startup %esp */
2932 "\tpushl %eax\n"
2933 "\tcall __start_in_C_darwin\n"
2934 "\tint $3\n"
2935 "\tint $3\n"
2936);
2937#elif defined(VGP_amd64_darwin)
2938asm("\n"
2939 ".text\n"
2940 "\t.globl __start\n"
2941 ".align 3,0x90\n"
2942 "__start:\n"
2943 /* set up the new stack in %rdi */
2944 "\tmovabsq $_vgPlain_interim_stack, %rdi\n"
2945 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
2946 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
2947 "\tandq $~15, %rdi\n"
2948 /* install it, and collect the original one */
2949 "\txchgq %rdi, %rsp\n"
2950 /* call _start_in_C_darwin, passing it the startup %rsp */
2951 "\tcall __start_in_C_darwin\n"
2952 "\tint $3\n"
2953 "\tint $3\n"
2954);
2955#endif
2956
njnf76d27a2009-05-28 01:53:07 +00002957void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2);
2958void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2) {
2959 // skip check
2960 return VG_(memcpy)(dest,src,n);
2961}
2962void* __memset_chk(void *s, int c, SizeT n, SizeT n2);
2963void* __memset_chk(void *s, int c, SizeT n, SizeT n2) {
2964 // skip check
2965 return VG_(memset)(s,c,n);
2966}
2967void bzero(void *s, SizeT n);
2968void bzero(void *s, SizeT n) {
2969 VG_(memset)(s,0,n);
2970}
2971
2972void* memcpy(void *dest, const void *src, SizeT n);
2973void* memcpy(void *dest, const void *src, SizeT n) {
2974 return VG_(memcpy)(dest,src,n);
2975}
2976void* memset(void *s, int c, SizeT n);
2977void* memset(void *s, int c, SizeT n) {
2978 return VG_(memset)(s,c,n);
2979}
2980
njnf76d27a2009-05-28 01:53:07 +00002981/* Avoid compiler warnings: this fn _is_ used, but labelling it
2982 'static' causes gcc to complain it isn't. */
2983void _start_in_C_darwin ( UWord* pArgc );
2984void _start_in_C_darwin ( UWord* pArgc )
2985{
2986 Int r;
njnea2d6fd2010-07-01 00:20:20 +00002987 Int argc = *(Int *)pArgc; // not pArgc[0] on LP64
njnf76d27a2009-05-28 01:53:07 +00002988 HChar** argv = (HChar**)&pArgc[1];
2989 HChar** envp = (HChar**)&pArgc[1+argc+1];
2990
2991 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
2992 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
2993
2994 the_iicii.sp_at_startup = (Addr)pArgc;
2995
2996 r = valgrind_main( (Int)argc, argv, envp );
2997 /* NOTREACHED */
2998 VG_(exit)(r);
2999}
3000
3001
njn49f80e82009-05-21 01:25:43 +00003002#else
3003
3004# error "Unknown OS"
3005#endif
sewardj17c11042006-10-15 01:26:40 +00003006
3007
sewardj0af71bb2010-07-01 14:50:30 +00003008/*====================================================================*/
3009/*=== {u,}{div,mod}di3 replacements ===*/
3010/*====================================================================*/
njnea2d6fd2010-07-01 00:20:20 +00003011
3012/* For static linking on x86-darwin, we need to supply our own 64-bit
3013 integer division code, else the link dies thusly:
3014
3015 ld_classic: Undefined symbols:
3016 ___udivdi3
3017 ___umoddi3
3018*/
3019#if defined(VGP_x86_darwin)
3020
3021/* Routines for doing signed/unsigned 64 x 64 ==> 64 div and mod
3022 (udivdi3, umoddi3, divdi3, moddi3) using only 32 x 32 ==> 32
3023 division. Cobbled together from
3024
3025 http://www.hackersdelight.org/HDcode/divlu.c
3026 http://www.hackersdelight.org/HDcode/divls.c
3027 http://www.hackersdelight.org/HDcode/newCode/divDouble.c
3028
3029 The code from those three files is covered by the following license,
3030 as it appears at:
3031
3032 http://www.hackersdelight.org/permissions.htm
3033
3034 You are free to use, copy, and distribute any of the code on
3035 this web site, whether modified by you or not. You need not give
3036 attribution. This includes the algorithms (some of which appear
3037 in Hacker's Delight), the Hacker's Assistant, and any code
3038 submitted by readers. Submitters implicitly agree to this.
3039*/
3040
3041/* Long division, unsigned (64/32 ==> 32).
3042 This procedure performs unsigned "long division" i.e., division of a
304364-bit unsigned dividend by a 32-bit unsigned divisor, producing a
304432-bit quotient. In the overflow cases (divide by 0, or quotient
3045exceeds 32 bits), it returns a remainder of 0xFFFFFFFF (an impossible
3046value).
3047 The dividend is u1 and u0, with u1 being the most significant word.
3048The divisor is parameter v. The value returned is the quotient.
3049 Max line length is 57, to fit in hacker.book. */
3050
3051static Int nlz32(UInt x)
3052{
3053 Int n;
3054 if (x == 0) return(32);
3055 n = 0;
3056 if (x <= 0x0000FFFF) {n = n +16; x = x <<16;}
3057 if (x <= 0x00FFFFFF) {n = n + 8; x = x << 8;}
3058 if (x <= 0x0FFFFFFF) {n = n + 4; x = x << 4;}
3059 if (x <= 0x3FFFFFFF) {n = n + 2; x = x << 2;}
3060 if (x <= 0x7FFFFFFF) {n = n + 1;}
3061 return n;
3062}
3063
3064/* 64 x 32 ==> 32 unsigned division, using only 32 x 32 ==> 32
3065 division as a primitive. */
3066static UInt divlu2(UInt u1, UInt u0, UInt v, UInt *r)
3067{
3068 const UInt b = 65536; // Number base (16 bits).
3069 UInt un1, un0, // Norm. dividend LSD's.
3070 vn1, vn0, // Norm. divisor digits.
3071 q1, q0, // Quotient digits.
3072 un32, un21, un10, // Dividend digit pairs.
3073 rhat; // A remainder.
3074 Int s; // Shift amount for norm.
3075
3076 if (u1 >= v) { // If overflow, set rem.
3077 if (r != NULL) // to an impossible value,
3078 *r = 0xFFFFFFFF; // and return the largest
3079 return 0xFFFFFFFF;} // possible quotient.
3080
3081 s = nlz32(v); // 0 <= s <= 31.
3082 v = v << s; // Normalize divisor.
3083 vn1 = v >> 16; // Break divisor up into
3084 vn0 = v & 0xFFFF; // two 16-bit digits.
3085
3086 un32 = (u1 << s) | ((u0 >> (32 - s)) & (-s >> 31));
3087 un10 = u0 << s; // Shift dividend left.
3088
3089 un1 = un10 >> 16; // Break right half of
3090 un0 = un10 & 0xFFFF; // dividend into two digits.
3091
3092 q1 = un32/vn1; // Compute the first
3093 rhat = un32 - q1*vn1; // quotient digit, q1.
3094 again1:
3095 if (q1 >= b || q1*vn0 > b*rhat + un1) {
3096 q1 = q1 - 1;
3097 rhat = rhat + vn1;
3098 if (rhat < b) goto again1;}
3099
3100 un21 = un32*b + un1 - q1*v; // Multiply and subtract.
3101
3102 q0 = un21/vn1; // Compute the second
3103 rhat = un21 - q0*vn1; // quotient digit, q0.
3104 again2:
3105 if (q0 >= b || q0*vn0 > b*rhat + un0) {
3106 q0 = q0 - 1;
3107 rhat = rhat + vn1;
3108 if (rhat < b) goto again2;}
3109
3110 if (r != NULL) // If remainder is wanted,
3111 *r = (un21*b + un0 - q0*v) >> s; // return it.
3112 return q1*b + q0;
3113}
3114
3115
3116/* 64 x 32 ==> 32 signed division, using only 32 x 32 ==> 32 division
3117 as a primitive. */
3118static Int divls(Int u1, UInt u0, Int v, Int *r)
3119{
3120 Int q, uneg, vneg, diff, borrow;
3121
3122 uneg = u1 >> 31; // -1 if u < 0.
3123 if (uneg) { // Compute the absolute
3124 u0 = -u0; // value of the dividend u.
3125 borrow = (u0 != 0);
3126 u1 = -u1 - borrow;}
3127
3128 vneg = v >> 31; // -1 if v < 0.
3129 v = (v ^ vneg) - vneg; // Absolute value of v.
3130
3131 if ((UInt)u1 >= (UInt)v) goto overflow;
3132
3133 q = divlu2(u1, u0, v, (UInt *)r);
3134
3135 diff = uneg ^ vneg; // Negate q if signs of
3136 q = (q ^ diff) - diff; // u and v differed.
3137 if (uneg && r != NULL)
3138 *r = -*r;
3139
3140 if ((diff ^ q) < 0 && q != 0) { // If overflow,
3141 overflow: // set remainder
3142 if (r != NULL) // to an impossible value,
3143 *r = 0x80000000; // and return the largest
3144 q = 0x80000000;} // possible neg. quotient.
3145 return q;
3146}
3147
3148
3149
3150/* This file contains a program for doing 64/64 ==> 64 division, on a
3151machine that does not have that instruction but that does have
3152instructions for "long division" (64/32 ==> 32). Code for unsigned
3153division is given first, followed by a simple program for doing the
3154signed version by using the unsigned version.
3155 These programs are useful in implementing "long long" (64-bit)
3156arithmetic on a machine that has the long division instruction. It will
3157work on 64- and 32-bit machines, provided the compiler implements long
3158long's (64-bit integers). It is desirable that the machine have the
3159Count Leading Zeros instruction.
3160 In the GNU world, these programs are known as __divdi3 and __udivdi3,
3161and similar names are used here.
3162 This material is not in HD, but may be in a future edition.
3163Max line length is 57, to fit in hacker.book. */
3164
3165
3166static Int nlz64(ULong x)
3167{
3168 Int n;
3169 if (x == 0) return(64);
3170 n = 0;
3171 if (x <= 0x00000000FFFFFFFFULL) {n = n + 32; x = x << 32;}
3172 if (x <= 0x0000FFFFFFFFFFFFULL) {n = n + 16; x = x << 16;}
3173 if (x <= 0x00FFFFFFFFFFFFFFULL) {n = n + 8; x = x << 8;}
3174 if (x <= 0x0FFFFFFFFFFFFFFFULL) {n = n + 4; x = x << 4;}
3175 if (x <= 0x3FFFFFFFFFFFFFFFULL) {n = n + 2; x = x << 2;}
3176 if (x <= 0x7FFFFFFFFFFFFFFFULL) {n = n + 1;}
3177 return n;
3178}
3179
3180// ---------------------------- udivdi3 --------------------------------
3181
3182 /* The variables u0, u1, etc. take on only 32-bit values, but they
3183 are declared long long to avoid some compiler warning messages and to
3184 avoid some unnecessary EXTRs that the compiler would put in, to
3185 convert long longs to ints.
3186
3187 First the procedure takes care of the case in which the divisor is a
3188 32-bit quantity. There are two subcases: (1) If the left half of the
3189 dividend is less than the divisor, one execution of DIVU is all that
3190 is required (overflow is not possible). (2) Otherwise it does two
3191 divisions, using the grade school method, with variables used as
3192 suggested below.
3193
3194 q1 q0
3195 ________
3196 v) u1 u0
3197 q1*v
3198 ____
3199 k u0 */
3200
3201/* These macros must be used with arguments of the appropriate type
3202(unsigned long long for DIVU and long long for DIVS. They are
3203simulations of the presumed machines ops. I.e., they look at only the
3204low-order 32 bits of the divisor, they return garbage if the division
3205overflows, and they return garbage in the high-order half of the
3206quotient doubleword.
3207 In practice, these would be replaced with uses of the machine's DIVU
3208and DIVS instructions (e.g., by using the GNU "asm" facility). */
3209
3210static UInt DIVU ( ULong u, UInt v )
3211{
3212 UInt uHi = (UInt)(u >> 32);
3213 UInt uLo = (UInt)u;
3214 return divlu2(uHi, uLo, v, NULL);
3215}
3216
3217static Int DIVS ( Long u, Int v )
3218{
3219 Int uHi = (Int)(u >> 32);
3220 UInt uLo = (UInt)u;
3221 return divls(uHi, uLo, v, NULL);
3222}
3223
3224/* 64 x 64 ==> 64 unsigned division, using only 32 x 32 ==> 32
3225 division as a primitive. */
3226static ULong udivdi3(ULong u, ULong v)
3227{
3228 ULong u0, u1, v1, q0, q1, k, n;
3229
3230 if (v >> 32 == 0) { // If v < 2**32:
3231 if (u >> 32 < v) // If u/v cannot overflow,
3232 return DIVU(u, v) // just do one division.
3233 & 0xFFFFFFFF;
3234 else { // If u/v would overflow:
3235 u1 = u >> 32; // Break u up into two
3236 u0 = u & 0xFFFFFFFF; // halves.
3237 q1 = DIVU(u1, v) // First quotient digit.
3238 & 0xFFFFFFFF;
3239 k = u1 - q1*v; // First remainder, < v.
3240 q0 = DIVU((k << 32) + u0, v) // 2nd quot. digit.
3241 & 0xFFFFFFFF;
3242 return (q1 << 32) + q0;
3243 }
3244 }
3245 // Here v >= 2**32.
3246 n = nlz64(v); // 0 <= n <= 31.
3247 v1 = (v << n) >> 32; // Normalize the divisor
3248 // so its MSB is 1.
3249 u1 = u >> 1; // To ensure no overflow.
3250 q1 = DIVU(u1, v1) // Get quotient from
3251 & 0xFFFFFFFF; // divide unsigned insn.
3252 q0 = (q1 << n) >> 31; // Undo normalization and
3253 // division of u by 2.
3254 if (q0 != 0) // Make q0 correct or
3255 q0 = q0 - 1; // too small by 1.
3256 if ((u - q0*v) >= v)
3257 q0 = q0 + 1; // Now q0 is correct.
3258 return q0;
3259}
3260
3261
3262// ----------------------------- divdi3 --------------------------------
3263
3264/* This routine presumes that smallish cases (those which can be done in
3265one execution of DIVS) are common. If this is not the case, the test for
3266this case should be deleted.
3267 Note that the test for when DIVS can be used is not entirely
3268accurate. For example, DIVS is not used if v = 0xFFFFFFFF8000000,
3269whereas if could be (if u is sufficiently small in magnitude). */
3270
3271// ------------------------------ cut ----------------------------------
3272
3273static ULong my_llabs ( Long x )
3274{
3275 ULong t = x >> 63;
3276 return (x ^ t) - t;
3277}
3278
3279/* 64 x 64 ==> 64 signed division, using only 32 x 32 ==> 32 division
3280 as a primitive. */
3281static Long divdi3(Long u, Long v)
3282{
3283 ULong au, av;
3284 Long q, t;
3285 au = my_llabs(u);
3286 av = my_llabs(v);
3287 if (av >> 31 == 0) { // If |v| < 2**31 and
3288 // if (v << 32 >> 32 == v) { // If v is in range and
3289 if (au < av << 31) { // |u|/|v| cannot
3290 q = DIVS(u, v); // overflow, use DIVS.
3291 return (q << 32) >> 32;
3292 }
3293 }
3294 q = udivdi3(au,av); // Invoke udivdi3.
3295 t = (u ^ v) >> 63; // If u, v have different
3296 return (q ^ t) - t; // signs, negate q.
3297}
3298
3299// ---------------------------- end cut --------------------------------
3300
sewardj0af71bb2010-07-01 14:50:30 +00003301ULong __udivdi3 (ULong u, ULong v);
njnea2d6fd2010-07-01 00:20:20 +00003302ULong __udivdi3 (ULong u, ULong v)
3303{
3304 return udivdi3(u,v);
3305}
3306
sewardj0af71bb2010-07-01 14:50:30 +00003307Long __divdi3 (Long u, Long v);
njnea2d6fd2010-07-01 00:20:20 +00003308Long __divdi3 (Long u, Long v)
3309{
3310 return divdi3(u,v);
3311}
3312
sewardj0af71bb2010-07-01 14:50:30 +00003313ULong __umoddi3 (ULong u, ULong v);
njnea2d6fd2010-07-01 00:20:20 +00003314ULong __umoddi3 (ULong u, ULong v)
3315{
3316 ULong q = __udivdi3(u, v);
3317 ULong r = u - q * v;
3318 return r;
3319}
3320
sewardj0af71bb2010-07-01 14:50:30 +00003321Long __moddi3 (Long u, Long v);
njnea2d6fd2010-07-01 00:20:20 +00003322Long __moddi3 (Long u, Long v)
3323{
3324 Long q = __divdi3(u, v);
3325 Long r = u - q * v;
3326 return r;
3327}
3328
sewardj70d71c72011-08-23 07:35:42 +00003329/* ------------------------------------------------
3330 ld_classic: Undefined symbols:
3331 ___fixunsdfdi
3332 ------------------------------------------------
3333*/
3334
3335/* ===-- fixunsdfdi.c - Implement __fixunsdfdi -----------------------------===
3336 *
3337 * The LLVM Compiler Infrastructure
3338 *
3339 * This file is dual licensed under the MIT and the University of Illinois Open
3340 * Source Licenses. See LICENSE.TXT for details.
3341 *
3342 * ===----------------------------------------------------------------------===
3343 *
3344 * This file implements __fixunsdfdi for the compiler_rt library.
3345 *
3346 * ===----------------------------------------------------------------------===
3347 */
3348
3349/* As per http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses,
3350
3351 the "NCSA/University of Illinois Open Source License" is compatible
3352 with the GPL (both version 2 and 3). What is claimed to be
3353 compatible is this
3354
3355 http://www.opensource.org/licenses/UoI-NCSA.php
3356
3357 and the LLVM documentation at
3358
3359 http://www.llvm.org/docs/DeveloperPolicy.html#license
3360
3361 says all the code in LLVM is available under the University of
3362 Illinois/NCSA Open Source License, at this URL
3363
3364 http://www.opensource.org/licenses/UoI-NCSA.php
3365
3366 viz, the same one that the FSF pages claim is compatible. So I
3367 think it's OK to include it.
3368*/
3369
3370/* Returns: convert a to a unsigned long long, rounding toward zero.
3371 * Negative values all become zero.
3372 */
3373
3374/* Assumption: double is a IEEE 64 bit floating point type
3375 * du_int is a 64 bit integral type
3376 * value in double is representable in du_int or is negative
3377 * (no range checking performed)
3378 */
3379
3380/* seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm */
3381
3382typedef unsigned long long du_int;
3383typedef unsigned su_int;
3384
3385typedef union
3386{
3387 du_int all;
3388 struct
3389 {
3390#if VG_LITTLEENDIAN
3391 su_int low;
3392 su_int high;
3393#else
3394 su_int high;
3395 su_int low;
3396#endif /* VG_LITTLEENDIAN */
3397 }s;
3398} udwords;
3399
3400typedef union
3401{
3402 udwords u;
3403 double f;
3404} double_bits;
3405
3406du_int __fixunsdfdi(double a);
3407
3408du_int
3409__fixunsdfdi(double a)
3410{
3411 double_bits fb;
3412 fb.f = a;
3413 int e = ((fb.u.s.high & 0x7FF00000) >> 20) - 1023;
3414 if (e < 0 || (fb.u.s.high & 0x80000000))
3415 return 0;
3416 udwords r;
3417 r.s.high = (fb.u.s.high & 0x000FFFFF) | 0x00100000;
3418 r.s.low = fb.u.s.low;
3419 if (e > 52)
3420 r.all <<= (e - 52);
3421 else
3422 r.all >>= (52 - e);
3423 return r.all;
3424}
3425
3426
njnea2d6fd2010-07-01 00:20:20 +00003427#endif
3428
3429
sewardjde4a1d02002-03-22 01:27:54 +00003430/*--------------------------------------------------------------------*/
njn04e16982005-05-31 00:23:43 +00003431/*--- end ---*/
sewardjde4a1d02002-03-22 01:27:54 +00003432/*--------------------------------------------------------------------*/