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