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