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