Home | History | Annotate | Line # | Download | only in ld.elf_so
rtld.c revision 1.14
      1 /*	$NetBSD: rtld.c,v 1.14 1999/02/27 10:35:16 pk 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 /*
    122  * Initialize the dynamic linker.  The argument is the address at which
    123  * the dynamic linker has been mapped into memory.  The primary task of
    124  * this function is to relocate the dynamic linker.
    125  */
    126 static void
    127 _rtld_init(
    128     caddr_t mapbase)
    129 {
    130 	Obj_Entry objself;	/* The dynamic linker shared object */
    131 #ifdef RTLD_RELOCATE_SELF
    132 	int dodebug = false;
    133 #else
    134 	int dodebug = true;
    135 #endif
    136 
    137 	memset(&objself, 0, sizeof objself);
    138 
    139 	/* Conjure up an Obj_Entry structure for the dynamic linker. */
    140 	objself.path = NULL;
    141 	objself.rtld = true;
    142 	objself.mapbase = mapbase;
    143 
    144 #if defined(__mips__)
    145 	/*
    146 	* mips and ld.so currently linked at load address,
    147 	* so no relocation needed
    148 	*/
    149 	objself.relocbase = 0;
    150 #else
    151 	objself.relocbase = mapbase;
    152 #endif
    153 
    154 	objself.pltgot = NULL;
    155 
    156 #ifdef OLD_GOT
    157 	objself.dynamic = (Elf_Dyn *)_GLOBAL_OFFSET_TABLE_[0];
    158 #else
    159 	objself.dynamic = (Elf_Dyn *)&_DYNAMIC;
    160 #endif
    161 
    162 #ifdef RTLD_RELOCATE_SELF
    163 	/* We have not been relocated yet, so fix the dynamic address */
    164 	objself.dynamic = (Elf_Dyn *)
    165 		((u_long)mapbase + (char *) objself.dynamic);
    166 #endif /* RTLD_RELOCATE_SELF */
    167 
    168 	_rtld_digest_dynamic(&objself);
    169 
    170 #ifdef __alpha__
    171 	/* XXX XXX XXX */
    172 	objself.pltgot = NULL;
    173 #endif
    174 	assert(objself.needed == NULL);
    175 
    176 #if !defined(__mips__) && !defined(__i386__)
    177 	/* no relocation for mips/i386 */
    178 	assert(!objself.textrel);
    179 #endif
    180 
    181 	_rtld_relocate_objects(&objself, true, dodebug);
    182 
    183 	/*
    184 	 * Now that we relocated ourselves, we can use globals.
    185 	 */
    186 	_rtld_objself = objself;
    187 
    188 	_rtld_objself.path = _rtld_path;
    189 	_rtld_add_paths(&_rtld_paths, RTLD_DEFAULT_LIBRARY_PATH, true);
    190 
    191 	/*
    192 	 * Set up the _rtld_objlist pointer, so that rtld symbols can be found.
    193 	 */
    194 	_rtld_objlist = &_rtld_objself;
    195 
    196 	/* Make the object list empty again. */
    197 	_rtld_objlist = NULL;
    198 	_rtld_objtail = &_rtld_objlist;
    199 
    200 	_rtld_debug.r_brk = _rtld_debug_state;
    201 	_rtld_debug.r_state = RT_CONSISTENT;
    202 }
    203 
    204 /*
    205  * Cleanup procedure.  It will be called (by the atexit() mechanism) just
    206  * before the process exits.
    207  */
    208 static void
    209 _rtld_exit(void)
    210 {
    211 	dbg("rtld_exit()");
    212 
    213 	_rtld_call_fini_functions(_rtld_objlist->next);
    214 }
    215 
    216 /*
    217  * Main entry point for dynamic linking.  The argument is the stack
    218  * pointer.  The stack is expected to be laid out as described in the
    219  * SVR4 ABI specification, Intel 386 Processor Supplement.  Specifically,
    220  * the stack pointer points to a word containing ARGC.  Following that
    221  * in the stack is a null-terminated sequence of pointers to argument
    222  * strings.  Then comes a null-terminated sequence of pointers to
    223  * environment strings.  Finally, there is a sequence of "auxiliary
    224  * vector" entries.
    225  *
    226  * This function returns the entry point for the main program in %eax,
    227  * and the dynamic linker's exit procedure in %edx.  We accomplish this
    228  * by declaring the return value to have the 64-bit type "long long".
    229  * Such values are returned with their most-significant 32 bits in %edx,
    230  * and their least-significant 32 bits in %eax.
    231  */
    232 Elf_Addr _rtld(Elf_Word *);
    233 
    234 Elf_Addr
    235 _rtld(
    236     Elf_Word *sp)
    237 {
    238     const AuxInfo *pAUX_base, *pAUX_entry, *pAUX_execfd,
    239 	          *pAUX_phdr, *pAUX_phent, *pAUX_phnum;
    240     char **env;
    241     const AuxInfo *aux;
    242     const AuxInfo *auxp;
    243     Elf_Word * const osp = sp;
    244     bool bind_now = 0;
    245     const char *ld_bind_now;
    246     const char **argv;
    247 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
    248     int i = 0;
    249 #endif
    250 
    251     /*
    252      * On entry, the dynamic linker itself has not been relocated yet.
    253      * Be very careful not to reference any global data until after
    254      * _rtld_init has returned.  It is OK to reference file-scope statics
    255      * and string constants, and to call static and global functions.
    256      */
    257     /* Find the auxiliary vector on the stack. */
    258     /* first Elf_Word reserved to address of exit routine */
    259 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
    260     dbg("sp = %p, argc = %d, argv = %p <%s>\n", sp, sp[2],
    261 	&sp[3], (char *)sp[3]);
    262     dbg("got is at %p, dynamic is at %p\n", _GLOBAL_OFFSET_TABLE_, &_DYNAMIC);
    263     debug = 1;
    264     dbg("_ctype_ is %p\n", _ctype_);
    265 #endif
    266 
    267     sp += 2;		/* skip over return argument space */
    268     argv = (const char **) &sp[1];
    269     sp += sp[0] + 2;	/* Skip over argc, arguments, and NULL terminator */
    270     env = (char **) sp;
    271     while (*sp++ != 0) {	/* Skip over environment, and NULL terminator */
    272 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
    273 	dbg("env[%d] = %p %s\n", i++, (void *)sp[-1], (char *)sp[-1]);
    274 #endif
    275     }
    276     aux = (const AuxInfo *) sp;
    277 
    278     /* Digest the auxiliary vector. */
    279     pAUX_base = pAUX_entry = pAUX_execfd =
    280     	        pAUX_phdr  = pAUX_phent = pAUX_phnum  = NULL;
    281     for (auxp = aux;  auxp->au_id != AUX_null;  ++auxp) {
    282 	switch(auxp->au_id) {
    283 	    case AUX_base:
    284 		pAUX_base   = auxp; break;
    285 	    case AUX_entry:
    286 		pAUX_entry  = auxp; break;
    287 	    case AUX_execfd:
    288 		pAUX_execfd = auxp; break;
    289 	    case AUX_phdr:
    290 		pAUX_phdr   = auxp; break;
    291 	    case AUX_phent:
    292 		pAUX_phent  = auxp; break;
    293 	    case AUX_phnum:
    294 		pAUX_phnum  = auxp; break;
    295 	}
    296     }
    297 
    298     /* Initialize and relocate ourselves. */
    299     assert(pAUX_base != NULL);
    300     _rtld_init((caddr_t) pAUX_base->au_v);
    301 
    302 #ifdef RTLD_DEBUG
    303     dbg("_ctype_ is %p\n", _ctype_);
    304 #endif
    305 
    306     __progname = _rtld_objself.path;
    307     environ = env;
    308 
    309     _rtld_trust = geteuid() == getuid() && getegid() == getgid();
    310 
    311     ld_bind_now = getenv("LD_BIND_NOW");
    312     if (ld_bind_now != NULL && *ld_bind_now != '\0')
    313 	bind_now = true;
    314     if (_rtld_trust) {
    315 #ifdef DEBUG
    316 	const char *ld_debug = getenv("LD_DEBUG");
    317 	if (ld_debug != NULL && *ld_debug != '\0')
    318 	    debug = 1;
    319 #endif
    320 	_rtld_add_paths(&_rtld_paths, getenv("LD_LIBRARY_PATH"), true);
    321     }
    322 
    323     dbg("%s is initialized, base address = %p", __progname,
    324 	(void *)pAUX_base->au_v);
    325 
    326     /*
    327      * Load the main program, or process its program header if it is
    328      * already loaded.
    329      */
    330     if (pAUX_execfd != NULL) {	/* Load the main program. */
    331 	int fd = pAUX_execfd->au_v;
    332 	dbg("loading main program");
    333 	_rtld_objmain = _rtld_map_object(argv[0], fd);
    334 	close(fd);
    335 	if (_rtld_objmain == NULL)
    336 	    _rtld_die();
    337     } else {				/* Main program already loaded. */
    338 	const Elf_Phdr *phdr;
    339 	int phnum;
    340 	caddr_t entry;
    341 
    342 	dbg("processing main program's program header");
    343 	assert(pAUX_phdr != NULL);
    344 	phdr = (const Elf_Phdr *) pAUX_phdr->au_v;
    345 	assert(pAUX_phnum != NULL);
    346 	phnum = pAUX_phnum->au_v;
    347 	assert(pAUX_phent != NULL);
    348 	assert(pAUX_phent->au_v == sizeof(Elf_Phdr));
    349 	assert(pAUX_entry != NULL);
    350 	entry = (caddr_t) pAUX_entry->au_v;
    351 	_rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
    352     }
    353 
    354     _rtld_objmain->path = xstrdup("main program");
    355     _rtld_objmain->mainprog = true;
    356     _rtld_digest_dynamic(_rtld_objmain);
    357 
    358     _rtld_linkmap_add(_rtld_objmain);
    359     _rtld_linkmap_add(&_rtld_objself);
    360 
    361     /* Link the main program into the list of objects. */
    362     *_rtld_objtail = _rtld_objmain;
    363     _rtld_objtail = &_rtld_objmain->next;
    364     ++_rtld_objmain->refcount;
    365 
    366     dbg("loading needed objects");
    367     if (_rtld_load_needed_objects(_rtld_objmain) == -1)
    368 	_rtld_die();
    369 
    370     dbg("relocating objects");
    371     if (_rtld_relocate_objects(_rtld_objmain, bind_now, true) == -1)
    372 	_rtld_die();
    373 
    374     dbg("doing copy relocations");
    375     if (_rtld_do_copy_relocations(_rtld_objmain, true) == -1)
    376 	_rtld_die();
    377 
    378     dbg("calling _init functions");
    379     _rtld_call_init_functions(_rtld_objmain->next);
    380 
    381     dbg("control at program entry point = %p, obj = %p, exit = %p",
    382 	_rtld_objmain->entry, _rtld_objmain, _rtld_exit);
    383 
    384     /* Return with the entry point and the exit procedure in at the top of
    385      * stack.
    386      */
    387 
    388     _rtld_debug_state();	/* say hello to gdb! */
    389 
    390     ((void **) osp)[0] = _rtld_exit;
    391     ((void **) osp)[1] = _rtld_objmain;
    392     return (Elf_Addr) _rtld_objmain->entry;
    393 }
    394 
    395 void
    396 _rtld_die(
    397     void)
    398 {
    399     const char *msg = _rtld_dlerror();
    400 
    401     if (msg == NULL)
    402 	msg = "Fatal error";
    403     xerrx(1, "%s\n", msg);
    404 }
    405 
    406 static Obj_Entry *
    407 _rtld_dlcheck(
    408     void *handle)
    409 {
    410     Obj_Entry *obj;
    411 
    412     for (obj = _rtld_objlist;  obj != NULL;  obj = obj->next)
    413 	if (obj == (Obj_Entry *) handle)
    414 	    break;
    415 
    416     if (obj == NULL || obj->dl_refcount == 0) {
    417 	xwarnx("Invalid shared object handle %p", handle);
    418 	return NULL;
    419     }
    420     return obj;
    421 }
    422 
    423 static void
    424 _rtld_unref_object_dag(
    425     Obj_Entry *root)
    426 {
    427     assert(root->refcount != 0);
    428     --root->refcount;
    429     if (root->refcount == 0) {
    430 	const Needed_Entry *needed;
    431 
    432 	for (needed = root->needed;  needed != NULL;  needed = needed->next)
    433 	    _rtld_unref_object_dag(needed->obj);
    434     }
    435 }
    436 
    437 int
    438 _rtld_dlclose(
    439     void *handle)
    440 {
    441     Obj_Entry *root = _rtld_dlcheck(handle);
    442 
    443     if (root == NULL)
    444 	return -1;
    445 
    446     _rtld_debug.r_state = RT_DELETE;
    447     _rtld_debug_state();
    448 
    449     --root->dl_refcount;
    450     _rtld_unref_object_dag(root);
    451     if (root->refcount == 0) {	/* We are finished with some objects. */
    452 	Obj_Entry *obj;
    453 	Obj_Entry **linkp;
    454 
    455 	/* Finalize objects that are about to be unmapped. */
    456 	for (obj = _rtld_objlist->next;  obj != NULL;  obj = obj->next)
    457 	    if (obj->refcount == 0 && obj->fini != NULL)
    458 		(*obj->fini)();
    459 
    460 	/* Unmap all objects that are no longer referenced. */
    461 	linkp = &_rtld_objlist->next;
    462 	while((obj = *linkp) != NULL) {
    463 	    if (obj->refcount == 0) {
    464 		munmap(obj->mapbase, obj->mapsize);
    465 		free(obj->path);
    466 		while(obj->needed != NULL) {
    467 		    Needed_Entry *needed = obj->needed;
    468 		    obj->needed = needed->next;
    469 		    free(needed);
    470 		}
    471 		_rtld_linkmap_delete(obj);
    472 		*linkp = obj->next;
    473 		if (obj->next == NULL)
    474 		    _rtld_objtail = linkp;
    475 		free(obj);
    476 	    } else
    477 		linkp = &obj->next;
    478 	}
    479     }
    480 
    481     _rtld_debug.r_state = RT_CONSISTENT;
    482     _rtld_debug_state();
    483 
    484     return 0;
    485 }
    486 
    487 char *
    488 _rtld_dlerror(
    489     void)
    490 {
    491     char *msg = error_message;
    492     error_message = NULL;
    493     return msg;
    494 }
    495 
    496 void *
    497 _rtld_dlopen(
    498     const char *name,
    499     int mode)
    500 {
    501     Obj_Entry **old_obj_tail = _rtld_objtail;
    502     Obj_Entry *obj = NULL;
    503 
    504     _rtld_debug.r_state = RT_ADD;
    505     _rtld_debug_state();
    506 
    507     if (name == NULL) {
    508 	obj = _rtld_objmain;
    509     } else {
    510 	char *path = _rtld_find_library(name, NULL);
    511 	if (path != NULL)
    512 	    obj = _rtld_load_object(path, true);
    513     }
    514 
    515     if (obj != NULL) {
    516 	++obj->dl_refcount;
    517 	if (*old_obj_tail != NULL) {		/* We loaded something new. */
    518 	    assert(*old_obj_tail == obj);
    519 
    520 	    /* FIXME - Clean up properly after an error. */
    521 	    if (_rtld_load_needed_objects(obj) == -1) {
    522 		--obj->dl_refcount;
    523 		obj = NULL;
    524 	    } else if (_rtld_relocate_objects(obj, (mode & 3) == RTLD_NOW,
    525 		true) == -1) {
    526 		--obj->dl_refcount;
    527 		obj = NULL;
    528 	    } else {
    529 		_rtld_call_init_functions(obj);
    530 	    }
    531 	}
    532     }
    533 
    534     _rtld_debug.r_state = RT_CONSISTENT;
    535     _rtld_debug_state();
    536 
    537     return obj;
    538 }
    539 
    540 void *
    541 _rtld_dlsym(
    542     void *handle,
    543     const char *name)
    544 {
    545     const Obj_Entry *obj = _rtld_dlcheck(handle);
    546     const Elf_Sym *def;
    547     const Obj_Entry *defobj;
    548 
    549     if (obj == NULL)
    550 	return NULL;
    551 
    552     /*
    553      * FIXME - This isn't correct.  The search should include the whole
    554      * DAG rooted at the given object.
    555      */
    556     def = _rtld_find_symdef(_rtld_objlist, 0, name, obj, &defobj, false);
    557     if (def != NULL)
    558 	return defobj->relocbase + def->st_value;
    559 
    560     _rtld_error("Undefined symbol \"%s\"", name);
    561     return NULL;
    562 }
    563 
    564 /*
    565  * Error reporting function.  Use it like printf.  If formats the message
    566  * into a buffer, and sets things up so that the next call to dlerror()
    567  * will return the message.
    568  */
    569 void
    570 _rtld_error(
    571     const char *fmt, ...)
    572 {
    573     static char buf[512];
    574     va_list ap;
    575 
    576     va_start(ap, fmt);
    577     xvsnprintf(buf, sizeof buf, fmt, ap);
    578     error_message = buf;
    579     va_end(ap);
    580 }
    581 
    582 void
    583 _rtld_debug_state(
    584     void)
    585 {
    586     /* do nothing */
    587 }
    588 
    589 void
    590 _rtld_linkmap_add(
    591     Obj_Entry *obj)
    592 {
    593     struct link_map *l = &obj->linkmap;
    594     struct link_map *prev;
    595 
    596     obj->linkmap.l_name = obj->path;
    597     obj->linkmap.l_addr = obj->mapbase;
    598     obj->linkmap.l_ld = obj->dynamic;
    599 #ifdef __mips__
    600     /* GDB needs load offset on MIPS to use the symbols */
    601     obj->linkmap.l_offs = obj->relocbase;
    602 #endif
    603 
    604     if (_rtld_debug.r_map == NULL) {
    605 	_rtld_debug.r_map = l;
    606 	return;
    607     }
    608 
    609     for (prev = _rtld_debug.r_map; prev->l_next != NULL; prev = prev->l_next)
    610 	;
    611     l->l_prev = prev;
    612     prev->l_next = l;
    613     l->l_next = NULL;
    614 }
    615 
    616 void
    617 _rtld_linkmap_delete(
    618     Obj_Entry *obj)
    619 {
    620     struct link_map *l = &obj->linkmap;
    621 
    622     if (l->l_prev == NULL) {
    623 	if ((_rtld_debug.r_map = l->l_next) != NULL)
    624 	    l->l_next->l_prev = NULL;
    625 	return;
    626     }
    627 
    628     if ((l->l_prev->l_next = l->l_next) != NULL)
    629 	l->l_next->l_prev = l->l_prev;
    630 }
    631