fixed refresh logic (initial patch by Igor Kovalenko)
[qemu] / linux-user / elfload.c
1 /* This is the Linux kernel elf-loading code, ported into user space */
2
3 #include <stdio.h>
4 #include <sys/types.h>
5 #include <fcntl.h>
6 #include <errno.h>
7 #include <unistd.h>
8 #include <sys/mman.h>
9 #include <stdlib.h>
10 #include <string.h>
11
12 #include "qemu.h"
13 #include "disas.h"
14
15 /* this flag is uneffective under linux too, should be deleted */
16 #ifndef MAP_DENYWRITE
17 #define MAP_DENYWRITE 0
18 #endif
19
20 /* should probably go in elf.h */
21 #ifndef ELIBBAD
22 #define ELIBBAD 80
23 #endif
24
25 #ifdef TARGET_I386
26
27 #define ELF_PLATFORM get_elf_platform()
28
29 static const char *get_elf_platform(void)
30 {
31     static char elf_platform[] = "i386";
32     int family = (global_env->cpuid_version >> 8) & 0xff;
33     if (family > 6)
34         family = 6;
35     if (family >= 3)
36         elf_platform[1] = '0' + family;
37     return elf_platform;
38 }
39
40 #define ELF_HWCAP get_elf_hwcap()
41
42 static uint32_t get_elf_hwcap(void)
43 {
44   return global_env->cpuid_features;
45 }
46
47 #define ELF_START_MMAP 0x80000000
48
49 /*
50  * This is used to ensure we don't load something for the wrong architecture.
51  */
52 #define elf_check_arch(x) ( ((x) == EM_386) || ((x) == EM_486) )
53
54 /*
55  * These are used to set parameters in the core dumps.
56  */
57 #define ELF_CLASS       ELFCLASS32
58 #define ELF_DATA        ELFDATA2LSB
59 #define ELF_ARCH        EM_386
60
61 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
62 {
63     regs->esp = infop->start_stack;
64     regs->eip = infop->entry;
65
66     /* SVR4/i386 ABI (pages 3-31, 3-32) says that when the program
67        starts %edx contains a pointer to a function which might be
68        registered using `atexit'.  This provides a mean for the
69        dynamic linker to call DT_FINI functions for shared libraries
70        that have been loaded before the code runs.
71
72        A value of 0 tells we have no such handler.  */
73     regs->edx = 0;
74 }
75
76 #define USE_ELF_CORE_DUMP
77 #define ELF_EXEC_PAGESIZE       4096
78
79 #endif
80
81 #ifdef TARGET_ARM
82
83 #define ELF_START_MMAP 0x80000000
84
85 #define elf_check_arch(x) ( (x) == EM_ARM )
86
87 #define ELF_CLASS       ELFCLASS32
88 #ifdef TARGET_WORDS_BIGENDIAN
89 #define ELF_DATA        ELFDATA2MSB
90 #else
91 #define ELF_DATA        ELFDATA2LSB
92 #endif
93 #define ELF_ARCH        EM_ARM
94
95 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
96 {
97     target_long stack = infop->start_stack;
98     memset(regs, 0, sizeof(*regs));
99     regs->ARM_cpsr = 0x10;
100     if (infop->entry & 1)
101       regs->ARM_cpsr |= CPSR_T;
102     regs->ARM_pc = infop->entry & 0xfffffffe;
103     regs->ARM_sp = infop->start_stack;
104     regs->ARM_r2 = tgetl(stack + 8); /* envp */
105     regs->ARM_r1 = tgetl(stack + 4); /* envp */
106     /* XXX: it seems that r0 is zeroed after ! */
107     regs->ARM_r0 = 0;
108     /* For uClinux PIC binaries.  */
109     regs->ARM_r10 = infop->start_data;
110 }
111
112 #define USE_ELF_CORE_DUMP
113 #define ELF_EXEC_PAGESIZE       4096
114
115 enum
116 {
117   ARM_HWCAP_ARM_SWP       = 1 << 0,
118   ARM_HWCAP_ARM_HALF      = 1 << 1,
119   ARM_HWCAP_ARM_THUMB     = 1 << 2,
120   ARM_HWCAP_ARM_26BIT     = 1 << 3,
121   ARM_HWCAP_ARM_FAST_MULT = 1 << 4,
122   ARM_HWCAP_ARM_FPA       = 1 << 5,
123   ARM_HWCAP_ARM_VFP       = 1 << 6,
124   ARM_HWCAP_ARM_EDSP      = 1 << 7,
125 };
126
127 #define ELF_HWCAP (ARM_HWCAP_ARM_SWP | ARM_HWCAP_ARM_HALF              \
128                     | ARM_HWCAP_ARM_THUMB | ARM_HWCAP_ARM_FAST_MULT     \
129                     | ARM_HWCAP_ARM_FPA | ARM_HWCAP_ARM_VFP)
130
131 #endif
132
133 #ifdef TARGET_SPARC
134 #ifdef TARGET_SPARC64
135
136 #define ELF_START_MMAP 0x80000000
137
138 #define elf_check_arch(x) ( (x) == EM_SPARCV9 )
139
140 #define ELF_CLASS   ELFCLASS64
141 #define ELF_DATA    ELFDATA2MSB
142 #define ELF_ARCH    EM_SPARCV9
143
144 #define STACK_BIAS              2047
145
146 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
147 {
148     regs->tstate = 0;
149     regs->pc = infop->entry;
150     regs->npc = regs->pc + 4;
151     regs->y = 0;
152     regs->u_regs[14] = infop->start_stack - 16 * 8 - STACK_BIAS;
153 }
154
155 #else
156 #define ELF_START_MMAP 0x80000000
157
158 #define elf_check_arch(x) ( (x) == EM_SPARC )
159
160 #define ELF_CLASS   ELFCLASS32
161 #define ELF_DATA    ELFDATA2MSB
162 #define ELF_ARCH    EM_SPARC
163
164 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
165 {
166     regs->psr = 0;
167     regs->pc = infop->entry;
168     regs->npc = regs->pc + 4;
169     regs->y = 0;
170     regs->u_regs[14] = infop->start_stack - 16 * 4;
171 }
172
173 #endif
174 #endif
175
176 #ifdef TARGET_PPC
177
178 #define ELF_START_MMAP 0x80000000
179
180 #define elf_check_arch(x) ( (x) == EM_PPC )
181
182 #define ELF_CLASS       ELFCLASS32
183 #ifdef TARGET_WORDS_BIGENDIAN
184 #define ELF_DATA        ELFDATA2MSB
185 #else
186 #define ELF_DATA        ELFDATA2LSB
187 #endif
188 #define ELF_ARCH        EM_PPC
189
190 /*
191  * We need to put in some extra aux table entries to tell glibc what
192  * the cache block size is, so it can use the dcbz instruction safely.
193  */
194 #define AT_DCACHEBSIZE          19
195 #define AT_ICACHEBSIZE          20
196 #define AT_UCACHEBSIZE          21
197 /* A special ignored type value for PPC, for glibc compatibility.  */
198 #define AT_IGNOREPPC            22
199 /*
200  * The requirements here are:
201  * - keep the final alignment of sp (sp & 0xf)
202  * - make sure the 32-bit value at the first 16 byte aligned position of
203  *   AUXV is greater than 16 for glibc compatibility.
204  *   AT_IGNOREPPC is used for that.
205  * - for compatibility with glibc ARCH_DLINFO must always be defined on PPC,
206  *   even if DLINFO_ARCH_ITEMS goes to zero or is undefined.
207  */
208 #define DLINFO_ARCH_ITEMS       5
209 #define ARCH_DLINFO                                                     \
210 do {                                                                    \
211         NEW_AUX_ENT(AT_DCACHEBSIZE, 0x20);                              \
212         NEW_AUX_ENT(AT_ICACHEBSIZE, 0x20);                              \
213         NEW_AUX_ENT(AT_UCACHEBSIZE, 0);                                 \
214         /*                                                              \
215          * Now handle glibc compatibility.                              \
216          */                                                             \
217         NEW_AUX_ENT(AT_IGNOREPPC, AT_IGNOREPPC);                        \
218         NEW_AUX_ENT(AT_IGNOREPPC, AT_IGNOREPPC);                        \
219  } while (0)
220
221 static inline void init_thread(struct target_pt_regs *_regs, struct image_info *infop)
222 {
223     target_ulong pos = infop->start_stack;
224     target_ulong tmp;
225
226     _regs->msr = 1 << MSR_PR; /* Set user mode */
227     _regs->gpr[1] = infop->start_stack;
228     _regs->nip = infop->entry;
229     /* Note that isn't exactly what regular kernel does
230      * but this is what the ABI wants and is needed to allow
231      * execution of PPC BSD programs.
232      */
233     _regs->gpr[3] = tgetl(pos);
234     pos += sizeof(target_ulong);
235     _regs->gpr[4] = pos;
236     for (tmp = 1; tmp != 0; pos += sizeof(target_ulong))
237         tmp = ldl(pos);
238     _regs->gpr[5] = pos;
239 }
240
241 #define USE_ELF_CORE_DUMP
242 #define ELF_EXEC_PAGESIZE       4096
243
244 #endif
245
246 #ifdef TARGET_MIPS
247
248 #define ELF_START_MMAP 0x80000000
249
250 #define elf_check_arch(x) ( (x) == EM_MIPS )
251
252 #define ELF_CLASS   ELFCLASS32
253 #ifdef TARGET_WORDS_BIGENDIAN
254 #define ELF_DATA        ELFDATA2MSB
255 #else
256 #define ELF_DATA        ELFDATA2LSB
257 #endif
258 #define ELF_ARCH    EM_MIPS
259
260 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
261 {
262     regs->cp0_status = CP0St_UM;
263     regs->cp0_epc = infop->entry;
264     regs->regs[29] = infop->start_stack;
265 }
266
267 #endif /* TARGET_MIPS */
268
269 #ifdef TARGET_SH4
270
271 #define ELF_START_MMAP 0x80000000
272
273 #define elf_check_arch(x) ( (x) == EM_SH )
274
275 #define ELF_CLASS ELFCLASS32
276 #define ELF_DATA  ELFDATA2LSB
277 #define ELF_ARCH  EM_SH
278
279 static inline void init_thread(struct target_pt_regs *regs, struct image_info *infop)
280 {
281   /* Check other registers XXXXX */
282   regs->pc = infop->entry;
283   regs->regs[15] = infop->start_stack - 16 * 4;
284 }
285
286 #define USE_ELF_CORE_DUMP
287 #define ELF_EXEC_PAGESIZE        4096
288
289 #endif
290
291 #ifndef ELF_PLATFORM
292 #define ELF_PLATFORM (NULL)
293 #endif
294
295 #ifndef ELF_HWCAP
296 #define ELF_HWCAP 0
297 #endif
298
299 #include "elf.h"
300
301 struct exec
302 {
303   unsigned int a_info;   /* Use macros N_MAGIC, etc for access */
304   unsigned int a_text;   /* length of text, in bytes */
305   unsigned int a_data;   /* length of data, in bytes */
306   unsigned int a_bss;    /* length of uninitialized data area, in bytes */
307   unsigned int a_syms;   /* length of symbol table data in file, in bytes */
308   unsigned int a_entry;  /* start address */
309   unsigned int a_trsize; /* length of relocation info for text, in bytes */
310   unsigned int a_drsize; /* length of relocation info for data, in bytes */
311 };
312
313
314 #define N_MAGIC(exec) ((exec).a_info & 0xffff)
315 #define OMAGIC 0407
316 #define NMAGIC 0410
317 #define ZMAGIC 0413
318 #define QMAGIC 0314
319
320 /* max code+data+bss space allocated to elf interpreter */
321 #define INTERP_MAP_SIZE (32 * 1024 * 1024)
322
323 /* max code+data+bss+brk space allocated to ET_DYN executables */
324 #define ET_DYN_MAP_SIZE (128 * 1024 * 1024)
325
326 /* from personality.h */
327
328 /* Flags for bug emulation. These occupy the top three bytes. */
329 #define STICKY_TIMEOUTS         0x4000000
330 #define WHOLE_SECONDS           0x2000000
331
332 /* Personality types. These go in the low byte. Avoid using the top bit,
333  * it will conflict with error returns.
334  */
335 #define PER_MASK                (0x00ff)
336 #define PER_LINUX               (0x0000)
337 #define PER_SVR4                (0x0001 | STICKY_TIMEOUTS)
338 #define PER_SVR3                (0x0002 | STICKY_TIMEOUTS)
339 #define PER_SCOSVR3             (0x0003 | STICKY_TIMEOUTS | WHOLE_SECONDS)
340 #define PER_WYSEV386            (0x0004 | STICKY_TIMEOUTS)
341 #define PER_ISCR4               (0x0005 | STICKY_TIMEOUTS)
342 #define PER_BSD                 (0x0006)
343 #define PER_XENIX               (0x0007 | STICKY_TIMEOUTS)
344
345 /* Necessary parameters */
346 #define TARGET_ELF_EXEC_PAGESIZE TARGET_PAGE_SIZE
347 #define TARGET_ELF_PAGESTART(_v) ((_v) & ~(unsigned long)(TARGET_ELF_EXEC_PAGESIZE-1))
348 #define TARGET_ELF_PAGEOFFSET(_v) ((_v) & (TARGET_ELF_EXEC_PAGESIZE-1))
349
350 #define INTERPRETER_NONE 0
351 #define INTERPRETER_AOUT 1
352 #define INTERPRETER_ELF 2
353
354 #define DLINFO_ITEMS 12
355
356 static inline void memcpy_fromfs(void * to, const void * from, unsigned long n)
357 {
358         memcpy(to, from, n);
359 }
360
361 extern unsigned long x86_stack_size;
362
363 static int load_aout_interp(void * exptr, int interp_fd);
364
365 #ifdef BSWAP_NEEDED
366 static void bswap_ehdr(struct elfhdr *ehdr)
367 {
368     bswap16s(&ehdr->e_type);                    /* Object file type */
369     bswap16s(&ehdr->e_machine);         /* Architecture */
370     bswap32s(&ehdr->e_version);         /* Object file version */
371     bswaptls(&ehdr->e_entry);           /* Entry point virtual address */
372     bswaptls(&ehdr->e_phoff);           /* Program header table file offset */
373     bswaptls(&ehdr->e_shoff);           /* Section header table file offset */
374     bswap32s(&ehdr->e_flags);           /* Processor-specific flags */
375     bswap16s(&ehdr->e_ehsize);          /* ELF header size in bytes */
376     bswap16s(&ehdr->e_phentsize);               /* Program header table entry size */
377     bswap16s(&ehdr->e_phnum);           /* Program header table entry count */
378     bswap16s(&ehdr->e_shentsize);               /* Section header table entry size */
379     bswap16s(&ehdr->e_shnum);           /* Section header table entry count */
380     bswap16s(&ehdr->e_shstrndx);                /* Section header string table index */
381 }
382
383 static void bswap_phdr(struct elf_phdr *phdr)
384 {
385     bswap32s(&phdr->p_type);                    /* Segment type */
386     bswaptls(&phdr->p_offset);          /* Segment file offset */
387     bswaptls(&phdr->p_vaddr);           /* Segment virtual address */
388     bswaptls(&phdr->p_paddr);           /* Segment physical address */
389     bswaptls(&phdr->p_filesz);          /* Segment size in file */
390     bswaptls(&phdr->p_memsz);           /* Segment size in memory */
391     bswap32s(&phdr->p_flags);           /* Segment flags */
392     bswaptls(&phdr->p_align);           /* Segment alignment */
393 }
394
395 static void bswap_shdr(struct elf_shdr *shdr)
396 {
397     bswap32s(&shdr->sh_name);
398     bswap32s(&shdr->sh_type);
399     bswaptls(&shdr->sh_flags);
400     bswaptls(&shdr->sh_addr);
401     bswaptls(&shdr->sh_offset);
402     bswaptls(&shdr->sh_size);
403     bswap32s(&shdr->sh_link);
404     bswap32s(&shdr->sh_info);
405     bswaptls(&shdr->sh_addralign);
406     bswaptls(&shdr->sh_entsize);
407 }
408
409 static void bswap_sym(Elf32_Sym *sym)
410 {
411     bswap32s(&sym->st_name);
412     bswap32s(&sym->st_value);
413     bswap32s(&sym->st_size);
414     bswap16s(&sym->st_shndx);
415 }
416 #endif
417
418 /*
419  * 'copy_elf_strings()' copies argument/envelope strings from user
420  * memory to free pages in kernel mem. These are in a format ready
421  * to be put directly into the top of new user memory.
422  *
423  */
424 static unsigned long copy_elf_strings(int argc,char ** argv, void **page,
425                                       unsigned long p)
426 {
427     char *tmp, *tmp1, *pag = NULL;
428     int len, offset = 0;
429
430     if (!p) {
431         return 0;       /* bullet-proofing */
432     }
433     while (argc-- > 0) {
434         tmp = argv[argc];
435         if (!tmp) {
436             fprintf(stderr, "VFS: argc is wrong");
437             exit(-1);
438         }
439         tmp1 = tmp;
440         while (*tmp++);
441         len = tmp - tmp1;
442         if (p < len) {  /* this shouldn't happen - 128kB */
443                 return 0;
444         }
445         while (len) {
446             --p; --tmp; --len;
447             if (--offset < 0) {
448                 offset = p % TARGET_PAGE_SIZE;
449                 pag = (char *)page[p/TARGET_PAGE_SIZE];
450                 if (!pag) {
451                     pag = (char *)malloc(TARGET_PAGE_SIZE);
452                     page[p/TARGET_PAGE_SIZE] = pag;
453                     if (!pag)
454                         return 0;
455                 }
456             }
457             if (len == 0 || offset == 0) {
458                 *(pag + offset) = *tmp;
459             }
460             else {
461               int bytes_to_copy = (len > offset) ? offset : len;
462               tmp -= bytes_to_copy;
463               p -= bytes_to_copy;
464               offset -= bytes_to_copy;
465               len -= bytes_to_copy;
466               memcpy_fromfs(pag + offset, tmp, bytes_to_copy + 1);
467             }
468         }
469     }
470     return p;
471 }
472
473 unsigned long setup_arg_pages(target_ulong p, struct linux_binprm * bprm,
474                                               struct image_info * info)
475 {
476     target_ulong stack_base, size, error;
477     int i;
478
479     /* Create enough stack to hold everything.  If we don't use
480      * it for args, we'll use it for something else...
481      */
482     size = x86_stack_size;
483     if (size < MAX_ARG_PAGES*TARGET_PAGE_SIZE)
484         size = MAX_ARG_PAGES*TARGET_PAGE_SIZE;
485     error = target_mmap(0, 
486                         size + qemu_host_page_size,
487                         PROT_READ | PROT_WRITE,
488                         MAP_PRIVATE | MAP_ANONYMOUS,
489                         -1, 0);
490     if (error == -1) {
491         perror("stk mmap");
492         exit(-1);
493     }
494     /* we reserve one extra page at the top of the stack as guard */
495     target_mprotect(error + size, qemu_host_page_size, PROT_NONE);
496
497     stack_base = error + size - MAX_ARG_PAGES*TARGET_PAGE_SIZE;
498     p += stack_base;
499
500     for (i = 0 ; i < MAX_ARG_PAGES ; i++) {
501         if (bprm->page[i]) {
502             info->rss++;
503
504             memcpy_to_target(stack_base, bprm->page[i], TARGET_PAGE_SIZE);
505             free(bprm->page[i]);
506         }
507         stack_base += TARGET_PAGE_SIZE;
508     }
509     return p;
510 }
511
512 static void set_brk(unsigned long start, unsigned long end)
513 {
514         /* page-align the start and end addresses... */
515         start = HOST_PAGE_ALIGN(start);
516         end = HOST_PAGE_ALIGN(end);
517         if (end <= start)
518                 return;
519         if(target_mmap(start, end - start,
520                        PROT_READ | PROT_WRITE | PROT_EXEC,
521                        MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) == -1) {
522             perror("cannot mmap brk");
523             exit(-1);
524         }
525 }
526
527
528 /* We need to explicitly zero any fractional pages after the data
529    section (i.e. bss).  This would contain the junk from the file that
530    should not be in memory. */
531 static void padzero(unsigned long elf_bss)
532 {
533         unsigned long nbyte;
534
535         /* XXX: this is really a hack : if the real host page size is
536            smaller than the target page size, some pages after the end
537            of the file may not be mapped. A better fix would be to
538            patch target_mmap(), but it is more complicated as the file
539            size must be known */
540         if (qemu_real_host_page_size < qemu_host_page_size) {
541             unsigned long end_addr, end_addr1;
542             end_addr1 = (elf_bss + qemu_real_host_page_size - 1) & 
543                 ~(qemu_real_host_page_size - 1);
544             end_addr = HOST_PAGE_ALIGN(elf_bss);
545             if (end_addr1 < end_addr) {
546                 mmap((void *)end_addr1, end_addr - end_addr1,
547                      PROT_READ|PROT_WRITE|PROT_EXEC,
548                      MAP_FIXED|MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
549             }
550         }
551
552         nbyte = elf_bss & (qemu_host_page_size-1);
553         if (nbyte) {
554             nbyte = qemu_host_page_size - nbyte;
555             do {
556                 tput8(elf_bss, 0);
557                 elf_bss++;
558             } while (--nbyte);
559         }
560 }
561
562
563 static unsigned long create_elf_tables(target_ulong p, int argc, int envc,
564                                        struct elfhdr * exec,
565                                        unsigned long load_addr,
566                                        unsigned long load_bias,
567                                        unsigned long interp_load_addr, int ibcs,
568                                        struct image_info *info)
569 {
570         target_ulong sp;
571         int size;
572         target_ulong u_platform;
573         const char *k_platform;
574         const int n = sizeof(target_ulong);
575
576         sp = p;
577         u_platform = 0;
578         k_platform = ELF_PLATFORM;
579         if (k_platform) {
580             size_t len = strlen(k_platform) + 1;
581             sp -= (len + n - 1) & ~(n - 1);
582             u_platform = sp;
583             memcpy_to_target(sp, k_platform, len);
584         }
585         /*
586          * Force 16 byte _final_ alignment here for generality.
587          */
588         sp = sp &~ (target_ulong)15;
589         size = (DLINFO_ITEMS + 1) * 2;
590         if (k_platform)
591           size += 2;
592 #ifdef DLINFO_ARCH_ITEMS
593         size += DLINFO_ARCH_ITEMS * 2;
594 #endif
595         size += envc + argc + 2;
596         size += (!ibcs ? 3 : 1);        /* argc itself */
597         size *= n;
598         if (size & 15)
599             sp -= 16 - (size & 15);
600         
601 #define NEW_AUX_ENT(id, val) do { \
602             sp -= n; tputl(sp, val); \
603             sp -= n; tputl(sp, id); \
604           } while(0)
605         NEW_AUX_ENT (AT_NULL, 0);
606
607         /* There must be exactly DLINFO_ITEMS entries here.  */
608         NEW_AUX_ENT(AT_PHDR, (target_ulong)(load_addr + exec->e_phoff));
609         NEW_AUX_ENT(AT_PHENT, (target_ulong)(sizeof (struct elf_phdr)));
610         NEW_AUX_ENT(AT_PHNUM, (target_ulong)(exec->e_phnum));
611         NEW_AUX_ENT(AT_PAGESZ, (target_ulong)(TARGET_PAGE_SIZE));
612         NEW_AUX_ENT(AT_BASE, (target_ulong)(interp_load_addr));
613         NEW_AUX_ENT(AT_FLAGS, (target_ulong)0);
614         NEW_AUX_ENT(AT_ENTRY, load_bias + exec->e_entry);
615         NEW_AUX_ENT(AT_UID, (target_ulong) getuid());
616         NEW_AUX_ENT(AT_EUID, (target_ulong) geteuid());
617         NEW_AUX_ENT(AT_GID, (target_ulong) getgid());
618         NEW_AUX_ENT(AT_EGID, (target_ulong) getegid());
619         NEW_AUX_ENT(AT_HWCAP, (target_ulong) ELF_HWCAP);
620         if (k_platform)
621             NEW_AUX_ENT(AT_PLATFORM, u_platform);
622 #ifdef ARCH_DLINFO
623         /* 
624          * ARCH_DLINFO must come last so platform specific code can enforce
625          * special alignment requirements on the AUXV if necessary (eg. PPC).
626          */
627         ARCH_DLINFO;
628 #endif
629 #undef NEW_AUX_ENT
630
631         sp = loader_build_argptr(envc, argc, sp, p, !ibcs);
632         return sp;
633 }
634
635
636 static unsigned long load_elf_interp(struct elfhdr * interp_elf_ex,
637                                      int interpreter_fd,
638                                      unsigned long *interp_load_addr)
639 {
640         struct elf_phdr *elf_phdata  =  NULL;
641         struct elf_phdr *eppnt;
642         unsigned long load_addr = 0;
643         int load_addr_set = 0;
644         int retval;
645         unsigned long last_bss, elf_bss;
646         unsigned long error;
647         int i;
648         
649         elf_bss = 0;
650         last_bss = 0;
651         error = 0;
652
653 #ifdef BSWAP_NEEDED
654         bswap_ehdr(interp_elf_ex);
655 #endif
656         /* First of all, some simple consistency checks */
657         if ((interp_elf_ex->e_type != ET_EXEC && 
658              interp_elf_ex->e_type != ET_DYN) || 
659            !elf_check_arch(interp_elf_ex->e_machine)) {
660                 return ~0UL;
661         }
662         
663
664         /* Now read in all of the header information */
665         
666         if (sizeof(struct elf_phdr) * interp_elf_ex->e_phnum > TARGET_PAGE_SIZE)
667             return ~0UL;
668         
669         elf_phdata =  (struct elf_phdr *) 
670                 malloc(sizeof(struct elf_phdr) * interp_elf_ex->e_phnum);
671
672         if (!elf_phdata)
673           return ~0UL;
674         
675         /*
676          * If the size of this structure has changed, then punt, since
677          * we will be doing the wrong thing.
678          */
679         if (interp_elf_ex->e_phentsize != sizeof(struct elf_phdr)) {
680             free(elf_phdata);
681             return ~0UL;
682         }
683
684         retval = lseek(interpreter_fd, interp_elf_ex->e_phoff, SEEK_SET);
685         if(retval >= 0) {
686             retval = read(interpreter_fd,
687                            (char *) elf_phdata,
688                            sizeof(struct elf_phdr) * interp_elf_ex->e_phnum);
689         }
690         if (retval < 0) {
691                 perror("load_elf_interp");
692                 exit(-1);
693                 free (elf_phdata);
694                 return retval;
695         }
696 #ifdef BSWAP_NEEDED
697         eppnt = elf_phdata;
698         for (i=0; i<interp_elf_ex->e_phnum; i++, eppnt++) {
699             bswap_phdr(eppnt);
700         }
701 #endif
702
703         if (interp_elf_ex->e_type == ET_DYN) {
704             /* in order to avoid harcoding the interpreter load
705                address in qemu, we allocate a big enough memory zone */
706             error = target_mmap(0, INTERP_MAP_SIZE,
707                                 PROT_NONE, MAP_PRIVATE | MAP_ANON, 
708                                 -1, 0);
709             if (error == -1) {
710                 perror("mmap");
711                 exit(-1);
712             }
713             load_addr = error;
714             load_addr_set = 1;
715         }
716
717         eppnt = elf_phdata;
718         for(i=0; i<interp_elf_ex->e_phnum; i++, eppnt++)
719           if (eppnt->p_type == PT_LOAD) {
720             int elf_type = MAP_PRIVATE | MAP_DENYWRITE;
721             int elf_prot = 0;
722             unsigned long vaddr = 0;
723             unsigned long k;
724
725             if (eppnt->p_flags & PF_R) elf_prot =  PROT_READ;
726             if (eppnt->p_flags & PF_W) elf_prot |= PROT_WRITE;
727             if (eppnt->p_flags & PF_X) elf_prot |= PROT_EXEC;
728             if (interp_elf_ex->e_type == ET_EXEC || load_addr_set) {
729                 elf_type |= MAP_FIXED;
730                 vaddr = eppnt->p_vaddr;
731             }
732             error = target_mmap(load_addr+TARGET_ELF_PAGESTART(vaddr),
733                  eppnt->p_filesz + TARGET_ELF_PAGEOFFSET(eppnt->p_vaddr),
734                  elf_prot,
735                  elf_type,
736                  interpreter_fd,
737                  eppnt->p_offset - TARGET_ELF_PAGEOFFSET(eppnt->p_vaddr));
738             
739             if (error == -1) {
740               /* Real error */
741               close(interpreter_fd);
742               free(elf_phdata);
743               return ~0UL;
744             }
745
746             if (!load_addr_set && interp_elf_ex->e_type == ET_DYN) {
747               load_addr = error;
748               load_addr_set = 1;
749             }
750
751             /*
752              * Find the end of the file  mapping for this phdr, and keep
753              * track of the largest address we see for this.
754              */
755             k = load_addr + eppnt->p_vaddr + eppnt->p_filesz;
756             if (k > elf_bss) elf_bss = k;
757
758             /*
759              * Do the same thing for the memory mapping - between
760              * elf_bss and last_bss is the bss section.
761              */
762             k = load_addr + eppnt->p_memsz + eppnt->p_vaddr;
763             if (k > last_bss) last_bss = k;
764           }
765         
766         /* Now use mmap to map the library into memory. */
767
768         close(interpreter_fd);
769
770         /*
771          * Now fill out the bss section.  First pad the last page up
772          * to the page boundary, and then perform a mmap to make sure
773          * that there are zeromapped pages up to and including the last
774          * bss page.
775          */
776         padzero(elf_bss);
777         elf_bss = TARGET_ELF_PAGESTART(elf_bss + qemu_host_page_size - 1); /* What we have mapped so far */
778
779         /* Map the last of the bss segment */
780         if (last_bss > elf_bss) {
781             target_mmap(elf_bss, last_bss-elf_bss,
782                         PROT_READ|PROT_WRITE|PROT_EXEC,
783                         MAP_FIXED|MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
784         }
785         free(elf_phdata);
786
787         *interp_load_addr = load_addr;
788         return ((unsigned long) interp_elf_ex->e_entry) + load_addr;
789 }
790
791 /* Best attempt to load symbols from this ELF object. */
792 static void load_symbols(struct elfhdr *hdr, int fd)
793 {
794     unsigned int i;
795     struct elf_shdr sechdr, symtab, strtab;
796     char *strings;
797     struct syminfo *s;
798
799     lseek(fd, hdr->e_shoff, SEEK_SET);
800     for (i = 0; i < hdr->e_shnum; i++) {
801         if (read(fd, &sechdr, sizeof(sechdr)) != sizeof(sechdr))
802             return;
803 #ifdef BSWAP_NEEDED
804         bswap_shdr(&sechdr);
805 #endif
806         if (sechdr.sh_type == SHT_SYMTAB) {
807             symtab = sechdr;
808             lseek(fd, hdr->e_shoff
809                   + sizeof(sechdr) * sechdr.sh_link, SEEK_SET);
810             if (read(fd, &strtab, sizeof(strtab))
811                 != sizeof(strtab))
812                 return;
813 #ifdef BSWAP_NEEDED
814             bswap_shdr(&strtab);
815 #endif
816             goto found;
817         }
818     }
819     return; /* Shouldn't happen... */
820
821  found:
822     /* Now know where the strtab and symtab are.  Snarf them. */
823     s = malloc(sizeof(*s));
824     s->disas_symtab = malloc(symtab.sh_size);
825     s->disas_strtab = strings = malloc(strtab.sh_size);
826     if (!s->disas_symtab || !s->disas_strtab)
827         return;
828         
829     lseek(fd, symtab.sh_offset, SEEK_SET);
830     if (read(fd, s->disas_symtab, symtab.sh_size) != symtab.sh_size)
831         return;
832
833 #ifdef BSWAP_NEEDED
834     for (i = 0; i < symtab.sh_size / sizeof(struct elf_sym); i++)
835         bswap_sym(s->disas_symtab + sizeof(struct elf_sym)*i);
836 #endif
837
838     lseek(fd, strtab.sh_offset, SEEK_SET);
839     if (read(fd, strings, strtab.sh_size) != strtab.sh_size)
840         return;
841     s->disas_num_syms = symtab.sh_size / sizeof(struct elf_sym);
842     s->next = syminfos;
843     syminfos = s;
844 }
845
846 int load_elf_binary(struct linux_binprm * bprm, struct target_pt_regs * regs,
847                     struct image_info * info)
848 {
849     struct elfhdr elf_ex;
850     struct elfhdr interp_elf_ex;
851     struct exec interp_ex;
852     int interpreter_fd = -1; /* avoid warning */
853     unsigned long load_addr, load_bias;
854     int load_addr_set = 0;
855     unsigned int interpreter_type = INTERPRETER_NONE;
856     unsigned char ibcs2_interpreter;
857     int i;
858     unsigned long mapped_addr;
859     struct elf_phdr * elf_ppnt;
860     struct elf_phdr *elf_phdata;
861     unsigned long elf_bss, k, elf_brk;
862     int retval;
863     char * elf_interpreter;
864     unsigned long elf_entry, interp_load_addr = 0;
865     int status;
866     unsigned long start_code, end_code, end_data;
867     unsigned long elf_stack;
868     char passed_fileno[6];
869
870     ibcs2_interpreter = 0;
871     status = 0;
872     load_addr = 0;
873     load_bias = 0;
874     elf_ex = *((struct elfhdr *) bprm->buf);          /* exec-header */
875 #ifdef BSWAP_NEEDED
876     bswap_ehdr(&elf_ex);
877 #endif
878
879     /* First of all, some simple consistency checks */
880     if ((elf_ex.e_type != ET_EXEC && elf_ex.e_type != ET_DYN) ||
881                                 (! elf_check_arch(elf_ex.e_machine))) {
882             return -ENOEXEC;
883     }
884
885     bprm->p = copy_elf_strings(1, &bprm->filename, bprm->page, bprm->p);
886     bprm->p = copy_elf_strings(bprm->envc,bprm->envp,bprm->page,bprm->p);
887     bprm->p = copy_elf_strings(bprm->argc,bprm->argv,bprm->page,bprm->p);
888     if (!bprm->p) {
889         retval = -E2BIG;
890     }
891
892     /* Now read in all of the header information */
893     elf_phdata = (struct elf_phdr *)malloc(elf_ex.e_phentsize*elf_ex.e_phnum);
894     if (elf_phdata == NULL) {
895         return -ENOMEM;
896     }
897
898     retval = lseek(bprm->fd, elf_ex.e_phoff, SEEK_SET);
899     if(retval > 0) {
900         retval = read(bprm->fd, (char *) elf_phdata, 
901                                 elf_ex.e_phentsize * elf_ex.e_phnum);
902     }
903
904     if (retval < 0) {
905         perror("load_elf_binary");
906         exit(-1);
907         free (elf_phdata);
908         return -errno;
909     }
910
911 #ifdef BSWAP_NEEDED
912     elf_ppnt = elf_phdata;
913     for (i=0; i<elf_ex.e_phnum; i++, elf_ppnt++) {
914         bswap_phdr(elf_ppnt);
915     }
916 #endif
917     elf_ppnt = elf_phdata;
918
919     elf_bss = 0;
920     elf_brk = 0;
921
922
923     elf_stack = ~0UL;
924     elf_interpreter = NULL;
925     start_code = ~0UL;
926     end_code = 0;
927     end_data = 0;
928
929     for(i=0;i < elf_ex.e_phnum; i++) {
930         if (elf_ppnt->p_type == PT_INTERP) {
931             if ( elf_interpreter != NULL )
932             {
933                 free (elf_phdata);
934                 free(elf_interpreter);
935                 close(bprm->fd);
936                 return -EINVAL;
937             }
938
939             /* This is the program interpreter used for
940              * shared libraries - for now assume that this
941              * is an a.out format binary
942              */
943
944             elf_interpreter = (char *)malloc(elf_ppnt->p_filesz);
945
946             if (elf_interpreter == NULL) {
947                 free (elf_phdata);
948                 close(bprm->fd);
949                 return -ENOMEM;
950             }
951
952             retval = lseek(bprm->fd, elf_ppnt->p_offset, SEEK_SET);
953             if(retval >= 0) {
954                 retval = read(bprm->fd, elf_interpreter, elf_ppnt->p_filesz);
955             }
956             if(retval < 0) {
957                 perror("load_elf_binary2");
958                 exit(-1);
959             }   
960
961             /* If the program interpreter is one of these two,
962                then assume an iBCS2 image. Otherwise assume
963                a native linux image. */
964
965             /* JRP - Need to add X86 lib dir stuff here... */
966
967             if (strcmp(elf_interpreter,"/usr/lib/libc.so.1") == 0 ||
968                 strcmp(elf_interpreter,"/usr/lib/ld.so.1") == 0) {
969               ibcs2_interpreter = 1;
970             }
971
972 #if 0
973             printf("Using ELF interpreter %s\n", elf_interpreter);
974 #endif
975             if (retval >= 0) {
976                 retval = open(path(elf_interpreter), O_RDONLY);
977                 if(retval >= 0) {
978                     interpreter_fd = retval;
979                 }
980                 else {
981                     perror(elf_interpreter);
982                     exit(-1);
983                     /* retval = -errno; */
984                 }
985             }
986
987             if (retval >= 0) {
988                 retval = lseek(interpreter_fd, 0, SEEK_SET);
989                 if(retval >= 0) {
990                     retval = read(interpreter_fd,bprm->buf,128);
991                 }
992             }
993             if (retval >= 0) {
994                 interp_ex = *((struct exec *) bprm->buf); /* aout exec-header */
995                 interp_elf_ex=*((struct elfhdr *) bprm->buf); /* elf exec-header */
996             }
997             if (retval < 0) {
998                 perror("load_elf_binary3");
999                 exit(-1);
1000                 free (elf_phdata);
1001                 free(elf_interpreter);
1002                 close(bprm->fd);
1003                 return retval;
1004             }
1005         }
1006         elf_ppnt++;
1007     }
1008
1009     /* Some simple consistency checks for the interpreter */
1010     if (elf_interpreter){
1011         interpreter_type = INTERPRETER_ELF | INTERPRETER_AOUT;
1012
1013         /* Now figure out which format our binary is */
1014         if ((N_MAGIC(interp_ex) != OMAGIC) && (N_MAGIC(interp_ex) != ZMAGIC) &&
1015                 (N_MAGIC(interp_ex) != QMAGIC)) {
1016           interpreter_type = INTERPRETER_ELF;
1017         }
1018
1019         if (interp_elf_ex.e_ident[0] != 0x7f ||
1020                 strncmp(&interp_elf_ex.e_ident[1], "ELF",3) != 0) {
1021             interpreter_type &= ~INTERPRETER_ELF;
1022         }
1023
1024         if (!interpreter_type) {
1025             free(elf_interpreter);
1026             free(elf_phdata);
1027             close(bprm->fd);
1028             return -ELIBBAD;
1029         }
1030     }
1031
1032     /* OK, we are done with that, now set up the arg stuff,
1033        and then start this sucker up */
1034
1035     {
1036         char * passed_p;
1037
1038         if (interpreter_type == INTERPRETER_AOUT) {
1039             snprintf(passed_fileno, sizeof(passed_fileno), "%d", bprm->fd);
1040             passed_p = passed_fileno;
1041
1042             if (elf_interpreter) {
1043                 bprm->p = copy_elf_strings(1,&passed_p,bprm->page,bprm->p);
1044                 bprm->argc++;
1045             }
1046         }
1047         if (!bprm->p) {
1048             if (elf_interpreter) {
1049                 free(elf_interpreter);
1050             }
1051             free (elf_phdata);
1052             close(bprm->fd);
1053             return -E2BIG;
1054         }
1055     }
1056
1057     /* OK, This is the point of no return */
1058     info->end_data = 0;
1059     info->end_code = 0;
1060     info->start_mmap = (unsigned long)ELF_START_MMAP;
1061     info->mmap = 0;
1062     elf_entry = (unsigned long) elf_ex.e_entry;
1063
1064     /* Do this so that we can load the interpreter, if need be.  We will
1065        change some of these later */
1066     info->rss = 0;
1067     bprm->p = setup_arg_pages(bprm->p, bprm, info);
1068     info->start_stack = bprm->p;
1069
1070     /* Now we do a little grungy work by mmaping the ELF image into
1071      * the correct location in memory.  At this point, we assume that
1072      * the image should be loaded at fixed address, not at a variable
1073      * address.
1074      */
1075
1076     for(i = 0, elf_ppnt = elf_phdata; i < elf_ex.e_phnum; i++, elf_ppnt++) {
1077         int elf_prot = 0;
1078         int elf_flags = 0;
1079         unsigned long error;
1080         
1081         if (elf_ppnt->p_type != PT_LOAD)
1082             continue;
1083         
1084         if (elf_ppnt->p_flags & PF_R) elf_prot |= PROT_READ;
1085         if (elf_ppnt->p_flags & PF_W) elf_prot |= PROT_WRITE;
1086         if (elf_ppnt->p_flags & PF_X) elf_prot |= PROT_EXEC;
1087         elf_flags = MAP_PRIVATE | MAP_DENYWRITE;
1088         if (elf_ex.e_type == ET_EXEC || load_addr_set) {
1089             elf_flags |= MAP_FIXED;
1090         } else if (elf_ex.e_type == ET_DYN) {
1091             /* Try and get dynamic programs out of the way of the default mmap
1092                base, as well as whatever program they might try to exec.  This
1093                is because the brk will follow the loader, and is not movable.  */
1094             /* NOTE: for qemu, we do a big mmap to get enough space
1095                without harcoding any address */
1096             error = target_mmap(0, ET_DYN_MAP_SIZE,
1097                                 PROT_NONE, MAP_PRIVATE | MAP_ANON, 
1098                                 -1, 0);
1099             if (error == -1) {
1100                 perror("mmap");
1101                 exit(-1);
1102             }
1103             load_bias = TARGET_ELF_PAGESTART(error - elf_ppnt->p_vaddr);
1104         }
1105         
1106         error = target_mmap(TARGET_ELF_PAGESTART(load_bias + elf_ppnt->p_vaddr),
1107                             (elf_ppnt->p_filesz +
1108                              TARGET_ELF_PAGEOFFSET(elf_ppnt->p_vaddr)),
1109                             elf_prot,
1110                             (MAP_FIXED | MAP_PRIVATE | MAP_DENYWRITE),
1111                             bprm->fd,
1112                             (elf_ppnt->p_offset - 
1113                              TARGET_ELF_PAGEOFFSET(elf_ppnt->p_vaddr)));
1114         if (error == -1) {
1115             perror("mmap");
1116             exit(-1);
1117         }
1118
1119 #ifdef LOW_ELF_STACK
1120         if (TARGET_ELF_PAGESTART(elf_ppnt->p_vaddr) < elf_stack)
1121             elf_stack = TARGET_ELF_PAGESTART(elf_ppnt->p_vaddr);
1122 #endif
1123         
1124         if (!load_addr_set) {
1125             load_addr_set = 1;
1126             load_addr = elf_ppnt->p_vaddr - elf_ppnt->p_offset;
1127             if (elf_ex.e_type == ET_DYN) {
1128                 load_bias += error -
1129                     TARGET_ELF_PAGESTART(load_bias + elf_ppnt->p_vaddr);
1130                 load_addr += load_bias;
1131             }
1132         }
1133         k = elf_ppnt->p_vaddr;
1134         if (k < start_code) 
1135             start_code = k;
1136         k = elf_ppnt->p_vaddr + elf_ppnt->p_filesz;
1137         if (k > elf_bss) 
1138             elf_bss = k;
1139         if ((elf_ppnt->p_flags & PF_X) && end_code <  k)
1140             end_code = k;
1141         if (end_data < k) 
1142             end_data = k;
1143         k = elf_ppnt->p_vaddr + elf_ppnt->p_memsz;
1144         if (k > elf_brk) elf_brk = k;
1145     }
1146
1147     elf_entry += load_bias;
1148     elf_bss += load_bias;
1149     elf_brk += load_bias;
1150     start_code += load_bias;
1151     end_code += load_bias;
1152     //    start_data += load_bias;
1153     end_data += load_bias;
1154
1155     if (elf_interpreter) {
1156         if (interpreter_type & 1) {
1157             elf_entry = load_aout_interp(&interp_ex, interpreter_fd);
1158         }
1159         else if (interpreter_type & 2) {
1160             elf_entry = load_elf_interp(&interp_elf_ex, interpreter_fd,
1161                                             &interp_load_addr);
1162         }
1163
1164         close(interpreter_fd);
1165         free(elf_interpreter);
1166
1167         if (elf_entry == ~0UL) {
1168             printf("Unable to load interpreter\n");
1169             free(elf_phdata);
1170             exit(-1);
1171             return 0;
1172         }
1173     }
1174
1175     free(elf_phdata);
1176
1177     if (loglevel)
1178         load_symbols(&elf_ex, bprm->fd);
1179
1180     if (interpreter_type != INTERPRETER_AOUT) close(bprm->fd);
1181     info->personality = (ibcs2_interpreter ? PER_SVR4 : PER_LINUX);
1182
1183 #ifdef LOW_ELF_STACK
1184     info->start_stack = bprm->p = elf_stack - 4;
1185 #endif
1186     bprm->p = create_elf_tables(bprm->p,
1187                     bprm->argc,
1188                     bprm->envc,
1189                     &elf_ex,
1190                     load_addr, load_bias,
1191                     interp_load_addr,
1192                     (interpreter_type == INTERPRETER_AOUT ? 0 : 1),
1193                     info);
1194     info->start_brk = info->brk = elf_brk;
1195     info->end_code = end_code;
1196     info->start_code = start_code;
1197     info->start_data = end_code;
1198     info->end_data = end_data;
1199     info->start_stack = bprm->p;
1200
1201     /* Calling set_brk effectively mmaps the pages that we need for the bss and break
1202        sections */
1203     set_brk(elf_bss, elf_brk);
1204
1205     padzero(elf_bss);
1206
1207 #if 0
1208     printf("(start_brk) %x\n" , info->start_brk);
1209     printf("(end_code) %x\n" , info->end_code);
1210     printf("(start_code) %x\n" , info->start_code);
1211     printf("(end_data) %x\n" , info->end_data);
1212     printf("(start_stack) %x\n" , info->start_stack);
1213     printf("(brk) %x\n" , info->brk);
1214 #endif
1215
1216     if ( info->personality == PER_SVR4 )
1217     {
1218             /* Why this, you ask???  Well SVr4 maps page 0 as read-only,
1219                and some applications "depend" upon this behavior.
1220                Since we do not have the power to recompile these, we
1221                emulate the SVr4 behavior.  Sigh.  */
1222             mapped_addr = target_mmap(0, qemu_host_page_size, PROT_READ | PROT_EXEC,
1223                                       MAP_FIXED | MAP_PRIVATE, -1, 0);
1224     }
1225
1226     info->entry = elf_entry;
1227
1228     return 0;
1229 }
1230
1231 static int load_aout_interp(void * exptr, int interp_fd)
1232 {
1233     printf("a.out interpreter not yet supported\n");
1234     return(0);
1235 }
1236
1237 void do_init_thread(struct target_pt_regs *regs, struct image_info *infop)
1238 {
1239     init_thread(regs, infop);
1240 }