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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
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
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
64 #include "wine/port.h"
70 #include <sys/types.h>
73 #ifdef HAVE_SYS_MMAN_H
74 # include <sys/mman.h>
85 #ifdef HAVE_SYS_LINK_H
86 # include <sys/link.h>
92 #define ELF_PREFERRED_ADDRESS(loader, maplength, mapstartpref) (mapstartpref)
93 #define ELF_FIXED_ADDRESS(loader, mapstart) ((void) 0)
95 #define MAP_BASE_ADDR(l) 0
98 #define MAP_COPY MAP_PRIVATE
100 #ifndef MAP_NORESERVE
101 #define MAP_NORESERVE 0
104 static struct wine_preload_info preload_info[] =
106 { (void *)0x00000000, 0x00110000 }, /* DOS area */
107 { (void *)0x80000000, 0x01000000 }, /* shared heap */
108 { (void *)0x00110000, 0x0fef0000 }, /* default PE exe range (may be set with WINEPRELOADRESERVE) */
109 { 0, 0 } /* end of list */
117 /* older systems may not define these */
122 static unsigned int page_size, page_mask;
123 static char *preloader_start, *preloader_end;
125 struct wld_link_map {
132 ElfW(Addr) l_map_start, l_map_end;
138 * The _start function is the entry and exit point of this program
140 * It calls wld_start, passing a pointer to the args it receives
141 * then jumps to the address wld_start returns.
145 __ASM_GLOBAL_FUNC(_start,
147 "\tleal -128(%esp),%esp\n" /* allocate some space for extra aux values */
148 "\tpushl %eax\n" /* orig stack pointer */
149 "\tpushl %esp\n" /* ptr to orig stack pointer */
151 "\tpopl %ecx\n" /* remove ptr to stack pointer */
152 "\tpopl %esp\n" /* new stack pointer */
153 "\tpush %eax\n" /* ELF interpreter entry point */
160 * wld_printf - just the basics
162 * %x prints a hex number
165 static void wld_vsprintf(char *str, const char *fmt, va_list args )
167 static const char hex_chars[16] = "0123456789abcdef";
178 unsigned int x = va_arg( args, unsigned int );
180 *str++ = hex_chars[(x>>(i*4))&0xf];
184 char *s = va_arg( args, char * );
197 static void wld_printf(const char *fmt, ... )
202 va_start( args, fmt );
203 wld_vsprintf(buffer, fmt, args );
205 write(2, buffer, strlen(buffer));
208 static void fatal_error(const char *fmt, ... )
213 va_start( args, fmt );
214 wld_vsprintf(buffer, fmt, args );
216 write(2, buffer, strlen(buffer));
222 * Dump interesting bits of the ELF auxv_t structure that is passed
223 * as the 4th parameter to the _start function
225 static void dump_auxiliary( ElfW(auxv_t) *av )
227 #define NAME(at) { at, #at }
228 static const struct { int val; const char *name; } names[] =
250 for ( ; av->a_type != AT_NULL; av++)
252 for (i = 0; names[i].name; i++) if (names[i].val == av->a_type) break;
253 if (names[i].name) wld_printf("%s = %x\n", names[i].name, av->a_un.a_val);
254 else wld_printf( "%x = %x\n", av->a_type, av->a_un.a_val );
260 * set_auxiliary_values
262 * Set the new auxiliary values
264 static void set_auxiliary_values( ElfW(auxv_t) *av, const ElfW(auxv_t) *new_av, void **stack )
266 int i, j, av_count = 0, new_count = 0;
268 /* count how many aux values we have already */
269 while (av[av_count].a_type != AT_NULL) av_count++;
271 /* count how many values we have in new_av that aren't in av */
272 for (j = 0; new_av[j].a_type != AT_NULL; j++)
274 for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
275 if (i == av_count) new_count++;
278 if (new_count) /* need to make room for the extra values */
280 char *new_stack = (char *)*stack - new_count * sizeof(*av);
281 memmove( new_stack, *stack, (char *)(av + av_count) - (char *)*stack );
286 /* now set the values */
287 for (j = 0; new_av[j].a_type != AT_NULL; j++)
289 for (i = 0; i < av_count; i++) if (av[i].a_type == new_av[j].a_type) break;
290 if (i < av_count) av[i].a_un.a_val = new_av[j].a_un.a_val;
293 av[av_count].a_type = new_av[j].a_type;
294 av[av_count].a_un.a_val = new_av[j].a_un.a_val;
300 wld_printf("New auxiliary info:\n");
301 dump_auxiliary( av );
308 * Get a field of the auxiliary structure
310 static int get_auxiliary( ElfW(auxv_t) *av, int type, int def_val )
312 for ( ; av->a_type != AT_NULL; av++)
313 if( av->a_type == type ) return av->a_un.a_val;
320 * modelled after _dl_map_object_from_fd() from glibc-2.3.1/elf/dl-load.c
322 * This function maps the segments from an ELF object, and optionally
323 * stores information about the mapping into the auxv_t structure.
325 static void map_so_lib( const char *name, struct wld_link_map *l)
328 unsigned char buf[0x800];
329 ElfW(Ehdr) *header = (ElfW(Ehdr)*)buf;
330 ElfW(Phdr) *phdr, *ph;
331 /* Scan the program header table, collecting its load commands. */
334 ElfW(Addr) mapstart, mapend, dataend, allocend;
338 size_t nloadcmds = 0, maplength;
340 fd = open( name, O_RDONLY );
341 if (fd == -1) fatal_error("%s: could not open\n", name );
343 if (read( fd, buf, sizeof(buf) ) != sizeof(buf))
344 fatal_error("%s: failed to read ELF header\n", name);
346 phdr = (void*) (((unsigned char*)buf) + header->e_phoff);
348 if( ( header->e_ident[0] != 0x7f ) ||
349 ( header->e_ident[1] != 'E' ) ||
350 ( header->e_ident[2] != 'L' ) ||
351 ( header->e_ident[3] != 'F' ) )
352 fatal_error( "%s: not an ELF binary... don't know how to load it\n", name );
354 if( header->e_machine != EM_386 )
355 fatal_error("%s: not an i386 ELF binary... don't know how to load it\n", name );
357 if (header->e_phnum > sizeof(loadcmds)/sizeof(loadcmds[0]))
358 fatal_error( "%s: oops... not enough space for load commands\n", name );
360 maplength = header->e_phnum * sizeof (ElfW(Phdr));
361 if (header->e_phoff + maplength > sizeof(buf))
362 fatal_error( "%s: oops... not enough space for ELF headers\n", name );
367 l->l_phnum = header->e_phnum;
368 l->l_entry = header->e_entry;
371 for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph)
375 wld_printf( "ph = %x\n", ph );
376 wld_printf( " p_type = %x\n", ph->p_type );
377 wld_printf( " p_flags = %x\n", ph->p_flags );
378 wld_printf( " p_offset = %x\n", ph->p_offset );
379 wld_printf( " p_vaddr = %x\n", ph->p_vaddr );
380 wld_printf( " p_paddr = %x\n", ph->p_paddr );
381 wld_printf( " p_filesz = %x\n", ph->p_filesz );
382 wld_printf( " p_memsz = %x\n", ph->p_memsz );
383 wld_printf( " p_align = %x\n", ph->p_align );
388 /* These entries tell us where to find things once the file's
389 segments are mapped in. We record the addresses it says
390 verbatim, and later correct for the run-time load address. */
392 l->l_ld = (void *) ph->p_vaddr;
393 l->l_ldnum = ph->p_memsz / sizeof (Elf32_Dyn);
397 l->l_phdr = (void *) ph->p_vaddr;
402 if ((ph->p_align & page_mask) != 0)
403 fatal_error( "%s: ELF load command alignment not page-aligned\n", name );
405 if (((ph->p_vaddr - ph->p_offset) & (ph->p_align - 1)) != 0)
406 fatal_error( "%s: ELF load command address/offset not properly aligned\n", name );
408 c = &loadcmds[nloadcmds++];
409 c->mapstart = ph->p_vaddr & ~(ph->p_align - 1);
410 c->mapend = ((ph->p_vaddr + ph->p_filesz + page_mask) & ~page_mask);
411 c->dataend = ph->p_vaddr + ph->p_filesz;
412 c->allocend = ph->p_vaddr + ph->p_memsz;
413 c->mapoff = ph->p_offset & ~(ph->p_align - 1);
416 if (ph->p_flags & PF_R)
417 c->prot |= PROT_READ;
418 if (ph->p_flags & PF_W)
419 c->prot |= PROT_WRITE;
420 if (ph->p_flags & PF_X)
421 c->prot |= PROT_EXEC;
426 l->l_interp = ph->p_vaddr;
431 * We don't need to set anything up because we're
432 * emulating the kernel, not ld-linux.so.2
433 * The ELF loader will set up the TLS data itself.
442 /* Now process the load commands and map segments into memory. */
445 /* Length of the sections to be loaded. */
446 maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart;
448 if( header->e_type == ET_DYN )
451 mappref = (ELF_PREFERRED_ADDRESS (loader, maplength, c->mapstart)
452 - MAP_BASE_ADDR (l));
454 /* Remember which part of the address space this object uses. */
455 l->l_map_start = (ElfW(Addr)) mmap ((void *) mappref, maplength,
456 c->prot, MAP_COPY | MAP_FILE,
458 /* wld_printf("set : offset = %x\n", c->mapoff); */
459 /* wld_printf("l->l_map_start = %x\n", l->l_map_start); */
461 l->l_map_end = l->l_map_start + maplength;
462 l->l_addr = l->l_map_start - c->mapstart;
464 mprotect ((caddr_t) (l->l_addr + c->mapend),
465 loadcmds[nloadcmds - 1].allocend - c->mapend,
472 if ((char *)c->mapstart + maplength > preloader_start &&
473 (char *)c->mapstart <= preloader_end)
474 fatal_error( "%s: binary overlaps preloader (%x-%x)\n",
475 name, c->mapstart, (char *)c->mapstart + maplength );
477 ELF_FIXED_ADDRESS (loader, c->mapstart);
480 /* Remember which part of the address space this object uses. */
481 l->l_map_start = c->mapstart + l->l_addr;
482 l->l_map_end = l->l_map_start + maplength;
484 while (c < &loadcmds[nloadcmds])
486 if (c->mapend > c->mapstart)
487 /* Map the segment contents from the file. */
488 mmap ((void *) (l->l_addr + c->mapstart),
489 c->mapend - c->mapstart, c->prot,
490 MAP_FIXED | MAP_COPY | MAP_FILE, fd, c->mapoff);
494 && (ElfW(Off)) c->mapoff <= header->e_phoff
495 && ((size_t) (c->mapend - c->mapstart + c->mapoff)
496 >= header->e_phoff + header->e_phnum * sizeof (ElfW(Phdr))))
497 /* Found the program header in this segment. */
498 l->l_phdr = (void *)(unsigned int) (c->mapstart + header->e_phoff - c->mapoff);
500 if (c->allocend > c->dataend)
502 /* Extra zero pages should appear at the end of this segment,
503 after the data mapped from the file. */
504 ElfW(Addr) zero, zeroend, zeropage;
506 zero = l->l_addr + c->dataend;
507 zeroend = l->l_addr + c->allocend;
508 zeropage = (zero + page_mask) & ~page_mask;
511 * This is different from the dl-load load...
512 * ld-linux.so.2 relies on the whole page being zero'ed
514 zeroend = (zeroend + page_mask) & ~page_mask;
516 if (zeroend < zeropage)
518 /* All the extra data is in the last page of the segment.
519 We can just zero it. */
525 /* Zero the final part of the last page of the segment. */
526 if ((c->prot & PROT_WRITE) == 0)
529 mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot|PROT_WRITE);
531 memset ((void *) zero, '\0', zeropage - zero);
532 if ((c->prot & PROT_WRITE) == 0)
533 mprotect ((caddr_t) (zero & ~page_mask), page_size, c->prot);
536 if (zeroend > zeropage)
538 /* Map the remaining zero pages in from the zero fill FD. */
540 mapat = mmap ((caddr_t) zeropage, zeroend - zeropage,
541 c->prot, MAP_ANON|MAP_PRIVATE|MAP_FIXED,
549 if (l->l_phdr == NULL) fatal_error("no program header\n");
551 l->l_phdr = (void *)((ElfW(Addr))l->l_phdr + l->l_addr);
552 l->l_entry += l->l_addr;
559 * Find a symbol in the symbol table of the executable loaded
561 static void *find_symbol( const ElfW(Phdr) *phdr, int num, char *var )
563 const ElfW(Dyn) *dyn = NULL;
564 const ElfW(Phdr) *ph;
565 const ElfW(Sym) *symtab = NULL;
566 const char *strings = NULL;
567 uint32_t i, symtabend = 0;
569 /* check the values */
571 wld_printf("%x %x\n", phdr, num );
573 if( ( phdr == NULL ) || ( num == 0 ) )
575 wld_printf("could not find PT_DYNAMIC header entry\n");
579 /* parse the (already loaded) ELF executable's header */
580 for (ph = phdr; ph < &phdr[num]; ++ph)
582 if( PT_DYNAMIC == ph->p_type )
584 dyn = (void *) ph->p_vaddr;
585 num = ph->p_memsz / sizeof (Elf32_Dyn);
589 if( !dyn ) return NULL;
593 if( dyn->d_tag == DT_STRTAB )
594 strings = (const char*) dyn->d_un.d_ptr;
595 if( dyn->d_tag == DT_SYMTAB )
596 symtab = (const ElfW(Sym) *)dyn->d_un.d_ptr;
597 if( dyn->d_tag == DT_HASH )
598 symtabend = *((const uint32_t *)dyn->d_un.d_ptr + 1);
600 wld_printf("%x %x\n", dyn->d_tag, dyn->d_un.d_ptr );
605 if( (!symtab) || (!strings) ) return NULL;
607 for (i = 0; i < symtabend; i++)
609 if( ( ELF32_ST_BIND(symtab[i].st_info) == STT_OBJECT ) &&
610 ( 0 == strcmp( strings+symtab[i].st_name, var ) ) )
613 wld_printf("Found %s -> %x\n", strings+symtab[i].st_name, symtab[i].st_value );
615 return (void*)symtab[i].st_value;
624 * Reserve a range specified in string format
626 static void preload_reserve( const char *str )
629 unsigned long result = 0;
630 void *start = NULL, *end = NULL;
633 for (p = str; *p; p++)
635 if (*p >= '0' && *p <= '9') result = result * 16 + *p - '0';
636 else if (*p >= 'a' && *p <= 'f') result = result * 16 + *p - 'a' + 10;
637 else if (*p >= 'A' && *p <= 'F') result = result * 16 + *p - 'A' + 10;
640 if (!first) goto error;
641 start = (void *)(result & ~page_mask);
647 if (!first) end = (void *)((result + page_mask) & ~page_mask);
648 else if (result) goto error; /* single value '0' is allowed */
651 if (end <= start) start = end = NULL;
652 else if ((char *)end > preloader_start &&
653 (char *)start <= preloader_end)
655 wld_printf( "WINEPRELOADRESERVE range %x-%x overlaps preloader %x-%x\n",
656 start, end, preloader_start, preloader_end );
660 /* entry 2 is for the PE exe */
661 preload_info[2].addr = start;
662 preload_info[2].size = (char *)end - (char *)start;
666 fatal_error( "invalid WINEPRELOADRESERVE value '%s'\n", str );
673 * Repeat the actions the kernel would do when loading a dynamically linked .so
674 * Load the binary and then its ELF interpreter.
675 * Note, we assume that the binary is a dynamically linked ELF shared object.
677 void* wld_start( void **stack )
681 char *interp, *reserve = NULL;
682 ElfW(auxv_t) new_av[11], *av;
683 struct wld_link_map main_binary_map, ld_so_map;
684 struct wine_preload_info **wine_main_preload_info;
687 argv = (char **)pargc + 1;
689 /* skip over the parameters */
690 p = argv + *pargc + 1;
692 /* skip over the environment */
695 static const char res[] = "WINEPRELOADRESERVE=";
696 if (!strncmp( *p, res, sizeof(res)-1 )) reserve = *p + sizeof(res) - 1;
700 av = (ElfW(auxv_t)*) (p+1);
701 page_size = get_auxiliary( av, AT_PAGESZ, 4096 );
702 page_mask = page_size - 1;
704 preloader_start = (char *)_start - ((unsigned int)_start & page_mask);
705 preloader_end = (char *)((unsigned int)(_end + page_mask) & ~page_mask);
708 wld_printf( "stack = %x\n", *stack );
709 for( i = 0; i < *pargc; i++ ) wld_printf("argv[%x] = %s\n", i, argv[i]);
710 dump_auxiliary( av );
713 /* reserve memory that Wine needs */
714 if (reserve) preload_reserve( reserve );
715 for (i = 0; preload_info[i].size; i++)
716 mmap( preload_info[i].addr, preload_info[i].size,
717 PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, -1, 0 );
719 /* load the main binary */
720 map_so_lib( argv[0], &main_binary_map );
722 /* load the ELF interpreter */
723 interp = (char *)main_binary_map.l_addr + main_binary_map.l_interp;
724 map_so_lib( interp, &ld_so_map );
726 /* store pointer to the preload info into the appropriate main binary variable */
727 wine_main_preload_info = find_symbol( main_binary_map.l_phdr, main_binary_map.l_phnum,
728 "wine_main_preload_info" );
729 if (wine_main_preload_info) *wine_main_preload_info = preload_info;
730 else wld_printf( "wine_main_preload_info not found\n" );
732 #define SET_NEW_AV(n,type,val) new_av[n].a_type = (type); new_av[n].a_un.a_val = (val);
733 SET_NEW_AV( 0, AT_PHDR, (unsigned long)main_binary_map.l_phdr );
734 SET_NEW_AV( 1, AT_PHENT, sizeof(ElfW(Phdr)) );
735 SET_NEW_AV( 2, AT_PHNUM, main_binary_map.l_phnum );
736 SET_NEW_AV( 3, AT_PAGESZ, page_size );
737 SET_NEW_AV( 4, AT_BASE, ld_so_map.l_addr );
738 SET_NEW_AV( 5, AT_FLAGS, get_auxiliary( av, AT_FLAGS, 0 ) );
739 SET_NEW_AV( 6, AT_ENTRY, main_binary_map.l_entry );
740 SET_NEW_AV( 7, AT_UID, get_auxiliary( av, AT_UID, getuid() ) );
741 SET_NEW_AV( 8, AT_EUID, get_auxiliary( av, AT_EUID, geteuid() ) );
742 SET_NEW_AV( 9, AT_GID, get_auxiliary( av, AT_GID, getgid() ) );
743 SET_NEW_AV(10, AT_EGID, get_auxiliary( av, AT_EGID, getegid() ) );
746 set_auxiliary_values( av, new_av, stack );
749 wld_printf("new stack = %x\n", *stack);
750 wld_printf("jumping to %x\n", ld_so_map.l_entry);
753 return (void *)ld_so_map.l_entry;