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