Statistics
| Branch: | Revision:

root / linux-user / elfload.c @ cf129f3a

History | View | Annotate | Download (80.4 kB)

1
/* This is the Linux kernel elf-loading code, ported into user space */
2
#include <sys/time.h>
3
#include <sys/param.h>
4

    
5
#include <stdio.h>
6
#include <sys/types.h>
7
#include <fcntl.h>
8
#include <errno.h>
9
#include <unistd.h>
10
#include <sys/mman.h>
11
#include <sys/resource.h>
12
#include <stdlib.h>
13
#include <string.h>
14
#include <time.h>
15

    
16
#include "qemu.h"
17
#include "disas.h"
18

    
19
#ifdef _ARCH_PPC64
20
#undef ARCH_DLINFO
21
#undef ELF_PLATFORM
22
#undef ELF_HWCAP
23
#undef ELF_CLASS
24
#undef ELF_DATA
25
#undef ELF_ARCH
26
#endif
27

    
28
#define ELF_OSABI   ELFOSABI_SYSV
29

    
30
/* from personality.h */
31

    
32
/*
33
 * Flags for bug emulation.
34
 *
35
 * These occupy the top three bytes.
36
 */
37
enum {
38
        ADDR_NO_RANDOMIZE =         0x0040000,        /* disable randomization of VA space */
39
        FDPIC_FUNCPTRS =        0x0080000,        /* userspace function ptrs point to descriptors
40
                                                 * (signal handling)
41
                                                 */
42
        MMAP_PAGE_ZERO =        0x0100000,
43
        ADDR_COMPAT_LAYOUT =        0x0200000,
44
        READ_IMPLIES_EXEC =        0x0400000,
45
        ADDR_LIMIT_32BIT =        0x0800000,
46
        SHORT_INODE =                0x1000000,
47
        WHOLE_SECONDS =                0x2000000,
48
        STICKY_TIMEOUTS        =        0x4000000,
49
        ADDR_LIMIT_3GB =         0x8000000,
50
};
51

    
52
/*
53
 * Personality types.
54
 *
55
 * These go in the low byte.  Avoid using the top bit, it will
56
 * conflict with error returns.
57
 */
58
enum {
59
        PER_LINUX =                0x0000,
60
        PER_LINUX_32BIT =        0x0000 | ADDR_LIMIT_32BIT,
61
        PER_LINUX_FDPIC =        0x0000 | FDPIC_FUNCPTRS,
62
        PER_SVR4 =                0x0001 | STICKY_TIMEOUTS | MMAP_PAGE_ZERO,
63
        PER_SVR3 =                0x0002 | STICKY_TIMEOUTS | SHORT_INODE,
64
        PER_SCOSVR3 =                0x0003 | STICKY_TIMEOUTS |
65
                                         WHOLE_SECONDS | SHORT_INODE,
66
        PER_OSR5 =                0x0003 | STICKY_TIMEOUTS | WHOLE_SECONDS,
67
        PER_WYSEV386 =                0x0004 | STICKY_TIMEOUTS | SHORT_INODE,
68
        PER_ISCR4 =                0x0005 | STICKY_TIMEOUTS,
69
        PER_BSD =                0x0006,
70
        PER_SUNOS =                0x0006 | STICKY_TIMEOUTS,
71
        PER_XENIX =                0x0007 | STICKY_TIMEOUTS | SHORT_INODE,
72
        PER_LINUX32 =                0x0008,
73
        PER_LINUX32_3GB =        0x0008 | ADDR_LIMIT_3GB,
74
        PER_IRIX32 =                0x0009 | STICKY_TIMEOUTS,/* IRIX5 32-bit */
75
        PER_IRIXN32 =                0x000a | STICKY_TIMEOUTS,/* IRIX6 new 32-bit */
76
        PER_IRIX64 =                0x000b | STICKY_TIMEOUTS,/* IRIX6 64-bit */
77
        PER_RISCOS =                0x000c,
78
        PER_SOLARIS =                0x000d | STICKY_TIMEOUTS,
79
        PER_UW7 =                0x000e | STICKY_TIMEOUTS | MMAP_PAGE_ZERO,
80
        PER_OSF4 =                0x000f,                         /* OSF/1 v4 */
81
        PER_HPUX =                0x0010,
82
        PER_MASK =                0x00ff,
83
};
84

    
85
/*
86
 * Return the base personality without flags.
87
 */
88
#define personality(pers)        (pers & PER_MASK)
89

    
90
/* this flag is uneffective under linux too, should be deleted */
91
#ifndef MAP_DENYWRITE
92
#define MAP_DENYWRITE 0
93
#endif
94

    
95
/* should probably go in elf.h */
96
#ifndef ELIBBAD
97
#define ELIBBAD 80
98
#endif
99

    
100
typedef target_ulong        target_elf_greg_t;
101
#ifdef USE_UID16
102
typedef uint16_t        target_uid_t;
103
typedef uint16_t        target_gid_t;
104
#else
105
typedef uint32_t        target_uid_t;
106
typedef uint32_t        target_gid_t;
107
#endif
108
typedef int32_t                target_pid_t;
109

    
110
#ifdef TARGET_I386
111

    
112
#define ELF_PLATFORM get_elf_platform()
113

    
114
static const char *get_elf_platform(void)
115
{
116
    static char elf_platform[] = "i386";
117
    int family = (thread_env->cpuid_version >> 8) & 0xff;
118
    if (family > 6)
119
        family = 6;
120
    if (family >= 3)
121
        elf_platform[1] = '0' + family;
122
    return elf_platform;
123
}
124

    
125
#define ELF_HWCAP get_elf_hwcap()
126

    
127
static uint32_t get_elf_hwcap(void)
128
{
129
  return thread_env->cpuid_features;
130
}
131

    
132
#ifdef TARGET_X86_64
133
#define ELF_START_MMAP 0x2aaaaab000ULL
134
#define elf_check_arch(x) ( ((x) == ELF_ARCH) )
135

    
136
#define ELF_CLASS      ELFCLASS64
137
#define ELF_DATA       ELFDATA2LSB
138
#define ELF_ARCH       EM_X86_64
139

    
140
static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
141
{
142
    regs->rax = 0;
143
    regs->rsp = infop->start_stack;
144
    regs->rip = infop->entry;
145
}
146

    
147
#define ELF_NREG    27
148
typedef target_elf_greg_t  target_elf_gregset_t[ELF_NREG];
149

    
150
/*
151
 * Note that ELF_NREG should be 29 as there should be place for
152
 * TRAPNO and ERR "registers" as well but linux doesn't dump
153
 * those.
154
 *
155
 * See linux kernel: arch/x86/include/asm/elf.h
156
 */
157
static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUState *env)
158
{
159
    (*regs)[0] = env->regs[15];
160
    (*regs)[1] = env->regs[14];
161
    (*regs)[2] = env->regs[13];
162
    (*regs)[3] = env->regs[12];
163
    (*regs)[4] = env->regs[R_EBP];
164
    (*regs)[5] = env->regs[R_EBX];
165
    (*regs)[6] = env->regs[11];
166
    (*regs)[7] = env->regs[10];
167
    (*regs)[8] = env->regs[9];
168
    (*regs)[9] = env->regs[8];
169
    (*regs)[10] = env->regs[R_EAX];
170
    (*regs)[11] = env->regs[R_ECX];
171
    (*regs)[12] = env->regs[R_EDX];
172
    (*regs)[13] = env->regs[R_ESI];
173
    (*regs)[14] = env->regs[R_EDI];
174
    (*regs)[15] = env->regs[R_EAX]; /* XXX */
175
    (*regs)[16] = env->eip;
176
    (*regs)[17] = env->segs[R_CS].selector & 0xffff;
177
    (*regs)[18] = env->eflags;
178
    (*regs)[19] = env->regs[R_ESP];
179
    (*regs)[20] = env->segs[R_SS].selector & 0xffff;
180
    (*regs)[21] = env->segs[R_FS].selector & 0xffff;
181
    (*regs)[22] = env->segs[R_GS].selector & 0xffff;
182
    (*regs)[23] = env->segs[R_DS].selector & 0xffff;
183
    (*regs)[24] = env->segs[R_ES].selector & 0xffff;
184
    (*regs)[25] = env->segs[R_FS].selector & 0xffff;
185
    (*regs)[26] = env->segs[R_GS].selector & 0xffff;
186
}
187

    
188
#else
189

    
190
#define ELF_START_MMAP 0x80000000
191

    
192
/*
193
 * This is used to ensure we don't load something for the wrong architecture.
194
 */
195
#define elf_check_arch(x) ( ((x) == EM_386) || ((x) == EM_486) )
196

    
197
/*
198
 * These are used to set parameters in the core dumps.
199
 */
200
#define ELF_CLASS        ELFCLASS32
201
#define ELF_DATA        ELFDATA2LSB
202
#define ELF_ARCH        EM_386
203

    
204
static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
205
{
206
    regs->esp = infop->start_stack;
207
    regs->eip = infop->entry;
208

    
209
    /* SVR4/i386 ABI (pages 3-31, 3-32) says that when the program
210
       starts %edx contains a pointer to a function which might be
211
       registered using `atexit'.  This provides a mean for the
212
       dynamic linker to call DT_FINI functions for shared libraries
213
       that have been loaded before the code runs.
214

215
       A value of 0 tells we have no such handler.  */
216
    regs->edx = 0;
217
}
218

    
219
#define ELF_NREG    17
220
typedef target_elf_greg_t  target_elf_gregset_t[ELF_NREG];
221

    
222
/*
223
 * Note that ELF_NREG should be 19 as there should be place for
224
 * TRAPNO and ERR "registers" as well but linux doesn't dump
225
 * those.
226
 *
227
 * See linux kernel: arch/x86/include/asm/elf.h
228
 */
229
static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUState *env)
230
{
231
    (*regs)[0] = env->regs[R_EBX];
232
    (*regs)[1] = env->regs[R_ECX];
233
    (*regs)[2] = env->regs[R_EDX];
234
    (*regs)[3] = env->regs[R_ESI];
235
    (*regs)[4] = env->regs[R_EDI];
236
    (*regs)[5] = env->regs[R_EBP];
237
    (*regs)[6] = env->regs[R_EAX];
238
    (*regs)[7] = env->segs[R_DS].selector & 0xffff;
239
    (*regs)[8] = env->segs[R_ES].selector & 0xffff;
240
    (*regs)[9] = env->segs[R_FS].selector & 0xffff;
241
    (*regs)[10] = env->segs[R_GS].selector & 0xffff;
242
    (*regs)[11] = env->regs[R_EAX]; /* XXX */
243
    (*regs)[12] = env->eip;
244
    (*regs)[13] = env->segs[R_CS].selector & 0xffff;
245
    (*regs)[14] = env->eflags;
246
    (*regs)[15] = env->regs[R_ESP];
247
    (*regs)[16] = env->segs[R_SS].selector & 0xffff;
248
}
249
#endif
250

    
251
#define USE_ELF_CORE_DUMP
252
#define ELF_EXEC_PAGESIZE        4096
253

    
254
#endif
255

    
256
#ifdef TARGET_ARM
257

    
258
#define ELF_START_MMAP 0x80000000
259

    
260
#define elf_check_arch(x) ( (x) == EM_ARM )
261

    
262
#define ELF_CLASS        ELFCLASS32
263
#ifdef TARGET_WORDS_BIGENDIAN
264
#define ELF_DATA        ELFDATA2MSB
265
#else
266
#define ELF_DATA        ELFDATA2LSB
267
#endif
268
#define ELF_ARCH        EM_ARM
269

    
270
static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
271
{
272
    abi_long stack = infop->start_stack;
273
    memset(regs, 0, sizeof(*regs));
274
    regs->ARM_cpsr = 0x10;
275
    if (infop->entry & 1)
276
      regs->ARM_cpsr |= CPSR_T;
277
    regs->ARM_pc = infop->entry & 0xfffffffe;
278
    regs->ARM_sp = infop->start_stack;
279
    /* FIXME - what to for failure of get_user()? */
280
    get_user_ual(regs->ARM_r2, stack + 8); /* envp */
281
    get_user_ual(regs->ARM_r1, stack + 4); /* envp */
282
    /* XXX: it seems that r0 is zeroed after ! */
283
    regs->ARM_r0 = 0;
284
    /* For uClinux PIC binaries.  */
285
    /* XXX: Linux does this only on ARM with no MMU (do we care ?) */
286
    regs->ARM_r10 = infop->start_data;
287
}
288

    
289
#define ELF_NREG    18
290
typedef target_elf_greg_t  target_elf_gregset_t[ELF_NREG];
291

    
292
static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUState *env)
293
{
294
    (*regs)[0] = tswapl(env->regs[0]);
295
    (*regs)[1] = tswapl(env->regs[1]);
296
    (*regs)[2] = tswapl(env->regs[2]);
297
    (*regs)[3] = tswapl(env->regs[3]);
298
    (*regs)[4] = tswapl(env->regs[4]);
299
    (*regs)[5] = tswapl(env->regs[5]);
300
    (*regs)[6] = tswapl(env->regs[6]);
301
    (*regs)[7] = tswapl(env->regs[7]);
302
    (*regs)[8] = tswapl(env->regs[8]);
303
    (*regs)[9] = tswapl(env->regs[9]);
304
    (*regs)[10] = tswapl(env->regs[10]);
305
    (*regs)[11] = tswapl(env->regs[11]);
306
    (*regs)[12] = tswapl(env->regs[12]);
307
    (*regs)[13] = tswapl(env->regs[13]);
308
    (*regs)[14] = tswapl(env->regs[14]);
309
    (*regs)[15] = tswapl(env->regs[15]);
310

    
311
    (*regs)[16] = tswapl(cpsr_read((CPUState *)env));
312
    (*regs)[17] = tswapl(env->regs[0]); /* XXX */
313
}
314

    
315
#define USE_ELF_CORE_DUMP
316
#define ELF_EXEC_PAGESIZE        4096
317

    
318
enum
319
{
320
  ARM_HWCAP_ARM_SWP       = 1 << 0,
321
  ARM_HWCAP_ARM_HALF      = 1 << 1,
322
  ARM_HWCAP_ARM_THUMB     = 1 << 2,
323
  ARM_HWCAP_ARM_26BIT     = 1 << 3,
324
  ARM_HWCAP_ARM_FAST_MULT = 1 << 4,
325
  ARM_HWCAP_ARM_FPA       = 1 << 5,
326
  ARM_HWCAP_ARM_VFP       = 1 << 6,
327
  ARM_HWCAP_ARM_EDSP      = 1 << 7,
328
  ARM_HWCAP_ARM_JAVA      = 1 << 8,
329
  ARM_HWCAP_ARM_IWMMXT    = 1 << 9,
330
  ARM_HWCAP_ARM_THUMBEE   = 1 << 10,
331
  ARM_HWCAP_ARM_NEON      = 1 << 11,
332
  ARM_HWCAP_ARM_VFPv3     = 1 << 12,
333
  ARM_HWCAP_ARM_VFPv3D16  = 1 << 13,
334
};
335

    
336
#define ELF_HWCAP (ARM_HWCAP_ARM_SWP | ARM_HWCAP_ARM_HALF              \
337
                    | ARM_HWCAP_ARM_THUMB | ARM_HWCAP_ARM_FAST_MULT     \
