2 /*--------------------------------------------------------------------*/
3 /*--- Startup: create initial process image on Linux ---*/
4 /*--- initimg-linux.c ---*/
5 /*--------------------------------------------------------------------*/
8 This file is part of Valgrind, a dynamic binary instrumentation
11 Copyright (C) 2000-2010 Julian Seward
14 This program is free software; you can redistribute it and/or
15 modify it under the terms of the GNU General Public License as
16 published by the Free Software Foundation; either version 2 of the
17 License, or (at your option) any later version.
19 This program is distributed in the hope that it will be useful, but
20 WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 General Public License for more details.
24 You should have received a copy of the GNU General Public License
25 along with this program; if not, write to the Free Software
26 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
29 The GNU General Public License is contained in the file COPYING.
32 #if defined(VGO_linux)
34 #include "pub_core_basics.h"
35 #include "pub_core_vki.h"
36 #include "pub_core_debuglog.h"
37 #include "pub_core_libcbase.h"
38 #include "pub_core_libcassert.h"
39 #include "pub_core_libcfile.h"
40 #include "pub_core_libcproc.h"
41 #include "pub_core_libcprint.h"
42 #include "pub_core_xarray.h"
43 #include "pub_core_clientstate.h"
44 #include "pub_core_aspacemgr.h"
45 #include "pub_core_mallocfree.h"
46 #include "pub_core_machine.h"
47 #include "pub_core_ume.h"
48 #include "pub_core_options.h"
49 #include "pub_core_syscall.h"
50 #include "pub_core_tooliface.h" /* VG_TRACK */
51 #include "pub_core_threadstate.h" /* ThreadArchState */
52 #include "priv_initimg_pathscan.h"
53 #include "pub_core_initimg.h" /* self */
55 /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
57 #define _FILE_OFFSET_BITS 64
58 /* This is for ELF types etc, and also the AT_ constants. */
60 /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
63 /*====================================================================*/
64 /*=== Loading the client ===*/
65 /*====================================================================*/
67 /* Load the client whose name is VG_(argv_the_exename). */
69 static void load_client ( /*OUT*/ExeInfo* info,
70 /*OUT*/Addr* client_ip,
71 /*OUT*/Addr* client_toc)
77 vg_assert( VG_(args_the_exename) != NULL);
78 exe_name = ML_(find_executable)( VG_(args_the_exename) );
81 VG_(printf)("valgrind: %s: command not found\n", VG_(args_the_exename));
82 VG_(exit)(127); // 127 is Posix NOTFOUND
85 VG_(memset)(info, 0, sizeof(*info));
86 ret = VG_(do_exec)(exe_name, info);
88 VG_(printf)("valgrind: could not execute '%s'\n", exe_name);
92 // The client was successfully loaded! Continue.
94 /* Get hold of a file descriptor which refers to the client
95 executable. This is needed for attaching to GDB. */
96 res = VG_(open)(exe_name, VKI_O_RDONLY, VKI_S_IRUSR);
98 VG_(cl_exec_fd) = sr_Res(res);
100 /* Copy necessary bits of 'info' that were filled in */
101 *client_ip = info->init_ip;
102 *client_toc = info->init_toc;
103 VG_(brk_base) = VG_(brk_limit) = VG_PGROUNDUP(info->brkbase);
107 /*====================================================================*/
108 /*=== Setting up the client's environment ===*/
109 /*====================================================================*/
111 /* Prepare the client's environment. This is basically a copy of our
114 LD_PRELOAD=$VALGRIND_LIB/vgpreload_core-PLATFORM.so:
115 ($VALGRIND_LIB/vgpreload_TOOL-PLATFORM.so:)?
118 If this is missing, then it is added.
120 Also, remove any binding for VALGRIND_LAUNCHER=. The client should
121 not be able to see this.
123 If this needs to handle any more variables it should be hacked
124 into something table driven. The copy is VG_(malloc)'d space.
126 static HChar** setup_client_env ( HChar** origenv, const HChar* toolname)
128 HChar* preload_core = "vgpreload_core";
129 HChar* ld_preload = "LD_PRELOAD=";
130 HChar* v_launcher = VALGRIND_LAUNCHER "=";
131 Int ld_preload_len = VG_(strlen)( ld_preload );
132 Int v_launcher_len = VG_(strlen)( v_launcher );
133 Bool ld_preload_done = False;
134 Int vglib_len = VG_(strlen)(VG_(libdir));
139 HChar* preload_tool_path;
142 /* Alloc space for the vgpreload_core.so path and vgpreload_<tool>.so
143 paths. We might not need the space for vgpreload_<tool>.so, but it
144 doesn't hurt to over-allocate briefly. The 16s are just cautious
146 Int preload_core_path_len = vglib_len + sizeof(preload_core)
147 + sizeof(VG_PLATFORM) + 16;
148 Int preload_tool_path_len = vglib_len + VG_(strlen)(toolname)
149 + sizeof(VG_PLATFORM) + 16;
150 Int preload_string_len = preload_core_path_len + preload_tool_path_len;
151 HChar* preload_string = VG_(malloc)("initimg-linux.sce.1",
155 vg_assert(preload_string);
157 /* Determine if there's a vgpreload_<tool>_<platform>.so file, and setup
159 preload_tool_path = VG_(malloc)("initimg-linux.sce.2", preload_tool_path_len);
160 vg_assert(preload_tool_path);
161 VG_(snprintf)(preload_tool_path, preload_tool_path_len,
162 "%s/vgpreload_%s-%s.so", VG_(libdir), toolname, VG_PLATFORM);
163 if (VG_(access)(preload_tool_path, True/*r*/, False/*w*/, False/*x*/) == 0) {
164 VG_(snprintf)(preload_string, preload_string_len, "%s/%s-%s.so:%s",
165 VG_(libdir), preload_core, VG_PLATFORM, preload_tool_path);
167 VG_(snprintf)(preload_string, preload_string_len, "%s/%s-%s.so",
168 VG_(libdir), preload_core, VG_PLATFORM);
170 VG_(free)(preload_tool_path);
172 VG_(debugLog)(2, "initimg", "preload_string:\n");
173 VG_(debugLog)(2, "initimg", " \"%s\"\n", preload_string);
175 /* Count the original size of the env */
176 if (debug) VG_(printf)("\n\n");
178 for (cpp = origenv; cpp && *cpp; cpp++) {
180 if (debug) VG_(printf)("XXXXXXXXX: BEFORE %s\n", *cpp);
183 /* Allocate a new space */
184 ret = VG_(malloc) ("initimg-linux.sce.3",
185 sizeof(HChar *) * (envc+1+1)); /* 1 new entry + NULL */
189 for (cpp = ret; *origenv; ) {
190 if (debug) VG_(printf)("XXXXXXXXX: COPY %s\n", *origenv);
195 vg_assert(envc == (cpp - ret));
197 /* Walk over the new environment, mashing as we go */
198 for (cpp = ret; cpp && *cpp; cpp++) {
199 if (VG_(memcmp)(*cpp, ld_preload, ld_preload_len) == 0) {
200 Int len = VG_(strlen)(*cpp) + preload_string_len;
201 HChar *cp = VG_(malloc)("initimg-linux.sce.4", len);
204 VG_(snprintf)(cp, len, "%s%s:%s",
205 ld_preload, preload_string, (*cpp)+ld_preload_len);
209 ld_preload_done = True;
211 if (debug) VG_(printf)("XXXXXXXXX: MASH %s\n", *cpp);
214 /* Add the missing bits */
215 if (!ld_preload_done) {
216 Int len = ld_preload_len + preload_string_len;
217 HChar *cp = VG_(malloc) ("initimg-linux.sce.5", len);
220 VG_(snprintf)(cp, len, "%s%s", ld_preload, preload_string);
223 if (debug) VG_(printf)("XXXXXXXXX: ADD %s\n", cp);
226 /* ret[0 .. envc-1] is live now. */
227 /* Find and remove a binding for VALGRIND_LAUNCHER. */
228 for (i = 0; i < envc; i++)
229 if (0 == VG_(memcmp(ret[i], v_launcher, v_launcher_len)))
233 for (; i < envc-1; i++)
238 VG_(free)(preload_string);
241 for (i = 0; i < envc; i++) {
242 if (debug) VG_(printf)("XXXXXXXXX: FINAL %s\n", ret[i]);
249 /*====================================================================*/
250 /*=== Setting up the client's stack ===*/
251 /*====================================================================*/
253 #ifndef AT_DCACHEBSIZE
254 #define AT_DCACHEBSIZE 19
255 #endif /* AT_DCACHEBSIZE */
257 #ifndef AT_ICACHEBSIZE
258 #define AT_ICACHEBSIZE 20
259 #endif /* AT_ICACHEBSIZE */
261 #ifndef AT_UCACHEBSIZE
262 #define AT_UCACHEBSIZE 21
263 #endif /* AT_UCACHEBSIZE */
265 #ifndef AT_BASE_PLATFORM
266 #define AT_BASE_PLATFORM 24
267 #endif /* AT_BASE_PLATFORM */
271 #endif /* AT_RANDOM */
275 #endif /* AT_EXECFN */
278 #define AT_SYSINFO 32
279 #endif /* AT_SYSINFO */
281 #ifndef AT_SYSINFO_EHDR
282 #define AT_SYSINFO_EHDR 33
283 #endif /* AT_SYSINFO_EHDR */
286 #define AT_SECURE 23 /* secure mode boolean */
287 #endif /* AT_SECURE */
289 /* Add a string onto the string table, and return its address */
290 static char *copy_str(char **tab, const char *str)
300 VG_(printf)("copied %p \"%s\" len %lld\n", orig, orig, (Long)(cp-orig));
308 /* ----------------------------------------------------------------
310 This sets up the client's initial stack, containing the args,
311 environment and aux vector.
313 The format of the stack is:
315 higher address +-----------------+ <- clstack_end
333 lower address +-----------------+ <- sp
337 Allocate and create the initial client stack. It is allocated down
338 from clstack_end, which was previously determined by the address
339 space manager. The returned value is the SP value for the client.
341 The client's auxv is created by copying and modifying our own one.
342 As a side effect of scanning our own auxv, some important bits of
345 VG_(cache_line_size_ppc32) // ppc32 only -- cache line size
346 VG_(have_altivec_ppc32) // ppc32 only -- is Altivec supported?
348 ---------------------------------------------------------------- */
360 struct auxv *find_auxv(UWord* sp)
362 sp++; // skip argc (Nb: is word-sized, not int-sized!)
364 while (*sp != 0) // skip argv
368 while (*sp != 0) // skip env
372 #if defined(VGA_ppc32) || defined(VGA_ppc64)
373 # if defined AT_IGNOREPPC
374 while (*sp == AT_IGNOREPPC) // skip AT_IGNOREPPC entries
379 return (struct auxv *)sp;
383 Addr setup_client_stack( void* init_sp,
388 SizeT clstack_max_size )
392 char *strtab; /* string table */
396 const struct auxv *orig_auxv;
397 const struct auxv *cauxv;
398 unsigned stringsize; /* total size of strings in bytes */
399 unsigned auxsize; /* total size of auxv in bytes */
400 Int argc; /* total argc */
401 Int envc; /* total number of env vars */
402 unsigned stacksize; /* total client stack size */
403 Addr client_SP; /* client stack base (initial SP) */
408 vg_assert(VG_IS_PAGE_ALIGNED(clstack_end+1));
409 vg_assert( VG_(args_for_client) );
411 /* use our own auxv as a prototype */
412 orig_auxv = find_auxv(init_sp);
414 /* ==================== compute sizes ==================== */
416 /* first of all, work out how big the client stack will be */
418 have_exename = VG_(args_the_exename) != NULL;
420 /* paste on the extra args if the loader needs them (ie, the #!
421 interpreter and its argument) */
423 if (info->interp_name != NULL) {
425 stringsize += VG_(strlen)(info->interp_name) + 1;
427 if (info->interp_args != NULL) {
429 stringsize += VG_(strlen)(info->interp_args) + 1;
432 /* now scan the args we're given... */
434 stringsize += VG_(strlen)( VG_(args_the_exename) ) + 1;
436 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
438 stringsize += VG_(strlen)( * (HChar**)
439 VG_(indexXA)( VG_(args_for_client), i ))
443 /* ...and the environment */
445 for (cpp = orig_envp; cpp && *cpp; cpp++) {
447 stringsize += VG_(strlen)(*cpp) + 1;
450 /* now, how big is the auxv? */
451 auxsize = sizeof(*auxv); /* there's always at least one entry: AT_NULL */
452 for (cauxv = orig_auxv; cauxv->a_type != AT_NULL; cauxv++) {
453 if (cauxv->a_type == AT_PLATFORM ||
454 cauxv->a_type == AT_BASE_PLATFORM)
455 stringsize += VG_(strlen)(cauxv->u.a_ptr) + 1;
456 else if (cauxv->a_type == AT_RANDOM)
458 else if (cauxv->a_type == AT_EXECFN)
459 stringsize += VG_(strlen)(VG_(args_the_exename)) + 1;
460 auxsize += sizeof(*cauxv);
463 # if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux)
464 auxsize += 2 * sizeof(*cauxv);
467 /* OK, now we know how big the client stack is */
469 sizeof(Word) + /* argc */
470 (have_exename ? sizeof(char **) : 0) + /* argc[0] == exename */
471 sizeof(char **)*argc + /* argv */
472 sizeof(char **) + /* terminal NULL */
473 sizeof(char **)*envc + /* envp */
474 sizeof(char **) + /* terminal NULL */
476 VG_ROUNDUP(stringsize, sizeof(Word)); /* strings (aligned) */
478 if (0) VG_(printf)("stacksize = %d\n", stacksize);
480 /* client_SP is the client's stack pointer */
481 client_SP = clstack_end - stacksize;
482 client_SP = VG_ROUNDDN(client_SP, 16); /* make stack 16 byte aligned */
484 /* base of the string table (aligned) */
485 stringbase = strtab = (char *)clstack_end
486 - VG_ROUNDUP(stringsize, sizeof(int));
488 clstack_start = VG_PGROUNDDN(client_SP);
490 /* The max stack size */
491 clstack_max_size = VG_PGROUNDUP(clstack_max_size);
493 /* Record stack extent -- needed for stack-change code. */
494 VG_(clstk_base) = clstack_start;
495 VG_(clstk_end) = clstack_end;
498 VG_(printf)("stringsize=%d auxsize=%d stacksize=%d maxsize=0x%x\n"
501 stringsize, auxsize, stacksize, (Int)clstack_max_size,
502 (void*)clstack_start, (void*)clstack_end);
504 /* ==================== allocate space ==================== */
506 { SizeT anon_size = clstack_end - clstack_start + 1;
507 SizeT resvn_size = clstack_max_size - anon_size;
508 Addr anon_start = clstack_start;
509 Addr resvn_start = anon_start - resvn_size;
510 SizeT inner_HACK = 0;
513 /* So far we've only accounted for space requirements down to the
514 stack pointer. If this target's ABI requires a redzone below
515 the stack pointer, we need to allocate an extra page, to
516 handle the worst case in which the stack pointer is almost at
517 the bottom of a page, and so there is insufficient room left
518 over to put the redzone in. In this case the simple thing to
519 do is allocate an extra page, by shrinking the reservation by
520 one page and growing the anonymous area by a corresponding
522 vg_assert(VG_STACK_REDZONE_SZB >= 0);
523 vg_assert(VG_STACK_REDZONE_SZB < VKI_PAGE_SIZE);
524 if (VG_STACK_REDZONE_SZB > 0) {
525 vg_assert(resvn_size > VKI_PAGE_SIZE);
526 resvn_size -= VKI_PAGE_SIZE;
527 anon_start -= VKI_PAGE_SIZE;
528 anon_size += VKI_PAGE_SIZE;
531 vg_assert(VG_IS_PAGE_ALIGNED(anon_size));
532 vg_assert(VG_IS_PAGE_ALIGNED(resvn_size));
533 vg_assert(VG_IS_PAGE_ALIGNED(anon_start));
534 vg_assert(VG_IS_PAGE_ALIGNED(resvn_start));
535 vg_assert(resvn_start == clstack_end + 1 - clstack_max_size);
538 inner_HACK = 1024*1024; // create 1M non-fault-extending stack
542 VG_(printf)("%#lx 0x%lx %#lx 0x%lx\n",
543 resvn_start, resvn_size, anon_start, anon_size);
545 /* Create a shrinkable reservation followed by an anonymous
546 segment. Together these constitute a growdown stack. */
547 res = VG_(mk_SysRes_Error)(0);
548 ok = VG_(am_create_reservation)(
550 resvn_size -inner_HACK,
552 anon_size +inner_HACK
555 /* allocate a stack - mmap enough space for the stack */
556 res = VG_(am_mmap_anon_fixed_client)(
557 anon_start -inner_HACK,
558 anon_size +inner_HACK,
559 VKI_PROT_READ|VKI_PROT_WRITE|VKI_PROT_EXEC
562 if ((!ok) || sr_isError(res)) {
563 /* Allocation of the stack failed. We have to stop. */
564 VG_(printf)("valgrind: "
565 "I failed to allocate space for the application's stack.\n");
566 VG_(printf)("valgrind: "
567 "This may be the result of a very large --main-stacksize=\n");
568 VG_(printf)("valgrind: setting. Cannot continue. Sorry.\n\n");
573 vg_assert(!sr_isError(res));
576 /* ==================== create client stack ==================== */
578 ptr = (Addr*)client_SP;
580 /* --- client argc --- */
581 *ptr++ = argc + (have_exename ? 1 : 0);
583 /* --- client argv --- */
584 if (info->interp_name) {
585 *ptr++ = (Addr)copy_str(&strtab, info->interp_name);
586 VG_(free)(info->interp_name);
588 if (info->interp_args) {
589 *ptr++ = (Addr)copy_str(&strtab, info->interp_args);
590 VG_(free)(info->interp_args);
594 *ptr++ = (Addr)copy_str(&strtab, VG_(args_the_exename));
596 for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
597 *ptr++ = (Addr)copy_str(
599 * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
605 VG_(client_envp) = (Char **)ptr;
606 for (cpp = orig_envp; cpp && *cpp; ptr++, cpp++)
607 *ptr = (Addr)copy_str(&strtab, *cpp);
611 auxv = (struct auxv *)ptr;
612 *client_auxv = (UInt *)auxv;
614 # if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux)
615 auxv[0].a_type = AT_IGNOREPPC;
616 auxv[0].u.a_val = AT_IGNOREPPC;
617 auxv[1].a_type = AT_IGNOREPPC;
618 auxv[1].u.a_val = AT_IGNOREPPC;
622 for (; orig_auxv->a_type != AT_NULL; auxv++, orig_auxv++) {
623 const NSegment *ehdrseg;
625 /* copy the entry... */
628 /* ...and fix up / examine the copy */
629 switch(auxv->a_type) {
642 /* All these are pointerless, so we don't need to do
643 anything about them. */
648 auxv->a_type = AT_IGNORE;
650 auxv->u.a_val = info->phdr;
655 auxv->a_type = AT_IGNORE;
657 auxv->u.a_val = info->phnum;
661 auxv->u.a_val = info->interp_base;
665 case AT_BASE_PLATFORM:
666 /* points to a platform description string */
667 auxv->u.a_ptr = copy_str(&strtab, orig_auxv->u.a_ptr);
671 auxv->u.a_val = info->entry;
680 # if defined(VGP_ppc32_linux)
681 /* acquire cache info */
682 if (auxv->u.a_val > 0) {
683 VG_(machine_ppc32_set_clszB)( auxv->u.a_val );
684 VG_(debugLog)(2, "initimg",
685 "PPC32 cache line size %u (type %u)\n",
686 (UInt)auxv->u.a_val, (UInt)auxv->a_type );
688 # elif defined(VGP_ppc64_linux)
689 /* acquire cache info */
690 if (auxv->u.a_val > 0) {
691 VG_(machine_ppc64_set_clszB)( auxv->u.a_val );
692 VG_(debugLog)(2, "initimg",
693 "PPC64 cache line size %u (type %u)\n",
694 (UInt)auxv->u.a_val, (UInt)auxv->a_type );
699 # if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux)
705 /* If this is 1, then it means that this program is
706 running suid, and therefore the dynamic linker should
707 be careful about LD_PRELOAD, etc. However, since
708 stage1 (the thing the kernel actually execve's) should
709 never be SUID, and we need LD_PRELOAD to work for the
710 client, we set AT_SECURE to 0. */
715 /* Trash this, because we don't reproduce it */
716 auxv->a_type = AT_IGNORE;
719 # if !defined(VGP_ppc32_linux) && !defined(VGP_ppc64_linux)
720 case AT_SYSINFO_EHDR:
721 /* Trash this, because we don't reproduce it */
722 ehdrseg = VG_(am_find_nsegment)((Addr)auxv->u.a_ptr);
724 VG_(am_munmap_valgrind)(ehdrseg->start, ehdrseg->end - ehdrseg->start);
725 auxv->a_type = AT_IGNORE;
730 /* points to 16 random bytes - we need to ensure this is
731 propagated to the client as glibc will assume it is
732 present if it is built for kernel 2.6.29 or later */
733 auxv->u.a_ptr = strtab;
734 VG_(memcpy)(strtab, orig_auxv->u.a_ptr, 16);
739 /* points to the executable filename */
740 auxv->u.a_ptr = copy_str(&strtab, VG_(args_the_exename));
744 /* stomp out anything we don't know about */
745 VG_(debugLog)(2, "initimg",
746 "stomping auxv entry %lld\n",
747 (ULong)auxv->a_type);
748 auxv->a_type = AT_IGNORE;
753 vg_assert(auxv->a_type == AT_NULL);
755 vg_assert((strtab-stringbase) == stringsize);
757 /* client_SP is pointing at client's argc/argv */
759 if (0) VG_(printf)("startup SP = %#lx\n", client_SP);
764 /* Allocate the client data segment. It is an expandable anonymous
765 mapping abutting a shrinkable reservation of size max_dseg_size.
766 The data segment starts at VG_(brk_base), which is page-aligned,
767 and runs up to VG_(brk_limit), which isn't. */
769 static void setup_client_dataseg ( SizeT max_size )
773 Addr anon_start = VG_(brk_base);
774 SizeT anon_size = VKI_PAGE_SIZE;
775 Addr resvn_start = anon_start + anon_size;
776 SizeT resvn_size = max_size - anon_size;
778 vg_assert(VG_IS_PAGE_ALIGNED(anon_size));
779 vg_assert(VG_IS_PAGE_ALIGNED(resvn_size));
780 vg_assert(VG_IS_PAGE_ALIGNED(anon_start));
781 vg_assert(VG_IS_PAGE_ALIGNED(resvn_start));
783 /* Because there's been no brk activity yet: */
784 vg_assert(VG_(brk_base) == VG_(brk_limit));
786 /* Try to create the data seg and associated reservation where
787 VG_(brk_base) says. */
788 ok = VG_(am_create_reservation)(
796 /* Hmm, that didn't work. Well, let aspacem suggest an address
797 it likes better, and try again with that. */
798 anon_start = VG_(am_get_advisory_client_simple)
799 ( 0/*floating*/, anon_size+resvn_size, &ok );
801 resvn_start = anon_start + anon_size;
802 ok = VG_(am_create_reservation)(
809 VG_(brk_base) = VG_(brk_limit) = anon_start;
811 /* that too might have failed, but if it has, we're hosed: there
816 /* We make the data segment (heap) executable because LinuxThreads on
817 ppc32 creates trampolines in this area. Also, on x86/Linux the data
818 segment is RWX natively, at least according to /proc/self/maps.
819 Also, having a non-executable data seg would kill any program which
820 tried to create code in the data seg and then run it. */
821 sres = VG_(am_mmap_anon_fixed_client)(
824 VKI_PROT_READ|VKI_PROT_WRITE|VKI_PROT_EXEC
826 vg_assert(!sr_isError(sres));
827 vg_assert(sr_Res(sres) == anon_start);
831 /*====================================================================*/
832 /*=== TOP-LEVEL: VG_(setup_client_initial_image) ===*/
833 /*====================================================================*/
835 /* Create the client's initial memory image. */
836 IIFinaliseImageInfo VG_(ii_create_image)( IICreateImageInfo iicii )
841 IIFinaliseImageInfo iifii;
842 VG_(memset)( &iifii, 0, sizeof(iifii) );
844 //--------------------------------------------------------------
845 // Load client executable, finding in $PATH if necessary
846 // p: get_helprequest_and_toolname() [for 'exec', 'need_help']
847 // p: layout_remaining_space [so there's space]
848 //--------------------------------------------------------------
849 VG_(debugLog)(1, "initimg", "Loading client\n");
851 if (VG_(args_the_exename) == NULL)
852 VG_(err_missing_prog)();
854 load_client(&info, &iifii.initial_client_IP, &iifii.initial_client_TOC);
856 //--------------------------------------------------------------
857 // Set up client's environment
858 // p: set-libdir [for VG_(libdir)]
859 // p: get_helprequest_and_toolname [for toolname]
860 //--------------------------------------------------------------
861 VG_(debugLog)(1, "initimg", "Setup client env\n");
862 env = setup_client_env(iicii.envp, iicii.toolname);
864 //--------------------------------------------------------------
865 // Setup client stack, eip, and VG_(client_arg[cv])
866 // p: load_client() [for 'info']
867 // p: fix_environment() [for 'env']
868 //--------------------------------------------------------------
870 /* When allocating space for the client stack on Linux, take
871 notice of the --main-stacksize value. This makes it possible
872 to run programs with very large (primary) stack requirements
873 simply by specifying --main-stacksize. */
874 /* Logic is as follows:
875 - by default, use the client's current stack rlimit
876 - if that exceeds 16M, clamp to 16M
877 - if a larger --main-stacksize value is specified, use that instead
878 - in all situations, the minimum allowed stack size is 1M
880 void* init_sp = iicii.argv - 1;
881 SizeT m1 = 1024 * 1024;
883 SizeT szB = (SizeT)VG_(client_rlimit_stack).rlim_cur;
884 if (szB < m1) szB = m1;
885 if (szB > m16) szB = m16;
886 if (VG_(clo_main_stacksize) > 0) szB = VG_(clo_main_stacksize);
887 if (szB < m1) szB = m1;
888 szB = VG_PGROUNDUP(szB);
889 VG_(debugLog)(1, "initimg",
890 "Setup client stack: size will be %ld\n", szB);
892 iifii.clstack_max_size = szB;
894 iifii.initial_client_SP
895 = setup_client_stack( init_sp, env,
896 &info, &iifii.client_auxv,
897 iicii.clstack_top, iifii.clstack_max_size );
901 VG_(debugLog)(2, "initimg",
903 "initial_IP=%p initial_TOC=%p brk_base=%p\n",
904 (void*)(iifii.initial_client_IP),
905 (void*)(iifii.initial_client_TOC),
906 (void*)VG_(brk_base) );
907 VG_(debugLog)(2, "initimg",
909 "initial_SP=%p max_stack_size=%ld\n",
910 (void*)(iifii.initial_client_SP),
911 (SizeT)iifii.clstack_max_size );
914 //--------------------------------------------------------------
915 // Setup client data (brk) segment. Initially a 1-page segment
916 // which abuts a shrinkable reservation.
917 // p: load_client() [for 'info' and hence VG_(brk_base)]
918 //--------------------------------------------------------------
920 SizeT m1 = 1024 * 1024;
922 SizeT dseg_max_size = (SizeT)VG_(client_rlimit_data).rlim_cur;
923 VG_(debugLog)(1, "initimg", "Setup client data (brk) segment\n");
924 if (dseg_max_size < m1) dseg_max_size = m1;
925 if (dseg_max_size > m8) dseg_max_size = m8;
926 dseg_max_size = VG_PGROUNDUP(dseg_max_size);
928 setup_client_dataseg( dseg_max_size );
935 /*====================================================================*/
936 /*=== TOP-LEVEL: VG_(finalise_thread1state) ===*/
937 /*====================================================================*/
939 /* Just before starting the client, we may need to make final
940 adjustments to its initial image. Also we need to set up the VEX
941 guest state for thread 1 (the root thread) and copy in essential
942 starting values. This is handed the IIFinaliseImageInfo created by
943 VG_(ii_create_image).
945 void VG_(ii_finalise_image)( IIFinaliseImageInfo iifii )
947 ThreadArchState* arch = &VG_(threads)[1].arch;
949 /* On Linux we get client_{ip/sp/toc}, and start the client with
950 all other registers zeroed. */
952 # if defined(VGP_x86_linux)
953 vg_assert(0 == sizeof(VexGuestX86State) % 16);
955 /* Zero out the initial state, and set up the simulated FPU in a
957 LibVEX_GuestX86_initialise(&arch->vex);
959 /* Zero out the shadow areas. */
960 VG_(memset)(&arch->vex_shadow1, 0, sizeof(VexGuestX86State));
961 VG_(memset)(&arch->vex_shadow2, 0, sizeof(VexGuestX86State));
963 /* Put essential stuff into the new state. */
964 arch->vex.guest_ESP = iifii.initial_client_SP;
965 arch->vex.guest_EIP = iifii.initial_client_IP;
967 /* initialise %cs, %ds and %ss to point at the operating systems
968 default code, data and stack segments */
969 asm volatile("movw %%cs, %0" : : "m" (arch->vex.guest_CS));
970 asm volatile("movw %%ds, %0" : : "m" (arch->vex.guest_DS));
971 asm volatile("movw %%ss, %0" : : "m" (arch->vex.guest_SS));
973 # elif defined(VGP_amd64_linux)
974 vg_assert(0 == sizeof(VexGuestAMD64State) % 16);
976 /* Zero out the initial state, and set up the simulated FPU in a
978 LibVEX_GuestAMD64_initialise(&arch->vex);
980 /* Zero out the shadow areas. */
981 VG_(memset)(&arch->vex_shadow1, 0, sizeof(VexGuestAMD64State));
982 VG_(memset)(&arch->vex_shadow2, 0, sizeof(VexGuestAMD64State));
984 /* Put essential stuff into the new state. */
985 arch->vex.guest_RSP = iifii.initial_client_SP;
986 arch->vex.guest_RIP = iifii.initial_client_IP;
988 # elif defined(VGP_ppc32_linux)
989 vg_assert(0 == sizeof(VexGuestPPC32State) % 16);
991 /* Zero out the initial state, and set up the simulated FPU in a
993 LibVEX_GuestPPC32_initialise(&arch->vex);
995 /* Zero out the shadow areas. */
996 VG_(memset)(&arch->vex_shadow1, 0, sizeof(VexGuestPPC32State));
997 VG_(memset)(&arch->vex_shadow2, 0, sizeof(VexGuestPPC32State));
999 /* Put essential stuff into the new state. */
1000 arch->vex.guest_GPR1 = iifii.initial_client_SP;
1001 arch->vex.guest_CIA = iifii.initial_client_IP;
1003 # elif defined(VGP_ppc64_linux)
1004 vg_assert(0 == sizeof(VexGuestPPC64State) % 16);
1006 /* Zero out the initial state, and set up the simulated FPU in a
1008 LibVEX_GuestPPC64_initialise(&arch->vex);
1010 /* Zero out the shadow areas. */
1011 VG_(memset)(&arch->vex_shadow1, 0, sizeof(VexGuestPPC64State));
1012 VG_(memset)(&arch->vex_shadow2, 0, sizeof(VexGuestPPC64State));
1014 /* Put essential stuff into the new state. */
1015 arch->vex.guest_GPR1 = iifii.initial_client_SP;
1016 arch->vex.guest_GPR2 = iifii.initial_client_TOC;
1017 arch->vex.guest_CIA = iifii.initial_client_IP;
1019 # elif defined(VGP_arm_linux)
1020 /* Zero out the initial state, and set up the simulated FPU in a
1022 LibVEX_GuestARM_initialise(&arch->vex);
1024 /* Zero out the shadow areas. */
1025 VG_(memset)(&arch->vex_shadow1, 0, sizeof(VexGuestARMState));
1026 VG_(memset)(&arch->vex_shadow2, 0, sizeof(VexGuestARMState));
1028 arch->vex.guest_R13 = iifii.initial_client_SP;
1029 arch->vex.guest_R15 = iifii.initial_client_IP;
1031 /* This is just EABI stuff. */
1032 // FIXME jrs: what's this for?
1033 arch->vex.guest_R1 = iifii.initial_client_SP;
1036 # error Unknown platform
1039 /* Tell the tool that we just wrote to the registers. */
1040 VG_TRACK( post_reg_write, Vg_CoreStartup, /*tid*/1, /*offset*/0,
1041 sizeof(VexGuestArchState));
1044 #endif // defined(VGO_linux)
1046 /*--------------------------------------------------------------------*/
1048 /*--------------------------------------------------------------------*/