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