xref: /freebsd/libexec/rtld-elf/rtld.c (revision 04c9749ff0148ec8f73b150cec8bc2c094a5d31a)
1 /*-
2  * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
13  *
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.
24  *
25  * $FreeBSD$
26  */
27 
28 /*
29  * Dynamic linker for ELF.
30  *
31  * John Polstra <jdp@polstra.com>.
32  */
33 
34 #ifndef __GNUC__
35 #error "GCC is needed to compile this file"
36 #endif
37 
38 #include <sys/param.h>
39 #include <sys/mman.h>
40 #include <sys/stat.h>
41 
42 #include <dlfcn.h>
43 #include <err.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <stdarg.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 
52 #include "debug.h"
53 #include "rtld.h"
54 
55 #define END_SYM		"_end"
56 #define PATH_RTLD	"/usr/libexec/ld-elf.so.1"
57 
58 /* Types. */
59 typedef void (*func_ptr_type)();
60 
61 /*
62  * This structure provides a reentrant way to keep a list of objects and
63  * check which ones have already been processed in some way.
64  */
65 typedef struct Struct_DoneList {
66     Obj_Entry **objs;			/* Array of object pointers */
67     unsigned int num_alloc;		/* Allocated size of the array */
68     unsigned int num_used;		/* Number of array slots used */
69 } DoneList;
70 
71 /*
72  * Function declarations.
73  */
74 static const char *basename(const char *);
75 static void die(void);
76 static void digest_dynamic(Obj_Entry *);
77 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
78 static Obj_Entry *dlcheck(void *);
79 static bool donelist_check(DoneList *, Obj_Entry *);
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, DoneList *);
84 static void init_rtld(caddr_t);
85 static void initlist_add_neededs(Needed_Entry *needed, Objlist *list);
86 static void initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail,
87   Objlist *list);
88 static bool is_exported(const Elf_Sym *);
89 static void linkmap_add(Obj_Entry *);
90 static void linkmap_delete(Obj_Entry *);
91 static int load_needed_objects(Obj_Entry *);
92 static int load_preload_objects(void);
93 static Obj_Entry *load_object(char *);
94 static void lock_check(void);
95 static Obj_Entry *obj_from_addr(const void *);
96 static void objlist_call_fini(Objlist *);
97 static void objlist_call_init(Objlist *);
98 static void objlist_clear(Objlist *);
99 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
100 static void objlist_init(Objlist *);
101 static void objlist_push_head(Objlist *, Obj_Entry *);
102 static void objlist_push_tail(Objlist *, Obj_Entry *);
103 static void objlist_remove(Objlist *, Obj_Entry *);
104 static void objlist_remove_unref(Objlist *);
105 static int relocate_objects(Obj_Entry *, bool);
106 static void rtld_exit(void);
107 static char *search_library_path(const char *, const char *);
108 static void set_program_var(const char *, const void *);
109 static const Elf_Sym *symlook_list(const char *, unsigned long,
110   Objlist *, const Obj_Entry **, bool in_plt, DoneList *);
111 static void trace_loaded_objects(Obj_Entry *obj);
112 static void unload_object(Obj_Entry *);
113 static void unref_dag(Obj_Entry *);
114 
115 void r_debug_state(void);
116 void xprintf(const char *, ...);
117 
118 /*
119  * Data declarations.
120  */
121 static char *error_message;	/* Message for dlerror(), or NULL */
122 struct r_debug r_debug;	/* for GDB; */
123 static bool trust;		/* False for setuid and setgid programs */
124 static char *ld_bind_now;	/* Environment variable for immediate binding */
125 static char *ld_debug;		/* Environment variable for debugging */
126 static char *ld_library_path;	/* Environment variable for search path */
127 static char *ld_preload;	/* Environment variable for libraries to
128 				   load first */
129 static char *ld_tracing;	/* Called from ldd to print libs */
130 static Obj_Entry *obj_list;	/* Head of linked list of shared objects */
131 static Obj_Entry **obj_tail;	/* Link field of last object in list */
132 static Obj_Entry *obj_main;	/* The main program shared object */
133 static Obj_Entry obj_rtld;	/* The dynamic linker shared object */
134 static unsigned int obj_count;	/* Number of objects in obj_list */
135 
136 static Objlist list_global =	/* Objects dlopened with RTLD_GLOBAL */
137   STAILQ_HEAD_INITIALIZER(list_global);
138 static Objlist list_main =	/* Objects loaded at program startup */
139   STAILQ_HEAD_INITIALIZER(list_main);
140 static Objlist list_fini =	/* Objects needing fini() calls */
141   STAILQ_HEAD_INITIALIZER(list_fini);
142 
143 static LockInfo lockinfo;
144 
145 static Elf_Sym sym_zero;	/* For resolving undefined weak refs. */
146 
147 #define GDB_STATE(s)	r_debug.r_state = s; r_debug_state();
148 
149 extern Elf_Dyn _DYNAMIC;
150 #pragma weak _DYNAMIC
151 
152 /*
153  * These are the functions the dynamic linker exports to application
154  * programs.  They are the only symbols the dynamic linker is willing
155  * to export from itself.
156  */
157 static func_ptr_type exports[] = {
158     (func_ptr_type) &_rtld_error,
159     (func_ptr_type) &dlclose,
160     (func_ptr_type) &dlerror,
161     (func_ptr_type) &dlopen,
162     (func_ptr_type) &dlsym,
163     (func_ptr_type) &dladdr,
164     (func_ptr_type) &dllockinit,
165     NULL
166 };
167 
168 /*
169  * Global declarations normally provided by crt1.  The dynamic linker is
170  * not built with crt1, so we have to provide them ourselves.
171  */
172 char *__progname;
173 char **environ;
174 
175 /*
176  * Fill in a DoneList with an allocation large enough to hold all of
177  * the currently-loaded objects.  Keep this as a macro since it calls
178  * alloca and we want that to occur within the scope of the caller.
179  */
180 #define donelist_init(dlp)					\
181     ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]),	\
182     assert((dlp)->objs != NULL),				\
183     (dlp)->num_alloc = obj_count,				\
184     (dlp)->num_used = 0)
185 
186 static __inline void
187 rlock_acquire(void)
188 {
189     lockinfo.rlock_acquire(lockinfo.thelock);
190     atomic_incr_int(&lockinfo.rcount);
191     lock_check();
192 }
193 
194 static __inline void
195 wlock_acquire(void)
196 {
197     lockinfo.wlock_acquire(lockinfo.thelock);
198     atomic_incr_int(&lockinfo.wcount);
199     lock_check();
200 }
201 
202 static __inline void
203 rlock_release(void)
204 {
205     atomic_decr_int(&lockinfo.rcount);
206     lockinfo.rlock_release(lockinfo.thelock);
207 }
208 
209 static __inline void
210 wlock_release(void)
211 {
212     atomic_decr_int(&lockinfo.wcount);
213     lockinfo.wlock_release(lockinfo.thelock);
214 }
215 
216 /*
217  * Main entry point for dynamic linking.  The first argument is the
218  * stack pointer.  The stack is expected to be laid out as described
219  * in the SVR4 ABI specification, Intel 386 Processor Supplement.
220  * Specifically, the stack pointer points to a word containing
221  * ARGC.  Following that in the stack is a null-terminated sequence
222  * of pointers to argument strings.  Then comes a null-terminated
223  * sequence of pointers to environment strings.  Finally, there is a
224  * sequence of "auxiliary vector" entries.
225  *
226  * The second argument points to a place to store the dynamic linker's
227  * exit procedure pointer and the third to a place to store the main
228  * program's object.
229  *
230  * The return value is the main program's entry point.
231  */
232 func_ptr_type
233 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
234 {
235     Elf_Auxinfo *aux_info[AT_COUNT];
236     int i;
237     int argc;
238     char **argv;
239     char **env;
240     Elf_Auxinfo *aux;
241     Elf_Auxinfo *auxp;
242     const char *argv0;
243     Obj_Entry *obj;
244     Obj_Entry **preload_tail;
245     Objlist initlist;
246 
247     /*
248      * On entry, the dynamic linker itself has not been relocated yet.
249      * Be very careful not to reference any global data until after
250      * init_rtld has returned.  It is OK to reference file-scope statics
251      * and string constants, and to call static and global functions.
252      */
253 
254     /* Find the auxiliary vector on the stack. */
255     argc = *sp++;
256     argv = (char **) sp;
257     sp += argc + 1;	/* Skip over arguments and NULL terminator */
258     env = (char **) sp;
259     while (*sp++ != 0)	/* Skip over environment, and NULL terminator */
260 	;
261     aux = (Elf_Auxinfo *) sp;
262 
263     /* Digest the auxiliary vector. */
264     for (i = 0;  i < AT_COUNT;  i++)
265 	aux_info[i] = NULL;
266     for (auxp = aux;  auxp->a_type != AT_NULL;  auxp++) {
267 	if (auxp->a_type < AT_COUNT)
268 	    aux_info[auxp->a_type] = auxp;
269     }
270 
271     /* Initialize and relocate ourselves. */
272     assert(aux_info[AT_BASE] != NULL);
273     init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
274 
275     __progname = obj_rtld.path;
276     argv0 = argv[0] != NULL ? argv[0] : "(null)";
277     environ = env;
278 
279     trust = geteuid() == getuid() && getegid() == getgid();
280 
281     ld_bind_now = getenv("LD_BIND_NOW");
282     if (trust) {
283 	ld_debug = getenv("LD_DEBUG");
284 	ld_library_path = getenv("LD_LIBRARY_PATH");
285 	ld_preload = getenv("LD_PRELOAD");
286     }
287     ld_tracing = getenv("LD_TRACE_LOADED_OBJECTS");
288 
289     if (ld_debug != NULL && *ld_debug != '\0')
290 	debug = 1;
291     dbg("%s is initialized, base address = %p", __progname,
292 	(caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
293     dbg("RTLD dynamic = %p", obj_rtld.dynamic);
294     dbg("RTLD pltgot  = %p", obj_rtld.pltgot);
295 
296     /*
297      * Load the main program, or process its program header if it is
298      * already loaded.
299      */
300     if (aux_info[AT_EXECFD] != NULL) {	/* Load the main program. */
301 	int fd = aux_info[AT_EXECFD]->a_un.a_val;
302 	dbg("loading main program");
303 	obj_main = map_object(fd, argv0, NULL);
304 	close(fd);
305 	if (obj_main == NULL)
306 	    die();
307     } else {				/* Main program already loaded. */
308 	const Elf_Phdr *phdr;
309 	int phnum;
310 	caddr_t entry;
311 
312 	dbg("processing main program's program header");
313 	assert(aux_info[AT_PHDR] != NULL);
314 	phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
315 	assert(aux_info[AT_PHNUM] != NULL);
316 	phnum = aux_info[AT_PHNUM]->a_un.a_val;
317 	assert(aux_info[AT_PHENT] != NULL);
318 	assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
319 	assert(aux_info[AT_ENTRY] != NULL);
320 	entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
321 	if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
322 	    die();
323     }
324 
325     obj_main->path = xstrdup(argv0);
326     obj_main->mainprog = true;
327 
328     /*
329      * Get the actual dynamic linker pathname from the executable if
330      * possible.  (It should always be possible.)  That ensures that
331      * gdb will find the right dynamic linker even if a non-standard
332      * one is being used.
333      */
334     if (obj_main->interp != NULL &&
335       strcmp(obj_main->interp, obj_rtld.path) != 0) {
336 	free(obj_rtld.path);
337 	obj_rtld.path = xstrdup(obj_main->interp);
338     }
339 
340     digest_dynamic(obj_main);
341 
342     linkmap_add(obj_main);
343     linkmap_add(&obj_rtld);
344 
345     /* Link the main program into the list of objects. */
346     *obj_tail = obj_main;
347     obj_tail = &obj_main->next;
348     obj_count++;
349     obj_main->refcount++;
350     /* Make sure we don't call the main program's init and fini functions. */
351     obj_main->init = obj_main->fini = NULL;
352 
353     /* Initialize a fake symbol for resolving undefined weak references. */
354     sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
355     sym_zero.st_shndx = SHN_ABS;
356 
357     dbg("loading LD_PRELOAD libraries");
358     if (load_preload_objects() == -1)
359 	die();
360     preload_tail = obj_tail;
361 
362     dbg("loading needed objects");
363     if (load_needed_objects(obj_main) == -1)
364 	die();
365 
366     /* Make a list of all objects loaded at startup. */
367     for (obj = obj_list;  obj != NULL;  obj = obj->next)
368 	objlist_push_tail(&list_main, obj);
369 
370     if (ld_tracing) {		/* We're done */
371 	trace_loaded_objects(obj_main);
372 	exit(0);
373     }
374 
375     if (relocate_objects(obj_main,
376 	ld_bind_now != NULL && *ld_bind_now != '\0') == -1)
377 	die();
378 
379     dbg("doing copy relocations");
380     if (do_copy_relocations(obj_main) == -1)
381 	die();
382 
383     dbg("initializing key program variables");
384     set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
385     set_program_var("environ", env);
386 
387     dbg("initializing thread locks");
388     lockdflt_init(&lockinfo);
389     lockinfo.thelock = lockinfo.lock_create(lockinfo.context);
390 
391     /* Make a list of init functions to call. */
392     objlist_init(&initlist);
393     initlist_add_objects(obj_list, preload_tail, &initlist);
394 
395     r_debug_state();		/* say hello to gdb! */
396 
397     objlist_call_init(&initlist);
398     wlock_acquire();
399     objlist_clear(&initlist);
400     wlock_release();
401 
402     dbg("transferring control to program entry point = %p", obj_main->entry);
403 
404     /* Return the exit procedure and the program entry point. */
405     *exit_proc = rtld_exit;
406     *objp = obj_main;
407     return (func_ptr_type) obj_main->entry;
408 }
409 
410 Elf_Addr
411 _rtld_bind(Obj_Entry *obj, Elf_Word reloff)
412 {
413     const Elf_Rel *rel;
414     const Elf_Sym *def;
415     const Obj_Entry *defobj;
416     Elf_Addr *where;
417     Elf_Addr target;
418 
419     rlock_acquire();
420     if (obj->pltrel)
421 	rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
422     else
423 	rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
424 
425     where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
426     def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true);
427     if (def == NULL)
428 	die();
429 
430     target = (Elf_Addr)(defobj->relocbase + def->st_value);
431 
432     dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
433       defobj->strtab + def->st_name, basename(obj->path),
434       (void *)target, basename(defobj->path));
435 
436     reloc_jmpslot(where, target);
437     rlock_release();
438     return target;
439 }
440 
441 /*
442  * Error reporting function.  Use it like printf.  If formats the message
443  * into a buffer, and sets things up so that the next call to dlerror()
444  * will return the message.
445  */
446 void
447 _rtld_error(const char *fmt, ...)
448 {
449     static char buf[512];
450     va_list ap;
451 
452     va_start(ap, fmt);
453     vsnprintf(buf, sizeof buf, fmt, ap);
454     error_message = buf;
455     va_end(ap);
456 }
457 
458 static const char *
459 basename(const char *name)
460 {
461     const char *p = strrchr(name, '/');
462     return p != NULL ? p + 1 : name;
463 }
464 
465 static void
466 die(void)
467 {
468     const char *msg = dlerror();
469 
470     if (msg == NULL)
471 	msg = "Fatal error";
472     errx(1, "%s", msg);
473 }
474 
475 /*
476  * Process a shared object's DYNAMIC section, and save the important
477  * information in its Obj_Entry structure.
478  */
479 static void
480 digest_dynamic(Obj_Entry *obj)
481 {
482     const Elf_Dyn *dynp;
483     Needed_Entry **needed_tail = &obj->needed;
484     const Elf_Dyn *dyn_rpath = NULL;
485     int plttype = DT_REL;
486 
487     for (dynp = obj->dynamic;  dynp->d_tag != DT_NULL;  dynp++) {
488 	switch (dynp->d_tag) {
489 
490 	case DT_REL:
491 	    obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
492 	    break;
493 
494 	case DT_RELSZ:
495 	    obj->relsize = dynp->d_un.d_val;
496 	    break;
497 
498 	case DT_RELENT:
499 	    assert(dynp->d_un.d_val == sizeof(Elf_Rel));
500 	    break;
501 
502 	case DT_JMPREL:
503 	    obj->pltrel = (const Elf_Rel *)
504 	      (obj->relocbase + dynp->d_un.d_ptr);
505 	    break;
506 
507 	case DT_PLTRELSZ:
508 	    obj->pltrelsize = dynp->d_un.d_val;
509 	    break;
510 
511 	case DT_RELA:
512 	    obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
513 	    break;
514 
515 	case DT_RELASZ:
516 	    obj->relasize = dynp->d_un.d_val;
517 	    break;
518 
519 	case DT_RELAENT:
520 	    assert(dynp->d_un.d_val == sizeof(Elf_Rela));
521 	    break;
522 
523 	case DT_PLTREL:
524 	    plttype = dynp->d_un.d_val;
525 	    assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
526 	    break;
527 
528 	case DT_SYMTAB:
529 	    obj->symtab = (const Elf_Sym *)
530 	      (obj->relocbase + dynp->d_un.d_ptr);
531 	    break;
532 
533 	case DT_SYMENT:
534 	    assert(dynp->d_un.d_val == sizeof(Elf_Sym));
535 	    break;
536 
537 	case DT_STRTAB:
538 	    obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
539 	    break;
540 
541 	case DT_STRSZ:
542 	    obj->strsize = dynp->d_un.d_val;
543 	    break;
544 
545 	case DT_HASH:
546 	    {
547 		const Elf_Addr *hashtab = (const Elf_Addr *)
548 		  (obj->relocbase + dynp->d_un.d_ptr);
549 		obj->nbuckets = hashtab[0];
550 		obj->nchains = hashtab[1];
551 		obj->buckets = hashtab + 2;
552 		obj->chains = obj->buckets + obj->nbuckets;
553 	    }
554 	    break;
555 
556 	case DT_NEEDED:
557 	    if (!obj->rtld) {
558 		Needed_Entry *nep = NEW(Needed_Entry);
559 		nep->name = dynp->d_un.d_val;
560 		nep->obj = NULL;
561 		nep->next = NULL;
562 
563 		*needed_tail = nep;
564 		needed_tail = &nep->next;
565 	    }
566 	    break;
567 
568 	case DT_PLTGOT:
569 	    obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
570 	    break;
571 
572 	case DT_TEXTREL:
573 	    obj->textrel = true;
574 	    break;
575 
576 	case DT_SYMBOLIC:
577 	    obj->symbolic = true;
578 	    break;
579 
580 	case DT_RPATH:
581 	    /*
582 	     * We have to wait until later to process this, because we
583 	     * might not have gotten the address of the string table yet.
584 	     */
585 	    dyn_rpath = dynp;
586 	    break;
587 
588 	case DT_SONAME:
589 	    /* Not used by the dynamic linker. */
590 	    break;
591 
592 	case DT_INIT:
593 	    obj->init = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
594 	    break;
595 
596 	case DT_FINI:
597 	    obj->fini = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
598 	    break;
599 
600 	case DT_DEBUG:
601 	    /* XXX - not implemented yet */
602 	    dbg("Filling in DT_DEBUG entry");
603 	    ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
604 	    break;
605 
606 	default:
607 	    dbg("Ignoring d_tag %d = %#x", dynp->d_tag, dynp->d_tag);
608 	    break;
609 	}
610     }
611 
612     obj->traced = false;
613 
614     if (plttype == DT_RELA) {
615 	obj->pltrela = (const Elf_Rela *) obj->pltrel;
616 	obj->pltrel = NULL;
617 	obj->pltrelasize = obj->pltrelsize;
618 	obj->pltrelsize = 0;
619     }
620 
621     if (dyn_rpath != NULL)
622 	obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
623 }
624 
625 /*
626  * Process a shared object's program header.  This is used only for the
627  * main program, when the kernel has already loaded the main program
628  * into memory before calling the dynamic linker.  It creates and
629  * returns an Obj_Entry structure.
630  */
631 static Obj_Entry *
632 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
633 {
634     Obj_Entry *obj;
635     const Elf_Phdr *phlimit = phdr + phnum;
636     const Elf_Phdr *ph;
637     int nsegs = 0;
638 
639     obj = obj_new();
640     for (ph = phdr;  ph < phlimit;  ph++) {
641 	switch (ph->p_type) {
642 
643 	case PT_PHDR:
644 	    if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
645 		_rtld_error("%s: invalid PT_PHDR", path);
646 		return NULL;
647 	    }
648 	    obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
649 	    obj->phsize = ph->p_memsz;
650 	    break;
651 
652 	case PT_INTERP:
653 	    obj->interp = (const char *) ph->p_vaddr;
654 	    break;
655 
656 	case PT_LOAD:
657 	    if (nsegs >= 2) {
658 		_rtld_error("%s: too many PT_LOAD segments", path);
659 		return NULL;
660 	    }
661 	    if (nsegs == 0) {	/* First load segment */
662 		obj->vaddrbase = trunc_page(ph->p_vaddr);
663 		obj->mapbase = (caddr_t) obj->vaddrbase;
664 		obj->relocbase = obj->mapbase - obj->vaddrbase;
665 		obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
666 		  obj->vaddrbase;
667 	    } else {		/* Last load segment */
668 		obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
669 		  obj->vaddrbase;
670 	    }
671 	    nsegs++;
672 	    break;
673 
674 	case PT_DYNAMIC:
675 	    obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
676 	    break;
677 	}
678     }
679     if (nsegs < 2) {
680 	_rtld_error("%s: too few PT_LOAD segments", path);
681 	return NULL;
682     }
683 
684     obj->entry = entry;
685     return obj;
686 }
687 
688 static Obj_Entry *
689 dlcheck(void *handle)
690 {
691     Obj_Entry *obj;
692 
693     for (obj = obj_list;  obj != NULL;  obj = obj->next)
694 	if (obj == (Obj_Entry *) handle)
695 	    break;
696 
697     if (obj == NULL || obj->dl_refcount == 0) {
698 	_rtld_error("Invalid shared object handle %p", handle);
699 	return NULL;
700     }
701     return obj;
702 }
703 
704 /*
705  * If the given object is already in the donelist, return true.  Otherwise
706  * add the object to the list and return false.
707  */
708 static bool
709 donelist_check(DoneList *dlp, Obj_Entry *obj)
710 {
711     unsigned int i;
712 
713     for (i = 0;  i < dlp->num_used;  i++)
714 	if (dlp->objs[i] == obj)
715 	    return true;
716     /*
717      * Our donelist allocation should always be sufficient.  But if
718      * our threads locking isn't working properly, more shared objects
719      * could have been loaded since we allocated the list.  That should
720      * never happen, but we'll handle it properly just in case it does.
721      */
722     if (dlp->num_used < dlp->num_alloc)
723 	dlp->objs[dlp->num_used++] = obj;
724     return false;
725 }
726 
727 /*
728  * Hash function for symbol table lookup.  Don't even think about changing
729  * this.  It is specified by the System V ABI.
730  */
731 unsigned long
732 elf_hash(const char *name)
733 {
734     const unsigned char *p = (const unsigned char *) name;
735     unsigned long h = 0;
736     unsigned long g;
737 
738     while (*p != '\0') {
739 	h = (h << 4) + *p++;
740 	if ((g = h & 0xf0000000) != 0)
741 	    h ^= g >> 24;
742 	h &= ~g;
743     }
744     return h;
745 }
746 
747 /*
748  * Find the library with the given name, and return its full pathname.
749  * The returned string is dynamically allocated.  Generates an error
750  * message and returns NULL if the library cannot be found.
751  *
752  * If the second argument is non-NULL, then it refers to an already-
753  * loaded shared object, whose library search path will be searched.
754  *
755  * The search order is:
756  *   rpath in the referencing file
757  *   LD_LIBRARY_PATH
758  *   ldconfig hints
759  *   /usr/lib
760  */
761 static char *
762 find_library(const char *name, const Obj_Entry *refobj)
763 {
764     char *pathname;
765 
766     if (strchr(name, '/') != NULL) {	/* Hard coded pathname */
767 	if (name[0] != '/' && !trust) {
768 	    _rtld_error("Absolute pathname required for shared object \"%s\"",
769 	      name);
770 	    return NULL;
771 	}
772 	return xstrdup(name);
773     }
774 
775     dbg(" Searching for \"%s\"", name);
776 
777     if ((refobj != NULL &&
778       (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
779       (pathname = search_library_path(name, ld_library_path)) != NULL ||
780       (pathname = search_library_path(name, gethints())) != NULL ||
781       (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
782 	return pathname;
783 
784     _rtld_error("Shared object \"%s\" not found", name);
785     return NULL;
786 }
787 
788 /*
789  * Given a symbol number in a referencing object, find the corresponding
790  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
791  * no definition was found.  Returns a pointer to the Obj_Entry of the
792  * defining object via the reference parameter DEFOBJ_OUT.
793  */
794 const Elf_Sym *
795 find_symdef(unsigned long symnum, Obj_Entry *refobj,
796     const Obj_Entry **defobj_out, bool in_plt)
797 {
798     DoneList donelist;
799     const Elf_Sym *ref;
800     const Elf_Sym *def;
801     const Elf_Sym *symp;
802     const Obj_Entry *obj;
803     const Obj_Entry *defobj;
804     const Objlist_Entry *elm;
805     const char *name;
806     unsigned long hash;
807 
808     ref = refobj->symtab + symnum;
809     name = refobj->strtab + ref->st_name;
810     hash = elf_hash(name);
811     def = NULL;
812     defobj = NULL;
813     donelist_init(&donelist);
814 
815     /* Look first in the referencing object if linked symbolically. */
816     if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
817 	symp = symlook_obj(name, hash, refobj, in_plt);
818 	if (symp != NULL) {
819 	    def = symp;
820 	    defobj = refobj;
821 	}
822     }
823 
824     /* Search all objects loaded at program start up. */
825     if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
826 	symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist);
827 	if (symp != NULL &&
828 	  (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
829 	    def = symp;
830 	    defobj = obj;
831 	}
832     }
833 
834     /* Search all dlopened DAGs containing the referencing object. */
835     STAILQ_FOREACH(elm, &refobj->dldags, link) {
836 	if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
837 	    break;
838 	symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
839 	  &donelist);
840 	if (symp != NULL &&
841 	  (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
842 	    def = symp;
843 	    defobj = obj;
844 	}
845     }
846 
847     /* Search all RTLD_GLOBAL objects. */
848     if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
849 	symp = symlook_list(name, hash, &list_global, &obj, in_plt, &donelist);
850 	if (symp != NULL &&
851 	  (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
852 	    def = symp;
853 	    defobj = obj;
854 	}
855     }
856 
857     /*
858      * Search the dynamic linker itself, and possibly resolve the
859      * symbol from there.  This is how the application links to
860      * dynamic linker services such as dlopen.  Only the values listed
861      * in the "exports" array can be resolved from the dynamic linker.
862      */
863     if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
864 	symp = symlook_obj(name, hash, &obj_rtld, in_plt);
865 	if (symp != NULL && is_exported(symp)) {
866 	    def = symp;
867 	    defobj = &obj_rtld;
868 	}
869     }
870 
871     /*
872      * If we found no definition and the reference is weak, treat the
873      * symbol as having the value zero.
874      */
875     if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
876 	def = &sym_zero;
877 	defobj = obj_main;
878     }
879 
880     if (def != NULL)
881 	*defobj_out = defobj;
882     else
883 	_rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
884     return def;
885 }
886 
887 /*
888  * Return the search path from the ldconfig hints file, reading it if
889  * necessary.  Returns NULL if there are problems with the hints file,
890  * or if the search path there is empty.
891  */
892 static const char *
893 gethints(void)
894 {
895     static char *hints;
896 
897     if (hints == NULL) {
898 	int fd;
899 	struct elfhints_hdr hdr;
900 	char *p;
901 
902 	/* Keep from trying again in case the hints file is bad. */
903 	hints = "";
904 
905 	if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
906 	    return NULL;
907 	if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
908 	  hdr.magic != ELFHINTS_MAGIC ||
909 	  hdr.version != 1) {
910 	    close(fd);
911 	    return NULL;
912 	}
913 	p = xmalloc(hdr.dirlistlen + 1);
914 	if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
915 	  read(fd, p, hdr.dirlistlen + 1) != hdr.dirlistlen + 1) {
916 	    free(p);
917 	    close(fd);
918 	    return NULL;
919 	}
920 	hints = p;
921 	close(fd);
922     }
923     return hints[0] != '\0' ? hints : NULL;
924 }
925 
926 static void
927 init_dag(Obj_Entry *root)
928 {
929     DoneList donelist;
930 
931     donelist_init(&donelist);
932     init_dag1(root, root, &donelist);
933 }
934 
935 static void
936 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
937 {
938     const Needed_Entry *needed;
939 
940     if (donelist_check(dlp, obj))
941 	return;
942     objlist_push_tail(&obj->dldags, root);
943     objlist_push_tail(&root->dagmembers, obj);
944     for (needed = obj->needed;  needed != NULL;  needed = needed->next)
945 	if (needed->obj != NULL)
946 	    init_dag1(root, needed->obj, dlp);
947 }
948 
949 /*
950  * Initialize the dynamic linker.  The argument is the address at which
951  * the dynamic linker has been mapped into memory.  The primary task of
952  * this function is to relocate the dynamic linker.
953  */
954 static void
955 init_rtld(caddr_t mapbase)
956 {
957     /*
958      * Conjure up an Obj_Entry structure for the dynamic linker.
959      *
960      * The "path" member is supposed to be dynamically-allocated, but we
961      * aren't yet initialized sufficiently to do that.  Below we will
962      * replace the static version with a dynamically-allocated copy.
963      */
964     obj_rtld.path = PATH_RTLD;
965     obj_rtld.rtld = true;
966     obj_rtld.mapbase = mapbase;
967 #ifdef PIC
968     obj_rtld.relocbase = mapbase;
969 #endif
970     if (&_DYNAMIC != 0) {
971 	obj_rtld.dynamic = rtld_dynamic(&obj_rtld);
972 	digest_dynamic(&obj_rtld);
973 	assert(obj_rtld.needed == NULL);
974 	assert(!obj_rtld.textrel);
975 
976 	/*
977 	 * Temporarily put the dynamic linker entry into the object list, so
978 	 * that symbols can be found.
979 	 */
980 	obj_list = &obj_rtld;
981 	obj_tail = &obj_rtld.next;
982 	obj_count = 1;
983 
984 	relocate_objects(&obj_rtld, true);
985     }
986 
987     /* Make the object list empty again. */
988     obj_list = NULL;
989     obj_tail = &obj_list;
990     obj_count = 0;
991 
992     /* Replace the path with a dynamically allocated copy. */
993     obj_rtld.path = xstrdup(obj_rtld.path);
994 
995     r_debug.r_brk = r_debug_state;
996     r_debug.r_state = RT_CONSISTENT;
997 }
998 
999 /*
1000  * Add the init functions from a needed object list (and its recursive
1001  * needed objects) to "list".  This is not used directly; it is a helper
1002  * function for initlist_add_objects().  The write lock must be held
1003  * when this function is called.
1004  */
1005 static void
1006 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1007 {
1008     /* Recursively process the successor needed objects. */
1009     if (needed->next != NULL)
1010 	initlist_add_neededs(needed->next, list);
1011 
1012     /* Process the current needed object. */
1013     if (needed->obj != NULL)
1014 	initlist_add_objects(needed->obj, &needed->obj->next, list);
1015 }
1016 
1017 /*
1018  * Scan all of the DAGs rooted in the range of objects from "obj" to
1019  * "tail" and add their init functions to "list".  This recurses over
1020  * the DAGs and ensure the proper init ordering such that each object's
1021  * needed libraries are initialized before the object itself.  At the
1022  * same time, this function adds the objects to the global finalization
1023  * list "list_fini" in the opposite order.  The write lock must be
1024  * held when this function is called.
1025  */
1026 static void
1027 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1028 {
1029     if (obj->init_done)
1030 	return;
1031     obj->init_done = true;
1032 
1033     /* Recursively process the successor objects. */
1034     if (&obj->next != tail)
1035 	initlist_add_objects(obj->next, tail, list);
1036 
1037     /* Recursively process the needed objects. */
1038     if (obj->needed != NULL)
1039 	initlist_add_neededs(obj->needed, list);
1040 
1041     /* Add the object to the init list. */
1042     if (obj->init != NULL)
1043 	objlist_push_tail(list, obj);
1044 
1045     /* Add the object to the global fini list in the reverse order. */
1046     if (obj->fini != NULL)
1047 	objlist_push_head(&list_fini, obj);
1048 }
1049 
1050 static bool
1051 is_exported(const Elf_Sym *def)
1052 {
1053     func_ptr_type value;
1054     const func_ptr_type *p;
1055 
1056     value = (func_ptr_type)(obj_rtld.relocbase + def->st_value);
1057     for (p = exports;  *p != NULL;  p++)
1058 	if (*p == value)
1059 	    return true;
1060     return false;
1061 }
1062 
1063 /*
1064  * Given a shared object, traverse its list of needed objects, and load
1065  * each of them.  Returns 0 on success.  Generates an error message and
1066  * returns -1 on failure.
1067  */
1068 static int
1069 load_needed_objects(Obj_Entry *first)
1070 {
1071     Obj_Entry *obj;
1072 
1073     for (obj = first;  obj != NULL;  obj = obj->next) {
1074 	Needed_Entry *needed;
1075 
1076 	for (needed = obj->needed;  needed != NULL;  needed = needed->next) {
1077 	    const char *name = obj->strtab + needed->name;
1078 	    char *path = find_library(name, obj);
1079 
1080 	    needed->obj = NULL;
1081 	    if (path == NULL && !ld_tracing)
1082 		return -1;
1083 
1084 	    if (path) {
1085 		needed->obj = load_object(path);
1086 		if (needed->obj == NULL && !ld_tracing)
1087 		    return -1;		/* XXX - cleanup */
1088 	    }
1089 	}
1090     }
1091 
1092     return 0;
1093 }
1094 
1095 static int
1096 load_preload_objects(void)
1097 {
1098     char *p = ld_preload;
1099     static const char delim[] = " \t:;";
1100 
1101     if (p == NULL)
1102 	return NULL;
1103 
1104     p += strspn(p, delim);
1105     while (*p != '\0') {
1106 	size_t len = strcspn(p, delim);
1107 	char *path;
1108 	char savech;
1109 
1110 	savech = p[len];
1111 	p[len] = '\0';
1112 	if ((path = find_library(p, NULL)) == NULL)
1113 	    return -1;
1114 	if (load_object(path) == NULL)
1115 	    return -1;	/* XXX - cleanup */
1116 	p[len] = savech;
1117 	p += len;
1118 	p += strspn(p, delim);
1119     }
1120     return 0;
1121 }
1122 
1123 /*
1124  * Load a shared object into memory, if it is not already loaded.  The
1125  * argument must be a string allocated on the heap.  This function assumes
1126  * responsibility for freeing it when necessary.
1127  *
1128  * Returns a pointer to the Obj_Entry for the object.  Returns NULL
1129  * on failure.
1130  */
1131 static Obj_Entry *
1132 load_object(char *path)
1133 {
1134     Obj_Entry *obj;
1135     int fd = -1;
1136     struct stat sb;
1137 
1138     for (obj = obj_list->next;  obj != NULL;  obj = obj->next)
1139 	if (strcmp(obj->path, path) == 0)
1140 	    break;
1141 
1142     /*
1143      * If we didn't find a match by pathname, open the file and check
1144      * again by device and inode.  This avoids false mismatches caused
1145      * by multiple links or ".." in pathnames.
1146      *
1147      * To avoid a race, we open the file and use fstat() rather than
1148      * using stat().
1149      */
1150     if (obj == NULL) {
1151 	if ((fd = open(path, O_RDONLY)) == -1) {
1152 	    _rtld_error("Cannot open \"%s\"", path);
1153 	    return NULL;
1154 	}
1155 	if (fstat(fd, &sb) == -1) {
1156 	    _rtld_error("Cannot fstat \"%s\"", path);
1157 	    close(fd);
1158 	    return NULL;
1159 	}
1160 	for (obj = obj_list->next;  obj != NULL;  obj = obj->next) {
1161 	    if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1162 		close(fd);
1163 		break;
1164 	    }
1165 	}
1166     }
1167 
1168     if (obj == NULL) {	/* First use of this object, so we must map it in */
1169 	dbg("loading \"%s\"", path);
1170 	obj = map_object(fd, path, &sb);
1171 	close(fd);
1172 	if (obj == NULL) {
1173 	    free(path);
1174 	    return NULL;
1175 	}
1176 
1177 	obj->path = path;
1178 	digest_dynamic(obj);
1179 
1180 	*obj_tail = obj;
1181 	obj_tail = &obj->next;
1182 	obj_count++;
1183 	linkmap_add(obj);	/* for GDB */
1184 
1185 	dbg("  %p .. %p: %s", obj->mapbase,
1186 	  obj->mapbase + obj->mapsize - 1, obj->path);
1187 	if (obj->textrel)
1188 	    dbg("  WARNING: %s has impure text", obj->path);
1189     } else
1190 	free(path);
1191 
1192     obj->refcount++;
1193     return obj;
1194 }
1195 
1196 /*
1197  * Check for locking violations and die if one is found.
1198  */
1199 static void
1200 lock_check(void)
1201 {
1202     int rcount, wcount;
1203 
1204     rcount = lockinfo.rcount;
1205     wcount = lockinfo.wcount;
1206     assert(rcount >= 0);
1207     assert(wcount >= 0);
1208     if (wcount > 1 || (wcount != 0 && rcount != 0)) {
1209 	_rtld_error("Application locking error: %d readers and %d writers"
1210 	  " in dynamic linker.  See DLLOCKINIT(3) in manual pages.",
1211 	  rcount, wcount);
1212 	die();
1213     }
1214 }
1215 
1216 static Obj_Entry *
1217 obj_from_addr(const void *addr)
1218 {
1219     unsigned long endhash;
1220     Obj_Entry *obj;
1221 
1222     endhash = elf_hash(END_SYM);
1223     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
1224 	const Elf_Sym *endsym;
1225 
1226 	if (addr < (void *) obj->mapbase)
1227 	    continue;
1228 	if ((endsym = symlook_obj(END_SYM, endhash, obj, true)) == NULL)
1229 	    continue;	/* No "end" symbol?! */
1230 	if (addr < (void *) (obj->relocbase + endsym->st_value))
1231 	    return obj;
1232     }
1233     return NULL;
1234 }
1235 
1236 /*
1237  * Call the finalization functions for each of the objects in "list"
1238  * which are unreferenced.  All of the objects are expected to have
1239  * non-NULL fini functions.
1240  */
1241 static void
1242 objlist_call_fini(Objlist *list)
1243 {
1244     Objlist_Entry *elm;
1245 
1246     STAILQ_FOREACH(elm, list, link) {
1247 	if (elm->obj->refcount == 0) {
1248 	    dbg("calling fini function for %s", elm->obj->path);
1249 	    (*elm->obj->fini)();
1250 	}
1251     }
1252 }
1253 
1254 /*
1255  * Call the initialization functions for each of the objects in
1256  * "list".  All of the objects are expected to have non-NULL init
1257  * functions.
1258  */
1259 static void
1260 objlist_call_init(Objlist *list)
1261 {
1262     Objlist_Entry *elm;
1263 
1264     STAILQ_FOREACH(elm, list, link) {
1265 	dbg("calling init function for %s", elm->obj->path);
1266 	(*elm->obj->init)();
1267     }
1268 }
1269 
1270 static void
1271 objlist_clear(Objlist *list)
1272 {
1273     Objlist_Entry *elm;
1274 
1275     while (!STAILQ_EMPTY(list)) {
1276 	elm = STAILQ_FIRST(list);
1277 	STAILQ_REMOVE_HEAD(list, link);
1278 	free(elm);
1279     }
1280 }
1281 
1282 static Objlist_Entry *
1283 objlist_find(Objlist *list, const Obj_Entry *obj)
1284 {
1285     Objlist_Entry *elm;
1286 
1287     STAILQ_FOREACH(elm, list, link)
1288 	if (elm->obj == obj)
1289 	    return elm;
1290     return NULL;
1291 }
1292 
1293 static void
1294 objlist_init(Objlist *list)
1295 {
1296     STAILQ_INIT(list);
1297 }
1298 
1299 static void
1300 objlist_push_head(Objlist *list, Obj_Entry *obj)
1301 {
1302     Objlist_Entry *elm;
1303 
1304     elm = NEW(Objlist_Entry);
1305     elm->obj = obj;
1306     STAILQ_INSERT_HEAD(list, elm, link);
1307 }
1308 
1309 static void
1310 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1311 {
1312     Objlist_Entry *elm;
1313 
1314     elm = NEW(Objlist_Entry);
1315     elm->obj = obj;
1316     STAILQ_INSERT_TAIL(list, elm, link);
1317 }
1318 
1319 static void
1320 objlist_remove(Objlist *list, Obj_Entry *obj)
1321 {
1322     Objlist_Entry *elm;
1323 
1324     if ((elm = objlist_find(list, obj)) != NULL) {
1325 	STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1326 	free(elm);
1327     }
1328 }
1329 
1330 /*
1331  * Remove all of the unreferenced objects from "list".
1332  */
1333 static void
1334 objlist_remove_unref(Objlist *list)
1335 {
1336     Objlist newlist;
1337     Objlist_Entry *elm;
1338 
1339     STAILQ_INIT(&newlist);
1340     while (!STAILQ_EMPTY(list)) {
1341 	elm = STAILQ_FIRST(list);
1342 	STAILQ_REMOVE_HEAD(list, link);
1343 	if (elm->obj->refcount == 0)
1344 	    free(elm);
1345 	else
1346 	    STAILQ_INSERT_TAIL(&newlist, elm, link);
1347     }
1348     *list = newlist;
1349 }
1350 
1351 /*
1352  * Relocate newly-loaded shared objects.  The argument is a pointer to
1353  * the Obj_Entry for the first such object.  All objects from the first
1354  * to the end of the list of objects are relocated.  Returns 0 on success,
1355  * or -1 on failure.
1356  */
1357 static int
1358 relocate_objects(Obj_Entry *first, bool bind_now)
1359 {
1360     Obj_Entry *obj;
1361 
1362     for (obj = first;  obj != NULL;  obj = obj->next) {
1363 	if (obj != &obj_rtld)
1364 	    dbg("relocating \"%s\"", obj->path);
1365 	if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1366 	    obj->symtab == NULL || obj->strtab == NULL) {
1367 	    _rtld_error("%s: Shared object has no run-time symbol table",
1368 	      obj->path);
1369 	    return -1;
1370 	}
1371 
1372 	if (obj->textrel) {
1373 	    /* There are relocations to the write-protected text segment. */
1374 	    if (mprotect(obj->mapbase, obj->textsize,
1375 	      PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1376 		_rtld_error("%s: Cannot write-enable text segment: %s",
1377 		  obj->path, strerror(errno));
1378 		return -1;
1379 	    }
1380 	}
1381 
1382 	/* Process the non-PLT relocations. */
1383 	if (reloc_non_plt(obj, &obj_rtld))
1384 		return -1;
1385 
1386 	if (obj->textrel) {	/* Re-protected the text segment. */
1387 	    if (mprotect(obj->mapbase, obj->textsize,
1388 	      PROT_READ|PROT_EXEC) == -1) {
1389 		_rtld_error("%s: Cannot write-protect text segment: %s",
1390 		  obj->path, strerror(errno));
1391 		return -1;
1392 	    }
1393 	}
1394 
1395 	/* Process the PLT relocations. */
1396 	if (reloc_plt(obj) == -1)
1397 	    return -1;
1398 	/* Relocate the jump slots if we are doing immediate binding. */
1399 	if (bind_now)
1400 	    if (reloc_jmpslots(obj) == -1)
1401 		return -1;
1402 
1403 
1404 	/*
1405 	 * Set up the magic number and version in the Obj_Entry.  These
1406 	 * were checked in the crt1.o from the original ElfKit, so we
1407 	 * set them for backward compatibility.
1408 	 */
1409 	obj->magic = RTLD_MAGIC;
1410 	obj->version = RTLD_VERSION;
1411 
1412 	/* Set the special PLT or GOT entries. */
1413 	init_pltgot(obj);
1414     }
1415 
1416     return 0;
1417 }
1418 
1419 /*
1420  * Cleanup procedure.  It will be called (by the atexit mechanism) just
1421  * before the process exits.
1422  */
1423 static void
1424 rtld_exit(void)
1425 {
1426     Obj_Entry *obj;
1427 
1428     dbg("rtld_exit()");
1429     wlock_acquire();
1430     /* Clear all the reference counts so the fini functions will be called. */
1431     for (obj = obj_list;  obj != NULL;  obj = obj->next)
1432 	obj->refcount = 0;
1433     wlock_release();
1434     objlist_call_fini(&list_fini);
1435     /* No need to remove the items from the list, since we are exiting. */
1436 }
1437 
1438 static char *
1439 search_library_path(const char *name, const char *path)
1440 {
1441     size_t namelen = strlen(name);
1442     const char *p = path;
1443 
1444     if (p == NULL)
1445 	return NULL;
1446 
1447     p += strspn(p, ":;");
1448     while (*p != '\0') {
1449 	size_t len = strcspn(p, ":;");
1450 
1451 	if (*p == '/' || trust) {
1452 	    char *pathname;
1453 	    const char *dir = p;
1454 	    size_t dirlen = len;
1455 
1456 	    pathname = xmalloc(dirlen + 1 + namelen + 1);
1457 	    strncpy(pathname, dir, dirlen);
1458 	    pathname[dirlen] = '/';
1459 	    strcpy(pathname + dirlen + 1, name);
1460 
1461 	    dbg("  Trying \"%s\"", pathname);
1462 	    if (access(pathname, F_OK) == 0)		/* We found it */
1463 		return pathname;
1464 
1465 	    free(pathname);
1466 	}
1467 	p += len;
1468 	p += strspn(p, ":;");
1469     }
1470 
1471     return NULL;
1472 }
1473 
1474 int
1475 dlclose(void *handle)
1476 {
1477     Obj_Entry *root;
1478 
1479     wlock_acquire();
1480     root = dlcheck(handle);
1481     if (root == NULL) {
1482 	wlock_release();
1483 	return -1;
1484     }
1485 
1486     /* Unreference the object and its dependencies. */
1487     root->dl_refcount--;
1488     unref_dag(root);
1489 
1490     if (root->refcount == 0) {
1491 	/*
1492 	 * The object is no longer referenced, so we must unload it.
1493 	 * First, call the fini functions with no locks held.
1494 	 */
1495 	wlock_release();
1496 	objlist_call_fini(&list_fini);
1497 	wlock_acquire();
1498 	objlist_remove_unref(&list_fini);
1499 
1500 	/* Finish cleaning up the newly-unreferenced objects. */
1501 	GDB_STATE(RT_DELETE);
1502 	unload_object(root);
1503 	GDB_STATE(RT_CONSISTENT);
1504     }
1505     wlock_release();
1506     return 0;
1507 }
1508 
1509 const char *
1510 dlerror(void)
1511 {
1512     char *msg = error_message;
1513     error_message = NULL;
1514     return msg;
1515 }
1516 
1517 /*
1518  * This function is deprecated and has no effect.
1519  */
1520 void
1521 dllockinit(void *context,
1522 	   void *(*lock_create)(void *context),
1523            void (*rlock_acquire)(void *lock),
1524            void (*wlock_acquire)(void *lock),
1525            void (*lock_release)(void *lock),
1526            void (*lock_destroy)(void *lock),
1527 	   void (*context_destroy)(void *context))
1528 {
1529     static void *cur_context;
1530     static void (*cur_context_destroy)(void *);
1531 
1532     /* Just destroy the context from the previous call, if necessary. */
1533     if (cur_context_destroy != NULL)
1534 	cur_context_destroy(cur_context);
1535     cur_context = context;
1536     cur_context_destroy = context_destroy;
1537 }
1538 
1539 void *
1540 dlopen(const char *name, int mode)
1541 {
1542     Obj_Entry **old_obj_tail;
1543     Obj_Entry *obj;
1544     Objlist initlist;
1545 
1546     objlist_init(&initlist);
1547 
1548     wlock_acquire();
1549     GDB_STATE(RT_ADD);
1550 
1551     old_obj_tail = obj_tail;
1552     obj = NULL;
1553     if (name == NULL) {
1554 	obj = obj_main;
1555 	obj->refcount++;
1556     } else {
1557 	char *path = find_library(name, obj_main);
1558 	if (path != NULL)
1559 	    obj = load_object(path);
1560     }
1561 
1562     if (obj) {
1563 	obj->dl_refcount++;
1564 	if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
1565 	    objlist_push_tail(&list_global, obj);
1566 	mode &= RTLD_MODEMASK;
1567 	if (*old_obj_tail != NULL) {		/* We loaded something new. */
1568 	    assert(*old_obj_tail == obj);
1569 
1570 	    if (load_needed_objects(obj) == -1 ||
1571 	      (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW)) == -1) {
1572 		obj->dl_refcount--;
1573 		unref_dag(obj);
1574 		if (obj->refcount == 0)
1575 		    unload_object(obj);
1576 		obj = NULL;
1577 	    } else {
1578 		/* Make list of init functions to call. */
1579 		initlist_add_objects(obj, &obj->next, &initlist);
1580 	    }
1581 	}
1582     }
1583 
1584     GDB_STATE(RT_CONSISTENT);
1585 
1586     /* Call the init functions with no locks held. */
1587     wlock_release();
1588     objlist_call_init(&initlist);
1589     wlock_acquire();
1590     objlist_clear(&initlist);
1591     wlock_release();
1592     return obj;
1593 }
1594 
1595 void *
1596 dlsym(void *handle, const char *name)
1597 {
1598     const Obj_Entry *obj;
1599     unsigned long hash;
1600     const Elf_Sym *def;
1601     const Obj_Entry *defobj;
1602 
1603     hash = elf_hash(name);
1604     def = NULL;
1605     defobj = NULL;
1606 
1607     rlock_acquire();
1608     if (handle == NULL || handle == RTLD_NEXT) {
1609 	void *retaddr;
1610 
1611 	retaddr = __builtin_return_address(0);	/* __GNUC__ only */
1612 	if ((obj = obj_from_addr(retaddr)) == NULL) {
1613 	    _rtld_error("Cannot determine caller's shared object");
1614 	    rlock_release();
1615 	    return NULL;
1616 	}
1617 	if (handle == NULL) {	/* Just the caller's shared object. */
1618 	    def = symlook_obj(name, hash, obj, true);
1619 	    defobj = obj;
1620 	} else {		/* All the shared objects after the caller's */
1621 	    while ((obj = obj->next) != NULL) {
1622 		if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1623 		    defobj = obj;
1624 		    break;
1625 		}
1626 	    }
1627 	}
1628     } else {
1629 	if ((obj = dlcheck(handle)) == NULL) {
1630 	    rlock_release();
1631 	    return NULL;
1632 	}
1633 
1634 	if (obj->mainprog) {
1635 	    DoneList donelist;
1636 
1637 	    /* Search main program and all libraries loaded by it. */
1638 	    donelist_init(&donelist);
1639 	    def = symlook_list(name, hash, &list_main, &defobj, true,
1640 	      &donelist);
1641 	} else {
1642 	    /*
1643 	     * XXX - This isn't correct.  The search should include the whole
1644 	     * DAG rooted at the given object.
1645 	     */
1646 	    def = symlook_obj(name, hash, obj, true);
1647 	    defobj = obj;
1648 	}
1649     }
1650 
1651     if (def != NULL) {
1652 	rlock_release();
1653 	return defobj->relocbase + def->st_value;
1654     }
1655 
1656     _rtld_error("Undefined symbol \"%s\"", name);
1657     rlock_release();
1658     return NULL;
1659 }
1660 
1661 int
1662 dladdr(const void *addr, Dl_info *info)
1663 {
1664     const Obj_Entry *obj;
1665     const Elf_Sym *def;
1666     void *symbol_addr;
1667     unsigned long symoffset;
1668 
1669     rlock_acquire();
1670     obj = obj_from_addr(addr);
1671     if (obj == NULL) {
1672         _rtld_error("No shared object contains address");
1673 	rlock_release();
1674         return 0;
1675     }
1676     info->dli_fname = obj->path;
1677     info->dli_fbase = obj->mapbase;
1678     info->dli_saddr = (void *)0;
1679     info->dli_sname = NULL;
1680 
1681     /*
1682      * Walk the symbol list looking for the symbol whose address is
1683      * closest to the address sent in.
1684      */
1685     for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1686         def = obj->symtab + symoffset;
1687 
1688         /*
1689          * For skip the symbol if st_shndx is either SHN_UNDEF or
1690          * SHN_COMMON.
1691          */
1692         if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1693             continue;
1694 
1695         /*
1696          * If the symbol is greater than the specified address, or if it
1697          * is further away from addr than the current nearest symbol,
1698          * then reject it.
1699          */
1700         symbol_addr = obj->relocbase + def->st_value;
1701         if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1702             continue;
1703 
1704         /* Update our idea of the nearest symbol. */
1705         info->dli_sname = obj->strtab + def->st_name;
1706         info->dli_saddr = symbol_addr;
1707 
1708         /* Exact match? */
1709         if (info->dli_saddr == addr)
1710             break;
1711     }
1712     rlock_release();
1713     return 1;
1714 }
1715 
1716 static void
1717 linkmap_add(Obj_Entry *obj)
1718 {
1719     struct link_map *l = &obj->linkmap;
1720     struct link_map *prev;
1721 
1722     obj->linkmap.l_name = obj->path;
1723     obj->linkmap.l_addr = obj->mapbase;
1724     obj->linkmap.l_ld = obj->dynamic;
1725 #ifdef __mips__
1726     /* GDB needs load offset on MIPS to use the symbols */
1727     obj->linkmap.l_offs = obj->relocbase;
1728 #endif
1729 
1730     if (r_debug.r_map == NULL) {
1731 	r_debug.r_map = l;
1732 	return;
1733     }
1734 
1735     /*
1736      * Scan to the end of the list, but not past the entry for the
1737      * dynamic linker, which we want to keep at the very end.
1738      */
1739     for (prev = r_debug.r_map;
1740       prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
1741       prev = prev->l_next)
1742 	;
1743 
1744     /* Link in the new entry. */
1745     l->l_prev = prev;
1746     l->l_next = prev->l_next;
1747     if (l->l_next != NULL)
1748 	l->l_next->l_prev = l;
1749     prev->l_next = l;
1750 }
1751 
1752 static void
1753 linkmap_delete(Obj_Entry *obj)
1754 {
1755     struct link_map *l = &obj->linkmap;
1756 
1757     if (l->l_prev == NULL) {
1758 	if ((r_debug.r_map = l->l_next) != NULL)
1759 	    l->l_next->l_prev = NULL;
1760 	return;
1761     }
1762 
1763     if ((l->l_prev->l_next = l->l_next) != NULL)
1764 	l->l_next->l_prev = l->l_prev;
1765 }
1766 
1767 /*
1768  * Function for the debugger to set a breakpoint on to gain control.
1769  */
1770 void
1771 r_debug_state(void)
1772 {
1773 }
1774 
1775 /*
1776  * Set a pointer variable in the main program to the given value.  This
1777  * is used to set key variables such as "environ" before any of the
1778  * init functions are called.
1779  */
1780 static void
1781 set_program_var(const char *name, const void *value)
1782 {
1783     const Obj_Entry *obj;
1784     unsigned long hash;
1785 
1786     hash = elf_hash(name);
1787     for (obj = obj_main;  obj != NULL;  obj = obj->next) {
1788 	const Elf_Sym *def;
1789 
1790 	if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
1791 	    const void **addr;
1792 
1793 	    addr = (const void **)(obj->relocbase + def->st_value);
1794 	    dbg("\"%s\": *%p <-- %p", name, addr, value);
1795 	    *addr = value;
1796 	    break;
1797 	}
1798     }
1799 }
1800 
1801 static const Elf_Sym *
1802 symlook_list(const char *name, unsigned long hash, Objlist *objlist,
1803   const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
1804 {
1805     const Elf_Sym *symp;
1806     const Elf_Sym *def;
1807     const Obj_Entry *defobj;
1808     const Objlist_Entry *elm;
1809 
1810     def = NULL;
1811     defobj = NULL;
1812     STAILQ_FOREACH(elm, objlist, link) {
1813 	if (donelist_check(dlp, elm->obj))
1814 	    continue;
1815 	if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
1816 	    if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
1817 		def = symp;
1818 		defobj = elm->obj;
1819 		if (ELF_ST_BIND(def->st_info) != STB_WEAK)
1820 		    break;
1821 	    }
1822 	}
1823     }
1824     if (def != NULL)
1825 	*defobj_out = defobj;
1826     return def;
1827 }
1828 
1829 /*
1830  * Search the symbol table of a single shared object for a symbol of
1831  * the given name.  Returns a pointer to the symbol, or NULL if no
1832  * definition was found.
1833  *
1834  * The symbol's hash value is passed in for efficiency reasons; that
1835  * eliminates many recomputations of the hash value.
1836  */
1837 const Elf_Sym *
1838 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
1839   bool in_plt)
1840 {
1841     if (obj->buckets != NULL) {
1842 	unsigned long symnum = obj->buckets[hash % obj->nbuckets];
1843 
1844 	while (symnum != STN_UNDEF) {
1845 	    const Elf_Sym *symp;
1846 	    const char *strp;
1847 
1848 	    if (symnum >= obj->nchains)
1849 		return NULL;	/* Bad object */
1850 	    symp = obj->symtab + symnum;
1851 	    strp = obj->strtab + symp->st_name;
1852 
1853 	    if (strcmp(name, strp) == 0)
1854 		return symp->st_shndx != SHN_UNDEF ||
1855 		  (!in_plt && symp->st_value != 0 &&
1856 		  ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
1857 
1858 	    symnum = obj->chains[symnum];
1859 	}
1860     }
1861     return NULL;
1862 }
1863 
1864 static void
1865 trace_loaded_objects(Obj_Entry *obj)
1866 {
1867     char	*fmt1, *fmt2, *fmt, *main_local;
1868     int		c;
1869 
1870     if ((main_local = getenv("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
1871 	main_local = "";
1872 
1873     if ((fmt1 = getenv("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
1874 	fmt1 = "\t%o => %p (%x)\n";
1875 
1876     if ((fmt2 = getenv("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
1877 	fmt2 = "\t%o (%x)\n";
1878 
1879     for (; obj; obj = obj->next) {
1880 	Needed_Entry		*needed;
1881 	char			*name, *path;
1882 	bool			is_lib;
1883 
1884 	for (needed = obj->needed; needed; needed = needed->next) {
1885 	    if (needed->obj != NULL) {
1886 		if (needed->obj->traced)
1887 		    continue;
1888 		needed->obj->traced = true;
1889 		path = needed->obj->path;
1890 	    } else
1891 		path = "not found";
1892 
1893 	    name = (char *)obj->strtab + needed->name;
1894 	    is_lib = strncmp(name, "lib", 3) == 0;	/* XXX - bogus */
1895 
1896 	    fmt = is_lib ? fmt1 : fmt2;
1897 	    while ((c = *fmt++) != '\0') {
1898 		switch (c) {
1899 		default:
1900 		    putchar(c);
1901 		    continue;
1902 		case '\\':
1903 		    switch (c = *fmt) {
1904 		    case '\0':
1905 			continue;
1906 		    case 'n':
1907 			putchar('\n');
1908 			break;
1909 		    case 't':
1910 			putchar('\t');
1911 			break;
1912 		    }
1913 		    break;
1914 		case '%':
1915 		    switch (c = *fmt) {
1916 		    case '\0':
1917 			continue;
1918 		    case '%':
1919 		    default:
1920 			putchar(c);
1921 			break;
1922 		    case 'A':
1923 			printf("%s", main_local);
1924 			break;
1925 		    case 'a':
1926 			printf("%s", obj_main->path);
1927 			break;
1928 		    case 'o':
1929 			printf("%s", name);
1930 			break;
1931 #if 0
1932 		    case 'm':
1933 			printf("%d", sodp->sod_major);
1934 			break;
1935 		    case 'n':
1936 			printf("%d", sodp->sod_minor);
1937 			break;
1938 #endif
1939 		    case 'p':
1940 			printf("%s", path);
1941 			break;
1942 		    case 'x':
1943 			printf("%p", needed->obj ? needed->obj->mapbase : 0);
1944 			break;
1945 		    }
1946 		    break;
1947 		}
1948 		++fmt;
1949 	    }
1950 	}
1951     }
1952 }
1953 
1954 /*
1955  * Unload a dlopened object and its dependencies from memory and from
1956  * our data structures.  It is assumed that the DAG rooted in the
1957  * object has already been unreferenced, and that the object has a
1958  * reference count of 0.
1959  */
1960 static void
1961 unload_object(Obj_Entry *root)
1962 {
1963     Obj_Entry *obj;
1964     Obj_Entry **linkp;
1965     Objlist_Entry *elm;
1966 
1967     assert(root->refcount == 0);
1968 
1969     /* Remove the DAG from all objects' DAG lists. */
1970     STAILQ_FOREACH(elm, &root->dagmembers , link)
1971 	objlist_remove(&elm->obj->dldags, root);
1972 
1973     /* Remove the DAG from the RTLD_GLOBAL list. */
1974     objlist_remove(&list_global, root);
1975 
1976     /* Unmap all objects that are no longer referenced. */
1977     linkp = &obj_list->next;
1978     while ((obj = *linkp) != NULL) {
1979 	if (obj->refcount == 0) {
1980 	    dbg("unloading \"%s\"", obj->path);
1981 	    munmap(obj->mapbase, obj->mapsize);
1982 	    linkmap_delete(obj);
1983 	    *linkp = obj->next;
1984 	    obj_count--;
1985 	    obj_free(obj);
1986 	} else
1987 	    linkp = &obj->next;
1988     }
1989     obj_tail = linkp;
1990 }
1991 
1992 static void
1993 unref_dag(Obj_Entry *root)
1994 {
1995     const Needed_Entry *needed;
1996 
1997     assert(root->refcount != 0);
1998     root->refcount--;
1999     if (root->refcount == 0)
2000 	for (needed = root->needed;  needed != NULL;  needed = needed->next)
2001 	    if (needed->obj != NULL)
2002 		unref_dag(needed->obj);
2003 }
2004 
2005 /*
2006  * Non-mallocing printf, for use by malloc itself.
2007  * XXX - This doesn't belong in this module.
2008  */
2009 void
2010 xprintf(const char *fmt, ...)
2011 {
2012     char buf[256];
2013     va_list ap;
2014 
2015     va_start(ap, fmt);
2016     vsprintf(buf, fmt, ap);
2017     (void)write(1, buf, strlen(buf));
2018     va_end(ap);
2019 }
2020