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