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