kernel32: Update English resource.
[wine/testsucceed.git] / loader / preloader.c
bloba94c52cf146bd7090fe61532ce66798dd13c2383
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;
163 * The __bb_init_func is an empty function only called when file is
164 * compiled with gcc flags "-fprofile-arcs -ftest-coverage". This
165 * function is normally provided by libc's startup files, but since we
166 * build the preloader with "-nostartfiles -nodefaultlibs", we have to
167 * provide our own (empty) version, otherwise linker fails.
169 void __bb_init_func(void) { return; }
171 /* similar to the above but for -fstack-protector */
172 void *__stack_chk_guard = 0;
173 void __stack_chk_fail_local(void) { return; }
174 void __stack_chk_fail(void) { return; }
176 #ifdef __i386__
178 /* data for setting up the glibc-style thread-local storage in %gs */
180 static int thread_data[256];
182 struct
184 /* this is the kernel modify_ldt struct */
185 unsigned int entry_number;
186 unsigned long base_addr;
187 unsigned int limit;
188 unsigned int seg_32bit : 1;
189 unsigned int contents : 2;
190 unsigned int read_exec_only : 1;
191 unsigned int limit_in_pages : 1;
192 unsigned int seg_not_present : 1;
193 unsigned int usable : 1;
194 unsigned int garbage : 25;
195 } thread_ldt = { -1, (unsigned long)thread_data, 0xfffff, 1, 0, 0, 1, 0, 1, 0 };
199 * The _start function is the entry and exit point of this program
201 * It calls wld_start, passing a pointer to the args it receives
202 * then jumps to the address wld_start returns.
204 void _start(void);
205 extern char _end[];
206 __ASM_GLOBAL_FUNC(_start,
207 "\tmovl $243,%eax\n" /* SYS_set_thread_area */
208 "\tmovl $thread_ldt,%ebx\n"
209 "\tint $0x80\n" /* allocate gs segment */
210 "\torl %eax,%eax\n"
211 "\tjl 1f\n"
212 "\tmovl thread_ldt,%eax\n" /* thread_ldt.entry_number */
213 "\tshl $3,%eax\n"
214 "\torl $3,%eax\n"
215 "\tmov %ax,%gs\n"
216 "\tmov %ax,%fs\n" /* set %fs too so libwine can retrieve it later on */
217 "1:\tmovl %esp,%eax\n"
218 "\tleal -136(%esp),%esp\n" /* allocate some space for extra aux values */
219 "\tpushl %eax\n" /* orig stack pointer */
220 "\tpushl %esp\n" /* ptr to orig stack pointer */
221 "\tcall wld_start\n"
222 "\tpopl %ecx\n" /* remove ptr to stack pointer */
223 "\tpopl %esp\n" /* new stack pointer */
224 "\tpush %eax\n" /* ELF interpreter entry point */
225 "\txor %eax,%eax\n"
226 "\txor %ecx,%ecx\n"
227 "\txor %edx,%edx\n"
228 "\tmov %ax,%gs\n" /* clear %gs again */
229 "\tret\n")
231 /* wrappers for Linux system calls */
233 #define SYSCALL_RET(ret) (((ret) < 0 && (ret) > -4096) ? -1 : (ret))
235 static inline __attribute__((noreturn)) void wld_exit( int code )
237 for (;;) /* avoid warning */
238 __asm__ __volatile__( "pushl %%ebx; movl %1,%%ebx; int $0x80; popl %%ebx"
239 : : "a" (SYS_exit), "r" (code) );
242 static inline int wld_open( const char *name, int flags )
244 int ret;
245 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
246 : "=a" (ret) : "0" (SYS_open), "r" (name), "c" (flags) );
247 return SYSCALL_RET(ret);
250 static inline int wld_close( int fd )
252 int ret;
253 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
254 : "=a" (ret) : "0" (SYS_close), "r" (fd) );
255 return SYSCALL_RET(ret);
258 static inline ssize_t wld_read( int fd, void *buffer, size_t len )
260 int ret;
261 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
262 : "=a" (ret)
263 : "0" (SYS_read), "r" (fd), "c" (buffer), "d" (len)
264 : "memory" );
265 return SYSCALL_RET(ret);
268 static inline ssize_t wld_write( int fd, const void *buffer, size_t len )
270 int ret;
271 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
272 : "=a" (ret) : "0" (SYS_write), "r" (fd), "c" (buffer), "d" (len) );
273 return SYSCALL_RET(ret);
276 static inline int wld_mprotect( const void *addr, size_t len, int prot )
278 int ret;
279 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
280 : "=a" (ret) : "0" (SYS_mprotect), "r" (addr), "c" (len), "d" (prot) );
281 return SYSCALL_RET(ret);
284 static void *wld_mmap( void *start, size_t len, int prot, int flags, int fd, off_t offset )
286 int ret;
288 struct
290 void *addr;
291 unsigned int length;
292 unsigned int prot;
293 unsigned int flags;
294 unsigned int fd;
295 unsigned int offset;
296 } args;
298 args.addr = start;
299 args.length = len;
300 args.prot = prot;
301 args.flags = flags;
302 args.fd = fd;
303 args.offset = offset;
304 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
305 : "=a" (ret) : "0" (SYS_mmap), "q" (&args) : "memory" );
306 return (void *)SYSCALL_RET(ret);
309 static inline uid_t wld_getuid(void)
311 uid_t ret;
312 __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_getuid) );
313 return ret;
316 static inline uid_t wld_geteuid(void)
318 uid_t ret;
319 __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_geteuid) );
320 return ret;
323 static inline gid_t wld_getgid(void)
325 gid_t ret;
326 __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_getgid) );
327 return ret;
330 static inline gid_t wld_getegid(void)
332 gid_t ret;
333 __asm__( "int $0x80" : "=a" (ret) : "0" (SYS_getegid) );
334 return ret;
337 static inline int wld_prctl( int code, long arg )
339 int ret;
340 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
341 : "=a" (ret) : "0" (SYS_prctl), "r" (code), "c" (arg) );
342 return SYSCALL_RET(ret);
345 #elif defined(__x86_64__)
347 void *thread_data[256];
350 * The _start function is the entry and exit point of this program
352 * It calls wld_start, passing a pointer to the args it receives
353 * then jumps to the address wld_start returns.
355 void _start(void);
356 extern char _end[];
357 __ASM_GLOBAL_FUNC(_start,
358 "movq %rsp,%rax\n\t"
359 "leaq -144(%rsp),%rsp\n\t" /* allocate some space for extra aux values */
360 "movq %rax,(%rsp)\n\t" /* orig stack pointer */
361 "movq $thread_data,%rsi\n\t"
362 "movq $0x1002,%rdi\n\t" /* ARCH_SET_FS */
363 "movq $158,%rax\n\t" /* SYS_arch_prctl */
364 "syscall\n\t"
365 "movq %rsp,%rdi\n\t" /* ptr to orig stack pointer */
366 "call wld_start\n\t"
367 "movq (%rsp),%rsp\n\t" /* new stack pointer */
368 "pushq %rax\n\t" /* ELF interpreter entry point */
369 "xorq %rax,%rax\n\t"
370 "xorq %rcx,%rcx\n\t"
371 "xorq %rdx,%rdx\n\t"
372 "xorq %rsi,%rsi\n\t"
373 "xorq %rdi,%rdi\n\t"
374 "xorq %r8,%r8\n\t"
375 "xorq %r9,%r9\n\t"
376 "xorq %r10,%r10\n\t"
377 "xorq %r11,%r11\n\t"
378 "ret")
380 #define SYSCALL_FUNC( name, nr ) \
381 __ASM_GLOBAL_FUNC( name, \
382 "movq $" #nr ",%rax\n\t" \
383 "movq %rcx,%r10\n\t" \
384 "syscall\n\t" \
385 "leaq 4096(%rax),%rcx\n\t" \
386 "movq $-1,%rdx\n\t" \
387 "cmp $4096,%rcx\n\t" \
388 "cmovb %rdx,%rax\n\t" \
389 "ret" )
391 #define SYSCALL_NOERR( name, nr ) \
392 __ASM_GLOBAL_FUNC( name, \
393 "movq $" #nr ",%rax\n\t" \
394 "syscall\n\t" \
395 "ret" )
397 void wld_exit( int code ) __attribute__((noreturn));
398 SYSCALL_NOERR( wld_exit, 60 /* SYS_exit */ );
400 ssize_t wld_read( int fd, void *buffer, size_t len );
401 SYSCALL_FUNC( wld_read, 0 /* SYS_read */ );
403 ssize_t wld_write( int fd, const void *buffer, size_t len );
404 SYSCALL_FUNC( wld_write, 1 /* SYS_write */ );
406 int wld_open( const char *name, int flags );
407 SYSCALL_FUNC( wld_open, 2 /* SYS_open */ );
409 int wld_close( int fd );
410 SYSCALL_FUNC( wld_close, 3 /* SYS_close */ );
412 void *wld_mmap( void *start, size_t len, int prot, int flags, int fd, off_t offset );
413 SYSCALL_FUNC( wld_mmap, 9 /* SYS_mmap */ );
415 int wld_mprotect( const void *addr, size_t len, int prot );
416 SYSCALL_FUNC( wld_mprotect, 10 /* SYS_mprotect */ );
418 int wld_prctl( int code, int arg );
419 SYSCALL_FUNC( wld_prctl, 157 /* SYS_prctl */ );
421 uid_t wld_getuid(void);
422 SYSCALL_NOERR( wld_getuid, 102 /* SYS_getuid */ );
424 gid_t wld_getgid(void);
425 SYSCALL_NOERR( wld_getgid, 104 /* SYS_getgid */ );
427 uid_t wld_geteuid(void);
428 SYSCALL_NOERR( wld_geteuid, 107 /* SYS_geteuid */ );
430 gid_t wld_getegid(void);
431 SYSCALL_NOERR( wld_getegid, 108 /* SYS_getegid */ );
433 #else
434 #error preloader not implemented for this CPU
435 #endif
437 /* replacement for libc functions */
439 static int wld_strcmp( const char *str1, const char *str2 )
441 while (*str1 && (*str1 == *str2)) { str1++; str2++; }
442 return *str1 - *str2;
445 static int wld_strncmp( const char *str1, const char *str2, size_t len )
447 if (len <= 0) return 0;
448 while ((--len > 0) && *str1 && (*str1 == *str2)) { str1++; str2++; }
449 return *str1 - *str2;
452 static inline void *wld_memset( void *dest, int val, size_t len )
454 char *dst = dest;
455 while (len--) *dst++ = val;
456 return dest;
460 * wld_printf - just the basics
462 * %x prints a hex number
463 * %s prints a string
464 * %p prints a pointer
466 static int wld_vsprintf(char *buffer, const char *fmt, va_list args )
468 static const char hex_chars[16] = "0123456789abcdef";
469 const char *p = fmt;
470 char *str = buffer;
471 int i;
473 while( *p )
475 if( *p == '%' )
477 p++;
478 if( *p == 'x' )
480 unsigned int x = va_arg( args, unsigned int );
481 for (i = 2*sizeof(x) - 1; i >= 0; i--)
482 *str++ = hex_chars[(x>>(i*4))&0xf];
484 else if (p[0] == 'l' && p[1] == 'x')
486 unsigned long x = va_arg( args, unsigned long );
487 for (i = 2*sizeof(x) - 1; i >= 0; i--)
488 *str++ = hex_chars[(x>>(i*4))&0xf];
489 p++;
491 else if( *p == 'p' )
493 unsigned long x = (unsigned long)va_arg( args, void * );
494 for (i = 2*sizeof(x) - 1; i >= 0; i--)
495 *str++ = hex_chars[(x>>(i*4))&0xf];
497 else if( *p == 's' )
499 char *s = va_arg( args, char * );
500 while(*s)
501 *str++ = *s++;
503 else if( *p == 0 )
504 break;
505 p++;
507 *str++ = *p++;
509 *str = 0;
510 return str - buffer;
513 static __attribute__((format(printf,1,2))) void wld_printf(const char *fmt, ... )
515 va_list args;
516 char buffer[256];
517 int len;
519 va_start( args, fmt );
520 len = wld_vsprintf(buffer, fmt, args );
521 va_end( args );
522 wld_write(2, buffer, len);
525 static __attribute__((noreturn,format(printf,1,2))) void fatal_error(const char *fmt, ... )
527 va_list args;
528 char buffer[256];
529 int len;
531 va_start( args, fmt );
532 len = wld_vsprintf(buffer, fmt, args );
533 va_end( args );
534 wld_write(2, buffer, len);
535 wld_exit(1);
538 #ifdef DUMP_AUX_INFO
540 * Dump interesting bits of the ELF auxv_t structure that is passed
541 * as the 4th parameter to the _start function
543 static void dump_auxiliary( ElfW(auxv_t) *av )
545 #define NAME(at) { at, #at }
546 static const struct { int val; const char *name; } names[] =
548 NAME(AT_BASE),
549 NAME(AT_CLKTCK),
550 NAME(AT_EGID),
551 NAME(AT_ENTRY),
552 NAME(AT_EUID),
553 NAME(AT_FLAGS),
554 NAME(AT_GID),
555 NAME(AT_HWCAP),
556 NAME(AT_PAGESZ),
557 NAME(AT_PHDR),
558 NAME(AT_PHENT),
559 NAME(AT_PHNUM),
560 NAME(AT_PLATFORM),
561 NAME(AT_SYSINFO),
562 NAME(AT_SYSINFO_EHDR),
563 NAME(AT_UID),
564 { 0, NULL }
566 #undef NAME
568 int i;
570 for ( ; av->a_type != AT_NULL; av++)
572 for (i = 0; names[i].name; i++) if (names[i].val == av->a_type) break;
573 if (names[i].name) wld_printf("%s = %lx\n", names[i].name, (unsigned long)av->a_un.a_val);
574 else wld_printf( "%lx = %lx\n", (unsigned long)av->a_type, (unsigned long)av->a_un.a_val );
577 #endif
580 * set_auxiliary_values
582 * Set the new auxiliary values
584 static void set_auxiliary_values( ElfW(auxv_t) *av, const ElfW(auxv_t) *new_av,
585 const ElfW(auxv_t) *delete_av, void **stack )
587 int i, j, av_count = 0, new_count = 0, delete_count = 0;
588 char *src, *dst;
590 /* count how many aux values we have already */
591 while (av[av_count].a_type != AT_NULL) av_count++;
593 /* delete unwanted values */
594 for (j = 0; delete_av[j].a_type != AT_NULL; j++)
596 for (i = 0; i < av_count; i++) if (av[i].a_type == delete_av[j].a_type)
598 av[i].a_type = av[av_count-1].a_type;
599 av[i].a_un.a_val = av[av_count-1].a_un.a_val;
600 av[--av_count].a_type = AT_NULL;
601 delete_count++;
602 break;
606 /* count how many values we have in new_av that aren't in av */
607 for (j = 0; new_av[j].a_type != AT_NULL; j++)
609 for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
610 if (i == av_count) new_count++;
613 src = (char *)*stack;
614 dst = src - (new_count - delete_count) * sizeof(*av);
615 dst = (char *)((unsigned long)dst & ~15);
616 if (dst < src) /* need to make room for the extra values */
618 int len = (char *)(av + av_count + 1) - src;
619 for (i = 0; i < len; i++) dst[i] = src[i];
621 else if (dst > src) /* get rid of unused values */
623 int len = (char *)(av + av_count + 1) - src;
624 for (i = len - 1; i >= 0; i--) dst[i] = src[i];
626 *stack = dst;
627 av = (ElfW(auxv_t) *)((char *)av + (dst - src));
629 /* now set the values */
630 for (j = 0; new_av[j].a_type != AT_NULL; j++)
632 for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
633 if (i < av_count) av[i].a_un.a_val = new_av[j].a_un.a_val;
634 else
636 av[av_count].a_type = new_av[j].a_type;
637 av[av_count].a_un.a_val = new_av[j].a_un.a_val;
638 av_count++;
642 #ifdef DUMP_AUX_INFO
643 wld_printf("New auxiliary info:\n");
644 dump_auxiliary( av );
645 #endif
649 * get_auxiliary
651 * Get a field of the auxiliary structure
653 static int get_auxiliary( ElfW(auxv_t) *av, int type, int def_val )
655 for ( ; av->a_type != AT_NULL; av++)
656 if( av->a_type == type ) return av->a_un.a_val;
657 return def_val;
661 * map_so_lib
663 * modelled after _dl_map_object_from_fd() from glibc-2.3.1/elf/dl-load.c
665 * This function maps the segments from an ELF object, and optionally
666 * stores information about the mapping into the auxv_t structure.
668 static void map_so_lib( const char *name, struct wld_link_map *l)
670 int fd;
671 unsigned char buf[0x800];
672 ElfW(Ehdr) *header = (ElfW(Ehdr)*)buf;
673 ElfW(Phdr) *phdr, *ph;
674 /* Scan the program header table, collecting its load commands. */
675 struct loadcmd
677 ElfW(Addr) mapstart, mapend, dataend, allocend;
678 off_t mapoff;
679 int prot;
680 } loadcmds[16], *c;
681 size_t nloadcmds = 0, maplength;
683 fd = wld_open( name, O_RDONLY );
684 if (fd == -1) fatal_error("%s: could not open\n", name );
686 if (wld_read( fd, buf, sizeof(buf) ) != sizeof(buf))
687 fatal_error("%s: failed to read ELF header\n", name);
689 phdr = (void*) (((unsigned char*)buf) + header->e_phoff);
691 if( ( header->e_ident[0] != 0x7f ) ||
692 ( header->e_ident[1] != 'E' ) ||
693 ( header->e_ident[2] != 'L' ) ||
694 ( header->e_ident[3] != 'F' ) )
695 fatal_error( "%s: not an ELF binary... don't know how to load it\n", name );
697 #ifdef __i386__
698 if( header->e_machine != EM_386 )
699 fatal_error("%s: not an i386 ELF binary... don't know how to load it\n", name );
700 #elif defined(__x86_64__)
701 if( header->e_machine != EM_X86_64 )
702 fatal_error("%s: not an x86-64 ELF binary... don't know how to load it\n", name );
703 #endif
705 if (header->e_phnum > sizeof(loadcmds)/sizeof(loadcmds[0]))
706 fatal_error( "%s: oops... not enough space for load commands\n", name );
708 maplength = header->e_phnum * sizeof (ElfW(Phdr));
709 if (header->e_phoff + maplength > sizeof(buf))
710 fatal_error( "%s: oops... not enough space for ELF headers\n", name );
712 l->l_ld = 0;
713 l->l_addr = 0;
714 l->l_phdr = 0;
715 l->l_phnum = header->e_phnum;
716 l->l_entry = header->e_entry;
717 l->l_interp = 0;
719 for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
722 #ifdef DUMP_SEGMENTS
723 wld_printf( "ph = %p\n", ph );
724 wld_printf( " p_type = %lx\n", (unsigned long)ph->p_type );
725 wld_printf( " p_flags = %lx\n", (unsigned long)ph->p_flags );
726 wld_printf( " p_offset = %lx\n", (unsigned long)ph->p_offset );
727 wld_printf( " p_vaddr = %lx\n", (unsigned long)ph->p_vaddr );
728 wld_printf( " p_paddr = %lx\n", (unsigned long)ph->p_paddr );
729 wld_printf( " p_filesz = %lx\n", (unsigned long)ph->p_filesz );
730 wld_printf( " p_memsz = %lx\n", (unsigned long)ph->p_memsz );
731 wld_printf( " p_align = %lx\n", (unsigned long)ph->p_align );
732 #endif
734 switch (ph->p_type)
736 /* These entries tell us where to find things once the file's
737 segments are mapped in. We record the addresses it says
738 verbatim, and later correct for the run-time load address. */
739 case PT_DYNAMIC:
740 l->l_ld = (void *) ph->p_vaddr;
741 l->l_ldnum = ph->p_memsz / sizeof (Elf32_Dyn);
742 break;
744 case PT_PHDR:
745 l->l_phdr = (void *) ph->p_vaddr;
746 break;
748 case PT_LOAD:
750 if ((ph->p_align & page_mask) != 0)
751 fatal_error( "%s: ELF load command alignment not page-aligned\n", name );
753 if (((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1)) != 0)
754 fatal_error( "%s: ELF load command address/offset not properly aligned\n", name );
756 c = &loadcmds[nloadcmds++];
757 c->mapstart = ph->p_vaddr & ~(ph->p_align - 1);
758 c->mapend = ((ph->p_vaddr + ph->p_filesz + page_mask) & ~page_mask);
759 c->dataend = ph->p_vaddr + ph->p_filesz;
760 c->allocend = ph->p_vaddr + ph->p_memsz;
761 c->mapoff = ph->p_offset & ~(ph->p_align - 1);
763 c->prot = 0;
764 if (ph->p_flags & PF_R)
765 c->prot |= PROT_READ;
766 if (ph->p_flags & PF_W)
767 c->prot |= PROT_WRITE;
768 if (ph->p_flags & PF_X)
769 c->prot |= PROT_EXEC;
771 break;
773 case PT_INTERP:
774 l->l_interp = ph->p_vaddr;
775 break;
777 case PT_TLS:
779 * We don't need to set anything up because we're
780 * emulating the kernel, not ld-linux.so.2
781 * The ELF loader will set up the TLS data itself.
783 case PT_SHLIB:
784 case PT_NOTE:
785 default:
786 break;
790 /* Now process the load commands and map segments into memory. */
791 if (!nloadcmds)
792 fatal_error( "%s: no segments to load\n", name );
793 c = loadcmds;
795 /* Length of the sections to be loaded. */
796 maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
798 if( header->e_type == ET_DYN )
800 ElfW(Addr) mappref;
801 mappref = (ELF_PREFERRED_ADDRESS (loader, maplength, c->mapstart)
802 - MAP_BASE_ADDR (l));
804 /* Remember which part of the address space this object uses. */
805 l->l_map_start = (ElfW(Addr)) wld_mmap ((void *) mappref, maplength,
806 c->prot, MAP_COPY | MAP_FILE,
807 fd, c->mapoff);
808 /* wld_printf("set : offset = %x\n", c->mapoff); */
809 /* wld_printf("l->l_map_start = %x\n", l->l_map_start); */
811 l->l_map_end = l->l_map_start + maplength;
812 l->l_addr = l->l_map_start - c->mapstart;
814 wld_mprotect ((caddr_t) (l->l_addr + c->mapend),
815 loadcmds[nloadcmds - 1].allocend - c->mapend,
816 PROT_NONE);
817 goto postmap;
819 else
821 /* sanity check */
822 if ((char *)c->mapstart + maplength > preloader_start &&
823 (char *)c->mapstart <= preloader_end)
824 fatal_error( "%s: binary overlaps preloader (%p-%p)\n",
825 name, (char *)c->mapstart, (char *)c->mapstart + maplength );
827 ELF_FIXED_ADDRESS (loader, c->mapstart);
830 /* Remember which part of the address space this object uses. */
831 l->l_map_start = c->mapstart + l->l_addr;
832 l->l_map_end = l->l_map_start + maplength;
834 while (c < &loadcmds[nloadcmds])
836 if (c->mapend > c->mapstart)
837 /* Map the segment contents from the file. */
838 wld_mmap ((void *) (l->l_addr + c->mapstart),
839 c->mapend - c->mapstart, c->prot,
840 MAP_FIXED | MAP_COPY | MAP_FILE, fd, c->mapoff);
842 postmap:
843 if (l->l_phdr == 0
844 && (ElfW(Off)) c->mapoff <= header->e_phoff
845 && ((size_t) (c->mapend - c->mapstart + c->mapoff)
846 >= header->e_phoff + header->e_phnum * sizeof (ElfW(Phdr))))
847 /* Found the program header in this segment. */
848 l->l_phdr = (void *)(unsigned long)(c->mapstart + header->e_phoff - c->mapoff);
850 if (c->allocend > c->dataend)
852 /* Extra zero pages should appear at the end of this segment,
853 after the data mapped from the file. */
854 ElfW(Addr) zero, zeroend, zeropage;
856 zero = l->l_addr + c->dataend;
857 zeroend = l->l_addr + c->allocend;
858 zeropage = (zero + page_mask) & ~page_mask;
861 * This is different from the dl-load load...
862 * ld-linux.so.2 relies on the whole page being zero'ed
864 zeroend = (zeroend + page_mask) & ~page_mask;
866 if (zeroend < zeropage)
868 /* All the extra data is in the last page of the segment.
869 We can just zero it. */
870 zeropage = zeroend;
873 if (zeropage > zero)
875 /* Zero the final part of the last page of the segment. */
876 if ((c->prot & PROT_WRITE) == 0)
878 /* Dag nab it. */
879 wld_mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot|PROT_WRITE);
881 wld_memset ((void *) zero, '\0', zeropage - zero);
882 if ((c->prot & PROT_WRITE) == 0)
883 wld_mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot);
886 if (zeroend > zeropage)
888 /* Map the remaining zero pages in from the zero fill FD. */
889 wld_mmap ((caddr_t) zeropage, zeroend - zeropage,
890 c->prot, MAP_ANON|MAP_PRIVATE|MAP_FIXED,
891 -1, 0);
895 ++c;
898 if (l->l_phdr == NULL) fatal_error("no program header\n");
900 l->l_phdr = (void *)((ElfW(Addr))l->l_phdr + l->l_addr);
901 l->l_entry += l->l_addr;
903 wld_close( fd );
907 static unsigned int elf_hash( const char *name )
909 unsigned int hi, hash = 0;
910 while (*name)
912 hash = (hash << 4) + (unsigned char)*name++;
913 hi = hash & 0xf0000000;
914 hash ^= hi;
915 hash ^= hi >> 24;
917 return hash;
920 static unsigned int gnu_hash( const char *name )
922 unsigned int h = 5381;
923 while (*name) h = h * 33 + (unsigned char)*name++;
924 return h;
928 * Find a symbol in the symbol table of the executable loaded
930 static void *find_symbol( const ElfW(Phdr) *phdr, int num, const char *var, int type )
932 const ElfW(Dyn) *dyn = NULL;
933 const ElfW(Phdr) *ph;
934 const ElfW(Sym) *symtab = NULL;
935 const Elf_Symndx *hashtab = NULL;
936 const Elf32_Word *gnu_hashtab = NULL;
937 const char *strings = NULL;
938 Elf_Symndx idx;
940 /* check the values */
941 #ifdef DUMP_SYMS
942 wld_printf("%p %x\n", phdr, num );
943 #endif
944 if( ( phdr == NULL ) || ( num == 0 ) )
946 wld_printf("could not find PT_DYNAMIC header entry\n");
947 return NULL;
950 /* parse the (already loaded) ELF executable's header */
951 for (ph = phdr; ph < &phdr[num]; ++ph)
953 if( PT_DYNAMIC == ph->p_type )
955 dyn = (void *) ph->p_vaddr;
956 num = ph->p_memsz / sizeof (*dyn);
957 break;
960 if( !dyn ) return NULL;
962 while( dyn->d_tag )
964 if( dyn->d_tag == DT_STRTAB )
965 strings = (const char*) dyn->d_un.d_ptr;
966 if( dyn->d_tag == DT_SYMTAB )
967 symtab = (const ElfW(Sym) *)dyn->d_un.d_ptr;
968 if( dyn->d_tag == DT_HASH )
969 hashtab = (const Elf_Symndx *)dyn->d_un.d_ptr;
970 if( dyn->d_tag == DT_GNU_HASH )
971 gnu_hashtab = (const Elf32_Word *)dyn->d_un.d_ptr;
972 #ifdef DUMP_SYMS
973 wld_printf("%lx %p\n", (unsigned long)dyn->d_tag, (void *)dyn->d_un.d_ptr );
974 #endif
975 dyn++;
978 if( (!symtab) || (!strings) ) return NULL;
980 if (gnu_hashtab) /* new style hash table */
982 const unsigned int hash = gnu_hash(var);
983 const Elf32_Word nbuckets = gnu_hashtab[0];
984 const Elf32_Word symbias = gnu_hashtab[1];
985 const Elf32_Word nwords = gnu_hashtab[2];
986 const ElfW(Addr) *bitmask = (const ElfW(Addr) *)(gnu_hashtab + 4);
987 const Elf32_Word *buckets = (const Elf32_Word *)(bitmask + nwords);
988 const Elf32_Word *chains = buckets + nbuckets - symbias;
990 if (!(idx = buckets[hash % nbuckets])) return NULL;
993 if ((chains[idx] & ~1u) == (hash & ~1u) &&
994 symtab[idx].st_info == ELF32_ST_INFO( STB_GLOBAL, type ) &&
995 !wld_strcmp( strings + symtab[idx].st_name, var ))
996 goto found;
997 } while (!(chains[idx++] & 1u));
999 else if (hashtab) /* old style hash table */
1001 const unsigned int hash = elf_hash(var);
1002 const Elf_Symndx nbuckets = hashtab[0];
1003 const Elf_Symndx *buckets = hashtab + 2;
1004 const Elf_Symndx *chains = buckets + nbuckets;
1006 for (idx = buckets[hash % nbuckets]; idx != STN_UNDEF; idx = chains[idx])
1008 if (symtab[idx].st_info == ELF32_ST_INFO( STB_GLOBAL, type ) &&
1009 !wld_strcmp( strings + symtab[idx].st_name, var ))
1010 goto found;
1013 return NULL;
1015 found:
1016 #ifdef DUMP_SYMS
1017 wld_printf("Found %s -> %p\n", strings + symtab[idx].st_name, (void *)symtab[idx].st_value );
1018 #endif
1019 return (void *)symtab[idx].st_value;
1023 * preload_reserve
1025 * Reserve a range specified in string format
1027 static void preload_reserve( const char *str )
1029 const char *p;
1030 unsigned long result = 0;
1031 void *start = NULL, *end = NULL;
1032 int i, first = 1;
1034 for (p = str; *p; p++)
1036 if (*p >= '0' && *p <= '9') result = result * 16 + *p - '0';
1037 else if (*p >= 'a' && *p <= 'f') result = result * 16 + *p - 'a' + 10;
1038 else if (*p >= 'A' && *p <= 'F') result = result * 16 + *p - 'A' + 10;
1039 else if (*p == '-')
1041 if (!first) goto error;
1042 start = (void *)(result & ~page_mask);
1043 result = 0;
1044 first = 0;
1046 else goto error;
1048 if (!first) end = (void *)((result + page_mask) & ~page_mask);
1049 else if (result) goto error; /* single value '0' is allowed */
1051 /* sanity checks */
1052 if (end <= start) start = end = NULL;
1053 else if ((char *)end > preloader_start &&
1054 (char *)start <= preloader_end)
1056 wld_printf( "WINEPRELOADRESERVE range %p-%p overlaps preloader %p-%p\n",
1057 start, end, preloader_start, preloader_end );
1058 start = end = NULL;
1061 /* check for overlap with low memory areas */
1062 for (i = 0; preload_info[i].size; i++)
1064 if ((char *)preload_info[i].addr > (char *)0x00110000) break;
1065 if ((char *)end <= (char *)preload_info[i].addr + preload_info[i].size)
1067 start = end = NULL;
1068 break;
1070 if ((char *)start < (char *)preload_info[i].addr + preload_info[i].size)
1071 start = (char *)preload_info[i].addr + preload_info[i].size;
1074 while (preload_info[i].size) i++;
1075 preload_info[i].addr = start;
1076 preload_info[i].size = (char *)end - (char *)start;
1077 return;
1079 error:
1080 fatal_error( "invalid WINEPRELOADRESERVE value '%s'\n", str );
1083 /* check if address is in one of the reserved ranges */
1084 static int is_addr_reserved( const void *addr )
1086 int i;
1088 for (i = 0; preload_info[i].size; i++)
1090 if ((const char *)addr >= (const char *)preload_info[i].addr &&
1091 (const char *)addr < (const char *)preload_info[i].addr + preload_info[i].size)
1092 return 1;
1094 return 0;
1097 /* remove a range from the preload list */
1098 static void remove_preload_range( int i )
1100 while (preload_info[i].size)
1102 preload_info[i].addr = preload_info[i+1].addr;
1103 preload_info[i].size = preload_info[i+1].size;
1104 i++;
1109 * is_in_preload_range
1111 * Check if address of the given aux value is in one of the reserved ranges
1113 static int is_in_preload_range( const ElfW(auxv_t) *av, int type )
1115 while (av->a_type != AT_NULL)
1117 if (av->a_type == type) return is_addr_reserved( (const void *)av->a_un.a_val );
1118 av++;
1120 return 0;
1123 /* set the process name if supported */
1124 static void set_process_name( int argc, char *argv[] )
1126 int i;
1127 unsigned int off;
1128 char *p, *name, *end;
1130 /* set the process short name */
1131 for (p = name = argv[1]; *p; p++) if (p[0] == '/' && p[1]) name = p + 1;
1132 if (wld_prctl( 15 /* PR_SET_NAME */, (long)name ) == -1) return;
1134 /* find the end of the argv array and move everything down */
1135 end = argv[argc - 1];
1136 while (*end) end++;
1137 off = argv[1] - argv[0];
1138 for (p = argv[1]; p <= end; p++) *(p - off) = *p;
1139 wld_memset( end - off, 0, off );
1140 for (i = 1; i < argc; i++) argv[i] -= off;
1145 * wld_start
1147 * Repeat the actions the kernel would do when loading a dynamically linked .so
1148 * Load the binary and then its ELF interpreter.
1149 * Note, we assume that the binary is a dynamically linked ELF shared object.
1151 void* wld_start( void **stack )
1153 long i, *pargc;
1154 char **argv, **p;
1155 char *interp, *reserve = NULL;
1156 ElfW(auxv_t) new_av[12], delete_av[3], *av;
1157 struct wld_link_map main_binary_map, ld_so_map;
1158 struct wine_preload_info **wine_main_preload_info;
1160 pargc = *stack;
1161 argv = (char **)pargc + 1;
1162 if (*pargc < 2) fatal_error( "Usage: %s wine_binary [args]\n", argv[0] );
1164 /* skip over the parameters */
1165 p = argv + *pargc + 1;
1167 /* skip over the environment */
1168 while (*p)
1170 static const char res[] = "WINEPRELOADRESERVE=";
1171 if (!wld_strncmp( *p, res, sizeof(res)-1 )) reserve = *p + sizeof(res) - 1;
1172 p++;
1175 av = (ElfW(auxv_t)*) (p+1);
1176 page_size = get_auxiliary( av, AT_PAGESZ, 4096 );
1177 page_mask = page_size - 1;
1179 preloader_start = (char *)_start - ((unsigned long)_start & page_mask);
1180 preloader_end = (char *)((unsigned long)(_end + page_mask) & ~page_mask);
1182 #ifdef DUMP_AUX_INFO
1183 wld_printf( "stack = %p\n", *stack );
1184 for( i = 0; i < *pargc; i++ ) wld_printf("argv[%lx] = %s\n", i, argv[i]);
1185 dump_auxiliary( av );
1186 #endif
1188 /* reserve memory that Wine needs */
1189 if (reserve) preload_reserve( reserve );
1190 for (i = 0; preload_info[i].size; i++)
1192 if ((char *)av >= (char *)preload_info[i].addr &&
1193 (char *)pargc <= (char *)preload_info[i].addr + preload_info[i].size)
1195 remove_preload_range( i );
1196 i--;
1198 else if (wld_mmap( preload_info[i].addr, preload_info[i].size, PROT_NONE,
1199 MAP_FIXED | MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, -1, 0 ) == (void *)-1)
1201 /* don't warn for low 64k */
1202 if (preload_info[i].addr >= (void *)0x10000)
1203 wld_printf( "preloader: Warning: failed to reserve range %p-%p\n",
1204 preload_info[i].addr, (char *)preload_info[i].addr + preload_info[i].size );
1205 remove_preload_range( i );
1206 i--;
1210 /* add an executable page at the top of the address space to defeat
1211 * broken no-exec protections that play with the code selector limit */
1212 if (is_addr_reserved( (char *)0x80000000 - page_size ))
1213 wld_mprotect( (char *)0x80000000 - page_size, page_size, PROT_EXEC | PROT_READ );
1215 /* load the main binary */
1216 map_so_lib( argv[1], &main_binary_map );
1218 /* load the ELF interpreter */
1219 interp = (char *)main_binary_map.l_addr + main_binary_map.l_interp;
1220 map_so_lib( interp, &ld_so_map );
1222 /* store pointer to the preload info into the appropriate main binary variable */
1223 wine_main_preload_info = find_symbol( main_binary_map.l_phdr, main_binary_map.l_phnum,
1224 "wine_main_preload_info", STT_OBJECT );
1225 if (wine_main_preload_info) *wine_main_preload_info = preload_info;
1226 else wld_printf( "wine_main_preload_info not found\n" );
1228 #define SET_NEW_AV(n,type,val) new_av[n].a_type = (type); new_av[n].a_un.a_val = (val);
1229 SET_NEW_AV( 0, AT_PHDR, (unsigned long)main_binary_map.l_phdr );
1230 SET_NEW_AV( 1, AT_PHENT, sizeof(ElfW(Phdr)) );
1231 SET_NEW_AV( 2, AT_PHNUM, main_binary_map.l_phnum );
1232 SET_NEW_AV( 3, AT_PAGESZ, page_size );
1233 SET_NEW_AV( 4, AT_BASE, ld_so_map.l_addr );
1234 SET_NEW_AV( 5, AT_FLAGS, get_auxiliary( av, AT_FLAGS, 0 ) );
1235 SET_NEW_AV( 6, AT_ENTRY, main_binary_map.l_entry );
1236 SET_NEW_AV( 7, AT_UID, get_auxiliary( av, AT_UID, wld_getuid() ) );
1237 SET_NEW_AV( 8, AT_EUID, get_auxiliary( av, AT_EUID, wld_geteuid() ) );
1238 SET_NEW_AV( 9, AT_GID, get_auxiliary( av, AT_GID, wld_getgid() ) );
1239 SET_NEW_AV(10, AT_EGID, get_auxiliary( av, AT_EGID, wld_getegid() ) );
1240 SET_NEW_AV(11, AT_NULL, 0 );
1241 #undef SET_NEW_AV
1243 i = 0;
1244 /* delete sysinfo values if addresses conflict */
1245 if (is_in_preload_range( av, AT_SYSINFO ) || is_in_preload_range( av, AT_SYSINFO_EHDR ))
1247 delete_av[i++].a_type = AT_SYSINFO;
1248 delete_av[i++].a_type = AT_SYSINFO_EHDR;
1250 delete_av[i].a_type = AT_NULL;
1252 /* get rid of first argument */
1253 set_process_name( *pargc, argv );
1254 pargc[1] = pargc[0] - 1;
1255 *stack = pargc + 1;
1257 set_auxiliary_values( av, new_av, delete_av, stack );
1259 #ifdef DUMP_AUX_INFO
1260 wld_printf("new stack = %p\n", *stack);
1261 wld_printf("jumping to %p\n", (void *)ld_so_map.l_entry);
1262 #endif
1264 return (void *)ld_so_map.l_entry;