rtld.c revision 1.23 1 /* $NetBSD: rtld.c,v 1.23 1999/08/19 23:42:15 christos Exp $ */
2
3 /*
4 * Copyright 1996 John D. Polstra.
5 * Copyright 1996 Matt Thomas <matt (at) 3am-software.com>
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by John Polstra.
19 * 4. The name of the author may not be used to endorse or promote products
20 * derived from this software without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 /*
35 * Dynamic linker for ELF.
36 *
37 * John Polstra <jdp (at) polstra.com>.
38 */
39
40 #include <err.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <stdarg.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 #include <sys/param.h>
49 #include <sys/mman.h>
50 #include <dirent.h>
51
52 #include <ctype.h>
53
54 #include <dlfcn.h>
55 #include "debug.h"
56 #include "rtld.h"
57
58 #if !defined(lint)
59 #include "sysident.h"
60 #endif
61
62 /*
63 * Debugging support.
64 */
65
66 typedef void (*funcptr) __P((void));
67
68 /*
69 * Function declarations.
70 */
71 static void _rtld_init __P((caddr_t));
72 static void _rtld_exit __P((void));
73
74 Elf_Addr _rtld __P((Elf_Word *));
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 char _rtld_path[] = _PATH_RTLD;
89 #ifdef VARPSZ
90 int _rtld_pagesz; /* Page size, as provided by kernel */
91 #endif
92
93 Search_Path *_rtld_default_paths;
94 Search_Path *_rtld_paths;
95 /*
96 * Global declarations normally provided by crt0.
97 */
98 char *__progname;
99 char **environ;
100
101 #ifdef OLD_GOT
102 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
103 #else
104 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
105 extern Elf_Dyn _DYNAMIC;
106 #endif
107
108 static void _rtld_call_fini_functions __P((Obj_Entry *));
109 static void _rtld_call_init_functions __P((Obj_Entry *));
110 static Obj_Entry *_rtld_dlcheck __P((void *));
111 static void _rtld_unref_object_dag __P((Obj_Entry *));
112
113 static void
114 _rtld_call_fini_functions(first)
115 Obj_Entry *first;
116 {
117 Obj_Entry *obj;
118
119 for (obj = first; obj != NULL; obj = obj->next)
120 if (obj->fini != NULL)
121 (*obj->fini)();
122 }
123
124 static void
125 _rtld_call_init_functions(first)
126 Obj_Entry *first;
127 {
128 if (first != NULL) {
129 _rtld_call_init_functions(first->next);
130 if (first->init != NULL)
131 (*first->init)();
132 }
133 }
134
135 /*
136 * Initialize the dynamic linker. The argument is the address at which
137 * the dynamic linker has been mapped into memory. The primary task of
138 * this function is to relocate the dynamic linker.
139 */
140 static void
141 _rtld_init(mapbase)
142 caddr_t mapbase;
143 {
144 Obj_Entry objself;/* The dynamic linker shared object */
145 #ifdef RTLD_RELOCATE_SELF
146 int dodebug = false;
147 #else
148 int dodebug = true;
149 #endif
150
151 memset(&objself, 0, sizeof objself);
152
153 /* Conjure up an Obj_Entry structure for the dynamic linker. */
154 objself.path = NULL;
155 objself.rtld = true;
156 objself.mapbase = mapbase;
157
158 #if defined(__mips__)
159 /*
160 * mips and ld.so currently linked at load address,
161 * so no relocation needed
162 */
163 objself.relocbase = 0;
164 #else
165 objself.relocbase = mapbase;
166 #endif
167
168 objself.pltgot = NULL;
169
170 #ifdef OLD_GOT
171 objself.dynamic = (Elf_Dyn *) _GLOBAL_OFFSET_TABLE_[0];
172 #else
173 objself.dynamic = (Elf_Dyn *) & _DYNAMIC;
174 #endif
175
176 #ifdef RTLD_RELOCATE_SELF
177 /* We have not been relocated yet, so fix the dynamic address */
178 objself.dynamic = (Elf_Dyn *)
179 ((u_long) mapbase + (char *) objself.dynamic);
180 #endif /* RTLD_RELOCATE_SELF */
181
182 _rtld_digest_dynamic(&objself);
183
184 #ifdef __alpha__
185 /* XXX XXX XXX */
186 objself.pltgot = NULL;
187 #endif
188 assert(objself.needed == NULL);
189
190 #if !defined(__mips__) && !defined(__i386__)
191 /* no relocation for mips/i386 */
192 assert(!objself.textrel);
193 #endif
194
195 _rtld_relocate_objects(&objself, true, dodebug);
196
197 /*
198 * Now that we relocated ourselves, we can use globals.
199 */
200 _rtld_objself = objself;
201
202 _rtld_objself.path = _rtld_path;
203 _rtld_add_paths(&_rtld_default_paths, RTLD_DEFAULT_LIBRARY_PATH, true);
204
205 /*
206 * Set up the _rtld_objlist pointer, so that rtld symbols can be found.
207 */
208 _rtld_objlist = &_rtld_objself;
209
210 /* Make the object list empty again. */
211 _rtld_objlist = NULL;
212 _rtld_objtail = &_rtld_objlist;
213
214 _rtld_debug.r_brk = _rtld_debug_state;
215 _rtld_debug.r_state = RT_CONSISTENT;
216 }
217
218 /*
219 * Cleanup procedure. It will be called (by the atexit() mechanism) just
220 * before the process exits.
221 */
222 static void
223 _rtld_exit()
224 {
225 dbg(("rtld_exit()"));
226
227 _rtld_call_fini_functions(_rtld_objlist->next);
228 }
229
230 /*
231 * Main entry point for dynamic linking. The argument is the stack
232 * pointer. The stack is expected to be laid out as described in the
233 * SVR4 ABI specification, Intel 386 Processor Supplement. Specifically,
234 * the stack pointer points to a word containing ARGC. Following that
235 * in the stack is a null-terminated sequence of pointers to argument
236 * strings. Then comes a null-terminated sequence of pointers to
237 * environment strings. Finally, there is a sequence of "auxiliary
238 * vector" entries.
239 *
240 * This function returns the entry point for the main program, the dynamic
241 * linker's exit procedure in sp[0], and a pointer to the main object in
242 * sp[1].
243 */
244 Elf_Addr
245 _rtld(sp)
246 Elf_Word *sp;
247 {
248 const AuxInfo *pAUX_base, *pAUX_entry, *pAUX_execfd, *pAUX_phdr,
249 *pAUX_phent, *pAUX_phnum;
250 #ifdef VARPSZ
251 const AuxInfo *pAUX_pagesz;
252 #endif
253 char **env;
254 const AuxInfo *aux;
255 const AuxInfo *auxp;
256 Elf_Word *const osp = sp;
257 bool bind_now = 0;
258 const char *ld_bind_now;
259 const char **argv;
260 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
261 int i = 0;
262 #endif
263
264 /*
265 * On entry, the dynamic linker itself has not been relocated yet.
266 * Be very careful not to reference any global data until after
267 * _rtld_init has returned. It is OK to reference file-scope statics
268 * and string constants, and to call static and global functions.
269 */
270 /* Find the auxiliary vector on the stack. */
271 /* first Elf_Word reserved to address of exit routine */
272 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
273 dbg(("sp = %p, argc = %ld, argv = %p <%s>\n", sp, (long)sp[2],
274 &sp[3], (char *) sp[3]));
275 dbg(("got is at %p, dynamic is at %p\n",
276 _GLOBAL_OFFSET_TABLE_, &_DYNAMIC));
277 debug = 1;
278 dbg(("_ctype_ is %p\n", _ctype_));
279 #endif
280
281 sp += 2; /* skip over return argument space */
282 argv = (const char **) &sp[1];
283 sp += sp[0] + 2; /* Skip over argc, arguments, and NULL
284 * terminator */
285 env = (char **) sp;
286 while (*sp++ != 0) { /* Skip over environment, and NULL terminator */
287 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
288 dbg(("env[%d] = %p %s\n", i++, (void *)sp[-1], (char *)sp[-1]));
289 #endif
290 }
291 aux = (const AuxInfo *) sp;
292
293 /* Digest the auxiliary vector. */
294 pAUX_base = pAUX_entry = pAUX_execfd = NULL;
295 pAUX_phdr = pAUX_phent = pAUX_phnum = NULL;
296 #ifdef VARPSZ
297 pAUX_pagesz = NULL;
298 #endif
299 for (auxp = aux; auxp->au_id != AUX_null; ++auxp) {
300 switch (auxp->au_id) {
301 case AUX_base:
302 pAUX_base = auxp;
303 break;
304 case AUX_entry:
305 pAUX_entry = auxp;
306 break;
307 case AUX_execfd:
308 pAUX_execfd = auxp;
309 break;
310 case AUX_phdr:
311 pAUX_phdr = auxp;
312 break;
313 case AUX_phent:
314 pAUX_phent = auxp;
315 break;
316 case AUX_phnum:
317 pAUX_phnum = auxp;
318 break;
319 #ifdef VARPSZ
320 case AUX_pagesz:
321 pAUX_pagesz = auxp;
322 break;
323 #endif
324 }
325 }
326
327 /* Initialize and relocate ourselves. */
328 assert(pAUX_base != NULL);
329 _rtld_init((caddr_t) pAUX_base->au_v);
330
331 #ifdef VARPSZ
332 assert(pAUX_pagesz != NULL);
333 _rtld_pagesz = (int)pAUX_pagesz->au_v;
334 #endif
335
336 #ifdef RTLD_DEBUG
337 dbg(("_ctype_ is %p\n", _ctype_));
338 #endif
339
340 __progname = _rtld_objself.path;
341 environ = env;
342
343 _rtld_trust = geteuid() == getuid() && getegid() == getgid();
344
345 ld_bind_now = getenv("LD_BIND_NOW");
346 if (ld_bind_now != NULL && *ld_bind_now != '\0')
347 bind_now = true;
348 if (_rtld_trust) {
349 #ifdef DEBUG
350 const char *ld_debug = getenv("LD_DEBUG");
351 if (ld_debug != NULL && *ld_debug != '\0')
352 debug = 1;
353 #endif
354 _rtld_add_paths(&_rtld_paths, getenv("LD_LIBRARY_PATH"), true);
355 }
356 _rtld_process_hints(&_rtld_paths, _PATH_LD_HINTS, true);
357 dbg(("%s is initialized, base address = %p", __progname,
358 (void *) pAUX_base->au_v));
359
360 /*
361 * Load the main program, or process its program header if it is
362 * already loaded.
363 */
364 if (pAUX_execfd != NULL) { /* Load the main program. */
365 int fd = pAUX_execfd->au_v;
366 dbg(("loading main program"));
367 _rtld_objmain = _rtld_map_object(argv[0], fd);
368 close(fd);
369 if (_rtld_objmain == NULL)
370 _rtld_die();
371 } else { /* Main program already loaded. */
372 const Elf_Phdr *phdr;
373 int phnum;
374 caddr_t entry;
375
376 dbg(("processing main program's program header"));
377 assert(pAUX_phdr != NULL);
378 phdr = (const Elf_Phdr *) pAUX_phdr->au_v;
379 assert(pAUX_phnum != NULL);
380 phnum = pAUX_phnum->au_v;
381 assert(pAUX_phent != NULL);
382 assert(pAUX_phent->au_v == sizeof(Elf_Phdr));
383 assert(pAUX_entry != NULL);
384 entry = (caddr_t) pAUX_entry->au_v;
385 _rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
386 }
387
388 _rtld_objmain->path = xstrdup("main program");
389 _rtld_objmain->mainprog = true;
390 _rtld_digest_dynamic(_rtld_objmain);
391
392 _rtld_linkmap_add(_rtld_objmain);
393 _rtld_linkmap_add(&_rtld_objself);
394
395 /* Link the main program into the list of objects. */
396 *_rtld_objtail = _rtld_objmain;
397 _rtld_objtail = &_rtld_objmain->next;
398 ++_rtld_objmain->refcount;
399
400 /*
401 * Pre-load user-specified objects after the main program but before
402 * any shared object dependencies.
403 */
404 dbg(("preloading objects"));
405 if (_rtld_trust && _rtld_preload(getenv("LD_PRELOAD"), true) == -1)
406 _rtld_die();
407
408 dbg(("loading needed objects"));
409 if (_rtld_load_needed_objects(_rtld_objmain) == -1)
410 _rtld_die();
411
412 dbg(("relocating objects"));
413 if (_rtld_relocate_objects(_rtld_objmain, bind_now, true) == -1)
414 _rtld_die();
415
416 dbg(("doing copy relocations"));
417 if (_rtld_do_copy_relocations(_rtld_objmain, true) == -1)
418 _rtld_die();
419
420 dbg(("calling _init functions"));
421 _rtld_call_init_functions(_rtld_objmain->next);
422
423 dbg(("control at program entry point = %p, obj = %p, exit = %p",
424 _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
425
426 /*
427 * Return with the entry point and the exit procedure in at the top
428 * of stack.
429 */
430
431 _rtld_debug_state(); /* say hello to gdb! */
432
433 ((void **) osp)[0] = _rtld_exit;
434 ((void **) osp)[1] = _rtld_objmain;
435 return (Elf_Addr) _rtld_objmain->entry;
436 }
437
438 void
439 _rtld_die()
440 {
441 const char *msg = _rtld_dlerror();
442
443 if (msg == NULL)
444 msg = "Fatal error";
445 xerrx(1, "%s\n", msg);
446 }
447
448 static Obj_Entry *
449 _rtld_dlcheck(handle)
450 void *handle;
451 {
452 Obj_Entry *obj;
453
454 for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
455 if (obj == (Obj_Entry *) handle)
456 break;
457
458 if (obj == NULL || obj->dl_refcount == 0) {
459 xwarnx("Invalid shared object handle %p", handle);
460 return NULL;
461 }
462 return obj;
463 }
464
465 static void
466 _rtld_unref_object_dag(root)
467 Obj_Entry *root;
468 {
469 assert(root->refcount != 0);
470 --root->refcount;
471 if (root->refcount == 0) {
472 const Needed_Entry *needed;
473
474 for (needed = root->needed; needed != NULL;
475 needed = needed->next)
476 _rtld_unref_object_dag(needed->obj);
477 }
478 }
479
480 int
481 _rtld_dlclose(handle)
482 void *handle;
483 {
484 Obj_Entry *root = _rtld_dlcheck(handle);
485
486 if (root == NULL)
487 return -1;
488
489 _rtld_debug.r_state = RT_DELETE;
490 _rtld_debug_state();
491
492 --root->dl_refcount;
493 _rtld_unref_object_dag(root);
494 if (root->refcount == 0) { /* We are finished with some objects. */
495 Obj_Entry *obj;
496 Obj_Entry **linkp;
497
498 /* Finalize objects that are about to be unmapped. */
499 for (obj = _rtld_objlist->next; obj != NULL; obj = obj->next)
500 if (obj->refcount == 0 && obj->fini != NULL)
501 (*obj->fini) ();
502
503 /* Unmap all objects that are no longer referenced. */
504 linkp = &_rtld_objlist->next;
505 while ((obj = *linkp) != NULL) {
506 if (obj->refcount == 0) {
507 munmap(obj->mapbase, obj->mapsize);
508 free(obj->path);
509 while (obj->needed != NULL) {
510 Needed_Entry *needed = obj->needed;
511 obj->needed = needed->next;
512 free(needed);
513 }
514 _rtld_linkmap_delete(obj);
515 *linkp = obj->next;
516 if (obj->next == NULL)
517 _rtld_objtail = linkp;
518 free(obj);
519 } else
520 linkp = &obj->next;
521 }
522 }
523 _rtld_debug.r_state = RT_CONSISTENT;
524 _rtld_debug_state();
525
526 return 0;
527 }
528
529 char *
530 _rtld_dlerror()
531 {
532 char *msg = error_message;
533 error_message = NULL;
534 return msg;
535 }
536
537 void *
538 _rtld_dlopen(name, mode)
539 const char *name;
540 int mode;
541 {
542 Obj_Entry **old_obj_tail = _rtld_objtail;
543 Obj_Entry *obj = NULL;
544
545 _rtld_debug.r_state = RT_ADD;
546 _rtld_debug_state();
547
548 if (name == NULL) {
549 obj = _rtld_objmain;
550 } else {
551 char *path = _rtld_find_library(name, _rtld_objmain);
552 if (path != NULL)
553 obj = _rtld_load_object(path, true);
554 }
555
556 if (obj != NULL) {
557 ++obj->dl_refcount;
558 if (*old_obj_tail != NULL) { /* We loaded something new. */
559 assert(*old_obj_tail == obj);
560
561 /* FIXME - Clean up properly after an error. */
562 if (_rtld_load_needed_objects(obj) == -1) {
563 --obj->dl_refcount;
564 obj = NULL;
565 } else if (_rtld_relocate_objects(obj,
566 (mode & 3) == RTLD_NOW, true) == -1) {
567 --obj->dl_refcount;
568 obj = NULL;
569 } else {
570 _rtld_call_init_functions(obj);
571 }
572 }
573 }
574 _rtld_debug.r_state = RT_CONSISTENT;
575 _rtld_debug_state();
576
577 return obj;
578 }
579
580 void *
581 _rtld_dlsym(handle, name)
582 void *handle;
583 const char *name;
584 {
585 const Obj_Entry *obj = _rtld_dlcheck(handle);
586 const Elf_Sym *def;
587 const Obj_Entry *defobj;
588
589 if (obj == NULL)
590 return NULL;
591
592 /*
593 * FIXME - This isn't correct. The search should include the whole
594 * DAG rooted at the given object.
595 */
596 def = _rtld_find_symdef(_rtld_objlist, 0, name, obj, &defobj, false);
597 if (def != NULL)
598 return defobj->relocbase + def->st_value;
599
600 _rtld_error("Undefined symbol \"%s\"", name);
601 return NULL;
602 }
603
604 /*
605 * Error reporting function. Use it like printf. If formats the message
606 * into a buffer, and sets things up so that the next call to dlerror()
607 * will return the message.
608 */
609 void
610 #ifdef __STDC__
611 _rtld_error(const char *fmt,...)
612 #else
613 _rtld_error(va_alist)
614 va_dcl
615 #endif
616 {
617 static char buf[512];
618 va_list ap;
619 #ifdef __STDC__
620 va_start(ap, fmt);
621 #else
622 const char *fmt;
623
624 va_start(ap);
625 fmt = va_arg(ap, const char *);
626 #endif
627 xvsnprintf(buf, sizeof buf, fmt, ap);
628 error_message = buf;
629 va_end(ap);
630 }
631
632 void
633 _rtld_debug_state()
634 {
635 /* do nothing */
636 }
637
638 void
639 _rtld_linkmap_add(obj)
640 Obj_Entry *obj;
641 {
642 struct link_map *l = &obj->linkmap;
643 struct link_map *prev;
644
645 obj->linkmap.l_name = obj->path;
646 obj->linkmap.l_addr = obj->mapbase;
647 obj->linkmap.l_ld = obj->dynamic;
648 #ifdef __mips__
649 /* GDB needs load offset on MIPS to use the symbols */
650 obj->linkmap.l_offs = obj->relocbase;
651 #endif
652
653 if (_rtld_debug.r_map == NULL) {
654 _rtld_debug.r_map = l;
655 return;
656 }
657 for (prev = _rtld_debug.r_map; prev->l_next != NULL; prev = prev->l_next);
658 l->l_prev = prev;
659 prev->l_next = l;
660 l->l_next = NULL;
661 }
662
663 void
664 _rtld_linkmap_delete(obj)
665 Obj_Entry *obj;
666 {
667 struct link_map *l = &obj->linkmap;
668
669 if (l->l_prev == NULL) {
670 if ((_rtld_debug.r_map = l->l_next) != NULL)
671 l->l_next->l_prev = NULL;
672 return;
673 }
674 if ((l->l_prev->l_next = l->l_next) != NULL)
675 l->l_next->l_prev = l->l_prev;
676 }
677