338
                    | ARM_HWCAP_ARM_FPA | ARM_HWCAP_ARM_VFP \
339
                    | ARM_HWCAP_ARM_NEON | ARM_HWCAP_ARM_VFPv3 )
340

    
341
#endif
342

    
343
#ifdef TARGET_SPARC
344
#ifdef TARGET_SPARC64
345

    
346
#define ELF_START_MMAP 0x80000000
347

    
348
#ifndef TARGET_ABI32
349
#define elf_check_arch(x) ( (x) == EM_SPARCV9 || (x) == EM_SPARC32PLUS )
350
#else
351
#define elf_check_arch(x) ( (x) == EM_SPARC32PLUS || (x) == EM_SPARC )
352
#endif
353

    
354
#define ELF_CLASS   ELFCLASS64
355
#define ELF_DATA    ELFDATA2MSB
356
#define ELF_ARCH    EM_SPARCV9
357

    
358
#define STACK_BIAS                2047
359

    
360
static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
361
{
362
#ifndef TARGET_ABI32
363
    regs->tstate = 0;
364
#endif
365
    regs->pc = infop->entry;
366
    regs->npc = regs->pc + 4;
367
    regs->y = 0;
368
#ifdef TARGET_ABI32
369
    regs->u_regs[14] = infop->start_stack - 16 * 4;
370
#else
371
    if (personality(infop->personality) == PER_LINUX32)
372
        regs->u_regs[14] = infop->start_stack - 16 * 4;
373
    else
374
        regs->u_regs[14] = infop->start_stack - 16 * 8 - STACK_BIAS;
375
#endif
376
}
377

    
378
#else
379
#define ELF_START_MMAP 0x80000000
380

    
381
#define elf_check_arch(x) ( (x) == EM_SPARC )
382

    
383
#define ELF_CLASS   ELFCLASS32
384
#define ELF_DATA    ELFDATA2MSB
385
#define ELF_ARCH    EM_SPARC
386

    
387
static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
388
{
389
    regs->psr = 0;
390
    regs->pc = infop->entry;
391
    regs->npc = regs->pc + 4;
392
    regs->y = 0;
393
    regs->u_regs[14] = infop->start_stack - 16 * 4;
394
}
395

    
396
#endif
397
#endif
398

    
399
#ifdef TARGET_PPC
400

    
401
#define ELF_START_MMAP 0x80000000
402

    
403
#if defined(TARGET_PPC64) && !defined(TARGET_ABI32)
404

    
405
#define elf_check_arch(x) ( (x) == EM_PPC64 )
406

    
407
#define ELF_CLASS        ELFCLASS64
408

    
409
#else
410

    
411
#define elf_check_arch(x) ( (x) == EM_PPC )
412

    
413
#define ELF_CLASS        ELFCLASS32
414

    
415
#endif
416

    
417
#ifdef TARGET_WORDS_BIGENDIAN
418
#define ELF_DATA        ELFDATA2MSB
419
#else
420
#define ELF_DATA        ELFDATA2LSB
421
#endif
422
#define ELF_ARCH        EM_PPC
423

    
424
/* Feature masks for the Aux Vector Hardware Capabilities (AT_HWCAP).
425
   See arch/powerpc/include/asm/cputable.h.  */
426
enum {
427
    QEMU_PPC_FEATURE_32 = 0x80000000,
428
    QEMU_PPC_FEATURE_64 = 0x40000000,
429
    QEMU_PPC_FEATURE_601_INSTR = 0x20000000,
430
    QEMU_PPC_FEATURE_HAS_ALTIVEC = 0x10000000,
431
    QEMU_PPC_FEATURE_HAS_FPU = 0x08000000,
432
    QEMU_PPC_FEATURE_HAS_MMU = 0x04000000,
433
    QEMU_PPC_FEATURE_HAS_4xxMAC = 0x02000000,
434
    QEMU_PPC_FEATURE_UNIFIED_CACHE = 0x01000000,
435
    QEMU_PPC_FEATURE_HAS_SPE = 0x00800000,
436
    QEMU_PPC_FEATURE_HAS_EFP_SINGLE = 0x00400000,
437
    QEMU_PPC_FEATURE_HAS_EFP_DOUBLE = 0x00200000,
438
    QEMU_PPC_FEATURE_NO_TB = 0x00100000,
439
    QEMU_PPC_FEATURE_POWER4 = 0x00080000,
440
    QEMU_PPC_FEATURE_POWER5 = 0x00040000,
441
    QEMU_PPC_FEATURE_POWER5_PLUS = 0x00020000,
442
    QEMU_PPC_FEATURE_CELL = 0x00010000,
443
    QEMU_PPC_FEATURE_BOOKE = 0x00008000,
444
    QEMU_PPC_FEATURE_SMT = 0x00004000,
445
    QEMU_PPC_FEATURE_ICACHE_SNOOP = 0x00002000,
446
    QEMU_PPC_FEATURE_ARCH_2_05 = 0x00001000,
447
    QEMU_PPC_FEATURE_PA6T = 0x00000800,
448
    QEMU_PPC_FEATURE_HAS_DFP = 0x00000400,
449
    QEMU_PPC_FEATURE_POWER6_EXT = 0x00000200,
450
    QEMU_PPC_FEATURE_ARCH_2_06 = 0x00000100,
451
    QEMU_PPC_FEATURE_HAS_VSX = 0x00000080,
452
    QEMU_PPC_FEATURE_PSERIES_PERFMON_COMPAT = 0x00000040,
453

    
454
    QEMU_PPC_FEATURE_TRUE_LE = 0x00000002,
455
    QEMU_PPC_FEATURE_PPC_LE = 0x00000001,
456
};
457

    
458
#define ELF_HWCAP get_elf_hwcap()
459

    
460
static uint32_t get_elf_hwcap(void)
461
{
462
    CPUState *e = thread_env;
463
    uint32_t features = 0;
464

    
465
    /* We don't have to be terribly complete here; the high points are
466
       Altivec/FP/SPE support.  Anything else is just a bonus.  */
467
#define GET_FEATURE(flag, feature)              \
468
    do {if (e->insns_flags & flag) features |= feature; } while(0)
469
    GET_FEATURE(PPC_64B, QEMU_PPC_FEATURE_64);
470
    GET_FEATURE(PPC_FLOAT, QEMU_PPC_FEATURE_HAS_FPU);
471
    GET_FEATURE(PPC_ALTIVEC, QEMU_PPC_FEATURE_HAS_ALTIVEC);
472
    GET_FEATURE(PPC_SPE, QEMU_PPC_FEATURE_HAS_SPE);
473
    GET_FEATURE(PPC_SPE_SINGLE, QEMU_PPC_FEATURE_HAS_EFP_SINGLE);
474
    GET_FEATURE(PPC_SPE_DOUBLE, QEMU_PPC_FEATURE_HAS_EFP_DOUBLE);
475
    GET_FEATURE(PPC_BOOKE, QEMU_PPC_FEATURE_BOOKE);
476
    GET_FEATURE(PPC_405_MAC, QEMU_PPC_FEATURE_HAS_4xxMAC);
477
#undef GET_FEATURE
478

    
479
    return features;
480
}
481

    
482
/*
483
 * We need to put in some extra aux table entries to tell glibc what
484
 * the cache block size is, so it can use the dcbz instruction safely.
485
 */
486
#define AT_DCACHEBSIZE          19
487
#define AT_ICACHEBSIZE          20
488
#define AT_UCACHEBSIZE          21
489
/* A special ignored type value for PPC, for glibc compatibility.  */
490
#define AT_IGNOREPPC            22
491
/*
492
 * The requirements here are:
493
 * - keep the final alignment of sp (sp & 0xf)
494
 * - make sure the 32-bit value at the first 16 byte aligned position of
495
 *   AUXV is greater than 16 for glibc compatibility.
496
 *   AT_IGNOREPPC is used for that.
497
 * - for compatibility with glibc ARCH_DLINFO must always be defined on PPC,
498
 *   even if DLINFO_ARCH_ITEMS goes to zero or is undefined.
499
 */
500
#define DLINFO_ARCH_ITEMS       5
501
#define ARCH_DLINFO                                                     \
502
do {                                                                    \
503
        NEW_AUX_ENT(AT_DCACHEBSIZE, 0x20);                              \
504
        NEW_AUX_ENT(AT_ICACHEBSIZE, 0x20);                              \
505
        NEW_AUX_ENT(AT_UCACHEBSIZE, 0);                                 \
506
        /*                                                              \
507
         * Now handle glibc compatibility.                              \
508
         */                                                             \
509
        NEW_AUX_ENT(AT_IGNOREPPC, AT_IGNOREPPC);                        \
510
        NEW_AUX_ENT(AT_IGNOREPPC, AT_IGNOREPPC);                        \
511
 } while (0)
