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