mshtml: Print wine_gecko version in load_wine_gecko.
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 #ifdef HAVE_SYS_STAT_H
72 # include <sys/stat.h>
73 #endif
74 #include <fcntl.h>
75 #ifdef HAVE_SYS_MMAN_H
76 # include <sys/mman.h>
77 #endif
78 #ifdef HAVE_SYS_SYSCALL_H
79 # include <sys/syscall.h>
80 #endif
81 #ifdef HAVE_UNISTD_H
82 # include <unistd.h>
83 #endif
84 #ifdef HAVE_ELF_H
85 # include <elf.h>
86 #endif
87 #ifdef HAVE_LINK_H
88 # include <link.h>
89 #endif
90 #ifdef HAVE_SYS_LINK_H
91 # include <sys/link.h>
92 #endif
93
94 #include "main.h"
95
96 /* ELF definitions */
97 #define ELF_PREFERRED_ADDRESS(loader, maplength, mapstartpref) (mapstartpref)
98 #define ELF_FIXED_ADDRESS(loader, mapstart) ((void) 0)
99
100 #define MAP_BASE_ADDR(l)     0
101
102 #ifndef MAP_COPY
103 #define MAP_COPY MAP_PRIVATE
104 #endif
105 #ifndef MAP_NORESERVE
106 #define MAP_NORESERVE 0
107 #endif
108
109 static struct wine_preload_info preload_info[] =
110 {
111     { (void *)0x00000000, 0x60000000 },  /* low memory area */
112     { (void *)0x7f000000, 0x02000000 },  /* top-down allocations + shared heap */
113     { 0, 0 },                            /* PE exe range set with WINEPRELOADRESERVE */
114     { 0, 0 }                             /* end of list */
115 };
116
117 /* debugging */
118 #undef DUMP_SEGMENTS
119 #undef DUMP_AUX_INFO
120 #undef DUMP_SYMS
121
122 /* older systems may not define these */
123 #ifndef PT_TLS
124 #define PT_TLS 7
125 #endif
126
127 #ifndef AT_SYSINFO
128 #define AT_SYSINFO 32
129 #endif
130 #ifndef AT_SYSINFO_EHDR
131 #define AT_SYSINFO_EHDR 33
132 #endif
133
134 #ifndef DT_GNU_HASH
135 #define DT_GNU_HASH 0x6ffffef5
136 #endif
137
138 static unsigned int page_size, page_mask;
139 static char *preloader_start, *preloader_end;
140
141 struct wld_link_map {
142     ElfW(Addr) l_addr;
143     ElfW(Dyn) *l_ld;
144     ElfW(Phdr)*l_phdr;
145     ElfW(Addr) l_entry;
146     ElfW(Half) l_ldnum;
147     ElfW(Half) l_phnum;
148     ElfW(Addr) l_map_start, l_map_end;
149     ElfW(Addr) l_interp;
150 };
151
152
153 /*
154  * The __bb_init_func is an empty function only called when file is
155  * compiled with gcc flags "-fprofile-arcs -ftest-coverage".  This
156  * function is normally provided by libc's startup files, but since we
157  * build the preloader with "-nostartfiles -nodefaultlibs", we have to
158  * provide our own (empty) version, otherwise linker fails.
159  */
160 void __bb_init_func(void) { return; }
161
162 /* similar to the above but for -fstack-protector */
163 void *__stack_chk_guard = 0;
164 void __stack_chk_fail(void) { return; }
165
166 /*
167  * The _start function is the entry and exit point of this program
168  *
169  *  It calls wld_start, passing a pointer to the args it receives
170  *  then jumps to the address wld_start returns.
171  */
172 void _start();
173 extern char _end[];
174 __ASM_GLOBAL_FUNC(_start,
175                   "\tmovl %esp,%eax\n"
176                   "\tleal -136(%esp),%esp\n"  /* allocate some space for extra aux values */
177                   "\tpushl %eax\n"            /* orig stack pointer */
178                   "\tpushl %esp\n"            /* ptr to orig stack pointer */
179                   "\tcall wld_start\n"
180                   "\tpopl %ecx\n"             /* remove ptr to stack pointer */
181                   "\tpopl %esp\n"             /* new stack pointer */
182                   "\tpush %eax\n"             /* ELF interpreter entry point */
183                   "\txor %eax,%eax\n"
184                   "\txor %ecx,%ecx\n"
185                   "\txor %edx,%edx\n"
186                   "\tret\n")
187
188 /* wrappers for Linux system calls */
189
190 #define SYSCALL_RET(ret) (((ret) < 0 && (ret) > -4096) ? -1 : (ret))
191
192 static inline __attribute__((noreturn)) void wld_exit( int code )
193 {
194     for (;;)  /* avoid warning */
195         __asm__ __volatile__( "pushl %%ebx; movl %1,%%ebx; int $0x80; popl %%ebx"
196                               : : "a" (SYS_exit), "r" (code) );
197 }
198
199 static inline int wld_open( const char *name, int flags )
200 {
201     int ret;
202     __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
203                           : "=a" (ret) : "0" (SYS_open), "r" (name), "c" (flags) );
204     return SYSCALL_RET(ret);
205 }
206
207 static inline int wld_close( int fd )
208 {
209     int ret;
210     __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
211                           : "=a" (ret) : "0" (SYS_close), "r" (fd) );
212     return SYSCALL_RET(ret);
213 }
214
215 static inline ssize_t wld_read( int fd, void *buffer, size_t len )
216 {
217     int ret;
218     __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
219                           : "=a" (ret)
220                           : "0" (SYS_read), "r" (fd), "c" (buffer), "d" (len)
221                           : "memory" );
222     return SYSCALL_RET(ret);
223 }
224
225 static inline ssize_t wld_write( int fd, const void *buffer, size_t len )
226 {
227     int ret;
228     __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
229                           : "=a" (ret) : "0" (SYS_write), "r" (fd), "c" (buffer), "d" (len) );
230     return SYSCALL_RET(ret);
231 }
232
233 static inline int wld_mprotect( const void *addr, size_t len, int prot )
234 {
235     int ret;
236     __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
237                           : "=a" (ret) : "0" (SYS_mprotect), "r" (addr), "c" (len), "d" (prot) );
238     return SYSCALL_RET(ret);
239 }
240
241 static void *wld_mmap( void *start, size_t len, int prot, int flags, int fd, off_t offset )
242 {
243     int ret;
244
245     struct
246     {
247         void        *addr;
248         unsigned int length;
249         unsigned int prot;
250         unsigned int flags;
251         unsigned int fd;
252         unsigned int offset;
253     } args;
254
255     args.addr   = start;
256     args.length = len;
257     args.prot   = prot;
258     args.flags  = flags;
259     args.fd     = fd;
260     args.offset = offset;
261     __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
262                           : "=a" (ret) : "0" (SYS_mmap), "q" (&args) : "memory" );
263     return (void *)SYSCALL_RET(ret);
264 }
265
266 static inline uid_t wld_getuid(void)
267 {
268     uid_t ret;
269     __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_getuid) );
270     return ret;
271 }
272
273 static inline uid_t wld_geteuid(void)
274 {
275     uid_t ret;
276     __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_geteuid) );
277     return ret;
278 }
279
280 static inline gid_t wld_getgid(void)
281 {
282     gid_t ret;
283     __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_getgid) );
284     return ret;
285 }
286
287 static inline gid_t wld_getegid(void)
288 {
289     gid_t ret;
290     __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_getegid) );
291     return ret;
292 }
293
294 static inline int wld_prctl( int code, int arg )
295 {
296     int ret;
297     __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
298                           : "=a" (ret) : "0" (SYS_prctl), "r" (code), "c" (arg) );
299     return SYSCALL_RET(ret);
300 }
301
302
303 /* replacement for libc functions */
304
305 static int wld_strcmp( const char *str1, const char *str2 )
306 {
307     while (*str1 && (*str1 == *str2)) { str1++; str2++; }
308     return *str1 - *str2;
309 }
310
311 static int wld_strncmp( const char *str1, const char *str2, size_t len )
312 {
313     if (len <= 0) return 0;
314     while ((--len > 0) && *str1 && (*str1 == *str2)) { str1++; str2++; }
315     return *str1 - *str2;
316 }
317
318 static inline void *wld_memset( void *dest, int val, size_t len )
319 {
320     char *dst = dest;
321     while (len--) *dst++ = val;
322     return dest;
323 }
324
325 /*
326  * wld_printf - just the basics
327  *
328  *  %x prints a hex number
329  *  %s prints a string
330  */
331 static int wld_vsprintf(char *buffer, const char *fmt, va_list args )
332 {
333     static const char hex_chars[16] = "0123456789abcdef";
334     const char *p = fmt;
335     char *str = buffer;
336
337     while( *p )
338     {
339         if( *p == '%' )
340         {
341             p++;
342             if( *p == 'x' )
343             {
344                 int i;
345                 unsigned int x = va_arg( args, unsigned int );
346                 for(i=7; i>=0; i--)
347                     *str++ = hex_chars[(x>>(i*4))&0xf];
348             }
349             else if( *p == 's' )
350             {
351                 char *s = va_arg( args, char * );
352                 while(*s)
353                     *str++ = *s++;
354             }
355             else if( *p == 0 )
356                 break;
357             p++;
358         }
359         *str++ = *p++;
360     }
361     *str = 0;
362     return str - buffer;
363 }
364
365 static void wld_printf(const char *fmt, ... )
366 {
367     va_list args;
368     char buffer[256];
369     int len;
370
371     va_start( args, fmt );
372     len = wld_vsprintf(buffer, fmt, args );
373     va_end( args );
374     wld_write(2, buffer, len);
375 }
376
377 static __attribute__((noreturn)) void fatal_error(const char *fmt, ... )
378 {
379     va_list args;
380     char buffer[256];
381     int len;
382
383     va_start( args, fmt );
384     len = wld_vsprintf(buffer, fmt, args );
385     va_end( args );
386     wld_write(2, buffer, len);
387     wld_exit(1);
388 }
389
390 #ifdef DUMP_AUX_INFO
391 /*
392  *  Dump interesting bits of the ELF auxv_t structure that is passed
393  *   as the 4th parameter to the _start function
394  */
395 static void dump_auxiliary( ElfW(auxv_t) *av )
396 {
397 #define NAME(at) { at, #at }
398     static const struct { int val; const char *name; } names[] =
399     {
400         NAME(AT_BASE),
401         NAME(AT_CLKTCK),
402         NAME(AT_EGID),
403         NAME(AT_ENTRY),
404         NAME(AT_EUID),
405         NAME(AT_FLAGS),
406         NAME(AT_GID),
407         NAME(AT_HWCAP),
408         NAME(AT_PAGESZ),
409         NAME(AT_PHDR),
410         NAME(AT_PHENT),
411         NAME(AT_PHNUM),
412         NAME(AT_PLATFORM),
413         NAME(AT_SYSINFO),
414         NAME(AT_SYSINFO_EHDR),
415         NAME(AT_UID),
416         { 0, NULL }
417     };
418 #undef NAME
419
420     int i;
421
422     for (  ; av->a_type != AT_NULL; av++)
423     {
424         for (i = 0; names[i].name; i++) if (names[i].val == av->a_type) break;
425         if (names[i].name) wld_printf("%s = %x\n", names[i].name, av->a_un.a_val);
426         else wld_printf( "%x = %x\n", av->a_type, av->a_un.a_val );
427     }
428 }
429 #endif
430
431 /*
432  * set_auxiliary_values
433  *
434  * Set the new auxiliary values
435  */
436 static void set_auxiliary_values( ElfW(auxv_t) *av, const ElfW(auxv_t) *new_av,
437                                   const ElfW(auxv_t) *delete_av, void **stack )
438 {
439     int i, j, av_count = 0, new_count = 0, delete_count = 0;
440     char *src, *dst;
441
442     /* count how many aux values we have already */
443     while (av[av_count].a_type != AT_NULL) av_count++;
444
445     /* delete unwanted values */
446     for (j = 0; delete_av[j].a_type != AT_NULL; j++)
447     {
448         for (i = 0; i < av_count; i++) if (av[i].a_type == delete_av[j].a_type)
449         {
450             av[i].a_type = av[av_count-1].a_type;
451             av[i].a_un.a_val = av[av_count-1].a_un.a_val;
452             av[--av_count].a_type = AT_NULL;
453             delete_count++;
454             break;
455         }
456     }
457
458     /* count how many values we have in new_av that aren't in av */
459     for (j = 0; new_av[j].a_type != AT_NULL; j++)
460     {
461         for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
462         if (i == av_count) new_count++;
463     }
464
465     src = (char *)*stack;
466     dst = src - (new_count - delete_count) * sizeof(*av);
467     if (new_count > delete_count)   /* need to make room for the extra values */
468     {
469         int len = (char *)(av + av_count + 1) - src;
470         for (i = 0; i < len; i++) dst[i] = src[i];
471     }
472     else if (new_count < delete_count)  /* get rid of unused values */
473     {
474         int len = (char *)(av + av_count + 1) - dst;
475         for (i = len - 1; i >= 0; i--) dst[i] = src[i];
476     }
477     *stack = dst;
478     av -= (new_count - delete_count);
479
480     /* now set the values */
481     for (j = 0; new_av[j].a_type != AT_NULL; j++)
482     {
483         for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
484         if (i < av_count) av[i].a_un.a_val = new_av[j].a_un.a_val;
485         else
486         {
487             av[av_count].a_type     = new_av[j].a_type;
488             av[av_count].a_un.a_val = new_av[j].a_un.a_val;
489             av_count++;
490         }
491     }
492
493 #ifdef DUMP_AUX_INFO
494     wld_printf("New auxiliary info:\n");
495     dump_auxiliary( av );
496 #endif
497 }
498
499 /*
500  * get_auxiliary
501  *
502  * Get a field of the auxiliary structure
503  */
504 static int get_auxiliary( ElfW(auxv_t) *av, int type, int def_val )
505 {
506   for ( ; av->a_type != AT_NULL; av++)
507       if( av->a_type == type ) return av->a_un.a_val;
508   return def_val;
509 }
510
511 /*
512  * map_so_lib
513  *
514  * modelled after _dl_map_object_from_fd() from glibc-2.3.1/elf/dl-load.c
515  *
516  * This function maps the segments from an ELF object, and optionally
517  *  stores information about the mapping into the auxv_t structure.
518  */
519 static void map_so_lib( const char *name, struct wld_link_map *l)
520 {
521     int fd;
522     unsigned char buf[0x800];
523     ElfW(Ehdr) *header = (ElfW(Ehdr)*)buf;
524     ElfW(Phdr) *phdr, *ph;
525     /* Scan the program header table, collecting its load commands.  */
526     struct loadcmd
527       {
528         ElfW(Addr) mapstart, mapend, dataend, allocend;
529         off_t mapoff;
530         int prot;
531       } loadcmds[16], *c;
532     size_t nloadcmds = 0, maplength;
533
534     fd = wld_open( name, O_RDONLY );
535     if (fd == -1) fatal_error("%s: could not open\n", name );
536
537     if (wld_read( fd, buf, sizeof(buf) ) != sizeof(buf))
538         fatal_error("%s: failed to read ELF header\n", name);
539
540     phdr = (void*) (((unsigned char*)buf) + header->e_phoff);
541
542     if( ( header->e_ident[0] != 0x7f ) ||
543         ( header->e_ident[1] != 'E' ) ||
544         ( header->e_ident[2] != 'L' ) ||
545         ( header->e_ident[3] != 'F' ) )
546         fatal_error( "%s: not an ELF binary... don't know how to load it\n", name );
547
548     if( header->e_machine != EM_386 )
549         fatal_error("%s: not an i386 ELF binary... don't know how to load it\n", name );
550
551     if (header->e_phnum > sizeof(loadcmds)/sizeof(loadcmds[0]))
552         fatal_error( "%s: oops... not enough space for load commands\n", name );
553
554     maplength = header->e_phnum * sizeof (ElfW(Phdr));
555     if (header->e_phoff + maplength > sizeof(buf))
556         fatal_error( "%s: oops... not enough space for ELF headers\n", name );
557
558     l->l_ld = 0;
559     l->l_addr = 0;
560     l->l_phdr = 0;
561     l->l_phnum = header->e_phnum;
562     l->l_entry = header->e_entry;
563     l->l_interp = 0;
564
565     for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
566     {
567
568 #ifdef DUMP_SEGMENTS
569       wld_printf( "ph = %x\n", ph );
570       wld_printf( " p_type   = %x\n", ph->p_type );
571       wld_printf( " p_flags  = %x\n", ph->p_flags );
572       wld_printf( " p_offset = %x\n", ph->p_offset );
573       wld_printf( " p_vaddr  = %x\n", ph->p_vaddr );
574       wld_printf( " p_paddr  = %x\n", ph->p_paddr );
575       wld_printf( " p_filesz = %x\n", ph->p_filesz );
576       wld_printf( " p_memsz  = %x\n", ph->p_memsz );
577       wld_printf( " p_align  = %x\n", ph->p_align );
578 #endif
579
580       switch (ph->p_type)
581         {
582           /* These entries tell us where to find things once the file's
583              segments are mapped in.  We record the addresses it says
584              verbatim, and later correct for the run-time load address.  */
585         case PT_DYNAMIC:
586           l->l_ld = (void *) ph->p_vaddr;
587           l->l_ldnum = ph->p_memsz / sizeof (Elf32_Dyn);
588           break;
589
590         case PT_PHDR:
591           l->l_phdr = (void *) ph->p_vaddr;
592           break;
593
594         case PT_LOAD:
595           {
596             if ((ph->p_align & page_mask) != 0)
597               fatal_error( "%s: ELF load command alignment not page-aligned\n", name );
598
599             if (((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1)) != 0)
600               fatal_error( "%s: ELF load command address/offset not properly aligned\n", name );
601
602             c = &loadcmds[nloadcmds++];
603             c->mapstart = ph->p_vaddr & ~(ph->p_align - 1);
604             c->mapend = ((ph->p_vaddr + ph->p_filesz + page_mask) & ~page_mask);
605             c->dataend = ph->p_vaddr + ph->p_filesz;
606             c->allocend = ph->p_vaddr + ph->p_memsz;
607             c->mapoff = ph->p_offset & ~(ph->p_align - 1);
608
609             c->prot = 0;
610             if (ph->p_flags & PF_R)
611               c->prot |= PROT_READ;
612             if (ph->p_flags & PF_W)
613               c->prot |= PROT_WRITE;
614             if (ph->p_flags & PF_X)
615               c->prot |= PROT_EXEC;
616           }
617           break;
618
619         case PT_INTERP:
620           l->l_interp = ph->p_vaddr;
621           break;
622
623         case PT_TLS:
624           /*
625            * We don't need to set anything up because we're
626            * emulating the kernel, not ld-linux.so.2
627            * The ELF loader will set up the TLS data itself.
628            */
629         case PT_SHLIB:
630         case PT_NOTE:
631         default:
632           break;
633         }
634     }
635
636     /* Now process the load commands and map segments into memory.  */
637     c = loadcmds;
638
639     /* Length of the sections to be loaded.  */
640     maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
641
642     if( header->e_type == ET_DYN )
643     {
644         ElfW(Addr) mappref;
645         mappref = (ELF_PREFERRED_ADDRESS (loader, maplength, c->mapstart)
646                    - MAP_BASE_ADDR (l));
647
648         /* Remember which part of the address space this object uses.  */
649         l->l_map_start = (ElfW(Addr)) wld_mmap ((void *) mappref, maplength,
650                                               c->prot, MAP_COPY | MAP_FILE,
651                                               fd, c->mapoff);
652         /* wld_printf("set  : offset = %x\n", c->mapoff); */
653         /* wld_printf("l->l_map_start = %x\n", l->l_map_start); */
654
655         l->l_map_end = l->l_map_start + maplength;
656         l->l_addr = l->l_map_start - c->mapstart;
657
658         wld_mprotect ((caddr_t) (l->l_addr + c->mapend),
659                     loadcmds[nloadcmds - 1].allocend - c->mapend,
660                     PROT_NONE);
661         goto postmap;
662     }
663     else
664     {
665         /* sanity check */
666         if ((char *)c->mapstart + maplength > preloader_start &&
667             (char *)c->mapstart <= preloader_end)
668             fatal_error( "%s: binary overlaps preloader (%x-%x)\n",
669                          name, c->mapstart, (char *)c->mapstart + maplength );
670
671         ELF_FIXED_ADDRESS (loader, c->mapstart);
672     }
673
674     /* Remember which part of the address space this object uses.  */
675     l->l_map_start = c->mapstart + l->l_addr;
676     l->l_map_end = l->l_map_start + maplength;
677
678     while (c < &loadcmds[nloadcmds])
679       {
680         if (c->mapend > c->mapstart)
681             /* Map the segment contents from the file.  */
682             wld_mmap ((void *) (l->l_addr + c->mapstart),
683                         c->mapend - c->mapstart, c->prot,
684                         MAP_FIXED | MAP_COPY | MAP_FILE, fd, c->mapoff);
685
686       postmap:
687         if (l->l_phdr == 0
688             && (ElfW(Off)) c->mapoff <= header->e_phoff
689             && ((size_t) (c->mapend - c->mapstart + c->mapoff)
690                 >= header->e_phoff + header->e_phnum * sizeof (ElfW(Phdr))))
691           /* Found the program header in this segment.  */
692           l->l_phdr = (void *)(unsigned int) (c->mapstart + header->e_phoff - c->mapoff);
693
694         if (c->allocend > c->dataend)
695           {
696             /* Extra zero pages should appear at the end of this segment,
697                after the data mapped from the file.   */
698             ElfW(Addr) zero, zeroend, zeropage;
699
700             zero = l->l_addr + c->dataend;
701             zeroend = l->l_addr + c->allocend;
702             zeropage = (zero + page_mask) & ~page_mask;
703
704             /*
705              * This is different from the dl-load load...
706              *  ld-linux.so.2 relies on the whole page being zero'ed
707              */
708             zeroend = (zeroend + page_mask) & ~page_mask;
709
710             if (zeroend < zeropage)
711             {
712               /* All the extra data is in the last page of the segment.
713                  We can just zero it.  */
714               zeropage = zeroend;
715             }
716
717             if (zeropage > zero)
718               {
719                 /* Zero the final part of the last page of the segment.  */
720                 if ((c->prot & PROT_WRITE) == 0)
721                   {
722                     /* Dag nab it.  */
723                     wld_mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot|PROT_WRITE);
724                   }
725                 wld_memset ((void *) zero, '\0', zeropage - zero);
726                 if ((c->prot & PROT_WRITE) == 0)
727                   wld_mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot);
728               }
729
730             if (zeroend > zeropage)
731               {
732                 /* Map the remaining zero pages in from the zero fill FD.  */
733                 caddr_t mapat;
734                 mapat = wld_mmap ((caddr_t) zeropage, zeroend - zeropage,
735                                 c->prot, MAP_ANON|MAP_PRIVATE|MAP_FIXED,
736                                 -1, 0);
737               }
738           }
739
740         ++c;
741       }
742
743     if (l->l_phdr == NULL) fatal_error("no program header\n");
744
745     l->l_phdr = (void *)((ElfW(Addr))l->l_phdr + l->l_addr);
746     l->l_entry += l->l_addr;
747
748     wld_close( fd );
749 }
750
751
752 static unsigned int elf_hash( const char *name )
753 {
754     unsigned int hi, hash = 0;
755     while (*name)
756     {
757         hash = (hash << 4) + (unsigned char)*name++;
758         hi = hash & 0xf0000000;
759         hash ^= hi;
760         hash ^= hi >> 24;
761     }
762     return hash;
763 }
764
765 static unsigned int gnu_hash( const char *name )
766 {
767     unsigned int h = 5381;
768     while (*name) h = h * 33 + (unsigned char)*name++;
769     return h;
770 }
771
772 /*
773  * Find a symbol in the symbol table of the executable loaded
774  */
775 static void *find_symbol( const ElfW(Phdr) *phdr, int num, const char *var, int type )
776 {
777     const ElfW(Dyn) *dyn = NULL;
778     const ElfW(Phdr) *ph;
779     const ElfW(Sym) *symtab = NULL;
780     const Elf_Symndx *hashtab = NULL;
781     const Elf32_Word *gnu_hashtab = NULL;
782     const char *strings = NULL;
783     Elf_Symndx idx;
784
785     /* check the values */
786 #ifdef DUMP_SYMS
787     wld_printf("%x %x\n", phdr, num );
788 #endif
789     if( ( phdr == NULL ) || ( num == 0 ) )
790     {
791         wld_printf("could not find PT_DYNAMIC header entry\n");
792         return NULL;
793     }
794
795     /* parse the (already loaded) ELF executable's header */
796     for (ph = phdr; ph < &phdr[num]; ++ph)
797     {
798         if( PT_DYNAMIC == ph->p_type )
799         {
800             dyn = (void *) ph->p_vaddr;
801             num = ph->p_memsz / sizeof (Elf32_Dyn);
802             break;
803         }
804     }
805     if( !dyn ) return NULL;
806
807     while( dyn->d_tag )
808     {
809         if( dyn->d_tag == DT_STRTAB )
810             strings = (const char*) dyn->d_un.d_ptr;
811         if( dyn->d_tag == DT_SYMTAB )
812             symtab = (const ElfW(Sym) *)dyn->d_un.d_ptr;
813         if( dyn->d_tag == DT_HASH )
814             hashtab = (const Elf_Symndx *)dyn->d_un.d_ptr;
815         if( dyn->d_tag == DT_GNU_HASH )
816             gnu_hashtab = (const Elf32_Word *)dyn->d_un.d_ptr;
817 #ifdef DUMP_SYMS
818         wld_printf("%x %x\n", dyn->d_tag, dyn->d_un.d_ptr );
819 #endif
820         dyn++;
821     }
822
823     if( (!symtab) || (!strings) ) return NULL;
824
825     if (gnu_hashtab)  /* new style hash table */
826     {
827         const unsigned int hash   = gnu_hash(var);
828         const Elf32_Word nbuckets = gnu_hashtab[0];
829         const Elf32_Word symbias  = gnu_hashtab[1];
830         const Elf32_Word nwords   = gnu_hashtab[2];
831         const ElfW(Addr) *bitmask = (const ElfW(Addr) *)(gnu_hashtab + 4);
832         const Elf32_Word *buckets = (const Elf32_Word *)(bitmask + nwords);
833         const Elf32_Word *chains  = buckets + nbuckets - symbias;
834
835         if (!(idx = buckets[hash % nbuckets])) return NULL;
836         do
837         {
838             if ((chains[idx] & ~1u) == (hash & ~1u) &&
839                 symtab[idx].st_info == ELF32_ST_INFO( STB_GLOBAL, type ) &&
840                 !wld_strcmp( strings + symtab[idx].st_name, var ))
841                 goto found;
842         } while (!(chains[idx++] & 1u));
843     }
844     else if (hashtab)  /* old style hash table */
845     {
846         const unsigned int hash   = elf_hash(var);
847         const Elf_Symndx nbuckets = hashtab[0];
848         const Elf_Symndx *buckets = hashtab + 2;
849         const Elf_Symndx *chains  = buckets + nbuckets;
850
851         for (idx = buckets[hash % nbuckets]; idx != STN_UNDEF; idx = chains[idx])
852         {
853             if (symtab[idx].st_info == ELF32_ST_INFO( STB_GLOBAL, type ) &&
854                 !wld_strcmp( strings + symtab[idx].st_name, var ))
855                 goto found;
856         }
857     }
858     return NULL;
859
860 found:
861 #ifdef DUMP_SYMS
862     wld_printf("Found %s -> %x\n", strings + symtab[idx].st_name, symtab[idx].st_value );
863 #endif
864     return (void *)symtab[idx].st_value;
865 }
866
867 /*
868  *  preload_reserve
869  *
870  * Reserve a range specified in string format
871  */
872 static void preload_reserve( const char *str )
873 {
874     const char *p;
875     unsigned long result = 0;
876     void *start = NULL, *end = NULL;
877     int first = 1;
878
879     for (p = str; *p; p++)
880     {
881         if (*p >= '0' && *p <= '9') result = result * 16 + *p - '0';
882         else if (*p >= 'a' && *p <= 'f') result = result * 16 + *p - 'a' + 10;
883         else if (*p >= 'A' && *p <= 'F') result = result * 16 + *p - 'A' + 10;
884         else if (*p == '-')
885         {
886             if (!first) goto error;
887             start = (void *)(result & ~page_mask);
888             result = 0;
889             first = 0;
890         }
891         else goto error;
892     }
893     if (!first) end = (void *)((result + page_mask) & ~page_mask);
894     else if (result) goto error;  /* single value '0' is allowed */
895
896     /* sanity checks */
897     if (end <= start) start = end = NULL;
898     else if ((char *)end > preloader_start &&
899              (char *)start <= preloader_end)
900     {
901         wld_printf( "WINEPRELOADRESERVE range %x-%x overlaps preloader %x-%x\n",
902                      start, end, preloader_start, preloader_end );
903         start = end = NULL;
904     }
905
906     /* check for overlap with low memory area */
907     if ((char *)end <= (char *)preload_info[0].addr + preload_info[0].size)
908         start = end = NULL;
909     else if ((char *)start < (char *)preload_info[0].addr + preload_info[0].size)
910         start = (char *)preload_info[0].addr + preload_info[0].size;
911
912     /* entry 2 is for the PE exe */
913     preload_info[2].addr = start;
914     preload_info[2].size = (char *)end - (char *)start;
915     return;
916
917 error:
918     fatal_error( "invalid WINEPRELOADRESERVE value '%s'\n", str );
919 }
920
921 /*
922  *  is_in_preload_range
923  *
924  * Check if address of the given aux value is in one of the reserved ranges
925  */
926 static int is_in_preload_range( const ElfW(auxv_t) *av, int type )
927 {
928     int i;
929
930     while (av->a_type != type && av->a_type != AT_NULL) av++;
931
932     if (av->a_type == type)
933     {
934         for (i = 0; preload_info[i].size; i++)
935         {
936             if ((char *)av->a_un.a_val >= (char *)preload_info[i].addr &&
937                 (char *)av->a_un.a_val < (char *)preload_info[i].addr + preload_info[i].size)
938                 return 1;
939         }
940     }
941     return 0;
942 }
943
944 /* set the process name if supported */
945 static void set_process_name( int argc, char *argv[] )
946 {
947     unsigned int i, off;
948     char *p, *name, *end;
949
950     /* set the process short name */
951     for (p = name = argv[1]; *p; p++) if (p[0] == '/' && p[1]) name = p + 1;
952     if (wld_prctl( 15 /* PR_SET_NAME */, (int)name ) == -1) return;
953
954     /* find the end of the argv array and move everything down */
955     end = argv[argc - 1];
956     while (*end) end++;
957     off = argv[1] - argv[0];
958     for (p = argv[1]; p <= end; p++) *(p - off) = *p;
959     wld_memset( end - off, 0, off );
960     for (i = 1; i < argc; i++) argv[i] -= off;
961 }
962
963
964 /*
965  *  wld_start
966  *
967  *  Repeat the actions the kernel would do when loading a dynamically linked .so
968  *  Load the binary and then its ELF interpreter.
969  *  Note, we assume that the binary is a dynamically linked ELF shared object.
970  */
971 void* wld_start( void **stack )
972 {
973     int i, *pargc;
974     char **argv, **p;
975     char *interp, *reserve = NULL;
976     ElfW(auxv_t) new_av[12], delete_av[3], *av;
977     struct wld_link_map main_binary_map, ld_so_map;
978     struct wine_preload_info **wine_main_preload_info;
979
980     pargc = *stack;
981     argv = (char **)pargc + 1;
982     if (*pargc < 2) fatal_error( "Usage: %s wine_binary [args]\n", argv[0] );
983
984     /* skip over the parameters */
985     p = argv + *pargc + 1;
986
987     /* skip over the environment */
988     while (*p)
989     {
990         static const char res[] = "WINEPRELOADRESERVE=";
991         if (!wld_strncmp( *p, res, sizeof(res)-1 )) reserve = *p + sizeof(res) - 1;
992         p++;
993     }
994
995     av = (ElfW(auxv_t)*) (p+1);
996     page_size = get_auxiliary( av, AT_PAGESZ, 4096 );
997     page_mask = page_size - 1;
998
999     preloader_start = (char *)_start - ((unsigned int)_start & page_mask);
1000     preloader_end = (char *)((unsigned int)(_end + page_mask) & ~page_mask);
1001
1002 #ifdef DUMP_AUX_INFO
1003     wld_printf( "stack = %x\n", *stack );
1004     for( i = 0; i < *pargc; i++ ) wld_printf("argv[%x] = %s\n", i, argv[i]);
1005     dump_auxiliary( av );
1006 #endif
1007
1008     /* reserve memory that Wine needs */
1009     if (reserve) preload_reserve( reserve );
1010     for (i = 0; preload_info[i].size; i++)
1011         wld_mmap( preload_info[i].addr, preload_info[i].size,
1012                   PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, -1, 0 );
1013
1014     /* add an executable page at the top of the address space to defeat
1015      * broken no-exec protections that play with the code selector limit */
1016     wld_mprotect( (char *)0x80000000 - page_size, page_size, PROT_EXEC | PROT_READ );
1017
1018     /* load the main binary */
1019     map_so_lib( argv[1], &main_binary_map );
1020
1021     /* load the ELF interpreter */
1022     interp = (char *)main_binary_map.l_addr + main_binary_map.l_interp;
1023     map_so_lib( interp, &ld_so_map );
1024
1025     /* store pointer to the preload info into the appropriate main binary variable */
1026     wine_main_preload_info = find_symbol( main_binary_map.l_phdr, main_binary_map.l_phnum,
1027                                           "wine_main_preload_info", STT_OBJECT );
1028     if (wine_main_preload_info) *wine_main_preload_info = preload_info;
1029     else wld_printf( "wine_main_preload_info not found\n" );
1030
1031 #define SET_NEW_AV(n,type,val) new_av[n].a_type = (type); new_av[n].a_un.a_val = (val);
1032     SET_NEW_AV( 0, AT_PHDR, (unsigned long)main_binary_map.l_phdr );
1033     SET_NEW_AV( 1, AT_PHENT, sizeof(ElfW(Phdr)) );
1034     SET_NEW_AV( 2, AT_PHNUM, main_binary_map.l_phnum );
1035     SET_NEW_AV( 3, AT_PAGESZ, page_size );
1036     SET_NEW_AV( 4, AT_BASE, ld_so_map.l_addr );
1037     SET_NEW_AV( 5, AT_FLAGS, get_auxiliary( av, AT_FLAGS, 0 ) );
1038     SET_NEW_AV( 6, AT_ENTRY, main_binary_map.l_entry );
1039     SET_NEW_AV( 7, AT_UID, get_auxiliary( av, AT_UID, wld_getuid() ) );
1040     SET_NEW_AV( 8, AT_EUID, get_auxiliary( av, AT_EUID, wld_geteuid() ) );
1041     SET_NEW_AV( 9, AT_GID, get_auxiliary( av, AT_GID, wld_getgid() ) );
1042     SET_NEW_AV(10, AT_EGID, get_auxiliary( av, AT_EGID, wld_getegid() ) );
1043     SET_NEW_AV(11, AT_NULL, 0 );
1044 #undef SET_NEW_AV
1045
1046     i = 0;
1047     /* delete sysinfo values if addresses conflict */
1048     if (is_in_preload_range( av, AT_SYSINFO )) delete_av[i++].a_type = AT_SYSINFO;
1049     if (is_in_preload_range( av, AT_SYSINFO_EHDR )) delete_av[i++].a_type = AT_SYSINFO_EHDR;
1050     delete_av[i].a_type = AT_NULL;
1051
1052     /* get rid of first argument */
1053     set_process_name( *pargc, argv );
1054     pargc[1] = pargc[0] - 1;
1055     *stack = pargc + 1;
1056
1057     set_auxiliary_values( av, new_av, delete_av, stack );
1058
1059 #ifdef DUMP_AUX_INFO
1060     wld_printf("new stack = %x\n", *stack);
1061     wld_printf("jumping to %x\n", ld_so_map.l_entry);
1062 #endif
1063
1064     return (void *)ld_so_map.l_entry;
1065 }