Define AT_SYSINFO_* if it's missing.
[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, 0x0fef0000 },  /* default PE exe range (may be set with WINEPRELOADRESERVE) */
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__( "int $0x80" : : "a" (SYS_exit), "b" (code) );
177 }
178
179 static inline int wld_open( const char *name, int flags )
180 {
181     int ret;
182     __asm__ __volatile__( "int $0x80" : "=a" (ret) : "0" (SYS_open), "b" (name), "c" (flags) );
183     return SYSCALL_RET(ret);
184 }
185
186 static inline int wld_close( int fd )
187 {
188     int ret;
189     __asm__ __volatile__( "int $0x80" : "=a" (ret) : "0" (SYS_close), "b" (fd) );
190     return SYSCALL_RET(ret);
191 }
192
193 static inline ssize_t wld_read( int fd, void *buffer, size_t len )
194 {
195     int ret;
196     __asm__ __volatile__( "int $0x80" : "=a" (ret)
197                           : "0" (SYS_read), "b" (fd), "c" (buffer), "d" (len)
198                           : "memory" );
199     return SYSCALL_RET(ret);
200 }
201
202 static inline ssize_t wld_write( int fd, const void *buffer, size_t len )
203 {
204     int ret;
205     __asm__ __volatile__( "int $0x80" : "=a" (ret)
206                           : "0" (SYS_write), "b" (fd), "c" (buffer), "d" (len) );
207     return SYSCALL_RET(ret);
208 }
209
210 static inline int wld_mprotect( const void *addr, size_t len, int prot )
211 {
212     int ret;
213     __asm__ __volatile__( "int $0x80" : "=a" (ret) : "0" (SYS_mprotect), "b" (addr), "c" (len), "d" (prot) );
214     return SYSCALL_RET(ret);
215 }
216
217 static void *wld_mmap( void *start, size_t len, int prot, int flags, int fd, off_t offset )
218 {
219     int ret;
220
221     struct
222     {
223         void        *addr;
224         unsigned int length;
225         unsigned int prot;
226         unsigned int flags;
227         unsigned int fd;
228         unsigned int offset;
229     } args;
230
231     args.addr   = start;
232     args.length = len;
233     args.prot   = prot;
234     args.flags  = flags;
235     args.fd     = fd;
236     args.offset = offset;
237     __asm__ __volatile__( "int $0x80" : "=a" (ret) : "0" (SYS_mmap), "b" (&args) : "memory" );
238     return (void *)SYSCALL_RET(ret);
239 }
240
241 static inline uid_t wld_getuid(void)
242 {
243     uid_t ret;
244     __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_getuid) );
245     return ret;
246 }
247
248 static inline uid_t wld_geteuid(void)
249 {
250     uid_t ret;
251     __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_geteuid) );
252     return ret;
253 }
254
255 static inline gid_t wld_getgid(void)
256 {
257     gid_t ret;
258     __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_getgid) );
259     return ret;
260 }
261
262 static inline gid_t wld_getegid(void)
263 {
264     gid_t ret;
265     __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_getegid) );
266     return ret;
267 }
268
269
270 /* replacement for libc functions */
271
272 static int wld_strcmp( const char *str1, const char *str2 )
273 {
274     while (*str1 && (*str1 == *str2)) { str1++; str2++; }
275     return *str1 - *str2;
276 }
277
278 static int wld_strncmp( const char *str1, const char *str2, size_t len )
279 {
280     if (len <= 0) return 0;
281     while ((--len > 0) && *str1 && (*str1 == *str2)) { str1++; str2++; }
282     return *str1 - *str2;
283 }
284
285 static inline void *wld_memset( void *dest, int val, size_t len )
286 {
287     char *dst = dest;
288     while (len--) *dst++ = val;
289     return dest;
290 }
291
292 /*
293  * wld_printf - just the basics
294  *
295  *  %x prints a hex number
296  *  %s prints a string
297  */
298 static void wld_vsprintf(char *str, const char *fmt, va_list args )
299 {
300     static const char hex_chars[16] = "0123456789abcdef";
301     const char *p = fmt;
302
303     while( *p )
304     {
305         if( *p == '%' )
306         {
307             p++;
308             if( *p == 'x' )
309             {
310                 int i;
311                 unsigned int x = va_arg( args, unsigned int );
312                 for(i=7; i>=0; i--)
313                     *str++ = hex_chars[(x>>(i*4))&0xf];
314             }
315             else if( *p == 's' )
316             {
317                 char *s = va_arg( args, char * );
318                 while(*s)
319                     *str++ = *s++;
320             }
321             else if( *p == 0 )
322                 break;
323             p++;
324         }
325         *str++ = *p++;
326     }
327     *str = 0;
328 }
329
330 static void wld_printf(const char *fmt, ... )
331 {
332     va_list args;
333     char buffer[256];
334
335     va_start( args, fmt );
336     wld_vsprintf(buffer, fmt, args );
337     va_end( args );
338     wld_write(2, buffer, strlen(buffer));
339 }
340
341 static __attribute__((noreturn)) void fatal_error(const char *fmt, ... )
342 {
343     va_list args;
344     char buffer[256];
345
346     va_start( args, fmt );
347     wld_vsprintf(buffer, fmt, args );
348     va_end( args );
349     wld_write(2, buffer, strlen(buffer));
350     wld_exit(1);
351 }
352
353 #ifdef DUMP_AUX_INFO
354 /*
355  *  Dump interesting bits of the ELF auxv_t structure that is passed
356  *   as the 4th parameter to the _start function
357  */
358 static void dump_auxiliary( ElfW(auxv_t) *av )
359 {
360 #define NAME(at) { at, #at }
361     static const struct { int val; const char *name; } names[] =
362     {
363         NAME(AT_BASE),
364         NAME(AT_CLKTCK),
365         NAME(AT_EGID),
366         NAME(AT_ENTRY),
367         NAME(AT_EUID),
368         NAME(AT_FLAGS),
369         NAME(AT_GID),
370         NAME(AT_HWCAP),
371         NAME(AT_PAGESZ),
372         NAME(AT_PHDR),
373         NAME(AT_PHENT),
374         NAME(AT_PHNUM),
375         NAME(AT_PLATFORM),
376         NAME(AT_SYSINFO),
377         NAME(AT_SYSINFO_EHDR),
378         NAME(AT_UID),
379         { 0, NULL }
380     };
381 #undef NAME
382
383     int i;
384
385     for (  ; av->a_type != AT_NULL; av++)
386     {
387         for (i = 0; names[i].name; i++) if (names[i].val == av->a_type) break;
388         if (names[i].name) wld_printf("%s = %x\n", names[i].name, av->a_un.a_val);
389         else wld_printf( "%x = %x\n", av->a_type, av->a_un.a_val );
390     }
391 }
392 #endif
393
394 /*
395  * set_auxiliary_values
396  *
397  * Set the new auxiliary values
398  */
399 static void set_auxiliary_values( ElfW(auxv_t) *av, const ElfW(auxv_t) *new_av,
400                                   const ElfW(auxv_t) *delete_av, void **stack )
401 {
402     int i, j, av_count = 0, new_count = 0, delete_count = 0;
403     char *src, *dst;
404
405     /* count how many aux values we have already */
406     while (av[av_count].a_type != AT_NULL) av_count++;
407
408     /* delete unwanted values */
409     for (j = 0; delete_av[j].a_type != AT_NULL; j++)
410     {
411         for (i = 0; i < av_count; i++) if (av[i].a_type == delete_av[j].a_type)
412         {
413             av[i].a_type = av[av_count-1].a_type;
414             av[i].a_un.a_val = av[av_count-1].a_un.a_val;
415             av[--av_count].a_type = AT_NULL;
416             delete_count++;
417             break;
418         }
419     }
420
421     /* count how many values we have in new_av that aren't in av */
422     for (j = 0; new_av[j].a_type != AT_NULL; j++)
423     {
424         for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
425         if (i == av_count) new_count++;
426     }
427
428     src = (char *)*stack;
429     dst = src - (new_count - delete_count) * sizeof(*av);
430     if (new_count > delete_count)   /* need to make room for the extra values */
431     {
432         int len = (char *)(av + av_count + 1) - src;
433         for (i = 0; i < len; i++) dst[i] = src[i];
434     }
435     else if (new_count < delete_count)  /* get rid of unused values */
436     {
437         int len = (char *)(av + av_count + 1) - dst;
438         for (i = len - 1; i >= 0; i--) dst[i] = src[i];
439     }
440     *stack = dst;
441     av -= (new_count - delete_count);
442
443     /* now set the values */
444     for (j = 0; new_av[j].a_type != AT_NULL; j++)
445     {
446         for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
447         if (i < av_count) av[i].a_un.a_val = new_av[j].a_un.a_val;
448         else
449         {
450             av[av_count].a_type     = new_av[j].a_type;
451             av[av_count].a_un.a_val = new_av[j].a_un.a_val;
452             av_count++;
453         }
454     }
455
456 #ifdef DUMP_AUX_INFO
457     wld_printf("New auxiliary info:\n");
458     dump_auxiliary( av );
459 #endif
460 }
461
462 /*
463  * get_auxiliary
464  *
465  * Get a field of the auxiliary structure
466  */
467 static int get_auxiliary( ElfW(auxv_t) *av, int type, int def_val )
468 {
469   for ( ; av->a_type != AT_NULL; av++)
470       if( av->a_type == type ) return av->a_un.a_val;
471   return def_val;
472 }
473
474 /*
475  * map_so_lib
476  *
477  * modelled after _dl_map_object_from_fd() from glibc-2.3.1/elf/dl-load.c
478  *
479  * This function maps the segments from an ELF object, and optionally
480  *  stores information about the mapping into the auxv_t structure.
481  */
482 static void map_so_lib( const char *name, struct wld_link_map *l)
483 {
484     int fd;
485     unsigned char buf[0x800];
486     ElfW(Ehdr) *header = (ElfW(Ehdr)*)buf;
487     ElfW(Phdr) *phdr, *ph;
488     /* Scan the program header table, collecting its load commands.  */
489     struct loadcmd
490       {
491         ElfW(Addr) mapstart, mapend, dataend, allocend;
492         off_t mapoff;
493         int prot;
494       } loadcmds[16], *c;
495     size_t nloadcmds = 0, maplength;
496
497     fd = wld_open( name, O_RDONLY );
498     if (fd == -1) fatal_error("%s: could not open\n", name );
499
500     if (wld_read( fd, buf, sizeof(buf) ) != sizeof(buf))
501         fatal_error("%s: failed to read ELF header\n", name);
502
503     phdr = (void*) (((unsigned char*)buf) + header->e_phoff);
504
505     if( ( header->e_ident[0] != 0x7f ) ||
506         ( header->e_ident[1] != 'E' ) ||
507         ( header->e_ident[2] != 'L' ) ||
508         ( header->e_ident[3] != 'F' ) )
509         fatal_error( "%s: not an ELF binary... don't know how to load it\n", name );
510
511     if( header->e_machine != EM_386 )
512         fatal_error("%s: not an i386 ELF binary... don't know how to load it\n", name );
513
514     if (header->e_phnum > sizeof(loadcmds)/sizeof(loadcmds[0]))
515         fatal_error( "%s: oops... not enough space for load commands\n", name );
516
517     maplength = header->e_phnum * sizeof (ElfW(Phdr));
518     if (header->e_phoff + maplength > sizeof(buf))
519         fatal_error( "%s: oops... not enough space for ELF headers\n", name );
520
521     l->l_ld = 0;
522     l->l_addr = 0;
523     l->l_phdr = 0;
524     l->l_phnum = header->e_phnum;
525     l->l_entry = header->e_entry;
526     l->l_interp = 0;
527
528     for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
529     {
530
531 #ifdef DUMP_SEGMENTS
532       wld_printf( "ph = %x\n", ph );
533       wld_printf( " p_type   = %x\n", ph->p_type );
534       wld_printf( " p_flags  = %x\n", ph->p_flags );
535       wld_printf( " p_offset = %x\n", ph->p_offset );
536       wld_printf( " p_vaddr  = %x\n", ph->p_vaddr );
537       wld_printf( " p_paddr  = %x\n", ph->p_paddr );
538       wld_printf( " p_filesz = %x\n", ph->p_filesz );
539       wld_printf( " p_memsz  = %x\n", ph->p_memsz );
540       wld_printf( " p_align  = %x\n", ph->p_align );
541 #endif
542
543       switch (ph->p_type)
544         {
545           /* These entries tell us where to find things once the file's
546              segments are mapped in.  We record the addresses it says
547              verbatim, and later correct for the run-time load address.  */
548         case PT_DYNAMIC:
549           l->l_ld = (void *) ph->p_vaddr;
550           l->l_ldnum = ph->p_memsz / sizeof (Elf32_Dyn);
551           break;
552
553         case PT_PHDR:
554           l->l_phdr = (void *) ph->p_vaddr;
555           break;
556
557         case PT_LOAD:
558           {
559             if ((ph->p_align & page_mask) != 0)
560               fatal_error( "%s: ELF load command alignment not page-aligned\n", name );
561
562             if (((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1)) != 0)
563               fatal_error( "%s: ELF load command address/offset not properly aligned\n", name );
564
565             c = &loadcmds[nloadcmds++];
566             c->mapstart = ph->p_vaddr & ~(ph->p_align - 1);
567             c->mapend = ((ph->p_vaddr + ph->p_filesz + page_mask) & ~page_mask);
568             c->dataend = ph->p_vaddr + ph->p_filesz;
569             c->allocend = ph->p_vaddr + ph->p_memsz;
570             c->mapoff = ph->p_offset & ~(ph->p_align - 1);
571
572             c->prot = 0;
573             if (ph->p_flags & PF_R)
574               c->prot |= PROT_READ;
575             if (ph->p_flags & PF_W)
576               c->prot |= PROT_WRITE;
577             if (ph->p_flags & PF_X)
578               c->prot |= PROT_EXEC;
579           }
580           break;
581
582         case PT_INTERP:
583           l->l_interp = ph->p_vaddr;
584           break;
585
586         case PT_TLS:
587           /*
588            * We don't need to set anything up because we're
589            * emulating the kernel, not ld-linux.so.2
590            * The ELF loader will set up the TLS data itself.
591            */
592         case PT_SHLIB:
593         case PT_NOTE:
594         default:
595           break;
596         }
597     }
598
599     /* Now process the load commands and map segments into memory.  */
600     c = loadcmds;
601
602     /* Length of the sections to be loaded.  */
603     maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
604
605     if( header->e_type == ET_DYN )
606     {
607         ElfW(Addr) mappref;
608         mappref = (ELF_PREFERRED_ADDRESS (loader, maplength, c->mapstart)
609                    - MAP_BASE_ADDR (l));
610
611         /* Remember which part of the address space this object uses.  */
612         l->l_map_start = (ElfW(Addr)) wld_mmap ((void *) mappref, maplength,
613                                               c->prot, MAP_COPY | MAP_FILE,
614                                               fd, c->mapoff);
615         /* wld_printf("set  : offset = %x\n", c->mapoff); */
616         /* wld_printf("l->l_map_start = %x\n", l->l_map_start); */
617
618         l->l_map_end = l->l_map_start + maplength;
619         l->l_addr = l->l_map_start - c->mapstart;
620
621         wld_mprotect ((caddr_t) (l->l_addr + c->mapend),
622                     loadcmds[nloadcmds - 1].allocend - c->mapend,
623                     PROT_NONE);
624         goto postmap;
625     }
626     else
627     {
628         /* sanity check */
629         if ((char *)c->mapstart + maplength > preloader_start &&
630             (char *)c->mapstart <= preloader_end)
631             fatal_error( "%s: binary overlaps preloader (%x-%x)\n",
632                          name, c->mapstart, (char *)c->mapstart + maplength );
633
634         ELF_FIXED_ADDRESS (loader, c->mapstart);
635     }
636
637     /* Remember which part of the address space this object uses.  */
638     l->l_map_start = c->mapstart + l->l_addr;
639     l->l_map_end = l->l_map_start + maplength;
640
641     while (c < &loadcmds[nloadcmds])
642       {
643         if (c->mapend > c->mapstart)
644             /* Map the segment contents from the file.  */
645             wld_mmap ((void *) (l->l_addr + c->mapstart),
646                         c->mapend - c->mapstart, c->prot,
647                         MAP_FIXED | MAP_COPY | MAP_FILE, fd, c->mapoff);
648
649       postmap:
650         if (l->l_phdr == 0
651             && (ElfW(Off)) c->mapoff <= header->e_phoff
652             && ((size_t) (c->mapend - c->mapstart + c->mapoff)
653                 >= header->e_phoff + header->e_phnum * sizeof (ElfW(Phdr))))
654           /* Found the program header in this segment.  */
655           l->l_phdr = (void *)(unsigned int) (c->mapstart + header->e_phoff - c->mapoff);
656
657         if (c->allocend > c->dataend)
658           {
659             /* Extra zero pages should appear at the end of this segment,
660                after the data mapped from the file.   */
661             ElfW(Addr) zero, zeroend, zeropage;
662
663             zero = l->l_addr + c->dataend;
664             zeroend = l->l_addr + c->allocend;
665             zeropage = (zero + page_mask) & ~page_mask;
666
667             /*
668              * This is different from the dl-load load...
669              *  ld-linux.so.2 relies on the whole page being zero'ed
670              */
671             zeroend = (zeroend + page_mask) & ~page_mask;
672
673             if (zeroend < zeropage)
674             {
675               /* All the extra data is in the last page of the segment.
676                  We can just zero it.  */
677               zeropage = zeroend;
678             }
679
680             if (zeropage > zero)
681               {
682                 /* Zero the final part of the last page of the segment.  */
683                 if ((c->prot & PROT_WRITE) == 0)
684                   {
685                     /* Dag nab it.  */
686                     wld_mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot|PROT_WRITE);
687                   }
688                 wld_memset ((void *) zero, '\0', zeropage - zero);
689                 if ((c->prot & PROT_WRITE) == 0)
690                   wld_mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot);
691               }
692
693             if (zeroend > zeropage)
694               {
695                 /* Map the remaining zero pages in from the zero fill FD.  */
696                 caddr_t mapat;
697                 mapat = wld_mmap ((caddr_t) zeropage, zeroend - zeropage,
698                                 c->prot, MAP_ANON|MAP_PRIVATE|MAP_FIXED,
699                                 -1, 0);
700               }
701           }
702
703         ++c;
704       }
705
706     if (l->l_phdr == NULL) fatal_error("no program header\n");
707
708     l->l_phdr = (void *)((ElfW(Addr))l->l_phdr + l->l_addr);
709     l->l_entry += l->l_addr;
710
711     wld_close( fd );
712 }
713
714
715 /*
716  * Find a symbol in the symbol table of the executable loaded
717  */
718 static void *find_symbol( const ElfW(Phdr) *phdr, int num, char *var )
719 {
720     const ElfW(Dyn) *dyn = NULL;
721     const ElfW(Phdr) *ph;
722     const ElfW(Sym) *symtab = NULL;
723     const char *strings = NULL;
724     uint32_t i, symtabend = 0;
725
726     /* check the values */
727 #ifdef DUMP_SYMS
728     wld_printf("%x %x\n", phdr, num );
729 #endif
730     if( ( phdr == NULL ) || ( num == 0 ) )
731     {
732         wld_printf("could not find PT_DYNAMIC header entry\n");
733         return NULL;
734     }
735
736     /* parse the (already loaded) ELF executable's header */
737     for (ph = phdr; ph < &phdr[num]; ++ph)
738     {
739         if( PT_DYNAMIC == ph->p_type )
740         {
741             dyn = (void *) ph->p_vaddr;
742             num = ph->p_memsz / sizeof (Elf32_Dyn);
743             break;
744         }
745     }
746     if( !dyn ) return NULL;
747
748     while( dyn->d_tag )
749     {
750         if( dyn->d_tag == DT_STRTAB )
751             strings = (const char*) dyn->d_un.d_ptr;
752         if( dyn->d_tag == DT_SYMTAB )
753             symtab = (const ElfW(Sym) *)dyn->d_un.d_ptr;
754         if( dyn->d_tag == DT_HASH )
755             symtabend = *((const uint32_t *)dyn->d_un.d_ptr + 1);
756 #ifdef DUMP_SYMS
757         wld_printf("%x %x\n", dyn->d_tag, dyn->d_un.d_ptr );
758 #endif
759         dyn++;
760     }
761
762     if( (!symtab) || (!strings) ) return NULL;
763
764     for (i = 0; i < symtabend; i++)
765     {
766         if( ( ELF32_ST_BIND(symtab[i].st_info) == STT_OBJECT ) &&
767             ( 0 == wld_strcmp( strings+symtab[i].st_name, var ) ) )
768         {
769 #ifdef DUMP_SYMS
770             wld_printf("Found %s -> %x\n", strings+symtab[i].st_name, symtab[i].st_value );
771 #endif
772             return (void*)symtab[i].st_value;
773         }
774     }
775     return NULL;
776 }
777
778 /*
779  *  preload_reserve
780  *
781  * Reserve a range specified in string format
782  */
783 static void preload_reserve( const char *str )
784 {
785     const char *p;
786     unsigned long result = 0;
787     void *start = NULL, *end = NULL;
788     int first = 1;
789
790     for (p = str; *p; p++)
791     {
792         if (*p >= '0' && *p <= '9') result = result * 16 + *p - '0';
793         else if (*p >= 'a' && *p <= 'f') result = result * 16 + *p - 'a' + 10;
794         else if (*p >= 'A' && *p <= 'F') result = result * 16 + *p - 'A' + 10;
795         else if (*p == '-')
796         {
797             if (!first) goto error;
798             start = (void *)(result & ~page_mask);
799             result = 0;
800             first = 0;
801         }
802         else goto error;
803     }
804     if (!first) end = (void *)((result + page_mask) & ~page_mask);
805     else if (result) goto error;  /* single value '0' is allowed */
806
807     /* sanity checks */
808     if (end <= start) start = end = NULL;
809     else if ((char *)end > preloader_start &&
810              (char *)start <= preloader_end)
811     {
812         wld_printf( "WINEPRELOADRESERVE range %x-%x overlaps preloader %x-%x\n",
813                      start, end, preloader_start, preloader_end );
814         start = end = NULL;
815     }
816
817     /* entry 2 is for the PE exe */
818     preload_info[2].addr = start;
819     preload_info[2].size = (char *)end - (char *)start;
820     return;
821
822 error:
823     fatal_error( "invalid WINEPRELOADRESERVE value '%s'\n", str );
824 }
825
826 /*
827  *  is_in_preload_range
828  *
829  * Check if address of the given aux value is in one of the reserved ranges
830  */
831 static int is_in_preload_range( const ElfW(auxv_t) *av, int type )
832 {
833     int i;
834
835     while (av->a_type != type && av->a_type != AT_NULL) av++;
836
837     if (av->a_type == type)
838     {
839         for (i = 0; preload_info[i].size; i++)
840         {
841             if ((char *)av->a_un.a_ptr >= (char *)preload_info[i].addr &&
842                 (char *)av->a_un.a_ptr < (char *)preload_info[i].addr + preload_info[i].size)
843                 return 1;
844         }
845     }
846     return 0;
847 }
848
849 /*
850  *  wld_start
851  *
852  *  Repeat the actions the kernel would do when loading a dynamically linked .so
853  *  Load the binary and then its ELF interpreter.
854  *  Note, we assume that the binary is a dynamically linked ELF shared object.
855  */
856 void* wld_start( void **stack )
857 {
858     int i, *pargc;
859     char **argv, **p;
860     char *interp, *reserve = NULL;
861     ElfW(auxv_t) new_av[12], delete_av[3], *av;
862     struct wld_link_map main_binary_map, ld_so_map;
863     struct wine_preload_info **wine_main_preload_info;
864
865     pargc = *stack;
866     argv = (char **)pargc + 1;
867     if (*pargc < 2) fatal_error( "Usage: %s wine_binary [args]\n", argv[0] );
868
869     /* skip over the parameters */
870     p = argv + *pargc + 1;
871
872     /* skip over the environment */
873     while (*p)
874     {
875         static const char res[] = "WINEPRELOADRESERVE=";
876         if (!wld_strncmp( *p, res, sizeof(res)-1 )) reserve = *p + sizeof(res) - 1;
877         p++;
878     }
879
880     av = (ElfW(auxv_t)*) (p+1);
881     page_size = get_auxiliary( av, AT_PAGESZ, 4096 );
882     page_mask = page_size - 1;
883
884     preloader_start = (char *)_start - ((unsigned int)_start & page_mask);
885     preloader_end = (char *)((unsigned int)(_end + page_mask) & ~page_mask);
886
887 #ifdef DUMP_AUX_INFO
888     wld_printf( "stack = %x\n", *stack );
889     for( i = 0; i < *pargc; i++ ) wld_printf("argv[%x] = %s\n", i, argv[i]);
890     dump_auxiliary( av );
891 #endif
892
893     /* reserve memory that Wine needs */
894     if (reserve) preload_reserve( reserve );
895     for (i = 0; preload_info[i].size; i++)
896         wld_mmap( preload_info[i].addr, preload_info[i].size,
897                   PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, -1, 0 );
898
899     /* load the main binary */
900     map_so_lib( argv[1], &main_binary_map );
901
902     /* load the ELF interpreter */
903     interp = (char *)main_binary_map.l_addr + main_binary_map.l_interp;
904     map_so_lib( interp, &ld_so_map );
905
906     /* store pointer to the preload info into the appropriate main binary variable */
907     wine_main_preload_info = find_symbol( main_binary_map.l_phdr, main_binary_map.l_phnum,
908                                           "wine_main_preload_info" );
909     if (wine_main_preload_info) *wine_main_preload_info = preload_info;
910     else wld_printf( "wine_main_preload_info not found\n" );
911
912 #define SET_NEW_AV(n,type,val) new_av[n].a_type = (type); new_av[n].a_un.a_val = (val);
913     SET_NEW_AV( 0, AT_PHDR, (unsigned long)main_binary_map.l_phdr );
914     SET_NEW_AV( 1, AT_PHENT, sizeof(ElfW(Phdr)) );
915     SET_NEW_AV( 2, AT_PHNUM, main_binary_map.l_phnum );
916     SET_NEW_AV( 3, AT_PAGESZ, page_size );
917     SET_NEW_AV( 4, AT_BASE, ld_so_map.l_addr );
918     SET_NEW_AV( 5, AT_FLAGS, get_auxiliary( av, AT_FLAGS, 0 ) );
919     SET_NEW_AV( 6, AT_ENTRY, main_binary_map.l_entry );
920     SET_NEW_AV( 7, AT_UID, get_auxiliary( av, AT_UID, wld_getuid() ) );
921     SET_NEW_AV( 8, AT_EUID, get_auxiliary( av, AT_EUID, wld_geteuid() ) );
922     SET_NEW_AV( 9, AT_GID, get_auxiliary( av, AT_GID, wld_getgid() ) );
923     SET_NEW_AV(10, AT_EGID, get_auxiliary( av, AT_EGID, wld_getegid() ) );
924     SET_NEW_AV(11, AT_NULL, 0 );
925 #undef SET_NEW_AV
926
927     i = 0;
928     /* delete sysinfo values if addresses conflict */
929     if (is_in_preload_range( av, AT_SYSINFO )) delete_av[i++].a_type = AT_SYSINFO;
930     if (is_in_preload_range( av, AT_SYSINFO_EHDR )) delete_av[i++].a_type = AT_SYSINFO_EHDR;
931     delete_av[i].a_type = AT_NULL;
932
933     /* get rid of first argument */
934     pargc[1] = pargc[0] - 1;
935     *stack = pargc + 1;
936
937     set_auxiliary_values( av, new_av, delete_av, stack );
938
939 #ifdef DUMP_AUX_INFO
940     wld_printf("new stack = %x\n", *stack);
941     wld_printf("jumping to %x\n", ld_so_map.l_entry);
942 #endif
943
944     return (void *)ld_so_map.l_entry;
945 }