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