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