blob: 1bb7e1fabe33053941f168040e9d5e5cebc5bad2 [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
sewardj03f8d3f2012-08-05 15:46:46 +000010 Copyright (C) 2000-2012 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"
philippe14711e82012-06-14 22:18:50 +000069#include "pub_tool_inner.h"
70#if defined(ENABLE_INNER_CLIENT_REQUEST)
71#include "valgrind.h"
72#endif
sewardj17c11042006-10-15 01:26:40 +000073
sewardjb5f6f512005-03-10 23:59:00 +000074
nethercote71980f02004-01-24 18:18:54 +000075/*====================================================================*/
76/*=== Counters, for profiling purposes only ===*/
77/*====================================================================*/
sewardjde4a1d02002-03-22 01:27:54 +000078
nethercote3a42fb82004-08-03 18:08:50 +000079static void print_all_stats ( void )
nethercote71980f02004-01-24 18:18:54 +000080{
njn42c83552005-12-05 20:45:59 +000081 VG_(print_translation_stats)();
nethercote92e7b7f2004-08-07 17:52:25 +000082 VG_(print_tt_tc_stats)();
nethercote844e7122004-08-02 15:27:22 +000083 VG_(print_scheduler_stats)();
philippef3a6e932013-01-10 20:42:51 +000084 VG_(print_ExeContext_stats)( False /* with_stacktraces */ );
sewardj12ab7652006-10-17 02:10:42 +000085 VG_(print_errormgr_stats)();
njn9271cbc2005-03-13 05:38:25 +000086
nethercote3a42fb82004-08-03 18:08:50 +000087 // Memory stats
nethercote885dd912004-08-03 23:14:00 +000088 if (VG_(clo_verbosity) > 2) {
sewardj738856f2009-07-15 14:48:32 +000089 VG_(message)(Vg_DebugMsg, "\n");
nethercote3a42fb82004-08-03 18:08:50 +000090 VG_(message)(Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +000091 "------ Valgrind's internal memory use stats follow ------\n" );
nethercote885dd912004-08-03 23:14:00 +000092 VG_(sanity_check_malloc_all)();
sewardj738856f2009-07-15 14:48:32 +000093 VG_(message)(Vg_DebugMsg, "------\n" );
nethercote3a42fb82004-08-03 18:08:50 +000094 VG_(print_all_arena_stats)();
sewardj738856f2009-07-15 14:48:32 +000095 VG_(message)(Vg_DebugMsg, "\n");
nethercote3a42fb82004-08-03 18:08:50 +000096 }
nethercote71980f02004-01-24 18:18:54 +000097}
98
99
100/*====================================================================*/
sewardj71bc3cb2005-05-19 00:25:45 +0000101/*=== Command-line: variables, processing, etc ===*/
102/*====================================================================*/
103
104// See pub_{core,tool}_options.h for explanations of all these.
105
sewardj45f4e7c2005-09-27 19:20:21 +0000106static void usage_NORETURN ( Bool debug_help )
njn7cf0bd32002-06-08 13:36:03 +0000107{
florian95a128b2011-09-29 14:26:38 +0000108 /* 'usage1' contains a %s
109 - for the name of the GDB executable
110 - for the name of vgdb's path prefix
111 which must be supplied when they are VG_(printf)'d. */
floriane543f302012-10-21 19:43:43 +0000112 const HChar usage1[] =
njn00cfcfc2005-11-12 18:53:50 +0000113"usage: valgrind [options] prog-and-args\n"
njn25e49d8e72002-09-23 09:36:25 +0000114"\n"
njn97db7612009-08-04 02:32:55 +0000115" tool-selection option, with default in [ ]:\n"
sewardjb5f6f512005-03-10 23:59:00 +0000116" --tool=<name> use the Valgrind tool named <name> [memcheck]\n"
njn97db7612009-08-04 02:32:55 +0000117"\n"
118" basic user options for all Valgrind tools, with defaults in [ ]:\n"
nethercotea76368b2004-06-16 11:56:29 +0000119" -h --help show this message\n"
nethercote6c999f22004-01-31 22:55:15 +0000120" --help-debug show this message, plus debugging options\n"
njn25e49d8e72002-09-23 09:36:25 +0000121" --version show version\n"
njn25e49d8e72002-09-23 09:36:25 +0000122" -q --quiet run silently; only print error msgs\n"
sewardj2d9e8742009-08-07 15:46:56 +0000123" -v --verbose be more verbose -- show misc extra info\n"
sewardj6e31f802007-11-17 22:29:25 +0000124" --trace-children=no|yes Valgrind-ise child processes (follow execve)? [no]\n"
sewardj06421272009-11-05 08:55:13 +0000125" --trace-children-skip=patt1,patt2,... specifies a list of executables\n"
126" that --trace-children=yes should not trace into\n"
sewardj9ab64a42010-12-06 11:40:04 +0000127" --trace-children-skip-by-arg=patt1,patt2,... same as --trace-children-skip=\n"
128" but check the argv[] entries for children, rather\n"
129" than the exe name, to make a follow/no-follow decision\n"
njn97db7612009-08-04 02:32:55 +0000130" --child-silent-after-fork=no|yes omit child output between fork & exec? [no]\n"
sewardj3b290482011-05-06 21:02:55 +0000131" --vgdb=no|yes|full activate gdbserver? [yes]\n"
132" full is slower but provides precise watchpoint/step\n"
sewardj1568e172011-06-18 08:28:04 +0000133" --vgdb-error=<number> invoke gdbserver after <number> errors [%d]\n"
134" to get started quickly, use --vgdb-error=0\n"
135" and follow the on-screen directions\n"
nethercote0d588502004-06-21 13:27:11 +0000136" --track-fds=no|yes track open file descriptors? [no]\n"
thughes6233a382004-08-21 11:10:44 +0000137" --time-stamp=no|yes add timestamps to log messages? [no]\n"
njnce545552005-07-25 22:36:52 +0000138" --log-fd=<number> log messages to file descriptor [2=stderr]\n"
njn374a36d2007-11-23 01:41:32 +0000139" --log-file=<file> log messages to <file>\n"
njnce545552005-07-25 22:36:52 +0000140" --log-socket=ipaddr:port log messages to socket ipaddr:port\n"
nethercote2b0793f2003-12-02 10:41:18 +0000141"\n"
nethercote2b0793f2003-12-02 10:41:18 +0000142" user options for Valgrind tools that report errors:\n"
sewardj738856f2009-07-15 14:48:32 +0000143" --xml=yes emit error output in XML (some tools only)\n"
144" --xml-fd=<number> XML output to file descriptor\n"
145" --xml-file=<file> XML output to <file>\n"
146" --xml-socket=ipaddr:port XML output to socket ipaddr:port\n"
147" --xml-user-comment=STR copy STR verbatim into XML output\n"
nethercote2b0793f2003-12-02 10:41:18 +0000148" --demangle=no|yes automatically demangle C++ names? [yes]\n"
njn20b4a152005-10-19 22:39:40 +0000149" --num-callers=<number> show <number> callers in stack traces [12]\n"
nethercote2b0793f2003-12-02 10:41:18 +0000150" --error-limit=no|yes stop showing new errors if too many? [yes]\n"
sewardjb9779082006-05-12 23:50:15 +0000151" --error-exitcode=<number> exit code to return if errors found [0=disable]\n"
nethercote2b0793f2003-12-02 10:41:18 +0000152" --show-below-main=no|yes continue stack traces below main() [no]\n"
153" --suppressions=<filename> suppress errors described in <filename>\n"
sewardjd153fae2005-01-10 17:24:47 +0000154" --gen-suppressions=no|yes|all print suppressions for errors? [no]\n"
nethercote04d0fbc2004-01-26 16:48:06 +0000155" --db-attach=no|yes start debugger when errors detected? [no]\n"
sewardj7839d112007-11-20 19:45:03 +0000156" --db-command=<command> command to start debugger [%s -nw %%f %%p]\n"
nethercote04d0fbc2004-01-26 16:48:06 +0000157" --input-fd=<number> file descriptor for input [0=stdin]\n"
njn97db7612009-08-04 02:32:55 +0000158" --dsymutil=no|yes run dsymutil on Mac OS X when helpful? [no]\n"
sewardj97724e52005-04-02 23:40:59 +0000159" --max-stackframe=<number> assume stack switch for SP changes larger\n"
160" than <number> bytes [2000000]\n"
sewardj95d86c02007-12-18 01:49:23 +0000161" --main-stacksize=<number> set size of main thread's stack (in bytes)\n"
162" [use current 'ulimit' value]\n"
njn97db7612009-08-04 02:32:55 +0000163"\n"
164" user options for Valgrind tools that replace malloc:\n"
philipped99c26a2012-07-31 22:17:28 +0000165" --alignment=<number> set minimum alignment of heap allocations [%s]\n"
166" --redzone-size=<number> set minimum size of redzones added before/after\n"
167" heap blocks (in bytes). [%s]\n"
njn97db7612009-08-04 02:32:55 +0000168"\n"
169" uncommon user options for all Valgrind tools:\n"
sewardj14cdbf82010-10-12 00:44:05 +0000170" --fullpath-after= (with nothing after the '=')\n"
171" show full source paths in call stacks\n"
172" --fullpath-after=string like --fullpath-after=, but only show the\n"
173" part of the path after 'string'. Allows removal\n"
174" of path prefixes. Use this flag multiple times\n"
175" to specify a set of prefixes to remove.\n"
sewardj8b6573d2012-12-05 22:15:14 +0000176" --extra-debuginfo-path=path absolute path to search for additional\n"
177" debug symbols, in addition to existing default\n"
178" well known search paths.\n"
sewardj6dbcc632011-06-07 21:39:28 +0000179" --smc-check=none|stack|all|all-non-file [stack]\n"
180" checks for self-modifying code: none, only for\n"
181" code found in stacks, for all code, or for all\n"
182" code except that from file-backed mappings\n"
njn97db7612009-08-04 02:32:55 +0000183" --read-var-info=yes|no read debug info on stack and global variables\n"
184" and use it to print better error messages in\n"
185" tools that make use of it (Memcheck, Helgrind,\n"
bartf6122a02010-03-27 07:38:39 +0000186" DRD) [no]\n"
sewardj3b290482011-05-06 21:02:55 +0000187" --vgdb-poll=<number> gdbserver poll max every <number> basic blocks [%d] \n"
188" --vgdb-shadow-registers=no|yes let gdb see the shadow registers [no]\n"
189" --vgdb-prefix=<prefix> prefix for vgdb FIFOs [%s]\n"
njn97db7612009-08-04 02:32:55 +0000190" --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]\n"
191" --sim-hints=hint1,hint2,... known hints:\n"
sewardjcc3de2d2011-08-18 15:08:20 +0000192" lax-ioctls, enable-outer, fuse-compatible [none]\n"
bart78bfc712011-12-08 16:14:59 +0000193" --fair-sched=no|yes|try schedule threads fairly on multicore systems [no]\n"
njn97db7612009-08-04 02:32:55 +0000194" --kernel-variant=variant1,variant2,... known variants: bproc [none]\n"
195" handle non-standard kernel variants\n"
philippe46207652013-01-20 17:11:58 +0000196" --merge-recursive-frames=<number> merge frames between identical\n"
197" program counters in max <number> frames) [0]\n"
njn97db7612009-08-04 02:32:55 +0000198" --show-emwarns=no|yes show warnings about emulation limits? [no]\n"
sewardjf9ebc392010-05-09 22:30:43 +0000199" --require-text-symbol=:sonamepattern:symbolpattern abort run if the\n"
200" stated shared object doesn't have the stated\n"
201" text symbol. Patterns can contain ? and *.\n"
philippe1e470b52012-05-11 19:33:46 +0000202" --soname-synonyms=syn1=pattern1,syn2=pattern2,... synonym soname\n"
sewardj260c6482012-08-07 14:46:34 +0000203" specify patterns for function wrapping or replacement.\n"
204" To use a non-libc malloc library that is\n"
205" in the main exe: --soname-synonyms=somalloc=NONE\n"
206" in libxyzzy.so: --soname-synonyms=somalloc=libxyzzy.so\n"
sewardjc30cd9b2012-12-06 18:08:54 +0000207" --sigill-diagnostics=yes|no warn about illegal instructions? [yes]\n"
fitzhardinge98abfc72003-12-16 02:05:15 +0000208"\n";
njn7cf0bd32002-06-08 13:36:03 +0000209
floriane543f302012-10-21 19:43:43 +0000210 const HChar usage2[] =
njn25e49d8e72002-09-23 09:36:25 +0000211"\n"
nethercote2b0793f2003-12-02 10:41:18 +0000212" debugging options for all Valgrind tools:\n"
njn97db7612009-08-04 02:32:55 +0000213" -d show verbose debugging output\n"
njnb1cc5d62010-07-06 04:05:23 +0000214" --stats=no|yes show tool and core statistics [no]\n"
njn25e49d8e72002-09-23 09:36:25 +0000215" --sanity-level=<number> level of sanity checking to do [1]\n"
sewardjfa8ec112005-01-19 11:55:34 +0000216" --trace-flags=<XXXXXXXX> show generated code? (X = 0|1) [00000000]\n"
217" --profile-flags=<XXXXXXXX> ditto, but for profiling (X = 0|1) [00000000]\n"
sewardj17c5e2e2012-12-28 09:12:14 +0000218" --profile-interval=<number> show profile every <number> event checks\n"
219" [0, meaning only at the end of the run]\n"
sewardj33afdb52006-01-17 02:36:40 +0000220" --trace-notbelow=<number> only show BBs above <number> [999999999]\n"
florian29e022d2012-07-02 21:13:34 +0000221" --trace-notabove=<number> only show BBs below <number> [0]\n"
njn25e49d8e72002-09-23 09:36:25 +0000222" --trace-syscalls=no|yes show all system calls? [no]\n"
223" --trace-signals=no|yes show signal handling details? [no]\n"
224" --trace-symtab=no|yes show symbol table details? [no]\n"
sewardjf767d962007-02-12 17:47:14 +0000225" --trace-symtab-patt=<patt> limit debuginfo tracing to obj name <patt>\n"
sewardjce058b02005-05-01 08:55:38 +0000226" --trace-cfi=no|yes show call-frame-info details? [no]\n"
sewardjf767d962007-02-12 17:47:14 +0000227" --debug-dump=syms mimic /usr/bin/readelf --syms\n"
228" --debug-dump=line mimic /usr/bin/readelf --debug-dump=line\n"
229" --debug-dump=frames mimic /usr/bin/readelf --debug-dump=frames\n"
sewardj0ec07f32006-01-12 12:32:32 +0000230" --trace-redir=no|yes show redirection details? [no]\n"
njn25e49d8e72002-09-23 09:36:25 +0000231" --trace-sched=no|yes show thread scheduler details? [no]\n"
sewardj9c606bd2008-09-18 18:12:50 +0000232" --profile-heap=no|yes profile Valgrind's own space use\n"
philippe06444372012-10-12 21:46:55 +0000233" --core-redzone-size=<number> set minimum size of redzones added before/after\n"
philipped99c26a2012-07-31 22:17:28 +0000234" heap blocks allocated for Valgrind internal use (in bytes) [4]\n"
jsgf855d93d2003-10-13 22:26:55 +0000235" --wait-for-gdb=yes|no pause on startup to wait for gdb attach\n"
sewardj17c11042006-10-15 01:26:40 +0000236" --sym-offsets=yes|no show syms in form 'name+offset' ? [no]\n"
sewardjb5f6f512005-03-10 23:59:00 +0000237" --command-line-only=no|yes only use command line options [no]\n"
njn613812e2005-03-11 04:57:30 +0000238"\n"
njn97db7612009-08-04 02:32:55 +0000239" Vex options for all Valgrind tools:\n"
240" --vex-iropt-verbosity=<0..9> [0]\n"
241" --vex-iropt-level=<0..2> [2]\n"
philippe5b240c22012-08-14 22:28:31 +0000242" --vex-iropt-register-updates=sp-at-mem-access\n"
243" |unwindregs-at-mem-access\n"
philippe0c0291a2012-08-01 22:03:12 +0000244" |allregs-at-mem-access\n"
245" |allregs-at-each-insn [unwindregs-at-mem-access]\n"
njn97db7612009-08-04 02:32:55 +0000246" --vex-iropt-unroll-thresh=<0..400> [120]\n"
247" --vex-guest-max-insns=<1..100> [50]\n"
248" --vex-guest-chase-thresh=<0..99> [10]\n"
sewardj540cc4a2010-01-15 10:57:57 +0000249" --vex-guest-chase-cond=no|yes [no]\n"
sewardjfa8ec112005-01-19 11:55:34 +0000250" --trace-flags and --profile-flags values (omit the middle space):\n"
sewardj2a99cf62004-11-24 10:44:19 +0000251" 1000 0000 show conversion into IR\n"
252" 0100 0000 show after initial opt\n"
253" 0010 0000 show after instrumentation\n"
254" 0001 0000 show after second opt\n"
255" 0000 1000 show after tree building\n"
256" 0000 0100 show selecting insns\n"
257" 0000 0010 show after reg-alloc\n"
258" 0000 0001 show final assembly\n"
sewardj17c5e2e2012-12-28 09:12:14 +0000259" 0000 0000 show summary profile only\n"
260" (Nb: you need --trace-notbelow and/or --trace-notabove "
261" with --trace-flags for full details)\n"
sewardj2a99cf62004-11-24 10:44:19 +0000262"\n"
nethercote2b0793f2003-12-02 10:41:18 +0000263" debugging options for Valgrind tools that report errors\n"
264" --dump-error=<number> show translation for basic block associated\n"
265" with <number>'th error context [0=show none]\n"
njn97db7612009-08-04 02:32:55 +0000266"\n"
267" debugging options for Valgrind tools that replace malloc:\n"
268" --trace-malloc=no|yes show client malloc details? [no]\n"
fitzhardinge98abfc72003-12-16 02:05:15 +0000269"\n";
njn3e884182003-04-15 13:03:23 +0000270
floriane543f302012-10-21 19:43:43 +0000271 const HChar usage3[] =
njn3e884182003-04-15 13:03:23 +0000272"\n"
nethercote71980f02004-01-24 18:18:54 +0000273" Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc\n"
njn25e49d8e72002-09-23 09:36:25 +0000274"\n"
njn10b9aea2009-07-14 06:55:05 +0000275" %s is %s\n"
sewardj03f8d3f2012-08-05 15:46:46 +0000276" Valgrind is Copyright (C) 2000-2012, and GNU GPL'd, by Julian Seward et al.\n"
277" LibVEX is Copyright (C) 2004-2012, and GNU GPL'd, by OpenWorks LLP et al.\n"
njnd04b7c62002-10-03 14:05:52 +0000278"\n"
njn10b9aea2009-07-14 06:55:05 +0000279" Bug reports, feedback, admiration, abuse, etc, to: %s.\n"
njn25e49d8e72002-09-23 09:36:25 +0000280"\n";
njn7cf0bd32002-06-08 13:36:03 +0000281
floriane6a4ed12012-10-21 02:30:18 +0000282 const HChar* gdb_path = GDB_PATH;
florian19f91bb2012-11-10 22:29:54 +0000283 HChar default_alignment[30];
284 HChar default_redzone_size[30];
sewardj12373b12007-11-20 21:38:14 +0000285
njnbe9b47b2005-05-15 16:22:58 +0000286 // Ensure the message goes to stdout
sewardj738856f2009-07-15 14:48:32 +0000287 VG_(log_output_sink).fd = 1;
288 VG_(log_output_sink).is_socket = False;
njnbe9b47b2005-05-15 16:22:58 +0000289
philipped99c26a2012-07-31 22:17:28 +0000290 if (VG_(needs).malloc_replacement) {
291 VG_(sprintf)(default_alignment, "%d", VG_MIN_MALLOC_SZB);
292 VG_(sprintf)(default_redzone_size, "%lu", VG_(tdict).tool_client_redzone_szB);
293 } else {
294 VG_(strcpy)(default_alignment, "not used by this tool");
295 VG_(strcpy)(default_redzone_size, "not used by this tool");
296 }
297 /* 'usage1' a type as described after each arg. */
sewardj3b290482011-05-06 21:02:55 +0000298 VG_(printf)(usage1,
philipped99c26a2012-07-31 22:17:28 +0000299 VG_(clo_vgdb_error) /* int */,
300 gdb_path /* char* */,
301 default_alignment /* char* */,
302 default_redzone_size /* char* */,
303 VG_(clo_vgdb_poll) /* int */,
304 VG_(vgdb_prefix_default)() /* char* */
305 );
fitzhardinge98abfc72003-12-16 02:05:15 +0000306 if (VG_(details).name) {
307 VG_(printf)(" user options for %s:\n", VG_(details).name);
fitzhardinge98abfc72003-12-16 02:05:15 +0000308 if (VG_(needs).command_line_options)
njn51d827b2005-05-09 01:02:08 +0000309 VG_TDICT_CALL(tool_print_usage);
fitzhardinge98abfc72003-12-16 02:05:15 +0000310 else
311 VG_(printf)(" (none)\n");
312 }
nethercote6c999f22004-01-31 22:55:15 +0000313 if (debug_help) {
sewardjbbaef872008-11-01 23:55:32 +0000314 VG_(printf)("%s", usage2);
fitzhardinge98abfc72003-12-16 02:05:15 +0000315
nethercote6c999f22004-01-31 22:55:15 +0000316 if (VG_(details).name) {
317 VG_(printf)(" debugging options for %s:\n", VG_(details).name);
318
319 if (VG_(needs).command_line_options)
njn51d827b2005-05-09 01:02:08 +0000320 VG_TDICT_CALL(tool_print_debug_usage);
nethercote6c999f22004-01-31 22:55:15 +0000321 else
322 VG_(printf)(" (none)\n");
323 }
fitzhardinge98abfc72003-12-16 02:05:15 +0000324 }
njn10b9aea2009-07-14 06:55:05 +0000325 VG_(printf)(usage3, VG_(details).name, VG_(details).copyright_author,
326 VG_BUGS_TO);
nethercotef4928da2004-06-15 10:54:40 +0000327 VG_(exit)(0);
njn7cf0bd32002-06-08 13:36:03 +0000328}
sewardjde4a1d02002-03-22 01:27:54 +0000329
sewardjde4a1d02002-03-22 01:27:54 +0000330
sewardj95d86c02007-12-18 01:49:23 +0000331/* Peer at previously set up VG_(args_for_valgrind) and do some
332 minimal command line processing that must happen early on:
sewardj45f4e7c2005-09-27 19:20:21 +0000333
sewardj95d86c02007-12-18 01:49:23 +0000334 - show the version string, if requested (-v)
335 - extract any request for help (--help, -h, --help-debug)
336 - get the toolname (--tool=)
337 - set VG_(clo_max_stackframe) (--max-stackframe=)
338 - set VG_(clo_main_stacksize) (--main-stacksize=)
philippe72faf102012-03-11 22:24:03 +0000339 - set VG_(clo_sim_hints) (--sim-hints=)
sewardj95d86c02007-12-18 01:49:23 +0000340
341 That's all it does. The main command line processing is done below
342 by main_process_cmd_line_options. Note that
343 main_process_cmd_line_options has to handle but ignore the ones we
344 have handled here.
345*/
346static void early_process_cmd_line_options ( /*OUT*/Int* need_help,
florian19f91bb2012-11-10 22:29:54 +0000347 /*OUT*/const HChar** tool )
sewardj45f4e7c2005-09-27 19:20:21 +0000348{
349 UInt i;
350 HChar* str;
sewardj8b635a42004-11-22 19:01:47 +0000351
sewardj14c7cc52007-02-25 15:08:24 +0000352 vg_assert( VG_(args_for_valgrind) );
nethercote71980f02004-01-24 18:18:54 +0000353
sewardj14c7cc52007-02-25 15:08:24 +0000354 /* parse the options we have (only the options we care about now) */
355 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
356
357 str = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
sewardj45f4e7c2005-09-27 19:20:21 +0000358 vg_assert(str);
nethercote71980f02004-01-24 18:18:54 +0000359
njn83df0b62009-02-25 01:01:05 +0000360 // Nb: the version string goes to stdout.
sewardj738856f2009-07-15 14:48:32 +0000361 if VG_XACT_CLO(str, "--version", VG_(log_output_sink).fd, 1) {
362 VG_(log_output_sink).is_socket = False;
sewardj45f4e7c2005-09-27 19:20:21 +0000363 VG_(printf)("valgrind-" VERSION "\n");
364 VG_(exit)(0);
njn83df0b62009-02-25 01:01:05 +0000365 }
njncce38e62010-07-06 04:25:12 +0000366 else if VG_XACT_CLO(str, "--help", *need_help, *need_help+1) {}
367 else if VG_XACT_CLO(str, "-h", *need_help, *need_help+1) {}
sewardj45f4e7c2005-09-27 19:20:21 +0000368
njncce38e62010-07-06 04:25:12 +0000369 else if VG_XACT_CLO(str, "--help-debug", *need_help, *need_help+2) {}
nethercote71980f02004-01-24 18:18:54 +0000370
sewardj45f4e7c2005-09-27 19:20:21 +0000371 // The tool has already been determined, but we need to know the name
372 // here.
njn83df0b62009-02-25 01:01:05 +0000373 else if VG_STR_CLO(str, "--tool", *tool) {}
sewardj5bdfbd22007-12-15 22:13:05 +0000374
sewardj95d86c02007-12-18 01:49:23 +0000375 // Set up VG_(clo_max_stackframe) and VG_(clo_main_stacksize).
376 // These are needed by VG_(ii_create_image), which happens
377 // before main_process_cmd_line_options().
njn83df0b62009-02-25 01:01:05 +0000378 else if VG_INT_CLO(str, "--max-stackframe", VG_(clo_max_stackframe)) {}
379 else if VG_INT_CLO(str, "--main-stacksize", VG_(clo_main_stacksize)) {}
philippe72faf102012-03-11 22:24:03 +0000380
381 // Set up VG_(clo_sim_hints). This is needed a.o. for an inner
382 // running in an outer, to have "no-inner-prefix" enabled
383 // as early as possible.
384 else if VG_STR_CLO (str, "--sim-hints", VG_(clo_sim_hints)) {}
nethercote71980f02004-01-24 18:18:54 +0000385 }
nethercote71980f02004-01-24 18:18:54 +0000386}
387
sewardj95d86c02007-12-18 01:49:23 +0000388/* The main processing for command line options. See comments above
sewardj738856f2009-07-15 14:48:32 +0000389 on early_process_cmd_line_options.
390
391 Comments on how the logging options are handled:
392
393 User can specify:
394 --log-fd= for a fd to write to (default setting, fd = 2)
395 --log-file= for a file name to write to
396 --log-socket= for a socket to write to
397
398 As a result of examining these and doing relevant socket/file
399 opening, a final fd is established. This is stored in
400 VG_(log_output_sink) in m_libcprint. Also, if --log-file=STR was
401 specified, then STR, after expansion of %p and %q templates within
402 it, is stored in VG_(clo_log_fname_expanded), in m_options, just in
403 case anybody wants to know what it is.
404
405 When printing, VG_(log_output_sink) is consulted to find the
406 fd to send output to.
407
408 Exactly analogous actions are undertaken for the XML output
409 channel, with the one difference that the default fd is -1, meaning
410 the channel is disabled by default.
sewardj95d86c02007-12-18 01:49:23 +0000411*/
sewardj738856f2009-07-15 14:48:32 +0000412static
413void main_process_cmd_line_options ( /*OUT*/Bool* logging_to_fd,
florian19f91bb2012-11-10 22:29:54 +0000414 /*OUT*/HChar** xml_fname_unexpanded,
sewardj738856f2009-07-15 14:48:32 +0000415 const HChar* toolname )
nethercote71980f02004-01-24 18:18:54 +0000416{
njnda033f52005-12-19 21:27:58 +0000417 // VG_(clo_log_fd) is used by all the messaging. It starts as 2 (stderr)
418 // and we cannot change it until we know what we are changing it to is
419 // ok. So we have tmp_log_fd to hold the tmp fd prior to that point.
sewardj92645592005-07-23 09:18:34 +0000420 SysRes sres;
sewardj738856f2009-07-15 14:48:32 +0000421 Int i, tmp_log_fd, tmp_xml_fd;
sewardj92645592005-07-23 09:18:34 +0000422 Int toolname_len = VG_(strlen)(toolname);
florian19f91bb2012-11-10 22:29:54 +0000423 const HChar* tmp_str; // Used in a couple of places.
njnbe9b47b2005-05-15 16:22:58 +0000424 enum {
425 VgLogTo_Fd,
426 VgLogTo_File,
njnbe9b47b2005-05-15 16:22:58 +0000427 VgLogTo_Socket
sewardj738856f2009-07-15 14:48:32 +0000428 } log_to = VgLogTo_Fd, // Where is logging output to be sent?
429 xml_to = VgLogTo_Fd; // Where is XML output to be sent?
sewardjde4a1d02002-03-22 01:27:54 +0000430
sewardj738856f2009-07-15 14:48:32 +0000431 /* Temporarily holds the string STR specified with
432 --{log,xml}-{name,socket}=STR. 'fs' stands for
433 file-or-socket. */
florian19f91bb2012-11-10 22:29:54 +0000434 const HChar* log_fsname_unexpanded = NULL;
435 const HChar* xml_fsname_unexpanded = NULL;
sewardj738856f2009-07-15 14:48:32 +0000436
sewardjc30cd9b2012-12-06 18:08:54 +0000437 /* Whether the user has explicitly provided --sigill-diagnostics.
438 If not explicitly given depends on general verbosity setting. */
439 Bool sigill_diag_set = False;
440
sewardj738856f2009-07-15 14:48:32 +0000441 /* Log to stderr by default, but usage message goes to stdout. XML
442 output is initially disabled. */
njnda033f52005-12-19 21:27:58 +0000443 tmp_log_fd = 2;
sewardj738856f2009-07-15 14:48:32 +0000444 tmp_xml_fd = -1;
445
sewardj19d81412002-06-03 01:10:40 +0000446 /* Check for sane path in ./configure --prefix=... */
fitzhardinge98abfc72003-12-16 02:05:15 +0000447 if (VG_LIBDIR[0] != '/')
sewardj17c11042006-10-15 01:26:40 +0000448 VG_(err_config_error)("Please use absolute paths in "
florian1763e812011-07-12 19:07:05 +0000449 "./configure --prefix=... or --libdir=...\n");
sewardj38170912002-05-10 21:07:22 +0000450
sewardj14c7cc52007-02-25 15:08:24 +0000451 vg_assert( VG_(args_for_valgrind) );
nethercote71980f02004-01-24 18:18:54 +0000452
sewardj738856f2009-07-15 14:48:32 +0000453 /* BEGIN command-line processing loop */
454
sewardj14c7cc52007-02-25 15:08:24 +0000455 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
456
457 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
sewardj45f4e7c2005-09-27 19:20:21 +0000458 HChar* colon = arg;
nethercote71980f02004-01-24 18:18:54 +0000459
njn1274d242007-03-26 23:38:42 +0000460 // Look for a colon in the option name.
thughes3bfd5a02004-07-18 08:05:44 +0000461 while (*colon && *colon != ':' && *colon != '=')
462 colon++;
nethercote71980f02004-01-24 18:18:54 +0000463
njn1274d242007-03-26 23:38:42 +0000464 // Does it have the form "--toolname:foo"? We have to do it at the start
465 // in case someone has combined a prefix with a core-specific option,
466 // eg. "--memcheck:verbose".
thughes3bfd5a02004-07-18 08:05:44 +0000467 if (*colon == ':') {
njn83df0b62009-02-25 01:01:05 +0000468 if (VG_STREQN(2, arg, "--") &&
469 VG_STREQN(toolname_len, arg+2, toolname) &&
470 VG_STREQN(1, arg+2+toolname_len, ":"))
nethercote71980f02004-01-24 18:18:54 +0000471 {
njn1274d242007-03-26 23:38:42 +0000472 // Prefix matches, convert "--toolname:foo" to "--foo".
473 // Two things to note:
474 // - We cannot modify the option in-place. If we did, and then
475 // a child was spawned with --trace-children=yes, the
476 // now-non-prefixed option would be passed and could screw up
477 // the child.
478 // - We create copies, and never free them. Why? Non-prefixed
479 // options hang around forever, so tools need not make copies
480 // of strings within them. We need to have the same behaviour
481 // for prefixed options. The pointer to the copy will be lost
482 // once we leave this function (although a tool may keep a
483 // pointer into it), but the space wasted is insignificant.
484 // (In bug #142197, the copies were being freed, which caused
485 // problems for tools that reasonably assumed that arguments
486 // wouldn't disappear on them.)
nethercote71980f02004-01-24 18:18:54 +0000487 if (0)
488 VG_(printf)("tool-specific arg: %s\n", arg);
sewardj9c606bd2008-09-18 18:12:50 +0000489 arg = VG_(strdup)("main.mpclo.1", arg + toolname_len + 1);
nethercote71980f02004-01-24 18:18:54 +0000490 arg[0] = '-';
491 arg[1] = '-';
492
493 } else {
494 // prefix doesn't match, skip to next arg
495 continue;
496 }
497 }
498
fitzhardinge98abfc72003-12-16 02:05:15 +0000499 /* Ignore these options - they've already been handled */
njn83df0b62009-02-25 01:01:05 +0000500 if VG_STREQN( 7, arg, "--tool=") {}
501 else if VG_STREQN(20, arg, "--command-line-only=") {}
502 else if VG_STREQ( arg, "--") {}
503 else if VG_STREQ( arg, "-d") {}
philippe06444372012-10-12 21:46:55 +0000504 else if VG_STREQN(17, arg, "--max-stackframe=") {}
505 else if VG_STREQN(17, arg, "--main-stacksize=") {}
506 else if VG_STREQN(12, arg, "--sim-hints=") {}
507 else if VG_STREQN(15, arg, "--profile-heap=") {}
508 else if VG_STREQN(20, arg, "--core-redzone-size=") {}
509 else if VG_STREQN(15, arg, "--redzone-size=") {}
nethercote27fec902004-06-16 21:26:32 +0000510
philippe0c0291a2012-08-01 22:03:12 +0000511 /* Obsolete options. Report an error and exit */
512 else if VG_STREQN(34, arg, "--vex-iropt-precise-memory-exns=no") {
513 VG_(fmsg_bad_option)
514 (arg,
515 "--vex-iropt-precise-memory-exns is obsolete\n"
516 "Use --vex-iropt-register-updates=unwindregs-at-mem-access instead\n");
517 }
518 else if VG_STREQN(35, arg, "--vex-iropt-precise-memory-exns=yes") {
519 VG_(fmsg_bad_option)
520 (arg,
521 "--vex-iropt-precise-memory-exns is obsolete\n"
522 "Use --vex-iropt-register-updates=allregs-at-mem-access instead\n"
523 " (or --vex-iropt-register-updates=allregs-at-each-insn)\n");
524 }
525
njn83df0b62009-02-25 01:01:05 +0000526 // These options are new.
527 else if (VG_STREQ(arg, "-v") ||
528 VG_STREQ(arg, "--verbose"))
sewardjde4a1d02002-03-22 01:27:54 +0000529 VG_(clo_verbosity)++;
nethercote27fec902004-06-16 21:26:32 +0000530
njn83df0b62009-02-25 01:01:05 +0000531 else if (VG_STREQ(arg, "-q") ||
532 VG_STREQ(arg, "--quiet"))
sewardjde4a1d02002-03-22 01:27:54 +0000533 VG_(clo_verbosity)--;
534
sewardjc30cd9b2012-12-06 18:08:54 +0000535 else if VG_BOOL_CLO(arg, "--sigill-diagnostics", VG_(clo_sigill_diag))
536 sigill_diag_set = True;
537
sewardj2d9e8742009-08-07 15:46:56 +0000538 else if VG_BOOL_CLO(arg, "--stats", VG_(clo_stats)) {}
bartdb4384e2011-10-11 18:49:35 +0000539 else if VG_BOOL_CLO(arg, "--xml", VG_(clo_xml))
540 VG_(debugLog_setXml)(VG_(clo_xml));
541
sewardj3b290482011-05-06 21:02:55 +0000542 else if VG_XACT_CLO(arg, "--vgdb=no", VG_(clo_vgdb), Vg_VgdbNo) {}
543 else if VG_XACT_CLO(arg, "--vgdb=yes", VG_(clo_vgdb), Vg_VgdbYes) {}
philippe0c0291a2012-08-01 22:03:12 +0000544 else if VG_XACT_CLO(arg, "--vgdb=full", VG_(clo_vgdb), Vg_VgdbFull) {
545 /* automatically updates register values at each insn
546 with --vgdb=full */
547 VG_(clo_vex_control).iropt_register_updates
548 = VexRegUpdAllregsAtEachInsn;
549 }
sewardj3b290482011-05-06 21:02:55 +0000550 else if VG_INT_CLO (arg, "--vgdb-poll", VG_(clo_vgdb_poll)) {}
551 else if VG_INT_CLO (arg, "--vgdb-error", VG_(clo_vgdb_error)) {}
552 else if VG_STR_CLO (arg, "--vgdb-prefix", VG_(clo_vgdb_prefix)) {}
553 else if VG_BOOL_CLO(arg, "--vgdb-shadow-registers",
554 VG_(clo_vgdb_shadow_registers)) {}
njn83df0b62009-02-25 01:01:05 +0000555 else if VG_BOOL_CLO(arg, "--db-attach", VG_(clo_db_attach)) {}
556 else if VG_BOOL_CLO(arg, "--demangle", VG_(clo_demangle)) {}
philippe1e470b52012-05-11 19:33:46 +0000557 else if VG_STR_CLO (arg, "--soname-synonyms",VG_(clo_soname_synonyms)) {}
njn83df0b62009-02-25 01:01:05 +0000558 else if VG_BOOL_CLO(arg, "--error-limit", VG_(clo_error_limit)) {}
559 else if VG_INT_CLO (arg, "--error-exitcode", VG_(clo_error_exitcode)) {}
560 else if VG_BOOL_CLO(arg, "--show-emwarns", VG_(clo_show_emwarns)) {}
sewardj95d86c02007-12-18 01:49:23 +0000561
njn83df0b62009-02-25 01:01:05 +0000562 else if VG_BOOL_CLO(arg, "--run-libc-freeres", VG_(clo_run_libc_freeres)) {}
563 else if VG_BOOL_CLO(arg, "--show-below-main", VG_(clo_show_below_main)) {}
564 else if VG_BOOL_CLO(arg, "--time-stamp", VG_(clo_time_stamp)) {}
565 else if VG_BOOL_CLO(arg, "--track-fds", VG_(clo_track_fds)) {}
566 else if VG_BOOL_CLO(arg, "--trace-children", VG_(clo_trace_children)) {}
567 else if VG_BOOL_CLO(arg, "--child-silent-after-fork",
568 VG_(clo_child_silent_after_fork)) {}
bart78bfc712011-12-08 16:14:59 +0000569 else if VG_STR_CLO(arg, "--fair-sched", tmp_str) {
570 if (VG_(strcmp)(tmp_str, "yes") == 0)
571 VG_(clo_fair_sched) = enable_fair_sched;
572 else if (VG_(strcmp)(tmp_str, "try") == 0)
573 VG_(clo_fair_sched) = try_fair_sched;
574 else if (VG_(strcmp)(tmp_str, "no") == 0)
575 VG_(clo_fair_sched) = disable_fair_sched;
576 else
577 VG_(fmsg_bad_option)(arg, "");
578
579 }
njn83df0b62009-02-25 01:01:05 +0000580 else if VG_BOOL_CLO(arg, "--trace-sched", VG_(clo_trace_sched)) {}
581 else if VG_BOOL_CLO(arg, "--trace-signals", VG_(clo_trace_signals)) {}
582 else if VG_BOOL_CLO(arg, "--trace-symtab", VG_(clo_trace_symtab)) {}
583 else if VG_STR_CLO (arg, "--trace-symtab-patt", VG_(clo_trace_symtab_patt)) {}
584 else if VG_BOOL_CLO(arg, "--trace-cfi", VG_(clo_trace_cfi)) {}
585 else if VG_XACT_CLO(arg, "--debug-dump=syms", VG_(clo_debug_dump_syms),
586 True) {}
587 else if VG_XACT_CLO(arg, "--debug-dump=line", VG_(clo_debug_dump_line),
588 True) {}
589 else if VG_XACT_CLO(arg, "--debug-dump=frames",
590 VG_(clo_debug_dump_frames), True) {}
591 else if VG_BOOL_CLO(arg, "--trace-redir", VG_(clo_trace_redir)) {}
sewardj95d86c02007-12-18 01:49:23 +0000592
njn83df0b62009-02-25 01:01:05 +0000593 else if VG_BOOL_CLO(arg, "--trace-syscalls", VG_(clo_trace_syscalls)) {}
594 else if VG_BOOL_CLO(arg, "--wait-for-gdb", VG_(clo_wait_for_gdb)) {}
595 else if VG_STR_CLO (arg, "--db-command", VG_(clo_db_command)) {}
njn83df0b62009-02-25 01:01:05 +0000596 else if VG_BOOL_CLO(arg, "--sym-offsets", VG_(clo_sym_offsets)) {}
597 else if VG_BOOL_CLO(arg, "--read-var-info", VG_(clo_read_var_info)) {}
sewardjf767d962007-02-12 17:47:14 +0000598
njn83df0b62009-02-25 01:01:05 +0000599 else if VG_INT_CLO (arg, "--dump-error", VG_(clo_dump_error)) {}
600 else if VG_INT_CLO (arg, "--input-fd", VG_(clo_input_fd)) {}
601 else if VG_INT_CLO (arg, "--sanity-level", VG_(clo_sanity_level)) {}
602 else if VG_BINT_CLO(arg, "--num-callers", VG_(clo_backtrace_size), 1,
603 VG_DEEPEST_BACKTRACE) {}
philippe46207652013-01-20 17:11:58 +0000604 else if VG_BINT_CLO(arg, "--merge-recursive-frames",
605 VG_(clo_merge_recursive_frames), 0,
606 VG_DEEPEST_BACKTRACE) {}
sewardjde4a1d02002-03-22 01:27:54 +0000607
njn83df0b62009-02-25 01:01:05 +0000608 else if VG_XACT_CLO(arg, "--smc-check=none", VG_(clo_smc_check),
609 Vg_SmcNone);
610 else if VG_XACT_CLO(arg, "--smc-check=stack", VG_(clo_smc_check),
611 Vg_SmcStack);
612 else if VG_XACT_CLO(arg, "--smc-check=all", VG_(clo_smc_check),
613 Vg_SmcAll);
sewardj6dbcc632011-06-07 21:39:28 +0000614 else if VG_XACT_CLO(arg, "--smc-check=all-non-file",
615 VG_(clo_smc_check),
616 Vg_SmcAllNonFile);
sewardjde4a1d02002-03-22 01:27:54 +0000617
njn97db7612009-08-04 02:32:55 +0000618 else if VG_STR_CLO (arg, "--kernel-variant", VG_(clo_kernel_variant)) {}
sewardj26412bd2005-07-07 10:05:05 +0000619
njn97db7612009-08-04 02:32:55 +0000620 else if VG_BOOL_CLO(arg, "--dsymutil", VG_(clo_dsymutil)) {}
njnf76d27a2009-05-28 01:53:07 +0000621
sewardj9ab64a42010-12-06 11:40:04 +0000622 else if VG_STR_CLO (arg, "--trace-children-skip",
623 VG_(clo_trace_children_skip)) {}
624 else if VG_STR_CLO (arg, "--trace-children-skip-by-arg",
625 VG_(clo_trace_children_skip_by_arg)) {}
sewardj06421272009-11-05 08:55:13 +0000626
njn83df0b62009-02-25 01:01:05 +0000627 else if VG_BINT_CLO(arg, "--vex-iropt-verbosity",
628 VG_(clo_vex_control).iropt_verbosity, 0, 10) {}
629 else if VG_BINT_CLO(arg, "--vex-iropt-level",
630 VG_(clo_vex_control).iropt_level, 0, 2) {}
philippe0c0291a2012-08-01 22:03:12 +0000631 else if VG_XACT_CLO(arg,
philippe5b240c22012-08-14 22:28:31 +0000632 "--vex-iropt-register-updates=sp-at-mem-access",
633 VG_(clo_vex_control).iropt_register_updates,
634 VexRegUpdSpAtMemAccess);
635 else if VG_XACT_CLO(arg,
philippe0c0291a2012-08-01 22:03:12 +0000636 "--vex-iropt-register-updates=unwindregs-at-mem-access",
637 VG_(clo_vex_control).iropt_register_updates,
638 VexRegUpdUnwindregsAtMemAccess);
639 else if VG_XACT_CLO(arg,
640 "--vex-iropt-register-updates=allregs-at-mem-access",
641 VG_(clo_vex_control).iropt_register_updates,
642 VexRegUpdAllregsAtMemAccess);
643 else if VG_XACT_CLO(arg,
644 "--vex-iropt-register-updates=allregs-at-each-insn",
645 VG_(clo_vex_control).iropt_register_updates,
646 VexRegUpdAllregsAtEachInsn);
njn83df0b62009-02-25 01:01:05 +0000647 else if VG_BINT_CLO(arg, "--vex-iropt-unroll-thresh",
648 VG_(clo_vex_control).iropt_unroll_thresh, 0, 400) {}
649 else if VG_BINT_CLO(arg, "--vex-guest-max-insns",
650 VG_(clo_vex_control).guest_max_insns, 1, 100) {}
651 else if VG_BINT_CLO(arg, "--vex-guest-chase-thresh",
652 VG_(clo_vex_control).guest_chase_thresh, 0, 99) {}
sewardj540cc4a2010-01-15 10:57:57 +0000653 else if VG_BOOL_CLO(arg, "--vex-guest-chase-cond",
654 VG_(clo_vex_control).guest_chase_cond) {}
sewardj94c8eb42008-09-19 20:13:39 +0000655
njn83df0b62009-02-25 01:01:05 +0000656 else if VG_INT_CLO(arg, "--log-fd", tmp_log_fd) {
657 log_to = VgLogTo_Fd;
sewardj738856f2009-07-15 14:48:32 +0000658 log_fsname_unexpanded = NULL;
659 }
660 else if VG_INT_CLO(arg, "--xml-fd", tmp_xml_fd) {
661 xml_to = VgLogTo_Fd;
662 xml_fsname_unexpanded = NULL;
sewardj4cf05692002-10-27 20:28:29 +0000663 }
664
sewardj738856f2009-07-15 14:48:32 +0000665 else if VG_STR_CLO(arg, "--log-file", log_fsname_unexpanded) {
njn83df0b62009-02-25 01:01:05 +0000666 log_to = VgLogTo_File;
sewardj4cf05692002-10-27 20:28:29 +0000667 }
sewardj738856f2009-07-15 14:48:32 +0000668 else if VG_STR_CLO(arg, "--xml-file", xml_fsname_unexpanded) {
669 xml_to = VgLogTo_File;
670 }
671
672 else if VG_STR_CLO(arg, "--log-socket", log_fsname_unexpanded) {
njn83df0b62009-02-25 01:01:05 +0000673 log_to = VgLogTo_Socket;
sewardj73cf3bc2002-11-03 03:20:15 +0000674 }
sewardj738856f2009-07-15 14:48:32 +0000675 else if VG_STR_CLO(arg, "--xml-socket", xml_fsname_unexpanded) {
676 xml_to = VgLogTo_Socket;
677 }
sewardj73cf3bc2002-11-03 03:20:15 +0000678
njn83df0b62009-02-25 01:01:05 +0000679 else if VG_STR_CLO(arg, "--xml-user-comment",
680 VG_(clo_xml_user_comment)) {}
sewardj768db0e2005-07-19 14:18:56 +0000681
njn83df0b62009-02-25 01:01:05 +0000682 else if VG_STR_CLO(arg, "--suppressions", tmp_str) {
sewardjde4a1d02002-03-22 01:27:54 +0000683 if (VG_(clo_n_suppressions) >= VG_CLO_MAX_SFILES) {
njnb1cc5d62010-07-06 04:05:23 +0000684 VG_(fmsg_bad_option)(arg,
685 "Too many suppression files specified.\n"
686 "Increase VG_CLO_MAX_SFILES and recompile.\n");
sewardjde4a1d02002-03-22 01:27:54 +0000687 }
njn83df0b62009-02-25 01:01:05 +0000688 VG_(clo_suppressions)[VG_(clo_n_suppressions)] = tmp_str;
sewardjde4a1d02002-03-22 01:27:54 +0000689 VG_(clo_n_suppressions)++;
690 }
sewardjde4a1d02002-03-22 01:27:54 +0000691
sewardj14cdbf82010-10-12 00:44:05 +0000692 else if VG_STR_CLO (arg, "--fullpath-after", tmp_str) {
693 if (VG_(clo_n_fullpath_after) >= VG_CLO_MAX_FULLPATH_AFTER) {
694 VG_(fmsg_bad_option)(arg,
695 "Too many --fullpath-after= specifications.\n"
696 "Increase VG_CLO_MAX_FULLPATH_AFTER and recompile.\n");
697 }
698 VG_(clo_fullpath_after)[VG_(clo_n_fullpath_after)] = tmp_str;
699 VG_(clo_n_fullpath_after)++;
700 }
701
sewardj8b6573d2012-12-05 22:15:14 +0000702 else if VG_STR_CLO (arg, "--extra-debuginfo-path",
703 VG_(clo_extra_debuginfo_path)) {}
704
sewardjf9ebc392010-05-09 22:30:43 +0000705 else if VG_STR_CLO(arg, "--require-text-symbol", tmp_str) {
706 if (VG_(clo_n_req_tsyms) >= VG_CLO_MAX_REQ_TSYMS) {
njnb1cc5d62010-07-06 04:05:23 +0000707 VG_(fmsg_bad_option)(arg,
708 "Too many --require-text-symbol= specifications.\n"
709 "Increase VG_CLO_MAX_REQ_TSYMS and recompile.\n");
sewardjf9ebc392010-05-09 22:30:43 +0000710 }
711 /* String needs to be of the form C?*C?*, where C is any
712 character, but is the same both times. Having it in this
713 form facilitates finding the boundary between the sopatt
714 and the fnpatt just by looking for the second occurrence
715 of C, without hardwiring any assumption about what C
716 is. */
florian19f91bb2012-11-10 22:29:54 +0000717 HChar patt[7];
sewardjf9ebc392010-05-09 22:30:43 +0000718 Bool ok = True;
719 ok = tmp_str && VG_(strlen)(tmp_str) > 0;
720 if (ok) {
721 patt[0] = patt[3] = tmp_str[0];
722 patt[1] = patt[4] = '?';
723 patt[2] = patt[5] = '*';
724 patt[6] = 0;
725 ok = VG_(string_match)(patt, tmp_str);
726 }
727 if (!ok) {
njnb1cc5d62010-07-06 04:05:23 +0000728 VG_(fmsg_bad_option)(arg,
729 "Invalid --require-text-symbol= specification.\n");
sewardjf9ebc392010-05-09 22:30:43 +0000730 }
731 VG_(clo_req_tsyms)[VG_(clo_n_req_tsyms)] = tmp_str;
732 VG_(clo_n_req_tsyms)++;
733 }
734
sewardjfa8ec112005-01-19 11:55:34 +0000735 /* "stuvwxyz" --> stuvwxyz (binary) */
njn83df0b62009-02-25 01:01:05 +0000736 else if VG_STR_CLO(arg, "--trace-flags", tmp_str) {
sewardjfa8ec112005-01-19 11:55:34 +0000737 Int j;
njn83df0b62009-02-25 01:01:05 +0000738 if (8 != VG_(strlen)(tmp_str)) {
njnb1cc5d62010-07-06 04:05:23 +0000739 VG_(fmsg_bad_option)(arg,
740 "--trace-flags argument must have 8 digits\n");
sewardjfa8ec112005-01-19 11:55:34 +0000741 }
742 for (j = 0; j < 8; j++) {
njn83df0b62009-02-25 01:01:05 +0000743 if ('0' == tmp_str[j]) { /* do nothing */ }
744 else if ('1' == tmp_str[j]) VG_(clo_trace_flags) |= (1 << (7-j));
sewardjfa8ec112005-01-19 11:55:34 +0000745 else {
njnb1cc5d62010-07-06 04:05:23 +0000746 VG_(fmsg_bad_option)(arg,
747 "--trace-flags argument can only contain 0s and 1s\n");
sewardjfa8ec112005-01-19 11:55:34 +0000748 }
749 }
750 }
751
sewardj17c5e2e2012-12-28 09:12:14 +0000752 else if VG_INT_CLO (arg, "--trace-notbelow", VG_(clo_trace_notbelow)) {}
753
754 else if VG_INT_CLO (arg, "--trace-notabove", VG_(clo_trace_notabove)) {}
755
sewardjfa8ec112005-01-19 11:55:34 +0000756 /* "stuvwxyz" --> stuvwxyz (binary) */
njn83df0b62009-02-25 01:01:05 +0000757 else if VG_STR_CLO(arg, "--profile-flags", tmp_str) {
njn25e49d8e72002-09-23 09:36:25 +0000758 Int j;
njn83df0b62009-02-25 01:01:05 +0000759 if (8 != VG_(strlen)(tmp_str)) {
njnb1cc5d62010-07-06 04:05:23 +0000760 VG_(fmsg_bad_option)(arg,
761 "--profile-flags argument must have 8 digits\n");
njn25e49d8e72002-09-23 09:36:25 +0000762 }
sewardj8b635a42004-11-22 19:01:47 +0000763 for (j = 0; j < 8; j++) {
njn83df0b62009-02-25 01:01:05 +0000764 if ('0' == tmp_str[j]) { /* do nothing */ }
sewardj17c5e2e2012-12-28 09:12:14 +0000765 else if ('1' == tmp_str[j]) VG_(clo_profyle_flags) |= (1 << (7-j));
njn25e49d8e72002-09-23 09:36:25 +0000766 else {
njnb1cc5d62010-07-06 04:05:23 +0000767 VG_(fmsg_bad_option)(arg,
768 "--profile-flags argument can only contain 0s and 1s\n");
njn25e49d8e72002-09-23 09:36:25 +0000769 }
770 }
sewardj17c5e2e2012-12-28 09:12:14 +0000771 VG_(clo_profyle_sbs) = True;
njn25e49d8e72002-09-23 09:36:25 +0000772 }
sewardjde4a1d02002-03-22 01:27:54 +0000773
sewardj17c5e2e2012-12-28 09:12:14 +0000774 else if VG_INT_CLO (arg, "--profile-interval",
775 VG_(clo_profyle_interval)) {}
florian29e022d2012-07-02 21:13:34 +0000776
njn83df0b62009-02-25 01:01:05 +0000777 else if VG_XACT_CLO(arg, "--gen-suppressions=no",
778 VG_(clo_gen_suppressions), 0) {}
779 else if VG_XACT_CLO(arg, "--gen-suppressions=yes",
780 VG_(clo_gen_suppressions), 1) {}
781 else if VG_XACT_CLO(arg, "--gen-suppressions=all",
782 VG_(clo_gen_suppressions), 2) {}
sewardjd153fae2005-01-10 17:24:47 +0000783
nethercote71980f02004-01-24 18:18:54 +0000784 else if ( ! VG_(needs).command_line_options
njn51d827b2005-05-09 01:02:08 +0000785 || ! VG_TDICT_CALL(tool_process_cmd_line_option, arg) ) {
njnb1cc5d62010-07-06 04:05:23 +0000786 VG_(fmsg_bad_option)(arg, "");
njn25e49d8e72002-09-23 09:36:25 +0000787 }
sewardjde4a1d02002-03-22 01:27:54 +0000788 }
789
sewardj738856f2009-07-15 14:48:32 +0000790 /* END command-line processing loop */
791
florianb985e2d2011-09-29 03:03:45 +0000792 /* Determine the path prefix for vgdb */
793 if (VG_(clo_vgdb_prefix) == NULL)
794 VG_(clo_vgdb_prefix) = VG_(vgdb_prefix_default)();
795
sewardj998d40d2004-12-06 14:24:52 +0000796 /* Make VEX control parameters sane */
797
798 if (VG_(clo_vex_control).guest_chase_thresh
799 >= VG_(clo_vex_control).guest_max_insns)
800 VG_(clo_vex_control).guest_chase_thresh
801 = VG_(clo_vex_control).guest_max_insns - 1;
802
803 if (VG_(clo_vex_control).guest_chase_thresh < 0)
804 VG_(clo_vex_control).guest_chase_thresh = 0;
805
806 /* Check various option values */
nethercote27fec902004-06-16 21:26:32 +0000807
njnf9ebf672003-05-12 21:41:30 +0000808 if (VG_(clo_verbosity) < 0)
sewardjde4a1d02002-03-22 01:27:54 +0000809 VG_(clo_verbosity) = 0;
810
sewardjc30cd9b2012-12-06 18:08:54 +0000811 if (!sigill_diag_set)
812 VG_(clo_sigill_diag) = (VG_(clo_verbosity) > 0);
813
florian29e022d2012-07-02 21:13:34 +0000814 if (VG_(clo_trace_notbelow) == -1) {
815 if (VG_(clo_trace_notabove) == -1) {
816 /* [] */
817 VG_(clo_trace_notbelow) = 2147483647;
818 VG_(clo_trace_notabove) = 0;
819 } else {
820 /* [0 .. notabove] */
821 VG_(clo_trace_notbelow) = 0;
822 }
823 } else {
824 if (VG_(clo_trace_notabove) == -1) {
825 /* [notbelow .. ] */
826 VG_(clo_trace_notabove) = 2147483647;
827 } else {
828 /* [notbelow .. notabove] */
829 }
830 }
831
sewardj3b290482011-05-06 21:02:55 +0000832 VG_(dyn_vgdb_error) = VG_(clo_vgdb_error);
833
njnbe9b47b2005-05-15 16:22:58 +0000834 if (VG_(clo_gen_suppressions) > 0 &&
835 !VG_(needs).core_errors && !VG_(needs).tool_errors) {
njnb1cc5d62010-07-06 04:05:23 +0000836 VG_(fmsg_bad_option)("--gen-suppressions=yes",
837 "Can't use --gen-suppressions= with %s\n"
838 "because it doesn't generate errors.\n", VG_(details).name);
njnbe9b47b2005-05-15 16:22:58 +0000839 }
840
sewardj738856f2009-07-15 14:48:32 +0000841 /* If XML output is requested, check that the tool actually
842 supports it. */
843 if (VG_(clo_xml) && !VG_(needs).xml_output) {
844 VG_(clo_xml) = False;
njnb1cc5d62010-07-06 04:05:23 +0000845 VG_(fmsg_bad_option)("--xml=yes",
sewardj738856f2009-07-15 14:48:32 +0000846 "%s does not support XML output.\n", VG_(details).name);
sewardj738856f2009-07-15 14:48:32 +0000847 /*NOTREACHED*/
848 }
849
850 vg_assert( VG_(clo_gen_suppressions) >= 0 );
851 vg_assert( VG_(clo_gen_suppressions) <= 2 );
852
sewardj71bc3cb2005-05-19 00:25:45 +0000853 /* If we've been asked to emit XML, mash around various other
854 options so as to constrain the output somewhat, and to remove
sewardj738856f2009-07-15 14:48:32 +0000855 any need for user input during the run.
856 */
sewardj71bc3cb2005-05-19 00:25:45 +0000857 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +0000858
859 /* We can't allow --gen-suppressions=yes, since that requires us
860 to print the error and then ask the user if she wants a
861 suppression for it, but in XML mode we won't print it until
862 we know whether we also need to print a suppression. Hence a
863 circular dependency. So disallow this.
864 (--gen-suppressions=all is still OK since we don't need any
865 user interaction in this case.) */
866 if (VG_(clo_gen_suppressions) == 1) {
njnb1cc5d62010-07-06 04:05:23 +0000867 VG_(fmsg_bad_option)(
868 "--xml=yes together with --gen-suppressions=yes",
869 "When --xml=yes is specified, --gen-suppressions=no\n"
870 "or --gen-suppressions=all is allowed, but not "
sewardj738856f2009-07-15 14:48:32 +0000871 "--gen-suppressions=yes.\n");
sewardj738856f2009-07-15 14:48:32 +0000872 }
873
874 /* We can't allow DB attaching (or we maybe could, but results
875 could be chaotic ..) since it requires user input. Hence
876 disallow. */
877 if (VG_(clo_db_attach)) {
njnb1cc5d62010-07-06 04:05:23 +0000878 VG_(fmsg_bad_option)(
879 "--xml=yes together with --db-attach=yes",
880 "--db-attach=yes is not allowed with --xml=yes\n"
881 "because it would require user input.\n");
sewardj738856f2009-07-15 14:48:32 +0000882 }
883
884 /* Disallow dump_error in XML mode; sounds like a recipe for
885 chaos. No big deal; dump_error is a flag for debugging V
886 itself. */
887 if (VG_(clo_dump_error) > 0) {
njnb1cc5d62010-07-06 04:05:23 +0000888 VG_(fmsg_bad_option)("--xml=yes together with --dump-error", "");
sewardj738856f2009-07-15 14:48:32 +0000889 }
890
sewardj71bc3cb2005-05-19 00:25:45 +0000891 /* Disable error limits (this might be a bad idea!) */
892 VG_(clo_error_limit) = False;
893 /* Disable emulation warnings */
sewardj738856f2009-07-15 14:48:32 +0000894
sewardj71bc3cb2005-05-19 00:25:45 +0000895 /* Also, we want to set options for the leak checker, but that
896 will have to be done in Memcheck's flag-handling code, not
897 here. */
898 }
899
njnbe9b47b2005-05-15 16:22:58 +0000900 /* All non-logging-related options have been checked. If the logging
901 option specified is ok, we can switch to it, as we know we won't
902 have to generate any other command-line-related error messages.
903 (So far we should be still attached to stderr, so we can show on
904 the terminal any problems to do with processing command line
905 opts.)
906
sewardj738856f2009-07-15 14:48:32 +0000907 So set up logging now. After this is done, VG_(log_output_sink)
908 and (if relevant) VG_(xml_output_sink) should be connected to
909 whatever sink has been selected, and we indiscriminately chuck
910 stuff into it without worrying what the nature of it is. Oh the
911 wonder of Unix streams. */
sewardj4cf05692002-10-27 20:28:29 +0000912
sewardj738856f2009-07-15 14:48:32 +0000913 vg_assert(VG_(log_output_sink).fd == 2 /* stderr */);
914 vg_assert(VG_(log_output_sink).is_socket == False);
915 vg_assert(VG_(clo_log_fname_expanded) == NULL);
916
917 vg_assert(VG_(xml_output_sink).fd == -1 /* disabled */);
918 vg_assert(VG_(xml_output_sink).is_socket == False);
919 vg_assert(VG_(clo_xml_fname_expanded) == NULL);
920
921 /* --- set up the normal text output channel --- */
sewardj4cf05692002-10-27 20:28:29 +0000922
njnbe9b47b2005-05-15 16:22:58 +0000923 switch (log_to) {
sewardj73cf3bc2002-11-03 03:20:15 +0000924
sewardj4cf05692002-10-27 20:28:29 +0000925 case VgLogTo_Fd:
sewardj738856f2009-07-15 14:48:32 +0000926 vg_assert(log_fsname_unexpanded == NULL);
sewardj4cf05692002-10-27 20:28:29 +0000927 break;
sewardj73cf3bc2002-11-03 03:20:15 +0000928
sewardj4cf05692002-10-27 20:28:29 +0000929 case VgLogTo_File: {
florian19f91bb2012-11-10 22:29:54 +0000930 HChar* logfilename;
jsgff3c3f1a2003-10-14 22:13:28 +0000931
sewardj738856f2009-07-15 14:48:32 +0000932 vg_assert(log_fsname_unexpanded != NULL);
933 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
jsgff3c3f1a2003-10-14 22:13:28 +0000934
njn374a36d2007-11-23 01:41:32 +0000935 // Nb: we overwrite an existing file of this name without asking
936 // any questions.
sewardj738856f2009-07-15 14:48:32 +0000937 logfilename = VG_(expand_file_name)("--log-file",
938 log_fsname_unexpanded);
njn374a36d2007-11-23 01:41:32 +0000939 sres = VG_(open)(logfilename,
njnda033f52005-12-19 21:27:58 +0000940 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
941 VKI_S_IRUSR|VKI_S_IWUSR);
njncda2f0f2009-05-18 02:12:08 +0000942 if (!sr_isError(sres)) {
943 tmp_log_fd = sr_Res(sres);
sewardj738856f2009-07-15 14:48:32 +0000944 VG_(clo_log_fname_expanded) = logfilename;
njnbe9b47b2005-05-15 16:22:58 +0000945 } else {
njnb1cc5d62010-07-06 04:05:23 +0000946 VG_(fmsg)("can't create log file '%s': %s\n",
947 logfilename, VG_(strerror)(sr_Err(sres)));
948 VG_(exit)(1);
sewardj603d4102005-01-11 14:01:02 +0000949 /*NOTREACHED*/
njn374a36d2007-11-23 01:41:32 +0000950 }
sewardj738856f2009-07-15 14:48:32 +0000951 break;
sewardj73cf3bc2002-11-03 03:20:15 +0000952 }
953
954 case VgLogTo_Socket: {
sewardj738856f2009-07-15 14:48:32 +0000955 vg_assert(log_fsname_unexpanded != NULL);
956 vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */
957 tmp_log_fd = VG_(connect_via_socket)( log_fsname_unexpanded );
njnda033f52005-12-19 21:27:58 +0000958 if (tmp_log_fd == -1) {
njnb1cc5d62010-07-06 04:05:23 +0000959 VG_(fmsg)("Invalid --log-socket spec of '%s'\n",
960 log_fsname_unexpanded);
961 VG_(exit)(1);
njnbe9b47b2005-05-15 16:22:58 +0000962 /*NOTREACHED*/
sewardj4cf05692002-10-27 20:28:29 +0000963 }
njnda033f52005-12-19 21:27:58 +0000964 if (tmp_log_fd == -2) {
njnb1cc5d62010-07-06 04:05:23 +0000965 VG_(umsg)("failed to connect to logging server '%s'.\n"
966 "Log messages will sent to stderr instead.\n",
967 log_fsname_unexpanded );
968
sewardj570f8902002-11-03 11:44:36 +0000969 /* We don't change anything here. */
sewardj738856f2009-07-15 14:48:32 +0000970 vg_assert(VG_(log_output_sink).fd == 2);
njnda033f52005-12-19 21:27:58 +0000971 tmp_log_fd = 2;
sewardj570f8902002-11-03 11:44:36 +0000972 } else {
njnda033f52005-12-19 21:27:58 +0000973 vg_assert(tmp_log_fd > 0);
sewardj738856f2009-07-15 14:48:32 +0000974 VG_(log_output_sink).is_socket = True;
sewardj570f8902002-11-03 11:44:36 +0000975 }
sewardj73cf3bc2002-11-03 03:20:15 +0000976 break;
977 }
sewardj4cf05692002-10-27 20:28:29 +0000978 }
979
sewardj738856f2009-07-15 14:48:32 +0000980 /* --- set up the XML output channel --- */
sewardj71bc3cb2005-05-19 00:25:45 +0000981
sewardj738856f2009-07-15 14:48:32 +0000982 switch (xml_to) {
983
984 case VgLogTo_Fd:
985 vg_assert(xml_fsname_unexpanded == NULL);
986 break;
987
988 case VgLogTo_File: {
florian19f91bb2012-11-10 22:29:54 +0000989 HChar* xmlfilename;
sewardj738856f2009-07-15 14:48:32 +0000990
991 vg_assert(xml_fsname_unexpanded != NULL);
992 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
993
994 // Nb: we overwrite an existing file of this name without asking
995 // any questions.
996 xmlfilename = VG_(expand_file_name)("--xml-file",
997 xml_fsname_unexpanded);
998 sres = VG_(open)(xmlfilename,
999 VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
1000 VKI_S_IRUSR|VKI_S_IWUSR);
1001 if (!sr_isError(sres)) {
1002 tmp_xml_fd = sr_Res(sres);
1003 VG_(clo_xml_fname_expanded) = xmlfilename;
1004 /* strdup here is probably paranoid overkill, but ... */
1005 *xml_fname_unexpanded = VG_(strdup)( "main.mpclo.2",
1006 xml_fsname_unexpanded );
1007 } else {
njnb1cc5d62010-07-06 04:05:23 +00001008 VG_(fmsg)("can't create XML file '%s': %s\n",
1009 xmlfilename, VG_(strerror)(sr_Err(sres)));
1010 VG_(exit)(1);
sewardj738856f2009-07-15 14:48:32 +00001011 /*NOTREACHED*/
1012 }
1013 break;
1014 }
1015
1016 case VgLogTo_Socket: {
1017 vg_assert(xml_fsname_unexpanded != NULL);
1018 vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */
1019 tmp_xml_fd = VG_(connect_via_socket)( xml_fsname_unexpanded );
1020 if (tmp_xml_fd == -1) {
njnb1cc5d62010-07-06 04:05:23 +00001021 VG_(fmsg)("Invalid --xml-socket spec of '%s'\n",
1022 xml_fsname_unexpanded );
1023 VG_(exit)(1);
sewardj738856f2009-07-15 14:48:32 +00001024 /*NOTREACHED*/
1025 }
1026 if (tmp_xml_fd == -2) {
njnb1cc5d62010-07-06 04:05:23 +00001027 VG_(umsg)("failed to connect to XML logging server '%s'.\n"
1028 "XML output will sent to stderr instead.\n",
1029 xml_fsname_unexpanded);
sewardj738856f2009-07-15 14:48:32 +00001030 /* We don't change anything here. */
1031 vg_assert(VG_(xml_output_sink).fd == 2);
1032 tmp_xml_fd = 2;
1033 } else {
1034 vg_assert(tmp_xml_fd > 0);
1035 VG_(xml_output_sink).is_socket = True;
1036 }
1037 break;
1038 }
sewardj71bc3cb2005-05-19 00:25:45 +00001039 }
1040
sewardj738856f2009-07-15 14:48:32 +00001041 /* If we've got this far, and XML mode was requested, but no XML
1042 output channel appears to have been specified, just stop. We
1043 could continue, and XML output will simply vanish into nowhere,
1044 but that is likely to confuse the hell out of users, which is
1045 distinctly Ungood. */
1046 if (VG_(clo_xml) && tmp_xml_fd == -1) {
njnb1cc5d62010-07-06 04:05:23 +00001047 VG_(fmsg_bad_option)(
1048 "--xml=yes, but no XML destination specified",
sewardj738856f2009-07-15 14:48:32 +00001049 "--xml=yes has been specified, but there is no XML output\n"
1050 "destination. You must specify an XML output destination\n"
njnb1cc5d62010-07-06 04:05:23 +00001051 "using --xml-fd, --xml-file or --xml-socket.\n"
1052 );
sewardj738856f2009-07-15 14:48:32 +00001053 }
1054
1055 // Finalise the output fds: the log fd ..
1056
njnda033f52005-12-19 21:27:58 +00001057 if (tmp_log_fd >= 0) {
sewardj738856f2009-07-15 14:48:32 +00001058 // Move log_fd into the safe range, so it doesn't conflict with
1059 // any app fds.
njnda033f52005-12-19 21:27:58 +00001060 tmp_log_fd = VG_(fcntl)(tmp_log_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
1061 if (tmp_log_fd < 0) {
sewardj738856f2009-07-15 14:48:32 +00001062 VG_(message)(Vg_UserMsg, "valgrind: failed to move logfile fd "
1063 "into safe range, using stderr\n");
1064 VG_(log_output_sink).fd = 2; // stderr
1065 VG_(log_output_sink).is_socket = False;
njnda033f52005-12-19 21:27:58 +00001066 } else {
sewardj738856f2009-07-15 14:48:32 +00001067 VG_(log_output_sink).fd = tmp_log_fd;
1068 VG_(fcntl)(VG_(log_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
njnda033f52005-12-19 21:27:58 +00001069 }
1070 } else {
1071 // If they said --log-fd=-1, don't print anything. Plausible for use in
1072 // regression testing suites that use client requests to count errors.
sewardj738856f2009-07-15 14:48:32 +00001073 VG_(log_output_sink).fd = -1;
1074 VG_(log_output_sink).is_socket = False;
jsgf855d93d2003-10-13 22:26:55 +00001075 }
1076
sewardj738856f2009-07-15 14:48:32 +00001077 // Finalise the output fds: and the XML fd ..
1078
1079 if (tmp_xml_fd >= 0) {
1080 // Move xml_fd into the safe range, so it doesn't conflict with
1081 // any app fds.
1082 tmp_xml_fd = VG_(fcntl)(tmp_xml_fd, VKI_F_DUPFD, VG_(fd_hard_limit));
1083 if (tmp_xml_fd < 0) {
1084 VG_(message)(Vg_UserMsg, "valgrind: failed to move XML file fd "
1085 "into safe range, using stderr\n");
1086 VG_(xml_output_sink).fd = 2; // stderr
1087 VG_(xml_output_sink).is_socket = False;
1088 } else {
1089 VG_(xml_output_sink).fd = tmp_xml_fd;
1090 VG_(fcntl)(VG_(xml_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC);
1091 }
1092 } else {
1093 // If they said --xml-fd=-1, don't print anything. Plausible for use in
1094 // regression testing suites that use client requests to count errors.
1095 VG_(xml_output_sink).fd = -1;
1096 VG_(xml_output_sink).is_socket = False;
1097 }
1098
1099 // Suppressions related stuff
1100
sewardj45f4e7c2005-09-27 19:20:21 +00001101 if (VG_(clo_n_suppressions) < VG_CLO_MAX_SFILES-1 &&
1102 (VG_(needs).core_errors || VG_(needs).tool_errors)) {
1103 /* If we haven't reached the max number of suppressions, load
1104 the default one. */
floriane6a4ed12012-10-21 02:30:18 +00001105 static const HChar default_supp[] = "default.supp";
sewardj45f4e7c2005-09-27 19:20:21 +00001106 Int len = VG_(strlen)(VG_(libdir)) + 1 + sizeof(default_supp);
florian19f91bb2012-11-10 22:29:54 +00001107 HChar *buf = VG_(arena_malloc)(VG_AR_CORE, "main.mpclo.3", len);
sewardj45f4e7c2005-09-27 19:20:21 +00001108 VG_(sprintf)(buf, "%s/%s", VG_(libdir), default_supp);
1109 VG_(clo_suppressions)[VG_(clo_n_suppressions)] = buf;
1110 VG_(clo_n_suppressions)++;
1111 }
sewardjde4a1d02002-03-22 01:27:54 +00001112
sewardj738856f2009-07-15 14:48:32 +00001113 *logging_to_fd = log_to == VgLogTo_Fd || log_to == VgLogTo_Socket;
sewardj45f4e7c2005-09-27 19:20:21 +00001114}
1115
sewardj4efbaa72008-06-04 06:51:58 +00001116// Write the name and value of log file qualifiers to the xml file.
florian19f91bb2012-11-10 22:29:54 +00001117static void print_file_vars(HChar* format)
sewardj4efbaa72008-06-04 06:51:58 +00001118{
1119 Int i = 0;
1120
1121 while (format[i]) {
1122 if (format[i] == '%') {
1123 // We saw a '%'. What's next...
1124 i++;
1125 if ('q' == format[i]) {
1126 i++;
1127 if ('{' == format[i]) {
1128 // Get the env var name, print its contents.
florian19f91bb2012-11-10 22:29:54 +00001129 HChar* qualname;
1130 HChar* qual;
sewardj4efbaa72008-06-04 06:51:58 +00001131 i++;
1132 qualname = &format[i];
1133 while (True) {
1134 if ('}' == format[i]) {
1135 // Temporarily replace the '}' with NUL to extract var
1136 // name.
1137 format[i] = 0;
1138 qual = VG_(getenv)(qualname);
1139 break;
1140 }
1141 i++;
1142 }
1143
bartb3af9cf2011-10-06 19:08:37 +00001144 VG_(printf_xml)(
1145 "<logfilequalifier> <var>%pS</var> "
1146 "<value>%pS</value> </logfilequalifier>\n",
sewardj7ca100d2009-08-15 23:05:34 +00001147 qualname,qual
1148 );
sewardj4efbaa72008-06-04 06:51:58 +00001149 format[i] = '}';
1150 i++;
1151 }
1152 }
1153 } else {
1154 i++;
1155 }
1156 }
1157}
1158
sewardj45f4e7c2005-09-27 19:20:21 +00001159
1160/*====================================================================*/
1161/*=== Printing the preamble ===*/
1162/*====================================================================*/
1163
barta92677a2011-10-22 08:24:32 +00001164// Print the argument, escaping any chars that require it.
florian19f91bb2012-11-10 22:29:54 +00001165static void umsg_arg(const HChar* arg)
njnf8a11cf2009-08-02 23:03:06 +00001166{
1167 SizeT len = VG_(strlen)(arg);
floriane6a4ed12012-10-21 02:30:18 +00001168 const HChar* special = " \\<>";
njnf8a11cf2009-08-02 23:03:06 +00001169 Int i;
1170 for (i = 0; i < len; i++) {
1171 if (VG_(strchr)(special, arg[i])) {
barta92677a2011-10-22 08:24:32 +00001172 VG_(umsg)("\\"); // escape with a backslash if necessary
njnf8a11cf2009-08-02 23:03:06 +00001173 }
barta92677a2011-10-22 08:24:32 +00001174 VG_(umsg)("%c", arg[i]);
njnf8a11cf2009-08-02 23:03:06 +00001175 }
1176}
1177
barta92677a2011-10-22 08:24:32 +00001178// Send output to the XML-stream and escape any XML meta-characters.
florian19f91bb2012-11-10 22:29:54 +00001179static void xml_arg(const HChar* arg)
barta92677a2011-10-22 08:24:32 +00001180{
1181 VG_(printf_xml)("%pS", arg);
1182}
1183
sewardj45f4e7c2005-09-27 19:20:21 +00001184/* Ok, the logging sink is running now. Print a suitable preamble.
1185 If logging to file or a socket, write details of parent PID and
1186 command line args, to help people trying to interpret the
1187 results of a run which encompasses multiple processes. */
sewardj738856f2009-07-15 14:48:32 +00001188static void print_preamble ( Bool logging_to_fd,
florian19f91bb2012-11-10 22:29:54 +00001189 HChar* xml_fname_unexpanded,
sewardj738856f2009-07-15 14:48:32 +00001190 const HChar* toolname )
sewardj45f4e7c2005-09-27 19:20:21 +00001191{
sewardj738856f2009-07-15 14:48:32 +00001192 Int i;
florian6bd9dc12012-11-23 16:17:43 +00001193 const HChar* xpre = VG_(clo_xml) ? " <line>" : "";
1194 const HChar* xpost = VG_(clo_xml) ? "</line>" : "";
sewardj738856f2009-07-15 14:48:32 +00001195 UInt (*umsg_or_xml)( const HChar*, ... )
1196 = VG_(clo_xml) ? VG_(printf_xml) : VG_(umsg);
tom60a4b0b2005-10-12 10:45:27 +00001197
florian19f91bb2012-11-10 22:29:54 +00001198 void (*umsg_or_xml_arg)( const HChar* )
barta92677a2011-10-22 08:24:32 +00001199 = VG_(clo_xml) ? xml_arg : umsg_arg;
1200
sewardj14c7cc52007-02-25 15:08:24 +00001201 vg_assert( VG_(args_for_client) );
1202 vg_assert( VG_(args_for_valgrind) );
sewardj99a2ceb2007-11-09 12:30:36 +00001203 vg_assert( toolname );
sewardj14c7cc52007-02-25 15:08:24 +00001204
sewardj71bc3cb2005-05-19 00:25:45 +00001205 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +00001206 VG_(printf_xml)("<?xml version=\"1.0\"?>\n");
1207 VG_(printf_xml)("\n");
1208 VG_(printf_xml)("<valgrindoutput>\n");
1209 VG_(printf_xml)("\n");
1210 VG_(printf_xml)("<protocolversion>4</protocolversion>\n");
1211 VG_(printf_xml)("<protocoltool>%s</protocoltool>\n", toolname);
1212 VG_(printf_xml)("\n");
sewardj71bc3cb2005-05-19 00:25:45 +00001213 }
1214
sewardj738856f2009-07-15 14:48:32 +00001215 if (VG_(clo_xml) || VG_(clo_verbosity > 0)) {
sewardjd7bddad2005-06-13 16:48:32 +00001216
1217 if (VG_(clo_xml))
sewardj738856f2009-07-15 14:48:32 +00001218 VG_(printf_xml)("<preamble>\n");
sewardjd7bddad2005-06-13 16:48:32 +00001219
nethercote996901a2004-08-03 13:29:09 +00001220 /* Tool details */
bartb3af9cf2011-10-06 19:08:37 +00001221 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 +00001222 xpre,
njnd04b7c62002-10-03 14:05:52 +00001223 VG_(details).name,
njnb9c427c2004-12-01 14:14:42 +00001224 NULL == VG_(details).version ? "" : "-",
njnd04b7c62002-10-03 14:05:52 +00001225 NULL == VG_(details).version
floriane6a4ed12012-10-21 02:30:18 +00001226 ? "" : VG_(details).version,
sewardj71bc3cb2005-05-19 00:25:45 +00001227 VG_(details).description,
sewardj738856f2009-07-15 14:48:32 +00001228 xpost );
sewardj99a2ceb2007-11-09 12:30:36 +00001229
njn10b9aea2009-07-14 06:55:05 +00001230 if (VG_(strlen)(toolname) >= 4 && VG_STREQN(4, toolname, "exp-")) {
sewardj738856f2009-07-15 14:48:32 +00001231 umsg_or_xml(
njnb6267bd2009-08-12 00:14:16 +00001232 "%sNOTE: This is an Experimental-Class Valgrind Tool%s\n",
sewardj99a2ceb2007-11-09 12:30:36 +00001233 xpre, xpost
1234 );
1235 }
1236
bartb3af9cf2011-10-06 19:08:37 +00001237 umsg_or_xml( VG_(clo_xml) ? "%s%pS%s\n" : "%s%s%s\n",
sewardj743a2082010-07-23 17:03:22 +00001238 xpre, VG_(details).copyright_author, xpost );
sewardj3b2736a2002-03-24 12:18:35 +00001239
njnd04b7c62002-10-03 14:05:52 +00001240 /* Core details */
sewardj738856f2009-07-15 14:48:32 +00001241 umsg_or_xml(
njnf73d87f2009-07-24 04:47:04 +00001242 "%sUsing Valgrind-%s and LibVEX; rerun with -h for copyright info%s\n",
1243 xpre, VERSION, xpost
sewardj738856f2009-07-15 14:48:32 +00001244 );
sewardj45f4e7c2005-09-27 19:20:21 +00001245
njnf3977a32009-08-04 00:27:56 +00001246 // Print the command line. At one point we wrapped at 80 chars and
1247 // printed a '\' as a line joiner, but that makes it hard to cut and
1248 // paste the command line (because of the "==pid==" prefixes), so we now
1249 // favour utility and simplicity over aesthetics.
1250 umsg_or_xml("%sCommand: ", xpre);
njn53162bf2009-07-29 23:34:49 +00001251 if (VG_(args_the_exename))
barta92677a2011-10-22 08:24:32 +00001252 umsg_or_xml_arg(VG_(args_the_exename));
1253
njn53162bf2009-07-29 23:34:49 +00001254 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1255 HChar* s = *(HChar**)VG_(indexXA)( VG_(args_for_client), i );
njnf8a11cf2009-08-02 23:03:06 +00001256 umsg_or_xml(" ");
barta92677a2011-10-22 08:24:32 +00001257 umsg_or_xml_arg(s);
njn53162bf2009-07-29 23:34:49 +00001258 }
njnf3977a32009-08-04 00:27:56 +00001259 umsg_or_xml("%s\n", xpost);
njn53162bf2009-07-29 23:34:49 +00001260
sewardjd7bddad2005-06-13 16:48:32 +00001261 if (VG_(clo_xml))
sewardj738856f2009-07-15 14:48:32 +00001262 VG_(printf_xml)("</preamble>\n");
njnd04b7c62002-10-03 14:05:52 +00001263 }
1264
njnb6267bd2009-08-12 00:14:16 +00001265 // Print the parent PID, and other stuff, if necessary.
sewardj45f4e7c2005-09-27 19:20:21 +00001266 if (!VG_(clo_xml) && VG_(clo_verbosity) > 0 && !logging_to_fd) {
njn305dc002009-07-30 23:36:43 +00001267 VG_(umsg)("Parent PID: %d\n", VG_(getppid)());
sewardj4cf05692002-10-27 20:28:29 +00001268 }
sewardj71bc3cb2005-05-19 00:25:45 +00001269 else
1270 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +00001271 VG_(printf_xml)("\n");
1272 VG_(printf_xml)("<pid>%d</pid>\n", VG_(getpid)());
1273 VG_(printf_xml)("<ppid>%d</ppid>\n", VG_(getppid)());
bartb3af9cf2011-10-06 19:08:37 +00001274 VG_(printf_xml)("<tool>%pS</tool>\n", toolname);
sewardj738856f2009-07-15 14:48:32 +00001275 if (xml_fname_unexpanded)
1276 print_file_vars(xml_fname_unexpanded);
sewardj768db0e2005-07-19 14:18:56 +00001277 if (VG_(clo_xml_user_comment)) {
1278 /* Note: the user comment itself is XML and is therefore to
1279 be passed through verbatim (%s) rather than escaped
bartb3af9cf2011-10-06 19:08:37 +00001280 (%pS). */
sewardj738856f2009-07-15 14:48:32 +00001281 VG_(printf_xml)("<usercomment>%s</usercomment>\n",
1282 VG_(clo_xml_user_comment));
sewardj768db0e2005-07-19 14:18:56 +00001283 }
sewardj738856f2009-07-15 14:48:32 +00001284 VG_(printf_xml)("\n");
1285 VG_(printf_xml)("<args>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001286
sewardj738856f2009-07-15 14:48:32 +00001287 VG_(printf_xml)(" <vargv>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001288 if (VG_(name_of_launcher))
bartb3af9cf2011-10-06 19:08:37 +00001289 VG_(printf_xml)(" <exe>%pS</exe>\n",
sewardj738856f2009-07-15 14:48:32 +00001290 VG_(name_of_launcher));
sewardj125fd4f2007-03-08 19:56:14 +00001291 else
bartb3af9cf2011-10-06 19:08:37 +00001292 VG_(printf_xml)(" <exe>%pS</exe>\n",
njnb1cc5d62010-07-06 04:05:23 +00001293 "(launcher name unknown)");
sewardj14c7cc52007-02-25 15:08:24 +00001294 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
bartb3af9cf2011-10-06 19:08:37 +00001295 VG_(printf_xml)(
1296 " <arg>%pS</arg>\n",
sewardj738856f2009-07-15 14:48:32 +00001297 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1298 );
sewardjb8a3dac2005-07-19 12:39:11 +00001299 }
sewardj738856f2009-07-15 14:48:32 +00001300 VG_(printf_xml)(" </vargv>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001301
sewardj738856f2009-07-15 14:48:32 +00001302 VG_(printf_xml)(" <argv>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001303 if (VG_(args_the_exename))
bartb3af9cf2011-10-06 19:08:37 +00001304 VG_(printf_xml)(" <exe>%pS</exe>\n",
sewardj738856f2009-07-15 14:48:32 +00001305 VG_(args_the_exename));
sewardj14c7cc52007-02-25 15:08:24 +00001306 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
bartb3af9cf2011-10-06 19:08:37 +00001307 VG_(printf_xml)(
1308 " <arg>%pS</arg>\n",
sewardj738856f2009-07-15 14:48:32 +00001309 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1310 );
sewardj8665d8e2005-06-01 17:35:23 +00001311 }
sewardj738856f2009-07-15 14:48:32 +00001312 VG_(printf_xml)(" </argv>\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001313
sewardj738856f2009-07-15 14:48:32 +00001314 VG_(printf_xml)("</args>\n");
sewardj71bc3cb2005-05-19 00:25:45 +00001315 }
sewardj4cf05692002-10-27 20:28:29 +00001316
njnb6267bd2009-08-12 00:14:16 +00001317 // Last thing in the preamble is a blank line.
sewardj738856f2009-07-15 14:48:32 +00001318 if (VG_(clo_xml))
1319 VG_(printf_xml)("\n");
njnb6267bd2009-08-12 00:14:16 +00001320 else if (VG_(clo_verbosity) > 0)
1321 VG_(umsg)("\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001322
sewardjae284e52012-08-02 18:25:04 +00001323# if defined(VGO_darwin) && DARWIN_VERS == DARWIN_10_8
1324 /* Uh, this doesn't play nice with XML output. */
1325 umsg_or_xml( "WARNING: Support on MacOS 10.8 is experimental and mostly broken.\n");
1326 umsg_or_xml( "WARNING: Expect incorrect results, assertions and crashes.\n");
1327 umsg_or_xml( "WARNING: In particular, Memcheck on 32-bit programs will fail to\n");
1328 umsg_or_xml( "WARNING: detect any errors associated with heap-allocated data.\n");
1329 umsg_or_xml( "\n" );
1330# endif
1331
sewardjde4a1d02002-03-22 01:27:54 +00001332 if (VG_(clo_verbosity) > 1) {
sewardj92645592005-07-23 09:18:34 +00001333 SysRes fd;
sewardj1f0bbc72005-11-16 03:51:02 +00001334 VexArch vex_arch;
1335 VexArchInfo vex_archinfo;
sewardj45f4e7c2005-09-27 19:20:21 +00001336 if (!logging_to_fd)
sewardj738856f2009-07-15 14:48:32 +00001337 VG_(message)(Vg_DebugMsg, "\n");
njna3311642009-08-10 01:29:14 +00001338 VG_(message)(Vg_DebugMsg, "Valgrind options:\n");
sewardj14c7cc52007-02-25 15:08:24 +00001339 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
1340 VG_(message)(Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +00001341 " %s\n",
sewardj14c7cc52007-02-25 15:08:24 +00001342 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ));
sewardjde4a1d02002-03-22 01:27:54 +00001343 }
nethercotea70f7352004-04-18 12:08:46 +00001344
sewardj738856f2009-07-15 14:48:32 +00001345 VG_(message)(Vg_DebugMsg, "Contents of /proc/version:\n");
nethercotea70f7352004-04-18 12:08:46 +00001346 fd = VG_(open) ( "/proc/version", VKI_O_RDONLY, 0 );
njncda2f0f2009-05-18 02:12:08 +00001347 if (sr_isError(fd)) {
sewardj738856f2009-07-15 14:48:32 +00001348 VG_(message)(Vg_DebugMsg, " can't open /proc/version\n");
nethercotea70f7352004-04-18 12:08:46 +00001349 } else {
sewardj71bc3cb2005-05-19 00:25:45 +00001350# define BUF_LEN 256
florian19f91bb2012-11-10 22:29:54 +00001351 HChar version_buf[BUF_LEN];
njnf3977a32009-08-04 00:27:56 +00001352 Int n = VG_(read) ( sr_Res(fd), version_buf, BUF_LEN );
1353 vg_assert(n <= BUF_LEN);
1354 if (n > 0) {
1355 version_buf[n-1] = '\0';
sewardj738856f2009-07-15 14:48:32 +00001356 VG_(message)(Vg_DebugMsg, " %s\n", version_buf);
nethercotea70f7352004-04-18 12:08:46 +00001357 } else {
sewardj738856f2009-07-15 14:48:32 +00001358 VG_(message)(Vg_DebugMsg, " (empty?)\n");
nethercotea70f7352004-04-18 12:08:46 +00001359 }
njncda2f0f2009-05-18 02:12:08 +00001360 VG_(close)(sr_Res(fd));
sewardj71bc3cb2005-05-19 00:25:45 +00001361# undef BUF_LEN
nethercotea70f7352004-04-18 12:08:46 +00001362 }
sewardj1f0bbc72005-11-16 03:51:02 +00001363
1364 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
sewardje3121f32006-01-27 21:23:23 +00001365 VG_(message)(
1366 Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +00001367 "Arch and hwcaps: %s, %s\n",
sewardje3121f32006-01-27 21:23:23 +00001368 LibVEX_ppVexArch ( vex_arch ),
1369 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1370 );
sewardje66f2e02006-12-30 17:45:08 +00001371 VG_(message)(
1372 Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +00001373 "Page sizes: currently %d, max supported %d\n",
sewardje66f2e02006-12-30 17:45:08 +00001374 (Int)VKI_PAGE_SIZE, (Int)VKI_MAX_PAGE_SIZE
1375 );
sewardj738856f2009-07-15 14:48:32 +00001376 VG_(message)(Vg_DebugMsg,
1377 "Valgrind library directory: %s\n", VG_(libdir));
sewardjde4a1d02002-03-22 01:27:54 +00001378 }
nethercotef6a1d502004-08-09 12:21:57 +00001379}
1380
sewardjde4a1d02002-03-22 01:27:54 +00001381
nethercote71980f02004-01-24 18:18:54 +00001382/*====================================================================*/
1383/*=== File descriptor setup ===*/
1384/*====================================================================*/
1385
sewardj5f229e22005-09-28 01:36:01 +00001386/* Number of file descriptors that Valgrind tries to reserve for
1387 it's own use - just a small constant. */
1388#define N_RESERVED_FDS (10)
1389
nethercote71980f02004-01-24 18:18:54 +00001390static void setup_file_descriptors(void)
1391{
1392 struct vki_rlimit rl;
sewardj17c11042006-10-15 01:26:40 +00001393 Bool show = False;
nethercote71980f02004-01-24 18:18:54 +00001394
1395 /* Get the current file descriptor limits. */
1396 if (VG_(getrlimit)(VKI_RLIMIT_NOFILE, &rl) < 0) {
1397 rl.rlim_cur = 1024;
1398 rl.rlim_max = 1024;
1399 }
1400
njnf76d27a2009-05-28 01:53:07 +00001401# if defined(VGO_darwin)
1402 /* Darwin lies. It reports file max as RLIM_INFINITY but
1403 silently disallows anything bigger than 10240. */
1404 if (rl.rlim_cur >= 10240 && rl.rlim_max == 0x7fffffffffffffffULL) {
1405 rl.rlim_max = 10240;
1406 }
1407# endif
1408
sewardj17c11042006-10-15 01:26:40 +00001409 if (show)
njn8a7b41b2007-09-23 00:51:24 +00001410 VG_(printf)("fd limits: host, before: cur %lu max %lu\n",
sewardja8ffda62008-07-18 18:23:24 +00001411 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
sewardj17c11042006-10-15 01:26:40 +00001412
nethercote71980f02004-01-24 18:18:54 +00001413 /* Work out where to move the soft limit to. */
njn14319cc2005-03-13 06:26:22 +00001414 if (rl.rlim_cur + N_RESERVED_FDS <= rl.rlim_max) {
1415 rl.rlim_cur = rl.rlim_cur + N_RESERVED_FDS;
nethercote71980f02004-01-24 18:18:54 +00001416 } else {
1417 rl.rlim_cur = rl.rlim_max;
1418 }
1419
1420 /* Reserve some file descriptors for our use. */
njn14319cc2005-03-13 06:26:22 +00001421 VG_(fd_soft_limit) = rl.rlim_cur - N_RESERVED_FDS;
1422 VG_(fd_hard_limit) = rl.rlim_cur - N_RESERVED_FDS;
nethercote71980f02004-01-24 18:18:54 +00001423
1424 /* Update the soft limit. */
1425 VG_(setrlimit)(VKI_RLIMIT_NOFILE, &rl);
1426
sewardj17c11042006-10-15 01:26:40 +00001427 if (show) {
njn8a7b41b2007-09-23 00:51:24 +00001428 VG_(printf)("fd limits: host, after: cur %lu max %lu\n",
sewardja8ffda62008-07-18 18:23:24 +00001429 (UWord)rl.rlim_cur, (UWord)rl.rlim_max);
sewardj17c11042006-10-15 01:26:40 +00001430 VG_(printf)("fd limits: guest : cur %u max %u\n",
1431 VG_(fd_soft_limit), VG_(fd_hard_limit));
1432 }
1433
sewardj45f4e7c2005-09-27 19:20:21 +00001434 if (VG_(cl_exec_fd) != -1)
1435 VG_(cl_exec_fd) = VG_(safe_fd)( VG_(cl_exec_fd) );
nethercote71980f02004-01-24 18:18:54 +00001436}
1437
sewardjde4a1d02002-03-22 01:27:54 +00001438
njn2da73352005-06-18 01:35:16 +00001439/*====================================================================*/
nethercote71980f02004-01-24 18:18:54 +00001440/*=== main() ===*/
1441/*====================================================================*/
1442
sewardjfdf91b42005-09-28 00:53:09 +00001443/* When main() is entered, we should be on the following stack, not
1444 the one the kernel gave us. We will run on this stack until
1445 simulation of the root thread is started, at which point a transfer
1446 is made to a dynamically allocated stack. This is for the sake of
1447 uniform overflow detection for all Valgrind threads. This is
1448 marked global even though it isn't, because assembly code below
1449 needs to reference the name. */
1450
1451/*static*/ VgStack VG_(interim_stack);
1452
sewardjf9d2f9b2006-11-17 20:00:57 +00001453/* These are the structures used to hold info for creating the initial
1454 client image.
1455
1456 'iicii' mostly holds important register state present at system
1457 startup (_start_valgrind). valgrind_main() then fills in the rest
1458 of it and passes it to VG_(ii_create_image)(). That produces
1459 'iifii', which is later handed to VG_(ii_finalise_image). */
1460
1461/* In all OS-instantiations, the_iicii has a field .sp_at_startup.
1462 This should get some address inside the stack on which we gained
sewardjfdf91b42005-09-28 00:53:09 +00001463 control (eg, it could be the SP at startup). It doesn't matter
1464 exactly where in the stack it is. This value is passed to the
sewardjf9d2f9b2006-11-17 20:00:57 +00001465 address space manager at startup. On Linux, aspacem then uses it
1466 to identify the initial stack segment and hence the upper end of
1467 the usable address space. */
sewardjfdf91b42005-09-28 00:53:09 +00001468
sewardjf9d2f9b2006-11-17 20:00:57 +00001469static IICreateImageInfo the_iicii;
1470static IIFinaliseImageInfo the_iifii;
1471
sewardjfdf91b42005-09-28 00:53:09 +00001472
sewardj9c606bd2008-09-18 18:12:50 +00001473/* A simple pair structure, used for conveying debuginfo handles to
1474 calls to VG_TRACK(new_mem_startup, ...). */
1475typedef struct { Addr a; ULong ull; } Addr_n_ULong;
1476
1477
sewardj1ae3f3a2005-09-28 10:47:38 +00001478/* --- Forwards decls to do with shutdown --- */
1479
1480static void final_tidyup(ThreadId tid);
1481
1482/* Do everything which needs doing when the last thread exits */
1483static
1484void shutdown_actions_NORETURN( ThreadId tid,
1485 VgSchedReturnCode tids_schedretcode );
1486
1487/* --- end of Forwards decls to do with shutdown --- */
sewardjfdf91b42005-09-28 00:53:09 +00001488
1489
sewardjf9d2f9b2006-11-17 20:00:57 +00001490/* By the time we get to valgrind_main, the_iicii should already have
1491 been filled in with any important details as required by whatever
1492 OS we have been built for.
1493*/
sewardj17c11042006-10-15 01:26:40 +00001494static
sewardjf9d2f9b2006-11-17 20:00:57 +00001495Int valgrind_main ( Int argc, HChar **argv, HChar **envp )
nethercote71980f02004-01-24 18:18:54 +00001496{
florian19f91bb2012-11-10 22:29:54 +00001497 const HChar* toolname = "memcheck"; // default to Memcheck
sewardj13247ca2005-12-30 22:52:20 +00001498 Int need_help = 0; // 0 = no, 1 = --help, 2 = --help-debug
sewardjde764e82007-11-09 23:13:22 +00001499 ThreadId tid_main = VG_INVALID_THREADID;
sewardj738856f2009-07-15 14:48:32 +00001500 Bool logging_to_fd = False;
florian19f91bb2012-11-10 22:29:54 +00001501 HChar* xml_fname_unexpanded = NULL;
sewardj45f4e7c2005-09-27 19:20:21 +00001502 Int loglevel, i;
nethercote73b526f2004-10-31 18:48:21 +00001503 struct vki_rlimit zero = { 0, 0 };
sewardj9c606bd2008-09-18 18:12:50 +00001504 XArray* addr2dihandle = NULL;
sewardj17c11042006-10-15 01:26:40 +00001505
philippe14711e82012-06-14 22:18:50 +00001506 // For an inner Valgrind, register the interim stack asap.
1507 // This is needed to allow the outer valgrind to do stacktraces during init.
1508 // Note that this stack is not unregistered when the main thread
1509 // is switching to the (real) stack. Unregistering this would imply
1510 // to save the stack id in a global variable, and have a "if"
1511 // in run_a_thread_NORETURN to do the unregistration only for the
1512 // main thread. This unregistration is not worth this complexity.
1513 INNER_REQUEST
1514 ((void) VALGRIND_STACK_REGISTER
1515 (&VG_(interim_stack).bytes[0],
1516 &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack))));
1517
1518
nethercote71980f02004-01-24 18:18:54 +00001519 //============================================================
nethercote71980f02004-01-24 18:18:54 +00001520 //
sewardj45f4e7c2005-09-27 19:20:21 +00001521 // Nb: startup is complex. Prerequisites are shown at every step.
nethercote71980f02004-01-24 18:18:54 +00001522 // *** Be very careful when messing with the order ***
sewardj45f4e7c2005-09-27 19:20:21 +00001523 //
1524 // The first order of business is to get debug logging, the address
1525 // space manager and the dynamic memory manager up and running.
1526 // Once that's done, we can relax a bit.
1527 //
nethercote71980f02004-01-24 18:18:54 +00001528 //============================================================
sewardj45f4e7c2005-09-27 19:20:21 +00001529
1530 /* This is needed to make VG_(getenv) usable early. */
florian19f91bb2012-11-10 22:29:54 +00001531 VG_(client_envp) = (HChar**)envp;
nethercote71980f02004-01-24 18:18:54 +00001532
sewardj1cf558c2005-04-25 01:36:56 +00001533 //--------------------------------------------------------------
njnf76d27a2009-05-28 01:53:07 +00001534 // Start up Mach kernel interface, if any
1535 // p: none
1536 //--------------------------------------------------------------
1537# if defined(VGO_darwin)
1538 VG_(mach_init)();
1539# endif
1540
1541 //--------------------------------------------------------------
sewardj1cf558c2005-04-25 01:36:56 +00001542 // Start up the logging mechanism
1543 // p: none
1544 //--------------------------------------------------------------
1545 /* Start the debugging-log system ASAP. First find out how many
njn83df0b62009-02-25 01:01:05 +00001546 "-d"s were specified. This is a pre-scan of the command line. Also
philipped99c26a2012-07-31 22:17:28 +00001547 get --profile-heap=yes, --core-redzone-size, --redzone-size which are
1548 needed by the time we start up dynamic memory management. */
sewardj1cf558c2005-04-25 01:36:56 +00001549 loglevel = 0;
1550 for (i = 1; i < argc; i++) {
njn83df0b62009-02-25 01:01:05 +00001551 if (argv[i][0] != '-') break;
1552 if VG_STREQ(argv[i], "--") break;
1553 if VG_STREQ(argv[i], "-d") loglevel++;
1554 if VG_BOOL_CLO(argv[i], "--profile-heap", VG_(clo_profile_heap)) {}
philipped99c26a2012-07-31 22:17:28 +00001555 if VG_BINT_CLO(argv[i], "--core-redzone-size", VG_(clo_core_redzone_size),
1556 0, MAX_CLO_REDZONE_SZB) {}
1557 if VG_BINT_CLO(argv[i], "--redzone-size", VG_(clo_redzone_size),
1558 0, MAX_CLO_REDZONE_SZB) {}
sewardj1cf558c2005-04-25 01:36:56 +00001559 }
1560
1561 /* ... and start the debug logger. Now we can safely emit logging
1562 messages all through startup. */
sewardj10759312005-05-30 23:52:47 +00001563 VG_(debugLog_startup)(loglevel, "Stage 2 (main)");
sewardj45f4e7c2005-09-27 19:20:21 +00001564 VG_(debugLog)(1, "main", "Welcome to Valgrind version "
1565 VERSION " debug logging\n");
1566
1567 //--------------------------------------------------------------
1568 // Ensure we're on a plausible stack.
1569 // p: logging
1570 //--------------------------------------------------------------
1571 VG_(debugLog)(1, "main", "Checking current stack is plausible\n");
sewardjfdf91b42005-09-28 00:53:09 +00001572 { HChar* limLo = (HChar*)(&VG_(interim_stack).bytes[0]);
1573 HChar* limHi = limLo + sizeof(VG_(interim_stack));
sewardjed8b0f62012-09-02 21:17:36 +00001574 HChar* volatile
1575 aLocal = (HChar*)&limLo; /* any auto local will do */
1576 /* Re "volatile": Apple clang version 4.0
1577 (tags/Apple/clang-421.0.57) (based on LLVM 3.1svn)" appeared
1578 to miscompile the following check, causing run to abort at
1579 this point (in 64-bit mode) even though aLocal is within limLo
1580 .. limHi. But in fact clang is within its rights to do
1581 strange things here. "The reason is that the comparisons
1582 aLocal < limLo and aLocal >= limHi cause undefined behaviour
1583 (according to c99 6.5.8) because they compare pointers that do
1584 not point into the same aggregate." Adding "volatile" appears
1585 to fix it because "The compiler would have to prove that there
1586 is undefined behavior in order to exploit it. But as a
1587 volatile variable can change its value in ways invisible to
1588 the compiler, the compiler must make the conservative
1589 assumption that it points into the same aggregate as the other
1590 pointer its compared against. I.e. the behaviour is possibly
1591 defined." (Analysis by Florian Krohm). */
sewardj45f4e7c2005-09-27 19:20:21 +00001592 if (aLocal < limLo || aLocal >= limHi) {
1593 /* something's wrong. Stop. */
1594 VG_(debugLog)(0, "main", "Root stack %p to %p, a local %p\n",
1595 limLo, limHi, aLocal );
1596 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1597 "Initial stack switched failed.\n");
1598 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1599 VG_(exit)(1);
1600 }
1601 }
1602
1603 //--------------------------------------------------------------
1604 // Ensure we have a plausible pointer to the stack on which
1605 // we gained control (not the current stack!)
1606 // p: logging
1607 //--------------------------------------------------------------
1608 VG_(debugLog)(1, "main", "Checking initial stack was noted\n");
sewardjf9d2f9b2006-11-17 20:00:57 +00001609 if (the_iicii.sp_at_startup == 0) {
sewardj45f4e7c2005-09-27 19:20:21 +00001610 VG_(debugLog)(0, "main", "Valgrind: FATAL: "
1611 "Initial stack was not noted.\n");
1612 VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n");
1613 VG_(exit)(1);
1614 }
1615
1616 //--------------------------------------------------------------
1617 // Start up the address space manager, and determine the
1618 // approximate location of the client's stack
njnea2d6fd2010-07-01 00:20:20 +00001619 // p: logging, plausible-stack
sewardj45f4e7c2005-09-27 19:20:21 +00001620 //--------------------------------------------------------------
1621 VG_(debugLog)(1, "main", "Starting the address space manager\n");
sewardj5db15402012-06-07 09:13:21 +00001622 vg_assert(VKI_PAGE_SIZE == 4096 || VKI_PAGE_SIZE == 65536
1623 || VKI_PAGE_SIZE == 16384);
1624 vg_assert(VKI_MAX_PAGE_SIZE == 4096 || VKI_MAX_PAGE_SIZE == 65536
1625 || VKI_MAX_PAGE_SIZE == 16384);
sewardje66f2e02006-12-30 17:45:08 +00001626 vg_assert(VKI_PAGE_SIZE <= VKI_MAX_PAGE_SIZE);
1627 vg_assert(VKI_PAGE_SIZE == (1 << VKI_PAGE_SHIFT));
1628 vg_assert(VKI_MAX_PAGE_SIZE == (1 << VKI_MAX_PAGE_SHIFT));
sewardjf9d2f9b2006-11-17 20:00:57 +00001629 the_iicii.clstack_top = VG_(am_startup)( the_iicii.sp_at_startup );
sewardj45f4e7c2005-09-27 19:20:21 +00001630 VG_(debugLog)(1, "main", "Address space manager is running\n");
1631
1632 //--------------------------------------------------------------
1633 // Start up the dynamic memory manager
1634 // p: address space management
philipped99c26a2012-07-31 22:17:28 +00001635 // p: getting --profile-heap,--core-redzone-size,--redzone-size
sewardj45f4e7c2005-09-27 19:20:21 +00001636 // In fact m_mallocfree is self-initialising, so there's no
1637 // initialisation call to do. Instead, try a simple malloc/
1638 // free pair right now to check that nothing is broken.
1639 //--------------------------------------------------------------
1640 VG_(debugLog)(1, "main", "Starting the dynamic memory manager\n");
sewardj9c606bd2008-09-18 18:12:50 +00001641 { void* p = VG_(malloc)( "main.vm.1", 12345 );
sewardj45f4e7c2005-09-27 19:20:21 +00001642 if (p) VG_(free)( p );
1643 }
1644 VG_(debugLog)(1, "main", "Dynamic memory manager is running\n");
sewardj1cf558c2005-04-25 01:36:56 +00001645
nethercotef4928da2004-06-15 10:54:40 +00001646 //============================================================
sewardj45f4e7c2005-09-27 19:20:21 +00001647 //
1648 // Dynamic memory management is now available.
1649 //
nethercotef4928da2004-06-15 10:54:40 +00001650 //============================================================
1651
sewardj45f4e7c2005-09-27 19:20:21 +00001652 //--------------------------------------------------------------
sewardjf98e1c02008-10-25 16:22:41 +00001653 // Initialise m_debuginfo
1654 // p: dynamic memory allocation
1655 VG_(debugLog)(1, "main", "Initialise m_debuginfo\n");
1656 VG_(di_initialise)();
1657
1658 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001659 // Look for alternative libdir
1660 { HChar *cp = VG_(getenv)(VALGRIND_LIB);
1661 if (cp != NULL)
1662 VG_(libdir) = cp;
njncde90d32009-07-22 22:41:38 +00001663 VG_(debugLog)(1, "main", "VG_(libdir) = %s\n", VG_(libdir));
sewardj45f4e7c2005-09-27 19:20:21 +00001664 }
1665
1666 //--------------------------------------------------------------
1667 // Extract the launcher name from the environment.
njna842d792009-05-21 01:15:18 +00001668 VG_(debugLog)(1, "main", "Getting launcher's name ...\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001669 VG_(name_of_launcher) = VG_(getenv)(VALGRIND_LAUNCHER);
1670 if (VG_(name_of_launcher) == NULL) {
1671 VG_(printf)("valgrind: You cannot run '%s' directly.\n", argv[0]);
1672 VG_(printf)("valgrind: You should use $prefix/bin/valgrind.\n");
1673 VG_(exit)(1);
1674 }
njna842d792009-05-21 01:15:18 +00001675 VG_(debugLog)(1, "main", "... %s\n", VG_(name_of_launcher));
sewardj45f4e7c2005-09-27 19:20:21 +00001676
1677 //--------------------------------------------------------------
fitzhardingeb50068f2004-02-24 23:42:55 +00001678 // Get the current process datasize rlimit, and set it to zero.
1679 // This prevents any internal uses of brk() from having any effect.
1680 // We remember the old value so we can restore it on exec, so that
1681 // child processes will have a reasonable brk value.
1682 VG_(getrlimit)(VKI_RLIMIT_DATA, &VG_(client_rlimit_data));
1683 zero.rlim_max = VG_(client_rlimit_data).rlim_max;
1684 VG_(setrlimit)(VKI_RLIMIT_DATA, &zero);
thughesc37184f2004-09-11 14:16:57 +00001685
1686 // Get the current process stack rlimit.
1687 VG_(getrlimit)(VKI_RLIMIT_STACK, &VG_(client_rlimit_stack));
1688
sewardje2d1e672005-11-12 23:10:48 +00001689 //--------------------------------------------------------------
1690 // Figure out what sort of CPU we're on, and whether it is
1691 // able to run V.
1692 VG_(debugLog)(1, "main", "Get hardware capabilities ...\n");
1693 { VexArch vex_arch;
1694 VexArchInfo vex_archinfo;
1695 Bool ok = VG_(machine_get_hwcaps)();
1696 if (!ok) {
1697 VG_(printf)("\n");
1698 VG_(printf)("valgrind: fatal error: unsupported CPU.\n");
1699 VG_(printf)(" Supported CPUs are:\n");
1700 VG_(printf)(" * x86 (practically any; Pentium-I or above), "
1701 "AMD Athlon or above)\n");
1702 VG_(printf)(" * AMD Athlon64/Opteron\n");
1703 VG_(printf)(" * PowerPC (most; ppc405 and above)\n");
sewardjb5b87402011-03-07 16:05:35 +00001704 VG_(printf)(" * System z (64bit only - s390x; z900 and above)\n");
sewardje2d1e672005-11-12 23:10:48 +00001705 VG_(printf)("\n");
1706 VG_(exit)(1);
1707 }
1708 VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo );
sewardje3121f32006-01-27 21:23:23 +00001709 VG_(debugLog)(
1710 1, "main", "... arch = %s, hwcaps = %s\n",
1711 LibVEX_ppVexArch ( vex_arch ),
1712 LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps )
1713 );
sewardje2d1e672005-11-12 23:10:48 +00001714 }
1715
sewardj198f34f2007-07-09 23:13:07 +00001716 //--------------------------------------------------------------
1717 // Record the working directory at startup
sewardj6e9de462011-06-28 07:25:29 +00001718 // p: none
sewardj198f34f2007-07-09 23:13:07 +00001719 VG_(debugLog)(1, "main", "Getting the working directory at startup\n");
1720 { Bool ok = VG_(record_startup_wd)();
1721 if (!ok)
1722 VG_(err_config_error)( "Can't establish current working "
florian1763e812011-07-12 19:07:05 +00001723 "directory at startup\n");
sewardj198f34f2007-07-09 23:13:07 +00001724 }
florian19f91bb2012-11-10 22:29:54 +00001725 { HChar buf[VKI_PATH_MAX+1];
sewardj198f34f2007-07-09 23:13:07 +00001726 Bool ok = VG_(get_startup_wd)( buf, sizeof(buf) );
1727 vg_assert(ok);
1728 buf[VKI_PATH_MAX] = 0;
1729 VG_(debugLog)(1, "main", "... %s\n", buf );
1730 }
1731
sewardj45f4e7c2005-09-27 19:20:21 +00001732 //============================================================
1733 // Command line argument handling order:
1734 // * If --help/--help-debug are present, show usage message
1735 // (including the tool-specific usage)
1736 // * (If no --tool option given, default to Memcheck)
1737 // * Then, if client is missing, abort with error msg
1738 // * Then, if any cmdline args are bad, abort with error msg
1739 //============================================================
1740
1741 //--------------------------------------------------------------
1742 // Split up argv into: C args, V args, V extra args, and exename.
1743 // p: dynamic memory allocation
1744 //--------------------------------------------------------------
1745 VG_(debugLog)(1, "main", "Split up command line\n");
1746 VG_(split_up_argv)( argc, argv );
sewardj14c7cc52007-02-25 15:08:24 +00001747 vg_assert( VG_(args_for_valgrind) );
1748 vg_assert( VG_(args_for_client) );
sewardj45f4e7c2005-09-27 19:20:21 +00001749 if (0) {
sewardj14c7cc52007-02-25 15:08:24 +00001750 for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++)
1751 VG_(printf)(
1752 "varg %s\n",
1753 * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )
1754 );
sewardj45f4e7c2005-09-27 19:20:21 +00001755 VG_(printf)(" exe %s\n", VG_(args_the_exename));
sewardj14c7cc52007-02-25 15:08:24 +00001756 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++)
1757 VG_(printf)(
1758 "carg %s\n",
1759 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
1760 );
nethercote71980f02004-01-24 18:18:54 +00001761 }
1762
1763 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001764 // Extract tool name and whether help has been requested.
1765 // Note we can't print the help message yet, even if requested,
1766 // because the tool has not been initialised.
1767 // p: split_up_argv [for VG_(args_for_valgrind)]
nethercote71980f02004-01-24 18:18:54 +00001768 //--------------------------------------------------------------
sewardj95d86c02007-12-18 01:49:23 +00001769 VG_(debugLog)(1, "main",
1770 "(early_) Process Valgrind's command line options\n");
1771 early_process_cmd_line_options(&need_help, &toolname);
nethercote71980f02004-01-24 18:18:54 +00001772
sewardj45f4e7c2005-09-27 19:20:21 +00001773 // Set default vex control params
1774 LibVEX_default_VexControl(& VG_(clo_vex_control));
nethercote71980f02004-01-24 18:18:54 +00001775
1776 //--------------------------------------------------------------
1777 // Load client executable, finding in $PATH if necessary
njn83df0b62009-02-25 01:01:05 +00001778 // p: early_process_cmd_line_options() [for 'exec', 'need_help',
1779 // clo_max_stackframe,
1780 // clo_main_stacksize]
sewardj95d86c02007-12-18 01:49:23 +00001781 // p: layout_remaining_space [so there's space]
sewardj17c11042006-10-15 01:26:40 +00001782 //
nethercote71980f02004-01-24 18:18:54 +00001783 // Set up client's environment
sewardj95d86c02007-12-18 01:49:23 +00001784 // p: set-libdir [for VG_(libdir)]
1785 // p: early_process_cmd_line_options [for toolname]
sewardj17c11042006-10-15 01:26:40 +00001786 //
nethercote5ee67ca2004-06-22 14:00:09 +00001787 // Setup client stack, eip, and VG_(client_arg[cv])
nethercote71980f02004-01-24 18:18:54 +00001788 // p: load_client() [for 'info']
1789 // p: fix_environment() [for 'env']
sewardj17c11042006-10-15 01:26:40 +00001790 //
sewardj45f4e7c2005-09-27 19:20:21 +00001791 // Setup client data (brk) segment. Initially a 1-page segment
1792 // which abuts a shrinkable reservation.
1793 // p: load_client() [for 'info' and hence VG_(brk_base)]
sewardjf9d2f9b2006-11-17 20:00:57 +00001794 //
1795 // p: _start_in_C (for zeroing out the_iicii and putting some
1796 // initial values into it)
sewardj45f4e7c2005-09-27 19:20:21 +00001797 //--------------------------------------------------------------
sewardj17c11042006-10-15 01:26:40 +00001798 if (!need_help) {
sewardjf9d2f9b2006-11-17 20:00:57 +00001799 VG_(debugLog)(1, "main", "Create initial image\n");
1800
njnf76d27a2009-05-28 01:53:07 +00001801# if defined(VGO_linux) || defined(VGO_darwin)
sewardjf9d2f9b2006-11-17 20:00:57 +00001802 the_iicii.argv = argv;
1803 the_iicii.envp = envp;
1804 the_iicii.toolname = toolname;
sewardjf9d2f9b2006-11-17 20:00:57 +00001805# else
njna842d792009-05-21 01:15:18 +00001806# error "Unknown platform"
sewardjf9d2f9b2006-11-17 20:00:57 +00001807# endif
1808
sewardjdc2f79e2007-12-22 14:14:04 +00001809 /* NOTE: this call reads VG_(clo_main_stacksize). */
sewardjf9d2f9b2006-11-17 20:00:57 +00001810 the_iifii = VG_(ii_create_image)( the_iicii );
sewardj45f4e7c2005-09-27 19:20:21 +00001811 }
nethercote71980f02004-01-24 18:18:54 +00001812
1813 //==============================================================
sewardj45f4e7c2005-09-27 19:20:21 +00001814 //
1815 // Finished loading/setting up the client address space.
1816 //
nethercote71980f02004-01-24 18:18:54 +00001817 //==============================================================
1818
1819 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00001820 // setup file descriptors
1821 // p: n/a
1822 //--------------------------------------------------------------
sewardj1fbc1a52005-04-25 02:05:54 +00001823 VG_(debugLog)(1, "main", "Setup file descriptors\n");
nethercote71980f02004-01-24 18:18:54 +00001824 setup_file_descriptors();
1825
1826 //--------------------------------------------------------------
tom41ad7e72012-10-04 20:27:38 +00001827 // create fake /proc/<pid>/cmdline and /proc/<pid>/auxv files
1828 // and then unlink them, but hold onto the fds, so we can handr
1829 // them out to the client when it tries to open
1830 // /proc/<pid>/cmdline or /proc/<pid>/auxv for itself.
sewardj45f4e7c2005-09-27 19:20:21 +00001831 // p: setup file descriptors
tom41ad7e72012-10-04 20:27:38 +00001832 // p: ii_create_image for VG_(client_auxv) setup.
nethercotec314eba2004-07-15 12:59:41 +00001833 //--------------------------------------------------------------
bart9b533f82009-08-25 20:15:41 +00001834#if !defined(VGO_linux)
1835 // client shouldn't be using /proc!
1836 VG_(cl_cmdline_fd) = -1;
tom41ad7e72012-10-04 20:27:38 +00001837 VG_(cl_auxv_fd) = -1;
bart9b533f82009-08-25 20:15:41 +00001838#else
1839 if (!need_help) {
philippecc648262013-05-26 21:09:20 +00001840 HChar buf[50], buf2[VG_(mkstemp_fullname_bufsz)(50-1)];
bart9b533f82009-08-25 20:15:41 +00001841 HChar nul[1];
1842 Int fd, r;
barta3054f52010-06-14 18:12:56 +00001843 const HChar* exename;
nethercotec314eba2004-07-15 12:59:41 +00001844
bart9b533f82009-08-25 20:15:41 +00001845 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/cmdline\n");
sewardj45f4e7c2005-09-27 19:20:21 +00001846
bart9b533f82009-08-25 20:15:41 +00001847 VG_(sprintf)(buf, "proc_%d_cmdline", VG_(getpid)());
1848 fd = VG_(mkstemp)( buf, buf2 );
1849 if (fd == -1)
florian1763e812011-07-12 19:07:05 +00001850 VG_(err_config_error)("Can't create client cmdline file in %s\n", buf2);
sewardj45f4e7c2005-09-27 19:20:21 +00001851
bart9b533f82009-08-25 20:15:41 +00001852 nul[0] = 0;
1853 exename = VG_(args_the_exename) ? VG_(args_the_exename)
1854 : "unknown_exename";
sewardjc7ffc942011-03-28 16:26:42 +00001855 VG_(write)(fd, exename, VG_(strlen)( exename ));
bart9b533f82009-08-25 20:15:41 +00001856 VG_(write)(fd, nul, 1);
1857
1858 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
1859 HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i );
1860 VG_(write)(fd, arg, VG_(strlen)( arg ));
sewardj45f4e7c2005-09-27 19:20:21 +00001861 VG_(write)(fd, nul, 1);
1862 }
bart9b533f82009-08-25 20:15:41 +00001863
1864 /* Don't bother to seek the file back to the start; instead do
1865 it every time a copy of it is given out (by PRE(sys_open)).
1866 That is probably more robust across fork() etc. */
1867
1868 /* Now delete it, but hang on to the fd. */
1869 r = VG_(unlink)( buf2 );
1870 if (r)
florian1763e812011-07-12 19:07:05 +00001871 VG_(err_config_error)("Can't delete client cmdline file in %s\n", buf2);
bart9b533f82009-08-25 20:15:41 +00001872
1873 VG_(cl_cmdline_fd) = fd;
tom41ad7e72012-10-04 20:27:38 +00001874
1875 VG_(debugLog)(1, "main", "Create fake /proc/<pid>/auxv\n");
1876
1877 VG_(sprintf)(buf, "proc_%d_auxv", VG_(getpid)());
1878 fd = VG_(mkstemp)( buf, buf2 );
1879 if (fd == -1)
1880 VG_(err_config_error)("Can't create client auxv file in %s\n", buf2);
1881
1882 UWord *client_auxv = VG_(client_auxv);
1883 unsigned int client_auxv_len = 0;
1884 while (*client_auxv != 0) {
1885 client_auxv++;
1886 client_auxv++;
1887 client_auxv_len += 2 * sizeof(UWord);
1888 }
1889 client_auxv_len += 2 * sizeof(UWord);
1890
1891 VG_(write)(fd, VG_(client_auxv), client_auxv_len);
1892
1893 /* Don't bother to seek the file back to the start; instead do
1894 it every time a copy of it is given out (by PRE(sys_open)).
1895 That is probably more robust across fork() etc. */
1896
1897 /* Now delete it, but hang on to the fd. */
1898 r = VG_(unlink)( buf2 );
1899 if (r)
1900 VG_(err_config_error)("Can't delete client auxv file in %s\n", buf2);
1901
1902 VG_(cl_auxv_fd) = fd;
sewardj45f4e7c2005-09-27 19:20:21 +00001903 }
bart9b533f82009-08-25 20:15:41 +00001904#endif
nethercotec314eba2004-07-15 12:59:41 +00001905
1906 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001907 // Init tool part 1: pre_clo_init
nethercotec314eba2004-07-15 12:59:41 +00001908 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
nethercotec314eba2004-07-15 12:59:41 +00001909 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
nethercote71980f02004-01-24 18:18:54 +00001910 //--------------------------------------------------------------
sewardj7cf4e6b2008-05-01 20:24:26 +00001911 VG_(debugLog)(1, "main", "Initialise the tool part 1 (pre_clo_init)\n");
njn08ce7b32009-02-27 03:38:28 +00001912 VG_(tl_pre_clo_init)();
nethercote71980f02004-01-24 18:18:54 +00001913
sewardj45f4e7c2005-09-27 19:20:21 +00001914 //--------------------------------------------------------------
nethercotef4928da2004-06-15 10:54:40 +00001915 // If --tool and --help/--help-debug was given, now give the core+tool
1916 // help message
sewardj95d86c02007-12-18 01:49:23 +00001917 // p: early_process_cmd_line_options() [for 'need_help']
1918 // p: tl_pre_clo_init [for 'VG_(tdict).usage']
sewardj45f4e7c2005-09-27 19:20:21 +00001919 //--------------------------------------------------------------
1920 VG_(debugLog)(1, "main", "Print help and quit, if requested\n");
nethercotef4928da2004-06-15 10:54:40 +00001921 if (need_help) {
njncce38e62010-07-06 04:25:12 +00001922 usage_NORETURN(/*--help-debug?*/need_help >= 2);
nethercotef4928da2004-06-15 10:54:40 +00001923 }
nethercotec314eba2004-07-15 12:59:41 +00001924
sewardj45f4e7c2005-09-27 19:20:21 +00001925 //--------------------------------------------------------------
1926 // Process command line options to Valgrind + tool
1927 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1928 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1929 //--------------------------------------------------------------
sewardj95d86c02007-12-18 01:49:23 +00001930 VG_(debugLog)(1, "main",
1931 "(main_) Process Valgrind's command line options, "
1932 "setup logging\n");
sewardj738856f2009-07-15 14:48:32 +00001933 main_process_cmd_line_options ( &logging_to_fd, &xml_fname_unexpanded,
1934 toolname );
sewardj45f4e7c2005-09-27 19:20:21 +00001935
1936 //--------------------------------------------------------------
sewardj592ae092005-11-08 19:01:44 +00001937 // Zeroise the millisecond counter by doing a first read of it.
1938 // p: none
1939 //--------------------------------------------------------------
1940 (void) VG_(read_millisecond_timer)();
1941
1942 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001943 // Print the preamble
1944 // p: tl_pre_clo_init [for 'VG_(details).name' and friends]
sewardj738856f2009-07-15 14:48:32 +00001945 // p: main_process_cmd_line_options()
1946 // [for VG_(clo_verbosity), VG_(clo_xml),
1947 // logging_to_fd, xml_fname_unexpanded]
sewardj45f4e7c2005-09-27 19:20:21 +00001948 //--------------------------------------------------------------
1949 VG_(debugLog)(1, "main", "Print the preamble...\n");
sewardj738856f2009-07-15 14:48:32 +00001950 print_preamble(logging_to_fd, xml_fname_unexpanded, toolname);
sewardj45f4e7c2005-09-27 19:20:21 +00001951 VG_(debugLog)(1, "main", "...finished the preamble\n");
1952
1953 //--------------------------------------------------------------
1954 // Init tool part 2: post_clo_init
1955 // p: setup_client_stack() [for 'VG_(client_arg[cv]']
1956 // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)']
1957 // p: print_preamble() [so any warnings printed in post_clo_init
1958 // are shown after the preamble]
1959 //--------------------------------------------------------------
1960 VG_(debugLog)(1, "main", "Initialise the tool part 2 (post_clo_init)\n");
njn51d827b2005-05-09 01:02:08 +00001961 VG_TDICT_CALL(tool_post_clo_init);
sewardj7cf4e6b2008-05-01 20:24:26 +00001962 {
1963 /* The tool's "needs" will by now be finalised, since it has no
1964 further opportunity to specify them. So now sanity check
1965 them. */
floriane6a4ed12012-10-21 02:30:18 +00001966 const HChar* s;
sewardj7cf4e6b2008-05-01 20:24:26 +00001967 Bool ok;
1968 ok = VG_(sanity_check_needs)( &s );
1969 if (!ok) {
1970 VG_(tool_panic)(s);
1971 }
1972 }
nethercotef4928da2004-06-15 10:54:40 +00001973
1974 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001975 // Initialise translation table and translation cache
1976 // p: aspacem [??]
1977 // p: tl_pre_clo_init [for 'VG_(details).avg_translation_sizeB']
nethercote71980f02004-01-24 18:18:54 +00001978 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00001979 VG_(debugLog)(1, "main", "Initialise TT/TC\n");
1980 VG_(init_tt_tc)();
sewardjb5f6f512005-03-10 23:59:00 +00001981
sewardj45f4e7c2005-09-27 19:20:21 +00001982 //--------------------------------------------------------------
1983 // Initialise the redirect table.
1984 // p: init_tt_tc [so it can call VG_(search_transtab) safely]
1985 // p: aspacem [so can change ownership of sysinfo pages]
1986 //--------------------------------------------------------------
1987 VG_(debugLog)(1, "main", "Initialise redirects\n");
sewardj0ec07f32006-01-12 12:32:32 +00001988 VG_(redir_initialise)();
nethercote71980f02004-01-24 18:18:54 +00001989
1990 //--------------------------------------------------------------
1991 // Allow GDB attach
sewardj95d86c02007-12-18 01:49:23 +00001992 // p: main_process_cmd_line_options() [for VG_(clo_wait_for_gdb)]
nethercote71980f02004-01-24 18:18:54 +00001993 //--------------------------------------------------------------
1994 /* Hook to delay things long enough so we can get the pid and
1995 attach GDB in another shell. */
1996 if (VG_(clo_wait_for_gdb)) {
sewardj87cd71c2011-07-05 09:13:41 +00001997 ULong iters, q;
sewardj1fbc1a52005-04-25 02:05:54 +00001998 VG_(debugLog)(1, "main", "Wait for GDB\n");
sewardj93ab8572005-02-06 14:10:40 +00001999 VG_(printf)("pid=%d, entering delay loop\n", VG_(getpid)());
sewardj8211a572005-06-23 21:37:47 +00002000
2001# if defined(VGP_x86_linux)
sewardj291849f2012-04-20 23:58:55 +00002002 iters = 10;
sewardj2c48c7b2005-11-29 13:05:56 +00002003# elif defined(VGP_amd64_linux) || defined(VGP_ppc64_linux)
sewardj8211a572005-06-23 21:37:47 +00002004 iters = 10;
2005# elif defined(VGP_ppc32_linux)
sewardjd714d2e2005-07-08 18:24:04 +00002006 iters = 5;
sewardj59570ff2010-01-01 11:59:33 +00002007# elif defined(VGP_arm_linux)
sewardj291849f2012-04-20 23:58:55 +00002008 iters = 5;
sewardjb5b87402011-03-07 16:05:35 +00002009# elif defined(VGP_s390x_linux)
2010 iters = 10;
petarj4df0bfc2013-02-27 23:17:33 +00002011# elif defined(VGP_mips32_linux) || defined(VGP_mips64_linux)
sewardj5db15402012-06-07 09:13:21 +00002012 iters = 10;
njnf76d27a2009-05-28 01:53:07 +00002013# elif defined(VGO_darwin)
2014 iters = 3;
sewardj8211a572005-06-23 21:37:47 +00002015# else
sewardj17c11042006-10-15 01:26:40 +00002016# error "Unknown plat"
sewardj8211a572005-06-23 21:37:47 +00002017# endif
2018
sewardj87cd71c2011-07-05 09:13:41 +00002019 iters *= 1000ULL * 1000 * 1000;
sewardj8211a572005-06-23 21:37:47 +00002020 for (q = 0; q < iters; q++)
sewardj87cd71c2011-07-05 09:13:41 +00002021 __asm__ __volatile__("" ::: "memory","cc");
nethercote71980f02004-01-24 18:18:54 +00002022 }
2023
sewardjb5d320c2005-03-13 18:57:15 +00002024 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00002025 // Search for file descriptors that are inherited from our parent
sewardj95d86c02007-12-18 01:49:23 +00002026 // p: main_process_cmd_line_options [for VG_(clo_track_fds)]
nethercote71980f02004-01-24 18:18:54 +00002027 //--------------------------------------------------------------
sewardj1fbc1a52005-04-25 02:05:54 +00002028 if (VG_(clo_track_fds)) {
2029 VG_(debugLog)(1, "main", "Init preopened fds\n");
nethercote71980f02004-01-24 18:18:54 +00002030 VG_(init_preopened_fds)();
sewardj1fbc1a52005-04-25 02:05:54 +00002031 }
nethercote71980f02004-01-24 18:18:54 +00002032
2033 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00002034 // Load debug info for the existing segments.
2035 // p: setup_code_redirect_table [so that redirs can be recorded]
2036 // p: mallocfree
2037 // p: probably: setup fds and process CLOs, so that logging works
sewardjf98e1c02008-10-25 16:22:41 +00002038 // p: initialise m_debuginfo
sewardj9c606bd2008-09-18 18:12:50 +00002039 //
2040 // While doing this, make a note of the debuginfo-handles that
sewardj6e9de462011-06-28 07:25:29 +00002041 // come back from VG_(di_notify_mmap).
sewardj9c606bd2008-09-18 18:12:50 +00002042 // Later, in "Tell the tool about the initial client memory permissions"
2043 // (just below) we can then hand these handles off to the tool in
2044 // calls to VG_TRACK(new_mem_startup, ...). This gives the tool the
2045 // opportunity to make further queries to m_debuginfo before the
2046 // client is started, if it wants. We put this information into an
2047 // XArray, each handle along with the associated segment start address,
2048 // and search the XArray for the handles later, when calling
2049 // VG_TRACK(new_mem_startup, ...).
sewardj45f4e7c2005-09-27 19:20:21 +00002050 //--------------------------------------------------------------
2051 VG_(debugLog)(1, "main", "Load initial debug info\n");
sewardj9c606bd2008-09-18 18:12:50 +00002052
2053 tl_assert(!addr2dihandle);
2054 addr2dihandle = VG_(newXA)( VG_(malloc), "main.vm.2",
2055 VG_(free), sizeof(Addr_n_ULong) );
2056 tl_assert(addr2dihandle);
2057
sewardj17c11042006-10-15 01:26:40 +00002058# if defined(VGO_linux)
sewardj45f4e7c2005-09-27 19:20:21 +00002059 { Addr* seg_starts;
2060 Int n_seg_starts;
sewardj9c606bd2008-09-18 18:12:50 +00002061 Addr_n_ULong anu;
sewardj45f4e7c2005-09-27 19:20:21 +00002062
njnac1e0332009-05-08 00:39:31 +00002063 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
sewardj17c11042006-10-15 01:26:40 +00002064 vg_assert(seg_starts && n_seg_starts >= 0);
sewardj45f4e7c2005-09-27 19:20:21 +00002065
sewardjf72cced2005-11-08 00:45:47 +00002066 /* show them all to the debug info reader. allow_SkFileV has to
2067 be True here so that we read info from the valgrind executable
2068 itself. */
sewardj9c606bd2008-09-18 18:12:50 +00002069 for (i = 0; i < n_seg_starts; i++) {
sewardj5f2dcad2011-10-24 08:53:03 +00002070 anu.ull = VG_(di_notify_mmap)( seg_starts[i], True/*allow_SkFileV*/,
2071 -1/*Don't use_fd*/);
sewardj9c606bd2008-09-18 18:12:50 +00002072 /* anu.ull holds the debuginfo handle returned by di_notify_mmap,
2073 if any. */
2074 if (anu.ull > 0) {
2075 anu.a = seg_starts[i];
2076 VG_(addToXA)( addr2dihandle, &anu );
2077 }
2078 }
sewardj45f4e7c2005-09-27 19:20:21 +00002079
2080 VG_(free)( seg_starts );
2081 }
njnf76d27a2009-05-28 01:53:07 +00002082# elif defined(VGO_darwin)
2083 { Addr* seg_starts;
2084 Int n_seg_starts;
2085 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
2086 vg_assert(seg_starts && n_seg_starts >= 0);
2087
2088 /* show them all to the debug info reader.
2089 Don't read from V segments (unlike Linux) */
2090 // GrP fixme really?
sewardj5f2dcad2011-10-24 08:53:03 +00002091 for (i = 0; i < n_seg_starts; i++) {
2092 VG_(di_notify_mmap)( seg_starts[i], False/*don't allow_SkFileV*/,
2093 -1/*don't use_fd*/);
2094 }
njnf76d27a2009-05-28 01:53:07 +00002095
2096 VG_(free)( seg_starts );
2097 }
sewardj17c11042006-10-15 01:26:40 +00002098# else
2099# error Unknown OS
2100# endif
sewardj45f4e7c2005-09-27 19:20:21 +00002101
2102 //--------------------------------------------------------------
2103 // Tell aspacem of ownership change of the asm helpers, so that
2104 // m_translate allows them to be translated. However, only do this
2105 // after the initial debug info read, since making a hole in the
2106 // address range for the stage2 binary confuses the debug info reader.
2107 // p: aspacem
2108 //--------------------------------------------------------------
2109 { Bool change_ownership_v_c_OK;
sewardj1a85f4f2006-01-12 21:15:35 +00002110 Addr co_start = VG_PGROUNDDN( (Addr)&VG_(trampoline_stuff_start) );
2111 Addr co_endPlus = VG_PGROUNDUP( (Addr)&VG_(trampoline_stuff_end) );
sewardj45f4e7c2005-09-27 19:20:21 +00002112 VG_(debugLog)(1,"redir",
2113 "transfer ownership V -> C of 0x%llx .. 0x%llx\n",
2114 (ULong)co_start, (ULong)co_endPlus-1 );
2115
2116 change_ownership_v_c_OK
2117 = VG_(am_change_ownership_v_to_c)( co_start, co_endPlus - co_start );
2118 vg_assert(change_ownership_v_c_OK);
2119 }
2120
bart6c63f5c2011-10-11 18:50:14 +00002121 if (VG_(clo_xml)) {
2122 HChar buf[50];
2123 VG_(elapsed_wallclock_time)(buf);
2124 VG_(printf_xml)( "<status>\n"
2125 " <state>RUNNING</state>\n"
2126 " <time>%pS</time>\n"
2127 "</status>\n",
2128 buf );
2129 VG_(printf_xml)( "\n" );
2130 }
2131
bart27233e92012-03-08 14:59:25 +00002132 VG_(init_Threads)();
2133
sewardj45f4e7c2005-09-27 19:20:21 +00002134 //--------------------------------------------------------------
sewardjde764e82007-11-09 23:13:22 +00002135 // Initialise the scheduler (phase 1) [generates tid_main]
2136 // p: none, afaics
2137 //--------------------------------------------------------------
2138 VG_(debugLog)(1, "main", "Initialise scheduler (phase 1)\n");
2139 tid_main = VG_(scheduler_init_phase1)();
2140 vg_assert(tid_main >= 0 && tid_main < VG_N_THREADS
2141 && tid_main != VG_INVALID_THREADID);
2142 /* Tell the tool about tid_main */
2143 VG_TRACK( pre_thread_ll_create, VG_INVALID_THREADID, tid_main );
2144
2145 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00002146 // Tell the tool about the initial client memory permissions
2147 // p: aspacem
2148 // p: mallocfree
2149 // p: setup_client_stack
2150 // p: setup_client_dataseg
sewardj9c606bd2008-09-18 18:12:50 +00002151 //
2152 // For each segment we tell the client about, look up in
2153 // addr2dihandle as created above, to see if there's a debuginfo
2154 // handle associated with the segment, that we can hand along
2155 // to the tool, to be helpful.
sewardj45f4e7c2005-09-27 19:20:21 +00002156 //--------------------------------------------------------------
2157 VG_(debugLog)(1, "main", "Tell tool about initial permissions\n");
2158 { Addr* seg_starts;
2159 Int n_seg_starts;
sewardj45f4e7c2005-09-27 19:20:21 +00002160
sewardj9c606bd2008-09-18 18:12:50 +00002161 tl_assert(addr2dihandle);
2162
tom7c1a19a2008-01-02 10:13:04 +00002163 /* Mark the main thread as running while we tell the tool about
2164 the client memory so that the tool can associate that memory
2165 with the main thread. */
2166 tl_assert(VG_(running_tid) == VG_INVALID_THREADID);
2167 VG_(running_tid) = tid_main;
2168
njnac1e0332009-05-08 00:39:31 +00002169 seg_starts = VG_(get_segment_starts)( &n_seg_starts );
sewardj17c11042006-10-15 01:26:40 +00002170 vg_assert(seg_starts && n_seg_starts >= 0);
sewardj45f4e7c2005-09-27 19:20:21 +00002171
2172 /* show interesting ones to the tool */
2173 for (i = 0; i < n_seg_starts; i++) {
sewardj9c606bd2008-09-18 18:12:50 +00002174 Word j, n;
sewardj12ab7652006-10-17 02:10:42 +00002175 NSegment const* seg
sewardj17c11042006-10-15 01:26:40 +00002176 = VG_(am_find_nsegment)( seg_starts[i] );
sewardj45f4e7c2005-09-27 19:20:21 +00002177 vg_assert(seg);
2178 if (seg->kind == SkFileC || seg->kind == SkAnonC) {
sewardjc6d86a32009-01-31 15:08:08 +00002179 /* This next assertion is tricky. If it is placed
2180 immediately before this 'if', it very occasionally fails.
2181 Why? Because previous iterations of the loop may have
2182 caused tools (via the new_mem_startup calls) to do
2183 dynamic memory allocation, and that may affect the mapped
2184 segments; in particular it may cause segment merging to
2185 happen. Hence we cannot assume that seg_starts[i], which
2186 reflects the state of the world before we started this
2187 loop, is the same as seg->start, as the latter reflects
2188 the state of the world (viz, mappings) at this particular
2189 iteration of the loop.
2190
2191 Why does moving it inside the 'if' make it safe? Because
2192 any dynamic memory allocation done by the tools will
2193 affect only the state of Valgrind-owned segments, not of
2194 Client-owned segments. And the 'if' guards against that
2195 -- we only get in here for Client-owned segments.
2196
2197 In other words: the loop may change the state of
2198 Valgrind-owned segments as it proceeds. But it should
2199 not cause the Client-owned segments to change. */
2200 vg_assert(seg->start == seg_starts[i]);
sewardj45f4e7c2005-09-27 19:20:21 +00002201 VG_(debugLog)(2, "main",
2202 "tell tool about %010lx-%010lx %c%c%c\n",
2203 seg->start, seg->end,
2204 seg->hasR ? 'r' : '-',
2205 seg->hasW ? 'w' : '-',
2206 seg->hasX ? 'x' : '-' );
sewardj9c606bd2008-09-18 18:12:50 +00002207 /* search addr2dihandle to see if we have an entry
2208 matching seg->start. */
2209 n = VG_(sizeXA)( addr2dihandle );
2210 for (j = 0; j < n; j++) {
2211 Addr_n_ULong* anl = VG_(indexXA)( addr2dihandle, j );
2212 if (anl->a == seg->start) {
2213 tl_assert(anl->ull > 0); /* check it's a valid handle */
2214 break;
2215 }
2216 }
2217 vg_assert(j >= 0 && j <= n);
sewardj45f4e7c2005-09-27 19:20:21 +00002218 VG_TRACK( new_mem_startup, seg->start, seg->end+1-seg->start,
sewardj9c606bd2008-09-18 18:12:50 +00002219 seg->hasR, seg->hasW, seg->hasX,
2220 /* and the retrieved debuginfo handle, if any */
2221 j < n
2222 ? ((Addr_n_ULong*)VG_(indexXA)( addr2dihandle, j ))->ull
2223 : 0 );
sewardj45f4e7c2005-09-27 19:20:21 +00002224 }
2225 }
2226
2227 VG_(free)( seg_starts );
sewardj9c606bd2008-09-18 18:12:50 +00002228 VG_(deleteXA)( addr2dihandle );
sewardj45f4e7c2005-09-27 19:20:21 +00002229
2230 /* Also do the initial stack permissions. */
barte05b3a42010-09-07 16:32:53 +00002231 {
2232 SSizeT inaccessible_len;
2233 NSegment const* seg
sewardjf9d2f9b2006-11-17 20:00:57 +00002234 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
sewardj17c11042006-10-15 01:26:40 +00002235 vg_assert(seg);
2236 vg_assert(seg->kind == SkAnonC);
sewardjf9d2f9b2006-11-17 20:00:57 +00002237 vg_assert(the_iifii.initial_client_SP >= seg->start);
2238 vg_assert(the_iifii.initial_client_SP <= seg->end);
sewardj45f4e7c2005-09-27 19:20:21 +00002239
sewardj17c11042006-10-15 01:26:40 +00002240 /* Stuff below the initial SP is unaddressable. Take into
2241 account any ABI-mandated space below the stack pointer that
2242 is required (VG_STACK_REDZONE_SZB). setup_client_stack()
2243 will have allocated an extra page if a red zone is required,
2244 to be on the safe side. */
barte05b3a42010-09-07 16:32:53 +00002245 inaccessible_len = the_iifii.initial_client_SP - VG_STACK_REDZONE_SZB
2246 - seg->start;
2247 vg_assert(inaccessible_len >= 0);
2248 if (inaccessible_len > 0)
2249 VG_TRACK( die_mem_stack,
2250 seg->start,
2251 inaccessible_len );
sewardj17c11042006-10-15 01:26:40 +00002252 VG_(debugLog)(2, "main", "mark stack inaccessible %010lx-%010lx\n",
2253 seg->start,
sewardjf9d2f9b2006-11-17 20:00:57 +00002254 the_iifii.initial_client_SP-1 - VG_STACK_REDZONE_SZB);
sewardj17c11042006-10-15 01:26:40 +00002255 }
sewardj45f4e7c2005-09-27 19:20:21 +00002256
2257 /* Also the assembly helpers. */
2258 VG_TRACK( new_mem_startup,
2259 (Addr)&VG_(trampoline_stuff_start),
sewardjc6527d62006-02-13 17:54:31 +00002260 (Addr)&VG_(trampoline_stuff_end)
2261 - (Addr)&VG_(trampoline_stuff_start),
sewardj45f4e7c2005-09-27 19:20:21 +00002262 False, /* readable? */
2263 False, /* writable? */
sewardj9c606bd2008-09-18 18:12:50 +00002264 True /* executable? */,
2265 0 /* di_handle: no associated debug info */ );
tom7c1a19a2008-01-02 10:13:04 +00002266
2267 /* Clear the running thread indicator */
2268 VG_(running_tid) = VG_INVALID_THREADID;
2269 tl_assert(VG_(running_tid) == VG_INVALID_THREADID);
sewardj45f4e7c2005-09-27 19:20:21 +00002270 }
2271
2272 //--------------------------------------------------------------
sewardjde764e82007-11-09 23:13:22 +00002273 // Initialise the scheduler (phase 2)
2274 // p: Initialise the scheduler (phase 1) [for tid_main]
nethercote71980f02004-01-24 18:18:54 +00002275 // p: setup_file_descriptors() [else VG_(safe_fd)() breaks]
sewardj45f4e7c2005-09-27 19:20:21 +00002276 // p: setup_client_stack
nethercote71980f02004-01-24 18:18:54 +00002277 //--------------------------------------------------------------
sewardjde764e82007-11-09 23:13:22 +00002278 VG_(debugLog)(1, "main", "Initialise scheduler (phase 2)\n");
sewardj12ab7652006-10-17 02:10:42 +00002279 { NSegment const* seg
sewardjf9d2f9b2006-11-17 20:00:57 +00002280 = VG_(am_find_nsegment)( the_iifii.initial_client_SP );
sewardj45f4e7c2005-09-27 19:20:21 +00002281 vg_assert(seg);
2282 vg_assert(seg->kind == SkAnonC);
sewardjf9d2f9b2006-11-17 20:00:57 +00002283 vg_assert(the_iifii.initial_client_SP >= seg->start);
2284 vg_assert(the_iifii.initial_client_SP <= seg->end);
sewardjde764e82007-11-09 23:13:22 +00002285 VG_(scheduler_init_phase2)( tid_main,
2286 seg->end, the_iifii.clstack_max_size );
sewardj45f4e7c2005-09-27 19:20:21 +00002287 }
nethercote71980f02004-01-24 18:18:54 +00002288
2289 //--------------------------------------------------------------
sewardj17c11042006-10-15 01:26:40 +00002290 // Set up state for the root thread
sewardjb5f6f512005-03-10 23:59:00 +00002291 // p: ?
sewardj17c11042006-10-15 01:26:40 +00002292 // setup_scheduler() [for sched-specific thread 1 stuff]
sewardjf9d2f9b2006-11-17 20:00:57 +00002293 // VG_(ii_create_image) [for 'the_iicii' initial info]
sewardj2a99cf62004-11-24 10:44:19 +00002294 //--------------------------------------------------------------
sewardjf9d2f9b2006-11-17 20:00:57 +00002295 VG_(debugLog)(1, "main", "Finalise initial image\n");
2296 VG_(ii_finalise_image)( the_iifii );
njnea4b28c2004-11-30 16:04:58 +00002297
sewardj2a99cf62004-11-24 10:44:19 +00002298 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00002299 // Initialise the signal handling subsystem
sewardjb5f6f512005-03-10 23:59:00 +00002300 // p: n/a
nethercote71980f02004-01-24 18:18:54 +00002301 //--------------------------------------------------------------
2302 // Nb: temporarily parks the saved blocking-mask in saved_sigmask.
sewardj1fbc1a52005-04-25 02:05:54 +00002303 VG_(debugLog)(1, "main", "Initialise signal management\n");
njncda2f0f2009-05-18 02:12:08 +00002304 /* Check that the kernel-interface signal definitions look sane */
2305 VG_(vki_do_initial_consistency_checks)();
2306 /* .. and go on to use them. */
nethercote71980f02004-01-24 18:18:54 +00002307 VG_(sigstartup_actions)();
2308
2309 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00002310 // Read suppression file
sewardj95d86c02007-12-18 01:49:23 +00002311 // p: main_process_cmd_line_options() [for VG_(clo_suppressions)]
nethercote71980f02004-01-24 18:18:54 +00002312 //--------------------------------------------------------------
sewardj1fbc1a52005-04-25 02:05:54 +00002313 if (VG_(needs).core_errors || VG_(needs).tool_errors) {
2314 VG_(debugLog)(1, "main", "Load suppressions\n");
nethercote71980f02004-01-24 18:18:54 +00002315 VG_(load_suppressions)();
sewardj1fbc1a52005-04-25 02:05:54 +00002316 }
nethercote71980f02004-01-24 18:18:54 +00002317
2318 //--------------------------------------------------------------
rjwalsh0140af52005-06-04 20:42:33 +00002319 // register client stack
2320 //--------------------------------------------------------------
njn945ed2e2005-06-24 03:28:30 +00002321 VG_(clstk_id) = VG_(register_stack)(VG_(clstk_base), VG_(clstk_end));
rjwalsh0140af52005-06-04 20:42:33 +00002322
2323 //--------------------------------------------------------------
sewardj45f4e7c2005-09-27 19:20:21 +00002324 // Show the address space state so far
2325 //--------------------------------------------------------------
2326 VG_(debugLog)(1, "main", "\n");
2327 VG_(debugLog)(1, "main", "\n");
2328 VG_(am_show_nsegments)(1,"Memory layout at client startup");
2329 VG_(debugLog)(1, "main", "\n");
2330 VG_(debugLog)(1, "main", "\n");
2331
2332 //--------------------------------------------------------------
nethercote71980f02004-01-24 18:18:54 +00002333 // Run!
2334 //--------------------------------------------------------------
sewardj1fbc1a52005-04-25 02:05:54 +00002335 VG_(debugLog)(1, "main", "Running thread 1\n");
sewardj1ae3f3a2005-09-28 10:47:38 +00002336
sewardj1d887112005-05-30 21:44:08 +00002337 /* As a result of the following call, the last thread standing
sewardj1ae3f3a2005-09-28 10:47:38 +00002338 eventually winds up running shutdown_actions_NORETURN
2339 just below. Unfortunately, simply exporting said function
2340 causes m_main to be part of a module cycle, which is pretty
2341 nonsensical. So instead of doing that, the address of said
2342 function is stored in a global variable 'owned' by m_syswrap,
2343 and it uses that function pointer to get back here when it needs
2344 to. */
2345
2346 /* Set continuation address. */
2347 VG_(address_of_m_main_shutdown_actions_NORETURN)
2348 = & shutdown_actions_NORETURN;
2349
2350 /* Run the first thread, eventually ending up at the continuation
2351 address. */
njnaf839f52005-06-23 03:27:57 +00002352 VG_(main_thread_wrapper_NORETURN)(1);
nethercote71980f02004-01-24 18:18:54 +00002353
sewardj1d887112005-05-30 21:44:08 +00002354 /*NOTREACHED*/
2355 vg_assert(0);
sewardjb5f6f512005-03-10 23:59:00 +00002356}
2357
sewardj17c11042006-10-15 01:26:40 +00002358/* Do everything which needs doing when the last thread exits or when
sewardj6e9de462011-06-28 07:25:29 +00002359 a thread exits requesting a complete process exit.
sewardj17c11042006-10-15 01:26:40 +00002360
2361 We enter here holding The Lock. For the case VgSrc_ExitProcess we
2362 must never release it, because to do so would allow other threads
2363 to continue after the system is ostensibly shut down. So we must
2364 go to our grave, so to speak, holding the lock.
2365
2366 In fact, there is never any point in releasing the lock at this
2367 point - we have it, we're shutting down the entire system, and
2368 for the case VgSrc_ExitProcess doing so positively causes trouble.
2369 So don't.
2370
2371 The final_tidyup call makes a bit of a nonsense of the ExitProcess
2372 case, since it will run the libc_freeres function, thus allowing
2373 other lurking threads to run again. Hmm. */
sewardjb5f6f512005-03-10 23:59:00 +00002374
sewardj1ae3f3a2005-09-28 10:47:38 +00002375static
2376void shutdown_actions_NORETURN( ThreadId tid,
2377 VgSchedReturnCode tids_schedretcode )
sewardjb5f6f512005-03-10 23:59:00 +00002378{
sewardj1d887112005-05-30 21:44:08 +00002379 VG_(debugLog)(1, "main", "entering VG_(shutdown_actions_NORETURN)\n");
sewardj17c11042006-10-15 01:26:40 +00002380 VG_(am_show_nsegments)(1,"Memory layout at client shutdown");
sewardj1d887112005-05-30 21:44:08 +00002381
sewardjb5f6f512005-03-10 23:59:00 +00002382 vg_assert(VG_(is_running_thread)(tid));
2383
sewardj12ab7652006-10-17 02:10:42 +00002384 vg_assert(tids_schedretcode == VgSrc_ExitThread
2385 || tids_schedretcode == VgSrc_ExitProcess
2386 || tids_schedretcode == VgSrc_FatalSig );
sewardjb5f6f512005-03-10 23:59:00 +00002387
sewardj12ab7652006-10-17 02:10:42 +00002388 if (tids_schedretcode == VgSrc_ExitThread) {
sewardjb5f6f512005-03-10 23:59:00 +00002389
sewardj17c11042006-10-15 01:26:40 +00002390 // We are the last surviving thread. Right?
2391 vg_assert( VG_(count_living_threads)() == 1 );
sewardjb5f6f512005-03-10 23:59:00 +00002392
sewardj17c11042006-10-15 01:26:40 +00002393 // Wait for all other threads to exit.
2394 // jrs: Huh? but they surely are already gone
2395 VG_(reap_threads)(tid);
sewardjb5f6f512005-03-10 23:59:00 +00002396
sewardj17c11042006-10-15 01:26:40 +00002397 // Clean the client up before the final report
2398 // this causes the libc_freeres function to run
2399 final_tidyup(tid);
2400
2401 /* be paranoid */
2402 vg_assert(VG_(is_running_thread)(tid));
2403 vg_assert(VG_(count_living_threads)() == 1);
2404
2405 } else {
2406
2407 // We may not be the last surviving thread. However, we
2408 // want to shut down the entire process. We hold the lock
2409 // and we need to keep hold of it all the way out, in order
2410 // that none of the other threads ever run again.
2411 vg_assert( VG_(count_living_threads)() >= 1 );
2412
sewardj17c11042006-10-15 01:26:40 +00002413 // Clean the client up before the final report
2414 // this causes the libc_freeres function to run
2415 // perhaps this is unsafe, as per comment above
2416 final_tidyup(tid);
2417
2418 /* be paranoid */
2419 vg_assert(VG_(is_running_thread)(tid));
2420 vg_assert(VG_(count_living_threads)() >= 1);
2421 }
sewardjb5f6f512005-03-10 23:59:00 +00002422
2423 VG_(threads)[tid].status = VgTs_Empty;
nethercote71980f02004-01-24 18:18:54 +00002424 //--------------------------------------------------------------
sewardj738856f2009-07-15 14:48:32 +00002425 // Finalisation: cleanup, messages, etc. Order not so important, only
nethercote71980f02004-01-24 18:18:54 +00002426 // affects what order the messages come.
2427 //--------------------------------------------------------------
njnb6267bd2009-08-12 00:14:16 +00002428 // First thing in the post-amble is a blank line.
sewardj738856f2009-07-15 14:48:32 +00002429 if (VG_(clo_xml))
2430 VG_(printf_xml)("\n");
njnb6267bd2009-08-12 00:14:16 +00002431 else if (VG_(clo_verbosity) > 0)
2432 VG_(message)(Vg_UserMsg, "\n");
nethercote71980f02004-01-24 18:18:54 +00002433
sewardj71bc3cb2005-05-19 00:25:45 +00002434 if (VG_(clo_xml)) {
sewardj68cde6f2005-07-19 12:17:51 +00002435 HChar buf[50];
sewardj592ae092005-11-08 19:01:44 +00002436 VG_(elapsed_wallclock_time)(buf);
bartb3af9cf2011-10-06 19:08:37 +00002437 VG_(printf_xml)( "<status>\n"
sewardj738856f2009-07-15 14:48:32 +00002438 " <state>FINISHED</state>\n"
bartb3af9cf2011-10-06 19:08:37 +00002439 " <time>%pS</time>\n"
njnb6267bd2009-08-12 00:14:16 +00002440 "</status>\n"
2441 "\n",
sewardj738856f2009-07-15 14:48:32 +00002442 buf);
sewardj71bc3cb2005-05-19 00:25:45 +00002443 }
2444
nethercote71980f02004-01-24 18:18:54 +00002445 /* Print out file descriptor summary and stats. */
2446 if (VG_(clo_track_fds))
philippec3360382012-10-21 14:37:14 +00002447 VG_(show_open_fds)("at exit");
nethercote71980f02004-01-24 18:18:54 +00002448
sewardj2d9e8742009-08-07 15:46:56 +00002449 /* Call the tool's finalisation function. This makes Memcheck's
2450 leak checker run, and possibly chuck a bunch of leak errors into
2451 the error management machinery. */
2452 VG_TDICT_CALL(tool_fini, 0/*exitcode*/);
nethercote71980f02004-01-24 18:18:54 +00002453
sewardj2d9e8742009-08-07 15:46:56 +00002454 /* Show the error counts. */
sewardj7ca100d2009-08-15 23:05:34 +00002455 if (VG_(clo_xml)
2456 && (VG_(needs).core_errors || VG_(needs).tool_errors)) {
sewardj2d9e8742009-08-07 15:46:56 +00002457 VG_(show_error_counts_as_XML)();
sewardj738856f2009-07-15 14:48:32 +00002458 }
sewardj2d9e8742009-08-07 15:46:56 +00002459
2460 /* In XML mode, this merely prints the used suppressions. */
2461 if (VG_(needs).core_errors || VG_(needs).tool_errors)
sewardj3b290482011-05-06 21:02:55 +00002462 VG_(show_all_errors)(VG_(clo_verbosity), VG_(clo_xml));
nethercote71980f02004-01-24 18:18:54 +00002463
sewardj71bc3cb2005-05-19 00:25:45 +00002464 if (VG_(clo_xml)) {
sewardj738856f2009-07-15 14:48:32 +00002465 VG_(printf_xml)("\n");
2466 VG_(printf_xml)("</valgrindoutput>\n");
2467 VG_(printf_xml)("\n");
sewardj71bc3cb2005-05-19 00:25:45 +00002468 }
2469
nethercote885dd912004-08-03 23:14:00 +00002470 VG_(sanity_check_general)( True /*include expensive checks*/ );
nethercote71980f02004-01-24 18:18:54 +00002471
sewardj2d9e8742009-08-07 15:46:56 +00002472 if (VG_(clo_stats))
nethercote3a42fb82004-08-03 18:08:50 +00002473 print_all_stats();
nethercote71980f02004-01-24 18:18:54 +00002474
sewardj9c606bd2008-09-18 18:12:50 +00002475 /* Show a profile of the heap(s) at shutdown. Optionally, first
2476 throw away all the debug info, as that makes it easy to spot
2477 leaks in the debuginfo reader. */
2478 if (VG_(clo_profile_heap)) {
2479 if (0) VG_(di_discard_ALL_debuginfo)();
2480 VG_(print_arena_cc_analysis)();
2481 }
2482
sewardj17c5e2e2012-12-28 09:12:14 +00002483 /* If profiling has been requested, but with zero interval, it
2484 means "profile at the end of the run only". In which case we
2485 need to dump the profile now. */
2486 if (VG_(clo_profyle_sbs) && VG_(clo_profyle_interval) == 0) {
2487 VG_(get_and_show_SB_profile)(0/*denoting end-of-run*/);
njn2025cf92005-06-26 20:44:48 +00002488 }
sewardjfa8ec112005-01-19 11:55:34 +00002489
sewardj8b635a42004-11-22 19:01:47 +00002490 /* Print Vex storage stats */
sewardjbf426512005-01-17 18:35:30 +00002491 if (0)
2492 LibVEX_ShowAllocStats();
sewardj1d887112005-05-30 21:44:08 +00002493
sewardj738856f2009-07-15 14:48:32 +00002494 /* Flush any output cached by previous calls to VG_(message). */
2495 VG_(message_flush)();
2496
sewardj17c5e2e2012-12-28 09:12:14 +00002497 /* terminate gdbserver if ever it was started. We terminate it here
2498 so that it get the output above if output was redirected to
2499 gdb */
philippe0447bbd2012-10-17 21:32:03 +00002500 VG_(gdbserver_exit) (tid, tids_schedretcode);
sewardj3b290482011-05-06 21:02:55 +00002501
njn8aa35852005-06-10 22:59:56 +00002502 /* Ok, finally exit in the os-specific way, according to the scheduler's
2503 return code. In short, if the (last) thread exited by calling
2504 sys_exit, do likewise; if the (last) thread stopped due to a fatal
2505 signal, terminate the entire system with that same fatal signal. */
2506 VG_(debugLog)(1, "core_os",
njn7b85dd52005-06-12 17:26:29 +00002507 "VG_(terminate_NORETURN)(tid=%lld)\n", (ULong)tid);
njn8aa35852005-06-10 22:59:56 +00002508
njn8aa35852005-06-10 22:59:56 +00002509 switch (tids_schedretcode) {
sewardj12ab7652006-10-17 02:10:42 +00002510 case VgSrc_ExitThread: /* the normal way out (Linux) */
sewardj6e9de462011-06-28 07:25:29 +00002511 case VgSrc_ExitProcess: /* the normal way out (AIX) -- still needed? */
sewardjb9779082006-05-12 23:50:15 +00002512 /* Change the application return code to user's return code,
2513 if an error was found */
2514 if (VG_(clo_error_exitcode) > 0
2515 && VG_(get_n_errs_found)() > 0) {
2516 VG_(exit)( VG_(clo_error_exitcode) );
2517 } else {
2518 /* otherwise, return the client's exit code, in the normal
2519 way. */
2520 VG_(exit)( VG_(threads)[tid].os_state.exitcode );
2521 }
njn8aa35852005-06-10 22:59:56 +00002522 /* NOT ALIVE HERE! */
sewardj17c11042006-10-15 01:26:40 +00002523 VG_(core_panic)("entered the afterlife in main() -- ExitT/P");
njn8aa35852005-06-10 22:59:56 +00002524 break; /* what the hell :) */
2525
2526 case VgSrc_FatalSig:
2527 /* We were killed by a fatal signal, so replicate the effect */
2528 vg_assert(VG_(threads)[tid].os_state.fatalsig != 0);
2529 VG_(kill_self)(VG_(threads)[tid].os_state.fatalsig);
njnf76d27a2009-05-28 01:53:07 +00002530 /* we shouldn't be alive at this point. But VG_(kill_self)
2531 sometimes fails with EPERM on Darwin, for unclear reasons. */
2532# if defined(VGO_darwin)
2533 VG_(debugLog)(0, "main", "VG_(kill_self) failed. Exiting normally.\n");
2534 VG_(exit)(0); /* bogus, but we really need to exit now */
2535 /* fall through .. */
2536# endif
njn8aa35852005-06-10 22:59:56 +00002537 VG_(core_panic)("main(): signal was supposed to be fatal");
2538 break;
2539
2540 default:
2541 VG_(core_panic)("main(): unexpected scheduler return code");
2542 }
njne96be672005-05-08 19:08:54 +00002543}
sewardj8b635a42004-11-22 19:01:47 +00002544
sewardj1ae3f3a2005-09-28 10:47:38 +00002545/* -------------------- */
2546
2547/* Final clean-up before terminating the process.
2548 Clean up the client by calling __libc_freeres() (if requested)
2549 This is Linux-specific?
njnf76d27a2009-05-28 01:53:07 +00002550 GrP fixme glibc-specific, anyway
sewardj1ae3f3a2005-09-28 10:47:38 +00002551*/
2552static void final_tidyup(ThreadId tid)
2553{
njnf76d27a2009-05-28 01:53:07 +00002554#if !defined(VGO_darwin)
sewardjcf951812006-01-17 02:22:21 +00002555# if defined(VGP_ppc64_linux)
2556 Addr r2;
2557# endif
sewardj0ec07f32006-01-12 12:32:32 +00002558 Addr __libc_freeres_wrapper = VG_(client___libc_freeres_wrapper);
sewardj1ae3f3a2005-09-28 10:47:38 +00002559
2560 vg_assert(VG_(is_running_thread)(tid));
2561
2562 if ( !VG_(needs).libc_freeres ||
2563 !VG_(clo_run_libc_freeres) ||
sewardj0ec07f32006-01-12 12:32:32 +00002564 0 == __libc_freeres_wrapper )
sewardj1ae3f3a2005-09-28 10:47:38 +00002565 return; /* can't/won't do it */
2566
sewardjcf951812006-01-17 02:22:21 +00002567# if defined(VGP_ppc64_linux)
2568 r2 = VG_(get_tocptr)( __libc_freeres_wrapper );
2569 if (r2 == 0) {
2570 VG_(message)(Vg_UserMsg,
sewardj738856f2009-07-15 14:48:32 +00002571 "Caught __NR_exit, but can't run __libc_freeres()\n");
sewardjcf951812006-01-17 02:22:21 +00002572 VG_(message)(Vg_UserMsg,
sewardj738856f2009-07-15 14:48:32 +00002573 " since cannot establish TOC pointer for it.\n");
sewardjcf951812006-01-17 02:22:21 +00002574 return;
2575 }
2576# endif
2577
sewardj1ae3f3a2005-09-28 10:47:38 +00002578 if (VG_(clo_verbosity) > 2 ||
2579 VG_(clo_trace_syscalls) ||
2580 VG_(clo_trace_sched))
2581 VG_(message)(Vg_DebugMsg,
sewardj738856f2009-07-15 14:48:32 +00002582 "Caught __NR_exit; running __libc_freeres()\n");
sewardj1ae3f3a2005-09-28 10:47:38 +00002583
sewardj0ec07f32006-01-12 12:32:32 +00002584 /* set thread context to point to libc_freeres_wrapper */
sewardj1a85f4f2006-01-12 21:15:35 +00002585 /* ppc64-linux note: __libc_freeres_wrapper gives us the real
2586 function entry point, not a fn descriptor, so can use it
2587 directly. However, we need to set R2 (the toc pointer)
2588 appropriately. */
sewardj1ae3f3a2005-09-28 10:47:38 +00002589 VG_(set_IP)(tid, __libc_freeres_wrapper);
sewardjcf951812006-01-17 02:22:21 +00002590# if defined(VGP_ppc64_linux)
2591 VG_(threads)[tid].arch.vex.guest_GPR2 = r2;
2592# endif
sewardj5db15402012-06-07 09:13:21 +00002593 /* mips-linux note: we need to set t9 */
petarj4df0bfc2013-02-27 23:17:33 +00002594# if defined(VGP_mips32_linux) || defined(VGP_mips64_linux)
sewardj5db15402012-06-07 09:13:21 +00002595 VG_(threads)[tid].arch.vex.guest_r25 = __libc_freeres_wrapper;
2596# endif
sewardj1ae3f3a2005-09-28 10:47:38 +00002597
2598 /* Block all blockable signals by copying the real block state into
2599 the thread's block state*/
2600 VG_(sigprocmask)(VKI_SIG_BLOCK, NULL, &VG_(threads)[tid].sig_mask);
2601 VG_(threads)[tid].tmp_sig_mask = VG_(threads)[tid].sig_mask;
2602
2603 /* and restore handlers to default */
2604 VG_(set_default_handler)(VKI_SIGSEGV);
2605 VG_(set_default_handler)(VKI_SIGBUS);
2606 VG_(set_default_handler)(VKI_SIGILL);
2607 VG_(set_default_handler)(VKI_SIGFPE);
2608
2609 // We were exiting, so assert that...
2610 vg_assert(VG_(is_exiting)(tid));
2611 // ...but now we're not again
2612 VG_(threads)[tid].exitreason = VgSrc_None;
2613
2614 // run until client thread exits - ideally with LIBC_FREERES_DONE,
2615 // but exit/exitgroup/signal will do
2616 VG_(scheduler)(tid);
2617
2618 vg_assert(VG_(is_exiting)(tid));
njnf76d27a2009-05-28 01:53:07 +00002619#endif
sewardj1ae3f3a2005-09-28 10:47:38 +00002620}
2621
sewardj45f4e7c2005-09-27 19:20:21 +00002622
2623/*====================================================================*/
njn49f80e82009-05-21 01:25:43 +00002624/*=== Getting to main() alive: LINUX ===*/
sewardj45f4e7c2005-09-27 19:20:21 +00002625/*====================================================================*/
2626
sewardj17c11042006-10-15 01:26:40 +00002627#if defined(VGO_linux)
2628
sewardj45f4e7c2005-09-27 19:20:21 +00002629/* If linking of the final executables is done with glibc present,
2630 then Valgrind starts at main() above as usual, and all of the
2631 following code is irrelevant.
2632
2633 However, this is not the intended mode of use. The plan is to
2634 avoid linking against glibc, by giving gcc the flags
2635 -nodefaultlibs -lgcc -nostartfiles at startup.
2636
2637 From this derive two requirements:
2638
petarje70c45e2013-02-15 03:12:17 +00002639 1. gcc may emit calls to memcpy, memmove and memset to deal with
2640 structure assignments etc. Since we have chosen to ignore all the
sewardj45f4e7c2005-09-27 19:20:21 +00002641 "normal" supporting libraries, we have to provide our own
2642 implementations of them. No problem.
2643
2644 2. We have to provide a symbol "_start", to which the kernel
2645 hands control at startup. Hence the code below.
2646*/
2647
2648/* ---------------- Requirement 1 ---------------- */
2649
sewardj17c11042006-10-15 01:26:40 +00002650void* memcpy(void *dest, const void *src, SizeT n);
2651void* memcpy(void *dest, const void *src, SizeT n) {
sewardj45f4e7c2005-09-27 19:20:21 +00002652 return VG_(memcpy)(dest,src,n);
2653}
petarje70c45e2013-02-15 03:12:17 +00002654void* memmove(void *dest, const void *src, SizeT n);
2655void* memmove(void *dest, const void *src, SizeT n) {
2656 return VG_(memmove)(dest,src,n);
2657}
sewardj17c11042006-10-15 01:26:40 +00002658void* memset(void *s, int c, SizeT n);
2659void* memset(void *s, int c, SizeT n) {
sewardj45f4e7c2005-09-27 19:20:21 +00002660 return VG_(memset)(s,c,n);
2661}
2662
bart82616e12010-06-13 13:46:24 +00002663/* BVA: abort() for those platforms that need it (PPC and ARM). */
2664void abort(void);
2665void abort(void){
2666 VG_(printf)("Something called raise().\n");
2667 vg_assert(0);
2668}
2669
sewardj59570ff2010-01-01 11:59:33 +00002670/* EAZG: ARM's EABI will call floating point exception handlers in
2671 libgcc which boil down to an abort or raise, that's usually defined
2672 in libc. Instead, define them here. */
2673#if defined(VGP_arm_linux)
2674void raise(void);
2675void raise(void){
2676 VG_(printf)("Something called raise().\n");
2677 vg_assert(0);
2678}
2679
sewardj59570ff2010-01-01 11:59:33 +00002680void __aeabi_unwind_cpp_pr0(void);
2681void __aeabi_unwind_cpp_pr0(void){
2682 VG_(printf)("Something called __aeabi_unwind_cpp_pr0()\n");
2683 vg_assert(0);
2684}
sewardj38efe4b2010-08-22 12:23:01 +00002685
2686void __aeabi_unwind_cpp_pr1(void);
2687void __aeabi_unwind_cpp_pr1(void){
2688 VG_(printf)("Something called __aeabi_unwind_cpp_pr1()\n");
2689 vg_assert(0);
2690}
sewardj59570ff2010-01-01 11:59:33 +00002691#endif
2692
sewardj45f4e7c2005-09-27 19:20:21 +00002693/* ---------------- Requirement 2 ---------------- */
2694
2695/* Glibc's sysdeps/i386/elf/start.S has the following gem of a
2696 comment, which explains how the stack looks right at process start
2697 (when _start is jumped to). Hence _start passes %esp to
sewardj17c11042006-10-15 01:26:40 +00002698 _start_in_C_linux, which extracts argc/argv/envp and starts up
sewardj45f4e7c2005-09-27 19:20:21 +00002699 correctly. */
2700
2701/* This is the canonical entry point, usually the first thing in the text
2702 segment. The SVR4/i386 ABI (pages 3-31, 3-32) says that when the entry
2703 point runs, most registers' values are unspecified, except for:
2704
2705 %edx Contains a function pointer to be registered with `atexit'.
2706 This is how the dynamic linker arranges to have DT_FINI
2707 functions called for shared libraries that have been loaded
2708 before this code runs.
2709
2710 %esp The stack contains the arguments and environment:
2711 0(%esp) argc
2712 4(%esp) argv[0]
2713 ...
2714 (4*argc)(%esp) NULL
2715 (4*(argc+1))(%esp) envp[0]
2716 ...
2717 NULL
2718*/
2719
2720/* The kernel hands control to _start, which extracts the initial
sewardj17c11042006-10-15 01:26:40 +00002721 stack pointer and calls onwards to _start_in_C_linux. This also switches
sewardja48a4932005-09-29 11:09:56 +00002722 the new stack. */
sewardj45f4e7c2005-09-27 19:20:21 +00002723#if defined(VGP_x86_linux)
2724asm("\n"
sewardjd9fc3822005-11-18 23:50:43 +00002725 ".text\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002726 "\t.globl _start\n"
2727 "\t.type _start,@function\n"
2728 "_start:\n"
2729 /* set up the new stack in %eax */
sewardjfdf91b42005-09-28 00:53:09 +00002730 "\tmovl $vgPlain_interim_stack, %eax\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002731 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
2732 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
2733 "\tsubl $16, %eax\n"
2734 "\tandl $~15, %eax\n"
2735 /* install it, and collect the original one */
2736 "\txchgl %eax, %esp\n"
sewardj17c11042006-10-15 01:26:40 +00002737 /* call _start_in_C_linux, passing it the startup %esp */
sewardj45f4e7c2005-09-27 19:20:21 +00002738 "\tpushl %eax\n"
sewardj17c11042006-10-15 01:26:40 +00002739 "\tcall _start_in_C_linux\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002740 "\thlt\n"
sewardj2fedc642005-11-19 02:02:57 +00002741 ".previous\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002742);
2743#elif defined(VGP_amd64_linux)
2744asm("\n"
sewardjd9fc3822005-11-18 23:50:43 +00002745 ".text\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002746 "\t.globl _start\n"
2747 "\t.type _start,@function\n"
2748 "_start:\n"
2749 /* set up the new stack in %rdi */
sewardjfdf91b42005-09-28 00:53:09 +00002750 "\tmovq $vgPlain_interim_stack, %rdi\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002751 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
2752 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
2753 "\tandq $~15, %rdi\n"
2754 /* install it, and collect the original one */
2755 "\txchgq %rdi, %rsp\n"
sewardj17c11042006-10-15 01:26:40 +00002756 /* call _start_in_C_linux, passing it the startup %rsp */
2757 "\tcall _start_in_C_linux\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002758 "\thlt\n"
sewardj2fedc642005-11-19 02:02:57 +00002759 ".previous\n"
sewardj45f4e7c2005-09-27 19:20:21 +00002760);
sewardja48a4932005-09-29 11:09:56 +00002761#elif defined(VGP_ppc32_linux)
2762asm("\n"
sewardjd9fc3822005-11-18 23:50:43 +00002763 ".text\n"
sewardja48a4932005-09-29 11:09:56 +00002764 "\t.globl _start\n"
2765 "\t.type _start,@function\n"
2766 "_start:\n"
2767 /* set up the new stack in r16 */
2768 "\tlis 16,vgPlain_interim_stack@ha\n"
2769 "\tla 16,vgPlain_interim_stack@l(16)\n"
2770 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2771 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2772 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2773 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2774 "\tadd 16,17,16\n"
2775 "\tadd 16,18,16\n"
2776 "\trlwinm 16,16,0,0,27\n"
2777 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2778 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2779 boundary. And r1 is the original SP. Set the SP to r16 and
sewardj17c11042006-10-15 01:26:40 +00002780 call _start_in_C_linux, passing it the initial SP. */
sewardja48a4932005-09-29 11:09:56 +00002781 "\tmr 3,1\n"
2782 "\tmr 1,16\n"
sewardj17c11042006-10-15 01:26:40 +00002783 "\tbl _start_in_C_linux\n"
sewardja48a4932005-09-29 11:09:56 +00002784 "\ttrap\n"
sewardj2fedc642005-11-19 02:02:57 +00002785 ".previous\n"
sewardja48a4932005-09-29 11:09:56 +00002786);
sewardj2c48c7b2005-11-29 13:05:56 +00002787#elif defined(VGP_ppc64_linux)
2788asm("\n"
cerion21082042005-12-06 19:07:08 +00002789 /* PPC64 ELF ABI says '_start' points to a function descriptor.
2790 So we must have one, and that is what goes into the .opd section. */
cerion297c88f2005-12-22 15:53:12 +00002791 "\t.align 2\n"
cerion21082042005-12-06 19:07:08 +00002792 "\t.global _start\n"
2793 "\t.section \".opd\",\"aw\"\n"
2794 "\t.align 3\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002795 "_start:\n"
cerion21082042005-12-06 19:07:08 +00002796 "\t.quad ._start,.TOC.@tocbase,0\n"
2797 "\t.previous\n"
2798 "\t.type ._start,@function\n"
2799 "\t.global ._start\n"
2800 "._start:\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002801 /* set up the new stack in r16 */
2802 "\tlis 16, vgPlain_interim_stack@highest\n"
2803 "\tori 16,16,vgPlain_interim_stack@higher\n"
2804 "\tsldi 16,16,32\n"
2805 "\toris 16,16,vgPlain_interim_stack@h\n"
2806 "\tori 16,16,vgPlain_interim_stack@l\n"
2807 "\txor 17,17,17\n"
2808 "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n"
2809 "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n"
2810 "\txor 18,18,18\n"
2811 "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n"
2812 "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n"
2813 "\tadd 16,17,16\n"
2814 "\tadd 16,18,16\n"
2815 "\trldicr 16,16,0,59\n"
2816 /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2817 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2818 boundary. And r1 is the original SP. Set the SP to r16 and
sewardj17c11042006-10-15 01:26:40 +00002819 call _start_in_C_linux, passing it the initial SP. */
sewardj2c48c7b2005-11-29 13:05:56 +00002820 "\tmr 3,1\n"
2821 "\tmr 1,16\n"
sewardj5e21d442012-07-21 10:08:29 +00002822 "\tlis 14, _start_in_C_linux@highest\n"
2823 "\tori 14,14,_start_in_C_linux@higher\n"
2824 "\tsldi 14,14,32\n"
2825 "\toris 14,14,_start_in_C_linux@h\n"
2826 "\tori 14,14,_start_in_C_linux@l\n"
2827 "\tld 14,0(14)\n"
2828 "\tmtctr 14\n"
2829 "\tbctrl\n"
cerion21082042005-12-06 19:07:08 +00002830 "\tnop\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002831 "\ttrap\n"
sewardj2c48c7b2005-11-29 13:05:56 +00002832);
sewardjb5b87402011-03-07 16:05:35 +00002833#elif defined(VGP_s390x_linux)
2834/*
2835 This is the canonical entry point, usually the first thing in the text
2836 segment. Most registers' values are unspecified, except for:
2837
2838 %r14 Contains a function pointer to be registered with `atexit'.
2839 This is how the dynamic linker arranges to have DT_FINI
2840 functions called for shared libraries that have been loaded
2841 before this code runs.
2842
2843 %r15 The stack contains the arguments and environment:
2844 0(%r15) argc
2845 8(%r15) argv[0]
2846 ...
2847 (8*argc)(%r15) NULL
2848 (8*(argc+1))(%r15) envp[0]
2849 ...
2850 NULL
2851*/
2852asm("\n\t"
2853 ".text\n\t"
2854 ".globl _start\n\t"
2855 ".type _start,@function\n\t"
2856 "_start:\n\t"
2857 /* set up the new stack in %r1 */
2858 "larl %r1, vgPlain_interim_stack\n\t"
2859 "larl %r5, 1f\n\t"
2860 "ag %r1, 0(%r5)\n\t"
2861 "ag %r1, 2f-1f(%r5)\n\t"
2862 "nill %r1, 0xFFF0\n\t"
2863 /* install it, and collect the original one */
2864 "lgr %r2, %r15\n\t"
2865 "lgr %r15, %r1\n\t"
2866 /* call _start_in_C_linux, passing it the startup %r15 */
2867 "brasl %r14, _start_in_C_linux\n\t"
2868 /* trigger execution of an invalid opcode -> halt machine */
2869 "j .+2\n\t"
2870 "1: .quad "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n\t"
2871 "2: .quad "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n\t"
2872 ".previous\n"
2873);
sewardj59570ff2010-01-01 11:59:33 +00002874#elif defined(VGP_arm_linux)
2875asm("\n"
sewardjb51c9262011-05-03 14:24:11 +00002876 "\t.text\n"
2877 "\t.align 4\n"
2878 "\t.type _start,#function\n"
sewardj59570ff2010-01-01 11:59:33 +00002879 "\t.global _start\n"
2880 "_start:\n"
2881 "\tldr r0, [pc, #36]\n"
2882 "\tldr r1, [pc, #36]\n"
2883 "\tadd r0, r1, r0\n"
2884 "\tldr r1, [pc, #32]\n"
2885 "\tadd r0, r1, r0\n"
2886 "\tmvn r1, #15\n"
2887 "\tand r0, r0, r1\n"
2888 "\tmov r1, sp\n"
2889 "\tmov sp, r0\n"
2890 "\tmov r0, r1\n"
2891 "\tb _start_in_C_linux\n"
2892 "\t.word vgPlain_interim_stack\n"
2893 "\t.word "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
2894 "\t.word "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
2895);
sewardj5db15402012-06-07 09:13:21 +00002896#elif defined(VGP_mips32_linux)
2897asm("\n"
2898 "\t.type _gp_disp,@object\n"
2899 ".text\n"
2900 "\t.globl __start\n"
2901 "\t.type __start,@function\n"
2902 "__start:\n"
2903
2904 "\tbal 1f\n"
2905 "\tnop\n"
2906
2907 "1:\n"
2908
2909 "\tlui $28, %hi(_gp_disp)\n"
2910 "\taddiu $28, $28, %lo(_gp_disp)\n"
2911 "\taddu $28, $28, $31\n"
2912 /* t1/$9 <- Addr(interim_stack) */
2913 "\tlui $9, %hi(vgPlain_interim_stack)\n"
2914 /* t1/$9 <- Addr(interim_stack) */
2915 "\taddiu $9, %lo(vgPlain_interim_stack)\n"
2916
2917
2918 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
2919 "\tli $11, "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
2920
2921 "\taddu $9, $9, $10\n"
2922 "\taddu $9, $9, $11\n"
2923 "\tli $12, 0xFFFFFFF0\n"
2924 "\tand $9, $9, $12\n"
2925 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2926 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2927 boundary. And $29 is the original SP. Set the SP to t1 and
2928 call _start_in_C, passing it the initial SP. */
2929
2930 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
2931 "\tmove $29, $9\n" // $sp <- t1 (new sp)
2932
2933 "\tlui $25, %hi(_start_in_C_linux)\n"
2934 "\taddiu $25, %lo(_start_in_C_linux)\n"
2935
2936 "\tbal _start_in_C_linux\n"
2937 "\tbreak 0x7\n"
2938 ".previous\n"
2939);
petarj4df0bfc2013-02-27 23:17:33 +00002940#elif defined(VGP_mips64_linux)
2941asm(
2942".text\n"
2943".globl __start\n"
2944".type __start,@function\n"
2945"__start:\n"
2946 "\t.set noreorder\n"
2947 "\t.cpload $25\n"
2948 "\t.set reorder\n"
2949 "\t.cprestore 16\n"
2950 "\tlui $9, %hi(vgPlain_interim_stack)\n"
2951 /* t1/$9 <- Addr(interim_stack) */
2952 "\tdaddiu $9, %lo(vgPlain_interim_stack)\n"
2953
2954 "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n"
2955 "\tli $11, "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n"
2956
2957 "\tdaddu $9, $9, $10\n"
2958 "\tdaddu $9, $9, $11\n"
2959 "\tli $12, 0xFFFFFF00\n"
2960 "\tand $9, $9, $12\n"
2961 /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB +
2962 VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte
2963 boundary. And $29 is the original SP. Set the SP to t1 and
2964 call _start_in_C, passing it the initial SP. */
2965
2966 "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg)
2967 "\tmove $29, $9\n" // $sp <- t1 (new sp)
2968
2969 "\tlui $9, %highest(_start_in_C_linux)\n"
2970 "\tori $9, %higher(_start_in_C_linux)\n"
2971 "\tdsll32 $9, $9, 0x0\n"
2972 "\tlui $10, %hi(_start_in_C_linux)\n"
2973 "\tdaddiu $10, %lo(_start_in_C_linux)\n"
2974 "\tdaddu $25, $9, $10\n"
2975 "\tjalr $25\n"
2976 "\tnop\n"
2977".end __start\n"
2978);
sewardj45f4e7c2005-09-27 19:20:21 +00002979#else
njn49f80e82009-05-21 01:25:43 +00002980# error "Unknown linux platform"
sewardj45f4e7c2005-09-27 19:20:21 +00002981#endif
2982
sewardje66f2e02006-12-30 17:45:08 +00002983/* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
2984#define _GNU_SOURCE
2985#define _FILE_OFFSET_BITS 64
2986/* This is in order to get AT_NULL and AT_PAGESIZE. */
2987#include <elf.h>
2988/* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
2989
sewardj45f4e7c2005-09-27 19:20:21 +00002990/* Avoid compiler warnings: this fn _is_ used, but labelling it
philippe9fdca562012-04-16 22:06:47 +00002991 'static' causes gcc to complain it isn't.
2992 attribute 'used' also ensures the code is not eliminated at link
2993 time */
2994__attribute__ ((used))
sewardj17c11042006-10-15 01:26:40 +00002995void _start_in_C_linux ( UWord* pArgc );
philippe9fdca562012-04-16 22:06:47 +00002996__attribute__ ((used))
sewardj17c11042006-10-15 01:26:40 +00002997void _start_in_C_linux ( UWord* pArgc )
sewardj45f4e7c2005-09-27 19:20:21 +00002998{
2999 Int r;
3000 Word argc = pArgc[0];
3001 HChar** argv = (HChar**)&pArgc[1];
3002 HChar** envp = (HChar**)&pArgc[1+argc+1];
sewardjf9d2f9b2006-11-17 20:00:57 +00003003
3004 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3005 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3006
3007 the_iicii.sp_at_startup = (Addr)pArgc;
3008
sewardje66f2e02006-12-30 17:45:08 +00003009# if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux)
3010 {
3011 /* ppc/ppc64 can be configured with different page sizes.
3012 Determine this early. This is an ugly hack and really should
3013 be moved into valgrind_main. */
3014 UWord *sp = &pArgc[1+argc+1];
3015 while (*sp++ != 0)
3016 ;
3017 for (; *sp != AT_NULL && *sp != AT_PAGESZ; sp += 2);
3018 if (*sp == AT_PAGESZ) {
3019 VKI_PAGE_SIZE = sp[1];
3020 for (VKI_PAGE_SHIFT = 12;
3021 VKI_PAGE_SHIFT <= VKI_MAX_PAGE_SHIFT; VKI_PAGE_SHIFT++)
3022 if (VKI_PAGE_SIZE == (1UL << VKI_PAGE_SHIFT))
3023 break;
3024 }
3025 }
3026# endif
3027
sewardjf9d2f9b2006-11-17 20:00:57 +00003028 r = valgrind_main( (Int)argc, argv, envp );
sewardj17c11042006-10-15 01:26:40 +00003029 /* NOTREACHED */
sewardj45f4e7c2005-09-27 19:20:21 +00003030 VG_(exit)(r);
3031}
3032
sewardj17c11042006-10-15 01:26:40 +00003033
3034/*====================================================================*/
njnf76d27a2009-05-28 01:53:07 +00003035/*=== Getting to main() alive: darwin ===*/
3036/*====================================================================*/
3037
3038#elif defined(VGO_darwin)
3039
njnea2d6fd2010-07-01 00:20:20 +00003040/*
3041 Memory layout established by kernel:
3042
3043 0(%esp) argc
3044 4(%esp) argv[0]
3045 ...
3046 argv[argc-1]
3047 NULL
3048 envp[0]
3049 ...
3050 envp[n]
3051 NULL
3052 executable name (presumably, a pointer to it)
3053 NULL
3054
3055 Ditto in the 64-bit case, except all offsets from SP are obviously
3056 twice as large.
3057*/
3058
3059/* The kernel hands control to _start, which extracts the initial
3060 stack pointer and calls onwards to _start_in_C_darwin. This also
3061 switches to the new stack. */
3062#if defined(VGP_x86_darwin)
3063asm("\n"
3064 ".text\n"
3065 ".align 2,0x90\n"
3066 "\t.globl __start\n"
3067 "__start:\n"
3068 /* set up the new stack in %eax */
3069 "\tmovl $_vgPlain_interim_stack, %eax\n"
3070 "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n"
3071 "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n"
3072 "\tsubl $16, %eax\n"
3073 "\tandl $~15, %eax\n"
3074 /* install it, and collect the original one */
3075 "\txchgl %eax, %esp\n"
sewardj69197362012-03-07 16:38:12 +00003076 "\tsubl $12, %esp\n" // keep stack 16 aligned; see #295428
njnea2d6fd2010-07-01 00:20:20 +00003077 /* call _start_in_C_darwin, passing it the startup %esp */
3078 "\tpushl %eax\n"
3079 "\tcall __start_in_C_darwin\n"
3080 "\tint $3\n"
3081 "\tint $3\n"
3082);
3083#elif defined(VGP_amd64_darwin)
3084asm("\n"
3085 ".text\n"
3086 "\t.globl __start\n"
3087 ".align 3,0x90\n"
3088 "__start:\n"
3089 /* set up the new stack in %rdi */
3090 "\tmovabsq $_vgPlain_interim_stack, %rdi\n"
3091 "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n"
3092 "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n"
3093 "\tandq $~15, %rdi\n"
3094 /* install it, and collect the original one */
3095 "\txchgq %rdi, %rsp\n"
3096 /* call _start_in_C_darwin, passing it the startup %rsp */
3097 "\tcall __start_in_C_darwin\n"
3098 "\tint $3\n"
3099 "\tint $3\n"
3100);
3101#endif
3102
njnf76d27a2009-05-28 01:53:07 +00003103void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2);
3104void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2) {
3105 // skip check
3106 return VG_(memcpy)(dest,src,n);
3107}
3108void* __memset_chk(void *s, int c, SizeT n, SizeT n2);
3109void* __memset_chk(void *s, int c, SizeT n, SizeT n2) {
3110 // skip check
3111 return VG_(memset)(s,c,n);
3112}
3113void bzero(void *s, SizeT n);
3114void bzero(void *s, SizeT n) {
3115 VG_(memset)(s,0,n);
3116}
3117
3118void* memcpy(void *dest, const void *src, SizeT n);
3119void* memcpy(void *dest, const void *src, SizeT n) {
3120 return VG_(memcpy)(dest,src,n);
3121}
3122void* memset(void *s, int c, SizeT n);
3123void* memset(void *s, int c, SizeT n) {
3124 return VG_(memset)(s,c,n);
3125}
3126
njnf76d27a2009-05-28 01:53:07 +00003127/* Avoid compiler warnings: this fn _is_ used, but labelling it
3128 'static' causes gcc to complain it isn't. */
3129void _start_in_C_darwin ( UWord* pArgc );
3130void _start_in_C_darwin ( UWord* pArgc )
3131{
3132 Int r;
njnea2d6fd2010-07-01 00:20:20 +00003133 Int argc = *(Int *)pArgc; // not pArgc[0] on LP64
njnf76d27a2009-05-28 01:53:07 +00003134 HChar** argv = (HChar**)&pArgc[1];
3135 HChar** envp = (HChar**)&pArgc[1+argc+1];
3136
3137 VG_(memset)( &the_iicii, 0, sizeof(the_iicii) );
3138 VG_(memset)( &the_iifii, 0, sizeof(the_iifii) );
3139
3140 the_iicii.sp_at_startup = (Addr)pArgc;
3141
3142 r = valgrind_main( (Int)argc, argv, envp );
3143 /* NOTREACHED */
3144 VG_(exit)(r);
3145}
3146
3147
njn49f80e82009-05-21 01:25:43 +00003148#else
3149
3150# error "Unknown OS"
3151#endif
sewardj17c11042006-10-15 01:26:40 +00003152
3153
sewardj0af71bb2010-07-01 14:50:30 +00003154/*====================================================================*/
3155/*=== {u,}{div,mod}di3 replacements ===*/
3156/*====================================================================*/
njnea2d6fd2010-07-01 00:20:20 +00003157
3158/* For static linking on x86-darwin, we need to supply our own 64-bit
3159 integer division code, else the link dies thusly:
3160
3161 ld_classic: Undefined symbols:
3162 ___udivdi3
3163 ___umoddi3
3164*/
3165#if defined(VGP_x86_darwin)
3166
3167/* Routines for doing signed/unsigned 64 x 64 ==> 64 div and mod
3168 (udivdi3, umoddi3, divdi3, moddi3) using only 32 x 32 ==> 32
3169 division. Cobbled together from
3170
3171 http://www.hackersdelight.org/HDcode/divlu.c
3172 http://www.hackersdelight.org/HDcode/divls.c
3173 http://www.hackersdelight.org/HDcode/newCode/divDouble.c
3174
3175 The code from those three files is covered by the following license,
3176 as it appears at:
3177
3178 http://www.hackersdelight.org/permissions.htm
3179
3180 You are free to use, copy, and distribute any of the code on
3181 this web site, whether modified by you or not. You need not give
3182 attribution. This includes the algorithms (some of which appear
3183 in Hacker's Delight), the Hacker's Assistant, and any code
3184 submitted by readers. Submitters implicitly agree to this.
3185*/
3186
3187/* Long division, unsigned (64/32 ==> 32).
3188 This procedure performs unsigned "long division" i.e., division of a
318964-bit unsigned dividend by a 32-bit unsigned divisor, producing a
319032-bit quotient. In the overflow cases (divide by 0, or quotient
3191exceeds 32 bits), it returns a remainder of 0xFFFFFFFF (an impossible
3192value).
3193 The dividend is u1 and u0, with u1 being the most significant word.
3194The divisor is parameter v. The value returned is the quotient.
3195 Max line length is 57, to fit in hacker.book. */
3196
3197static Int nlz32(UInt x)
3198{
3199 Int n;
3200 if (x == 0) return(32);
3201 n = 0;
3202 if (x <= 0x0000FFFF) {n = n +16; x = x <<16;}
3203 if (x <= 0x00FFFFFF) {n = n + 8; x = x << 8;}
3204 if (x <= 0x0FFFFFFF) {n = n + 4; x = x << 4;}
3205 if (x <= 0x3FFFFFFF) {n = n + 2; x = x << 2;}
3206 if (x <= 0x7FFFFFFF) {n = n + 1;}
3207 return n;
3208}
3209
3210/* 64 x 32 ==> 32 unsigned division, using only 32 x 32 ==> 32
3211 division as a primitive. */
3212static UInt divlu2(UInt u1, UInt u0, UInt v, UInt *r)
3213{
3214 const UInt b = 65536; // Number base (16 bits).
3215 UInt un1, un0, // Norm. dividend LSD's.
3216 vn1, vn0, // Norm. divisor digits.
3217 q1, q0, // Quotient digits.
3218 un32, un21, un10, // Dividend digit pairs.
3219 rhat; // A remainder.
3220 Int s; // Shift amount for norm.
3221
3222 if (u1 >= v) { // If overflow, set rem.
3223 if (r != NULL) // to an impossible value,
3224 *r = 0xFFFFFFFF; // and return the largest
3225 return 0xFFFFFFFF;} // possible quotient.
3226
3227 s = nlz32(v); // 0 <= s <= 31.
3228 v = v << s; // Normalize divisor.
3229 vn1 = v >> 16; // Break divisor up into
3230 vn0 = v & 0xFFFF; // two 16-bit digits.
3231
3232 un32 = (u1 << s) | ((u0 >> (32 - s)) & (-s >> 31));
3233 un10 = u0 << s; // Shift dividend left.
3234
3235 un1 = un10 >> 16; // Break right half of
3236 un0 = un10 & 0xFFFF; // dividend into two digits.
3237
3238 q1 = un32/vn1; // Compute the first
3239 rhat = un32 - q1*vn1; // quotient digit, q1.
3240 again1:
3241 if (q1 >= b || q1*vn0 > b*rhat + un1) {
3242 q1 = q1 - 1;
3243 rhat = rhat + vn1;
3244 if (rhat < b) goto again1;}
3245
3246 un21 = un32*b + un1 - q1*v; // Multiply and subtract.
3247
3248 q0 = un21/vn1; // Compute the second
3249 rhat = un21 - q0*vn1; // quotient digit, q0.
3250 again2:
3251 if (q0 >= b || q0*vn0 > b*rhat + un0) {
3252 q0 = q0 - 1;
3253 rhat = rhat + vn1;
3254 if (rhat < b) goto again2;}
3255
3256 if (r != NULL) // If remainder is wanted,
3257 *r = (un21*b + un0 - q0*v) >> s; // return it.
3258 return q1*b + q0;
3259}
3260
3261
3262/* 64 x 32 ==> 32 signed division, using only 32 x 32 ==> 32 division
3263 as a primitive. */
3264static Int divls(Int u1, UInt u0, Int v, Int *r)
3265{
3266 Int q, uneg, vneg, diff, borrow;
3267
3268 uneg = u1 >> 31; // -1 if u < 0.
3269 if (uneg) { // Compute the absolute
3270 u0 = -u0; // value of the dividend u.
3271 borrow = (u0 != 0);
3272 u1 = -u1 - borrow;}
3273
3274 vneg = v >> 31; // -1 if v < 0.
3275 v = (v ^ vneg) - vneg; // Absolute value of v.
3276
3277 if ((UInt)u1 >= (UInt)v) goto overflow;
3278
3279 q = divlu2(u1, u0, v, (UInt *)r);
3280
3281 diff = uneg ^ vneg; // Negate q if signs of
3282 q = (q ^ diff) - diff; // u and v differed.
3283 if (uneg && r != NULL)
3284 *r = -*r;
3285
3286 if ((diff ^ q) < 0 && q != 0) { // If overflow,
3287 overflow: // set remainder
3288 if (r != NULL) // to an impossible value,
3289 *r = 0x80000000; // and return the largest
3290 q = 0x80000000;} // possible neg. quotient.
3291 return q;
3292}
3293
3294
3295
3296/* This file contains a program for doing 64/64 ==> 64 division, on a
3297machine that does not have that instruction but that does have
3298instructions for "long division" (64/32 ==> 32). Code for unsigned
3299division is given first, followed by a simple program for doing the
3300signed version by using the unsigned version.
3301 These programs are useful in implementing "long long" (64-bit)
3302arithmetic on a machine that has the long division instruction. It will
3303work on 64- and 32-bit machines, provided the compiler implements long
3304long's (64-bit integers). It is desirable that the machine have the
3305Count Leading Zeros instruction.
3306 In the GNU world, these programs are known as __divdi3 and __udivdi3,
3307and similar names are used here.
3308 This material is not in HD, but may be in a future edition.
3309Max line length is 57, to fit in hacker.book. */
3310
3311
3312static Int nlz64(ULong x)
3313{
3314 Int n;
3315 if (x == 0) return(64);
3316 n = 0;
3317 if (x <= 0x00000000FFFFFFFFULL) {n = n + 32; x = x << 32;}
3318 if (x <= 0x0000FFFFFFFFFFFFULL) {n = n + 16; x = x << 16;}
3319 if (x <= 0x00FFFFFFFFFFFFFFULL) {n = n + 8; x = x << 8;}
3320 if (x <= 0x0FFFFFFFFFFFFFFFULL) {n = n + 4; x = x << 4;}
3321 if (x <= 0x3FFFFFFFFFFFFFFFULL) {n = n + 2; x = x << 2;}
3322 if (x <= 0x7FFFFFFFFFFFFFFFULL) {n = n + 1;}
3323 return n;
3324}
3325
3326// ---------------------------- udivdi3 --------------------------------
3327
3328 /* The variables u0, u1, etc. take on only 32-bit values, but they
3329 are declared long long to avoid some compiler warning messages and to
3330 avoid some unnecessary EXTRs that the compiler would put in, to
3331 convert long longs to ints.
3332
3333 First the procedure takes care of the case in which the divisor is a
3334 32-bit quantity. There are two subcases: (1) If the left half of the
3335 dividend is less than the divisor, one execution of DIVU is all that
3336 is required (overflow is not possible). (2) Otherwise it does two
3337 divisions, using the grade school method, with variables used as
3338 suggested below.
3339
3340 q1 q0
3341 ________
3342 v) u1 u0
3343 q1*v
3344 ____
3345 k u0 */
3346
3347/* These macros must be used with arguments of the appropriate type
3348(unsigned long long for DIVU and long long for DIVS. They are
3349simulations of the presumed machines ops. I.e., they look at only the
3350low-order 32 bits of the divisor, they return garbage if the division
3351overflows, and they return garbage in the high-order half of the
3352quotient doubleword.
3353 In practice, these would be replaced with uses of the machine's DIVU
3354and DIVS instructions (e.g., by using the GNU "asm" facility). */
3355
3356static UInt DIVU ( ULong u, UInt v )
3357{
3358 UInt uHi = (UInt)(u >> 32);
3359 UInt uLo = (UInt)u;
3360 return divlu2(uHi, uLo, v, NULL);
3361}
3362
3363static Int DIVS ( Long u, Int v )
3364{
3365 Int uHi = (Int)(u >> 32);
3366 UInt uLo = (UInt)u;
3367 return divls(uHi, uLo, v, NULL);
3368}
3369
3370/* 64 x 64 ==> 64 unsigned division, using only 32 x 32 ==> 32
3371 division as a primitive. */
3372static ULong udivdi3(ULong u, ULong v)
3373{
3374 ULong u0, u1, v1, q0, q1, k, n;
3375
3376 if (v >> 32 == 0) { // If v < 2**32:
3377 if (u >> 32 < v) // If u/v cannot overflow,
3378 return DIVU(u, v) // just do one division.
3379 & 0xFFFFFFFF;
3380 else { // If u/v would overflow:
3381 u1 = u >> 32; // Break u up into two
3382 u0 = u & 0xFFFFFFFF; // halves.
3383 q1 = DIVU(u1, v) // First quotient digit.
3384 & 0xFFFFFFFF;
3385 k = u1 - q1*v; // First remainder, < v.
3386 q0 = DIVU((k << 32) + u0, v) // 2nd quot. digit.
3387 & 0xFFFFFFFF;
3388 return (q1 << 32) + q0;
3389 }
3390 }
3391 // Here v >= 2**32.
3392 n = nlz64(v); // 0 <= n <= 31.
3393 v1 = (v << n) >> 32; // Normalize the divisor
3394 // so its MSB is 1.
3395 u1 = u >> 1; // To ensure no overflow.
3396 q1 = DIVU(u1, v1) // Get quotient from
3397 & 0xFFFFFFFF; // divide unsigned insn.
3398 q0 = (q1 << n) >> 31; // Undo normalization and
3399 // division of u by 2.
3400 if (q0 != 0) // Make q0 correct or
3401 q0 = q0 - 1; // too small by 1.
3402 if ((u - q0*v) >= v)
3403 q0 = q0 + 1; // Now q0 is correct.
3404 return q0;
3405}
3406
3407
3408// ----------------------------- divdi3 --------------------------------
3409
3410/* This routine presumes that smallish cases (those which can be done in
3411one execution of DIVS) are common. If this is not the case, the test for
3412this case should be deleted.
3413 Note that the test for when DIVS can be used is not entirely
3414accurate. For example, DIVS is not used if v = 0xFFFFFFFF8000000,
3415whereas if could be (if u is sufficiently small in magnitude). */
3416
3417// ------------------------------ cut ----------------------------------
3418
3419static ULong my_llabs ( Long x )
3420{
3421 ULong t = x >> 63;
3422 return (x ^ t) - t;
3423}
3424
3425/* 64 x 64 ==> 64 signed division, using only 32 x 32 ==> 32 division
3426 as a primitive. */
3427static Long divdi3(Long u, Long v)
3428{
3429 ULong au, av;
3430 Long q, t;
3431 au = my_llabs(u);
3432 av = my_llabs(v);
3433 if (av >> 31 == 0) { // If |v| < 2**31 and
3434 // if (v << 32 >> 32 == v) { // If v is in range and
3435 if (au < av << 31) { // |u|/|v| cannot
3436 q = DIVS(u, v); // overflow, use DIVS.
3437 return (q << 32) >> 32;
3438 }
3439 }
3440 q = udivdi3(au,av); // Invoke udivdi3.
3441 t = (u ^ v) >> 63; // If u, v have different
3442 return (q ^ t) - t; // signs, negate q.
3443}
3444
3445// ---------------------------- end cut --------------------------------
3446
sewardj0af71bb2010-07-01 14:50:30 +00003447ULong __udivdi3 (ULong u, ULong v);
njnea2d6fd2010-07-01 00:20:20 +00003448ULong __udivdi3 (ULong u, ULong v)
3449{
3450 return udivdi3(u,v);
3451}
3452
sewardj0af71bb2010-07-01 14:50:30 +00003453Long __divdi3 (Long u, Long v);
njnea2d6fd2010-07-01 00:20:20 +00003454Long __divdi3 (Long u, Long v)
3455{
3456 return divdi3(u,v);
3457}
3458
sewardj0af71bb2010-07-01 14:50:30 +00003459ULong __umoddi3 (ULong u, ULong v);
njnea2d6fd2010-07-01 00:20:20 +00003460ULong __umoddi3 (ULong u, ULong v)
3461{
3462 ULong q = __udivdi3(u, v);
3463 ULong r = u - q * v;
3464 return r;
3465}
3466
sewardj0af71bb2010-07-01 14:50:30 +00003467Long __moddi3 (Long u, Long v);
njnea2d6fd2010-07-01 00:20:20 +00003468Long __moddi3 (Long u, Long v)
3469{
3470 Long q = __divdi3(u, v);
3471 Long r = u - q * v;
3472 return r;
3473}
3474
sewardj70d71c72011-08-23 07:35:42 +00003475/* ------------------------------------------------
3476 ld_classic: Undefined symbols:
3477 ___fixunsdfdi
3478 ------------------------------------------------
3479*/
3480
3481/* ===-- fixunsdfdi.c - Implement __fixunsdfdi -----------------------------===
3482 *
3483 * The LLVM Compiler Infrastructure
3484 *
3485 * This file is dual licensed under the MIT and the University of Illinois Open
3486 * Source Licenses. See LICENSE.TXT for details.
3487 *
3488 * ===----------------------------------------------------------------------===
3489 *
3490 * This file implements __fixunsdfdi for the compiler_rt library.
3491 *
3492 * ===----------------------------------------------------------------------===
3493 */
3494
3495/* As per http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses,
3496
3497 the "NCSA/University of Illinois Open Source License" is compatible
3498 with the GPL (both version 2 and 3). What is claimed to be
3499 compatible is this
3500
3501 http://www.opensource.org/licenses/UoI-NCSA.php
3502
3503 and the LLVM documentation at
3504
3505 http://www.llvm.org/docs/DeveloperPolicy.html#license
3506
3507 says all the code in LLVM is available under the University of
3508 Illinois/NCSA Open Source License, at this URL
3509
3510 http://www.opensource.org/licenses/UoI-NCSA.php
3511
3512 viz, the same one that the FSF pages claim is compatible. So I
3513 think it's OK to include it.
3514*/
3515
3516/* Returns: convert a to a unsigned long long, rounding toward zero.
3517 * Negative values all become zero.
3518 */
3519
3520/* Assumption: double is a IEEE 64 bit floating point type
3521 * du_int is a 64 bit integral type
3522 * value in double is representable in du_int or is negative
3523 * (no range checking performed)
3524 */
3525
3526/* seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm */
3527
3528typedef unsigned long long du_int;
3529typedef unsigned su_int;
3530
3531typedef union
3532{
3533 du_int all;
3534 struct
3535 {
3536#if VG_LITTLEENDIAN
3537 su_int low;
3538 su_int high;
3539#else
3540 su_int high;
3541 su_int low;
3542#endif /* VG_LITTLEENDIAN */
3543 }s;
3544} udwords;
3545
3546typedef union
3547{
3548 udwords u;
3549 double f;
3550} double_bits;
3551
3552du_int __fixunsdfdi(double a);
3553
3554du_int
3555__fixunsdfdi(double a)
3556{
3557 double_bits fb;
3558 fb.f = a;
3559 int e = ((fb.u.s.high & 0x7FF00000) >> 20) - 1023;
3560 if (e < 0 || (fb.u.s.high & 0x80000000))
3561 return 0;
3562 udwords r;
3563 r.s.high = (fb.u.s.high & 0x000FFFFF) | 0x00100000;
3564 r.s.low = fb.u.s.low;
3565 if (e > 52)
3566 r.all <<= (e - 52);
3567 else
3568 r.all >>= (52 - e);
3569 return r.all;
3570}
3571
3572
njnea2d6fd2010-07-01 00:20:20 +00003573#endif
3574
3575
sewardjde4a1d02002-03-22 01:27:54 +00003576/*--------------------------------------------------------------------*/
njn04e16982005-05-31 00:23:43 +00003577/*--- end ---*/
sewardjde4a1d02002-03-22 01:27:54 +00003578/*--------------------------------------------------------------------*/