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