Statistics
| Branch: | Revision:

root / linux-user / elfload.c @ 9955ffac

History | View | Annotate | Download (82.9 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
40
                                           descriptors (signal handling) */
41
    MMAP_PAGE_ZERO =    0x0100000,
42
    ADDR_COMPAT_LAYOUT = 0x0200000,
43
    READ_IMPLIES_EXEC = 0x0400000,
44
    ADDR_LIMIT_32BIT =  0x0800000,
45
    SHORT_INODE =       0x1000000,
46
    WHOLE_SECONDS =     0x2000000,
47
    STICKY_TIMEOUTS =   0x4000000,
48
    ADDR_LIMIT_3GB =    0x8000000,
49
};
50

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

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

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

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

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

    
108
#ifdef TARGET_I386
109

    
110
#define ELF_PLATFORM get_elf_platform()
111

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

    
123
#define ELF_HWCAP get_elf_hwcap()
124

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

    
130
#ifdef TARGET_X86_64
131
#define ELF_START_MMAP 0x2aaaaab000ULL
132
#define elf_check_arch(x) ( ((x) == ELF_ARCH) )
133

    
134
#define ELF_CLASS      ELFCLASS64
135
#define ELF_DATA       ELFDATA2LSB
136
#define ELF_ARCH       EM_X86_64
137

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

    
145
#define ELF_NREG    27
146
typedef target_elf_greg_t  target_elf_gregset_t[ELF_NREG];
147

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

    
186
#else
187

    
188
#define ELF_START_MMAP 0x80000000
189

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

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

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

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

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

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

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

    
250
#define USE_ELF_CORE_DUMP
251
#define ELF_EXEC_PAGESIZE       4096
252

    
253
#endif
254

    
255
#ifdef TARGET_ARM
256

    
257
#define ELF_START_MMAP 0x80000000
258

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

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

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

    
379
#else
380
#define ELF_START_MMAP 0x80000000
381

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

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

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

    
398
#endif
399
#endif
400

    
401
#ifdef TARGET_PPC
402

    
403
#define ELF_START_MMAP 0x80000000
404

    
405
#if defined(TARGET_PPC64) && !defined(TARGET_ABI32)
406

    
407
#define elf_check_arch(x) ( (x) == EM_PPC64 )
408

    
409
#define ELF_CLASS       ELFCLASS64
410

    
411
#else
412

    
413
#define elf_check_arch(x) ( (x) == EM_PPC )
414

    
415
#define ELF_CLASS       ELFCLASS32
416

    
417
#endif
418

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

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

    
456
    QEMU_PPC_FEATURE_TRUE_LE = 0x00000002,
457
    QEMU_PPC_FEATURE_PPC_LE = 0x00000001,
458
};
459

    
460
#define ELF_HWCAP get_elf_hwcap()
461

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

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

    
481
    return features;
482
}
483

    
484
/*
485
 * The requirements here are:
486
 * - keep the final alignment of sp (sp & 0xf)
487
 * - make sure the 32-bit value at the first 16 byte aligned position of
488
 *   AUXV is greater than 16 for glibc compatibility.
489
 *   AT_IGNOREPPC is used for that.
490
 * - for compatibility with glibc ARCH_DLINFO must always be defined on PPC,
491
 *   even if DLINFO_ARCH_ITEMS goes to zero or is undefined.
492
 */
493
#define DLINFO_ARCH_ITEMS       5
494
#define ARCH_DLINFO                                     \
495
    do {                                                \
496
        NEW_AUX_ENT(AT_DCACHEBSIZE, 0x20);              \
497
        NEW_AUX_ENT(AT_ICACHEBSIZE, 0x20);              \
498
        NEW_AUX_ENT(AT_UCACHEBSIZE, 0);                 \
499
        /*                                              \
500
         * Now handle glibc compatibility.              \
501
         */                                             \
502
        NEW_AUX_ENT(AT_IGNOREPPC, AT_IGNOREPPC);        \
503
        NEW_AUX_ENT(AT_IGNOREPPC, AT_IGNOREPPC);        \
504
    } while (0)
505

    
506
static inline void init_thread(struct target_pt_regs *_regs, struct image_info *infop)
507
{
508
    _regs->gpr[1] = infop->start_stack;
509
#if defined(TARGET_PPC64) && !defined(TARGET_ABI32)
510
    _regs->gpr[2] = ldq_raw(infop->entry + 8) + infop->load_addr;
511
    infop->entry = ldq_raw(infop->entry) + infop->load_addr;
512
#endif
513
    _regs->nip = infop->entry;
514
}
515

    
516
/* See linux kernel: arch/powerpc/include/asm/elf.h.  */
517
#define ELF_NREG 48
518
typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
519

    
520
static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUState *env)
521
{
522
    int i;
523
    target_ulong ccr = 0;
524

    
525
    for (i = 0; i < ARRAY_SIZE(env->gpr); i++) {
526
        (*regs)[i] = tswapl(env->gpr[i]);
527
    }
528

    
529
    (*regs)[32] = tswapl(env->nip);
530
    (*regs)[33] = tswapl(env->msr);
531
    (*regs)[35] = tswapl(env->ctr);
532
    (*regs)[36] = tswapl(env->lr);
533
    (*regs)[37] = tswapl(env->xer);
534

    
535
    for (i = 0; i < ARRAY_SIZE(env->crf); i++) {
536
        ccr |= env->crf[i] << (32 - ((i + 1) * 4));
537
    }
538
    (*regs)[38] = tswapl(ccr);
539
}
540

    
541
#define USE_ELF_CORE_DUMP
542
#define ELF_EXEC_PAGESIZE       4096
543

    
544
#endif
545

    
546
#ifdef TARGET_MIPS
547

    
548
#define ELF_START_MMAP 0x80000000
549

    
550
#define elf_check_arch(x) ( (x) == EM_MIPS )
551

    
552
#ifdef TARGET_MIPS64
553
#define ELF_CLASS   ELFCLASS64
554
#else
555
#define ELF_CLASS   ELFCLASS32
556
#endif
557
#ifdef TARGET_WORDS_BIGENDIAN
558
#define ELF_DATA        ELFDATA2MSB
559
#else
560
#define ELF_DATA        ELFDATA2LSB
561
#endif
562
#define ELF_ARCH    EM_MIPS
563

    
564
static inline void init_thread(struct target_pt_regs *regs,
565
                               struct image_info *infop)
