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