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