rtld.c revision 1.16 1 /* $NetBSD: rtld.c,v 1.16 1999/03/03 21:18:00 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 #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 in %eax,
235 * and the dynamic linker's exit procedure in %edx. We accomplish this
236 * by declaring the return value to have the 64-bit type "long long".
237 * Such values are returned with their most-significant 32 bits in %edx,
238 * and their least-significant 32 bits in %eax.
239 */
240 Elf_Addr
241 _rtld(sp)
242 Elf_Word *sp;
243 {
244 const AuxInfo *pAUX_base, *pAUX_entry, *pAUX_execfd, *pAUX_phdr,
245 *pAUX_phent, *pAUX_phnum;
246 char **env;
247 const AuxInfo *aux;
248 const AuxInfo *auxp;
249 Elf_Word *const osp = sp;
250 bool bind_now = 0;
251 const char *ld_bind_now;
252 const char **argv;
253 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
254 int i = 0;
255 #endif
256
257 /*
258 * On entry, the dynamic linker itself has not been relocated yet.
259 * Be very careful not to reference any global data until after
260 * _rtld_init has returned. It is OK to reference file-scope statics
261 * and string constants, and to call static and global functions.
262 */
263 /* Find the auxiliary vector on the stack. */
264 /* first Elf_Word reserved to address of exit routine */
265 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
266 dbg(("sp = %p, argc = %ld, argv = %p <%s>\n", sp, (long)sp[2],
267 &sp[3], (char *) sp[3]));
268 dbg(("got is at %p, dynamic is at %p\n",
269 _GLOBAL_OFFSET_TABLE_, &_DYNAMIC));
270 debug = 1;
271 dbg(("_ctype_ is %p\n", _ctype_));
272 #endif
273
274 sp += 2; /* skip over return argument space */
275 argv = (const char **) &sp[1];
276 sp += sp[0] + 2; /* Skip over argc, arguments, and NULL
277 * terminator */
278 env = (char **) sp;
279 while (*sp++ != 0) { /* Skip over environment, and NULL terminator */
280 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
281 dbg(("env[%d] = %p %s\n", i++, (void *)sp[-1], (char *)sp[-1]));
282 #endif
283 }
284 aux = (const AuxInfo *) sp;
285
286 /* Digest the auxiliary vector. */
287 pAUX_base = pAUX_entry = pAUX_execfd = NULL;
288 pAUX_phdr = pAUX_phent = pAUX_phnum = NULL;
289 for (auxp = aux; auxp->au_id != AUX_null; ++auxp) {
290 switch (auxp->au_id) {
291 case AUX_base:
292 pAUX_base = auxp;
293 break;
294 case AUX_entry:
295 pAUX_entry = auxp;
296 break;
297 case AUX_execfd:
298 pAUX_execfd = auxp;
299 break;
300 case AUX_phdr:
301 pAUX_phdr = auxp;
302 break;
303 case AUX_phent:
304 pAUX_phent = auxp;
305 break;
306 case AUX_phnum:
307 pAUX_phnum = auxp;
308 break;
309 }
310 }
311
312 /* Initialize and relocate ourselves. */
313 assert(pAUX_base != NULL);
314 _rtld_init((caddr_t) pAUX_base->au_v);
315
316 #ifdef RTLD_DEBUG
317 dbg(("_ctype_ is %p\n", _ctype_));
318 #endif
319
320 __progname = _rtld_objself.path;
321 environ = env;
322
323 _rtld_trust = geteuid() == getuid() && getegid() == getgid();
324
325 ld_bind_now = getenv("LD_BIND_NOW");
326 if (ld_bind_now != NULL && *ld_bind_now != '\0')
327 bind_now = true;
328 if (_rtld_trust) {
329 #ifdef DEBUG
330 const char *ld_debug = getenv("LD_DEBUG");
331 if (ld_debug != NULL && *ld_debug != '\0')
332 debug = 1;
333 #endif
334 _rtld_add_paths(&_rtld_paths, getenv("LD_LIBRARY_PATH"), true);
335 }
336 dbg(("%s is initialized, base address = %p", __progname,
337 (void *) pAUX_base->au_v));
338
339 /*
340 * Load the main program, or process its program header if it is
341 * already loaded.
342 */
343 if (pAUX_execfd != NULL) { /* Load the main program. */
344 int fd = pAUX_execfd->au_v;
345 dbg(("loading main program"));
346 _rtld_objmain = _rtld_map_object(argv[0], fd);
347 close(fd);
348 if (_rtld_objmain == NULL)
349 _rtld_die();
350 } else { /* Main program already loaded. */
351 const Elf_Phdr *phdr;
352 int phnum;
353 caddr_t entry;
354
355 dbg(("processing main program's program header"));
356 assert(pAUX_phdr != NULL);
357 phdr = (const Elf_Phdr *) pAUX_phdr->au_v;
358 assert(pAUX_phnum != NULL);
359 phnum = pAUX_phnum->au_v;
360 assert(pAUX_phent != NULL);
361 assert(pAUX_phent->au_v == sizeof(Elf_Phdr));
362 assert(pAUX_entry != NULL);
363 entry = (caddr_t) pAUX_entry->au_v;
364 _rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
365 }
366
367 _rtld_objmain->path = xstrdup("main program");
368 _rtld_objmain->mainprog = true;
369 _rtld_digest_dynamic(_rtld_objmain);
370
371 _rtld_linkmap_add(_rtld_objmain);
372 _rtld_linkmap_add(&_rtld_objself);
373
374 /* Link the main program into the list of objects. */
375 *_rtld_objtail = _rtld_objmain;
376 _rtld_objtail = &_rtld_objmain->next;
377 ++_rtld_objmain->refcount;
378
379 dbg(("loading needed objects"));
380 if (_rtld_load_needed_objects(_rtld_objmain) == -1)
381 _rtld_die();
382
383 dbg(("relocating objects"));
384 if (_rtld_relocate_objects(_rtld_objmain, bind_now, true) == -1)
385 _rtld_die();
386
387 dbg(("doing copy relocations"));
388 if (_rtld_do_copy_relocations(_rtld_objmain, true) == -1)
389 _rtld_die();
390
391 dbg(("calling _init functions"));
392 _rtld_call_init_functions(_rtld_objmain->next);
393
394 dbg(("control at program entry point = %p, obj = %p, exit = %p",
395 _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
396
397 /*
398 * Return with the entry point and the exit procedure in at the top
399 * of stack.
400 */
401
402 _rtld_debug_state(); /* say hello to gdb! */
403
404 ((void **) osp)[0] = _rtld_exit;
405 ((void **) osp)[1] = _rtld_objmain;
406 return (Elf_Addr) _rtld_objmain->entry;
407 }
408
409 void
410 _rtld_die()
411 {
412 const char *msg = _rtld_dlerror();
413
414 if (msg == NULL)
415 msg = "Fatal error";
416 xerrx(1, "%s\n", msg);
417 }
418
419 static Obj_Entry *
420 _rtld_dlcheck(handle)
421 void *handle;
422 {
423 Obj_Entry *obj;
424
425 for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
426 if (obj == (Obj_Entry *) handle)
427 break;
428
429 if (obj == NULL || obj->dl_refcount == 0) {
430 xwarnx("Invalid shared object handle %p", handle);
431 return NULL;
432 }
433 return obj;
434 }
435
436 static void
437 _rtld_unref_object_dag(root)
438 Obj_Entry *root;
439 {
440 assert(root->refcount != 0);
441 --root->refcount;
442 if (root->refcount == 0) {
443 const Needed_Entry *needed;
444
445 for (needed = root->needed; needed != NULL;
446 needed = needed->next)
447 _rtld_unref_object_dag(needed->obj);
448 }
449 }
450
451 int
452 _rtld_dlclose(handle)
453 void *handle;
454 {
455 Obj_Entry *root = _rtld_dlcheck(handle);
456
457 if (root == NULL)
458 return -1;
459
460 _rtld_debug.r_state = RT_DELETE;
461 _rtld_debug_state();
462
463 --root->dl_refcount;
464 _rtld_unref_object_dag(root);
465 if (root->refcount == 0) { /* We are finished with some objects. */
466 Obj_Entry *obj;
467 Obj_Entry **linkp;
468
469 /* Finalize objects that are about to be unmapped. */
470 for (obj = _rtld_objlist->next; obj != NULL; obj = obj->next)
471 if (obj->refcount == 0 && obj->fini != NULL)
472 (*obj->fini) ();
473
474 /* Unmap all objects that are no longer referenced. */
475 linkp = &_rtld_objlist->next;
476 while ((obj = *linkp) != NULL) {
477 if (obj->refcount == 0) {
478 munmap(obj->mapbase, obj->mapsize);
479 free(obj->path);
480 while (obj->needed != NULL) {
481 Needed_Entry *needed = obj->needed;
482 obj->needed = needed->next;
483 free(needed);
484 }
485 _rtld_linkmap_delete(obj);
486 *linkp = obj->next;
487 if (obj->next == NULL)
488 _rtld_objtail = linkp;
489 free(obj);
490 } else
491 linkp = &obj->next;
492 }
493 }
494 _rtld_debug.r_state = RT_CONSISTENT;
495 _rtld_debug_state();
496
497 return 0;
498 }
499
500 char *
501 _rtld_dlerror()
502 {
503 char *msg = error_message;
504 error_message = NULL;
505 return msg;
506 }
507
508 void *
509 _rtld_dlopen(name, mode)
510 const char *name;
511 int mode;
512 {
513 Obj_Entry **old_obj_tail = _rtld_objtail;
514 Obj_Entry *obj = NULL;
515
516 _rtld_debug.r_state = RT_ADD;
517 _rtld_debug_state();
518
519 if (name == NULL) {
520 obj = _rtld_objmain;
521 } else {
522 char *path = _rtld_find_library(name, NULL);
523 if (path != NULL)
524 obj = _rtld_load_object(path, true);
525 }
526
527 if (obj != NULL) {
528 ++obj->dl_refcount;
529 if (*old_obj_tail != NULL) { /* We loaded something new. */
530 assert(*old_obj_tail == obj);
531
532 /* FIXME - Clean up properly after an error. */
533 if (_rtld_load_needed_objects(obj) == -1) {
534 --obj->dl_refcount;
535 obj = NULL;
536 } else if (_rtld_relocate_objects(obj,
537 (mode & 3) == RTLD_NOW, true) == -1) {
538 --obj->dl_refcount;
539 obj = NULL;
540 } else {
541 _rtld_call_init_functions(obj);
542 }
543 }
544 }
545 _rtld_debug.r_state = RT_CONSISTENT;
546 _rtld_debug_state();
547
548 return obj;
549 }
550
551 void *
552 _rtld_dlsym(handle, name)
553 void *handle;
554 const char *name;
555 {
556 const Obj_Entry *obj = _rtld_dlcheck(handle);
557 const Elf_Sym *def;
558 const Obj_Entry *defobj;
559
560 if (obj == NULL)
561 return NULL;
562
563 /*
564 * FIXME - This isn't correct. The search should include the whole
565 * DAG rooted at the given object.
566 */
567 def = _rtld_find_symdef(_rtld_objlist, 0, name, obj, &defobj, false);
568 if (def != NULL)
569 return defobj->relocbase + def->st_value;
570
571 _rtld_error("Undefined symbol \"%s\"", name);
572 return NULL;
573 }
574
575 /*
576 * Error reporting function. Use it like printf. If formats the message
577 * into a buffer, and sets things up so that the next call to dlerror()
578 * will return the message.
579 */
580 void
581 #ifdef __STDC__
582 _rtld_error(const char *fmt,...)
583 #else
584 _rtld_error(va_alist)
585 va_dcl
586 #endif
587 {
588 static char buf[512];
589 va_list ap;
590 #ifdef __STDC__
591 va_start(ap, fmt);
592 #else
593 const char *fmt;
594
595 va_start(ap);
596 fmt = va_arg(ap, const char *);
597 #endif
598 xvsnprintf(buf, sizeof buf, fmt, ap);
599 error_message = buf;
600 va_end(ap);
601 }
602
603 void
604 _rtld_debug_state()
605 {
606 /* do nothing */
607 }
608
609 void
610 _rtld_linkmap_add(obj)
611 Obj_Entry *obj;
612 {
613 struct link_map *l = &obj->linkmap;
614 struct link_map *prev;
615
616 obj->linkmap.l_name = obj->path;
617 obj->linkmap.l_addr = obj->mapbase;
618 obj->linkmap.l_ld = obj->dynamic;
619 #ifdef __mips__
620 /* GDB needs load offset on MIPS to use the symbols */
621 obj->linkmap.l_offs = obj->relocbase;
622 #endif
623
624 if (_rtld_debug.r_map == NULL) {
625 _rtld_debug.r_map = l;
626 return;
627 }
628 for (prev = _rtld_debug.r_map; prev->l_next != NULL; prev = prev->l_next);
629 l->l_prev = prev;
630 prev->l_next = l;
631 l->l_next = NULL;
632 }
633
634 void
635 _rtld_linkmap_delete(obj)
636 Obj_Entry *obj;
637 {
638 struct link_map *l = &obj->linkmap;
639
640 if (l->l_prev == NULL) {
641 if ((_rtld_debug.r_map = l->l_next) != NULL)
642 l->l_next->l_prev = NULL;
643 return;
644 }
645 if ((l->l_prev->l_next = l->l_next) != NULL)
646 l->l_next->l_prev = l->l_prev;
647 }
648