512

    
513
static inline void init_thread(struct target_pt_regs *_regs, struct image_info *infop)
514
{
515
    _regs->gpr[1] = infop->start_stack;
516
#if defined(TARGET_PPC64) && !defined(TARGET_ABI32)
517
    _regs->gpr[2] = ldq_raw(infop->entry + 8) + infop->load_addr;
518
    infop->entry = ldq_raw(infop->entry) + infop->load_addr;
519
#endif
520
    _regs->nip = infop->entry;
521
}
522

    
523
/* See linux kernel: arch/powerpc/include/asm/elf.h.  */
524
#define ELF_NREG 48
525
typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
526

    
527
static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUState *env)
528
{
529
    int i;
530
    target_ulong ccr = 0;
531

    
532
    for (i = 0; i < ARRAY_SIZE(env->gpr); i++) {
533
        (*regs)[i] = tswapl(env->gpr[i]);
534
    }
535

    
536
    (*regs)[32] = tswapl(env->nip);
537
    (*regs)[33] = tswapl(env->msr);
538
    (*regs)[35] = tswapl(env->ctr);
539
    (*regs)[36] = tswapl(env->lr);
540
    (*regs)[37] = tswapl(env->xer);
541

    
542
    for (i = 0; i < ARRAY_SIZE(env->crf); i++) {
543
        ccr |= env->crf[i] << (32 - ((i + 1) * 4));
544
    }
545
    (*regs)[38] = tswapl(ccr);
546
}
547

    
548
#define USE_ELF_CORE_DUMP
549
#define ELF_EXEC_PAGESIZE        4096
550

    
551
#endif
552

    
553
#ifdef TARGET_MIPS
554

    
555
#define ELF_START_MMAP 0x80000000
556

    
557
#define elf_check_arch(x) ( (x) == EM_MIPS )
558

    
559
#ifdef TARGET_MIPS64
560
#define ELF_CLASS   ELFCLASS64
561
#else
562
#define ELF_CLASS   ELFCLASS32
563
#endif
564
#ifdef TARGET_WORDS_BIGENDIAN
565
#define ELF_DATA        ELFDATA2MSB
566
#else
567
#define ELF_DATA        ELFDATA2LSB
568
#endif
569
#define ELF_ARCH    EM_MIPS
570

    
571
static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
572
{
573
    regs->cp0_status = 2 << CP0St_KSU;
574
    regs->cp0_epc = infop->entry;
575
    regs->regs[29] = infop->start_stack;
576
}
577

    
578
/* See linux kernel: arch/mips/include/asm/elf.h.  */
579
#define ELF_NREG 45
580
typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
581

    
582
/* See linux kernel: arch/mips/include/asm/reg.h.  */
583
enum {
584
#ifdef TARGET_MIPS64
585
    TARGET_EF_R0 = 0,
586
#else
587
    TARGET_EF_R0 = 6,
588
#endif
589
    TARGET_EF_R26 = TARGET_EF_R0 + 26,
590
    TARGET_EF_R27 = TARGET_EF_R0 + 27,
591
    TARGET_EF_LO = TARGET_EF_R0 + 32,
592
    TARGET_EF_HI = TARGET_EF_R0 + 33,
593
    TARGET_EF_CP0_EPC = TARGET_EF_R0 + 34,
594
    TARGET_EF_CP0_BADVADDR = TARGET_EF_R0 + 35,
595
    TARGET_EF_CP0_STATUS = TARGET_EF_R0 + 36,
596
    TARGET_EF_CP0_CAUSE = TARGET_EF_R0 + 37
597
};
598

    
599
/* See linux kernel: arch/mips/kernel/process.c:elf_dump_regs.  */
600
static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUState *env)
601
{
602
    int i;
603

    
604
    for (i = 0; i < TARGET_EF_R0; i++) {
605
        (*regs)[i] = 0;
606
    }
607
    (*regs)[TARGET_EF_R0] = 0;
608

    
609
    for (i = 1; i < ARRAY_SIZE(env->active_tc.gpr); i++) {
610
        (*regs)[TARGET_EF_R0 + i] = tswapl(env->active_tc.gpr[i]);
611
    }
612

    
613
    (*regs)[TARGET_EF_R26] = 0;
614
    (*regs)[TARGET_EF_R27] = 0;
615
    (*regs)[TARGET_EF_LO] = tswapl(env->active_tc.LO[0]);
616
    (*regs)[TARGET_EF_HI] = tswapl(env->active_tc.HI[0]);
617
    (*regs)[TARGET_EF_CP0_EPC] = tswapl(env->active_tc.PC);
618
    (*regs)[TARGET_EF_CP0_BADVADDR] = tswapl(env->CP0_BadVAddr);
619
    (*regs)[TARGET_EF_CP0_STATUS] = tswapl(env->CP0_Status);
620
    (*regs)[TARGET_EF_CP0_CAUSE] = tswapl(env->CP0_Cause);
621
}
622

    
623
#define USE_ELF_CORE_DUMP
624
#define ELF_EXEC_PAGESIZE        4096
625

    
626
#endif /* TARGET_MIPS */
627

    
628
#ifdef TARGET_MICROBLAZE
629

    
630
#define ELF_START_MMAP 0x80000000
631

    
632
#define elf_check_arch(x) ( (x) == EM_MICROBLAZE || (x) == EM_MICROBLAZE_OLD)
633

    
634
#define ELF_CLASS   ELFCLASS32
635
#define ELF_DATA        ELFDATA2MSB
636
#define ELF_ARCH    EM_MICROBLAZE
637

    
638
static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
639
{
640
    regs->pc = infop->entry;
641
    regs->r1 = infop->start_stack;
642

    
643
}
644

    
645
#define ELF_EXEC_PAGESIZE        4096
646

    
647
#define USE_ELF_CORE_DUMP
648
#define ELF_NREG 38
649
typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
650

    
651
/* See linux kernel: arch/mips/kernel/process.c:elf_dump_regs.  */
652
static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUState *env)
653
{
654
    int i, pos = 0;
655

    
656
    for (i = 0; i < 32; i++) {
657
        (*regs)[pos++] = tswapl(env->regs[i]);
658
    }
659

    
660
    for (i = 0; i < 6; i++) {
661
        (*regs)[pos++] = tswapl(env->sregs[i]);
662
    }
663
}
664

    
665
#endif /* TARGET_MICROBLAZE */
666

    
667
#ifdef TARGET_SH4
668

    
669
#define ELF_START_MMAP 0x80000000
670

    
671
#define elf_check_arch(x) ( (x) == EM_SH )
672

    
673
#define ELF_CLASS ELFCLASS32
674
#define ELF_DATA  ELFDATA2LSB
675
#define ELF_ARCH  EM_SH
676

    
677
static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
678
{
679
  /* Check other registers XXXXX */
680
  regs->pc = infop->entry;
681
  regs->regs[15] = infop->start_stack;
682
}
683

    
684
/* See linux kernel: arch/sh/include/asm/elf.h.  */
685
#define ELF_NREG 23
686
typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
687

    
688
/* See linux kernel: arch/sh/include/asm/ptrace.h.  */
689
enum {
690
    TARGET_REG_PC = 16,
691
    TARGET_REG_PR = 17,
692
    TARGET_REG_SR = 18,
693
    TARGET_REG_GBR = 19,
694
    TARGET_REG_MACH = 20,
695
    TARGET_REG_MACL = 21,
696
    TARGET_REG_SYSCALL = 22
697
};
698

    
699
static inline void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUState *env)
700
{
701
    int i;
702

    
703
    for (i = 0; i < 16; i++) {
704
        (*regs[i]) = tswapl(env->gregs[i]);
705
    }
706

    
707
    (*regs)[TARGET_REG_PC] = tswapl(env->pc);
708
    (*regs)[TARGET_REG_PR] = tswapl(env->pr);
709
    (*regs)[TARGET_REG_SR] = tswapl(env->sr);
710
    (*regs)[TARGET_REG_GBR] = tswapl(env->gbr);
711
    (*regs)[TARGET_REG_MACH] = tswapl(env->mach);
712
    (*regs)[TARGET_REG_MACL] = tswapl(env->macl);
713
    (*regs)[TARGET_REG_SYSCALL] = 0; /* FIXME */
714
}
715

    
716
#define USE_ELF_CORE_DUMP
717
#define ELF_EXEC_PAGESIZE        4096
718

    
719
#endif
720

    
721
#ifdef TARGET_CRIS
722

    
723
#define ELF_START_MMAP 0x80000000
724

    
725
#define elf_check_arch(x) ( (x) == EM_CRIS )
726

    
727
#define ELF_CLASS ELFCLASS32
728
#define ELF_DATA  ELFDATA2LSB
729
#define ELF_ARCH  EM_CRIS
730

    
731
static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
732
{
733
  regs->erp = infop->entry;
734
}
735

    
736
#define ELF_EXEC_PAGESIZE        8192
737

    
738
#endif
739

    
740
#ifdef TARGET_M68K
741

    
742
#define ELF_START_MMAP 0x80000000
743

    
744
#define elf_check_arch(x) ( (x) == EM_68K )
745

    
746
#define ELF_CLASS        ELFCLASS32
747
#define ELF_DATA        ELFDATA2MSB
748
#define ELF_ARCH        EM_68K
749

    
750
/* ??? Does this need to do anything?
751
#define ELF_PLAT_INIT(_r) */
752

    
753
static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
754
{
755
    regs->usp = infop->start_stack;
756
    regs->sr = 0;
757
    regs->pc = infop->entry;
758
}
759

    
760
/* See linux kernel: arch/m68k/include/asm/elf.h.  */
761
#define ELF_NREG 20
762
typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
763

    
764
static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUState *env)
765
{
766
    (*regs)[0] = tswapl(env->dregs[1]);
767
    (*regs)[1] = tswapl(env->dregs[2]);
768
    (*regs)[2] = tswapl(env->dregs[3]);
769
    (*regs)[3] = tswapl(env->dregs[4]);
770
    (*regs)[4] = tswapl(env->dregs[5]);
771
    (*regs)[5] = tswapl(env->dregs[6]);
772
    (*regs)[6] = tswapl(env->dregs[7]);
773
    (*regs)[7] = tswapl(env->aregs[0]);
774
    (*regs)[8] = tswapl(env->aregs[1]);
775
    (*regs)[9] = tswapl(env->aregs[2]);
776
    (*regs)[10] = tswapl(env->aregs[3]);
777
    (*regs)[11] = tswapl(env->aregs[4]);
778
    (*regs)[12] = tswapl(env->aregs[5]);
779
    (*regs)[13] = tswapl(env->aregs[6]);
780
    (*regs)[14] = tswapl(env->dregs[0]);
781
    (*regs)[15] = tswapl(env->aregs[7]);
782
    (*regs)[16] = tswapl(env->dregs[0]); /* FIXME: orig_d0 */
783
    (*regs)[17] = tswapl(env->sr);
784
    (*regs)[18] = tswapl(env->pc);
785
    (*regs)[19] = 0;  /* FIXME: regs->format | regs->vector */
786
}
787

    
788
#define USE_ELF_CORE_DUMP
789
#define ELF_EXEC_PAGESIZE        8192
790

    
791
#endif
792

    
793
#ifdef TARGET_ALPHA
794

    
795
#define ELF_START_MMAP (0x30000000000ULL)
796

    
797
#define elf_check_arch(x) ( (x) == ELF_ARCH )
798

    
799
#define ELF_CLASS      ELFCLASS64
800
#define ELF_DATA       ELFDATA2MSB
801
#define ELF_ARCH       EM_ALPHA
802

    
803
static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
804
{
805
    regs->pc = infop->entry;
806
    regs->ps = 8;
807
    regs->usp = infop->start_stack;
808
}
809

    
810
#define ELF_EXEC_PAGESIZE        8192
811

    
812
#endif /* TARGET_ALPHA */
813

    
814
#ifndef ELF_PLATFORM
815
#define ELF_PLATFORM (NULL)
816
#endif
817

    
818
#ifndef ELF_HWCAP
819
#define ELF_HWCAP 0
820
#endif
821

    
822
#ifdef TARGET_ABI32
823
#undef ELF_CLASS
824
#define ELF_CLASS ELFCLASS32
825
#undef bswaptls
826
#define bswaptls(ptr) bswap32s(ptr)
827
#endif
828

    
829
#include "elf.h"
830

    
831
struct exec
832
{
833
  unsigned int a_info;   /* Use macros N_MAGIC, etc for access */
834
  unsigned int a_text;   /* length of text, in bytes */
835
  unsigned int a_data;   /* length of data, in bytes */
836
  unsigned int a_bss;    /* length of uninitialized data area, in bytes */
837
  unsigned int a_syms;   /* length of symbol table data in file, in bytes */
838
  unsigned int a_entry;  /* start address */
839
  unsigned int a_trsize; /* length of relocation info for text, in bytes */
840
  unsigned int a_drsize; /* length of relocation info for data, in bytes */
841
};
842

    
843

    
844
#define N_MAGIC(exec) ((exec).a_info & 0xffff)
845
#define OMAGIC 0407
846
#define NMAGIC 0410
847
#define ZMAGIC 0413
848
#define QMAGIC 0314
849

    
850
/* max code+data+bss space allocated to elf interpreter */
851
#define INTERP_MAP_SIZE (32 * 1024 * 1024)
852

    
853
/* max code+data+bss+brk space allocated to ET_DYN executables */
854
#define ET_DYN_MAP_SIZE (128 * 1024 * 1024)
855

    
856
/* Necessary parameters */
857
#define TARGET_ELF_EXEC_PAGESIZE TARGET_PAGE_SIZE
858
#define TARGET_ELF_PAGESTART(_v) ((_v) & ~(unsigned long)(TARGET_ELF_EXEC_PAGESIZE-1))
859
#define TARGET_ELF_PAGEOFFSET(_v) ((_v) & (TARGET_ELF_EXEC_PAGESIZE-1))
860

    
861
#define INTERPRETER_NONE 0
862
#define INTERPRETER_AOUT 1
863
#define INTERPRETER_ELF 2
864

    
865
#define DLINFO_ITEMS 12
866

    
867
static inline void memcpy_fromfs(void * to, const void * from, unsigned long n)
868
{
869
        memcpy(to, from, n);
870
}
871

    
872
static int load_aout_interp(void * exptr, int interp_fd);
873

    
874
#ifdef BSWAP_NEEDED
875
static void bswap_ehdr(struct elfhdr *ehdr)
876
{
877
    bswap16s(&ehdr->e_type);                        /* Object file type */
878
    bswap16s(&ehdr->e_machine);                /* Architecture */
879
    bswap32s(&ehdr->e_version);                /* Object file version */
880
    bswaptls(&ehdr->e_entry);                /* Entry point virtual address */
881
    bswaptls(&ehdr->e_phoff);                /* Program header table file offset */
882
    bswaptls(&ehdr->e_shoff);                /* Section header table file offset */
883
    bswap32s(&ehdr->e_flags);                /* Processor-specific flags */
884
    bswap16s(&ehdr->e_ehsize);                /* ELF header size in bytes */
885
    bswap16s(&ehdr->e_phentsize);                /* Program header table entry size */
886
    bswap16s(&ehdr->e_phnum);                /* Program header table entry count */
887
    bswap16s(&ehdr->e_shentsize);                /* Section header table entry size */
888
    bswap16s(&ehdr->e_shnum);                /* Section header table entry count */
889
    bswap16s(&ehdr->e_shstrndx);                /* Section header string table index */
890
}
891

    
892
static void bswap_phdr(struct elf_phdr *phdr)
893
{
894
    bswap32s(&phdr->p_type);                        /* Segment type */
895
    bswaptls(&phdr->p_offset);                /* Segment file offset */
896
    bswaptls(&phdr->p_vaddr);                /* Segment virtual address */
897
    bswaptls(&phdr->p_paddr);                /* Segment physical address */
898
    bswaptls(&phdr->p_filesz);                /* Segment size in file */
899
    bswaptls(&phdr->p_memsz);                /* Segment size in memory */
900
    bswap32s(&phdr->p_flags);                /* Segment flags */
901
    bswaptls(&phdr->p_align);                /* Segment alignment */
902
}
903

    
904
static void bswap_shdr(struct elf_shdr *shdr)
905
{
906
    bswap32s(&shdr->sh_name);
907
    bswap32s(&shdr->sh_type);
908
    bswaptls(&shdr->sh_flags);
909
    bswaptls(&shdr->sh_addr);
910
    bswaptls(&shdr->sh_offset);
911
    bswaptls(&shdr->sh_size);
912
    bswap32s(&shdr->sh_link);
913
    bswap32s(&shdr->sh_info);
914
    bswaptls(&shdr->sh_addralign);
915
    bswaptls(&shdr->sh_entsize);
916
}
917

    
918
static void bswap_sym(struct elf_sym *sym)
919
{
920
    bswap32s(&sym->st_name);
921
    bswaptls(&sym->st_value);
922
    bswaptls(&sym->st_size);
923
    bswap16s(&sym->st_shndx);
924
}
925
#endif
926

    
927
#ifdef USE_ELF_CORE_DUMP
928
static int elf_core_dump(int, const CPUState *);
929

    
930
#ifdef BSWAP_NEEDED
931
static void bswap_note(struct elf_note *en)
932
{
933
    bswap32s(&en->n_namesz);
934
    bswap32s(&en->n_descsz);
935
    bswap32s(&en->n_type);
936
}
937
#endif /* BSWAP_NEEDED */
938

    
939
#endif /* USE_ELF_CORE_DUMP */
940

    
941
/*
942
 * 'copy_elf_strings()' copies argument/envelope strings from user
943
 * memory to free pages in kernel mem. These are in a format ready
944
 * to be put directly into the top of new user memory.
945
 *
946
 */
947
static abi_ulong copy_elf_strings(int argc,char ** argv, void **page,
948
                                  abi_ulong p)
949
{
950
    char *tmp, *tmp1, *pag = NULL;
951
    int len, offset = 0;
952

    
953
    if (!p) {
954
        return 0;       /* bullet-proofing */
955
    }
956
    while (argc-- > 0) {
957
        tmp = argv[argc];
958
        if (!tmp) {
959
            fprintf(stderr, "VFS: argc is wrong");
960
            exit(-1);
961
        }
962
        tmp1 = tmp;
963
        while (*tmp++);
964
        len = tmp - tmp1;
965
        if (p < len) {  /* this shouldn't happen - 128kB */
966
                return 0;
967
        }
968
        while (len) {
969
            --p; --tmp; --len;
970
            if (--offset < 0) {
971
                offset = p % TARGET_PAGE_SIZE;
972
                pag = (char *)page[p/TARGET_PAGE_SIZE];
973
                if (!pag) {
974
                    pag = (char *)malloc(TARGET_PAGE_SIZE);
975
                    memset(pag, 0, TARGET_PAGE_SIZE);
976
                    page[p/TARGET_PAGE_SIZE] = pag;
977
                    if (!pag)
978
                        return 0;
979
                }
980
            }
981
            if (len == 0 || offset == 0) {
982
                *(pag + offset) = *tmp;
983
            }
984
            else {
985
              int bytes_to_copy = (len > offset) ? offset : len;
986
              tmp -= bytes_to_copy;
987
              p -= bytes_to_copy;
988
              offset -= bytes_to_copy;
989
              len -= bytes_to_copy;
990
              memcpy_fromfs(pag + offset, tmp, bytes_to_copy + 1);
991
            }
992
        }
993
    }
994
    return p;
995
}
996

    
997
static abi_ulong setup_arg_pages(abi_ulong p, struct linux_binprm *bprm,
998
                                 struct image_info *info)
