Update.
[glibc.git] / elf / rtld.c
blobf7b76ada8d471b3e5e98cd90f0c8fff88d4626ee
1 /* Run time dynamic linker.
2 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
15 You should have received a copy of the GNU Library General Public
16 License along with the GNU C Library; see the file COPYING.LIB. If not,
17 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
20 #include <link.h>
21 #include <stddef.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <sys/mman.h> /* Check if MAP_ANON is defined. */
26 #include "../stdio-common/_itoa.h"
27 #include <assert.h>
28 #include "dynamic-link.h"
31 /* System-specific function to do initial startup for the dynamic linker.
32 After this, file access calls and getenv must work. This is responsible
33 for setting __libc_enable_secure if we need to be secure (e.g. setuid),
34 and for setting _dl_argc and _dl_argv, and then calling _dl_main. */
35 extern ElfW(Addr) _dl_sysdep_start (void **start_argptr,
36 void (*dl_main) (const ElfW(Phdr) *phdr,
37 ElfW(Half) phent,
38 ElfW(Addr) *user_entry));
39 extern void _dl_sysdep_start_cleanup (void);
41 /* System-dependent function to read a file's whole contents
42 in the most convenient manner available. */
43 extern void *_dl_sysdep_read_whole_file (const char *filename,
44 size_t *filesize_ptr,
45 int mmap_prot);
47 /* Helper function to handle errors while resolving symbols. */
48 static void print_unresolved (const char *errstring, const char *objname);
51 int _dl_argc;
52 char **_dl_argv;
53 const char *_dl_rpath;
54 const char *_dl_library_path;
56 /* Set nonzero during loading and initialization of executable and
57 libraries, cleared before the executable's entry point runs. This
58 must not be initialized to nonzero, because the unused dynamic
59 linker loaded in for libc.so's "ld.so.1" dep will provide the
60 definition seen by libc.so's initializer; that value must be zero,
61 and will be since that dynamic linker's _dl_start and dl_main will
62 never be called. */
63 int _dl_starting_up;
65 static void dl_main (const ElfW(Phdr) *phdr,
66 ElfW(Half) phent,
67 ElfW(Addr) *user_entry);
69 struct link_map _dl_rtld_map;
71 #ifdef RTLD_START
72 RTLD_START
73 #else
74 #error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
75 #endif
77 ElfW(Addr)
78 _dl_start (void *arg)
80 struct link_map bootstrap_map;
82 /* This #define produces dynamic linking inline functions for
83 bootstrap relocation instead of general-purpose relocation. */
84 #define RTLD_BOOTSTRAP
85 #define RESOLVE(sym, flags) bootstrap_map.l_addr
86 #include "dynamic-link.h"
88 /* Figure out the run-time load address of the dynamic linker itself. */
89 bootstrap_map.l_addr = elf_machine_load_address ();
91 /* Read our own dynamic section and fill in the info array. */
92 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
93 elf_get_dynamic_info (bootstrap_map.l_ld, bootstrap_map.l_info);
95 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
96 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
97 #endif
99 /* Relocate ourselves so we can do normal function calls and
100 data access using the global offset table. */
102 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0);
105 /* Now life is sane; we can call functions and access global data.
106 Set up to use the operating system facilities, and find out from
107 the operating system's program loader where to find the program
108 header table in core. */
111 /* Transfer data about ourselves to the permanent link_map structure. */
112 _dl_rtld_map.l_addr = bootstrap_map.l_addr;
113 _dl_rtld_map.l_ld = bootstrap_map.l_ld;
114 memcpy (_dl_rtld_map.l_info, bootstrap_map.l_info,
115 sizeof _dl_rtld_map.l_info);
116 _dl_setup_hash (&_dl_rtld_map);
118 /* Cache the DT_RPATH stored in ld.so itself; this will be
119 the default search path. */
120 _dl_rpath = (void *) (_dl_rtld_map.l_addr +
121 _dl_rtld_map.l_info[DT_STRTAB]->d_un.d_ptr +
122 _dl_rtld_map.l_info[DT_RPATH]->d_un.d_val);
124 /* Call the OS-dependent function to set up life so we can do things like
125 file access. It will call `dl_main' (below) to do all the real work
126 of the dynamic linker, and then unwind our frame and run the user
127 entry point on the same stack we entered on. */
128 return _dl_sysdep_start (arg, &dl_main);
132 /* Now life is peachy; we can do all normal operations.
133 On to the real work. */
135 void _start (void);
137 unsigned int _dl_skip_args; /* Nonzero if we were run directly. */
139 static void
140 dl_main (const ElfW(Phdr) *phdr,
141 ElfW(Half) phent,
142 ElfW(Addr) *user_entry)
144 const ElfW(Phdr) *ph;
145 struct link_map *l;
146 int lazy;
147 enum { normal, list, verify, trace } mode;
148 struct link_map **preloads;
149 unsigned int npreloads;
150 const char *preloadlist;
151 size_t file_size;
152 char *file;
154 mode = getenv ("LD_TRACE_LOADED_OBJECTS") != NULL ? trace : normal;
155 _dl_library_path = getenv ("LD_LIBRARY_PATH");
157 /* LAZY is determined by the parameters --datadeps and --function-deps
158 if we trace the binary. */
159 if (mode == trace)
160 lazy = -1;
161 else
162 lazy = !__libc_enable_secure && *(getenv ("LD_BIND_NOW") ?: "") == '\0';
164 /* Set up a flag which tells we are just starting. */
165 _dl_starting_up = 1;
167 if (*user_entry == (ElfW(Addr)) &_start)
169 /* Ho ho. We are not the program interpreter! We are the program
170 itself! This means someone ran ld.so as a command. Well, that
171 might be convenient to do sometimes. We support it by
172 interpreting the args like this:
174 ld.so PROGRAM ARGS...
176 The first argument is the name of a file containing an ELF
177 executable we will load and run with the following arguments.
178 To simplify life here, PROGRAM is searched for using the
179 normal rules for shared objects, rather than $PATH or anything
180 like that. We just load it and use its entry point; we don't
181 pay attention to its PT_INTERP command (we are the interpreter
182 ourselves). This is an easy way to test a new ld.so before
183 installing it. */
184 if (_dl_argc < 2)
185 _dl_sysdep_fatal ("\
186 Usage: ld.so [--list|--verify] EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
187 You have invoked `ld.so', the helper program for shared library executables.\n\
188 This program usually lives in the file `/lib/ld.so', and special directives\n\
189 in executable files using ELF shared libraries tell the system's program\n\
190 loader to load the helper program from this file. This helper program loads\n\
191 the shared libraries needed by the program executable, prepares the program\n\
192 to run, and runs it. You may invoke this helper program directly from the\n\
193 command line to load and run an ELF executable file; this is like executing\n\
194 that file itself, but always uses this helper program from the file you\n\
195 specified, instead of the helper program file specified in the executable\n\
196 file you run. This is mostly of use for maintainers to test new versions\n\
197 of this helper program; chances are you did not intend to run this program.\n",
198 NULL);
200 /* Note the place where the dynamic linker actually came from. */
201 _dl_rtld_map.l_name = _dl_argv[0];
203 while (_dl_argc > 1)
204 if (! strcmp (_dl_argv[1], "--list"))
206 mode = list;
207 lazy = -1; /* This means do no dependency analysis. */
209 ++_dl_skip_args;
210 --_dl_argc;
211 ++_dl_argv;
213 else if (! strcmp (_dl_argv[1], "--verify"))
215 mode = verify;
217 ++_dl_skip_args;
218 --_dl_argc;
219 ++_dl_argv;
221 else if (! strcmp (_dl_argv[1], "--data-relocs"))
223 mode = trace;
224 lazy = 1; /* This means do only data relocation analysis. */
226 ++_dl_skip_args;
227 --_dl_argc;
228 ++_dl_argv;
230 else if (! strcmp (_dl_argv[1], "--function-relocs"))
232 mode = trace;
233 lazy = 0; /* This means do also function relocation analysis. */
235 ++_dl_skip_args;
236 --_dl_argc;
237 ++_dl_argv;
239 else if (! strcmp (_dl_argv[1], "--library-path")
240 && _dl_argc > 2)
242 _dl_library_path = _dl_argv[2];
243 _dl_skip_args += 2;
244 _dl_argc -= 2;
245 _dl_argv += 2;
247 else
248 break;
250 ++_dl_skip_args;
251 --_dl_argc;
252 ++_dl_argv;
254 if (mode == verify)
256 void doit (void)
258 l = _dl_map_object (NULL, _dl_argv[0], 0, lt_library, 0);
260 char *err_str = NULL;
262 (void) _dl_catch_error (&err_str, doit);
263 if (err_str != NULL)
265 free (err_str);
266 _exit (EXIT_FAILURE);
269 else
270 l = _dl_map_object (NULL, _dl_argv[0], 0, lt_library, 0);
272 phdr = l->l_phdr;
273 phent = l->l_phnum;
274 l->l_name = (char *) "";
275 *user_entry = l->l_entry;
277 else
279 /* Create a link_map for the executable itself.
280 This will be what dlopen on "" returns. */
281 l = _dl_new_object ((char *) "", "", lt_executable);
282 if (l == NULL)
283 _dl_sysdep_fatal ("cannot allocate memory for link map", NULL);
284 l->l_phdr = phdr;
285 l->l_phnum = phent;
286 l->l_entry = *user_entry;
289 if (l != _dl_loaded)
291 /* GDB assumes that the first element on the chain is the
292 link_map for the executable itself, and always skips it.
293 Make sure the first one is indeed that one. */
294 l->l_prev->l_next = l->l_next;
295 if (l->l_next)
296 l->l_next->l_prev = l->l_prev;
297 l->l_prev = NULL;
298 l->l_next = _dl_loaded;
299 _dl_loaded->l_prev = l;
300 _dl_loaded = l;
303 /* Scan the program header table for the dynamic section. */
304 for (ph = phdr; ph < &phdr[phent]; ++ph)
305 switch (ph->p_type)
307 case PT_DYNAMIC:
308 /* This tells us where to find the dynamic section,
309 which tells us everything we need to do. */
310 l->l_ld = (void *) l->l_addr + ph->p_vaddr;
311 break;
312 case PT_INTERP:
313 /* This "interpreter segment" was used by the program loader to
314 find the program interpreter, which is this program itself, the
315 dynamic linker. We note what name finds us, so that a future
316 dlopen call or DT_NEEDED entry, for something that wants to link
317 against the dynamic linker as a shared library, will know that
318 the shared object is already loaded. */
319 _dl_rtld_map.l_libname = (const char *) l->l_addr + ph->p_vaddr;
320 break;
322 if (! _dl_rtld_map.l_libname && _dl_rtld_map.l_name)
323 /* We were invoked directly, so the program might not have a PT_INTERP. */
324 _dl_rtld_map.l_libname = _dl_rtld_map.l_name;
325 else
326 assert (_dl_rtld_map.l_libname); /* How else did we get here? */
328 if (mode == verify)
329 /* We were called just to verify that this is a dynamic executable
330 using us as the program interpreter. */
331 _exit (l->l_ld == NULL ? EXIT_FAILURE : EXIT_SUCCESS);
333 /* Extract the contents of the dynamic section for easy access. */
334 elf_get_dynamic_info (l->l_ld, l->l_info);
335 if (l->l_info[DT_HASH])
336 /* Set up our cache of pointers into the hash table. */
337 _dl_setup_hash (l);
339 /* Put the link_map for ourselves on the chain so it can be found by
340 name. */
341 if (! _dl_rtld_map.l_name)
342 /* If not invoked directly, the dynamic linker shared object file was
343 found by the PT_INTERP name. */
344 _dl_rtld_map.l_name = (char *) _dl_rtld_map.l_libname;
345 _dl_rtld_map.l_type = lt_library;
346 while (l->l_next)
347 l = l->l_next;
348 l->l_next = &_dl_rtld_map;
349 _dl_rtld_map.l_prev = l;
351 /* We have two ways to specify objects to preload: via environment
352 variable and via the file /etc/ld.so.preload. The later can also
353 be used when security is enabled. */
354 preloads = NULL;
355 npreloads = 0;
357 preloadlist = getenv ("LD_PRELOAD");
358 if (preloadlist)
360 /* The LD_PRELOAD environment variable gives list of libraries
361 separated by white space or colons that are loaded before the
362 executable's dependencies and prepended to the global scope
363 list. If the binary is running setuid all elements
364 containing a '/' are ignored since it is insecure. */
365 char *list = strdupa (preloadlist);
366 char *p;
367 while ((p = strsep (&list, " :")) != NULL)
368 if (! __libc_enable_secure || strchr (p, '/') == NULL)
370 struct link_map *new_map = _dl_map_object (l, p, 1, lt_library, 0);
371 if (new_map->l_opencount == 1)
372 /* It is no duplicate. */
373 ++npreloads;
377 /* Read the contents of the file. */
378 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
379 PROT_READ | PROT_WRITE);
380 if (file)
382 /* Parse the file. It contains names of libraries to be loaded,
383 separated by white spaces or `:'. It may also contain
384 comments introduced by `#'. */
385 char *problem;
386 char *runp;
387 size_t rest;
389 /* Eliminate comments. */
390 runp = file;
391 rest = file_size;
392 while (rest > 0)
394 char *comment = memchr (runp, '#', rest);
395 if (comment == NULL)
396 break;
398 rest -= comment - runp;
400 *comment = ' ';
401 while (--rest > 0 && *++comment != '\n');
404 /* We have one problematic case: if we have a name at the end of
405 the file without a trailing terminating characters, we cannot
406 place the \0. Handle the case separately. */
407 if (file_size > 0 && file[file_size - 1] != ' '
408 && file[file_size - 1] != '\t' && file[file_size - 1] != '\n'
409 && file[file_size - 1] != ':')
411 problem = &file[file_size];
412 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
413 && problem[-1] != '\n' && problem[-1] != ':')
414 --problem;
416 if (problem > file)
417 problem[-1] = '\0';
419 else
421 problem = NULL;
422 if (file_size > 0)
423 file[file_size - 1] = '\0';
426 if (file_size > 0 && file != problem)
428 char *p;
429 runp = file + strspn (file, ": \t\n");
430 while ((p = strsep (&runp, ": \t\n")) != NULL)
432 struct link_map *new_map = _dl_map_object (l, p, 1,
433 lt_library, 0);
434 if (new_map->l_opencount == 1)
435 /* It is no duplicate. */
436 ++npreloads;
438 if (runp != NULL)
439 runp += strspn (runp, ": \t\n");
443 if (problem != NULL)
445 char *p = strndupa (problem, file_size - (problem - file));
446 struct link_map *new_map = _dl_map_object (l, p, 1,
447 lt_library, 0);
448 if (new_map->l_opencount == 1)
449 /* It is no duplicate. */
450 ++npreloads;
453 /* We don't need the file anymore. */
454 __munmap (file, file_size);
457 if (npreloads != 0)
459 /* Set up PRELOADS with a vector of the preloaded libraries. */
460 struct link_map *l;
461 unsigned int i;
462 preloads = __alloca (npreloads * sizeof preloads[0]);
463 l = _dl_rtld_map.l_next; /* End of the chain before preloads. */
464 i = 0;
467 preloads[i++] = l;
468 l = l->l_next;
469 } while (l);
470 assert (i == npreloads);
473 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
474 specified some libraries to load, these are inserted before the actual
475 dependencies in the executable's searchlist for symbol resolution. */
476 _dl_map_object_deps (l, preloads, npreloads, mode == trace);
478 #ifndef MAP_ANON
479 /* We are done mapping things, so close the zero-fill descriptor. */
480 __close (_dl_zerofd);
481 _dl_zerofd = -1;
482 #endif
484 /* Remove _dl_rtld_map from the chain. */
485 _dl_rtld_map.l_prev->l_next = _dl_rtld_map.l_next;
486 if (_dl_rtld_map.l_next)
487 _dl_rtld_map.l_next->l_prev = _dl_rtld_map.l_prev;
489 if (_dl_rtld_map.l_opencount)
491 /* Some DT_NEEDED entry referred to the interpreter object itself, so
492 put it back in the list of visible objects. We insert it into the
493 chain in symbol search order because gdb uses the chain's order as
494 its symbol search order. */
495 unsigned int i = 1;
496 while (l->l_searchlist[i] != &_dl_rtld_map)
497 ++i;
498 _dl_rtld_map.l_prev = l->l_searchlist[i - 1];
499 _dl_rtld_map.l_next = (i + 1 < l->l_nsearchlist ?
500 l->l_searchlist[i + 1] : NULL);
501 assert (_dl_rtld_map.l_prev->l_next == _dl_rtld_map.l_next);
502 _dl_rtld_map.l_prev->l_next = &_dl_rtld_map;
503 if (_dl_rtld_map.l_next)
505 assert (_dl_rtld_map.l_next->l_prev == _dl_rtld_map.l_prev);
506 _dl_rtld_map.l_next->l_prev = &_dl_rtld_map;
510 if (mode != normal)
512 /* We were run just to list the shared libraries. It is
513 important that we do this before real relocation, because the
514 functions we call below for output may no longer work properly
515 after relocation. */
517 int i;
519 if (! _dl_loaded->l_info[DT_NEEDED])
520 _dl_sysdep_message ("\t", "statically linked\n", NULL);
521 else
522 for (l = _dl_loaded->l_next; l; l = l->l_next)
523 if (l->l_opencount == 0)
524 /* The library was not found. */
525 _dl_sysdep_message ("\t", l->l_libname, " => not found\n", NULL);
526 else
528 char buf[20], *bp;
529 buf[sizeof buf - 1] = '\0';
530 bp = _itoa (l->l_addr, &buf[sizeof buf - 1], 16, 0);
531 while ((size_t) (&buf[sizeof buf - 1] - bp)
532 < sizeof l->l_addr * 2)
533 *--bp = '0';
534 _dl_sysdep_message ("\t", l->l_libname, " => ", l->l_name,
535 " (0x", bp, ")\n", NULL);
538 if (mode != trace)
539 for (i = 1; i < _dl_argc; ++i)
541 const ElfW(Sym) *ref = NULL;
542 ElfW(Addr) loadbase = _dl_lookup_symbol (_dl_argv[i], &ref,
543 &_dl_default_scope[2],
544 "argument",
545 DL_LOOKUP_NOPLT);
546 char buf[20], *bp;
547 buf[sizeof buf - 1] = '\0';
548 bp = _itoa (ref->st_value, &buf[sizeof buf - 1], 16, 0);
549 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
550 *--bp = '0';
551 _dl_sysdep_message (_dl_argv[i], " found at 0x", bp, NULL);
552 buf[sizeof buf - 1] = '\0';
553 bp = _itoa (loadbase, &buf[sizeof buf - 1], 16, 0);
554 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
555 *--bp = '0';
556 _dl_sysdep_message (" in object at 0x", bp, "\n", NULL);
558 else if (lazy >= 0)
560 /* We have to do symbol dependency testing. */
561 void doit (void)
563 _dl_relocate_object (l, _dl_object_relocation_scope (l), lazy);
566 l = _dl_loaded;
567 while (l->l_next)
568 l = l->l_next;
571 if (l != &_dl_rtld_map && l->l_opencount > 0)
573 _dl_receive_error (print_unresolved, doit);
574 *_dl_global_scope_end = NULL;
576 l = l->l_prev;
577 } while (l);
580 _exit (0);
584 /* Now we have all the objects loaded. Relocate them all except for
585 the dynamic linker itself. We do this in reverse order so that copy
586 relocs of earlier objects overwrite the data written by later
587 objects. We do not re-relocate the dynamic linker itself in this
588 loop because that could result in the GOT entries for functions we
589 call being changed, and that would break us. It is safe to relocate
590 the dynamic linker out of order because it has no copy relocs (we
591 know that because it is self-contained). */
593 l = _dl_loaded;
594 while (l->l_next)
595 l = l->l_next;
598 if (l != &_dl_rtld_map)
600 _dl_relocate_object (l, _dl_object_relocation_scope (l), lazy);
601 *_dl_global_scope_end = NULL;
603 l = l->l_prev;
604 } while (l);
606 /* Do any necessary cleanups for the startup OS interface code.
607 We do these now so that no calls are made after rtld re-relocation
608 which might be resolved to different functions than we expect.
609 We cannot do this before relocating the other objects because
610 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
611 _dl_sysdep_start_cleanup ();
613 if (_dl_rtld_map.l_opencount > 0)
614 /* There was an explicit ref to the dynamic linker as a shared lib.
615 Re-relocate ourselves with user-controlled symbol definitions. */
616 _dl_relocate_object (&_dl_rtld_map, &_dl_default_scope[2], 0);
620 /* Initialize _r_debug. */
621 struct r_debug *r = _dl_debug_initialize (_dl_rtld_map.l_addr);
623 l = _dl_loaded;
625 #ifdef ELF_MACHINE_DEBUG_SETUP
627 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
629 ELF_MACHINE_DEBUG_SETUP (l, r);
630 ELF_MACHINE_DEBUG_SETUP (&_dl_rtld_map, r);
632 #else
634 if (l->l_info[DT_DEBUG])
635 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
636 with the run-time address of the r_debug structure */
637 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
639 /* Fill in the pointer in the dynamic linker's own dynamic section, in
640 case you run gdb on the dynamic linker directly. */
641 if (_dl_rtld_map.l_info[DT_DEBUG])
642 _dl_rtld_map.l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
644 #endif
646 /* Notify the debugger that all objects are now mapped in. */
647 r->r_state = RT_ADD;
648 _dl_debug_state ();
651 /* Once we return, _dl_sysdep_start will invoke
652 the DT_INIT functions and then *USER_ENTRY. */
655 /* This is a little helper function for resolving symbols while
656 tracing the binary. */
657 static void
658 print_unresolved (const char *errstring, const char *objname)
660 _dl_sysdep_error (errstring, " (", objname, ")\n", NULL);