2 * Copyright 1996, 1997, 1998, 1999 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>
59 #define assert(cond) ((cond) ? (void) 0 :\
60 (msg("oops: " __XSTRING(__LINE__) "\n"), abort()))
61 #define msg(s) (write(1, s, strlen(s)))
62 #define trace() msg("trace: " __XSTRING(__LINE__) "\n");
64 #define END_SYM "_end"
65 #define PATH_RTLD "/usr/libexec/ld-elf.so.1"
68 typedef void (*func_ptr_type)();
71 * Function declarations.
73 static const char *basename(const char *);
74 static void call_fini_functions(Obj_Entry *);
75 static void call_init_functions(Obj_Entry *);
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 const char *gethints(void);
82 static void init_dag(Obj_Entry *);
83 static void init_dag1(Obj_Entry *root, Obj_Entry *obj);
84 static void init_rtld(caddr_t);
85 static bool is_exported(const Elf_Sym *);
86 static void linkmap_add(Obj_Entry *);
87 static void linkmap_delete(Obj_Entry *);
88 static int load_needed_objects(Obj_Entry *);
89 static int load_preload_objects(void);
90 static Obj_Entry *load_object(char *);
91 static Obj_Entry *obj_from_addr(const void *);
92 static void objlist_add(Objlist *, Obj_Entry *);
93 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
94 static void objlist_remove(Objlist *, Obj_Entry *);
95 static int relocate_objects(Obj_Entry *, bool);
96 static void rtld_exit(void);
97 static char *search_library_path(const char *, const char *);
98 static void set_program_var(const char *, const void *);
99 static const Elf_Sym *symlook_list(const char *, unsigned long,
100 Objlist *, const Obj_Entry **, bool in_plt);
101 static void trace_loaded_objects(Obj_Entry *obj);
102 static void unload_object(Obj_Entry *, bool do_fini_funcs);
103 static void unref_dag(Obj_Entry *);
105 void r_debug_state(void);
106 void xprintf(const char *, ...);
111 static char *error_message; /* Message for dlerror(), or NULL */
112 struct r_debug r_debug; /* for GDB; */
113 static bool trust; /* False for setuid and setgid programs */
114 static char *ld_bind_now; /* Environment variable for immediate binding */
115 static char *ld_debug; /* Environment variable for debugging */
116 static char *ld_library_path; /* Environment variable for search path */
117 static char *ld_preload; /* Environment variable for libraries to
119 static char *ld_tracing; /* Called from ldd to print libs */
120 static Obj_Entry *obj_list; /* Head of linked list of shared objects */
121 static Obj_Entry **obj_tail; /* Link field of last object in list */
122 static Obj_Entry *obj_main; /* The main program shared object */
123 static Obj_Entry obj_rtld; /* The dynamic linker shared object */
124 static unsigned long curmark; /* Current mark value */
126 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
127 STAILQ_HEAD_INITIALIZER(list_global);
128 static Objlist list_main = /* Objects loaded at program startup */
129 STAILQ_HEAD_INITIALIZER(list_main);
131 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
133 #define GDB_STATE(s) r_debug.r_state = s; r_debug_state();
135 extern Elf_Dyn _DYNAMIC;
136 #pragma weak _DYNAMIC
139 * These are the functions the dynamic linker exports to application
140 * programs. They are the only symbols the dynamic linker is willing
141 * to export from itself.
143 static func_ptr_type exports[] = {
144 (func_ptr_type) &_rtld_error,
145 (func_ptr_type) &dlclose,
146 (func_ptr_type) &dlerror,
147 (func_ptr_type) &dlopen,
148 (func_ptr_type) &dlsym,
149 (func_ptr_type) &dladdr,
154 * Global declarations normally provided by crt1. The dynamic linker is
155 * not build with crt1, so we have to provide them ourselves.
161 * Main entry point for dynamic linking. The first argument is the
162 * stack pointer. The stack is expected to be laid out as described
163 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
164 * Specifically, the stack pointer points to a word containing
165 * ARGC. Following that in the stack is a null-terminated sequence
166 * of pointers to argument strings. Then comes a null-terminated
167 * sequence of pointers to environment strings. Finally, there is a
168 * sequence of "auxiliary vector" entries.
170 * The second argument points to a place to store the dynamic linker's
171 * exit procedure pointer and the third to a place to store the main
174 * The return value is the main program's entry point.
177 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
179 Elf_Auxinfo *aux_info[AT_COUNT];
190 * On entry, the dynamic linker itself has not been relocated yet.
191 * Be very careful not to reference any global data until after
192 * init_rtld has returned. It is OK to reference file-scope statics
193 * and string constants, and to call static and global functions.
196 /* Find the auxiliary vector on the stack. */
199 sp += argc + 1; /* Skip over arguments and NULL terminator */
201 while (*sp++ != 0) /* Skip over environment, and NULL terminator */
203 aux = (Elf_Auxinfo *) sp;
205 /* Digest the auxiliary vector. */
206 for (i = 0; i < AT_COUNT; i++)
208 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
209 if (auxp->a_type < AT_COUNT)
210 aux_info[auxp->a_type] = auxp;
213 /* Initialize and relocate ourselves. */
214 assert(aux_info[AT_BASE] != NULL);
215 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
217 __progname = obj_rtld.path;
218 argv0 = argv[0] != NULL ? argv[0] : "(null)";
221 trust = geteuid() == getuid() && getegid() == getgid();
223 ld_bind_now = getenv("LD_BIND_NOW");
225 ld_debug = getenv("LD_DEBUG");
226 ld_library_path = getenv("LD_LIBRARY_PATH");
227 ld_preload = getenv("LD_PRELOAD");
229 ld_tracing = getenv("LD_TRACE_LOADED_OBJECTS");
231 if (ld_debug != NULL && *ld_debug != '\0')
233 dbg("%s is initialized, base address = %p", __progname,
234 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
235 dbg("RTLD dynamic = %p", obj_rtld.dynamic);
236 dbg("RTLD pltgot = %p", obj_rtld.pltgot);
239 * Load the main program, or process its program header if it is
242 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
243 int fd = aux_info[AT_EXECFD]->a_un.a_val;
244 dbg("loading main program");
245 obj_main = map_object(fd, argv0, NULL);
247 if (obj_main == NULL)
249 } else { /* Main program already loaded. */
250 const Elf_Phdr *phdr;
254 dbg("processing main program's program header");
255 assert(aux_info[AT_PHDR] != NULL);
256 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
257 assert(aux_info[AT_PHNUM] != NULL);
258 phnum = aux_info[AT_PHNUM]->a_un.a_val;
259 assert(aux_info[AT_PHENT] != NULL);
260 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
261 assert(aux_info[AT_ENTRY] != NULL);
262 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
263 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
267 obj_main->path = xstrdup(argv0);
268 obj_main->mainprog = true;
271 * Get the actual dynamic linker pathname from the executable if
272 * possible. (It should always be possible.) That ensures that
273 * gdb will find the right dynamic linker even if a non-standard
276 if (obj_main->interp != NULL &&
277 strcmp(obj_main->interp, obj_rtld.path) != 0) {
279 obj_rtld.path = xstrdup(obj_main->interp);
282 digest_dynamic(obj_main);
284 linkmap_add(obj_main);
285 linkmap_add(&obj_rtld);
287 /* Link the main program into the list of objects. */
288 *obj_tail = obj_main;
289 obj_tail = &obj_main->next;
290 obj_main->refcount++;
292 /* Initialize a fake symbol for resolving undefined weak references. */
293 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
294 sym_zero.st_shndx = SHN_ABS;
296 dbg("loading LD_PRELOAD libraries");
297 if (load_preload_objects() == -1)
300 dbg("loading needed objects");
301 if (load_needed_objects(obj_main) == -1)
304 for (obj = obj_list; obj != NULL; obj = obj->next)
305 objlist_add(&list_main, obj);
307 if (ld_tracing) { /* We're done */
308 trace_loaded_objects(obj_main);
312 dbg("relocating objects");
313 if (relocate_objects(obj_main,
314 ld_bind_now != NULL && *ld_bind_now != '\0') == -1)
317 dbg("doing copy relocations");
318 if (do_copy_relocations(obj_main) == -1)
321 dbg("initializing key program variables");
322 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
323 set_program_var("environ", env);
325 r_debug_state(); /* say hello to gdb! */
327 dbg("calling _init functions");
328 call_init_functions(obj_main->next);
330 dbg("transferring control to program entry point = %p", obj_main->entry);
332 /* Return the exit procedure and the program entry point. */
333 *exit_proc = rtld_exit;
335 return (func_ptr_type) obj_main->entry;
339 _rtld_bind(Obj_Entry *obj, Elf_Word reloff)
343 const Obj_Entry *defobj;
348 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
350 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
352 where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
353 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true);
357 target = (Elf_Addr)(defobj->relocbase + def->st_value);
359 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
360 defobj->strtab + def->st_name, basename(obj->path),
361 (void *)target, basename(defobj->path));
363 reloc_jmpslot(where, target);
368 * Error reporting function. Use it like printf. If formats the message
369 * into a buffer, and sets things up so that the next call to dlerror()
370 * will return the message.
373 _rtld_error(const char *fmt, ...)
375 static char buf[512];
379 vsnprintf(buf, sizeof buf, fmt, ap);
385 basename(const char *name)
387 const char *p = strrchr(name, '/');
388 return p != NULL ? p + 1 : name;
392 call_fini_functions(Obj_Entry *first)
396 for (obj = first; obj != NULL; obj = obj->next)
397 if (obj->fini != NULL)
402 call_init_functions(Obj_Entry *first)
405 call_init_functions(first->next);
406 if (first->init != NULL)
414 const char *msg = dlerror();
422 * Process a shared object's DYNAMIC section, and save the important
423 * information in its Obj_Entry structure.
426 digest_dynamic(Obj_Entry *obj)
429 Needed_Entry **needed_tail = &obj->needed;
430 const Elf_Dyn *dyn_rpath = NULL;
431 int plttype = DT_REL;
433 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) {
434 switch (dynp->d_tag) {
437 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
441 obj->relsize = dynp->d_un.d_val;
445 assert(dynp->d_un.d_val == sizeof(Elf_Rel));
449 obj->pltrel = (const Elf_Rel *)
450 (obj->relocbase + dynp->d_un.d_ptr);
454 obj->pltrelsize = dynp->d_un.d_val;
458 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
462 obj->relasize = dynp->d_un.d_val;
466 assert(dynp->d_un.d_val == sizeof(Elf_Rela));
470 plttype = dynp->d_un.d_val;
471 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
475 obj->symtab = (const Elf_Sym *)
476 (obj->relocbase + dynp->d_un.d_ptr);
480 assert(dynp->d_un.d_val == sizeof(Elf_Sym));
484 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
488 obj->strsize = dynp->d_un.d_val;
493 const Elf_Addr *hashtab = (const Elf_Addr *)
494 (obj->relocbase + dynp->d_un.d_ptr);
495 obj->nbuckets = hashtab[0];
496 obj->nchains = hashtab[1];
497 obj->buckets = hashtab + 2;
498 obj->chains = obj->buckets + obj->nbuckets;
504 Needed_Entry *nep = NEW(Needed_Entry);
505 nep->name = dynp->d_un.d_val;
510 needed_tail = &nep->next;
515 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
523 obj->symbolic = true;
528 * We have to wait until later to process this, because we
529 * might not have gotten the address of the string table yet.
535 /* Not used by the dynamic linker. */
539 obj->init = (void (*)(void)) (obj->relocbase + dynp->d_un.d_ptr);
543 obj->fini = (void (*)(void)) (obj->relocbase + dynp->d_un.d_ptr);
547 /* XXX - not implemented yet */
548 dbg("Filling in DT_DEBUG entry");
549 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
553 xprintf("Ignored d_tag %d\n",dynp->d_tag);
560 if (plttype == DT_RELA) {
561 obj->pltrela = (const Elf_Rela *) obj->pltrel;
563 obj->pltrelasize = obj->pltrelsize;
567 if (dyn_rpath != NULL)
568 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
572 * Process a shared object's program header. This is used only for the
573 * main program, when the kernel has already loaded the main program
574 * into memory before calling the dynamic linker. It creates and
575 * returns an Obj_Entry structure.
578 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
581 const Elf_Phdr *phlimit = phdr + phnum;
586 for (ph = phdr; ph < phlimit; ph++) {
587 switch (ph->p_type) {
590 if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
591 _rtld_error("%s: invalid PT_PHDR", path);
594 obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
595 obj->phsize = ph->p_memsz;
599 obj->interp = (const char *) ph->p_vaddr;
604 _rtld_error("%s: too many PT_LOAD segments", path);
607 if (nsegs == 0) { /* First load segment */
608 obj->vaddrbase = trunc_page(ph->p_vaddr);
609 obj->mapbase = (caddr_t) obj->vaddrbase;
610 obj->relocbase = obj->mapbase - obj->vaddrbase;
611 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
613 } else { /* Last load segment */
614 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
621 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
626 _rtld_error("%s: too few PT_LOAD segments", path);
635 dlcheck(void *handle)
639 for (obj = obj_list; obj != NULL; obj = obj->next)
640 if (obj == (Obj_Entry *) handle)
643 if (obj == NULL || obj->dl_refcount == 0) {
644 _rtld_error("Invalid shared object handle %p", handle);
651 * Hash function for symbol table lookup. Don't even think about changing
652 * this. It is specified by the System V ABI.
655 elf_hash(const char *name)
657 const unsigned char *p = (const unsigned char *) name;
663 if ((g = h & 0xf0000000) != 0)
671 * Find the library with the given name, and return its full pathname.
672 * The returned string is dynamically allocated. Generates an error
673 * message and returns NULL if the library cannot be found.
675 * If the second argument is non-NULL, then it refers to an already-
676 * loaded shared object, whose library search path will be searched.
678 * The search order is:
681 * rpath in the referencing file
685 find_library(const char *name, const Obj_Entry *refobj)
689 if (strchr(name, '/') != NULL) { /* Hard coded pathname */
690 if (name[0] != '/' && !trust) {
691 _rtld_error("Absolute pathname required for shared object \"%s\"",
695 return xstrdup(name);
698 dbg(" Searching for \"%s\"", name);
700 if ((refobj != NULL &&
701 (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
702 (pathname = search_library_path(name, ld_library_path)) != NULL ||
703 (pathname = search_library_path(name, gethints())) != NULL ||
704 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
707 _rtld_error("Shared object \"%s\" not found", name);
712 * Given a symbol number in a referencing object, find the corresponding
713 * definition of the symbol. Returns a pointer to the symbol, or NULL if
714 * no definition was found. Returns a pointer to the Obj_Entry of the
715 * defining object via the reference parameter DEFOBJ_OUT.
718 find_symdef(unsigned long symnum, Obj_Entry *refobj,
719 const Obj_Entry **defobj_out, bool in_plt)
724 const Obj_Entry *obj;
725 const Obj_Entry *defobj;
726 const Objlist_Entry *elm;
730 ref = refobj->symtab + symnum;
731 name = refobj->strtab + ref->st_name;
732 hash = elf_hash(name);
737 if (refobj->symbolic) { /* Look first in the referencing object */
738 symp = symlook_obj(name, hash, refobj, in_plt);
739 refobj->mark = curmark;
746 /* Search all objects loaded at program start up. */
747 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
748 symp = symlook_list(name, hash, &list_main, &obj, in_plt);
750 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
756 /* Search all dlopened DAGs containing the referencing object. */
757 STAILQ_FOREACH(elm, &refobj->dldags, link) {
758 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
760 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt);
762 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
768 /* Search all RTLD_GLOBAL objects. */
769 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
770 symp = symlook_list(name, hash, &list_global, &obj, in_plt);
772 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
779 * Search the dynamic linker itself, and possibly resolve the
780 * symbol from there. This is how the application links to
781 * dynamic linker services such as dlopen. Only the values listed
782 * in the "exports" array can be resolved from the dynamic linker.
784 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
785 symp = symlook_obj(name, hash, &obj_rtld, in_plt);
786 if (symp != NULL && is_exported(symp)) {
793 * If we found no definition and the reference is weak, treat the
794 * symbol as having the value zero.
796 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
802 *defobj_out = defobj;
804 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
809 * Return the search path from the ldconfig hints file, reading it if
810 * necessary. Returns NULL if there are problems with the hints file,
811 * or if the search path there is empty.
820 struct elfhints_hdr hdr;
823 /* Keep from trying again in case the hints file is bad. */
826 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
828 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
829 hdr.magic != ELFHINTS_MAGIC ||
834 p = xmalloc(hdr.dirlistlen + 1);
835 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
836 read(fd, p, hdr.dirlistlen + 1) != hdr.dirlistlen + 1) {
844 return hints[0] != '\0' ? hints : NULL;
848 init_dag(Obj_Entry *root)
851 init_dag1(root, root);
855 init_dag1(Obj_Entry *root, Obj_Entry *obj)
857 const Needed_Entry *needed;
859 if (obj->mark == curmark)
862 objlist_add(&obj->dldags, root);
863 objlist_add(&root->dagmembers, obj);
864 for (needed = obj->needed; needed != NULL; needed = needed->next)
865 if (needed->obj != NULL)
866 init_dag1(root, needed->obj);
870 * Initialize the dynamic linker. The argument is the address at which
871 * the dynamic linker has been mapped into memory. The primary task of
872 * this function is to relocate the dynamic linker.
875 init_rtld(caddr_t mapbase)
878 * Conjure up an Obj_Entry structure for the dynamic linker.
880 * The "path" member is supposed to be dynamically-allocated, but we
881 * aren't yet initialized sufficiently to do that. Below we will
882 * replace the static version with a dynamically-allocated copy.
884 obj_rtld.path = PATH_RTLD;
885 obj_rtld.rtld = true;
886 obj_rtld.mapbase = mapbase;
888 obj_rtld.relocbase = mapbase;
890 if (&_DYNAMIC != 0) {
891 obj_rtld.dynamic = rtld_dynamic(&obj_rtld);
892 digest_dynamic(&obj_rtld);
893 assert(obj_rtld.needed == NULL);
894 assert(!obj_rtld.textrel);
897 * Temporarily put the dynamic linker entry into the object list, so
898 * that symbols can be found.
900 obj_list = &obj_rtld;
901 obj_tail = &obj_rtld.next;
903 relocate_objects(&obj_rtld, true);
906 /* Make the object list empty again. */
908 obj_tail = &obj_list;
910 /* Replace the path with a dynamically allocated copy. */
911 obj_rtld.path = xstrdup(obj_rtld.path);
913 r_debug.r_brk = r_debug_state;
914 r_debug.r_state = RT_CONSISTENT;
918 is_exported(const Elf_Sym *def)
921 const func_ptr_type *p;
923 value = (func_ptr_type)(obj_rtld.relocbase + def->st_value);
924 for (p = exports; *p != NULL; p++)
931 * Given a shared object, traverse its list of needed objects, and load
932 * each of them. Returns 0 on success. Generates an error message and
933 * returns -1 on failure.
936 load_needed_objects(Obj_Entry *first)
940 for (obj = first; obj != NULL; obj = obj->next) {
941 Needed_Entry *needed;
943 for (needed = obj->needed; needed != NULL; needed = needed->next) {
944 const char *name = obj->strtab + needed->name;
945 char *path = find_library(name, obj);
948 if (path == NULL && !ld_tracing)
952 needed->obj = load_object(path);
953 if (needed->obj == NULL && !ld_tracing)
954 return -1; /* XXX - cleanup */
963 load_preload_objects(void)
965 char *p = ld_preload;
970 p += strspn(p, ":;");
972 size_t len = strcspn(p, ":;");
978 if ((path = find_library(p, NULL)) == NULL)
980 if (load_object(path) == NULL)
981 return -1; /* XXX - cleanup */
984 p += strspn(p, ":;");
990 * Load a shared object into memory, if it is not already loaded. The
991 * argument must be a string allocated on the heap. This function assumes
992 * responsibility for freeing it when necessary.
994 * Returns a pointer to the Obj_Entry for the object. Returns NULL
998 load_object(char *path)
1004 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1005 if (strcmp(obj->path, path) == 0)
1009 * If we didn't find a match by pathname, open the file and check
1010 * again by device and inode. This avoids false mismatches caused
1011 * by multiple links or ".." in pathnames.
1013 * To avoid a race, we open the file and use fstat() rather than
1017 if ((fd = open(path, O_RDONLY)) == -1) {
1018 _rtld_error("Cannot open \"%s\"", path);
1021 if (fstat(fd, &sb) == -1) {
1022 _rtld_error("Cannot fstat \"%s\"", path);
1026 for (obj = obj_list->next; obj != NULL; obj = obj->next) {
1027 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1034 if (obj == NULL) { /* First use of this object, so we must map it in */
1035 dbg("loading \"%s\"", path);
1036 obj = map_object(fd, path, &sb);
1044 digest_dynamic(obj);
1047 obj_tail = &obj->next;
1048 linkmap_add(obj); /* for GDB */
1050 dbg(" %p .. %p: %s", obj->mapbase,
1051 obj->mapbase + obj->mapsize - 1, obj->path);
1053 dbg(" WARNING: %s has impure text", obj->path);
1062 obj_from_addr(const void *addr)
1064 unsigned long endhash;
1067 endhash = elf_hash(END_SYM);
1068 for (obj = obj_list; obj != NULL; obj = obj->next) {
1069 const Elf_Sym *endsym;
1071 if (addr < (void *) obj->mapbase)
1073 if ((endsym = symlook_obj(END_SYM, endhash, obj, true)) == NULL)
1074 continue; /* No "end" symbol?! */
1075 if (addr < (void *) (obj->relocbase + endsym->st_value))
1082 objlist_add(Objlist *list, Obj_Entry *obj)
1086 elm = NEW(Objlist_Entry);
1088 STAILQ_INSERT_TAIL(list, elm, link);
1091 static Objlist_Entry *
1092 objlist_find(Objlist *list, const Obj_Entry *obj)
1096 STAILQ_FOREACH(elm, list, link)
1097 if (elm->obj == obj)
1103 objlist_remove(Objlist *list, Obj_Entry *obj)
1107 if ((elm = objlist_find(list, obj)) != NULL) {
1108 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1114 * Relocate newly-loaded shared objects. The argument is a pointer to
1115 * the Obj_Entry for the first such object. All objects from the first
1116 * to the end of the list of objects are relocated. Returns 0 on success,
1120 relocate_objects(Obj_Entry *first, bool bind_now)
1124 for (obj = first; obj != NULL; obj = obj->next) {
1125 if (obj != &obj_rtld)
1126 dbg("relocating \"%s\"", obj->path);
1127 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1128 obj->symtab == NULL || obj->strtab == NULL) {
1129 _rtld_error("%s: Shared object has no run-time symbol table",
1135 /* There are relocations to the write-protected text segment. */
1136 if (mprotect(obj->mapbase, obj->textsize,
1137 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1138 _rtld_error("%s: Cannot write-enable text segment: %s",
1139 obj->path, strerror(errno));
1144 /* Process the non-PLT relocations. */
1145 if (reloc_non_plt(obj, &obj_rtld))
1148 if (obj->textrel) { /* Re-protected the text segment. */
1149 if (mprotect(obj->mapbase, obj->textsize,
1150 PROT_READ|PROT_EXEC) == -1) {
1151 _rtld_error("%s: Cannot write-protect text segment: %s",
1152 obj->path, strerror(errno));
1157 /* Process the PLT relocations. */
1158 if (reloc_plt(obj, bind_now))
1162 * Set up the magic number and version in the Obj_Entry. These
1163 * were checked in the crt1.o from the original ElfKit, so we
1164 * set them for backward compatibility.
1166 obj->magic = RTLD_MAGIC;
1167 obj->version = RTLD_VERSION;
1169 /* Set the special PLT or GOT entries. */
1177 * Cleanup procedure. It will be called (by the atexit mechanism) just
1178 * before the process exits.
1184 call_fini_functions(obj_list->next);
1188 search_library_path(const char *name, const char *path)
1190 size_t namelen = strlen(name);
1191 const char *p = path;
1196 p += strspn(p, ":;");
1197 while (*p != '\0') {
1198 size_t len = strcspn(p, ":;");
1200 if (*p == '/' || trust) {
1202 const char *dir = p;
1203 size_t dirlen = len;
1205 pathname = xmalloc(dirlen + 1 + namelen + 1);
1206 strncpy(pathname, dir, dirlen);
1207 pathname[dirlen] = '/';
1208 strcpy(pathname + dirlen + 1, name);
1210 dbg(" Trying \"%s\"", pathname);
1211 if (access(pathname, F_OK) == 0) /* We found it */
1217 p += strspn(p, ":;");
1224 dlclose(void *handle)
1226 Obj_Entry *root = dlcheck(handle);
1231 GDB_STATE(RT_DELETE);
1232 unload_object(root, true);
1233 root->dl_refcount--;
1234 GDB_STATE(RT_CONSISTENT);
1242 char *msg = error_message;
1243 error_message = NULL;
1248 dlopen(const char *name, int mode)
1250 Obj_Entry **old_obj_tail = obj_tail;
1251 Obj_Entry *obj = NULL;
1259 char *path = find_library(name, obj_main);
1261 obj = load_object(path);
1266 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
1267 objlist_add(&list_global, obj);
1268 mode &= RTLD_MODEMASK;
1269 if (*old_obj_tail != NULL) { /* We loaded something new. */
1270 assert(*old_obj_tail == obj);
1272 if (load_needed_objects(obj) == -1 ||
1273 (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW)) == -1) {
1274 unload_object(obj, false);
1278 call_init_functions(obj);
1282 GDB_STATE(RT_CONSISTENT);
1288 dlsym(void *handle, const char *name)
1290 const Obj_Entry *obj;
1293 const Obj_Entry *defobj;
1295 hash = elf_hash(name);
1299 if (handle == NULL || handle == RTLD_NEXT) {
1302 retaddr = __builtin_return_address(0); /* __GNUC__ only */
1303 if ((obj = obj_from_addr(retaddr)) == NULL) {
1304 _rtld_error("Cannot determine caller's shared object");
1307 if (handle == NULL) { /* Just the caller's shared object. */
1308 def = symlook_obj(name, hash, obj, true);
1310 } else { /* All the shared objects after the caller's */
1311 while ((obj = obj->next) != NULL) {
1312 if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1319 if ((obj = dlcheck(handle)) == NULL)
1322 if (obj->mainprog) {
1323 /* Search main program and all libraries loaded by it. */
1325 def = symlook_list(name, hash, &list_main, &defobj, true);
1328 * XXX - This isn't correct. The search should include the whole
1329 * DAG rooted at the given object.
1331 def = symlook_obj(name, hash, obj, true);
1337 return defobj->relocbase + def->st_value;
1339 _rtld_error("Undefined symbol \"%s\"", name);
1344 dladdr(const void *addr, Dl_info *info)
1346 const Obj_Entry *obj;
1349 unsigned long symoffset;
1351 obj = obj_from_addr(addr);
1353 _rtld_error("No shared object contains address");
1356 info->dli_fname = obj->path;
1357 info->dli_fbase = obj->mapbase;
1358 info->dli_saddr = (void *)0;
1359 info->dli_sname = NULL;
1362 * Walk the symbol list looking for the symbol whose address is
1363 * closest to the address sent in.
1365 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1366 def = obj->symtab + symoffset;
1369 * For skip the symbol if st_shndx is either SHN_UNDEF or
1372 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1376 * If the symbol is greater than the specified address, or if it
1377 * is further away from addr than the current nearest symbol,
1380 symbol_addr = obj->relocbase + def->st_value;
1381 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1384 /* Update our idea of the nearest symbol. */
1385 info->dli_sname = obj->strtab + def->st_name;
1386 info->dli_saddr = symbol_addr;
1389 if (info->dli_saddr == addr)
1396 linkmap_add(Obj_Entry *obj)
1398 struct link_map *l = &obj->linkmap;
1399 struct link_map *prev;
1401 obj->linkmap.l_name = obj->path;
1402 obj->linkmap.l_addr = obj->mapbase;
1403 obj->linkmap.l_ld = obj->dynamic;
1405 /* GDB needs load offset on MIPS to use the symbols */
1406 obj->linkmap.l_offs = obj->relocbase;
1409 if (r_debug.r_map == NULL) {
1415 * Scan to the end of the list, but not past the entry for the
1416 * dynamic linker, which we want to keep at the very end.
1418 for (prev = r_debug.r_map;
1419 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
1420 prev = prev->l_next)
1423 /* Link in the new entry. */
1425 l->l_next = prev->l_next;
1426 if (l->l_next != NULL)
1427 l->l_next->l_prev = l;
1432 linkmap_delete(Obj_Entry *obj)
1434 struct link_map *l = &obj->linkmap;
1436 if (l->l_prev == NULL) {
1437 if ((r_debug.r_map = l->l_next) != NULL)
1438 l->l_next->l_prev = NULL;
1442 if ((l->l_prev->l_next = l->l_next) != NULL)
1443 l->l_next->l_prev = l->l_prev;
1447 * Function for the debugger to set a breakpoint on to gain control.
1455 * Set a pointer variable in the main program to the given value. This
1456 * is used to set key variables such as "environ" before any of the
1457 * init functions are called.
1460 set_program_var(const char *name, const void *value)
1462 const Obj_Entry *obj;
1465 hash = elf_hash(name);
1466 for (obj = obj_main; obj != NULL; obj = obj->next) {
1469 if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
1472 addr = (const void **)(obj->relocbase + def->st_value);
1473 dbg("\"%s\": *%p <-- %p", name, addr, value);
1480 static const Elf_Sym *
1481 symlook_list(const char *name, unsigned long hash, Objlist *objlist,
1482 const Obj_Entry **defobj_out, bool in_plt)
1484 const Elf_Sym *symp;
1486 const Obj_Entry *defobj;
1487 const Objlist_Entry *elm;
1491 STAILQ_FOREACH(elm, objlist, link) {
1492 if (elm->obj->mark == curmark)
1494 elm->obj->mark = curmark;
1495 if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
1496 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
1499 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
1505 *defobj_out = defobj;
1510 * Search the symbol table of a single shared object for a symbol of
1511 * the given name. Returns a pointer to the symbol, or NULL if no
1512 * definition was found.
1514 * The symbol's hash value is passed in for efficiency reasons; that
1515 * eliminates many recomputations of the hash value.
1518 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
1521 if (obj->buckets != NULL) {
1522 unsigned long symnum = obj->buckets[hash % obj->nbuckets];
1524 while (symnum != STN_UNDEF) {
1525 const Elf_Sym *symp;
1528 if (symnum >= obj->nchains)
1529 return NULL; /* Bad object */
1530 symp = obj->symtab + symnum;
1531 strp = obj->strtab + symp->st_name;
1533 if (strcmp(name, strp) == 0)
1534 return symp->st_shndx != SHN_UNDEF ||
1535 (!in_plt && symp->st_value != 0 &&
1536 ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
1538 symnum = obj->chains[symnum];
1545 trace_loaded_objects(Obj_Entry *obj)
1547 char *fmt1, *fmt2, *fmt, *main_local;
1550 if ((main_local = getenv("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
1553 if ((fmt1 = getenv("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
1554 fmt1 = "\t%o => %p (%x)\n";
1556 if ((fmt2 = getenv("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
1557 fmt2 = "\t%o (%x)\n";
1559 for (; obj; obj = obj->next) {
1560 Needed_Entry *needed;
1564 for (needed = obj->needed; needed; needed = needed->next) {
1565 if (needed->obj != NULL) {
1566 if (needed->obj->traced)
1568 needed->obj->traced = true;
1569 path = needed->obj->path;
1573 name = (char *)obj->strtab + needed->name;
1574 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */
1576 fmt = is_lib ? fmt1 : fmt2;
1577 while ((c = *fmt++) != '\0') {
1603 printf("%s", main_local);
1606 printf("%s", obj_main->path);
1613 printf("%d", sodp->sod_major);
1616 printf("%d", sodp->sod_minor);
1623 printf("%p", needed->obj ? needed->obj->mapbase : 0);
1635 * Note, this is called only for objects loaded by dlopen().
1638 unload_object(Obj_Entry *root, bool do_fini_funcs)
1641 if (root->refcount == 0) { /* We are finished with some objects. */
1646 /* Finalize objects that are about to be unmapped. */
1648 for (obj = obj_list->next; obj != NULL; obj = obj->next)
1649 if (obj->refcount == 0 && obj->fini != NULL)
1652 /* Remove the DAG from all objects' DAG lists. */
1653 STAILQ_FOREACH(elm, &root->dagmembers , link)
1654 objlist_remove(&elm->obj->dldags, root);
1656 /* Remove the DAG from the RTLD_GLOBAL list. */
1657 objlist_remove(&list_global, root);
1659 /* Unmap all objects that are no longer referenced. */
1660 linkp = &obj_list->next;
1661 while ((obj = *linkp) != NULL) {
1662 if (obj->refcount == 0) {
1663 dbg("unloading \"%s\"", obj->path);
1664 munmap(obj->mapbase, obj->mapsize);
1665 linkmap_delete(obj);
1676 unref_dag(Obj_Entry *root)
1678 const Needed_Entry *needed;
1680 assert(root->refcount != 0);
1682 if (root->refcount == 0)
1683 for (needed = root->needed; needed != NULL; needed = needed->next)
1684 if (needed->obj != NULL)
1685 unref_dag(needed->obj);
1689 * Non-mallocing printf, for use by malloc itself.
1690 * XXX - This doesn't belong in this module.
1693 xprintf(const char *fmt, ...)
1699 vsprintf(buf, fmt, ap);
1700 (void)write(1, buf, strlen(buf));