999
{
1000
    abi_ulong stack_base, size, error;
1001
    int i;
1002

    
1003
    /* Create enough stack to hold everything.  If we don't use
1004
     * it for args, we'll use it for something else...
1005
     */
1006
    size = guest_stack_size;
1007
    if (size < MAX_ARG_PAGES*TARGET_PAGE_SIZE)
1008
        size = MAX_ARG_PAGES*TARGET_PAGE_SIZE;
1009
    error = target_mmap(0,
1010
                        size + qemu_host_page_size,
1011
                        PROT_READ | PROT_WRITE,
1012
                        MAP_PRIVATE | MAP_ANONYMOUS,
1013
                        -1, 0);
1014
    if (error == -1) {
1015
        perror("stk mmap");
1016
        exit(-1);
1017
    }
1018
    /* we reserve one extra page at the top of the stack as guard */
1019
    target_mprotect(error + size, qemu_host_page_size, PROT_NONE);
1020

    
1021
    info->stack_limit = error;
1022
    stack_base = error + size - MAX_ARG_PAGES*TARGET_PAGE_SIZE;
1023
    p += stack_base;
1024

    
1025
    for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
1026
        if (bprm->page[i]) {
1027
            info->rss++;
1028
            /* FIXME - check return value of memcpy_to_target() for failure */
1029
            memcpy_to_target(stack_base, bprm->page[i], TARGET_PAGE_SIZE);
1030
            free(bprm->page[i]);
1031
        }
1032
        stack_base += TARGET_PAGE_SIZE;
1033
    }
1034
    return p;
1035
}
1036

    
1037
/* Map and zero the bss.  We need to explicitly zero any fractional pages
1038
   after the data section (i.e. bss).  */
1039
static void zero_bss(abi_ulong elf_bss, abi_ulong last_bss, int prot)
1040
{
1041
    uintptr_t host_start, host_map_start, host_end;
1042

    
1043
    last_bss = TARGET_PAGE_ALIGN(last_bss);
1044

    
1045
    /* ??? There is confusion between qemu_real_host_page_size and
1046
       qemu_host_page_size here and elsewhere in target_mmap, which
1047
       may lead to the end of the data section mapping from the file
1048
       not being mapped.  At least there was an explicit test and
1049
       comment for that here, suggesting that "the file size must
1050
       be known".  The comment probably pre-dates the introduction
1051
       of the fstat system call in target_mmap which does in fact
1052
       find out the size.  What isn't clear is if the workaround
1053
       here is still actually needed.  For now, continue with it,
1054
       but merge it with the "normal" mmap that would allocate the bss.  */
1055

    
1056
    host_start = (uintptr_t) g2h(elf_bss);
1057
    host_end = (uintptr_t) g2h(last_bss);
1058
    host_map_start = (host_start + qemu_real_host_page_size - 1);
1059
    host_map_start &= -qemu_real_host_page_size;
1060

    
1061
    if (host_map_start < host_end) {
1062
        void *p = mmap((void *)host_map_start, host_end - host_map_start,
1063
                       prot, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
1064
        if (p == MAP_FAILED) {
1065
            perror("cannot mmap brk");
1066
            exit(-1);
1067
        }
1068

    
1069
        /* Since we didn't use target_mmap, make sure to record
1070
           the validity of the pages with qemu.  */
1071
        page_set_flags(elf_bss & TARGET_PAGE_MASK, last_bss, prot|PAGE_VALID);
1072
    }
1073

    
1074
    if (host_start < host_map_start) {
1075
        memset((void *)host_start, 0, host_map_start - host_start);
1076
    }
1077
}
1078

    
1079
static abi_ulong create_elf_tables(abi_ulong p, int argc, int envc,
1080
                                   struct elfhdr * exec,
1081
                                   abi_ulong load_addr,
1082
                                   abi_ulong load_bias,
1083
                                   abi_ulong interp_load_addr, int ibcs,
1084
                                   struct image_info *info)
1085
{
1086
        abi_ulong sp;
1087
        int size;
1088
        abi_ulong u_platform;
1089
        const char *k_platform;
1090
        const int n = sizeof(elf_addr_t);
1091

    
1092
        sp = p;
1093
        u_platform = 0;
1094
        k_platform = ELF_PLATFORM;
1095
        if (k_platform) {
1096
            size_t len = strlen(k_platform) + 1;
1097
            sp -= (len + n - 1) & ~(n - 1);
1098
            u_platform = sp;
1099
            /* FIXME - check return value of memcpy_to_target() for failure */
1100
            memcpy_to_target(sp, k_platform, len);
1101
        }
1102
        /*
1103
         * Force 16 byte _final_ alignment here for generality.
1104
         */
1105
        sp = sp &~ (abi_ulong)15;
1106
        size = (DLINFO_ITEMS + 1) * 2;
1107
        if (k_platform)
1108
          size += 2;
1109
#ifdef DLINFO_ARCH_ITEMS
1110
        size += DLINFO_ARCH_ITEMS * 2;
1111
#endif
1112
        size += envc + argc + 2;
1113
        size += (!ibcs ? 3 : 1);        /* argc itself */
1114
        size *= n;
1115
        if (size & 15)
1116
            sp -= 16 - (size & 15);
1117

    
1118
        /* This is correct because Linux defines
1119
         * elf_addr_t as Elf32_Off / Elf64_Off
1120
         */
1121
#define NEW_AUX_ENT(id, val) do {                \
1122
            sp -= n; put_user_ual(val, sp);        \
1123
            sp -= n; put_user_ual(id, sp);        \
1124
          } while(0)
1125

    
1126
        NEW_AUX_ENT (AT_NULL, 0);
1127

    
1128
        /* There must be exactly DLINFO_ITEMS entries here.  */
1129
        NEW_AUX_ENT(AT_PHDR, (abi_ulong)(load_addr + exec->e_phoff));
1130
        NEW_AUX_ENT(AT_PHENT, (abi_ulong)(sizeof (struct elf_phdr)));
1131
        NEW_AUX_ENT(AT_PHNUM, (abi_ulong)(exec->e_phnum));
1132
        NEW_AUX_ENT(AT_PAGESZ, (abi_ulong)(TARGET_PAGE_SIZE));
1133
        NEW_AUX_ENT(AT_BASE, (abi_ulong)(interp_load_addr));
1134
        NEW_AUX_ENT(AT_FLAGS, (abi_ulong)0);
1135
        NEW_AUX_ENT(AT_ENTRY, load_bias + exec->e_entry);
1136
        NEW_AUX_ENT(AT_UID, (abi_ulong) getuid());
1137
        NEW_AUX_ENT(AT_EUID, (abi_ulong) geteuid());
1138
        NEW_AUX_ENT(AT_GID, (abi_ulong) getgid());
1139
        NEW_AUX_ENT(AT_EGID, (abi_ulong) getegid());
1140
        NEW_AUX_ENT(AT_HWCAP, (abi_ulong) ELF_HWCAP);
1141
        NEW_AUX_ENT(AT_CLKTCK, (abi_ulong) sysconf(_SC_CLK_TCK));
1142
        if (k_platform)
1143
            NEW_AUX_ENT(AT_PLATFORM, u_platform);
1144
#ifdef ARCH_DLINFO
1145
        /*
1146
         * ARCH_DLINFO must come last so platform specific code can enforce
1147
         * special alignment requirements on the AUXV if necessary (eg. PPC).
1148
         */
1149
        ARCH_DLINFO;
1150
#endif
1151
#undef NEW_AUX_ENT
1152

    
1153
        info->saved_auxv = sp;
1154

    
1155
        sp = loader_build_argptr(envc, argc, sp, p, !ibcs);
1156
        return sp;
1157
}
1158

    
1159

    
1160
static abi_ulong load_elf_interp(struct elfhdr * interp_elf_ex,
1161
                                 int interpreter_fd,
1162
                                 abi_ulong *interp_load_addr)
1163
{
1164
        struct elf_phdr *elf_phdata  =  NULL;
1165
        struct elf_phdr *eppnt;
1166
        abi_ulong load_addr = 0;
1167
        int load_addr_set = 0;
1168
        int retval;
1169
        abi_ulong error;
1170
        int i;
1171

    
1172
        error = 0;
1173

    
1174
#ifdef BSWAP_NEEDED
1175
        bswap_ehdr(interp_elf_ex);
1176
#endif
1177
        /* First of all, some simple consistency checks */
1178
        if ((interp_elf_ex->e_type != ET_EXEC &&
1179
             interp_elf_ex->e_type != ET_DYN) ||
1180
           !elf_check_arch(interp_elf_ex->e_machine)) {
1181
                return ~((abi_ulong)0UL);
1182
        }
1183

    
1184

    
1185
        /* Now read in all of the header information */
1186

    
1187
        if (sizeof(struct elf_phdr) * interp_elf_ex->e_phnum > TARGET_PAGE_SIZE)
1188
            return ~(abi_ulong)0UL;
1189

    
1190
        elf_phdata =  (struct elf_phdr *)
1191
                malloc(sizeof(struct elf_phdr) * interp_elf_ex->e_phnum);
1192

    
1193
        if (!elf_phdata)
1194
          return ~((abi_ulong)0UL);
1195

    
1196
        /*
1197
         * If the size of this structure has changed, then punt, since
1198
         * we will be doing the wrong thing.
1199
         */
1200
        if (interp_elf_ex->e_phentsize != sizeof(struct elf_phdr)) {
1201
            free(elf_phdata);
1202
            return ~((abi_ulong)0UL);
1203
        }
1204

    
1205
        retval = lseek(interpreter_fd, interp_elf_ex->e_phoff, SEEK_SET);
1206
        if(retval >= 0) {
1207
            retval = read(interpreter_fd,
1208
                           (char *) elf_phdata,
1209
                           sizeof(struct elf_phdr) * interp_elf_ex->e_phnum);
1210
        }
1211
        if (retval < 0) {
1212
                perror("load_elf_interp");
1213
                exit(-1);
1214
                free (elf_phdata);
1215
                return retval;
1216
         }
1217
#ifdef BSWAP_NEEDED
1218
        eppnt = elf_phdata;
1219
        for (i=0; i<interp_elf_ex->e_phnum; i++, eppnt++) {
1220
            bswap_phdr(eppnt);
1221
        }
1222
#endif
1223

    
1224
        if (interp_elf_ex->e_type == ET_DYN) {
1225
            /* in order to avoid hardcoding the interpreter load
1226
               address in qemu, we allocate a big enough memory zone */
1227
            error = target_mmap(0, INTERP_MAP_SIZE,
1228
                                PROT_NONE, MAP_PRIVATE | MAP_ANON,
1229
                                -1, 0);
1230
            if (error == -1) {
1231
                perror("mmap");
1232
                exit(-1);
1233
            }
1234
            load_addr = error;
1235
            load_addr_set = 1;
1236
        }
1237

    
1238
        eppnt = elf_phdata;
1239
        for(i=0; i<interp_elf_ex->e_phnum; i++, eppnt++)
1240
          if (eppnt->p_type == PT_LOAD) {
1241
            int elf_type = MAP_PRIVATE | MAP_DENYWRITE;
1242
            int elf_prot = 0;
1243
            abi_ulong vaddr = 0;
1244

    
1245
            if (eppnt->p_flags & PF_R) elf_prot =  PROT_READ;
1246
            if (eppnt->p_flags & PF_W) elf_prot |= PROT_WRITE;
1247
            if (eppnt->p_flags & PF_X) elf_prot |= PROT_EXEC;
1248
            if (interp_elf_ex->e_type == ET_EXEC || load_addr_set) {
1249
                    elf_type |= MAP_FIXED;
1250
                    vaddr = eppnt->p_vaddr;
1251
            }
1252
            error = target_mmap(load_addr+TARGET_ELF_PAGESTART(vaddr),
1253
                 eppnt->p_filesz + TARGET_ELF_PAGEOFFSET(eppnt->p_vaddr),
1254
                 elf_prot,
1255
                 elf_type,
1256
                 interpreter_fd,
1257
                 eppnt->p_offset - TARGET_ELF_PAGEOFFSET(eppnt->p_vaddr));
1258

    
1259
            if (error == -1) {
1260
              /* Real error */
1261
              close(interpreter_fd);
1262
              free(elf_phdata);
1263
              return ~((abi_ulong)0UL);
1264
            }
1265

    
1266
            if (!load_addr_set && interp_elf_ex->e_type == ET_DYN) {
1267
              load_addr = error;
1268
              load_addr_set = 1;
1269
            }
1270

    
1271
            /* If the load segment requests extra zeros (e.g. bss), map it.  */
1272
            if (eppnt->p_filesz < eppnt->p_memsz) {
1273
                abi_ulong base = load_addr + eppnt->p_vaddr;
1274
                zero_bss(base + eppnt->p_filesz,
1275
                         base + eppnt->p_memsz, elf_prot);
1276
            }
1277
          }
1278

    
1279
        /* Now use mmap to map the library into memory. */
1280

    
1281
        close(interpreter_fd);
1282
        free(elf_phdata);
1283

    
1284
        *interp_load_addr = load_addr;
1285
        return ((abi_ulong) interp_elf_ex->e_entry) + load_addr;
1286
}
1287

    
1288
static int symfind(const void *s0, const void *s1)
1289
{
1290
    struct elf_sym *key = (struct elf_sym *)s0;
1291
    struct elf_sym *sym = (struct elf_sym *)s1;
1292
    int result = 0;
1293
    if (key->st_value < sym->st_value) {
1294
        result = -1;
1295
    } else if (key->st_value >= sym->st_value + sym->st_size) {
1296
        result = 1;
1297
    }
1298
    return result;
1299
}
1300

    
1301
static const char *lookup_symbolxx(struct syminfo *s, target_ulong orig_addr)
1302
{
1303
#if ELF_CLASS == ELFCLASS32
1304
    struct elf_sym *syms = s->disas_symtab.elf32;
1305
#else
1306
    struct elf_sym *syms = s->disas_symtab.elf64;
1307
#endif
1308

    
1309
    // binary search
1310
    struct elf_sym key;
1311
    struct elf_sym *sym;
1312

    
1313
    key.st_value = orig_addr;
1314

    
1315
    sym = bsearch(&key, syms, s->disas_num_syms, sizeof(*syms), symfind);
1316
    if (sym != NULL) {
1317
        return s->disas_strtab + sym->st_name;
1318
    }
1319

    
1320
    return "";
1321
}
1322

    
1323
/* FIXME: This should use elf_ops.h  */
1324
static int symcmp(const void *s0, const void *s1)
1325
{
1326
    struct elf_sym *sym0 = (struct elf_sym *)s0;
1327
    struct elf_sym *sym1 = (struct elf_sym *)s1;
1328
    return (sym0->st_value < sym1->st_value)
1329
        ? -1
1330
        : ((sym0->st_value > sym1->st_value) ? 1 : 0);
1331
}
1332

    
1333
/* Best attempt to load symbols from this ELF object. */
1334
static void load_symbols(struct elfhdr *hdr, int fd)
1335
{
1336
    unsigned int i, nsyms;
1337
    struct elf_shdr sechdr, symtab, strtab;
1338
    char *strings;
1339
    struct syminfo *s;
1340
    struct elf_sym *syms;
1341

    
1342
    lseek(fd, hdr->e_shoff, SEEK_SET);
1343
    for (i = 0; i < hdr->e_shnum; i++) {
1344
        if (read(fd, &sechdr, sizeof(sechdr)) != sizeof(sechdr))
1345
            return;
1346
#ifdef BSWAP_NEEDED
1347
        bswap_shdr(&sechdr);
1348
#endif
1349
        if (sechdr.sh_type == SHT_SYMTAB) {
1350
            symtab = sechdr;
1351
            lseek(fd, hdr->e_shoff
1352
                  + sizeof(sechdr) * sechdr.sh_link, SEEK_SET);
1353
            if (read(fd, &strtab, sizeof(strtab))
1354
                != sizeof(strtab))
1355
                return;
1356
#ifdef BSWAP_NEEDED
1357
            bswap_shdr(&strtab);
1358
#endif
1359
            goto found;
1360
        }
1361
    }
1362
    return; /* Shouldn't happen... */
1363

    
1364
 found:
1365
    /* Now know where the strtab and symtab are.  Snarf them. */
1366
    s = malloc(sizeof(*s));
1367
    syms = malloc(symtab.sh_size);
1368
    if (!syms)
1369
        return;
1370
    s->disas_strtab = strings = malloc(strtab.sh_size);
1371
    if (!s->disas_strtab)
1372
        return;
1373

    
1374
    lseek(fd, symtab.sh_offset, SEEK_SET);
1375
    if (read(fd, syms, symtab.sh_size) != symtab.sh_size)
1376
        return;
1377

    
1378
    nsyms = symtab.sh_size / sizeof(struct elf_sym);
1379

    
1380
    i = 0;
1381
    while (i < nsyms) {
1382
#ifdef BSWAP_NEEDED
1383
        bswap_sym(syms + i);
1384
#endif
1385
        // Throw away entries which we do not need.
1386
        if (syms[i].st_shndx == SHN_UNDEF ||
1387
                syms[i].st_shndx >= SHN_LORESERVE ||
1388
                ELF_ST_TYPE(syms[i].st_info) != STT_FUNC) {
1389
            nsyms--;
1390
            if (i < nsyms) {
1391
                syms[i] = syms[nsyms];
1392
            }
1393
            continue;
1394
        }
1395
#if defined(TARGET_ARM) || defined (TARGET_MIPS)
1396
        /* The bottom address bit marks a Thumb or MIPS16 symbol.  */
1397
        syms[i].st_value &= ~(target_ulong)1;
1398
#endif
1399
        i++;
1400
    }
1401
    syms = realloc(syms, nsyms * sizeof(*syms));
1402

    
1403
    qsort(syms, nsyms, sizeof(*syms), symcmp);
1404

    
1405
    lseek(fd, strtab.sh_offset, SEEK_SET);
1406
    if (read(fd, strings, strtab.sh_size) != strtab.sh_size)
1407
        return;
1408
    s->disas_num_syms = nsyms;
1409
#if ELF_CLASS == ELFCLASS32
1410
    s->disas_symtab.elf32 = syms;
1411
    s->lookup_symbol = lookup_symbolxx;
1412
#else
1413
    s->disas_symtab.elf64 = syms;
1414
    s->lookup_symbol = lookup_symbolxx;
1415
#endif
1416
    s->next = syminfos;
1417
    syminfos = s;
1418
}
1419

    
1420
int load_elf_binary(struct linux_binprm * bprm, struct target_pt_regs * regs,
1421
                    struct image_info * info)