566
{
567
    regs->cp0_status = 2 << CP0St_KSU;
568
    regs->cp0_epc = infop->entry;
569
    regs->regs[29] = infop->start_stack;
570
}
571

    
572
/* See linux kernel: arch/mips/include/asm/elf.h.  */
573
#define ELF_NREG 45
574
typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
575

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

    
593
/* See linux kernel: arch/mips/kernel/process.c:elf_dump_regs.  */
594
static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUState *env)
595
{
596
    int i;
597

    
598
    for (i = 0; i < TARGET_EF_R0; i++) {
599
        (*regs)[i] = 0;
600
    }
601
    (*regs)[TARGET_EF_R0] = 0;
602

    
603
    for (i = 1; i < ARRAY_SIZE(env->active_tc.gpr); i++) {
604
        (*regs)[TARGET_EF_R0 + i] = tswapl(env->active_tc.gpr[i]);
605
    }
606

    
607
    (*regs)[TARGET_EF_R26] = 0;
608
    (*regs)[TARGET_EF_R27] = 0;
609
    (*regs)[TARGET_EF_LO] = tswapl(env->active_tc.LO[0]);
610
    (*regs)[TARGET_EF_HI] = tswapl(env->active_tc.HI[0]);
611
    (*regs)[TARGET_EF_CP0_EPC] = tswapl(env->active_tc.PC);
612
    (*regs)[TARGET_EF_CP0_BADVADDR] = tswapl(env->CP0_BadVAddr);
613
    (*regs)[TARGET_EF_CP0_STATUS] = tswapl(env->CP0_Status);
614
    (*regs)[TARGET_EF_CP0_CAUSE] = tswapl(env->CP0_Cause);
615
}
616

    
617
#define USE_ELF_CORE_DUMP
618
#define ELF_EXEC_PAGESIZE        4096
619

    
620
#endif /* TARGET_MIPS */
621

    
622
#ifdef TARGET_MICROBLAZE
623

    
624
#define ELF_START_MMAP 0x80000000
625

    
626
#define elf_check_arch(x) ( (x) == EM_MICROBLAZE || (x) == EM_MICROBLAZE_OLD)
627

    
628
#define ELF_CLASS   ELFCLASS32
629
#define ELF_DATA    ELFDATA2MSB
630
#define ELF_ARCH    EM_MICROBLAZE
631

    
632
static inline void init_thread(struct target_pt_regs *regs,
633
                               struct image_info *infop)
