2 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * Dynamic linker for ELF.
31 * John Polstra <jdp@polstra.com>.
35 #error "GCC is needed to compile this file"
38 #include <sys/param.h>
55 #define END_SYM "_end"
56 #define PATH_RTLD "/usr/libexec/ld-elf.so.1"
59 typedef void (*func_ptr_type)();
61 typedef struct Struct_LockInfo {
62 void *context; /* Client context for creating locks */
63 void *thelock; /* The one big lock */
65 void (*rlock_acquire)(void *lock);
66 void (*wlock_acquire)(void *lock);
67 void (*lock_release)(void *lock);
68 void (*lock_destroy)(void *lock);
69 void (*context_destroy)(void *context);
73 * Function declarations.
75 static const char *basename(const char *);
76 static void die(void);
77 static void digest_dynamic(Obj_Entry *);
78 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
79 static Obj_Entry *dlcheck(void *);
80 static char *find_library(const char *, const Obj_Entry *);
81 static void funclist_call(Funclist *);
82 static void funclist_clear(Funclist *);
83 static void funclist_init(Funclist *);
84 static void funclist_push_head(Funclist *, InitFunc);
85 static void funclist_push_tail(Funclist *, InitFunc);
86 static const char *gethints(void);
87 static void init_dag(Obj_Entry *);
88 static void init_dag1(Obj_Entry *root, Obj_Entry *obj);
89 static void init_rtld(caddr_t);
90 static bool is_exported(const Elf_Sym *);
91 static void linkmap_add(Obj_Entry *);
92 static void linkmap_delete(Obj_Entry *);
93 static int load_needed_objects(Obj_Entry *);
94 static int load_preload_objects(void);
95 static Obj_Entry *load_object(char *);
96 static void lock_nop(void *);
97 static Obj_Entry *obj_from_addr(const void *);
98 static void objlist_add(Objlist *, Obj_Entry *);
99 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
100 static void objlist_remove(Objlist *, Obj_Entry *);
101 static void prebind(void *);
102 static int relocate_objects(Obj_Entry *, bool);
103 static void rtld_exit(void);
104 static char *search_library_path(const char *, const char *);
105 static void set_program_var(const char *, const void *);
106 static const Elf_Sym *symlook_list(const char *, unsigned long,
107 Objlist *, const Obj_Entry **, bool in_plt);
108 static void trace_loaded_objects(Obj_Entry *obj);
109 static void unload_object(Obj_Entry *);
110 static void unref_dag(Obj_Entry *);
112 void r_debug_state(void);
113 void xprintf(const char *, ...);
118 static char *error_message; /* Message for dlerror(), or NULL */
119 struct r_debug r_debug; /* for GDB; */
120 static bool trust; /* False for setuid and setgid programs */
121 static char *ld_bind_now; /* Environment variable for immediate binding */
122 static char *ld_debug; /* Environment variable for debugging */
123 static char *ld_library_path; /* Environment variable for search path */
124 static char *ld_preload; /* Environment variable for libraries to
126 static char *ld_tracing; /* Called from ldd to print libs */
127 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
128 static Obj_Entry **obj_tail; /* Link field of last object in list */
129 static Obj_Entry *obj_main; /* The main program shared object */
130 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
131 static unsigned long curmark; /* Current mark value */
133 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
134 STAILQ_HEAD_INITIALIZER(list_global);
135 static Objlist list_main = /* Objects loaded at program startup */
136 STAILQ_HEAD_INITIALIZER(list_main);
138 static LockInfo lockinfo;
140 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
142 #define GDB_STATE(s) r_debug.r_state = s; r_debug_state();
144 extern Elf_Dyn _DYNAMIC;
145 #pragma weak _DYNAMIC
148 * These are the functions the dynamic linker exports to application
149 * programs. They are the only symbols the dynamic linker is willing
150 * to export from itself.
152 static func_ptr_type exports[] = {
153 (func_ptr_type) &_rtld_error,
154 (func_ptr_type) &dlclose,
155 (func_ptr_type) &dlerror,
156 (func_ptr_type) &dlopen,
157 (func_ptr_type) &dlsym,
158 (func_ptr_type) &dladdr,
159 (func_ptr_type) &dllockinit,
164 * Global declarations normally provided by crt1. The dynamic linker is
165 * not built with crt1, so we have to provide them ourselves.
173 lockinfo.rlock_acquire(lockinfo.thelock);
179 lockinfo.wlock_acquire(lockinfo.thelock);
185 lockinfo.lock_release(lockinfo.thelock);
189 * Main entry point for dynamic linking. The first argument is the
190 * stack pointer. The stack is expected to be laid out as described
191 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
192 * Specifically, the stack pointer points to a word containing
193 * ARGC. Following that in the stack is a null-terminated sequence
194 * of pointers to argument strings. Then comes a null-terminated
195 * sequence of pointers to environment strings. Finally, there is a
196 * sequence of "auxiliary vector" entries.
198 * The second argument points to a place to store the dynamic linker's
199 * exit procedure pointer and the third to a place to store the main
202 * The return value is the main program's entry point.
205 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
207 Elf_Auxinfo *aux_info[AT_COUNT];
219 * On entry, the dynamic linker itself has not been relocated yet.
220 * Be very careful not to reference any global data until after
221 * init_rtld has returned. It is OK to reference file-scope statics
222 * and string constants, and to call static and global functions.
225 /* Find the auxiliary vector on the stack. */
228 sp += argc + 1; /* Skip over arguments and NULL terminator */
230 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
232 aux = (Elf_Auxinfo *) sp;
234 /* Digest the auxiliary vector. */
235 for (i = 0; i < AT_COUNT; i++)
237 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
238 if (auxp->a_type < AT_COUNT)
239 aux_info[auxp->a_type] = auxp;
242 /* Initialize and relocate ourselves. */
243 assert(aux_info[AT_BASE] != NULL);
244 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
246 __progname = obj_rtld.path;
247 argv0 = argv[0] != NULL ? argv[0] : "(null)";
250 trust = geteuid() == getuid() && getegid() == getgid();
252 ld_bind_now = getenv("LD_BIND_NOW");
254 ld_debug = getenv("LD_DEBUG");
255 ld_library_path = getenv("LD_LIBRARY_PATH");
256 ld_preload = getenv("LD_PRELOAD");
258 ld_tracing = getenv("LD_TRACE_LOADED_OBJECTS");
260 if (ld_debug != NULL && *ld_debug != '\0')
262 dbg("%s is initialized, base address = %p", __progname,
263 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
264 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
265 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
268 * Load the main program, or process its program header if it is
271 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
272 int fd = aux_info[AT_EXECFD]->a_un.a_val;
273 dbg("loading main program");
274 obj_main = map_object(fd, argv0, NULL);
276 if (obj_main == NULL)
278 } else { /* Main program already loaded. */
279 const Elf_Phdr *phdr;
283 dbg("processing main program's program header");
284 assert(aux_info[AT_PHDR] != NULL);
285 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
286 assert(aux_info[AT_PHNUM] != NULL);
287 phnum = aux_info[AT_PHNUM]->a_un.a_val;
288 assert(aux_info[AT_PHENT] != NULL);
289 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
290 assert(aux_info[AT_ENTRY] != NULL);
291 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
292 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
296 obj_main->path = xstrdup(argv0);
297 obj_main->mainprog = true;
300 * Get the actual dynamic linker pathname from the executable if
301 * possible. (It should always be possible.) That ensures that
302 * gdb will find the right dynamic linker even if a non-standard
305 if (obj_main->interp != NULL &&
306 strcmp(obj_main->interp, obj_rtld.path) != 0) {
308 obj_rtld.path = xstrdup(obj_main->interp);
311 digest_dynamic(obj_main);
313 linkmap_add(obj_main);
314 linkmap_add(&obj_rtld);
316 /* Link the main program into the list of objects. */
317 *obj_tail = obj_main;
318 obj_tail = &obj_main->next;
319 obj_main->refcount++;
321 /* Initialize a fake symbol for resolving undefined weak references. */
322 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
323 sym_zero.st_shndx = SHN_ABS;
325 dbg("loading LD_PRELOAD libraries");
326 if (load_preload_objects() == -1)
329 dbg("loading needed objects");
330 if (load_needed_objects(obj_main) == -1)
334 * Make a list of all objects loaded at startup. Also construct
335 * the list of init functions to call, in reverse order.
337 funclist_init(&initlist);
338 for (obj = obj_list; obj != NULL; obj = obj->next) {
339 objlist_add(&list_main, obj);
340 if (obj->init != NULL && !obj->mainprog)
341 funclist_push_head(&initlist, obj->init);
344 if (ld_tracing) { /* We're done */
345 trace_loaded_objects(obj_main);
349 if (relocate_objects(obj_main,
350 ld_bind_now != NULL && *ld_bind_now != '\0') == -1)
353 dbg("doing copy relocations");
354 if (do_copy_relocations(obj_main) == -1)
357 dbg("initializing key program variables");
358 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
359 set_program_var("environ", env);
361 dbg("initializing default locks");
362 dllockinit(NULL, NULL, NULL, NULL, NULL, NULL, NULL);
364 r_debug_state(); /* say hello to gdb! */
366 funclist_call(&initlist);
368 funclist_clear(&initlist);
371 dbg("transferring control to program entry point = %p", obj_main->entry);
373 /* Return the exit procedure and the program entry point. */
374 *exit_proc = rtld_exit;
376 return (func_ptr_type) obj_main->entry;
380 _rtld_bind(Obj_Entry *obj, Elf_Word reloff)
384 const Obj_Entry *defobj;
390 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
392 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
394 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
395 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true);
399 target = (Elf_Addr)(defobj->relocbase + def->st_value);
401 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
402 defobj->strtab + def->st_name, basename(obj->path),
403 (void *)target, basename(defobj->path));
405 reloc_jmpslot(where, target);
411 * Error reporting function. Use it like printf. If formats the message
412 * into a buffer, and sets things up so that the next call to dlerror()
413 * will return the message.
416 _rtld_error(const char *fmt, ...)
418 static char buf[512];
422 vsnprintf(buf, sizeof buf, fmt, ap);
428 basename(const char *name)
430 const char *p = strrchr(name, '/');
431 return p != NULL ? p + 1 : name;
437 const char *msg = dlerror();
445 * Process a shared object's DYNAMIC section, and save the important
446 * information in its Obj_Entry structure.
449 digest_dynamic(Obj_Entry *obj)
452 Needed_Entry **needed_tail = &obj->needed;
453 const Elf_Dyn *dyn_rpath = NULL;
454 int plttype = DT_REL;
456 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
457 switch (dynp->d_tag) {
460 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
464 obj->relsize = dynp->d_un.d_val;
468 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
472 obj->pltrel = (const Elf_Rel *)
473 (obj->relocbase + dynp->d_un.d_ptr);
477 obj->pltrelsize = dynp->d_un.d_val;
481 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
485 obj->relasize = dynp->d_un.d_val;
489 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
493 plttype = dynp->d_un.d_val;
494 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
498 obj->symtab = (const Elf_Sym *)
499 (obj->relocbase + dynp->d_un.d_ptr);
503 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
507 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
511 obj->strsize = dynp->d_un.d_val;
516 const Elf_Addr *hashtab = (const Elf_Addr *)
517 (obj->relocbase + dynp->d_un.d_ptr);
518 obj->nbuckets = hashtab[0];
519 obj->nchains = hashtab[1];
520 obj->buckets = hashtab + 2;
521 obj->chains = obj->buckets + obj->nbuckets;
527 Needed_Entry *nep = NEW(Needed_Entry);
528 nep->name = dynp->d_un.d_val;
533 needed_tail = &nep->next;
538 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
546 obj->symbolic = true;
551 * We have to wait until later to process this, because we
552 * might not have gotten the address of the string table yet.
558 /* Not used by the dynamic linker. */
562 obj->init = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
566 obj->fini = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
570 /* XXX - not implemented yet */
571 dbg("Filling in DT_DEBUG entry");
572 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
576 dbg("Ignoring d_tag %d = %#x", dynp->d_tag, dynp->d_tag);
583 if (plttype == DT_RELA) {
584 obj->pltrela = (const Elf_Rela *) obj->pltrel;
586 obj->pltrelasize = obj->pltrelsize;
590 if (dyn_rpath != NULL)
591 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
595 * Process a shared object's program header. This is used only for the
596 * main program, when the kernel has already loaded the main program
597 * into memory before calling the dynamic linker. It creates and
598 * returns an Obj_Entry structure.
601 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
604 const Elf_Phdr *phlimit = phdr + phnum;
609 for (ph = phdr; ph < phlimit; ph++) {
610 switch (ph->p_type) {
613 if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
614 _rtld_error("%s: invalid PT_PHDR", path);
617 obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
618 obj->phsize = ph->p_memsz;
622 obj->interp = (const char *) ph->p_vaddr;
627 _rtld_error("%s: too many PT_LOAD segments", path);
630 if (nsegs == 0) { /* First load segment */
631 obj->vaddrbase = trunc_page(ph->p_vaddr);
632 obj->mapbase = (caddr_t) obj->vaddrbase;
633 obj->relocbase = obj->mapbase - obj->vaddrbase;
634 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
636 } else { /* Last load segment */
637 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
644 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
649 _rtld_error("%s: too few PT_LOAD segments", path);
658 dlcheck(void *handle)
662 for (obj = obj_list; obj != NULL; obj = obj->next)
663 if (obj == (Obj_Entry *) handle)
666 if (obj == NULL || obj->dl_refcount == 0) {
667 _rtld_error("Invalid shared object handle %p", handle);
674 * Hash function for symbol table lookup. Don't even think about changing
675 * this. It is specified by the System V ABI.
678 elf_hash(const char *name)
680 const unsigned char *p = (const unsigned char *) name;
686 if ((g = h & 0xf0000000) != 0)
694 * Find the library with the given name, and return its full pathname.
695 * The returned string is dynamically allocated. Generates an error
696 * message and returns NULL if the library cannot be found.
698 * If the second argument is non-NULL, then it refers to an already-
699 * loaded shared object, whose library search path will be searched.
701 * The search order is:
702 * rpath in the referencing file
708 find_library(const char *name, const Obj_Entry *refobj)
712 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
713 if (name[0] != '/' && !trust) {
714 _rtld_error("Absolute pathname required for shared object \"%s\"",
718 return xstrdup(name);
721 dbg(" Searching for \"%s\"", name);
723 if ((refobj != NULL &&
724 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
725 (pathname = search_library_path(name, ld_library_path)) != NULL ||
726 (pathname = search_library_path(name, gethints())) != NULL ||
727 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
730 _rtld_error("Shared object \"%s\" not found", name);
735 * Given a symbol number in a referencing object, find the corresponding
736 * definition of the symbol. Returns a pointer to the symbol, or NULL if
737 * no definition was found. Returns a pointer to the Obj_Entry of the
738 * defining object via the reference parameter DEFOBJ_OUT.
741 find_symdef(unsigned long symnum, Obj_Entry *refobj,
742 const Obj_Entry **defobj_out, bool in_plt)
747 const Obj_Entry *obj;
748 const Obj_Entry *defobj;
749 const Objlist_Entry *elm;
753 ref = refobj->symtab + symnum;
754 name = refobj->strtab + ref->st_name;
755 hash = elf_hash(name);
760 if (refobj->symbolic) { /* Look first in the referencing object */
761 symp = symlook_obj(name, hash, refobj, in_plt);
762 refobj->mark = curmark;
769 /* Search all objects loaded at program start up. */
770 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
771 symp = symlook_list(name, hash, &list_main, &obj, in_plt);
773 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
779 /* Search all dlopened DAGs containing the referencing object. */
780 STAILQ_FOREACH(elm, &refobj->dldags, link) {
781 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
783 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt);
785 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
791 /* Search all RTLD_GLOBAL objects. */
792 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
793 symp = symlook_list(name, hash, &list_global, &obj, in_plt);
795 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
802 * Search the dynamic linker itself, and possibly resolve the
803 * symbol from there. This is how the application links to
804 * dynamic linker services such as dlopen. Only the values listed
805 * in the "exports" array can be resolved from the dynamic linker.
807 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
808 symp = symlook_obj(name, hash, &obj_rtld, in_plt);
809 if (symp != NULL && is_exported(symp)) {
816 * If we found no definition and the reference is weak, treat the
817 * symbol as having the value zero.
819 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
825 *defobj_out = defobj;
827 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
832 funclist_call(Funclist *list)
836 STAILQ_FOREACH(elm, list, link) {
837 dbg("calling init/fini function at %p", elm->func);
843 funclist_clear(Funclist *list)
847 while (!STAILQ_EMPTY(list)) {
848 elm = STAILQ_FIRST(list);
849 STAILQ_REMOVE_HEAD(list, link);
855 funclist_init(Funclist *list)
861 funclist_push_head(Funclist *list, InitFunc func)
865 elm = NEW(Funclist_Entry);
867 STAILQ_INSERT_HEAD(list, elm, link);
871 funclist_push_tail(Funclist *list, InitFunc func)
875 elm = NEW(Funclist_Entry);
877 STAILQ_INSERT_TAIL(list, elm, link);
881 * Return the search path from the ldconfig hints file, reading it if
882 * necessary. Returns NULL if there are problems with the hints file,
883 * or if the search path there is empty.
892 struct elfhints_hdr hdr;
895 /* Keep from trying again in case the hints file is bad. */
898 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
900 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
901 hdr.magic != ELFHINTS_MAGIC ||
906 p = xmalloc(hdr.dirlistlen + 1);
907 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
908 read(fd, p, hdr.dirlistlen + 1) != hdr.dirlistlen + 1) {
916 return hints[0] != '\0' ? hints : NULL;
920 init_dag(Obj_Entry *root)
923 init_dag1(root, root);
927 init_dag1(Obj_Entry *root, Obj_Entry *obj)
929 const Needed_Entry *needed;
931 if (obj->mark == curmark)
934 objlist_add(&obj->dldags, root);
935 objlist_add(&root->dagmembers, obj);
936 for (needed = obj->needed; needed != NULL; needed = needed->next)
937 if (needed->obj != NULL)
938 init_dag1(root, needed->obj);
942 * Initialize the dynamic linker. The argument is the address at which
943 * the dynamic linker has been mapped into memory. The primary task of
944 * this function is to relocate the dynamic linker.
947 init_rtld(caddr_t mapbase)
950 * Conjure up an Obj_Entry structure for the dynamic linker.
952 * The "path" member is supposed to be dynamically-allocated, but we
953 * aren't yet initialized sufficiently to do that. Below we will
954 * replace the static version with a dynamically-allocated copy.
956 obj_rtld.path = PATH_RTLD;
957 obj_rtld.rtld = true;
958 obj_rtld.mapbase = mapbase;
960 obj_rtld.relocbase = mapbase;
962 if (&_DYNAMIC != 0) {
963 obj_rtld.dynamic = rtld_dynamic(&obj_rtld);
964 digest_dynamic(&obj_rtld);
965 assert(obj_rtld.needed == NULL);
966 assert(!obj_rtld.textrel);
969 * Temporarily put the dynamic linker entry into the object list, so
970 * that symbols can be found.
972 obj_list = &obj_rtld;
973 obj_tail = &obj_rtld.next;
975 relocate_objects(&obj_rtld, true);
978 /* Make the object list empty again. */
980 obj_tail = &obj_list;
982 /* Replace the path with a dynamically allocated copy. */
983 obj_rtld.path = xstrdup(obj_rtld.path);
985 r_debug.r_brk = r_debug_state;
986 r_debug.r_state = RT_CONSISTENT;
990 is_exported(const Elf_Sym *def)
993 const func_ptr_type *p;
995 value = (func_ptr_type)(obj_rtld.relocbase + def->st_value);
996 for (p = exports; *p != NULL; p++)
1003 * Given a shared object, traverse its list of needed objects, and load
1004 * each of them. Returns 0 on success. Generates an error message and
1005 * returns -1 on failure.
1008 load_needed_objects(Obj_Entry *first)
1012 for (obj = first; obj != NULL; obj = obj->next) {
1013 Needed_Entry *needed;
1015 for (needed = obj->needed; needed != NULL; needed = needed->next) {
1016 const char *name = obj->strtab + needed->name;
1017 char *path = find_library(name, obj);
1020 if (path == NULL && !ld_tracing)
1024 needed->obj = load_object(path);
1025 if (needed->obj == NULL && !ld_tracing)
1026 return -1; /* XXX - cleanup */
1035 load_preload_objects(void)
1037 char *p = ld_preload;
1038 static const char delim[] = " \t:;";
1043 p += strspn(p, delim);
1044 while (*p != '\0') {
1045 size_t len = strcspn(p, delim);
1051 if ((path = find_library(p, NULL)) == NULL)
1053 if (load_object(path) == NULL)
1054 return -1; /* XXX - cleanup */
1057 p += strspn(p, delim);
1063 * Load a shared object into memory, if it is not already loaded. The
1064 * argument must be a string allocated on the heap. This function assumes
1065 * responsibility for freeing it when necessary.
1067 * Returns a pointer to the Obj_Entry for the object. Returns NULL
1071 load_object(char *path)
1077 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1078 if (strcmp(obj->path, path) == 0)
1082 * If we didn't find a match by pathname, open the file and check
1083 * again by device and inode. This avoids false mismatches caused
1084 * by multiple links or ".." in pathnames.
1086 * To avoid a race, we open the file and use fstat() rather than
1090 if ((fd = open(path, O_RDONLY)) == -1) {
1091 _rtld_error("Cannot open \"%s\"", path);
1094 if (fstat(fd, &sb) == -1) {
1095 _rtld_error("Cannot fstat \"%s\"", path);
1099 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1100 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1107 if (obj == NULL) { /* First use of this object, so we must map it in */
1108 dbg("loading \"%s\"", path);
1109 obj = map_object(fd, path, &sb);
1117 digest_dynamic(obj);
1120 obj_tail = &obj->next;
1121 linkmap_add(obj); /* for GDB */
1123 dbg(" %p .. %p: %s", obj->mapbase,
1124 obj->mapbase + obj->mapsize - 1, obj->path);
1126 dbg(" WARNING: %s has impure text", obj->path);
1135 lock_nop(void *lock)
1140 obj_from_addr(const void *addr)
1142 unsigned long endhash;
1145 endhash = elf_hash(END_SYM);
1146 for (obj = obj_list; obj != NULL; obj = obj->next) {
1147 const Elf_Sym *endsym;
1149 if (addr < (void *) obj->mapbase)
1151 if ((endsym = symlook_obj(END_SYM, endhash, obj, true)) == NULL)
1152 continue; /* No "end" symbol?! */
1153 if (addr < (void *) (obj->relocbase + endsym->st_value))
1160 objlist_add(Objlist *list, Obj_Entry *obj)
1164 elm = NEW(Objlist_Entry);
1166 STAILQ_INSERT_TAIL(list, elm, link);
1169 static Objlist_Entry *
1170 objlist_find(Objlist *list, const Obj_Entry *obj)
1174 STAILQ_FOREACH(elm, list, link)
1175 if (elm->obj == obj)
1181 objlist_remove(Objlist *list, Obj_Entry *obj)
1185 if ((elm = objlist_find(list, obj)) != NULL) {
1186 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1192 * Relocate newly-loaded shared objects. The argument is a pointer to
1193 * the Obj_Entry for the first such object. All objects from the first
1194 * to the end of the list of objects are relocated. Returns 0 on success,
1198 relocate_objects(Obj_Entry *first, bool bind_now)
1202 for (obj = first; obj != NULL; obj = obj->next) {
1203 if (obj != &obj_rtld)
1204 dbg("relocating \"%s\"", obj->path);
1205 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1206 obj->symtab == NULL || obj->strtab == NULL) {
1207 _rtld_error("%s: Shared object has no run-time symbol table",
1213 /* There are relocations to the write-protected text segment. */
1214 if (mprotect(obj->mapbase, obj->textsize,
1215 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1216 _rtld_error("%s: Cannot write-enable text segment: %s",
1217 obj->path, strerror(errno));
1222 /* Process the non-PLT relocations. */
1223 if (reloc_non_plt(obj, &obj_rtld))
1226 if (obj->textrel) { /* Re-protected the text segment. */
1227 if (mprotect(obj->mapbase, obj->textsize,
1228 PROT_READ|PROT_EXEC) == -1) {
1229 _rtld_error("%s: Cannot write-protect text segment: %s",
1230 obj->path, strerror(errno));
1235 /* Process the PLT relocations. */
1236 if (reloc_plt(obj) == -1)
1238 /* Relocate the jump slots if we are doing immediate binding. */
1240 if (reloc_jmpslots(obj) == -1)
1245 * Set up the magic number and version in the Obj_Entry. These
1246 * were checked in the crt1.o from the original ElfKit, so we
1247 * set them for backward compatibility.
1249 obj->magic = RTLD_MAGIC;
1250 obj->version = RTLD_VERSION;
1252 /* Set the special PLT or GOT entries. */
1260 * Cleanup procedure. It will be called (by the atexit mechanism) just
1261 * before the process exits.
1269 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1270 if (obj->fini != NULL)
1275 search_library_path(const char *name, const char *path)
1277 size_t namelen = strlen(name);
1278 const char *p = path;
1283 p += strspn(p, ":;");
1284 while (*p != '\0') {
1285 size_t len = strcspn(p, ":;");
1287 if (*p == '/' || trust) {
1289 const char *dir = p;
1290 size_t dirlen = len;
1292 pathname = xmalloc(dirlen + 1 + namelen + 1);
1293 strncpy(pathname, dir, dirlen);
1294 pathname[dirlen] = '/';
1295 strcpy(pathname + dirlen + 1, name);
1297 dbg(" Trying \"%s\"", pathname);
1298 if (access(pathname, F_OK) == 0) /* We found it */
1304 p += strspn(p, ":;");
1311 dlclose(void *handle)
1318 root = dlcheck(handle);
1324 /* Unreference the object and its dependencies. */
1325 root->dl_refcount--;
1328 if (root->refcount == 0) {
1330 * The object is no longer referenced, so we must unload it.
1331 * First, make a list of the fini functions and then call them
1332 * with no locks held.
1334 funclist_init(&finilist);
1335 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1336 if (obj->refcount == 0 && obj->fini != NULL)
1337 funclist_push_tail(&finilist, obj->fini);
1340 funclist_call(&finilist);
1342 funclist_clear(&finilist);
1344 /* Finish cleaning up the newly-unreferenced objects. */
1345 GDB_STATE(RT_DELETE);
1346 unload_object(root);
1347 GDB_STATE(RT_CONSISTENT);
1356 char *msg = error_message;
1357 error_message = NULL;
1362 dllockinit(void *context,
1363 void *(*lock_create)(void *context),
1364 void (*rlock_acquire)(void *lock),
1365 void (*wlock_acquire)(void *lock),
1366 void (*lock_release)(void *lock),
1367 void (*lock_destroy)(void *lock),
1368 void (*context_destroy)(void *context))
1370 bool is_dflt = false;
1372 /* NULL arguments mean reset to the built-in locks. */
1373 if (lock_create == NULL) {
1376 lock_create = lockdflt_create;
1377 rlock_acquire = wlock_acquire = lockdflt_acquire;
1378 lock_release = lockdflt_release;
1379 lock_destroy = lockdflt_destroy;
1380 context_destroy = NULL;
1383 /* Temporarily set locking methods to no-ops. */
1384 lockinfo.rlock_acquire = lock_nop;
1385 lockinfo.wlock_acquire = lock_nop;
1386 lockinfo.lock_release = lock_nop;
1388 /* Release any existing locks and context. */
1389 if (lockinfo.lock_destroy != NULL)
1390 lockinfo.lock_destroy(lockinfo.thelock);
1391 if (lockinfo.context_destroy != NULL)
1392 lockinfo.context_destroy(lockinfo.context);
1395 * Make sure the shared objects containing the locking methods are
1396 * fully bound, to avoid infinite recursion when they are called
1397 * from the lazy binding code.
1400 prebind((void *)rlock_acquire);
1401 prebind((void *)wlock_acquire);
1402 prebind((void *)lock_release);
1405 /* Allocate our lock. */
1406 lockinfo.thelock = lock_create(lockinfo.context);
1408 /* Record the new method information. */
1409 lockinfo.context = context;
1410 lockinfo.rlock_acquire = rlock_acquire;
1411 lockinfo.wlock_acquire = wlock_acquire;
1412 lockinfo.lock_release = lock_release;
1413 lockinfo.lock_destroy = lock_destroy;
1414 lockinfo.context_destroy = context_destroy;
1422 if ((obj = obj_from_addr(addr)) == NULL) {
1423 _rtld_error("Cannot determine shared object of locking method at %p",
1427 if (!obj->rtld && !obj->jmpslots_done) {
1428 dbg("Pre-binding %s for locking", obj->path);
1429 if (reloc_jmpslots(obj) == -1)
1435 dlopen(const char *name, int mode)
1437 Obj_Entry **old_obj_tail;
1442 funclist_init(&initlist);
1447 old_obj_tail = obj_tail;
1453 char *path = find_library(name, obj_main);
1455 obj = load_object(path);
1460 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
1461 objlist_add(&list_global, obj);
1462 mode &= RTLD_MODEMASK;
1463 if (*old_obj_tail != NULL) { /* We loaded something new. */
1464 assert(*old_obj_tail == obj);
1466 if (load_needed_objects(obj) == -1 ||
1467 (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW)) == -1) {
1470 if (obj->refcount == 0)
1474 /* Make list of init functions to call, in reverse order */
1475 for (initobj = obj; initobj != NULL; initobj = initobj->next)
1476 if (initobj->init != NULL)
1477 funclist_push_head(&initlist, initobj->init);
1482 GDB_STATE(RT_CONSISTENT);
1484 /* Call the init functions with no locks held. */
1486 funclist_call(&initlist);
1488 funclist_clear(&initlist);
1494 dlsym(void *handle, const char *name)
1496 const Obj_Entry *obj;
1499 const Obj_Entry *defobj;
1501 hash = elf_hash(name);
1506 if (handle == NULL || handle == RTLD_NEXT) {
1509 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1510 if ((obj = obj_from_addr(retaddr)) == NULL) {
1511 _rtld_error("Cannot determine caller's shared object");
1515 if (handle == NULL) { /* Just the caller's shared object. */
1516 def = symlook_obj(name, hash, obj, true);
1518 } else { /* All the shared objects after the caller's */
1519 while ((obj = obj->next) != NULL) {
1520 if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1527 if ((obj = dlcheck(handle)) == NULL) {
1532 if (obj->mainprog) {
1533 /* Search main program and all libraries loaded by it. */
1535 def = symlook_list(name, hash, &list_main, &defobj, true);
1538 * XXX - This isn't correct. The search should include the whole
1539 * DAG rooted at the given object.
1541 def = symlook_obj(name, hash, obj, true);
1548 return defobj->relocbase + def->st_value;
1551 _rtld_error("Undefined symbol \"%s\"", name);
1557 dladdr(const void *addr, Dl_info *info)
1559 const Obj_Entry *obj;
1562 unsigned long symoffset;
1565 obj = obj_from_addr(addr);
1567 _rtld_error("No shared object contains address");
1571 info->dli_fname = obj->path;
1572 info->dli_fbase = obj->mapbase;
1573 info->dli_saddr = (void *)0;
1574 info->dli_sname = NULL;
1577 * Walk the symbol list looking for the symbol whose address is
1578 * closest to the address sent in.
1580 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1581 def = obj->symtab + symoffset;
1584 * For skip the symbol if st_shndx is either SHN_UNDEF or
1587 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1591 * If the symbol is greater than the specified address, or if it
1592 * is further away from addr than the current nearest symbol,
1595 symbol_addr = obj->relocbase + def->st_value;
1596 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1599 /* Update our idea of the nearest symbol. */
1600 info->dli_sname = obj->strtab + def->st_name;
1601 info->dli_saddr = symbol_addr;
1604 if (info->dli_saddr == addr)
1612 linkmap_add(Obj_Entry *obj)
1614 struct link_map *l = &obj->linkmap;
1615 struct link_map *prev;
1617 obj->linkmap.l_name = obj->path;
1618 obj->linkmap.l_addr = obj->mapbase;
1619 obj->linkmap.l_ld = obj->dynamic;
1621 /* GDB needs load offset on MIPS to use the symbols */
1622 obj->linkmap.l_offs = obj->relocbase;
1625 if (r_debug.r_map == NULL) {
1631 * Scan to the end of the list, but not past the entry for the
1632 * dynamic linker, which we want to keep at the very end.
1634 for (prev = r_debug.r_map;
1635 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
1636 prev = prev->l_next)
1639 /* Link in the new entry. */
1641 l->l_next = prev->l_next;
1642 if (l->l_next != NULL)
1643 l->l_next->l_prev = l;
1648 linkmap_delete(Obj_Entry *obj)
1650 struct link_map *l = &obj->linkmap;
1652 if (l->l_prev == NULL) {
1653 if ((r_debug.r_map = l->l_next) != NULL)
1654 l->l_next->l_prev = NULL;
1658 if ((l->l_prev->l_next = l->l_next) != NULL)
1659 l->l_next->l_prev = l->l_prev;
1663 * Function for the debugger to set a breakpoint on to gain control.
1671 * Set a pointer variable in the main program to the given value. This
1672 * is used to set key variables such as "environ" before any of the
1673 * init functions are called.
1676 set_program_var(const char *name, const void *value)
1678 const Obj_Entry *obj;
1681 hash = elf_hash(name);
1682 for (obj = obj_main; obj != NULL; obj = obj->next) {
1685 if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
1688 addr = (const void **)(obj->relocbase + def->st_value);
1689 dbg("\"%s\": *%p <-- %p", name, addr, value);
1696 static const Elf_Sym *
1697 symlook_list(const char *name, unsigned long hash, Objlist *objlist,
1698 const Obj_Entry **defobj_out, bool in_plt)
1700 const Elf_Sym *symp;
1702 const Obj_Entry *defobj;
1703 const Objlist_Entry *elm;
1707 STAILQ_FOREACH(elm, objlist, link) {
1708 if (elm->obj->mark == curmark)
1710 elm->obj->mark = curmark;
1711 if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
1712 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
1715 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
1721 *defobj_out = defobj;
1726 * Search the symbol table of a single shared object for a symbol of
1727 * the given name. Returns a pointer to the symbol, or NULL if no
1728 * definition was found.
1730 * The symbol's hash value is passed in for efficiency reasons; that
1731 * eliminates many recomputations of the hash value.
1734 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
1737 if (obj->buckets != NULL) {
1738 unsigned long symnum = obj->buckets[hash % obj->nbuckets];
1740 while (symnum != STN_UNDEF) {
1741 const Elf_Sym *symp;
1744 if (symnum >= obj->nchains)
1745 return NULL; /* Bad object */
1746 symp = obj->symtab + symnum;
1747 strp = obj->strtab + symp->st_name;
1749 if (strcmp(name, strp) == 0)
1750 return symp->st_shndx != SHN_UNDEF ||
1751 (!in_plt && symp->st_value != 0 &&
1752 ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
1754 symnum = obj->chains[symnum];
1761 trace_loaded_objects(Obj_Entry *obj)
1763 char *fmt1, *fmt2, *fmt, *main_local;
1766 if ((main_local = getenv("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
1769 if ((fmt1 = getenv("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
1770 fmt1 = "\t%o => %p (%x)\n";
1772 if ((fmt2 = getenv("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
1773 fmt2 = "\t%o (%x)\n";
1775 for (; obj; obj = obj->next) {
1776 Needed_Entry *needed;
1780 for (needed = obj->needed; needed; needed = needed->next) {
1781 if (needed->obj != NULL) {
1782 if (needed->obj->traced)
1784 needed->obj->traced = true;
1785 path = needed->obj->path;
1789 name = (char *)obj->strtab + needed->name;
1790 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
1792 fmt = is_lib ? fmt1 : fmt2;
1793 while ((c = *fmt++) != '\0') {
1819 printf("%s", main_local);
1822 printf("%s", obj_main->path);
1829 printf("%d", sodp->sod_major);
1832 printf("%d", sodp->sod_minor);
1839 printf("%p", needed->obj ? needed->obj->mapbase : 0);
1851 * Unload a dlopened object and its dependencies from memory and from
1852 * our data structures. It is assumed that the DAG rooted in the
1853 * object has already been unreferenced, and that the object has a
1854 * reference count of 0.
1857 unload_object(Obj_Entry *root)
1863 assert(root->refcount == 0);
1865 /* Remove the DAG from all objects' DAG lists. */
1866 STAILQ_FOREACH(elm, &root->dagmembers , link)
1867 objlist_remove(&elm->obj->dldags, root);
1869 /* Remove the DAG from the RTLD_GLOBAL list. */
1870 objlist_remove(&list_global, root);
1872 /* Unmap all objects that are no longer referenced. */
1873 linkp = &obj_list->next;
1874 while ((obj = *linkp) != NULL) {
1875 if (obj->refcount == 0) {
1876 dbg("unloading \"%s\"", obj->path);
1877 munmap(obj->mapbase, obj->mapsize);
1878 linkmap_delete(obj);
1888 unref_dag(Obj_Entry *root)
1890 const Needed_Entry *needed;
1892 assert(root->refcount != 0);
1894 if (root->refcount == 0)
1895 for (needed = root->needed; needed != NULL; needed = needed->next)
1896 if (needed->obj != NULL)
1897 unref_dag(needed->obj);
1901 * Non-mallocing printf, for use by malloc itself.
1902 * XXX - This doesn't belong in this module.
1905 xprintf(const char *fmt, ...)
1911 vsprintf(buf, fmt, ap);
1912 (void)write(1, buf, strlen(buf));