1422
{
1423
    struct elfhdr elf_ex;
1424
    struct elfhdr interp_elf_ex;
1425
    struct exec interp_ex;
1426
    int interpreter_fd = -1; /* avoid warning */
1427
    abi_ulong load_addr, load_bias;
1428
    int load_addr_set = 0;
1429
    unsigned int interpreter_type = INTERPRETER_NONE;
1430
    unsigned char ibcs2_interpreter;
1431
    int i;
1432
    abi_ulong mapped_addr;
1433
    struct elf_phdr * elf_ppnt;
1434
    struct elf_phdr *elf_phdata;
1435
    abi_ulong k, elf_brk;
1436
    int retval;
1437
    char * elf_interpreter;
1438
    abi_ulong elf_entry, interp_load_addr = 0;
1439
    int status;
1440
    abi_ulong start_code, end_code, start_data, end_data;
1441
    abi_ulong reloc_func_desc = 0;
1442
    abi_ulong elf_stack;
1443
    char passed_fileno[6];
1444

    
1445
    ibcs2_interpreter = 0;
1446
    status = 0;
1447
    load_addr = 0;
1448
    load_bias = 0;
1449
    elf_ex = *((struct elfhdr *) bprm->buf);          /* exec-header */
1450
#ifdef BSWAP_NEEDED
1451
    bswap_ehdr(&elf_ex);
1452
#endif
1453

    
1454
    /* First of all, some simple consistency checks */
1455
    if ((elf_ex.e_type != ET_EXEC && elf_ex.e_type != ET_DYN) ||
1456
                                       (! elf_check_arch(elf_ex.e_machine))) {
1457
            return -ENOEXEC;
1458
    }
1459

    
1460
    bprm->p = copy_elf_strings(1, &bprm->filename, bprm->page, bprm->p);
1461
    bprm->p = copy_elf_strings(bprm->envc,bprm->envp,bprm->page,bprm->p);
1462
    bprm->p = copy_elf_strings(bprm->argc,bprm->argv,bprm->page,bprm->p);
1463
    if (!bprm->p) {
1464
        retval = -E2BIG;
1465
    }
1466

    
1467
    /* Now read in all of the header information */
1468
    elf_phdata = (struct elf_phdr *)malloc(elf_ex.e_phentsize*elf_ex.e_phnum);
1469
    if (elf_phdata == NULL) {
1470
        return -ENOMEM;
1471
    }
1472

    
1473
    retval = lseek(bprm->fd, elf_ex.e_phoff, SEEK_SET);
1474
    if(retval > 0) {
1475
        retval = read(bprm->fd, (char *) elf_phdata,
1476
                                elf_ex.e_phentsize * elf_ex.e_phnum);
1477
    }
1478

    
1479
    if (retval < 0) {
1480
        perror("load_elf_binary");
1481
        exit(-1);
1482
        free (elf_phdata);
1483
        return -errno;
1484
    }
1485

    
1486
#ifdef BSWAP_NEEDED
1487
    elf_ppnt = elf_phdata;
1488
    for (i=0; i<elf_ex.e_phnum; i++, elf_ppnt++) {
1489
        bswap_phdr(elf_ppnt);
1490
    }
1491
#endif
1492
    elf_ppnt = elf_phdata;
1493

    
1494
    elf_brk = 0;
1495

    
1496
    elf_stack = ~((abi_ulong)0UL);
1497
    elf_interpreter = NULL;
1498
    start_code = ~((abi_ulong)0UL);
1499
    end_code = 0;
1500
    start_data = 0;
1501
    end_data = 0;
1502
    interp_ex.a_info = 0;
1503

    
1504
    for(i=0;i < elf_ex.e_phnum; i++) {
1505
        if (elf_ppnt->p_type == PT_INTERP) {
1506
            if ( elf_interpreter != NULL )
1507
            {
1508
                free (elf_phdata);
1509
                free(elf_interpreter);
1510
                close(bprm->fd);
1511
                return -EINVAL;
1512
            }
1513

    
1514
            /* This is the program interpreter used for
1515
             * shared libraries - for now assume that this
1516
             * is an a.out format binary
1517
             */
1518

    
1519
            elf_interpreter = (char *)malloc(elf_ppnt->p_filesz);
1520

    
1521
            if (elf_interpreter == NULL) {
1522
                free (elf_phdata);
1523
                close(bprm->fd);
1524
                return -ENOMEM;
1525
            }
1526

    
1527
            retval = lseek(bprm->fd, elf_ppnt->p_offset, SEEK_SET);
1528
            if(retval >= 0) {
1529
                retval = read(bprm->fd, elf_interpreter, elf_ppnt->p_filesz);
1530
            }
1531
            if(retval < 0) {
1532
                 perror("load_elf_binary2");
1533
                exit(-1);
1534
            }
1535

    
1536
            /* If the program interpreter is one of these two,
1537
               then assume an iBCS2 image. Otherwise assume
1538
               a native linux image. */
1539

    
1540
            /* JRP - Need to add X86 lib dir stuff here... */
1541

    
1542
            if (strcmp(elf_interpreter,"/usr/lib/libc.so.1") == 0 ||
1543
                strcmp(elf_interpreter,"/usr/lib/ld.so.1") == 0) {
1544
              ibcs2_interpreter = 1;
1545
            }
1546

    
1547
#if 0
1548
            printf("Using ELF interpreter %s\n", path(elf_interpreter));
1549
#endif
1550
            if (retval >= 0) {
1551
                retval = open(path(elf_interpreter), O_RDONLY);
1552
                if(retval >= 0) {
1553
                    interpreter_fd = retval;
1554
                }
1555
                else {
1556
                    perror(elf_interpreter);
1557
                    exit(-1);
1558
                    /* retval = -errno; */
1559
                }
1560
            }
1561

    
1562
            if (retval >= 0) {
1563
                retval = lseek(interpreter_fd, 0, SEEK_SET);
1564
                if(retval >= 0) {
1565
                    retval = read(interpreter_fd,bprm->buf,128);
1566
                }
1567
            }
1568
            if (retval >= 0) {
1569
                interp_ex = *((struct exec *) bprm->buf); /* aout exec-header */
1570
                interp_elf_ex = *((struct elfhdr *) bprm->buf); /* elf exec-header */
1571
            }
1572
            if (retval < 0) {
1573
                perror("load_elf_binary3");
1574
                exit(-1);
1575
                free (elf_phdata);
1576
                free(elf_interpreter);
1577
                close(bprm->fd);
1578
                return retval;
1579
            }
1580
        }
1581
        elf_ppnt++;
1582
    }
1583

    
1584
    /* Some simple consistency checks for the interpreter */
1585
    if (elf_interpreter){
1586
        interpreter_type = INTERPRETER_ELF | INTERPRETER_AOUT;
1587

    
1588
        /* Now figure out which format our binary is */
1589
        if ((N_MAGIC(interp_ex) != OMAGIC) && (N_MAGIC(interp_ex) != ZMAGIC) &&
1590
                    (N_MAGIC(interp_ex) != QMAGIC)) {
1591
          interpreter_type = INTERPRETER_ELF;
1592
        }
1593

    
1594
        if (interp_elf_ex.e_ident[0] != 0x7f ||
1595
            strncmp((char *)&interp_elf_ex.e_ident[1], "ELF",3) != 0) {
1596
            interpreter_type &= ~INTERPRETER_ELF;
1597
        }
1598

    
1599
        if (!interpreter_type) {
1600
            free(elf_interpreter);
1601
            free(elf_phdata);
1602
            close(bprm->fd);
1603
            return -ELIBBAD;
1604
        }
1605
    }
1606

    
1607
    /* OK, we are done with that, now set up the arg stuff,
1608
       and then start this sucker up */
1609

    
1610
    {
1611
        char * passed_p;
1612

    
1613
        if (interpreter_type == INTERPRETER_AOUT) {
1614
            snprintf(passed_fileno, sizeof(passed_fileno), "%d", bprm->fd);
1615
            passed_p = passed_fileno;
1616

    
1617
            if (elf_interpreter) {
1618
                bprm->p = copy_elf_strings(1,&passed_p,bprm->page,bprm->p);
1619
                bprm->argc++;
1620
            }
1621
        }
1622
        if (!bprm->p) {
1623
            if (elf_interpreter) {
1624
                free(elf_interpreter);
1625
            }
1626
            free (elf_phdata);
1627
            close(bprm->fd);
1628
            return -E2BIG;
1629
        }
1630
    }
1631

    
1632
    /* OK, This is the point of no return */
1633
    info->end_data = 0;
1634
    info->end_code = 0;
1635
    info->start_mmap = (abi_ulong)ELF_START_MMAP;
1636
    info->mmap = 0;
1637
    elf_entry = (abi_ulong) elf_ex.e_entry;
1638

    
1639
#if defined(CONFIG_USE_GUEST_BASE)
1640
    /*
1641
     * In case where user has not explicitly set the guest_base, we
1642
     * probe here that should we set it automatically.
1643
     */
1644
    if (!(have_guest_base || reserved_va)) {
1645
        /*
1646
         * Go through ELF program header table and find the address
1647
         * range used by loadable segments.  Check that this is available on
1648
         * the host, and if not find a suitable value for guest_base.  */
1649
        abi_ulong app_start = ~0;
1650
        abi_ulong app_end = 0;
1651
        abi_ulong addr;
1652
        unsigned long host_start;
1653
        unsigned long real_start;
1654
        unsigned long host_size;
1655
        for (i = 0, elf_ppnt = elf_phdata; i < elf_ex.e_phnum;
1656
            i++, elf_ppnt++) {
1657
            if (elf_ppnt->p_type != PT_LOAD)
1658
                continue;
1659
            addr = elf_ppnt->p_vaddr;
1660
            if (addr < app_start) {
1661
                app_start = addr;
1662
            }
1663
            addr += elf_ppnt->p_memsz;
1664
            if (addr > app_end) {
1665
                app_end = addr;
1666
            }
1667
        }
1668

    
1669
        /* If we don't have any loadable segments then something
1670
           is very wrong.  */
1671
        assert(app_start < app_end);
1672

    
1673
        /* Round addresses to page boundaries.  */
1674
        app_start = app_start & qemu_host_page_mask;
1675
        app_end = HOST_PAGE_ALIGN(app_end);
1676
        if (app_start < mmap_min_addr) {
1677
            host_start = HOST_PAGE_ALIGN(mmap_min_addr);
1678
        } else {
1679
            host_start = app_start;
1680
            if (host_start != app_start) {
1681
                fprintf(stderr, "qemu: Address overflow loading ELF binary\n");
1682
                abort();
1683
            }
1684
        }
1685
        host_size = app_end - app_start;
1686
        while (1) {
1687
            /* Do not use mmap_find_vma here because that is limited to the
1688
               guest address space.  We are going to make the
1689
               guest address space fit whatever we're given.  */
1690
            real_start = (unsigned long)mmap((void *)host_start, host_size,
1691
                PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_NORESERVE, -1, 0);
1692
            if (real_start == (unsigned long)-1) {
1693
                fprintf(stderr, "qemu: Virtual memory exausted\n");
1694
                abort();
1695
            }
1696
            if (real_start == host_start) {
1697
                break;
1698
            }
1699
            /* That address didn't work.  Unmap and try a different one.
1700
               The address the host picked because is typically
1701
               right at the top of the host address space and leaves the
1702
               guest with no usable address space.  Resort to a linear search.
1703
               We already compensated for mmap_min_addr, so this should not
1704
               happen often.  Probably means we got unlucky and host address
1705
               space randomization put a shared library somewhere
1706
               inconvenient.  */
1707
            munmap((void *)real_start, host_size);
1708
            host_start += qemu_host_page_size;
1709
            if (host_start == app_start) {
1710
                /* Theoretically possible if host doesn't have any
1711
                   suitably aligned areas.  Normally the first mmap will
1712
                   fail.  */
1713
                fprintf(stderr, "qemu: Unable to find space for application\n");
1714
                abort();
1715
            }
1716
        }
1717
        qemu_log("Relocating guest address space from 0x" TARGET_ABI_FMT_lx
1718
                 " to 0x%lx\n", app_start, real_start);
1719
        guest_base = real_start - app_start;
1720
    }
1721
#endif /* CONFIG_USE_GUEST_BASE */
1722

    
1723
    /* Do this so that we can load the interpreter, if need be.  We will
1724
       change some of these later */
1725
    info->rss = 0;
1726
    bprm->p = setup_arg_pages(bprm->p, bprm, info);
1727
    info->start_stack = bprm->p;
1728

    
1729
    /* Now we do a little grungy work by mmaping the ELF image into
1730
     * the correct location in memory.  At this point, we assume that
1731
     * the image should be loaded at fixed address, not at a variable
1732
     * address.
1733
     */
1734

    
1735
    for(i = 0, elf_ppnt = elf_phdata; i < elf_ex.e_phnum; i++, elf_ppnt++) {
1736
        int elf_prot = 0;
1737
        int elf_flags = 0;
1738
        abi_ulong error;
1739

    
1740
        if (elf_ppnt->p_type != PT_LOAD)
1741
            continue;
1742

    
1743
        if (elf_ppnt->p_flags & PF_R) elf_prot |= PROT_READ;
1744
        if (elf_ppnt->p_flags & PF_W) elf_prot |= PROT_WRITE;
1745
        if (elf_ppnt->p_flags & PF_X) elf_prot |= PROT_EXEC;
1746
        elf_flags = MAP_PRIVATE | MAP_DENYWRITE;
1747
        if (elf_ex.e_type == ET_EXEC || load_addr_set) {
1748
            elf_flags |= MAP_FIXED;
1749
        } else if (elf_ex.e_type == ET_DYN) {
1750
            /* Try and get dynamic programs out of the way of the default mmap
1751
               base, as well as whatever program they might try to exec.  This
1752
               is because the brk will follow the loader, and is not movable.  */
1753
            /* NOTE: for qemu, we do a big mmap to get enough space
1754
               without hardcoding any address */
1755
            error = target_mmap(0, ET_DYN_MAP_SIZE,
1756
                                PROT_NONE, MAP_PRIVATE | MAP_ANON,
1757
                                -1, 0);
1758
            if (error == -1) {
1759
                perror("mmap");
1760
                exit(-1);
1761
            }
1762
            load_bias = TARGET_ELF_PAGESTART(error - elf_ppnt->p_vaddr);
1763
        }
1764

    
1765
        error = target_mmap(TARGET_ELF_PAGESTART(load_bias + elf_ppnt->p_vaddr),
1766
                            (elf_ppnt->p_filesz +
1767
                             TARGET_ELF_PAGEOFFSET(elf_ppnt->p_vaddr)),
1768
                            elf_prot,
1769
                            (MAP_FIXED | MAP_PRIVATE | MAP_DENYWRITE),
1770
                            bprm->fd,
1771
                            (elf_ppnt->p_offset -
1772
                             TARGET_ELF_PAGEOFFSET(elf_ppnt->p_vaddr)));
1773
        if (error == -1) {
1774
            perror("mmap");
1775
            exit(-1);
1776
        }
1777

    
1778
#ifdef LOW_ELF_STACK
1779
        if (TARGET_ELF_PAGESTART(elf_ppnt->p_vaddr) < elf_stack)
1780
            elf_stack = TARGET_ELF_PAGESTART(elf_ppnt->p_vaddr);
1781
#endif
1782

    
1783
        if (!load_addr_set) {
1784
            load_addr_set = 1;
1785
            load_addr = elf_ppnt->p_vaddr - elf_ppnt->p_offset;
1786
            if (elf_ex.e_type == ET_DYN) {
1787
                load_bias += error -
1788
                    TARGET_ELF_PAGESTART(load_bias + elf_ppnt->p_vaddr);
1789
                load_addr += load_bias;
1790
                reloc_func_desc = load_bias;
1791
            }
1792
        }
1793
        k = elf_ppnt->p_vaddr;
1794
        if (k < start_code)
1795
            start_code = k;
1796
        if (start_data < k)
1797
            start_data = k;
1798
        k = elf_ppnt->p_vaddr + elf_ppnt->p_filesz;
1799
        if ((elf_ppnt->p_flags & PF_X) && end_code <  k)
1800
            end_code = k;
1801
        if (end_data < k)
1802
            end_data = k;
1803
        k = elf_ppnt->p_vaddr + elf_ppnt->p_memsz;
1804
        if (k > elf_brk) {
1805
            elf_brk = TARGET_PAGE_ALIGN(k);
1806
        }
1807

    
1808
        /* If the load segment requests extra zeros (e.g. bss), map it.  */
1809
        if (elf_ppnt->p_filesz < elf_ppnt->p_memsz) {
1810
            abi_ulong base = load_bias + elf_ppnt->p_vaddr;
1811
            zero_bss(base + elf_ppnt->p_filesz,
1812
                     base + elf_ppnt->p_memsz, elf_prot);
1813
        }
1814
    }
1815

    
1816
    elf_entry += load_bias;
1817
    elf_brk += load_bias;
1818
    start_code += load_bias;
1819
    end_code += load_bias;
1820
    start_data += load_bias;
1821
    end_data += load_bias;
1822

    
1823
    if (elf_interpreter) {
1824
        if (interpreter_type & 1) {
1825
            elf_entry = load_aout_interp(&interp_ex, interpreter_fd);
1826
        }
1827
        else if (interpreter_type & 2) {
1828
            elf_entry = load_elf_interp(&interp_elf_ex, interpreter_fd,
1829
                                            &interp_load_addr);
1830
        }
1831
        reloc_func_desc = interp_load_addr;
1832

    
1833
        close(interpreter_fd);
1834
        free(elf_interpreter);
1835

    
1836
        if (elf_entry == ~((abi_ulong)0UL)) {
1837
            printf("Unable to load interpreter\n");
1838
            free(elf_phdata);
1839
            exit(-1);
1840
            return 0;
1841
        }
1842
    }
1843

    
1844
    free(elf_phdata);
1845

    
1846
    if (qemu_log_enabled())
1847
        load_symbols(&elf_ex, bprm->fd);
1848

    
1849
    if (interpreter_type != INTERPRETER_AOUT) close(bprm->fd);
1850
    info->personality = (ibcs2_interpreter ? PER_SVR4 : PER_LINUX);
1851

    
1852
#ifdef LOW_ELF_STACK
1853
    info->start_stack = bprm->p = elf_stack - 4;
1854
#endif
1855
    bprm->p = create_elf_tables(bprm->p,
1856
                    bprm->argc,
1857
                    bprm->envc,
1858
                    &elf_ex,
1859
                    load_addr, load_bias,
1860
                    interp_load_addr,
1861
                    (interpreter_type == INTERPRETER_AOUT ? 0 : 1),
1862
                    info);
1863
    info->load_addr = reloc_func_desc;
1864
    info->start_brk = info->brk = elf_brk;
1865
    info->end_code = end_code;
1866
    info->start_code = start_code;
1867
    info->start_data = start_data;
1868
    info->end_data = end_data;
1869
    info->start_stack = bprm->p;
1870

    
1871
#if 0
1872
    printf("(start_brk) %x\n" , info->start_brk);
1873
    printf("(end_code) %x\n" , info->end_code);
1874
    printf("(start_code) %x\n" , info->start_code);
1875
    printf("(end_data) %x\n" , info->end_data);
1876
    printf("(start_stack) %x\n" , info->start_stack);
1877
    printf("(brk) %x\n" , info->brk);
1878
#endif
1879

    
1880
    if ( info->personality == PER_SVR4 )
1881
    {
1882
            /* Why this, you ask???  Well SVr4 maps page 0 as read-only,
1883
               and some applications "depend" upon this behavior.
1884
               Since we do not have the power to recompile these, we
1885
               emulate the SVr4 behavior.  Sigh.  */
1886
            mapped_addr = target_mmap(0, qemu_host_page_size, PROT_READ | PROT_EXEC,
1887
                                      MAP_FIXED | MAP_PRIVATE, -1, 0);
1888
    }
1889

    
1890
    info->entry = elf_entry;
1891

    
1892
#ifdef USE_ELF_CORE_DUMP
1893
    bprm->core_dump = &elf_core_dump;
1894
#endif
1895

    
1896
    return 0;
1897
}
1898

    
1899
#ifdef USE_ELF_CORE_DUMP
1900

    
1901
/*
1902
 * Definitions to generate Intel SVR4-like core files.
1903
 * These mostly have the same names as the SVR4 types with "target_elf_"
1904
 * tacked on the front to prevent clashes with linux definitions,
1905
 * and the typedef forms have been avoided.  This is mostly like
1906
 * the SVR4 structure, but more Linuxy, with things that Linux does
1907
 * not support and which gdb doesn't really use excluded.
1908
 *
1909
 * Fields we don't dump (their contents is zero) in linux-user qemu
1910
 * are marked with XXX.
1911
 *
1912
 * Core dump code is copied from linux kernel (fs/binfmt_elf.c).
1913
 *
1914
 * Porting ELF coredump for target is (quite) simple process.  First you
1915
 * define USE_ELF_CORE_DUMP in target ELF code (where init_thread() for
1916
 * the target resides):
1917
 *
1918
 * #define USE_ELF_CORE_DUMP
1919
 *
1920
 * Next you define type of register set used for dumping.  ELF specification
1921
 * says that it needs to be array of elf_greg_t that has size of ELF_NREG.
1922
 *
1923
 * typedef <target_regtype> target_elf_greg_t;
1924
 * #define ELF_NREG <number of registers>
1925
 * typedef taret_elf_greg_t target_elf_gregset_t[ELF_NREG];
1926
 *
1927
 * Last step is to implement target specific function that copies registers
1928
 * from given cpu into just specified register set.  Prototype is:
1929
 *
1930
 * static void elf_core_copy_regs(taret_elf_gregset_t *regs,
1931
 *                                const CPUState *env);
1932
 *
1933
 * Parameters:
1934
 *     regs - copy register values into here (allocated and zeroed by caller)
1935
 *     env - copy registers from here
1936
 *
1937
 * Example for ARM target is provided in this file.
1938
 */
