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