Home | History | Annotate | Line # | Download | only in ld.elf_so
rtld.c revision 1.13
      1 /*	$NetBSD: rtld.c,v 1.13 1999/02/24 18:31:00 christos Exp $	*/
      2 
      3 /*
      4  * Copyright 1996 John D. Polstra.
      5  * Copyright 1996 Matt Thomas <matt (at) 3am-software.com>
      6  * All rights reserved.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. All advertising materials mentioning features or use of this software
     17  *    must display the following acknowledgement:
     18  *      This product includes software developed by John Polstra.
     19  * 4. The name of the author may not be used to endorse or promote products
     20  *    derived from this software without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     25  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     32  */
     33 
     34 /*
     35  * Dynamic linker for ELF.
     36  *
     37  * John Polstra <jdp (at) polstra.com>.
     38  */
     39 
     40 #include <err.h>
     41 #include <errno.h>
     42 #include <fcntl.h>
     43 #include <stdarg.h>
     44 #include <stdio.h>
     45 #include <stdlib.h>
     46 #include <string.h>
     47 #include <unistd.h>
     48 #include <sys/param.h>
     49 #include <sys/mman.h>
     50 #include <dirent.h>
     51 
     52 #include <ctype.h>
     53 
     54 #include <dlfcn.h>
     55 #include "debug.h"
     56 #include "rtld.h"
     57 
     58 #include "sysident.h"
     59 
     60 /*
     61  * Debugging support.
     62  */
     63 
     64 typedef void (*funcptr)(void);
     65 
     66 /*
     67  * Function declarations.
     68  */
     69 static void _rtld_init(caddr_t);
     70 static void _rtld_exit(void);
     71 
     72 /*
     73  * Data declarations.
     74  */
     75 static char *error_message;	/* Message for dlopen(), or NULL */
     76 
     77 struct r_debug _rtld_debug;	/* for GDB; */
     78 bool _rtld_trust;		/* False for setuid and setgid programs */
     79 Obj_Entry *_rtld_objlist;	/* Head of linked list of shared objects */
     80 Obj_Entry **_rtld_objtail;	/* Link field of last object in list */
     81 Obj_Entry *_rtld_objmain;	/* The main program shared object */
     82 Obj_Entry _rtld_objself;	/* The dynamic linker shared object */
     83 char _rtld_path[] = _PATH_RTLD;
     84 
     85 Search_Path *_rtld_paths;
     86 /*
     87  * Global declarations normally provided by crt0.
     88  */
     89 char *__progname;
     90 char **environ;
     91 
     92 #ifdef OLD_GOT
     93 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
     94 #else
     95 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
     96 extern Elf_Dyn _DYNAMIC;
     97 #endif
     98 
     99 static void
    100 _rtld_call_fini_functions(
    101     Obj_Entry *first)
    102 {
    103     Obj_Entry *obj;
    104 
    105     for (obj = first;  obj != NULL;  obj = obj->next)
    106 	if (obj->fini != NULL)
    107 	    (*obj->fini)();
    108 }
    109 
    110 static void
    111 _rtld_call_init_functions(
    112     Obj_Entry *first)
    113 {
    114     if (first != NULL) {
    115 	_rtld_call_init_functions(first->next);
    116 	if (first->init != NULL)
    117 	    (*first->init)();
    118     }
    119 }
    120 
    121 /*
    123  * Initialize the dynamic linker.  The argument is the address at which
    124  * the dynamic linker has been mapped into memory.  The primary task of
    125  * this function is to relocate the dynamic linker.
    126  */
    127 static void
    128 _rtld_init(
    129     caddr_t mapbase)
    130 {
    131     Obj_Entry objself;	/* The dynamic linker shared object */
    132 #ifdef RTLD_RELOCATE_SELF
    133     int dodebug = false;
    134 #else
    135     int dodebug = true;
    136 #endif
    137 
    138     /* Conjure up an Obj_Entry structure for the dynamic linker. */
    139     objself.path = NULL;
    140     objself.rtld = true;
    141     objself.mapbase = mapbase;
    142 #if defined(__mips__)
    143     /*
    144      * mips and ld.so currently linked at load address,
    145      * so no relocation needed
    146      */
    147     objself.relocbase = 0;
    148 #else
    149     objself.relocbase = mapbase;
    150 #endif
    151     objself.pltgot = NULL;
    152 #ifdef OLD_GOT
    153     objself.dynamic = (Elf_Dyn *)_GLOBAL_OFFSET_TABLE_[0];
    154 #else
    155     objself.dynamic = (Elf_Dyn *)&_DYNAMIC;
    156 #endif
    157 
    158 #ifdef RTLD_RELOCATE_SELF
    159     /* We have not been relocated yet, so fix the dynamic address */
    160     objself.dynamic = (Elf_Dyn *)((u_long)mapbase + (char *) objself.dynamic);
    161 #endif /* RTLD_RELOCATE_SELF */
    162 
    163     _rtld_digest_dynamic(&objself);
    164 #ifdef __alpha__
    165     /* XXX XXX XXX */
    166     objself.pltgot = NULL;
    167 #endif
    168     assert(objself.needed == NULL);
    169 #if !defined(__mips__) && !defined(__i386__)
    170     /* no relocation for mips/i386 */
    171     assert(!objself.textrel);
    172 #endif
    173 
    174     _rtld_relocate_objects(&objself, true, dodebug);
    175 
    176     /*
    177      * Now that we relocated ourselves, we can use globals.
    178      */
    179     _rtld_objself = objself;
    180 
    181     _rtld_objself.path = _rtld_path;
    182     _rtld_add_paths(&_rtld_paths, RTLD_DEFAULT_LIBRARY_PATH, true);
    183 
    184     /* Set up the _rtld_objlist pointer, so that rtld symbols can be found. */
    185     _rtld_objlist = &_rtld_objself;
    186 
    187     /* Make the object list empty again. */
    188     _rtld_objlist = NULL;
    189     _rtld_objtail = &_rtld_objlist;
    190 
    191     _rtld_debug.r_brk = _rtld_debug_state;
    192     _rtld_debug.r_state = RT_CONSISTENT;
    193 }
    194 
    195 /*
    197  * Cleanup procedure.  It will be called (by the atexit() mechanism) just
    198  * before the process exits.
    199  */
    200 static void
    201 _rtld_exit(void)
    202 {
    203     dbg("rtld_exit()");
    204 
    205     _rtld_call_fini_functions(_rtld_objlist->next);
    206 }
    207 
    208 /*
    210  * Main entry point for dynamic linking.  The argument is the stack
    211  * pointer.  The stack is expected to be laid out as described in the
    212  * SVR4 ABI specification, Intel 386 Processor Supplement.  Specifically,
    213  * the stack pointer points to a word containing ARGC.  Following that
    214  * in the stack is a null-terminated sequence of pointers to argument
    215  * strings.  Then comes a null-terminated sequence of pointers to
    216  * environment strings.  Finally, there is a sequence of "auxiliary
    217  * vector" entries.
    218  *
    219  * This function returns the entry point for the main program in %eax,
    220  * and the dynamic linker's exit procedure in %edx.  We accomplish this
    221  * by declaring the return value to have the 64-bit type "long long".
    222  * Such values are returned with their most-significant 32 bits in %edx,
    223  * and their least-significant 32 bits in %eax.
    224  */
    225 Elf_Addr _rtld(Elf_Word *);
    226 
    227 Elf_Addr
    228 _rtld(
    229     Elf_Word *sp)
    230 {
    231     const AuxInfo *pAUX_base, *pAUX_entry, *pAUX_execfd,
    232 	          *pAUX_phdr, *pAUX_phent, *pAUX_phnum;
    233     char **env;
    234     const AuxInfo *aux;
    235     const AuxInfo *auxp;
    236     Elf_Word * const osp = sp;
    237     bool bind_now = 0;
    238     const char *ld_bind_now;
    239     const char **argv;
    240 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
    241     int i = 0;
    242 #endif
    243 
    244     /*
    245      * On entry, the dynamic linker itself has not been relocated yet.
    246      * Be very careful not to reference any global data until after
    247      * _rtld_init has returned.  It is OK to reference file-scope statics
    248      * and string constants, and to call static and global functions.
    249      */
    250     /* Find the auxiliary vector on the stack. */
    251     /* first Elf_Word reserved to address of exit routine */
    252 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
    253     dbg("sp = %p, argc = %d, argv = %p <%s>\n", sp, sp[2],
    254 	&sp[3], (char *)sp[3]);
    255     dbg("got is at %p, dynamic is at %p\n", _GLOBAL_OFFSET_TABLE_, &_DYNAMIC);
    256     debug = 1;
    257     dbg("_ctype_ is %p\n", _ctype_);
    258 #endif
    259 
    260     sp += 2;		/* skip over return argument space */
    261     argv = (const char **) &sp[1];
    262     sp += sp[0] + 2;	/* Skip over argc, arguments, and NULL terminator */
    263     env = (char **) sp;
    264     while (*sp++ != 0) {	/* Skip over environment, and NULL terminator */
    265 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
    266 	dbg("env[%d] = %p %s\n", i++, (void *)sp[-1], (char *)sp[-1]);
    267 #endif
    268     }
    269     aux = (const AuxInfo *) sp;
    270 
    271     /* Digest the auxiliary vector. */
    272     pAUX_base = pAUX_entry = pAUX_execfd =
    273     	        pAUX_phdr  = pAUX_phent = pAUX_phnum  = NULL;
    274     for (auxp = aux;  auxp->au_id != AUX_null;  ++auxp) {
    275 	switch(auxp->au_id) {
    276 	    case AUX_base:
    277 		pAUX_base   = auxp; break;
    278 	    case AUX_entry:
    279 		pAUX_entry  = auxp; break;
    280 	    case AUX_execfd:
    281 		pAUX_execfd = auxp; break;
    282 	    case AUX_phdr:
    283 		pAUX_phdr   = auxp; break;
    284 	    case AUX_phent:
    285 		pAUX_phent  = auxp; break;
    286 	    case AUX_phnum:
    287 		pAUX_phnum  = auxp; break;
    288 	}
    289     }
    290 
    291     /* Initialize and relocate ourselves. */
    292     assert(pAUX_base != NULL);
    293     _rtld_init((caddr_t) pAUX_base->au_v);
    294 
    295 #ifdef RTLD_DEBUG
    296     dbg("_ctype_ is %p\n", _ctype_);
    297 #endif
    298 
    299     __progname = _rtld_objself.path;
    300     environ = env;
    301 
    302     _rtld_trust = geteuid() == getuid() && getegid() == getgid();
    303 
    304     ld_bind_now = getenv("LD_BIND_NOW");
    305     if (ld_bind_now != NULL && *ld_bind_now != '\0')
    306 	bind_now = true;
    307     if (_rtld_trust) {
    308 #ifdef DEBUG
    309 	const char *ld_debug = getenv("LD_DEBUG");
    310 	if (ld_debug != NULL && *ld_debug != '\0')
    311 	    debug = 1;
    312 #endif
    313 	_rtld_add_paths(&_rtld_paths, getenv("LD_LIBRARY_PATH"), true);
    314     }
    315 
    316     dbg("%s is initialized, base address = %p", __progname,
    317 	(void *)pAUX_base->au_v);
    318 
    319     /*
    320      * Load the main program, or process its program header if it is
    321      * already loaded.
    322      */
    323     if (pAUX_execfd != NULL) {	/* Load the main program. */
    324 	int fd = pAUX_execfd->au_v;
    325 	dbg("loading main program");
    326 	_rtld_objmain = _rtld_map_object(argv[0], fd);
    327 	close(fd);
    328 	if (_rtld_objmain == NULL)
    329 	    _rtld_die();
    330     } else {				/* Main program already loaded. */
    331 	const Elf_Phdr *phdr;
    332 	int phnum;
    333 	caddr_t entry;
    334 
    335 	dbg("processing main program's program header");
    336 	assert(pAUX_phdr != NULL);
    337 	phdr = (const Elf_Phdr *) pAUX_phdr->au_v;
    338 	assert(pAUX_phnum != NULL);
    339 	phnum = pAUX_phnum->au_v;
    340 	assert(pAUX_phent != NULL);
    341 	assert(pAUX_phent->au_v == sizeof(Elf_Phdr));
    342 	assert(pAUX_entry != NULL);
    343 	entry = (caddr_t) pAUX_entry->au_v;
    344 	_rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
    345     }
    346 
    347     _rtld_objmain->path = xstrdup("main program");
    348     _rtld_objmain->mainprog = true;
    349     _rtld_digest_dynamic(_rtld_objmain);
    350 
    351     _rtld_linkmap_add(_rtld_objmain);
    352     _rtld_linkmap_add(&_rtld_objself);
    353 
    354     /* Link the main program into the list of objects. */
    355     *_rtld_objtail = _rtld_objmain;
    356     _rtld_objtail = &_rtld_objmain->next;
    357     ++_rtld_objmain->refcount;
    358 
    359     dbg("loading needed objects");
    360     if (_rtld_load_needed_objects(_rtld_objmain) == -1)
    361 	_rtld_die();
    362 
    363     dbg("relocating objects");
    364     if (_rtld_relocate_objects(_rtld_objmain, bind_now, true) == -1)
    365 	_rtld_die();
    366 
    367     dbg("doing copy relocations");
    368     if (_rtld_do_copy_relocations(_rtld_objmain, true) == -1)
    369 	_rtld_die();
    370 
    371     dbg("calling _init functions");
    372     _rtld_call_init_functions(_rtld_objmain->next);
    373 
    374     dbg("control at program entry point = %p, obj = %p, exit = %p",
    375 	_rtld_objmain->entry, _rtld_objmain, _rtld_exit);
    376 
    377     /* Return with the entry point and the exit procedure in at the top of
    378      * stack.
    379      */
    380 
    381     _rtld_debug_state();	/* say hello to gdb! */
    382 
    383     ((void **) osp)[0] = _rtld_exit;
    384     ((void **) osp)[1] = _rtld_objmain;
    385     return (Elf_Addr) _rtld_objmain->entry;
    386 }
    387 
    388 void
    389 _rtld_die(
    390     void)
    391 {
    392     const char *msg = _rtld_dlerror();
    393 
    394     if (msg == NULL)
    395 	msg = "Fatal error";
    396     xerrx(1, "%s\n", msg);
    397 }
    398 
    399 static Obj_Entry *
    400 _rtld_dlcheck(
    401     void *handle)
    402 {
    403     Obj_Entry *obj;
    404 
    405     for (obj = _rtld_objlist;  obj != NULL;  obj = obj->next)
    406 	if (obj == (Obj_Entry *) handle)
    407 	    break;
    408 
    409     if (obj == NULL || obj->dl_refcount == 0) {
    410 	xwarnx("Invalid shared object handle %p", handle);
    411 	return NULL;
    412     }
    413     return obj;
    414 }
    415 
    416 static void
    417 _rtld_unref_object_dag(
    418     Obj_Entry *root)
    419 {
    420     assert(root->refcount != 0);
    421     --root->refcount;
    422     if (root->refcount == 0) {
    423 	const Needed_Entry *needed;
    424 
    425 	for (needed = root->needed;  needed != NULL;  needed = needed->next)
    426 	    _rtld_unref_object_dag(needed->obj);
    427     }
    428 }
    429 
    430 int
    431 _rtld_dlclose(
    432     void *handle)
    433 {
    434     Obj_Entry *root = _rtld_dlcheck(handle);
    435 
    436     if (root == NULL)
    437 	return -1;
    438 
    439     _rtld_debug.r_state = RT_DELETE;
    440     _rtld_debug_state();
    441 
    442     --root->dl_refcount;
    443     _rtld_unref_object_dag(root);
    444     if (root->refcount == 0) {	/* We are finished with some objects. */
    445 	Obj_Entry *obj;
    446 	Obj_Entry **linkp;
    447 
    448 	/* Finalize objects that are about to be unmapped. */
    449 	for (obj = _rtld_objlist->next;  obj != NULL;  obj = obj->next)
    450 	    if (obj->refcount == 0 && obj->fini != NULL)
    451 		(*obj->fini)();
    452 
    453 	/* Unmap all objects that are no longer referenced. */
    454 	linkp = &_rtld_objlist->next;
    455 	while((obj = *linkp) != NULL) {
    456 	    if (obj->refcount == 0) {
    457 		munmap(obj->mapbase, obj->mapsize);
    458 		free(obj->path);
    459 		while(obj->needed != NULL) {
    460 		    Needed_Entry *needed = obj->needed;
    461 		    obj->needed = needed->next;
    462 		    free(needed);
    463 		}
    464 		_rtld_linkmap_delete(obj);
    465 		*linkp = obj->next;
    466 		if (obj->next == NULL)
    467 		    _rtld_objtail = linkp;
    468 		free(obj);
    469 	    } else
    470 		linkp = &obj->next;
    471 	}
    472     }
    473 
    474     _rtld_debug.r_state = RT_CONSISTENT;
    475     _rtld_debug_state();
    476 
    477     return 0;
    478 }
    479 
    480 char *
    481 _rtld_dlerror(
    482     void)
    483 {
    484     char *msg = error_message;
    485     error_message = NULL;
    486     return msg;
    487 }
    488 
    489 void *
    490 _rtld_dlopen(
    491     const char *name,
    492     int mode)
    493 {
    494     Obj_Entry **old_obj_tail = _rtld_objtail;
    495     Obj_Entry *obj = NULL;
    496 
    497     _rtld_debug.r_state = RT_ADD;
    498     _rtld_debug_state();
    499 
    500     if (name == NULL) {
    501 	obj = _rtld_objmain;
    502     } else {
    503 	char *path = _rtld_find_library(name, NULL);
    504 	if (path != NULL)
    505 	    obj = _rtld_load_object(path, true);
    506     }
    507 
    508     if (obj != NULL) {
    509 	++obj->dl_refcount;
    510 	if (*old_obj_tail != NULL) {		/* We loaded something new. */
    511 	    assert(*old_obj_tail == obj);
    512 
    513 	    /* FIXME - Clean up properly after an error. */
    514 	    if (_rtld_load_needed_objects(obj) == -1) {
    515 		--obj->dl_refcount;
    516 		obj = NULL;
    517 	    } else if (_rtld_relocate_objects(obj, (mode & 3) == RTLD_NOW,
    518 		true) == -1) {
    519 		--obj->dl_refcount;
    520 		obj = NULL;
    521 	    } else {
    522 		_rtld_call_init_functions(obj);
    523 	    }
    524 	}
    525     }
    526 
    527     _rtld_debug.r_state = RT_CONSISTENT;
    528     _rtld_debug_state();
    529 
    530     return obj;
    531 }
    532 
    533 void *
    534 _rtld_dlsym(
    535     void *handle,
    536     const char *name)
    537 {
    538     const Obj_Entry *obj = _rtld_dlcheck(handle);
    539     const Elf_Sym *def;
    540     const Obj_Entry *defobj;
    541 
    542     if (obj == NULL)
    543 	return NULL;
    544 
    545     /*
    546      * FIXME - This isn't correct.  The search should include the whole
    547      * DAG rooted at the given object.
    548      */
    549     def = _rtld_find_symdef(_rtld_objlist, 0, name, obj, &defobj, false);
    550     if (def != NULL)
    551 	return defobj->relocbase + def->st_value;
    552 
    553     _rtld_error("Undefined symbol \"%s\"", name);
    554     return NULL;
    555 }
    556 
    557 /*
    558  * Error reporting function.  Use it like printf.  If formats the message
    559  * into a buffer, and sets things up so that the next call to dlerror()
    560  * will return the message.
    561  */
    562 void
    563 _rtld_error(
    564     const char *fmt, ...)
    565 {
    566     static char buf[512];
    567     va_list ap;
    568 
    569     va_start(ap, fmt);
    570     xvsnprintf(buf, sizeof buf, fmt, ap);
    571     error_message = buf;
    572     va_end(ap);
    573 }
    574 
    575 void
    577 _rtld_debug_state(
    578     void)
    579 {
    580     /* do nothing */
    581 }
    582 
    583 void
    584 _rtld_linkmap_add(
    585     Obj_Entry *obj)
    586 {
    587     struct link_map *l = &obj->linkmap;
    588     struct link_map *prev;
    589 
    590     obj->linkmap.l_name = obj->path;
    591     obj->linkmap.l_addr = obj->mapbase;
    592     obj->linkmap.l_ld = obj->dynamic;
    593 #ifdef __mips__
    594     /* GDB needs load offset on MIPS to use the symbols */
    595     obj->linkmap.l_offs = obj->relocbase;
    596 #endif
    597 
    598     if (_rtld_debug.r_map == NULL) {
    599 	_rtld_debug.r_map = l;
    600 	return;
    601     }
    602 
    603     for (prev = _rtld_debug.r_map; prev->l_next != NULL; prev = prev->l_next)
    604 	;
    605     l->l_prev = prev;
    606     prev->l_next = l;
    607     l->l_next = NULL;
    608 }
    609 
    610 void
    611 _rtld_linkmap_delete(
    612     Obj_Entry *obj)
    613 {
    614     struct link_map *l = &obj->linkmap;
    615 
    616     if (l->l_prev == NULL) {
    617 	if ((_rtld_debug.r_map = l->l_next) != NULL)
    618 	    l->l_next->l_prev = NULL;
    619 	return;
    620     }
    621 
    622     if ((l->l_prev->l_next = l->l_next) != NULL)
    623 	l->l_next->l_prev = l->l_prev;
    624 }
    625