1939

    
1940
/* An ELF note in memory */
1941
struct memelfnote {
1942
    const char *name;
1943
    size_t     namesz;
1944
    size_t     namesz_rounded;
1945
    int        type;
1946
    size_t     datasz;
1947
    void       *data;
1948
    size_t     notesz;
1949
};
1950

    
1951
struct target_elf_siginfo {
1952
    int  si_signo; /* signal number */
1953
    int  si_code;  /* extra code */
1954
    int  si_errno; /* errno */
1955
};
1956

    
1957
struct target_elf_prstatus {
1958
    struct target_elf_siginfo pr_info;      /* Info associated with signal */
1959
    short              pr_cursig;    /* Current signal */
1960
    target_ulong       pr_sigpend;   /* XXX */
1961
    target_ulong       pr_sighold;   /* XXX */
1962
    target_pid_t       pr_pid;
1963
    target_pid_t       pr_ppid;
1964
    target_pid_t       pr_pgrp;
1965
    target_pid_t       pr_sid;
1966
    struct target_timeval pr_utime;  /* XXX User time */
1967
    struct target_timeval pr_stime;  /* XXX System time */
1968
    struct target_timeval pr_cutime; /* XXX Cumulative user time */
1969
    struct target_timeval pr_cstime; /* XXX Cumulative system time */
1970
    target_elf_gregset_t      pr_reg;       /* GP registers */
1971
    int                pr_fpvalid;   /* XXX */
1972
};
1973

    
1974
#define ELF_PRARGSZ     (80) /* Number of chars for args */
1975

    
1976
struct target_elf_prpsinfo {
1977
    char         pr_state;       /* numeric process state */
1978
    char         pr_sname;       /* char for pr_state */
1979
    char         pr_zomb;        /* zombie */
1980
    char         pr_nice;        /* nice val */
1981
    target_ulong pr_flag;        /* flags */
1982
    target_uid_t pr_uid;
1983
    target_gid_t pr_gid;
1984
    target_pid_t pr_pid, pr_ppid, pr_pgrp, pr_sid;
1985
    /* Lots missing */
1986
    char    pr_fname[16];           /* filename of executable */
1987
    char    pr_psargs[ELF_PRARGSZ]; /* initial part of arg list */
1988
};
1989

    
1990
/* Here is the structure in which status of each thread is captured. */
1991
struct elf_thread_status {
1992
    QTAILQ_ENTRY(elf_thread_status)  ets_link;
1993
    struct target_elf_prstatus prstatus;   /* NT_PRSTATUS */
1994
#if 0
1995
    elf_fpregset_t fpu;             /* NT_PRFPREG */
1996
    struct task_struct *thread;
1997
    elf_fpxregset_t xfpu;           /* ELF_CORE_XFPREG_TYPE */
1998
#endif
1999
    struct memelfnote notes[1];
2000
    int num_notes;
2001
};
2002

    
2003
struct elf_note_info {
2004
    struct memelfnote   *notes;
2005
    struct target_elf_prstatus *prstatus;  /* NT_PRSTATUS */
2006
    struct target_elf_prpsinfo *psinfo;    /* NT_PRPSINFO */
2007

    
2008
    QTAILQ_HEAD(thread_list_head, elf_thread_status) thread_list;
2009
#if 0
2010
    /*
2011
     * Current version of ELF coredump doesn't support
2012
     * dumping fp regs etc.
2013
     */
2014
    elf_fpregset_t *fpu;
2015
    elf_fpxregset_t *xfpu;
2016
    int thread_status_size;
2017
#endif
2018
    int notes_size;
2019
    int numnote;
2020
};
2021

    
2022
struct vm_area_struct {
2023
    abi_ulong   vma_start;  /* start vaddr of memory region */
2024
    abi_ulong   vma_end;    /* end vaddr of memory region */
2025
    abi_ulong   vma_flags;  /* protection etc. flags for the region */
2026
    QTAILQ_ENTRY(vm_area_struct) vma_link;
2027
};
2028

    
2029
struct mm_struct {
2030
    QTAILQ_HEAD(, vm_area_struct) mm_mmap;
2031
    int mm_count;           /* number of mappings */
2032
};
2033

    
2034
static struct mm_struct *vma_init(void);
2035
static void vma_delete(struct mm_struct *);
2036
static int vma_add_mapping(struct mm_struct *, abi_ulong,
2037
    abi_ulong, abi_ulong);
