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