Update to 2.1.x development version
[glibc.git] / elf / rtld.c
blob26cacef89454804b5f04d8eba9de8331649f427e
1 /* Run time dynamic linker.
2 Copyright (C) 1995, 1996, 1997 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 (int errcode, const char *objname,
49 const char *errsting);
51 /* Helper function to handle errors when a version is missing. */
52 static void print_missing_version (int errcode, const char *objname,
53 const char *errsting);
56 int _dl_argc;
57 char **_dl_argv;
58 const char *_dl_rpath;
60 /* Set nonzero during loading and initialization of executable and
61 libraries, cleared before the executable's entry point runs. This
62 must not be initialized to nonzero, because the unused dynamic
63 linker loaded in for libc.so's "ld.so.1" dep will provide the
64 definition seen by libc.so's initializer; that value must be zero,
65 and will be since that dynamic linker's _dl_start and dl_main will
66 never be called. */
67 int _dl_starting_up;
69 static void dl_main (const ElfW(Phdr) *phdr,
70 ElfW(Half) phent,
71 ElfW(Addr) *user_entry);
73 struct link_map _dl_rtld_map;
74 struct libname_list _dl_rtld_libname;
76 #ifdef RTLD_START
77 RTLD_START
78 #else
79 #error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
80 #endif
82 ElfW(Addr)
83 _dl_start (void *arg)
85 struct link_map bootstrap_map;
87 /* This #define produces dynamic linking inline functions for
88 bootstrap relocation instead of general-purpose relocation. */
89 #define RTLD_BOOTSTRAP
90 #define RESOLVE(sym, version, flags) bootstrap_map.l_addr
91 #include "dynamic-link.h"
93 /* Figure out the run-time load address of the dynamic linker itself. */
94 bootstrap_map.l_addr = elf_machine_load_address ();
96 /* Read our own dynamic section and fill in the info array. */
97 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
98 elf_get_dynamic_info (bootstrap_map.l_ld, bootstrap_map.l_info);
100 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
101 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
102 #endif
104 /* Relocate ourselves so we can do normal function calls and
105 data access using the global offset table. */
107 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0);
110 /* Now life is sane; we can call functions and access global data.
111 Set up to use the operating system facilities, and find out from
112 the operating system's program loader where to find the program
113 header table in core. */
116 /* Transfer data about ourselves to the permanent link_map structure. */
117 _dl_rtld_map.l_addr = bootstrap_map.l_addr;
118 _dl_rtld_map.l_ld = bootstrap_map.l_ld;
119 memcpy (_dl_rtld_map.l_info, bootstrap_map.l_info,
120 sizeof _dl_rtld_map.l_info);
121 _dl_setup_hash (&_dl_rtld_map);
123 /* Cache the DT_RPATH stored in ld.so itself; this will be
124 the default search path. */
125 _dl_rpath = (void *) (_dl_rtld_map.l_addr +
126 _dl_rtld_map.l_info[DT_STRTAB]->d_un.d_ptr +
127 _dl_rtld_map.l_info[DT_RPATH]->d_un.d_val);
129 /* Call the OS-dependent function to set up life so we can do things like
130 file access. It will call `dl_main' (below) to do all the real work
131 of the dynamic linker, and then unwind our frame and run the user
132 entry point on the same stack we entered on. */
133 return _dl_sysdep_start (arg, &dl_main);
137 /* Now life is peachy; we can do all normal operations.
138 On to the real work. */
140 void _start (void);
142 unsigned int _dl_skip_args; /* Nonzero if we were run directly. */
144 static void
145 dl_main (const ElfW(Phdr) *phdr,
146 ElfW(Half) phent,
147 ElfW(Addr) *user_entry)
149 const ElfW(Phdr) *ph;
150 struct link_map *l;
151 int lazy;
152 enum { normal, list, verify, trace } mode;
153 struct link_map **preloads;
154 unsigned int npreloads;
155 const char *preloadlist;
156 size_t file_size;
157 char *file;
159 mode = getenv ("LD_TRACE_LOADED_OBJECTS") != NULL ? trace : normal;
161 /* LAZY is determined by the parameters --datadeps and --function-deps
162 if we trace the binary. */
163 if (mode == trace)
164 lazy = (*(getenv ("LD_WARN") ?: "") == '\0' ? -1
165 : (*(getenv ("LD_BIND_NOW") ?: "") == '\0' ? 1 : 0));
166 else
167 lazy = !__libc_enable_secure && *(getenv ("LD_BIND_NOW") ?: "") == '\0';
169 /* Set up a flag which tells we are just starting. */
170 _dl_starting_up = 1;
172 if (*user_entry == (ElfW(Addr)) &_start)
174 /* Ho ho. We are not the program interpreter! We are the program
175 itself! This means someone ran ld.so as a command. Well, that
176 might be convenient to do sometimes. We support it by
177 interpreting the args like this:
179 ld.so PROGRAM ARGS...
181 The first argument is the name of a file containing an ELF
182 executable we will load and run with the following arguments.
183 To simplify life here, PROGRAM is searched for using the
184 normal rules for shared objects, rather than $PATH or anything
185 like that. We just load it and use its entry point; we don't
186 pay attention to its PT_INTERP command (we are the interpreter
187 ourselves). This is an easy way to test a new ld.so before
188 installing it. */
189 if (_dl_argc < 2)
190 _dl_sysdep_fatal ("\
191 Usage: ld.so [--list|--verify] EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
192 You have invoked `ld.so', the helper program for shared library executables.\n\
193 This program usually lives in the file `/lib/ld.so', and special directives\n\
194 in executable files using ELF shared libraries tell the system's program\n\
195 loader to load the helper program from this file. This helper program loads\n\
196 the shared libraries needed by the program executable, prepares the program\n\
197 to run, and runs it. You may invoke this helper program directly from the\n\
198 command line to load and run an ELF executable file; this is like executing\n\
199 that file itself, but always uses this helper program from the file you\n\
200 specified, instead of the helper program file specified in the executable\n\
201 file you run. This is mostly of use for maintainers to test new versions\n\
202 of this helper program; chances are you did not intend to run this program.\n",
203 NULL);
205 /* Note the place where the dynamic linker actually came from. */
206 _dl_rtld_map.l_name = _dl_argv[0];
208 while (_dl_argc > 1)
209 if (! strcmp (_dl_argv[1], "--list"))
211 mode = list;
212 lazy = -1; /* This means do no dependency analysis. */
214 ++_dl_skip_args;
215 --_dl_argc;
216 ++_dl_argv;
218 else if (! strcmp (_dl_argv[1], "--verify"))
220 mode = verify;
222 ++_dl_skip_args;
223 --_dl_argc;
224 ++_dl_argv;
226 else
227 break;
229 ++_dl_skip_args;
230 --_dl_argc;
231 ++_dl_argv;
233 if (mode == verify)
235 void doit (void)
237 l = _dl_map_object (NULL, _dl_argv[0], lt_library, 0);
239 char *err_str = NULL;
240 const char *obj_name __attribute__ ((unused));
242 (void) _dl_catch_error (&err_str, &obj_name, doit);
243 if (err_str != NULL)
245 free (err_str);
246 _exit (EXIT_FAILURE);
249 else
250 l = _dl_map_object (NULL, _dl_argv[0], lt_library, 0);
252 phdr = l->l_phdr;
253 phent = l->l_phnum;
254 l->l_name = (char *) "";
255 *user_entry = l->l_entry;
257 else
259 /* Create a link_map for the executable itself.
260 This will be what dlopen on "" returns. */
261 l = _dl_new_object ((char *) "", "", lt_executable);
262 if (l == NULL)
263 _dl_sysdep_fatal ("cannot allocate memory for link map", NULL);
264 l->l_phdr = phdr;
265 l->l_phnum = phent;
266 l->l_entry = *user_entry;
269 if (l != _dl_loaded)
271 /* GDB assumes that the first element on the chain is the
272 link_map for the executable itself, and always skips it.
273 Make sure the first one is indeed that one. */
274 l->l_prev->l_next = l->l_next;
275 if (l->l_next)
276 l->l_next->l_prev = l->l_prev;
277 l->l_prev = NULL;
278 l->l_next = _dl_loaded;
279 _dl_loaded->l_prev = l;
280 _dl_loaded = l;
283 /* Scan the program header table for the dynamic section. */
284 for (ph = phdr; ph < &phdr[phent]; ++ph)
285 switch (ph->p_type)
287 case PT_DYNAMIC:
288 /* This tells us where to find the dynamic section,
289 which tells us everything we need to do. */
290 l->l_ld = (void *) l->l_addr + ph->p_vaddr;
291 break;
292 case PT_INTERP:
293 /* This "interpreter segment" was used by the program loader to
294 find the program interpreter, which is this program itself, the
295 dynamic linker. We note what name finds us, so that a future
296 dlopen call or DT_NEEDED entry, for something that wants to link
297 against the dynamic linker as a shared library, will know that
298 the shared object is already loaded. */
299 _dl_rtld_libname.name = (const char *) l->l_addr + ph->p_vaddr;
300 _dl_rtld_libname.next = NULL;
301 _dl_rtld_map.l_libname = &_dl_rtld_libname;
302 break;
304 if (! _dl_rtld_map.l_libname && _dl_rtld_map.l_name)
306 /* We were invoked directly, so the program might not have a
307 PT_INTERP. */
308 _dl_rtld_libname.name = _dl_rtld_map.l_name;
309 _dl_rtld_libname.next = NULL;
310 _dl_rtld_map.l_libname = &_dl_rtld_libname;
312 else
313 assert (_dl_rtld_map.l_libname); /* How else did we get here? */
315 if (mode == verify)
316 /* We were called just to verify that this is a dynamic executable
317 using us as the program interpreter. */
318 _exit (l->l_ld == NULL ? EXIT_FAILURE : EXIT_SUCCESS);
320 /* Extract the contents of the dynamic section for easy access. */
321 elf_get_dynamic_info (l->l_ld, l->l_info);
322 if (l->l_info[DT_HASH])
323 /* Set up our cache of pointers into the hash table. */
324 _dl_setup_hash (l);
326 /* Put the link_map for ourselves on the chain so it can be found by
327 name. */
328 if (! _dl_rtld_map.l_name)
329 /* If not invoked directly, the dynamic linker shared object file was
330 found by the PT_INTERP name. */
331 _dl_rtld_map.l_name = (char *) _dl_rtld_map.l_libname->name;
332 _dl_rtld_map.l_type = lt_library;
333 while (l->l_next)
334 l = l->l_next;
335 l->l_next = &_dl_rtld_map;
336 _dl_rtld_map.l_prev = l;
338 /* We have two ways to specify objects to preload: via environment
339 variable and via the file /etc/ld.so.preload. The later can also
340 be used when security is enabled. */
341 preloads = NULL;
342 npreloads = 0;
344 preloadlist = getenv ("LD_PRELOAD");
345 if (preloadlist)
347 /* The LD_PRELOAD environment variable gives a white space
348 separated list of libraries that are loaded before the
349 executable's dependencies and prepended to the global scope
350 list. If the binary is running setuid all elements
351 containing a '/' are ignored since it is insecure. */
352 char *list = strdupa (preloadlist);
353 char *p;
354 while ((p = strsep (&list, " ")) != NULL)
355 if (! __libc_enable_secure || strchr (p, '/') == NULL)
357 (void) _dl_map_object (NULL, p, lt_library, 0);
358 ++npreloads;
362 /* Read the contents of the file. */
363 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
364 PROT_READ | PROT_WRITE);
365 if (file)
367 /* Parse the file. It contains names of libraries to be loaded,
368 separated by white spaces or `:'. It may also contain
369 comments introduced by `#'. */
370 char *problem;
371 char *runp;
372 size_t rest;
374 /* Eliminate comments. */
375 runp = file;
376 rest = file_size;
377 while (rest > 0)
379 char *comment = memchr (runp, '#', rest);
380 if (comment == NULL)
381 break;
383 rest -= comment - runp;
385 *comment = ' ';
386 while (--rest > 0 && *++comment != '\n');
389 /* We have one problematic case: if we have a name at the end of
390 the file without a trailing terminating characters, we cannot
391 place the \0. Handle the case separately. */
392 if (file[file_size - 1] != ' ' && file[file_size] != '\t'
393 && file[file_size] != '\n')
395 problem = &file[file_size];
396 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
397 && problem[-1] != '\n')
398 --problem;
400 if (problem > file)
401 problem[-1] = '\0';
403 else
404 problem = NULL;
406 if (file != problem)
408 char *p;
409 runp = file;
410 while ((p = strsep (&runp, ": \t\n")) != NULL)
412 (void) _dl_map_object (NULL, p, lt_library, 0);
413 ++npreloads;
417 if (problem != NULL)
419 char *p = strndupa (problem, file_size - (problem - file));
420 (void) _dl_map_object (NULL, p, lt_library, 0);
423 /* We don't need the file anymore. */
424 __munmap (file, file_size);
427 if (npreloads != 0)
429 /* Set up PRELOADS with a vector of the preloaded libraries. */
430 struct link_map *l;
431 unsigned int i;
432 preloads = __alloca (npreloads * sizeof preloads[0]);
433 l = _dl_rtld_map.l_next; /* End of the chain before preloads. */
434 i = 0;
437 preloads[i++] = l;
438 l = l->l_next;
439 } while (l);
440 assert (i == npreloads);
443 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
444 specified some libraries to load, these are inserted before the actual
445 dependencies in the executable's searchlist for symbol resolution. */
446 _dl_map_object_deps (l, preloads, npreloads, mode == trace);
448 #ifndef MAP_ANON
449 /* We are done mapping things, so close the zero-fill descriptor. */
450 __close (_dl_zerofd);
451 _dl_zerofd = -1;
452 #endif
454 /* Remove _dl_rtld_map from the chain. */
455 _dl_rtld_map.l_prev->l_next = _dl_rtld_map.l_next;
456 if (_dl_rtld_map.l_next)
457 _dl_rtld_map.l_next->l_prev = _dl_rtld_map.l_prev;
459 if (_dl_rtld_map.l_opencount)
461 /* Some DT_NEEDED entry referred to the interpreter object itself, so
462 put it back in the list of visible objects. We insert it into the
463 chain in symbol search order because gdb uses the chain's order as
464 its symbol search order. */
465 unsigned int i = 1;
466 while (l->l_searchlist[i] != &_dl_rtld_map)
467 ++i;
468 _dl_rtld_map.l_prev = l->l_searchlist[i - 1];
469 _dl_rtld_map.l_next = (i + 1 < l->l_nsearchlist ?
470 l->l_searchlist[i + 1] : NULL);
471 assert (_dl_rtld_map.l_prev->l_next == _dl_rtld_map.l_next);
472 _dl_rtld_map.l_prev->l_next = &_dl_rtld_map;
473 if (_dl_rtld_map.l_next)
475 assert (_dl_rtld_map.l_next->l_prev == _dl_rtld_map.l_prev);
476 _dl_rtld_map.l_next->l_prev = &_dl_rtld_map;
480 /* Now let us see whether all libraries are available in the
481 versions we need. */
483 void doit (void)
485 if (_dl_check_all_versions (l, 1) && mode == normal)
486 /* We cannot start the application. Abort now. */
487 _exit (1);
490 _dl_receive_error (print_missing_version, doit);
493 if (mode != normal)
495 /* We were run just to list the shared libraries. It is
496 important that we do this before real relocation, because the
497 functions we call below for output may no longer work properly
498 after relocation. */
500 int i;
502 if (! _dl_loaded->l_info[DT_NEEDED])
503 _dl_sysdep_message ("\t", "statically linked\n", NULL);
504 else
505 for (l = _dl_loaded->l_next; l; l = l->l_next)
506 if (l->l_opencount == 0)
507 /* The library was not found. */
508 _dl_sysdep_message ("\t", l->l_libname->name, " => not found\n",
509 NULL);
510 else
512 char buf[20], *bp;
513 buf[sizeof buf - 1] = '\0';
514 bp = _itoa (l->l_addr, &buf[sizeof buf - 1], 16, 0);
515 while ((size_t) (&buf[sizeof buf - 1] - bp)
516 < sizeof l->l_addr * 2)
517 *--bp = '0';
518 _dl_sysdep_message ("\t", l->l_libname->name, " => ", l->l_name,
519 " (0x", bp, ")\n", NULL);
522 if (mode != trace)
523 for (i = 1; i < _dl_argc; ++i)
525 const ElfW(Sym) *ref = NULL;
526 ElfW(Addr) loadbase = _dl_lookup_symbol (_dl_argv[i], &ref,
527 &_dl_default_scope[2],
528 "argument",
529 DL_LOOKUP_NOPLT);
530 char buf[20], *bp;
531 buf[sizeof buf - 1] = '\0';
532 bp = _itoa (ref->st_value, &buf[sizeof buf - 1], 16, 0);
533 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
534 *--bp = '0';
535 _dl_sysdep_message (_dl_argv[i], " found at 0x", bp, NULL);
536 buf[sizeof buf - 1] = '\0';
537 bp = _itoa (loadbase, &buf[sizeof buf - 1], 16, 0);
538 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
539 *--bp = '0';
540 _dl_sysdep_message (" in object at 0x", bp, "\n", NULL);
542 else if (lazy >= 0)
544 /* We have to do symbol dependency testing. */
545 void doit (void)
547 _dl_relocate_object (l, _dl_object_relocation_scope (l), lazy);
550 l = _dl_loaded;
551 while (l->l_next)
552 l = l->l_next;
555 if (l != &_dl_rtld_map && l->l_opencount > 0)
557 _dl_receive_error (print_unresolved, doit);
558 *_dl_global_scope_end = NULL;
560 l = l->l_prev;
561 } while (l);
564 _exit (0);
568 /* Now we have all the objects loaded. Relocate them all except for
569 the dynamic linker itself. We do this in reverse order so that copy
570 relocs of earlier objects overwrite the data written by later
571 objects. We do not re-relocate the dynamic linker itself in this
572 loop because that could result in the GOT entries for functions we
573 call being changed, and that would break us. It is safe to relocate
574 the dynamic linker out of order because it has no copy relocs (we
575 know that because it is self-contained). */
577 l = _dl_loaded;
578 while (l->l_next)
579 l = l->l_next;
582 if (l != &_dl_rtld_map)
584 _dl_relocate_object (l, _dl_object_relocation_scope (l), lazy);
585 *_dl_global_scope_end = NULL;
587 l = l->l_prev;
588 } while (l);
590 /* Do any necessary cleanups for the startup OS interface code.
591 We do these now so that no calls are made after rtld re-relocation
592 which might be resolved to different functions than we expect.
593 We cannot do this before relocating the other objects because
594 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
595 _dl_sysdep_start_cleanup ();
597 if (_dl_rtld_map.l_opencount > 0)
598 /* There was an explicit ref to the dynamic linker as a shared lib.
599 Re-relocate ourselves with user-controlled symbol definitions. */
600 _dl_relocate_object (&_dl_rtld_map, &_dl_default_scope[2], 0);
604 /* Initialize _r_debug. */
605 struct r_debug *r = _dl_debug_initialize (_dl_rtld_map.l_addr);
607 l = _dl_loaded;
609 #ifdef ELF_MACHINE_DEBUG_SETUP
611 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
613 ELF_MACHINE_DEBUG_SETUP (l, r);
614 ELF_MACHINE_DEBUG_SETUP (&_dl_rtld_map, r);
616 #else
618 if (l->l_info[DT_DEBUG])
619 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
620 with the run-time address of the r_debug structure */
621 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
623 /* Fill in the pointer in the dynamic linker's own dynamic section, in
624 case you run gdb on the dynamic linker directly. */
625 if (_dl_rtld_map.l_info[DT_DEBUG])
626 _dl_rtld_map.l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
628 #endif
630 /* Notify the debugger that all objects are now mapped in. */
631 r->r_state = RT_ADD;
632 _dl_debug_state ();
635 /* Once we return, _dl_sysdep_start will invoke
636 the DT_INIT functions and then *USER_ENTRY. */
639 /* This is a little helper function for resolving symbols while
640 tracing the binary. */
641 static void
642 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
643 const char *errstring)
645 _dl_sysdep_error (errstring, " (", objname, ")\n", NULL);
648 /* This is a little helper function for resolving symbols while
649 tracing the binary. */
650 static void
651 print_missing_version (int errcode __attribute__ ((unused)),
652 const char *objname, const char *errstring)
654 _dl_sysdep_error (_dl_argv[0] ?: "<program name unknown>", ": ",
655 objname, ": ", errstring, "\n", NULL);