quartz: Fix result in put_FullScreenMode().
[wine.git] / loader / preloader.c
blobd0551bae63a6619d1200d0bf1c9c0806a240385d
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 #ifdef __linux__
65 #include "config.h"
67 #include <stdarg.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <sys/types.h>
72 #include <sys/stat.h>
73 #include <fcntl.h>
74 #include <sys/mman.h>
75 #ifdef HAVE_SYS_SYSCALL_H
76 # include <sys/syscall.h>
77 #endif
78 #include <unistd.h>
79 #ifdef HAVE_ELF_H
80 # include <elf.h>
81 #endif
82 #ifdef HAVE_LINK_H
83 # include <link.h>
84 #endif
85 #ifdef HAVE_SYS_LINK_H
86 # include <sys/link.h>
87 #endif
89 #include "wine/asm.h"
90 #include "main.h"
92 #pragma GCC visibility push(hidden)
94 /* ELF definitions */
95 #define ELF_PREFERRED_ADDRESS(loader, maplength, mapstartpref) (mapstartpref)
96 #define ELF_FIXED_ADDRESS(loader, mapstart) ((void) 0)
98 #define MAP_BASE_ADDR(l) 0
100 #ifndef MAP_COPY
101 #define MAP_COPY MAP_PRIVATE
102 #endif
103 #ifndef MAP_NORESERVE
104 #define MAP_NORESERVE 0
105 #endif
107 static struct wine_preload_info preload_info[] =
109 #if defined(__i386__) || defined(__arm__)
110 { (void *)0x00000000, 0x00010000 }, /* low 64k */
111 { (void *)0x00010000, 0x00100000 }, /* DOS area */
112 { (void *)0x00110000, 0x67ef0000 }, /* low memory area */
113 { (void *)0x7f000000, 0x03000000 }, /* top-down allocations + shared user data + virtual heap */
114 #else
115 { (void *)0x000000010000, 0x00100000 }, /* DOS area */
116 { (void *)0x000000110000, 0x67ef0000 }, /* low memory area */
117 { (void *)0x00007f000000, 0x00ff0000 }, /* 32-bit top-down allocations + shared user data */
118 { (void *)0x7ffffe000000, 0x01ff0000 }, /* top-down allocations + virtual heap */
119 #endif
120 { 0, 0 }, /* PE exe range set with WINEPRELOADRESERVE */
121 { 0, 0 } /* end of list */
124 /* debugging */
125 #undef DUMP_SEGMENTS
126 #undef DUMP_AUX_INFO
127 #undef DUMP_SYMS
128 #undef DUMP_MAPS
130 /* older systems may not define these */
131 #ifndef PT_TLS
132 #define PT_TLS 7
133 #endif
135 #ifndef AT_SYSINFO
136 #define AT_SYSINFO 32
137 #endif
138 #ifndef AT_SYSINFO_EHDR
139 #define AT_SYSINFO_EHDR 33
140 #endif
142 #ifndef DT_GNU_HASH
143 #define DT_GNU_HASH 0x6ffffef5
144 #endif
146 static size_t page_size, page_mask;
147 static char *preloader_start, *preloader_end;
149 struct wld_link_map {
150 ElfW(Addr) l_addr;
151 ElfW(Dyn) *l_ld;
152 ElfW(Phdr)*l_phdr;
153 ElfW(Addr) l_entry;
154 ElfW(Half) l_ldnum;
155 ElfW(Half) l_phnum;
156 ElfW(Addr) l_map_start, l_map_end;
157 ElfW(Addr) l_interp;
160 struct wld_auxv
162 ElfW(Addr) a_type;
163 union
165 ElfW(Addr) a_val;
166 } a_un;
170 * The __bb_init_func is an empty function only called when file is
171 * compiled with gcc flags "-fprofile-arcs -ftest-coverage". This
172 * function is normally provided by libc's startup files, but since we
173 * build the preloader with "-nostartfiles -nodefaultlibs", we have to
174 * provide our own (empty) version, otherwise linker fails.
176 void __bb_init_func(void) { return; }
178 #ifdef __i386__
180 /* data for setting up the glibc-style thread-local storage in %gs */
182 static int thread_data[256];
184 struct
186 /* this is the kernel modify_ldt struct */
187 unsigned int entry_number;
188 unsigned long base_addr;
189 unsigned int limit;
190 unsigned int seg_32bit : 1;
191 unsigned int contents : 2;
192 unsigned int read_exec_only : 1;
193 unsigned int limit_in_pages : 1;
194 unsigned int seg_not_present : 1;
195 unsigned int usable : 1;
196 unsigned int garbage : 25;
197 } thread_ldt = { -1, (unsigned long)thread_data, 0xfffff, 1, 0, 0, 1, 0, 1, 0 };
201 * The _start function is the entry and exit point of this program
203 * It calls wld_start, passing a pointer to the args it receives
204 * then jumps to the address wld_start returns.
206 void _start(void);
207 extern char _end[];
208 __ASM_GLOBAL_FUNC(_start,
209 __ASM_CFI("\t.cfi_undefined %eip\n")
210 "\tmovl $243,%eax\n" /* SYS_set_thread_area */
211 "\tmovl $thread_ldt,%ebx\n"
212 "\tint $0x80\n" /* allocate gs segment */
213 "\torl %eax,%eax\n"
214 "\tjl 1f\n"
215 "\tmovl thread_ldt,%eax\n" /* thread_ldt.entry_number */
216 "\tshl $3,%eax\n"
217 "\torl $3,%eax\n"
218 "\tmov %ax,%gs\n"
219 "\tmov %ax,%fs\n" /* set %fs too so libwine can retrieve it later on */
220 "1:\tmovl %esp,%eax\n"
221 "\tleal -136(%esp),%esp\n" /* allocate some space for extra aux values */
222 "\tpushl %eax\n" /* orig stack pointer */
223 "\tpushl %esp\n" /* ptr to orig stack pointer */
224 "\tcall wld_start\n"
225 "\tpopl %ecx\n" /* remove ptr to stack pointer */
226 "\tpopl %esp\n" /* new stack pointer */
227 "\tpush %eax\n" /* ELF interpreter entry point */
228 "\txor %eax,%eax\n"
229 "\txor %ecx,%ecx\n"
230 "\txor %edx,%edx\n"
231 "\tmov %ax,%gs\n" /* clear %gs again */
232 "\tret\n")
234 /* wrappers for Linux system calls */
236 #define SYSCALL_RET(ret) (((ret) < 0 && (ret) > -4096) ? -1 : (ret))
238 static inline __attribute__((noreturn)) void wld_exit( int code )
240 for (;;) /* avoid warning */
241 __asm__ __volatile__( "pushl %%ebx; movl %1,%%ebx; int $0x80; popl %%ebx"
242 : : "a" (1 /* SYS_exit */), "r" (code) );
245 static inline int wld_open( const char *name, int flags )
247 int ret;
248 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
249 : "=a" (ret) : "0" (5 /* SYS_open */), "r" (name), "c" (flags) );
250 return SYSCALL_RET(ret);
253 static inline int wld_close( int fd )
255 int ret;
256 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
257 : "=a" (ret) : "0" (6 /* SYS_close */), "r" (fd) );
258 return SYSCALL_RET(ret);
261 static inline ssize_t wld_read( int fd, void *buffer, size_t len )
263 int ret;
264 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
265 : "=a" (ret)
266 : "0" (3 /* SYS_read */), "r" (fd), "c" (buffer), "d" (len)
267 : "memory" );
268 return SYSCALL_RET(ret);
271 static inline ssize_t wld_write( int fd, const void *buffer, size_t len )
273 int ret;
274 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
275 : "=a" (ret) : "0" (4 /* SYS_write */), "r" (fd), "c" (buffer), "d" (len) );
276 return SYSCALL_RET(ret);
279 static inline int wld_mprotect( const void *addr, size_t len, int prot )
281 int ret;
282 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
283 : "=a" (ret) : "0" (125 /* SYS_mprotect */), "r" (addr), "c" (len), "d" (prot) );
284 return SYSCALL_RET(ret);
287 void *wld_mmap( void *start, size_t len, int prot, int flags, int fd, unsigned int offset );
288 __ASM_GLOBAL_FUNC(wld_mmap,
289 "\tpushl %ebp\n"
290 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
291 "\tpushl %ebx\n"
292 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
293 "\tpushl %esi\n"
294 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
295 "\tpushl %edi\n"
296 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
297 "\tmovl $192,%eax\n" /* SYS_mmap2 */
298 "\tmovl 20(%esp),%ebx\n" /* start */
299 "\tmovl 24(%esp),%ecx\n" /* len */
300 "\tmovl 28(%esp),%edx\n" /* prot */
301 "\tmovl 32(%esp),%esi\n" /* flags */
302 "\tmovl 36(%esp),%edi\n" /* fd */
303 "\tmovl 40(%esp),%ebp\n" /* offset */
304 "\tshrl $12,%ebp\n"
305 "\tint $0x80\n"
306 "\tcmpl $-4096,%eax\n"
307 "\tjbe 2f\n"
308 "\tcmpl $-38,%eax\n" /* ENOSYS */
309 "\tjne 1f\n"
310 "\tmovl $90,%eax\n" /* SYS_mmap */
311 "\tleal 20(%esp),%ebx\n"
312 "\tint $0x80\n"
313 "\tcmpl $-4096,%eax\n"
314 "\tjbe 2f\n"
315 "1:\tmovl $-1,%eax\n"
316 "2:\tpopl %edi\n"
317 __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
318 "\tpopl %esi\n"
319 __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
320 "\tpopl %ebx\n"
321 __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
322 "\tpopl %ebp\n"
323 __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
324 "\tret\n" )
326 static inline int wld_prctl( int code, long arg )
328 int ret;
329 __asm__ __volatile__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
330 : "=a" (ret) : "0" (172 /* SYS_prctl */), "r" (code), "c" (arg) );
331 return SYSCALL_RET(ret);
334 #elif defined(__x86_64__)
336 void *thread_data[256];
339 * The _start function is the entry and exit point of this program
341 * It calls wld_start, passing a pointer to the args it receives
342 * then jumps to the address wld_start returns.
344 void _start(void);
345 extern char _end[];
346 __ASM_GLOBAL_FUNC(_start,
347 __ASM_CFI(".cfi_undefined %rip\n\t")
348 "movq %rsp,%rax\n\t"
349 "leaq -144(%rsp),%rsp\n\t" /* allocate some space for extra aux values */
350 "movq %rax,(%rsp)\n\t" /* orig stack pointer */
351 "leaq thread_data(%rip),%rsi\n\t"
352 "movq $0x1002,%rdi\n\t" /* ARCH_SET_FS */
353 "movq $158,%rax\n\t" /* SYS_arch_prctl */
354 "syscall\n\t"
355 "movq %rsp,%rdi\n\t" /* ptr to orig stack pointer */
356 "call wld_start\n\t"
357 "movq (%rsp),%rsp\n\t" /* new stack pointer */
358 "pushq %rax\n\t" /* ELF interpreter entry point */
359 "xorq %rax,%rax\n\t"
360 "xorq %rcx,%rcx\n\t"
361 "xorq %rdx,%rdx\n\t"
362 "xorq %rsi,%rsi\n\t"
363 "xorq %rdi,%rdi\n\t"
364 "xorq %r8,%r8\n\t"
365 "xorq %r9,%r9\n\t"
366 "xorq %r10,%r10\n\t"
367 "xorq %r11,%r11\n\t"
368 "ret")
370 #define SYSCALL_FUNC( name, nr ) \
371 __ASM_GLOBAL_FUNC( name, \
372 "movq $" #nr ",%rax\n\t" \
373 "movq %rcx,%r10\n\t" \
374 "syscall\n\t" \
375 "leaq 4096(%rax),%rcx\n\t" \
376 "movq $-1,%rdx\n\t" \
377 "cmp $4096,%rcx\n\t" \
378 "cmovb %rdx,%rax\n\t" \
379 "ret" )
381 #define SYSCALL_NOERR( name, nr ) \
382 __ASM_GLOBAL_FUNC( name, \
383 "movq $" #nr ",%rax\n\t" \
384 "syscall\n\t" \
385 "ret" )
387 void wld_exit( int code ) __attribute__((noreturn));
388 SYSCALL_NOERR( wld_exit, 60 /* SYS_exit */ );
390 ssize_t wld_read( int fd, void *buffer, size_t len );
391 SYSCALL_FUNC( wld_read, 0 /* SYS_read */ );
393 ssize_t wld_write( int fd, const void *buffer, size_t len );
394 SYSCALL_FUNC( wld_write, 1 /* SYS_write */ );
396 int wld_open( const char *name, int flags );
397 SYSCALL_FUNC( wld_open, 2 /* SYS_open */ );
399 int wld_close( int fd );
400 SYSCALL_FUNC( wld_close, 3 /* SYS_close */ );
402 void *wld_mmap( void *start, size_t len, int prot, int flags, int fd, off_t offset );
403 SYSCALL_FUNC( wld_mmap, 9 /* SYS_mmap */ );
405 int wld_mprotect( const void *addr, size_t len, int prot );
406 SYSCALL_FUNC( wld_mprotect, 10 /* SYS_mprotect */ );
408 int wld_prctl( int code, long arg );
409 SYSCALL_FUNC( wld_prctl, 157 /* SYS_prctl */ );
411 uid_t wld_getuid(void);
412 SYSCALL_NOERR( wld_getuid, 102 /* SYS_getuid */ );
414 gid_t wld_getgid(void);
415 SYSCALL_NOERR( wld_getgid, 104 /* SYS_getgid */ );
417 uid_t wld_geteuid(void);
418 SYSCALL_NOERR( wld_geteuid, 107 /* SYS_geteuid */ );
420 gid_t wld_getegid(void);
421 SYSCALL_NOERR( wld_getegid, 108 /* SYS_getegid */ );
423 #elif defined(__aarch64__)
425 void *thread_data[256];
428 * The _start function is the entry and exit point of this program
430 * It calls wld_start, passing a pointer to the args it receives
431 * then jumps to the address wld_start returns.
433 void _start(void);
434 extern char _end[];
435 __ASM_GLOBAL_FUNC(_start,
436 "mov x0, SP\n\t"
437 "sub SP, SP, #144\n\t" /* allocate some space for extra aux values */
438 "str x0, [SP]\n\t" /* orig stack pointer */
439 "adrp x0, thread_data\n\t"
440 "add x0, x0, :lo12:thread_data\n\t"
441 "msr tpidr_el0, x0\n\t"
442 "mov x0, SP\n\t" /* ptr to orig stack pointer */
443 "bl wld_start\n\t"
444 "ldr x1, [SP]\n\t" /* new stack pointer */
445 "mov SP, x1\n\t"
446 "mov x30, x0\n\t"
447 "mov x0, #0\n\t"
448 "mov x1, #0\n\t"
449 "mov x2, #0\n\t"
450 "mov x3, #0\n\t"
451 "mov x4, #0\n\t"
452 "mov x5, #0\n\t"
453 "mov x6, #0\n\t"
454 "mov x7, #0\n\t"
455 "mov x8, #0\n\t"
456 "mov x9, #0\n\t"
457 "mov x10, #0\n\t"
458 "mov x11, #0\n\t"
459 "mov x12, #0\n\t"
460 "mov x13, #0\n\t"
461 "mov x14, #0\n\t"
462 "mov x15, #0\n\t"
463 "mov x16, #0\n\t"
464 "mov x17, #0\n\t"
465 "mov x18, #0\n\t"
466 "ret")
468 #define SYSCALL_FUNC( name, nr ) \
469 __ASM_GLOBAL_FUNC( name, \
470 "stp x8, x9, [SP, #-16]!\n\t" \
471 "mov x8, #" #nr "\n\t" \
472 "svc #0\n\t" \
473 "ldp x8, x9, [SP], #16\n\t" \
474 "cmn x0, #1, lsl#12\n\t" \
475 "cinv x0, x0, hi\n\t" \
476 "b.hi 1f\n\t" \
477 "ret\n\t" \
478 "1: mov x0, #-1\n\t" \
479 "ret" )
481 #define SYSCALL_NOERR( name, nr ) \
482 __ASM_GLOBAL_FUNC( name, \
483 "stp x8, x9, [SP, #-16]!\n\t" \
484 "mov x8, #" #nr "\n\t" \
485 "svc #0\n\t" \
486 "ldp x8, x9, [SP], #16\n\t" \
487 "ret" )
489 void wld_exit( int code ) __attribute__((noreturn));
490 SYSCALL_NOERR( wld_exit, 93 /* SYS_exit */ );
492 ssize_t wld_read( int fd, void *buffer, size_t len );
493 SYSCALL_FUNC( wld_read, 63 /* SYS_read */ );
495 ssize_t wld_write( int fd, const void *buffer, size_t len );
496 SYSCALL_FUNC( wld_write, 64 /* SYS_write */ );
498 int wld_openat( int dirfd, const char *name, int flags );
499 SYSCALL_FUNC( wld_openat, 56 /* SYS_openat */ );
501 int wld_open( const char *name, int flags )
503 return wld_openat(-100 /* AT_FDCWD */, name, flags);
506 int wld_close( int fd );
507 SYSCALL_FUNC( wld_close, 57 /* SYS_close */ );
509 void *wld_mmap( void *start, size_t len, int prot, int flags, int fd, off_t offset );
510 SYSCALL_FUNC( wld_mmap, 222 /* SYS_mmap */ );
512 int wld_mprotect( const void *addr, size_t len, int prot );
513 SYSCALL_FUNC( wld_mprotect, 226 /* SYS_mprotect */ );
515 int wld_prctl( int code, long arg );
516 SYSCALL_FUNC( wld_prctl, 167 /* SYS_prctl */ );
518 uid_t wld_getuid(void);
519 SYSCALL_NOERR( wld_getuid, 174 /* SYS_getuid */ );
521 gid_t wld_getgid(void);
522 SYSCALL_NOERR( wld_getgid, 176 /* SYS_getgid */ );
524 uid_t wld_geteuid(void);
525 SYSCALL_NOERR( wld_geteuid, 175 /* SYS_geteuid */ );
527 gid_t wld_getegid(void);
528 SYSCALL_NOERR( wld_getegid, 177 /* SYS_getegid */ );
530 #elif defined(__arm__)
532 void *thread_data[256];
535 * The _start function is the entry and exit point of this program
537 * It calls wld_start, passing a pointer to the args it receives
538 * then jumps to the address wld_start returns.
540 void _start(void);
541 extern char _end[];
542 __ASM_GLOBAL_FUNC(_start,
543 __ASM_EHABI(".cantunwind\n\t")
544 "mov r0, sp\n\t"
545 "sub sp, sp, #144\n\t" /* allocate some space for extra aux values */
546 "str r0, [sp]\n\t" /* orig stack pointer */
547 "ldr r0, =thread_data\n\t"
548 "movw r7, #0x0005\n\t" /* __ARM_NR_set_tls */
549 "movt r7, #0xf\n\t" /* __ARM_NR_set_tls */
550 "svc #0\n\t"
551 "mov r0, sp\n\t" /* ptr to orig stack pointer */
552 "bl wld_start\n\t"
553 "ldr r1, [sp]\n\t" /* new stack pointer */
554 "mov sp, r1\n\t"
555 "mov lr, r0\n\t"
556 "mov r0, #0\n\t"
557 "mov r1, #0\n\t"
558 "mov r2, #0\n\t"
559 "mov r3, #0\n\t"
560 "mov r12, #0\n\t"
561 "bx lr\n\t"
562 ".ltorg\n\t")
564 #define SYSCALL_FUNC( name, nr ) \
565 __ASM_GLOBAL_FUNC( name, \
566 __ASM_EHABI(".cantunwind\n\t") \
567 "push {r4-r5,r7,lr}\n\t" \
568 "ldr r4, [sp, #16]\n\t" \
569 "ldr r5, [sp, #20]\n\t" \
570 "mov r7, #" #nr "\n\t" \
571 "svc #0\n\t" \
572 "cmn r0, #4096\n\t" \
573 "it hi\n\t" \
574 "movhi r0, #-1\n\t" \
575 "pop {r4-r5,r7,pc}\n\t" )
577 #define SYSCALL_NOERR( name, nr ) \
578 __ASM_GLOBAL_FUNC( name, \
579 __ASM_EHABI(".cantunwind\n\t") \
580 "push {r7,lr}\n\t" \
581 "mov r7, #" #nr "\n\t" \
582 "svc #0\n\t" \
583 "pop {r7,pc}\n\t" )
585 void wld_exit( int code ) __attribute__((noreturn));
586 SYSCALL_NOERR( wld_exit, 1 /* SYS_exit */ );
588 ssize_t wld_read( int fd, void *buffer, size_t len );
589 SYSCALL_FUNC( wld_read, 3 /* SYS_read */ );
591 ssize_t wld_write( int fd, const void *buffer, size_t len );
592 SYSCALL_FUNC( wld_write, 4 /* SYS_write */ );
594 int wld_openat( int dirfd, const char *name, int flags );
595 SYSCALL_FUNC( wld_openat, 322 /* SYS_openat */ );
597 int wld_open( const char *name, int flags )
599 return wld_openat(-100 /* AT_FDCWD */, name, flags);
602 int wld_close( int fd );
603 SYSCALL_FUNC( wld_close, 6 /* SYS_close */ );
605 void *wld_mmap2( void *start, size_t len, int prot, int flags, int fd, int offset );
606 SYSCALL_FUNC( wld_mmap2, 192 /* SYS_mmap2 */ );
608 void *wld_mmap( void *start, size_t len, int prot, int flags, int fd, off_t offset )
610 return wld_mmap2(start, len, prot, flags, fd, offset >> 12);
613 int wld_mprotect( const void *addr, size_t len, int prot );
614 SYSCALL_FUNC( wld_mprotect, 125 /* SYS_mprotect */ );
616 int wld_prctl( int code, long arg );
617 SYSCALL_FUNC( wld_prctl, 172 /* SYS_prctl */ );
619 uid_t wld_getuid(void);
620 SYSCALL_NOERR( wld_getuid, 24 /* SYS_getuid */ );
622 gid_t wld_getgid(void);
623 SYSCALL_NOERR( wld_getgid, 47 /* SYS_getgid */ );
625 uid_t wld_geteuid(void);
626 SYSCALL_NOERR( wld_geteuid, 49 /* SYS_geteuid */ );
628 gid_t wld_getegid(void);
629 SYSCALL_NOERR( wld_getegid, 50 /* SYS_getegid */ );
631 unsigned long long __aeabi_uidivmod(unsigned int num, unsigned int den)
633 unsigned int bit = 1;
634 unsigned int quota = 0;
635 if (!den)
636 wld_exit(1);
637 while (den < num && !(den & 0x80000000)) {
638 den <<= 1;
639 bit <<= 1;
641 do {
642 if (den <= num) {
643 quota |= bit;
644 num -= den;
646 bit >>= 1;
647 den >>= 1;
648 } while (bit);
649 return ((unsigned long long)num << 32) | quota;
652 #else
653 #error preloader not implemented for this CPU
654 #endif
656 /* replacement for libc functions */
658 static int wld_strcmp( const char *str1, const char *str2 )
660 while (*str1 && (*str1 == *str2)) { str1++; str2++; }
661 return *str1 - *str2;
664 static int wld_strncmp( const char *str1, const char *str2, size_t len )
666 if (len <= 0) return 0;
667 while ((--len > 0) && *str1 && (*str1 == *str2)) { str1++; str2++; }
668 return *str1 - *str2;
671 static inline void *wld_memset( void *dest, int val, size_t len )
673 char *dst = dest;
674 while (len--) *dst++ = val;
675 return dest;
679 * wld_printf - just the basics
681 * %x prints a hex number
682 * %s prints a string
683 * %p prints a pointer
685 static int wld_vsprintf(char *buffer, const char *fmt, va_list args )
687 static const char hex_chars[16] = "0123456789abcdef";
688 const char *p = fmt;
689 char *str = buffer;
690 int i;
692 while( *p )
694 if( *p == '%' )
696 p++;
697 if( *p == 'x' )
699 unsigned int x = va_arg( args, unsigned int );
700 for (i = 2*sizeof(x) - 1; i >= 0; i--)
701 *str++ = hex_chars[(x>>(i*4))&0xf];
703 else if (p[0] == 'l' && p[1] == 'x')
705 unsigned long x = va_arg( args, unsigned long );
706 for (i = 2*sizeof(x) - 1; i >= 0; i--)
707 *str++ = hex_chars[(x>>(i*4))&0xf];
708 p++;
710 else if( *p == 'p' )
712 unsigned long x = (unsigned long)va_arg( args, void * );
713 for (i = 2*sizeof(x) - 1; i >= 0; i--)
714 *str++ = hex_chars[(x>>(i*4))&0xf];
716 else if( *p == 's' )
718 char *s = va_arg( args, char * );
719 while(*s)
720 *str++ = *s++;
722 else if( *p == 0 )
723 break;
724 p++;
726 *str++ = *p++;
728 *str = 0;
729 return str - buffer;
732 static __attribute__((format(printf,1,2))) void wld_printf(const char *fmt, ... )
734 va_list args;
735 char buffer[256];
736 int len;
738 va_start( args, fmt );
739 len = wld_vsprintf(buffer, fmt, args );
740 va_end( args );
741 wld_write(2, buffer, len);
744 static __attribute__((noreturn,format(printf,1,2))) void fatal_error(const char *fmt, ... )
746 va_list args;
747 char buffer[256];
748 int len;
750 va_start( args, fmt );
751 len = wld_vsprintf(buffer, fmt, args );
752 va_end( args );
753 wld_write(2, buffer, len);
754 wld_exit(1);
758 * The __stack_chk_* symbols are only used when file is compiled with gcc flags
759 * "-fstack-protector". This function is normally provided by libc's startup
760 * files, but since we build the preloader with "-nostartfiles -nodefaultlibs",
761 * we have to provide our own version to keep the linker happy.
763 unsigned long __stack_chk_guard = 0;
765 void __attribute__((noreturn)) __stack_chk_fail(void)
767 static const char message[] = "preloader: stack overrun detected, crashing\n";
769 /* Avoid using non-syscall functions that can re-enter this function */
770 wld_write(2, message, sizeof(message) - 1);
772 /* Deliberate induce crash and possibly dump core */
773 *(volatile char *)0;
775 /* Last resort if the zero page turns out to be actually readable */
776 wld_exit(1);
779 void __attribute__((noreturn)) __stack_chk_fail_local(void)
781 __stack_chk_fail();
784 #ifdef DUMP_AUX_INFO
786 * Dump interesting bits of the ELF auxv_t structure that is passed
787 * as the 4th parameter to the _start function
789 static void dump_auxiliary( struct wld_auxv *av )
791 #define NAME(at) { at, #at }
792 static const struct { int val; const char *name; } names[] =
794 NAME(AT_BASE),
795 NAME(AT_CLKTCK),
796 NAME(AT_EGID),
797 NAME(AT_ENTRY),
798 NAME(AT_EUID),
799 NAME(AT_FLAGS),
800 NAME(AT_GID),
801 NAME(AT_HWCAP),
802 NAME(AT_PAGESZ),
803 NAME(AT_PHDR),
804 NAME(AT_PHENT),
805 NAME(AT_PHNUM),
806 NAME(AT_PLATFORM),
807 NAME(AT_SYSINFO),
808 NAME(AT_SYSINFO_EHDR),
809 NAME(AT_UID),
810 { 0, NULL }
812 #undef NAME
814 int i;
816 for ( ; av->a_type != AT_NULL; av++)
818 for (i = 0; names[i].name; i++) if (names[i].val == av->a_type) break;
819 if (names[i].name) wld_printf("%s = %lx\n", names[i].name, (unsigned long)av->a_un.a_val);
820 else wld_printf( "%lx = %lx\n", (unsigned long)av->a_type, (unsigned long)av->a_un.a_val );
823 #endif
826 * set_auxiliary_values
828 * Set the new auxiliary values
830 static void set_auxiliary_values( struct wld_auxv *av, const struct wld_auxv *new_av,
831 const struct wld_auxv *delete_av, void **stack )
833 int i, j, av_count = 0, new_count = 0, delete_count = 0;
834 char *src, *dst;
836 /* count how many aux values we have already */
837 while (av[av_count].a_type != AT_NULL) av_count++;
839 /* delete unwanted values */
840 for (j = 0; delete_av[j].a_type != AT_NULL; j++)
842 for (i = 0; i < av_count; i++) if (av[i].a_type == delete_av[j].a_type)
844 av[i].a_type = av[av_count-1].a_type;
845 av[i].a_un.a_val = av[av_count-1].a_un.a_val;
846 av[--av_count].a_type = AT_NULL;
847 delete_count++;
848 break;
852 /* count how many values we have in new_av that aren't in av */
853 for (j = 0; new_av[j].a_type != AT_NULL; j++)
855 for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
856 if (i == av_count) new_count++;
859 src = (char *)*stack;
860 dst = src - (new_count - delete_count) * sizeof(*av);
861 dst = (char *)((unsigned long)dst & ~15);
862 if (dst < src) /* need to make room for the extra values */
864 int len = (char *)(av + av_count + 1) - src;
865 for (i = 0; i < len; i++) dst[i] = src[i];
867 else if (dst > src) /* get rid of unused values */
869 int len = (char *)(av + av_count + 1) - src;
870 for (i = len - 1; i >= 0; i--) dst[i] = src[i];
872 *stack = dst;
873 av = (struct wld_auxv *)((char *)av + (dst - src));
875 /* now set the values */
876 for (j = 0; new_av[j].a_type != AT_NULL; j++)
878 for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
879 if (i < av_count) av[i].a_un.a_val = new_av[j].a_un.a_val;
880 else
882 av[av_count].a_type = new_av[j].a_type;
883 av[av_count].a_un.a_val = new_av[j].a_un.a_val;
884 av_count++;
888 #ifdef DUMP_AUX_INFO
889 wld_printf("New auxiliary info:\n");
890 dump_auxiliary( av );
891 #endif
895 * get_auxiliary
897 * Get a field of the auxiliary structure
899 static ElfW(Addr) get_auxiliary( struct wld_auxv *av, int type, ElfW(Addr) def_val )
901 for ( ; av->a_type != AT_NULL; av++)
902 if( av->a_type == type ) return av->a_un.a_val;
903 return def_val;
907 * map_so_lib
909 * modelled after _dl_map_object_from_fd() from glibc-2.3.1/elf/dl-load.c
911 * This function maps the segments from an ELF object, and optionally
912 * stores information about the mapping into the auxv_t structure.
914 static void map_so_lib( const char *name, struct wld_link_map *l)
916 int fd;
917 unsigned char buf[0x800];
918 ElfW(Ehdr) *header = (ElfW(Ehdr)*)buf;
919 ElfW(Phdr) *phdr, *ph;
920 /* Scan the program header table, collecting its load commands. */
921 struct loadcmd
923 ElfW(Addr) mapstart, mapend, dataend, allocend;
924 off_t mapoff;
925 int prot;
926 } loadcmds[16], *c;
927 size_t nloadcmds = 0, maplength;
929 fd = wld_open( name, O_RDONLY );
930 if (fd == -1) fatal_error("%s: could not open\n", name );
932 if (wld_read( fd, buf, sizeof(buf) ) != sizeof(buf))
933 fatal_error("%s: failed to read ELF header\n", name);
935 phdr = (void*) (((unsigned char*)buf) + header->e_phoff);
937 if( ( header->e_ident[0] != 0x7f ) ||
938 ( header->e_ident[1] != 'E' ) ||
939 ( header->e_ident[2] != 'L' ) ||
940 ( header->e_ident[3] != 'F' ) )
941 fatal_error( "%s: not an ELF binary... don't know how to load it\n", name );
943 #ifdef __i386__
944 if( header->e_machine != EM_386 )
945 fatal_error("%s: not an i386 ELF binary... don't know how to load it\n", name );
946 #elif defined(__x86_64__)
947 if( header->e_machine != EM_X86_64 )
948 fatal_error("%s: not an x86-64 ELF binary... don't know how to load it\n", name );
949 #elif defined(__aarch64__)
950 if( header->e_machine != EM_AARCH64 )
951 fatal_error("%s: not an aarch64 ELF binary... don't know how to load it\n", name );
952 #elif defined(__arm__)
953 if( header->e_machine != EM_ARM )
954 fatal_error("%s: not an arm ELF binary... don't know how to load it\n", name );
955 #endif
957 if (header->e_phnum > sizeof(loadcmds)/sizeof(loadcmds[0]))
958 fatal_error( "%s: oops... not enough space for load commands\n", name );
960 maplength = header->e_phnum * sizeof (ElfW(Phdr));
961 if (header->e_phoff + maplength > sizeof(buf))
962 fatal_error( "%s: oops... not enough space for ELF headers\n", name );
964 l->l_ld = 0;
965 l->l_addr = 0;
966 l->l_phdr = 0;
967 l->l_phnum = header->e_phnum;
968 l->l_entry = header->e_entry;
969 l->l_interp = 0;
971 for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
974 #ifdef DUMP_SEGMENTS
975 wld_printf( "ph = %p\n", ph );
976 wld_printf( " p_type = %lx\n", (unsigned long)ph->p_type );
977 wld_printf( " p_flags = %lx\n", (unsigned long)ph->p_flags );
978 wld_printf( " p_offset = %lx\n", (unsigned long)ph->p_offset );
979 wld_printf( " p_vaddr = %lx\n", (unsigned long)ph->p_vaddr );
980 wld_printf( " p_paddr = %lx\n", (unsigned long)ph->p_paddr );
981 wld_printf( " p_filesz = %lx\n", (unsigned long)ph->p_filesz );
982 wld_printf( " p_memsz = %lx\n", (unsigned long)ph->p_memsz );
983 wld_printf( " p_align = %lx\n", (unsigned long)ph->p_align );
984 #endif
986 switch (ph->p_type)
988 /* These entries tell us where to find things once the file's
989 segments are mapped in. We record the addresses it says
990 verbatim, and later correct for the run-time load address. */
991 case PT_DYNAMIC:
992 l->l_ld = (void *) ph->p_vaddr;
993 l->l_ldnum = ph->p_memsz / sizeof (Elf32_Dyn);
994 break;
996 case PT_PHDR:
997 l->l_phdr = (void *) ph->p_vaddr;
998 break;
1000 case PT_LOAD:
1002 if ((ph->p_align & page_mask) != 0)
1003 fatal_error( "%s: ELF load command alignment not page-aligned\n", name );
1005 if (((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1)) != 0)
1006 fatal_error( "%s: ELF load command address/offset not properly aligned\n", name );
1008 c = &loadcmds[nloadcmds++];
1009 c->mapstart = ph->p_vaddr & ~(ph->p_align - 1);
1010 c->mapend = ((ph->p_vaddr + ph->p_filesz + page_mask) & ~page_mask);
1011 c->dataend = ph->p_vaddr + ph->p_filesz;
1012 c->allocend = ph->p_vaddr + ph->p_memsz;
1013 c->mapoff = ph->p_offset & ~(ph->p_align - 1);
1015 c->prot = 0;
1016 if (ph->p_flags & PF_R)
1017 c->prot |= PROT_READ;
1018 if (ph->p_flags & PF_W)
1019 c->prot |= PROT_WRITE;
1020 if (ph->p_flags & PF_X)
1021 c->prot |= PROT_EXEC;
1023 break;
1025 case PT_INTERP:
1026 l->l_interp = ph->p_vaddr;
1027 break;
1029 case PT_TLS:
1031 * We don't need to set anything up because we're
1032 * emulating the kernel, not ld-linux.so.2
1033 * The ELF loader will set up the TLS data itself.
1035 case PT_SHLIB:
1036 case PT_NOTE:
1037 default:
1038 break;
1042 /* Now process the load commands and map segments into memory. */
1043 if (!nloadcmds)
1044 fatal_error( "%s: no segments to load\n", name );
1045 c = loadcmds;
1047 /* Length of the sections to be loaded. */
1048 maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
1050 if( header->e_type == ET_DYN )
1052 ElfW(Addr) mappref;
1053 mappref = (ELF_PREFERRED_ADDRESS (loader, maplength, c->mapstart)
1054 - MAP_BASE_ADDR (l));
1056 /* Remember which part of the address space this object uses. */
1057 l->l_map_start = (ElfW(Addr)) wld_mmap ((void *) mappref, maplength,
1058 c->prot, MAP_COPY | MAP_FILE,
1059 fd, c->mapoff);
1060 /* wld_printf("set : offset = %x\n", c->mapoff); */
1061 /* wld_printf("l->l_map_start = %x\n", l->l_map_start); */
1063 l->l_map_end = l->l_map_start + maplength;
1064 l->l_addr = l->l_map_start - c->mapstart;
1066 wld_mprotect ((caddr_t) (l->l_addr + c->mapend),
1067 loadcmds[nloadcmds - 1].allocend - c->mapend,
1068 PROT_NONE);
1069 goto postmap;
1071 else
1073 /* sanity check */
1074 if ((char *)c->mapstart + maplength > preloader_start &&
1075 (char *)c->mapstart <= preloader_end)
1076 fatal_error( "%s: binary overlaps preloader (%p-%p)\n",
1077 name, (char *)c->mapstart, (char *)c->mapstart + maplength );
1079 ELF_FIXED_ADDRESS (loader, c->mapstart);
1082 /* Remember which part of the address space this object uses. */
1083 l->l_map_start = c->mapstart + l->l_addr;
1084 l->l_map_end = l->l_map_start + maplength;
1086 while (c < &loadcmds[nloadcmds])
1088 if (c->mapend > c->mapstart)
1089 /* Map the segment contents from the file. */
1090 wld_mmap ((void *) (l->l_addr + c->mapstart),
1091 c->mapend - c->mapstart, c->prot,
1092 MAP_FIXED | MAP_COPY | MAP_FILE, fd, c->mapoff);
1094 postmap:
1095 if (l->l_phdr == 0
1096 && (ElfW(Off)) c->mapoff <= header->e_phoff
1097 && ((size_t) (c->mapend - c->mapstart + c->mapoff)
1098 >= header->e_phoff + header->e_phnum * sizeof (ElfW(Phdr))))
1099 /* Found the program header in this segment. */
1100 l->l_phdr = (void *)(unsigned long)(c->mapstart + header->e_phoff - c->mapoff);
1102 if (c->allocend > c->dataend)
1104 /* Extra zero pages should appear at the end of this segment,
1105 after the data mapped from the file. */
1106 ElfW(Addr) zero, zeroend, zeropage;
1108 zero = l->l_addr + c->dataend;
1109 zeroend = l->l_addr + c->allocend;
1110 zeropage = (zero + page_mask) & ~page_mask;
1113 * This is different from the dl-load load...
1114 * ld-linux.so.2 relies on the whole page being zero'ed
1116 zeroend = (zeroend + page_mask) & ~page_mask;
1118 if (zeroend < zeropage)
1120 /* All the extra data is in the last page of the segment.
1121 We can just zero it. */
1122 zeropage = zeroend;
1125 if (zeropage > zero)
1127 /* Zero the final part of the last page of the segment. */
1128 if ((c->prot & PROT_WRITE) == 0)
1130 /* Dag nab it. */
1131 wld_mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot|PROT_WRITE);
1133 wld_memset ((void *) zero, '\0', zeropage - zero);
1134 if ((c->prot & PROT_WRITE) == 0)
1135 wld_mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot);
1138 if (zeroend > zeropage)
1140 /* Map the remaining zero pages in from the zero fill FD. */
1141 wld_mmap ((caddr_t) zeropage, zeroend - zeropage,
1142 c->prot, MAP_ANON|MAP_PRIVATE|MAP_FIXED,
1143 -1, 0);
1147 ++c;
1150 if (l->l_phdr == NULL) fatal_error("no program header\n");
1152 l->l_phdr = (void *)((ElfW(Addr))l->l_phdr + l->l_addr);
1153 l->l_entry += l->l_addr;
1155 wld_close( fd );
1159 static unsigned int wld_elf_hash( const char *name )
1161 unsigned int hi, hash = 0;
1162 while (*name)
1164 hash = (hash << 4) + (unsigned char)*name++;
1165 hi = hash & 0xf0000000;
1166 hash ^= hi;
1167 hash ^= hi >> 24;
1169 return hash;
1172 static unsigned int gnu_hash( const char *name )
1174 unsigned int h = 5381;
1175 while (*name) h = h * 33 + (unsigned char)*name++;
1176 return h;
1180 * Find a symbol in the symbol table of the executable loaded
1182 static void *find_symbol( const struct wld_link_map *map, const char *var, int type )
1184 const ElfW(Dyn) *dyn = NULL;
1185 const ElfW(Phdr) *ph;
1186 const ElfW(Sym) *symtab = NULL;
1187 const Elf32_Word *hashtab = NULL;
1188 const Elf32_Word *gnu_hashtab = NULL;
1189 const char *strings = NULL;
1190 Elf32_Word idx;
1192 /* check the values */
1193 #ifdef DUMP_SYMS
1194 wld_printf("%p %x\n", map->l_phdr, map->l_phnum );
1195 #endif
1196 /* parse the (already loaded) ELF executable's header */
1197 for (ph = map->l_phdr; ph < &map->l_phdr[map->l_phnum]; ++ph)
1199 if( PT_DYNAMIC == ph->p_type )
1201 dyn = (void *)(ph->p_vaddr + map->l_addr);
1202 break;
1205 if( !dyn ) return NULL;
1207 while( dyn->d_tag )
1209 if( dyn->d_tag == DT_STRTAB )
1210 strings = (const char*)(dyn->d_un.d_ptr + map->l_addr);
1211 if( dyn->d_tag == DT_SYMTAB )
1212 symtab = (const ElfW(Sym) *)(dyn->d_un.d_ptr + map->l_addr);
1213 if( dyn->d_tag == DT_HASH )
1214 hashtab = (const Elf32_Word *)(dyn->d_un.d_ptr + map->l_addr);
1215 if( dyn->d_tag == DT_GNU_HASH )
1216 gnu_hashtab = (const Elf32_Word *)(dyn->d_un.d_ptr + map->l_addr);
1217 #ifdef DUMP_SYMS
1218 wld_printf("%lx %p\n", (unsigned long)dyn->d_tag, (void *)dyn->d_un.d_ptr );
1219 #endif
1220 dyn++;
1223 if( (!symtab) || (!strings) ) return NULL;
1225 if (gnu_hashtab) /* new style hash table */
1227 const unsigned int hash = gnu_hash(var);
1228 const Elf32_Word nbuckets = gnu_hashtab[0];
1229 const Elf32_Word symbias = gnu_hashtab[1];
1230 const Elf32_Word nwords = gnu_hashtab[2];
1231 const ElfW(Addr) *bitmask = (const ElfW(Addr) *)(gnu_hashtab + 4);
1232 const Elf32_Word *buckets = (const Elf32_Word *)(bitmask + nwords);
1233 const Elf32_Word *chains = buckets + nbuckets - symbias;
1235 if (!(idx = buckets[hash % nbuckets])) return NULL;
1238 if ((chains[idx] & ~1u) == (hash & ~1u) &&
1239 ELF32_ST_BIND(symtab[idx].st_info) == STB_GLOBAL &&
1240 ELF32_ST_TYPE(symtab[idx].st_info) == type &&
1241 !wld_strcmp( strings + symtab[idx].st_name, var ))
1242 goto found;
1243 } while (!(chains[idx++] & 1u));
1245 else if (hashtab) /* old style hash table */
1247 const unsigned int hash = wld_elf_hash(var);
1248 const Elf32_Word nbuckets = hashtab[0];
1249 const Elf32_Word *buckets = hashtab + 2;
1250 const Elf32_Word *chains = buckets + nbuckets;
1252 for (idx = buckets[hash % nbuckets]; idx; idx = chains[idx])
1254 if (ELF32_ST_BIND(symtab[idx].st_info) == STB_GLOBAL &&
1255 ELF32_ST_TYPE(symtab[idx].st_info) == type &&
1256 !wld_strcmp( strings + symtab[idx].st_name, var ))
1257 goto found;
1260 return NULL;
1262 found:
1263 #ifdef DUMP_SYMS
1264 wld_printf("Found %s -> %p\n", strings + symtab[idx].st_name, (void *)symtab[idx].st_value );
1265 #endif
1266 return (void *)(symtab[idx].st_value + map->l_addr);
1270 * preload_reserve
1272 * Reserve a range specified in string format
1274 static void preload_reserve( const char *str )
1276 const char *p;
1277 unsigned long result = 0;
1278 void *start = NULL, *end = NULL;
1279 int i, first = 1;
1281 for (p = str; *p; p++)
1283 if (*p >= '0' && *p <= '9') result = result * 16 + *p - '0';
1284 else if (*p >= 'a' && *p <= 'f') result = result * 16 + *p - 'a' + 10;
1285 else if (*p >= 'A' && *p <= 'F') result = result * 16 + *p - 'A' + 10;
1286 else if (*p == '-')
1288 if (!first) goto error;
1289 start = (void *)(result & ~page_mask);
1290 result = 0;
1291 first = 0;
1293 else goto error;
1295 if (!first) end = (void *)((result + page_mask) & ~page_mask);
1296 else if (result) goto error; /* single value '0' is allowed */
1298 /* sanity checks */
1299 if (end <= start) start = end = NULL;
1300 else if ((char *)end > preloader_start &&
1301 (char *)start <= preloader_end)
1303 wld_printf( "WINEPRELOADRESERVE range %p-%p overlaps preloader %p-%p\n",
1304 start, end, preloader_start, preloader_end );
1305 start = end = NULL;
1308 /* check for overlap with low memory areas */
1309 for (i = 0; preload_info[i].size; i++)
1311 if ((char *)preload_info[i].addr > (char *)0x00110000) break;
1312 if ((char *)end <= (char *)preload_info[i].addr + preload_info[i].size)
1314 start = end = NULL;
1315 break;
1317 if ((char *)start < (char *)preload_info[i].addr + preload_info[i].size)
1318 start = (char *)preload_info[i].addr + preload_info[i].size;
1321 while (preload_info[i].size) i++;
1322 preload_info[i].addr = start;
1323 preload_info[i].size = (char *)end - (char *)start;
1324 return;
1326 error:
1327 fatal_error( "invalid WINEPRELOADRESERVE value '%s'\n", str );
1330 /* check if address is in one of the reserved ranges */
1331 static int is_addr_reserved( const void *addr )
1333 int i;
1335 for (i = 0; preload_info[i].size; i++)
1337 if ((const char *)addr >= (const char *)preload_info[i].addr &&
1338 (const char *)addr < (const char *)preload_info[i].addr + preload_info[i].size)
1339 return 1;
1341 return 0;
1344 /* remove a range from the preload list */
1345 static void remove_preload_range( int i )
1347 while (preload_info[i].size)
1349 preload_info[i].addr = preload_info[i+1].addr;
1350 preload_info[i].size = preload_info[i+1].size;
1351 i++;
1356 * is_in_preload_range
1358 * Check if address of the given aux value is in one of the reserved ranges
1360 static int is_in_preload_range( const struct wld_auxv *av, int type )
1362 while (av->a_type != AT_NULL)
1364 if (av->a_type == type) return is_addr_reserved( (const void *)av->a_un.a_val );
1365 av++;
1367 return 0;
1370 /* set the process name if supported */
1371 static void set_process_name( int argc, char *argv[] )
1373 int i;
1374 unsigned int off;
1375 char *p, *name, *end;
1377 /* set the process short name */
1378 for (p = name = argv[1]; *p; p++) if (p[0] == '/' && p[1]) name = p + 1;
1379 if (wld_prctl( 15 /* PR_SET_NAME */, (long)name ) == -1) return;
1381 /* find the end of the argv array and move everything down */
1382 end = argv[argc - 1];
1383 while (*end) end++;
1384 off = argv[1] - argv[0];
1385 for (p = argv[1]; p <= end; p++) *(p - off) = *p;
1386 wld_memset( end - off, 0, off );
1387 for (i = 1; i < argc; i++) argv[i] -= off;
1392 * wld_start
1394 * Repeat the actions the kernel would do when loading a dynamically linked .so
1395 * Load the binary and then its ELF interpreter.
1396 * Note, we assume that the binary is a dynamically linked ELF shared object.
1398 void* wld_start( void **stack )
1400 long i, *pargc;
1401 char **argv, **p;
1402 char *interp, *reserve = NULL;
1403 struct wld_auxv new_av[8], delete_av[3], *av;
1404 struct wld_link_map main_binary_map, ld_so_map;
1405 struct wine_preload_info **wine_main_preload_info;
1407 pargc = *stack;
1408 argv = (char **)pargc + 1;
1409 if (*pargc < 2) fatal_error( "Usage: %s wine_binary [args]\n", argv[0] );
1411 /* skip over the parameters */
1412 p = argv + *pargc + 1;
1414 /* skip over the environment */
1415 while (*p)
1417 static const char res[] = "WINEPRELOADRESERVE=";
1418 if (!wld_strncmp( *p, res, sizeof(res)-1 )) reserve = *p + sizeof(res) - 1;
1419 p++;
1422 av = (struct wld_auxv *)(p+1);
1423 page_size = get_auxiliary( av, AT_PAGESZ, 4096 );
1424 page_mask = page_size - 1;
1426 preloader_start = (char *)((unsigned long)_start & ~page_mask);
1427 preloader_end = (char *)((unsigned long)(_end + page_mask) & ~page_mask);
1429 #ifdef DUMP_AUX_INFO
1430 wld_printf( "stack = %p\n", *stack );
1431 for( i = 0; i < *pargc; i++ ) wld_printf("argv[%lx] = %s\n", i, argv[i]);
1432 dump_auxiliary( av );
1433 #endif
1435 /* reserve memory that Wine needs */
1436 if (reserve) preload_reserve( reserve );
1437 for (i = 0; preload_info[i].size; i++)
1439 if ((char *)av >= (char *)preload_info[i].addr &&
1440 (char *)pargc <= (char *)preload_info[i].addr + preload_info[i].size)
1442 remove_preload_range( i );
1443 i--;
1445 else if (wld_mmap( preload_info[i].addr, preload_info[i].size, PROT_NONE,
1446 MAP_FIXED | MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, -1, 0 ) == (void *)-1)
1448 /* don't warn for low 64k */
1449 if (preload_info[i].addr >= (void *)0x10000
1450 #ifdef __aarch64__
1451 && preload_info[i].addr < (void *)0x7fffffffff /* ARM64 address space might end here*/
1452 #endif
1454 wld_printf( "preloader: Warning: failed to reserve range %p-%p\n",
1455 preload_info[i].addr, (char *)preload_info[i].addr + preload_info[i].size );
1456 remove_preload_range( i );
1457 i--;
1461 /* add an executable page at the top of the address space to defeat
1462 * broken no-exec protections that play with the code selector limit */
1463 if (is_addr_reserved( (char *)0x80000000 - page_size ))
1464 wld_mprotect( (char *)0x80000000 - page_size, page_size, PROT_EXEC | PROT_READ );
1466 /* load the main binary */
1467 map_so_lib( argv[1], &main_binary_map );
1469 /* load the ELF interpreter */
1470 interp = (char *)main_binary_map.l_addr + main_binary_map.l_interp;
1471 map_so_lib( interp, &ld_so_map );
1473 /* store pointer to the preload info into the appropriate main binary variable */
1474 wine_main_preload_info = find_symbol( &main_binary_map, "wine_main_preload_info", STT_OBJECT );
1475 if (wine_main_preload_info) *wine_main_preload_info = preload_info;
1476 else wld_printf( "wine_main_preload_info not found\n" );
1478 #define SET_NEW_AV(n,type,val) new_av[n].a_type = (type); new_av[n].a_un.a_val = (val);
1479 SET_NEW_AV( 0, AT_PHDR, (unsigned long)main_binary_map.l_phdr );
1480 SET_NEW_AV( 1, AT_PHENT, sizeof(ElfW(Phdr)) );
1481 SET_NEW_AV( 2, AT_PHNUM, main_binary_map.l_phnum );
1482 SET_NEW_AV( 3, AT_PAGESZ, page_size );
1483 SET_NEW_AV( 4, AT_BASE, ld_so_map.l_addr );
1484 SET_NEW_AV( 5, AT_FLAGS, get_auxiliary( av, AT_FLAGS, 0 ) );
1485 SET_NEW_AV( 6, AT_ENTRY, main_binary_map.l_entry );
1486 SET_NEW_AV( 7, AT_NULL, 0 );
1487 #undef SET_NEW_AV
1489 i = 0;
1490 /* delete sysinfo values if addresses conflict */
1491 if (is_in_preload_range( av, AT_SYSINFO ) || is_in_preload_range( av, AT_SYSINFO_EHDR ))
1493 delete_av[i++].a_type = AT_SYSINFO;
1494 delete_av[i++].a_type = AT_SYSINFO_EHDR;
1496 delete_av[i].a_type = AT_NULL;
1498 /* get rid of first argument */
1499 set_process_name( *pargc, argv );
1500 pargc[1] = pargc[0] - 1;
1501 *stack = pargc + 1;
1503 set_auxiliary_values( av, new_av, delete_av, stack );
1505 #ifdef DUMP_AUX_INFO
1506 wld_printf("new stack = %p\n", *stack);
1507 wld_printf("jumping to %p\n", (void *)ld_so_map.l_entry);
1508 #endif
1509 #ifdef DUMP_MAPS
1511 char buffer[1024];
1512 int len, fd = wld_open( "/proc/self/maps", O_RDONLY );
1513 if (fd != -1)
1515 while ((len = wld_read( fd, buffer, sizeof(buffer) )) > 0) wld_write( 2, buffer, len );
1516 wld_close( fd );
1519 #endif
1521 return (void *)ld_so_map.l_entry;
1524 #pragma GCC visibility pop
1526 #endif /* __linux__ */