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