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