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