Increase PE reserve area size to 512Mb.
[wine] / loader / preloader.c
1 /*
2  * Preloader for ld.so
3  *
4  * Copyright (C) 1995,96,97,98,99,2000,2001,2002 Free Software Foundation, Inc.
5  * Copyright (C) 2004 Mike McCormack for CodeWeavers
6  * Copyright (C) 2004 Alexandre Julliard
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 /*
24  * Design notes
25  *
26  * The goal of this program is to be a workaround for exec-shield, as used
27  *  by the Linux kernel distributed with Fedora Core and other distros.
28  *
29  * To do this, we implement our own shared object loader that reserves memory
30  * that is important to Wine, and then loads the main binary and its ELF
31  * interpreter.
32  *
33  * We will try to set up the stack and memory area so that the program that
34  * loads after us (eg. the wine binary) never knows we were here, except that
35  * areas of memory it needs are already magically reserved.
36  *
37  * The following memory areas are important to Wine:
38  *  0x00000000 - 0x00110000  the DOS area
39  *  0x80000000 - 0x81000000  the shared heap
40  *  ???        - ???         the PE binary load address (usually starting at 0x00400000)
41  *
42  * If this program is used as the shared object loader, the only difference
43  * that the loaded programs should see is that this loader will be mapped
44  * into memory when it starts.
45  */
46
47 /*
48  * References (things I consulted to understand how ELF loading works):
49  *
50  * glibc 2.3.2   elf/dl-load.c
51  *  http://www.gnu.org/directory/glibc.html
52  *
53  * Linux 2.6.4   fs/binfmt_elf.c
54  *  ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.4.tar.bz2
55  *
56  * Userland exec, by <grugq@hcunix.net>
57  *  http://cert.uni-stuttgart.de/archive/bugtraq/2004/01/msg00002.html
58  *
59  * The ELF specification:
60  *  http://www.linuxbase.org/spec/booksets/LSB-Embedded/LSB-Embedded/book387.html
61  */
62
63 #include "config.h"
64 #include "wine/port.h"
65
66 #include <stdarg.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <sys/types.h>
71 #include <sys/stat.h>
72 #include <fcntl.h>
73 #ifdef HAVE_SYS_MMAN_H
74 # include <sys/mman.h>
75 #endif
76 #ifdef HAVE_SYS_SYSCALL_H
77 # include <sys/syscall.h>
78 #endif
79 #ifdef HAVE_UNISTD_H
80 # include <unistd.h>
81 #endif
82 #ifdef HAVE_ELF_H
83 # include <elf.h>
84 #endif
85 #ifdef HAVE_LINK_H
86 # include <link.h>
87 #endif
88 #ifdef HAVE_SYS_LINK_H
89 # include <sys/link.h>
90 #endif
91
92 #include "main.h"
93
94 /* ELF definitions */
95 #define ELF_PREFERRED_ADDRESS(loader, maplength, mapstartpref) (mapstartpref)
96 #define ELF_FIXED_ADDRESS(loader, mapstart) ((void) 0)
97
98 #define MAP_BASE_ADDR(l)     0
99
100 #ifndef MAP_COPY
101 #define MAP_COPY MAP_PRIVATE
102 #endif
103 #ifndef MAP_NORESERVE
104 #define MAP_NORESERVE 0
105 #endif
106
107 static struct wine_preload_info preload_info[] =
108 {
109     { (void *)0x00000000, 0x00110000 },  /* DOS area */
110     { (void *)0x80000000, 0x01000000 },  /* shared heap */
111     { (void *)0x00110000, 0x1fef0000 },  /* PE exe range (may be set with WINEPRELOADRESERVE), defaults to 512mb */
112     { 0, 0 }                             /* end of list */
113 };
114
115 /* debugging */
116 #undef DUMP_SEGMENTS
117 #undef DUMP_AUX_INFO
118 #undef DUMP_SYMS
119
120 /* older systems may not define these */
121 #ifndef PT_TLS
122 #define PT_TLS 7
123 #endif
124
125 #ifndef AT_SYSINFO
126 #define AT_SYSINFO 32
127 #endif
128 #ifndef AT_SYSINFO_EHDR
129 #define AT_SYSINFO_EHDR 33
130 #endif
131
132 static unsigned int page_size, page_mask;
133 static char *preloader_start, *preloader_end;
134
135 struct wld_link_map {
136     ElfW(Addr) l_addr;
137     ElfW(Dyn) *l_ld;
138     ElfW(Phdr)*l_phdr;
139     ElfW(Addr) l_entry;
140     ElfW(Half) l_ldnum;
141     ElfW(Half) l_phnum;
142     ElfW(Addr) l_map_start, l_map_end;
143     ElfW(Addr) l_interp;
144 };
145
146
147 /*
148  * The _start function is the entry and exit point of this program
149  *
150  *  It calls wld_start, passing a pointer to the args it receives
151  *  then jumps to the address wld_start returns.
152  */
153 void _start();
154 extern char _end[];
155 __ASM_GLOBAL_FUNC(_start,
156                   "\tmovl %esp,%eax\n"
157                   "\tleal -128(%esp),%esp\n"  /* allocate some space for extra aux values */
158                   "\tpushl %eax\n"            /* orig stack pointer */
159                   "\tpushl %esp\n"            /* ptr to orig stack pointer */
160                   "\tcall wld_start\n"
161                   "\tpopl %ecx\n"             /* remove ptr to stack pointer */
162                   "\tpopl %esp\n"             /* new stack pointer */
163                   "\tpush %eax\n"             /* ELF interpreter entry point */
164                   "\txor %eax,%eax\n"
165                   "\txor %ecx,%ecx\n"
166                   "\txor %edx,%edx\n"
167                   "\tret\n")
168
169 /* wrappers for Linux system calls */
170
171 #define SYSCALL_RET(ret) (((ret) < 0 && (ret) > -4096) ? -1 : (ret))
172
173 static inline __attribute__((noreturn)) void wld_exit( int code )
174 {
175     for (;;)  /* avoid warning */
176         __asm__ __volatile__( "pushl %%ebx; movl %1,%%ebx; int $0x80; popl %%ebx"
177                               : : "a" (SYS_exit), "r" (code) );
178 }
179
180 static inline int wld_open( const char *name, int flags )
181 {
182     int ret;
183     __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
184                           : "=a" (ret) : "0" (SYS_open), "r" (name), "c" (flags) );
185     return SYSCALL_RET(ret);
186 }
187
188 static inline int wld_close( int fd )
189 {
190     int ret;
191     __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
192                           : "=a" (ret) : "0" (SYS_close), "r" (fd) );
193     return SYSCALL_RET(ret);
194 }
195
196 static inline ssize_t wld_read( int fd, void *buffer, size_t len )
197 {
198     int ret;
199     __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
200                           : "=a" (ret)
201                           : "0" (SYS_read), "r" (fd), "c" (buffer), "d" (len)
202                           : "memory" );
203     return SYSCALL_RET(ret);
204 }
205
206 static inline ssize_t wld_write( int fd, const void *buffer, size_t len )
207 {
208     int ret;
209     __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
210                           : "=a" (ret) : "0" (SYS_write), "r" (fd), "c" (buffer), "d" (len) );
211     return SYSCALL_RET(ret);
212 }
213
214 static inline int wld_mprotect( const void *addr, size_t len, int prot )
215 {
216     int ret;
217     __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
218                           : "=a" (ret) : "0" (SYS_mprotect), "r" (addr), "c" (len), "d" (prot) );
219     return SYSCALL_RET(ret);
220 }
221
222 static void *wld_mmap( void *start, size_t len, int prot, int flags, int fd, off_t offset )
223 {
224     int ret;
225
226     struct
227     {
228         void        *addr;
229         unsigned int length;
230         unsigned int prot;
231         unsigned int flags;
232         unsigned int fd;
233         unsigned int offset;
234     } args;
235
236     args.addr   = start;
237     args.length = len;
238     args.prot   = prot;
239     args.flags  = flags;
240     args.fd     = fd;
241     args.offset = offset;
242     __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
243                           : "=a" (ret) : "0" (SYS_mmap), "q" (&args) : "memory" );
244     return (void *)SYSCALL_RET(ret);
245 }
246
247 static inline uid_t wld_getuid(void)
248 {
249     uid_t ret;
250     __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_getuid) );
251     return ret;
252 }
253
254 static inline uid_t wld_geteuid(void)
255 {
256     uid_t ret;
257     __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_geteuid) );
258     return ret;
259 }
260
261 static inline gid_t wld_getgid(void)
262 {
263     gid_t ret;
264     __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_getgid) );
265     return ret;
266 }
267
268 static inline gid_t wld_getegid(void)
269 {
270     gid_t ret;
271     __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_getegid) );
272     return ret;
273 }
274
275
276 /* replacement for libc functions */
277
278 static int wld_strcmp( const char *str1, const char *str2 )
279 {
280     while (*str1 && (*str1 == *str2)) { str1++; str2++; }
281     return *str1 - *str2;
282 }
283
284 static int wld_strncmp( const char *str1, const char *str2, size_t len )
285 {
286     if (len <= 0) return 0;
287     while ((--len > 0) && *str1 && (*str1 == *str2)) { str1++; str2++; }
288     return *str1 - *str2;
289 }
290
291 static inline void *wld_memset( void *dest, int val, size_t len )
292 {
293     char *dst = dest;
294     while (len--) *dst++ = val;
295     return dest;
296 }
297
298 /*
299  * wld_printf - just the basics
300  *
301  *  %x prints a hex number
302  *  %s prints a string
303  */
304 static int wld_vsprintf(char *buffer, const char *fmt, va_list args )
305 {
306     static const char hex_chars[16] = "0123456789abcdef";
307     const char *p = fmt;
308     char *str = buffer;
309
310     while( *p )
311     {
312         if( *p == '%' )
313         {
314             p++;
315             if( *p == 'x' )
316             {
317                 int i;
318                 unsigned int x = va_arg( args, unsigned int );
319                 for(i=7; i>=0; i--)
320                     *str++ = hex_chars[(x>>(i*4))&0xf];
321             }
322             else if( *p == 's' )
323             {
324                 char *s = va_arg( args, char * );
325                 while(*s)
326                     *str++ = *s++;
327             }
328             else if( *p == 0 )
329                 break;
330             p++;
331         }
332         *str++ = *p++;
333     }
334     *str = 0;
335     return str - buffer;
336 }
337
338 static void wld_printf(const char *fmt, ... )
339 {
340     va_list args;
341     char buffer[256];
342     int len;
343
344     va_start( args, fmt );
345     len = wld_vsprintf(buffer, fmt, args );
346     va_end( args );
347     wld_write(2, buffer, len);
348 }
349
350 static __attribute__((noreturn)) void fatal_error(const char *fmt, ... )
351 {
352     va_list args;
353     char buffer[256];
354     int len;
355
356     va_start( args, fmt );
357     len = wld_vsprintf(buffer, fmt, args );
358     va_end( args );
359     wld_write(2, buffer, len);
360     wld_exit(1);
361 }
362
363 #ifdef DUMP_AUX_INFO
364 /*
365  *  Dump interesting bits of the ELF auxv_t structure that is passed
366  *   as the 4th parameter to the _start function
367  */
368 static void dump_auxiliary( ElfW(auxv_t) *av )
369 {
370 #define NAME(at) { at, #at }
371     static const struct { int val; const char *name; } names[] =
372     {
373         NAME(AT_BASE),
374         NAME(AT_CLKTCK),
375         NAME(AT_EGID),
376         NAME(AT_ENTRY),
377         NAME(AT_EUID),
378         NAME(AT_FLAGS),
379         NAME(AT_GID),
380         NAME(AT_HWCAP),
381         NAME(AT_PAGESZ),
382         NAME(AT_PHDR),
383         NAME(AT_PHENT),
384         NAME(AT_PHNUM),
385         NAME(AT_PLATFORM),
386         NAME(AT_SYSINFO),
387         NAME(AT_SYSINFO_EHDR),
388         NAME(AT_UID),
389         { 0, NULL }
390     };
391 #undef NAME
392
393     int i;
394
395     for (  ; av->a_type != AT_NULL; av++)
396     {
397         for (i = 0; names[i].name; i++) if (names[i].val == av->a_type) break;
398         if (names[i].name) wld_printf("%s = %x\n", names[i].name, av->a_un.a_val);
399         else wld_printf( "%x = %x\n", av->a_type, av->a_un.a_val );
400     }
401 }
402 #endif
403
404 /*
405  * set_auxiliary_values
406  *
407  * Set the new auxiliary values
408  */
409 static void set_auxiliary_values( ElfW(auxv_t) *av, const ElfW(auxv_t) *new_av,
410                                   const ElfW(auxv_t) *delete_av, void **stack )
411 {
412     int i, j, av_count = 0, new_count = 0, delete_count = 0;
413     char *src, *dst;
414
415     /* count how many aux values we have already */
416     while (av[av_count].a_type != AT_NULL) av_count++;
417
418     /* delete unwanted values */
419     for (j = 0; delete_av[j].a_type != AT_NULL; j++)
420     {
421         for (i = 0; i < av_count; i++) if (av[i].a_type == delete_av[j].a_type)
422         {
423             av[i].a_type = av[av_count-1].a_type;
424             av[i].a_un.a_val = av[av_count-1].a_un.a_val;
425             av[--av_count].a_type = AT_NULL;
426             delete_count++;
427             break;
428         }
429     }
430
431     /* count how many values we have in new_av that aren't in av */
432     for (j = 0; new_av[j].a_type != AT_NULL; j++)
433     {
434         for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
435         if (i == av_count) new_count++;
436     }
437
438     src = (char *)*stack;
439     dst = src - (new_count - delete_count) * sizeof(*av);
440     if (new_count > delete_count)   /* need to make room for the extra values */
441     {
442         int len = (char *)(av + av_count + 1) - src;
443         for (i = 0; i < len; i++) dst[i] = src[i];
444     }
445     else if (new_count < delete_count)  /* get rid of unused values */
446     {
447         int len = (char *)(av + av_count + 1) - dst;
448         for (i = len - 1; i >= 0; i--) dst[i] = src[i];
449     }
450     *stack = dst;
451     av -= (new_count - delete_count);
452
453     /* now set the values */
454     for (j = 0; new_av[j].a_type != AT_NULL; j++)
455     {
456         for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
457         if (i < av_count) av[i].a_un.a_val = new_av[j].a_un.a_val;
458         else
459         {
460             av[av_count].a_type     = new_av[j].a_type;
461             av[av_count].a_un.a_val = new_av[j].a_un.a_val;
462             av_count++;
463         }
464     }
465
466 #ifdef DUMP_AUX_INFO
467     wld_printf("New auxiliary info:\n");
468     dump_auxiliary( av );
469 #endif
470 }
471
472 /*
473  * get_auxiliary
474  *
475  * Get a field of the auxiliary structure
476  */
477 static int get_auxiliary( ElfW(auxv_t) *av, int type, int def_val )
478 {
479   for ( ; av->a_type != AT_NULL; av++)
480       if( av->a_type == type ) return av->a_un.a_val;
481   return def_val;
482 }
483
484 /*
485  * map_so_lib
486  *
487  * modelled after _dl_map_object_from_fd() from glibc-2.3.1/elf/dl-load.c
488  *
489  * This function maps the segments from an ELF object, and optionally
490  *  stores information about the mapping into the auxv_t structure.
491  */
492 static void map_so_lib( const char *name, struct wld_link_map *l)
493 {
494     int fd;
495     unsigned char buf[0x800];
496     ElfW(Ehdr) *header = (ElfW(Ehdr)*)buf;
497     ElfW(Phdr) *phdr, *ph;
498     /* Scan the program header table, collecting its load commands.  */
499     struct loadcmd
500       {
501         ElfW(Addr) mapstart, mapend, dataend, allocend;
502         off_t mapoff;
503         int prot;
504       } loadcmds[16], *c;
505     size_t nloadcmds = 0, maplength;
506
507     fd = wld_open( name, O_RDONLY );
508     if (fd == -1) fatal_error("%s: could not open\n", name );
509
510     if (wld_read( fd, buf, sizeof(buf) ) != sizeof(buf))
511         fatal_error("%s: failed to read ELF header\n", name);
512
513     phdr = (void*) (((unsigned char*)buf) + header->e_phoff);
514
515     if( ( header->e_ident[0] != 0x7f ) ||
516         ( header->e_ident[1] != 'E' ) ||
517         ( header->e_ident[2] != 'L' ) ||
518         ( header->e_ident[3] != 'F' ) )
519         fatal_error( "%s: not an ELF binary... don't know how to load it\n", name );
520
521     if( header->e_machine != EM_386 )
522         fatal_error("%s: not an i386 ELF binary... don't know how to load it\n", name );
523
524     if (header->e_phnum > sizeof(loadcmds)/sizeof(loadcmds[0]))
525         fatal_error( "%s: oops... not enough space for load commands\n", name );
526
527     maplength = header->e_phnum * sizeof (ElfW(Phdr));
528     if (header->e_phoff + maplength > sizeof(buf))
529         fatal_error( "%s: oops... not enough space for ELF headers\n", name );
530
531     l->l_ld = 0;
532     l->l_addr = 0;
533     l->l_phdr = 0;
534     l->l_phnum = header->e_phnum;
535     l->l_entry = header->e_entry;
536     l->l_interp = 0;
537
538     for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
539     {
540
541 #ifdef DUMP_SEGMENTS
542       wld_printf( "ph = %x\n", ph );
543       wld_printf( " p_type   = %x\n", ph->p_type );
544       wld_printf( " p_flags  = %x\n", ph->p_flags );
545       wld_printf( " p_offset = %x\n", ph->p_offset );
546       wld_printf( " p_vaddr  = %x\n", ph->p_vaddr );
547       wld_printf( " p_paddr  = %x\n", ph->p_paddr );
548       wld_printf( " p_filesz = %x\n", ph->p_filesz );
549       wld_printf( " p_memsz  = %x\n", ph->p_memsz );
550       wld_printf( " p_align  = %x\n", ph->p_align );
551 #endif
552
553       switch (ph->p_type)
554         {
555           /* These entries tell us where to find things once the file's
556              segments are mapped in.  We record the addresses it says
557              verbatim, and later correct for the run-time load address.  */
558         case PT_DYNAMIC:
559           l->l_ld = (void *) ph->p_vaddr;
560           l->l_ldnum = ph->p_memsz / sizeof (Elf32_Dyn);
561           break;
562
563         case PT_PHDR:
564           l->l_phdr = (void *) ph->p_vaddr;
565           break;
566
567         case PT_LOAD:
568           {
569             if ((ph->p_align & page_mask) != 0)
570               fatal_error( "%s: ELF load command alignment not page-aligned\n", name );
571
572             if (((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1)) != 0)
573               fatal_error( "%s: ELF load command address/offset not properly aligned\n", name );
574
575             c = &loadcmds[nloadcmds++];
576             c->mapstart = ph->p_vaddr & ~(ph->p_align - 1);
577             c->mapend = ((ph->p_vaddr + ph->p_filesz + page_mask) & ~page_mask);
578             c->dataend = ph->p_vaddr + ph->p_filesz;
579             c->allocend = ph->p_vaddr + ph->p_memsz;
580             c->mapoff = ph->p_offset & ~(ph->p_align - 1);
581
582             c->prot = 0;
583             if (ph->p_flags & PF_R)
584               c->prot |= PROT_READ;
585             if (ph->p_flags & PF_W)
586               c->prot |= PROT_WRITE;
587             if (ph->p_flags & PF_X)
588               c->prot |= PROT_EXEC;
589           }
590           break;
591
592         case PT_INTERP:
593           l->l_interp = ph->p_vaddr;
594           break;
595
596         case PT_TLS:
597           /*
598            * We don't need to set anything up because we're
599            * emulating the kernel, not ld-linux.so.2
600            * The ELF loader will set up the TLS data itself.
601            */
602         case PT_SHLIB:
603         case PT_NOTE:
604         default:
605           break;
606         }
607     }
608
609     /* Now process the load commands and map segments into memory.  */
610     c = loadcmds;
611
612     /* Length of the sections to be loaded.  */
613     maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
614
615     if( header->e_type == ET_DYN )
616     {
617         ElfW(Addr) mappref;
618         mappref = (ELF_PREFERRED_ADDRESS (loader, maplength, c->mapstart)
619                    - MAP_BASE_ADDR (l));
620
621         /* Remember which part of the address space this object uses.  */
622         l->l_map_start = (ElfW(Addr)) wld_mmap ((void *) mappref, maplength,
623                                               c->prot, MAP_COPY | MAP_FILE,
624                                               fd, c->mapoff);
625         /* wld_printf("set  : offset = %x\n", c->mapoff); */
626         /* wld_printf("l->l_map_start = %x\n", l->l_map_start); */
627
628         l->l_map_end = l->l_map_start + maplength;
629         l->l_addr = l->l_map_start - c->mapstart;
630
631         wld_mprotect ((caddr_t) (l->l_addr + c->mapend),
632                     loadcmds[nloadcmds - 1].allocend - c->mapend,
633                     PROT_NONE);
634         goto postmap;
635     }
636     else
637     {
638         /* sanity check */
639         if ((char *)c->mapstart + maplength > preloader_start &&
640             (char *)c->mapstart <= preloader_end)
641             fatal_error( "%s: binary overlaps preloader (%x-%x)\n",
642                          name, c->mapstart, (char *)c->mapstart + maplength );
643
644         ELF_FIXED_ADDRESS (loader, c->mapstart);
645     }
646
647     /* Remember which part of the address space this object uses.  */
648     l->l_map_start = c->mapstart + l->l_addr;
649     l->l_map_end = l->l_map_start + maplength;
650
651     while (c < &loadcmds[nloadcmds])
652       {
653         if (c->mapend > c->mapstart)
654             /* Map the segment contents from the file.  */
655             wld_mmap ((void *) (l->l_addr + c->mapstart),
656                         c->mapend - c->mapstart, c->prot,
657                         MAP_FIXED | MAP_COPY | MAP_FILE, fd, c->mapoff);
658
659       postmap:
660         if (l->l_phdr == 0
661             && (ElfW(Off)) c->mapoff <= header->e_phoff
662             && ((size_t) (c->mapend - c->mapstart + c->mapoff)
663                 >= header->e_phoff + header->e_phnum * sizeof (ElfW(Phdr))))
664           /* Found the program header in this segment.  */
665           l->l_phdr = (void *)(unsigned int) (c->mapstart + header->e_phoff - c->mapoff);
666
667         if (c->allocend > c->dataend)
668           {
669             /* Extra zero pages should appear at the end of this segment,
670                after the data mapped from the file.   */
671             ElfW(Addr) zero, zeroend, zeropage;
672
673             zero = l->l_addr + c->dataend;
674             zeroend = l->l_addr + c->allocend;
675             zeropage = (zero + page_mask) & ~page_mask;
676
677             /*
678              * This is different from the dl-load load...
679              *  ld-linux.so.2 relies on the whole page being zero'ed
680              */
681             zeroend = (zeroend + page_mask) & ~page_mask;
682
683             if (zeroend < zeropage)
684             {
685               /* All the extra data is in the last page of the segment.
686                  We can just zero it.  */
687               zeropage = zeroend;
688             }
689
690             if (zeropage > zero)
691               {
692                 /* Zero the final part of the last page of the segment.  */
693                 if ((c->prot & PROT_WRITE) == 0)
694                   {
695                     /* Dag nab it.  */
696                     wld_mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot|PROT_WRITE);
697                   }
698                 wld_memset ((void *) zero, '\0', zeropage - zero);
699                 if ((c->prot & PROT_WRITE) == 0)
700                   wld_mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot);
701               }
702
703             if (zeroend > zeropage)
704               {
705                 /* Map the remaining zero pages in from the zero fill FD.  */
706                 caddr_t mapat;
707                 mapat = wld_mmap ((caddr_t) zeropage, zeroend - zeropage,
708                                 c->prot, MAP_ANON|MAP_PRIVATE|MAP_FIXED,
709                                 -1, 0);
710               }
711           }
712
713         ++c;
714       }
715
716     if (l->l_phdr == NULL) fatal_error("no program header\n");
717
718     l->l_phdr = (void *)((ElfW(Addr))l->l_phdr + l->l_addr);
719     l->l_entry += l->l_addr;
720
721     wld_close( fd );
722 }
723
724
725 /*
726  * Find a symbol in the symbol table of the executable loaded
727  */
728 static void *find_symbol( const ElfW(Phdr) *phdr, int num, const char *var )
729 {
730     const ElfW(Dyn) *dyn = NULL;
731     const ElfW(Phdr) *ph;
732     const ElfW(Sym) *symtab = NULL;
733     const char *strings = NULL;
734     uint32_t i, symtabend = 0;
735
736     /* check the values */
737 #ifdef DUMP_SYMS
738     wld_printf("%x %x\n", phdr, num );
739 #endif
740     if( ( phdr == NULL ) || ( num == 0 ) )
741     {
742         wld_printf("could not find PT_DYNAMIC header entry\n");
743         return NULL;
744     }
745
746     /* parse the (already loaded) ELF executable's header */
747     for (ph = phdr; ph < &phdr[num]; ++ph)
748     {
749         if( PT_DYNAMIC == ph->p_type )
750         {
751             dyn = (void *) ph->p_vaddr;
752             num = ph->p_memsz / sizeof (Elf32_Dyn);
753             break;
754         }
755     }
756     if( !dyn ) return NULL;
757
758     while( dyn->d_tag )
759     {
760         if( dyn->d_tag == DT_STRTAB )
761             strings = (const char*) dyn->d_un.d_ptr;
762         if( dyn->d_tag == DT_SYMTAB )
763             symtab = (const ElfW(Sym) *)dyn->d_un.d_ptr;
764         if( dyn->d_tag == DT_HASH )
765             symtabend = *((const uint32_t *)dyn->d_un.d_ptr + 1);
766 #ifdef DUMP_SYMS
767         wld_printf("%x %x\n", dyn->d_tag, dyn->d_un.d_ptr );
768 #endif
769         dyn++;
770     }
771
772     if( (!symtab) || (!strings) ) return NULL;
773
774     for (i = 0; i < symtabend; i++)
775     {
776         if( ( ELF32_ST_BIND(symtab[i].st_info) == STT_OBJECT ) &&
777             ( 0 == wld_strcmp( strings+symtab[i].st_name, var ) ) )
778         {
779 #ifdef DUMP_SYMS
780             wld_printf("Found %s -> %x\n", strings+symtab[i].st_name, symtab[i].st_value );
781 #endif
782             return (void*)symtab[i].st_value;
783         }
784     }
785     return NULL;
786 }
787
788 /*
789  *  preload_reserve
790  *
791  * Reserve a range specified in string format
792  */
793 static void preload_reserve( const char *str )
794 {
795     const char *p;
796     unsigned long result = 0;
797     void *start = NULL, *end = NULL;
798     int first = 1;
799
800     for (p = str; *p; p++)
801     {
802         if (*p >= '0' && *p <= '9') result = result * 16 + *p - '0';
803         else if (*p >= 'a' && *p <= 'f') result = result * 16 + *p - 'a' + 10;
804         else if (*p >= 'A' && *p <= 'F') result = result * 16 + *p - 'A' + 10;
805         else if (*p == '-')
806         {
807             if (!first) goto error;
808             start = (void *)(result & ~page_mask);
809             result = 0;
810             first = 0;
811         }
812         else goto error;
813     }
814     if (!first) end = (void *)((result + page_mask) & ~page_mask);
815     else if (result) goto error;  /* single value '0' is allowed */
816
817     /* sanity checks */
818     if (end <= start) start = end = NULL;
819     else if ((char *)end > preloader_start &&
820              (char *)start <= preloader_end)
821     {
822         wld_printf( "WINEPRELOADRESERVE range %x-%x overlaps preloader %x-%x\n",
823                      start, end, preloader_start, preloader_end );
824         start = end = NULL;
825     }
826
827     /* entry 2 is for the PE exe */
828     preload_info[2].addr = start;
829     preload_info[2].size = (char *)end - (char *)start;
830     return;
831
832 error:
833     fatal_error( "invalid WINEPRELOADRESERVE value '%s'\n", str );
834 }
835
836 /*
837  *  is_in_preload_range
838  *
839  * Check if address of the given aux value is in one of the reserved ranges
840  */
841 static int is_in_preload_range( const ElfW(auxv_t) *av, int type )
842 {
843     int i;
844
845     while (av->a_type != type && av->a_type != AT_NULL) av++;
846
847     if (av->a_type == type)
848     {
849         for (i = 0; preload_info[i].size; i++)
850         {
851             if ((char *)av->a_un.a_ptr >= (char *)preload_info[i].addr &&
852                 (char *)av->a_un.a_ptr < (char *)preload_info[i].addr + preload_info[i].size)
853                 return 1;
854         }
855     }
856     return 0;
857 }
858
859 /*
860  *  wld_start
861  *
862  *  Repeat the actions the kernel would do when loading a dynamically linked .so
863  *  Load the binary and then its ELF interpreter.
864  *  Note, we assume that the binary is a dynamically linked ELF shared object.
865  */
866 void* wld_start( void **stack )
867 {
868     int i, *pargc;
869     char **argv, **p;
870     char *interp, *reserve = NULL;
871     ElfW(auxv_t) new_av[12], delete_av[3], *av;
872     struct wld_link_map main_binary_map, ld_so_map;
873     struct wine_preload_info **wine_main_preload_info;
874
875     pargc = *stack;
876     argv = (char **)pargc + 1;
877     if (*pargc < 2) fatal_error( "Usage: %s wine_binary [args]\n", argv[0] );
878
879     /* skip over the parameters */
880     p = argv + *pargc + 1;
881
882     /* skip over the environment */
883     while (*p)
884     {
885         static const char res[] = "WINEPRELOADRESERVE=";
886         if (!wld_strncmp( *p, res, sizeof(res)-1 )) reserve = *p + sizeof(res) - 1;
887         p++;
888     }
889
890     av = (ElfW(auxv_t)*) (p+1);
891     page_size = get_auxiliary( av, AT_PAGESZ, 4096 );
892     page_mask = page_size - 1;
893
894     preloader_start = (char *)_start - ((unsigned int)_start & page_mask);
895     preloader_end = (char *)((unsigned int)(_end + page_mask) & ~page_mask);
896
897 #ifdef DUMP_AUX_INFO
898     wld_printf( "stack = %x\n", *stack );
899     for( i = 0; i < *pargc; i++ ) wld_printf("argv[%x] = %s\n", i, argv[i]);
900     dump_auxiliary( av );
901 #endif
902
903     /* reserve memory that Wine needs */
904     if (reserve) preload_reserve( reserve );
905     for (i = 0; preload_info[i].size; i++)
906         wld_mmap( preload_info[i].addr, preload_info[i].size,
907                   PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, -1, 0 );
908
909     /* load the main binary */
910     map_so_lib( argv[1], &main_binary_map );
911
912     /* load the ELF interpreter */
913     interp = (char *)main_binary_map.l_addr + main_binary_map.l_interp;
914     map_so_lib( interp, &ld_so_map );
915
916     /* store pointer to the preload info into the appropriate main binary variable */
917     wine_main_preload_info = find_symbol( main_binary_map.l_phdr, main_binary_map.l_phnum,
918                                           "wine_main_preload_info" );
919     if (wine_main_preload_info) *wine_main_preload_info = preload_info;
920     else wld_printf( "wine_main_preload_info not found\n" );
921
922 #define SET_NEW_AV(n,type,val) new_av[n].a_type = (type); new_av[n].a_un.a_val = (val);
923     SET_NEW_AV( 0, AT_PHDR, (unsigned long)main_binary_map.l_phdr );
924     SET_NEW_AV( 1, AT_PHENT, sizeof(ElfW(Phdr)) );
925     SET_NEW_AV( 2, AT_PHNUM, main_binary_map.l_phnum );
926     SET_NEW_AV( 3, AT_PAGESZ, page_size );
927     SET_NEW_AV( 4, AT_BASE, ld_so_map.l_addr );
928     SET_NEW_AV( 5, AT_FLAGS, get_auxiliary( av, AT_FLAGS, 0 ) );
929     SET_NEW_AV( 6, AT_ENTRY, main_binary_map.l_entry );
930     SET_NEW_AV( 7, AT_UID, get_auxiliary( av, AT_UID, wld_getuid() ) );
931     SET_NEW_AV( 8, AT_EUID, get_auxiliary( av, AT_EUID, wld_geteuid() ) );
932     SET_NEW_AV( 9, AT_GID, get_auxiliary( av, AT_GID, wld_getgid() ) );
933     SET_NEW_AV(10, AT_EGID, get_auxiliary( av, AT_EGID, wld_getegid() ) );
934     SET_NEW_AV(11, AT_NULL, 0 );
935 #undef SET_NEW_AV
936
937     i = 0;
938     /* delete sysinfo values if addresses conflict */
939     if (is_in_preload_range( av, AT_SYSINFO )) delete_av[i++].a_type = AT_SYSINFO;
940     if (is_in_preload_range( av, AT_SYSINFO_EHDR )) delete_av[i++].a_type = AT_SYSINFO_EHDR;
941     delete_av[i].a_type = AT_NULL;
942
943     /* get rid of first argument */
944     pargc[1] = pargc[0] - 1;
945     *stack = pargc + 1;
946
947     set_auxiliary_values( av, new_av, delete_av, stack );
948
949 #ifdef DUMP_AUX_INFO
950     wld_printf("new stack = %x\n", *stack);
951     wld_printf("jumping to %x\n", ld_so_map.l_entry);
952 #endif
953
954     return (void *)ld_so_map.l_entry;
955 }