]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/valgrind/src/valgrind-3.6.0-svn/coregrind/m_initimg/initimg-linux.c
115d4a40ab4947f71f5c875357400125d76ed4d4
[l4.git] / l4 / pkg / valgrind / src / valgrind-3.6.0-svn / coregrind / m_initimg / initimg-linux.c
1
2 /*--------------------------------------------------------------------*/
3 /*--- Startup: create initial process image on Linux               ---*/
4 /*---                                              initimg-linux.c ---*/
5 /*--------------------------------------------------------------------*/
6
7 /*
8    This file is part of Valgrind, a dynamic binary instrumentation
9    framework.
10
11    Copyright (C) 2000-2010 Julian Seward
12       jseward@acm.org
13
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.
18
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.
23
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
27    02111-1307, USA.
28
29    The GNU General Public License is contained in the file COPYING.
30 */
31
32 #if defined(VGO_linux)
33
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 */
54
55 /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */
56 #define _GNU_SOURCE
57 #define _FILE_OFFSET_BITS 64
58 /* This is for ELF types etc, and also the AT_ constants. */
59 #include <elf.h>
60 /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */
61
62
63 /*====================================================================*/
64 /*=== Loading the client                                           ===*/
65 /*====================================================================*/
66
67 /* Load the client whose name is VG_(argv_the_exename). */
68
69 static void load_client ( /*OUT*/ExeInfo* info, 
70                           /*OUT*/Addr*    client_ip,
71                           /*OUT*/Addr*    client_toc)
72 {
73    HChar* exe_name;
74    Int    ret;
75    SysRes res;
76
77    vg_assert( VG_(args_the_exename) != NULL);
78    exe_name = ML_(find_executable)( VG_(args_the_exename) );
79
80    if (!exe_name) {
81       VG_(printf)("valgrind: %s: command not found\n", VG_(args_the_exename));
82       VG_(exit)(127);      // 127 is Posix NOTFOUND
83    }
84
85    VG_(memset)(info, 0, sizeof(*info));
86    ret = VG_(do_exec)(exe_name, info);
87    if (ret < 0) {
88       VG_(printf)("valgrind: could not execute '%s'\n", exe_name);
89       VG_(exit)(1);
90    }
91
92    // The client was successfully loaded!  Continue.
93
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);
97    if (!sr_isError(res))
98       VG_(cl_exec_fd) = sr_Res(res);
99
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);
104 }
105
106
107 /*====================================================================*/
108 /*=== Setting up the client's environment                          ===*/
109 /*====================================================================*/
110
111 /* Prepare the client's environment.  This is basically a copy of our
112    environment, except:
113
114      LD_PRELOAD=$VALGRIND_LIB/vgpreload_core-PLATFORM.so:
115                 ($VALGRIND_LIB/vgpreload_TOOL-PLATFORM.so:)?
116                 $LD_PRELOAD
117
118    If this is missing, then it is added.
119
120    Also, remove any binding for VALGRIND_LAUNCHER=.  The client should
121    not be able to see this.
122
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.
125 */
126 static HChar** setup_client_env ( HChar** origenv, const HChar* toolname)
127 {
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));
135    Bool   debug           = False;
136
137    HChar** cpp;
138    HChar** ret;
139    HChar*  preload_tool_path;
140    Int     envc, i;
141
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
145       slop. */
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",
152                                            preload_string_len);
153    vg_assert(origenv);
154    vg_assert(toolname);
155    vg_assert(preload_string);
156
157    /* Determine if there's a vgpreload_<tool>_<platform>.so file, and setup
158       preload_string. */
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);
166    } else {
167       VG_(snprintf)(preload_string, preload_string_len, "%s/%s-%s.so", 
168                     VG_(libdir), preload_core, VG_PLATFORM);
169    }
170    VG_(free)(preload_tool_path);
171
172    VG_(debugLog)(2, "initimg", "preload_string:\n");
173    VG_(debugLog)(2, "initimg", "  \"%s\"\n", preload_string);
174
175    /* Count the original size of the env */
176    if (debug) VG_(printf)("\n\n");
177    envc = 0;
178    for (cpp = origenv; cpp && *cpp; cpp++) {
179       envc++;
180       if (debug) VG_(printf)("XXXXXXXXX: BEFORE %s\n", *cpp);
181    }
182
183    /* Allocate a new space */
184    ret = VG_(malloc) ("initimg-linux.sce.3",
185                       sizeof(HChar *) * (envc+1+1)); /* 1 new entry + NULL */
186    vg_assert(ret);
187
188    /* copy it over */
189    for (cpp = ret; *origenv; ) {
190       if (debug) VG_(printf)("XXXXXXXXX: COPY   %s\n", *origenv);
191       *cpp++ = *origenv++;
192    }
193    *cpp = NULL;
194    
195    vg_assert(envc == (cpp - ret));
196
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);
202          vg_assert(cp);
203
204          VG_(snprintf)(cp, len, "%s%s:%s",
205                        ld_preload, preload_string, (*cpp)+ld_preload_len);
206
207          *cpp = cp;
208
209          ld_preload_done = True;
210       }
211       if (debug) VG_(printf)("XXXXXXXXX: MASH   %s\n", *cpp);
212    }
213
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);
218       vg_assert(cp);
219
220       VG_(snprintf)(cp, len, "%s%s", ld_preload, preload_string);
221
222       ret[envc++] = cp;
223       if (debug) VG_(printf)("XXXXXXXXX: ADD    %s\n", cp);
224    }
225
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)))
230          break;
231
232    if (i < envc) {
233       for (; i < envc-1; i++)
234          ret[i] = ret[i+1];
235       envc--;
236    }
237
238    VG_(free)(preload_string);
239    ret[envc] = NULL;
240
241    for (i = 0; i < envc; i++) {
242       if (debug) VG_(printf)("XXXXXXXXX: FINAL  %s\n", ret[i]);
243    }
244
245    return ret;
246 }
247
248
249 /*====================================================================*/
250 /*=== Setting up the client's stack                                ===*/
251 /*====================================================================*/
252
253 #ifndef AT_DCACHEBSIZE
254 #define AT_DCACHEBSIZE          19
255 #endif /* AT_DCACHEBSIZE */
256
257 #ifndef AT_ICACHEBSIZE
258 #define AT_ICACHEBSIZE          20
259 #endif /* AT_ICACHEBSIZE */
260
261 #ifndef AT_UCACHEBSIZE
262 #define AT_UCACHEBSIZE          21
263 #endif /* AT_UCACHEBSIZE */
264
265 #ifndef AT_BASE_PLATFORM
266 #define AT_BASE_PLATFORM        24
267 #endif /* AT_BASE_PLATFORM */
268
269 #ifndef AT_RANDOM
270 #define AT_RANDOM               25
271 #endif /* AT_RANDOM */
272
273 #ifndef AT_EXECFN
274 #define AT_EXECFN               31
275 #endif /* AT_EXECFN */
276
277 #ifndef AT_SYSINFO
278 #define AT_SYSINFO              32
279 #endif /* AT_SYSINFO */
280
281 #ifndef AT_SYSINFO_EHDR
282 #define AT_SYSINFO_EHDR         33
283 #endif /* AT_SYSINFO_EHDR */
284
285 #ifndef AT_SECURE
286 #define AT_SECURE 23   /* secure mode boolean */
287 #endif  /* AT_SECURE */
288
289 /* Add a string onto the string table, and return its address */
290 static char *copy_str(char **tab, const char *str)
291 {
292    char *cp = *tab;
293    char *orig = cp;
294
295    while(*str)
296       *cp++ = *str++;
297    *cp++ = '\0';
298
299    if (0)
300       VG_(printf)("copied %p \"%s\" len %lld\n", orig, orig, (Long)(cp-orig));
301
302    *tab = cp;
303
304    return orig;
305 }
306
307
308 /* ----------------------------------------------------------------
309  
310    This sets up the client's initial stack, containing the args,
311    environment and aux vector.
312
313    The format of the stack is:
314
315    higher address +-----------------+ <- clstack_end
316                   |                 |
317                   : string table    :
318                   |                 |
319                   +-----------------+
320                   | AT_NULL         |
321                   -                 -
322                   | auxv            |
323                   +-----------------+
324                   | NULL            |
325                   -                 -
326                   | envp            |
327                   +-----------------+
328                   | NULL            |
329                   -                 -
330                   | argv            |
331                   +-----------------+
332                   | argc            |
333    lower address  +-----------------+ <- sp
334                   | undefined       |
335                   :                 :
336
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.
340
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
343    info are collected:
344
345       VG_(cache_line_size_ppc32) // ppc32 only -- cache line size
346       VG_(have_altivec_ppc32)    // ppc32 only -- is Altivec supported?
347
348    ---------------------------------------------------------------- */
349
350 struct auxv
351 {
352    Word a_type;
353    union {
354       void *a_ptr;
355       Word a_val;
356    } u;
357 };
358
359 static
360 struct auxv *find_auxv(UWord* sp)
361 {
362    sp++;                // skip argc (Nb: is word-sized, not int-sized!)
363
364    while (*sp != 0)     // skip argv
365       sp++;
366    sp++;
367
368    while (*sp != 0)     // skip env
369       sp++;
370    sp++;
371    
372 #if defined(VGA_ppc32) || defined(VGA_ppc64)
373 # if defined AT_IGNOREPPC
374    while (*sp == AT_IGNOREPPC)        // skip AT_IGNOREPPC entries
375       sp += 2;
376 # endif
377 #endif
378
379    return (struct auxv *)sp;
380 }
381
382 static 
383 Addr setup_client_stack( void*  init_sp,
384                          char** orig_envp, 
385                          const ExeInfo* info,
386                          UInt** client_auxv,
387                          Addr   clstack_end,
388                          SizeT  clstack_max_size )
389 {
390    SysRes res;
391    char **cpp;
392    char *strtab;                /* string table */
393    char *stringbase;
394    Addr *ptr;
395    struct auxv *auxv;
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) */
404    Addr clstack_start;
405    Int i;
406    Bool have_exename;
407
408    vg_assert(VG_IS_PAGE_ALIGNED(clstack_end+1));
409    vg_assert( VG_(args_for_client) );
410
411    /* use our own auxv as a prototype */
412    orig_auxv = find_auxv(init_sp);
413
414    /* ==================== compute sizes ==================== */
415
416    /* first of all, work out how big the client stack will be */
417    stringsize   = 0;
418    have_exename = VG_(args_the_exename) != NULL;
419
420    /* paste on the extra args if the loader needs them (ie, the #! 
421       interpreter and its argument) */
422    argc = 0;
423    if (info->interp_name != NULL) {
424       argc++;
425       stringsize += VG_(strlen)(info->interp_name) + 1;
426    }
427    if (info->interp_args != NULL) {
428       argc++;
429       stringsize += VG_(strlen)(info->interp_args) + 1;
430    }
431
432    /* now scan the args we're given... */
433    if (have_exename)
434       stringsize += VG_(strlen)( VG_(args_the_exename) ) + 1;
435
436    for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
437       argc++;
438       stringsize += VG_(strlen)( * (HChar**) 
439                                    VG_(indexXA)( VG_(args_for_client), i ))
440                     + 1;
441    }
442
443    /* ...and the environment */
444    envc = 0;
445    for (cpp = orig_envp; cpp && *cpp; cpp++) {
446       envc++;
447       stringsize += VG_(strlen)(*cpp) + 1;
448    }
449
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)
457          stringsize += 16;
458       else if (cauxv->a_type == AT_EXECFN)
459          stringsize += VG_(strlen)(VG_(args_the_exename)) + 1;
460       auxsize += sizeof(*cauxv);
461    }
462
463 #  if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux)
464    auxsize += 2 * sizeof(*cauxv);
465 #  endif
466
467    /* OK, now we know how big the client stack is */
468    stacksize =
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 */
475       auxsize +                               /* auxv */
476       VG_ROUNDUP(stringsize, sizeof(Word));   /* strings (aligned) */
477
478    if (0) VG_(printf)("stacksize = %d\n", stacksize);
479
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 */
483
484    /* base of the string table (aligned) */
485    stringbase = strtab = (char *)clstack_end 
486                          - VG_ROUNDUP(stringsize, sizeof(int));
487
488    clstack_start = VG_PGROUNDDN(client_SP);
489
490    /* The max stack size */
491    clstack_max_size = VG_PGROUNDUP(clstack_max_size);
492
493    /* Record stack extent -- needed for stack-change code. */
494    VG_(clstk_base) = clstack_start;
495    VG_(clstk_end)  = clstack_end;
496
497    if (0)
498       VG_(printf)("stringsize=%d auxsize=%d stacksize=%d maxsize=0x%x\n"
499                   "clstack_start %p\n"
500                   "clstack_end   %p\n",
501                   stringsize, auxsize, stacksize, (Int)clstack_max_size,
502                   (void*)clstack_start, (void*)clstack_end);
503
504    /* ==================== allocate space ==================== */
505
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;
511      Bool  ok;
512
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
521         page. */
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;
529      }
530
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);
536
537 #    ifdef ENABLE_INNER
538      inner_HACK = 1024*1024; // create 1M non-fault-extending stack
539 #    endif
540
541      if (0)
542         VG_(printf)("%#lx 0x%lx  %#lx 0x%lx\n",
543                     resvn_start, resvn_size, anon_start, anon_size);
544
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)(
549              resvn_start,
550              resvn_size -inner_HACK,
551              SmUpper, 
552              anon_size +inner_HACK
553           );
554      if (ok) {
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
560               );
561      }
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");
569         VG_(exit)(0);
570      }
571
572      vg_assert(ok);
573      vg_assert(!sr_isError(res)); 
574    }
575
576    /* ==================== create client stack ==================== */
577
578    ptr = (Addr*)client_SP;
579
580    /* --- client argc --- */
581    *ptr++ = argc + (have_exename ? 1 : 0);
582
583    /* --- client argv --- */
584    if (info->interp_name) {
585       *ptr++ = (Addr)copy_str(&strtab, info->interp_name);
586       VG_(free)(info->interp_name);
587    }
588    if (info->interp_args) {
589       *ptr++ = (Addr)copy_str(&strtab, info->interp_args);
590       VG_(free)(info->interp_args);
591    }
592
593    if (have_exename)
594       *ptr++ = (Addr)copy_str(&strtab, VG_(args_the_exename));
595
596    for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
597       *ptr++ = (Addr)copy_str(
598                        &strtab, 
599                        * (HChar**) VG_(indexXA)( VG_(args_for_client), i )
600                      );
601    }
602    *ptr++ = 0;
603
604    /* --- envp --- */
605    VG_(client_envp) = (Char **)ptr;
606    for (cpp = orig_envp; cpp && *cpp; ptr++, cpp++)
607       *ptr = (Addr)copy_str(&strtab, *cpp);
608    *ptr++ = 0;
609
610    /* --- auxv --- */
611    auxv = (struct auxv *)ptr;
612    *client_auxv = (UInt *)auxv;
613
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;
619    auxv += 2;
620 #  endif
621
622    for (; orig_auxv->a_type != AT_NULL; auxv++, orig_auxv++) {
623       const NSegment *ehdrseg;
624
625       /* copy the entry... */
626       *auxv = *orig_auxv;
627
628       /* ...and fix up / examine the copy */
629       switch(auxv->a_type) {
630
631          case AT_IGNORE:
632          case AT_PHENT:
633          case AT_PAGESZ:
634          case AT_FLAGS:
635          case AT_NOTELF:
636          case AT_UID:
637          case AT_EUID:
638          case AT_GID:
639          case AT_EGID:
640          case AT_CLKTCK:
641          case AT_FPUCW:
642             /* All these are pointerless, so we don't need to do
643                anything about them. */
644             break;
645
646          case AT_PHDR:
647             if (info->phdr == 0)
648                auxv->a_type = AT_IGNORE;
649             else
650                auxv->u.a_val = info->phdr;
651             break;
652
653          case AT_PHNUM:
654             if (info->phdr == 0)
655                auxv->a_type = AT_IGNORE;
656             else
657                auxv->u.a_val = info->phnum;
658             break;
659
660          case AT_BASE:
661             auxv->u.a_val = info->interp_base;
662             break;
663
664          case AT_PLATFORM:
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);
668             break;
669
670          case AT_ENTRY:
671             auxv->u.a_val = info->entry;
672             break;
673
674          case AT_HWCAP:
675             break;
676
677          case AT_DCACHEBSIZE:
678          case AT_ICACHEBSIZE:
679          case AT_UCACHEBSIZE:
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 );
687             }
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 );
695             }
696 #           endif
697             break;
698
699 #        if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux)
700          case AT_IGNOREPPC:
701             break;
702 #        endif
703
704          case AT_SECURE:
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. */
711             auxv->u.a_val = 0;
712             break;
713
714          case AT_SYSINFO:
715             /* Trash this, because we don't reproduce it */
716             auxv->a_type = AT_IGNORE;
717             break;
718
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);
723             vg_assert(ehdrseg);
724             VG_(am_munmap_valgrind)(ehdrseg->start, ehdrseg->end - ehdrseg->start);
725             auxv->a_type = AT_IGNORE;
726             break;
727 #        endif
728
729          case AT_RANDOM:
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);
735             strtab += 16;
736             break;
737
738          case AT_EXECFN:
739             /* points to the executable filename */
740             auxv->u.a_ptr = copy_str(&strtab, VG_(args_the_exename));
741             break;
742
743          default:
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;
749             break;
750       }
751    }
752    *auxv = *orig_auxv;
753    vg_assert(auxv->a_type == AT_NULL);
754
755    vg_assert((strtab-stringbase) == stringsize);
756
757    /* client_SP is pointing at client's argc/argv */
758
759    if (0) VG_(printf)("startup SP = %#lx\n", client_SP);
760    return client_SP;
761 }
762
763
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. */
768
769 static void setup_client_dataseg ( SizeT max_size )
770 {
771    Bool   ok;
772    SysRes sres;
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;
777
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));
782
783    /* Because there's been no brk activity yet: */
784    vg_assert(VG_(brk_base) == VG_(brk_limit));
785
786    /* Try to create the data seg and associated reservation where
787       VG_(brk_base) says. */
788    ok = VG_(am_create_reservation)( 
789            resvn_start, 
790            resvn_size, 
791            SmLower, 
792            anon_size
793         );
794
795    if (!ok) {
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 );
800       if (ok) {
801          resvn_start = anon_start + anon_size;
802          ok = VG_(am_create_reservation)( 
803                  resvn_start, 
804                  resvn_size, 
805                  SmLower, 
806                  anon_size
807               );
808          if (ok)
809             VG_(brk_base) = VG_(brk_limit) = anon_start;
810       }
811       /* that too might have failed, but if it has, we're hosed: there
812          is no Plan C. */
813    }
814    vg_assert(ok);
815
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)( 
822              anon_start, 
823              anon_size, 
824              VKI_PROT_READ|VKI_PROT_WRITE|VKI_PROT_EXEC
825           );
826    vg_assert(!sr_isError(sres));
827    vg_assert(sr_Res(sres) == anon_start);
828 }
829
830
831 /*====================================================================*/
832 /*=== TOP-LEVEL: VG_(setup_client_initial_image)                   ===*/
833 /*====================================================================*/
834
835 /* Create the client's initial memory image. */
836 IIFinaliseImageInfo VG_(ii_create_image)( IICreateImageInfo iicii )
837 {
838    ExeInfo info;
839    HChar** env = NULL;
840
841    IIFinaliseImageInfo iifii;
842    VG_(memset)( &iifii, 0, sizeof(iifii) );
843
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");
850
851    if (VG_(args_the_exename) == NULL)
852       VG_(err_missing_prog)();
853
854    load_client(&info, &iifii.initial_client_IP, &iifii.initial_client_TOC);
855
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);
863
864    //--------------------------------------------------------------
865    // Setup client stack, eip, and VG_(client_arg[cv])
866    //   p: load_client()     [for 'info']
867    //   p: fix_environment() [for 'env']
868    //--------------------------------------------------------------
869    {
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
879       */
880       void* init_sp = iicii.argv - 1;
881       SizeT m1  = 1024 * 1024;
882       SizeT m16 = 16 * m1;
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);
891
892       iifii.clstack_max_size = szB;
893
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 );
898
899       VG_(free)(env);
900
901       VG_(debugLog)(2, "initimg",
902                        "Client info: "
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",
908                        "Client info: "
909                        "initial_SP=%p max_stack_size=%ld\n",
910                        (void*)(iifii.initial_client_SP),
911                        (SizeT)iifii.clstack_max_size );
912    }
913
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    //--------------------------------------------------------------
919    { 
920       SizeT m1 = 1024 * 1024;
921       SizeT m8 = 8 * m1;
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);
927
928       setup_client_dataseg( dseg_max_size );
929    }
930
931    return iifii;
932 }
933
934
935 /*====================================================================*/
936 /*=== TOP-LEVEL: VG_(finalise_thread1state)                        ===*/
937 /*====================================================================*/
938
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).
944 */
945 void VG_(ii_finalise_image)( IIFinaliseImageInfo iifii )
946 {
947    ThreadArchState* arch = &VG_(threads)[1].arch;
948
949    /* On Linux we get client_{ip/sp/toc}, and start the client with
950       all other registers zeroed. */
951
952 #  if defined(VGP_x86_linux)
953    vg_assert(0 == sizeof(VexGuestX86State) % 16);
954
955    /* Zero out the initial state, and set up the simulated FPU in a
956       sane way. */
957    LibVEX_GuestX86_initialise(&arch->vex);
958
959    /* Zero out the shadow areas. */
960    VG_(memset)(&arch->vex_shadow1, 0, sizeof(VexGuestX86State));
961    VG_(memset)(&arch->vex_shadow2, 0, sizeof(VexGuestX86State));
962
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;
966
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));
972
973 #  elif defined(VGP_amd64_linux)
974    vg_assert(0 == sizeof(VexGuestAMD64State) % 16);
975
976    /* Zero out the initial state, and set up the simulated FPU in a
977       sane way. */
978    LibVEX_GuestAMD64_initialise(&arch->vex);
979
980    /* Zero out the shadow areas. */
981    VG_(memset)(&arch->vex_shadow1, 0, sizeof(VexGuestAMD64State));
982    VG_(memset)(&arch->vex_shadow2, 0, sizeof(VexGuestAMD64State));
983
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;
987
988 #  elif defined(VGP_ppc32_linux)
989    vg_assert(0 == sizeof(VexGuestPPC32State) % 16);
990
991    /* Zero out the initial state, and set up the simulated FPU in a
992       sane way. */
993    LibVEX_GuestPPC32_initialise(&arch->vex);
994
995    /* Zero out the shadow areas. */
996    VG_(memset)(&arch->vex_shadow1, 0, sizeof(VexGuestPPC32State));
997    VG_(memset)(&arch->vex_shadow2, 0, sizeof(VexGuestPPC32State));
998
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;
1002
1003 #  elif defined(VGP_ppc64_linux)
1004    vg_assert(0 == sizeof(VexGuestPPC64State) % 16);
1005
1006    /* Zero out the initial state, and set up the simulated FPU in a
1007       sane way. */
1008    LibVEX_GuestPPC64_initialise(&arch->vex);
1009
1010    /* Zero out the shadow areas. */
1011    VG_(memset)(&arch->vex_shadow1, 0, sizeof(VexGuestPPC64State));
1012    VG_(memset)(&arch->vex_shadow2, 0, sizeof(VexGuestPPC64State));
1013
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;
1018
1019 #   elif defined(VGP_arm_linux)
1020    /* Zero out the initial state, and set up the simulated FPU in a
1021       sane way. */
1022    LibVEX_GuestARM_initialise(&arch->vex);
1023
1024    /* Zero out the shadow areas. */
1025    VG_(memset)(&arch->vex_shadow1, 0, sizeof(VexGuestARMState));
1026    VG_(memset)(&arch->vex_shadow2, 0, sizeof(VexGuestARMState));
1027
1028    arch->vex.guest_R13 = iifii.initial_client_SP;
1029    arch->vex.guest_R15 = iifii.initial_client_IP;
1030
1031    /* This is just EABI stuff. */
1032    // FIXME jrs: what's this for?
1033    arch->vex.guest_R1 =  iifii.initial_client_SP;
1034
1035 #  else
1036 #    error Unknown platform
1037 #  endif
1038
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));
1042 }
1043
1044 #endif // defined(VGO_linux)
1045
1046 /*--------------------------------------------------------------------*/
1047 /*---                                                              ---*/
1048 /*--------------------------------------------------------------------*/