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