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