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