rtld.c revision 1.140 1 /* $NetBSD: rtld.c,v 1.140 2011/03/13 21:08:45 joerg Exp $ */
2
3 /*
4 * Copyright 1996 John D. Polstra.
5 * Copyright 1996 Matt Thomas <matt (at) 3am-software.com>
6 * Copyright 2002 Charles M. Hannum <root (at) ihack.net>
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by John Polstra.
20 * 4. The name of the author may not be used to endorse or promote products
21 * derived from this software without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 */
34
35 /*
36 * Dynamic linker for ELF.
37 *
38 * John Polstra <jdp (at) polstra.com>.
39 */
40
41 #include <sys/cdefs.h>
42 #ifndef lint
43 __RCSID("$NetBSD: rtld.c,v 1.140 2011/03/13 21:08:45 joerg Exp $");
44 #endif /* not lint */
45
46 #include <err.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <stdarg.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 #include <sys/param.h>
55 #include <sys/mman.h>
56 #include <dirent.h>
57
58 #include <ctype.h>
59
60 #include <dlfcn.h>
61 #include "debug.h"
62 #include "rtld.h"
63
64 #if !defined(lint)
65 #include "sysident.h"
66 #endif
67
68 /*
69 * Function declarations.
70 */
71 static void _rtld_init(caddr_t, caddr_t, const char *);
72 static void _rtld_exit(void);
73
74 Elf_Addr _rtld(Elf_Addr *, Elf_Addr);
75
76
77 /*
78 * Data declarations.
79 */
80 static char *error_message; /* Message for dlopen(), or NULL */
81
82 struct r_debug _rtld_debug; /* for GDB; */
83 bool _rtld_trust; /* False for setuid and setgid programs */
84 Obj_Entry *_rtld_objlist; /* Head of linked list of shared objects */
85 Obj_Entry **_rtld_objtail; /* Link field of last object in list */
86 Obj_Entry *_rtld_objmain; /* The main program shared object */
87 Obj_Entry _rtld_objself; /* The dynamic linker shared object */
88 u_int _rtld_objcount; /* Number of objects in _rtld_objlist */
89 u_int _rtld_objloads; /* Number of objects loaded in _rtld_objlist */
90 const char _rtld_path[] = _PATH_RTLD;
91
92 /* Initialize a fake symbol for resolving undefined weak references. */
93 Elf_Sym _rtld_sym_zero = {
94 .st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE),
95 .st_shndx = SHN_ABS,
96 };
97 size_t _rtld_pagesz; /* Page size, as provided by kernel */
98
99 Search_Path *_rtld_default_paths;
100 Search_Path *_rtld_paths;
101
102 Library_Xform *_rtld_xforms;
103
104 /*
105 * Global declarations normally provided by crt0.
106 */
107 char *__progname;
108 char **environ;
109
110 #if defined(RTLD_DEBUG)
111 #ifndef __sh__
112 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
113 #else /* 32-bit SuperH */
114 register Elf_Addr *_GLOBAL_OFFSET_TABLE_ asm("r12");
115 #endif
116 #endif /* RTLD_DEBUG */
117 extern Elf_Dyn _DYNAMIC;
118
119 static void _rtld_call_fini_functions(int);
120 static void _rtld_call_init_functions(void);
121 static void _rtld_initlist_visit(Objlist *, Obj_Entry *, int);
122 static void _rtld_initlist_tsort(Objlist *, int);
123 static Obj_Entry *_rtld_dlcheck(void *);
124 static void _rtld_init_dag(Obj_Entry *);
125 static void _rtld_init_dag1(Obj_Entry *, Obj_Entry *);
126 static void _rtld_objlist_remove(Objlist *, Obj_Entry *);
127 static void _rtld_objlist_clear(Objlist *);
128 static void _rtld_unload_object(Obj_Entry *, bool);
129 static void _rtld_unref_dag(Obj_Entry *);
130 static Obj_Entry *_rtld_obj_from_addr(const void *);
131
132 static void
133 _rtld_call_fini_functions(int force)
134 {
135 Objlist_Entry *elm;
136 Objlist finilist;
137 Obj_Entry *obj;
138
139 dbg(("_rtld_call_fini_functions(%d)", force));
140
141 SIMPLEQ_INIT(&finilist);
142 _rtld_initlist_tsort(&finilist, 1);
143
144 /* First pass: objects _not_ marked with DF_1_INITFIRST. */
145 SIMPLEQ_FOREACH(elm, &finilist, link) {
146 obj = elm->obj;
147 if (obj->refcount > 0 && !force) {
148 continue;
149 }
150 if (obj->fini == NULL || obj->fini_called || obj->z_initfirst) {
151 continue;
152 }
153 dbg (("calling fini function %s at %p", obj->path,
154 (void *)obj->fini));
155 obj->fini_called = 1;
156 (*obj->fini)();
157 }
158
159 /* Second pass: objects marked with DF_1_INITFIRST. */
160 SIMPLEQ_FOREACH(elm, &finilist, link) {
161 obj = elm->obj;
162 if (obj->refcount > 0 && !force) {
163 continue;
164 }
165 if (obj->fini == NULL || obj->fini_called) {
166 continue;
167 }
168 dbg (("calling fini function %s at %p (DF_1_INITFIRST)",
169 obj->path, (void *)obj->fini));
170 obj->fini_called = 1;
171 (*obj->fini)();
172 }
173
174 _rtld_objlist_clear(&finilist);
175 }
176
177 static void
178 _rtld_call_init_functions()
179 {
180 Objlist_Entry *elm;
181 Objlist initlist;
182 Obj_Entry *obj;
183
184 dbg(("_rtld_call_init_functions()"));
185 SIMPLEQ_INIT(&initlist);
186 _rtld_initlist_tsort(&initlist, 0);
187
188 /* First pass: objects marked with DF_1_INITFIRST. */
189 SIMPLEQ_FOREACH(elm, &initlist, link) {
190 obj = elm->obj;
191 if (obj->init == NULL || obj->init_called || !obj->z_initfirst) {
192 continue;
193 }
194 dbg (("calling init function %s at %p (DF_1_INITFIRST)",
195 obj->path, (void *)obj->init));
196 obj->init_called = 1;
197 (*obj->init)();
198 }
199
200 /* Second pass: all other objects. */
201 SIMPLEQ_FOREACH(elm, &initlist, link) {
202 obj = elm->obj;
203 if (obj->init == NULL || obj->init_called) {
204 continue;
205 }
206 dbg (("calling init function %s at %p", obj->path,
207 (void *)obj->init));
208 obj->init_called = 1;
209 (*obj->init)();
210 }
211
212 _rtld_objlist_clear(&initlist);
213 }
214
215 /*
216 * Initialize the dynamic linker. The argument is the address at which
217 * the dynamic linker has been mapped into memory. The primary task of
218 * this function is to create an Obj_Entry for the dynamic linker and
219 * to resolve the PLT relocation for platforms that need it (those that
220 * define __HAVE_FUNCTION_DESCRIPTORS
221 */
222 static void
223 _rtld_init(caddr_t mapbase, caddr_t relocbase, const char *execname)
224 {
225
226 /* Conjure up an Obj_Entry structure for the dynamic linker. */
227 _rtld_objself.path = __UNCONST(_rtld_path);
228 _rtld_objself.pathlen = sizeof(_rtld_path)-1;
229 _rtld_objself.rtld = true;
230 _rtld_objself.mapbase = mapbase;
231 _rtld_objself.relocbase = relocbase;
232 _rtld_objself.dynamic = (Elf_Dyn *) &_DYNAMIC;
233 _rtld_objself.strtab = "_rtld_sym_zero";
234
235 /*
236 * Set value to -relocbase so that
237 *
238 * _rtld_objself.relocbase + _rtld_sym_zero.st_value == 0
239 *
240 * This allows unresolved references to weak symbols to be computed
241 * to a value of 0.
242 */
243 _rtld_sym_zero.st_value = -(uintptr_t)relocbase;
244
245 _rtld_digest_dynamic(_rtld_path, &_rtld_objself);
246 assert(!_rtld_objself.needed);
247 #if !defined(__hppa__)
248 assert(!_rtld_objself.pltrel && !_rtld_objself.pltrela);
249 #else
250 _rtld_relocate_plt_objects(&_rtld_objself);
251 #endif
252 #if !defined(__mips__) && !defined(__hppa__)
253 assert(!_rtld_objself.pltgot);
254 #endif
255 #if !defined(__arm__) && !defined(__mips__) && !defined(__sh__)
256 /* ARM, MIPS and SH{3,5} have a bogus DT_TEXTREL. */
257 assert(!_rtld_objself.textrel);
258 #endif
259
260 _rtld_add_paths(execname, &_rtld_default_paths,
261 RTLD_DEFAULT_LIBRARY_PATH);
262
263 #ifdef RTLD_ARCH_SUBDIR
264 _rtld_add_paths(execname, &_rtld_default_paths,
265 RTLD_DEFAULT_LIBRARY_PATH "/" RTLD_ARCH_SUBDIR);
266 #endif
267
268 /*
269 * Set up the _rtld_objlist pointer, so that rtld symbols can be found.
270 */
271 _rtld_objlist = &_rtld_objself;
272
273 /* Make the object list empty again. */
274 _rtld_objlist = NULL;
275 _rtld_objtail = &_rtld_objlist;
276 _rtld_objcount = 0;
277
278 _rtld_debug.r_brk = _rtld_debug_state;
279 _rtld_debug.r_state = RT_CONSISTENT;
280 }
281
282 /*
283 * Cleanup procedure. It will be called (by the atexit() mechanism) just
284 * before the process exits.
285 */
286 static void
287 _rtld_exit(void)
288 {
289 dbg(("rtld_exit()"));
290
291 _rtld_call_fini_functions(1);
292 }
293
294 /*
295 * Main entry point for dynamic linking. The argument is the stack
296 * pointer. The stack is expected to be laid out as described in the
297 * SVR4 ABI specification, Intel 386 Processor Supplement. Specifically,
298 * the stack pointer points to a word containing ARGC. Following that
299 * in the stack is a null-terminated sequence of pointers to argument
300 * strings. Then comes a null-terminated sequence of pointers to
301 * environment strings. Finally, there is a sequence of "auxiliary
302 * vector" entries.
303 *
304 * This function returns the entry point for the main program, the dynamic
305 * linker's exit procedure in sp[0], and a pointer to the main object in
306 * sp[1].
307 */
308 Elf_Addr
309 _rtld(Elf_Addr *sp, Elf_Addr relocbase)
310 {
311 const AuxInfo *pAUX_base, *pAUX_entry, *pAUX_execfd, *pAUX_phdr,
312 *pAUX_phent, *pAUX_phnum, *pAUX_euid, *pAUX_egid,
313 *pAUX_ruid, *pAUX_rgid;
314 const AuxInfo *pAUX_pagesz;
315 char **env, **oenvp;
316 const AuxInfo *aux;
317 const AuxInfo *auxp;
318 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
319 Obj_Entry *obj;
320 #endif
321 Elf_Addr *const osp = sp;
322 bool bind_now = 0;
323 const char *ld_bind_now, *ld_preload, *ld_library_path;
324 const char **argv;
325 const char *execname;
326 long argc;
327 const char **real___progname;
328 const Obj_Entry **real___mainprog_obj;
329 char ***real_environ;
330 #ifdef DEBUG
331 const char *ld_debug;
332 #endif
333 #ifdef RTLD_DEBUG
334 int i = 0;
335 #endif
336
337 /*
338 * On entry, the dynamic linker itself has not been relocated yet.
339 * Be very careful not to reference any global data until after
340 * _rtld_init has returned. It is OK to reference file-scope statics
341 * and string constants, and to call static and global functions.
342 */
343 /* Find the auxiliary vector on the stack. */
344 /* first Elf_Word reserved to address of exit routine */
345 #if defined(RTLD_DEBUG)
346 debug = 1;
347 dbg(("sp = %p, argc = %ld, argv = %p <%s> relocbase %p", sp,
348 (long)sp[2], &sp[3], (char *) sp[3], (void *)relocbase));
349 dbg(("got is at %p, dynamic is at %p", _GLOBAL_OFFSET_TABLE_,
350 &_DYNAMIC));
351 dbg(("_ctype_ is %p", _ctype_));
352 #endif
353
354 sp += 2; /* skip over return argument space */
355 argv = (const char **) &sp[1];
356 argc = *(long *)sp;
357 sp += 2 + argc; /* Skip over argc, arguments, and NULL
358 * terminator */
359 env = (char **) sp;
360 while (*sp++ != 0) { /* Skip over environment, and NULL terminator */
361 #if defined(RTLD_DEBUG)
362 dbg(("env[%d] = %p %s", i++, (void *)sp[-1], (char *)sp[-1]));
363 #endif
364 }
365 aux = (const AuxInfo *) sp;
366
367 pAUX_base = pAUX_entry = pAUX_execfd = NULL;
368 pAUX_phdr = pAUX_phent = pAUX_phnum = NULL;
369 pAUX_euid = pAUX_ruid = pAUX_egid = pAUX_rgid = NULL;
370 pAUX_pagesz = NULL;
371
372 execname = NULL;
373
374 /* Digest the auxiliary vector. */
375 for (auxp = aux; auxp->a_type != AT_NULL; ++auxp) {
376 switch (auxp->a_type) {
377 case AT_BASE:
378 pAUX_base = auxp;
379 break;
380 case AT_ENTRY:
381 pAUX_entry = auxp;
382 break;
383 case AT_EXECFD:
384 pAUX_execfd = auxp;
385 break;
386 case AT_PHDR:
387 pAUX_phdr = auxp;
388 break;
389 case AT_PHENT:
390 pAUX_phent = auxp;
391 break;
392 case AT_PHNUM:
393 pAUX_phnum = auxp;
394 break;
395 #ifdef AT_EUID
396 case AT_EUID:
397 pAUX_euid = auxp;
398 break;
399 case AT_RUID:
400 pAUX_ruid = auxp;
401 break;
402 case AT_EGID:
403 pAUX_egid = auxp;
404 break;
405 case AT_RGID:
406 pAUX_rgid = auxp;
407 break;
408 #endif
409 #ifdef AT_SUN_EXECNAME
410 case AT_SUN_EXECNAME:
411 execname = (const char *)(const void *)auxp->a_v;
412 break;
413 #endif
414 case AT_PAGESZ:
415 pAUX_pagesz = auxp;
416 break;
417 }
418 }
419
420 /* Initialize and relocate ourselves. */
421 if (pAUX_base == NULL) {
422 _rtld_error("Bad pAUX_base");
423 _rtld_die();
424 }
425 assert(pAUX_pagesz != NULL);
426 _rtld_pagesz = (int)pAUX_pagesz->a_v;
427 _rtld_init((caddr_t)pAUX_base->a_v, (caddr_t)relocbase, execname);
428
429 __progname = _rtld_objself.path;
430 environ = env;
431
432 _rtld_trust = ((pAUX_euid ? (uid_t)pAUX_euid->a_v : geteuid()) ==
433 (pAUX_ruid ? (uid_t)pAUX_ruid->a_v : getuid())) &&
434 ((pAUX_egid ? (gid_t)pAUX_egid->a_v : getegid()) ==
435 (pAUX_rgid ? (gid_t)pAUX_rgid->a_v : getgid()));
436
437 #ifdef DEBUG
438 ld_debug = NULL;
439 #endif
440 ld_bind_now = NULL;
441 ld_library_path = NULL;
442 ld_preload = NULL;
443 /*
444 * Inline avoid using normal getenv/unsetenv here as the libc
445 * code is quite a bit more complicated.
446 */
447 for (oenvp = env; *env != NULL; ++env) {
448 static const char bind_var[] = "LD_BIND_NOW=";
449 static const char debug_var[] = "LD_DEBUG=";
450 static const char path_var[] = "LD_LIBRARY_PATH=";
451 static const char preload_var[] = "LD_PRELOAD=";
452 #define LEN(x) (sizeof(x) - 1)
453
454 if ((*env)[0] != 'L' || (*env)[1] != 'D') {
455 /*
456 * Special case to skip most entries without
457 * the more expensive calls to strncmp.
458 */
459 *oenvp++ = *env;
460 } else if (strncmp(*env, debug_var, LEN(debug_var)) == 0) {
461 if (_rtld_trust) {
462 #ifdef DEBUG
463 ld_debug = *env + LEN(debug_var);
464 #endif
465 *oenvp++ = *env;
466 }
467 } else if (strncmp(*env, bind_var, LEN(bind_var)) == 0) {
468 ld_bind_now = *env + LEN(bind_var);
469 } else if (strncmp(*env, path_var, LEN(path_var)) == 0) {
470 if (_rtld_trust) {
471 ld_library_path = *env + LEN(path_var);
472 *oenvp++ = *env;
473 }
474 } else if (strncmp(*env, preload_var, LEN(preload_var)) == 0) {
475 if (_rtld_trust) {
476 ld_preload = *env + LEN(preload_var);
477 *oenvp++ = *env;
478 }
479 } else {
480 *oenvp++ = *env;
481 }
482 #undef LEN
483 }
484 *oenvp++ = NULL;
485
486 if (ld_bind_now != NULL && *ld_bind_now != '\0')
487 bind_now = true;
488 if (_rtld_trust) {
489 #ifdef DEBUG
490 #ifdef RTLD_DEBUG
491 debug = 0;
492 #endif
493 if (ld_debug != NULL && *ld_debug != '\0')
494 debug = 1;
495 #endif
496 _rtld_add_paths(execname, &_rtld_paths, ld_library_path);
497 } else {
498 execname = NULL;
499 }
500 _rtld_process_hints(execname, &_rtld_paths, &_rtld_xforms,
501 _PATH_LD_HINTS);
502 dbg(("dynamic linker is initialized, mapbase=%p, relocbase=%p",
503 _rtld_objself.mapbase, _rtld_objself.relocbase));
504
505 /*
506 * Load the main program, or process its program header if it is
507 * already loaded.
508 */
509 if (pAUX_execfd != NULL) { /* Load the main program. */
510 int fd = pAUX_execfd->a_v;
511 const char *obj_name = argv[0] ? argv[0] : "main program";
512 dbg(("loading main program"));
513 _rtld_objmain = _rtld_map_object(obj_name, fd, NULL);
514 close(fd);
515 if (_rtld_objmain == NULL)
516 _rtld_die();
517 } else { /* Main program already loaded. */
518 const Elf_Phdr *phdr;
519 int phnum;
520 caddr_t entry;
521
522 dbg(("processing main program's program header"));
523 assert(pAUX_phdr != NULL);
524 phdr = (const Elf_Phdr *) pAUX_phdr->a_v;
525 assert(pAUX_phnum != NULL);
526 phnum = pAUX_phnum->a_v;
527 assert(pAUX_phent != NULL);
528 assert(pAUX_phent->a_v == sizeof(Elf_Phdr));
529 assert(pAUX_entry != NULL);
530 entry = (caddr_t) pAUX_entry->a_v;
531 _rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
532 _rtld_objmain->path = xstrdup(argv[0] ? argv[0] :
533 "main program");
534 _rtld_objmain->pathlen = strlen(_rtld_objmain->path);
535 }
536
537 _rtld_objmain->mainprog = true;
538
539 /*
540 * Get the actual dynamic linker pathname from the executable if
541 * possible. (It should always be possible.) That ensures that
542 * gdb will find the right dynamic linker even if a non-standard
543 * one is being used.
544 */
545 if (_rtld_objmain->interp != NULL &&
546 strcmp(_rtld_objmain->interp, _rtld_objself.path) != 0)
547 _rtld_objself.path = xstrdup(_rtld_objmain->interp);
548 dbg(("actual dynamic linker is %s", _rtld_objself.path));
549
550 _rtld_digest_dynamic(execname, _rtld_objmain);
551
552 /* Link the main program into the list of objects. */
553 *_rtld_objtail = _rtld_objmain;
554 _rtld_objtail = &_rtld_objmain->next;
555 _rtld_objcount++;
556 _rtld_objloads++;
557
558 _rtld_linkmap_add(_rtld_objmain);
559 _rtld_linkmap_add(&_rtld_objself);
560
561 ++_rtld_objmain->refcount;
562 _rtld_objmain->mainref = 1;
563 _rtld_objlist_push_tail(&_rtld_list_main, _rtld_objmain);
564
565 if (ld_preload) {
566 /*
567 * Pre-load user-specified objects after the main program
568 * but before any shared object dependencies.
569 */
570 dbg(("preloading objects"));
571 if (_rtld_preload(ld_preload) == -1)
572 _rtld_die();
573 }
574
575 dbg(("loading needed objects"));
576 if (_rtld_load_needed_objects(_rtld_objmain, _RTLD_MAIN) == -1)
577 _rtld_die();
578
579 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
580 dbg(("initializing initial Thread Local Storage"));
581 /*
582 * All initial objects get the TLS space from the static block.
583 */
584 for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
585 _rtld_tls_offset_allocate(obj);
586 _rtld_tls_initial_allocation();
587 #endif
588
589 dbg(("relocating objects"));
590 if (_rtld_relocate_objects(_rtld_objmain, bind_now) == -1)
591 _rtld_die();
592
593 dbg(("doing copy relocations"));
594 if (_rtld_do_copy_relocations(_rtld_objmain) == -1)
595 _rtld_die();
596
597 /*
598 * Set the __progname, environ and, __mainprog_obj before
599 * calling anything that might use them.
600 */
601 real___progname = _rtld_objmain_sym("__progname");
602 if (real___progname) {
603 if (argv[0] != NULL) {
604 if ((*real___progname = strrchr(argv[0], '/')) == NULL)
605 (*real___progname) = argv[0];
606 else
607 (*real___progname)++;
608 } else {
609 (*real___progname) = NULL;
610 }
611 }
612 real_environ = _rtld_objmain_sym("environ");
613 if (real_environ)
614 *real_environ = environ;
615 /*
616 * Set __mainprog_obj for old binaries.
617 */
618 real___mainprog_obj = _rtld_objmain_sym("__mainprog_obj");
619 if (real___mainprog_obj)
620 *real___mainprog_obj = _rtld_objmain;
621
622 dbg(("calling _init functions"));
623 _rtld_call_init_functions();
624
625 dbg(("control at program entry point = %p, obj = %p, exit = %p",
626 _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
627
628 /*
629 * Return with the entry point and the exit procedure in at the top
630 * of stack.
631 */
632
633 _rtld_debug_state(); /* say hello to gdb! */
634
635 ((void **) osp)[0] = _rtld_exit;
636 ((void **) osp)[1] = _rtld_objmain;
637 return (Elf_Addr) _rtld_objmain->entry;
638 }
639
640 void
641 _rtld_die(void)
642 {
643 const char *msg = dlerror();
644
645 if (msg == NULL)
646 msg = "Fatal error";
647 xerrx(1, "%s", msg);
648 }
649
650 static Obj_Entry *
651 _rtld_dlcheck(void *handle)
652 {
653 Obj_Entry *obj;
654
655 for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
656 if (obj == (Obj_Entry *) handle)
657 break;
658
659 if (obj == NULL || obj->dl_refcount == 0) {
660 xwarnx("Invalid shared object handle %p", handle);
661 return NULL;
662 }
663 return obj;
664 }
665
666 static void
667 _rtld_initlist_visit(Objlist* list, Obj_Entry *obj, int rev)
668 {
669 Needed_Entry* elm;
670
671 /* dbg(("_rtld_initlist_visit(%s)", obj->path)); */
672
673 if (obj->init_done)
674 return;
675 obj->init_done = 1;
676
677 for (elm = obj->needed; elm != NULL; elm = elm->next) {
678 if (elm->obj != NULL) {
679 _rtld_initlist_visit(list, elm->obj, rev);
680 }
681 }
682
683 if (rev) {
684 _rtld_objlist_push_head(list, obj);
685 } else {
686 _rtld_objlist_push_tail(list, obj);
687 }
688 }
689
690 static void
691 _rtld_initlist_tsort(Objlist* list, int rev)
692 {
693 dbg(("_rtld_initlist_tsort"));
694
695 Obj_Entry* obj;
696
697 for (obj = _rtld_objlist->next; obj; obj = obj->next) {
698 obj->init_done = 0;
699 }
700
701 for (obj = _rtld_objlist->next; obj; obj = obj->next) {
702 _rtld_initlist_visit(list, obj, rev);
703 }
704 }
705
706 static void
707 _rtld_init_dag(Obj_Entry *root)
708 {
709
710 _rtld_init_dag1(root, root);
711 }
712
713 static void
714 _rtld_init_dag1(Obj_Entry *root, Obj_Entry *obj)
715 {
716 const Needed_Entry *needed;
717
718 if (!obj->mainref) {
719 if (_rtld_objlist_find(&obj->dldags, root))
720 return;
721 dbg(("add %p (%s) to %p (%s) DAG", obj, obj->path, root,
722 root->path));
723 _rtld_objlist_push_tail(&obj->dldags, root);
724 _rtld_objlist_push_tail(&root->dagmembers, obj);
725 }
726 for (needed = obj->needed; needed != NULL; needed = needed->next)
727 if (needed->obj != NULL)
728 _rtld_init_dag1(root, needed->obj);
729 }
730
731 /*
732 * Note, this is called only for objects loaded by dlopen().
733 */
734 static void
735 _rtld_unload_object(Obj_Entry *root, bool do_fini_funcs)
736 {
737
738 _rtld_unref_dag(root);
739 if (root->refcount == 0) { /* We are finished with some objects. */
740 Obj_Entry *obj;
741 Obj_Entry **linkp;
742 Objlist_Entry *elm;
743
744 /* Finalize objects that are about to be unmapped. */
745 if (do_fini_funcs)
746 _rtld_call_fini_functions(0);
747
748 /* Remove the DAG from all objects' DAG lists. */
749 SIMPLEQ_FOREACH(elm, &root->dagmembers, link)
750 _rtld_objlist_remove(&elm->obj->dldags, root);
751
752 /* Remove the DAG from the RTLD_GLOBAL list. */
753 if (root->globalref) {
754 root->globalref = 0;
755 _rtld_objlist_remove(&_rtld_list_global, root);
756 }
757
758 /* Unmap all objects that are no longer referenced. */
759 linkp = &_rtld_objlist->next;
760 while ((obj = *linkp) != NULL) {
761 if (obj->refcount == 0) {
762 dbg(("unloading \"%s\"", obj->path));
763 if (obj->ehdr != MAP_FAILED)
764 munmap(obj->ehdr, _rtld_pagesz);
765 munmap(obj->mapbase, obj->mapsize);
766 _rtld_objlist_remove(&_rtld_list_global, obj);
767 _rtld_linkmap_delete(obj);
768 *linkp = obj->next;
769 _rtld_objcount--;
770 _rtld_obj_free(obj);
771 } else
772 linkp = &obj->next;
773 }
774 _rtld_objtail = linkp;
775 }
776 }
777
778 void
779 _rtld_ref_dag(Obj_Entry *root)
780 {
781 const Needed_Entry *needed;
782
783 assert(root);
784
785 ++root->refcount;
786
787 dbg(("incremented reference on \"%s\" (%d)", root->path,
788 root->refcount));
789 for (needed = root->needed; needed != NULL;
790 needed = needed->next) {
791 if (needed->obj != NULL)
792 _rtld_ref_dag(needed->obj);
793 }
794 }
795
796 static void
797 _rtld_unref_dag(Obj_Entry *root)
798 {
799
800 assert(root);
801 assert(root->refcount != 0);
802
803 --root->refcount;
804 dbg(("decremented reference on \"%s\" (%d)", root->path,
805 root->refcount));
806
807 if (root->refcount == 0) {
808 const Needed_Entry *needed;
809
810 for (needed = root->needed; needed != NULL;
811 needed = needed->next) {
812 if (needed->obj != NULL)
813 _rtld_unref_dag(needed->obj);
814 }
815 }
816 }
817
818 __strong_alias(__dlclose,dlclose)
819 int
820 dlclose(void *handle)
821 {
822 Obj_Entry *root = _rtld_dlcheck(handle);
823
824 if (root == NULL)
825 return -1;
826
827 _rtld_debug.r_state = RT_DELETE;
828 _rtld_debug_state();
829
830 --root->dl_refcount;
831 _rtld_unload_object(root, true);
832
833 _rtld_debug.r_state = RT_CONSISTENT;
834 _rtld_debug_state();
835
836 return 0;
837 }
838
839 __strong_alias(__dlerror,dlerror)
840 char *
841 dlerror(void)
842 {
843 char *msg = error_message;
844
845 error_message = NULL;
846 return msg;
847 }
848
849 __strong_alias(__dlopen,dlopen)
850 void *
851 dlopen(const char *name, int mode)
852 {
853 Obj_Entry **old_obj_tail = _rtld_objtail;
854 Obj_Entry *obj = NULL;
855 int flags = _RTLD_DLOPEN;
856 bool nodelete;
857 bool now;
858
859 flags |= (mode & RTLD_GLOBAL) ? _RTLD_GLOBAL : 0;
860 flags |= (mode & RTLD_NOLOAD) ? _RTLD_NOLOAD : 0;
861
862 nodelete = (mode & RTLD_NODELETE) ? true : false;
863 now = ((mode & RTLD_MODEMASK) == RTLD_NOW) ? true : false;
864
865 _rtld_debug.r_state = RT_ADD;
866 _rtld_debug_state();
867
868 if (name == NULL) {
869 obj = _rtld_objmain;
870 obj->refcount++;
871 } else
872 obj = _rtld_load_library(name, _rtld_objmain, flags);
873
874
875 if (obj != NULL) {
876 ++obj->dl_refcount;
877 if (*old_obj_tail != NULL) { /* We loaded something new. */
878 assert(*old_obj_tail == obj);
879
880 if (_rtld_load_needed_objects(obj, flags) == -1 ||
881 (_rtld_init_dag(obj),
882 _rtld_relocate_objects(obj,
883 (now || obj->z_now))) == -1) {
884 _rtld_unload_object(obj, false);
885 obj->dl_refcount--;
886 obj = NULL;
887 } else {
888 _rtld_call_init_functions();
889 }
890 }
891 if (obj != NULL) {
892 if ((nodelete || obj->z_nodelete) && !obj->ref_nodel) {
893 dbg(("dlopen obj %s nodelete", obj->path));
894 _rtld_ref_dag(obj);
895 obj->z_nodelete = obj->ref_nodel = true;
896 }
897 }
898 }
899 _rtld_debug.r_state = RT_CONSISTENT;
900 _rtld_debug_state();
901
902 return obj;
903 }
904
905 /*
906 * Find a symbol in the main program.
907 */
908 void *
909 _rtld_objmain_sym(const char *name)
910 {
911 unsigned long hash;
912 const Elf_Sym *def;
913 const Obj_Entry *obj;
914 DoneList donelist;
915
916 hash = _rtld_elf_hash(name);
917 obj = _rtld_objmain;
918 _rtld_donelist_init(&donelist);
919
920 def = _rtld_symlook_list(name, hash, &_rtld_list_main, &obj, false,
921 &donelist);
922
923 if (def != NULL)
924 return obj->relocbase + def->st_value;
925 return NULL;
926 }
927
928 #ifdef __powerpc__
929 static void *
930 hackish_return_address(void)
931 {
932 return __builtin_return_address(1);
933 }
934 #endif
935
936 __strong_alias(__dlsym,dlsym)
937 void *
938 dlsym(void *handle, const char *name)
939 {
940 const Obj_Entry *obj;
941 unsigned long hash;
942 const Elf_Sym *def;
943 const Obj_Entry *defobj;
944 void *retaddr;
945 DoneList donelist;
946
947 hash = _rtld_elf_hash(name);
948 def = NULL;
949 defobj = NULL;
950
951 switch ((intptr_t)handle) {
952 case (intptr_t)NULL:
953 case (intptr_t)RTLD_NEXT:
954 case (intptr_t)RTLD_DEFAULT:
955 case (intptr_t)RTLD_SELF:
956 #ifdef __powerpc__
957 retaddr = hackish_return_address();
958 #else
959 retaddr = __builtin_return_address(0);
960 #endif
961 if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
962 _rtld_error("Cannot determine caller's shared object");
963 return NULL;
964 }
965
966 switch ((intptr_t)handle) {
967 case (intptr_t)NULL: /* Just the caller's shared object. */
968 def = _rtld_symlook_obj(name, hash, obj, false);
969 defobj = obj;
970 break;
971
972 case (intptr_t)RTLD_NEXT: /* Objects after callers */
973 obj = obj->next;
974 /*FALLTHROUGH*/
975
976 case (intptr_t)RTLD_SELF: /* Caller included */
977 for (; obj; obj = obj->next) {
978 if ((def = _rtld_symlook_obj(name, hash, obj,
979 false)) != NULL) {
980 defobj = obj;
981 break;
982 }
983 }
984 break;
985
986 case (intptr_t)RTLD_DEFAULT:
987 def = _rtld_symlook_default(name, hash, obj, &defobj,
988 false);
989 break;
990
991 default:
992 abort();
993 }
994 break;
995
996 default:
997 if ((obj = _rtld_dlcheck(handle)) == NULL)
998 return NULL;
999
1000 _rtld_donelist_init(&donelist);
1001
1002 if (obj->mainprog) {
1003 /* Search main program and all libraries loaded by it */
1004 def = _rtld_symlook_list(name, hash, &_rtld_list_main,
1005 &defobj, false, &donelist);
1006 } else {
1007 Needed_Entry fake;
1008 DoneList depth;
1009
1010 /* Search the object and all the libraries loaded by it. */
1011 fake.next = NULL;
1012 fake.obj = __UNCONST(obj);
1013 fake.name = 0;
1014
1015 _rtld_donelist_init(&depth);
1016 def = _rtld_symlook_needed(name, hash, &fake, &defobj,
1017 false, &donelist, &depth);
1018 }
1019
1020 break;
1021 }
1022
1023 if (def != NULL) {
1024 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1025 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
1026 return (void *)_rtld_function_descriptor_alloc(defobj,
1027 def, 0);
1028 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
1029 return defobj->relocbase + def->st_value;
1030 }
1031
1032 _rtld_error("Undefined symbol \"%s\"", name);
1033 return NULL;
1034 }
1035
1036 __strong_alias(__dladdr,dladdr)
1037 int
1038 dladdr(const void *addr, Dl_info *info)
1039 {
1040 const Obj_Entry *obj;
1041 const Elf_Sym *def, *best_def;
1042 void *symbol_addr;
1043 unsigned long symoffset;
1044
1045 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1046 addr = _rtld_function_descriptor_function(addr);
1047 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
1048
1049 obj = _rtld_obj_from_addr(addr);
1050 if (obj == NULL) {
1051 _rtld_error("No shared object contains address");
1052 return 0;
1053 }
1054 info->dli_fname = obj->path;
1055 info->dli_fbase = obj->mapbase;
1056 info->dli_saddr = (void *)0;
1057 info->dli_sname = NULL;
1058
1059 /*
1060 * Walk the symbol list looking for the symbol whose address is
1061 * closest to the address sent in.
1062 */
1063 best_def = NULL;
1064 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1065 def = obj->symtab + symoffset;
1066
1067 /*
1068 * For skip the symbol if st_shndx is either SHN_UNDEF or
1069 * SHN_COMMON.
1070 */
1071 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1072 continue;
1073
1074 /*
1075 * If the symbol is greater than the specified address, or if it
1076 * is further away from addr than the current nearest symbol,
1077 * then reject it.
1078 */
1079 symbol_addr = obj->relocbase + def->st_value;
1080 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1081 continue;
1082
1083 /* Update our idea of the nearest symbol. */
1084 info->dli_sname = obj->strtab + def->st_name;
1085 info->dli_saddr = symbol_addr;
1086 best_def = def;
1087
1088 /* Exact match? */
1089 if (info->dli_saddr == addr)
1090 break;
1091 }
1092
1093 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1094 if (best_def != NULL && ELF_ST_TYPE(best_def->st_info) == STT_FUNC)
1095 info->dli_saddr = (void *)_rtld_function_descriptor_alloc(obj,
1096 best_def, 0);
1097 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
1098
1099 return 1;
1100 }
1101
1102 __strong_alias(__dlinfo,dlinfo)
1103 int
1104 dlinfo(void *handle, int req, void *v)
1105 {
1106 const Obj_Entry *obj;
1107 void *retaddr;
1108
1109 if (handle == RTLD_SELF) {
1110 #ifdef __powerpc__
1111 retaddr = hackish_return_address();
1112 #else
1113 retaddr = __builtin_return_address(0);
1114 #endif
1115 if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
1116 _rtld_error("Cannot determine caller's shared object");
1117 return -1;
1118 }
1119 } else {
1120 if ((obj = _rtld_dlcheck(handle)) == NULL) {
1121 _rtld_error("Invalid handle");
1122 return -1;
1123 }
1124 }
1125
1126 switch (req) {
1127 case RTLD_DI_LINKMAP:
1128 {
1129 const struct link_map **map = v;
1130
1131 *map = &obj->linkmap;
1132 break;
1133 }
1134
1135 default:
1136 _rtld_error("Invalid request");
1137 return -1;
1138 }
1139
1140 return 0;
1141 }
1142
1143 __strong_alias(__dl_iterate_phdr,dl_iterate_phdr);
1144 int
1145 dl_iterate_phdr(int (*callback)(struct dl_phdr_info *, size_t, void *), void *param)
1146 {
1147 struct dl_phdr_info phdr_info;
1148 const Obj_Entry *obj;
1149 int error = 0;
1150
1151 for (obj = _rtld_objlist; obj != NULL; obj = obj->next) {
1152 phdr_info.dlpi_addr = (Elf_Addr)obj->relocbase;
1153 phdr_info.dlpi_name = STAILQ_FIRST(&obj->names) ?
1154 STAILQ_FIRST(&obj->names)->name : obj->path;
1155 phdr_info.dlpi_phdr = obj->phdr;
1156 phdr_info.dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
1157 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
1158 phdr_info.dlpi_tls_modid = obj->tlsindex;
1159 phdr_info.dlpi_tls_data = obj->tlsinit;
1160 #else
1161 phdr_info.dlpi_tls_modid = 0;
1162 phdr_info.dlpi_tls_data = 0;
1163 #endif
1164 phdr_info.dlpi_adds = _rtld_objloads;
1165 phdr_info.dlpi_subs = _rtld_objloads - _rtld_objcount;
1166
1167 error = callback(&phdr_info, sizeof(phdr_info), param);
1168 if (error)
1169 break;
1170 }
1171
1172 return error;
1173 }
1174
1175 /*
1176 * Error reporting function. Use it like printf. If formats the message
1177 * into a buffer, and sets things up so that the next call to dlerror()
1178 * will return the message.
1179 */
1180 void
1181 _rtld_error(const char *fmt,...)
1182 {
1183 static char buf[512];
1184 va_list ap;
1185
1186 va_start(ap, fmt);
1187 xvsnprintf(buf, sizeof buf, fmt, ap);
1188 error_message = buf;
1189 va_end(ap);
1190 }
1191
1192 void
1193 _rtld_debug_state(void)
1194 {
1195
1196 /* do nothing */
1197 }
1198
1199 void
1200 _rtld_linkmap_add(Obj_Entry *obj)
1201 {
1202 struct link_map *l = &obj->linkmap;
1203 struct link_map *prev;
1204
1205 obj->linkmap.l_name = obj->path;
1206 obj->linkmap.l_addr = obj->relocbase;
1207 obj->linkmap.l_ld = obj->dynamic;
1208 #ifdef __mips__
1209 /* XXX This field is not standard and will be removed eventually. */
1210 obj->linkmap.l_offs = obj->relocbase;
1211 #endif
1212
1213 if (_rtld_debug.r_map == NULL) {
1214 _rtld_debug.r_map = l;
1215 return;
1216 }
1217
1218 /*
1219 * Scan to the end of the list, but not past the entry for the
1220 * dynamic linker, which we want to keep at the very end.
1221 */
1222 for (prev = _rtld_debug.r_map;
1223 prev->l_next != NULL && prev->l_next != &_rtld_objself.linkmap;
1224 prev = prev->l_next);
1225
1226 l->l_prev = prev;
1227 l->l_next = prev->l_next;
1228 if (l->l_next != NULL)
1229 l->l_next->l_prev = l;
1230 prev->l_next = l;
1231 }
1232
1233 void
1234 _rtld_linkmap_delete(Obj_Entry *obj)
1235 {
1236 struct link_map *l = &obj->linkmap;
1237
1238 if (l->l_prev == NULL) {
1239 if ((_rtld_debug.r_map = l->l_next) != NULL)
1240 l->l_next->l_prev = NULL;
1241 return;
1242 }
1243 if ((l->l_prev->l_next = l->l_next) != NULL)
1244 l->l_next->l_prev = l->l_prev;
1245 }
1246
1247 static Obj_Entry *
1248 _rtld_obj_from_addr(const void *addr)
1249 {
1250 Obj_Entry *obj;
1251
1252 for (obj = _rtld_objlist; obj != NULL; obj = obj->next) {
1253 if (addr < (void *) obj->mapbase)
1254 continue;
1255 if (addr < (void *) (obj->mapbase + obj->mapsize))
1256 return obj;
1257 }
1258 return NULL;
1259 }
1260
1261 static void
1262 _rtld_objlist_clear(Objlist *list)
1263 {
1264 while (!SIMPLEQ_EMPTY(list)) {
1265 Objlist_Entry* elm = SIMPLEQ_FIRST(list);
1266 SIMPLEQ_REMOVE_HEAD(list, link);
1267 xfree(elm);
1268 }
1269 }
1270
1271 static void
1272 _rtld_objlist_remove(Objlist *list, Obj_Entry *obj)
1273 {
1274 Objlist_Entry *elm;
1275
1276 if ((elm = _rtld_objlist_find(list, obj)) != NULL) {
1277 SIMPLEQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1278 xfree(elm);
1279 }
1280 }
1281