Merge branch 'master' of /home/nchip/public_html/qemu into garage-push
[qemu] / linux-user / elfload.c
1 /* This is the Linux kernel elf-loading code, ported into user space */
2 #include <sys/time.h>
3 #include <sys/param.h>
4
5 #include <stdio.h>
6 #include <sys/types.h>
7 #include <fcntl.h>
8 #include <errno.h>
9 #include <unistd.h>
10 #include <sys/mman.h>
11 #include <sys/resource.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <time.h>
15
16 #include "qemu.h"
17 #include "disas.h"
18
19 #ifdef _ARCH_PPC64
20 #undef ARCH_DLINFO
21 #undef ELF_PLATFORM
22 #undef ELF_HWCAP
23 #undef ELF_CLASS
24 #undef ELF_DATA
25 #undef ELF_ARCH
26 #endif
27
28 #define ELF_OSABI   ELFOSABI_SYSV
29
30 /* from personality.h */
31
32 /*
33  * Flags for bug emulation.
34  *
35  * These occupy the top three bytes.
36  */
37 enum {
38         ADDR_NO_RANDOMIZE =     0x0040000,      /* disable randomization of VA space */
39         FDPIC_FUNCPTRS =        0x0080000,      /* userspace function ptrs point to descriptors
40                                                  * (signal handling)
41                                                  */
42         MMAP_PAGE_ZERO =        0x0100000,
43         ADDR_COMPAT_LAYOUT =    0x0200000,
44         READ_IMPLIES_EXEC =     0x0400000,
45         ADDR_LIMIT_32BIT =      0x0800000,
46         SHORT_INODE =           0x1000000,
47         WHOLE_SECONDS =         0x2000000,
48         STICKY_TIMEOUTS =       0x4000000,
49         ADDR_LIMIT_3GB =        0x8000000,
50 };
51
52 /*
53  * Personality types.
54  *
55  * These go in the low byte.  Avoid using the top bit, it will
56  * conflict with error returns.
57  */
58 enum {
59         PER_LINUX =             0x0000,
60         PER_LINUX_32BIT =       0x0000 | ADDR_LIMIT_32BIT,
61         PER_LINUX_FDPIC =       0x0000 | FDPIC_FUNCPTRS,
62         PER_SVR4 =              0x0001 | STICKY_TIMEOUTS | MMAP_PAGE_ZERO,
63         PER_SVR3 =              0x0002 | STICKY_TIMEOUTS | SHORT_INODE,
64         PER_SCOSVR3 =           0x0003 | STICKY_TIMEOUTS |
65                                          WHOLE_SECONDS | SHORT_INODE,
66         PER_OSR5 =              0x0003 | STICKY_TIMEOUTS | WHOLE_SECONDS,
67         PER_WYSEV386 =          0x0004 | STICKY_TIMEOUTS | SHORT_INODE,
68         PER_ISCR4 =             0x0005 | STICKY_TIMEOUTS,
69         PER_BSD =               0x0006,
70         PER_SUNOS =             0x0006 | STICKY_TIMEOUTS,
71         PER_XENIX =             0x0007 | STICKY_TIMEOUTS | SHORT_INODE,
72         PER_LINUX32 =           0x0008,
73         PER_LINUX32_3GB =       0x0008 | ADDR_LIMIT_3GB,
74         PER_IRIX32 =            0x0009 | STICKY_TIMEOUTS,/* IRIX5 32-bit */
75         PER_IRIXN32 =           0x000a | STICKY_TIMEOUTS,/* IRIX6 new 32-bit */
76         PER_IRIX64 =            0x000b | STICKY_TIMEOUTS,/* IRIX6 64-bit */
77         PER_RISCOS =            0x000c,
78         PER_SOLARIS =           0x000d | STICKY_TIMEOUTS,
79         PER_UW7 =               0x000e | STICKY_TIMEOUTS | MMAP_PAGE_ZERO,
80         PER_OSF4 =              0x000f,                  /* OSF/1 v4 */
81         PER_HPUX =              0x0010,
82         PER_MASK =              0x00ff,
83 };
84
85 /*
86  * Return the base personality without flags.
87  */
88 #define personality(pers)       (pers & PER_MASK)
89
90 /* this flag is uneffective under linux too, should be deleted */
91 #ifndef MAP_DENYWRITE
92 #define MAP_DENYWRITE 0
93 #endif
94
95 /* should probably go in elf.h */
96 #ifndef ELIBBAD
97 #define ELIBBAD 80
98 #endif
99
100 #ifdef TARGET_I386
101
102 #define ELF_PLATFORM get_elf_platform()
103
104 static const char *get_elf_platform(void)
105 {
106     static char elf_platform[] = "i386";
107     int family = (thread_env->cpuid_version >> 8) & 0xff;
108     if (family > 6)
109         family = 6;
110     if (family >= 3)
111         elf_platform[1] = '0' + family;
112     return elf_platform;
113 }
114
115 #define ELF_HWCAP get_elf_hwcap()
116
117 static uint32_t get_elf_hwcap(void)
118 {
119   return thread_env->cpuid_features;
120 }
121
122 #ifdef TARGET_X86_64
123 #define ELF_START_MMAP 0x2aaaaab000ULL
124 #define elf_check_arch(x) ( ((x) == ELF_ARCH) )
125
126 #define ELF_CLASS      ELFCLASS64
127 #define ELF_DATA       ELFDATA2LSB
128 #define ELF_ARCH       EM_X86_64
129
130 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
131 {
132     regs->rax = 0;
133     regs->rsp = infop->start_stack;
134     regs->rip = infop->entry;
135 }
136
137 typedef target_ulong    elf_greg_t;
138 typedef uint32_t        target_uid_t;
139 typedef uint32_t        target_gid_t;
140 typedef int32_t         target_pid_t;
141
142 #define ELF_NREG    27
143 typedef elf_greg_t  elf_gregset_t[ELF_NREG];
144
145 /*
146  * Note that ELF_NREG should be 29 as there should be place for
147  * TRAPNO and ERR "registers" as well but linux doesn't dump
148  * those.
149  *
150  * See linux kernel: arch/x86/include/asm/elf.h
151  */ 
152 static void elf_core_copy_regs(elf_gregset_t *regs, const CPUState *env)
153 {
154     (*regs)[0] = env->regs[15];
155     (*regs)[1] = env->regs[14];
156     (*regs)[2] = env->regs[13];
157     (*regs)[3] = env->regs[12];
158     (*regs)[4] = env->regs[R_EBP];
159     (*regs)[5] = env->regs[R_EBX];
160     (*regs)[6] = env->regs[11];
161     (*regs)[7] = env->regs[10];
162     (*regs)[8] = env->regs[9];
163     (*regs)[9] = env->regs[8];
164     (*regs)[10] = env->regs[R_EAX];
165     (*regs)[11] = env->regs[R_ECX];
166     (*regs)[12] = env->regs[R_EDX];
167     (*regs)[13] = env->regs[R_ESI];
168     (*regs)[14] = env->regs[R_EDI];
169     (*regs)[15] = env->regs[R_EAX]; /* XXX */
170     (*regs)[16] = env->eip;
171     (*regs)[17] = env->segs[R_CS].selector & 0xffff;
172     (*regs)[18] = env->eflags;
173     (*regs)[19] = env->regs[R_ESP];
174     (*regs)[20] = env->segs[R_SS].selector & 0xffff;
175     (*regs)[21] = env->segs[R_FS].selector & 0xffff;
176     (*regs)[22] = env->segs[R_GS].selector & 0xffff;
177     (*regs)[23] = env->segs[R_DS].selector & 0xffff;
178     (*regs)[24] = env->segs[R_ES].selector & 0xffff;
179     (*regs)[25] = env->segs[R_FS].selector & 0xffff;
180     (*regs)[26] = env->segs[R_GS].selector & 0xffff;
181 }
182
183 #else
184
185 #define ELF_START_MMAP 0x80000000
186
187 /*
188  * This is used to ensure we don't load something for the wrong architecture.
189  */
190 #define elf_check_arch(x) ( ((x) == EM_386) || ((x) == EM_486) )
191
192 /*
193  * These are used to set parameters in the core dumps.
194  */
195 #define ELF_CLASS       ELFCLASS32
196 #define ELF_DATA        ELFDATA2LSB
197 #define ELF_ARCH        EM_386
198
199 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
200 {
201     regs->esp = infop->start_stack;
202     regs->eip = infop->entry;
203
204     /* SVR4/i386 ABI (pages 3-31, 3-32) says that when the program
205        starts %edx contains a pointer to a function which might be
206        registered using `atexit'.  This provides a mean for the
207        dynamic linker to call DT_FINI functions for shared libraries
208        that have been loaded before the code runs.
209
210        A value of 0 tells we have no such handler.  */
211     regs->edx = 0;
212 }
213
214 typedef target_ulong    elf_greg_t;
215 typedef uint16_t        target_uid_t;
216 typedef uint16_t        target_gid_t;
217 typedef int32_t         target_pid_t;
218
219 #define ELF_NREG    17
220 typedef elf_greg_t  elf_gregset_t[ELF_NREG];
221
222 /*
223  * Note that ELF_NREG should be 19 as there should be place for
224  * TRAPNO and ERR "registers" as well but linux doesn't dump
225  * those.
226  *
227  * See linux kernel: arch/x86/include/asm/elf.h
228  */ 
229 static void elf_core_copy_regs(elf_gregset_t *regs, const CPUState *env)
230 {
231     (*regs)[0] = env->regs[R_EBX];
232     (*regs)[1] = env->regs[R_ECX];
233     (*regs)[2] = env->regs[R_EDX];
234     (*regs)[3] = env->regs[R_ESI];
235     (*regs)[4] = env->regs[R_EDI];
236     (*regs)[5] = env->regs[R_EBP];
237     (*regs)[6] = env->regs[R_EAX];
238     (*regs)[7] = env->segs[R_DS].selector & 0xffff;
239     (*regs)[8] = env->segs[R_ES].selector & 0xffff;
240     (*regs)[9] = env->segs[R_FS].selector & 0xffff;
241     (*regs)[10] = env->segs[R_GS].selector & 0xffff;
242     (*regs)[11] = env->regs[R_EAX]; /* XXX */
243     (*regs)[12] = env->eip;
244     (*regs)[13] = env->segs[R_CS].selector & 0xffff;
245     (*regs)[14] = env->eflags;
246     (*regs)[15] = env->regs[R_ESP];
247     (*regs)[16] = env->segs[R_SS].selector & 0xffff;
248 }
249 #endif
250
251 #define USE_ELF_CORE_DUMP
252 #define ELF_EXEC_PAGESIZE       4096
253
254 #endif
255
256 #ifdef TARGET_ARM
257
258 #define ELF_START_MMAP 0x80000000
259
260 #define elf_check_arch(x) ( (x) == EM_ARM )
261
262 #define ELF_CLASS       ELFCLASS32
263 #ifdef TARGET_WORDS_BIGENDIAN
264 #define ELF_DATA        ELFDATA2MSB
265 #else
266 #define ELF_DATA        ELFDATA2LSB
267 #endif
268 #define ELF_ARCH        EM_ARM
269
270 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
271 {
272     abi_long stack = infop->start_stack;
273     memset(regs, 0, sizeof(*regs));
274     regs->ARM_cpsr = 0x10;
275     if (infop->entry & 1)
276       regs->ARM_cpsr |= CPSR_T;
277     regs->ARM_pc = infop->entry & 0xfffffffe;
278     regs->ARM_sp = infop->start_stack;
279     /* FIXME - what to for failure of get_user()? */
280     get_user_ual(regs->ARM_r2, stack + 8); /* envp */
281     get_user_ual(regs->ARM_r1, stack + 4); /* envp */
282     /* XXX: it seems that r0 is zeroed after ! */
283     regs->ARM_r0 = 0;
284     /* For uClinux PIC binaries.  */
285     /* XXX: Linux does this only on ARM with no MMU (do we care ?) */
286     regs->ARM_r10 = infop->start_data;
287 }
288
289 typedef uint32_t elf_greg_t;
290 typedef uint16_t target_uid_t;
291 typedef uint16_t target_gid_t;
292 typedef int32_t  target_pid_t;
293
294 #define ELF_NREG    18
295 typedef elf_greg_t  elf_gregset_t[ELF_NREG];
296
297 static void elf_core_copy_regs(elf_gregset_t *regs, const CPUState *env)
298 {
299     (*regs)[0] = env->regs[0];
300     (*regs)[1] = env->regs[1];
301     (*regs)[2] = env->regs[2];
302     (*regs)[3] = env->regs[3]; 
303     (*regs)[4] = env->regs[4];
304     (*regs)[5] = env->regs[5];
305     (*regs)[6] = env->regs[6];
306     (*regs)[7] = env->regs[7];
307     (*regs)[8] = env->regs[8];
308     (*regs)[9] = env->regs[9];
309     (*regs)[10] = env->regs[10];
310     (*regs)[11] = env->regs[11];
311     (*regs)[12] = env->regs[12];
312     (*regs)[13] = env->regs[13]; 
313     (*regs)[14] = env->regs[14];
314     (*regs)[15] = env->regs[15];
315
316     (*regs)[16] = cpsr_read((CPUState *)env);
317     (*regs)[17] = env->regs[0]; /* XXX */
318 }
319
320 #define USE_ELF_CORE_DUMP
321 #define ELF_EXEC_PAGESIZE       4096
322
323 enum
324 {
325   ARM_HWCAP_ARM_SWP       = 1 << 0,
326   ARM_HWCAP_ARM_HALF      = 1 << 1,
327   ARM_HWCAP_ARM_THUMB     = 1 << 2,
328   ARM_HWCAP_ARM_26BIT     = 1 << 3,
329   ARM_HWCAP_ARM_FAST_MULT = 1 << 4,
330   ARM_HWCAP_ARM_FPA       = 1 << 5,
331   ARM_HWCAP_ARM_VFP       = 1 << 6,
332   ARM_HWCAP_ARM_EDSP      = 1 << 7,
333 };
334
335 #define ELF_HWCAP (ARM_HWCAP_ARM_SWP | ARM_HWCAP_ARM_HALF              \
336                     | ARM_HWCAP_ARM_THUMB | ARM_HWCAP_ARM_FAST_MULT     \
337                     | ARM_HWCAP_ARM_FPA | ARM_HWCAP_ARM_VFP)
338
339 #endif
340
341 #ifdef TARGET_SPARC
342 #ifdef TARGET_SPARC64
343
344 #define ELF_START_MMAP 0x80000000
345
346 #ifndef TARGET_ABI32
347 #define elf_check_arch(x) ( (x) == EM_SPARCV9 || (x) == EM_SPARC32PLUS )
348 #else
349 #define elf_check_arch(x) ( (x) == EM_SPARC32PLUS || (x) == EM_SPARC )
350 #endif
351
352 #define ELF_CLASS   ELFCLASS64
353 #define ELF_DATA    ELFDATA2MSB
354 #define ELF_ARCH    EM_SPARCV9
355
356 #define STACK_BIAS              2047
357
358 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
359 {
360 #ifndef TARGET_ABI32
361     regs->tstate = 0;
362 #endif
363     regs->pc = infop->entry;
364     regs->npc = regs->pc + 4;
365     regs->y = 0;
366 #ifdef TARGET_ABI32
367     regs->u_regs[14] = infop->start_stack - 16 * 4;
368 #else
369     if (personality(infop->personality) == PER_LINUX32)
370         regs->u_regs[14] = infop->start_stack - 16 * 4;
371     else
372         regs->u_regs[14] = infop->start_stack - 16 * 8 - STACK_BIAS;
373 #endif
374 }
375
376 #else
377 #define ELF_START_MMAP 0x80000000
378
379 #define elf_check_arch(x) ( (x) == EM_SPARC )
380
381 #define ELF_CLASS   ELFCLASS32
382 #define ELF_DATA    ELFDATA2MSB
383 #define ELF_ARCH    EM_SPARC
384
385 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
386 {
387     regs->psr = 0;
388     regs->pc = infop->entry;
389     regs->npc = regs->pc + 4;
390     regs->y = 0;
391     regs->u_regs[14] = infop->start_stack - 16 * 4;
392 }
393
394 #endif
395 #endif
396
397 #ifdef TARGET_PPC
398
399 #define ELF_START_MMAP 0x80000000
400
401 #if defined(TARGET_PPC64) && !defined(TARGET_ABI32)
402
403 #define elf_check_arch(x) ( (x) == EM_PPC64 )
404
405 #define ELF_CLASS       ELFCLASS64
406
407 #else
408
409 #define elf_check_arch(x) ( (x) == EM_PPC )
410
411 #define ELF_CLASS       ELFCLASS32
412
413 #endif
414
415 #ifdef TARGET_WORDS_BIGENDIAN
416 #define ELF_DATA        ELFDATA2MSB
417 #else
418 #define ELF_DATA        ELFDATA2LSB
419 #endif
420 #define ELF_ARCH        EM_PPC
421
422 /* Feature masks for the Aux Vector Hardware Capabilities (AT_HWCAP).
423    See arch/powerpc/include/asm/cputable.h.  */
424 enum {
425     PPC_FEATURE_32 = 0x80000000,
426     PPC_FEATURE_64 = 0x40000000,
427     PPC_FEATURE_601_INSTR = 0x20000000,
428     PPC_FEATURE_HAS_ALTIVEC = 0x10000000,
429     PPC_FEATURE_HAS_FPU = 0x08000000,
430     PPC_FEATURE_HAS_MMU = 0x04000000,
431     PPC_FEATURE_HAS_4xxMAC = 0x02000000,
432     PPC_FEATURE_UNIFIED_CACHE = 0x01000000,
433     PPC_FEATURE_HAS_SPE = 0x00800000,
434     PPC_FEATURE_HAS_EFP_SINGLE = 0x00400000,
435     PPC_FEATURE_HAS_EFP_DOUBLE = 0x00200000,
436     PPC_FEATURE_NO_TB = 0x00100000,
437     PPC_FEATURE_POWER4 = 0x00080000,
438     PPC_FEATURE_POWER5 = 0x00040000,
439     PPC_FEATURE_POWER5_PLUS = 0x00020000,
440     PPC_FEATURE_CELL = 0x00010000,
441     PPC_FEATURE_BOOKE = 0x00008000,
442     PPC_FEATURE_SMT = 0x00004000,
443     PPC_FEATURE_ICACHE_SNOOP = 0x00002000,
444     PPC_FEATURE_ARCH_2_05 = 0x00001000,
445     PPC_FEATURE_PA6T = 0x00000800,
446     PPC_FEATURE_HAS_DFP = 0x00000400,
447     PPC_FEATURE_POWER6_EXT = 0x00000200,
448     PPC_FEATURE_ARCH_2_06 = 0x00000100,
449     PPC_FEATURE_HAS_VSX = 0x00000080,
450     PPC_FEATURE_PSERIES_PERFMON_COMPAT = 0x00000040,
451
452     PPC_FEATURE_TRUE_LE = 0x00000002,
453     PPC_FEATURE_PPC_LE = 0x00000001,
454 };
455
456 #define ELF_HWCAP get_elf_hwcap()
457
458 static uint32_t get_elf_hwcap(void)
459 {
460     CPUState *e = thread_env;
461     uint32_t features = 0;
462
463     /* We don't have to be terribly complete here; the high points are
464        Altivec/FP/SPE support.  Anything else is just a bonus.  */
465 #define GET_FEATURE(flag, feature)              \
466     do {if (e->insns_flags & flag) features |= feature; } while(0)
467     GET_FEATURE(PPC_64B, PPC_FEATURE_64);
468     GET_FEATURE(PPC_FLOAT, PPC_FEATURE_HAS_FPU);
469     GET_FEATURE(PPC_ALTIVEC, PPC_FEATURE_HAS_ALTIVEC);
470     GET_FEATURE(PPC_SPE, PPC_FEATURE_HAS_SPE);
471     GET_FEATURE(PPC_SPE_SINGLE, PPC_FEATURE_HAS_EFP_SINGLE);
472     GET_FEATURE(PPC_SPE_DOUBLE, PPC_FEATURE_HAS_EFP_DOUBLE);
473     GET_FEATURE(PPC_BOOKE, PPC_FEATURE_BOOKE);
474     GET_FEATURE(PPC_405_MAC, PPC_FEATURE_HAS_4xxMAC);
475 #undef GET_FEATURE
476
477     return features;
478 }
479
480 /*
481  * We need to put in some extra aux table entries to tell glibc what
482  * the cache block size is, so it can use the dcbz instruction safely.
483  */
484 #define AT_DCACHEBSIZE          19
485 #define AT_ICACHEBSIZE          20
486 #define AT_UCACHEBSIZE          21
487 /* A special ignored type value for PPC, for glibc compatibility.  */
488 #define AT_IGNOREPPC            22
489 /*
490  * The requirements here are:
491  * - keep the final alignment of sp (sp & 0xf)
492  * - make sure the 32-bit value at the first 16 byte aligned position of
493  *   AUXV is greater than 16 for glibc compatibility.
494  *   AT_IGNOREPPC is used for that.
495  * - for compatibility with glibc ARCH_DLINFO must always be defined on PPC,
496  *   even if DLINFO_ARCH_ITEMS goes to zero or is undefined.
497  */
498 #define DLINFO_ARCH_ITEMS       5
499 #define ARCH_DLINFO                                                     \
500 do {                                                                    \
501         NEW_AUX_ENT(AT_DCACHEBSIZE, 0x20);                              \
502         NEW_AUX_ENT(AT_ICACHEBSIZE, 0x20);                              \
503         NEW_AUX_ENT(AT_UCACHEBSIZE, 0);                                 \
504         /*                                                              \
505          * Now handle glibc compatibility.                              \
506          */                                                             \
507         NEW_AUX_ENT(AT_IGNOREPPC, AT_IGNOREPPC);                        \
508         NEW_AUX_ENT(AT_IGNOREPPC, AT_IGNOREPPC);                        \
509  } while (0)
510
511 static inline void init_thread(struct target_pt_regs *_regs, struct image_info *infop)
512 {
513     abi_ulong pos = infop->start_stack;
514     abi_ulong tmp;
515 #if defined(TARGET_PPC64) && !defined(TARGET_ABI32)
516     abi_ulong entry, toc;
517 #endif
518
519     _regs->gpr[1] = infop->start_stack;
520 #if defined(TARGET_PPC64) && !defined(TARGET_ABI32)
521     entry = ldq_raw(infop->entry) + infop->load_addr;
522     toc = ldq_raw(infop->entry + 8) + infop->load_addr;
523     _regs->gpr[2] = toc;
524     infop->entry = entry;
525 #endif
526     _regs->nip = infop->entry;
527     /* Note that isn't exactly what regular kernel does
528      * but this is what the ABI wants and is needed to allow
529      * execution of PPC BSD programs.
530      */
531     /* FIXME - what to for failure of get_user()? */
532     get_user_ual(_regs->gpr[3], pos);
533     pos += sizeof(abi_ulong);
534     _regs->gpr[4] = pos;
535     for (tmp = 1; tmp != 0; pos += sizeof(abi_ulong))
536         tmp = ldl(pos);
537     _regs->gpr[5] = pos;
538 }
539
540 #define ELF_EXEC_PAGESIZE       4096
541
542 #endif
543
544 #ifdef TARGET_MIPS
545
546 #define ELF_START_MMAP 0x80000000
547
548 #define elf_check_arch(x) ( (x) == EM_MIPS )
549
550 #ifdef TARGET_MIPS64
551 #define ELF_CLASS   ELFCLASS64
552 #else
553 #define ELF_CLASS   ELFCLASS32
554 #endif
555 #ifdef TARGET_WORDS_BIGENDIAN
556 #define ELF_DATA        ELFDATA2MSB
557 #else
558 #define ELF_DATA        ELFDATA2LSB
559 #endif
560 #define ELF_ARCH    EM_MIPS
561
562 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
563 {
564     regs->cp0_status = 2 << CP0St_KSU;
565     regs->cp0_epc = infop->entry;
566     regs->regs[29] = infop->start_stack;
567 }
568
569 #define ELF_EXEC_PAGESIZE        4096
570
571 #endif /* TARGET_MIPS */
572
573 #ifdef TARGET_MICROBLAZE
574
575 #define ELF_START_MMAP 0x80000000
576
577 #define elf_check_arch(x) ( (x) == EM_XILINX_MICROBLAZE )
578
579 #define ELF_CLASS   ELFCLASS32
580 #define ELF_DATA        ELFDATA2MSB
581 #define ELF_ARCH    EM_MIPS
582
583 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
584 {
585     regs->pc = infop->entry;
586     regs->r1 = infop->start_stack;
587
588 }
589
590 #define USE_ELF_CORE_DUMP
591 #define ELF_EXEC_PAGESIZE        4096
592
593 #endif /* TARGET_MICROBLAZE */
594
595 #ifdef TARGET_SH4
596
597 #define ELF_START_MMAP 0x80000000
598
599 #define elf_check_arch(x) ( (x) == EM_SH )
600
601 #define ELF_CLASS ELFCLASS32
602 #define ELF_DATA  ELFDATA2LSB
603 #define ELF_ARCH  EM_SH
604
605 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
606 {
607   /* Check other registers XXXXX */
608   regs->pc = infop->entry;
609   regs->regs[15] = infop->start_stack;
610 }
611
612 #define ELF_EXEC_PAGESIZE        4096
613
614 #endif
615
616 #ifdef TARGET_CRIS
617
618 #define ELF_START_MMAP 0x80000000
619
620 #define elf_check_arch(x) ( (x) == EM_CRIS )
621
622 #define ELF_CLASS ELFCLASS32
623 #define ELF_DATA  ELFDATA2LSB
624 #define ELF_ARCH  EM_CRIS
625
626 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
627 {
628   regs->erp = infop->entry;
629 }
630
631 #define ELF_EXEC_PAGESIZE        8192
632
633 #endif
634
635 #ifdef TARGET_M68K
636
637 #define ELF_START_MMAP 0x80000000
638
639 #define elf_check_arch(x) ( (x) == EM_68K )
640
641 #define ELF_CLASS       ELFCLASS32
642 #define ELF_DATA        ELFDATA2MSB
643 #define ELF_ARCH        EM_68K
644
645 /* ??? Does this need to do anything?
646 #define ELF_PLAT_INIT(_r) */
647
648 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
649 {
650     regs->usp = infop->start_stack;
651     regs->sr = 0;
652     regs->pc = infop->entry;
653 }
654
655 #define ELF_EXEC_PAGESIZE       8192
656
657 #endif
658
659 #ifdef TARGET_ALPHA
660
661 #define ELF_START_MMAP (0x30000000000ULL)
662
663 #define elf_check_arch(x) ( (x) == ELF_ARCH )
664
665 #define ELF_CLASS      ELFCLASS64
666 #define ELF_DATA       ELFDATA2MSB
667 #define ELF_ARCH       EM_ALPHA
668
669 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
670 {
671     regs->pc = infop->entry;
672     regs->ps = 8;
673     regs->usp = infop->start_stack;
674     regs->unique = infop->start_data; /* ? */
675     printf("Set unique value to " TARGET_FMT_lx " (" TARGET_FMT_lx ")\n",
676            regs->unique, infop->start_data);
677 }
678
679 #define ELF_EXEC_PAGESIZE        8192
680
681 #endif /* TARGET_ALPHA */
682
683 #ifndef ELF_PLATFORM
684 #define ELF_PLATFORM (NULL)
685 #endif
686
687 #ifndef ELF_HWCAP
688 #define ELF_HWCAP 0
689 #endif
690
691 #ifdef TARGET_ABI32
692 #undef ELF_CLASS
693 #define ELF_CLASS ELFCLASS32
694 #undef bswaptls
695 #define bswaptls(ptr) bswap32s(ptr)
696 #endif
697
698 #include "elf.h"
699
700 struct exec
701 {
702   unsigned int a_info;   /* Use macros N_MAGIC, etc for access */
703   unsigned int a_text;   /* length of text, in bytes */
704   unsigned int a_data;   /* length of data, in bytes */
705   unsigned int a_bss;    /* length of uninitialized data area, in bytes */
706   unsigned int a_syms;   /* length of symbol table data in file, in bytes */
707   unsigned int a_entry;  /* start address */
708   unsigned int a_trsize; /* length of relocation info for text, in bytes */
709   unsigned int a_drsize; /* length of relocation info for data, in bytes */
710 };
711
712
713 #define N_MAGIC(exec) ((exec).a_info & 0xffff)
714 #define OMAGIC 0407
715 #define NMAGIC 0410
716 #define ZMAGIC 0413
717 #define QMAGIC 0314
718
719 /* max code+data+bss space allocated to elf interpreter */
720 #define INTERP_MAP_SIZE (32 * 1024 * 1024)
721
722 /* max code+data+bss+brk space allocated to ET_DYN executables */
723 #define ET_DYN_MAP_SIZE (128 * 1024 * 1024)
724
725 /* Necessary parameters */
726 #define TARGET_ELF_EXEC_PAGESIZE TARGET_PAGE_SIZE
727 #define TARGET_ELF_PAGESTART(_v) ((_v) & ~(unsigned long)(TARGET_ELF_EXEC_PAGESIZE-1))
728 #define TARGET_ELF_PAGEOFFSET(_v) ((_v) & (TARGET_ELF_EXEC_PAGESIZE-1))
729
730 #define INTERPRETER_NONE 0
731 #define INTERPRETER_AOUT 1
732 #define INTERPRETER_ELF 2
733
734 #define DLINFO_ITEMS 12
735
736 static inline void memcpy_fromfs(void * to, const void * from, unsigned long n)
737 {
738         memcpy(to, from, n);
739 }
740
741 static int load_aout_interp(void * exptr, int interp_fd);
742
743 #ifdef BSWAP_NEEDED
744 static void bswap_ehdr(struct elfhdr *ehdr)
745 {
746     bswap16s(&ehdr->e_type);                    /* Object file type */
747     bswap16s(&ehdr->e_machine);         /* Architecture */
748     bswap32s(&ehdr->e_version);         /* Object file version */
749     bswaptls(&ehdr->e_entry);           /* Entry point virtual address */
750     bswaptls(&ehdr->e_phoff);           /* Program header table file offset */
751     bswaptls(&ehdr->e_shoff);           /* Section header table file offset */
752     bswap32s(&ehdr->e_flags);           /* Processor-specific flags */
753     bswap16s(&ehdr->e_ehsize);          /* ELF header size in bytes */
754     bswap16s(&ehdr->e_phentsize);               /* Program header table entry size */
755     bswap16s(&ehdr->e_phnum);           /* Program header table entry count */
756     bswap16s(&ehdr->e_shentsize);               /* Section header table entry size */
757     bswap16s(&ehdr->e_shnum);           /* Section header table entry count */
758     bswap16s(&ehdr->e_shstrndx);                /* Section header string table index */
759 }
760
761 static void bswap_phdr(struct elf_phdr *phdr)
762 {
763     bswap32s(&phdr->p_type);                    /* Segment type */
764     bswaptls(&phdr->p_offset);          /* Segment file offset */
765     bswaptls(&phdr->p_vaddr);           /* Segment virtual address */
766     bswaptls(&phdr->p_paddr);           /* Segment physical address */
767     bswaptls(&phdr->p_filesz);          /* Segment size in file */
768     bswaptls(&phdr->p_memsz);           /* Segment size in memory */
769     bswap32s(&phdr->p_flags);           /* Segment flags */
770     bswaptls(&phdr->p_align);           /* Segment alignment */
771 }
772
773 static void bswap_shdr(struct elf_shdr *shdr)
774 {
775     bswap32s(&shdr->sh_name);
776     bswap32s(&shdr->sh_type);
777     bswaptls(&shdr->sh_flags);
778     bswaptls(&shdr->sh_addr);
779     bswaptls(&shdr->sh_offset);
780     bswaptls(&shdr->sh_size);
781     bswap32s(&shdr->sh_link);
782     bswap32s(&shdr->sh_info);
783     bswaptls(&shdr->sh_addralign);
784     bswaptls(&shdr->sh_entsize);
785 }
786
787 static void bswap_sym(struct elf_sym *sym)
788 {
789     bswap32s(&sym->st_name);
790     bswaptls(&sym->st_value);
791     bswaptls(&sym->st_size);
792     bswap16s(&sym->st_shndx);
793 }
794 #endif
795
796 #ifdef USE_ELF_CORE_DUMP
797 static int elf_core_dump(int, const CPUState *);
798
799 #ifdef BSWAP_NEEDED
800 static void bswap_note(struct elf_note *en)
801 {
802     bswaptls(&en->n_namesz);
803     bswaptls(&en->n_descsz);
804     bswaptls(&en->n_type);
805 }
806 #endif /* BSWAP_NEEDED */
807
808 #endif /* USE_ELF_CORE_DUMP */
809
810 /*
811  * 'copy_elf_strings()' copies argument/envelope strings from user
812  * memory to free pages in kernel mem. These are in a format ready
813  * to be put directly into the top of new user memory.
814  *
815  */
816 static abi_ulong copy_elf_strings(int argc,char ** argv, void **page,
817                                   abi_ulong p)
818 {
819     char *tmp, *tmp1, *pag = NULL;
820     int len, offset = 0;
821
822     if (!p) {
823         return 0;       /* bullet-proofing */
824     }
825     while (argc-- > 0) {
826         tmp = argv[argc];
827         if (!tmp) {
828             fprintf(stderr, "VFS: argc is wrong");
829             exit(-1);
830         }
831         tmp1 = tmp;
832         while (*tmp++);
833         len = tmp - tmp1;
834         if (p < len) {  /* this shouldn't happen - 128kB */
835                 return 0;
836         }
837         while (len) {
838             --p; --tmp; --len;
839             if (--offset < 0) {
840                 offset = p % TARGET_PAGE_SIZE;
841                 pag = (char *)page[p/TARGET_PAGE_SIZE];
842                 if (!pag) {
843                     pag = (char *)malloc(TARGET_PAGE_SIZE);
844                     memset(pag, 0, TARGET_PAGE_SIZE);
845                     page[p/TARGET_PAGE_SIZE] = pag;
846                     if (!pag)
847                         return 0;
848                 }
849             }
850             if (len == 0 || offset == 0) {
851                 *(pag + offset) = *tmp;
852             }
853             else {
854               int bytes_to_copy = (len > offset) ? offset : len;
855               tmp -= bytes_to_copy;
856               p -= bytes_to_copy;
857               offset -= bytes_to_copy;
858               len -= bytes_to_copy;
859               memcpy_fromfs(pag + offset, tmp, bytes_to_copy + 1);
860             }
861         }
862     }
863     return p;
864 }
865
866 static abi_ulong setup_arg_pages(abi_ulong p, struct linux_binprm *bprm,
867                                  struct image_info *info)
868 {
869     abi_ulong stack_base, size, error;
870     int i;
871
872     /* Create enough stack to hold everything.  If we don't use
873      * it for args, we'll use it for something else...
874      */
875     size = x86_stack_size;
876     if (size < MAX_ARG_PAGES*TARGET_PAGE_SIZE)
877         size = MAX_ARG_PAGES*TARGET_PAGE_SIZE;
878     error = target_mmap(0,
879                         size + qemu_host_page_size,
880                         PROT_READ | PROT_WRITE,
881                         MAP_PRIVATE | MAP_ANONYMOUS,
882                         -1, 0);
883     if (error == -1) {
884         perror("stk mmap");
885         exit(-1);
886     }
887     /* we reserve one extra page at the top of the stack as guard */
888     target_mprotect(error + size, qemu_host_page_size, PROT_NONE);
889
890     stack_base = error + size - MAX_ARG_PAGES*TARGET_PAGE_SIZE;
891     p += stack_base;
892
893     for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
894         if (bprm->page[i]) {
895             info->rss++;
896             /* FIXME - check return value of memcpy_to_target() for failure */
897             memcpy_to_target(stack_base, bprm->page[i], TARGET_PAGE_SIZE);
898             free(bprm->page[i]);
899         }
900         stack_base += TARGET_PAGE_SIZE;
901     }
902     return p;
903 }
904
905 static void set_brk(abi_ulong start, abi_ulong end)
906 {
907         /* page-align the start and end addresses... */
908         start = HOST_PAGE_ALIGN(start);
909         end = HOST_PAGE_ALIGN(end);
910         if (end <= start)
911                 return;
912         if(target_mmap(start, end - start,
913                        PROT_READ | PROT_WRITE | PROT_EXEC,
914                        MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) == -1) {
915             perror("cannot mmap brk");
916             exit(-1);
917         }
918 }
919
920
921 /* We need to explicitly zero any fractional pages after the data
922    section (i.e. bss).  This would contain the junk from the file that
923    should not be in memory. */
924 static void padzero(abi_ulong elf_bss, abi_ulong last_bss)
925 {
926         abi_ulong nbyte;
927
928         if (elf_bss >= last_bss)
929                 return;
930
931         /* XXX: this is really a hack : if the real host page size is
932            smaller than the target page size, some pages after the end
933            of the file may not be mapped. A better fix would be to
934            patch target_mmap(), but it is more complicated as the file
935            size must be known */
936         if (qemu_real_host_page_size < qemu_host_page_size) {
937             abi_ulong end_addr, end_addr1;
938             end_addr1 = (elf_bss + qemu_real_host_page_size - 1) &
939                 ~(qemu_real_host_page_size - 1);
940             end_addr = HOST_PAGE_ALIGN(elf_bss);
941             if (end_addr1 < end_addr) {
942                 mmap((void *)g2h(end_addr1), end_addr - end_addr1,
943                      PROT_READ|PROT_WRITE|PROT_EXEC,
944                      MAP_FIXED|MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
945             }
946         }
947
948         nbyte = elf_bss & (qemu_host_page_size-1);
949         if (nbyte) {
950             nbyte = qemu_host_page_size - nbyte;
951             do {
952                 /* FIXME - what to do if put_user() fails? */
953                 put_user_u8(0, elf_bss);
954                 elf_bss++;
955             } while (--nbyte);
956         }
957 }
958
959
960 static abi_ulong create_elf_tables(abi_ulong p, int argc, int envc,
961                                    struct elfhdr * exec,
962                                    abi_ulong load_addr,
963                                    abi_ulong load_bias,
964                                    abi_ulong interp_load_addr, int ibcs,
965                                    struct image_info *info)
966 {
967         abi_ulong sp;
968         int size;
969         abi_ulong u_platform;
970         const char *k_platform;
971         const int n = sizeof(elf_addr_t);
972
973         sp = p;
974         u_platform = 0;
975         k_platform = ELF_PLATFORM;
976         if (k_platform) {
977             size_t len = strlen(k_platform) + 1;
978             sp -= (len + n - 1) & ~(n - 1);
979             u_platform = sp;
980             /* FIXME - check return value of memcpy_to_target() for failure */
981             memcpy_to_target(sp, k_platform, len);
982         }
983         /*
984          * Force 16 byte _final_ alignment here for generality.
985          */
986         sp = sp &~ (abi_ulong)15;
987         size = (DLINFO_ITEMS + 1) * 2;
988         if (k_platform)
989           size += 2;
990 #ifdef DLINFO_ARCH_ITEMS
991         size += DLINFO_ARCH_ITEMS * 2;
992 #endif
993         size += envc + argc + 2;
994         size += (!ibcs ? 3 : 1);        /* argc itself */
995         size *= n;
996         if (size & 15)
997             sp -= 16 - (size & 15);
998
999         /* This is correct because Linux defines
1000          * elf_addr_t as Elf32_Off / Elf64_Off
1001          */
1002 #define NEW_AUX_ENT(id, val) do {               \
1003             sp -= n; put_user_ual(val, sp);     \
1004             sp -= n; put_user_ual(id, sp);      \
1005           } while(0)
1006
1007         NEW_AUX_ENT (AT_NULL, 0);
1008
1009         /* There must be exactly DLINFO_ITEMS entries here.  */
1010         NEW_AUX_ENT(AT_PHDR, (abi_ulong)(load_addr + exec->e_phoff));
1011         NEW_AUX_ENT(AT_PHENT, (abi_ulong)(sizeof (struct elf_phdr)));
1012         NEW_AUX_ENT(AT_PHNUM, (abi_ulong)(exec->e_phnum));
1013         NEW_AUX_ENT(AT_PAGESZ, (abi_ulong)(TARGET_PAGE_SIZE));
1014         NEW_AUX_ENT(AT_BASE, (abi_ulong)(interp_load_addr));
1015         NEW_AUX_ENT(AT_FLAGS, (abi_ulong)0);
1016         NEW_AUX_ENT(AT_ENTRY, load_bias + exec->e_entry);
1017         NEW_AUX_ENT(AT_UID, (abi_ulong) getuid());
1018         NEW_AUX_ENT(AT_EUID, (abi_ulong) geteuid());
1019         NEW_AUX_ENT(AT_GID, (abi_ulong) getgid());
1020         NEW_AUX_ENT(AT_EGID, (abi_ulong) getegid());
1021         NEW_AUX_ENT(AT_HWCAP, (abi_ulong) ELF_HWCAP);
1022         NEW_AUX_ENT(AT_CLKTCK, (abi_ulong) sysconf(_SC_CLK_TCK));
1023         if (k_platform)
1024             NEW_AUX_ENT(AT_PLATFORM, u_platform);
1025 #ifdef ARCH_DLINFO
1026         /*
1027          * ARCH_DLINFO must come last so platform specific code can enforce
1028          * special alignment requirements on the AUXV if necessary (eg. PPC).
1029          */
1030         ARCH_DLINFO;
1031 #endif
1032 #undef NEW_AUX_ENT
1033
1034         info->saved_auxv = sp;
1035
1036         sp = loader_build_argptr(envc, argc, sp, p, !ibcs);
1037         return sp;
1038 }
1039
1040
1041 static abi_ulong load_elf_interp(struct elfhdr * interp_elf_ex,
1042                                  int interpreter_fd,
1043                                  abi_ulong *interp_load_addr)
1044 {
1045         struct elf_phdr *elf_phdata  =  NULL;
1046         struct elf_phdr *eppnt;
1047         abi_ulong load_addr = 0;
1048         int load_addr_set = 0;
1049         int retval;
1050         abi_ulong last_bss, elf_bss;
1051         abi_ulong error;
1052         int i;
1053
1054         elf_bss = 0;
1055         last_bss = 0;
1056         error = 0;
1057
1058 #ifdef BSWAP_NEEDED
1059         bswap_ehdr(interp_elf_ex);
1060 #endif
1061         /* First of all, some simple consistency checks */
1062         if ((interp_elf_ex->e_type != ET_EXEC &&
1063              interp_elf_ex->e_type != ET_DYN) ||
1064            !elf_check_arch(interp_elf_ex->e_machine)) {
1065                 return ~((abi_ulong)0UL);
1066         }
1067
1068
1069         /* Now read in all of the header information */
1070
1071         if (sizeof(struct elf_phdr) * interp_elf_ex->e_phnum > TARGET_PAGE_SIZE)
1072             return ~(abi_ulong)0UL;
1073
1074         elf_phdata =  (struct elf_phdr *)
1075                 malloc(sizeof(struct elf_phdr) * interp_elf_ex->e_phnum);
1076
1077         if (!elf_phdata)
1078           return ~((abi_ulong)0UL);
1079
1080         /*
1081          * If the size of this structure has changed, then punt, since
1082          * we will be doing the wrong thing.
1083          */
1084         if (interp_elf_ex->e_phentsize != sizeof(struct elf_phdr)) {
1085             free(elf_phdata);
1086             return ~((abi_ulong)0UL);
1087         }
1088
1089         retval = lseek(interpreter_fd, interp_elf_ex->e_phoff, SEEK_SET);
1090         if(retval >= 0) {
1091             retval = read(interpreter_fd,
1092                            (char *) elf_phdata,
1093                            sizeof(struct elf_phdr) * interp_elf_ex->e_phnum);
1094         }
1095         if (retval < 0) {
1096                 perror("load_elf_interp");
1097                 exit(-1);
1098                 free (elf_phdata);
1099                 return retval;
1100         }
1101 #ifdef BSWAP_NEEDED
1102         eppnt = elf_phdata;
1103         for (i=0; i<interp_elf_ex->e_phnum; i++, eppnt++) {
1104             bswap_phdr(eppnt);
1105         }
1106 #endif
1107
1108         if (interp_elf_ex->e_type == ET_DYN) {
1109             /* in order to avoid hardcoding the interpreter load
1110                address in qemu, we allocate a big enough memory zone */
1111             error = target_mmap(0, INTERP_MAP_SIZE,
1112                                 PROT_NONE, MAP_PRIVATE | MAP_ANON,
1113                                 -1, 0);
1114             if (error == -1) {
1115                 perror("mmap");
1116                 exit(-1);
1117             }
1118             load_addr = error;
1119             load_addr_set = 1;
1120         }
1121
1122         eppnt = elf_phdata;
1123         for(i=0; i<interp_elf_ex->e_phnum; i++, eppnt++)
1124           if (eppnt->p_type == PT_LOAD) {
1125             int elf_type = MAP_PRIVATE | MAP_DENYWRITE;
1126             int elf_prot = 0;
1127             abi_ulong vaddr = 0;
1128             abi_ulong k;
1129
1130             if (eppnt->p_flags & PF_R) elf_prot =  PROT_READ;
1131             if (eppnt->p_flags & PF_W) elf_prot |= PROT_WRITE;
1132             if (eppnt->p_flags & PF_X) elf_prot |= PROT_EXEC;
1133             if (interp_elf_ex->e_type == ET_EXEC || load_addr_set) {
1134                 elf_type |= MAP_FIXED;
1135                 vaddr = eppnt->p_vaddr;
1136             }
1137             error = target_mmap(load_addr+TARGET_ELF_PAGESTART(vaddr),
1138                  eppnt->p_filesz + TARGET_ELF_PAGEOFFSET(eppnt->p_vaddr),
1139                  elf_prot,
1140                  elf_type,
1141                  interpreter_fd,
1142                  eppnt->p_offset - TARGET_ELF_PAGEOFFSET(eppnt->p_vaddr));
1143
1144             if (error == -1) {
1145               /* Real error */
1146               close(interpreter_fd);
1147               free(elf_phdata);
1148               return ~((abi_ulong)0UL);
1149             }
1150
1151             if (!load_addr_set && interp_elf_ex->e_type == ET_DYN) {
1152               load_addr = error;
1153               load_addr_set = 1;
1154             }
1155
1156             /*
1157              * Find the end of the file  mapping for this phdr, and keep
1158              * track of the largest address we see for this.
1159              */
1160             k = load_addr + eppnt->p_vaddr + eppnt->p_filesz;
1161             if (k > elf_bss) elf_bss = k;
1162
1163             /*
1164              * Do the same thing for the memory mapping - between
1165              * elf_bss and last_bss is the bss section.
1166              */
1167             k = load_addr + eppnt->p_memsz + eppnt->p_vaddr;
1168             if (k > last_bss) last_bss = k;
1169           }
1170
1171         /* Now use mmap to map the library into memory. */
1172
1173         close(interpreter_fd);
1174
1175         /*
1176          * Now fill out the bss section.  First pad the last page up
1177          * to the page boundary, and then perform a mmap to make sure
1178          * that there are zeromapped pages up to and including the last
1179          * bss page.
1180          */
1181         padzero(elf_bss, last_bss);
1182         elf_bss = TARGET_ELF_PAGESTART(elf_bss + qemu_host_page_size - 1); /* What we have mapped so far */
1183
1184         /* Map the last of the bss segment */
1185         if (last_bss > elf_bss) {
1186             target_mmap(elf_bss, last_bss-elf_bss,
1187                         PROT_READ|PROT_WRITE|PROT_EXEC,
1188                         MAP_FIXED|MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
1189         }
1190         free(elf_phdata);
1191
1192         *interp_load_addr = load_addr;
1193         return ((abi_ulong) interp_elf_ex->e_entry) + load_addr;
1194 }
1195
1196 static int symfind(const void *s0, const void *s1)
1197 {
1198     struct elf_sym *key = (struct elf_sym *)s0;
1199     struct elf_sym *sym = (struct elf_sym *)s1;
1200     int result = 0;
1201     if (key->st_value < sym->st_value) {
1202         result = -1;
1203     } else if (key->st_value > sym->st_value + sym->st_size) {
1204         result = 1;
1205     }
1206     return result;
1207 }
1208
1209 static const char *lookup_symbolxx(struct syminfo *s, target_ulong orig_addr)
1210 {
1211 #if ELF_CLASS == ELFCLASS32
1212     struct elf_sym *syms = s->disas_symtab.elf32;
1213 #else
1214     struct elf_sym *syms = s->disas_symtab.elf64;
1215 #endif
1216
1217     // binary search
1218     struct elf_sym key;
1219     struct elf_sym *sym;
1220
1221     key.st_value = orig_addr;
1222
1223     sym = bsearch(&key, syms, s->disas_num_syms, sizeof(*syms), symfind);
1224     if (sym != 0) {
1225         return s->disas_strtab + sym->st_name;
1226     }
1227
1228     return "";
1229 }
1230
1231 /* FIXME: This should use elf_ops.h  */
1232 static int symcmp(const void *s0, const void *s1)
1233 {
1234     struct elf_sym *sym0 = (struct elf_sym *)s0;
1235     struct elf_sym *sym1 = (struct elf_sym *)s1;
1236     return (sym0->st_value < sym1->st_value)
1237         ? -1
1238         : ((sym0->st_value > sym1->st_value) ? 1 : 0);
1239 }
1240
1241 /* Best attempt to load symbols from this ELF object. */
1242 static void load_symbols(struct elfhdr *hdr, int fd)
1243 {
1244     unsigned int i, nsyms;
1245     struct elf_shdr sechdr, symtab, strtab;
1246     char *strings;
1247     struct syminfo *s;
1248     struct elf_sym *syms;
1249
1250     lseek(fd, hdr->e_shoff, SEEK_SET);
1251     for (i = 0; i < hdr->e_shnum; i++) {
1252         if (read(fd, &sechdr, sizeof(sechdr)) != sizeof(sechdr))
1253             return;
1254 #ifdef BSWAP_NEEDED
1255         bswap_shdr(&sechdr);
1256 #endif
1257         if (sechdr.sh_type == SHT_SYMTAB) {
1258             symtab = sechdr;
1259             lseek(fd, hdr->e_shoff
1260                   + sizeof(sechdr) * sechdr.sh_link, SEEK_SET);
1261             if (read(fd, &strtab, sizeof(strtab))
1262                 != sizeof(strtab))
1263                 return;
1264 #ifdef BSWAP_NEEDED
1265             bswap_shdr(&strtab);
1266 #endif
1267             goto found;
1268         }
1269     }
1270     return; /* Shouldn't happen... */
1271
1272  found:
1273     /* Now know where the strtab and symtab are.  Snarf them. */
1274     s = malloc(sizeof(*s));
1275     syms = malloc(symtab.sh_size);
1276     if (!syms)
1277         return;
1278     s->disas_strtab = strings = malloc(strtab.sh_size);
1279     if (!s->disas_strtab)
1280         return;
1281
1282     lseek(fd, symtab.sh_offset, SEEK_SET);
1283     if (read(fd, syms, symtab.sh_size) != symtab.sh_size)
1284         return;
1285
1286     nsyms = symtab.sh_size / sizeof(struct elf_sym);
1287
1288     i = 0;
1289     while (i < nsyms) {
1290 #ifdef BSWAP_NEEDED
1291         bswap_sym(syms + i);
1292 #endif
1293         // Throw away entries which we do not need.
1294         if (syms[i].st_shndx == SHN_UNDEF ||
1295                 syms[i].st_shndx >= SHN_LORESERVE ||
1296                 ELF_ST_TYPE(syms[i].st_info) != STT_FUNC) {
1297             nsyms--;
1298             if (i < nsyms) {
1299                 syms[i] = syms[nsyms];
1300             }
1301             continue;
1302         }
1303 #if defined(TARGET_ARM) || defined (TARGET_MIPS)
1304         /* The bottom address bit marks a Thumb or MIPS16 symbol.  */
1305         syms[i].st_value &= ~(target_ulong)1;
1306 #endif
1307         i++;
1308     }
1309     syms = realloc(syms, nsyms * sizeof(*syms));
1310
1311     qsort(syms, nsyms, sizeof(*syms), symcmp);
1312
1313     lseek(fd, strtab.sh_offset, SEEK_SET);
1314     if (read(fd, strings, strtab.sh_size) != strtab.sh_size)
1315         return;
1316     s->disas_num_syms = nsyms;
1317 #if ELF_CLASS == ELFCLASS32
1318     s->disas_symtab.elf32 = syms;
1319     s->lookup_symbol = lookup_symbolxx;
1320 #else
1321     s->disas_symtab.elf64 = syms;
1322     s->lookup_symbol = lookup_symbolxx;
1323 #endif
1324     s->next = syminfos;
1325     syminfos = s;
1326 }
1327
1328 int load_elf_binary(struct linux_binprm * bprm, struct target_pt_regs * regs,
1329                     struct image_info * info)
1330 {
1331     struct elfhdr elf_ex;
1332     struct elfhdr interp_elf_ex;
1333     struct exec interp_ex;
1334     int interpreter_fd = -1; /* avoid warning */
1335     abi_ulong load_addr, load_bias;
1336     int load_addr_set = 0;
1337     unsigned int interpreter_type = INTERPRETER_NONE;
1338     unsigned char ibcs2_interpreter;
1339     int i;
1340     abi_ulong mapped_addr;
1341     struct elf_phdr * elf_ppnt;
1342     struct elf_phdr *elf_phdata;
1343     abi_ulong elf_bss, k, elf_brk;
1344     int retval;
1345     char * elf_interpreter;
1346     abi_ulong elf_entry, interp_load_addr = 0;
1347     int status;
1348     abi_ulong start_code, end_code, start_data, end_data;
1349     abi_ulong reloc_func_desc = 0;
1350     abi_ulong elf_stack;
1351     char passed_fileno[6];
1352
1353     ibcs2_interpreter = 0;
1354     status = 0;
1355     load_addr = 0;
1356     load_bias = 0;
1357     elf_ex = *((struct elfhdr *) bprm->buf);          /* exec-header */
1358 #ifdef BSWAP_NEEDED
1359     bswap_ehdr(&elf_ex);
1360 #endif
1361
1362     /* First of all, some simple consistency checks */
1363     if ((elf_ex.e_type != ET_EXEC && elf_ex.e_type != ET_DYN) ||
1364                                 (! elf_check_arch(elf_ex.e_machine))) {
1365             return -ENOEXEC;
1366     }
1367
1368     bprm->p = copy_elf_strings(1, &bprm->filename, bprm->page, bprm->p);
1369     bprm->p = copy_elf_strings(bprm->envc,bprm->envp,bprm->page,bprm->p);
1370     bprm->p = copy_elf_strings(bprm->argc,bprm->argv,bprm->page,bprm->p);
1371     if (!bprm->p) {
1372         retval = -E2BIG;
1373     }
1374
1375     /* Now read in all of the header information */
1376     elf_phdata = (struct elf_phdr *)malloc(elf_ex.e_phentsize*elf_ex.e_phnum);
1377     if (elf_phdata == NULL) {
1378         return -ENOMEM;
1379     }
1380
1381     retval = lseek(bprm->fd, elf_ex.e_phoff, SEEK_SET);
1382     if(retval > 0) {
1383         retval = read(bprm->fd, (char *) elf_phdata,
1384                                 elf_ex.e_phentsize * elf_ex.e_phnum);
1385     }
1386
1387     if (retval < 0) {
1388         perror("load_elf_binary");
1389         exit(-1);
1390         free (elf_phdata);
1391         return -errno;
1392     }
1393
1394 #ifdef BSWAP_NEEDED
1395     elf_ppnt = elf_phdata;
1396     for (i=0; i<elf_ex.e_phnum; i++, elf_ppnt++) {
1397         bswap_phdr(elf_ppnt);
1398     }
1399 #endif
1400     elf_ppnt = elf_phdata;
1401
1402     elf_bss = 0;
1403     elf_brk = 0;
1404
1405
1406     elf_stack = ~((abi_ulong)0UL);
1407     elf_interpreter = NULL;
1408     start_code = ~((abi_ulong)0UL);
1409     end_code = 0;
1410     start_data = 0;
1411     end_data = 0;
1412     interp_ex.a_info = 0;
1413
1414     for(i=0;i < elf_ex.e_phnum; i++) {
1415         if (elf_ppnt->p_type == PT_INTERP) {
1416             if ( elf_interpreter != NULL )
1417             {
1418                 free (elf_phdata);
1419                 free(elf_interpreter);
1420                 close(bprm->fd);
1421                 return -EINVAL;
1422             }
1423
1424             /* This is the program interpreter used for
1425              * shared libraries - for now assume that this
1426              * is an a.out format binary
1427              */
1428
1429             elf_interpreter = (char *)malloc(elf_ppnt->p_filesz);
1430
1431             if (elf_interpreter == NULL) {
1432                 free (elf_phdata);
1433                 close(bprm->fd);
1434                 return -ENOMEM;
1435             }
1436
1437             retval = lseek(bprm->fd, elf_ppnt->p_offset, SEEK_SET);
1438             if(retval >= 0) {
1439                 retval = read(bprm->fd, elf_interpreter, elf_ppnt->p_filesz);
1440             }
1441             if(retval < 0) {
1442                 perror("load_elf_binary2");
1443                 exit(-1);
1444             }
1445
1446             /* If the program interpreter is one of these two,
1447                then assume an iBCS2 image. Otherwise assume
1448                a native linux image. */
1449
1450             /* JRP - Need to add X86 lib dir stuff here... */
1451
1452             if (strcmp(elf_interpreter,"/usr/lib/libc.so.1") == 0 ||
1453                 strcmp(elf_interpreter,"/usr/lib/ld.so.1") == 0) {
1454               ibcs2_interpreter = 1;
1455             }
1456
1457 #if 0
1458             printf("Using ELF interpreter %s\n", elf_interpreter);
1459 #endif
1460             if (retval >= 0) {
1461                 retval = open(path(elf_interpreter), O_RDONLY);
1462                 if(retval >= 0) {
1463                     interpreter_fd = retval;
1464                 }
1465                 else {
1466                     perror(elf_interpreter);
1467                     exit(-1);
1468                     /* retval = -errno; */
1469                 }
1470             }
1471
1472             if (retval >= 0) {
1473                 retval = lseek(interpreter_fd, 0, SEEK_SET);
1474                 if(retval >= 0) {
1475                     retval = read(interpreter_fd,bprm->buf,128);
1476                 }
1477             }
1478             if (retval >= 0) {
1479                 interp_ex = *((struct exec *) bprm->buf); /* aout exec-header */
1480                 interp_elf_ex=*((struct elfhdr *) bprm->buf); /* elf exec-header */
1481             }
1482             if (retval < 0) {
1483                 perror("load_elf_binary3");
1484                 exit(-1);
1485                 free (elf_phdata);
1486                 free(elf_interpreter);
1487                 close(bprm->fd);
1488                 return retval;
1489             }
1490         }
1491         elf_ppnt++;
1492     }
1493
1494     /* Some simple consistency checks for the interpreter */
1495     if (elf_interpreter){
1496         interpreter_type = INTERPRETER_ELF | INTERPRETER_AOUT;
1497
1498         /* Now figure out which format our binary is */
1499         if ((N_MAGIC(interp_ex) != OMAGIC) && (N_MAGIC(interp_ex) != ZMAGIC) &&
1500                 (N_MAGIC(interp_ex) != QMAGIC)) {
1501           interpreter_type = INTERPRETER_ELF;
1502         }
1503
1504         if (interp_elf_ex.e_ident[0] != 0x7f ||
1505             strncmp((char *)&interp_elf_ex.e_ident[1], "ELF",3) != 0) {
1506             interpreter_type &= ~INTERPRETER_ELF;
1507         }
1508
1509         if (!interpreter_type) {
1510             free(elf_interpreter);
1511             free(elf_phdata);
1512             close(bprm->fd);
1513             return -ELIBBAD;
1514         }
1515     }
1516
1517     /* OK, we are done with that, now set up the arg stuff,
1518        and then start this sucker up */
1519
1520     {
1521         char * passed_p;
1522
1523         if (interpreter_type == INTERPRETER_AOUT) {
1524             snprintf(passed_fileno, sizeof(passed_fileno), "%d", bprm->fd);
1525             passed_p = passed_fileno;
1526
1527             if (elf_interpreter) {
1528                 bprm->p = copy_elf_strings(1,&passed_p,bprm->page,bprm->p);
1529                 bprm->argc++;
1530             }
1531         }
1532         if (!bprm->p) {
1533             if (elf_interpreter) {
1534                 free(elf_interpreter);
1535             }
1536             free (elf_phdata);
1537             close(bprm->fd);
1538             return -E2BIG;
1539         }
1540     }
1541
1542     /* OK, This is the point of no return */
1543     info->end_data = 0;
1544     info->end_code = 0;
1545     info->start_mmap = (abi_ulong)ELF_START_MMAP;
1546     info->mmap = 0;
1547     elf_entry = (abi_ulong) elf_ex.e_entry;
1548
1549 #if defined(CONFIG_USE_GUEST_BASE)
1550     /*
1551      * In case where user has not explicitly set the guest_base, we
1552      * probe here that should we set it automatically.
1553      */
1554     if (guest_base == 0) {
1555         /*
1556          * Go through ELF program header table and find out whether
1557          * any of the segments drop below our current mmap_min_addr and
1558          * in that case set guest_base to corresponding address.
1559          */
1560         for (i = 0, elf_ppnt = elf_phdata; i < elf_ex.e_phnum;
1561             i++, elf_ppnt++) {
1562             if (elf_ppnt->p_type != PT_LOAD)
1563                 continue;
1564             if (HOST_PAGE_ALIGN(elf_ppnt->p_vaddr) < mmap_min_addr) {
1565                 guest_base = HOST_PAGE_ALIGN(mmap_min_addr);
1566                 qemu_log("setting guest_base=0x%lx\n", guest_base);
1567                 break;
1568             }
1569         }
1570     }
1571 #endif /* CONFIG_USE_GUEST_BASE */
1572
1573     /* Do this so that we can load the interpreter, if need be.  We will
1574        change some of these later */
1575     info->rss = 0;
1576     bprm->p = setup_arg_pages(bprm->p, bprm, info);
1577     info->start_stack = bprm->p;
1578
1579     /* Now we do a little grungy work by mmaping the ELF image into
1580      * the correct location in memory.  At this point, we assume that
1581      * the image should be loaded at fixed address, not at a variable
1582      * address.
1583      */
1584
1585     for(i = 0, elf_ppnt = elf_phdata; i < elf_ex.e_phnum; i++, elf_ppnt++) {
1586         int elf_prot = 0;
1587         int elf_flags = 0;
1588         abi_ulong error;
1589
1590         if (elf_ppnt->p_type != PT_LOAD)
1591             continue;
1592
1593         if (elf_ppnt->p_flags & PF_R) elf_prot |= PROT_READ;
1594         if (elf_ppnt->p_flags & PF_W) elf_prot |= PROT_WRITE;
1595         if (elf_ppnt->p_flags & PF_X) elf_prot |= PROT_EXEC;
1596         elf_flags = MAP_PRIVATE | MAP_DENYWRITE;
1597         if (elf_ex.e_type == ET_EXEC || load_addr_set) {
1598             elf_flags |= MAP_FIXED;
1599         } else if (elf_ex.e_type == ET_DYN) {
1600             /* Try and get dynamic programs out of the way of the default mmap
1601                base, as well as whatever program they might try to exec.  This
1602                is because the brk will follow the loader, and is not movable.  */
1603             /* NOTE: for qemu, we do a big mmap to get enough space
1604                without hardcoding any address */
1605             error = target_mmap(0, ET_DYN_MAP_SIZE,
1606                                 PROT_NONE, MAP_PRIVATE | MAP_ANON,
1607                                 -1, 0);
1608             if (error == -1) {
1609                 perror("mmap");
1610                 exit(-1);
1611             }
1612             load_bias = TARGET_ELF_PAGESTART(error - elf_ppnt->p_vaddr);
1613         }
1614
1615         error = target_mmap(TARGET_ELF_PAGESTART(load_bias + elf_ppnt->p_vaddr),
1616                             (elf_ppnt->p_filesz +
1617                              TARGET_ELF_PAGEOFFSET(elf_ppnt->p_vaddr)),
1618                             elf_prot,
1619                             (MAP_FIXED | MAP_PRIVATE | MAP_DENYWRITE),
1620                             bprm->fd,
1621                             (elf_ppnt->p_offset -
1622                              TARGET_ELF_PAGEOFFSET(elf_ppnt->p_vaddr)));
1623         if (error == -1) {
1624             perror("mmap");
1625             exit(-1);
1626         }
1627
1628 #ifdef LOW_ELF_STACK
1629         if (TARGET_ELF_PAGESTART(elf_ppnt->p_vaddr) < elf_stack)
1630             elf_stack = TARGET_ELF_PAGESTART(elf_ppnt->p_vaddr);
1631 #endif
1632
1633         if (!load_addr_set) {
1634             load_addr_set = 1;
1635             load_addr = elf_ppnt->p_vaddr - elf_ppnt->p_offset;
1636             if (elf_ex.e_type == ET_DYN) {
1637                 load_bias += error -
1638                     TARGET_ELF_PAGESTART(load_bias + elf_ppnt->p_vaddr);
1639                 load_addr += load_bias;
1640                 reloc_func_desc = load_bias;
1641             }
1642         }
1643         k = elf_ppnt->p_vaddr;
1644         if (k < start_code)
1645             start_code = k;
1646         if (start_data < k)
1647             start_data = k;
1648         k = elf_ppnt->p_vaddr + elf_ppnt->p_filesz;
1649         if (k > elf_bss)
1650             elf_bss = k;
1651         if ((elf_ppnt->p_flags & PF_X) && end_code <  k)
1652             end_code = k;
1653         if (end_data < k)
1654             end_data = k;
1655         k = elf_ppnt->p_vaddr + elf_ppnt->p_memsz;
1656         if (k > elf_brk) elf_brk = k;
1657     }
1658
1659     elf_entry += load_bias;
1660     elf_bss += load_bias;
1661     elf_brk += load_bias;
1662     start_code += load_bias;
1663     end_code += load_bias;
1664     start_data += load_bias;
1665     end_data += load_bias;
1666
1667     if (elf_interpreter) {
1668         if (interpreter_type & 1) {
1669             elf_entry = load_aout_interp(&interp_ex, interpreter_fd);
1670         }
1671         else if (interpreter_type & 2) {
1672             elf_entry = load_elf_interp(&interp_elf_ex, interpreter_fd,
1673                                             &interp_load_addr);
1674         }
1675         reloc_func_desc = interp_load_addr;
1676
1677         close(interpreter_fd);
1678         free(elf_interpreter);
1679
1680         if (elf_entry == ~((abi_ulong)0UL)) {
1681             printf("Unable to load interpreter\n");
1682             free(elf_phdata);
1683             exit(-1);
1684             return 0;
1685         }
1686     }
1687
1688     free(elf_phdata);
1689
1690     if (qemu_log_enabled())
1691         load_symbols(&elf_ex, bprm->fd);
1692
1693     if (interpreter_type != INTERPRETER_AOUT) close(bprm->fd);
1694     info->personality = (ibcs2_interpreter ? PER_SVR4 : PER_LINUX);
1695
1696 #ifdef LOW_ELF_STACK
1697     info->start_stack = bprm->p = elf_stack - 4;
1698 #endif
1699     bprm->p = create_elf_tables(bprm->p,
1700                     bprm->argc,
1701                     bprm->envc,
1702                     &elf_ex,
1703                     load_addr, load_bias,
1704                     interp_load_addr,
1705                     (interpreter_type == INTERPRETER_AOUT ? 0 : 1),
1706                     info);
1707     info->load_addr = reloc_func_desc;
1708     info->start_brk = info->brk = elf_brk;
1709     info->end_code = end_code;
1710     info->start_code = start_code;
1711     info->start_data = start_data;
1712     info->end_data = end_data;
1713     info->start_stack = bprm->p;
1714
1715     /* Calling set_brk effectively mmaps the pages that we need for the bss and break
1716        sections */
1717     set_brk(elf_bss, elf_brk);
1718
1719     padzero(elf_bss, elf_brk);
1720
1721 #if 0
1722     printf("(start_brk) %x\n" , info->start_brk);
1723     printf("(end_code) %x\n" , info->end_code);
1724     printf("(start_code) %x\n" , info->start_code);
1725     printf("(end_data) %x\n" , info->end_data);
1726     printf("(start_stack) %x\n" , info->start_stack);
1727     printf("(brk) %x\n" , info->brk);
1728 #endif
1729
1730     if ( info->personality == PER_SVR4 )
1731     {
1732             /* Why this, you ask???  Well SVr4 maps page 0 as read-only,
1733                and some applications "depend" upon this behavior.
1734                Since we do not have the power to recompile these, we
1735                emulate the SVr4 behavior.  Sigh.  */
1736             mapped_addr = target_mmap(0, qemu_host_page_size, PROT_READ | PROT_EXEC,
1737                                       MAP_FIXED | MAP_PRIVATE, -1, 0);
1738     }
1739
1740     info->entry = elf_entry;
1741
1742 #ifdef USE_ELF_CORE_DUMP
1743     bprm->core_dump = &elf_core_dump;
1744 #endif
1745
1746     return 0;
1747 }
1748
1749 #ifdef USE_ELF_CORE_DUMP
1750
1751 /*
1752  * Definitions to generate Intel SVR4-like core files.
1753  * These mostly have the same names as the SVR4 types with "elf_"
1754  * tacked on the front to prevent clashes with linux definitions,
1755  * and the typedef forms have been avoided.  This is mostly like
1756  * the SVR4 structure, but more Linuxy, with things that Linux does
1757  * not support and which gdb doesn't really use excluded.
1758  *
1759  * Fields we don't dump (their contents is zero) in linux-user qemu
1760  * are marked with XXX.
1761  *
1762  * Core dump code is copied from linux kernel (fs/binfmt_elf.c).
1763  *
1764  * Porting ELF coredump for target is (quite) simple process.  First you
1765  * define ELF_USE_CORE_DUMP in target ELF code (where init_thread() for
1766  * the target resides):
1767  *
1768  * #define USE_ELF_CORE_DUMP
1769  *
1770  * Next you define type of register set used for dumping.  ELF specification
1771  * says that it needs to be array of elf_greg_t that has size of ELF_NREG.
1772  *
1773  * typedef <target_regtype> elf_greg_t;
1774  * #define ELF_NREG <number of registers>
1775  * typedef elf_greg_t elf_gregset_t[ELF_NREG];
1776  *
1777  * Then define following types to match target types.  Actual types can
1778  * be found from linux kernel (arch/<ARCH>/include/asm/posix_types.h):
1779  *
1780  * typedef <target_uid_type> target_uid_t;
1781  * typedef <target_gid_type> target_gid_t;
1782  * typedef <target_pid_type> target_pid_t;
1783  *
1784  * Last step is to implement target specific function that copies registers
1785  * from given cpu into just specified register set.  Prototype is:
1786  *
1787  * static void elf_core_copy_regs(elf_gregset_t *regs, const CPUState *env);
1788  *
1789  * Parameters:
1790  *     regs - copy register values into here (allocated and zeroed by caller)
1791  *     env - copy registers from here
1792  *
1793  * Example for ARM target is provided in this file.
1794  */
1795
1796 /* An ELF note in memory */
1797 struct memelfnote {
1798     const char *name;
1799     size_t     namesz;
1800     size_t     namesz_rounded;
1801     int        type;
1802     size_t     datasz;
1803     void       *data;
1804     size_t     notesz;
1805 };
1806
1807 struct elf_siginfo {
1808     int  si_signo; /* signal number */
1809     int  si_code;  /* extra code */
1810     int  si_errno; /* errno */
1811 };
1812
1813 struct elf_prstatus {
1814     struct elf_siginfo pr_info;      /* Info associated with signal */
1815     short              pr_cursig;    /* Current signal */
1816     target_ulong       pr_sigpend;   /* XXX */
1817     target_ulong       pr_sighold;   /* XXX */
1818     target_pid_t       pr_pid;
1819     target_pid_t       pr_ppid;
1820     target_pid_t       pr_pgrp;
1821     target_pid_t       pr_sid;
1822     struct target_timeval pr_utime;  /* XXX User time */
1823     struct target_timeval pr_stime;  /* XXX System time */
1824     struct target_timeval pr_cutime; /* XXX Cumulative user time */
1825     struct target_timeval pr_cstime; /* XXX Cumulative system time */
1826     elf_gregset_t      pr_reg;       /* GP registers */
1827     int                pr_fpvalid;   /* XXX */
1828 };
1829
1830 #define ELF_PRARGSZ     (80) /* Number of chars for args */
1831
1832 struct elf_prpsinfo {
1833     char         pr_state;       /* numeric process state */
1834     char         pr_sname;       /* char for pr_state */
1835     char         pr_zomb;        /* zombie */
1836     char         pr_nice;        /* nice val */
1837     target_ulong pr_flag;        /* flags */
1838     target_uid_t pr_uid;
1839     target_gid_t pr_gid;
1840     target_pid_t pr_pid, pr_ppid, pr_pgrp, pr_sid;
1841     /* Lots missing */
1842     char    pr_fname[16];           /* filename of executable */
1843     char    pr_psargs[ELF_PRARGSZ]; /* initial part of arg list */
1844 };
1845
1846 /* Here is the structure in which status of each thread is captured. */
1847 struct elf_thread_status {
1848     TAILQ_ENTRY(elf_thread_status)  ets_link;
1849     struct elf_prstatus prstatus;   /* NT_PRSTATUS */
1850 #if 0
1851     elf_fpregset_t fpu;             /* NT_PRFPREG */
1852     struct task_struct *thread;
1853     elf_fpxregset_t xfpu;           /* ELF_CORE_XFPREG_TYPE */
1854 #endif
1855     struct memelfnote notes[1];
1856     int num_notes;
1857 };
1858
1859 struct elf_note_info {
1860     struct memelfnote   *notes;
1861     struct elf_prstatus *prstatus;  /* NT_PRSTATUS */
1862     struct elf_prpsinfo *psinfo;    /* NT_PRPSINFO */
1863
1864     TAILQ_HEAD(thread_list_head, elf_thread_status) thread_list;
1865 #if 0
1866     /*
1867      * Current version of ELF coredump doesn't support
1868      * dumping fp regs etc.
1869      */
1870     elf_fpregset_t *fpu;
1871     elf_fpxregset_t *xfpu;
1872     int thread_status_size;
1873 #endif
1874     int notes_size;
1875     int numnote;
1876 };
1877
1878 struct vm_area_struct {
1879     abi_ulong   vma_start;  /* start vaddr of memory region */
1880     abi_ulong   vma_end;    /* end vaddr of memory region */
1881     abi_ulong   vma_flags;  /* protection etc. flags for the region */
1882     TAILQ_ENTRY(vm_area_struct) vma_link;
1883 };
1884
1885 struct mm_struct {
1886     TAILQ_HEAD(, vm_area_struct) mm_mmap;
1887     int mm_count;           /* number of mappings */
1888 };
1889
1890 static struct mm_struct *vma_init(void);
1891 static void vma_delete(struct mm_struct *);
1892 static int vma_add_mapping(struct mm_struct *, abi_ulong,
1893     abi_ulong, abi_ulong);
1894 static int vma_get_mapping_count(const struct mm_struct *);
1895 static struct vm_area_struct *vma_first(const struct mm_struct *);
1896 static struct vm_area_struct *vma_next(struct vm_area_struct *);
1897 static abi_ulong vma_dump_size(const struct vm_area_struct *);
1898 static int vma_walker(void *priv, unsigned long start, unsigned long end,
1899     unsigned long flags);
1900
1901 static void fill_elf_header(struct elfhdr *, int, uint16_t, uint32_t);
1902 static void fill_note(struct memelfnote *, const char *, int,
1903     unsigned int, void *);
1904 static void fill_prstatus(struct elf_prstatus *, const TaskState *, int);
1905 static int fill_psinfo(struct elf_prpsinfo *, const TaskState *);
1906 static void fill_auxv_note(struct memelfnote *, const TaskState *);
1907 static void fill_elf_note_phdr(struct elf_phdr *, int, off_t);
1908 static size_t note_size(const struct memelfnote *);
1909 static void free_note_info(struct elf_note_info *);
1910 static int fill_note_info(struct elf_note_info *, long, const CPUState *);
1911 static void fill_thread_info(struct elf_note_info *, const CPUState *);
1912 static int core_dump_filename(const TaskState *, char *, size_t);
1913
1914 static int dump_write(int, const void *, size_t);
1915 static int write_note(struct memelfnote *, int);
1916 static int write_note_info(struct elf_note_info *, int);
1917
1918 #ifdef BSWAP_NEEDED
1919 static void bswap_prstatus(struct elf_prstatus *);
1920 static void bswap_psinfo(struct elf_prpsinfo *);
1921
1922 static void bswap_prstatus(struct elf_prstatus *prstatus)
1923 {
1924     prstatus->pr_info.si_signo = tswapl(prstatus->pr_info.si_signo);
1925     prstatus->pr_info.si_code = tswapl(prstatus->pr_info.si_code);
1926     prstatus->pr_info.si_errno = tswapl(prstatus->pr_info.si_errno);
1927     prstatus->pr_cursig = tswap16(prstatus->pr_cursig);
1928     prstatus->pr_sigpend = tswapl(prstatus->pr_sigpend);
1929     prstatus->pr_sighold = tswapl(prstatus->pr_sighold);
1930     prstatus->pr_pid = tswap32(prstatus->pr_pid);
1931     prstatus->pr_ppid = tswap32(prstatus->pr_ppid);
1932     prstatus->pr_pgrp = tswap32(prstatus->pr_pgrp);
1933     prstatus->pr_sid = tswap32(prstatus->pr_sid);
1934     /* cpu times are not filled, so we skip them */
1935     /* regs should be in correct format already */
1936     prstatus->pr_fpvalid = tswap32(prstatus->pr_fpvalid);
1937 }
1938
1939 static void bswap_psinfo(struct elf_prpsinfo *psinfo)
1940 {
1941     psinfo->pr_flag = tswapl(psinfo->pr_flag);
1942     psinfo->pr_uid = tswap16(psinfo->pr_uid);
1943     psinfo->pr_gid = tswap16(psinfo->pr_gid);
1944     psinfo->pr_pid = tswap32(psinfo->pr_pid);
1945     psinfo->pr_ppid = tswap32(psinfo->pr_ppid);
1946     psinfo->pr_pgrp = tswap32(psinfo->pr_pgrp);
1947     psinfo->pr_sid = tswap32(psinfo->pr_sid);
1948 }
1949 #endif /* BSWAP_NEEDED */
1950
1951 /*
1952  * Minimal support for linux memory regions.  These are needed
1953  * when we are finding out what memory exactly belongs to
1954  * emulated process.  No locks needed here, as long as
1955  * thread that received the signal is stopped.
1956  */
1957
1958 static struct mm_struct *vma_init(void)
1959 {
1960     struct mm_struct *mm;
1961
1962     if ((mm = qemu_malloc(sizeof (*mm))) == NULL)
1963         return (NULL);
1964
1965     mm->mm_count = 0;
1966     TAILQ_INIT(&mm->mm_mmap);
1967
1968     return (mm);
1969 }
1970
1971 static void vma_delete(struct mm_struct *mm)
1972 {
1973     struct vm_area_struct *vma;
1974
1975     while ((vma = vma_first(mm)) != NULL) {
1976         TAILQ_REMOVE(&mm->mm_mmap, vma, vma_link);
1977         qemu_free(vma);
1978     }
1979     qemu_free(mm);
1980 }
1981
1982 static int vma_add_mapping(struct mm_struct *mm, abi_ulong start,
1983     abi_ulong end, abi_ulong flags)
1984 {
1985     struct vm_area_struct *vma;
1986
1987     if ((vma = qemu_mallocz(sizeof (*vma))) == NULL)
1988         return (-1);
1989
1990     vma->vma_start = start;
1991     vma->vma_end = end;
1992     vma->vma_flags = flags;
1993
1994     TAILQ_INSERT_TAIL(&mm->mm_mmap, vma, vma_link);
1995     mm->mm_count++;
1996
1997     return (0);
1998 }
1999
2000 static struct vm_area_struct *vma_first(const struct mm_struct *mm)
2001 {
2002     return (TAILQ_FIRST(&mm->mm_mmap));
2003 }
2004
2005 static struct vm_area_struct *vma_next(struct vm_area_struct *vma)
2006 {
2007     return (TAILQ_NEXT(vma, vma_link));
2008 }
2009
2010 static int vma_get_mapping_count(const struct mm_struct *mm)
2011 {
2012     return (mm->mm_count);
2013 }
2014
2015 /*
2016  * Calculate file (dump) size of given memory region.
2017  */
2018 static abi_ulong vma_dump_size(const struct vm_area_struct *vma)
2019 {
2020     /* if we cannot even read the first page, skip it */
2021     if (!access_ok(VERIFY_READ, vma->vma_start, TARGET_PAGE_SIZE))
2022         return (0);
2023
2024     /*
2025      * Usually we don't dump executable pages as they contain
2026      * non-writable code that debugger can read directly from
2027      * target library etc.  However, thread stacks are marked
2028      * also executable so we read in first page of given region
2029      * and check whether it contains elf header.  If there is
2030      * no elf header, we dump it.
2031      */
2032     if (vma->vma_flags & PROT_EXEC) {
2033         char page[TARGET_PAGE_SIZE];
2034
2035         copy_from_user(page, vma->vma_start, sizeof (page));
2036         if ((page[EI_MAG0] == ELFMAG0) &&
2037             (page[EI_MAG1] == ELFMAG1) &&
2038             (page[EI_MAG2] == ELFMAG2) &&
2039             (page[EI_MAG3] == ELFMAG3)) {
2040             /*
2041              * Mappings are possibly from ELF binary.  Don't dump
2042              * them.
2043              */
2044             return (0);
2045         }
2046     }
2047
2048     return (vma->vma_end - vma->vma_start);
2049 }
2050
2051 static int vma_walker(void *priv, unsigned long start, unsigned long end,
2052     unsigned long flags)
2053 {
2054     struct mm_struct *mm = (struct mm_struct *)priv;
2055
2056     /*
2057      * Don't dump anything that qemu has reserved for internal use.
2058      */
2059     if (flags & PAGE_RESERVED)
2060         return (0);
2061
2062     vma_add_mapping(mm, start, end, flags);
2063     return (0);
2064 }
2065
2066 static void fill_note(struct memelfnote *note, const char *name, int type,
2067     unsigned int sz, void *data)
2068 {
2069     unsigned int namesz;
2070
2071     namesz = strlen(name) + 1;
2072     note->name = name;
2073     note->namesz = namesz;
2074     note->namesz_rounded = roundup(namesz, sizeof (int32_t));
2075     note->type = type;
2076     note->datasz = roundup(sz, sizeof (int32_t));;
2077     note->data = data;
2078
2079     /*
2080      * We calculate rounded up note size here as specified by
2081      * ELF document.
2082      */
2083     note->notesz = sizeof (struct elf_note) +
2084         note->namesz_rounded + note->datasz;
2085 }
2086
2087 static void fill_elf_header(struct elfhdr *elf, int segs, uint16_t machine,
2088     uint32_t flags)
2089 {
2090     (void) memset(elf, 0, sizeof(*elf));
2091
2092     (void) memcpy(elf->e_ident, ELFMAG, SELFMAG);
2093     elf->e_ident[EI_CLASS] = ELF_CLASS;
2094     elf->e_ident[EI_DATA] = ELF_DATA;
2095     elf->e_ident[EI_VERSION] = EV_CURRENT;
2096     elf->e_ident[EI_OSABI] = ELF_OSABI;
2097
2098     elf->e_type = ET_CORE;
2099     elf->e_machine = machine;
2100     elf->e_version = EV_CURRENT;
2101     elf->e_phoff = sizeof(struct elfhdr);
2102     elf->e_flags = flags;
2103     elf->e_ehsize = sizeof(struct elfhdr);
2104     elf->e_phentsize = sizeof(struct elf_phdr);
2105     elf->e_phnum = segs;
2106
2107 #ifdef BSWAP_NEEDED
2108     bswap_ehdr(elf);
2109 #endif
2110 }
2111
2112 static void fill_elf_note_phdr(struct elf_phdr *phdr, int sz, off_t offset)
2113 {
2114     phdr->p_type = PT_NOTE;
2115     phdr->p_offset = offset;
2116     phdr->p_vaddr = 0;
2117     phdr->p_paddr = 0;
2118     phdr->p_filesz = sz;
2119     phdr->p_memsz = 0;
2120     phdr->p_flags = 0;
2121     phdr->p_align = 0;
2122
2123 #ifdef BSWAP_NEEDED
2124     bswap_phdr(phdr);
2125 #endif
2126 }
2127
2128 static size_t note_size(const struct memelfnote *note)
2129 {
2130     return (note->notesz);
2131 }
2132
2133 static void fill_prstatus(struct elf_prstatus *prstatus,
2134     const TaskState *ts, int signr)
2135 {
2136     (void) memset(prstatus, 0, sizeof (*prstatus));
2137     prstatus->pr_info.si_signo = prstatus->pr_cursig = signr;
2138     prstatus->pr_pid = ts->ts_tid;
2139     prstatus->pr_ppid = getppid();
2140     prstatus->pr_pgrp = getpgrp();
2141     prstatus->pr_sid = getsid(0);
2142
2143 #ifdef BSWAP_NEEDED
2144     bswap_prstatus(prstatus);
2145 #endif
2146 }
2147
2148 static int fill_psinfo(struct elf_prpsinfo *psinfo, const TaskState *ts)
2149 {
2150     char *filename, *base_filename;
2151     unsigned int i, len;
2152
2153     (void) memset(psinfo, 0, sizeof (*psinfo));
2154
2155     len = ts->info->arg_end - ts->info->arg_start;
2156     if (len >= ELF_PRARGSZ)
2157         len = ELF_PRARGSZ - 1;
2158     if (copy_from_user(&psinfo->pr_psargs, ts->info->arg_start, len))
2159         return -EFAULT;
2160     for (i = 0; i < len; i++)
2161         if (psinfo->pr_psargs[i] == 0)
2162             psinfo->pr_psargs[i] = ' ';
2163     psinfo->pr_psargs[len] = 0;
2164
2165     psinfo->pr_pid = getpid();
2166     psinfo->pr_ppid = getppid();
2167     psinfo->pr_pgrp = getpgrp();
2168     psinfo->pr_sid = getsid(0);
2169     psinfo->pr_uid = getuid();
2170     psinfo->pr_gid = getgid();
2171
2172     filename = strdup(ts->bprm->filename);
2173     base_filename = strdup(basename(filename));
2174     (void) strncpy(psinfo->pr_fname, base_filename,
2175         sizeof(psinfo->pr_fname));
2176     free(base_filename);
2177     free(filename);
2178
2179 #ifdef BSWAP_NEEDED
2180     bswap_psinfo(psinfo);
2181 #endif
2182     return (0);
2183 }
2184
2185 static void fill_auxv_note(struct memelfnote *note, const TaskState *ts)
2186 {
2187     elf_addr_t auxv = (elf_addr_t)ts->info->saved_auxv;
2188     elf_addr_t orig_auxv = auxv;
2189     abi_ulong val;
2190     void *ptr;
2191     int i, len;
2192
2193     /*
2194      * Auxiliary vector is stored in target process stack.  It contains
2195      * {type, value} pairs that we need to dump into note.  This is not
2196      * strictly necessary but we do it here for sake of completeness.
2197      */
2198
2199     /* find out lenght of the vector, AT_NULL is terminator */
2200     i = len = 0;
2201     do {
2202         get_user_ual(val, auxv);
2203         i += 2;
2204         auxv += 2 * sizeof (elf_addr_t);
2205     } while (val != AT_NULL);
2206     len = i * sizeof (elf_addr_t);
2207
2208     /* read in whole auxv vector and copy it to memelfnote */
2209     ptr = lock_user(VERIFY_READ, orig_auxv, len, 0);
2210     if (ptr != NULL) {
2211         fill_note(note, "CORE", NT_AUXV, len, ptr);
2212         unlock_user(ptr, auxv, len);
2213     }
2214 }
2215
2216 /*
2217  * Constructs name of coredump file.  We have following convention
2218  * for the name:
2219  *     qemu_<basename-of-target-binary>_<date>-<time>_<pid>.core
2220  *
2221  * Returns 0 in case of success, -1 otherwise (errno is set).
2222  */
2223 static int core_dump_filename(const TaskState *ts, char *buf,
2224     size_t bufsize)
2225 {
2226     char timestamp[64];
2227     char *filename = NULL;
2228     char *base_filename = NULL;
2229     struct timeval tv;
2230     struct tm tm;
2231
2232     assert(bufsize >= PATH_MAX);
2233
2234     if (gettimeofday(&tv, NULL) < 0) {
2235         (void) fprintf(stderr, "unable to get current timestamp: %s",
2236             strerror(errno));
2237         return (-1);
2238     }
2239
2240     filename = strdup(ts->bprm->filename);
2241     base_filename = strdup(basename(filename));
2242     (void) strftime(timestamp, sizeof (timestamp), "%Y%m%d-%H%M%S",
2243         localtime_r(&tv.tv_sec, &tm));
2244     (void) snprintf(buf, bufsize, "qemu_%s_%s_%d.core",
2245         base_filename, timestamp, (int)getpid());
2246     free(base_filename);
2247     free(filename);
2248
2249     return (0);
2250 }
2251
2252 static int dump_write(int fd, const void *ptr, size_t size)
2253 {
2254     const char *bufp = (const char *)ptr;
2255     ssize_t bytes_written, bytes_left;
2256     struct rlimit dumpsize;
2257     off_t pos;
2258
2259     bytes_written = 0;
2260     getrlimit(RLIMIT_CORE, &dumpsize);
2261     if ((pos = lseek(fd, 0, SEEK_CUR))==-1) {
2262         if (errno == ESPIPE) { /* not a seekable stream */
2263             bytes_left = size;
2264         } else {
2265             return pos;
2266         }
2267     } else {
2268         if (dumpsize.rlim_cur <= pos) {
2269             return -1;
2270         } else if (dumpsize.rlim_cur == RLIM_INFINITY) {
2271             bytes_left = size;
2272         } else {
2273             size_t limit_left=dumpsize.rlim_cur - pos;
2274             bytes_left = limit_left >= size ? size : limit_left ;
2275         }
2276     }
2277
2278     /*
2279      * In normal conditions, single write(2) should do but
2280      * in case of socket etc. this mechanism is more portable.
2281      */
2282     do {
2283         bytes_written = write(fd, bufp, bytes_left);
2284         if (bytes_written < 0) {
2285             if (errno == EINTR)
2286                 continue;
2287             return (-1);
2288         } else if (bytes_written == 0) { /* eof */
2289             return (-1);
2290         }
2291         bufp += bytes_written;
2292         bytes_left -= bytes_written;
2293     } while (bytes_left > 0);
2294
2295     return (0);
2296 }
2297
2298 static int write_note(struct memelfnote *men, int fd)
2299 {
2300     struct elf_note en;
2301
2302     en.n_namesz = men->namesz;
2303     en.n_type = men->type;
2304     en.n_descsz = men->datasz;
2305
2306 #ifdef BSWAP_NEEDED
2307     bswap_note(&en);
2308 #endif
2309
2310     if (dump_write(fd, &en, sizeof(en)) != 0)
2311         return (-1);
2312     if (dump_write(fd, men->name, men->namesz_rounded) != 0)
2313         return (-1);
2314     if (dump_write(fd, men->data, men->datasz) != 0)
2315         return (-1);
2316
2317     return (0);
2318 }
2319
2320 static void fill_thread_info(struct elf_note_info *info, const CPUState *env)
2321 {
2322     TaskState *ts = (TaskState *)env->opaque;
2323     struct elf_thread_status *ets;
2324
2325     ets = qemu_mallocz(sizeof (*ets));
2326     ets->num_notes = 1; /* only prstatus is dumped */
2327     fill_prstatus(&ets->prstatus, ts, 0);
2328     elf_core_copy_regs(&ets->prstatus.pr_reg, env);
2329     fill_note(&ets->notes[0], "CORE", NT_PRSTATUS, sizeof (ets->prstatus),
2330         &ets->prstatus);
2331
2332     TAILQ_INSERT_TAIL(&info->thread_list, ets, ets_link);
2333
2334     info->notes_size += note_size(&ets->notes[0]);
2335 }
2336
2337 static int fill_note_info(struct elf_note_info *info,
2338     long signr, const CPUState *env)
2339 {
2340 #define NUMNOTES 3
2341     CPUState *cpu = NULL;
2342     TaskState *ts = (TaskState *)env->opaque;
2343     int i;
2344
2345     (void) memset(info, 0, sizeof (*info));
2346
2347     TAILQ_INIT(&info->thread_list);
2348
2349     info->notes = qemu_mallocz(NUMNOTES * sizeof (struct memelfnote));
2350     if (info->notes == NULL)
2351         return (-ENOMEM);
2352     info->prstatus = qemu_mallocz(sizeof (*info->prstatus));
2353     if (info->prstatus == NULL)
2354         return (-ENOMEM);
2355     info->psinfo = qemu_mallocz(sizeof (*info->psinfo));
2356     if (info->prstatus == NULL)
2357         return (-ENOMEM);
2358
2359     /*
2360      * First fill in status (and registers) of current thread
2361      * including process info & aux vector.
2362      */
2363     fill_prstatus(info->prstatus, ts, signr);
2364     elf_core_copy_regs(&info->prstatus->pr_reg, env);
2365     fill_note(&info->notes[0], "CORE", NT_PRSTATUS,
2366         sizeof (*info->prstatus), info->prstatus);
2367     fill_psinfo(info->psinfo, ts);
2368     fill_note(&info->notes[1], "CORE", NT_PRPSINFO,
2369         sizeof (*info->psinfo), info->psinfo);
2370     fill_auxv_note(&info->notes[2], ts);
2371     info->numnote = 3;
2372
2373     info->notes_size = 0;
2374     for (i = 0; i < info->numnote; i++)
2375         info->notes_size += note_size(&info->notes[i]);
2376
2377     /* read and fill status of all threads */
2378     cpu_list_lock();
2379     for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
2380         if (cpu == thread_env)
2381             continue;
2382         fill_thread_info(info, cpu);
2383     }
2384     cpu_list_unlock();
2385
2386     return (0);
2387 }
2388
2389 static void free_note_info(struct elf_note_info *info)
2390 {
2391     struct elf_thread_status *ets;
2392
2393     while (!TAILQ_EMPTY(&info->thread_list)) {
2394         ets = TAILQ_FIRST(&info->thread_list);
2395         TAILQ_REMOVE(&info->thread_list, ets, ets_link);
2396         qemu_free(ets);
2397     }
2398
2399     qemu_free(info->prstatus);
2400     qemu_free(info->psinfo);
2401     qemu_free(info->notes);
2402 }
2403
2404 static int write_note_info(struct elf_note_info *info, int fd)
2405 {
2406     struct elf_thread_status *ets;
2407     int i, error = 0;
2408
2409     /* write prstatus, psinfo and auxv for current thread */
2410     for (i = 0; i < info->numnote; i++)
2411         if ((error = write_note(&info->notes[i], fd)) != 0)
2412             return (error);
2413
2414     /* write prstatus for each thread */
2415     for (ets = info->thread_list.tqh_first; ets != NULL;
2416         ets = ets->ets_link.tqe_next) {
2417         if ((error = write_note(&ets->notes[0], fd)) != 0)
2418             return (error);
2419     }
2420
2421     return (0);
2422 }
2423
2424 /*
2425  * Write out ELF coredump.
2426  *
2427  * See documentation of ELF object file format in:
2428  * http://www.caldera.com/developers/devspecs/gabi41.pdf
2429  *
2430  * Coredump format in linux is following:
2431  *
2432  * 0   +----------------------+         \
2433  *     | ELF header           | ET_CORE  |
2434  *     +----------------------+          |
2435  *     | ELF program headers  |          |--- headers
2436  *     | - NOTE section       |          |
2437  *     | - PT_LOAD sections   |          |
2438  *     +----------------------+         /
2439  *     | NOTEs:               |
2440  *     | - NT_PRSTATUS        |
2441  *     | - NT_PRSINFO         |
2442  *     | - NT_AUXV            |
2443  *     +----------------------+ <-- aligned to target page
2444  *     | Process memory dump  |
2445  *     :                      :
2446  *     .                      .
2447  *     :                      :
2448  *     |                      |
2449  *     +----------------------+
2450  *
2451  * NT_PRSTATUS -> struct elf_prstatus (per thread)
2452  * NT_PRSINFO  -> struct elf_prpsinfo
2453  * NT_AUXV is array of { type, value } pairs (see fill_auxv_note()).
2454  *
2455  * Format follows System V format as close as possible.  Current
2456  * version limitations are as follows:
2457  *     - no floating point registers are dumped
2458  *
2459  * Function returns 0 in case of success, negative errno otherwise.
2460  *
2461  * TODO: make this work also during runtime: it should be
2462  * possible to force coredump from running process and then
2463  * continue processing.  For example qemu could set up SIGUSR2
2464  * handler (provided that target process haven't registered
2465  * handler for that) that does the dump when signal is received.
2466  */
2467 static int elf_core_dump(int signr, const CPUState *env)
2468 {
2469     const TaskState *ts = (const TaskState *)env->opaque;
2470     struct vm_area_struct *vma = NULL;
2471     char corefile[PATH_MAX];
2472     struct elf_note_info info;
2473     struct elfhdr elf;
2474     struct elf_phdr phdr;
2475     struct rlimit dumpsize;
2476     struct mm_struct *mm = NULL;
2477     off_t offset = 0, data_offset = 0;
2478     int segs = 0;
2479     int fd = -1;
2480
2481     errno = 0;
2482     getrlimit(RLIMIT_CORE, &dumpsize);
2483     if (dumpsize.rlim_cur == 0)
2484        return 0;
2485
2486     if (core_dump_filename(ts, corefile, sizeof (corefile)) < 0)
2487         return (-errno);
2488
2489     if ((fd = open(corefile, O_WRONLY | O_CREAT,
2490         S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0)
2491         return (-errno);
2492
2493     /*
2494      * Walk through target process memory mappings and
2495      * set up structure containing this information.  After
2496      * this point vma_xxx functions can be used.
2497      */
2498     if ((mm = vma_init()) == NULL)
2499         goto out;
2500
2501     walk_memory_regions(mm, vma_walker);
2502     segs = vma_get_mapping_count(mm);
2503
2504     /*
2505      * Construct valid coredump ELF header.  We also
2506      * add one more segment for notes.
2507      */
2508     fill_elf_header(&elf, segs + 1, ELF_MACHINE, 0);
2509     if (dump_write(fd, &elf, sizeof (elf)) != 0)
2510         goto out;
2511
2512     /* fill in in-memory version of notes */
2513     if (fill_note_info(&info, signr, env) < 0)
2514         goto out;
2515
2516     offset += sizeof (elf);                             /* elf header */
2517     offset += (segs + 1) * sizeof (struct elf_phdr);    /* program headers */
2518
2519     /* write out notes program header */
2520     fill_elf_note_phdr(&phdr, info.notes_size, offset);
2521
2522     offset += info.notes_size;
2523     if (dump_write(fd, &phdr, sizeof (phdr)) != 0)
2524         goto out;
2525
2526     /*
2527      * ELF specification wants data to start at page boundary so
2528      * we align it here.
2529      */
2530     offset = roundup(offset, ELF_EXEC_PAGESIZE);
2531
2532     /*
2533      * Write program headers for memory regions mapped in
2534      * the target process.
2535      */
2536     for (vma = vma_first(mm); vma != NULL; vma = vma_next(vma)) {
2537         (void) memset(&phdr, 0, sizeof (phdr));
2538
2539         phdr.p_type = PT_LOAD;
2540         phdr.p_offset = offset;
2541         phdr.p_vaddr = vma->vma_start;
2542         phdr.p_paddr = 0;
2543         phdr.p_filesz = vma_dump_size(vma);
2544         offset += phdr.p_filesz;
2545         phdr.p_memsz = vma->vma_end - vma->vma_start;
2546         phdr.p_flags = vma->vma_flags & PROT_READ ? PF_R : 0;
2547         if (vma->vma_flags & PROT_WRITE)
2548             phdr.p_flags |= PF_W;
2549         if (vma->vma_flags & PROT_EXEC)
2550             phdr.p_flags |= PF_X;
2551         phdr.p_align = ELF_EXEC_PAGESIZE;
2552
2553         dump_write(fd, &phdr, sizeof (phdr));
2554     }
2555
2556     /*
2557      * Next we write notes just after program headers.  No
2558      * alignment needed here.
2559      */
2560     if (write_note_info(&info, fd) < 0)
2561         goto out;
2562
2563     /* align data to page boundary */
2564     data_offset = lseek(fd, 0, SEEK_CUR);
2565     data_offset = TARGET_PAGE_ALIGN(data_offset);
2566     if (lseek(fd, data_offset, SEEK_SET) != data_offset)
2567         goto out;
2568
2569     /*
2570      * Finally we can dump process memory into corefile as well.
2571      */
2572     for (vma = vma_first(mm); vma != NULL; vma = vma_next(vma)) {
2573         abi_ulong addr;
2574         abi_ulong end;
2575
2576         end = vma->vma_start + vma_dump_size(vma);
2577
2578         for (addr = vma->vma_start; addr < end;
2579             addr += TARGET_PAGE_SIZE) {
2580             char page[TARGET_PAGE_SIZE];
2581             int error;
2582
2583             /*
2584              *  Read in page from target process memory and
2585              *  write it to coredump file.
2586              */
2587             error = copy_from_user(page, addr, sizeof (page));
2588             if (error != 0) {
2589                 (void) fprintf(stderr, "unable to dump " TARGET_FMT_lx "\n",
2590                     addr);
2591                 errno = -error;
2592                 goto out;
2593             }
2594             if (dump_write(fd, page, TARGET_PAGE_SIZE) < 0)
2595                 goto out;
2596         }
2597     }
2598
2599 out:
2600     free_note_info(&info);
2601     if (mm != NULL)
2602         vma_delete(mm);
2603     (void) close(fd);
2604
2605     if (errno != 0)
2606         return (-errno);
2607     return (0);
2608 }
2609
2610 #endif /* USE_ELF_CORE_DUMP */
2611
2612 static int load_aout_interp(void * exptr, int interp_fd)
2613 {
2614     printf("a.out interpreter not yet supported\n");
2615     return(0);
2616 }
2617
2618 void do_init_thread(struct target_pt_regs *regs, struct image_info *infop)
2619 {
2620     init_thread(regs, infop);
2621 }