634
{
635
    regs->pc = infop->entry;
636
    regs->r1 = infop->start_stack;
637

    
638
}
639

    
640
#define ELF_EXEC_PAGESIZE        4096
641

    
642
#define USE_ELF_CORE_DUMP
643
#define ELF_NREG 38
644
typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
645

    
646
/* See linux kernel: arch/mips/kernel/process.c:elf_dump_regs.  */
647
static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUState *env)
648
{
649
    int i, pos = 0;
650

    
651
    for (i = 0; i < 32; i++) {
652
        (*regs)[pos++] = tswapl(env->regs[i]);
653
    }
654

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

    
660
#endif /* TARGET_MICROBLAZE */
661

    
662
#ifdef TARGET_SH4
663

    
664
#define ELF_START_MMAP 0x80000000
665

    
666
#define elf_check_arch(x) ( (x) == EM_SH )
667

    
668
#define ELF_CLASS ELFCLASS32
669
#define ELF_DATA  ELFDATA2LSB
670
#define ELF_ARCH  EM_SH
671

    
672
static inline void init_thread(struct target_pt_regs *regs,
673
                               struct image_info *infop)
674
{
675
    /* Check other registers XXXXX */
676
    regs->pc = infop->entry;
677
    regs->regs[15] = infop->start_stack;
678
}
679

    
680
/* See linux kernel: arch/sh/include/asm/elf.h.  */
681
#define ELF_NREG 23
682
typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
683

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

    
695
static inline void elf_core_copy_regs(target_elf_gregset_t *regs,
696
                                      const CPUState *env)
697
{
698
    int i;
699

    
700
    for (i = 0; i < 16; i++) {
701
        (*regs[i]) = tswapl(env->gregs[i]);
702
    }
703

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

    
713
#define USE_ELF_CORE_DUMP
714
#define ELF_EXEC_PAGESIZE        4096
715

    
716
#endif
717

    
718
#ifdef TARGET_CRIS
719

    
720
#define ELF_START_MMAP 0x80000000
721

    
722
#define elf_check_arch(x) ( (x) == EM_CRIS )
723

    
724
#define ELF_CLASS ELFCLASS32
725
#define ELF_DATA  ELFDATA2LSB
726
#define ELF_ARCH  EM_CRIS
727

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

    
734
#define ELF_EXEC_PAGESIZE        8192
735

    
736
#endif
737

    
738
#ifdef TARGET_M68K
739

    
740
#define ELF_START_MMAP 0x80000000
741

    
742
#define elf_check_arch(x) ( (x) == EM_68K )
743

    
744
#define ELF_CLASS       ELFCLASS32
745
#define ELF_DATA        ELFDATA2MSB
746
#define ELF_ARCH        EM_68K
747

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

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

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

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

    
787
#define USE_ELF_CORE_DUMP
788
#define ELF_EXEC_PAGESIZE       8192
789

    
790
#endif
791

    
792
#ifdef TARGET_ALPHA
793

    
794
#define ELF_START_MMAP (0x30000000000ULL)
795

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

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

    
802
static inline void init_thread(struct target_pt_regs *regs,
803
                               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
                                 char bprm_buf[BPRM_BUF_SIZE])
1164
{
1165
    struct elf_phdr *elf_phdata  =  NULL;
1166
    struct elf_phdr *eppnt;
1167
    abi_ulong load_addr = 0;
1168
    int load_addr_set = 0;
1169
    int retval;
1170
    abi_ulong error;
1171
    int i;
1172

    
1173
    error = 0;
1174

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

    
1185

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

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

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

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

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

    
1206
    i = interp_elf_ex->e_phnum * sizeof(struct elf_phdr);
1207
    if (interp_elf_ex->e_phoff + i <= BPRM_BUF_SIZE) {
1208
        memcpy(elf_phdata, bprm_buf + interp_elf_ex->e_phoff, i);
1209
    } else {
1210
        retval = pread(interpreter_fd, elf_phdata, i, interp_elf_ex->e_phoff);
1211
        if (retval != i) {
1212
            perror("load_elf_interp");
1213
            exit(-1);
1214
        }
1215
    }
1216
#ifdef BSWAP_NEEDED
1217
    eppnt = elf_phdata;
1218
    for (i=0; i<interp_elf_ex->e_phnum; i++, eppnt++) {
1219
        bswap_phdr(eppnt);
1220
    }
1221
#endif
1222

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

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

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

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

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

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

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

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

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

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

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

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

    
1312
    key.st_value = orig_addr;
1313

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

    
1319
    return "";
1320
}
1321

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1472
    i = elf_ex.e_phnum * sizeof(struct elf_phdr);
1473
    if (elf_ex.e_phoff + i <= BPRM_BUF_SIZE) {
1474
        memcpy(elf_phdata, bprm->buf + elf_ex.e_phoff, i);
1475
    } else {
1476
        retval = pread(bprm->fd, (char *) elf_phdata, i, elf_ex.e_phoff);
1477
        if (retval != i) {
1478
            perror("load_elf_binary");
1479
            exit(-1);
1480
        }
1481
    }
1482

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

    
1491
    elf_brk = 0;
1492

    
1493
    elf_stack = ~((abi_ulong)0UL);
1494
    elf_interpreter = NULL;
1495
    start_code = ~((abi_ulong)0UL);
1496
    end_code = 0;
1497
    start_data = 0;
1498
    end_data = 0;
1499
    interp_ex.a_info = 0;
1500

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

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

    
1516
            elf_interpreter = (char *)malloc(elf_ppnt->p_filesz);
1517

    
1518
            if (elf_interpreter == NULL) {
1519
                free (elf_phdata);
1520
                close(bprm->fd);
1521
                return -ENOMEM;
1522
            }
1523

    
1524
            if (elf_ppnt->p_offset + elf_ppnt->p_filesz <= BPRM_BUF_SIZE) {
1525
                memcpy(elf_interpreter, bprm->buf + elf_ppnt->p_offset,
1526
                       elf_ppnt->p_filesz);
1527
            } else {
1528
                retval = pread(bprm->fd, elf_interpreter, elf_ppnt->p_filesz,
1529
                               elf_ppnt->p_offset);
1530
                if (retval != elf_ppnt->p_filesz) {
1531
                    perror("load_elf_binary2");
1532
                    exit(-1);
1533
                }
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
            retval = open(path(elf_interpreter), O_RDONLY);
1548
            if (retval < 0) {
1549
                perror(elf_interpreter);
1550
                exit(-1);
1551
            }
1552
            interpreter_fd = retval;
1553

    
1554
            retval = read(interpreter_fd, bprm->buf, BPRM_BUF_SIZE);
1555
            if (retval < 0) {
1556
                perror("load_elf_binary3");
1557
                exit(-1);
1558
            }
1559
            if (retval < BPRM_BUF_SIZE) {
1560
                memset(bprm->buf, 0, BPRM_BUF_SIZE - retval);
1561
            }
1562

    
1563
            interp_ex = *((struct exec *) bprm->buf); /* aout exec-header */
1564
            interp_elf_ex = *((struct elfhdr *) bprm->buf); /* elf exec-header */
1565
        }
1566
        elf_ppnt++;
1567
    }
1568

    
1569
    /* Some simple consistency checks for the interpreter */
1570
    if (elf_interpreter){
1571
        interpreter_type = INTERPRETER_ELF | INTERPRETER_AOUT;
1572

    
1573
        /* Now figure out which format our binary is */
1574
        if ((N_MAGIC(interp_ex) != OMAGIC) && (N_MAGIC(interp_ex) != ZMAGIC) &&
1575
            (N_MAGIC(interp_ex) != QMAGIC)) {
1576
            interpreter_type = INTERPRETER_ELF;
1577
        }
1578

    
1579
        if (interp_elf_ex.e_ident[0] != 0x7f ||
1580
            strncmp((char *)&interp_elf_ex.e_ident[1], "ELF",3) != 0) {
1581
            interpreter_type &= ~INTERPRETER_ELF;
1582
        }
1583

    
1584
        if (!interpreter_type) {
1585
            free(elf_interpreter);
1586
            free(elf_phdata);
1587
            close(bprm->fd);
1588
            return -ELIBBAD;
1589
        }
1590
    }
1591

    
1592
    /* OK, we are done with that, now set up the arg stuff,
1593
       and then start this sucker up */
1594

    
1595
    {
1596
        char * passed_p;
1597

    
1598
        if (interpreter_type == INTERPRETER_AOUT) {
1599
            snprintf(passed_fileno, sizeof(passed_fileno), "%d", bprm->fd);
1600
            passed_p = passed_fileno;
1601

    
1602
            if (elf_interpreter) {
1603
                bprm->p = copy_elf_strings(1,&passed_p,bprm->page,bprm->p);
1604
                bprm->argc++;
1605
            }
1606
        }
1607
        if (!bprm->p) {
1608
            if (elf_interpreter) {
1609
                free(elf_interpreter);
1610
            }
1611
            free (elf_phdata);
1612
            close(bprm->fd);
1613
            return -E2BIG;
1614
        }
1615
    }
1616

    
1617
    /* OK, This is the point of no return */
1618
    info->end_data = 0;
1619
    info->end_code = 0;
1620
    info->start_mmap = (abi_ulong)ELF_START_MMAP;
1621
    info->mmap = 0;
1622
    elf_entry = (abi_ulong) elf_ex.e_entry;
1623

    
1624
#if defined(CONFIG_USE_GUEST_BASE)
1625
    /*
1626
     * In case where user has not explicitly set the guest_base, we
1627
     * probe here that should we set it automatically.
1628
     */
1629
    if (!(have_guest_base || reserved_va)) {
1630
        /*
1631
         * Go through ELF program header table and find the address
1632
         * range used by loadable segments.  Check that this is available on
1633
         * the host, and if not find a suitable value for guest_base.  */
1634
        abi_ulong app_start = ~0;
1635
        abi_ulong app_end = 0;
1636
        abi_ulong addr;
1637
        unsigned long host_start;
1638
        unsigned long real_start;
1639
        unsigned long host_size;
1640
        for (i = 0, elf_ppnt = elf_phdata; i < elf_ex.e_phnum;
1641
             i++, elf_ppnt++) {
1642
            if (elf_ppnt->p_type != PT_LOAD)
1643
                continue;
1644
            addr = elf_ppnt->p_vaddr;
1645
            if (addr < app_start) {
1646
                app_start = addr;
1647
            }
1648
            addr += elf_ppnt->p_memsz;
1649
            if (addr > app_end) {
1650
                app_end = addr;
1651
            }
1652
        }
1653

    
1654
        /* If we don't have any loadable segments then something
1655
           is very wrong.  */
1656
        assert(app_start < app_end);
1657

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

    
1708
    /* Do this so that we can load the interpreter, if need be.  We will
1709
       change some of these later */
1710
    info->rss = 0;
1711
    bprm->p = setup_arg_pages(bprm->p, bprm, info);
1712
    info->start_stack = bprm->p;
1713

    
1714
    /* Now we do a little grungy work by mmaping the ELF image into
1715
     * the correct location in memory.  At this point, we assume that
1716
     * the image should be loaded at fixed address, not at a variable
1717
     * address.
1718
     */
1719

    
1720
    for(i = 0, elf_ppnt = elf_phdata; i < elf_ex.e_phnum; i++, elf_ppnt++) {
1721
        int elf_prot = 0;
1722
        int elf_flags = 0;
1723
        abi_ulong error;
1724

    
1725
        if (elf_ppnt->p_type != PT_LOAD)
1726
            continue;
1727

    
1728
        if (elf_ppnt->p_flags & PF_R) elf_prot |= PROT_READ;
1729
        if (elf_ppnt->p_flags & PF_W) elf_prot |= PROT_WRITE;
1730
        if (elf_ppnt->p_flags & PF_X) elf_prot |= PROT_EXEC;
1731
        elf_flags = MAP_PRIVATE | MAP_DENYWRITE;
1732
        if (elf_ex.e_type == ET_EXEC || load_addr_set) {
1733
            elf_flags |= MAP_FIXED;
1734
        } else if (elf_ex.e_type == ET_DYN) {
1735
            /* Try and get dynamic programs out of the way of the default mmap
1736
               base, as well as whatever program they might try to exec.  This
1737
               is because the brk will follow the loader, and is not movable.  */
1738
            /* NOTE: for qemu, we do a big mmap to get enough space
1739
               without hardcoding any address */
1740
            error = target_mmap(0, ET_DYN_MAP_SIZE,
1741
                                PROT_NONE, MAP_PRIVATE | MAP_ANON,
1742
                                -1, 0);
1743
            if (error == -1) {
1744
                perror("mmap");
1745
                exit(-1);
1746
            }
1747
            load_bias = TARGET_ELF_PAGESTART(error - elf_ppnt->p_vaddr);
1748
        }
1749

    
1750
        error = target_mmap(TARGET_ELF_PAGESTART(load_bias + elf_ppnt->p_vaddr),
1751
                            (elf_ppnt->p_filesz +
1752
                             TARGET_ELF_PAGEOFFSET(elf_ppnt->p_vaddr)),
1753
                            elf_prot,
1754
                            (MAP_FIXED | MAP_PRIVATE | MAP_DENYWRITE),
1755
                            bprm->fd,
1756
                            (elf_ppnt->p_offset -
1757
                             TARGET_ELF_PAGEOFFSET(elf_ppnt->p_vaddr)));
1758
        if (error == -1) {
1759
            perror("mmap");
1760
            exit(-1);
1761
        }
1762

    
1763
#ifdef LOW_ELF_STACK
1764
        if (TARGET_ELF_PAGESTART(elf_ppnt->p_vaddr) < elf_stack)
1765
            elf_stack = TARGET_ELF_PAGESTART(elf_ppnt->p_vaddr);
1766
#endif
1767

    
1768
        if (!load_addr_set) {
1769
            load_addr_set = 1;
1770
            load_addr = elf_ppnt->p_vaddr - elf_ppnt->p_offset;
1771
            if (elf_ex.e_type == ET_DYN) {
1772
                load_bias += error -
1773
                    TARGET_ELF_PAGESTART(load_bias + elf_ppnt->p_vaddr);
1774
                load_addr += load_bias;
1775
                reloc_func_desc = load_bias;
1776
            }
1777
        }
1778
        k = elf_ppnt->p_vaddr;
1779
        if (k < start_code)
1780
            start_code = k;
1781
        if (start_data < k)
1782
            start_data = k;
1783
        k = elf_ppnt->p_vaddr + elf_ppnt->p_filesz;
1784
        if ((elf_ppnt->p_flags & PF_X) && end_code <  k)
1785
            end_code = k;
1786
        if (end_data < k)
1787
            end_data = k;
1788
        k = elf_ppnt->p_vaddr + elf_ppnt->p_memsz;
1789
        if (k > elf_brk) {
1790
            elf_brk = TARGET_PAGE_ALIGN(k);
1791
        }
1792

    
1793
        /* If the load segment requests extra zeros (e.g. bss), map it.  */
1794
        if (elf_ppnt->p_filesz < elf_ppnt->p_memsz) {
1795
            abi_ulong base = load_bias + elf_ppnt->p_vaddr;
1796
            zero_bss(base + elf_ppnt->p_filesz,
1797
                     base + elf_ppnt->p_memsz, elf_prot);
1798
        }
1799
    }
1800

    
1801
    elf_entry += load_bias;
1802
    elf_brk += load_bias;
1803
    start_code += load_bias;
1804
    end_code += load_bias;
1805
    start_data += load_bias;
1806
    end_data += load_bias;
1807

    
1808
    if (elf_interpreter) {
1809
        if (interpreter_type & 1) {
1810
            elf_entry = load_aout_interp(&interp_ex, interpreter_fd);
1811
        } else if (interpreter_type & 2) {
1812
            elf_entry = load_elf_interp(&interp_elf_ex, interpreter_fd,
1813
                                        &interp_load_addr, bprm->buf);
1814
        }
1815
        reloc_func_desc = interp_load_addr;
1816

    
1817
        close(interpreter_fd);
1818
        free(elf_interpreter);
1819

    
1820
        if (elf_entry == ~((abi_ulong)0UL)) {
1821
            printf("Unable to load interpreter\n");
1822
            free(elf_phdata);
1823
            exit(-1);
1824
            return 0;
1825
        }
1826
    }
1827

    
1828
    free(elf_phdata);
1829

    
1830
    if (qemu_log_enabled())
1831
        load_symbols(&elf_ex, bprm->fd);
1832

    
1833
    if (interpreter_type != INTERPRETER_AOUT) close(bprm->fd);
1834
    info->personality = (ibcs2_interpreter ? PER_SVR4 : PER_LINUX);
1835

    
1836
#ifdef LOW_ELF_STACK
1837
    info->start_stack = bprm->p = elf_stack - 4;
1838
#endif
1839
    bprm->p = create_elf_tables(bprm->p,
1840
                                bprm->argc,
1841
                                bprm->envc,
1842
                                &elf_ex,
1843
                                load_addr, load_bias,
1844
                                interp_load_addr,
1845
                                (interpreter_type == INTERPRETER_AOUT ? 0 : 1),
1846
                                info);
1847
    info->load_addr = reloc_func_desc;
1848
    info->start_brk = info->brk = elf_brk;
1849
    info->end_code = end_code;
1850
    info->start_code = start_code;
1851
    info->start_data = start_data;
1852
    info->end_data = end_data;
1853
    info->start_stack = bprm->p;
1854

    
1855
#if 0
1856
    printf("(start_brk) %x\n" , info->start_brk);
1857
    printf("(end_code) %x\n" , info->end_code);
1858
    printf("(start_code) %x\n" , info->start_code);
1859
    printf("(end_data) %x\n" , info->end_data);
1860
    printf("(start_stack) %x\n" , info->start_stack);
1861
    printf("(brk) %x\n" , info->brk);
1862
#endif
1863

    
1864
    if ( info->personality == PER_SVR4 )
1865
    {
1866
        /* Why this, you ask???  Well SVr4 maps page 0 as read-only,
1867
           and some applications "depend" upon this behavior.
1868
           Since we do not have the power to recompile these, we
1869
           emulate the SVr4 behavior.  Sigh.  */
1870
        mapped_addr = target_mmap(0, qemu_host_page_size, PROT_READ | PROT_EXEC,
1871
                                  MAP_FIXED | MAP_PRIVATE, -1, 0);
1872
    }
1873

    
1874
    info->entry = elf_entry;
1875

    
1876
#ifdef USE_ELF_CORE_DUMP
1877
    bprm->core_dump = &elf_core_dump;
1878
#endif
1879

    
1880
    return 0;
1881
}
1882

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

    
1923
/* An ELF note in memory */
1924
struct memelfnote {
1925
    const char *name;
1926
    size_t     namesz;
1927
    size_t     namesz_rounded;
1928
    int        type;
1929
    size_t     datasz;
1930
    void       *data;
1931
    size_t     notesz;
1932
};
1933

    
1934
struct target_elf_siginfo {
1935
    int  si_signo; /* signal number */
1936
    int  si_code;  /* extra code */
1937
    int  si_errno; /* errno */
1938
};
1939

    
1940
struct target_elf_prstatus {
1941
    struct target_elf_siginfo pr_info;      /* Info associated with signal */
1942
    short              pr_cursig;    /* Current signal */
1943
    target_ulong       pr_sigpend;   /* XXX */
1944
    target_ulong       pr_sighold;   /* XXX */
1945
    target_pid_t       pr_pid;
1946
    target_pid_t       pr_ppid;
1947
    target_pid_t       pr_pgrp;
1948
    target_pid_t       pr_sid;
1949
    struct target_timeval pr_utime;  /* XXX User time */
1950
    struct target_timeval pr_stime;  /* XXX System time */
1951
    struct target_timeval pr_cutime; /* XXX Cumulative user time */
1952
    struct target_timeval pr_cstime; /* XXX Cumulative system time */
1953
    target_elf_gregset_t      pr_reg;       /* GP registers */
1954
    int                pr_fpvalid;   /* XXX */
1955
};
1956

    
1957
#define ELF_PRARGSZ     (80) /* Number of chars for args */
1958

    
1959
struct target_elf_prpsinfo {
1960
    char         pr_state;       /* numeric process state */
1961
    char         pr_sname;       /* char for pr_state */
1962
    char         pr_zomb;        /* zombie */
1963
    char         pr_nice;        /* nice val */
1964
    target_ulong pr_flag;        /* flags */
1965
    target_uid_t pr_uid;
1966
    target_gid_t pr_gid;
1967
    target_pid_t pr_pid, pr_ppid, pr_pgrp, pr_sid;
1968
    /* Lots missing */
1969
    char    pr_fname[16];           /* filename of executable */
1970
    char    pr_psargs[ELF_PRARGSZ]; /* initial part of arg list */
1971
};
1972

    
1973
/* Here is the structure in which status of each thread is captured. */
1974
struct elf_thread_status {
1975
    QTAILQ_ENTRY(elf_thread_status)  ets_link;
1976
    struct target_elf_prstatus prstatus;   /* NT_PRSTATUS */
1977
#if 0
1978
    elf_fpregset_t fpu;             /* NT_PRFPREG */
1979
    struct task_struct *thread;
1980
    elf_fpxregset_t xfpu;           /* ELF_CORE_XFPREG_TYPE */
1981
#endif
1982
    struct memelfnote notes[1];
1983
    int num_notes;
1984
};
1985

    
1986
struct elf_note_info {
1987
    struct memelfnote   *notes;
1988
    struct target_elf_prstatus *prstatus;  /* NT_PRSTATUS */
1989
    struct target_elf_prpsinfo *psinfo;    /* NT_PRPSINFO */
1990

    
1991
    QTAILQ_HEAD(thread_list_head, elf_thread_status) thread_list;
1992
#if 0
1993
    /*
1994
     * Current version of ELF coredump doesn't support
1995
     * dumping fp regs etc.
1996
     */
1997
    elf_fpregset_t *fpu;
1998
    elf_fpxregset_t *xfpu;
1999
    int thread_status_size;
2000
#endif
2001
    int notes_size;
2002
    int numnote;
2003
};
2004

    
2005
struct vm_area_struct {
2006
    abi_ulong   vma_start;  /* start vaddr of memory region */
2007
    abi_ulong   vma_end;    /* end vaddr of memory region */
2008
    abi_ulong   vma_flags;  /* protection etc. flags for the region */
2009
    QTAILQ_ENTRY(vm_area_struct) vma_link;
2010
};
2011

    
2012
struct mm_struct {
2013
    QTAILQ_HEAD(, vm_area_struct) mm_mmap;
2014
    int mm_count;           /* number of mappings */
2015
};
2016

    
2017
static struct mm_struct *vma_init(void);
2018
static void vma_delete(struct mm_struct *);
2019
static int vma_add_mapping(struct mm_struct *, abi_ulong,
2020
                           abi_ulong, abi_ulong);
2021
static int vma_get_mapping_count(const struct mm_struct *);
2022
static struct vm_area_struct *vma_first(const struct mm_struct *);
2023
static struct vm_area_struct *vma_next(struct vm_area_struct *);
2024
static abi_ulong vma_dump_size(const struct vm_area_struct *);
2025
static int vma_walker(void *priv, abi_ulong start, abi_ulong end,
2026
                      unsigned long flags);
2027

    
2028
static void fill_elf_header(struct elfhdr *, int, uint16_t, uint32_t);
2029
static void fill_note(struct memelfnote *, const char *, int,
2030
                      unsigned int, void *);
2031
static void fill_prstatus(struct target_elf_prstatus *, const TaskState *, int);
2032
static int fill_psinfo(struct target_elf_prpsinfo *, const TaskState *);
2033
static void fill_auxv_note(struct memelfnote *, const TaskState *);
2034
static void fill_elf_note_phdr(struct elf_phdr *, int, off_t);
2035
static size_t note_size(const struct memelfnote *);
2036
static void free_note_info(struct elf_note_info *);
2037
static int fill_note_info(struct elf_note_info *, long, const CPUState *);
2038
static void fill_thread_info(struct elf_note_info *, const CPUState *);
2039
static int core_dump_filename(const TaskState *, char *, size_t);
2040

    
2041
static int dump_write(int, const void *, size_t);
2042
static int write_note(struct memelfnote *, int);
2043
static int write_note_info(struct elf_note_info *, int);
2044

    
2045
#ifdef BSWAP_NEEDED
2046
static void bswap_prstatus(struct target_elf_prstatus *);
2047
static void bswap_psinfo(struct target_elf_prpsinfo *);
2048

    
2049
static void bswap_prstatus(struct target_elf_prstatus *prstatus)
2050
{
2051
    prstatus->pr_info.si_signo = tswapl(prstatus->pr_info.si_signo);
2052
    prstatus->pr_info.si_code = tswapl(prstatus->pr_info.si_code);
2053
    prstatus->pr_info.si_errno = tswapl(prstatus->pr_info.si_errno);
2054
    prstatus->pr_cursig = tswap16(prstatus->pr_cursig);
2055
    prstatus->pr_sigpend = tswapl(prstatus->pr_sigpend);
2056
    prstatus->pr_sighold = tswapl(prstatus->pr_sighold);
2057
    prstatus->pr_pid = tswap32(prstatus->pr_pid);
2058
    prstatus->pr_ppid = tswap32(prstatus->pr_ppid);
2059
    prstatus->pr_pgrp = tswap32(prstatus->pr_pgrp);
2060
    prstatus->pr_sid = tswap32(prstatus->pr_sid);
2061
    /* cpu times are not filled, so we skip them */
2062
    /* regs should be in correct format already */
2063
    prstatus->pr_fpvalid = tswap32(prstatus->pr_fpvalid);
2064
}
2065

    
2066
static void bswap_psinfo(struct target_elf_prpsinfo *psinfo)
2067
{
2068
    psinfo->pr_flag = tswapl(psinfo->pr_flag);
2069
    psinfo->pr_uid = tswap16(psinfo->pr_uid);
2070
    psinfo->pr_gid = tswap16(psinfo->pr_gid);
2071
    psinfo->pr_pid = tswap32(psinfo->pr_pid);
2072
    psinfo->pr_ppid = tswap32(psinfo->pr_ppid);
2073
    psinfo->pr_pgrp = tswap32(psinfo->pr_pgrp);
2074
    psinfo->pr_sid = tswap32(psinfo->pr_sid);
2075
}
2076
#endif /* BSWAP_NEEDED */
2077

    
2078
/*
2079
 * Minimal support for linux memory regions.  These are needed
2080
 * when we are finding out what memory exactly belongs to
2081
 * emulated process.  No locks needed here, as long as
2082
 * thread that received the signal is stopped.
2083
 */
2084

    
2085
static struct mm_struct *vma_init(void)
2086
{
2087
    struct mm_struct *mm;
2088

    
2089
    if ((mm = qemu_malloc(sizeof (*mm))) == NULL)
2090
        return (NULL);
2091

    
2092
    mm->mm_count = 0;
2093
    QTAILQ_INIT(&mm->mm_mmap);
2094

    
2095
    return (mm);
2096
}
2097

    
2098
static void vma_delete(struct mm_struct *mm)
2099
{
2100
    struct vm_area_struct *vma;
2101

    
2102
    while ((vma = vma_first(mm)) != NULL) {
2103
        QTAILQ_REMOVE(&mm->mm_mmap, vma, vma_link);
2104
        qemu_free(vma);
2105
    }
2106
    qemu_free(mm);
2107
}
2108

    
2109
static int vma_add_mapping(struct mm_struct *mm, abi_ulong start,
2110
                           abi_ulong end, abi_ulong flags)
2111
{
2112
    struct vm_area_struct *vma;
2113

    
2114
    if ((vma = qemu_mallocz(sizeof (*vma))) == NULL)
2115
        return (-1);
2116

    
2117
    vma->vma_start = start;
2118
    vma->vma_end = end;
2119
    vma->vma_flags = flags;
2120

    
2121
    QTAILQ_INSERT_TAIL(&mm->mm_mmap, vma, vma_link);
2122
    mm->mm_count++;
2123

    
2124
    return (0);
2125
}
2126

    
2127
static struct vm_area_struct *vma_first(const struct mm_struct *mm)
2128
{
2129
    return (QTAILQ_FIRST(&mm->mm_mmap));
2130
}
2131

    
2132
static struct vm_area_struct *vma_next(struct vm_area_struct *vma)
2133
{
2134
    return (QTAILQ_NEXT(vma, vma_link));
2135
}
2136

    
2137
static int vma_get_mapping_count(const struct mm_struct *mm)
2138
{
2139
    return (mm->mm_count);
2140
}
2141

    
2142
/*
2143
 * Calculate file (dump) size of given memory region.
2144
 */
2145
static abi_ulong vma_dump_size(const struct vm_area_struct *vma)
2146
{
2147
    /* if we cannot even read the first page, skip it */
2148
    if (!access_ok(VERIFY_READ, vma->vma_start, TARGET_PAGE_SIZE))
2149
        return (0);
2150

    
2151
    /*
2152
     * Usually we don't dump executable pages as they contain
2153
     * non-writable code that debugger can read directly from
2154
     * target library etc.  However, thread stacks are marked
2155
     * also executable so we read in first page of given region
2156
     * and check whether it contains elf header.  If there is
2157
     * no elf header, we dump it.
2158
     */
2159
    if (vma->vma_flags & PROT_EXEC) {
2160
        char page[TARGET_PAGE_SIZE];
2161

    
2162
        copy_from_user(page, vma->vma_start, sizeof (page));
2163
        if ((page[EI_MAG0] == ELFMAG0) &&
2164
            (page[EI_MAG1] == ELFMAG1) &&
2165
            (page[EI_MAG2] == ELFMAG2) &&
2166
            (page[EI_MAG3] == ELFMAG3)) {
2167
            /*
2168
             * Mappings are possibly from ELF binary.  Don't dump
2169
             * them.
2170
             */
2171
            return (0);
2172
        }
2173
    }
2174

    
2175
    return (vma->vma_end - vma->vma_start);
2176
}
2177

    
2178
static int vma_walker(void *priv, abi_ulong start, abi_ulong end,
2179
                      unsigned long flags)
2180
{
2181
    struct mm_struct *mm = (struct mm_struct *)priv;
2182

    
2183
    vma_add_mapping(mm, start, end, flags);
2184
    return (0);
2185
}
2186

    
2187
static void fill_note(struct memelfnote *note, const char *name, int type,
2188
                      unsigned int sz, void *data)
2189
{
2190
    unsigned int namesz;
2191

    
2192
    namesz = strlen(name) + 1;
2193
    note->name = name;
2194
    note->namesz = namesz;
2195
    note->namesz_rounded = roundup(namesz, sizeof (int32_t));
2196
    note->type = type;
2197
    note->datasz = roundup(sz, sizeof (int32_t));;
2198
    note->data = data;
2199

    
2200
    /*
2201
     * We calculate rounded up note size here as specified by
2202
     * ELF document.
2203
     */
2204
    note->notesz = sizeof (struct elf_note) +
2205
        note->namesz_rounded + note->datasz;
2206
}
2207

    
2208
static void fill_elf_header(struct elfhdr *elf, int segs, uint16_t machine,
2209
                            uint32_t flags)
2210
{
2211
    (void) memset(elf, 0, sizeof(*elf));
2212

    
2213
    (void) memcpy(elf->e_ident, ELFMAG, SELFMAG);
2214
    elf->e_ident[EI_CLASS] = ELF_CLASS;
2215
    elf->e_ident[EI_DATA] = ELF_DATA;
2216
    elf->e_ident[EI_VERSION] = EV_CURRENT;
2217
    elf->e_ident[EI_OSABI] = ELF_OSABI;
2218

    
2219
    elf->e_type = ET_CORE;
2220
    elf->e_machine = machine;
2221
    elf->e_version = EV_CURRENT;
2222
    elf->e_phoff = sizeof(struct elfhdr);
2223
    elf->e_flags = flags;
2224
    elf->e_ehsize = sizeof(struct elfhdr);
2225
    elf->e_phentsize = sizeof(struct elf_phdr);
2226
    elf->e_phnum = segs;
2227

    
2228
#ifdef BSWAP_NEEDED
2229
    bswap_ehdr(elf);
2230
#endif
2231
}
2232

    
2233
static void fill_elf_note_phdr(struct elf_phdr *phdr, int sz, off_t offset)
2234
{
2235
    phdr->p_type = PT_NOTE;
2236
    phdr->p_offset = offset;
2237
    phdr->p_vaddr = 0;
2238
    phdr->p_paddr = 0;
2239
    phdr->p_filesz = sz;
2240
    phdr->p_memsz = 0;
2241
    phdr->p_flags = 0;
2242
    phdr->p_align = 0;
2243

    
2244
#ifdef BSWAP_NEEDED
2245
    bswap_phdr(phdr);
2246
#endif
2247
}
2248

    
2249
static size_t note_size(const struct memelfnote *note)
2250
{
2251
    return (note->notesz);
2252
}
2253

    
2254
static void fill_prstatus(struct target_elf_prstatus *prstatus,
2255
                          const TaskState *ts, int signr)
2256
{
2257
    (void) memset(prstatus, 0, sizeof (*prstatus));
2258
    prstatus->pr_info.si_signo = prstatus->pr_cursig = signr;
2259
    prstatus->pr_pid = ts->ts_tid;
2260
    prstatus->pr_ppid = getppid();
2261
    prstatus->pr_pgrp = getpgrp();
2262
    prstatus->pr_sid = getsid(0);
2263

    
2264
#ifdef BSWAP_NEEDED
2265
    bswap_prstatus(prstatus);
2266
#endif
2267
}
2268

    
2269
static int fill_psinfo(struct target_elf_prpsinfo *psinfo, const TaskState *ts)
2270
{
2271
    char *filename, *base_filename;
2272
    unsigned int i, len;
2273

    
2274
    (void) memset(psinfo, 0, sizeof (*psinfo));
2275

    
2276
    len = ts->info->arg_end - ts->info->arg_start;
2277
    if (len >= ELF_PRARGSZ)
2278
        len = ELF_PRARGSZ - 1;
2279
    if (copy_from_user(&psinfo->pr_psargs, ts->info->arg_start, len))
2280
        return -EFAULT;
2281
    for (i = 0; i < len; i++)
2282
        if (psinfo->pr_psargs[i] == 0)
2283
            psinfo->pr_psargs[i] = ' ';
2284
    psinfo->pr_psargs[len] = 0;
2285

    
2286
    psinfo->pr_pid = getpid();
2287
    psinfo->pr_ppid = getppid();
2288
    psinfo->pr_pgrp = getpgrp();
2289
    psinfo->pr_sid = getsid(0);
2290
    psinfo->pr_uid = getuid();
2291
    psinfo->pr_gid = getgid();
2292

    
2293
    filename = strdup(ts->bprm->filename);
2294
    base_filename = strdup(basename(filename));
2295
    (void) strncpy(psinfo->pr_fname, base_filename,
2296
                   sizeof(psinfo->pr_fname));
2297
    free(base_filename);
2298
    free(filename);
2299

    
2300
#ifdef BSWAP_NEEDED
2301
    bswap_psinfo(psinfo);
2302
#endif
2303
    return (0);
2304
}
2305

    
2306
static void fill_auxv_note(struct memelfnote *note, const TaskState *ts)
2307
{
2308
    elf_addr_t auxv = (elf_addr_t)ts->info->saved_auxv;
2309
    elf_addr_t orig_auxv = auxv;
2310
    abi_ulong val;
2311
    void *ptr;
2312
    int i, len;
2313

    
2314
    /*
2315
     * Auxiliary vector is stored in target process stack.  It contains
2316
     * {type, value} pairs that we need to dump into note.  This is not
2317
     * strictly necessary but we do it here for sake of completeness.
2318
     */
2319

    
2320
    /* find out lenght of the vector, AT_NULL is terminator */
2321
    i = len = 0;
2322
    do {
2323
        get_user_ual(val, auxv);
2324
        i += 2;
2325
        auxv += 2 * sizeof (elf_addr_t);
2326
    } while (val != AT_NULL);
2327
    len = i * sizeof (elf_addr_t);
2328

    
2329
    /* read in whole auxv vector and copy it to memelfnote */
2330
    ptr = lock_user(VERIFY_READ, orig_auxv, len, 0);
2331
    if (ptr != NULL) {
2332
        fill_note(note, "CORE", NT_AUXV, len, ptr);
2333
        unlock_user(ptr, auxv, len);
2334
    }
2335
}
2336

    
2337
/*
2338
 * Constructs name of coredump file.  We have following convention
2339
 * for the name:
2340
 *     qemu_<basename-of-target-binary>_<date>-<time>_<pid>.core
2341
 *
2342
 * Returns 0 in case of success, -1 otherwise (errno is set).
2343
 */
2344
static int core_dump_filename(const TaskState *ts, char *buf,
2345
                              size_t bufsize)
2346
{
2347
    char timestamp[64];
2348
    char *filename = NULL;
2349
    char *base_filename = NULL;
2350
    struct timeval tv;
2351
    struct tm tm;
2352

    
2353
    assert(bufsize >= PATH_MAX);
2354

    
2355
    if (gettimeofday(&tv, NULL) < 0) {
2356
        (void) fprintf(stderr, "unable to get current timestamp: %s",
2357
                       strerror(errno));
2358
        return (-1);
2359
    }
2360

    
2361
    filename = strdup(ts->bprm->filename);
2362
    base_filename = strdup(basename(filename));
2363
    (void) strftime(timestamp, sizeof (timestamp), "%Y%m%d-%H%M%S",
2364
                    localtime_r(&tv.tv_sec, &tm));
2365
    (void) snprintf(buf, bufsize, "qemu_%s_%s_%d.core",
2366
                    base_filename, timestamp, (int)getpid());
2367
    free(base_filename);
2368
    free(filename);
2369

    
2370
    return (0);
2371
}
2372

    
2373
static int dump_write(int fd, const void *ptr, size_t size)
2374
{
2375
    const char *bufp = (const char *)ptr;
2376
    ssize_t bytes_written, bytes_left;
2377
    struct rlimit dumpsize;
2378
    off_t pos;
2379

    
2380
    bytes_written = 0;
2381
    getrlimit(RLIMIT_CORE, &dumpsize);
2382
    if ((pos = lseek(fd, 0, SEEK_CUR))==-1) {
2383
        if (errno == ESPIPE) { /* not a seekable stream */
2384
            bytes_left = size;
2385
        } else {
2386
            return pos;
2387
        }
2388
    } else {
2389
        if (dumpsize.rlim_cur <= pos) {
2390
            return -1;
2391
        } else if (dumpsize.rlim_cur == RLIM_INFINITY) {
2392
            bytes_left = size;
2393
        } else {
2394
            size_t limit_left=dumpsize.rlim_cur - pos;
2395
            bytes_left = limit_left >= size ? size : limit_left ;
2396
        }
2397
    }
2398

    
2399
    /*
2400
     * In normal conditions, single write(2) should do but
2401
     * in case of socket etc. this mechanism is more portable.
2402
     */
2403
    do {
2404
        bytes_written = write(fd, bufp, bytes_left);
2405
        if (bytes_written < 0) {
2406
            if (errno == EINTR)
2407
                continue;
2408
            return (-1);
2409
        } else if (bytes_written == 0) { /* eof */
2410
            return (-1);
2411
        }
2412
        bufp += bytes_written;
2413
        bytes_left -= bytes_written;
2414
    } while (bytes_left > 0);
2415

    
2416
    return (0);
2417
}
2418

    
2419
static int write_note(struct memelfnote *men, int fd)
2420
{
2421
    struct elf_note en;
2422

    
2423
    en.n_namesz = men->namesz;
2424
    en.n_type = men->type;
2425
    en.n_descsz = men->datasz;
2426

    
2427
#ifdef BSWAP_NEEDED
2428
    bswap_note(&en);
2429
#endif
2430

    
2431
    if (dump_write(fd, &en, sizeof(en)) != 0)
2432
        return (-1);
2433
    if (dump_write(fd, men->name, men->namesz_rounded) != 0)
2434
        return (-1);
2435
    if (dump_write(fd, men->data, men->datasz) != 0)
2436
        return (-1);
2437

    
2438
    return (0);
2439
}
2440

    
2441
static void fill_thread_info(struct elf_note_info *info, const CPUState *env)
2442
{
2443
    TaskState *ts = (TaskState *)env->opaque;
2444
    struct elf_thread_status *ets;
2445

    
2446
    ets = qemu_mallocz(sizeof (*ets));
2447
    ets->num_notes = 1; /* only prstatus is dumped */
2448
    fill_prstatus(&ets->prstatus, ts, 0);
2449
    elf_core_copy_regs(&ets->prstatus.pr_reg, env);
2450
    fill_note(&ets->notes[0], "CORE", NT_PRSTATUS, sizeof (ets->prstatus),
2451
              &ets->prstatus);
2452

    
2453
    QTAILQ_INSERT_TAIL(&info->thread_list, ets, ets_link);
2454

    
2455
    info->notes_size += note_size(&ets->notes[0]);
2456
}
2457

    
2458
static int fill_note_info(struct elf_note_info *info,
2459
                          long signr, const CPUState *env)
2460
{
2461
#define NUMNOTES 3
2462
    CPUState *cpu = NULL;
2463
    TaskState *ts = (TaskState *)env->opaque;
2464
    int i;
2465

    
2466
    (void) memset(info, 0, sizeof (*info));
2467

    
2468
    QTAILQ_INIT(&info->thread_list);
2469

    
2470
    info->notes = qemu_mallocz(NUMNOTES * sizeof (struct memelfnote));
2471
    if (info->notes == NULL)
2472
        return (-ENOMEM);
2473
    info->prstatus = qemu_mallocz(sizeof (*info->prstatus));
2474
    if (info->prstatus == NULL)
2475
        return (-ENOMEM);
2476
    info->psinfo = qemu_mallocz(sizeof (*info->psinfo));
2477
    if (info->prstatus == NULL)
2478
        return (-ENOMEM);
2479

    
2480
    /*
2481
     * First fill in status (and registers) of current thread
2482
     * including process info & aux vector.
2483
     */
2484
    fill_prstatus(info->prstatus, ts, signr);
2485
    elf_core_copy_regs(&info->prstatus->pr_reg, env);
2486
    fill_note(&info->notes[0], "CORE", NT_PRSTATUS,
2487
              sizeof (*info->prstatus), info->prstatus);
2488
    fill_psinfo(info->psinfo, ts);
2489
    fill_note(&info->notes[1], "CORE", NT_PRPSINFO,
2490
              sizeof (*info->psinfo), info->psinfo);
2491
    fill_auxv_note(&info->notes[2], ts);
2492
    info->numnote = 3;
2493

    
2494
    info->notes_size = 0;
2495
    for (i = 0; i < info->numnote; i++)
2496
        info->notes_size += note_size(&info->notes[i]);
2497

    
2498
    /* read and fill status of all threads */
2499
    cpu_list_lock();
2500
    for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
2501
        if (cpu == thread_env)
2502
            continue;
2503
        fill_thread_info(info, cpu);
2504
    }
2505
    cpu_list_unlock();
2506

    
2507
    return (0);
2508
}
2509

    
2510
static void free_note_info(struct elf_note_info *info)
2511
{
2512
    struct elf_thread_status *ets;
2513

    
2514
    while (!QTAILQ_EMPTY(&info->thread_list)) {
2515
        ets = QTAILQ_FIRST(&info->thread_list);
2516
        QTAILQ_REMOVE(&info->thread_list, ets, ets_link);
2517
        qemu_free(ets);
2518
    }
2519

    
2520
    qemu_free(info->prstatus);
2521
    qemu_free(info->psinfo);
2522
    qemu_free(info->notes);
2523
}
2524

    
2525
static int write_note_info(struct elf_note_info *info, int fd)
2526
{
2527
    struct elf_thread_status *ets;
2528
    int i, error = 0;
2529

    
2530
    /* write prstatus, psinfo and auxv for current thread */
2531
    for (i = 0; i < info->numnote; i++)
2532
        if ((error = write_note(&info->notes[i], fd)) != 0)
2533
            return (error);
2534

    
2535
    /* write prstatus for each thread */
2536
    for (ets = info->thread_list.tqh_first; ets != NULL;
2537
         ets = ets->ets_link.tqe_next) {
2538
        if ((error = write_note(&ets->notes[0], fd)) != 0)
2539
            return (error);
2540
    }
2541

    
2542
    return (0);
2543
}
2544

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

    
2602
    errno = 0;
