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