Changes in crossover-wine-src-6.1.0 except for configure
[wine/hacks.git] / loader / preloader.c
blobb7043bd0e893da4cde5d4921789214ffb2be950f
1 /*
2 * Preloader for ld.so
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
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.
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.
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
24 * Design notes
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.
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.
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.
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)
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.
48 * References (things I consulted to understand how ELF loading works):
50 * glibc 2.3.2 elf/dl-load.c
51 * http://www.gnu.org/directory/glibc.html
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
56 * Userland exec, by <grugq@hcunix.net>
57 * http://cert.uni-stuttgart.de/archive/bugtraq/2004/01/msg00002.html
59 * The ELF specification:
60 * http://www.linuxbase.org/spec/booksets/LSB-Embedded/LSB-Embedded/book387.html
63 #include "config.h"
64 #include "wine/port.h"
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
94 #include "main.h"
96 /* ELF definitions */
97 #define ELF_PREFERRED_ADDRESS(loader, maplength, mapstartpref) (mapstartpref)
98 #define ELF_FIXED_ADDRESS(loader, mapstart) ((void) 0)
100 #define MAP_BASE_ADDR(l) 0
102 #ifndef MAP_COPY
103 #define MAP_COPY MAP_PRIVATE
104 #endif
105 #ifndef MAP_NORESERVE
106 #define MAP_NORESERVE 0
107 #endif
109 static struct wine_preload_info preload_info[] =
111 { (void *)0x00000000, 0x68000000 }, /* 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 */
117 /* debugging */
118 #undef DUMP_SEGMENTS
119 #undef DUMP_AUX_INFO
120 #undef DUMP_SYMS
122 /* older systems may not define these */
123 #ifndef PT_TLS
124 #define PT_TLS 7
125 #endif
127 #ifndef AT_SYSINFO
128 #define AT_SYSINFO 32
129 #endif
130 #ifndef AT_SYSINFO_EHDR
131 #define AT_SYSINFO_EHDR 33
132 #endif
134 #ifndef DT_GNU_HASH
135 #define DT_GNU_HASH 0x6ffffef5
136 #endif
138 static unsigned int page_size, page_mask;
139 static char *preloader_start, *preloader_end;
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;
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.
160 void __bb_init_func(void) { return; }
162 /* similar to the above but for -fstack-protector */
163 void *__stack_chk_guard = 0;
164 void __stack_chk_fail(void) { return; }
166 /* data for setting up the glibc-style thread-local storage in %gs */
168 static int thread_data[256];
170 struct
172 /* this is the kernel modify_ldt struct */
173 unsigned int entry_number;
174 unsigned long base_addr;
175 unsigned int limit;
176 unsigned int seg_32bit : 1;
177 unsigned int contents : 2;
178 unsigned int read_exec_only : 1;
179 unsigned int limit_in_pages : 1;
180 unsigned int seg_not_present : 1;
181 unsigned int useable : 1;
182 unsigned int garbage : 25;
183 } thread_ldt = { -1, (unsigned long)thread_data, 0xfffff, 1, 0, 0, 1, 0, 1, 0 };
187 * The _start function is the entry and exit point of this program
189 * It calls wld_start, passing a pointer to the args it receives
190 * then jumps to the address wld_start returns.
192 void _start();
193 extern char _end[];
194 __ASM_GLOBAL_FUNC(_start,
195 "\tmovl $243,%eax\n" /* SYS_set_thread_area */
196 "\tmovl $thread_ldt,%ebx\n"
197 "\tint $0x80\n" /* allocate gs segment */
198 "\torl %eax,%eax\n"
199 "\tjl 1f\n"
200 "\tmovl thread_ldt,%eax\n" /* thread_ldt.entry_number */
201 "\tshl $3,%eax\n"
202 "\torl $3,%eax\n"
203 "\tmov %ax,%gs\n"
204 "\tmov %ax,%fs\n" /* set %fs too so libwine can retrieve it later on */
205 "1:\tmovl %esp,%eax\n"
206 "\tleal -136(%esp),%esp\n" /* allocate some space for extra aux values */
207 "\tpushl %eax\n" /* orig stack pointer */
208 "\tpushl %esp\n" /* ptr to orig stack pointer */
209 "\tcall wld_start\n"
210 "\tpopl %ecx\n" /* remove ptr to stack pointer */
211 "\tpopl %esp\n" /* new stack pointer */
212 "\tpush %eax\n" /* ELF interpreter entry point */
213 "\txor %eax,%eax\n"
214 "\txor %ecx,%ecx\n"
215 "\txor %edx,%edx\n"
216 "\tmov %ax,%gs\n" /* clear %gs again */
217 "\tret\n")
219 /* wrappers for Linux system calls */
221 #define SYSCALL_RET(ret) (((ret) < 0 && (ret) > -4096) ? -1 : (ret))
223 static inline __attribute__((noreturn)) void wld_exit( int code )
225 for (;;) /* avoid warning */
226 __asm__ __volatile__( "pushl %%ebx; movl %1,%%ebx; int $0x80; popl %%ebx"
227 : : "a" (SYS_exit), "r" (code) );
230 static inline int wld_open( const char *name, int flags )
232 int ret;
233 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
234 : "=a" (ret) : "0" (SYS_open), "r" (name), "c" (flags) );
235 return SYSCALL_RET(ret);
238 static inline int wld_close( int fd )
240 int ret;
241 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
242 : "=a" (ret) : "0" (SYS_close), "r" (fd) );
243 return SYSCALL_RET(ret);
246 static inline ssize_t wld_read( int fd, void *buffer, size_t len )
248 int ret;
249 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
250 : "=a" (ret)
251 : "0" (SYS_read), "r" (fd), "c" (buffer), "d" (len)
252 : "memory" );
253 return SYSCALL_RET(ret);
256 static inline ssize_t wld_write( int fd, const void *buffer, size_t len )
258 int ret;
259 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
260 : "=a" (ret) : "0" (SYS_write), "r" (fd), "c" (buffer), "d" (len) );
261 return SYSCALL_RET(ret);
264 static inline int wld_mprotect( const void *addr, size_t len, int prot )
266 int ret;
267 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
268 : "=a" (ret) : "0" (SYS_mprotect), "r" (addr), "c" (len), "d" (prot) );
269 return SYSCALL_RET(ret);
272 static void *wld_mmap( void *start, size_t len, int prot, int flags, int fd, off_t offset )
274 int ret;
276 struct
278 void *addr;
279 unsigned int length;
280 unsigned int prot;
281 unsigned int flags;
282 unsigned int fd;
283 unsigned int offset;
284 } args;
286 args.addr = start;
287 args.length = len;
288 args.prot = prot;
289 args.flags = flags;
290 args.fd = fd;
291 args.offset = offset;
292 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
293 : "=a" (ret) : "0" (SYS_mmap), "q" (&args) : "memory" );
294 return (void *)SYSCALL_RET(ret);
297 static inline uid_t wld_getuid(void)
299 uid_t ret;
300 __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_getuid) );
301 return ret;
304 static inline uid_t wld_geteuid(void)
306 uid_t ret;
307 __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_geteuid) );
308 return ret;
311 static inline gid_t wld_getgid(void)
313 gid_t ret;
314 __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_getgid) );
315 return ret;
318 static inline gid_t wld_getegid(void)
320 gid_t ret;
321 __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_getegid) );
322 return ret;
325 static inline int wld_prctl( int code, int arg )
327 int ret;
328 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
329 : "=a" (ret) : "0" (SYS_prctl), "r" (code), "c" (arg) );
330 return SYSCALL_RET(ret);
334 /* replacement for libc functions */
336 static int wld_strcmp( const char *str1, const char *str2 )
338 while (*str1 && (*str1 == *str2)) { str1++; str2++; }
339 return *str1 - *str2;
342 static int wld_strncmp( const char *str1, const char *str2, size_t len )
344 if (len <= 0) return 0;
345 while ((--len > 0) && *str1 && (*str1 == *str2)) { str1++; str2++; }
346 return *str1 - *str2;
349 static inline void *wld_memset( void *dest, int val, size_t len )
351 char *dst = dest;
352 while (len--) *dst++ = val;
353 return dest;
357 * wld_printf - just the basics
359 * %x prints a hex number
360 * %s prints a string
361 * %p prints a pointer
363 static int wld_vsprintf(char *buffer, const char *fmt, va_list args )
365 static const char hex_chars[16] = "0123456789abcdef";
366 const char *p = fmt;
367 char *str = buffer;
368 int i;
370 while( *p )
372 if( *p == '%' )
374 p++;
375 if( *p == 'x' )
377 unsigned int x = va_arg( args, unsigned int );
378 for(i=7; i>=0; i--)
379 *str++ = hex_chars[(x>>(i*4))&0xf];
381 else if (p[0] == 'l' && p[1] == 'x')
383 unsigned long x = va_arg( args, unsigned long );
384 for(i=7; i>=0; i--)
385 *str++ = hex_chars[(x>>(i*4))&0xf];
386 p++;
388 else if( *p == 'p' )
390 unsigned long x = (unsigned long)va_arg( args, void * );
391 for(i=7; i>=0; i--)
392 *str++ = hex_chars[(x>>(i*4))&0xf];
394 else if( *p == 's' )
396 char *s = va_arg( args, char * );
397 while(*s)
398 *str++ = *s++;
400 else if( *p == 0 )
401 break;
402 p++;
404 *str++ = *p++;
406 *str = 0;
407 return str - buffer;
410 static __attribute__((format(printf,1,2))) void wld_printf(const char *fmt, ... )
412 va_list args;
413 char buffer[256];
414 int len;
416 va_start( args, fmt );
417 len = wld_vsprintf(buffer, fmt, args );
418 va_end( args );
419 wld_write(2, buffer, len);
422 static __attribute__((noreturn,format(printf,1,2))) void fatal_error(const char *fmt, ... )
424 va_list args;
425 char buffer[256];
426 int len;
428 va_start( args, fmt );
429 len = wld_vsprintf(buffer, fmt, args );
430 va_end( args );
431 wld_write(2, buffer, len);
432 wld_exit(1);
435 #ifdef DUMP_AUX_INFO
437 * Dump interesting bits of the ELF auxv_t structure that is passed
438 * as the 4th parameter to the _start function
440 static void dump_auxiliary( ElfW(auxv_t) *av )
442 #define NAME(at) { at, #at }
443 static const struct { int val; const char *name; } names[] =
445 NAME(AT_BASE),
446 NAME(AT_CLKTCK),
447 NAME(AT_EGID),
448 NAME(AT_ENTRY),
449 NAME(AT_EUID),
450 NAME(AT_FLAGS),
451 NAME(AT_GID),
452 NAME(AT_HWCAP),
453 NAME(AT_PAGESZ),
454 NAME(AT_PHDR),
455 NAME(AT_PHENT),
456 NAME(AT_PHNUM),
457 NAME(AT_PLATFORM),
458 NAME(AT_SYSINFO),
459 NAME(AT_SYSINFO_EHDR),
460 NAME(AT_UID),
461 { 0, NULL }
463 #undef NAME
465 int i;
467 for ( ; av->a_type != AT_NULL; av++)
469 for (i = 0; names[i].name; i++) if (names[i].val == av->a_type) break;
470 if (names[i].name) wld_printf("%s = %lx\n", names[i].name, av->a_un.a_val);
471 else wld_printf( "%x = %lx\n", av->a_type, av->a_un.a_val );
474 #endif
477 * set_auxiliary_values
479 * Set the new auxiliary values
481 static void set_auxiliary_values( ElfW(auxv_t) *av, const ElfW(auxv_t) *new_av,
482 const ElfW(auxv_t) *delete_av, void **stack )
484 int i, j, av_count = 0, new_count = 0, delete_count = 0;
485 char *src, *dst;
487 /* count how many aux values we have already */
488 while (av[av_count].a_type != AT_NULL) av_count++;
490 /* delete unwanted values */
491 for (j = 0; delete_av[j].a_type != AT_NULL; j++)
493 for (i = 0; i < av_count; i++) if (av[i].a_type == delete_av[j].a_type)
495 av[i].a_type = av[av_count-1].a_type;
496 av[i].a_un.a_val = av[av_count-1].a_un.a_val;
497 av[--av_count].a_type = AT_NULL;
498 delete_count++;
499 break;
503 /* count how many values we have in new_av that aren't in av */
504 for (j = 0; new_av[j].a_type != AT_NULL; j++)
506 for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
507 if (i == av_count) new_count++;
510 src = (char *)*stack;
511 dst = src - (new_count - delete_count) * sizeof(*av);
512 if (new_count > delete_count) /* need to make room for the extra values */
514 int len = (char *)(av + av_count + 1) - src;
515 for (i = 0; i < len; i++) dst[i] = src[i];
517 else if (new_count < delete_count) /* get rid of unused values */
519 int len = (char *)(av + av_count + 1) - dst;
520 for (i = len - 1; i >= 0; i--) dst[i] = src[i];
522 *stack = dst;
523 av -= (new_count - delete_count);
525 /* now set the values */
526 for (j = 0; new_av[j].a_type != AT_NULL; j++)
528 for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
529 if (i < av_count) av[i].a_un.a_val = new_av[j].a_un.a_val;
530 else
532 av[av_count].a_type = new_av[j].a_type;
533 av[av_count].a_un.a_val = new_av[j].a_un.a_val;
534 av_count++;
538 #ifdef DUMP_AUX_INFO
539 wld_printf("New auxiliary info:\n");
540 dump_auxiliary( av );
541 #endif
545 * get_auxiliary
547 * Get a field of the auxiliary structure
549 static int get_auxiliary( ElfW(auxv_t) *av, int type, int def_val )
551 for ( ; av->a_type != AT_NULL; av++)
552 if( av->a_type == type ) return av->a_un.a_val;
553 return def_val;
557 * map_so_lib
559 * modelled after _dl_map_object_from_fd() from glibc-2.3.1/elf/dl-load.c
561 * This function maps the segments from an ELF object, and optionally
562 * stores information about the mapping into the auxv_t structure.
564 static void map_so_lib( const char *name, struct wld_link_map *l)
566 int fd;
567 unsigned char buf[0x800];
568 ElfW(Ehdr) *header = (ElfW(Ehdr)*)buf;
569 ElfW(Phdr) *phdr, *ph;
570 /* Scan the program header table, collecting its load commands. */
571 struct loadcmd
573 ElfW(Addr) mapstart, mapend, dataend, allocend;
574 off_t mapoff;
575 int prot;
576 } loadcmds[16], *c;
577 size_t nloadcmds = 0, maplength;
579 fd = wld_open( name, O_RDONLY );
580 if (fd == -1) fatal_error("%s: could not open\n", name );
582 if (wld_read( fd, buf, sizeof(buf) ) != sizeof(buf))
583 fatal_error("%s: failed to read ELF header\n", name);
585 phdr = (void*) (((unsigned char*)buf) + header->e_phoff);
587 if( ( header->e_ident[0] != 0x7f ) ||
588 ( header->e_ident[1] != 'E' ) ||
589 ( header->e_ident[2] != 'L' ) ||
590 ( header->e_ident[3] != 'F' ) )
591 fatal_error( "%s: not an ELF binary... don't know how to load it\n", name );
593 if( header->e_machine != EM_386 )
594 fatal_error("%s: not an i386 ELF binary... don't know how to load it\n", name );
596 if (header->e_phnum > sizeof(loadcmds)/sizeof(loadcmds[0]))
597 fatal_error( "%s: oops... not enough space for load commands\n", name );
599 maplength = header->e_phnum * sizeof (ElfW(Phdr));
600 if (header->e_phoff + maplength > sizeof(buf))
601 fatal_error( "%s: oops... not enough space for ELF headers\n", name );
603 l->l_ld = 0;
604 l->l_addr = 0;
605 l->l_phdr = 0;
606 l->l_phnum = header->e_phnum;
607 l->l_entry = header->e_entry;
608 l->l_interp = 0;
610 for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
613 #ifdef DUMP_SEGMENTS
614 wld_printf( "ph = %p\n", ph );
615 wld_printf( " p_type = %x\n", ph->p_type );
616 wld_printf( " p_flags = %x\n", ph->p_flags );
617 wld_printf( " p_offset = %x\n", ph->p_offset );
618 wld_printf( " p_vaddr = %x\n", ph->p_vaddr );
619 wld_printf( " p_paddr = %x\n", ph->p_paddr );
620 wld_printf( " p_filesz = %x\n", ph->p_filesz );
621 wld_printf( " p_memsz = %x\n", ph->p_memsz );
622 wld_printf( " p_align = %x\n", ph->p_align );
623 #endif
625 switch (ph->p_type)
627 /* These entries tell us where to find things once the file's
628 segments are mapped in. We record the addresses it says
629 verbatim, and later correct for the run-time load address. */
630 case PT_DYNAMIC:
631 l->l_ld = (void *) ph->p_vaddr;
632 l->l_ldnum = ph->p_memsz / sizeof (Elf32_Dyn);
633 break;
635 case PT_PHDR:
636 l->l_phdr = (void *) ph->p_vaddr;
637 break;
639 case PT_LOAD:
641 if ((ph->p_align & page_mask) != 0)
642 fatal_error( "%s: ELF load command alignment not page-aligned\n", name );
644 if (((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1)) != 0)
645 fatal_error( "%s: ELF load command address/offset not properly aligned\n", name );
647 c = &loadcmds[nloadcmds++];
648 c->mapstart = ph->p_vaddr & ~(ph->p_align - 1);
649 c->mapend = ((ph->p_vaddr + ph->p_filesz + page_mask) & ~page_mask);
650 c->dataend = ph->p_vaddr + ph->p_filesz;
651 c->allocend = ph->p_vaddr + ph->p_memsz;
652 c->mapoff = ph->p_offset & ~(ph->p_align - 1);
654 c->prot = 0;
655 if (ph->p_flags & PF_R)
656 c->prot |= PROT_READ;
657 if (ph->p_flags & PF_W)
658 c->prot |= PROT_WRITE;
659 if (ph->p_flags & PF_X)
660 c->prot |= PROT_EXEC;
662 break;
664 case PT_INTERP:
665 l->l_interp = ph->p_vaddr;
666 break;
668 case PT_TLS:
670 * We don't need to set anything up because we're
671 * emulating the kernel, not ld-linux.so.2
672 * The ELF loader will set up the TLS data itself.
674 case PT_SHLIB:
675 case PT_NOTE:
676 default:
677 break;
681 /* Now process the load commands and map segments into memory. */
682 c = loadcmds;
684 /* Length of the sections to be loaded. */
685 maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
687 if( header->e_type == ET_DYN )
689 ElfW(Addr) mappref;
690 mappref = (ELF_PREFERRED_ADDRESS (loader, maplength, c->mapstart)
691 - MAP_BASE_ADDR (l));
693 /* Remember which part of the address space this object uses. */
694 l->l_map_start = (ElfW(Addr)) wld_mmap ((void *) mappref, maplength,
695 c->prot, MAP_COPY | MAP_FILE,
696 fd, c->mapoff);
697 /* wld_printf("set : offset = %x\n", c->mapoff); */
698 /* wld_printf("l->l_map_start = %x\n", l->l_map_start); */
700 l->l_map_end = l->l_map_start + maplength;
701 l->l_addr = l->l_map_start - c->mapstart;
703 wld_mprotect ((caddr_t) (l->l_addr + c->mapend),
704 loadcmds[nloadcmds - 1].allocend - c->mapend,
705 PROT_NONE);
706 goto postmap;
708 else
710 /* sanity check */
711 if ((char *)c->mapstart + maplength > preloader_start &&
712 (char *)c->mapstart <= preloader_end)
713 fatal_error( "%s: binary overlaps preloader (%p-%p)\n",
714 name, (char *)c->mapstart, (char *)c->mapstart + maplength );
716 ELF_FIXED_ADDRESS (loader, c->mapstart);
719 /* Remember which part of the address space this object uses. */
720 l->l_map_start = c->mapstart + l->l_addr;
721 l->l_map_end = l->l_map_start + maplength;
723 while (c < &loadcmds[nloadcmds])
725 if (c->mapend > c->mapstart)
726 /* Map the segment contents from the file. */
727 wld_mmap ((void *) (l->l_addr + c->mapstart),
728 c->mapend - c->mapstart, c->prot,
729 MAP_FIXED | MAP_COPY | MAP_FILE, fd, c->mapoff);
731 postmap:
732 if (l->l_phdr == 0
733 && (ElfW(Off)) c->mapoff <= header->e_phoff
734 && ((size_t) (c->mapend - c->mapstart + c->mapoff)
735 >= header->e_phoff + header->e_phnum * sizeof (ElfW(Phdr))))
736 /* Found the program header in this segment. */
737 l->l_phdr = (void *)(unsigned int) (c->mapstart + header->e_phoff - c->mapoff);
739 if (c->allocend > c->dataend)
741 /* Extra zero pages should appear at the end of this segment,
742 after the data mapped from the file. */
743 ElfW(Addr) zero, zeroend, zeropage;
745 zero = l->l_addr + c->dataend;
746 zeroend = l->l_addr + c->allocend;
747 zeropage = (zero + page_mask) & ~page_mask;
750 * This is different from the dl-load load...
751 * ld-linux.so.2 relies on the whole page being zero'ed
753 zeroend = (zeroend + page_mask) & ~page_mask;
755 if (zeroend < zeropage)
757 /* All the extra data is in the last page of the segment.
758 We can just zero it. */
759 zeropage = zeroend;
762 if (zeropage > zero)
764 /* Zero the final part of the last page of the segment. */
765 if ((c->prot & PROT_WRITE) == 0)
767 /* Dag nab it. */
768 wld_mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot|PROT_WRITE);
770 wld_memset ((void *) zero, '\0', zeropage - zero);
771 if ((c->prot & PROT_WRITE) == 0)
772 wld_mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot);
775 if (zeroend > zeropage)
777 /* Map the remaining zero pages in from the zero fill FD. */
778 caddr_t mapat;
779 mapat = wld_mmap ((caddr_t) zeropage, zeroend - zeropage,
780 c->prot, MAP_ANON|MAP_PRIVATE|MAP_FIXED,
781 -1, 0);
785 ++c;
788 if (l->l_phdr == NULL) fatal_error("no program header\n");
790 l->l_phdr = (void *)((ElfW(Addr))l->l_phdr + l->l_addr);
791 l->l_entry += l->l_addr;
793 wld_close( fd );
797 static unsigned int elf_hash( const char *name )
799 unsigned int hi, hash = 0;
800 while (*name)
802 hash = (hash << 4) + (unsigned char)*name++;
803 hi = hash & 0xf0000000;
804 hash ^= hi;
805 hash ^= hi >> 24;
807 return hash;
810 static unsigned int gnu_hash( const char *name )
812 unsigned int h = 5381;
813 while (*name) h = h * 33 + (unsigned char)*name++;
814 return h;
818 * Find a symbol in the symbol table of the executable loaded
820 static void *find_symbol( const ElfW(Phdr) *phdr, int num, const char *var, int type )
822 const ElfW(Dyn) *dyn = NULL;
823 const ElfW(Phdr) *ph;
824 const ElfW(Sym) *symtab = NULL;
825 const Elf_Symndx *hashtab = NULL;
826 const Elf32_Word *gnu_hashtab = NULL;
827 const char *strings = NULL;
828 Elf_Symndx idx;
830 /* check the values */
831 #ifdef DUMP_SYMS
832 wld_printf("%p %x\n", phdr, num );
833 #endif
834 if( ( phdr == NULL ) || ( num == 0 ) )
836 wld_printf("could not find PT_DYNAMIC header entry\n");
837 return NULL;
840 /* parse the (already loaded) ELF executable's header */
841 for (ph = phdr; ph < &phdr[num]; ++ph)
843 if( PT_DYNAMIC == ph->p_type )
845 dyn = (void *) ph->p_vaddr;
846 num = ph->p_memsz / sizeof (Elf32_Dyn);
847 break;
850 if( !dyn ) return NULL;
852 while( dyn->d_tag )
854 if( dyn->d_tag == DT_STRTAB )
855 strings = (const char*) dyn->d_un.d_ptr;
856 if( dyn->d_tag == DT_SYMTAB )
857 symtab = (const ElfW(Sym) *)dyn->d_un.d_ptr;
858 if( dyn->d_tag == DT_HASH )
859 hashtab = (const Elf_Symndx *)dyn->d_un.d_ptr;
860 if( dyn->d_tag == DT_GNU_HASH )
861 gnu_hashtab = (const Elf32_Word *)dyn->d_un.d_ptr;
862 #ifdef DUMP_SYMS
863 wld_printf("%x %x\n", dyn->d_tag, dyn->d_un.d_ptr );
864 #endif
865 dyn++;
868 if( (!symtab) || (!strings) ) return NULL;
870 if (gnu_hashtab) /* new style hash table */
872 const unsigned int hash = gnu_hash(var);
873 const Elf32_Word nbuckets = gnu_hashtab[0];
874 const Elf32_Word symbias = gnu_hashtab[1];
875 const Elf32_Word nwords = gnu_hashtab[2];
876 const ElfW(Addr) *bitmask = (const ElfW(Addr) *)(gnu_hashtab + 4);
877 const Elf32_Word *buckets = (const Elf32_Word *)(bitmask + nwords);
878 const Elf32_Word *chains = buckets + nbuckets - symbias;
880 if (!(idx = buckets[hash % nbuckets])) return NULL;
883 if ((chains[idx] & ~1u) == (hash & ~1u) &&
884 symtab[idx].st_info == ELF32_ST_INFO( STB_GLOBAL, type ) &&
885 !wld_strcmp( strings + symtab[idx].st_name, var ))
886 goto found;
887 } while (!(chains[idx++] & 1u));
889 else if (hashtab) /* old style hash table */
891 const unsigned int hash = elf_hash(var);
892 const Elf_Symndx nbuckets = hashtab[0];
893 const Elf_Symndx *buckets = hashtab + 2;
894 const Elf_Symndx *chains = buckets + nbuckets;
896 for (idx = buckets[hash % nbuckets]; idx != STN_UNDEF; idx = chains[idx])
898 if (symtab[idx].st_info == ELF32_ST_INFO( STB_GLOBAL, type ) &&
899 !wld_strcmp( strings + symtab[idx].st_name, var ))
900 goto found;
903 return NULL;
905 found:
906 #ifdef DUMP_SYMS
907 wld_printf("Found %s -> %x\n", strings + symtab[idx].st_name, symtab[idx].st_value );
908 #endif
909 return (void *)symtab[idx].st_value;
913 * preload_reserve
915 * Reserve a range specified in string format
917 static void preload_reserve( const char *str )
919 const char *p;
920 unsigned long result = 0;
921 void *start = NULL, *end = NULL;
922 int first = 1;
924 for (p = str; *p; p++)
926 if (*p >= '0' && *p <= '9') result = result * 16 + *p - '0';
927 else if (*p >= 'a' && *p <= 'f') result = result * 16 + *p - 'a' + 10;
928 else if (*p >= 'A' && *p <= 'F') result = result * 16 + *p - 'A' + 10;
929 else if (*p == '-')
931 if (!first) goto error;
932 start = (void *)(result & ~page_mask);
933 result = 0;
934 first = 0;
936 else goto error;
938 if (!first) end = (void *)((result + page_mask) & ~page_mask);
939 else if (result) goto error; /* single value '0' is allowed */
941 /* sanity checks */
942 if (end <= start) start = end = NULL;
943 else if ((char *)end > preloader_start &&
944 (char *)start <= preloader_end)
946 wld_printf( "WINEPRELOADRESERVE range %p-%p overlaps preloader %p-%p\n",
947 start, end, preloader_start, preloader_end );
948 start = end = NULL;
951 /* check for overlap with low memory area */
952 if ((char *)end <= (char *)preload_info[0].addr + preload_info[0].size)
953 start = end = NULL;
954 else if ((char *)start < (char *)preload_info[0].addr + preload_info[0].size)
955 start = (char *)preload_info[0].addr + preload_info[0].size;
957 /* entry 2 is for the PE exe */
958 preload_info[2].addr = start;
959 preload_info[2].size = (char *)end - (char *)start;
960 return;
962 error:
963 fatal_error( "invalid WINEPRELOADRESERVE value '%s'\n", str );
966 /* check if address is in one of the reserved ranges */
967 static int is_addr_reserved( const void *addr )
969 int i;
971 for (i = 0; preload_info[i].size; i++)
973 if ((const char *)addr >= (const char *)preload_info[i].addr &&
974 (const char *)addr < (const char *)preload_info[i].addr + preload_info[i].size)
975 return 1;
977 return 0;
980 /* remove a range from the preload list */
981 static void remove_preload_range( int i )
983 while (preload_info[i].size)
985 preload_info[i].addr = preload_info[i+1].addr;
986 preload_info[i].size = preload_info[i+1].size;
987 i++;
992 * is_in_preload_range
994 * Check if address of the given aux value is in one of the reserved ranges
996 static int is_in_preload_range( const ElfW(auxv_t) *av, int type )
998 while (av->a_type != AT_NULL)
1000 if (av->a_type == type) return is_addr_reserved( (const void *)av->a_un.a_val );
1001 av++;
1003 return 0;
1006 /* set the process name if supported */
1007 static void set_process_name( int argc, char *argv[] )
1009 int i;
1010 unsigned int off;
1011 char *p, *name, *end;
1013 /* set the process short name */
1014 for (p = name = argv[1]; *p; p++) if (p[0] == '/' && p[1]) name = p + 1;
1015 if (wld_prctl( 15 /* PR_SET_NAME */, (int)name ) == -1) return;
1017 /* find the end of the argv array and move everything down */
1018 end = argv[argc - 1];
1019 while (*end) end++;
1020 off = argv[1] - argv[0];
1021 for (p = argv[1]; p <= end; p++) *(p - off) = *p;
1022 wld_memset( end - off, 0, off );
1023 for (i = 1; i < argc; i++) argv[i] -= off;
1028 * wld_start
1030 * Repeat the actions the kernel would do when loading a dynamically linked .so
1031 * Load the binary and then its ELF interpreter.
1032 * Note, we assume that the binary is a dynamically linked ELF shared object.
1034 void* wld_start( void **stack )
1036 int i, *pargc;
1037 char **argv, **p;
1038 char *interp, *reserve = NULL;
1039 ElfW(auxv_t) new_av[12], delete_av[3], *av;
1040 struct wld_link_map main_binary_map, ld_so_map;
1041 struct wine_preload_info **wine_main_preload_info;
1043 pargc = *stack;
1044 argv = (char **)pargc + 1;
1045 if (*pargc < 2) fatal_error( "Usage: %s wine_binary [args]\n", argv[0] );
1047 /* skip over the parameters */
1048 p = argv + *pargc + 1;
1050 /* skip over the environment */
1051 while (*p)
1053 static const char res[] = "WINEPRELOADRESERVE=";
1054 if (!wld_strncmp( *p, res, sizeof(res)-1 )) reserve = *p + sizeof(res) - 1;
1055 p++;
1058 av = (ElfW(auxv_t)*) (p+1);
1059 page_size = get_auxiliary( av, AT_PAGESZ, 4096 );
1060 page_mask = page_size - 1;
1062 preloader_start = (char *)_start - ((unsigned int)_start & page_mask);
1063 preloader_end = (char *)((unsigned int)(_end + page_mask) & ~page_mask);
1065 #ifdef DUMP_AUX_INFO
1066 wld_printf( "stack = %p\n", *stack );
1067 for( i = 0; i < *pargc; i++ ) wld_printf("argv[%x] = %s\n", i, argv[i]);
1068 dump_auxiliary( av );
1069 #endif
1071 /* reserve memory that Wine needs */
1072 if (reserve) preload_reserve( reserve );
1073 for (i = 0; preload_info[i].size; i++)
1075 if (wld_mmap( preload_info[i].addr, preload_info[i].size, PROT_NONE,
1076 MAP_FIXED | MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, -1, 0 ) == (void *)-1)
1078 wld_printf( "preloader: Warning: failed to reserve range %p-%p\n",
1079 preload_info[i].addr, (char *)preload_info[i].addr + preload_info[i].size );
1080 remove_preload_range( i );
1081 i--;
1085 /* add an executable page at the top of the address space to defeat
1086 * broken no-exec protections that play with the code selector limit */
1087 if (is_addr_reserved( (char *)0x80000000 - page_size ))
1088 wld_mprotect( (char *)0x80000000 - page_size, page_size, PROT_EXEC | PROT_READ );
1090 /* load the main binary */
1091 map_so_lib( argv[1], &main_binary_map );
1093 /* load the ELF interpreter */
1094 interp = (char *)main_binary_map.l_addr + main_binary_map.l_interp;
1095 map_so_lib( interp, &ld_so_map );
1097 /* store pointer to the preload info into the appropriate main binary variable */
1098 wine_main_preload_info = find_symbol( main_binary_map.l_phdr, main_binary_map.l_phnum,
1099 "wine_main_preload_info", STT_OBJECT );
1100 if (wine_main_preload_info) *wine_main_preload_info = preload_info;
1101 else wld_printf( "wine_main_preload_info not found\n" );
1103 #define SET_NEW_AV(n,type,val) new_av[n].a_type = (type); new_av[n].a_un.a_val = (val);
1104 SET_NEW_AV( 0, AT_PHDR, (unsigned long)main_binary_map.l_phdr );
1105 SET_NEW_AV( 1, AT_PHENT, sizeof(ElfW(Phdr)) );
1106 SET_NEW_AV( 2, AT_PHNUM, main_binary_map.l_phnum );
1107 SET_NEW_AV( 3, AT_PAGESZ, page_size );
1108 SET_NEW_AV( 4, AT_BASE, ld_so_map.l_addr );
1109 SET_NEW_AV( 5, AT_FLAGS, get_auxiliary( av, AT_FLAGS, 0 ) );
1110 SET_NEW_AV( 6, AT_ENTRY, main_binary_map.l_entry );
1111 SET_NEW_AV( 7, AT_UID, get_auxiliary( av, AT_UID, wld_getuid() ) );
1112 SET_NEW_AV( 8, AT_EUID, get_auxiliary( av, AT_EUID, wld_geteuid() ) );
1113 SET_NEW_AV( 9, AT_GID, get_auxiliary( av, AT_GID, wld_getgid() ) );
1114 SET_NEW_AV(10, AT_EGID, get_auxiliary( av, AT_EGID, wld_getegid() ) );
1115 SET_NEW_AV(11, AT_NULL, 0 );
1116 #undef SET_NEW_AV
1118 i = 0;
1119 /* delete sysinfo values if addresses conflict */
1120 if (is_in_preload_range( av, AT_SYSINFO ) || is_in_preload_range( av, AT_SYSINFO_EHDR ))
1122 delete_av[i++].a_type = AT_SYSINFO;
1123 delete_av[i++].a_type = AT_SYSINFO_EHDR;
1125 delete_av[i].a_type = AT_NULL;
1127 /* get rid of first argument */
1128 set_process_name( *pargc, argv );
1129 pargc[1] = pargc[0] - 1;
1130 *stack = pargc + 1;
1132 set_auxiliary_values( av, new_av, delete_av, stack );
1134 #ifdef DUMP_AUX_INFO
1135 wld_printf("new stack = %p\n", *stack);
1136 wld_printf("jumping to %x\n", ld_so_map.l_entry);
1137 #endif
1139 return (void *)ld_so_map.l_entry;