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