blob: 185520786cfd5be8ff34865e1311e7d17bafaae6 [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
sewardj0f157dd2013-10-18 14:27:36 +000010 Copyright (C) 2000-2013 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"
sewardj17c5e2e2012-12-28 09:12:14 +000052#include "pub_core_sbprofile.h"
sewardj45f4e7c2005-09-27 19:20:21 +000053#include "pub_core_syscall.h" // VG_(strerror)
njnf76d27a2009-05-28 01:53:07 +000054#include "pub_core_mach.h"
njnf536bbb2005-06-13 04:21:38 +000055#include "pub_core_machine.h"
njnaf1d7df2005-06-11 01:31:52 +000056#include "pub_core_mallocfree.h"
njn20242342005-05-16 23:31:24 +000057#include "pub_core_options.h"
sewardjfdf91b42005-09-28 00:53:09 +000058#include "pub_core_debuginfo.h"
njnd1af0032005-05-29 17:01:48 +000059#include "pub_core_redir.h"
njnc7561b92005-06-19 01:24:32 +000060#include "pub_core_scheduler.h"
sewardjf9ebc392010-05-09 22:30:43 +000061#include "pub_core_seqmatch.h" // For VG_(string_match)
njn0c246472005-05-31 01:00:08 +000062#include "pub_core_signals.h"
njn2025cf92005-06-26 20:44:48 +000063#include "pub_core_stacks.h" // For VG_(register_stack)
njnc1b01812005-06-17 22:19:06 +000064#include "pub_core_syswrap.h"
njn43b9a8a2005-05-10 04:37:01 +000065#include "pub_core_tooliface.h"
sewardj17c11042006-10-15 01:26:40 +000066#include "pub_core_translate.h" // For VG_(translate)
njna7598f62005-06-18 03:27:58 +000067#include "pub_core_trampoline.h"
njn8bddf582005-05-13 23:40:55 +000068#include "pub_core_transtab.h"
florianc91f5842013-09-15 10:42:26 +000069#include "pub_core_inner.h"
philippe14711e82012-06-14 22:18:50 +000070#if defined(ENABLE_INNER_CLIENT_REQUEST)
florian1a046d52013-09-16 20:56:35 +000071#include "pub_core_clreq.h"
philippe14711e82012-06-14 22:18:50 +000072#endif
sewardj17c11042006-10-15 01:26:40 +000073
sewardjb5f6f512005-03-10 23:59:00 +000074
nethercote71980f02004-01-24 18:18:54 +000075/*====================================================================*/
sewardj71bc3cb2005-05-19 00:25:45 +000076/*=== Command-line: variables, processing, etc ===*/
77/*====================================================================*/
78
79// See pub_{core,tool}_options.h for explanations of all these.
80
sewardj45f4e7c2005-09-27 19:20:21 +000081static void usage_NORETURN ( Bool debug_help )
njn7cf0bd32002-06-08 13:36:03 +000082{
florian95a128b2011-09-29 14:26:38 +000083 /* 'usage1' contains a %s
84 - for the name of the GDB executable
85 - for the name of vgdb's path prefix
86 which must be supplied when they are VG_(printf)'d. */
floriane543f302012-10-21 19:43:43 +000087 const HChar usage1[] =
njn00cfcfc2005-11-12 18:53:50 +000088"usage: valgrind [options] prog-and-args\n"
njn25e49d8e72002-09-23 09:36:25 +000089"\n"
njn97db7612009-08-04 02:32:55 +000090" tool-selection option, with default in [ ]:\n"
sewardjb5f6f512005-03-10 23:59:00 +000091" --tool=<name> use the Valgrind tool named <name> [memcheck]\n"
njn97db7612009-08-04 02:32:55 +000092"\n"
93" basic user options for all Valgrind tools, with defaults in [ ]:\n"
nethercotea76368b2004-06-16 11:56:29 +000094" -h --help show this message\n"
nethercote6c999f22004-01-31 22:55:15 +000095" --help-debug show this message, plus debugging options\n"
njn25e49d8e72002-09-23 09:36:25 +000096" --version show version\n"
njn25e49d8e72002-09-23 09:36:25 +000097" -q --quiet run silently; only print error msgs\n"
sewardj2d9e8742009-08-07 15:46:56 +000098" -v --verbose be more verbose -- show misc extra info\n"
sewardj6e31f802007-11-17 22:29:25 +000099" --trace-children=no|yes Valgrind-ise child processes (follow execve)? [no]\n"
sewardj06421272009-11-05 08:55:13 +0000100" --trace-children-skip=patt1,patt2,... specifies a list of executables\n"
101" that --trace-children=yes should not trace into\n"
sewardj9ab64a42010-12-06 11:40:04 +0000102" --trace-children-skip-by-arg=patt1,patt2,... same as --trace-children-skip=\n"
103" but check the argv[] entries for children, rather\n"
104" than the exe name, to make a follow/no-follow decision\n"
njn97db7612009-08-04 02:32:55 +0000105" --child-silent-after-fork=no|yes omit child output between fork & exec? [no]\n"
sewardj3b290482011-05-06 21:02:55 +0000106" --vgdb=no|yes|full activate gdbserver? [yes]\n"
107" full is slower but provides precise watchpoint/step\n"
sewardj1568e172011-06-18 08:28:04 +0000108" --vgdb-error=<number> invoke gdbserver after <number> errors [%d]\n"
109" to get started quickly, use --vgdb-error=0\n"
110" and follow the on-screen directions\n"
philippe180a7502014-04-20 13:41:10 +0000111" --vgdb-stop-at=event1,event2,... invoke gdbserver for given events [none]\n"
112" where event is one of startup exit valgrindabexit all none\n"
nethercote0d588502004-06-21 13:27:11 +0000113" --track-fds=no|yes track open file descriptors? [no]\n"
thughes6233a382004-08-21 11:10:44 +0000114" --time-stamp=no|yes add timestamps to log messages? [no]\n"
njnce545552005-07-25 22:36:52 +0000115" --log-fd=<number> log messages to file descriptor [2=stderr]\n"
njn374a36d2007-11-23 01:41:32 +0000116" --log-file=<file> log messages to <file>\n"
njnce545552005-07-25 22:36:52 +0000117" --log-socket=ipaddr:port log messages to socket ipaddr:port\n"
nethercote2b0793f2003-12-02 10:41:18 +0000118"\n"
nethercote2b0793f2003-12-02 10:41:18 +0000119" user options for Valgrind tools that report errors:\n"
sewardj738856f2009-07-15 14:48:32 +0000120" --xml=yes emit error output in XML (some tools only)\n"
121" --xml-fd=<number> XML output to file descriptor\n"
122" --xml-file=<file> XML output to <file>\n"
123" --xml-socket=ipaddr:port XML output to socket ipaddr:port\n"
124" --xml-user-comment=STR copy STR verbatim into XML output\n"
nethercote2b0793f2003-12-02 10:41:18 +0000125" --demangle=no|yes automatically demangle C++ names? [yes]\n"
njn20b4a152005-10-19 22:39:40 +0000126" --num-callers=<number> show <number> callers in stack traces [12]\n"
nethercote2b0793f2003-12-02 10:41:18 +0000127" --error-limit=no|yes stop showing new errors if too many? [yes]\n"
sewardjb9779082006-05-12 23:50:15 +0000128" --error-exitcode=<number> exit code to return if errors found [0=disable]\n"
nethercote2b0793f2003-12-02 10:41:18 +0000129" --show-below-main=no|yes continue stack traces below main() [no]\n"
barta6efdfa2014-06-24 05:08:21 +0000130" --default-suppressions=yes|no\n"
131" load default suppressions [yes]\n"
nethercote2b0793f2003-12-02 10:41:18 +0000132" --suppressions=<filename> suppress errors described in <filename>\n"
sewardjd153fae2005-01-10 17:24:47 +0000133" --gen-suppressions=no|yes|all print suppressions for errors? [no]\n"
nethercote04d0fbc2004-01-26 16:48:06 +0000134" --db-attach=no|yes start debugger when errors detected? [no]\n"
florian882038d2014-09-01 06:37:07 +0000135" Note: deprecated feature\n"
sewardj7839d112007-11-20 19:45:03 +0000136" --db-command=<command> command to start debugger [%s -nw %%f %%p]\n"
nethercote04d0fbc2004-01-26 16:48:06 +0000137" --input-fd=<number> file descriptor for input [0=stdin]\n"
njn97db7612009-08-04 02:32:55 +0000138" --dsymutil=no|yes run dsymutil on Mac OS X when helpful? [no]\n"
sewardj97724e52005-04-02 23:40:59 +0000139" --max-stackframe=<number> assume stack switch for SP changes larger\n"
140" than <number> bytes [2000000]\n"
sewardj95d86c02007-12-18 01:49:23 +0000141" --main-stacksize=<number> set size of main thread's stack (in bytes)\n"
philippe3bcd51d2013-06-12 21:45:39 +0000142" [min(max(current 'ulimit' value,1MB),16MB)]\n"
njn97db7612009-08-04 02:32:55 +0000143"\n"
144" user options for Valgrind tools that replace malloc:\n"
philipped99c26a2012-07-31 22:17:28 +0000145" --alignment=<number> set minimum alignment of heap allocations [%s]\n"
146" --redzone-size=<number> set minimum size of redzones added before/after\n"
147" heap blocks (in bytes). [%s]\n"
njn97db7612009-08-04 02:32:55 +0000148"\n"
149" uncommon user options for all Valgrind tools:\n"
sewardj14cdbf82010-10-12 00:44:05 +0000150" --fullpath-after= (with nothing after the '=')\n"
151" show full source paths in call stacks\n"
152" --fullpath-after=string like --fullpath-after=, but only show the\n"
153" part of the path after 'string'. Allows removal\n"
154" of path prefixes. Use this flag multiple times\n"
155" to specify a set of prefixes to remove.\n"
sewardj8b6573d2012-12-05 22:15:14 +0000156" --extra-debuginfo-path=path absolute path to search for additional\n"
157" debug symbols, in addition to existing default\n"
158" well known search paths.\n"
sewardj5d616df2013-07-02 08:07:15 +0000159" --debuginfo-server=ipaddr:port also query this server\n"
160" (valgrind-di-server) for debug symbols\n"
161" --allow-mismatched-debuginfo=no|yes [no]\n"
162" for the above two flags only, accept debuginfo\n"
163" objects that don't \"match\" the main object\n"
sewardj6dbcc632011-06-07 21:39:28 +0000164" --smc-check=none|stack|all|all-non-file [stack]\n"
165" checks for self-modifying code: none, only for\n"
166" code found in stacks, for all code, or for all\n"
167" code except that from file-backed mappings\n"
philippea0a73932014-06-15 15:42:20 +0000168" --read-inline-info=yes|no read debug info about inlined function calls\n"
169" and use it to do better stack traces [no]\n"
njn97db7612009-08-04 02:32:55 +0000170" --read-var-info=yes|no read debug info on stack and global variables\n"
171" and use it to print better error messages in\n"
172" tools that make use of it (Memcheck, Helgrind,\n"
bartf6122a02010-03-27 07:38:39 +0000173" DRD) [no]\n"
sewardj3b290482011-05-06 21:02:55 +0000174" --vgdb-poll=<number> gdbserver poll max every <number> basic blocks [%d] \n"
175" --vgdb-shadow-registers=no|yes let gdb see the shadow registers [no]\n"
176" --vgdb-prefix=<prefix> prefix for vgdb FIFOs [%s]\n"
njn97db7612009-08-04 02:32:55 +0000177" --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]\n"
philippeec905f72014-08-17 20:03:51 +0000178" --sim-hints=hint1,hint2,... activate unusual sim behaviours [none] \n"
philippe98486902014-08-19 22:46:44 +0000179" where hint is one of lax-ioctls fuse-compatible enable-outer\n"
180" no-inner-prefix no-nptl-pthread-stackcache none\n"
bart78bfc712011-12-08 16:14:59 +0000181" --fair-sched=no|yes|try schedule threads fairly on multicore systems [no]\n"
philippeec905f72014-08-17 20:03:51 +0000182" --kernel-variant=variant1,variant2,... handle non-standard kernel"
183 " variants [none]\n"
184" where variant is one of bproc none\n"
philippe46207652013-01-20 17:11:58 +0000185" --merge-recursive-frames=<number> merge frames between identical\n"
186" program counters in max <number> frames) [0]\n"
philippe8e1bee42013-10-18 00:08:20 +0000187" --num-transtab-sectors=<number> size of translated code cache [%d]\n"
sewardja11ec172013-10-18 11:18:45 +0000188" more sectors may increase performance, but use more memory.\n"
philippee4d78122014-04-20 14:20:37 +0000189" --aspace-minaddr=0xPP avoid mapping memory below 0xPP [guessed]\n"
njn97db7612009-08-04 02:32:55 +0000190" --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"
sewardj260c6482012-08-07 14:46:34 +0000195" specify patterns for function wrapping or replacement.\n"
196" To use a non-libc malloc library that is\n"
197" in the main exe: --soname-synonyms=somalloc=NONE\n"
198" in libxyzzy.so: --soname-synonyms=somalloc=libxyzzy.so\n"
sewardjc30cd9b2012-12-06 18:08:54 +0000199" --sigill-diagnostics=yes|no warn about illegal instructions? [yes]\n"
sewardj49984ea2013-10-18 13:21:26 +0000200" --unw-stack-scan-thresh=<number> Enable stack-scan unwind if fewer\n"
201" than <number> good frames found [0, meaning \"disabled\"]\n"
202" NOTE: stack scanning is only available on arm-linux.\n"
203" --unw-stack-scan-frames=<number> Max number of frames that can be\n"
204" recovered by stack scanning [5]\n"
fitzhardinge98abfc72003-12-16 02:05:15 +0000205"\n";
njn7cf0bd32002-06-08 13:36:03 +0000206
floriane543f302012-10-21 19:43:43 +0000207 const HChar usage2[] =
njn25e49d8e72002-09-23 09:36:25 +0000208"\n"
nethercote2b0793f2003-12-02 10:41:18 +0000209" debugging options for all Valgrind tools:\n"
njn97db7612009-08-04 02:32:55 +0000210" -d show verbose debugging output\n"
njnb1cc5d62010-07-06 04:05:23 +0000211" --stats=no|yes show tool and core statistics [no]\n"
njn25e49d8e72002-09-23 09:36:25 +0000212" --sanity-level=<number> level of sanity checking to do [1]\n"
sewardjfa8ec112005-01-19 11:55:34 +0000213" --trace-flags=<XXXXXXXX> show generated code? (X = 0|1) [00000000]\n"
214" --profile-flags=<XXXXXXXX> ditto, but for profiling (X = 0|1) [00000000]\n"
sewardj17c5e2e2012-12-28 09:12:14 +0000215" --profile-interval=<number> show profile every <number> event checks\n"
216" [0, meaning only at the end of the run]\n"
sewardj33afdb52006-01-17 02:36:40 +0000217" --trace-notbelow=<number> only show BBs above <number> [999999999]\n"
florian29e022d2012-07-02 21:13:34 +0000218" --trace-notabove=<number> only show BBs below <number> [0]\n"
njn25e49d8e72002-09-23 09:36:25 +0000219" --trace-syscalls=no|yes show all system calls? [no]\n"
220" --trace-signals=no|yes show signal handling details? [no]\n"
221" --trace-symtab=no|yes show symbol table details? [no]\n"
sewardjf767d962007-02-12 17:47:14 +0000222" --trace-symtab-patt=<patt> limit debuginfo tracing to obj name <patt>\n"
sewardjce058b02005-05-01 08:55:38 +0000223" --trace-cfi=no|yes show call-frame-info details? [no]\n"
sewardjf767d962007-02-12 17:47:14 +0000224" --debug-dump=syms mimic /usr/bin/readelf --syms\n"
225" --debug-dump=line mimic /usr/bin/readelf --debug-dump=line\n"
226" --debug-dump=frames mimic /usr/bin/readelf --debug-dump=frames\n"
sewardj0ec07f32006-01-12 12:32:32 +0000227" --trace-redir=no|yes show redirection details? [no]\n"
njn25e49d8e72002-09-23 09:36:25 +0000228" --trace-sched=no|yes show thread scheduler details? [no]\n"
sewardj9c606bd2008-09-18 18:12:50 +0000229" --profile-heap=no|yes profile Valgrind's own space use\n"
philippe06444372012-10-12 21:46:55 +0000230" --core-redzone-size=<number> set minimum size of redzones added before/after\n"
philipped99c26a2012-07-31 22:17:28 +0000231" heap blocks allocated for Valgrind internal use (in bytes) [4]\n"
jsgf855d93d2003-10-13 22:26:55 +0000232" --wait-for-gdb=yes|no pause on startup to wait for gdb attach\n"
sewardj17c11042006-10-15 01:26:40 +0000233" --sym-offsets=yes|no show syms in form 'name+offset' ? [no]\n"
sewardjb5f6f512005-03-10 23:59:00 +0000234" --command-line-only=no|yes only use command line options [no]\n"
njn613812e2005-03-11 04:57:30 +0000235"\n"
njn97db7612009-08-04 02:32:55 +0000236" Vex options for all Valgrind tools:\n"
237" --vex-iropt-verbosity=<0..9> [0]\n"
238" --vex-iropt-level=<0..2> [2]\n"
philippe5b240c22012-08-14 22:28:31 +0000239" --vex-iropt-register-updates=sp-at-mem-access\n"
240" |unwindregs-at-mem-access\n"
philippe0c0291a2012-08-01 22:03:12 +0000241" |allregs-at-mem-access\n"
242" |allregs-at-each-insn [unwindregs-at-mem-access]\n"
njn97db7612009-08-04 02:32:55 +0000243" --vex-iropt-unroll-thresh=<0..400> [120]\n"
244" --vex-guest-max-insns=<1..100> [50]\n"
245" --vex-guest-chase-thresh=<0..99> [10]\n"
sewardj540cc4a2010-01-15 10:57:57 +0000246" --vex-guest-chase-cond=no|yes [no]\n"
sewardjfa8ec112005-01-19 11:55:34 +0000247" --trace-flags and --profile-flags values (omit the middle space):\n"
sewardj2a99cf62004-11-24 10:44:19 +0000248" 1000 0000 show conversion into IR\n"
249" 0100 0000 show after initial opt\n"
250" 0010 0000 show after instrumentation\n"
251" 0001 0000 show after second opt\n"
252" 0000 1000 show after tree building\n"
253" 0000 0100 show selecting insns\n"
254" 0000 0010 show after reg-alloc\n"
255" 0000 0001 show final assembly\n"
sewardj17c5e2e2012-12-28 09:12:14 +0000256" 0000 0000 show summary profile only\n"
sewardj5d616df2013-07-02 08:07:15 +0000257" (Nb: you need --trace-notbelow and/or --trace-notabove\n"
sewardj17c5e2e2012-12-28 09:12:14 +0000258" with --trace-flags for full details)\n"
sewardj2a99cf62004-11-24 10:44:19 +0000259"\n"
nethercote2b0793f2003-12-02 10:41:18 +0000260" debugging options for Valgrind tools that report errors\n"
261" --dump-error=<number> show translation for basic block associated\n"
262" with <number>'th error context [0=show none]\n"
njn97db7612009-08-04 02:32:55 +0000263"\n"
264" debugging options for Valgrind tools that replace malloc:\n"
265" --trace-malloc=no|yes show client malloc details? [no]\n"
fitzhardinge98abfc72003-12-16 02:05:15 +0000266"\n";
njn3e884182003-04-15 13:03:23 +0000267
floriane543f302012-10-21 19:43:43 +0000268 const HChar usage3[] =
njn3e884182003-04-15 13:03:23 +0000269"\n"
nethercote71980f02004-01-24 18:18:54 +0000270" Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc\n"
njn25e49d8e72002-09-23 09:36:25 +0000271"\n"
njn10b9aea2009-07-14 06:55:05 +0000272" %s is %s\n"
sewardj0f157dd2013-10-18 14:27:36 +0000273" Valgrind is Copyright (C) 2000-2013, and GNU GPL'd, by Julian Seward et al.\n"
274" LibVEX is Copyright (C) 2004-2013, and GNU GPL'd, by OpenWorks LLP et al.\n"
njnd04b7c62002-10-03 14:05:52 +0000275"\n"
njn10b9aea2009-07-14 06:55:05 +0000276" Bug reports, feedback, admiration, abuse, etc, to: %s.\n"
njn25e49d8e72002-09-23 09:36:25 +0000277"\n";
njn7cf0bd32002-06-08 13:36:03 +0000278
floriane6a4ed12012-10-21 02:30:18 +0000279 const HChar* gdb_path = GDB_PATH;
florian19f91bb2012-11-10 22:29:54 +0000280 HChar default_alignment[30];
281 HChar default_redzone_size[30];
sewardj12373b12007-11-20 21:38:14 +0000282
njnbe9b47b2005-05-15 16:22:58 +0000283 // Ensure the message goes to stdout
sewardj738856f2009-07-15 14:48:32 +0000284 VG_(log_output_sink).fd = 1;
285 VG_(log_output_sink).is_socket = False;
njnbe9b47b2005-05-15 16:22:58 +0000286
philipped99c26a2012-07-31 22:17:28 +0000287 if (VG_(needs).malloc_replacement) {
288 VG_(sprintf)(default_alignment, "%d", VG_MIN_MALLOC_SZB);
289 VG_(sprintf)(default_redzone_size, "%lu", VG_(tdict).tool_client_redzone_szB);
290 } else {
291 VG_(strcpy)(default_alignment, "not used by this tool");
292 VG_(strcpy)(default_redzone_size, "not used by this tool");
293 }
294 /* 'usage1' a type as described after each arg. */
sewardj3b290482011-05-06 21:02:55 +0000295 VG_(printf)(usage1,
philipped99c26a2012-07-31 22:17:28 +0000296 VG_(clo_vgdb_error) /* int */,
297 gdb_path /* char* */,
298 default_alignment /* char* */,
299 default_redzone_size /* char* */,
300 VG_(clo_vgdb_poll) /* int */,
philippe8e1bee42013-10-18 00:08:20 +0000301 VG_(vgdb_prefix_default)() /* char* */,
302 N_SECTORS_DEFAULT /* int */
philipped99c26a2012-07-31 22:17:28 +0000303 );
fitzhardinge98abfc72003-12-16 02:05:15 +0000304 if (VG_(details).name) {
305 VG_(printf)(" user options for %s:\n", VG_(details).name);
fitzhardinge98abfc72003-12-16 02:05:15 +0000306 if (VG_(needs).command_line_options)
njn51d827b2005-05-09 01:02:08 +0000307 VG_TDICT_CALL(tool_print_usage);
fitzhardinge98abfc72003-12-16 02:05:15 +0000308 else
309 VG_(printf)(" (none)\n");
310 }
nethercote6c999f22004-01-31 22:55:15 +0000311 if (debug_help) {
sewardjbbaef872008-11-01 23:55:32 +0000312 VG_(printf)("%s", usage2);
fitzhardinge98abfc72003-12-16 02:05:15 +0000313
nethercote6c999f22004-01-31 22:55:15 +0000314 if (VG_(details).name) {
315 VG_(printf)(" debugging options for %s:\n", VG_(details).name);
316
317 if (VG_(needs).command_line_options)
njn51d827b2005-05-09 01:02:08 +0000318 VG_TDICT_CALL(tool_print_debug_usage);
nethercote6c999f22004-01-31 22:55:15 +0000319 else
320 VG_(printf)(" (none)\n");
321 }
fitzhardinge98abfc72003-12-16 02:05:15 +0000322 }
njn10b9aea2009-07-14 06:55:05 +0000323 VG_(printf)(usage3, VG_(details).name, VG_(details).copyright_author,
324 VG_BUGS_TO);
nethercotef4928da2004-06-15 10:54:40 +0000325 VG_(exit)(0);
njn7cf0bd32002-06-08 13:36:03 +0000326}
sewardjde4a1d02002-03-22 01:27:54 +0000327
sewardjde4a1d02002-03-22 01:27:54 +0000328
sewardj95d86c02007-12-18 01:49:23 +0000329/* Peer at previously set up VG_(args_for_valgrind) and do some
330 minimal command line processing that must happen early on:
sewardj45f4e7c2005-09-27 19:20:21 +0000331
sewardj95d86c02007-12-18 01:49:23 +0000332 - show the version string, if requested (-v)
333 - extract any request for help (--help, -h, --help-debug)
334 - get the toolname (--tool=)
335 - set VG_(clo_max_stackframe) (--max-stackframe=)
336 - set VG_(clo_main_stacksize) (--main-stacksize=)
philippe72faf102012-03-11 22:24:03 +0000337 - set VG_(clo_sim_hints) (--sim-hints=)
sewardj95d86c02007-12-18 01:49:23 +0000338
339 That's all it does. The main command line processing is done below
340 by main_process_cmd_line_options. Note that
341 main_process_cmd_line_options has to handle but ignore the ones we
342 have handled here.
343*/
344static void early_process_cmd_line_options ( /*OUT*/Int* need_help,
florian19f91bb2012-11-10 22:29:54 +0000345 /*OUT*/const HChar** tool )
sewardj45f4e7c2005-09-27 19:20:21 +0000346{
347 UInt i;
348 HChar* str;
sewardj8b635a42004-11-22 19:01:47 +0000349
sewardj14c7cc52007-02-25 15:08:24 +0000350 vg_assert( VG_(args_for_valgrind) );
nethercote71980f02004-01-24 18:18:54 +0000351
sewardj14c7cc52007-02-25 15:08:24 +0000352 /* parse the options we have (only the options we care about now) */
353 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
354
355 str = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
sewardj45f4e7c2005-09-27 19:20:21 +0000356 vg_assert(str);
nethercote71980f02004-01-24 18:18:54 +0000357
njn83df0b62009-02-25 01:01:05 +0000358 // Nb: the version string goes to stdout.
sewardj738856f2009-07-15 14:48:32 +0000359 if VG_XACT_CLO(str, "--version", VG_(log_output_sink).fd, 1) {
360 VG_(log_output_sink).is_socket = False;
sewardj45f4e7c2005-09-27 19:20:21 +0000361 VG_(printf)("valgrind-" VERSION "\n");
362 VG_(exit)(0);
njn83df0b62009-02-25 01:01:05 +0000363 }
njncce38e62010-07-06 04:25:12 +0000364 else if VG_XACT_CLO(str, "--help", *need_help, *need_help+1) {}
365 else if VG_XACT_CLO(str, "-h", *need_help, *need_help+1) {}
sewardj45f4e7c2005-09-27 19:20:21 +0000366
njncce38e62010-07-06 04:25:12 +0000367 else if VG_XACT_CLO(str, "--help-debug", *need_help, *need_help+2) {}
nethercote71980f02004-01-24 18:18:54 +0000368
sewardj45f4e7c2005-09-27 19:20:21 +0000369 // The tool has already been determined, but we need to know the name
370 // here.
njn83df0b62009-02-25 01:01:05 +0000371 else if VG_STR_CLO(str, "--tool", *tool) {}
sewardj5bdfbd22007-12-15 22:13:05 +0000372
sewardj95d86c02007-12-18 01:49:23 +0000373 // Set up VG_(clo_max_stackframe) and VG_(clo_main_stacksize).
374 // These are needed by VG_(ii_create_image), which happens
375 // before main_process_cmd_line_options().
njn83df0b62009-02-25 01:01:05 +0000376 else if VG_INT_CLO(str, "--max-stackframe", VG_(clo_max_stackframe)) {}
377 else if VG_INT_CLO(str, "--main-stacksize", VG_(clo_main_stacksize)) {}
philippe72faf102012-03-11 22:24:03 +0000378
379 // Set up VG_(clo_sim_hints). This is needed a.o. for an inner
380 // running in an outer, to have "no-inner-prefix" enabled
381 // as early as possible.
philippeec905f72014-08-17 20:03:51 +0000382 else if VG_USETX_CLO (str, "--sim-hints",
philippeb071b712014-08-24 11:24:10 +0000383 "lax-ioctls,fuse-compatible,"
384 "enable-outer,no-inner-prefix,"
philippe98486902014-08-19 22:46:44 +0000385 "no-nptl-pthread-stackcache",
philippeec905f72014-08-17 20:03:51 +0000386 VG_(clo_sim_hints)) {}
nethercote71980f02004-01-24 18:18:54 +0000387 }
nethercote71980f02004-01-24 18:18:54 +0000388}
389
sewardj95d86c02007-12-18 01:49:23 +0000390/* The main processing for command line options. See comments above
sewardj738856f2009-07-15 14:48:32 +0000391 on early_process_cmd_line_options.
392
393 Comments on how the logging options are handled:
394
395 User can specify:
396 --log-fd= for a fd to write to (default setting, fd = 2)
397 --log-file= for a file name to write to
398 --log-socket= for a socket to write to
399
400 As a result of examining these and doing relevant socket/file
401 opening, a final fd is established. This is stored in
402 VG_(log_output_sink) in m_libcprint. Also, if --log-file=STR was
403 specified, then STR, after expansion of %p and %q templates within
404 it, is stored in VG_(clo_log_fname_expanded), in m_options, just in
405 case anybody wants to know what it is.
406
407 When printing, VG_(log_output_sink) is consulted to find the
408 fd to send output to.
409
410 Exactly analogous actions are undertaken for the XML output
411 channel, with the one difference that the default fd is -1, meaning
412 the channel is disabled by default.
sewardj95d86c02007-12-18 01:49:23 +0000413*/
sewardj738856f2009-07-15 14:48:32 +0000414static
415void main_process_cmd_line_options ( /*OUT*/Bool* logging_to_fd,
florian19f91bb2012-11-10 22:29:54 +0000416 /*OUT*/HChar** xml_fname_unexpanded,
sewardj738856f2009-07-15 14:48:32 +0000417 const HChar* toolname )
nethercote71980f02004-01-24 18:18:54 +0000418{
njnda033f52005-12-19 21:27:58 +0000419 // VG_(clo_log_fd) is used by all the messaging. It starts as 2 (stderr)
420 // and we cannot change it until we know what we are changing it to is
421 // ok. So we have tmp_log_fd to hold the tmp fd prior to that point.
sewardj92645592005-07-23 09:18:34 +0000422 SysRes sres;
sewardj738856f2009-07-15 14:48:32 +0000423 Int i, tmp_log_fd, tmp_xml_fd;
sewardj92645592005-07-23 09:18:34 +0000424 Int toolname_len = VG_(strlen)(toolname);
florian19f91bb2012-11-10 22:29:54 +0000425 const HChar* tmp_str; // Used in a couple of places.
njnbe9b47b2005-05-15 16:22:58 +0000426 enum {
427 VgLogTo_Fd,
428 VgLogTo_File,
njnbe9b47b2005-05-15 16:22:58 +0000429 VgLogTo_Socket
sewardj738856f2009-07-15 14:48:32 +0000430 } log_to = VgLogTo_Fd, // Where is logging output to be sent?
431 xml_to = VgLogTo_Fd; // Where is XML output to be sent?
sewardjde4a1d02002-03-22 01:27:54 +0000432
sewardj738856f2009-07-15 14:48:32 +0000433 /* Temporarily holds the string STR specified with
434 --{log,xml}-{name,socket}=STR. 'fs' stands for
435 file-or-socket. */
florian19f91bb2012-11-10 22:29:54 +0000436 const HChar* log_fsname_unexpanded = NULL;
437 const HChar* xml_fsname_unexpanded = NULL;
sewardj738856f2009-07-15 14:48:32 +0000438
sewardjc30cd9b2012-12-06 18:08:54 +0000439 /* Whether the user has explicitly provided --sigill-diagnostics.
440 If not explicitly given depends on general verbosity setting. */
441 Bool sigill_diag_set = False;
442
sewardj738856f2009-07-15 14:48:32 +0000443 /* Log to stderr by default, but usage message goes to stdout. XML
444 output is initially disabled. */
njnda033f52005-12-19 21:27:58 +0000445 tmp_log_fd = 2;
sewardj738856f2009-07-15 14:48:32 +0000446 tmp_xml_fd = -1;
447
sewardj19d81412002-06-03 01:10:40 +0000448 /* Check for sane path in ./configure --prefix=... */
fitzhardinge98abfc72003-12-16 02:05:15 +0000449 if (VG_LIBDIR[0] != '/')
sewardj17c11042006-10-15 01:26:40 +0000450 VG_(err_config_error)("Please use absolute paths in "
florian1763e812011-07-12 19:07:05 +0000451 "./configure --prefix=... or --libdir=...\n");
sewardj38170912002-05-10 21:07:22 +0000452
sewardj14c7cc52007-02-25 15:08:24 +0000453 vg_assert( VG_(args_for_valgrind) );
nethercote71980f02004-01-24 18:18:54 +0000454
sewardj738856f2009-07-15 14:48:32 +0000455 /* BEGIN command-line processing loop */
456
sewardj14c7cc52007-02-25 15:08:24 +0000457 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
458
459 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
sewardj45f4e7c2005-09-27 19:20:21 +0000460 HChar* colon = arg;
nethercote71980f02004-01-24 18:18:54 +0000461
njn1274d242007-03-26 23:38:42 +0000462 // Look for a colon in the option name.
thughes3bfd5a02004-07-18 08:05:44 +0000463 while (*colon && *colon != ':' && *colon != '=')
464 colon++;
nethercote71980f02004-01-24 18:18:54 +0000465
njn1274d242007-03-26 23:38:42 +0000466 // Does it have the form "--toolname:foo"? We have to do it at the start
467 // in case someone has combined a prefix with a core-specific option,
468 // eg. "--memcheck:verbose".
thughes3bfd5a02004-07-18 08:05:44 +0000469 if (*colon == ':') {
njn83df0b62009-02-25 01:01:05 +0000470 if (VG_STREQN(2, arg, "--") &&
471 VG_STREQN(toolname_len, arg+2, toolname) &&
472 VG_STREQN(1, arg+2+toolname_len, ":"))
nethercote71980f02004-01-24 18:18:54 +0000473 {
njn1274d242007-03-26 23:38:42 +0000474 // Prefix matches, convert "--toolname:foo" to "--foo".
475 // Two things to note:
476 // - We cannot modify the option in-place. If we did, and then
477 // a child was spawned with --trace-children=yes, the
478 // now-non-prefixed option would be passed and could screw up
479 // the child.
480 // - We create copies, and never free them. Why? Non-prefixed
481 // options hang around forever, so tools need not make copies
482 // of strings within them. We need to have the same behaviour
483 // for prefixed options. The pointer to the copy will be lost
484 // once we leave this function (although a tool may keep a
485 // pointer into it), but the space wasted is insignificant.
486 // (In bug #142197, the copies were being freed, which caused
487 // problems for tools that reasonably assumed that arguments
488 // wouldn't disappear on them.)
nethercote71980f02004-01-24 18:18:54 +0000489 if (0)
490 VG_(printf)("tool-specific arg: %s\n", arg);
sewardj9c606bd2008-09-18 18:12:50 +0000491 arg = VG_(strdup)("main.mpclo.1", arg + toolname_len + 1);
nethercote71980f02004-01-24 18:18:54 +0000492 arg[0] = '-';
493 arg[1] = '-';
494
495 } else {
496 // prefix doesn't match, skip to next arg
497 continue;
498 }
499 }
500
fitzhardinge98abfc72003-12-16 02:05:15 +0000501 /* Ignore these options - they've already been handled */
njn83df0b62009-02-25 01:01:05 +0000502 if VG_STREQN( 7, arg, "--tool=") {}
503 else if VG_STREQN(20, arg, "--command-line-only=") {}
504 else if VG_STREQ( arg, "--") {}
505 else if VG_STREQ( arg, "-d") {}
philippe06444372012-10-12 21:46:55 +0000506 else if VG_STREQN(17, arg, "--max-stackframe=") {}
507 else if VG_STREQN(17, arg, "--main-stacksize=") {}
philippee4d78122014-04-20 14:20:37 +0000508 else if VG_STREQN(12, arg, "--sim-hints=") {}
philippe06444372012-10-12 21:46:55 +0000509 else if VG_STREQN(15, arg, "--profile-heap=") {}
510 else if VG_STREQN(20, arg, "--core-redzone-size=") {}
511 else if VG_STREQN(15, arg, "--redzone-size=") {}
philippee4d78122014-04-20 14:20:37 +0000512 else if VG_STREQN(17, arg, "--aspace-minaddr=") {}
nethercote27fec902004-06-16 21:26:32 +0000513
philippe0c0291a2012-08-01 22:03:12 +0000514 /* Obsolete options. Report an error and exit */
515 else if VG_STREQN(34, arg, "--vex-iropt-precise-memory-exns=no") {
516 VG_(fmsg_bad_option)
517 (arg,
518 "--vex-iropt-precise-memory-exns is obsolete\n"
519 "Use --vex-iropt-register-updates=unwindregs-at-mem-access instead\n");
520 }
521 else if VG_STREQN(35, arg, "--vex-iropt-precise-memory-exns=yes") {
522 VG_(fmsg_bad_option)
523 (arg,
524 "--vex-iropt-precise-memory-exns is obsolete\n"
525 "Use --vex-iropt-register-updates=allregs-at-mem-access instead\n"
526 " (or --vex-iropt-register-updates=allregs-at-each-insn)\n");
527 }
528
njn83df0b62009-02-25 01:01:05 +0000529 // These options are new.
530 else if (VG_STREQ(arg, "-v") ||
531 VG_STREQ(arg, "--verbose"))
sewardjde4a1d02002-03-22 01:27:54 +0000532 VG_(clo_verbosity)++;
nethercote27fec902004-06-16 21:26:32 +0000533
njn83df0b62009-02-25 01:01:05 +0000534 else if (VG_STREQ(arg, "-q") ||
535 VG_STREQ(arg, "--quiet"))
sewardjde4a1d02002-03-22 01:27:54 +0000536 VG_(clo_verbosity)--;
537
sewardjc30cd9b2012-12-06 18:08:54 +0000538 else if VG_BOOL_CLO(arg, "--sigill-diagnostics", VG_(clo_sigill_diag))
539 sigill_diag_set = True;
540
sewardj2d9e8742009-08-07 15:46:56 +0000541 else if VG_BOOL_CLO(arg, "--stats", VG_(clo_stats)) {}
bartdb4384e2011-10-11 18:49:35 +0000542 else if VG_BOOL_CLO(arg, "--xml", VG_(clo_xml))
543 VG_(debugLog_setXml)(VG_(clo_xml));
544
sewardj3b290482011-05-06 21:02:55 +0000545 else if VG_XACT_CLO(arg, "--vgdb=no", VG_(clo_vgdb), Vg_VgdbNo) {}
546 else if VG_XACT_CLO(arg, "--vgdb=yes", VG_(clo_vgdb), Vg_VgdbYes) {}
philippe0c0291a2012-08-01 22:03:12 +0000547 else if VG_XACT_CLO(arg, "--vgdb=full", VG_(clo_vgdb), Vg_VgdbFull) {
548 /* automatically updates register values at each insn
549 with --vgdb=full */
550 VG_(clo_vex_control).iropt_register_updates
551 = VexRegUpdAllregsAtEachInsn;
552 }
sewardj3b290482011-05-06 21:02:55 +0000553 else if VG_INT_CLO (arg, "--vgdb-poll", VG_(clo_vgdb_poll)) {}
554 else if VG_INT_CLO (arg, "--vgdb-error", VG_(clo_vgdb_error)) {}
philippeec905f72014-08-17 20:03:51 +0000555 else if VG_USET_CLO (arg, "--vgdb-stop-at",
556 "startup,exit,valgrindabexit",
557 VG_(clo_vgdb_stop_at)) {}
philippecffe2a52014-01-11 13:56:48 +0000558 else if VG_STR_CLO (arg, "--vgdb-prefix", VG_(clo_vgdb_prefix)) {
559 VG_(arg_vgdb_prefix) = arg;
560 }
sewardj3b290482011-05-06 21:02:55 +0000561 else if VG_BOOL_CLO(arg, "--vgdb-shadow-registers",
562 VG_(clo_vgdb_shadow_registers)) {}
njn83df0b62009-02-25 01:01:05 +0000563 else if VG_BOOL_CLO(arg, "--db-attach", VG_(clo_db_attach)) {}
564 else if VG_BOOL_CLO(arg, "--demangle", VG_(clo_demangle)) {}
philippe1e470b52012-05-11 19:33:46 +0000565 else if VG_STR_CLO (arg, "--soname-synonyms",VG_(clo_soname_synonyms)) {}
njn83df0b62009-02-25 01:01:05 +0000566 else if VG_BOOL_CLO(arg, "--error-limit", VG_(clo_error_limit)) {}
567 else if VG_INT_CLO (arg, "--error-exitcode", VG_(clo_error_exitcode)) {}
568 else if VG_BOOL_CLO(arg, "--show-emwarns", VG_(clo_show_emwarns)) {}
sewardj95d86c02007-12-18 01:49:23 +0000569
njn83df0b62009-02-25 01:01:05 +0000570 else if VG_BOOL_CLO(arg, "--run-libc-freeres", VG_(clo_run_libc_freeres)) {}
571 else if VG_BOOL_CLO(arg, "--show-below-main", VG_(clo_show_below_main)) {}
572 else if VG_BOOL_CLO(arg, "--time-stamp", VG_(clo_time_stamp)) {}
573 else if VG_BOOL_CLO(arg, "--track-fds", VG_(clo_track_fds)) {}
574 else if VG_BOOL_CLO(arg, "--trace-children", VG_(clo_trace_children)) {}
575 else if VG_BOOL_CLO(arg, "--child-silent-after-fork",
576 VG_(clo_child_silent_after_fork)) {}
bart78bfc712011-12-08 16:14:59 +0000577 else if VG_STR_CLO(arg, "--fair-sched", tmp_str) {
578 if (VG_(strcmp)(tmp_str, "yes") == 0)
579 VG_(clo_fair_sched) = enable_fair_sched;
580 else if (VG_(strcmp)(tmp_str, "try") == 0)
581 VG_(clo_fair_sched) = try_fair_sched;
582 else if (VG_(strcmp)(tmp_str, "no") == 0)
583 VG_(clo_fair_sched) = disable_fair_sched;
584 else
mjwd898bf02014-05-16 22:38:46 +0000585 VG_(fmsg_bad_option)(arg, "");
586
bart78bfc712011-12-08 16:14:59 +0000587 }
njn83df0b62009-02-25 01:01:05 +0000588 else if VG_BOOL_CLO(arg, "--trace-sched", VG_(clo_trace_sched)) {}
589 else if VG_BOOL_CLO(arg, "--trace-signals", VG_(clo_trace_signals)) {}
590 else if VG_BOOL_CLO(arg, "--trace-symtab", VG_(clo_trace_symtab)) {}
591 else if VG_STR_CLO (arg, "--trace-symtab-patt", VG_(clo_trace_symtab_patt)) {}
592 else if VG_BOOL_CLO(arg, "--trace-cfi", VG_(clo_trace_cfi)) {}
593 else if VG_XACT_CLO(arg, "--debug-dump=syms", VG_(clo_debug_dump_syms),
594 True) {}
595 else if VG_XACT_CLO(arg, "--debug-dump=line", VG_(clo_debug_dump_line),
596 True) {}
597 else if VG_XACT_CLO(arg, "--debug-dump=frames",
598 VG_(clo_debug_dump_frames), True) {}
599 else if VG_BOOL_CLO(arg, "--trace-redir", VG_(clo_trace_redir)) {}
sewardj95d86c02007-12-18 01:49:23 +0000600
njn83df0b62009-02-25 01:01:05 +0000601 else if VG_BOOL_CLO(arg, "--trace-syscalls", VG_(clo_trace_syscalls)) {}
602 else if VG_BOOL_CLO(arg, "--wait-for-gdb", VG_(clo_wait_for_gdb)) {}
603 else if VG_STR_CLO (arg, "--db-command", VG_(clo_db_command)) {}
njn83df0b62009-02-25 01:01:05 +0000604 else if VG_BOOL_CLO(arg, "--sym-offsets", VG_(clo_sym_offsets)) {}
philippea0a73932014-06-15 15:42:20 +0000605 else if VG_BOOL_CLO(arg, "--read-inline-info", VG_(clo_read_inline_info)) {}
njn83df0b62009-02-25 01:01:05 +0000606 else if VG_BOOL_CLO(arg, "--read-var-info", VG_(clo_read_var_info)) {}
sewardjf767d962007-02-12 17:47:14 +0000607
njn83df0b62009-02-25 01:01:05 +0000608 else if VG_INT_CLO (arg, "--dump-error", VG_(clo_dump_error)) {}
609 else if VG_INT_CLO (arg, "--input-fd", VG_(clo_input_fd)) {}
610 else if VG_INT_CLO (arg, "--sanity-level", VG_(clo_sanity_level)) {}
611 else if VG_BINT_CLO(arg, "--num-callers", VG_(clo_backtrace_size), 1,
612 VG_DEEPEST_BACKTRACE) {}
philippe8e1bee42013-10-18 00:08:20 +0000613 else if VG_BINT_CLO(arg, "--num-transtab-sectors",
614 VG_(clo_num_transtab_sectors),
615 MIN_N_SECTORS, MAX_N_SECTORS) {}
philippe46207652013-01-20 17:11:58 +0000616 else if VG_BINT_CLO(arg, "--merge-recursive-frames",
617 VG_(clo_merge_recursive_frames), 0,
618 VG_DEEPEST_BACKTRACE) {}
sewardjde4a1d02002-03-22 01:27:54 +0000619
njn83df0b62009-02-25 01:01:05 +0000620 else if VG_XACT_CLO(arg, "--smc-check=none", VG_(clo_smc_check),
621 Vg_SmcNone);
622 else if VG_XACT_CLO(arg, "--smc-check=stack", VG_(clo_smc_check),
623 Vg_SmcStack);
624 else if VG_XACT_CLO(arg, "--smc-check=all", VG_(clo_smc_check),
625 Vg_SmcAll);
sewardj6dbcc632011-06-07 21:39:28 +0000626 else if VG_XACT_CLO(arg, "--smc-check=all-non-file",
627 VG_(clo_smc_check),
628 Vg_SmcAllNonFile);
sewardjde4a1d02002-03-22 01:27:54 +0000629
philippeec905f72014-08-17 20:03:51 +0000630 else if VG_USETX_CLO (arg, "--kernel-variant", "bproc",
631 VG_(clo_kernel_variant)) {}
sewardj26412bd2005-07-07 10:05:05 +0000632
njn97db7612009-08-04 02:32:55 +0000633 else if VG_BOOL_CLO(arg, "--dsymutil", VG_(clo_dsymutil)) {}
njnf76d27a2009-05-28 01:53:07 +0000634
sewardj9ab64a42010-12-06 11:40:04 +0000635 else if VG_STR_CLO (arg, "--trace-children-skip",
636 VG_(clo_trace_children_skip)) {}
637 else if VG_STR_CLO (arg, "--trace-children-skip-by-arg",
638 VG_(clo_trace_children_skip_by_arg)) {}
sewardj06421272009-11-05 08:55:13 +0000639
njn83df0b62009-02-25 01:01:05 +0000640 else if VG_BINT_CLO(arg, "--vex-iropt-verbosity",
641 VG_(clo_vex_control).iropt_verbosity, 0, 10) {}
642 else if VG_BINT_CLO(arg, "--vex-iropt-level",
643 VG_(clo_vex_control).iropt_level, 0, 2) {}
philippe0c0291a2012-08-01 22:03:12 +0000644 else if VG_XACT_CLO(arg,
philippe5b240c22012-08-14 22:28:31 +0000645 "--vex-iropt-register-updates=sp-at-mem-access",
646 VG_(clo_vex_control).iropt_register_updates,
647 VexRegUpdSpAtMemAccess);
648 else if VG_XACT_CLO(arg,
philippe0c0291a2012-08-01 22:03:12 +0000649 "--vex-iropt-register-updates=unwindregs-at-mem-access",
650 VG_(clo_vex_control).iropt_register_updates,
651 VexRegUpdUnwindregsAtMemAccess);
652 else if VG_XACT_CLO(arg,
653 "--vex-iropt-register-updates=allregs-at-mem-access",
654 VG_(clo_vex_control).iropt_register_updates,
655 VexRegUpdAllregsAtMemAccess);
656 else if VG_XACT_CLO(arg,
657 "--vex-iropt-register-updates=allregs-at-each-insn",
658 VG_(clo_vex_control).iropt_register_updates,
659 VexRegUpdAllregsAtEachInsn);
njn83df0b62009-02-25 01:01:05 +0000660 else if VG_BINT_CLO(arg, "--vex-iropt-unroll-thresh",
661 VG_(clo_vex_control).iropt_unroll_thresh, 0, 400) {}
662 else if VG_BINT_CLO(arg, "--vex-guest-max-insns",
663 VG_(clo_vex_control).guest_max_insns, 1, 100) {}
664 else if VG_BINT_CLO(arg, "--vex-guest-chase-thresh",
665 VG_(clo_vex_control).guest_chase_thresh, 0, 99) {}
sewardj540cc4a2010-01-15 10:57:57 +0000666 else if VG_BOOL_CLO(arg, "--vex-guest-chase-cond",
667 VG_(clo_vex_control).guest_chase_cond) {}
sewardj94c8eb42008-09-19 20:13:39 +0000668
njn83df0b62009-02-25 01:01:05 +0000669 else if VG_INT_CLO(arg, "--log-fd", tmp_log_fd) {
670 log_to = VgLogTo_Fd;
sewardj738856f2009-07-15 14:48:32 +0000671 log_fsname_unexpanded = NULL;
672 }
673 else if VG_INT_CLO(arg, "--xml-fd", tmp_xml_fd) {
674 xml_to = VgLogTo_Fd;
675 xml_fsname_unexpanded = NULL;
sewardj4cf05692002-10-27 20:28:29 +0000676 }
677
sewardj738856f2009-07-15 14:48:32 +0000678 else if VG_STR_CLO(arg, "--log-file", log_fsname_unexpanded) {
njn83df0b62009-02-25 01:01:05 +0000679 log_to = VgLogTo_File;
sewardj4cf05692002-10-27 20:28:29 +0000680 }
sewardj738856f2009-07-15 14:48:32 +0000681 else if VG_STR_CLO(arg, "--xml-file", xml_fsname_unexpanded) {
682 xml_to = VgLogTo_File;
683 }
684
685 else if VG_STR_CLO(arg, "--log-socket", log_fsname_unexpanded) {
njn83df0b62009-02-25 01:01:05 +0000686 log_to = VgLogTo_Socket;
sewardj73cf3bc2002-11-03 03:20:15 +0000687 }
sewardj738856f2009-07-15 14:48:32 +0000688 else if VG_STR_CLO(arg, "--xml-socket", xml_fsname_unexpanded) {
689 xml_to = VgLogTo_Socket;
690 }
sewardj73cf3bc2002-11-03 03:20:15 +0000691
sewardj5d616df2013-07-02 08:07:15 +0000692 else if VG_STR_CLO(arg, "--debuginfo-server",
693 VG_(clo_debuginfo_server)) {}
694
695 else if VG_BOOL_CLO(arg, "--allow-mismatched-debuginfo",
696 VG_(clo_allow_mismatched_debuginfo)) {}
697
njn83df0b62009-02-25 01:01:05 +0000698 else if VG_STR_CLO(arg, "--xml-user-comment",
699 VG_(clo_xml_user_comment)) {}
sewardj768db0e2005-07-19 14:18:56 +0000700
barta6efdfa2014-06-24 05:08:21 +0000701 else if VG_BOOL_CLO(arg, "--default-suppressions",
702 VG_(clo_default_supp)) { }
bart2c68e3e2014-06-22 10:11:59 +0000703
njn83df0b62009-02-25 01:01:05 +0000704 else if VG_STR_CLO(arg, "--suppressions", tmp_str) {
sewardjde4a1d02002-03-22 01:27:54 +0000705 if (VG_(clo_n_suppressions) >= VG_CLO_MAX_SFILES) {
njnb1cc5d62010-07-06 04:05:23 +0000706 VG_(fmsg_bad_option)(arg,
707 "Too many suppression files specified.\n"
708 "Increase VG_CLO_MAX_SFILES and recompile.\n");
sewardjde4a1d02002-03-22 01:27:54 +0000709 }
njn83df0b62009-02-25 01:01:05 +0000710 VG_(clo_suppressions)[VG_(clo_n_suppressions)] = tmp_str;
sewardjde4a1d02002-03-22 01:27:54 +0000711 VG_(clo_n_suppressions)++;
712 }
sewardjde4a1d02002-03-22 01:27:54 +0000713
sewardj14cdbf82010-10-12 00:44:05 +0000714 else if VG_STR_CLO (arg, "--fullpath-after", tmp_str) {
715 if (VG_(clo_n_fullpath_after) >= VG_CLO_MAX_FULLPATH_AFTER) {
716 VG_(fmsg_bad_option)(arg,
717 "Too many --fullpath-after= specifications.\n"
718 "Increase VG_CLO_MAX_FULLPATH_AFTER and recompile.\n");
719 }
720 VG_(clo_fullpath_after)[VG_(clo_n_fullpath_after)] = tmp_str;
721 VG_(clo_n_fullpath_after)++;
722 }
723
sewardj8b6573d2012-12-05 22:15:14 +0000724 else if VG_STR_CLO (arg, "--extra-debuginfo-path",
725 VG_(clo_extra_debuginfo_path)) {}
726
sewardjf9ebc392010-05-09 22:30:43 +0000727 else if VG_STR_CLO(arg, "--require-text-symbol", tmp_str) {
728 if (VG_(clo_n_req_tsyms) >= VG_CLO_MAX_REQ_TSYMS) {
njnb1cc5d62010-07-06 04:05:23 +0000729 VG_(fmsg_bad_option)(arg,
730 "Too many --require-text-symbol= specifications.\n"
731 "Increase VG_CLO_MAX_REQ_TSYMS and recompile.\n");
sewardjf9ebc392010-05-09 22:30:43 +0000732 }
733 /* String needs to be of the form C?*C?*, where C is any
734 character, but is the same both times. Having it in this
735 form facilitates finding the boundary between the sopatt
736 and the fnpatt just by looking for the second occurrence
737 of C, without hardwiring any assumption about what C
738 is. */
florian19f91bb2012-11-10 22:29:54 +0000739 HChar patt[7];
sewardjf9ebc392010-05-09 22:30:43 +0000740 Bool ok = True;
741 ok = tmp_str && VG_(strlen)(tmp_str) > 0;
742 if (ok) {
743 patt[0] = patt[3] = tmp_str[0];
744 patt[1] = patt[4] = '?';
745 patt[2] = patt[5] = '*';
746 patt[6] = 0;
747 ok = VG_(string_match)(patt, tmp_str);
748 }
749 if (!ok) {
njnb1cc5d62010-07-06 04:05:23 +0000750 VG_(fmsg_bad_option)(arg,
751 "Invalid --require-text-symbol= specification.\n");
sewardjf9ebc392010-05-09 22:30:43 +0000752 }
753 VG_(clo_req_tsyms)[VG_(clo_n_req_tsyms)] = tmp_str;
754 VG_(clo_n_req_tsyms)++;
755 }
756
sewardjfa8ec112005-01-19 11:55:34 +0000757 /* "stuvwxyz" --> stuvwxyz (binary) */
njn83df0b62009-02-25 01:01:05 +0000758 else if VG_STR_CLO(arg, "--trace-flags", tmp_str) {
sewardjfa8ec112005-01-19 11:55:34 +0000759 Int j;
njn83df0b62009-02-25 01:01:05 +0000760 if (8 != VG_(strlen)(tmp_str)) {
njnb1cc5d62010-07-06 04:05:23 +0000761 VG_(fmsg_bad_option)(arg,
762 "--trace-flags argument must have 8 digits\n");
sewardjfa8ec112005-01-19 11:55:34 +0000763 }
764 for (j = 0; j < 8; j++) {
njn83df0b62009-02-25 01:01:05 +0000765 if ('0' == tmp_str[j]) { /* do nothing */ }
766 else if ('1' == tmp_str[j]) VG_(clo_trace_flags) |= (1 << (7-j));
sewardjfa8ec112005-01-19 11:55:34 +0000767 else {
njnb1cc5d62010-07-06 04:05:23 +0000768 VG_(fmsg_bad_option)(arg,
769 "--trace-flags argument can only contain 0s and 1s\n");
sewardjfa8ec112005-01-19 11:55:34 +0000770 }
771 }
772 }
773
sewardj17c5e2e2012-12-28 09:12:14 +0000774 else if VG_INT_CLO (arg, "--trace-notbelow", VG_(clo_trace_notbelow)) {}
775
776 else if VG_INT_CLO (arg, "--trace-notabove", VG_(clo_trace_notabove)) {}
777
sewardjfa8ec112005-01-19 11:55:34 +0000778 /* "stuvwxyz" --> stuvwxyz (binary) */
njn83df0b62009-02-25 01:01:05 +0000779 else if VG_STR_CLO(arg, "--profile-flags", tmp_str) {
njn25e49d8e72002-09-23 09:36:25 +0000780 Int j;
njn83df0b62009-02-25 01:01:05 +0000781 if (8 != VG_(strlen)(tmp_str)) {
njnb1cc5d62010-07-06 04:05:23 +0000782 VG_(fmsg_bad_option)(arg,
783 "--profile-flags argument must have 8 digits\n");
njn25e49d8e72002-09-23 09:36:25 +0000784 }
sewardj8b635a42004-11-22 19:01:47 +0000785 for (j = 0; j < 8; j++) {
njn83df0b62009-02-25 01:01:05 +0000786 if ('0' == tmp_str[j]) { /* do nothing */ }
sewardj17c5e2e2012-12-28 09:12:14 +0000787 else if ('1' == tmp_str[j]) VG_(clo_profyle_flags) |= (1 << (7-j));
njn25e49d8e72002-09-23 09:36:25 +0000788 else {
njnb1cc5d62010-07-06 04:05:23 +0000789 VG_(fmsg_bad_option)(arg,
790 "--profile-flags argument can only contain 0s and 1s\n");
njn25e49d8e72002-09-23 09:36:25 +0000791 }
792 }
sewardj17c5e2e2012-12-28 09:12:14 +0000793 VG_(clo_profyle_sbs) = True;
njn25e49d8e72002-09-23 09:36:25 +0000794 }
sewardjde4a1d02002-03-22 01:27:54 +0000795
sewardj17c5e2e2012-12-28 09:12:14 +0000796 else if VG_INT_CLO (arg, "--profile-interval",
797 VG_(clo_profyle_interval)) {}
florian29e022d2012-07-02 21:13:34 +0000798
njn83df0b62009-02-25 01:01:05 +0000799 else if VG_XACT_CLO(arg, "--gen-suppressions=no",
800 VG_(clo_gen_suppressions), 0) {}
801 else if VG_XACT_CLO(arg, "--gen-suppressions=yes",
802 VG_(clo_gen_suppressions), 1) {}
803 else if VG_XACT_CLO(arg, "--gen-suppressions=all",
804 VG_(clo_gen_suppressions), 2) {}
sewardjd153fae2005-01-10 17:24:47 +0000805
sewardj49984ea2013-10-18 13:21:26 +0000806 else if VG_BINT_CLO(arg, "--unw-stack-scan-thresh",
807 VG_(clo_unw_stack_scan_thresh), 0, 100) {}
808 else if VG_BINT_CLO(arg, "--unw-stack-scan-frames",
809 VG_(clo_unw_stack_scan_frames), 0, 32) {}
810
nethercote71980f02004-01-24 18:18:54 +0000811 else if ( ! VG_(needs).command_line_options
njn51d827b2005-05-09 01:02:08 +0000812 || ! VG_TDICT_CALL(tool_process_cmd_line_option, arg) ) {
njnb1cc5d62010-07-06 04:05:23 +0000813 VG_(fmsg_bad_option)(arg, "");
njn25e49d8e72002-09-23 09:36:25 +0000814 }
sewardjde4a1d02002-03-22 01:27:54 +0000815 }
816
sewardj738856f2009-07-15 14:48:32 +0000817 /* END command-line processing loop */
818
florian882038d2014-09-01 06:37:07 +0000819 /* Notify about deprecated features */
820 if (VG_(clo_db_attach))
philippe574c2fd2014-09-01 20:47:55 +0000821 VG_(umsg)
822 ("\nWarning: --db-attach is a deprecated feature which will be\n"
823 " removed in the next release. Use --vgdb-error=1 instead\n\n");
florian882038d2014-09-01 06:37:07 +0000824
florianb985e2d2011-09-29 03:03:45 +0000825 /* Determine the path prefix for vgdb */
826 if (VG_(clo_vgdb_prefix) == NULL)
827 VG_(clo_vgdb_prefix) = VG_(vgdb_prefix_default)();
828
sewardj998d40d2004-12-06 14:24:52 +0000829 /* Make VEX control parameters sane */
830
831 if (VG_(clo_vex_control).guest_chase_thresh
832 >= VG_(clo_vex_control).guest_max_insns)
833 VG_(clo_vex_control).guest_chase_thresh
834 = VG_(clo_vex_control).guest_max_insns - 1;
835
836 if (VG_(clo_vex_control).guest_chase_thresh < 0)
837 VG_(clo_vex_control).guest_chase_thresh = 0;
838
839 /* Check various option values */
nethercote27fec902004-06-16 21:26:32 +0000840
njnf9ebf672003-05-12 21:41:30 +0000841 if (VG_(clo_verbosity) < 0)
sewardjde4a1d02002-03-22 01:27:54 +0000842 VG_(clo_verbosity) = 0;
843
sewardjc30cd9b2012-12-06 18:08:54 +0000844 if (!sigill_diag_set)
845 VG_(clo_sigill_diag) = (VG_(clo_verbosity) > 0);
846
florian29e022d2012-07-02 21:13:34 +0000847 if (VG_(clo_trace_notbelow) == -1) {
848 if (VG_(clo_trace_notabove) == -1) {
849 /* [] */
850 VG_(clo_trace_notbelow) = 2147483647;
851 VG_(clo_trace_notabove) = 0;
852 } else {
853 /* [0 .. notabove] */
854 VG_(clo_trace_notbelow) = 0;
855 }
856 } else {
857 if (VG_(clo_trace_notabove) == -1) {
858 /* [notbelow .. ] */
859 VG_(clo_trace_notabove) = 2147483647;
860 } else {
861 /* [notbelow .. notabove] */
862 }
863 }
864
sewardj3b290482011-05-06 21:02:55 +0000865 VG_(dyn_vgdb_error) = VG_(clo_vgdb_error);
866
njnbe9b47b2005-05-15 16:22:58 +0000867 if (VG_(clo_gen_suppressions) > 0 &&
868 !VG_(needs).core_errors && !VG_(needs).tool_errors) {
njnb1cc5d62010-07-06 04:05:23 +0000869 VG_(fmsg_bad_option)("--gen-suppressions=yes",
870 "Can't use --gen-suppressions= with %s\n"
871 "because it doesn't generate errors.\n", VG_(details).name);
njnbe9b47b2005-05-15 16:22:58 +0000872 }
873
sewardj738856f2009-07-15 14:48:32 +0000874 /* If XML output is requested, check that the tool actually
875 supports it. */
876 if (VG_(clo_xml) && !VG_(needs).xml_output) {
877 VG_(clo_xml) = False;
njnb1cc5d62010-07-06 04:05:23 +0000878 VG_(fmsg_bad_option)("--xml=yes",
sewardj738856f2009-07-15 14:48:32 +0000879 "%s does not support XML output.\n", VG_(details).name);
sewardj738856f2009-07-15 14:48:32 +0000880 /*NOTREACHED*/
881 }
882
883 vg_assert( VG_(clo_gen_suppressions) >= 0 );
884 vg_assert( VG_(clo_gen_suppressions) <= 2 );
885
sewardj71bc3cb2005-05-19 00:25:45 +0000886 /* If we've been asked to emit XML, mash around various other
887 options so as to constrain the output somewhat, and to remove
sewardj738856f2009-07-15 14:48:32 +0000888 any need for user input during the run.
889 */
sewardj71bc3cb2005-05-19 00:25:45 +0000890 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +0000891
892 /* We can't allow --gen-suppressions=yes, since that requires us
893 to print the error and then ask the user if she wants a
894 suppression for it, but in XML mode we won't print it until
895 we know whether we also need to print a suppression. Hence a
896 circular dependency. So disallow this.
897 (--gen-suppressions=all is still OK since we don't need any
898 user interaction in this case.) */
899 if (VG_(clo_gen_suppressions) == 1) {
njnb1cc5d62010-07-06 04:05:23 +0000900 VG_(fmsg_bad_option)(
901 "--xml=yes together with --gen-suppressions=yes",
902 "When --xml=yes is specified, --gen-suppressions=no\n"
903 "or --gen-suppressions=all is allowed, but not "
sewardj738856f2009-07-15 14:48:32 +0000904 "--gen-suppressions=yes.\n");
sewardj738856f2009-07-15 14:48:32 +0000905 }
906
907 /* We can't allow DB attaching (or we maybe could, but results
908 could be chaotic ..) since it requires user input. Hence
909 disallow. */
910 if (VG_(clo_db_attach)) {
njnb1cc5d62010-07-06 04:05:23 +0000911 VG_(fmsg_bad_option)(
912 "--xml=yes together with --db-attach=yes",
913 "--db-attach=yes is not allowed with --xml=yes\n"
914 "because it would require user input.\n");
sewardj738856f2009-07-15 14:48:32 +0000915 }
916
917 /* Disallow dump_error in XML mode; sounds like a recipe for
918 chaos. No big deal; dump_error is a flag for debugging V
919 itself. */
920 if (VG_(clo_dump_error) > 0) {
mjwd898bf02014-05-16 22:38:46 +0000921 VG_(fmsg_bad_option)("--xml=yes together with --dump-error", "");
sewardj738856f2009-07-15 14:48:32 +0000922 }
923
sewardj71bc3cb2005-05-19 00:25:45 +0000924 /* Disable error limits (this might be a bad idea!) */
925 VG_(clo_error_limit) = False;
926 /* Disable emulation warnings */
sewardj738856f2009-07-15 14:48:32 +0000927
sewardj71bc3cb2005-05-19 00:25:45 +0000928 /* Also, we want to set options for the leak checker, but that
929 will have to be done in Memcheck's flag-handling code, not
930 here. */
931 }
932
njnbe9b47b2005-05-15 16:22:58 +0000933 /* All non-logging-related options have been checked. If the logging
934 option specified is ok, we can switch to it, as we know we won't
935 have to generate any other command-line-related error messages.
936 (So far we should be still attached to stderr, so we can show on
937 the terminal any problems to do with processing command line
938 opts.)
939
sewardj738856f2009-07-15 14:48:32 +0000940 So set up logging now. After this is done, VG_(log_output_sink)
941 and (if relevant) VG_(xml_output_sink) should be connected to
942 whatever sink has been selected, and we indiscriminately chuck
943 stuff into it without worrying what the nature of it is. Oh the
944 wonder of Unix streams. */
sewardj4cf05692002-10-27 20:28:29 +0000945
sewardj738856f2009-07-15 14:48:32 +0000946 vg_assert(VG_(log_output_sink).fd == 2 /* stderr */);
947 vg_assert(VG_(log_output_sink).is_socket == False);
948 vg_assert(VG_(clo_log_fname_expanded) == NULL);
949
950 vg_assert(VG_(xml_output_sink).fd == -1 /* disabled */);
951 vg_assert(VG_(xml_output_sink).is_socket == False);
952 vg_assert(VG_(clo_xml_fname_expanded) == NULL);
953
954 /* --- set up the normal text output channel --- */
sewardj4cf05692002-10-27 20:28:29 +0000955
njnbe9b47b2005-05-15 16:22:58 +0000956 switch (log_to) {
sewardj73cf3bc2002-11-03 03:20:15 +0000957
sewardj4cf05692002-10-27 20:28:29 +0000958 case VgLogTo_Fd:
sewardj738856f2009-07-15 14:48:32 +0000959 vg_assert(log_fsname_unexpanded == NULL);
sewardj4cf05692002-10-27 20:28:29 +0000960 break;
sewardj73cf3bc2002-11-03 03:20:15 +0000961
sewardj4cf05692002-10-27 20:28:29 +0000962 case VgLogTo_File: {
florian19f91bb2012-11-10 22:29:54 +0000963 HChar* logfilename;
jsgff3c3f1a2003-10-14 22:13:28 +0000964
sewardj738856f2009-07-15 14:48:32 +0000965 vg_assert(log_fsname_unexpanded != NULL);
966 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
jsgff3c3f1a2003-10-14 22:13:28 +0000967
njn374a36d2007-11-23 01:41:32 +0000968 // Nb: we overwrite an existing file of this name without asking
969 // any questions.
sewardj738856f2009-07-15 14:48:32 +0000970 logfilename = VG_(expand_file_name)("--log-file",
971 log_fsname_unexpanded);
njn374a36d2007-11-23 01:41:32 +0000972 sres = VG_(open)(logfilename,
njnda033f52005-12-19 21:27:58 +0000973 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
974 VKI_S_IRUSR|VKI_S_IWUSR);
njncda2f0f2009-05-18 02:12:08 +0000975 if (!sr_isError(sres)) {
976 tmp_log_fd = sr_Res(sres);
sewardj738856f2009-07-15 14:48:32 +0000977 VG_(clo_log_fname_expanded) = logfilename;
njnbe9b47b2005-05-15 16:22:58 +0000978 } else {
njnb1cc5d62010-07-06 04:05:23 +0000979 VG_(fmsg)("can't create log file '%s': %s\n",
980 logfilename, VG_(strerror)(sr_Err(sres)));
981 VG_(exit)(1);
sewardj603d4102005-01-11 14:01:02 +0000982 /*NOTREACHED*/
njn374a36d2007-11-23 01:41:32 +0000983 }
sewardj738856f2009-07-15 14:48:32 +0000984 break;
sewardj73cf3bc2002-11-03 03:20:15 +0000985 }
986
987 case VgLogTo_Socket: {
sewardj738856f2009-07-15 14:48:32 +0000988 vg_assert(log_fsname_unexpanded != NULL);
989 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
990 tmp_log_fd = VG_(connect_via_socket)( log_fsname_unexpanded );
njnda033f52005-12-19 21:27:58 +0000991 if (tmp_log_fd == -1) {
njnb1cc5d62010-07-06 04:05:23 +0000992 VG_(fmsg)("Invalid --log-socket spec of '%s'\n",
993 log_fsname_unexpanded);
994 VG_(exit)(1);
njnbe9b47b2005-05-15 16:22:58 +0000995 /*NOTREACHED*/
sewardj4cf05692002-10-27 20:28:29 +0000996 }
njnda033f52005-12-19 21:27:58 +0000997 if (tmp_log_fd == -2) {
njnb1cc5d62010-07-06 04:05:23 +0000998 VG_(umsg)("failed to connect to logging server '%s'.\n"
999 "Log messages will sent to stderr instead.\n",
1000 log_fsname_unexpanded );
1001
sewardj570f8902002-11-03 11:44:36 +00001002 /* We don't change anything here. */
sewardj738856f2009-07-15 14:48:32 +00001003 vg_assert(VG_(log_output_sink).fd == 2);
njnda033f52005-12-19 21:27:58 +00001004 tmp_log_fd = 2;
sewardj570f8902002-11-03 11:44:36 +00001005 } else {
njnda033f52005-12-19 21:27:58 +00001006 vg_assert(tmp_log_fd > 0);
sewardj738856f2009-07-15 14:48:32 +00001007 VG_(log_output_sink).is_socket = True;
sewardj570f8902002-11-03 11:44:36 +00001008 }
sewardj73cf3bc2002-11-03 03:20:15 +00001009 break;
1010 }
sewardj4cf05692002-10-27 20:28:29 +00001011 }
1012
sewardj738856f2009-07-15 14:48:32 +00001013 /* --- set up the XML output channel --- */
sewardj71bc3cb2005-05-19 00:25:45 +00001014
sewardj738856f2009-07-15 14:48:32 +00001015 switch (xml_to) {
1016
1017 case VgLogTo_Fd:
1018 vg_assert(xml_fsname_unexpanded == NULL);
1019 break;
1020
1021 case VgLogTo_File: {
florian19f91bb2012-11-10 22:29:54 +00001022 HChar* xmlfilename;
sewardj738856f2009-07-15 14:48:32 +00001023
1024 vg_assert(xml_fsname_unexpanded != NULL);
1025 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
1026
1027 // Nb: we overwrite an existing file of this name without asking
1028 // any questions.
1029 xmlfilename = VG_(expand_file_name)("--xml-file",
1030 xml_fsname_unexpanded);
1031 sres = VG_(open)(xmlfilename,
1032 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
1033 VKI_S_IRUSR|VKI_S_IWUSR);
1034 if (!sr_isError(sres)) {
1035 tmp_xml_fd = sr_Res(sres);
1036 VG_(clo_xml_fname_expanded) = xmlfilename;
1037 /* strdup here is probably paranoid overkill, but ... */
1038 *xml_fname_unexpanded = VG_(strdup)( "main.mpclo.2",
1039 xml_fsname_unexpanded );
1040 } else {
njnb1cc5d62010-07-06 04:05:23 +00001041 VG_(fmsg)("can't create XML file '%s': %s\n",
1042 xmlfilename, VG_(strerror)(sr_Err(sres)));
1043 VG_(exit)(1);
sewardj738856f2009-07-15 14:48:32 +00001044 /*NOTREACHED*/
1045 }
1046 break;
1047 }
1048
1049 case VgLogTo_Socket: {
1050 vg_assert(xml_fsname_unexpanded != NULL);
1051 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
1052 tmp_xml_fd = VG_(connect_via_socket)( xml_fsname_unexpanded );
1053 if (tmp_xml_fd == -1) {
njnb1cc5d62010-07-06 04:05:23 +00001054 VG_(fmsg)("Invalid --xml-socket spec of '%s'\n",
1055 xml_fsname_unexpanded );
1056 VG_(exit)(1);
sewardj738856f2009-07-15 14:48:32 +00001057 /*NOTREACHED*/
1058 }
1059 if (tmp_xml_fd == -2) {
njnb1cc5d62010-07-06 04:05:23 +00001060 VG_(umsg)("failed to connect to XML logging server '%s'.\n"
1061 "XML output will sent to stderr instead.\n",
1062 xml_fsname_unexpanded);
sewardj738856f2009-07-15 14:48:32 +00001063 /* We don't change anything here. */
1064 vg_assert(VG_(xml_output_sink).fd == 2);
1065 tmp_xml_fd = 2;
1066 } else {
1067 vg_assert(tmp_xml_fd > 0);
1068 VG_(xml_output_sink).is_socket = True;
1069 }
1070 break;
1071 }
sewardj71bc3cb2005-05-19 00:25:45 +00001072 }
1073
sewardj738856f2009-07-15 14:48:32 +00001074 /* If we've got this far, and XML mode was requested, but no XML
1075 output channel appears to have been specified, just stop. We
1076 could continue, and XML output will simply vanish into nowhere,
1077 but that is likely to confuse the hell out of users, which is
1078 distinctly Ungood. */
1079 if (VG_(clo_xml) && tmp_xml_fd == -1) {
njnb1cc5d62010-07-06 04:05:23 +00001080 VG_(fmsg_bad_option)(
1081 "--xml=yes, but no XML destination specified",
sewardj738856f2009-07-15 14:48:32 +00001082 "--xml=yes has been specified, but there is no XML output\n"
1083 "destination. You must specify an XML output destination\n"
njnb1cc5d62010-07-06 04:05:23 +00001084 "using --xml-fd, --xml-file or --xml-socket.\n"
1085 );
sewardj738856f2009-07-15 14:48:32 +00001086 }
1087
1088 // Finalise the output fds: the log fd ..
1089
njnda033f52005-12-19 21:27:58 +00001090 if (tmp_log_fd >= 0) {
sewardj738856f2009-07-15 14:48:32 +00001091 // Move log_fd into the safe range, so it doesn't conflict with
1092 // any app fds.
njnda033f52005-12-19 21:27:58 +00001093 tmp_log_fd = VG_(fcntl)(tmp_log_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
1094 if (tmp_log_fd < 0) {
sewardj738856f2009-07-15 14:48:32 +00001095 VG_(message)(Vg_UserMsg, "valgrind: failed to move logfile fd "
1096 "into safe range, using stderr\n");
1097 VG_(log_output_sink).fd = 2; // stderr
1098 VG_(log_output_sink).is_socket = False;
njnda033f52005-12-19 21:27:58 +00001099 } else {
sewardj738856f2009-07-15 14:48:32 +00001100 VG_(log_output_sink).fd = tmp_log_fd;
1101 VG_(fcntl)(VG_(log_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
njnda033f52005-12-19 21:27:58 +00001102 }
1103 } else {
1104 // If they said --log-fd=-1, don't print anything. Plausible for use in
1105 // regression testing suites that use client requests to count errors.
sewardj738856f2009-07-15 14:48:32 +00001106 VG_(log_output_sink).fd = -1;
1107 VG_(log_output_sink).is_socket = False;
jsgf855d93d2003-10-13 22:26:55 +00001108 }
1109
sewardj738856f2009-07-15 14:48:32 +00001110 // Finalise the output fds: and the XML fd ..
1111
1112 if (tmp_xml_fd >= 0) {
1113 // Move xml_fd into the safe range, so it doesn't conflict with
1114 // any app fds.
1115 tmp_xml_fd = VG_(fcntl)(tmp_xml_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
1116 if (tmp_xml_fd < 0) {
1117 VG_(message)(Vg_UserMsg, "valgrind: failed to move XML file fd "
1118 "into safe range, using stderr\n");
1119 VG_(xml_output_sink).fd = 2; // stderr
1120 VG_(xml_output_sink).is_socket = False;
1121 } else {
1122 VG_(xml_output_sink).fd = tmp_xml_fd;
1123 VG_(fcntl)(VG_(xml_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
1124 }
1125 } else {
1126 // If they said --xml-fd=-1, don't print anything. Plausible for use in
1127 // regression testing suites that use client requests to count errors.
1128 VG_(xml_output_sink).fd = -1;
1129 VG_(xml_output_sink).is_socket = False;
1130 }
1131
1132 // Suppressions related stuff
1133
bart2c68e3e2014-06-22 10:11:59 +00001134 if (VG_(clo_default_supp) &&
1135 VG_(clo_n_suppressions) < VG_CLO_MAX_SFILES-1 &&
sewardj45f4e7c2005-09-27 19:20:21 +00001136 (VG_(needs).core_errors || VG_(needs).tool_errors)) {
1137 /* If we haven't reached the max number of suppressions, load
1138 the default one. */
floriane6a4ed12012-10-21 02:30:18 +00001139 static const HChar default_supp[] = "default.supp";
sewardj45f4e7c2005-09-27 19:20:21 +00001140 Int len = VG_(strlen)(VG_(libdir)) + 1 + sizeof(default_supp);
florian19f91bb2012-11-10 22:29:54 +00001141 HChar *buf = VG_(arena_malloc)(VG_AR_CORE, "main.mpclo.3", len);
sewardj45f4e7c2005-09-27 19:20:21 +00001142 VG_(sprintf)(buf, "%s/%s", VG_(libdir), default_supp);
1143 VG_(clo_suppressions)[VG_(clo_n_suppressions)] = buf;
1144 VG_(clo_n_suppressions)++;
1145 }
sewardjde4a1d02002-03-22 01:27:54 +00001146
sewardj738856f2009-07-15 14:48:32 +00001147 *logging_to_fd = log_to == VgLogTo_Fd || log_to == VgLogTo_Socket;
sewardj45f4e7c2005-09-27 19:20:21 +00001148}
1149
sewardj4efbaa72008-06-04 06:51:58 +00001150// Write the name and value of log file qualifiers to the xml file.
florian19f91bb2012-11-10 22:29:54 +00001151static void print_file_vars(HChar* format)
sewardj4efbaa72008-06-04 06:51:58 +00001152{
1153 Int i = 0;
1154
1155 while (format[i]) {
1156 if (format[i] == '%') {
1157 // We saw a '%'. What's next...
1158 i++;
1159 if ('q' == format[i]) {
1160 i++;
1161 if ('{' == format[i]) {
1162 // Get the env var name, print its contents.
florian19f91bb2012-11-10 22:29:54 +00001163 HChar* qualname;
1164 HChar* qual;
sewardj4efbaa72008-06-04 06:51:58 +00001165 i++;
1166 qualname = &format[i];
1167 while (True) {
1168 if ('}' == format[i]) {
1169 // Temporarily replace the '}' with NUL to extract var
1170 // name.
1171 format[i] = 0;
1172 qual = VG_(getenv)(qualname);
1173 break;
1174 }
1175 i++;
1176 }
1177
bartb3af9cf2011-10-06 19:08:37 +00001178 VG_(printf_xml)(
1179 "<logfilequalifier> <var>%pS</var> "
1180 "<value>%pS</value> </logfilequalifier>\n",
sewardj7ca100d2009-08-15 23:05:34 +00001181 qualname,qual
1182 );
sewardj4efbaa72008-06-04 06:51:58 +00001183 format[i] = '}';
1184 i++;
1185 }
1186 }
1187 } else {
1188 i++;
1189 }
1190 }
1191}
1192
sewardj45f4e7c2005-09-27 19:20:21 +00001193
1194/*====================================================================*/
1195/*=== Printing the preamble ===*/
1196/*====================================================================*/
1197
barta92677a2011-10-22 08:24:32 +00001198// Print the argument, escaping any chars that require it.
florian19f91bb2012-11-10 22:29:54 +00001199static void umsg_arg(const HChar* arg)
njnf8a11cf2009-08-02 23:03:06 +00001200{
1201 SizeT len = VG_(strlen)(arg);
floriane6a4ed12012-10-21 02:30:18 +00001202 const HChar* special = " \\<>";
njnf8a11cf2009-08-02 23:03:06 +00001203 Int i;
1204 for (i = 0; i < len; i++) {
1205 if (VG_(strchr)(special, arg[i])) {
barta92677a2011-10-22 08:24:32 +00001206 VG_(umsg)("\\"); // escape with a backslash if necessary
njnf8a11cf2009-08-02 23:03:06 +00001207 }
barta92677a2011-10-22 08:24:32 +00001208 VG_(umsg)("%c", arg[i]);
njnf8a11cf2009-08-02 23:03:06 +00001209 }
1210}
1211
barta92677a2011-10-22 08:24:32 +00001212// Send output to the XML-stream and escape any XML meta-characters.
florian19f91bb2012-11-10 22:29:54 +00001213static void xml_arg(const HChar* arg)
barta92677a2011-10-22 08:24:32 +00001214{
1215 VG_(printf_xml)("%pS", arg);
1216}
1217
sewardj45f4e7c2005-09-27 19:20:21 +00001218/* Ok, the logging sink is running now. Print a suitable preamble.
1219 If logging to file or a socket, write details of parent PID and
1220 command line args, to help people trying to interpret the
1221 results of a run which encompasses multiple processes. */
sewardj738856f2009-07-15 14:48:32 +00001222static void print_preamble ( Bool logging_to_fd,
florian19f91bb2012-11-10 22:29:54 +00001223 HChar* xml_fname_unexpanded,
sewardj738856f2009-07-15 14:48:32 +00001224 const HChar* toolname )
sewardj45f4e7c2005-09-27 19:20:21 +00001225{
sewardj738856f2009-07-15 14:48:32 +00001226 Int i;
florian6bd9dc12012-11-23 16:17:43 +00001227 const HChar* xpre = VG_(clo_xml) ? " <line>" : "";
1228 const HChar* xpost = VG_(clo_xml) ? "</line>" : "";
sewardj738856f2009-07-15 14:48:32 +00001229 UInt (*umsg_or_xml)( const HChar*, ... )
1230 = VG_(clo_xml) ? VG_(printf_xml) : VG_(umsg);
tom60a4b0b2005-10-12 10:45:27 +00001231
florian19f91bb2012-11-10 22:29:54 +00001232 void (*umsg_or_xml_arg)( const HChar* )
barta92677a2011-10-22 08:24:32 +00001233 = VG_(clo_xml) ? xml_arg : umsg_arg;
1234
sewardj14c7cc52007-02-25 15:08:24 +00001235 vg_assert( VG_(args_for_client) );
1236 vg_assert( VG_(args_for_valgrind) );
sewardj99a2ceb2007-11-09 12:30:36 +00001237 vg_assert( toolname );
sewardj14c7cc52007-02-25 15:08:24 +00001238
sewardj71bc3cb2005-05-19 00:25:45 +00001239 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +00001240 VG_(printf_xml)("<?xml version=\"1.0\"?>\n");
1241 VG_(printf_xml)("\n");
1242 VG_(printf_xml)("<valgrindoutput>\n");
1243 VG_(printf_xml)("\n");
1244 VG_(printf_xml)("<protocolversion>4</protocolversion>\n");
1245 VG_(printf_xml)("<protocoltool>%s</protocoltool>\n", toolname);
1246 VG_(printf_xml)("\n");
sewardj71bc3cb2005-05-19 00:25:45 +00001247 }
1248
sewardj738856f2009-07-15 14:48:32 +00001249 if (VG_(clo_xml) || VG_(clo_verbosity > 0)) {
sewardjd7bddad2005-06-13 16:48:32 +00001250
1251 if (VG_(clo_xml))
sewardj738856f2009-07-15 14:48:32 +00001252 VG_(printf_xml)("<preamble>\n");
sewardjd7bddad2005-06-13 16:48:32 +00001253
nethercote996901a2004-08-03 13:29:09 +00001254 /* Tool details */
bartb3af9cf2011-10-06 19:08:37 +00001255 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 +00001256 xpre,
njnd04b7c62002-10-03 14:05:52 +00001257 VG_(details).name,
njnb9c427c2004-12-01 14:14:42 +00001258 NULL == VG_(details).version ? "" : "-",
njnd04b7c62002-10-03 14:05:52 +00001259 NULL == VG_(details).version
floriane6a4ed12012-10-21 02:30:18 +00001260 ? "" : VG_(details).version,
sewardj71bc3cb2005-05-19 00:25:45 +00001261 VG_(details).description,
sewardj738856f2009-07-15 14:48:32 +00001262 xpost );
sewardj99a2ceb2007-11-09 12:30:36 +00001263
njn10b9aea2009-07-14 06:55:05 +00001264 if (VG_(strlen)(toolname) >= 4 && VG_STREQN(4, toolname, "exp-")) {
sewardj738856f2009-07-15 14:48:32 +00001265 umsg_or_xml(
njnb6267bd2009-08-12 00:14:16 +00001266 "%sNOTE: This is an Experimental-Class Valgrind Tool%s\n",
sewardj99a2ceb2007-11-09 12:30:36 +00001267 xpre, xpost
1268 );
1269 }
1270
bartb3af9cf2011-10-06 19:08:37 +00001271 umsg_or_xml( VG_(clo_xml) ? "%s%pS%s\n" : "%s%s%s\n",
sewardj743a2082010-07-23 17:03:22 +00001272 xpre, VG_(details).copyright_author, xpost );
sewardj3b2736a2002-03-24 12:18:35 +00001273
njnd04b7c62002-10-03 14:05:52 +00001274 /* Core details */
sewardj738856f2009-07-15 14:48:32 +00001275 umsg_or_xml(
njnf73d87f2009-07-24 04:47:04 +00001276 "%sUsing Valgrind-%s and LibVEX; rerun with -h for copyright info%s\n",
1277 xpre, VERSION, xpost
sewardj738856f2009-07-15 14:48:32 +00001278 );
sewardj45f4e7c2005-09-27 19:20:21 +00001279
njnf3977a32009-08-04 00:27:56 +00001280 // Print the command line. At one point we wrapped at 80 chars and
1281 // printed a '\' as a line joiner, but that makes it hard to cut and
1282 // paste the command line (because of the "==pid==" prefixes), so we now
1283 // favour utility and simplicity over aesthetics.
1284 umsg_or_xml("%sCommand: ", xpre);
florianb16609b2014-08-20 21:04:14 +00001285 umsg_or_xml_arg(VG_(args_the_exename));
barta92677a2011-10-22 08:24:32 +00001286
njn53162bf2009-07-29 23:34:49 +00001287 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1288 HChar* s = *(HChar**)VG_(indexXA)( VG_(args_for_client), i );
njnf8a11cf2009-08-02 23:03:06 +00001289 umsg_or_xml(" ");
barta92677a2011-10-22 08:24:32 +00001290 umsg_or_xml_arg(s);
njn53162bf2009-07-29 23:34:49 +00001291 }
njnf3977a32009-08-04 00:27:56 +00001292 umsg_or_xml("%s\n", xpost);
njn53162bf2009-07-29 23:34:49 +00001293
sewardjd7bddad2005-06-13 16:48:32 +00001294 if (VG_(clo_xml))
sewardj738856f2009-07-15 14:48:32 +00001295 VG_(printf_xml)("</preamble>\n");
njnd04b7c62002-10-03 14:05:52 +00001296 }
1297
njnb6267bd2009-08-12 00:14:16 +00001298 // Print the parent PID, and other stuff, if necessary.
sewardj45f4e7c2005-09-27 19:20:21 +00001299 if (!VG_(clo_xml) && VG_(clo_verbosity) > 0 && !logging_to_fd) {
njn305dc002009-07-30 23:36:43 +00001300 VG_(umsg)("Parent PID: %d\n", VG_(getppid)());
sewardj4cf05692002-10-27 20:28:29 +00001301 }
sewardj71bc3cb2005-05-19 00:25:45 +00001302 else
1303 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +00001304 VG_(printf_xml)("\n");
1305 VG_(printf_xml)("<pid>%d</pid>\n", VG_(getpid)());
1306 VG_(printf_xml)("<ppid>%d</ppid>\n", VG_(getppid)());
bartb3af9cf2011-10-06 19:08:37 +00001307 VG_(printf_xml)("<tool>%pS</tool>\n", toolname);
sewardj738856f2009-07-15 14:48:32 +00001308 if (xml_fname_unexpanded)
1309 print_file_vars(xml_fname_unexpanded);
sewardj768db0e2005-07-19 14:18:56 +00001310 if (VG_(clo_xml_user_comment)) {
1311 /* Note: the user comment itself is XML and is therefore to
1312 be passed through verbatim (%s) rather than escaped
bartb3af9cf2011-10-06 19:08:37 +00001313 (%pS). */
sewardj738856f2009-07-15 14:48:32 +00001314 VG_(printf_xml)("<usercomment>%s</usercomment>\n",
1315 VG_(clo_xml_user_comment));
sewardj768db0e2005-07-19 14:18:56 +00001316 }
sewardj738856f2009-07-15 14:48:32 +00001317 VG_(printf_xml)("\n");
1318 VG_(printf_xml)("<args>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001319
sewardj738856f2009-07-15 14:48:32 +00001320 VG_(printf_xml)(" <vargv>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001321 if (VG_(name_of_launcher))
bartb3af9cf2011-10-06 19:08:37 +00001322 VG_(printf_xml)(" <exe>%pS</exe>\n",
sewardj738856f2009-07-15 14:48:32 +00001323 VG_(name_of_launcher));
sewardj125fd4f2007-03-08 19:56:14 +00001324 else
bartb3af9cf2011-10-06 19:08:37 +00001325 VG_(printf_xml)(" <exe>%pS</exe>\n",
njnb1cc5d62010-07-06 04:05:23 +00001326 "(launcher name unknown)");
sewardj14c7cc52007-02-25 15:08:24 +00001327 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
bartb3af9cf2011-10-06 19:08:37 +00001328 VG_(printf_xml)(
1329 " <arg>%pS</arg>\n",
sewardj738856f2009-07-15 14:48:32 +00001330 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1331 );
sewardjb8a3dac2005-07-19 12:39:11 +00001332 }
sewardj738856f2009-07-15 14:48:32 +00001333 VG_(printf_xml)(" </vargv>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001334
sewardj738856f2009-07-15 14:48:32 +00001335 VG_(printf_xml)(" <argv>\n");
florianb16609b2014-08-20 21:04:14 +00001336 VG_(printf_xml)(" <exe>%pS</exe>\n",
sewardj738856f2009-07-15 14:48:32 +00001337 VG_(args_the_exename));
sewardj14c7cc52007-02-25 15:08:24 +00001338 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
bartb3af9cf2011-10-06 19:08:37 +00001339 VG_(printf_xml)(
1340 " <arg>%pS</arg>\n",
sewardj738856f2009-07-15 14:48:32 +00001341 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1342 );
sewardj8665d8e2005-06-01 17:35:23 +00001343 }
sewardj738856f2009-07-15 14:48:32 +00001344 VG_(printf_xml)(" </argv>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001345
sewardj738856f2009-07-15 14:48:32 +00001346 VG_(printf_xml)("</args>\n");
sewardj71bc3cb2005-05-19 00:25:45 +00001347 }
sewardj4cf05692002-10-27 20:28:29 +00001348
njnb6267bd2009-08-12 00:14:16 +00001349 // Last thing in the preamble is a blank line.
sewardj738856f2009-07-15 14:48:32 +00001350 if (VG_(clo_xml))
1351 VG_(printf_xml)("\n");
njnb6267bd2009-08-12 00:14:16 +00001352 else if (VG_(clo_verbosity) > 0)
1353 VG_(umsg)("\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001354
sewardjde4a1d02002-03-22 01:27:54 +00001355 if (VG_(clo_verbosity) > 1) {
sewardj92645592005-07-23 09:18:34 +00001356 SysRes fd;
sewardj1f0bbc72005-11-16 03:51:02 +00001357 VexArch vex_arch;
1358 VexArchInfo vex_archinfo;
sewardj45f4e7c2005-09-27 19:20:21 +00001359 if (!logging_to_fd)
sewardj738856f2009-07-15 14:48:32 +00001360 VG_(message)(Vg_DebugMsg, "\n");
njna3311642009-08-10 01:29:14 +00001361 VG_(message)(Vg_DebugMsg, "Valgrind options:\n");
sewardj14c7cc52007-02-25 15:08:24 +00001362 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
1363 VG_(message)(Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +00001364 " %s\n",
sewardj14c7cc52007-02-25 15:08:24 +00001365 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ));
sewardjde4a1d02002-03-22 01:27:54 +00001366 }
nethercotea70f7352004-04-18 12:08:46 +00001367
sewardj738856f2009-07-15 14:48:32 +00001368 VG_(message)(Vg_DebugMsg, "Contents of /proc/version:\n");
nethercotea70f7352004-04-18 12:08:46 +00001369 fd = VG_(open) ( "/proc/version", VKI_O_RDONLY, 0 );
njncda2f0f2009-05-18 02:12:08 +00001370 if (sr_isError(fd)) {
sewardj738856f2009-07-15 14:48:32 +00001371 VG_(message)(Vg_DebugMsg, " can't open /proc/version\n");
nethercotea70f7352004-04-18 12:08:46 +00001372 } else {
sewardj71bc3cb2005-05-19 00:25:45 +00001373# define BUF_LEN 256
florian19f91bb2012-11-10 22:29:54 +00001374 HChar version_buf[BUF_LEN];
njnf3977a32009-08-04 00:27:56 +00001375 Int n = VG_(read) ( sr_Res(fd), version_buf, BUF_LEN );
1376 vg_assert(n <= BUF_LEN);
1377 if (n > 0) {
1378 version_buf[n-1] = '\0';
sewardj738856f2009-07-15 14:48:32 +00001379 VG_(message)(Vg_DebugMsg, " %s\n", version_buf);
nethercotea70f7352004-04-18 12:08:46 +00001380 } else {
sewardj738856f2009-07-15 14:48:32 +00001381 VG_(message)(Vg_DebugMsg, " (empty?)\n");
nethercotea70f7352004-04-18 12:08:46 +00001382 }
njncda2f0f2009-05-18 02:12:08 +00001383 VG_(close)(sr_Res(fd));
sewardj71bc3cb2005-05-19 00:25:45 +00001384# undef BUF_LEN
nethercotea70f7352004-04-18 12:08:46 +00001385 }
sewardj1f0bbc72005-11-16 03:51:02 +00001386
1387 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
sewardje3121f32006-01-27 21:23:23 +00001388 VG_(message)(
1389 Vg_DebugMsg,
sewardj59731422014-07-24 12:45:24 +00001390 "Arch and hwcaps: %s, %s, %s\n",
1391 LibVEX_ppVexArch ( vex_arch ),
1392 LibVEX_ppVexEndness ( vex_archinfo.endness ),
1393 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
sewardje3121f32006-01-27 21:23:23 +00001394 );
sewardje66f2e02006-12-30 17:45:08 +00001395 VG_(message)(
1396 Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +00001397 "Page sizes: currently %d, max supported %d\n",
sewardje66f2e02006-12-30 17:45:08 +00001398 (Int)VKI_PAGE_SIZE, (Int)VKI_MAX_PAGE_SIZE
1399 );
sewardj738856f2009-07-15 14:48:32 +00001400 VG_(message)(Vg_DebugMsg,
1401 "Valgrind library directory: %s\n", VG_(libdir));
sewardjde4a1d02002-03-22 01:27:54 +00001402 }
nethercotef6a1d502004-08-09 12:21:57 +00001403}
1404
sewardjde4a1d02002-03-22 01:27:54 +00001405
nethercote71980f02004-01-24 18:18:54 +00001406/*====================================================================*/
1407/*=== File descriptor setup ===*/
1408/*====================================================================*/
1409
sewardj5f229e22005-09-28 01:36:01 +00001410/* Number of file descriptors that Valgrind tries to reserve for
1411 it's own use - just a small constant. */
1412#define N_RESERVED_FDS (10)
1413
nethercote71980f02004-01-24 18:18:54 +00001414static void setup_file_descriptors(void)
1415{
1416 struct vki_rlimit rl;
sewardj17c11042006-10-15 01:26:40 +00001417 Bool show = False;
nethercote71980f02004-01-24 18:18:54 +00001418
1419 /* Get the current file descriptor limits. */
1420 if (VG_(getrlimit)(VKI_RLIMIT_NOFILE, &rl) < 0) {
1421 rl.rlim_cur = 1024;
1422 rl.rlim_max = 1024;
1423 }
1424
njnf76d27a2009-05-28 01:53:07 +00001425# if defined(VGO_darwin)
1426 /* Darwin lies. It reports file max as RLIM_INFINITY but
1427 silently disallows anything bigger than 10240. */
1428 if (rl.rlim_cur >= 10240 && rl.rlim_max == 0x7fffffffffffffffULL) {
1429 rl.rlim_max = 10240;
1430 }
1431# endif
1432
sewardj17c11042006-10-15 01:26:40 +00001433 if (show)
njn8a7b41b2007-09-23 00:51:24 +00001434 VG_(printf)("fd limits: host, before: cur %lu max %lu\n",
sewardja8ffda62008-07-18 18:23:24 +00001435 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
sewardj17c11042006-10-15 01:26:40 +00001436
nethercote71980f02004-01-24 18:18:54 +00001437 /* Work out where to move the soft limit to. */
njn14319cc2005-03-13 06:26:22 +00001438 if (rl.rlim_cur + N_RESERVED_FDS <= rl.rlim_max) {
1439 rl.rlim_cur = rl.rlim_cur + N_RESERVED_FDS;
nethercote71980f02004-01-24 18:18:54 +00001440 } else {
1441 rl.rlim_cur = rl.rlim_max;
1442 }
1443
1444 /* Reserve some file descriptors for our use. */
njn14319cc2005-03-13 06:26:22 +00001445 VG_(fd_soft_limit) = rl.rlim_cur - N_RESERVED_FDS;
1446 VG_(fd_hard_limit) = rl.rlim_cur - N_RESERVED_FDS;
nethercote71980f02004-01-24 18:18:54 +00001447
1448 /* Update the soft limit. */
1449 VG_(setrlimit)(VKI_RLIMIT_NOFILE, &rl);
1450
sewardj17c11042006-10-15 01:26:40 +00001451 if (show) {
njn8a7b41b2007-09-23 00:51:24 +00001452 VG_(printf)("fd limits: host, after: cur %lu max %lu\n",
sewardja8ffda62008-07-18 18:23:24 +00001453 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
sewardj17c11042006-10-15 01:26:40 +00001454 VG_(printf)("fd limits: guest : cur %u max %u\n",
1455 VG_(fd_soft_limit), VG_(fd_hard_limit));
1456 }
1457
sewardj45f4e7c2005-09-27 19:20:21 +00001458 if (VG_(cl_exec_fd) != -1)
1459 VG_(cl_exec_fd) = VG_(safe_fd)( VG_(cl_exec_fd) );
nethercote71980f02004-01-24 18:18:54 +00001460}
1461
sewardjde4a1d02002-03-22 01:27:54 +00001462
njn2da73352005-06-18 01:35:16 +00001463/*====================================================================*/
nethercote71980f02004-01-24 18:18:54 +00001464/*=== main() ===*/
1465/*====================================================================*/
1466
sewardjfdf91b42005-09-28 00:53:09 +00001467/* When main() is entered, we should be on the following stack, not
1468 the one the kernel gave us. We will run on this stack until
1469 simulation of the root thread is started, at which point a transfer
1470 is made to a dynamically allocated stack. This is for the sake of
1471 uniform overflow detection for all Valgrind threads. This is
1472 marked global even though it isn't, because assembly code below
1473 needs to reference the name. */
1474
1475/*static*/ VgStack VG_(interim_stack);
1476
sewardjf9d2f9b2006-11-17 20:00:57 +00001477/* These are the structures used to hold info for creating the initial
1478 client image.
1479
1480 'iicii' mostly holds important register state present at system
1481 startup (_start_valgrind). valgrind_main() then fills in the rest
1482 of it and passes it to VG_(ii_create_image)(). That produces
1483 'iifii', which is later handed to VG_(ii_finalise_image). */
1484
1485/* In all OS-instantiations, the_iicii has a field .sp_at_startup.
1486 This should get some address inside the stack on which we gained
sewardjfdf91b42005-09-28 00:53:09 +00001487 control (eg, it could be the SP at startup). It doesn't matter
1488 exactly where in the stack it is. This value is passed to the
sewardjf9d2f9b2006-11-17 20:00:57 +00001489 address space manager at startup. On Linux, aspacem then uses it
1490 to identify the initial stack segment and hence the upper end of
1491 the usable address space. */
sewardjfdf91b42005-09-28 00:53:09 +00001492
sewardjf9d2f9b2006-11-17 20:00:57 +00001493static IICreateImageInfo the_iicii;
1494static IIFinaliseImageInfo the_iifii;
1495
sewardjfdf91b42005-09-28 00:53:09 +00001496
sewardj9c606bd2008-09-18 18:12:50 +00001497/* A simple pair structure, used for conveying debuginfo handles to
1498 calls to VG_TRACK(new_mem_startup, ...). */
1499typedef struct { Addr a; ULong ull; } Addr_n_ULong;
1500
1501
sewardj1ae3f3a2005-09-28 10:47:38 +00001502/* --- Forwards decls to do with shutdown --- */
1503
1504static void final_tidyup(ThreadId tid);
1505
1506/* Do everything which needs doing when the last thread exits */
1507static
1508void shutdown_actions_NORETURN( ThreadId tid,
1509 VgSchedReturnCode tids_schedretcode );
1510
1511/* --- end of Forwards decls to do with shutdown --- */
sewardjfdf91b42005-09-28 00:53:09 +00001512
1513
sewardjf9d2f9b2006-11-17 20:00:57 +00001514/* By the time we get to valgrind_main, the_iicii should already have
1515 been filled in with any important details as required by whatever
1516 OS we have been built for.
1517*/
sewardj17c11042006-10-15 01:26:40 +00001518static
sewardjf9d2f9b2006-11-17 20:00:57 +00001519Int valgrind_main ( Int argc, HChar **argv, HChar **envp )
nethercote71980f02004-01-24 18:18:54 +00001520{
florian19f91bb2012-11-10 22:29:54 +00001521 const HChar* toolname = "memcheck"; // default to Memcheck
sewardj13247ca2005-12-30 22:52:20 +00001522 Int need_help = 0; // 0 = no, 1 = --help, 2 = --help-debug
sewardjde764e82007-11-09 23:13:22 +00001523 ThreadId tid_main = VG_INVALID_THREADID;
sewardj738856f2009-07-15 14:48:32 +00001524 Bool logging_to_fd = False;
florian19f91bb2012-11-10 22:29:54 +00001525 HChar* xml_fname_unexpanded = NULL;
sewardj45f4e7c2005-09-27 19:20:21 +00001526 Int loglevel, i;
nethercote73b526f2004-10-31 18:48:21 +00001527 struct vki_rlimit zero = { 0, 0 };
sewardj9c606bd2008-09-18 18:12:50 +00001528 XArray* addr2dihandle = NULL;
sewardj17c11042006-10-15 01:26:40 +00001529
nethercote71980f02004-01-24 18:18:54 +00001530 //============================================================
nethercote71980f02004-01-24 18:18:54 +00001531 //
sewardj45f4e7c2005-09-27 19:20:21 +00001532 // Nb: startup is complex. Prerequisites are shown at every step.
nethercote71980f02004-01-24 18:18:54 +00001533 // *** Be very careful when messing with the order ***
sewardj45f4e7c2005-09-27 19:20:21 +00001534 //
1535 // The first order of business is to get debug logging, the address
1536 // space manager and the dynamic memory manager up and running.
1537 // Once that's done, we can relax a bit.
1538 //
nethercote71980f02004-01-24 18:18:54 +00001539 //============================================================
sewardj45f4e7c2005-09-27 19:20:21 +00001540
1541 /* This is needed to make VG_(getenv) usable early. */
florian19f91bb2012-11-10 22:29:54 +00001542 VG_(client_envp) = (HChar**)envp;
nethercote71980f02004-01-24 18:18:54 +00001543
sewardj1cf558c2005-04-25 01:36:56 +00001544 //--------------------------------------------------------------
njnf76d27a2009-05-28 01:53:07 +00001545 // Start up Mach kernel interface, if any
1546 // p: none
1547 //--------------------------------------------------------------
1548# if defined(VGO_darwin)
1549 VG_(mach_init)();
1550# endif
1551
1552 //--------------------------------------------------------------
sewardj1cf558c2005-04-25 01:36:56 +00001553 // Start up the logging mechanism
1554 // p: none
1555 //--------------------------------------------------------------
1556 /* Start the debugging-log system ASAP. First find out how many
njn83df0b62009-02-25 01:01:05 +00001557 "-d"s were specified. This is a pre-scan of the command line. Also
philippee4d78122014-04-20 14:20:37 +00001558 get --profile-heap=yes, --core-redzone-size, --redzone-size
1559 --aspace-minaddr which are needed by the time we start up dynamic
1560 memory management. */
sewardj1cf558c2005-04-25 01:36:56 +00001561 loglevel = 0;
1562 for (i = 1; i < argc; i++) {
philippee4d78122014-04-20 14:20:37 +00001563 const HChar* tmp_str;
njn83df0b62009-02-25 01:01:05 +00001564 if (argv[i][0] != '-') break;
1565 if VG_STREQ(argv[i], "--") break;
1566 if VG_STREQ(argv[i], "-d") loglevel++;
1567 if VG_BOOL_CLO(argv[i], "--profile-heap", VG_(clo_profile_heap)) {}
philipped99c26a2012-07-31 22:17:28 +00001568 if VG_BINT_CLO(argv[i], "--core-redzone-size", VG_(clo_core_redzone_size),
1569 0, MAX_CLO_REDZONE_SZB) {}
1570 if VG_BINT_CLO(argv[i], "--redzone-size", VG_(clo_redzone_size),
1571 0, MAX_CLO_REDZONE_SZB) {}
philippee4d78122014-04-20 14:20:37 +00001572 if VG_STR_CLO(argv[i], "--aspace-minaddr", tmp_str) {
1573# if VG_WORDSIZE == 4
1574 const Addr max = (Addr) 0x40000000; // 1Gb
1575# else
1576 const Addr max = (Addr) 0x200000000; // 8Gb
1577# endif
1578 Bool ok = VG_(parse_Addr) (&tmp_str, &VG_(clo_aspacem_minAddr));
1579 if (!ok)
1580 VG_(fmsg_bad_option)(argv[i], "Invalid address\n");
1581
1582 if (!VG_IS_PAGE_ALIGNED(VG_(clo_aspacem_minAddr))
1583 || VG_(clo_aspacem_minAddr) < (Addr) 0x1000
1584 || VG_(clo_aspacem_minAddr) > max) // 1Gb
1585 VG_(fmsg_bad_option)(argv[i],
1586 "Must be a page aligned address between "
1587 "0x1000 and 0x%lx\n", max);
1588 }
sewardj1cf558c2005-04-25 01:36:56 +00001589 }
1590
1591 /* ... and start the debug logger. Now we can safely emit logging
1592 messages all through startup. */
sewardj10759312005-05-30 23:52:47 +00001593 VG_(debugLog_startup)(loglevel, "Stage 2 (main)");
sewardj45f4e7c2005-09-27 19:20:21 +00001594 VG_(debugLog)(1, "main", "Welcome to Valgrind version "
1595 VERSION " debug logging\n");
1596
1597 //--------------------------------------------------------------
1598 // Ensure we're on a plausible stack.
1599 // p: logging
1600 //--------------------------------------------------------------
1601 VG_(debugLog)(1, "main", "Checking current stack is plausible\n");
sewardjfdf91b42005-09-28 00:53:09 +00001602 { HChar* limLo = (HChar*)(&VG_(interim_stack).bytes[0]);
1603 HChar* limHi = limLo + sizeof(VG_(interim_stack));
sewardjed8b0f62012-09-02 21:17:36 +00001604 HChar* volatile
1605 aLocal = (HChar*)&limLo; /* any auto local will do */
1606 /* Re "volatile": Apple clang version 4.0
1607 (tags/Apple/clang-421.0.57) (based on LLVM 3.1svn)" appeared
1608 to miscompile the following check, causing run to abort at
1609 this point (in 64-bit mode) even though aLocal is within limLo
1610 .. limHi. But in fact clang is within its rights to do
1611 strange things here. "The reason is that the comparisons
1612 aLocal < limLo and aLocal >= limHi cause undefined behaviour
1613 (according to c99 6.5.8) because they compare pointers that do
1614 not point into the same aggregate." Adding "volatile" appears
1615 to fix it because "The compiler would have to prove that there
1616 is undefined behavior in order to exploit it. But as a
1617 volatile variable can change its value in ways invisible to
1618 the compiler, the compiler must make the conservative
1619 assumption that it points into the same aggregate as the other
1620 pointer its compared against. I.e. the behaviour is possibly
1621 defined." (Analysis by Florian Krohm). */
sewardj45f4e7c2005-09-27 19:20:21 +00001622 if (aLocal < limLo || aLocal >= limHi) {
1623 /* something's wrong. Stop. */
1624 VG_(debugLog)(0, "main", "Root stack %p to %p, a local %p\n",
1625 limLo, limHi, aLocal );
1626 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1627 "Initial stack switched failed.\n");
1628 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1629 VG_(exit)(1);
1630 }
1631 }
1632
1633 //--------------------------------------------------------------
1634 // Ensure we have a plausible pointer to the stack on which
1635 // we gained control (not the current stack!)
1636 // p: logging
1637 //--------------------------------------------------------------
1638 VG_(debugLog)(1, "main", "Checking initial stack was noted\n");
sewardjf9d2f9b2006-11-17 20:00:57 +00001639 if (the_iicii.sp_at_startup == 0) {
sewardj45f4e7c2005-09-27 19:20:21 +00001640 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1641 "Initial stack was not noted.\n");
1642 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1643 VG_(exit)(1);
1644 }
1645
1646 //--------------------------------------------------------------
1647 // Start up the address space manager, and determine the
1648 // approximate location of the client's stack
njnea2d6fd2010-07-01 00:20:20 +00001649 // p: logging, plausible-stack
sewardj45f4e7c2005-09-27 19:20:21 +00001650 //--------------------------------------------------------------
1651 VG_(debugLog)(1, "main", "Starting the address space manager\n");
sewardj5db15402012-06-07 09:13:21 +00001652 vg_assert(VKI_PAGE_SIZE == 4096 || VKI_PAGE_SIZE == 65536
1653 || VKI_PAGE_SIZE == 16384);
1654 vg_assert(VKI_MAX_PAGE_SIZE == 4096 || VKI_MAX_PAGE_SIZE == 65536
1655 || VKI_MAX_PAGE_SIZE == 16384);
sewardje66f2e02006-12-30 17:45:08 +00001656 vg_assert(VKI_PAGE_SIZE <= VKI_MAX_PAGE_SIZE);
1657 vg_assert(VKI_PAGE_SIZE == (1 << VKI_PAGE_SHIFT));
1658 vg_assert(VKI_MAX_PAGE_SIZE == (1 << VKI_MAX_PAGE_SHIFT));
philippe38a74d22014-08-29 22:53:19 +00001659 the_iicii.clstack_end = VG_(am_startup)( the_iicii.sp_at_startup );
sewardj45f4e7c2005-09-27 19:20:21 +00001660 VG_(debugLog)(1, "main", "Address space manager is running\n");
1661
1662 //--------------------------------------------------------------
1663 // Start up the dynamic memory manager
1664 // p: address space management
philipped99c26a2012-07-31 22:17:28 +00001665 // p: getting --profile-heap,--core-redzone-size,--redzone-size
sewardj45f4e7c2005-09-27 19:20:21 +00001666 // In fact m_mallocfree is self-initialising, so there's no
1667 // initialisation call to do. Instead, try a simple malloc/
1668 // free pair right now to check that nothing is broken.
1669 //--------------------------------------------------------------
1670 VG_(debugLog)(1, "main", "Starting the dynamic memory manager\n");
sewardj9c606bd2008-09-18 18:12:50 +00001671 { void* p = VG_(malloc)( "main.vm.1", 12345 );
sewardj45f4e7c2005-09-27 19:20:21 +00001672 if (p) VG_(free)( p );
1673 }
1674 VG_(debugLog)(1, "main", "Dynamic memory manager is running\n");
sewardj1cf558c2005-04-25 01:36:56 +00001675
nethercotef4928da2004-06-15 10:54:40 +00001676 //============================================================
sewardj45f4e7c2005-09-27 19:20:21 +00001677 //
1678 // Dynamic memory management is now available.
1679 //
nethercotef4928da2004-06-15 10:54:40 +00001680 //============================================================
1681
sewardj45f4e7c2005-09-27 19:20:21 +00001682 //--------------------------------------------------------------
sewardjf98e1c02008-10-25 16:22:41 +00001683 // Initialise m_debuginfo
1684 // p: dynamic memory allocation
1685 VG_(debugLog)(1, "main", "Initialise m_debuginfo\n");
1686 VG_(di_initialise)();
1687
1688 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001689 // Look for alternative libdir
1690 { HChar *cp = VG_(getenv)(VALGRIND_LIB);
1691 if (cp != NULL)
1692 VG_(libdir) = cp;
njncde90d32009-07-22 22:41:38 +00001693 VG_(debugLog)(1, "main", "VG_(libdir) = %s\n", VG_(libdir));
sewardj45f4e7c2005-09-27 19:20:21 +00001694 }
1695
1696 //--------------------------------------------------------------
1697 // Extract the launcher name from the environment.
njna842d792009-05-21 01:15:18 +00001698 VG_(debugLog)(1, "main", "Getting launcher's name ...\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001699 VG_(name_of_launcher) = VG_(getenv)(VALGRIND_LAUNCHER);
1700 if (VG_(name_of_launcher) == NULL) {
1701 VG_(printf)("valgrind: You cannot run '%s' directly.\n", argv[0]);
1702 VG_(printf)("valgrind: You should use $prefix/bin/valgrind.\n");
1703 VG_(exit)(1);
1704 }
njna842d792009-05-21 01:15:18 +00001705 VG_(debugLog)(1, "main", "... %s\n", VG_(name_of_launcher));
sewardj45f4e7c2005-09-27 19:20:21 +00001706
1707 //--------------------------------------------------------------
fitzhardingeb50068f2004-02-24 23:42:55 +00001708 // Get the current process datasize rlimit, and set it to zero.
1709 // This prevents any internal uses of brk() from having any effect.
1710 // We remember the old value so we can restore it on exec, so that
1711 // child processes will have a reasonable brk value.
1712 VG_(getrlimit)(VKI_RLIMIT_DATA, &VG_(client_rlimit_data));
1713 zero.rlim_max = VG_(client_rlimit_data).rlim_max;
1714 VG_(setrlimit)(VKI_RLIMIT_DATA, &zero);
thughesc37184f2004-09-11 14:16:57 +00001715
1716 // Get the current process stack rlimit.
1717 VG_(getrlimit)(VKI_RLIMIT_STACK, &VG_(client_rlimit_stack));
1718
sewardje2d1e672005-11-12 23:10:48 +00001719 //--------------------------------------------------------------
1720 // Figure out what sort of CPU we're on, and whether it is
1721 // able to run V.
1722 VG_(debugLog)(1, "main", "Get hardware capabilities ...\n");
1723 { VexArch vex_arch;
1724 VexArchInfo vex_archinfo;
1725 Bool ok = VG_(machine_get_hwcaps)();
1726 if (!ok) {
1727 VG_(printf)("\n");
1728 VG_(printf)("valgrind: fatal error: unsupported CPU.\n");
1729 VG_(printf)(" Supported CPUs are:\n");
1730 VG_(printf)(" * x86 (practically any; Pentium-I or above), "
1731 "AMD Athlon or above)\n");
1732 VG_(printf)(" * AMD Athlon64/Opteron\n");
philippe3bcd51d2013-06-12 21:45:39 +00001733 VG_(printf)(" * ARM (armv7)\n");
sewardje2d1e672005-11-12 23:10:48 +00001734 VG_(printf)(" * PowerPC (most; ppc405 and above)\n");
sewardjb5b87402011-03-07 16:05:35 +00001735 VG_(printf)(" * System z (64bit only - s390x; z900 and above)\n");
sewardje2d1e672005-11-12 23:10:48 +00001736 VG_(printf)("\n");
1737 VG_(exit)(1);
1738 }
1739 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
sewardje3121f32006-01-27 21:23:23 +00001740 VG_(debugLog)(
1741 1, "main", "... arch = %s, hwcaps = %s\n",
1742 LibVEX_ppVexArch ( vex_arch ),
1743 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1744 );
sewardje2d1e672005-11-12 23:10:48 +00001745 }
1746
sewardj198f34f2007-07-09 23:13:07 +00001747 //--------------------------------------------------------------
1748 // Record the working directory at startup
sewardj6e9de462011-06-28 07:25:29 +00001749 // p: none
sewardj198f34f2007-07-09 23:13:07 +00001750 VG_(debugLog)(1, "main", "Getting the working directory at startup\n");
1751 { Bool ok = VG_(record_startup_wd)();
1752 if (!ok)
1753 VG_(err_config_error)( "Can't establish current working "
florian1763e812011-07-12 19:07:05 +00001754 "directory at startup\n");
sewardj198f34f2007-07-09 23:13:07 +00001755 }
florian19f91bb2012-11-10 22:29:54 +00001756 { HChar buf[VKI_PATH_MAX+1];
sewardj198f34f2007-07-09 23:13:07 +00001757 Bool ok = VG_(get_startup_wd)( buf, sizeof(buf) );
1758 vg_assert(ok);
1759 buf[VKI_PATH_MAX] = 0;
1760 VG_(debugLog)(1, "main", "... %s\n", buf );
1761 }
1762
sewardj45f4e7c2005-09-27 19:20:21 +00001763 //============================================================
1764 // Command line argument handling order:
1765 // * If --help/--help-debug are present, show usage message
1766 // (including the tool-specific usage)
1767 // * (If no --tool option given, default to Memcheck)
1768 // * Then, if client is missing, abort with error msg
1769 // * Then, if any cmdline args are bad, abort with error msg
1770 //============================================================
1771
1772 //--------------------------------------------------------------
1773 // Split up argv into: C args, V args, V extra args, and exename.
1774 // p: dynamic memory allocation
1775 //--------------------------------------------------------------
1776 VG_(debugLog)(1, "main", "Split up command line\n");
1777 VG_(split_up_argv)( argc, argv );
sewardj14c7cc52007-02-25 15:08:24 +00001778 vg_assert( VG_(args_for_valgrind) );
1779 vg_assert( VG_(args_for_client) );
sewardj45f4e7c2005-09-27 19:20:21 +00001780 if (0) {
sewardj14c7cc52007-02-25 15:08:24 +00001781 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++)
1782 VG_(printf)(
1783 "varg %s\n",
1784 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1785 );
sewardj45f4e7c2005-09-27 19:20:21 +00001786 VG_(printf)(" exe %s\n", VG_(args_the_exename));
sewardj14c7cc52007-02-25 15:08:24 +00001787 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++)
1788 VG_(printf)(
1789 "carg %s\n",
1790 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1791 );
nethercote71980f02004-01-24 18:18:54 +00001792 }
1793
1794 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001795 // Extract tool name and whether help has been requested.
1796 // Note we can't print the help message yet, even if requested,
1797 // because the tool has not been initialised.
1798 // p: split_up_argv [for VG_(args_for_valgrind)]
nethercote71980f02004-01-24 18:18:54 +00001799 //--------------------------------------------------------------
sewardj95d86c02007-12-18 01:49:23 +00001800 VG_(debugLog)(1, "main",
1801 "(early_) Process Valgrind's command line options\n");
1802 early_process_cmd_line_options(&need_help, &toolname);
nethercote71980f02004-01-24 18:18:54 +00001803
sewardj45f4e7c2005-09-27 19:20:21 +00001804 // Set default vex control params
1805 LibVEX_default_VexControl(& VG_(clo_vex_control));
nethercote71980f02004-01-24 18:18:54 +00001806
1807 //--------------------------------------------------------------
1808 // Load client executable, finding in $PATH if necessary
njn83df0b62009-02-25 01:01:05 +00001809 // p: early_process_cmd_line_options() [for 'exec', 'need_help',
1810 // clo_max_stackframe,
1811 // clo_main_stacksize]
sewardj95d86c02007-12-18 01:49:23 +00001812 // p: layout_remaining_space [so there's space]
sewardj17c11042006-10-15 01:26:40 +00001813 //
nethercote71980f02004-01-24 18:18:54 +00001814 // Set up client's environment
sewardj95d86c02007-12-18 01:49:23 +00001815 // p: set-libdir [for VG_(libdir)]
1816 // p: early_process_cmd_line_options [for toolname]
sewardj17c11042006-10-15 01:26:40 +00001817 //
nethercote5ee67ca2004-06-22 14:00:09 +00001818 // Setup client stack, eip, and VG_(client_arg[cv])
nethercote71980f02004-01-24 18:18:54 +00001819 // p: load_client() [for 'info']
1820 // p: fix_environment() [for 'env']
sewardj17c11042006-10-15 01:26:40 +00001821 //
sewardj45f4e7c2005-09-27 19:20:21 +00001822 // Setup client data (brk) segment. Initially a 1-page segment
1823 // which abuts a shrinkable reservation.
1824 // p: load_client() [for 'info' and hence VG_(brk_base)]
sewardjf9d2f9b2006-11-17 20:00:57 +00001825 //
1826 // p: _start_in_C (for zeroing out the_iicii and putting some
1827 // initial values into it)
sewardj45f4e7c2005-09-27 19:20:21 +00001828 //--------------------------------------------------------------
sewardj17c11042006-10-15 01:26:40 +00001829 if (!need_help) {
sewardjf9d2f9b2006-11-17 20:00:57 +00001830 VG_(debugLog)(1, "main", "Create initial image\n");
1831
njnf76d27a2009-05-28 01:53:07 +00001832# if defined(VGO_linux) || defined(VGO_darwin)
sewardjf9d2f9b2006-11-17 20:00:57 +00001833 the_iicii.argv = argv;
1834 the_iicii.envp = envp;
1835 the_iicii.toolname = toolname;
sewardjf9d2f9b2006-11-17 20:00:57 +00001836# else
njna842d792009-05-21 01:15:18 +00001837# error "Unknown platform"
sewardjf9d2f9b2006-11-17 20:00:57 +00001838# endif
1839
sewardjdc2f79e2007-12-22 14:14:04 +00001840 /* NOTE: this call reads VG_(clo_main_stacksize). */
sewardjf9d2f9b2006-11-17 20:00:57 +00001841 the_iifii = VG_(ii_create_image)( the_iicii );
sewardj45f4e7c2005-09-27 19:20:21 +00001842 }
nethercote71980f02004-01-24 18:18:54 +00001843
1844 //==============================================================
sewardj45f4e7c2005-09-27 19:20:21 +00001845 //
1846 // Finished loading/setting up the client address space.
1847 //
nethercote71980f02004-01-24 18:18:54 +00001848 //==============================================================
1849
1850 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00001851 // setup file descriptors
1852 // p: n/a
1853 //--------------------------------------------------------------
sewardj1fbc1a52005-04-25 02:05:54 +00001854 VG_(debugLog)(1, "main", "Setup file descriptors\n");
nethercote71980f02004-01-24 18:18:54 +00001855 setup_file_descriptors();
1856
1857 //--------------------------------------------------------------
tom41ad7e72012-10-04 20:27:38 +00001858 // create fake /proc/<pid>/cmdline and /proc/<pid>/auxv files
1859 // and then unlink them, but hold onto the fds, so we can handr
1860 // them out to the client when it tries to open
1861 // /proc/<pid>/cmdline or /proc/<pid>/auxv for itself.
sewardj45f4e7c2005-09-27 19:20:21 +00001862 // p: setup file descriptors
tom41ad7e72012-10-04 20:27:38 +00001863 // p: ii_create_image for VG_(client_auxv) setup.
nethercotec314eba2004-07-15 12:59:41 +00001864 //--------------------------------------------------------------
bart9b533f82009-08-25 20:15:41 +00001865#if !defined(VGO_linux)
1866 // client shouldn't be using /proc!
1867 VG_(cl_cmdline_fd) = -1;
tom41ad7e72012-10-04 20:27:38 +00001868 VG_(cl_auxv_fd) = -1;
bart9b533f82009-08-25 20:15:41 +00001869#else
1870 if (!need_help) {
philippecc648262013-05-26 21:09:20 +00001871 HChar buf[50], buf2[VG_(mkstemp_fullname_bufsz)(50-1)];
bart9b533f82009-08-25 20:15:41 +00001872 HChar nul[1];
1873 Int fd, r;
barta3054f52010-06-14 18:12:56 +00001874 const HChar* exename;
nethercotec314eba2004-07-15 12:59:41 +00001875
bart9b533f82009-08-25 20:15:41 +00001876 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/cmdline\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001877
bart9b533f82009-08-25 20:15:41 +00001878 VG_(sprintf)(buf, "proc_%d_cmdline", VG_(getpid)());
1879 fd = VG_(mkstemp)( buf, buf2 );
1880 if (fd == -1)
florian1763e812011-07-12 19:07:05 +00001881 VG_(err_config_error)("Can't create client cmdline file in %s\n", buf2);
sewardj45f4e7c2005-09-27 19:20:21 +00001882
bart9b533f82009-08-25 20:15:41 +00001883 nul[0] = 0;
florianb16609b2014-08-20 21:04:14 +00001884 exename = VG_(args_the_exename);
sewardjc7ffc942011-03-28 16:26:42 +00001885 VG_(write)(fd, exename, VG_(strlen)( exename ));
bart9b533f82009-08-25 20:15:41 +00001886 VG_(write)(fd, nul, 1);
1887
1888 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1889 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i );
1890 VG_(write)(fd, arg, VG_(strlen)( arg ));
sewardj45f4e7c2005-09-27 19:20:21 +00001891 VG_(write)(fd, nul, 1);
1892 }
bart9b533f82009-08-25 20:15:41 +00001893
1894 /* Don't bother to seek the file back to the start; instead do
1895 it every time a copy of it is given out (by PRE(sys_open)).
1896 That is probably more robust across fork() etc. */
1897
1898 /* Now delete it, but hang on to the fd. */
1899 r = VG_(unlink)( buf2 );
1900 if (r)
florian1763e812011-07-12 19:07:05 +00001901 VG_(err_config_error)("Can't delete client cmdline file in %s\n", buf2);
bart9b533f82009-08-25 20:15:41 +00001902
1903 VG_(cl_cmdline_fd) = fd;
tom41ad7e72012-10-04 20:27:38 +00001904
1905 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/auxv\n");
1906
1907 VG_(sprintf)(buf, "proc_%d_auxv", VG_(getpid)());
1908 fd = VG_(mkstemp)( buf, buf2 );
1909 if (fd == -1)
1910 VG_(err_config_error)("Can't create client auxv file in %s\n", buf2);
1911
1912 UWord *client_auxv = VG_(client_auxv);
1913 unsigned int client_auxv_len = 0;
1914 while (*client_auxv != 0) {
1915 client_auxv++;
1916 client_auxv++;
1917 client_auxv_len += 2 * sizeof(UWord);
1918 }
1919 client_auxv_len += 2 * sizeof(UWord);
1920
1921 VG_(write)(fd, VG_(client_auxv), client_auxv_len);
1922
1923 /* Don't bother to seek the file back to the start; instead do
1924 it every time a copy of it is given out (by PRE(sys_open)).
1925 That is probably more robust across fork() etc. */
1926
1927 /* Now delete it, but hang on to the fd. */
1928 r = VG_(unlink)( buf2 );
1929 if (r)
1930 VG_(err_config_error)("Can't delete client auxv file in %s\n", buf2);
1931
1932 VG_(cl_auxv_fd) = fd;
sewardj45f4e7c2005-09-27 19:20:21 +00001933 }
bart9b533f82009-08-25 20:15:41 +00001934#endif
nethercotec314eba2004-07-15 12:59:41 +00001935
1936 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001937 // Init tool part 1: pre_clo_init
nethercotec314eba2004-07-15 12:59:41 +00001938 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
nethercotec314eba2004-07-15 12:59:41 +00001939 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
nethercote71980f02004-01-24 18:18:54 +00001940 //--------------------------------------------------------------
sewardj7cf4e6b2008-05-01 20:24:26 +00001941 VG_(debugLog)(1, "main", "Initialise the tool part 1 (pre_clo_init)\n");
njn08ce7b32009-02-27 03:38:28 +00001942 VG_(tl_pre_clo_init)();
philippea0a73932014-06-15 15:42:20 +00001943 // Activate var info readers, if the tool asked for it:
1944 if (VG_(needs).var_info)
1945 VG_(clo_read_var_info) = True;
nethercote71980f02004-01-24 18:18:54 +00001946
sewardj45f4e7c2005-09-27 19:20:21 +00001947 //--------------------------------------------------------------
nethercotef4928da2004-06-15 10:54:40 +00001948 // If --tool and --help/--help-debug was given, now give the core+tool
1949 // help message
sewardj95d86c02007-12-18 01:49:23 +00001950 // p: early_process_cmd_line_options() [for 'need_help']
1951 // p: tl_pre_clo_init [for 'VG_(tdict).usage']
sewardj45f4e7c2005-09-27 19:20:21 +00001952 //--------------------------------------------------------------
1953 VG_(debugLog)(1, "main", "Print help and quit, if requested\n");
nethercotef4928da2004-06-15 10:54:40 +00001954 if (need_help) {
njncce38e62010-07-06 04:25:12 +00001955 usage_NORETURN(/*--help-debug?*/need_help >= 2);
nethercotef4928da2004-06-15 10:54:40 +00001956 }
nethercotec314eba2004-07-15 12:59:41 +00001957
sewardj45f4e7c2005-09-27 19:20:21 +00001958 //--------------------------------------------------------------
1959 // Process command line options to Valgrind + tool
1960 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1961 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1962 //--------------------------------------------------------------
sewardj95d86c02007-12-18 01:49:23 +00001963 VG_(debugLog)(1, "main",
1964 "(main_) Process Valgrind's command line options, "
1965 "setup logging\n");
sewardj738856f2009-07-15 14:48:32 +00001966 main_process_cmd_line_options ( &logging_to_fd, &xml_fname_unexpanded,
1967 toolname );
sewardj45f4e7c2005-09-27 19:20:21 +00001968
1969 //--------------------------------------------------------------
sewardj592ae092005-11-08 19:01:44 +00001970 // Zeroise the millisecond counter by doing a first read of it.
1971 // p: none
1972 //--------------------------------------------------------------
1973 (void) VG_(read_millisecond_timer)();
1974
1975 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001976 // Print the preamble
1977 // p: tl_pre_clo_init [for 'VG_(details).name' and friends]
sewardj738856f2009-07-15 14:48:32 +00001978 // p: main_process_cmd_line_options()
1979 // [for VG_(clo_verbosity), VG_(clo_xml),
1980 // logging_to_fd, xml_fname_unexpanded]
sewardj45f4e7c2005-09-27 19:20:21 +00001981 //--------------------------------------------------------------
1982 VG_(debugLog)(1, "main", "Print the preamble...\n");
sewardj738856f2009-07-15 14:48:32 +00001983 print_preamble(logging_to_fd, xml_fname_unexpanded, toolname);
sewardj45f4e7c2005-09-27 19:20:21 +00001984 VG_(debugLog)(1, "main", "...finished the preamble\n");
1985
1986 //--------------------------------------------------------------
1987 // Init tool part 2: post_clo_init
1988 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1989 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1990 // p: print_preamble() [so any warnings printed in post_clo_init
1991 // are shown after the preamble]
1992 //--------------------------------------------------------------
1993 VG_(debugLog)(1, "main", "Initialise the tool part 2 (post_clo_init)\n");
njn51d827b2005-05-09 01:02:08 +00001994 VG_TDICT_CALL(tool_post_clo_init);
sewardj7cf4e6b2008-05-01 20:24:26 +00001995 {
1996 /* The tool's "needs" will by now be finalised, since it has no
1997 further opportunity to specify them. So now sanity check
1998 them. */
floriane6a4ed12012-10-21 02:30:18 +00001999 const HChar* s;
sewardj7cf4e6b2008-05-01 20:24:26 +00002000 Bool ok;
2001 ok = VG_(sanity_check_needs)( &s );
2002 if (!ok) {
2003 VG_(tool_panic)(s);
2004 }
2005 }
nethercotef4928da2004-06-15 10:54:40 +00002006
2007 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00002008 // Initialise translation table and translation cache
2009 // p: aspacem [??]
2010 // p: tl_pre_clo_init [for 'VG_(details).avg_translation_sizeB']
nethercote71980f02004-01-24 18:18:54 +00002011 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00002012 VG_(debugLog)(1, "main", "Initialise TT/TC\n");
2013 VG_(init_tt_tc)();
sewardjb5f6f512005-03-10 23:59:00 +00002014
sewardj45f4e7c2005-09-27 19:20:21 +00002015 //--------------------------------------------------------------
2016 // Initialise the redirect table.
2017 // p: init_tt_tc [so it can call VG_(search_transtab) safely]
2018 // p: aspacem [so can change ownership of sysinfo pages]
2019 //--------------------------------------------------------------
2020 VG_(debugLog)(1, "main", "Initialise redirects\n");
sewardj0ec07f32006-01-12 12:32:32 +00002021 VG_(redir_initialise)();
nethercote71980f02004-01-24 18:18:54 +00002022
2023 //--------------------------------------------------------------
2024 // Allow GDB attach
sewardj95d86c02007-12-18 01:49:23 +00002025 // p: main_process_cmd_line_options() [for VG_(clo_wait_for_gdb)]
nethercote71980f02004-01-24 18:18:54 +00002026 //--------------------------------------------------------------
2027 /* Hook to delay things long enough so we can get the pid and
2028 attach GDB in another shell. */
2029 if (VG_(clo_wait_for_gdb)) {
sewardj87cd71c2011-07-05 09:13:41 +00002030 ULong iters, q;
sewardj1fbc1a52005-04-25 02:05:54 +00002031 VG_(debugLog)(1, "main", "Wait for GDB\n");
sewardj93ab8572005-02-06 14:10:40 +00002032 VG_(printf)("pid=%d, entering delay loop\n", VG_(getpid)());
sewardj8211a572005-06-23 21:37:47 +00002033
2034# if defined(VGP_x86_linux)
sewardj291849f2012-04-20 23:58:55 +00002035 iters = 10;
carllcae0cc22014-08-07 23:17:29 +00002036# elif defined(VGP_amd64_linux) || defined(VGP_ppc64be_linux) \
2037 || defined(VGP_ppc64le_linux)
sewardj8211a572005-06-23 21:37:47 +00002038 iters = 10;
2039# elif defined(VGP_ppc32_linux)
sewardjd714d2e2005-07-08 18:24:04 +00002040 iters = 5;
sewardj59570ff2010-01-01 11:59:33 +00002041# elif defined(VGP_arm_linux)
sewardj291849f2012-04-20 23:58:55 +00002042 iters = 5;
sewardjf0c12502014-01-12 12:54:00 +00002043# elif defined(VGP_arm64_linux)
2044 iters = 5;
sewardjb5b87402011-03-07 16:05:35 +00002045# elif defined(VGP_s390x_linux)
2046 iters = 10;
petarj4df0bfc2013-02-27 23:17:33 +00002047# elif defined(VGP_mips32_linux) || defined(VGP_mips64_linux)
sewardj5db15402012-06-07 09:13:21 +00002048 iters = 10;
njnf76d27a2009-05-28 01:53:07 +00002049# elif defined(VGO_darwin)
2050 iters = 3;
sewardj8211a572005-06-23 21:37:47 +00002051# else
sewardj17c11042006-10-15 01:26:40 +00002052# error "Unknown plat"
sewardj8211a572005-06-23 21:37:47 +00002053# endif
2054
sewardj87cd71c2011-07-05 09:13:41 +00002055 iters *= 1000ULL * 1000 * 1000;
sewardj8211a572005-06-23 21:37:47 +00002056 for (q = 0; q < iters; q++)
sewardj87cd71c2011-07-05 09:13:41 +00002057 __asm__ __volatile__("" ::: "memory","cc");
nethercote71980f02004-01-24 18:18:54 +00002058 }
2059
sewardjb5d320c2005-03-13 18:57:15 +00002060 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00002061 // Search for file descriptors that are inherited from our parent
sewardj95d86c02007-12-18 01:49:23 +00002062 // p: main_process_cmd_line_options [for VG_(clo_track_fds)]
nethercote71980f02004-01-24 18:18:54 +00002063 //--------------------------------------------------------------
sewardj1fbc1a52005-04-25 02:05:54 +00002064 if (VG_(clo_track_fds)) {
2065 VG_(debugLog)(1, "main", "Init preopened fds\n");
nethercote71980f02004-01-24 18:18:54 +00002066 VG_(init_preopened_fds)();
sewardj1fbc1a52005-04-25 02:05:54 +00002067 }
nethercote71980f02004-01-24 18:18:54 +00002068
2069 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00002070 // Load debug info for the existing segments.
2071 // p: setup_code_redirect_table [so that redirs can be recorded]
2072 // p: mallocfree
2073 // p: probably: setup fds and process CLOs, so that logging works
sewardjf98e1c02008-10-25 16:22:41 +00002074 // p: initialise m_debuginfo
sewardj9c606bd2008-09-18 18:12:50 +00002075 //
2076 // While doing this, make a note of the debuginfo-handles that
sewardj6e9de462011-06-28 07:25:29 +00002077 // come back from VG_(di_notify_mmap).
sewardj9c606bd2008-09-18 18:12:50 +00002078 // Later, in "Tell the tool about the initial client memory permissions"
2079 // (just below) we can then hand these handles off to the tool in
2080 // calls to VG_TRACK(new_mem_startup, ...). This gives the tool the
2081 // opportunity to make further queries to m_debuginfo before the
2082 // client is started, if it wants. We put this information into an
2083 // XArray, each handle along with the associated segment start address,
2084 // and search the XArray for the handles later, when calling
2085 // VG_TRACK(new_mem_startup, ...).
sewardj45f4e7c2005-09-27 19:20:21 +00002086 //--------------------------------------------------------------
2087 VG_(debugLog)(1, "main", "Load initial debug info\n");
sewardj9c606bd2008-09-18 18:12:50 +00002088
2089 tl_assert(!addr2dihandle);
2090 addr2dihandle = VG_(newXA)( VG_(malloc), "main.vm.2",
2091 VG_(free), sizeof(Addr_n_ULong) );
2092 tl_assert(addr2dihandle);
2093
sewardj17c11042006-10-15 01:26:40 +00002094# if defined(VGO_linux)
sewardj45f4e7c2005-09-27 19:20:21 +00002095 { Addr* seg_starts;
2096 Int n_seg_starts;
sewardj9c606bd2008-09-18 18:12:50 +00002097 Addr_n_ULong anu;
sewardj45f4e7c2005-09-27 19:20:21 +00002098
njnac1e0332009-05-08 00:39:31 +00002099 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
sewardj17c11042006-10-15 01:26:40 +00002100 vg_assert(seg_starts && n_seg_starts >= 0);
sewardj45f4e7c2005-09-27 19:20:21 +00002101
sewardjf72cced2005-11-08 00:45:47 +00002102 /* show them all to the debug info reader. allow_SkFileV has to
2103 be True here so that we read info from the valgrind executable
2104 itself. */
sewardj9c606bd2008-09-18 18:12:50 +00002105 for (i = 0; i < n_seg_starts; i++) {
sewardj5f2dcad2011-10-24 08:53:03 +00002106 anu.ull = VG_(di_notify_mmap)( seg_starts[i], True/*allow_SkFileV*/,
2107 -1/*Don't use_fd*/);
sewardj9c606bd2008-09-18 18:12:50 +00002108 /* anu.ull holds the debuginfo handle returned by di_notify_mmap,
2109 if any. */
2110 if (anu.ull > 0) {
2111 anu.a = seg_starts[i];
2112 VG_(addToXA)( addr2dihandle, &anu );
2113 }
2114 }
sewardj45f4e7c2005-09-27 19:20:21 +00002115
2116 VG_(free)( seg_starts );
2117 }
njnf76d27a2009-05-28 01:53:07 +00002118# elif defined(VGO_darwin)
2119 { Addr* seg_starts;
2120 Int n_seg_starts;
2121 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
2122 vg_assert(seg_starts && n_seg_starts >= 0);
2123
2124 /* show them all to the debug info reader.
2125 Don't read from V segments (unlike Linux) */
2126 // GrP fixme really?
sewardj5f2dcad2011-10-24 08:53:03 +00002127 for (i = 0; i < n_seg_starts; i++) {
2128 VG_(di_notify_mmap)( seg_starts[i], False/*don't allow_SkFileV*/,
2129 -1/*don't use_fd*/);
2130 }
njnf76d27a2009-05-28 01:53:07 +00002131
2132 VG_(free)( seg_starts );
2133 }
sewardj17c11042006-10-15 01:26:40 +00002134# else
2135# error Unknown OS
2136# endif
sewardj45f4e7c2005-09-27 19:20:21 +00002137
2138 //--------------------------------------------------------------
2139 // Tell aspacem of ownership change of the asm helpers, so that
2140 // m_translate allows them to be translated. However, only do this
2141 // after the initial debug info read, since making a hole in the
2142 // address range for the stage2 binary confuses the debug info reader.
2143 // p: aspacem
2144 //--------------------------------------------------------------
2145 { Bool change_ownership_v_c_OK;
sewardj1a85f4f2006-01-12 21:15:35 +00002146 Addr co_start = VG_PGROUNDDN( (Addr)&VG_(trampoline_stuff_start) );
2147 Addr co_endPlus = VG_PGROUNDUP( (Addr)&VG_(trampoline_stuff_end) );
sewardj45f4e7c2005-09-27 19:20:21 +00002148 VG_(debugLog)(1,"redir",
2149 "transfer ownership V -> C of 0x%llx .. 0x%llx\n",
2150 (ULong)co_start, (ULong)co_endPlus-1 );
2151
2152 change_ownership_v_c_OK
2153 = VG_(am_change_ownership_v_to_c)( co_start, co_endPlus - co_start );
2154 vg_assert(change_ownership_v_c_OK);
2155 }
2156
bart6c63f5c2011-10-11 18:50:14 +00002157 if (VG_(clo_xml)) {
2158 HChar buf[50];
2159 VG_(elapsed_wallclock_time)(buf);
2160 VG_(printf_xml)( "<status>\n"
2161 " <state>RUNNING</state>\n"
2162 " <time>%pS</time>\n"
2163 "</status>\n",
2164 buf );
2165 VG_(printf_xml)( "\n" );
2166 }
2167
bart27233e92012-03-08 14:59:25 +00002168 VG_(init_Threads)();
2169
sewardj45f4e7c2005-09-27 19:20:21 +00002170 //--------------------------------------------------------------
sewardjde764e82007-11-09 23:13:22 +00002171 // Initialise the scheduler (phase 1) [generates tid_main]
2172 // p: none, afaics
2173 //--------------------------------------------------------------
2174 VG_(debugLog)(1, "main", "Initialise scheduler (phase 1)\n");
2175 tid_main = VG_(scheduler_init_phase1)();
2176 vg_assert(tid_main >= 0 && tid_main < VG_N_THREADS
2177 && tid_main != VG_INVALID_THREADID);
2178 /* Tell the tool about tid_main */
2179 VG_TRACK( pre_thread_ll_create, VG_INVALID_THREADID, tid_main );
2180
2181 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00002182 // Tell the tool about the initial client memory permissions
2183 // p: aspacem
2184 // p: mallocfree
2185 // p: setup_client_stack
2186 // p: setup_client_dataseg
sewardj9c606bd2008-09-18 18:12:50 +00002187 //
2188 // For each segment we tell the client about, look up in
2189 // addr2dihandle as created above, to see if there's a debuginfo
2190 // handle associated with the segment, that we can hand along
2191 // to the tool, to be helpful.
sewardj45f4e7c2005-09-27 19:20:21 +00002192 //--------------------------------------------------------------
2193 VG_(debugLog)(1, "main", "Tell tool about initial permissions\n");
2194 { Addr* seg_starts;
2195 Int n_seg_starts;
sewardj45f4e7c2005-09-27 19:20:21 +00002196
sewardj9c606bd2008-09-18 18:12:50 +00002197 tl_assert(addr2dihandle);
2198
tom7c1a19a2008-01-02 10:13:04 +00002199 /* Mark the main thread as running while we tell the tool about
2200 the client memory so that the tool can associate that memory
2201 with the main thread. */
2202 tl_assert(VG_(running_tid) == VG_INVALID_THREADID);
2203 VG_(running_tid) = tid_main;
2204
njnac1e0332009-05-08 00:39:31 +00002205 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
sewardj17c11042006-10-15 01:26:40 +00002206 vg_assert(seg_starts && n_seg_starts >= 0);
sewardj45f4e7c2005-09-27 19:20:21 +00002207
2208 /* show interesting ones to the tool */
2209 for (i = 0; i < n_seg_starts; i++) {
sewardj9c606bd2008-09-18 18:12:50 +00002210 Word j, n;
sewardj12ab7652006-10-17 02:10:42 +00002211 NSegment const* seg
sewardj17c11042006-10-15 01:26:40 +00002212 = VG_(am_find_nsegment)( seg_starts[i] );
sewardj45f4e7c2005-09-27 19:20:21 +00002213 vg_assert(seg);
2214 if (seg->kind == SkFileC || seg->kind == SkAnonC) {
sewardjc6d86a32009-01-31 15:08:08 +00002215 /* This next assertion is tricky. If it is placed
2216 immediately before this 'if', it very occasionally fails.
2217 Why? Because previous iterations of the loop may have
2218 caused tools (via the new_mem_startup calls) to do
2219 dynamic memory allocation, and that may affect the mapped
2220 segments; in particular it may cause segment merging to
2221 happen. Hence we cannot assume that seg_starts[i], which
2222 reflects the state of the world before we started this
2223 loop, is the same as seg->start, as the latter reflects
2224 the state of the world (viz, mappings) at this particular
2225 iteration of the loop.
2226
2227 Why does moving it inside the 'if' make it safe? Because
2228 any dynamic memory allocation done by the tools will
2229 affect only the state of Valgrind-owned segments, not of
2230 Client-owned segments. And the 'if' guards against that
2231 -- we only get in here for Client-owned segments.
2232
2233 In other words: the loop may change the state of
2234 Valgrind-owned segments as it proceeds. But it should
2235 not cause the Client-owned segments to change. */
2236 vg_assert(seg->start == seg_starts[i]);
sewardj45f4e7c2005-09-27 19:20:21 +00002237 VG_(debugLog)(2, "main",
2238 "tell tool about %010lx-%010lx %c%c%c\n",
2239 seg->start, seg->end,
2240 seg->hasR ? 'r' : '-',
2241 seg->hasW ? 'w' : '-',
2242 seg->hasX ? 'x' : '-' );
sewardj9c606bd2008-09-18 18:12:50 +00002243 /* search addr2dihandle to see if we have an entry
2244 matching seg->start. */
2245 n = VG_(sizeXA)( addr2dihandle );
2246 for (j = 0; j < n; j++) {
2247 Addr_n_ULong* anl = VG_(indexXA)( addr2dihandle, j );
2248 if (anl->a == seg->start) {
2249 tl_assert(anl->ull > 0); /* check it's a valid handle */
2250 break;
2251 }
2252 }
2253 vg_assert(j >= 0 && j <= n);
sewardj45f4e7c2005-09-27 19:20:21 +00002254 VG_TRACK( new_mem_startup, seg->start, seg->end+1-seg->start,
sewardj9c606bd2008-09-18 18:12:50 +00002255 seg->hasR, seg->hasW, seg->hasX,
2256 /* and the retrieved debuginfo handle, if any */
2257 j < n
2258 ? ((Addr_n_ULong*)VG_(indexXA)( addr2dihandle, j ))->ull
2259 : 0 );
sewardj45f4e7c2005-09-27 19:20:21 +00002260 }
2261 }
2262
2263 VG_(free)( seg_starts );
sewardj9c606bd2008-09-18 18:12:50 +00002264 VG_(deleteXA)( addr2dihandle );
sewardj45f4e7c2005-09-27 19:20:21 +00002265
2266 /* Also do the initial stack permissions. */
barte05b3a42010-09-07 16:32:53 +00002267 {
2268 SSizeT inaccessible_len;
2269 NSegment const* seg
sewardjf9d2f9b2006-11-17 20:00:57 +00002270 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
sewardj17c11042006-10-15 01:26:40 +00002271 vg_assert(seg);
2272 vg_assert(seg->kind == SkAnonC);
sewardjf9d2f9b2006-11-17 20:00:57 +00002273 vg_assert(the_iifii.initial_client_SP >= seg->start);
2274 vg_assert(the_iifii.initial_client_SP <= seg->end);
sewardj45f4e7c2005-09-27 19:20:21 +00002275
sewardj17c11042006-10-15 01:26:40 +00002276 /* Stuff below the initial SP is unaddressable. Take into
2277 account any ABI-mandated space below the stack pointer that
2278 is required (VG_STACK_REDZONE_SZB). setup_client_stack()
2279 will have allocated an extra page if a red zone is required,
2280 to be on the safe side. */
barte05b3a42010-09-07 16:32:53 +00002281 inaccessible_len = the_iifii.initial_client_SP - VG_STACK_REDZONE_SZB
2282 - seg->start;
2283 vg_assert(inaccessible_len >= 0);
2284 if (inaccessible_len > 0)
2285 VG_TRACK( die_mem_stack,
2286 seg->start,
2287 inaccessible_len );
sewardj17c11042006-10-15 01:26:40 +00002288 VG_(debugLog)(2, "main", "mark stack inaccessible %010lx-%010lx\n",
2289 seg->start,
sewardjf9d2f9b2006-11-17 20:00:57 +00002290 the_iifii.initial_client_SP-1 - VG_STACK_REDZONE_SZB);
sewardj17c11042006-10-15 01:26:40 +00002291 }
sewardj45f4e7c2005-09-27 19:20:21 +00002292
2293 /* Also the assembly helpers. */
2294 VG_TRACK( new_mem_startup,
2295 (Addr)&VG_(trampoline_stuff_start),
sewardjc6527d62006-02-13 17:54:31 +00002296 (Addr)&VG_(trampoline_stuff_end)
2297 - (Addr)&VG_(trampoline_stuff_start),
sewardj45f4e7c2005-09-27 19:20:21 +00002298 False, /* readable? */
2299 False, /* writable? */
sewardj9c606bd2008-09-18 18:12:50 +00002300 True /* executable? */,
2301 0 /* di_handle: no associated debug info */ );
tom7c1a19a2008-01-02 10:13:04 +00002302
2303 /* Clear the running thread indicator */
2304 VG_(running_tid) = VG_INVALID_THREADID;
2305 tl_assert(VG_(running_tid) == VG_INVALID_THREADID);
sewardj882a9ec2014-07-08 07:44:07 +00002306
2307 /* Darwin only: tell the tools where the client's kernel commpage
2308 is. It would be better to do this by telling aspacemgr about
2309 it -- see the now disused record_system_memory() in
2310 initimg-darwin.c -- but that causes the sync checker to fail,
2311 since the mapping doesn't appear in the kernel-supplied
2312 process map. So do it here instead. */
2313# if defined(VGP_amd64_darwin)
2314 VG_TRACK( new_mem_startup,
2315 0x7fffffe00000, 0x7ffffffff000-0x7fffffe00000,
2316 True, False, True, /* r-x */
2317 0 /* di_handle: no associated debug info */ );
2318# elif defined(VGP_x86_darwin)
2319 VG_TRACK( new_mem_startup,
2320 0xfffec000, 0xfffff000-0xfffec000,
2321 True, False, True, /* r-x */
2322 0 /* di_handle: no associated debug info */ );
2323# endif
sewardj45f4e7c2005-09-27 19:20:21 +00002324 }
2325
2326 //--------------------------------------------------------------
sewardjde764e82007-11-09 23:13:22 +00002327 // Initialise the scheduler (phase 2)
2328 // p: Initialise the scheduler (phase 1) [for tid_main]
nethercote71980f02004-01-24 18:18:54 +00002329 // p: setup_file_descriptors() [else VG_(safe_fd)() breaks]
sewardj45f4e7c2005-09-27 19:20:21 +00002330 // p: setup_client_stack
nethercote71980f02004-01-24 18:18:54 +00002331 //--------------------------------------------------------------
sewardjde764e82007-11-09 23:13:22 +00002332 VG_(debugLog)(1, "main", "Initialise scheduler (phase 2)\n");
sewardj12ab7652006-10-17 02:10:42 +00002333 { NSegment const* seg
sewardjf9d2f9b2006-11-17 20:00:57 +00002334 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
sewardj45f4e7c2005-09-27 19:20:21 +00002335 vg_assert(seg);
2336 vg_assert(seg->kind == SkAnonC);
sewardjf9d2f9b2006-11-17 20:00:57 +00002337 vg_assert(the_iifii.initial_client_SP >= seg->start);
2338 vg_assert(the_iifii.initial_client_SP <= seg->end);
sewardjde764e82007-11-09 23:13:22 +00002339 VG_(scheduler_init_phase2)( tid_main,
2340 seg->end, the_iifii.clstack_max_size );
sewardj45f4e7c2005-09-27 19:20:21 +00002341 }
nethercote71980f02004-01-24 18:18:54 +00002342
2343 //--------------------------------------------------------------
sewardj17c11042006-10-15 01:26:40 +00002344 // Set up state for the root thread
sewardjb5f6f512005-03-10 23:59:00 +00002345 // p: ?
sewardj17c11042006-10-15 01:26:40 +00002346 // setup_scheduler() [for sched-specific thread 1 stuff]
sewardjf9d2f9b2006-11-17 20:00:57 +00002347 // VG_(ii_create_image) [for 'the_iicii' initial info]
sewardj2a99cf62004-11-24 10:44:19 +00002348 //--------------------------------------------------------------
sewardjf9d2f9b2006-11-17 20:00:57 +00002349 VG_(debugLog)(1, "main", "Finalise initial image\n");
2350 VG_(ii_finalise_image)( the_iifii );
njnea4b28c2004-11-30 16:04:58 +00002351
sewardj2a99cf62004-11-24 10:44:19 +00002352 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00002353 // Initialise the signal handling subsystem
sewardjb5f6f512005-03-10 23:59:00 +00002354 // p: n/a
nethercote71980f02004-01-24 18:18:54 +00002355 //--------------------------------------------------------------
2356 // Nb: temporarily parks the saved blocking-mask in saved_sigmask.
sewardj1fbc1a52005-04-25 02:05:54 +00002357 VG_(debugLog)(1, "main", "Initialise signal management\n");
njncda2f0f2009-05-18 02:12:08 +00002358 /* Check that the kernel-interface signal definitions look sane */
2359 VG_(vki_do_initial_consistency_checks)();
2360 /* .. and go on to use them. */
nethercote71980f02004-01-24 18:18:54 +00002361 VG_(sigstartup_actions)();
2362
2363 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00002364 // Read suppression file
sewardj95d86c02007-12-18 01:49:23 +00002365 // p: main_process_cmd_line_options() [for VG_(clo_suppressions)]
nethercote71980f02004-01-24 18:18:54 +00002366 //--------------------------------------------------------------
sewardj1fbc1a52005-04-25 02:05:54 +00002367 if (VG_(needs).core_errors || VG_(needs).tool_errors) {
2368 VG_(debugLog)(1, "main", "Load suppressions\n");
nethercote71980f02004-01-24 18:18:54 +00002369 VG_(load_suppressions)();
sewardj1fbc1a52005-04-25 02:05:54 +00002370 }
nethercote71980f02004-01-24 18:18:54 +00002371
2372 //--------------------------------------------------------------
rjwalsh0140af52005-06-04 20:42:33 +00002373 // register client stack
2374 //--------------------------------------------------------------
philippe38a74d22014-08-29 22:53:19 +00002375 VG_(clstk_id) = VG_(register_stack)(VG_(clstk_start_base), VG_(clstk_end));
rjwalsh0140af52005-06-04 20:42:33 +00002376
2377 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00002378 // Show the address space state so far
2379 //--------------------------------------------------------------
2380 VG_(debugLog)(1, "main", "\n");
2381 VG_(debugLog)(1, "main", "\n");
2382 VG_(am_show_nsegments)(1,"Memory layout at client startup");
2383 VG_(debugLog)(1, "main", "\n");
2384 VG_(debugLog)(1, "main", "\n");
2385
2386 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00002387 // Run!
2388 //--------------------------------------------------------------
sewardj1fbc1a52005-04-25 02:05:54 +00002389 VG_(debugLog)(1, "main", "Running thread 1\n");
sewardj1ae3f3a2005-09-28 10:47:38 +00002390
sewardj1d887112005-05-30 21:44:08 +00002391 /* As a result of the following call, the last thread standing
sewardj1ae3f3a2005-09-28 10:47:38 +00002392 eventually winds up running shutdown_actions_NORETURN
2393 just below. Unfortunately, simply exporting said function
2394 causes m_main to be part of a module cycle, which is pretty
2395 nonsensical. So instead of doing that, the address of said
2396 function is stored in a global variable 'owned' by m_syswrap,
2397 and it uses that function pointer to get back here when it needs
2398 to. */
2399
2400 /* Set continuation address. */
2401 VG_(address_of_m_main_shutdown_actions_NORETURN)
2402 = & shutdown_actions_NORETURN;
2403
2404 /* Run the first thread, eventually ending up at the continuation
2405 address. */
njnaf839f52005-06-23 03:27:57 +00002406 VG_(main_thread_wrapper_NORETURN)(1);
nethercote71980f02004-01-24 18:18:54 +00002407
sewardj1d887112005-05-30 21:44:08 +00002408 /*NOTREACHED*/
2409 vg_assert(0);
sewardjb5f6f512005-03-10 23:59:00 +00002410}
2411
sewardj17c11042006-10-15 01:26:40 +00002412/* Do everything which needs doing when the last thread exits or when
sewardj6e9de462011-06-28 07:25:29 +00002413 a thread exits requesting a complete process exit.
sewardj17c11042006-10-15 01:26:40 +00002414
2415 We enter here holding The Lock. For the case VgSrc_ExitProcess we
2416 must never release it, because to do so would allow other threads
2417 to continue after the system is ostensibly shut down. So we must
2418 go to our grave, so to speak, holding the lock.
2419
2420 In fact, there is never any point in releasing the lock at this
2421 point - we have it, we're shutting down the entire system, and
2422 for the case VgSrc_ExitProcess doing so positively causes trouble.
2423 So don't.
2424
2425 The final_tidyup call makes a bit of a nonsense of the ExitProcess
2426 case, since it will run the libc_freeres function, thus allowing
2427 other lurking threads to run again. Hmm. */
sewardjb5f6f512005-03-10 23:59:00 +00002428
sewardj1ae3f3a2005-09-28 10:47:38 +00002429static
2430void shutdown_actions_NORETURN( ThreadId tid,
2431 VgSchedReturnCode tids_schedretcode )
sewardjb5f6f512005-03-10 23:59:00 +00002432{
sewardj1d887112005-05-30 21:44:08 +00002433 VG_(debugLog)(1, "main", "entering VG_(shutdown_actions_NORETURN)\n");
sewardj17c11042006-10-15 01:26:40 +00002434 VG_(am_show_nsegments)(1,"Memory layout at client shutdown");
sewardj1d887112005-05-30 21:44:08 +00002435
sewardjb5f6f512005-03-10 23:59:00 +00002436 vg_assert(VG_(is_running_thread)(tid));
2437
sewardj12ab7652006-10-17 02:10:42 +00002438 vg_assert(tids_schedretcode == VgSrc_ExitThread
2439 || tids_schedretcode == VgSrc_ExitProcess
2440 || tids_schedretcode == VgSrc_FatalSig );
sewardjb5f6f512005-03-10 23:59:00 +00002441
sewardj12ab7652006-10-17 02:10:42 +00002442 if (tids_schedretcode == VgSrc_ExitThread) {
sewardjb5f6f512005-03-10 23:59:00 +00002443
sewardj17c11042006-10-15 01:26:40 +00002444 // We are the last surviving thread. Right?
2445 vg_assert( VG_(count_living_threads)() == 1 );
sewardjb5f6f512005-03-10 23:59:00 +00002446
sewardj17c11042006-10-15 01:26:40 +00002447 // Wait for all other threads to exit.
2448 // jrs: Huh? but they surely are already gone
2449 VG_(reap_threads)(tid);
sewardjb5f6f512005-03-10 23:59:00 +00002450
sewardj17c11042006-10-15 01:26:40 +00002451 // Clean the client up before the final report
2452 // this causes the libc_freeres function to run
2453 final_tidyup(tid);
2454
2455 /* be paranoid */
2456 vg_assert(VG_(is_running_thread)(tid));
2457 vg_assert(VG_(count_living_threads)() == 1);
2458
2459 } else {
2460
2461 // We may not be the last surviving thread. However, we
2462 // want to shut down the entire process. We hold the lock
2463 // and we need to keep hold of it all the way out, in order
2464 // that none of the other threads ever run again.
2465 vg_assert( VG_(count_living_threads)() >= 1 );
2466
sewardj17c11042006-10-15 01:26:40 +00002467 // Clean the client up before the final report
2468 // this causes the libc_freeres function to run
2469 // perhaps this is unsafe, as per comment above
2470 final_tidyup(tid);
2471
2472 /* be paranoid */
2473 vg_assert(VG_(is_running_thread)(tid));
2474 vg_assert(VG_(count_living_threads)() >= 1);
2475 }
sewardjb5f6f512005-03-10 23:59:00 +00002476
philippe180a7502014-04-20 13:41:10 +00002477 /* Final call to gdbserver, if requested. */
2478 if (VG_(gdbserver_stop_at) (VgdbStopAt_Exit)) {
2479 VG_(umsg)("(action at exit) vgdb me ... \n");
2480 VG_(gdbserver) (tid);
2481 }
sewardjb5f6f512005-03-10 23:59:00 +00002482 VG_(threads)[tid].status = VgTs_Empty;
philippe180a7502014-04-20 13:41:10 +00002483
nethercote71980f02004-01-24 18:18:54 +00002484 //--------------------------------------------------------------
sewardj738856f2009-07-15 14:48:32 +00002485 // Finalisation: cleanup, messages, etc. Order not so important, only
nethercote71980f02004-01-24 18:18:54 +00002486 // affects what order the messages come.
2487 //--------------------------------------------------------------
njnb6267bd2009-08-12 00:14:16 +00002488 // First thing in the post-amble is a blank line.
sewardj738856f2009-07-15 14:48:32 +00002489 if (VG_(clo_xml))
2490 VG_(printf_xml)("\n");
njnb6267bd2009-08-12 00:14:16 +00002491 else if (VG_(clo_verbosity) > 0)
2492 VG_(message)(Vg_UserMsg, "\n");
nethercote71980f02004-01-24 18:18:54 +00002493
sewardj71bc3cb2005-05-19 00:25:45 +00002494 if (VG_(clo_xml)) {
sewardj68cde6f2005-07-19 12:17:51 +00002495 HChar buf[50];
sewardj592ae092005-11-08 19:01:44 +00002496 VG_(elapsed_wallclock_time)(buf);
bartb3af9cf2011-10-06 19:08:37 +00002497 VG_(printf_xml)( "<status>\n"
sewardj738856f2009-07-15 14:48:32 +00002498 " <state>FINISHED</state>\n"
bartb3af9cf2011-10-06 19:08:37 +00002499 " <time>%pS</time>\n"
njnb6267bd2009-08-12 00:14:16 +00002500 "</status>\n"
2501 "\n",
sewardj738856f2009-07-15 14:48:32 +00002502 buf);
sewardj71bc3cb2005-05-19 00:25:45 +00002503 }
2504
nethercote71980f02004-01-24 18:18:54 +00002505 /* Print out file descriptor summary and stats. */
2506 if (VG_(clo_track_fds))
philippec3360382012-10-21 14:37:14 +00002507 VG_(show_open_fds)("at exit");
nethercote71980f02004-01-24 18:18:54 +00002508
sewardj2d9e8742009-08-07 15:46:56 +00002509 /* Call the tool's finalisation function. This makes Memcheck's
2510 leak checker run, and possibly chuck a bunch of leak errors into
2511 the error management machinery. */
2512 VG_TDICT_CALL(tool_fini, 0/*exitcode*/);
nethercote71980f02004-01-24 18:18:54 +00002513
sewardj2d9e8742009-08-07 15:46:56 +00002514 /* Show the error counts. */
sewardj7ca100d2009-08-15 23:05:34 +00002515 if (VG_(clo_xml)
2516 && (VG_(needs).core_errors || VG_(needs).tool_errors)) {
sewardj2d9e8742009-08-07 15:46:56 +00002517 VG_(show_error_counts_as_XML)();
sewardj738856f2009-07-15 14:48:32 +00002518 }
sewardj2d9e8742009-08-07 15:46:56 +00002519
2520 /* In XML mode, this merely prints the used suppressions. */
2521 if (VG_(needs).core_errors || VG_(needs).tool_errors)
sewardj3b290482011-05-06 21:02:55 +00002522 VG_(show_all_errors)(VG_(clo_verbosity), VG_(clo_xml));
nethercote71980f02004-01-24 18:18:54 +00002523
sewardj71bc3cb2005-05-19 00:25:45 +00002524 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +00002525 VG_(printf_xml)("\n");
2526 VG_(printf_xml)("</valgrindoutput>\n");
2527 VG_(printf_xml)("\n");
sewardj71bc3cb2005-05-19 00:25:45 +00002528 }
2529
nethercote885dd912004-08-03 23:14:00 +00002530 VG_(sanity_check_general)( True /*include expensive checks*/ );
nethercote71980f02004-01-24 18:18:54 +00002531
sewardj2d9e8742009-08-07 15:46:56 +00002532 if (VG_(clo_stats))
philippe4f6f3362014-04-19 00:25:54 +00002533 VG_(print_all_stats)(VG_(clo_verbosity) > 2, /* Memory stats */
2534 False /* tool prints stats in the tool fini */);
nethercote71980f02004-01-24 18:18:54 +00002535
sewardj9c606bd2008-09-18 18:12:50 +00002536 /* Show a profile of the heap(s) at shutdown. Optionally, first
2537 throw away all the debug info, as that makes it easy to spot
2538 leaks in the debuginfo reader. */
2539 if (VG_(clo_profile_heap)) {
2540 if (0) VG_(di_discard_ALL_debuginfo)();
2541 VG_(print_arena_cc_analysis)();
2542 }
2543
sewardj17c5e2e2012-12-28 09:12:14 +00002544 /* If profiling has been requested, but with zero interval, it
2545 means "profile at the end of the run only". In which case we
2546 need to dump the profile now. */
2547 if (VG_(clo_profyle_sbs) && VG_(clo_profyle_interval) == 0) {
2548 VG_(get_and_show_SB_profile)(0/*denoting end-of-run*/);
njn2025cf92005-06-26 20:44:48 +00002549 }
sewardjfa8ec112005-01-19 11:55:34 +00002550
sewardj8b635a42004-11-22 19:01:47 +00002551 /* Print Vex storage stats */
sewardjbf426512005-01-17 18:35:30 +00002552 if (0)
2553 LibVEX_ShowAllocStats();
sewardj1d887112005-05-30 21:44:08 +00002554
sewardj738856f2009-07-15 14:48:32 +00002555 /* Flush any output cached by previous calls to VG_(message). */
2556 VG_(message_flush)();
2557
philippe180a7502014-04-20 13:41:10 +00002558 /* Terminate gdbserver if ever it was started. We terminate it here
sewardj17c5e2e2012-12-28 09:12:14 +00002559 so that it get the output above if output was redirected to
2560 gdb */
philippe0447bbd2012-10-17 21:32:03 +00002561 VG_(gdbserver_exit) (tid, tids_schedretcode);
sewardj3b290482011-05-06 21:02:55 +00002562
njn8aa35852005-06-10 22:59:56 +00002563 /* Ok, finally exit in the os-specific way, according to the scheduler's
2564 return code. In short, if the (last) thread exited by calling
2565 sys_exit, do likewise; if the (last) thread stopped due to a fatal
2566 signal, terminate the entire system with that same fatal signal. */
2567 VG_(debugLog)(1, "core_os",
njn7b85dd52005-06-12 17:26:29 +00002568 "VG_(terminate_NORETURN)(tid=%lld)\n", (ULong)tid);
njn8aa35852005-06-10 22:59:56 +00002569
njn8aa35852005-06-10 22:59:56 +00002570 switch (tids_schedretcode) {
sewardj12ab7652006-10-17 02:10:42 +00002571 case VgSrc_ExitThread: /* the normal way out (Linux) */
sewardj6e9de462011-06-28 07:25:29 +00002572 case VgSrc_ExitProcess: /* the normal way out (AIX) -- still needed? */
sewardjb9779082006-05-12 23:50:15 +00002573 /* Change the application return code to user's return code,
2574 if an error was found */
2575 if (VG_(clo_error_exitcode) > 0
2576 && VG_(get_n_errs_found)() > 0) {
philippe180a7502014-04-20 13:41:10 +00002577 VG_(client_exit)( VG_(clo_error_exitcode) );
sewardjb9779082006-05-12 23:50:15 +00002578 } else {
2579 /* otherwise, return the client's exit code, in the normal
2580 way. */
philippe180a7502014-04-20 13:41:10 +00002581 VG_(client_exit)( VG_(threads)[tid].os_state.exitcode );
sewardjb9779082006-05-12 23:50:15 +00002582 }
njn8aa35852005-06-10 22:59:56 +00002583 /* NOT ALIVE HERE! */
sewardj17c11042006-10-15 01:26:40 +00002584 VG_(core_panic)("entered the afterlife in main() -- ExitT/P");
njn8aa35852005-06-10 22:59:56 +00002585 break; /* what the hell :) */
2586
2587 case VgSrc_FatalSig:
2588 /* We were killed by a fatal signal, so replicate the effect */
2589 vg_assert(VG_(threads)[tid].os_state.fatalsig != 0);
2590 VG_(kill_self)(VG_(threads)[tid].os_state.fatalsig);
njnf76d27a2009-05-28 01:53:07 +00002591 /* we shouldn't be alive at this point. But VG_(kill_self)
2592 sometimes fails with EPERM on Darwin, for unclear reasons. */
2593# if defined(VGO_darwin)
2594 VG_(debugLog)(0, "main", "VG_(kill_self) failed. Exiting normally.\n");
2595 VG_(exit)(0); /* bogus, but we really need to exit now */
2596 /* fall through .. */
2597# endif
njn8aa35852005-06-10 22:59:56 +00002598 VG_(core_panic)("main(): signal was supposed to be fatal");
2599 break;
2600
2601 default:
2602 VG_(core_panic)("main(): unexpected scheduler return code");
2603 }
njne96be672005-05-08 19:08:54 +00002604}
sewardj8b635a42004-11-22 19:01:47 +00002605
sewardj1ae3f3a2005-09-28 10:47:38 +00002606/* -------------------- */
2607
2608/* Final clean-up before terminating the process.
2609 Clean up the client by calling __libc_freeres() (if requested)
2610 This is Linux-specific?
njnf76d27a2009-05-28 01:53:07 +00002611 GrP fixme glibc-specific, anyway
sewardj1ae3f3a2005-09-28 10:47:38 +00002612*/
2613static void final_tidyup(ThreadId tid)
2614{
njnf76d27a2009-05-28 01:53:07 +00002615#if !defined(VGO_darwin)
carllcae0cc22014-08-07 23:17:29 +00002616# if defined(VGP_ppc64be_linux)
sewardjcf951812006-01-17 02:22:21 +00002617 Addr r2;
2618# endif
sewardj0ec07f32006-01-12 12:32:32 +00002619 Addr __libc_freeres_wrapper = VG_(client___libc_freeres_wrapper);
sewardj1ae3f3a2005-09-28 10:47:38 +00002620
2621 vg_assert(VG_(is_running_thread)(tid));
2622
2623 if ( !VG_(needs).libc_freeres ||
2624 !VG_(clo_run_libc_freeres) ||
sewardj0ec07f32006-01-12 12:32:32 +00002625 0 == __libc_freeres_wrapper )
sewardj1ae3f3a2005-09-28 10:47:38 +00002626 return; /* can't/won't do it */
2627
carllcae0cc22014-08-07 23:17:29 +00002628# if defined(VGP_ppc64be_linux)
sewardjcf951812006-01-17 02:22:21 +00002629 r2 = VG_(get_tocptr)( __libc_freeres_wrapper );
2630 if (r2 == 0) {
2631 VG_(message)(Vg_UserMsg,
sewardj738856f2009-07-15 14:48:32 +00002632 "Caught __NR_exit, but can't run __libc_freeres()\n");
sewardjcf951812006-01-17 02:22:21 +00002633 VG_(message)(Vg_UserMsg,
sewardj738856f2009-07-15 14:48:32 +00002634 " since cannot establish TOC pointer for it.\n");
sewardjcf951812006-01-17 02:22:21 +00002635 return;
2636 }
2637# endif
2638
sewardj1ae3f3a2005-09-28 10:47:38 +00002639 if (VG_(clo_verbosity) > 2 ||
2640 VG_(clo_trace_syscalls) ||
2641 VG_(clo_trace_sched))
2642 VG_(message)(Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +00002643 "Caught __NR_exit; running __libc_freeres()\n");
sewardj1ae3f3a2005-09-28 10:47:38 +00002644
sewardj0ec07f32006-01-12 12:32:32 +00002645 /* set thread context to point to libc_freeres_wrapper */
carllcae0cc22014-08-07 23:17:29 +00002646 /* ppc64be-linux note: __libc_freeres_wrapper gives us the real
sewardj1a85f4f2006-01-12 21:15:35 +00002647 function entry point, not a fn descriptor, so can use it
2648 directly. However, we need to set R2 (the toc pointer)
2649 appropriately. */
sewardj1ae3f3a2005-09-28 10:47:38 +00002650 VG_(set_IP)(tid, __libc_freeres_wrapper);
carllcae0cc22014-08-07 23:17:29 +00002651# if defined(VGP_ppc64be_linux)
sewardjcf951812006-01-17 02:22:21 +00002652 VG_(threads)[tid].arch.vex.guest_GPR2 = r2;
carll582d5822014-08-07 23:35:54 +00002653# elif defined(VGP_ppc64le_linux)
2654 /* setting GPR2 but not really needed, GPR12 is needed */
2655 VG_(threads)[tid].arch.vex.guest_GPR2 = __libc_freeres_wrapper;
2656 VG_(threads)[tid].arch.vex.guest_GPR12 = __libc_freeres_wrapper;
sewardjcf951812006-01-17 02:22:21 +00002657# endif
sewardj5db15402012-06-07 09:13:21 +00002658 /* mips-linux note: we need to set t9 */
petarj4df0bfc2013-02-27 23:17:33 +00002659# if defined(VGP_mips32_linux) || defined(VGP_mips64_linux)
sewardj5db15402012-06-07 09:13:21 +00002660 VG_(threads)[tid].arch.vex.guest_r25 = __libc_freeres_wrapper;
2661# endif
sewardj1ae3f3a2005-09-28 10:47:38 +00002662
2663 /* Block all blockable signals by copying the real block state into
2664 the thread's block state*/
2665 VG_(sigprocmask)(VKI_SIG_BLOCK, NULL, &VG_(threads)[tid].sig_mask);
2666 VG_(threads)[tid].tmp_sig_mask = VG_(threads)[tid].sig_mask;
2667
2668 /* and restore handlers to default */
2669 VG_(set_default_handler)(VKI_SIGSEGV);
2670 VG_(set_default_handler)(VKI_SIGBUS);
2671 VG_(set_default_handler)(VKI_SIGILL);
2672 VG_(set_default_handler)(VKI_SIGFPE);
2673
2674 // We were exiting, so assert that...
2675 vg_assert(VG_(is_exiting)(tid));
2676 // ...but now we're not again
2677 VG_(threads)[tid].exitreason = VgSrc_None;
2678
2679 // run until client thread exits - ideally with LIBC_FREERES_DONE,
2680 // but exit/exitgroup/signal will do
2681 VG_(scheduler)(tid);
2682
2683 vg_assert(VG_(is_exiting)(tid));
njnf76d27a2009-05-28 01:53:07 +00002684#endif
sewardj1ae3f3a2005-09-28 10:47:38 +00002685}
2686
sewardj45f4e7c2005-09-27 19:20:21 +00002687
2688/*====================================================================*/
njn49f80e82009-05-21 01:25:43 +00002689/*=== Getting to main() alive: LINUX ===*/
sewardj45f4e7c2005-09-27 19:20:21 +00002690/*====================================================================*/
2691
sewardj17c11042006-10-15 01:26:40 +00002692#if defined(VGO_linux)
2693
sewardj45f4e7c2005-09-27 19:20:21 +00002694/* If linking of the final executables is done with glibc present,
2695 then Valgrind starts at main() above as usual, and all of the
2696 following code is irrelevant.
2697
2698 However, this is not the intended mode of use. The plan is to
2699 avoid linking against glibc, by giving gcc the flags
2700 -nodefaultlibs -lgcc -nostartfiles at startup.
2701
2702 From this derive two requirements:
2703
petarje70c45e2013-02-15 03:12:17 +00002704 1. gcc may emit calls to memcpy, memmove and memset to deal with
2705 structure assignments etc. Since we have chosen to ignore all the
sewardj45f4e7c2005-09-27 19:20:21 +00002706 "normal" supporting libraries, we have to provide our own
2707 implementations of them. No problem.
2708
2709 2. We have to provide a symbol "_start", to which the kernel
2710 hands control at startup. Hence the code below.
2711*/
2712
2713/* ---------------- Requirement 1 ---------------- */
2714
sewardj17c11042006-10-15 01:26:40 +00002715void* memcpy(void *dest, const void *src, SizeT n);
2716void* memcpy(void *dest, const void *src, SizeT n) {
sewardj45f4e7c2005-09-27 19:20:21 +00002717 return VG_(memcpy)(dest,src,n);
2718}
petarje70c45e2013-02-15 03:12:17 +00002719void* memmove(void *dest, const void *src, SizeT n);
2720void* memmove(void *dest, const void *src, SizeT n) {
2721 return VG_(memmove)(dest,src,n);
2722}
sewardj17c11042006-10-15 01:26:40 +00002723void* memset(void *s, int c, SizeT n);
2724void* memset(void *s, int c, SizeT n) {
sewardj45f4e7c2005-09-27 19:20:21 +00002725 return VG_(memset)(s,c,n);
2726}
2727
bart82616e12010-06-13 13:46:24 +00002728/* BVA: abort() for those platforms that need it (PPC and ARM). */
2729void abort(void);
2730void abort(void){
2731 VG_(printf)("Something called raise().\n");
2732 vg_assert(0);
2733}
2734
sewardj59570ff2010-01-01 11:59:33 +00002735/* EAZG: ARM's EABI will call floating point exception handlers in
2736 libgcc which boil down to an abort or raise, that's usually defined
2737 in libc. Instead, define them here. */
2738#if defined(VGP_arm_linux)
2739void raise(void);
2740void raise(void){
2741 VG_(printf)("Something called raise().\n");
2742 vg_assert(0);
2743}
2744
sewardj59570ff2010-01-01 11:59:33 +00002745void __aeabi_unwind_cpp_pr0(void);
2746void __aeabi_unwind_cpp_pr0(void){
2747 VG_(printf)("Something called __aeabi_unwind_cpp_pr0()\n");
2748 vg_assert(0);
2749}
sewardj38efe4b2010-08-22 12:23:01 +00002750
2751void __aeabi_unwind_cpp_pr1(void);
2752void __aeabi_unwind_cpp_pr1(void){
2753 VG_(printf)("Something called __aeabi_unwind_cpp_pr1()\n");
2754 vg_assert(0);
2755}
sewardj59570ff2010-01-01 11:59:33 +00002756#endif
2757
sewardj45f4e7c2005-09-27 19:20:21 +00002758/* ---------------- Requirement 2 ---------------- */
2759
2760/* Glibc's sysdeps/i386/elf/start.S has the following gem of a
2761 comment, which explains how the stack looks right at process start
2762 (when _start is jumped to). Hence _start passes %esp to
sewardj17c11042006-10-15 01:26:40 +00002763 _start_in_C_linux, which extracts argc/argv/envp and starts up
sewardj45f4e7c2005-09-27 19:20:21 +00002764 correctly. */
2765
2766/* This is the canonical entry point, usually the first thing in the text
2767 segment. The SVR4/i386 ABI (pages 3-31, 3-32) says that when the entry
2768 point runs, most registers' values are unspecified, except for:
2769
2770 %edx Contains a function pointer to be registered with `atexit'.
2771 This is how the dynamic linker arranges to have DT_FINI
2772 functions called for shared libraries that have been loaded
2773 before this code runs.
2774
2775 %esp The stack contains the arguments and environment:
2776 0(%esp) argc
2777 4(%esp) argv[0]
2778 ...
2779 (4*argc)(%esp) NULL
2780 (4*(argc+1))(%esp) envp[0]
2781 ...
2782 NULL
2783*/
2784
2785/* The kernel hands control to _start, which extracts the initial
sewardj17c11042006-10-15 01:26:40 +00002786 stack pointer and calls onwards to _start_in_C_linux. This also switches
sewardja48a4932005-09-29 11:09:56 +00002787 the new stack. */
sewardj45f4e7c2005-09-27 19:20:21 +00002788#if defined(VGP_x86_linux)
2789asm("\n"
sewardjd9fc3822005-11-18 23:50:43 +00002790 ".text\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002791 "\t.globl _start\n"
2792 "\t.type _start,@function\n"
2793 "_start:\n"
2794 /* set up the new stack in %eax */
sewardjfdf91b42005-09-28 00:53:09 +00002795 "\tmovl $vgPlain_interim_stack, %eax\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002796 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
2797 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
2798 "\tsubl $16, %eax\n"
2799 "\tandl $~15, %eax\n"
2800 /* install it, and collect the original one */
2801 "\txchgl %eax, %esp\n"
sewardj17c11042006-10-15 01:26:40 +00002802 /* call _start_in_C_linux, passing it the startup %esp */
sewardj45f4e7c2005-09-27 19:20:21 +00002803 "\tpushl %eax\n"
sewardj17c11042006-10-15 01:26:40 +00002804 "\tcall _start_in_C_linux\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002805 "\thlt\n"
sewardj2fedc642005-11-19 02:02:57 +00002806 ".previous\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002807);
2808#elif defined(VGP_amd64_linux)
2809asm("\n"
sewardjd9fc3822005-11-18 23:50:43 +00002810 ".text\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002811 "\t.globl _start\n"
2812 "\t.type _start,@function\n"
2813 "_start:\n"
2814 /* set up the new stack in %rdi */
sewardjfdf91b42005-09-28 00:53:09 +00002815 "\tmovq $vgPlain_interim_stack, %rdi\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002816 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
2817 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
2818 "\tandq $~15, %rdi\n"
2819 /* install it, and collect the original one */
2820 "\txchgq %rdi, %rsp\n"
sewardj17c11042006-10-15 01:26:40 +00002821 /* call _start_in_C_linux, passing it the startup %rsp */
2822 "\tcall _start_in_C_linux\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002823 "\thlt\n"
sewardj2fedc642005-11-19 02:02:57 +00002824 ".previous\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002825);
sewardja48a4932005-09-29 11:09:56 +00002826#elif defined(VGP_ppc32_linux)
2827asm("\n"
sewardjd9fc3822005-11-18 23:50:43 +00002828 ".text\n"
sewardja48a4932005-09-29 11:09:56 +00002829 "\t.globl _start\n"
2830 "\t.type _start,@function\n"
2831 "_start:\n"
2832 /* set up the new stack in r16 */
2833 "\tlis 16,vgPlain_interim_stack@ha\n"
2834 "\tla 16,vgPlain_interim_stack@l(16)\n"
2835 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2836 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2837 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2838 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2839 "\tadd 16,17,16\n"
2840 "\tadd 16,18,16\n"
2841 "\trlwinm 16,16,0,0,27\n"
2842 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2843 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2844 boundary. And r1 is the original SP. Set the SP to r16 and
sewardj17c11042006-10-15 01:26:40 +00002845 call _start_in_C_linux, passing it the initial SP. */
sewardja48a4932005-09-29 11:09:56 +00002846 "\tmr 3,1\n"
2847 "\tmr 1,16\n"
sewardj17c11042006-10-15 01:26:40 +00002848 "\tbl _start_in_C_linux\n"
sewardja48a4932005-09-29 11:09:56 +00002849 "\ttrap\n"
sewardj2fedc642005-11-19 02:02:57 +00002850 ".previous\n"
sewardja48a4932005-09-29 11:09:56 +00002851);
carllcae0cc22014-08-07 23:17:29 +00002852#elif defined(VGP_ppc64be_linux)
sewardj2c48c7b2005-11-29 13:05:56 +00002853asm("\n"
cerion21082042005-12-06 19:07:08 +00002854 /* PPC64 ELF ABI says '_start' points to a function descriptor.
2855 So we must have one, and that is what goes into the .opd section. */
cerion297c88f2005-12-22 15:53:12 +00002856 "\t.align 2\n"
cerion21082042005-12-06 19:07:08 +00002857 "\t.global _start\n"
2858 "\t.section \".opd\",\"aw\"\n"
2859 "\t.align 3\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002860 "_start:\n"
cerion21082042005-12-06 19:07:08 +00002861 "\t.quad ._start,.TOC.@tocbase,0\n"
2862 "\t.previous\n"
2863 "\t.type ._start,@function\n"
2864 "\t.global ._start\n"
2865 "._start:\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002866 /* set up the new stack in r16 */
2867 "\tlis 16, vgPlain_interim_stack@highest\n"
2868 "\tori 16,16,vgPlain_interim_stack@higher\n"
2869 "\tsldi 16,16,32\n"
2870 "\toris 16,16,vgPlain_interim_stack@h\n"
2871 "\tori 16,16,vgPlain_interim_stack@l\n"
2872 "\txor 17,17,17\n"
2873 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2874 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2875 "\txor 18,18,18\n"
2876 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2877 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2878 "\tadd 16,17,16\n"
2879 "\tadd 16,18,16\n"
2880 "\trldicr 16,16,0,59\n"
2881 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2882 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2883 boundary. And r1 is the original SP. Set the SP to r16 and
sewardj17c11042006-10-15 01:26:40 +00002884 call _start_in_C_linux, passing it the initial SP. */
sewardj2c48c7b2005-11-29 13:05:56 +00002885 "\tmr 3,1\n"
2886 "\tmr 1,16\n"
sewardj5e21d442012-07-21 10:08:29 +00002887 "\tlis 14, _start_in_C_linux@highest\n"
2888 "\tori 14,14,_start_in_C_linux@higher\n"
2889 "\tsldi 14,14,32\n"
2890 "\toris 14,14,_start_in_C_linux@h\n"
2891 "\tori 14,14,_start_in_C_linux@l\n"
2892 "\tld 14,0(14)\n"
2893 "\tmtctr 14\n"
2894 "\tbctrl\n"
cerion21082042005-12-06 19:07:08 +00002895 "\tnop\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002896 "\ttrap\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002897);
carll582d5822014-08-07 23:35:54 +00002898#elif defined(VGP_ppc64le_linux)
2899/* Little Endian uses ELF version 2 but in the future may also
2900 * support other ELF versions.
2901 */
2902asm("\n"
2903 "\t.align 2\n"
2904 "\t.global _start\n"
2905 "\t.type _start,@function\n"
2906 "_start:\n"
2907 "#if _CALL_ELF == 2 \n"
2908 "0: addis 2,12,.TOC.-0b@ha\n"
2909 " addi 2,2,.TOC.-0b@l\n"
2910 " .localentry _start, .-_start\n"
2911 "#endif \n"
2912 /* set up the new stack in r16 */
2913 "\tlis 16, vgPlain_interim_stack@highest\n"
2914 "\tori 16,16,vgPlain_interim_stack@higher\n"
2915 "\tsldi 16,16,32\n"
2916 "\toris 16,16,vgPlain_interim_stack@h\n"
2917 "\tori 16,16,vgPlain_interim_stack@l\n"
2918 "\txor 17,17,17\n"
2919 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2920 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2921 "\txor 18,18,18\n"
2922 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2923 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2924 "\tadd 16,17,16\n"
2925 "\tadd 16,18,16\n"
2926 "\trldicr 16,16,0,59\n"
2927 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2928 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2929 boundary. And r1 is the original SP. Set the SP to r16 and
2930 call _start_in_C_linux, passing it the initial SP. */
2931 "\tmr 3,1\n"
2932 "\tmr 1,16\n"
2933 "\tlis 14, _start_in_C_linux@highest\n"
2934 "\tori 14,14,_start_in_C_linux@higher\n"
2935 "\tsldi 14,14,32\n"
2936 "\toris 14,14,_start_in_C_linux@h\n"
2937 "\tori 14,14,_start_in_C_linux@l\n"
2938 "\tmtctr 14\n"
2939 "\tbctrl\n"
2940 "\tnop\n"
2941 "\ttrap\n"
2942);
sewardjb5b87402011-03-07 16:05:35 +00002943#elif defined(VGP_s390x_linux)
2944/*
2945 This is the canonical entry point, usually the first thing in the text
2946 segment. Most registers' values are unspecified, except for:
2947
2948 %r14 Contains a function pointer to be registered with `atexit'.
2949 This is how the dynamic linker arranges to have DT_FINI
2950 functions called for shared libraries that have been loaded
2951 before this code runs.
2952
2953 %r15 The stack contains the arguments and environment:
2954 0(%r15) argc
2955 8(%r15) argv[0]
2956 ...
2957 (8*argc)(%r15) NULL
2958 (8*(argc+1))(%r15) envp[0]
2959 ...
2960 NULL
2961*/
2962asm("\n\t"
2963 ".text\n\t"
2964 ".globl _start\n\t"
2965 ".type _start,@function\n\t"
2966 "_start:\n\t"
2967 /* set up the new stack in %r1 */
2968 "larl %r1, vgPlain_interim_stack\n\t"
2969 "larl %r5, 1f\n\t"
2970 "ag %r1, 0(%r5)\n\t"
2971 "ag %r1, 2f-1f(%r5)\n\t"
2972 "nill %r1, 0xFFF0\n\t"
2973 /* install it, and collect the original one */
2974 "lgr %r2, %r15\n\t"
2975 "lgr %r15, %r1\n\t"
2976 /* call _start_in_C_linux, passing it the startup %r15 */
2977 "brasl %r14, _start_in_C_linux\n\t"
2978 /* trigger execution of an invalid opcode -> halt machine */
2979 "j .+2\n\t"
2980 "1: .quad "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n\t"
2981 "2: .quad "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n\t"
2982 ".previous\n"
2983);
sewardj59570ff2010-01-01 11:59:33 +00002984#elif defined(VGP_arm_linux)
2985asm("\n"
sewardjb51c9262011-05-03 14:24:11 +00002986 "\t.text\n"
2987 "\t.align 4\n"
2988 "\t.type _start,#function\n"
sewardj59570ff2010-01-01 11:59:33 +00002989 "\t.global _start\n"
2990 "_start:\n"
2991 "\tldr r0, [pc, #36]\n"
2992 "\tldr r1, [pc, #36]\n"
2993 "\tadd r0, r1, r0\n"
2994 "\tldr r1, [pc, #32]\n"
2995 "\tadd r0, r1, r0\n"
2996 "\tmvn r1, #15\n"
2997 "\tand r0, r0, r1\n"
2998 "\tmov r1, sp\n"
2999 "\tmov sp, r0\n"
3000 "\tmov r0, r1\n"
3001 "\tb _start_in_C_linux\n"
3002 "\t.word vgPlain_interim_stack\n"
3003 "\t.word "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
3004 "\t.word "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
3005);
sewardjf0c12502014-01-12 12:54:00 +00003006#elif defined(VGP_arm64_linux)
3007asm("\n"
3008 "\t.text\n"
3009 "\t.align 2\n"
3010 "\t.type _start,#function\n"
3011 "\t.global _start\n"
3012 "_start:\n"
3013 "\tadrp x0, vgPlain_interim_stack\n"
3014 "\tadd x0, x0, :lo12:vgPlain_interim_stack\n"
3015 // The next 2 assume that VG_STACK_GUARD_SZB fits in 32 bits
3016 "\tmov x1, (("VG_STRINGIFY(VG_STACK_GUARD_SZB)") >> 0) & 0xFFFF\n"
3017 "\tmovk x1, (("VG_STRINGIFY(VG_STACK_GUARD_SZB)") >> 16) & 0xFFFF,"
3018 " lsl 16\n"
3019 "\tadd x0, x0, x1\n"
3020 // The next 2 assume that VG_STACK_ACTIVE_SZB fits in 32 bits
3021 "\tmov x1, (("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)") >> 0) & 0xFFFF\n"
3022 "\tmovk x1, (("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)") >> 16) & 0xFFFF,"
3023 " lsl 16\n"
3024 "\tadd x0, x0, x1\n"
3025 "\tand x0, x0, -16\n"
3026 "\tmov x1, sp\n"
3027 "\tmov sp, x0\n"
3028 "\tmov x0, x1\n"
3029 "\tb _start_in_C_linux\n"
3030);
sewardj5db15402012-06-07 09:13:21 +00003031#elif defined(VGP_mips32_linux)
3032asm("\n"
3033 "\t.type _gp_disp,@object\n"
3034 ".text\n"
3035 "\t.globl __start\n"
3036 "\t.type __start,@function\n"
3037 "__start:\n"
3038
3039 "\tbal 1f\n"
3040 "\tnop\n"
3041
3042 "1:\n"
3043
3044 "\tlui $28, %hi(_gp_disp)\n"
3045 "\taddiu $28, $28, %lo(_gp_disp)\n"
3046 "\taddu $28, $28, $31\n"
3047 /* t1/$9 <- Addr(interim_stack) */
3048 "\tlui $9, %hi(vgPlain_interim_stack)\n"
3049 /* t1/$9 <- Addr(interim_stack) */
3050 "\taddiu $9, %lo(vgPlain_interim_stack)\n"
3051
3052
3053 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
3054 "\tli $11, "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
3055
3056 "\taddu $9, $9, $10\n"
3057 "\taddu $9, $9, $11\n"
3058 "\tli $12, 0xFFFFFFF0\n"
3059 "\tand $9, $9, $12\n"
3060 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
3061 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
3062 boundary. And $29 is the original SP. Set the SP to t1 and
3063 call _start_in_C, passing it the initial SP. */
3064
3065 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
3066 "\tmove $29, $9\n" // $sp <- t1 (new sp)
3067
3068 "\tlui $25, %hi(_start_in_C_linux)\n"
3069 "\taddiu $25, %lo(_start_in_C_linux)\n"
3070
3071 "\tbal _start_in_C_linux\n"
3072 "\tbreak 0x7\n"
3073 ".previous\n"
3074);
petarj4df0bfc2013-02-27 23:17:33 +00003075#elif defined(VGP_mips64_linux)
3076asm(
3077".text\n"
3078".globl __start\n"
3079".type __start,@function\n"
3080"__start:\n"
3081 "\t.set noreorder\n"
3082 "\t.cpload $25\n"
3083 "\t.set reorder\n"
3084 "\t.cprestore 16\n"
3085 "\tlui $9, %hi(vgPlain_interim_stack)\n"
3086 /* t1/$9 <- Addr(interim_stack) */
3087 "\tdaddiu $9, %lo(vgPlain_interim_stack)\n"
3088
3089 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
3090 "\tli $11, "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
3091
3092 "\tdaddu $9, $9, $10\n"
3093 "\tdaddu $9, $9, $11\n"
3094 "\tli $12, 0xFFFFFF00\n"
3095 "\tand $9, $9, $12\n"
3096 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
3097 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
3098 boundary. And $29 is the original SP. Set the SP to t1 and
3099 call _start_in_C, passing it the initial SP. */
3100
3101 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
3102 "\tmove $29, $9\n" // $sp <- t1 (new sp)
3103
3104 "\tlui $9, %highest(_start_in_C_linux)\n"
3105 "\tori $9, %higher(_start_in_C_linux)\n"
3106 "\tdsll32 $9, $9, 0x0\n"
3107 "\tlui $10, %hi(_start_in_C_linux)\n"
3108 "\tdaddiu $10, %lo(_start_in_C_linux)\n"
3109 "\tdaddu $25, $9, $10\n"
3110 "\tjalr $25\n"
3111 "\tnop\n"
dejanj124b9f22013-10-16 14:15:38 +00003112".previous\n"
petarj4df0bfc2013-02-27 23:17:33 +00003113);
sewardj45f4e7c2005-09-27 19:20:21 +00003114#else
njn49f80e82009-05-21 01:25:43 +00003115# error "Unknown linux platform"
sewardj45f4e7c2005-09-27 19:20:21 +00003116#endif
3117
sewardje66f2e02006-12-30 17:45:08 +00003118/* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
3119#define _GNU_SOURCE
3120#define _FILE_OFFSET_BITS 64
3121/* This is in order to get AT_NULL and AT_PAGESIZE. */
3122#include <elf.h>
3123/* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
3124
sewardj45f4e7c2005-09-27 19:20:21 +00003125/* Avoid compiler warnings: this fn _is_ used, but labelling it
philippe9fdca562012-04-16 22:06:47 +00003126 'static' causes gcc to complain it isn't.
3127 attribute 'used' also ensures the code is not eliminated at link
3128 time */
3129__attribute__ ((used))
sewardj17c11042006-10-15 01:26:40 +00003130void _start_in_C_linux ( UWord* pArgc );
philippe9fdca562012-04-16 22:06:47 +00003131__attribute__ ((used))
sewardj17c11042006-10-15 01:26:40 +00003132void _start_in_C_linux ( UWord* pArgc )
sewardj45f4e7c2005-09-27 19:20:21 +00003133{
3134 Int r;
3135 Word argc = pArgc[0];
3136 HChar** argv = (HChar**)&pArgc[1];
3137 HChar** envp = (HChar**)&pArgc[1+argc+1];
sewardjf9d2f9b2006-11-17 20:00:57 +00003138
philippe854be4c2013-10-22 21:20:14 +00003139 // For an inner Valgrind, register the interim stack asap.
3140 // This is needed to allow the outer valgrind to do stacktraces during init.
3141 // Note that this stack is not unregistered when the main thread
3142 // is switching to the (real) stack. Unregistering this would imply
3143 // to save the stack id in a global variable, and have a "if"
3144 // in run_a_thread_NORETURN to do the unregistration only for the
3145 // main thread. This unregistration is not worth this complexity.
3146 INNER_REQUEST
3147 ((void) VALGRIND_STACK_REGISTER
3148 (&VG_(interim_stack).bytes[0],
3149 &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack))));
3150
sewardjf9d2f9b2006-11-17 20:00:57 +00003151 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3152 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3153
3154 the_iicii.sp_at_startup = (Addr)pArgc;
3155
carllcae0cc22014-08-07 23:17:29 +00003156# if defined(VGP_ppc32_linux) || defined(VGP_ppc64be_linux) \
3157 || defined(VGP_ppc64le_linux) || defined(VGP_arm64_linux)
sewardje66f2e02006-12-30 17:45:08 +00003158 {
carllcae0cc22014-08-07 23:17:29 +00003159 /* ppc32/ppc64 can be configured with different page sizes.
sewardje66f2e02006-12-30 17:45:08 +00003160 Determine this early. This is an ugly hack and really should
3161 be moved into valgrind_main. */
3162 UWord *sp = &pArgc[1+argc+1];
3163 while (*sp++ != 0)
3164 ;
3165 for (; *sp != AT_NULL && *sp != AT_PAGESZ; sp += 2);
3166 if (*sp == AT_PAGESZ) {
3167 VKI_PAGE_SIZE = sp[1];
3168 for (VKI_PAGE_SHIFT = 12;
3169 VKI_PAGE_SHIFT <= VKI_MAX_PAGE_SHIFT; VKI_PAGE_SHIFT++)
3170 if (VKI_PAGE_SIZE == (1UL << VKI_PAGE_SHIFT))
3171 break;
3172 }
3173 }
3174# endif
3175
sewardjf9d2f9b2006-11-17 20:00:57 +00003176 r = valgrind_main( (Int)argc, argv, envp );
sewardj17c11042006-10-15 01:26:40 +00003177 /* NOTREACHED */
sewardj45f4e7c2005-09-27 19:20:21 +00003178 VG_(exit)(r);
3179}
3180
sewardj17c11042006-10-15 01:26:40 +00003181
3182/*====================================================================*/
njnf76d27a2009-05-28 01:53:07 +00003183/*=== Getting to main() alive: darwin ===*/
3184/*====================================================================*/
3185
3186#elif defined(VGO_darwin)
3187
njnea2d6fd2010-07-01 00:20:20 +00003188/*
3189 Memory layout established by kernel:
3190
3191 0(%esp) argc
3192 4(%esp) argv[0]
3193 ...
3194 argv[argc-1]
3195 NULL
3196 envp[0]
3197 ...
3198 envp[n]
3199 NULL
3200 executable name (presumably, a pointer to it)
3201 NULL
3202
3203 Ditto in the 64-bit case, except all offsets from SP are obviously
3204 twice as large.
3205*/
3206
3207/* The kernel hands control to _start, which extracts the initial
3208 stack pointer and calls onwards to _start_in_C_darwin. This also
3209 switches to the new stack. */
3210#if defined(VGP_x86_darwin)
3211asm("\n"
3212 ".text\n"
3213 ".align 2,0x90\n"
3214 "\t.globl __start\n"
3215 "__start:\n"
3216 /* set up the new stack in %eax */
3217 "\tmovl $_vgPlain_interim_stack, %eax\n"
3218 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
3219 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
3220 "\tsubl $16, %eax\n"
3221 "\tandl $~15, %eax\n"
3222 /* install it, and collect the original one */
3223 "\txchgl %eax, %esp\n"
sewardj69197362012-03-07 16:38:12 +00003224 "\tsubl $12, %esp\n" // keep stack 16 aligned; see #295428
njnea2d6fd2010-07-01 00:20:20 +00003225 /* call _start_in_C_darwin, passing it the startup %esp */
3226 "\tpushl %eax\n"
3227 "\tcall __start_in_C_darwin\n"
3228 "\tint $3\n"
3229 "\tint $3\n"
3230);
3231#elif defined(VGP_amd64_darwin)
3232asm("\n"
3233 ".text\n"
3234 "\t.globl __start\n"
3235 ".align 3,0x90\n"
3236 "__start:\n"
3237 /* set up the new stack in %rdi */
3238 "\tmovabsq $_vgPlain_interim_stack, %rdi\n"
3239 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
3240 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
3241 "\tandq $~15, %rdi\n"
3242 /* install it, and collect the original one */
3243 "\txchgq %rdi, %rsp\n"
3244 /* call _start_in_C_darwin, passing it the startup %rsp */
3245 "\tcall __start_in_C_darwin\n"
3246 "\tint $3\n"
3247 "\tint $3\n"
3248);
3249#endif
3250
njnf76d27a2009-05-28 01:53:07 +00003251void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2);
3252void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2) {
3253 // skip check
3254 return VG_(memcpy)(dest,src,n);
3255}
3256void* __memset_chk(void *s, int c, SizeT n, SizeT n2);
3257void* __memset_chk(void *s, int c, SizeT n, SizeT n2) {
3258 // skip check
3259 return VG_(memset)(s,c,n);
3260}
3261void bzero(void *s, SizeT n);
3262void bzero(void *s, SizeT n) {
3263 VG_(memset)(s,0,n);
3264}
3265
3266void* memcpy(void *dest, const void *src, SizeT n);
3267void* memcpy(void *dest, const void *src, SizeT n) {
3268 return VG_(memcpy)(dest,src,n);
3269}
3270void* memset(void *s, int c, SizeT n);
3271void* memset(void *s, int c, SizeT n) {
3272 return VG_(memset)(s,c,n);
3273}
3274
njnf76d27a2009-05-28 01:53:07 +00003275/* Avoid compiler warnings: this fn _is_ used, but labelling it
3276 'static' causes gcc to complain it isn't. */
3277void _start_in_C_darwin ( UWord* pArgc );
3278void _start_in_C_darwin ( UWord* pArgc )
3279{
3280 Int r;
njnea2d6fd2010-07-01 00:20:20 +00003281 Int argc = *(Int *)pArgc; // not pArgc[0] on LP64
njnf76d27a2009-05-28 01:53:07 +00003282 HChar** argv = (HChar**)&pArgc[1];
3283 HChar** envp = (HChar**)&pArgc[1+argc+1];
3284
philippe854be4c2013-10-22 21:20:14 +00003285 // See _start_in_C_linux
3286 INNER_REQUEST
3287 ((void) VALGRIND_STACK_REGISTER
3288 (&VG_(interim_stack).bytes[0],
3289 &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack))));
3290
njnf76d27a2009-05-28 01:53:07 +00003291 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3292 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3293
3294 the_iicii.sp_at_startup = (Addr)pArgc;
3295
3296 r = valgrind_main( (Int)argc, argv, envp );
3297 /* NOTREACHED */
3298 VG_(exit)(r);
3299}
3300
3301
njn49f80e82009-05-21 01:25:43 +00003302#else
3303
3304# error "Unknown OS"
3305#endif
sewardj17c11042006-10-15 01:26:40 +00003306
3307
sewardj0af71bb2010-07-01 14:50:30 +00003308/*====================================================================*/
3309/*=== {u,}{div,mod}di3 replacements ===*/
3310/*====================================================================*/
njnea2d6fd2010-07-01 00:20:20 +00003311
3312/* For static linking on x86-darwin, we need to supply our own 64-bit
3313 integer division code, else the link dies thusly:
3314
3315 ld_classic: Undefined symbols:
3316 ___udivdi3
3317 ___umoddi3
3318*/
3319#if defined(VGP_x86_darwin)
3320
3321/* Routines for doing signed/unsigned 64 x 64 ==> 64 div and mod
3322 (udivdi3, umoddi3, divdi3, moddi3) using only 32 x 32 ==> 32
3323 division. Cobbled together from
3324
3325 http://www.hackersdelight.org/HDcode/divlu.c
3326 http://www.hackersdelight.org/HDcode/divls.c
3327 http://www.hackersdelight.org/HDcode/newCode/divDouble.c
3328
3329 The code from those three files is covered by the following license,
3330 as it appears at:
3331
3332 http://www.hackersdelight.org/permissions.htm
3333
3334 You are free to use, copy, and distribute any of the code on
3335 this web site, whether modified by you or not. You need not give
3336 attribution. This includes the algorithms (some of which appear
3337 in Hacker's Delight), the Hacker's Assistant, and any code
3338 submitted by readers. Submitters implicitly agree to this.
3339*/
3340
3341/* Long division, unsigned (64/32 ==> 32).
3342 This procedure performs unsigned "long division" i.e., division of a
334364-bit unsigned dividend by a 32-bit unsigned divisor, producing a
334432-bit quotient. In the overflow cases (divide by 0, or quotient
3345exceeds 32 bits), it returns a remainder of 0xFFFFFFFF (an impossible
3346value).
3347 The dividend is u1 and u0, with u1 being the most significant word.
3348The divisor is parameter v. The value returned is the quotient.
3349 Max line length is 57, to fit in hacker.book. */
3350
3351static Int nlz32(UInt x)
3352{
3353 Int n;
3354 if (x == 0) return(32);
3355 n = 0;
3356 if (x <= 0x0000FFFF) {n = n +16; x = x <<16;}
3357 if (x <= 0x00FFFFFF) {n = n + 8; x = x << 8;}
3358 if (x <= 0x0FFFFFFF) {n = n + 4; x = x << 4;}
3359 if (x <= 0x3FFFFFFF) {n = n + 2; x = x << 2;}
3360 if (x <= 0x7FFFFFFF) {n = n + 1;}
3361 return n;
3362}
3363
3364/* 64 x 32 ==> 32 unsigned division, using only 32 x 32 ==> 32
3365 division as a primitive. */
3366static UInt divlu2(UInt u1, UInt u0, UInt v, UInt *r)
3367{
3368 const UInt b = 65536; // Number base (16 bits).
3369 UInt un1, un0, // Norm. dividend LSD's.
3370 vn1, vn0, // Norm. divisor digits.
3371 q1, q0, // Quotient digits.
3372 un32, un21, un10, // Dividend digit pairs.
3373 rhat; // A remainder.
3374 Int s; // Shift amount for norm.
3375
3376 if (u1 >= v) { // If overflow, set rem.
3377 if (r != NULL) // to an impossible value,
3378 *r = 0xFFFFFFFF; // and return the largest
3379 return 0xFFFFFFFF;} // possible quotient.
3380
3381 s = nlz32(v); // 0 <= s <= 31.
3382 v = v << s; // Normalize divisor.
3383 vn1 = v >> 16; // Break divisor up into
3384 vn0 = v & 0xFFFF; // two 16-bit digits.
3385
3386 un32 = (u1 << s) | ((u0 >> (32 - s)) & (-s >> 31));
3387 un10 = u0 << s; // Shift dividend left.
3388
3389 un1 = un10 >> 16; // Break right half of
3390 un0 = un10 & 0xFFFF; // dividend into two digits.
3391
3392 q1 = un32/vn1; // Compute the first
3393 rhat = un32 - q1*vn1; // quotient digit, q1.
3394 again1:
3395 if (q1 >= b || q1*vn0 > b*rhat + un1) {
3396 q1 = q1 - 1;
3397 rhat = rhat + vn1;
3398 if (rhat < b) goto again1;}
3399
3400 un21 = un32*b + un1 - q1*v; // Multiply and subtract.
3401
3402 q0 = un21/vn1; // Compute the second
3403 rhat = un21 - q0*vn1; // quotient digit, q0.
3404 again2:
3405 if (q0 >= b || q0*vn0 > b*rhat + un0) {
3406 q0 = q0 - 1;
3407 rhat = rhat + vn1;
3408 if (rhat < b) goto again2;}
3409
3410 if (r != NULL) // If remainder is wanted,
3411 *r = (un21*b + un0 - q0*v) >> s; // return it.
3412 return q1*b + q0;
3413}
3414
3415
3416/* 64 x 32 ==> 32 signed division, using only 32 x 32 ==> 32 division
3417 as a primitive. */
3418static Int divls(Int u1, UInt u0, Int v, Int *r)
3419{
3420 Int q, uneg, vneg, diff, borrow;
3421
3422 uneg = u1 >> 31; // -1 if u < 0.
3423 if (uneg) { // Compute the absolute
3424 u0 = -u0; // value of the dividend u.
3425 borrow = (u0 != 0);
3426 u1 = -u1 - borrow;}
3427
3428 vneg = v >> 31; // -1 if v < 0.
3429 v = (v ^ vneg) - vneg; // Absolute value of v.
3430
3431 if ((UInt)u1 >= (UInt)v) goto overflow;
3432
3433 q = divlu2(u1, u0, v, (UInt *)r);
3434
3435 diff = uneg ^ vneg; // Negate q if signs of
3436 q = (q ^ diff) - diff; // u and v differed.
3437 if (uneg && r != NULL)
3438 *r = -*r;
3439
3440 if ((diff ^ q) < 0 && q != 0) { // If overflow,
3441 overflow: // set remainder
3442 if (r != NULL) // to an impossible value,
3443 *r = 0x80000000; // and return the largest
3444 q = 0x80000000;} // possible neg. quotient.
3445 return q;
3446}
3447
3448
3449
3450/* This file contains a program for doing 64/64 ==> 64 division, on a
3451machine that does not have that instruction but that does have
3452instructions for "long division" (64/32 ==> 32). Code for unsigned
3453division is given first, followed by a simple program for doing the
3454signed version by using the unsigned version.
3455 These programs are useful in implementing "long long" (64-bit)
3456arithmetic on a machine that has the long division instruction. It will
3457work on 64- and 32-bit machines, provided the compiler implements long
3458long's (64-bit integers). It is desirable that the machine have the
3459Count Leading Zeros instruction.
3460 In the GNU world, these programs are known as __divdi3 and __udivdi3,
3461and similar names are used here.
3462 This material is not in HD, but may be in a future edition.
3463Max line length is 57, to fit in hacker.book. */
3464
3465
3466static Int nlz64(ULong x)
3467{
3468 Int n;
3469 if (x == 0) return(64);
3470 n = 0;
3471 if (x <= 0x00000000FFFFFFFFULL) {n = n + 32; x = x << 32;}
3472 if (x <= 0x0000FFFFFFFFFFFFULL) {n = n + 16; x = x << 16;}
3473 if (x <= 0x00FFFFFFFFFFFFFFULL) {n = n + 8; x = x << 8;}
3474 if (x <= 0x0FFFFFFFFFFFFFFFULL) {n = n + 4; x = x << 4;}
3475 if (x <= 0x3FFFFFFFFFFFFFFFULL) {n = n + 2; x = x << 2;}
3476 if (x <= 0x7FFFFFFFFFFFFFFFULL) {n = n + 1;}
3477 return n;
3478}
3479
3480// ---------------------------- udivdi3 --------------------------------
3481
3482 /* The variables u0, u1, etc. take on only 32-bit values, but they
3483 are declared long long to avoid some compiler warning messages and to
3484 avoid some unnecessary EXTRs that the compiler would put in, to
3485 convert long longs to ints.
3486
3487 First the procedure takes care of the case in which the divisor is a
3488 32-bit quantity. There are two subcases: (1) If the left half of the
3489 dividend is less than the divisor, one execution of DIVU is all that
3490 is required (overflow is not possible). (2) Otherwise it does two
3491 divisions, using the grade school method, with variables used as
3492 suggested below.
3493
3494 q1 q0
3495 ________
3496 v) u1 u0
3497 q1*v
3498 ____
3499 k u0 */
3500
3501/* These macros must be used with arguments of the appropriate type
3502(unsigned long long for DIVU and long long for DIVS. They are
3503simulations of the presumed machines ops. I.e., they look at only the
3504low-order 32 bits of the divisor, they return garbage if the division
3505overflows, and they return garbage in the high-order half of the
3506quotient doubleword.
3507 In practice, these would be replaced with uses of the machine's DIVU
3508and DIVS instructions (e.g., by using the GNU "asm" facility). */
3509
3510static UInt DIVU ( ULong u, UInt v )
3511{
3512 UInt uHi = (UInt)(u >> 32);
3513 UInt uLo = (UInt)u;
3514 return divlu2(uHi, uLo, v, NULL);
3515}
3516
3517static Int DIVS ( Long u, Int v )
3518{
3519 Int uHi = (Int)(u >> 32);
3520 UInt uLo = (UInt)u;
3521 return divls(uHi, uLo, v, NULL);
3522}
3523
3524/* 64 x 64 ==> 64 unsigned division, using only 32 x 32 ==> 32
3525 division as a primitive. */
3526static ULong udivdi3(ULong u, ULong v)
3527{
3528 ULong u0, u1, v1, q0, q1, k, n;
3529
3530 if (v >> 32 == 0) { // If v < 2**32:
3531 if (u >> 32 < v) // If u/v cannot overflow,
3532 return DIVU(u, v) // just do one division.
3533 & 0xFFFFFFFF;
3534 else { // If u/v would overflow:
3535 u1 = u >> 32; // Break u up into two
3536 u0 = u & 0xFFFFFFFF; // halves.
3537 q1 = DIVU(u1, v) // First quotient digit.
3538 & 0xFFFFFFFF;
3539 k = u1 - q1*v; // First remainder, < v.
3540 q0 = DIVU((k << 32) + u0, v) // 2nd quot. digit.
3541 & 0xFFFFFFFF;
3542 return (q1 << 32) + q0;
3543 }
3544 }
3545 // Here v >= 2**32.
3546 n = nlz64(v); // 0 <= n <= 31.
3547 v1 = (v << n) >> 32; // Normalize the divisor
3548 // so its MSB is 1.
3549 u1 = u >> 1; // To ensure no overflow.
3550 q1 = DIVU(u1, v1) // Get quotient from
3551 & 0xFFFFFFFF; // divide unsigned insn.
3552 q0 = (q1 << n) >> 31; // Undo normalization and
3553 // division of u by 2.
3554 if (q0 != 0) // Make q0 correct or
3555 q0 = q0 - 1; // too small by 1.
3556 if ((u - q0*v) >= v)
3557 q0 = q0 + 1; // Now q0 is correct.
3558 return q0;
3559}
3560
3561
3562// ----------------------------- divdi3 --------------------------------
3563
3564/* This routine presumes that smallish cases (those which can be done in
3565one execution of DIVS) are common. If this is not the case, the test for
3566this case should be deleted.
3567 Note that the test for when DIVS can be used is not entirely
3568accurate. For example, DIVS is not used if v = 0xFFFFFFFF8000000,
3569whereas if could be (if u is sufficiently small in magnitude). */
3570
3571// ------------------------------ cut ----------------------------------
3572
3573static ULong my_llabs ( Long x )
3574{
3575 ULong t = x >> 63;
3576 return (x ^ t) - t;
3577}
3578
3579/* 64 x 64 ==> 64 signed division, using only 32 x 32 ==> 32 division
3580 as a primitive. */
3581static Long divdi3(Long u, Long v)
3582{
3583 ULong au, av;
3584 Long q, t;
3585 au = my_llabs(u);
3586 av = my_llabs(v);
3587 if (av >> 31 == 0) { // If |v| < 2**31 and
3588 // if (v << 32 >> 32 == v) { // If v is in range and
3589 if (au < av << 31) { // |u|/|v| cannot
3590 q = DIVS(u, v); // overflow, use DIVS.
3591 return (q << 32) >> 32;
3592 }
3593 }
3594 q = udivdi3(au,av); // Invoke udivdi3.
3595 t = (u ^ v) >> 63; // If u, v have different
3596 return (q ^ t) - t; // signs, negate q.
3597}
3598
3599// ---------------------------- end cut --------------------------------
3600
sewardj0af71bb2010-07-01 14:50:30 +00003601ULong __udivdi3 (ULong u, ULong v);
njnea2d6fd2010-07-01 00:20:20 +00003602ULong __udivdi3 (ULong u, ULong v)
3603{
3604 return udivdi3(u,v);
3605}
3606
sewardj0af71bb2010-07-01 14:50:30 +00003607Long __divdi3 (Long u, Long v);
njnea2d6fd2010-07-01 00:20:20 +00003608Long __divdi3 (Long u, Long v)
3609{
3610 return divdi3(u,v);
3611}
3612
sewardj0af71bb2010-07-01 14:50:30 +00003613ULong __umoddi3 (ULong u, ULong v);
njnea2d6fd2010-07-01 00:20:20 +00003614ULong __umoddi3 (ULong u, ULong v)
3615{
3616 ULong q = __udivdi3(u, v);
3617 ULong r = u - q * v;
3618 return r;
3619}
3620
sewardj0af71bb2010-07-01 14:50:30 +00003621Long __moddi3 (Long u, Long v);
njnea2d6fd2010-07-01 00:20:20 +00003622Long __moddi3 (Long u, Long v)
3623{
3624 Long q = __divdi3(u, v);
3625 Long r = u - q * v;
3626 return r;
3627}
3628
sewardj70d71c72011-08-23 07:35:42 +00003629/* ------------------------------------------------
3630 ld_classic: Undefined symbols:
3631 ___fixunsdfdi
3632 ------------------------------------------------
3633*/
3634
3635/* ===-- fixunsdfdi.c - Implement __fixunsdfdi -----------------------------===
3636 *
3637 * The LLVM Compiler Infrastructure
3638 *
3639 * This file is dual licensed under the MIT and the University of Illinois Open
3640 * Source Licenses. See LICENSE.TXT for details.
3641 *
3642 * ===----------------------------------------------------------------------===
3643 *
3644 * This file implements __fixunsdfdi for the compiler_rt library.
3645 *
3646 * ===----------------------------------------------------------------------===
3647 */
3648
3649/* As per http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses,
3650
3651 the "NCSA/University of Illinois Open Source License" is compatible
3652 with the GPL (both version 2 and 3). What is claimed to be
3653 compatible is this
3654
3655 http://www.opensource.org/licenses/UoI-NCSA.php
3656
3657 and the LLVM documentation at
3658
3659 http://www.llvm.org/docs/DeveloperPolicy.html#license
3660
3661 says all the code in LLVM is available under the University of
3662 Illinois/NCSA Open Source License, at this URL
3663
3664 http://www.opensource.org/licenses/UoI-NCSA.php
3665
3666 viz, the same one that the FSF pages claim is compatible. So I
3667 think it's OK to include it.
3668*/
3669
3670/* Returns: convert a to a unsigned long long, rounding toward zero.
3671 * Negative values all become zero.
3672 */
3673
3674/* Assumption: double is a IEEE 64 bit floating point type
3675 * du_int is a 64 bit integral type
3676 * value in double is representable in du_int or is negative
3677 * (no range checking performed)
3678 */
3679
3680/* seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm */
3681
3682typedef unsigned long long du_int;
3683typedef unsigned su_int;
3684
3685typedef union
3686{
3687 du_int all;
3688 struct
3689 {
3690#if VG_LITTLEENDIAN
3691 su_int low;
3692 su_int high;
3693#else
3694 su_int high;
3695 su_int low;
3696#endif /* VG_LITTLEENDIAN */
3697 }s;
3698} udwords;
3699
3700typedef union
3701{
3702 udwords u;
3703 double f;
3704} double_bits;
3705
3706du_int __fixunsdfdi(double a);
3707
3708du_int
3709__fixunsdfdi(double a)
3710{
3711 double_bits fb;
3712 fb.f = a;
3713 int e = ((fb.u.s.high & 0x7FF00000) >> 20) - 1023;
3714 if (e < 0 || (fb.u.s.high & 0x80000000))
3715 return 0;
3716 udwords r;
3717 r.s.high = (fb.u.s.high & 0x000FFFFF) | 0x00100000;
3718 r.s.low = fb.u.s.low;
3719 if (e > 52)
3720 r.all <<= (e - 52);
3721 else
3722 r.all >>= (52 - e);
3723 return r.all;
3724}
3725
3726
njnea2d6fd2010-07-01 00:20:20 +00003727#endif
3728
3729
sewardjde4a1d02002-03-22 01:27:54 +00003730/*--------------------------------------------------------------------*/
njn04e16982005-05-31 00:23:43 +00003731/*--- end ---*/
sewardjde4a1d02002-03-22 01:27:54 +00003732/*--------------------------------------------------------------------*/