~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Wine Cross Reference
wine/loader/preloader.c

Version: ~ [ wine-1.1.1 ] ~ [ wine-1.1.0 ] ~ [ wine-1.0 ] ~ [ wine-1.0-rc5 ] ~ [ wine-1.0-rc4 ] ~ [ wine-1.0-rc3 ] ~ [ wine-1.0-rc2 ] ~ [ wine-1.0-rc1 ] ~ [ wine-0.9.61 ] ~ [ wine-0.9.60 ] ~ [ wine-0.9.59 ] ~ [ wine-0.9.58 ] ~ [ wine-0.9.57 ] ~ [ wine-0.9.56 ] ~ [ wine-0.9.55 ] ~ [ wine-0.9.54 ] ~ [ wine-0.9.53 ] ~ [ wine-0.9.52 ] ~ [ wine-0.9.51 ] ~ [ wine-0.9.50 ] ~ [ wine-0.9.49 ] ~ [ wine-0.9.48 ] ~ [ wine-0.9.47 ] ~ [ wine-0.9.46 ] ~ [ wine-0.9.45 ] ~ [ wine-0.9.44 ] ~ [ wine-0.9.43 ] ~ [ wine-0.9.42 ] ~ [ wine-0.9.41 ] ~ [ wine-0.9.40 ] ~ [ wine-0.9.39 ] ~ [ wine-0.9.38 ] ~ [ wine-0.9.37 ] ~ [ wine-0.9.36 ] ~ [ wine-0.9.35 ] ~ [ wine-0.9.34 ] ~ [ wine-0.9.33 ] ~ [ wine-0.9.32 ] ~ [ wine-0.9.31 ] ~ [ wine-0.9.30 ] ~ [ wine-0.9.29 ] ~ [ wine-0.9.28 ] ~ [ wine-0.9.27 ] ~ [ wine-0.9.26 ] ~ [ wine-0.9.25 ] ~ [ wine-0.9.24 ] ~ [ wine-0.9.23 ] ~ [ wine-0.9.22 ] ~ [ wine-0.9.21 ] ~ [ wine-0.9.20 ] ~ [ wine-0.9.19 ] ~ [ wine-0.9.18 ] ~ [ wine-0.9.17 ] ~ [ wine-0.9.16 ] ~ [ wine-0.9.15 ] ~ [ wine-0.9.14 ] ~ [ wine-0.9.13 ] ~ [ wine-0.9.12 ] ~ [ wine-0.9.11 ] ~ [ wine-0.9.10 ] ~ [ wine-0.9.9 ] ~ [ wine-0.9.8 ] ~ [ wine-0.9.7 ] ~ [ wine-0.9.6 ] ~ [ wine-0.9.5 ] ~ [ wine-0.9.4 ] ~ [ wine-0.9.3 ] ~ [ wine-0.9.2 ] ~ [ wine-0.9.1 ] ~ [ wine-0.9 ] ~ [ wine20050930 ] ~ [ wine20050830 ] ~ [ wine20050725 ] ~ [ wine20050628 ] ~ [ wine20050524 ] ~ [ wine20050419 ] ~ [ wine20050310 ] ~ [ wine20050211 ] ~ [ wine20050111 ] ~ [ wine20041201 ] ~ [ wine20041019 ] ~ [ wine20040914 ] ~ [ wine20040813 ] ~ [ wine20040716 ] ~ [ wine20040615 ] ~ [ wine20040505 ] ~ [ wine20040408 ] ~ [ wine20040309 ] ~ [ wine20040213 ] ~ [ wine20040121 ] ~ [ wine20031212 ] ~ [ wine20031118 ] ~ [ wine20031016 ] ~ [ wine20030911 ] ~ [ wine20030813 ] ~ [ wine20030709 ] ~ [ wine20030618 ] ~ [ wine20030508 ] ~ [ wine20030408 ] ~ [ wine20030318 ] ~ [ wine20030219 ] ~ [ wine20030115 ] ~ [ wine20021219 ] ~ [ wine20021125 ] ~ [ wine20021031 ] ~ [ wine20021007 ] ~ [ wine20020904 ] ~ [ wine20020804 ] ~ [ wine20020710 ] ~ [ wine20020605 ] ~ [ wine20020509 ] ~ [ wine20020411 ] ~ [ wine20020310 ] ~ [ wine20020228 ] ~ [ wine20011226 ] ~ [ wine20011108 ] ~ [ wine20011004 ] ~ [ wine20010824 ] ~ [ wine20010731 ] ~ [ wine20010629 ] ~ [ wine20010510 ] ~ [ wine20010418 ] ~ [ wine20010326 ] ~ [ wine20010305 ] ~ [ wine20010216 ] ~ [ wine20010112 ] ~ [ wine20001222 ] ~ [ wine20001202 ] ~ [ wine20001026 ] ~ [ wine20001002 ] ~ [ wine20000909 ] ~ [ wine20000821 ] ~ [ wine20000801 ] ~ [ wine20000716 ] ~ [ wine20000326 ] ~ [ wine20000227 ] ~ [ wine20000130 ] ~ [ wine20000109 ] ~

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