d3d9/tests: WARP returns a random color in uninitialized color attributes.
[wine.git] / loader / preloader.c
blob7cf29469d2ccf32d86aedacd2a094363cebd09e9
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 #ifdef __i386__
112 { (void *)0x00000000, 0x00010000 }, /* low 64k */
113 { (void *)0x00010000, 0x00100000 }, /* DOS area */
114 { (void *)0x00110000, 0x67ef0000 }, /* low memory area */
115 { (void *)0x7f000000, 0x03000000 }, /* top-down allocations + shared heap + virtual heap */
116 #else
117 { (void *)0x000000010000, 0x00100000 }, /* DOS area */
118 { (void *)0x000000110000, 0x67ef0000 }, /* low memory area */
119 { (void *)0x00007ff00000, 0x000f0000 }, /* shared user data */
120 { (void *)0x7ffffe000000, 0x01ff0000 }, /* top-down allocations + virtual heap */
121 #endif
122 { 0, 0 }, /* PE exe range set with WINEPRELOADRESERVE */
123 { 0, 0 } /* end of list */
126 /* debugging */
127 #undef DUMP_SEGMENTS
128 #undef DUMP_AUX_INFO
129 #undef DUMP_SYMS
131 /* older systems may not define these */
132 #ifndef PT_TLS
133 #define PT_TLS 7
134 #endif
136 #ifndef AT_SYSINFO
137 #define AT_SYSINFO 32
138 #endif
139 #ifndef AT_SYSINFO_EHDR
140 #define AT_SYSINFO_EHDR 33
141 #endif
143 #ifndef DT_GNU_HASH
144 #define DT_GNU_HASH 0x6ffffef5
145 #endif
147 static size_t page_size, page_mask;
148 static char *preloader_start, *preloader_end;
150 struct wld_link_map {
151 ElfW(Addr) l_addr;
152 ElfW(Dyn) *l_ld;
153 ElfW(Phdr)*l_phdr;
154 ElfW(Addr) l_entry;
155 ElfW(Half) l_ldnum;
156 ElfW(Half) l_phnum;
157 ElfW(Addr) l_map_start, l_map_end;
158 ElfW(Addr) l_interp;
161 struct wld_auxv
163 ElfW(Addr) a_type;
164 union
166 ElfW(Addr) a_val;
167 } a_un;
171 * The __bb_init_func is an empty function only called when file is
172 * compiled with gcc flags "-fprofile-arcs -ftest-coverage". This
173 * function is normally provided by libc's startup files, but since we
174 * build the preloader with "-nostartfiles -nodefaultlibs", we have to
175 * provide our own (empty) version, otherwise linker fails.
177 void __bb_init_func(void) { return; }
179 /* similar to the above but for -fstack-protector */
180 void *__stack_chk_guard = 0;
181 void __stack_chk_fail_local(void) { return; }
182 void __stack_chk_fail(void) { return; }
184 #ifdef __i386__
186 /* data for setting up the glibc-style thread-local storage in %gs */
188 static int thread_data[256];
190 struct
192 /* this is the kernel modify_ldt struct */
193 unsigned int entry_number;
194 unsigned long base_addr;
195 unsigned int limit;
196 unsigned int seg_32bit : 1;
197 unsigned int contents : 2;
198 unsigned int read_exec_only : 1;
199 unsigned int limit_in_pages : 1;
200 unsigned int seg_not_present : 1;
201 unsigned int usable : 1;
202 unsigned int garbage : 25;
203 } thread_ldt = { -1, (unsigned long)thread_data, 0xfffff, 1, 0, 0, 1, 0, 1, 0 };
207 * The _start function is the entry and exit point of this program
209 * It calls wld_start, passing a pointer to the args it receives
210 * then jumps to the address wld_start returns.
212 void _start(void);
213 extern char _end[];
214 __ASM_GLOBAL_FUNC(_start,
215 __ASM_CFI("\t.cfi_undefined %eip\n")
216 "\tmovl $243,%eax\n" /* SYS_set_thread_area */
217 "\tmovl $thread_ldt,%ebx\n"
218 "\tint $0x80\n" /* allocate gs segment */
219 "\torl %eax,%eax\n"
220 "\tjl 1f\n"
221 "\tmovl thread_ldt,%eax\n" /* thread_ldt.entry_number */
222 "\tshl $3,%eax\n"
223 "\torl $3,%eax\n"
224 "\tmov %ax,%gs\n"
225 "\tmov %ax,%fs\n" /* set %fs too so libwine can retrieve it later on */
226 "1:\tmovl %esp,%eax\n"
227 "\tleal -136(%esp),%esp\n" /* allocate some space for extra aux values */
228 "\tpushl %eax\n" /* orig stack pointer */
229 "\tpushl %esp\n" /* ptr to orig stack pointer */
230 "\tcall wld_start\n"
231 "\tpopl %ecx\n" /* remove ptr to stack pointer */
232 "\tpopl %esp\n" /* new stack pointer */
233 "\tpush %eax\n" /* ELF interpreter entry point */
234 "\txor %eax,%eax\n"
235 "\txor %ecx,%ecx\n"
236 "\txor %edx,%edx\n"
237 "\tmov %ax,%gs\n" /* clear %gs again */
238 "\tret\n")
240 /* wrappers for Linux system calls */
242 #define SYSCALL_RET(ret) (((ret) < 0 && (ret) > -4096) ? -1 : (ret))
244 static inline __attribute__((noreturn)) void wld_exit( int code )
246 for (;;) /* avoid warning */
247 __asm__ __volatile__( "pushl %%ebx; movl %1,%%ebx; int $0x80; popl %%ebx"
248 : : "a" (1 /* SYS_exit */), "r" (code) );
251 static inline int wld_open( const char *name, int flags )
253 int ret;
254 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
255 : "=a" (ret) : "0" (5 /* SYS_open */), "r" (name), "c" (flags) );
256 return SYSCALL_RET(ret);
259 static inline int wld_close( int fd )
261 int ret;
262 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
263 : "=a" (ret) : "0" (6 /* SYS_close */), "r" (fd) );
264 return SYSCALL_RET(ret);
267 static inline ssize_t wld_read( int fd, void *buffer, size_t len )
269 int ret;
270 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
271 : "=a" (ret)
272 : "0" (3 /* SYS_read */), "r" (fd), "c" (buffer), "d" (len)
273 : "memory" );
274 return SYSCALL_RET(ret);
277 static inline ssize_t wld_write( int fd, const void *buffer, size_t len )
279 int ret;
280 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
281 : "=a" (ret) : "0" (4 /* SYS_write */), "r" (fd), "c" (buffer), "d" (len) );
282 return SYSCALL_RET(ret);
285 static inline int wld_mprotect( const void *addr, size_t len, int prot )
287 int ret;
288 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
289 : "=a" (ret) : "0" (125 /* SYS_mprotect */), "r" (addr), "c" (len), "d" (prot) );
290 return SYSCALL_RET(ret);
293 static void *wld_mmap( void *start, size_t len, int prot, int flags, int fd, off_t offset )
295 int ret;
297 struct
299 void *addr;
300 unsigned int length;
301 unsigned int prot;
302 unsigned int flags;
303 unsigned int fd;
304 unsigned int offset;
305 } args;
307 args.addr = start;
308 args.length = len;
309 args.prot = prot;
310 args.flags = flags;
311 args.fd = fd;
312 args.offset = offset;
313 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
314 : "=a" (ret) : "0" (90 /* SYS_mmap */), "q" (&args) : "memory" );
315 return (void *)SYSCALL_RET(ret);
318 static inline uid_t wld_getuid(void)
320 uid_t ret;
321 __asm__( "int $0x80" : "=a" (ret) : "0" (24 /* SYS_getuid */) );
322 return ret;
325 static inline uid_t wld_geteuid(void)
327 uid_t ret;
328 __asm__( "int $0x80" : "=a" (ret) : "0" (49 /* SYS_geteuid */) );
329 return ret;
332 static inline gid_t wld_getgid(void)
334 gid_t ret;
335 __asm__( "int $0x80" : "=a" (ret) : "0" (47 /* SYS_getgid */) );
336 return ret;
339 static inline gid_t wld_getegid(void)
341 gid_t ret;
342 __asm__( "int $0x80" : "=a" (ret) : "0" (50 /* SYS_getegid */) );
343 return ret;
346 static inline int wld_prctl( int code, long arg )
348 int ret;
349 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
350 : "=a" (ret) : "0" (172 /* SYS_prctl */), "r" (code), "c" (arg) );
351 return SYSCALL_RET(ret);
354 #elif defined(__x86_64__)
356 void *thread_data[256];
359 * The _start function is the entry and exit point of this program
361 * It calls wld_start, passing a pointer to the args it receives
362 * then jumps to the address wld_start returns.
364 void _start(void);
365 extern char _end[];
366 __ASM_GLOBAL_FUNC(_start,
367 __ASM_CFI(".cfi_undefined %rip\n\t")
368 "movq %rsp,%rax\n\t"
369 "leaq -144(%rsp),%rsp\n\t" /* allocate some space for extra aux values */
370 "movq %rax,(%rsp)\n\t" /* orig stack pointer */
371 "movq $thread_data,%rsi\n\t"
372 "movq $0x1002,%rdi\n\t" /* ARCH_SET_FS */
373 "movq $158,%rax\n\t" /* SYS_arch_prctl */
374 "syscall\n\t"
375 "movq %rsp,%rdi\n\t" /* ptr to orig stack pointer */
376 "call wld_start\n\t"
377 "movq (%rsp),%rsp\n\t" /* new stack pointer */
378 "pushq %rax\n\t" /* ELF interpreter entry point */
379 "xorq %rax,%rax\n\t"
380 "xorq %rcx,%rcx\n\t"
381 "xorq %rdx,%rdx\n\t"
382 "xorq %rsi,%rsi\n\t"
383 "xorq %rdi,%rdi\n\t"
384 "xorq %r8,%r8\n\t"
385 "xorq %r9,%r9\n\t"
386 "xorq %r10,%r10\n\t"
387 "xorq %r11,%r11\n\t"
388 "ret")
390 #define SYSCALL_FUNC( name, nr ) \
391 __ASM_GLOBAL_FUNC( name, \
392 "movq $" #nr ",%rax\n\t" \
393 "movq %rcx,%r10\n\t" \
394 "syscall\n\t" \
395 "leaq 4096(%rax),%rcx\n\t" \
396 "movq $-1,%rdx\n\t" \
397 "cmp $4096,%rcx\n\t" \
398 "cmovb %rdx,%rax\n\t" \
399 "ret" )
401 #define SYSCALL_NOERR( name, nr ) \
402 __ASM_GLOBAL_FUNC( name, \
403 "movq $" #nr ",%rax\n\t" \
404 "syscall\n\t" \
405 "ret" )
407 void wld_exit( int code ) __attribute__((noreturn));
408 SYSCALL_NOERR( wld_exit, 60 /* SYS_exit */ );
410 ssize_t wld_read( int fd, void *buffer, size_t len );
411 SYSCALL_FUNC( wld_read, 0 /* SYS_read */ );
413 ssize_t wld_write( int fd, const void *buffer, size_t len );
414 SYSCALL_FUNC( wld_write, 1 /* SYS_write */ );
416 int wld_open( const char *name, int flags );
417 SYSCALL_FUNC( wld_open, 2 /* SYS_open */ );
419 int wld_close( int fd );
420 SYSCALL_FUNC( wld_close, 3 /* SYS_close */ );
422 void *wld_mmap( void *start, size_t len, int prot, int flags, int fd, off_t offset );
423 SYSCALL_FUNC( wld_mmap, 9 /* SYS_mmap */ );
425 int wld_mprotect( const void *addr, size_t len, int prot );
426 SYSCALL_FUNC( wld_mprotect, 10 /* SYS_mprotect */ );
428 int wld_prctl( int code, long arg );
429 SYSCALL_FUNC( wld_prctl, 157 /* SYS_prctl */ );
431 uid_t wld_getuid(void);
432 SYSCALL_NOERR( wld_getuid, 102 /* SYS_getuid */ );
434 gid_t wld_getgid(void);
435 SYSCALL_NOERR( wld_getgid, 104 /* SYS_getgid */ );
437 uid_t wld_geteuid(void);
438 SYSCALL_NOERR( wld_geteuid, 107 /* SYS_geteuid */ );
440 gid_t wld_getegid(void);
441 SYSCALL_NOERR( wld_getegid, 108 /* SYS_getegid */ );
443 #else
444 #error preloader not implemented for this CPU
445 #endif
447 /* replacement for libc functions */
449 static int wld_strcmp( const char *str1, const char *str2 )
451 while (*str1 && (*str1 == *str2)) { str1++; str2++; }
452 return *str1 - *str2;
455 static int wld_strncmp( const char *str1, const char *str2, size_t len )
457 if (len <= 0) return 0;
458 while ((--len > 0) && *str1 && (*str1 == *str2)) { str1++; str2++; }
459 return *str1 - *str2;
462 static inline void *wld_memset( void *dest, int val, size_t len )
464 char *dst = dest;
465 while (len--) *dst++ = val;
466 return dest;
470 * wld_printf - just the basics
472 * %x prints a hex number
473 * %s prints a string
474 * %p prints a pointer
476 static int wld_vsprintf(char *buffer, const char *fmt, va_list args )
478 static const char hex_chars[16] = "0123456789abcdef";
479 const char *p = fmt;
480 char *str = buffer;
481 int i;
483 while( *p )
485 if( *p == '%' )
487 p++;
488 if( *p == 'x' )
490 unsigned int x = va_arg( args, unsigned int );
491 for (i = 2*sizeof(x) - 1; i >= 0; i--)
492 *str++ = hex_chars[(x>>(i*4))&0xf];
494 else if (p[0] == 'l' && p[1] == 'x')
496 unsigned long x = va_arg( args, unsigned long );
497 for (i = 2*sizeof(x) - 1; i >= 0; i--)
498 *str++ = hex_chars[(x>>(i*4))&0xf];
499 p++;
501 else if( *p == 'p' )
503 unsigned long x = (unsigned long)va_arg( args, void * );
504 for (i = 2*sizeof(x) - 1; i >= 0; i--)
505 *str++ = hex_chars[(x>>(i*4))&0xf];
507 else if( *p == 's' )
509 char *s = va_arg( args, char * );
510 while(*s)
511 *str++ = *s++;
513 else if( *p == 0 )
514 break;
515 p++;
517 *str++ = *p++;
519 *str = 0;
520 return str - buffer;
523 static __attribute__((format(printf,1,2))) void wld_printf(const char *fmt, ... )
525 va_list args;
526 char buffer[256];
527 int len;
529 va_start( args, fmt );
530 len = wld_vsprintf(buffer, fmt, args );
531 va_end( args );
532 wld_write(2, buffer, len);
535 static __attribute__((noreturn,format(printf,1,2))) void fatal_error(const char *fmt, ... )
537 va_list args;
538 char buffer[256];
539 int len;
541 va_start( args, fmt );
542 len = wld_vsprintf(buffer, fmt, args );
543 va_end( args );
544 wld_write(2, buffer, len);
545 wld_exit(1);
548 #ifdef DUMP_AUX_INFO
550 * Dump interesting bits of the ELF auxv_t structure that is passed
551 * as the 4th parameter to the _start function
553 static void dump_auxiliary( struct wld_auxv *av )
555 #define NAME(at) { at, #at }
556 static const struct { int val; const char *name; } names[] =
558 NAME(AT_BASE),
559 NAME(AT_CLKTCK),
560 NAME(AT_EGID),
561 NAME(AT_ENTRY),
562 NAME(AT_EUID),
563 NAME(AT_FLAGS),
564 NAME(AT_GID),
565 NAME(AT_HWCAP),
566 NAME(AT_PAGESZ),
567 NAME(AT_PHDR),
568 NAME(AT_PHENT),
569 NAME(AT_PHNUM),
570 NAME(AT_PLATFORM),
571 NAME(AT_SYSINFO),
572 NAME(AT_SYSINFO_EHDR),
573 NAME(AT_UID),
574 { 0, NULL }
576 #undef NAME
578 int i;
580 for ( ; av->a_type != AT_NULL; av++)
582 for (i = 0; names[i].name; i++) if (names[i].val == av->a_type) break;
583 if (names[i].name) wld_printf("%s = %lx\n", names[i].name, (unsigned long)av->a_un.a_val);
584 else wld_printf( "%lx = %lx\n", (unsigned long)av->a_type, (unsigned long)av->a_un.a_val );
587 #endif
590 * set_auxiliary_values
592 * Set the new auxiliary values
594 static void set_auxiliary_values( struct wld_auxv *av, const struct wld_auxv *new_av,
595 const struct wld_auxv *delete_av, void **stack )
597 int i, j, av_count = 0, new_count = 0, delete_count = 0;
598 char *src, *dst;
600 /* count how many aux values we have already */
601 while (av[av_count].a_type != AT_NULL) av_count++;
603 /* delete unwanted values */
604 for (j = 0; delete_av[j].a_type != AT_NULL; j++)
606 for (i = 0; i < av_count; i++) if (av[i].a_type == delete_av[j].a_type)
608 av[i].a_type = av[av_count-1].a_type;
609 av[i].a_un.a_val = av[av_count-1].a_un.a_val;
610 av[--av_count].a_type = AT_NULL;
611 delete_count++;
612 break;
616 /* count how many values we have in new_av that aren't in av */
617 for (j = 0; new_av[j].a_type != AT_NULL; j++)
619 for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
620 if (i == av_count) new_count++;
623 src = (char *)*stack;
624 dst = src - (new_count - delete_count) * sizeof(*av);
625 dst = (char *)((unsigned long)dst & ~15);
626 if (dst < src) /* need to make room for the extra values */
628 int len = (char *)(av + av_count + 1) - src;
629 for (i = 0; i < len; i++) dst[i] = src[i];
631 else if (dst > src) /* get rid of unused values */
633 int len = (char *)(av + av_count + 1) - src;
634 for (i = len - 1; i >= 0; i--) dst[i] = src[i];
636 *stack = dst;
637 av = (struct wld_auxv *)((char *)av + (dst - src));
639 /* now set the values */
640 for (j = 0; new_av[j].a_type != AT_NULL; j++)
642 for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
643 if (i < av_count) av[i].a_un.a_val = new_av[j].a_un.a_val;
644 else
646 av[av_count].a_type = new_av[j].a_type;
647 av[av_count].a_un.a_val = new_av[j].a_un.a_val;
648 av_count++;
652 #ifdef DUMP_AUX_INFO
653 wld_printf("New auxiliary info:\n");
654 dump_auxiliary( av );
655 #endif
659 * get_auxiliary
661 * Get a field of the auxiliary structure
663 static int get_auxiliary( struct wld_auxv *av, int type, int def_val )
665 for ( ; av->a_type != AT_NULL; av++)
666 if( av->a_type == type ) return av->a_un.a_val;
667 return def_val;
671 * map_so_lib
673 * modelled after _dl_map_object_from_fd() from glibc-2.3.1/elf/dl-load.c
675 * This function maps the segments from an ELF object, and optionally
676 * stores information about the mapping into the auxv_t structure.
678 static void map_so_lib( const char *name, struct wld_link_map *l)
680 int fd;
681 unsigned char buf[0x800];
682 ElfW(Ehdr) *header = (ElfW(Ehdr)*)buf;
683 ElfW(Phdr) *phdr, *ph;
684 /* Scan the program header table, collecting its load commands. */
685 struct loadcmd
687 ElfW(Addr) mapstart, mapend, dataend, allocend;
688 off_t mapoff;
689 int prot;
690 } loadcmds[16], *c;
691 size_t nloadcmds = 0, maplength;
693 fd = wld_open( name, O_RDONLY );
694 if (fd == -1) fatal_error("%s: could not open\n", name );
696 if (wld_read( fd, buf, sizeof(buf) ) != sizeof(buf))
697 fatal_error("%s: failed to read ELF header\n", name);
699 phdr = (void*) (((unsigned char*)buf) + header->e_phoff);
701 if( ( header->e_ident[0] != 0x7f ) ||
702 ( header->e_ident[1] != 'E' ) ||
703 ( header->e_ident[2] != 'L' ) ||
704 ( header->e_ident[3] != 'F' ) )
705 fatal_error( "%s: not an ELF binary... don't know how to load it\n", name );
707 #ifdef __i386__
708 if( header->e_machine != EM_386 )
709 fatal_error("%s: not an i386 ELF binary... don't know how to load it\n", name );
710 #elif defined(__x86_64__)
711 if( header->e_machine != EM_X86_64 )
712 fatal_error("%s: not an x86-64 ELF binary... don't know how to load it\n", name );
713 #endif
715 if (header->e_phnum > sizeof(loadcmds)/sizeof(loadcmds[0]))
716 fatal_error( "%s: oops... not enough space for load commands\n", name );
718 maplength = header->e_phnum * sizeof (ElfW(Phdr));
719 if (header->e_phoff + maplength > sizeof(buf))
720 fatal_error( "%s: oops... not enough space for ELF headers\n", name );
722 l->l_ld = 0;
723 l->l_addr = 0;
724 l->l_phdr = 0;
725 l->l_phnum = header->e_phnum;
726 l->l_entry = header->e_entry;
727 l->l_interp = 0;
729 for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
732 #ifdef DUMP_SEGMENTS
733 wld_printf( "ph = %p\n", ph );
734 wld_printf( " p_type = %lx\n", (unsigned long)ph->p_type );
735 wld_printf( " p_flags = %lx\n", (unsigned long)ph->p_flags );
736 wld_printf( " p_offset = %lx\n", (unsigned long)ph->p_offset );
737 wld_printf( " p_vaddr = %lx\n", (unsigned long)ph->p_vaddr );
738 wld_printf( " p_paddr = %lx\n", (unsigned long)ph->p_paddr );
739 wld_printf( " p_filesz = %lx\n", (unsigned long)ph->p_filesz );
740 wld_printf( " p_memsz = %lx\n", (unsigned long)ph->p_memsz );
741 wld_printf( " p_align = %lx\n", (unsigned long)ph->p_align );
742 #endif
744 switch (ph->p_type)
746 /* These entries tell us where to find things once the file's
747 segments are mapped in. We record the addresses it says
748 verbatim, and later correct for the run-time load address. */
749 case PT_DYNAMIC:
750 l->l_ld = (void *) ph->p_vaddr;
751 l->l_ldnum = ph->p_memsz / sizeof (Elf32_Dyn);
752 break;
754 case PT_PHDR:
755 l->l_phdr = (void *) ph->p_vaddr;
756 break;
758 case PT_LOAD:
760 if ((ph->p_align & page_mask) != 0)
761 fatal_error( "%s: ELF load command alignment not page-aligned\n", name );
763 if (((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1)) != 0)
764 fatal_error( "%s: ELF load command address/offset not properly aligned\n", name );
766 c = &loadcmds[nloadcmds++];
767 c->mapstart = ph->p_vaddr & ~(ph->p_align - 1);
768 c->mapend = ((ph->p_vaddr + ph->p_filesz + page_mask) & ~page_mask);
769 c->dataend = ph->p_vaddr + ph->p_filesz;
770 c->allocend = ph->p_vaddr + ph->p_memsz;
771 c->mapoff = ph->p_offset & ~(ph->p_align - 1);
773 c->prot = 0;
774 if (ph->p_flags & PF_R)
775 c->prot |= PROT_READ;
776 if (ph->p_flags & PF_W)
777 c->prot |= PROT_WRITE;
778 if (ph->p_flags & PF_X)
779 c->prot |= PROT_EXEC;
781 break;
783 case PT_INTERP:
784 l->l_interp = ph->p_vaddr;
785 break;
787 case PT_TLS:
789 * We don't need to set anything up because we're
790 * emulating the kernel, not ld-linux.so.2
791 * The ELF loader will set up the TLS data itself.
793 case PT_SHLIB:
794 case PT_NOTE:
795 default:
796 break;
800 /* Now process the load commands and map segments into memory. */
801 if (!nloadcmds)
802 fatal_error( "%s: no segments to load\n", name );
803 c = loadcmds;
805 /* Length of the sections to be loaded. */
806 maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
808 if( header->e_type == ET_DYN )
810 ElfW(Addr) mappref;
811 mappref = (ELF_PREFERRED_ADDRESS (loader, maplength, c->mapstart)
812 - MAP_BASE_ADDR (l));
814 /* Remember which part of the address space this object uses. */
815 l->l_map_start = (ElfW(Addr)) wld_mmap ((void *) mappref, maplength,
816 c->prot, MAP_COPY | MAP_FILE,
817 fd, c->mapoff);
818 /* wld_printf("set : offset = %x\n", c->mapoff); */
819 /* wld_printf("l->l_map_start = %x\n", l->l_map_start); */
821 l->l_map_end = l->l_map_start + maplength;
822 l->l_addr = l->l_map_start - c->mapstart;
824 wld_mprotect ((caddr_t) (l->l_addr + c->mapend),
825 loadcmds[nloadcmds - 1].allocend - c->mapend,
826 PROT_NONE);
827 goto postmap;
829 else
831 /* sanity check */
832 if ((char *)c->mapstart + maplength > preloader_start &&
833 (char *)c->mapstart <= preloader_end)
834 fatal_error( "%s: binary overlaps preloader (%p-%p)\n",
835 name, (char *)c->mapstart, (char *)c->mapstart + maplength );
837 ELF_FIXED_ADDRESS (loader, c->mapstart);
840 /* Remember which part of the address space this object uses. */
841 l->l_map_start = c->mapstart + l->l_addr;
842 l->l_map_end = l->l_map_start + maplength;
844 while (c < &loadcmds[nloadcmds])
846 if (c->mapend > c->mapstart)
847 /* Map the segment contents from the file. */
848 wld_mmap ((void *) (l->l_addr + c->mapstart),
849 c->mapend - c->mapstart, c->prot,
850 MAP_FIXED | MAP_COPY | MAP_FILE, fd, c->mapoff);
852 postmap:
853 if (l->l_phdr == 0
854 && (ElfW(Off)) c->mapoff <= header->e_phoff
855 && ((size_t) (c->mapend - c->mapstart + c->mapoff)
856 >= header->e_phoff + header->e_phnum * sizeof (ElfW(Phdr))))
857 /* Found the program header in this segment. */
858 l->l_phdr = (void *)(unsigned long)(c->mapstart + header->e_phoff - c->mapoff);
860 if (c->allocend > c->dataend)
862 /* Extra zero pages should appear at the end of this segment,
863 after the data mapped from the file. */
864 ElfW(Addr) zero, zeroend, zeropage;
866 zero = l->l_addr + c->dataend;
867 zeroend = l->l_addr + c->allocend;
868 zeropage = (zero + page_mask) & ~page_mask;
871 * This is different from the dl-load load...
872 * ld-linux.so.2 relies on the whole page being zero'ed
874 zeroend = (zeroend + page_mask) & ~page_mask;
876 if (zeroend < zeropage)
878 /* All the extra data is in the last page of the segment.
879 We can just zero it. */
880 zeropage = zeroend;
883 if (zeropage > zero)
885 /* Zero the final part of the last page of the segment. */
886 if ((c->prot & PROT_WRITE) == 0)
888 /* Dag nab it. */
889 wld_mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot|PROT_WRITE);
891 wld_memset ((void *) zero, '\0', zeropage - zero);
892 if ((c->prot & PROT_WRITE) == 0)
893 wld_mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot);
896 if (zeroend > zeropage)
898 /* Map the remaining zero pages in from the zero fill FD. */
899 wld_mmap ((caddr_t) zeropage, zeroend - zeropage,
900 c->prot, MAP_ANON|MAP_PRIVATE|MAP_FIXED,
901 -1, 0);
905 ++c;
908 if (l->l_phdr == NULL) fatal_error("no program header\n");
910 l->l_phdr = (void *)((ElfW(Addr))l->l_phdr + l->l_addr);
911 l->l_entry += l->l_addr;
913 wld_close( fd );
917 static unsigned int wld_elf_hash( const char *name )
919 unsigned int hi, hash = 0;
920 while (*name)
922 hash = (hash << 4) + (unsigned char)*name++;
923 hi = hash & 0xf0000000;
924 hash ^= hi;
925 hash ^= hi >> 24;
927 return hash;
930 static unsigned int gnu_hash( const char *name )
932 unsigned int h = 5381;
933 while (*name) h = h * 33 + (unsigned char)*name++;
934 return h;
938 * Find a symbol in the symbol table of the executable loaded
940 static void *find_symbol( const ElfW(Phdr) *phdr, int num, const char *var, int type )
942 const ElfW(Dyn) *dyn = NULL;
943 const ElfW(Phdr) *ph;
944 const ElfW(Sym) *symtab = NULL;
945 const Elf32_Word *hashtab = NULL;
946 const Elf32_Word *gnu_hashtab = NULL;
947 const char *strings = NULL;
948 Elf32_Word idx;
950 /* check the values */
951 #ifdef DUMP_SYMS
952 wld_printf("%p %x\n", phdr, num );
953 #endif
954 if( ( phdr == NULL ) || ( num == 0 ) )
956 wld_printf("could not find PT_DYNAMIC header entry\n");
957 return NULL;
960 /* parse the (already loaded) ELF executable's header */
961 for (ph = phdr; ph < &phdr[num]; ++ph)
963 if( PT_DYNAMIC == ph->p_type )
965 dyn = (void *) ph->p_vaddr;
966 num = ph->p_memsz / sizeof (*dyn);
967 break;
970 if( !dyn ) return NULL;
972 while( dyn->d_tag )
974 if( dyn->d_tag == DT_STRTAB )
975 strings = (const char*) dyn->d_un.d_ptr;
976 if( dyn->d_tag == DT_SYMTAB )
977 symtab = (const ElfW(Sym) *)dyn->d_un.d_ptr;
978 if( dyn->d_tag == DT_HASH )
979 hashtab = (const Elf32_Word *)dyn->d_un.d_ptr;
980 if( dyn->d_tag == DT_GNU_HASH )
981 gnu_hashtab = (const Elf32_Word *)dyn->d_un.d_ptr;
982 #ifdef DUMP_SYMS
983 wld_printf("%lx %p\n", (unsigned long)dyn->d_tag, (void *)dyn->d_un.d_ptr );
984 #endif
985 dyn++;
988 if( (!symtab) || (!strings) ) return NULL;
990 if (gnu_hashtab) /* new style hash table */
992 const unsigned int hash = gnu_hash(var);
993 const Elf32_Word nbuckets = gnu_hashtab[0];
994 const Elf32_Word symbias = gnu_hashtab[1];
995 const Elf32_Word nwords = gnu_hashtab[2];
996 const ElfW(Addr) *bitmask = (const ElfW(Addr) *)(gnu_hashtab + 4);
997 const Elf32_Word *buckets = (const Elf32_Word *)(bitmask + nwords);
998 const Elf32_Word *chains = buckets + nbuckets - symbias;
1000 if (!(idx = buckets[hash % nbuckets])) return NULL;
1003 if ((chains[idx] & ~1u) == (hash & ~1u) &&
1004 ELF32_ST_BIND(symtab[idx].st_info) == STB_GLOBAL &&
1005 ELF32_ST_TYPE(symtab[idx].st_info) == type &&
1006 !wld_strcmp( strings + symtab[idx].st_name, var ))
1007 goto found;
1008 } while (!(chains[idx++] & 1u));
1010 else if (hashtab) /* old style hash table */
1012 const unsigned int hash = wld_elf_hash(var);
1013 const Elf32_Word nbuckets = hashtab[0];
1014 const Elf32_Word *buckets = hashtab + 2;
1015 const Elf32_Word *chains = buckets + nbuckets;
1017 for (idx = buckets[hash % nbuckets]; idx; idx = chains[idx])
1019 if (ELF32_ST_BIND(symtab[idx].st_info) == STB_GLOBAL &&
1020 ELF32_ST_TYPE(symtab[idx].st_info) == type &&
1021 !wld_strcmp( strings + symtab[idx].st_name, var ))
1022 goto found;
1025 return NULL;
1027 found:
1028 #ifdef DUMP_SYMS
1029 wld_printf("Found %s -> %p\n", strings + symtab[idx].st_name, (void *)symtab[idx].st_value );
1030 #endif
1031 return (void *)symtab[idx].st_value;
1035 * preload_reserve
1037 * Reserve a range specified in string format
1039 static void preload_reserve( const char *str )
1041 const char *p;
1042 unsigned long result = 0;
1043 void *start = NULL, *end = NULL;
1044 int i, first = 1;
1046 for (p = str; *p; p++)
1048 if (*p >= '0' && *p <= '9') result = result * 16 + *p - '0';
1049 else if (*p >= 'a' && *p <= 'f') result = result * 16 + *p - 'a' + 10;
1050 else if (*p >= 'A' && *p <= 'F') result = result * 16 + *p - 'A' + 10;
1051 else if (*p == '-')
1053 if (!first) goto error;
1054 start = (void *)(result & ~page_mask);
1055 result = 0;
1056 first = 0;
1058 else goto error;
1060 if (!first) end = (void *)((result + page_mask) & ~page_mask);
1061 else if (result) goto error; /* single value '0' is allowed */
1063 /* sanity checks */
1064 if (end <= start) start = end = NULL;
1065 else if ((char *)end > preloader_start &&
1066 (char *)start <= preloader_end)
1068 wld_printf( "WINEPRELOADRESERVE range %p-%p overlaps preloader %p-%p\n",
1069 start, end, preloader_start, preloader_end );
1070 start = end = NULL;
1073 /* check for overlap with low memory areas */
1074 for (i = 0; preload_info[i].size; i++)
1076 if ((char *)preload_info[i].addr > (char *)0x00110000) break;
1077 if ((char *)end <= (char *)preload_info[i].addr + preload_info[i].size)
1079 start = end = NULL;
1080 break;
1082 if ((char *)start < (char *)preload_info[i].addr + preload_info[i].size)
1083 start = (char *)preload_info[i].addr + preload_info[i].size;
1086 while (preload_info[i].size) i++;
1087 preload_info[i].addr = start;
1088 preload_info[i].size = (char *)end - (char *)start;
1089 return;
1091 error:
1092 fatal_error( "invalid WINEPRELOADRESERVE value '%s'\n", str );
1095 /* check if address is in one of the reserved ranges */
1096 static int is_addr_reserved( const void *addr )
1098 int i;
1100 for (i = 0; preload_info[i].size; i++)
1102 if ((const char *)addr >= (const char *)preload_info[i].addr &&
1103 (const char *)addr < (const char *)preload_info[i].addr + preload_info[i].size)
1104 return 1;
1106 return 0;
1109 /* remove a range from the preload list */
1110 static void remove_preload_range( int i )
1112 while (preload_info[i].size)
1114 preload_info[i].addr = preload_info[i+1].addr;
1115 preload_info[i].size = preload_info[i+1].size;
1116 i++;
1121 * is_in_preload_range
1123 * Check if address of the given aux value is in one of the reserved ranges
1125 static int is_in_preload_range( const struct wld_auxv *av, int type )
1127 while (av->a_type != AT_NULL)
1129 if (av->a_type == type) return is_addr_reserved( (const void *)av->a_un.a_val );
1130 av++;
1132 return 0;
1135 /* set the process name if supported */
1136 static void set_process_name( int argc, char *argv[] )
1138 int i;
1139 unsigned int off;
1140 char *p, *name, *end;
1142 /* set the process short name */
1143 for (p = name = argv[1]; *p; p++) if (p[0] == '/' && p[1]) name = p + 1;
1144 if (wld_prctl( 15 /* PR_SET_NAME */, (long)name ) == -1) return;
1146 /* find the end of the argv array and move everything down */
1147 end = argv[argc - 1];
1148 while (*end) end++;
1149 off = argv[1] - argv[0];
1150 for (p = argv[1]; p <= end; p++) *(p - off) = *p;
1151 wld_memset( end - off, 0, off );
1152 for (i = 1; i < argc; i++) argv[i] -= off;
1157 * wld_start
1159 * Repeat the actions the kernel would do when loading a dynamically linked .so
1160 * Load the binary and then its ELF interpreter.
1161 * Note, we assume that the binary is a dynamically linked ELF shared object.
1163 void* wld_start( void **stack )
1165 long i, *pargc;
1166 char **argv, **p;
1167 char *interp, *reserve = NULL;
1168 struct wld_auxv new_av[12], delete_av[3], *av;
1169 struct wld_link_map main_binary_map, ld_so_map;
1170 struct wine_preload_info **wine_main_preload_info;
1172 pargc = *stack;
1173 argv = (char **)pargc + 1;
1174 if (*pargc < 2) fatal_error( "Usage: %s wine_binary [args]\n", argv[0] );
1176 /* skip over the parameters */
1177 p = argv + *pargc + 1;
1179 /* skip over the environment */
1180 while (*p)
1182 static const char res[] = "WINEPRELOADRESERVE=";
1183 if (!wld_strncmp( *p, res, sizeof(res)-1 )) reserve = *p + sizeof(res) - 1;
1184 p++;
1187 av = (struct wld_auxv *)(p+1);
1188 page_size = get_auxiliary( av, AT_PAGESZ, 4096 );
1189 page_mask = page_size - 1;
1191 preloader_start = (char *)_start - ((unsigned long)_start & page_mask);
1192 preloader_end = (char *)((unsigned long)(_end + page_mask) & ~page_mask);
1194 #ifdef DUMP_AUX_INFO
1195 wld_printf( "stack = %p\n", *stack );
1196 for( i = 0; i < *pargc; i++ ) wld_printf("argv[%lx] = %s\n", i, argv[i]);
1197 dump_auxiliary( av );
1198 #endif
1200 /* reserve memory that Wine needs */
1201 if (reserve) preload_reserve( reserve );
1202 for (i = 0; preload_info[i].size; i++)
1204 if ((char *)av >= (char *)preload_info[i].addr &&
1205 (char *)pargc <= (char *)preload_info[i].addr + preload_info[i].size)
1207 remove_preload_range( i );
1208 i--;
1210 else if (wld_mmap( preload_info[i].addr, preload_info[i].size, PROT_NONE,
1211 MAP_FIXED | MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, -1, 0 ) == (void *)-1)
1213 /* don't warn for low 64k */
1214 if (preload_info[i].addr >= (void *)0x10000)
1215 wld_printf( "preloader: Warning: failed to reserve range %p-%p\n",
1216 preload_info[i].addr, (char *)preload_info[i].addr + preload_info[i].size );
1217 remove_preload_range( i );
1218 i--;
1222 /* add an executable page at the top of the address space to defeat
1223 * broken no-exec protections that play with the code selector limit */
1224 if (is_addr_reserved( (char *)0x80000000 - page_size ))
1225 wld_mprotect( (char *)0x80000000 - page_size, page_size, PROT_EXEC | PROT_READ );
1227 /* load the main binary */
1228 map_so_lib( argv[1], &main_binary_map );
1230 /* load the ELF interpreter */
1231 interp = (char *)main_binary_map.l_addr + main_binary_map.l_interp;
1232 map_so_lib( interp, &ld_so_map );
1234 /* store pointer to the preload info into the appropriate main binary variable */
1235 wine_main_preload_info = find_symbol( main_binary_map.l_phdr, main_binary_map.l_phnum,
1236 "wine_main_preload_info", STT_OBJECT );
1237 if (wine_main_preload_info) *wine_main_preload_info = preload_info;
1238 else wld_printf( "wine_main_preload_info not found\n" );
1240 #define SET_NEW_AV(n,type,val) new_av[n].a_type = (type); new_av[n].a_un.a_val = (val);
1241 SET_NEW_AV( 0, AT_PHDR, (unsigned long)main_binary_map.l_phdr );
1242 SET_NEW_AV( 1, AT_PHENT, sizeof(ElfW(Phdr)) );
1243 SET_NEW_AV( 2, AT_PHNUM, main_binary_map.l_phnum );
1244 SET_NEW_AV( 3, AT_PAGESZ, page_size );
1245 SET_NEW_AV( 4, AT_BASE, ld_so_map.l_addr );
1246 SET_NEW_AV( 5, AT_FLAGS, get_auxiliary( av, AT_FLAGS, 0 ) );
1247 SET_NEW_AV( 6, AT_ENTRY, main_binary_map.l_entry );
1248 SET_NEW_AV( 7, AT_UID, get_auxiliary( av, AT_UID, wld_getuid() ) );
1249 SET_NEW_AV( 8, AT_EUID, get_auxiliary( av, AT_EUID, wld_geteuid() ) );
1250 SET_NEW_AV( 9, AT_GID, get_auxiliary( av, AT_GID, wld_getgid() ) );
1251 SET_NEW_AV(10, AT_EGID, get_auxiliary( av, AT_EGID, wld_getegid() ) );
1252 SET_NEW_AV(11, AT_NULL, 0 );
1253 #undef SET_NEW_AV
1255 i = 0;
1256 /* delete sysinfo values if addresses conflict */
1257 if (is_in_preload_range( av, AT_SYSINFO ) || is_in_preload_range( av, AT_SYSINFO_EHDR ))
1259 delete_av[i++].a_type = AT_SYSINFO;
1260 delete_av[i++].a_type = AT_SYSINFO_EHDR;
1262 delete_av[i].a_type = AT_NULL;
1264 /* get rid of first argument */
1265 set_process_name( *pargc, argv );
1266 pargc[1] = pargc[0] - 1;
1267 *stack = pargc + 1;
1269 set_auxiliary_values( av, new_av, delete_av, stack );
1271 #ifdef DUMP_AUX_INFO
1272 wld_printf("new stack = %p\n", *stack);
1273 wld_printf("jumping to %p\n", (void *)ld_so_map.l_entry);
1274 #endif
1276 return (void *)ld_so_map.l_entry;