2038
static int vma_get_mapping_count(const struct mm_struct *);
2039
static struct vm_area_struct *vma_first(const struct mm_struct *);
2040
static struct vm_area_struct *vma_next(struct vm_area_struct *);
2041
static abi_ulong vma_dump_size(const struct vm_area_struct *);
2042
static int vma_walker(void *priv, abi_ulong start, abi_ulong end,
2043
    unsigned long flags);
2044

    
2045
static void fill_elf_header(struct elfhdr *, int, uint16_t, uint32_t);
2046
static void fill_note(struct memelfnote *, const char *, int,
2047
    unsigned int, void *);
2048
static void fill_prstatus(struct target_elf_prstatus *, const TaskState *, int);
2049
static int fill_psinfo(struct target_elf_prpsinfo *, const TaskState *);
2050
static void fill_auxv_note(struct memelfnote *, const TaskState *);
2051
static void fill_elf_note_phdr(struct elf_phdr *, int, off_t);
2052
static size_t note_size(const struct memelfnote *);
2053
static void free_note_info(struct elf_note_info *);
2054
static int fill_note_info(struct elf_note_info *, long, const CPUState *);
2055
static void fill_thread_info(struct elf_note_info *, const CPUState *);
2056
static int core_dump_filename(const TaskState *, char *, size_t);
2057

    
2058
static int dump_write(int, const void *, size_t);
2059
static int write_note(struct memelfnote *, int);
2060
static int write_note_info(struct elf_note_info *, int);
2061

    
2062
#ifdef BSWAP_NEEDED
2063
static void bswap_prstatus(struct target_elf_prstatus *);
2064
static void bswap_psinfo(struct target_elf_prpsinfo *);
2065

    
2066
static void bswap_prstatus(struct target_elf_prstatus *prstatus)
2067
{
2068
    prstatus->pr_info.si_signo = tswapl(prstatus->pr_info.si_signo);
2069
    prstatus->pr_info.si_code = tswapl(prstatus->pr_info.si_code);
2070
    prstatus->pr_info.si_errno = tswapl(prstatus->pr_info.si_errno);
2071
    prstatus->pr_cursig = tswap16(prstatus->pr_cursig);
2072
    prstatus->pr_sigpend = tswapl(prstatus->pr_sigpend);
2073
    prstatus->pr_sighold = tswapl(prstatus->pr_sighold);
2074
    prstatus->pr_pid = tswap32(prstatus->pr_pid);
2075
    prstatus->pr_ppid = tswap32(prstatus->pr_ppid);
2076
    prstatus->pr_pgrp = tswap32(prstatus->pr_pgrp);
2077
    prstatus->pr_sid = tswap32(prstatus->pr_sid);
2078
    /* cpu times are not filled, so we skip them */
2079
    /* regs should be in correct format already */
2080
    prstatus->pr_fpvalid = tswap32(prstatus->pr_fpvalid);
2081
}
2082

    
2083
static void bswap_psinfo(struct target_elf_prpsinfo *psinfo)
2084
{
2085
    psinfo->pr_flag = tswapl(psinfo->pr_flag);
2086
    psinfo->pr_uid = tswap16(psinfo->pr_uid);
2087
    psinfo->pr_gid = tswap16(psinfo->pr_gid);
2088
    psinfo->pr_pid = tswap32(psinfo->pr_pid);
2089
    psinfo->pr_ppid = tswap32(psinfo->pr_ppid);
2090
    psinfo->pr_pgrp = tswap32(psinfo->pr_pgrp);
2091
    psinfo->pr_sid = tswap32(psinfo->pr_sid);
2092
}
2093
#endif /* BSWAP_NEEDED */
2094

    
2095
/*
2096
 * Minimal support for linux memory regions.  These are needed
2097
 * when we are finding out what memory exactly belongs to
2098
 * emulated process.  No locks needed here, as long as
2099
 * thread that received the signal is stopped.
2100
 */
2101

    
2102
static struct mm_struct *vma_init(void)
2103
{
2104
    struct mm_struct *mm;
2105

    
2106
    if ((mm = qemu_malloc(sizeof (*mm))) == NULL)
2107
        return (NULL);
2108

    
2109
    mm->mm_count = 0;
2110
    QTAILQ_INIT(&mm->mm_mmap);
2111

    
2112
    return (mm);
2113
}
2114

    
2115
static void vma_delete(struct mm_struct *mm)
2116
{
2117
    struct vm_area_struct *vma;
2118

    
2119
    while ((vma = vma_first(mm)) != NULL) {
2120
        QTAILQ_REMOVE(&mm->mm_mmap, vma, vma_link);
2121
        qemu_free(vma);
2122
    }
2123
    qemu_free(mm);
2124
}
2125

    
2126
static int vma_add_mapping(struct mm_struct *mm, abi_ulong start,
2127
    abi_ulong end, abi_ulong flags)
2128
{
2129
    struct vm_area_struct *vma;
2130

    
2131
    if ((vma = qemu_mallocz(sizeof (*vma))) == NULL)
2132
        return (-1);
2133

    
2134
    vma->vma_start = start;
2135
    vma->vma_end = end;
2136
    vma->vma_flags = flags;
2137

    
2138
    QTAILQ_INSERT_TAIL(&mm->mm_mmap, vma, vma_link);
2139
    mm->mm_count++;
2140

    
2141
    return (0);
2142
}
2143

    
2144
static struct vm_area_struct *vma_first(const struct mm_struct *mm)
2145
{
2146
    return (QTAILQ_FIRST(&mm->mm_mmap));
2147
}
2148

    
2149
static struct vm_area_struct *vma_next(struct vm_area_struct *vma)
2150
{
2151
    return (QTAILQ_NEXT(vma, vma_link));
2152
}
2153

    
2154
static int vma_get_mapping_count(const struct mm_struct *mm)
2155
{
2156
    return (mm->mm_count);
2157
}
2158

    
2159
/*
2160
 * Calculate file (dump) size of given memory region.
2161
 */
2162
static abi_ulong vma_dump_size(const struct vm_area_struct *vma)
2163
{
2164
    /* if we cannot even read the first page, skip it */
2165
    if (!access_ok(VERIFY_READ, vma->vma_start, TARGET_PAGE_SIZE))
2166
        return (0);
2167

    
2168
    /*
2169
     * Usually we don't dump executable pages as they contain
2170
     * non-writable code that debugger can read directly from
2171
     * target library etc.  However, thread stacks are marked
2172
     * also executable so we read in first page of given region
2173
     * and check whether it contains elf header.  If there is
2174
     * no elf header, we dump it.
2175
     */
2176
    if (vma->vma_flags & PROT_EXEC) {
2177
        char page[TARGET_PAGE_SIZE];
2178

    
2179
        copy_from_user(page, vma->vma_start, sizeof (page));
2180
        if ((page[EI_MAG0] == ELFMAG0) &&
2181
            (page[EI_MAG1] == ELFMAG1) &&
2182
            (page[EI_MAG2] == ELFMAG2) &&
2183
            (page[EI_MAG3] == ELFMAG3)) {
2184
            /*
2185
             * Mappings are possibly from ELF binary.  Don't dump
2186
             * them.
2187
             */
2188
            return (0);
2189
        }
2190
    }
2191

    
2192
    return (vma->vma_end - vma->vma_start);
2193
}
2194

    
2195
static int vma_walker(void *priv, abi_ulong start, abi_ulong end,
2196
    unsigned long flags)
2197
{
2198
    struct mm_struct *mm = (struct mm_struct *)priv;
2199

    
2200
    vma_add_mapping(mm, start, end, flags);
2201
    return (0);
2202
}
2203

    
2204
static void fill_note(struct memelfnote *note, const char *name, int type,
2205
    unsigned int sz, void *data)
2206
{
2207
    unsigned int namesz;
2208

    
2209
    namesz = strlen(name) + 1;
2210
    note->name = name;
2211
    note->namesz = namesz;
2212
    note->namesz_rounded = roundup(namesz, sizeof (int32_t));
2213
    note->type = type;
2214
    note->datasz = roundup(sz, sizeof (int32_t));;
2215
    note->data = data;
2216

    
2217
    /*
2218
     * We calculate rounded up note size here as specified by
2219
     * ELF document.
2220
     */
2221
    note->notesz = sizeof (struct elf_note) +
2222
        note->namesz_rounded + note->datasz;
2223
}
2224

    
2225
static void fill_elf_header(struct elfhdr *elf, int segs, uint16_t machine,
2226
    uint32_t flags)
2227
{
2228
    (void) memset(elf, 0, sizeof(*elf));
2229

    
2230
    (void) memcpy(elf->e_ident, ELFMAG, SELFMAG);
2231
    elf->e_ident[EI_CLASS] = ELF_CLASS;
2232
    elf->e_ident[EI_DATA] = ELF_DATA;
2233
    elf->e_ident[EI_VERSION] = EV_CURRENT;
2234
    elf->e_ident[EI_OSABI] = ELF_OSABI;
2235

    
2236
    elf->e_type = ET_CORE;
2237
    elf->e_machine = machine;
2238
    elf->e_version = EV_CURRENT;
2239
    elf->e_phoff = sizeof(struct elfhdr);
2240
    elf->e_flags = flags;
2241
    elf->e_ehsize = sizeof(struct elfhdr);
2242
    elf->e_phentsize = sizeof(struct elf_phdr);
2243
    elf->e_phnum = segs;
2244

    
2245
#ifdef BSWAP_NEEDED
2246
    bswap_ehdr(elf);
2247
#endif
2248
}
2249

    
2250
static void fill_elf_note_phdr(struct elf_phdr *phdr, int sz, off_t offset)
2251
{
2252
    phdr->p_type = PT_NOTE;
2253
    phdr->p_offset = offset;
2254
    phdr->p_vaddr = 0;
2255
    phdr->p_paddr = 0;
2256
    phdr->p_filesz = sz;
2257
    phdr->p_memsz = 0;
2258
    phdr->p_flags = 0;
2259
    phdr->p_align = 0;
2260

    
2261
#ifdef BSWAP_NEEDED
2262
    bswap_phdr(phdr);
2263
#endif
2264
}
2265

    
2266
static size_t note_size(const struct memelfnote *note)
2267
{
2268
    return (note->notesz);
2269
}
2270

    
2271
static void fill_prstatus(struct target_elf_prstatus *prstatus,
2272
    const TaskState *ts, int signr)
2273
{
2274
    (void) memset(prstatus, 0, sizeof (*prstatus));
2275
    prstatus->pr_info.si_signo = prstatus->pr_cursig = signr;
2276
    prstatus->pr_pid = ts->ts_tid;
2277
    prstatus->pr_ppid = getppid();
2278
    prstatus->pr_pgrp = getpgrp();
2279
    prstatus->pr_sid = getsid(0);
2280

    
2281
#ifdef BSWAP_NEEDED
2282
    bswap_prstatus(prstatus);
2283
#endif
2284
}
2285

    
2286
static int fill_psinfo(struct target_elf_prpsinfo *psinfo, const TaskState *ts)
2287
{
2288
    char *filename, *base_filename;
2289
    unsigned int i, len;
2290

    
2291
    (void) memset(psinfo, 0, sizeof (*psinfo));
2292

    
2293
    len = ts->info->arg_end - ts->info->arg_start;
2294
    if (len >= ELF_PRARGSZ)
2295
        len = ELF_PRARGSZ - 1;
2296
    if (copy_from_user(&psinfo->pr_psargs, ts->info->arg_start, len))
2297
        return -EFAULT;
2298
    for (i = 0; i < len; i++)
2299
        if (psinfo->pr_psargs[i] == 0)
2300
            psinfo->pr_psargs[i] = ' ';
2301
    psinfo->pr_psargs[len] = 0;
2302

    
2303
    psinfo->pr_pid = getpid();
2304
    psinfo->pr_ppid = getppid();
2305
    psinfo->pr_pgrp = getpgrp();
2306
    psinfo->pr_sid = getsid(0);
2307
    psinfo->pr_uid = getuid();
2308
    psinfo->pr_gid = getgid();
2309

    
2310
    filename = strdup(ts->bprm->filename);
2311
    base_filename = strdup(basename(filename));
2312
    (void) strncpy(psinfo->pr_fname, base_filename,
2313
        sizeof(psinfo->pr_fname));
2314
    free(base_filename);
2315
    free(filename);
2316

    
2317
#ifdef BSWAP_NEEDED
2318
    bswap_psinfo(psinfo);
2319
#endif
2320
    return (0);
2321
}
2322

    
2323
static void fill_auxv_note(struct memelfnote *note, const TaskState *ts)
2324
{
2325
    elf_addr_t auxv = (elf_addr_t)ts->info->saved_auxv;
2326
    elf_addr_t orig_auxv = auxv;
2327
    abi_ulong val;
2328
    void *ptr;
2329
    int i, len;
2330

    
2331
    /*
2332
     * Auxiliary vector is stored in target process stack.  It contains
2333
     * {type, value} pairs that we need to dump into note.  This is not
2334
     * strictly necessary but we do it here for sake of completeness.
2335
     */
2336

    
2337
    /* find out lenght of the vector, AT_NULL is terminator */
2338
    i = len = 0;
2339
    do {
2340
        get_user_ual(val, auxv);
2341
        i += 2;
2342
        auxv += 2 * sizeof (elf_addr_t);
2343
    } while (val != AT_NULL);
2344
    len = i * sizeof (elf_addr_t);
2345

    
2346
    /* read in whole auxv vector and copy it to memelfnote */
2347
    ptr = lock_user(VERIFY_READ, orig_auxv, len, 0);
2348
    if (ptr != NULL) {
2349
        fill_note(note, "CORE", NT_AUXV, len, ptr);
2350
        unlock_user(ptr, auxv, len);
2351
    }
2352
}
2353

    
2354
/*
2355
 * Constructs name of coredump file.  We have following convention
2356
 * for the name:
2357
 *     qemu_<basename-of-target-binary>_<date>-<time>_<pid>.core
2358
 *
2359
 * Returns 0 in case of success, -1 otherwise (errno is set).
2360
 */
2361
static int core_dump_filename(const TaskState *ts, char *buf,
2362
    size_t bufsize)
