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