]> rtime.felk.cvut.cz Git - lisovros/qemu_apohw.git/blob - linux-user/elfload.c
linux-user/elfload.c: Fix A64 code which was incorrectly acting like A32
[lisovros/qemu_apohw.git] / linux-user / elfload.c
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/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 #ifdef TARGET_WORDS_BIGENDIAN
99 #define ELF_DATA        ELFDATA2MSB
100 #else
101 #define ELF_DATA        ELFDATA2LSB
102 #endif
103
104 #ifdef TARGET_ABI_MIPSN32
105 typedef abi_ullong      target_elf_greg_t;
106 #define tswapreg(ptr)   tswap64(ptr)
107 #else
108 typedef abi_ulong       target_elf_greg_t;
109 #define tswapreg(ptr)   tswapal(ptr)
110 #endif
111
112 #ifdef USE_UID16
113 typedef abi_ushort      target_uid_t;
114 typedef abi_ushort      target_gid_t;
115 #else
116 typedef abi_uint        target_uid_t;
117 typedef abi_uint        target_gid_t;
118 #endif
119 typedef abi_int         target_pid_t;
120
121 #ifdef TARGET_I386
122
123 #define ELF_PLATFORM get_elf_platform()
124
125 static const char *get_elf_platform(void)
126 {
127     static char elf_platform[] = "i386";
128     int family = object_property_get_int(OBJECT(thread_cpu), "family", NULL);
129     if (family > 6)
130         family = 6;
131     if (family >= 3)
132         elf_platform[1] = '0' + family;
133     return elf_platform;
134 }
135
136 #define ELF_HWCAP get_elf_hwcap()
137
138 static uint32_t get_elf_hwcap(void)
139 {
140     X86CPU *cpu = X86_CPU(thread_cpu);
141
142     return cpu->env.features[FEAT_1_EDX];
143 }
144
145 #ifdef TARGET_X86_64
146 #define ELF_START_MMAP 0x2aaaaab000ULL
147 #define elf_check_arch(x) ( ((x) == ELF_ARCH) )
148
149 #define ELF_CLASS      ELFCLASS64
150 #define ELF_ARCH       EM_X86_64
151
152 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
153 {
154     regs->rax = 0;
155     regs->rsp = infop->start_stack;
156     regs->rip = infop->entry;
157 }
158
159 #define ELF_NREG    27
160 typedef target_elf_greg_t  target_elf_gregset_t[ELF_NREG];
161
162 /*
163  * Note that ELF_NREG should be 29 as there should be place for
164  * TRAPNO and ERR "registers" as well but linux doesn't dump
165  * those.
166  *
167  * See linux kernel: arch/x86/include/asm/elf.h
168  */
169 static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUX86State *env)
170 {
171     (*regs)[0] = env->regs[15];
172     (*regs)[1] = env->regs[14];
173     (*regs)[2] = env->regs[13];
174     (*regs)[3] = env->regs[12];
175     (*regs)[4] = env->regs[R_EBP];
176     (*regs)[5] = env->regs[R_EBX];
177     (*regs)[6] = env->regs[11];
178     (*regs)[7] = env->regs[10];
179     (*regs)[8] = env->regs[9];
180     (*regs)[9] = env->regs[8];
181     (*regs)[10] = env->regs[R_EAX];
182     (*regs)[11] = env->regs[R_ECX];
183     (*regs)[12] = env->regs[R_EDX];
184     (*regs)[13] = env->regs[R_ESI];
185     (*regs)[14] = env->regs[R_EDI];
186     (*regs)[15] = env->regs[R_EAX]; /* XXX */
187     (*regs)[16] = env->eip;
188     (*regs)[17] = env->segs[R_CS].selector & 0xffff;
189     (*regs)[18] = env->eflags;
190     (*regs)[19] = env->regs[R_ESP];
191     (*regs)[20] = env->segs[R_SS].selector & 0xffff;
192     (*regs)[21] = env->segs[R_FS].selector & 0xffff;
193     (*regs)[22] = env->segs[R_GS].selector & 0xffff;
194     (*regs)[23] = env->segs[R_DS].selector & 0xffff;
195     (*regs)[24] = env->segs[R_ES].selector & 0xffff;
196     (*regs)[25] = env->segs[R_FS].selector & 0xffff;
197     (*regs)[26] = env->segs[R_GS].selector & 0xffff;
198 }
199
200 #else
201
202 #define ELF_START_MMAP 0x80000000
203
204 /*
205  * This is used to ensure we don't load something for the wrong architecture.
206  */
207 #define elf_check_arch(x) ( ((x) == EM_386) || ((x) == EM_486) )
208
209 /*
210  * These are used to set parameters in the core dumps.
211  */
212 #define ELF_CLASS       ELFCLASS32
213 #define ELF_ARCH        EM_386
214
215 static inline void init_thread(struct target_pt_regs *regs,
216                                struct image_info *infop)
217 {
218     regs->esp = infop->start_stack;
219     regs->eip = infop->entry;
220
221     /* SVR4/i386 ABI (pages 3-31, 3-32) says that when the program
222        starts %edx contains a pointer to a function which might be
223        registered using `atexit'.  This provides a mean for the
224        dynamic linker to call DT_FINI functions for shared libraries
225        that have been loaded before the code runs.
226
227        A value of 0 tells we have no such handler.  */
228     regs->edx = 0;
229 }
230
231 #define ELF_NREG    17
232 typedef target_elf_greg_t  target_elf_gregset_t[ELF_NREG];
233
234 /*
235  * Note that ELF_NREG should be 19 as there should be place for
236  * TRAPNO and ERR "registers" as well but linux doesn't dump
237  * those.
238  *
239  * See linux kernel: arch/x86/include/asm/elf.h
240  */
241 static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUX86State *env)
242 {
243     (*regs)[0] = env->regs[R_EBX];
244     (*regs)[1] = env->regs[R_ECX];
245     (*regs)[2] = env->regs[R_EDX];
246     (*regs)[3] = env->regs[R_ESI];
247     (*regs)[4] = env->regs[R_EDI];
248     (*regs)[5] = env->regs[R_EBP];
249     (*regs)[6] = env->regs[R_EAX];
250     (*regs)[7] = env->segs[R_DS].selector & 0xffff;
251     (*regs)[8] = env->segs[R_ES].selector & 0xffff;
252     (*regs)[9] = env->segs[R_FS].selector & 0xffff;
253     (*regs)[10] = env->segs[R_GS].selector & 0xffff;
254     (*regs)[11] = env->regs[R_EAX]; /* XXX */
255     (*regs)[12] = env->eip;
256     (*regs)[13] = env->segs[R_CS].selector & 0xffff;
257     (*regs)[14] = env->eflags;
258     (*regs)[15] = env->regs[R_ESP];
259     (*regs)[16] = env->segs[R_SS].selector & 0xffff;
260 }
261 #endif
262
263 #define USE_ELF_CORE_DUMP
264 #define ELF_EXEC_PAGESIZE       4096
265
266 #endif
267
268 #ifdef TARGET_ARM
269
270 #ifndef TARGET_AARCH64
271 /* 32 bit ARM definitions */
272
273 #define ELF_START_MMAP 0x80000000
274
275 #define elf_check_arch(x) ((x) == ELF_MACHINE)
276
277 #define ELF_ARCH        ELF_MACHINE
278 #define ELF_CLASS       ELFCLASS32
279
280 static inline void init_thread(struct target_pt_regs *regs,
281                                struct image_info *infop)
282 {
283     abi_long stack = infop->start_stack;
284     memset(regs, 0, sizeof(*regs));
285
286     regs->ARM_cpsr = 0x10;
287     if (infop->entry & 1)
288         regs->ARM_cpsr |= CPSR_T;
289     regs->ARM_pc = infop->entry & 0xfffffffe;
290     regs->ARM_sp = infop->start_stack;
291     /* FIXME - what to for failure of get_user()? */
292     get_user_ual(regs->ARM_r2, stack + 8); /* envp */
293     get_user_ual(regs->ARM_r1, stack + 4); /* envp */
294     /* XXX: it seems that r0 is zeroed after ! */
295     regs->ARM_r0 = 0;
296     /* For uClinux PIC binaries.  */
297     /* XXX: Linux does this only on ARM with no MMU (do we care ?) */
298     regs->ARM_r10 = infop->start_data;
299 }
300
301 #define ELF_NREG    18
302 typedef target_elf_greg_t  target_elf_gregset_t[ELF_NREG];
303
304 static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUARMState *env)
305 {
306     (*regs)[0] = tswapreg(env->regs[0]);
307     (*regs)[1] = tswapreg(env->regs[1]);
308     (*regs)[2] = tswapreg(env->regs[2]);
309     (*regs)[3] = tswapreg(env->regs[3]);
310     (*regs)[4] = tswapreg(env->regs[4]);
311     (*regs)[5] = tswapreg(env->regs[5]);
312     (*regs)[6] = tswapreg(env->regs[6]);
313     (*regs)[7] = tswapreg(env->regs[7]);
314     (*regs)[8] = tswapreg(env->regs[8]);
315     (*regs)[9] = tswapreg(env->regs[9]);
316     (*regs)[10] = tswapreg(env->regs[10]);
317     (*regs)[11] = tswapreg(env->regs[11]);
318     (*regs)[12] = tswapreg(env->regs[12]);
319     (*regs)[13] = tswapreg(env->regs[13]);
320     (*regs)[14] = tswapreg(env->regs[14]);
321     (*regs)[15] = tswapreg(env->regs[15]);
322
323     (*regs)[16] = tswapreg(cpsr_read((CPUARMState *)env));
324     (*regs)[17] = tswapreg(env->regs[0]); /* XXX */
325 }
326
327 #define USE_ELF_CORE_DUMP
328 #define ELF_EXEC_PAGESIZE       4096
329
330 enum
331 {
332     ARM_HWCAP_ARM_SWP       = 1 << 0,
333     ARM_HWCAP_ARM_HALF      = 1 << 1,
334     ARM_HWCAP_ARM_THUMB     = 1 << 2,
335     ARM_HWCAP_ARM_26BIT     = 1 << 3,
336     ARM_HWCAP_ARM_FAST_MULT = 1 << 4,
337     ARM_HWCAP_ARM_FPA       = 1 << 5,
338     ARM_HWCAP_ARM_VFP       = 1 << 6,
339     ARM_HWCAP_ARM_EDSP      = 1 << 7,
340     ARM_HWCAP_ARM_JAVA      = 1 << 8,
341     ARM_HWCAP_ARM_IWMMXT    = 1 << 9,
342     ARM_HWCAP_ARM_CRUNCH    = 1 << 10,
343     ARM_HWCAP_ARM_THUMBEE   = 1 << 11,
344     ARM_HWCAP_ARM_NEON      = 1 << 12,
345     ARM_HWCAP_ARM_VFPv3     = 1 << 13,
346     ARM_HWCAP_ARM_VFPv3D16  = 1 << 14,
347     ARM_HWCAP_ARM_TLS       = 1 << 15,
348     ARM_HWCAP_ARM_VFPv4     = 1 << 16,
349     ARM_HWCAP_ARM_IDIVA     = 1 << 17,
350     ARM_HWCAP_ARM_IDIVT     = 1 << 18,
351     ARM_HWCAP_ARM_VFPD32    = 1 << 19,
352     ARM_HWCAP_ARM_LPAE      = 1 << 20,
353     ARM_HWCAP_ARM_EVTSTRM   = 1 << 21,
354 };
355
356 #define TARGET_HAS_VALIDATE_GUEST_SPACE
357 /* Return 1 if the proposed guest space is suitable for the guest.
358  * Return 0 if the proposed guest space isn't suitable, but another
359  * address space should be tried.
360  * Return -1 if there is no way the proposed guest space can be
361  * valid regardless of the base.
362  * The guest code may leave a page mapped and populate it if the
363  * address is suitable.
364  */
365 static int validate_guest_space(unsigned long guest_base,
366                                 unsigned long guest_size)
367 {
368     unsigned long real_start, test_page_addr;
369
370     /* We need to check that we can force a fault on access to the
371      * commpage at 0xffff0fxx
372      */
373     test_page_addr = guest_base + (0xffff0f00 & qemu_host_page_mask);
374
375     /* If the commpage lies within the already allocated guest space,
376      * then there is no way we can allocate it.
377      */
378     if (test_page_addr >= guest_base
379         && test_page_addr <= (guest_base + guest_size)) {
380         return -1;
381     }
382
383     /* Note it needs to be writeable to let us initialise it */
384     real_start = (unsigned long)
385                  mmap((void *)test_page_addr, qemu_host_page_size,
386                      PROT_READ | PROT_WRITE,
387                      MAP_ANONYMOUS | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
388
389     /* If we can't map it then try another address */
390     if (real_start == -1ul) {
391         return 0;
392     }
393
394     if (real_start != test_page_addr) {
395         /* OS didn't put the page where we asked - unmap and reject */
396         munmap((void *)real_start, qemu_host_page_size);
397         return 0;
398     }
399
400     /* Leave the page mapped
401      * Populate it (mmap should have left it all 0'd)
402      */
403
404     /* Kernel helper versions */
405     __put_user(5, (uint32_t *)g2h(0xffff0ffcul));
406
407     /* Now it's populated make it RO */
408     if (mprotect((void *)test_page_addr, qemu_host_page_size, PROT_READ)) {
409         perror("Protecting guest commpage");
410         exit(-1);
411     }
412
413     return 1; /* All good */
414 }
415
416
417 #define ELF_HWCAP get_elf_hwcap()
418
419 static uint32_t get_elf_hwcap(void)
420 {
421     ARMCPU *cpu = ARM_CPU(thread_cpu);
422     uint32_t hwcaps = 0;
423
424     hwcaps |= ARM_HWCAP_ARM_SWP;
425     hwcaps |= ARM_HWCAP_ARM_HALF;
426     hwcaps |= ARM_HWCAP_ARM_THUMB;
427     hwcaps |= ARM_HWCAP_ARM_FAST_MULT;
428
429     /* probe for the extra features */
430 #define GET_FEATURE(feat, hwcap) \
431     do { if (arm_feature(&cpu->env, feat)) { hwcaps |= hwcap; } } while (0)
432     /* EDSP is in v5TE and above, but all our v5 CPUs are v5TE */
433     GET_FEATURE(ARM_FEATURE_V5, ARM_HWCAP_ARM_EDSP);
434     GET_FEATURE(ARM_FEATURE_VFP, ARM_HWCAP_ARM_VFP);
435     GET_FEATURE(ARM_FEATURE_IWMMXT, ARM_HWCAP_ARM_IWMMXT);
436     GET_FEATURE(ARM_FEATURE_THUMB2EE, ARM_HWCAP_ARM_THUMBEE);
437     GET_FEATURE(ARM_FEATURE_NEON, ARM_HWCAP_ARM_NEON);
438     GET_FEATURE(ARM_FEATURE_VFP3, ARM_HWCAP_ARM_VFPv3);
439     GET_FEATURE(ARM_FEATURE_V6K, ARM_HWCAP_ARM_TLS);
440     GET_FEATURE(ARM_FEATURE_VFP4, ARM_HWCAP_ARM_VFPv4);
441     GET_FEATURE(ARM_FEATURE_ARM_DIV, ARM_HWCAP_ARM_IDIVA);
442     GET_FEATURE(ARM_FEATURE_THUMB_DIV, ARM_HWCAP_ARM_IDIVT);
443     /* All QEMU's VFPv3 CPUs have 32 registers, see VFP_DREG in translate.c.
444      * Note that the ARM_HWCAP_ARM_VFPv3D16 bit is always the inverse of
445      * ARM_HWCAP_ARM_VFPD32 (and so always clear for QEMU); it is unrelated
446      * to our VFP_FP16 feature bit.
447      */
448     GET_FEATURE(ARM_FEATURE_VFP3, ARM_HWCAP_ARM_VFPD32);
449     GET_FEATURE(ARM_FEATURE_LPAE, ARM_HWCAP_ARM_LPAE);
450 #undef GET_FEATURE
451
452     return hwcaps;
453 }
454
455 #else
456 /* 64 bit ARM definitions */
457 #define ELF_START_MMAP 0x80000000
458
459 #define elf_check_arch(x) ((x) == ELF_MACHINE)
460
461 #define ELF_ARCH        ELF_MACHINE
462 #define ELF_CLASS       ELFCLASS64
463 #define ELF_PLATFORM    "aarch64"
464
465 static inline void init_thread(struct target_pt_regs *regs,
466                                struct image_info *infop)
467 {
468     abi_long stack = infop->start_stack;
469     memset(regs, 0, sizeof(*regs));
470
471     regs->pc = infop->entry & ~0x3ULL;
472     regs->sp = stack;
473 }
474
475 #define ELF_NREG    34
476 typedef target_elf_greg_t  target_elf_gregset_t[ELF_NREG];
477
478 static void elf_core_copy_regs(target_elf_gregset_t *regs,
479                                const CPUARMState *env)
480 {
481     int i;
482
483     for (i = 0; i < 32; i++) {
484         (*regs)[i] = tswapreg(env->xregs[i]);
485     }
486     (*regs)[32] = tswapreg(env->pc);
487     (*regs)[33] = tswapreg(pstate_read((CPUARMState *)env));
488 }
489
490 #define USE_ELF_CORE_DUMP
491 #define ELF_EXEC_PAGESIZE       4096
492
493 enum {
494     ARM_HWCAP_A64_FP            = 1 << 0,
495     ARM_HWCAP_A64_ASIMD         = 1 << 1,
496     ARM_HWCAP_A64_EVTSTRM       = 1 << 2,
497     ARM_HWCAP_A64_AES           = 1 << 3,
498     ARM_HWCAP_A64_PMULL         = 1 << 4,
499     ARM_HWCAP_A64_SHA1          = 1 << 5,
500     ARM_HWCAP_A64_SHA2          = 1 << 6,
501     ARM_HWCAP_A64_CRC32         = 1 << 7,
502 };
503
504 #define ELF_HWCAP get_elf_hwcap()
505
506 static uint32_t get_elf_hwcap(void)
507 {
508     ARMCPU *cpu = ARM_CPU(thread_cpu);
509     uint32_t hwcaps = 0;
510
511     hwcaps |= ARM_HWCAP_A64_FP;
512     hwcaps |= ARM_HWCAP_A64_ASIMD;
513
514     /* probe for the extra features */
515 #define GET_FEATURE(feat, hwcap) \
516     do { if (arm_feature(&cpu->env, feat)) { hwcaps |= hwcap; } } while (0)
517     GET_FEATURE(ARM_FEATURE_V8_AES, ARM_HWCAP_A64_PMULL);
518 #undef GET_FEATURE
519
520     return hwcaps;
521 }
522
523 #endif /* not TARGET_AARCH64 */
524 #endif /* TARGET_ARM */
525
526 #ifdef TARGET_UNICORE32
527
528 #define ELF_START_MMAP          0x80000000
529
530 #define elf_check_arch(x)       ((x) == EM_UNICORE32)
531
532 #define ELF_CLASS               ELFCLASS32
533 #define ELF_DATA                ELFDATA2LSB
534 #define ELF_ARCH                EM_UNICORE32
535
536 static inline void init_thread(struct target_pt_regs *regs,
537         struct image_info *infop)
538 {
539     abi_long stack = infop->start_stack;
540     memset(regs, 0, sizeof(*regs));
541     regs->UC32_REG_asr = 0x10;
542     regs->UC32_REG_pc = infop->entry & 0xfffffffe;
543     regs->UC32_REG_sp = infop->start_stack;
544     /* FIXME - what to for failure of get_user()? */
545     get_user_ual(regs->UC32_REG_02, stack + 8); /* envp */
546     get_user_ual(regs->UC32_REG_01, stack + 4); /* envp */
547     /* XXX: it seems that r0 is zeroed after ! */
548     regs->UC32_REG_00 = 0;
549 }
550
551 #define ELF_NREG    34
552 typedef target_elf_greg_t  target_elf_gregset_t[ELF_NREG];
553
554 static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUUniCore32State *env)
555 {
556     (*regs)[0] = env->regs[0];
557     (*regs)[1] = env->regs[1];
558     (*regs)[2] = env->regs[2];
559     (*regs)[3] = env->regs[3];
560     (*regs)[4] = env->regs[4];
561     (*regs)[5] = env->regs[5];
562     (*regs)[6] = env->regs[6];
563     (*regs)[7] = env->regs[7];
564     (*regs)[8] = env->regs[8];
565     (*regs)[9] = env->regs[9];
566     (*regs)[10] = env->regs[10];
567     (*regs)[11] = env->regs[11];
568     (*regs)[12] = env->regs[12];
569     (*regs)[13] = env->regs[13];
570     (*regs)[14] = env->regs[14];
571     (*regs)[15] = env->regs[15];
572     (*regs)[16] = env->regs[16];
573     (*regs)[17] = env->regs[17];
574     (*regs)[18] = env->regs[18];
575     (*regs)[19] = env->regs[19];
576     (*regs)[20] = env->regs[20];
577     (*regs)[21] = env->regs[21];
578     (*regs)[22] = env->regs[22];
579     (*regs)[23] = env->regs[23];
580     (*regs)[24] = env->regs[24];
581     (*regs)[25] = env->regs[25];
582     (*regs)[26] = env->regs[26];
583     (*regs)[27] = env->regs[27];
584     (*regs)[28] = env->regs[28];
585     (*regs)[29] = env->regs[29];
586     (*regs)[30] = env->regs[30];
587     (*regs)[31] = env->regs[31];
588
589     (*regs)[32] = cpu_asr_read((CPUUniCore32State *)env);
590     (*regs)[33] = env->regs[0]; /* XXX */
591 }
592
593 #define USE_ELF_CORE_DUMP
594 #define ELF_EXEC_PAGESIZE               4096
595
596 #define ELF_HWCAP                       (UC32_HWCAP_CMOV | UC32_HWCAP_UCF64)
597
598 #endif
599
600 #ifdef TARGET_SPARC
601 #ifdef TARGET_SPARC64
602
603 #define ELF_START_MMAP 0x80000000
604 #define ELF_HWCAP  (HWCAP_SPARC_FLUSH | HWCAP_SPARC_STBAR | HWCAP_SPARC_SWAP \
605                     | HWCAP_SPARC_MULDIV | HWCAP_SPARC_V9)
606 #ifndef TARGET_ABI32
607 #define elf_check_arch(x) ( (x) == EM_SPARCV9 || (x) == EM_SPARC32PLUS )
608 #else
609 #define elf_check_arch(x) ( (x) == EM_SPARC32PLUS || (x) == EM_SPARC )
610 #endif
611
612 #define ELF_CLASS   ELFCLASS64
613 #define ELF_ARCH    EM_SPARCV9
614
615 #define STACK_BIAS              2047
616
617 static inline void init_thread(struct target_pt_regs *regs,
618                                struct image_info *infop)
619 {
620 #ifndef TARGET_ABI32
621     regs->tstate = 0;
622 #endif
623     regs->pc = infop->entry;
624     regs->npc = regs->pc + 4;
625     regs->y = 0;
626 #ifdef TARGET_ABI32
627     regs->u_regs[14] = infop->start_stack - 16 * 4;
628 #else
629     if (personality(infop->personality) == PER_LINUX32)
630         regs->u_regs[14] = infop->start_stack - 16 * 4;
631     else
632         regs->u_regs[14] = infop->start_stack - 16 * 8 - STACK_BIAS;
633 #endif
634 }
635
636 #else
637 #define ELF_START_MMAP 0x80000000
638 #define ELF_HWCAP  (HWCAP_SPARC_FLUSH | HWCAP_SPARC_STBAR | HWCAP_SPARC_SWAP \
639                     | HWCAP_SPARC_MULDIV)
640 #define elf_check_arch(x) ( (x) == EM_SPARC )
641
642 #define ELF_CLASS   ELFCLASS32
643 #define ELF_ARCH    EM_SPARC
644
645 static inline void init_thread(struct target_pt_regs *regs,
646                                struct image_info *infop)
647 {
648     regs->psr = 0;
649     regs->pc = infop->entry;
650     regs->npc = regs->pc + 4;
651     regs->y = 0;
652     regs->u_regs[14] = infop->start_stack - 16 * 4;
653 }
654
655 #endif
656 #endif
657
658 #ifdef TARGET_PPC
659
660 #define ELF_START_MMAP 0x80000000
661
662 #if defined(TARGET_PPC64) && !defined(TARGET_ABI32)
663
664 #define elf_check_arch(x) ( (x) == EM_PPC64 )
665
666 #define ELF_CLASS       ELFCLASS64
667
668 #else
669
670 #define elf_check_arch(x) ( (x) == EM_PPC )
671
672 #define ELF_CLASS       ELFCLASS32
673
674 #endif
675
676 #define ELF_ARCH        EM_PPC
677
678 /* Feature masks for the Aux Vector Hardware Capabilities (AT_HWCAP).
679    See arch/powerpc/include/asm/cputable.h.  */
680 enum {
681     QEMU_PPC_FEATURE_32 = 0x80000000,
682     QEMU_PPC_FEATURE_64 = 0x40000000,
683     QEMU_PPC_FEATURE_601_INSTR = 0x20000000,
684     QEMU_PPC_FEATURE_HAS_ALTIVEC = 0x10000000,
685     QEMU_PPC_FEATURE_HAS_FPU = 0x08000000,
686     QEMU_PPC_FEATURE_HAS_MMU = 0x04000000,
687     QEMU_PPC_FEATURE_HAS_4xxMAC = 0x02000000,
688     QEMU_PPC_FEATURE_UNIFIED_CACHE = 0x01000000,
689     QEMU_PPC_FEATURE_HAS_SPE = 0x00800000,
690     QEMU_PPC_FEATURE_HAS_EFP_SINGLE = 0x00400000,
691     QEMU_PPC_FEATURE_HAS_EFP_DOUBLE = 0x00200000,
692     QEMU_PPC_FEATURE_NO_TB = 0x00100000,
693     QEMU_PPC_FEATURE_POWER4 = 0x00080000,
694     QEMU_PPC_FEATURE_POWER5 = 0x00040000,
695     QEMU_PPC_FEATURE_POWER5_PLUS = 0x00020000,
696     QEMU_PPC_FEATURE_CELL = 0x00010000,
697     QEMU_PPC_FEATURE_BOOKE = 0x00008000,
698     QEMU_PPC_FEATURE_SMT = 0x00004000,
699     QEMU_PPC_FEATURE_ICACHE_SNOOP = 0x00002000,
700     QEMU_PPC_FEATURE_ARCH_2_05 = 0x00001000,
701     QEMU_PPC_FEATURE_PA6T = 0x00000800,
702     QEMU_PPC_FEATURE_HAS_DFP = 0x00000400,
703     QEMU_PPC_FEATURE_POWER6_EXT = 0x00000200,
704     QEMU_PPC_FEATURE_ARCH_2_06 = 0x00000100,
705     QEMU_PPC_FEATURE_HAS_VSX = 0x00000080,
706     QEMU_PPC_FEATURE_PSERIES_PERFMON_COMPAT = 0x00000040,
707
708     QEMU_PPC_FEATURE_TRUE_LE = 0x00000002,
709     QEMU_PPC_FEATURE_PPC_LE = 0x00000001,
710 };
711
712 #define ELF_HWCAP get_elf_hwcap()
713
714 static uint32_t get_elf_hwcap(void)
715 {
716     PowerPCCPU *cpu = POWERPC_CPU(thread_cpu);
717     uint32_t features = 0;
718
719     /* We don't have to be terribly complete here; the high points are
720        Altivec/FP/SPE support.  Anything else is just a bonus.  */
721 #define GET_FEATURE(flag, feature)                                      \
722     do { if (cpu->env.insns_flags & flag) { features |= feature; } } while (0)
723     GET_FEATURE(PPC_64B, QEMU_PPC_FEATURE_64);
724     GET_FEATURE(PPC_FLOAT, QEMU_PPC_FEATURE_HAS_FPU);
725     GET_FEATURE(PPC_ALTIVEC, QEMU_PPC_FEATURE_HAS_ALTIVEC);
726     GET_FEATURE(PPC_SPE, QEMU_PPC_FEATURE_HAS_SPE);
727     GET_FEATURE(PPC_SPE_SINGLE, QEMU_PPC_FEATURE_HAS_EFP_SINGLE);
728     GET_FEATURE(PPC_SPE_DOUBLE, QEMU_PPC_FEATURE_HAS_EFP_DOUBLE);
729     GET_FEATURE(PPC_BOOKE, QEMU_PPC_FEATURE_BOOKE);
730     GET_FEATURE(PPC_405_MAC, QEMU_PPC_FEATURE_HAS_4xxMAC);
731 #undef GET_FEATURE
732
733     return features;
734 }
735
736 /*
737  * The requirements here are:
738  * - keep the final alignment of sp (sp & 0xf)
739  * - make sure the 32-bit value at the first 16 byte aligned position of
740  *   AUXV is greater than 16 for glibc compatibility.
741  *   AT_IGNOREPPC is used for that.
742  * - for compatibility with glibc ARCH_DLINFO must always be defined on PPC,
743  *   even if DLINFO_ARCH_ITEMS goes to zero or is undefined.
744  */
745 #define DLINFO_ARCH_ITEMS       5
746 #define ARCH_DLINFO                                     \
747     do {                                                \
748         NEW_AUX_ENT(AT_DCACHEBSIZE, 0x20);              \
749         NEW_AUX_ENT(AT_ICACHEBSIZE, 0x20);              \
750         NEW_AUX_ENT(AT_UCACHEBSIZE, 0);                 \
751         /*                                              \
752          * Now handle glibc compatibility.              \
753          */                                             \
754         NEW_AUX_ENT(AT_IGNOREPPC, AT_IGNOREPPC);        \
755         NEW_AUX_ENT(AT_IGNOREPPC, AT_IGNOREPPC);        \
756     } while (0)
757
758 static inline void init_thread(struct target_pt_regs *_regs, struct image_info *infop)
759 {
760     _regs->gpr[1] = infop->start_stack;
761 #if defined(TARGET_PPC64) && !defined(TARGET_ABI32)
762     _regs->gpr[2] = ldq_raw(infop->entry + 8) + infop->load_bias;
763     infop->entry = ldq_raw(infop->entry) + infop->load_bias;
764 #endif
765     _regs->nip = infop->entry;
766 }
767
768 /* See linux kernel: arch/powerpc/include/asm/elf.h.  */
769 #define ELF_NREG 48
770 typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
771
772 static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUPPCState *env)
773 {
774     int i;
775     target_ulong ccr = 0;
776
777     for (i = 0; i < ARRAY_SIZE(env->gpr); i++) {
778         (*regs)[i] = tswapreg(env->gpr[i]);
779     }
780
781     (*regs)[32] = tswapreg(env->nip);
782     (*regs)[33] = tswapreg(env->msr);
783     (*regs)[35] = tswapreg(env->ctr);
784     (*regs)[36] = tswapreg(env->lr);
785     (*regs)[37] = tswapreg(env->xer);
786
787     for (i = 0; i < ARRAY_SIZE(env->crf); i++) {
788         ccr |= env->crf[i] << (32 - ((i + 1) * 4));
789     }
790     (*regs)[38] = tswapreg(ccr);
791 }
792
793 #define USE_ELF_CORE_DUMP
794 #define ELF_EXEC_PAGESIZE       4096
795
796 #endif
797
798 #ifdef TARGET_MIPS
799
800 #define ELF_START_MMAP 0x80000000
801
802 #define elf_check_arch(x) ( (x) == EM_MIPS )
803
804 #ifdef TARGET_MIPS64
805 #define ELF_CLASS   ELFCLASS64
806 #else
807 #define ELF_CLASS   ELFCLASS32
808 #endif
809 #define ELF_ARCH    EM_MIPS
810
811 static inline void init_thread(struct target_pt_regs *regs,
812                                struct image_info *infop)
813 {
814     regs->cp0_status = 2 << CP0St_KSU;
815     regs->cp0_epc = infop->entry;
816     regs->regs[29] = infop->start_stack;
817 }
818
819 /* See linux kernel: arch/mips/include/asm/elf.h.  */
820 #define ELF_NREG 45
821 typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
822
823 /* See linux kernel: arch/mips/include/asm/reg.h.  */
824 enum {
825 #ifdef TARGET_MIPS64
826     TARGET_EF_R0 = 0,
827 #else
828     TARGET_EF_R0 = 6,
829 #endif
830     TARGET_EF_R26 = TARGET_EF_R0 + 26,
831     TARGET_EF_R27 = TARGET_EF_R0 + 27,
832     TARGET_EF_LO = TARGET_EF_R0 + 32,
833     TARGET_EF_HI = TARGET_EF_R0 + 33,
834     TARGET_EF_CP0_EPC = TARGET_EF_R0 + 34,
835     TARGET_EF_CP0_BADVADDR = TARGET_EF_R0 + 35,
836     TARGET_EF_CP0_STATUS = TARGET_EF_R0 + 36,
837     TARGET_EF_CP0_CAUSE = TARGET_EF_R0 + 37
838 };
839
840 /* See linux kernel: arch/mips/kernel/process.c:elf_dump_regs.  */
841 static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUMIPSState *env)
842 {
843     int i;
844
845     for (i = 0; i < TARGET_EF_R0; i++) {
846         (*regs)[i] = 0;
847     }
848     (*regs)[TARGET_EF_R0] = 0;
849
850     for (i = 1; i < ARRAY_SIZE(env->active_tc.gpr); i++) {
851         (*regs)[TARGET_EF_R0 + i] = tswapreg(env->active_tc.gpr[i]);
852     }
853
854     (*regs)[TARGET_EF_R26] = 0;
855     (*regs)[TARGET_EF_R27] = 0;
856     (*regs)[TARGET_EF_LO] = tswapreg(env->active_tc.LO[0]);
857     (*regs)[TARGET_EF_HI] = tswapreg(env->active_tc.HI[0]);
858     (*regs)[TARGET_EF_CP0_EPC] = tswapreg(env->active_tc.PC);
859     (*regs)[TARGET_EF_CP0_BADVADDR] = tswapreg(env->CP0_BadVAddr);
860     (*regs)[TARGET_EF_CP0_STATUS] = tswapreg(env->CP0_Status);
861     (*regs)[TARGET_EF_CP0_CAUSE] = tswapreg(env->CP0_Cause);
862 }
863
864 #define USE_ELF_CORE_DUMP
865 #define ELF_EXEC_PAGESIZE        4096
866
867 #endif /* TARGET_MIPS */
868
869 #ifdef TARGET_MICROBLAZE
870
871 #define ELF_START_MMAP 0x80000000
872
873 #define elf_check_arch(x) ( (x) == EM_MICROBLAZE || (x) == EM_MICROBLAZE_OLD)
874
875 #define ELF_CLASS   ELFCLASS32
876 #define ELF_ARCH    EM_MICROBLAZE
877
878 static inline void init_thread(struct target_pt_regs *regs,
879                                struct image_info *infop)
880 {
881     regs->pc = infop->entry;
882     regs->r1 = infop->start_stack;
883
884 }
885
886 #define ELF_EXEC_PAGESIZE        4096
887
888 #define USE_ELF_CORE_DUMP
889 #define ELF_NREG 38
890 typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
891
892 /* See linux kernel: arch/mips/kernel/process.c:elf_dump_regs.  */
893 static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUMBState *env)
894 {
895     int i, pos = 0;
896
897     for (i = 0; i < 32; i++) {
898         (*regs)[pos++] = tswapreg(env->regs[i]);
899     }
900
901     for (i = 0; i < 6; i++) {
902         (*regs)[pos++] = tswapreg(env->sregs[i]);
903     }
904 }
905
906 #endif /* TARGET_MICROBLAZE */
907
908 #ifdef TARGET_OPENRISC
909
910 #define ELF_START_MMAP 0x08000000
911
912 #define elf_check_arch(x) ((x) == EM_OPENRISC)
913
914 #define ELF_ARCH EM_OPENRISC
915 #define ELF_CLASS ELFCLASS32
916 #define ELF_DATA  ELFDATA2MSB
917
918 static inline void init_thread(struct target_pt_regs *regs,
919                                struct image_info *infop)
920 {
921     regs->pc = infop->entry;
922     regs->gpr[1] = infop->start_stack;
923 }
924
925 #define USE_ELF_CORE_DUMP
926 #define ELF_EXEC_PAGESIZE 8192
927
928 /* See linux kernel arch/openrisc/include/asm/elf.h.  */
929 #define ELF_NREG 34 /* gprs and pc, sr */
930 typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
931
932 static void elf_core_copy_regs(target_elf_gregset_t *regs,
933                                const CPUOpenRISCState *env)
934 {
935     int i;
936
937     for (i = 0; i < 32; i++) {
938         (*regs)[i] = tswapreg(env->gpr[i]);
939     }
940
941     (*regs)[32] = tswapreg(env->pc);
942     (*regs)[33] = tswapreg(env->sr);
943 }
944 #define ELF_HWCAP 0
945 #define ELF_PLATFORM NULL
946
947 #endif /* TARGET_OPENRISC */
948
949 #ifdef TARGET_SH4
950
951 #define ELF_START_MMAP 0x80000000
952
953 #define elf_check_arch(x) ( (x) == EM_SH )
954
955 #define ELF_CLASS ELFCLASS32
956 #define ELF_ARCH  EM_SH
957
958 static inline void init_thread(struct target_pt_regs *regs,
959                                struct image_info *infop)
960 {
961     /* Check other registers XXXXX */
962     regs->pc = infop->entry;
963     regs->regs[15] = infop->start_stack;
964 }
965
966 /* See linux kernel: arch/sh/include/asm/elf.h.  */
967 #define ELF_NREG 23
968 typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
969
970 /* See linux kernel: arch/sh/include/asm/ptrace.h.  */
971 enum {
972     TARGET_REG_PC = 16,
973     TARGET_REG_PR = 17,
974     TARGET_REG_SR = 18,
975     TARGET_REG_GBR = 19,
976     TARGET_REG_MACH = 20,
977     TARGET_REG_MACL = 21,
978     TARGET_REG_SYSCALL = 22
979 };
980
981 static inline void elf_core_copy_regs(target_elf_gregset_t *regs,
982                                       const CPUSH4State *env)
983 {
984     int i;
985
986     for (i = 0; i < 16; i++) {
987         (*regs[i]) = tswapreg(env->gregs[i]);
988     }
989
990     (*regs)[TARGET_REG_PC] = tswapreg(env->pc);
991     (*regs)[TARGET_REG_PR] = tswapreg(env->pr);
992     (*regs)[TARGET_REG_SR] = tswapreg(env->sr);
993     (*regs)[TARGET_REG_GBR] = tswapreg(env->gbr);
994     (*regs)[TARGET_REG_MACH] = tswapreg(env->mach);
995     (*regs)[TARGET_REG_MACL] = tswapreg(env->macl);
996     (*regs)[TARGET_REG_SYSCALL] = 0; /* FIXME */
997 }
998
999 #define USE_ELF_CORE_DUMP
1000 #define ELF_EXEC_PAGESIZE        4096
1001
1002 #endif
1003
1004 #ifdef TARGET_CRIS
1005
1006 #define ELF_START_MMAP 0x80000000
1007
1008 #define elf_check_arch(x) ( (x) == EM_CRIS )
1009
1010 #define ELF_CLASS ELFCLASS32
1011 #define ELF_ARCH  EM_CRIS
1012
1013 static inline void init_thread(struct target_pt_regs *regs,
1014                                struct image_info *infop)
1015 {
1016     regs->erp = infop->entry;
1017 }
1018
1019 #define ELF_EXEC_PAGESIZE        8192
1020
1021 #endif
1022
1023 #ifdef TARGET_M68K
1024
1025 #define ELF_START_MMAP 0x80000000
1026
1027 #define elf_check_arch(x) ( (x) == EM_68K )
1028
1029 #define ELF_CLASS       ELFCLASS32
1030 #define ELF_ARCH        EM_68K
1031
1032 /* ??? Does this need to do anything?
1033    #define ELF_PLAT_INIT(_r) */
1034
1035 static inline void init_thread(struct target_pt_regs *regs,
1036                                struct image_info *infop)
1037 {
1038     regs->usp = infop->start_stack;
1039     regs->sr = 0;
1040     regs->pc = infop->entry;
1041 }
1042
1043 /* See linux kernel: arch/m68k/include/asm/elf.h.  */
1044 #define ELF_NREG 20
1045 typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
1046
1047 static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUM68KState *env)
1048 {
1049     (*regs)[0] = tswapreg(env->dregs[1]);
1050     (*regs)[1] = tswapreg(env->dregs[2]);
1051     (*regs)[2] = tswapreg(env->dregs[3]);
1052     (*regs)[3] = tswapreg(env->dregs[4]);
1053     (*regs)[4] = tswapreg(env->dregs[5]);
1054     (*regs)[5] = tswapreg(env->dregs[6]);
1055     (*regs)[6] = tswapreg(env->dregs[7]);
1056     (*regs)[7] = tswapreg(env->aregs[0]);
1057     (*regs)[8] = tswapreg(env->aregs[1]);
1058     (*regs)[9] = tswapreg(env->aregs[2]);
1059     (*regs)[10] = tswapreg(env->aregs[3]);
1060     (*regs)[11] = tswapreg(env->aregs[4]);
1061     (*regs)[12] = tswapreg(env->aregs[5]);
1062     (*regs)[13] = tswapreg(env->aregs[6]);
1063     (*regs)[14] = tswapreg(env->dregs[0]);
1064     (*regs)[15] = tswapreg(env->aregs[7]);
1065     (*regs)[16] = tswapreg(env->dregs[0]); /* FIXME: orig_d0 */
1066     (*regs)[17] = tswapreg(env->sr);
1067     (*regs)[18] = tswapreg(env->pc);
1068     (*regs)[19] = 0;  /* FIXME: regs->format | regs->vector */
1069 }
1070
1071 #define USE_ELF_CORE_DUMP
1072 #define ELF_EXEC_PAGESIZE       8192
1073
1074 #endif
1075
1076 #ifdef TARGET_ALPHA
1077
1078 #define ELF_START_MMAP (0x30000000000ULL)
1079
1080 #define elf_check_arch(x) ( (x) == ELF_ARCH )
1081
1082 #define ELF_CLASS      ELFCLASS64
1083 #define ELF_ARCH       EM_ALPHA
1084
1085 static inline void init_thread(struct target_pt_regs *regs,
1086                                struct image_info *infop)
1087 {
1088     regs->pc = infop->entry;
1089     regs->ps = 8;
1090     regs->usp = infop->start_stack;
1091 }
1092
1093 #define ELF_EXEC_PAGESIZE        8192
1094
1095 #endif /* TARGET_ALPHA */
1096
1097 #ifdef TARGET_S390X
1098
1099 #define ELF_START_MMAP (0x20000000000ULL)
1100
1101 #define elf_check_arch(x) ( (x) == ELF_ARCH )
1102
1103 #define ELF_CLASS       ELFCLASS64
1104 #define ELF_DATA        ELFDATA2MSB
1105 #define ELF_ARCH        EM_S390
1106
1107 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
1108 {
1109     regs->psw.addr = infop->entry;
1110     regs->psw.mask = PSW_MASK_64 | PSW_MASK_32;
1111     regs->gprs[15] = infop->start_stack;
1112 }
1113
1114 #endif /* TARGET_S390X */
1115
1116 #ifndef ELF_PLATFORM
1117 #define ELF_PLATFORM (NULL)
1118 #endif
1119
1120 #ifndef ELF_HWCAP
1121 #define ELF_HWCAP 0
1122 #endif
1123
1124 #ifdef TARGET_ABI32
1125 #undef ELF_CLASS
1126 #define ELF_CLASS ELFCLASS32
1127 #undef bswaptls
1128 #define bswaptls(ptr) bswap32s(ptr)
1129 #endif
1130
1131 #include "elf.h"
1132
1133 struct exec
1134 {
1135     unsigned int a_info;   /* Use macros N_MAGIC, etc for access */
1136     unsigned int a_text;   /* length of text, in bytes */
1137     unsigned int a_data;   /* length of data, in bytes */
1138     unsigned int a_bss;    /* length of uninitialized data area, in bytes */
1139     unsigned int a_syms;   /* length of symbol table data in file, in bytes */
1140     unsigned int a_entry;  /* start address */
1141     unsigned int a_trsize; /* length of relocation info for text, in bytes */
1142     unsigned int a_drsize; /* length of relocation info for data, in bytes */
1143 };
1144
1145
1146 #define N_MAGIC(exec) ((exec).a_info & 0xffff)
1147 #define OMAGIC 0407
1148 #define NMAGIC 0410
1149 #define ZMAGIC 0413
1150 #define QMAGIC 0314
1151
1152 /* Necessary parameters */
1153 #define TARGET_ELF_EXEC_PAGESIZE TARGET_PAGE_SIZE
1154 #define TARGET_ELF_PAGESTART(_v) ((_v) & ~(unsigned long)(TARGET_ELF_EXEC_PAGESIZE-1))
1155 #define TARGET_ELF_PAGEOFFSET(_v) ((_v) & (TARGET_ELF_EXEC_PAGESIZE-1))
1156
1157 #define DLINFO_ITEMS 13
1158
1159 static inline void memcpy_fromfs(void * to, const void * from, unsigned long n)
1160 {
1161     memcpy(to, from, n);
1162 }
1163
1164 #ifdef BSWAP_NEEDED
1165 static void bswap_ehdr(struct elfhdr *ehdr)
1166 {
1167     bswap16s(&ehdr->e_type);            /* Object file type */
1168     bswap16s(&ehdr->e_machine);         /* Architecture */
1169     bswap32s(&ehdr->e_version);         /* Object file version */
1170     bswaptls(&ehdr->e_entry);           /* Entry point virtual address */
1171     bswaptls(&ehdr->e_phoff);           /* Program header table file offset */
1172     bswaptls(&ehdr->e_shoff);           /* Section header table file offset */
1173     bswap32s(&ehdr->e_flags);           /* Processor-specific flags */
1174     bswap16s(&ehdr->e_ehsize);          /* ELF header size in bytes */
1175     bswap16s(&ehdr->e_phentsize);       /* Program header table entry size */
1176     bswap16s(&ehdr->e_phnum);           /* Program header table entry count */
1177     bswap16s(&ehdr->e_shentsize);       /* Section header table entry size */
1178     bswap16s(&ehdr->e_shnum);           /* Section header table entry count */
1179     bswap16s(&ehdr->e_shstrndx);        /* Section header string table index */
1180 }
1181
1182 static void bswap_phdr(struct elf_phdr *phdr, int phnum)
1183 {
1184     int i;
1185     for (i = 0; i < phnum; ++i, ++phdr) {
1186         bswap32s(&phdr->p_type);        /* Segment type */
1187         bswap32s(&phdr->p_flags);       /* Segment flags */
1188         bswaptls(&phdr->p_offset);      /* Segment file offset */
1189         bswaptls(&phdr->p_vaddr);       /* Segment virtual address */
1190         bswaptls(&phdr->p_paddr);       /* Segment physical address */
1191         bswaptls(&phdr->p_filesz);      /* Segment size in file */
1192         bswaptls(&phdr->p_memsz);       /* Segment size in memory */
1193         bswaptls(&phdr->p_align);       /* Segment alignment */
1194     }
1195 }
1196
1197 static void bswap_shdr(struct elf_shdr *shdr, int shnum)
1198 {
1199     int i;
1200     for (i = 0; i < shnum; ++i, ++shdr) {
1201         bswap32s(&shdr->sh_name);
1202         bswap32s(&shdr->sh_type);
1203         bswaptls(&shdr->sh_flags);
1204         bswaptls(&shdr->sh_addr);
1205         bswaptls(&shdr->sh_offset);
1206         bswaptls(&shdr->sh_size);
1207         bswap32s(&shdr->sh_link);
1208         bswap32s(&shdr->sh_info);
1209         bswaptls(&shdr->sh_addralign);
1210         bswaptls(&shdr->sh_entsize);
1211     }
1212 }
1213
1214 static void bswap_sym(struct elf_sym *sym)
1215 {
1216     bswap32s(&sym->st_name);
1217     bswaptls(&sym->st_value);
1218     bswaptls(&sym->st_size);
1219     bswap16s(&sym->st_shndx);
1220 }
1221 #else
1222 static inline void bswap_ehdr(struct elfhdr *ehdr) { }
1223 static inline void bswap_phdr(struct elf_phdr *phdr, int phnum) { }
1224 static inline void bswap_shdr(struct elf_shdr *shdr, int shnum) { }
1225 static inline void bswap_sym(struct elf_sym *sym) { }
1226 #endif
1227
1228 #ifdef USE_ELF_CORE_DUMP
1229 static int elf_core_dump(int, const CPUArchState *);
1230 #endif /* USE_ELF_CORE_DUMP */
1231 static void load_symbols(struct elfhdr *hdr, int fd, abi_ulong load_bias);
1232
1233 /* Verify the portions of EHDR within E_IDENT for the target.
1234    This can be performed before bswapping the entire header.  */
1235 static bool elf_check_ident(struct elfhdr *ehdr)
1236 {
1237     return (ehdr->e_ident[EI_MAG0] == ELFMAG0
1238             && ehdr->e_ident[EI_MAG1] == ELFMAG1
1239             && ehdr->e_ident[EI_MAG2] == ELFMAG2
1240             && ehdr->e_ident[EI_MAG3] == ELFMAG3
1241             && ehdr->e_ident[EI_CLASS] == ELF_CLASS
1242             && ehdr->e_ident[EI_DATA] == ELF_DATA
1243             && ehdr->e_ident[EI_VERSION] == EV_CURRENT);
1244 }
1245
1246 /* Verify the portions of EHDR outside of E_IDENT for the target.
1247    This has to wait until after bswapping the header.  */
1248 static bool elf_check_ehdr(struct elfhdr *ehdr)
1249 {
1250     return (elf_check_arch(ehdr->e_machine)
1251             && ehdr->e_ehsize == sizeof(struct elfhdr)
1252             && ehdr->e_phentsize == sizeof(struct elf_phdr)
1253             && ehdr->e_shentsize == sizeof(struct elf_shdr)
1254             && (ehdr->e_type == ET_EXEC || ehdr->e_type == ET_DYN));
1255 }
1256
1257 /*
1258  * 'copy_elf_strings()' copies argument/envelope strings from user
1259  * memory to free pages in kernel mem. These are in a format ready
1260  * to be put directly into the top of new user memory.
1261  *
1262  */
1263 static abi_ulong copy_elf_strings(int argc,char ** argv, void **page,
1264                                   abi_ulong p)
1265 {
1266     char *tmp, *tmp1, *pag = NULL;
1267     int len, offset = 0;
1268
1269     if (!p) {
1270         return 0;       /* bullet-proofing */
1271     }
1272     while (argc-- > 0) {
1273         tmp = argv[argc];
1274         if (!tmp) {
1275             fprintf(stderr, "VFS: argc is wrong");
1276             exit(-1);
1277         }
1278         tmp1 = tmp;
1279         while (*tmp++);
1280         len = tmp - tmp1;
1281         if (p < len) {  /* this shouldn't happen - 128kB */
1282             return 0;
1283         }
1284         while (len) {
1285             --p; --tmp; --len;
1286             if (--offset < 0) {
1287                 offset = p % TARGET_PAGE_SIZE;
1288                 pag = (char *)page[p/TARGET_PAGE_SIZE];
1289                 if (!pag) {
1290                     pag = g_try_malloc0(TARGET_PAGE_SIZE);
1291                     page[p/TARGET_PAGE_SIZE] = pag;
1292                     if (!pag)
1293                         return 0;
1294                 }
1295             }
1296             if (len == 0 || offset == 0) {
1297                 *(pag + offset) = *tmp;
1298             }
1299             else {
1300                 int bytes_to_copy = (len > offset) ? offset : len;
1301                 tmp -= bytes_to_copy;
1302                 p -= bytes_to_copy;
1303                 offset -= bytes_to_copy;
1304                 len -= bytes_to_copy;
1305                 memcpy_fromfs(pag + offset, tmp, bytes_to_copy + 1);
1306             }
1307         }
1308     }
1309     return p;
1310 }
1311
1312 static abi_ulong setup_arg_pages(abi_ulong p, struct linux_binprm *bprm,
1313                                  struct image_info *info)
1314 {
1315     abi_ulong stack_base, size, error, guard;
1316     int i;
1317
1318     /* Create enough stack to hold everything.  If we don't use
1319        it for args, we'll use it for something else.  */
1320     size = guest_stack_size;
1321     if (size < MAX_ARG_PAGES*TARGET_PAGE_SIZE) {
1322         size = MAX_ARG_PAGES*TARGET_PAGE_SIZE;
1323     }
1324     guard = TARGET_PAGE_SIZE;
1325     if (guard < qemu_real_host_page_size) {
1326         guard = qemu_real_host_page_size;
1327     }
1328
1329     error = target_mmap(0, size + guard, PROT_READ | PROT_WRITE,
1330                         MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
1331     if (error == -1) {
1332         perror("mmap stack");
1333         exit(-1);
1334     }
1335
1336     /* We reserve one extra page at the top of the stack as guard.  */
1337     target_mprotect(error, guard, PROT_NONE);
1338
1339     info->stack_limit = error + guard;
1340     stack_base = info->stack_limit + size - MAX_ARG_PAGES*TARGET_PAGE_SIZE;
1341     p += stack_base;
1342
1343     for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
1344         if (bprm->page[i]) {
1345             info->rss++;
1346             /* FIXME - check return value of memcpy_to_target() for failure */
1347             memcpy_to_target(stack_base, bprm->page[i], TARGET_PAGE_SIZE);
1348             g_free(bprm->page[i]);
1349         }
1350         stack_base += TARGET_PAGE_SIZE;
1351     }
1352     return p;
1353 }
1354
1355 /* Map and zero the bss.  We need to explicitly zero any fractional pages
1356    after the data section (i.e. bss).  */
1357 static void zero_bss(abi_ulong elf_bss, abi_ulong last_bss, int prot)
1358 {
1359     uintptr_t host_start, host_map_start, host_end;
1360
1361     last_bss = TARGET_PAGE_ALIGN(last_bss);
1362
1363     /* ??? There is confusion between qemu_real_host_page_size and
1364        qemu_host_page_size here and elsewhere in target_mmap, which
1365        may lead to the end of the data section mapping from the file
1366        not being mapped.  At least there was an explicit test and
1367        comment for that here, suggesting that "the file size must
1368        be known".  The comment probably pre-dates the introduction
1369        of the fstat system call in target_mmap which does in fact
1370        find out the size.  What isn't clear is if the workaround
1371        here is still actually needed.  For now, continue with it,
1372        but merge it with the "normal" mmap that would allocate the bss.  */
1373
1374     host_start = (uintptr_t) g2h(elf_bss);
1375     host_end = (uintptr_t) g2h(last_bss);
1376     host_map_start = (host_start + qemu_real_host_page_size - 1);
1377     host_map_start &= -qemu_real_host_page_size;
1378
1379     if (host_map_start < host_end) {
1380         void *p = mmap((void *)host_map_start, host_end - host_map_start,
1381                        prot, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
1382         if (p == MAP_FAILED) {
1383             perror("cannot mmap brk");
1384             exit(-1);
1385         }
1386
1387         /* Since we didn't use target_mmap, make sure to record
1388            the validity of the pages with qemu.  */
1389         page_set_flags(elf_bss & TARGET_PAGE_MASK, last_bss, prot|PAGE_VALID);
1390     }
1391
1392     if (host_start < host_map_start) {
1393         memset((void *)host_start, 0, host_map_start - host_start);
1394     }
1395 }
1396
1397 #ifdef CONFIG_USE_FDPIC
1398 static abi_ulong loader_build_fdpic_loadmap(struct image_info *info, abi_ulong sp)
1399 {
1400     uint16_t n;
1401     struct elf32_fdpic_loadseg *loadsegs = info->loadsegs;
1402
1403     /* elf32_fdpic_loadseg */
1404     n = info->nsegs;
1405     while (n--) {
1406         sp -= 12;
1407         put_user_u32(loadsegs[n].addr, sp+0);
1408         put_user_u32(loadsegs[n].p_vaddr, sp+4);
1409         put_user_u32(loadsegs[n].p_memsz, sp+8);
1410     }
1411
1412     /* elf32_fdpic_loadmap */
1413     sp -= 4;
1414     put_user_u16(0, sp+0); /* version */
1415     put_user_u16(info->nsegs, sp+2); /* nsegs */
1416
1417     info->personality = PER_LINUX_FDPIC;
1418     info->loadmap_addr = sp;
1419
1420     return sp;
1421 }
1422 #endif
1423
1424 static abi_ulong create_elf_tables(abi_ulong p, int argc, int envc,
1425                                    struct elfhdr *exec,
1426                                    struct image_info *info,
1427                                    struct image_info *interp_info)
1428 {
1429     abi_ulong sp;
1430     abi_ulong sp_auxv;
1431     int size;
1432     int i;
1433     abi_ulong u_rand_bytes;
1434     uint8_t k_rand_bytes[16];
1435     abi_ulong u_platform;
1436     const char *k_platform;
1437     const int n = sizeof(elf_addr_t);
1438
1439     sp = p;
1440
1441 #ifdef CONFIG_USE_FDPIC
1442     /* Needs to be before we load the env/argc/... */
1443     if (elf_is_fdpic(exec)) {
1444         /* Need 4 byte alignment for these structs */
1445         sp &= ~3;
1446         sp = loader_build_fdpic_loadmap(info, sp);
1447         info->other_info = interp_info;
1448         if (interp_info) {
1449             interp_info->other_info = info;
1450             sp = loader_build_fdpic_loadmap(interp_info, sp);
1451         }
1452     }
1453 #endif
1454
1455     u_platform = 0;
1456     k_platform = ELF_PLATFORM;
1457     if (k_platform) {
1458         size_t len = strlen(k_platform) + 1;
1459         sp -= (len + n - 1) & ~(n - 1);
1460         u_platform = sp;
1461         /* FIXME - check return value of memcpy_to_target() for failure */
1462         memcpy_to_target(sp, k_platform, len);
1463     }
1464
1465     /*
1466      * Generate 16 random bytes for userspace PRNG seeding (not
1467      * cryptically secure but it's not the aim of QEMU).
1468      */
1469     srand((unsigned int) time(NULL));
1470     for (i = 0; i < 16; i++) {
1471         k_rand_bytes[i] = rand();
1472     }
1473     sp -= 16;
1474     u_rand_bytes = sp;
1475     /* FIXME - check return value of memcpy_to_target() for failure */
1476     memcpy_to_target(sp, k_rand_bytes, 16);
1477
1478     /*
1479      * Force 16 byte _final_ alignment here for generality.
1480      */
1481     sp = sp &~ (abi_ulong)15;
1482     size = (DLINFO_ITEMS + 1) * 2;
1483     if (k_platform)
1484         size += 2;
1485 #ifdef DLINFO_ARCH_ITEMS
1486     size += DLINFO_ARCH_ITEMS * 2;
1487 #endif
1488     size += envc + argc + 2;
1489     size += 1;  /* argc itself */
1490     size *= n;
1491     if (size & 15)
1492         sp -= 16 - (size & 15);
1493
1494     /* This is correct because Linux defines
1495      * elf_addr_t as Elf32_Off / Elf64_Off
1496      */
1497 #define NEW_AUX_ENT(id, val) do {               \
1498         sp -= n; put_user_ual(val, sp);         \
1499         sp -= n; put_user_ual(id, sp);          \
1500     } while(0)
1501
1502     sp_auxv = sp;
1503     NEW_AUX_ENT (AT_NULL, 0);
1504
1505     /* There must be exactly DLINFO_ITEMS entries here.  */
1506     NEW_AUX_ENT(AT_PHDR, (abi_ulong)(info->load_addr + exec->e_phoff));
1507     NEW_AUX_ENT(AT_PHENT, (abi_ulong)(sizeof (struct elf_phdr)));
1508     NEW_AUX_ENT(AT_PHNUM, (abi_ulong)(exec->e_phnum));
1509     NEW_AUX_ENT(AT_PAGESZ, (abi_ulong)(TARGET_PAGE_SIZE));
1510     NEW_AUX_ENT(AT_BASE, (abi_ulong)(interp_info ? interp_info->load_addr : 0));
1511     NEW_AUX_ENT(AT_FLAGS, (abi_ulong)0);
1512     NEW_AUX_ENT(AT_ENTRY, info->entry);
1513     NEW_AUX_ENT(AT_UID, (abi_ulong) getuid());
1514     NEW_AUX_ENT(AT_EUID, (abi_ulong) geteuid());
1515     NEW_AUX_ENT(AT_GID, (abi_ulong) getgid());
1516     NEW_AUX_ENT(AT_EGID, (abi_ulong) getegid());
1517     NEW_AUX_ENT(AT_HWCAP, (abi_ulong) ELF_HWCAP);
1518     NEW_AUX_ENT(AT_CLKTCK, (abi_ulong) sysconf(_SC_CLK_TCK));
1519     NEW_AUX_ENT(AT_RANDOM, (abi_ulong) u_rand_bytes);
1520
1521     if (k_platform)
1522         NEW_AUX_ENT(AT_PLATFORM, u_platform);
1523 #ifdef ARCH_DLINFO
1524     /*
1525      * ARCH_DLINFO must come last so platform specific code can enforce
1526      * special alignment requirements on the AUXV if necessary (eg. PPC).
1527      */
1528     ARCH_DLINFO;
1529 #endif
1530 #undef NEW_AUX_ENT
1531
1532     info->saved_auxv = sp;
1533     info->auxv_len = sp_auxv - sp;
1534
1535     sp = loader_build_argptr(envc, argc, sp, p, 0);
1536     return sp;
1537 }
1538
1539 #ifndef TARGET_HAS_VALIDATE_GUEST_SPACE
1540 /* If the guest doesn't have a validation function just agree */
1541 static int validate_guest_space(unsigned long guest_base,
1542                                 unsigned long guest_size)
1543 {
1544     return 1;
1545 }
1546 #endif
1547
1548 unsigned long init_guest_space(unsigned long host_start,
1549                                unsigned long host_size,
1550                                unsigned long guest_start,
1551                                bool fixed)
1552 {
1553     unsigned long current_start, real_start;
1554     int flags;
1555
1556     assert(host_start || host_size);
1557
1558     /* If just a starting address is given, then just verify that
1559      * address.  */
1560     if (host_start && !host_size) {
1561         if (validate_guest_space(host_start, host_size) == 1) {
1562             return host_start;
1563         } else {
1564             return (unsigned long)-1;
1565         }
1566     }
1567
1568     /* Setup the initial flags and start address.  */
1569     current_start = host_start & qemu_host_page_mask;
1570     flags = MAP_ANONYMOUS | MAP_PRIVATE | MAP_NORESERVE;
1571     if (fixed) {
1572         flags |= MAP_FIXED;
1573     }
1574
1575     /* Otherwise, a non-zero size region of memory needs to be mapped
1576      * and validated.  */
1577     while (1) {
1578         unsigned long real_size = host_size;
1579
1580         /* Do not use mmap_find_vma here because that is limited to the
1581          * guest address space.  We are going to make the
1582          * guest address space fit whatever we're given.
1583          */
1584         real_start = (unsigned long)
1585             mmap((void *)current_start, host_size, PROT_NONE, flags, -1, 0);
1586         if (real_start == (unsigned long)-1) {
1587             return (unsigned long)-1;
1588         }
1589
1590         /* Ensure the address is properly aligned.  */
1591         if (real_start & ~qemu_host_page_mask) {
1592             munmap((void *)real_start, host_size);
1593             real_size = host_size + qemu_host_page_size;
1594             real_start = (unsigned long)
1595                 mmap((void *)real_start, real_size, PROT_NONE, flags, -1, 0);
1596             if (real_start == (unsigned long)-1) {
1597                 return (unsigned long)-1;
1598             }
1599             real_start = HOST_PAGE_ALIGN(real_start);
1600         }
1601
1602         /* Check to see if the address is valid.  */
1603         if (!host_start || real_start == current_start) {
1604             int valid = validate_guest_space(real_start - guest_start,
1605                                              real_size);
1606             if (valid == 1) {
1607                 break;
1608             } else if (valid == -1) {
1609                 return (unsigned long)-1;
1610             }
1611             /* valid == 0, so try again. */
1612         }
1613
1614         /* That address didn't work.  Unmap and try a different one.
1615          * The address the host picked because is typically right at
1616          * the top of the host address space and leaves the guest with
1617          * no usable address space.  Resort to a linear search.  We
1618          * already compensated for mmap_min_addr, so this should not
1619          * happen often.  Probably means we got unlucky and host
1620          * address space randomization put a shared library somewhere
1621          * inconvenient.
1622          */
1623         munmap((void *)real_start, host_size);
1624         current_start += qemu_host_page_size;
1625         if (host_start == current_start) {
1626             /* Theoretically possible if host doesn't have any suitably
1627              * aligned areas.  Normally the first mmap will fail.
1628              */
1629             return (unsigned long)-1;
1630         }
1631     }
1632
1633     qemu_log("Reserved 0x%lx bytes of guest address space\n", host_size);
1634
1635     return real_start;
1636 }
1637
1638 static void probe_guest_base(const char *image_name,
1639                              abi_ulong loaddr, abi_ulong hiaddr)
1640 {
1641     /* Probe for a suitable guest base address, if the user has not set
1642      * it explicitly, and set guest_base appropriately.
1643      * In case of error we will print a suitable message and exit.
1644      */
1645 #if defined(CONFIG_USE_GUEST_BASE)
1646     const char *errmsg;
1647     if (!have_guest_base && !reserved_va) {
1648         unsigned long host_start, real_start, host_size;
1649
1650         /* Round addresses to page boundaries.  */
1651         loaddr &= qemu_host_page_mask;
1652         hiaddr = HOST_PAGE_ALIGN(hiaddr);
1653
1654         if (loaddr < mmap_min_addr) {
1655             host_start = HOST_PAGE_ALIGN(mmap_min_addr);
1656         } else {
1657             host_start = loaddr;
1658             if (host_start != loaddr) {
1659                 errmsg = "Address overflow loading ELF binary";
1660                 goto exit_errmsg;
1661             }
1662         }
1663         host_size = hiaddr - loaddr;
1664
1665         /* Setup the initial guest memory space with ranges gleaned from
1666          * the ELF image that is being loaded.
1667          */
1668         real_start = init_guest_space(host_start, host_size, loaddr, false);
1669         if (real_start == (unsigned long)-1) {
1670             errmsg = "Unable to find space for application";
1671             goto exit_errmsg;
1672         }
1673         guest_base = real_start - loaddr;
1674
1675         qemu_log("Relocating guest address space from 0x"
1676                  TARGET_ABI_FMT_lx " to 0x%lx\n",
1677                  loaddr, real_start);
1678     }
1679     return;
1680
1681 exit_errmsg:
1682     fprintf(stderr, "%s: %s\n", image_name, errmsg);
1683     exit(-1);
1684 #endif
1685 }
1686
1687
1688 /* Load an ELF image into the address space.
1689
1690    IMAGE_NAME is the filename of the image, to use in error messages.
1691    IMAGE_FD is the open file descriptor for the image.
1692
1693    BPRM_BUF is a copy of the beginning of the file; this of course
1694    contains the elf file header at offset 0.  It is assumed that this
1695    buffer is sufficiently aligned to present no problems to the host
1696    in accessing data at aligned offsets within the buffer.
1697
1698    On return: INFO values will be filled in, as necessary or available.  */
1699
1700 static void load_elf_image(const char *image_name, int image_fd,
1701                            struct image_info *info, char **pinterp_name,
1702                            char bprm_buf[BPRM_BUF_SIZE])
1703 {
1704     struct elfhdr *ehdr = (struct elfhdr *)bprm_buf;
1705     struct elf_phdr *phdr;
1706     abi_ulong load_addr, load_bias, loaddr, hiaddr, error;
1707     int i, retval;
1708     const char *errmsg;
1709
1710     /* First of all, some simple consistency checks */
1711     errmsg = "Invalid ELF image for this architecture";
1712     if (!elf_check_ident(ehdr)) {
1713         goto exit_errmsg;
1714     }
1715     bswap_ehdr(ehdr);
1716     if (!elf_check_ehdr(ehdr)) {
1717         goto exit_errmsg;
1718     }
1719
1720     i = ehdr->e_phnum * sizeof(struct elf_phdr);
1721     if (ehdr->e_phoff + i <= BPRM_BUF_SIZE) {
1722         phdr = (struct elf_phdr *)(bprm_buf + ehdr->e_phoff);
1723     } else {
1724         phdr = (struct elf_phdr *) alloca(i);
1725         retval = pread(image_fd, phdr, i, ehdr->e_phoff);
1726         if (retval != i) {
1727             goto exit_read;
1728         }
1729     }
1730     bswap_phdr(phdr, ehdr->e_phnum);
1731
1732 #ifdef CONFIG_USE_FDPIC
1733     info->nsegs = 0;
1734     info->pt_dynamic_addr = 0;
1735 #endif
1736
1737     /* Find the maximum size of the image and allocate an appropriate
1738        amount of memory to handle that.  */
1739     loaddr = -1, hiaddr = 0;
1740     for (i = 0; i < ehdr->e_phnum; ++i) {
1741         if (phdr[i].p_type == PT_LOAD) {
1742             abi_ulong a = phdr[i].p_vaddr;
1743             if (a < loaddr) {
1744                 loaddr = a;
1745             }
1746             a += phdr[i].p_memsz;
1747             if (a > hiaddr) {
1748                 hiaddr = a;
1749             }
1750 #ifdef CONFIG_USE_FDPIC
1751             ++info->nsegs;
1752 #endif
1753         }
1754     }
1755
1756     load_addr = loaddr;
1757     if (ehdr->e_type == ET_DYN) {
1758         /* The image indicates that it can be loaded anywhere.  Find a
1759            location that can hold the memory space required.  If the
1760            image is pre-linked, LOADDR will be non-zero.  Since we do
1761            not supply MAP_FIXED here we'll use that address if and
1762            only if it remains available.  */
1763         load_addr = target_mmap(loaddr, hiaddr - loaddr, PROT_NONE,
1764                                 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
1765                                 -1, 0);
1766         if (load_addr == -1) {
1767             goto exit_perror;
1768         }
1769     } else if (pinterp_name != NULL) {
1770         /* This is the main executable.  Make sure that the low
1771            address does not conflict with MMAP_MIN_ADDR or the
1772            QEMU application itself.  */
1773         probe_guest_base(image_name, loaddr, hiaddr);
1774     }
1775     load_bias = load_addr - loaddr;
1776
1777 #ifdef CONFIG_USE_FDPIC
1778     {
1779         struct elf32_fdpic_loadseg *loadsegs = info->loadsegs =
1780             g_malloc(sizeof(*loadsegs) * info->nsegs);
1781
1782         for (i = 0; i < ehdr->e_phnum; ++i) {
1783             switch (phdr[i].p_type) {
1784             case PT_DYNAMIC:
1785                 info->pt_dynamic_addr = phdr[i].p_vaddr + load_bias;
1786                 break;
1787             case PT_LOAD:
1788                 loadsegs->addr = phdr[i].p_vaddr + load_bias;
1789                 loadsegs->p_vaddr = phdr[i].p_vaddr;
1790                 loadsegs->p_memsz = phdr[i].p_memsz;
1791                 ++loadsegs;
1792                 break;
1793             }
1794         }
1795     }
1796 #endif
1797
1798     info->load_bias = load_bias;
1799     info->load_addr = load_addr;
1800     info->entry = ehdr->e_entry + load_bias;
1801     info->start_code = -1;
1802     info->end_code = 0;
1803     info->start_data = -1;
1804     info->end_data = 0;
1805     info->brk = 0;
1806     info->elf_flags = ehdr->e_flags;
1807
1808     for (i = 0; i < ehdr->e_phnum; i++) {
1809         struct elf_phdr *eppnt = phdr + i;
1810         if (eppnt->p_type == PT_LOAD) {
1811             abi_ulong vaddr, vaddr_po, vaddr_ps, vaddr_ef, vaddr_em;
1812             int elf_prot = 0;
1813
1814             if (eppnt->p_flags & PF_R) elf_prot =  PROT_READ;
1815             if (eppnt->p_flags & PF_W) elf_prot |= PROT_WRITE;
1816             if (eppnt->p_flags & PF_X) elf_prot |= PROT_EXEC;
1817
1818             vaddr = load_bias + eppnt->p_vaddr;
1819             vaddr_po = TARGET_ELF_PAGEOFFSET(vaddr);
1820             vaddr_ps = TARGET_ELF_PAGESTART(vaddr);
1821
1822             error = target_mmap(vaddr_ps, eppnt->p_filesz + vaddr_po,
1823                                 elf_prot, MAP_PRIVATE | MAP_FIXED,
1824                                 image_fd, eppnt->p_offset - vaddr_po);
1825             if (error == -1) {
1826                 goto exit_perror;
1827             }
1828
1829             vaddr_ef = vaddr + eppnt->p_filesz;
1830             vaddr_em = vaddr + eppnt->p_memsz;
1831
1832             /* If the load segment requests extra zeros (e.g. bss), map it.  */
1833             if (vaddr_ef < vaddr_em) {
1834                 zero_bss(vaddr_ef, vaddr_em, elf_prot);
1835             }
1836
1837             /* Find the full program boundaries.  */
1838             if (elf_prot & PROT_EXEC) {
1839                 if (vaddr < info->start_code) {
1840                     info->start_code = vaddr;
1841                 }
1842                 if (vaddr_ef > info->end_code) {
1843                     info->end_code = vaddr_ef;
1844                 }
1845             }
1846             if (elf_prot & PROT_WRITE) {
1847                 if (vaddr < info->start_data) {
1848                     info->start_data = vaddr;
1849                 }
1850                 if (vaddr_ef > info->end_data) {
1851                     info->end_data = vaddr_ef;
1852                 }
1853                 if (vaddr_em > info->brk) {
1854                     info->brk = vaddr_em;
1855                 }
1856             }
1857         } else if (eppnt->p_type == PT_INTERP && pinterp_name) {
1858             char *interp_name;
1859
1860             if (*pinterp_name) {
1861                 errmsg = "Multiple PT_INTERP entries";
1862                 goto exit_errmsg;
1863             }
1864             interp_name = malloc(eppnt->p_filesz);
1865             if (!interp_name) {
1866                 goto exit_perror;
1867             }
1868
1869             if (eppnt->p_offset + eppnt->p_filesz <= BPRM_BUF_SIZE) {
1870                 memcpy(interp_name, bprm_buf + eppnt->p_offset,
1871                        eppnt->p_filesz);
1872             } else {
1873                 retval = pread(image_fd, interp_name, eppnt->p_filesz,
1874                                eppnt->p_offset);
1875                 if (retval != eppnt->p_filesz) {
1876                     goto exit_perror;
1877                 }
1878             }
1879             if (interp_name[eppnt->p_filesz - 1] != 0) {
1880                 errmsg = "Invalid PT_INTERP entry";
1881                 goto exit_errmsg;
1882             }
1883             *pinterp_name = interp_name;
1884         }
1885     }
1886
1887     if (info->end_data == 0) {
1888         info->start_data = info->end_code;
1889         info->end_data = info->end_code;
1890         info->brk = info->end_code;
1891     }
1892
1893     if (qemu_log_enabled()) {
1894         load_symbols(ehdr, image_fd, load_bias);
1895     }
1896
1897     close(image_fd);
1898     return;
1899
1900  exit_read:
1901     if (retval >= 0) {
1902         errmsg = "Incomplete read of file header";
1903         goto exit_errmsg;
1904     }
1905  exit_perror:
1906     errmsg = strerror(errno);
1907  exit_errmsg:
1908     fprintf(stderr, "%s: %s\n", image_name, errmsg);
1909     exit(-1);
1910 }
1911
1912 static void load_elf_interp(const char *filename, struct image_info *info,
1913                             char bprm_buf[BPRM_BUF_SIZE])
1914 {
1915     int fd, retval;
1916
1917     fd = open(path(filename), O_RDONLY);
1918     if (fd < 0) {
1919         goto exit_perror;
1920     }
1921
1922     retval = read(fd, bprm_buf, BPRM_BUF_SIZE);
1923     if (retval < 0) {
1924         goto exit_perror;
1925     }
1926     if (retval < BPRM_BUF_SIZE) {
1927         memset(bprm_buf + retval, 0, BPRM_BUF_SIZE - retval);
1928     }
1929
1930     load_elf_image(filename, fd, info, NULL, bprm_buf);
1931     return;
1932
1933  exit_perror:
1934     fprintf(stderr, "%s: %s\n", filename, strerror(errno));
1935     exit(-1);
1936 }
1937
1938 static int symfind(const void *s0, const void *s1)
1939 {
1940     target_ulong addr = *(target_ulong *)s0;
1941     struct elf_sym *sym = (struct elf_sym *)s1;
1942     int result = 0;
1943     if (addr < sym->st_value) {
1944         result = -1;
1945     } else if (addr >= sym->st_value + sym->st_size) {
1946         result = 1;
1947     }
1948     return result;
1949 }
1950
1951 static const char *lookup_symbolxx(struct syminfo *s, target_ulong orig_addr)
1952 {
1953 #if ELF_CLASS == ELFCLASS32
1954     struct elf_sym *syms = s->disas_symtab.elf32;
1955 #else
1956     struct elf_sym *syms = s->disas_symtab.elf64;
1957 #endif
1958
1959     // binary search
1960     struct elf_sym *sym;
1961
1962     sym = bsearch(&orig_addr, syms, s->disas_num_syms, sizeof(*syms), symfind);
1963     if (sym != NULL) {
1964         return s->disas_strtab + sym->st_name;
1965     }
1966
1967     return "";
1968 }
1969
1970 /* FIXME: This should use elf_ops.h  */
1971 static int symcmp(const void *s0, const void *s1)
1972 {
1973     struct elf_sym *sym0 = (struct elf_sym *)s0;
1974     struct elf_sym *sym1 = (struct elf_sym *)s1;
1975     return (sym0->st_value < sym1->st_value)
1976         ? -1
1977         : ((sym0->st_value > sym1->st_value) ? 1 : 0);
1978 }
1979
1980 /* Best attempt to load symbols from this ELF object. */
1981 static void load_symbols(struct elfhdr *hdr, int fd, abi_ulong load_bias)
1982 {
1983     int i, shnum, nsyms, sym_idx = 0, str_idx = 0;
1984     struct elf_shdr *shdr;
1985     char *strings = NULL;
1986     struct syminfo *s = NULL;
1987     struct elf_sym *new_syms, *syms = NULL;
1988
1989     shnum = hdr->e_shnum;
1990     i = shnum * sizeof(struct elf_shdr);
1991     shdr = (struct elf_shdr *)alloca(i);
1992     if (pread(fd, shdr, i, hdr->e_shoff) != i) {
1993         return;
1994     }
1995
1996     bswap_shdr(shdr, shnum);
1997     for (i = 0; i < shnum; ++i) {
1998         if (shdr[i].sh_type == SHT_SYMTAB) {
1999             sym_idx = i;
2000             str_idx = shdr[i].sh_link;
2001             goto found;
2002         }
2003     }
2004
2005     /* There will be no symbol table if the file was stripped.  */
2006     return;
2007
2008  found:
2009     /* Now know where the strtab and symtab are.  Snarf them.  */
2010     s = malloc(sizeof(*s));
2011     if (!s) {
2012         goto give_up;
2013     }
2014
2015     i = shdr[str_idx].sh_size;
2016     s->disas_strtab = strings = malloc(i);
2017     if (!strings || pread(fd, strings, i, shdr[str_idx].sh_offset) != i) {
2018         goto give_up;
2019     }
2020
2021     i = shdr[sym_idx].sh_size;
2022     syms = malloc(i);
2023     if (!syms || pread(fd, syms, i, shdr[sym_idx].sh_offset) != i) {
2024         goto give_up;
2025     }
2026
2027     nsyms = i / sizeof(struct elf_sym);
2028     for (i = 0; i < nsyms; ) {
2029         bswap_sym(syms + i);
2030         /* Throw away entries which we do not need.  */
2031         if (syms[i].st_shndx == SHN_UNDEF
2032             || syms[i].st_shndx >= SHN_LORESERVE
2033             || ELF_ST_TYPE(syms[i].st_info) != STT_FUNC) {
2034             if (i < --nsyms) {
2035                 syms[i] = syms[nsyms];
2036             }
2037         } else {
2038 #if defined(TARGET_ARM) || defined (TARGET_MIPS)
2039             /* The bottom address bit marks a Thumb or MIPS16 symbol.  */
2040             syms[i].st_value &= ~(target_ulong)1;
2041 #endif
2042             syms[i].st_value += load_bias;
2043             i++;
2044         }
2045     }
2046
2047     /* No "useful" symbol.  */
2048     if (nsyms == 0) {
2049         goto give_up;
2050     }
2051
2052     /* Attempt to free the storage associated with the local symbols
2053        that we threw away.  Whether or not this has any effect on the
2054        memory allocation depends on the malloc implementation and how
2055        many symbols we managed to discard.  */
2056     new_syms = realloc(syms, nsyms * sizeof(*syms));
2057     if (new_syms == NULL) {
2058         goto give_up;
2059     }
2060     syms = new_syms;
2061
2062     qsort(syms, nsyms, sizeof(*syms), symcmp);
2063
2064     s->disas_num_syms = nsyms;
2065 #if ELF_CLASS == ELFCLASS32
2066     s->disas_symtab.elf32 = syms;
2067 #else
2068     s->disas_symtab.elf64 = syms;
2069 #endif
2070     s->lookup_symbol = lookup_symbolxx;
2071     s->next = syminfos;
2072     syminfos = s;
2073
2074     return;
2075
2076 give_up:
2077     free(s);
2078     free(strings);
2079     free(syms);
2080 }
2081
2082 int load_elf_binary(struct linux_binprm * bprm, struct target_pt_regs * regs,
2083                     struct image_info * info)
2084 {
2085     struct image_info interp_info;
2086     struct elfhdr elf_ex;
2087     char *elf_interpreter = NULL;
2088
2089     info->start_mmap = (abi_ulong)ELF_START_MMAP;
2090     info->mmap = 0;
2091     info->rss = 0;
2092
2093     load_elf_image(bprm->filename, bprm->fd, info,
2094                    &elf_interpreter, bprm->buf);
2095
2096     /* ??? We need a copy of the elf header for passing to create_elf_tables.
2097        If we do nothing, we'll have overwritten this when we re-use bprm->buf
2098        when we load the interpreter.  */
2099     elf_ex = *(struct elfhdr *)bprm->buf;
2100
2101     bprm->p = copy_elf_strings(1, &bprm->filename, bprm->page, bprm->p);
2102     bprm->p = copy_elf_strings(bprm->envc,bprm->envp,bprm->page,bprm->p);
2103     bprm->p = copy_elf_strings(bprm->argc,bprm->argv,bprm->page,bprm->p);
2104     if (!bprm->p) {
2105         fprintf(stderr, "%s: %s\n", bprm->filename, strerror(E2BIG));
2106         exit(-1);
2107     }
2108
2109     /* Do this so that we can load the interpreter, if need be.  We will
2110        change some of these later */
2111     bprm->p = setup_arg_pages(bprm->p, bprm, info);
2112
2113     if (elf_interpreter) {
2114         load_elf_interp(elf_interpreter, &interp_info, bprm->buf);
2115
2116         /* If the program interpreter is one of these two, then assume
2117            an iBCS2 image.  Otherwise assume a native linux image.  */
2118
2119         if (strcmp(elf_interpreter, "/usr/lib/libc.so.1") == 0
2120             || strcmp(elf_interpreter, "/usr/lib/ld.so.1") == 0) {
2121             info->personality = PER_SVR4;
2122
2123             /* Why this, you ask???  Well SVr4 maps page 0 as read-only,
2124                and some applications "depend" upon this behavior.  Since
2125                we do not have the power to recompile these, we emulate
2126                the SVr4 behavior.  Sigh.  */
2127             target_mmap(0, qemu_host_page_size, PROT_READ | PROT_EXEC,
2128                         MAP_FIXED | MAP_PRIVATE, -1, 0);
2129         }
2130     }
2131
2132     bprm->p = create_elf_tables(bprm->p, bprm->argc, bprm->envc, &elf_ex,
2133                                 info, (elf_interpreter ? &interp_info : NULL));
2134     info->start_stack = bprm->p;
2135
2136     /* If we have an interpreter, set that as the program's entry point.
2137        Copy the load_bias as well, to help PPC64 interpret the entry
2138        point as a function descriptor.  Do this after creating elf tables
2139        so that we copy the original program entry point into the AUXV.  */
2140     if (elf_interpreter) {
2141         info->load_bias = interp_info.load_bias;
2142         info->entry = interp_info.entry;
2143         free(elf_interpreter);
2144     }
2145
2146 #ifdef USE_ELF_CORE_DUMP
2147     bprm->core_dump = &elf_core_dump;
2148 #endif
2149
2150     return 0;
2151 }
2152
2153 #ifdef USE_ELF_CORE_DUMP
2154 /*
2155  * Definitions to generate Intel SVR4-like core files.
2156  * These mostly have the same names as the SVR4 types with "target_elf_"
2157  * tacked on the front to prevent clashes with linux definitions,
2158  * and the typedef forms have been avoided.  This is mostly like
2159  * the SVR4 structure, but more Linuxy, with things that Linux does
2160  * not support and which gdb doesn't really use excluded.
2161  *
2162  * Fields we don't dump (their contents is zero) in linux-user qemu
2163  * are marked with XXX.
2164  *
2165  * Core dump code is copied from linux kernel (fs/binfmt_elf.c).
2166  *
2167  * Porting ELF coredump for target is (quite) simple process.  First you
2168  * define USE_ELF_CORE_DUMP in target ELF code (where init_thread() for
2169  * the target resides):
2170  *
2171  * #define USE_ELF_CORE_DUMP
2172  *
2173  * Next you define type of register set used for dumping.  ELF specification
2174  * says that it needs to be array of elf_greg_t that has size of ELF_NREG.
2175  *
2176  * typedef <target_regtype> target_elf_greg_t;
2177  * #define ELF_NREG <number of registers>
2178  * typedef taret_elf_greg_t target_elf_gregset_t[ELF_NREG];
2179  *
2180  * Last step is to implement target specific function that copies registers
2181  * from given cpu into just specified register set.  Prototype is:
2182  *
2183  * static void elf_core_copy_regs(taret_elf_gregset_t *regs,
2184  *                                const CPUArchState *env);
2185  *
2186  * Parameters:
2187  *     regs - copy register values into here (allocated and zeroed by caller)
2188  *     env - copy registers from here
2189  *
2190  * Example for ARM target is provided in this file.
2191  */
2192
2193 /* An ELF note in memory */
2194 struct memelfnote {
2195     const char *name;
2196     size_t     namesz;
2197     size_t     namesz_rounded;
2198     int        type;
2199     size_t     datasz;
2200     size_t     datasz_rounded;
2201     void       *data;
2202     size_t     notesz;
2203 };
2204
2205 struct target_elf_siginfo {
2206     abi_int    si_signo; /* signal number */
2207     abi_int    si_code;  /* extra code */
2208     abi_int    si_errno; /* errno */
2209 };
2210
2211 struct target_elf_prstatus {
2212     struct target_elf_siginfo pr_info;      /* Info associated with signal */
2213     abi_short          pr_cursig;    /* Current signal */
2214     abi_ulong          pr_sigpend;   /* XXX */
2215     abi_ulong          pr_sighold;   /* XXX */
2216     target_pid_t       pr_pid;
2217     target_pid_t       pr_ppid;
2218     target_pid_t       pr_pgrp;
2219     target_pid_t       pr_sid;
2220     struct target_timeval pr_utime;  /* XXX User time */
2221     struct target_timeval pr_stime;  /* XXX System time */
2222     struct target_timeval pr_cutime; /* XXX Cumulative user time */
2223     struct target_timeval pr_cstime; /* XXX Cumulative system time */
2224     target_elf_gregset_t      pr_reg;       /* GP registers */
2225     abi_int            pr_fpvalid;   /* XXX */
2226 };
2227
2228 #define ELF_PRARGSZ     (80) /* Number of chars for args */
2229
2230 struct target_elf_prpsinfo {
2231     char         pr_state;       /* numeric process state */
2232     char         pr_sname;       /* char for pr_state */
2233     char         pr_zomb;        /* zombie */
2234     char         pr_nice;        /* nice val */
2235     abi_ulong    pr_flag;        /* flags */
2236     target_uid_t pr_uid;
2237     target_gid_t pr_gid;
2238     target_pid_t pr_pid, pr_ppid, pr_pgrp, pr_sid;
2239     /* Lots missing */
2240     char    pr_fname[16];           /* filename of executable */
2241     char    pr_psargs[ELF_PRARGSZ]; /* initial part of arg list */
2242 };
2243
2244 /* Here is the structure in which status of each thread is captured. */
2245 struct elf_thread_status {
2246     QTAILQ_ENTRY(elf_thread_status)  ets_link;
2247     struct target_elf_prstatus prstatus;   /* NT_PRSTATUS */
2248 #if 0
2249     elf_fpregset_t fpu;             /* NT_PRFPREG */
2250     struct task_struct *thread;
2251     elf_fpxregset_t xfpu;           /* ELF_CORE_XFPREG_TYPE */
2252 #endif
2253     struct memelfnote notes[1];
2254     int num_notes;
2255 };
2256
2257 struct elf_note_info {
2258     struct memelfnote   *notes;
2259     struct target_elf_prstatus *prstatus;  /* NT_PRSTATUS */
2260     struct target_elf_prpsinfo *psinfo;    /* NT_PRPSINFO */
2261
2262     QTAILQ_HEAD(thread_list_head, elf_thread_status) thread_list;
2263 #if 0
2264     /*
2265      * Current version of ELF coredump doesn't support
2266      * dumping fp regs etc.
2267      */
2268     elf_fpregset_t *fpu;
2269     elf_fpxregset_t *xfpu;
2270     int thread_status_size;
2271 #endif
2272     int notes_size;
2273     int numnote;
2274 };
2275
2276 struct vm_area_struct {
2277     abi_ulong   vma_start;  /* start vaddr of memory region */
2278     abi_ulong   vma_end;    /* end vaddr of memory region */
2279     abi_ulong   vma_flags;  /* protection etc. flags for the region */
2280     QTAILQ_ENTRY(vm_area_struct) vma_link;
2281 };
2282
2283 struct mm_struct {
2284     QTAILQ_HEAD(, vm_area_struct) mm_mmap;
2285     int mm_count;           /* number of mappings */
2286 };
2287
2288 static struct mm_struct *vma_init(void);
2289 static void vma_delete(struct mm_struct *);
2290 static int vma_add_mapping(struct mm_struct *, abi_ulong,
2291                            abi_ulong, abi_ulong);
2292 static int vma_get_mapping_count(const struct mm_struct *);
2293 static struct vm_area_struct *vma_first(const struct mm_struct *);
2294 static struct vm_area_struct *vma_next(struct vm_area_struct *);
2295 static abi_ulong vma_dump_size(const struct vm_area_struct *);
2296 static int vma_walker(void *priv, abi_ulong start, abi_ulong end,
2297                       unsigned long flags);
2298
2299 static void fill_elf_header(struct elfhdr *, int, uint16_t, uint32_t);
2300 static void fill_note(struct memelfnote *, const char *, int,
2301                       unsigned int, void *);
2302 static void fill_prstatus(struct target_elf_prstatus *, const TaskState *, int);
2303 static int fill_psinfo(struct target_elf_prpsinfo *, const TaskState *);
2304 static void fill_auxv_note(struct memelfnote *, const TaskState *);
2305 static void fill_elf_note_phdr(struct elf_phdr *, int, off_t);
2306 static size_t note_size(const struct memelfnote *);
2307 static void free_note_info(struct elf_note_info *);
2308 static int fill_note_info(struct elf_note_info *, long, const CPUArchState *);
2309 static void fill_thread_info(struct elf_note_info *, const CPUArchState *);
2310 static int core_dump_filename(const TaskState *, char *, size_t);
2311
2312 static int dump_write(int, const void *, size_t);
2313 static int write_note(struct memelfnote *, int);
2314 static int write_note_info(struct elf_note_info *, int);
2315
2316 #ifdef BSWAP_NEEDED
2317 static void bswap_prstatus(struct target_elf_prstatus *prstatus)
2318 {
2319     prstatus->pr_info.si_signo = tswap32(prstatus->pr_info.si_signo);
2320     prstatus->pr_info.si_code = tswap32(prstatus->pr_info.si_code);
2321     prstatus->pr_info.si_errno = tswap32(prstatus->pr_info.si_errno);
2322     prstatus->pr_cursig = tswap16(prstatus->pr_cursig);
2323     prstatus->pr_sigpend = tswapal(prstatus->pr_sigpend);
2324     prstatus->pr_sighold = tswapal(prstatus->pr_sighold);
2325     prstatus->pr_pid = tswap32(prstatus->pr_pid);
2326     prstatus->pr_ppid = tswap32(prstatus->pr_ppid);
2327     prstatus->pr_pgrp = tswap32(prstatus->pr_pgrp);
2328     prstatus->pr_sid = tswap32(prstatus->pr_sid);
2329     /* cpu times are not filled, so we skip them */
2330     /* regs should be in correct format already */
2331     prstatus->pr_fpvalid = tswap32(prstatus->pr_fpvalid);
2332 }
2333
2334 static void bswap_psinfo(struct target_elf_prpsinfo *psinfo)
2335 {
2336     psinfo->pr_flag = tswapal(psinfo->pr_flag);
2337     psinfo->pr_uid = tswap16(psinfo->pr_uid);
2338     psinfo->pr_gid = tswap16(psinfo->pr_gid);
2339     psinfo->pr_pid = tswap32(psinfo->pr_pid);
2340     psinfo->pr_ppid = tswap32(psinfo->pr_ppid);
2341     psinfo->pr_pgrp = tswap32(psinfo->pr_pgrp);
2342     psinfo->pr_sid = tswap32(psinfo->pr_sid);
2343 }
2344
2345 static void bswap_note(struct elf_note *en)
2346 {
2347     bswap32s(&en->n_namesz);
2348     bswap32s(&en->n_descsz);
2349     bswap32s(&en->n_type);
2350 }
2351 #else
2352 static inline void bswap_prstatus(struct target_elf_prstatus *p) { }
2353 static inline void bswap_psinfo(struct target_elf_prpsinfo *p) {}
2354 static inline void bswap_note(struct elf_note *en) { }
2355 #endif /* BSWAP_NEEDED */
2356
2357 /*
2358  * Minimal support for linux memory regions.  These are needed
2359  * when we are finding out what memory exactly belongs to
2360  * emulated process.  No locks needed here, as long as
2361  * thread that received the signal is stopped.
2362  */
2363
2364 static struct mm_struct *vma_init(void)
2365 {
2366     struct mm_struct *mm;
2367
2368     if ((mm = g_malloc(sizeof (*mm))) == NULL)
2369         return (NULL);
2370
2371     mm->mm_count = 0;
2372     QTAILQ_INIT(&mm->mm_mmap);
2373
2374     return (mm);
2375 }
2376
2377 static void vma_delete(struct mm_struct *mm)
2378 {
2379     struct vm_area_struct *vma;
2380
2381     while ((vma = vma_first(mm)) != NULL) {
2382         QTAILQ_REMOVE(&mm->mm_mmap, vma, vma_link);
2383         g_free(vma);
2384     }
2385     g_free(mm);
2386 }
2387
2388 static int vma_add_mapping(struct mm_struct *mm, abi_ulong start,
2389                            abi_ulong end, abi_ulong flags)
2390 {
2391     struct vm_area_struct *vma;
2392
2393     if ((vma = g_malloc0(sizeof (*vma))) == NULL)
2394         return (-1);
2395
2396     vma->vma_start = start;
2397     vma->vma_end = end;
2398     vma->vma_flags = flags;
2399
2400     QTAILQ_INSERT_TAIL(&mm->mm_mmap, vma, vma_link);
2401     mm->mm_count++;
2402
2403     return (0);
2404 }
2405
2406 static struct vm_area_struct *vma_first(const struct mm_struct *mm)
2407 {
2408     return (QTAILQ_FIRST(&mm->mm_mmap));
2409 }
2410
2411 static struct vm_area_struct *vma_next(struct vm_area_struct *vma)
2412 {
2413     return (QTAILQ_NEXT(vma, vma_link));
2414 }
2415
2416 static int vma_get_mapping_count(const struct mm_struct *mm)
2417 {
2418     return (mm->mm_count);
2419 }
2420
2421 /*
2422  * Calculate file (dump) size of given memory region.
2423  */
2424 static abi_ulong vma_dump_size(const struct vm_area_struct *vma)
2425 {
2426     /* if we cannot even read the first page, skip it */
2427     if (!access_ok(VERIFY_READ, vma->vma_start, TARGET_PAGE_SIZE))
2428         return (0);
2429
2430     /*
2431      * Usually we don't dump executable pages as they contain
2432      * non-writable code that debugger can read directly from
2433      * target library etc.  However, thread stacks are marked
2434      * also executable so we read in first page of given region
2435      * and check whether it contains elf header.  If there is
2436      * no elf header, we dump it.
2437      */
2438     if (vma->vma_flags & PROT_EXEC) {
2439         char page[TARGET_PAGE_SIZE];
2440
2441         copy_from_user(page, vma->vma_start, sizeof (page));
2442         if ((page[EI_MAG0] == ELFMAG0) &&
2443             (page[EI_MAG1] == ELFMAG1) &&
2444             (page[EI_MAG2] == ELFMAG2) &&
2445             (page[EI_MAG3] == ELFMAG3)) {
2446             /*
2447              * Mappings are possibly from ELF binary.  Don't dump
2448              * them.
2449              */
2450             return (0);
2451         }
2452     }
2453
2454     return (vma->vma_end - vma->vma_start);
2455 }
2456
2457 static int vma_walker(void *priv, abi_ulong start, abi_ulong end,
2458                       unsigned long flags)
2459 {
2460     struct mm_struct *mm = (struct mm_struct *)priv;
2461
2462     vma_add_mapping(mm, start, end, flags);
2463     return (0);
2464 }
2465
2466 static void fill_note(struct memelfnote *note, const char *name, int type,
2467                       unsigned int sz, void *data)
2468 {
2469     unsigned int namesz;
2470
2471     namesz = strlen(name) + 1;
2472     note->name = name;
2473     note->namesz = namesz;
2474     note->namesz_rounded = roundup(namesz, sizeof (int32_t));
2475     note->type = type;
2476     note->datasz = sz;
2477     note->datasz_rounded = roundup(sz, sizeof (int32_t));
2478
2479     note->data = data;
2480
2481     /*
2482      * We calculate rounded up note size here as specified by
2483      * ELF document.
2484      */
2485     note->notesz = sizeof (struct elf_note) +
2486         note->namesz_rounded + note->datasz_rounded;
2487 }
2488
2489 static void fill_elf_header(struct elfhdr *elf, int segs, uint16_t machine,
2490                             uint32_t flags)
2491 {
2492     (void) memset(elf, 0, sizeof(*elf));
2493
2494     (void) memcpy(elf->e_ident, ELFMAG, SELFMAG);
2495     elf->e_ident[EI_CLASS] = ELF_CLASS;
2496     elf->e_ident[EI_DATA] = ELF_DATA;
2497     elf->e_ident[EI_VERSION] = EV_CURRENT;
2498     elf->e_ident[EI_OSABI] = ELF_OSABI;
2499
2500     elf->e_type = ET_CORE;
2501     elf->e_machine = machine;
2502     elf->e_version = EV_CURRENT;
2503     elf->e_phoff = sizeof(struct elfhdr);
2504     elf->e_flags = flags;
2505     elf->e_ehsize = sizeof(struct elfhdr);
2506     elf->e_phentsize = sizeof(struct elf_phdr);
2507     elf->e_phnum = segs;
2508
2509     bswap_ehdr(elf);
2510 }
2511
2512 static void fill_elf_note_phdr(struct elf_phdr *phdr, int sz, off_t offset)
2513 {
2514     phdr->p_type = PT_NOTE;
2515     phdr->p_offset = offset;
2516     phdr->p_vaddr = 0;
2517     phdr->p_paddr = 0;
2518     phdr->p_filesz = sz;
2519     phdr->p_memsz = 0;
2520     phdr->p_flags = 0;
2521     phdr->p_align = 0;
2522
2523     bswap_phdr(phdr, 1);
2524 }
2525
2526 static size_t note_size(const struct memelfnote *note)
2527 {
2528     return (note->notesz);
2529 }
2530
2531 static void fill_prstatus(struct target_elf_prstatus *prstatus,
2532                           const TaskState *ts, int signr)
2533 {
2534     (void) memset(prstatus, 0, sizeof (*prstatus));
2535     prstatus->pr_info.si_signo = prstatus->pr_cursig = signr;
2536     prstatus->pr_pid = ts->ts_tid;
2537     prstatus->pr_ppid = getppid();
2538     prstatus->pr_pgrp = getpgrp();
2539     prstatus->pr_sid = getsid(0);
2540
2541     bswap_prstatus(prstatus);
2542 }
2543
2544 static int fill_psinfo(struct target_elf_prpsinfo *psinfo, const TaskState *ts)
2545 {
2546     char *base_filename;
2547     unsigned int i, len;
2548
2549     (void) memset(psinfo, 0, sizeof (*psinfo));
2550
2551     len = ts->info->arg_end - ts->info->arg_start;
2552     if (len >= ELF_PRARGSZ)
2553         len = ELF_PRARGSZ - 1;
2554     if (copy_from_user(&psinfo->pr_psargs, ts->info->arg_start, len))
2555         return -EFAULT;
2556     for (i = 0; i < len; i++)
2557         if (psinfo->pr_psargs[i] == 0)
2558             psinfo->pr_psargs[i] = ' ';
2559     psinfo->pr_psargs[len] = 0;
2560
2561     psinfo->pr_pid = getpid();
2562     psinfo->pr_ppid = getppid();
2563     psinfo->pr_pgrp = getpgrp();
2564     psinfo->pr_sid = getsid(0);
2565     psinfo->pr_uid = getuid();
2566     psinfo->pr_gid = getgid();
2567
2568     base_filename = g_path_get_basename(ts->bprm->filename);
2569     /*
2570      * Using strncpy here is fine: at max-length,
2571      * this field is not NUL-terminated.
2572      */
2573     (void) strncpy(psinfo->pr_fname, base_filename,
2574                    sizeof(psinfo->pr_fname));
2575
2576     g_free(base_filename);
2577     bswap_psinfo(psinfo);
2578     return (0);
2579 }
2580
2581 static void fill_auxv_note(struct memelfnote *note, const TaskState *ts)
2582 {
2583     elf_addr_t auxv = (elf_addr_t)ts->info->saved_auxv;
2584     elf_addr_t orig_auxv = auxv;
2585     void *ptr;
2586     int len = ts->info->auxv_len;
2587
2588     /*
2589      * Auxiliary vector is stored in target process stack.  It contains
2590      * {type, value} pairs that we need to dump into note.  This is not
2591      * strictly necessary but we do it here for sake of completeness.
2592      */
2593
2594     /* read in whole auxv vector and copy it to memelfnote */
2595     ptr = lock_user(VERIFY_READ, orig_auxv, len, 0);
2596     if (ptr != NULL) {
2597         fill_note(note, "CORE", NT_AUXV, len, ptr);
2598         unlock_user(ptr, auxv, len);
2599     }
2600 }
2601
2602 /*
2603  * Constructs name of coredump file.  We have following convention
2604  * for the name:
2605  *     qemu_<basename-of-target-binary>_<date>-<time>_<pid>.core
2606  *
2607  * Returns 0 in case of success, -1 otherwise (errno is set).
2608  */
2609 static int core_dump_filename(const TaskState *ts, char *buf,
2610                               size_t bufsize)
2611 {
2612     char timestamp[64];
2613     char *filename = NULL;
2614     char *base_filename = NULL;
2615     struct timeval tv;
2616     struct tm tm;
2617
2618     assert(bufsize >= PATH_MAX);
2619
2620     if (gettimeofday(&tv, NULL) < 0) {
2621         (void) fprintf(stderr, "unable to get current timestamp: %s",
2622                        strerror(errno));
2623         return (-1);
2624     }
2625
2626     filename = strdup(ts->bprm->filename);
2627     base_filename = strdup(basename(filename));
2628     (void) strftime(timestamp, sizeof (timestamp), "%Y%m%d-%H%M%S",
2629                     localtime_r(&tv.tv_sec, &tm));
2630     (void) snprintf(buf, bufsize, "qemu_%s_%s_%d.core",
2631                     base_filename, timestamp, (int)getpid());
2632     free(base_filename);
2633     free(filename);
2634
2635     return (0);
2636 }
2637
2638 static int dump_write(int fd, const void *ptr, size_t size)
2639 {
2640     const char *bufp = (const char *)ptr;
2641     ssize_t bytes_written, bytes_left;
2642     struct rlimit dumpsize;
2643     off_t pos;
2644
2645     bytes_written = 0;
2646     getrlimit(RLIMIT_CORE, &dumpsize);
2647     if ((pos = lseek(fd, 0, SEEK_CUR))==-1) {
2648         if (errno == ESPIPE) { /* not a seekable stream */
2649             bytes_left = size;
2650         } else {
2651             return pos;
2652         }
2653     } else {
2654         if (dumpsize.rlim_cur <= pos) {
2655             return -1;
2656         } else if (dumpsize.rlim_cur == RLIM_INFINITY) {
2657             bytes_left = size;
2658         } else {
2659             size_t limit_left=dumpsize.rlim_cur - pos;
2660             bytes_left = limit_left >= size ? size : limit_left ;
2661         }
2662     }
2663
2664     /*
2665      * In normal conditions, single write(2) should do but
2666      * in case of socket etc. this mechanism is more portable.
2667      */
2668     do {
2669         bytes_written = write(fd, bufp, bytes_left);
2670         if (bytes_written < 0) {
2671             if (errno == EINTR)
2672                 continue;
2673             return (-1);
2674         } else if (bytes_written == 0) { /* eof */
2675             return (-1);
2676         }
2677         bufp += bytes_written;
2678         bytes_left -= bytes_written;
2679     } while (bytes_left > 0);
2680
2681     return (0);
2682 }
2683
2684 static int write_note(struct memelfnote *men, int fd)
2685 {
2686     struct elf_note en;
2687
2688     en.n_namesz = men->namesz;
2689     en.n_type = men->type;
2690     en.n_descsz = men->datasz;
2691
2692     bswap_note(&en);
2693
2694     if (dump_write(fd, &en, sizeof(en)) != 0)
2695         return (-1);
2696     if (dump_write(fd, men->name, men->namesz_rounded) != 0)
2697         return (-1);
2698     if (dump_write(fd, men->data, men->datasz_rounded) != 0)
2699         return (-1);
2700
2701     return (0);
2702 }
2703
2704 static void fill_thread_info(struct elf_note_info *info, const CPUArchState *env)
2705 {
2706     TaskState *ts = (TaskState *)env->opaque;
2707     struct elf_thread_status *ets;
2708
2709     ets = g_malloc0(sizeof (*ets));
2710     ets->num_notes = 1; /* only prstatus is dumped */
2711     fill_prstatus(&ets->prstatus, ts, 0);
2712     elf_core_copy_regs(&ets->prstatus.pr_reg, env);
2713     fill_note(&ets->notes[0], "CORE", NT_PRSTATUS, sizeof (ets->prstatus),
2714               &ets->prstatus);
2715
2716     QTAILQ_INSERT_TAIL(&info->thread_list, ets, ets_link);
2717
2718     info->notes_size += note_size(&ets->notes[0]);
2719 }
2720
2721 static int fill_note_info(struct elf_note_info *info,
2722                           long signr, const CPUArchState *env)
2723 {
2724 #define NUMNOTES 3
2725     CPUState *cpu = NULL;
2726     TaskState *ts = (TaskState *)env->opaque;
2727     int i;
2728
2729     (void) memset(info, 0, sizeof (*info));
2730
2731     QTAILQ_INIT(&info->thread_list);
2732
2733     info->notes = g_malloc0(NUMNOTES * sizeof (struct memelfnote));
2734     if (info->notes == NULL)
2735         return (-ENOMEM);
2736     info->prstatus = g_malloc0(sizeof (*info->prstatus));
2737     if (info->prstatus == NULL)
2738         return (-ENOMEM);
2739     info->psinfo = g_malloc0(sizeof (*info->psinfo));
2740     if (info->prstatus == NULL)
2741         return (-ENOMEM);
2742
2743     /*
2744      * First fill in status (and registers) of current thread
2745      * including process info & aux vector.
2746      */
2747     fill_prstatus(info->prstatus, ts, signr);
2748     elf_core_copy_regs(&info->prstatus->pr_reg, env);
2749     fill_note(&info->notes[0], "CORE", NT_PRSTATUS,
2750               sizeof (*info->prstatus), info->prstatus);
2751     fill_psinfo(info->psinfo, ts);
2752     fill_note(&info->notes[1], "CORE", NT_PRPSINFO,
2753               sizeof (*info->psinfo), info->psinfo);
2754     fill_auxv_note(&info->notes[2], ts);
2755     info->numnote = 3;
2756
2757     info->notes_size = 0;
2758     for (i = 0; i < info->numnote; i++)
2759         info->notes_size += note_size(&info->notes[i]);
2760
2761     /* read and fill status of all threads */
2762     cpu_list_lock();
2763     CPU_FOREACH(cpu) {
2764         if (cpu == thread_cpu) {
2765             continue;
2766         }
2767         fill_thread_info(info, (CPUArchState *)cpu->env_ptr);
2768     }
2769     cpu_list_unlock();
2770
2771     return (0);
2772 }
2773
2774 static void free_note_info(struct elf_note_info *info)
2775 {
2776     struct elf_thread_status *ets;
2777
2778     while (!QTAILQ_EMPTY(&info->thread_list)) {
2779         ets = QTAILQ_FIRST(&info->thread_list);
2780         QTAILQ_REMOVE(&info->thread_list, ets, ets_link);
2781         g_free(ets);
2782     }
2783
2784     g_free(info->prstatus);
2785     g_free(info->psinfo);
2786     g_free(info->notes);
2787 }
2788
2789 static int write_note_info(struct elf_note_info *info, int fd)
2790 {
2791     struct elf_thread_status *ets;
2792     int i, error = 0;
2793
2794     /* write prstatus, psinfo and auxv for current thread */
2795     for (i = 0; i < info->numnote; i++)
2796         if ((error = write_note(&info->notes[i], fd)) != 0)
2797             return (error);
2798
2799     /* write prstatus for each thread */
2800     for (ets = info->thread_list.tqh_first; ets != NULL;
2801          ets = ets->ets_link.tqe_next) {
2802         if ((error = write_note(&ets->notes[0], fd)) != 0)
2803             return (error);
2804     }
2805
2806     return (0);
2807 }
2808
2809 /*
2810  * Write out ELF coredump.
2811  *
2812  * See documentation of ELF object file format in:
2813  * http://www.caldera.com/developers/devspecs/gabi41.pdf
2814  *
2815  * Coredump format in linux is following:
2816  *
2817  * 0   +----------------------+         \
2818  *     | ELF header           | ET_CORE  |
2819  *     +----------------------+          |
2820  *     | ELF program headers  |          |--- headers
2821  *     | - NOTE section       |          |
2822  *     | - PT_LOAD sections   |          |
2823  *     +----------------------+         /
2824  *     | NOTEs:               |
2825  *     | - NT_PRSTATUS        |
2826  *     | - NT_PRSINFO         |
2827  *     | - NT_AUXV            |
2828  *     +----------------------+ <-- aligned to target page
2829  *     | Process memory dump  |
2830  *     :                      :
2831  *     .                      .
2832  *     :                      :
2833  *     |                      |
2834  *     +----------------------+
2835  *
2836  * NT_PRSTATUS -> struct elf_prstatus (per thread)
2837  * NT_PRSINFO  -> struct elf_prpsinfo
2838  * NT_AUXV is array of { type, value } pairs (see fill_auxv_note()).
2839  *
2840  * Format follows System V format as close as possible.  Current
2841  * version limitations are as follows:
2842  *     - no floating point registers are dumped
2843  *
2844  * Function returns 0 in case of success, negative errno otherwise.
2845  *
2846  * TODO: make this work also during runtime: it should be
2847  * possible to force coredump from running process and then
2848  * continue processing.  For example qemu could set up SIGUSR2
2849  * handler (provided that target process haven't registered
2850  * handler for that) that does the dump when signal is received.
2851  */
2852 static int elf_core_dump(int signr, const CPUArchState *env)
2853 {
2854     const TaskState *ts = (const TaskState *)env->opaque;
2855     struct vm_area_struct *vma = NULL;
2856     char corefile[PATH_MAX];
2857     struct elf_note_info info;
2858     struct elfhdr elf;
2859     struct elf_phdr phdr;
2860     struct rlimit dumpsize;
2861     struct mm_struct *mm = NULL;
2862     off_t offset = 0, data_offset = 0;
2863     int segs = 0;
2864     int fd = -1;
2865
2866     errno = 0;
2867     getrlimit(RLIMIT_CORE, &dumpsize);
2868     if (dumpsize.rlim_cur == 0)
2869         return 0;
2870
2871     if (core_dump_filename(ts, corefile, sizeof (corefile)) < 0)
2872         return (-errno);
2873
2874     if ((fd = open(corefile, O_WRONLY | O_CREAT,
2875                    S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0)
2876         return (-errno);
2877
2878     /*
2879      * Walk through target process memory mappings and
2880      * set up structure containing this information.  After
2881      * this point vma_xxx functions can be used.
2882      */
2883     if ((mm = vma_init()) == NULL)
2884         goto out;
2885
2886     walk_memory_regions(mm, vma_walker);
2887     segs = vma_get_mapping_count(mm);
2888
2889     /*
2890      * Construct valid coredump ELF header.  We also
2891      * add one more segment for notes.
2892      */
2893     fill_elf_header(&elf, segs + 1, ELF_MACHINE, 0);
2894     if (dump_write(fd, &elf, sizeof (elf)) != 0)
2895         goto out;
2896
2897     /* fill in in-memory version of notes */
2898     if (fill_note_info(&info, signr, env) < 0)
2899         goto out;
2900
2901     offset += sizeof (elf);                             /* elf header */
2902     offset += (segs + 1) * sizeof (struct elf_phdr);    /* program headers */
2903
2904     /* write out notes program header */
2905     fill_elf_note_phdr(&phdr, info.notes_size, offset);
2906
2907     offset += info.notes_size;
2908     if (dump_write(fd, &phdr, sizeof (phdr)) != 0)
2909         goto out;
2910
2911     /*
2912      * ELF specification wants data to start at page boundary so
2913      * we align it here.
2914      */
2915     data_offset = offset = roundup(offset, ELF_EXEC_PAGESIZE);
2916
2917     /*
2918      * Write program headers for memory regions mapped in
2919      * the target process.
2920      */
2921     for (vma = vma_first(mm); vma != NULL; vma = vma_next(vma)) {
2922         (void) memset(&phdr, 0, sizeof (phdr));
2923
2924         phdr.p_type = PT_LOAD;
2925         phdr.p_offset = offset;
2926         phdr.p_vaddr = vma->vma_start;
2927         phdr.p_paddr = 0;
2928         phdr.p_filesz = vma_dump_size(vma);
2929         offset += phdr.p_filesz;
2930         phdr.p_memsz = vma->vma_end - vma->vma_start;
2931         phdr.p_flags = vma->vma_flags & PROT_READ ? PF_R : 0;
2932         if (vma->vma_flags & PROT_WRITE)
2933             phdr.p_flags |= PF_W;
2934         if (vma->vma_flags & PROT_EXEC)
2935             phdr.p_flags |= PF_X;
2936         phdr.p_align = ELF_EXEC_PAGESIZE;
2937
2938         bswap_phdr(&phdr, 1);
2939         dump_write(fd, &phdr, sizeof (phdr));
2940     }
2941
2942     /*
2943      * Next we write notes just after program headers.  No
2944      * alignment needed here.
2945      */
2946     if (write_note_info(&info, fd) < 0)
2947         goto out;
2948
2949     /* align data to page boundary */
2950     if (lseek(fd, data_offset, SEEK_SET) != data_offset)
2951         goto out;
2952
2953     /*
2954      * Finally we can dump process memory into corefile as well.
2955      */
2956     for (vma = vma_first(mm); vma != NULL; vma = vma_next(vma)) {
2957         abi_ulong addr;
2958         abi_ulong end;
2959
2960         end = vma->vma_start + vma_dump_size(vma);
2961
2962         for (addr = vma->vma_start; addr < end;
2963              addr += TARGET_PAGE_SIZE) {
2964             char page[TARGET_PAGE_SIZE];
2965             int error;
2966
2967             /*
2968              *  Read in page from target process memory and
2969              *  write it to coredump file.
2970              */
2971             error = copy_from_user(page, addr, sizeof (page));
2972             if (error != 0) {
2973                 (void) fprintf(stderr, "unable to dump " TARGET_ABI_FMT_lx "\n",
2974                                addr);
2975                 errno = -error;
2976                 goto out;
2977             }
2978             if (dump_write(fd, page, TARGET_PAGE_SIZE) < 0)
2979                 goto out;
2980         }
2981     }
2982
2983  out:
2984     free_note_info(&info);
2985     if (mm != NULL)
2986         vma_delete(mm);
2987     (void) close(fd);
2988
2989     if (errno != 0)
2990         return (-errno);
2991     return (0);
2992 }
2993 #endif /* USE_ELF_CORE_DUMP */
2994
2995 void do_init_thread(struct target_pt_regs *regs, struct image_info *infop)
2996 {
2997     init_thread(regs, infop);
2998 }