2363
{
2364
    char timestamp[64];
2365
    char *filename = NULL;
2366
    char *base_filename = NULL;
2367
    struct timeval tv;
2368
    struct tm tm;
2369

    
2370
    assert(bufsize >= PATH_MAX);
2371

    
2372
    if (gettimeofday(&tv, NULL) < 0) {
2373
        (void) fprintf(stderr, "unable to get current timestamp: %s",
2374
            strerror(errno));
2375
        return (-1);
2376
    }
2377

    
2378
    filename = strdup(ts->bprm->filename);
2379
    base_filename = strdup(basename(filename));
2380
    (void) strftime(timestamp, sizeof (timestamp), "%Y%m%d-%H%M%S",
2381
        localtime_r(&tv.tv_sec, &tm));
2382
    (void) snprintf(buf, bufsize, "qemu_%s_%s_%d.core",
2383
        base_filename, timestamp, (int)getpid());
2384
    free(base_filename);
2385
    free(filename);
2386

    
2387
    return (0);
2388
}
2389

    
2390
static int dump_write(int fd, const void *ptr, size_t size)
2391
{
2392
    const char *bufp = (const char *)ptr;
2393
    ssize_t bytes_written, bytes_left;
2394
    struct rlimit dumpsize;
2395
    off_t pos;
2396

    
2397
    bytes_written = 0;
2398
    getrlimit(RLIMIT_CORE, &dumpsize);
2399
    if ((pos = lseek(fd, 0, SEEK_CUR))==-1) {
2400
        if (errno == ESPIPE) { /* not a seekable stream */
2401
            bytes_left = size;
2402
        } else {
2403
            return pos;
2404
        }
2405
    } else {
2406
        if (dumpsize.rlim_cur <= pos) {
2407
            return -1;
2408
        } else if (dumpsize.rlim_cur == RLIM_INFINITY) {
2409
            bytes_left = size;
2410
        } else {
2411
            size_t limit_left=dumpsize.rlim_cur - pos;
2412
            bytes_left = limit_left >= size ? size : limit_left ;
2413
        }
2414
    }
2415

    
2416
    /*
2417
     * In normal conditions, single write(2) should do but
2418
     * in case of socket etc. this mechanism is more portable.
2419
     */
2420
    do {
2421
        bytes_written = write(fd, bufp, bytes_left);
2422
        if (bytes_written < 0) {
2423
            if (errno == EINTR)
2424
                continue;
2425
            return (-1);
2426
        } else if (bytes_written == 0) { /* eof */
2427
            return (-1);
2428
        }
2429
        bufp += bytes_written;
2430
        bytes_left -= bytes_written;
2431
    } while (bytes_left > 0);
2432

    
2433
    return (0);
2434
}
2435

    
2436
static int write_note(struct memelfnote *men, int fd)
2437
{
2438
    struct elf_note en;
2439

    
2440
    en.n_namesz = men->namesz;
2441
    en.n_type = men->type;
2442
    en.n_descsz = men->datasz;
2443

    
2444
#ifdef BSWAP_NEEDED
2445
    bswap_note(&en);
2446
#endif
2447

    
2448
    if (dump_write(fd, &en, sizeof(en)) != 0)
2449
        return (-1);
2450
    if (dump_write(fd, men->name, men->namesz_rounded) != 0)
2451
        return (-1);
2452
    if (dump_write(fd, men->data, men->datasz) != 0)
2453
        return (-1);
2454

    
2455
    return (0);
2456
}
2457

    
2458
static void fill_thread_info(struct elf_note_info *info, const CPUState *env)
2459
{
2460
    TaskState *ts = (TaskState *)env->opaque;
2461
    struct elf_thread_status *ets;
2462

    
2463
    ets = qemu_mallocz(sizeof (*ets));
2464
    ets->num_notes = 1; /* only prstatus is dumped */
2465
    fill_prstatus(&ets->prstatus, ts, 0);
2466
    elf_core_copy_regs(&ets->prstatus.pr_reg, env);
2467
    fill_note(&ets->notes[0], "CORE", NT_PRSTATUS, sizeof (ets->prstatus),
2468
        &ets->prstatus);
2469

    
2470
    QTAILQ_INSERT_TAIL(&info->thread_list, ets, ets_link);
2471

    
2472
    info->notes_size += note_size(&ets->notes[0]);
2473
}
2474

    
2475
static int fill_note_info(struct elf_note_info *info,
2476
    long signr, const CPUState *env)
2477
{
2478
#define NUMNOTES 3
2479
    CPUState *cpu = NULL;
2480
    TaskState *ts = (TaskState *)env->opaque;
2481
    int i;
2482

    
2483
    (void) memset(info, 0, sizeof (*info));
2484

    
2485
    QTAILQ_INIT(&info->thread_list);
2486

    
2487
    info->notes = qemu_mallocz(NUMNOTES * sizeof (struct memelfnote));
2488
    if (info->notes == NULL)
2489
        return (-ENOMEM);
2490
    info->prstatus = qemu_mallocz(sizeof (*info->prstatus));
2491
    if (info->prstatus == NULL)
2492
        return (-ENOMEM);
2493
    info->psinfo = qemu_mallocz(sizeof (*info->psinfo));
2494
    if (info->prstatus == NULL)
2495
        return (-ENOMEM);
2496

    
2497
    /*
2498
     * First fill in status (and registers) of current thread
2499
     * including process info & aux vector.
2500
     */
2501
    fill_prstatus(info->prstatus, ts, signr);
2502
    elf_core_copy_regs(&info->prstatus->pr_reg, env);
2503
    fill_note(&info->notes[0], "CORE", NT_PRSTATUS,
2504
        sizeof (*info->prstatus), info->prstatus);
2505
    fill_psinfo(info->psinfo, ts);
2506
    fill_note(&info->notes[1], "CORE", NT_PRPSINFO,
2507
        sizeof (*info->psinfo), info->psinfo);
2508
    fill_auxv_note(&info->notes[2], ts);
2509
    info->numnote = 3;
2510

    
2511
    info->notes_size = 0;
2512
    for (i = 0; i < info->numnote; i++)
2513
        info->notes_size += note_size(&info->notes[i]);
2514

    
2515
    /* read and fill status of all threads */
2516
    cpu_list_lock();
2517
    for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
2518
        if (cpu == thread_env)
2519
            continue;
2520
        fill_thread_info(info, cpu);
2521
    }
2522
    cpu_list_unlock();
2523

    
2524
    return (0);
2525
}
2526

    
2527
static void free_note_info(struct elf_note_info *info)
2528
{
2529
    struct elf_thread_status *ets;
2530

    
2531
    while (!QTAILQ_EMPTY(&info->thread_list)) {
2532
        ets = QTAILQ_FIRST(&info->thread_list);
2533
        QTAILQ_REMOVE(&info->thread_list, ets, ets_link);
2534
        qemu_free(ets);
2535
    }
2536

    
2537
    qemu_free(info->prstatus);
2538
    qemu_free(info->psinfo);
2539
    qemu_free(info->notes);
2540
}
2541

    
2542
static int write_note_info(struct elf_note_info *info, int fd)
2543
{
2544
    struct elf_thread_status *ets;
2545
    int i, error = 0;
2546

    
2547
    /* write prstatus, psinfo and auxv for current thread */
2548
    for (i = 0; i < info->numnote; i++)
2549
        if ((error = write_note(&info->notes[i], fd)) != 0)
2550
            return (error);
2551

    
2552
    /* write prstatus for each thread */
2553
    for (ets = info->thread_list.tqh_first; ets != NULL;
2554
        ets = ets->ets_link.tqe_next) {
2555
        if ((error = write_note(&ets->notes[0], fd)) != 0)
2556
            return (error);
2557
    }
2558

    
2559
    return (0);
2560
}
2561

    
2562
/*
2563
 * Write out ELF coredump.
2564
 *
2565
 * See documentation of ELF object file format in:
2566
 * http://www.caldera.com/developers/devspecs/gabi41.pdf
2567
 *
2568
 * Coredump format in linux is following:
2569
 *
2570
 * 0   +----------------------+         \
2571
 *     | ELF header           | ET_CORE  |
2572
 *     +----------------------+          |
2573
 *     | ELF program headers  |          |--- headers
2574
 *     | - NOTE section       |          |
2575
 *     | - PT_LOAD sections   |          |
2576
 *     +----------------------+         /
2577
 *     | NOTEs:               |
2578
 *     | - NT_PRSTATUS        |
2579
 *     | - NT_PRSINFO         |
2580
 *     | - NT_AUXV            |
2581
 *     +----------------------+ <-- aligned to target page
2582
 *     | Process memory dump  |
2583
 *     :                      :
2584
 *     .                      .
2585
 *     :                      :
2586
 *     |                      |
2587
 *     +----------------------+
2588
 *
2589
 * NT_PRSTATUS -> struct elf_prstatus (per thread)
2590
 * NT_PRSINFO  -> struct elf_prpsinfo
2591
 * NT_AUXV is array of { type, value } pairs (see fill_auxv_note()).
2592
 *
2593
 * Format follows System V format as close as possible.  Current
2594
 * version limitations are as follows:
2595
 *     - no floating point registers are dumped
2596
 *
2597
 * Function returns 0 in case of success, negative errno otherwise.
2598
 *
2599
 * TODO: make this work also during runtime: it should be
2600
 * possible to force coredump from running process and then
2601
 * continue processing.  For example qemu could set up SIGUSR2
2602
 * handler (provided that target process haven't registered
2603
 * handler for that) that does the dump when signal is received.
2604
 */
2605
static int elf_core_dump(int signr, const CPUState *env)
2606
{
2607
    const TaskState *ts = (const TaskState *)env->opaque;
2608
    struct vm_area_struct *vma = NULL;
2609
    char corefile[PATH_MAX];
2610
    struct elf_note_info info;
2611
    struct elfhdr elf;
2612
    struct elf_phdr phdr;
2613
    struct rlimit dumpsize;
2614
    struct mm_struct *mm = NULL;
2615
    off_t offset = 0, data_offset = 0;
2616
    int segs = 0;
2617
    int fd = -1;
2618

    
2619
    errno = 0;
2620
    getrlimit(RLIMIT_CORE, &dumpsize);
2621
    if (dumpsize.rlim_cur == 0)
2622
       return 0;
2623

    
2624
    if (core_dump_filename(ts, corefile, sizeof (corefile)) < 0)
2625
        return (-errno);
2626

    
2627
    if ((fd = open(corefile, O_WRONLY | O_CREAT,
2628
        S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0)
2629
        return (-errno);
2630

    
2631
    /*
2632
     * Walk through target process memory mappings and
2633
     * set up structure containing this information.  After
2634
     * this point vma_xxx functions can be used.
2635
     */
2636
    if ((mm = vma_init()) == NULL)
2637
        goto out;
2638

    
2639
    walk_memory_regions(mm, vma_walker);
2640
    segs = vma_get_mapping_count(mm);
2641

    
2642
    /*
2643
     * Construct valid coredump ELF header.  We also
2644
     * add one more segment for notes.
2645
     */
2646
    fill_elf_header(&elf, segs + 1, ELF_MACHINE, 0);
2647
    if (dump_write(fd, &elf, sizeof (elf)) != 0)
2648
        goto out;
2649

    
2650
    /* fill in in-memory version of notes */
2651
    if (fill_note_info(&info, signr, env) < 0)
2652
        goto out;
2653

    
2654
    offset += sizeof (elf);                             /* elf header */
2655
    offset += (segs + 1) * sizeof (struct elf_phdr);    /* program headers */
2656

    
2657
    /* write out notes program header */
2658
    fill_elf_note_phdr(&phdr, info.notes_size, offset);
2659

    
2660
    offset += info.notes_size;
2661
    if (dump_write(fd, &phdr, sizeof (phdr)) != 0)
2662
        goto out;
2663

    
2664
    /*
2665
     * ELF specification wants data to start at page boundary so
2666
     * we align it here.
2667
     */
2668
    offset = roundup(offset, ELF_EXEC_PAGESIZE);
2669

    
2670
    /*
2671
     * Write program headers for memory regions mapped in
2672
     * the target process.
2673
     */
2674
    for (vma = vma_first(mm); vma != NULL; vma = vma_next(vma)) {
2675
        (void) memset(&phdr, 0, sizeof (phdr));
2676

    
2677
        phdr.p_type = PT_LOAD;
2678
        phdr.p_offset = offset;
2679
        phdr.p_vaddr = vma->vma_start;
2680
        phdr.p_paddr = 0;
2681
        phdr.p_filesz = vma_dump_size(vma);
2682
        offset += phdr.p_filesz;
2683
        phdr.p_memsz = vma->vma_end - vma->vma_start;
2684
        phdr.p_flags = vma->vma_flags & PROT_READ ? PF_R : 0;
2685
        if (vma->vma_flags & PROT_WRITE)
2686
            phdr.p_flags |= PF_W;
2687
        if (vma->vma_flags & PROT_EXEC)
2688
            phdr.p_flags |= PF_X;
2689
        phdr.p_align = ELF_EXEC_PAGESIZE;
2690

    
2691
        dump_write(fd, &phdr, sizeof (phdr));
2692
    }
2693

    
2694
    /*
2695
     * Next we write notes just after program headers.  No
2696
     * alignment needed here.
2697
     */
2698
    if (write_note_info(&info, fd) < 0)
2699
        goto out;
2700

    
2701
    /* align data to page boundary */
2702
    data_offset = lseek(fd, 0, SEEK_CUR);
2703
    data_offset = TARGET_PAGE_ALIGN(data_offset);
2704
    if (lseek(fd, data_offset, SEEK_SET) != data_offset)
2705
        goto out;
2706

    
2707
    /*
2708
     * Finally we can dump process memory into corefile as well.
2709
     */
2710
    for (vma = vma_first(mm); vma != NULL; vma = vma_next(vma)) {
2711
        abi_ulong addr;
2712
        abi_ulong end;
2713

    
2714
        end = vma->vma_start + vma_dump_size(vma);
2715

    
2716
        for (addr = vma->vma_start; addr < end;
2717
            addr += TARGET_PAGE_SIZE) {
2718
            char page[TARGET_PAGE_SIZE];
2719
            int error;
2720

    
2721
            /*
2722
             *  Read in page from target process memory and
2723
             *  write it to coredump file.
2724
             */
2725
            error = copy_from_user(page, addr, sizeof (page));
2726
            if (error != 0) {
2727
                (void) fprintf(stderr, "unable to dump " TARGET_ABI_FMT_lx "\n",
2728
                    addr);
2729
                errno = -error;
2730
                goto out;
2731
            }
2732
            if (dump_write(fd, page, TARGET_PAGE_SIZE) < 0)
2733
                goto out;
2734
        }
2735
    }
2736

    
2737
out:
2738
    free_note_info(&info);
2739
    if (mm != NULL)
2740
        vma_delete(mm);
2741
    (void) close(fd);
2742

    
2743
    if (errno != 0)
2744
        return (-errno);
2745
    return (0);
2746
}
2747

    
2748
#endif /* USE_ELF_CORE_DUMP */
2749

    
2750
static int load_aout_interp(void * exptr, int interp_fd)
2751
{
2752
    printf("a.out interpreter not yet supported\n");
2753
    return(0);
2754
}
2755

    
2756
void do_init_thread(struct target_pt_regs *regs, struct image_info *infop)
2757
{
2758
    init_thread(regs, infop);
2759
}