2603
    getrlimit(RLIMIT_CORE, &dumpsize);
2604
    if (dumpsize.rlim_cur == 0)
2605
        return 0;
2606

    
2607
    if (core_dump_filename(ts, corefile, sizeof (corefile)) < 0)
2608
        return (-errno);
2609

    
2610
    if ((fd = open(corefile, O_WRONLY | O_CREAT,
2611
                   S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0)
2612
        return (-errno);
2613

    
2614
    /*
2615
     * Walk through target process memory mappings and
2616
     * set up structure containing this information.  After
2617
     * this point vma_xxx functions can be used.
2618
     */
2619
    if ((mm = vma_init()) == NULL)
2620
        goto out;
2621

    
2622
    walk_memory_regions(mm, vma_walker);
2623
    segs = vma_get_mapping_count(mm);
2624

    
2625
    /*
2626
     * Construct valid coredump ELF header.  We also
2627
     * add one more segment for notes.
2628
     */
2629
    fill_elf_header(&elf, segs + 1, ELF_MACHINE, 0);
2630
    if (dump_write(fd, &elf, sizeof (elf)) != 0)
2631
        goto out;
2632

    
2633
    /* fill in in-memory version of notes */
2634
    if (fill_note_info(&info, signr, env) < 0)
2635
        goto out;
2636

    
2637
    offset += sizeof (elf);                             /* elf header */
2638
    offset += (segs + 1) * sizeof (struct elf_phdr);    /* program headers */
2639

    
2640
    /* write out notes program header */
2641
    fill_elf_note_phdr(&phdr, info.notes_size, offset);
2642

    
2643
    offset += info.notes_size;
2644
    if (dump_write(fd, &phdr, sizeof (phdr)) != 0)
2645
        goto out;
2646

    
2647
    /*
2648
     * ELF specification wants data to start at page boundary so
2649
     * we align it here.
2650
     */
2651
    offset = roundup(offset, ELF_EXEC_PAGESIZE);
2652

    
2653
    /*
2654
     * Write program headers for memory regions mapped in
2655
     * the target process.
2656
     */
2657
    for (vma = vma_first(mm); vma != NULL; vma = vma_next(vma)) {
2658
        (void) memset(&phdr, 0, sizeof (phdr));
2659

    
2660
        phdr.p_type = PT_LOAD;
2661
        phdr.p_offset = offset;
2662
        phdr.p_vaddr = vma->vma_start;
2663
        phdr.p_paddr = 0;
2664
        phdr.p_filesz = vma_dump_size(vma);
2665
        offset += phdr.p_filesz;
2666
        phdr.p_memsz = vma->vma_end - vma->vma_start;
2667
        phdr.p_flags = vma->vma_flags & PROT_READ ? PF_R : 0;
2668
        if (vma->vma_flags & PROT_WRITE)
2669
            phdr.p_flags |= PF_W;
2670
        if (vma->vma_flags & PROT_EXEC)
2671
            phdr.p_flags |= PF_X;
2672
        phdr.p_align = ELF_EXEC_PAGESIZE;
2673

    
2674
        dump_write(fd, &phdr, sizeof (phdr));
2675
    }
2676

    
2677
    /*
2678
     * Next we write notes just after program headers.  No
2679
     * alignment needed here.
2680
     */
2681
    if (write_note_info(&info, fd) < 0)
2682
        goto out;
2683

    
2684
    /* align data to page boundary */
2685
    data_offset = lseek(fd, 0, SEEK_CUR);
2686
    data_offset = TARGET_PAGE_ALIGN(data_offset);
2687
    if (lseek(fd, data_offset, SEEK_SET) != data_offset)
2688
        goto out;
2689

    
2690
    /*
2691
     * Finally we can dump process memory into corefile as well.
2692
     */
2693
    for (vma = vma_first(mm); vma != NULL; vma = vma_next(vma)) {
2694
        abi_ulong addr;
2695
        abi_ulong end;
2696

    
2697
        end = vma->vma_start + vma_dump_size(vma);
2698

    
2699
        for (addr = vma->vma_start; addr < end;
2700
             addr += TARGET_PAGE_SIZE) {
2701
            char page[TARGET_PAGE_SIZE];
2702
            int error;
2703

    
2704
            /*
2705
             *  Read in page from target process memory and
2706
             *  write it to coredump file.
2707
             */
2708
            error = copy_from_user(page, addr, sizeof (page));
2709
            if (error != 0) {
2710
                (void) fprintf(stderr, "unable to dump " TARGET_ABI_FMT_lx "\n",
2711
                               addr);
2712
                errno = -error;
2713
                goto out;
2714
            }
2715
            if (dump_write(fd, page, TARGET_PAGE_SIZE) < 0)
2716
                goto out;
2717
        }
2718
    }
2719

    
2720
 out:
2721
    free_note_info(&info);
2722
    if (mm != NULL)
2723
        vma_delete(mm);
2724
    (void) close(fd);
2725

    
2726
    if (errno != 0)
2727
        return (-errno);
2728
    return (0);
2729
}
2730

    
2731
#endif /* USE_ELF_CORE_DUMP */
2732

    
2733
static int load_aout_interp(void * exptr, int interp_fd)
2734
{
2735
    printf("a.out interpreter not yet supported\n");
2736
    return(0);
2737
}
2738

    
2739
void do_init_thread(struct target_pt_regs *regs, struct image_info *infop)
2740
{
2741
    init_thread(regs, infop);
2742
}