Update.
[glibc.git] / elf / rtld.c
blobdf6a945105893bbaee674e98e8dd799275db26df
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 <fcntl.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <sys/mman.h> /* Check if MAP_ANON is defined. */
25 #include <elf/ldsodefs.h>
26 #include <stdio-common/_itoa.h>
27 #include <entry.h>
28 #include <fpu_control.h>
29 #include <hp-timing.h>
30 #include "dynamic-link.h"
31 #include "dl-librecon.h"
33 #include <assert.h>
35 /* System-specific function to do initial startup for the dynamic linker.
36 After this, file access calls and getenv must work. This is responsible
37 for setting __libc_enable_secure if we need to be secure (e.g. setuid),
38 and for setting _dl_argc and _dl_argv, and then calling _dl_main. */
39 extern ElfW(Addr) _dl_sysdep_start (void **start_argptr,
40 void (*dl_main) (const ElfW(Phdr) *phdr,
41 ElfW(Half) phent,
42 ElfW(Addr) *user_entry));
43 extern void _dl_sysdep_start_cleanup (void);
45 /* This function is used to unload the cache file if necessary. */
46 extern void _dl_unload_cache (void);
48 /* System-dependent function to read a file's whole contents
49 in the most convenient manner available. */
50 extern void *_dl_sysdep_read_whole_file (const char *filename,
51 size_t *filesize_ptr,
52 int mmap_prot);
54 /* Helper function to handle errors while resolving symbols. */
55 static void print_unresolved (int errcode, const char *objname,
56 const char *errsting);
58 /* Helper function to handle errors when a version is missing. */
59 static void print_missing_version (int errcode, const char *objname,
60 const char *errsting);
62 /* Print the various times we collected. */
63 static void print_statistics (void);
65 /* This is a list of all the modes the dynamic loader can be in. */
66 enum mode { normal, list, verify, trace };
68 /* Process all environments variables the dynamic linker must recognize.
69 Since all of them start with `LD_' we are a bit smarter while finding
70 all the entries. */
71 static void process_envvars (enum mode *modep, int *lazyp);
73 int _dl_argc;
74 char **_dl_argv;
75 unsigned int _dl_skip_args; /* Nonzero if we were run directly. */
76 int _dl_verbose;
77 const char *_dl_platform;
78 size_t _dl_platformlen;
79 unsigned long _dl_hwcap;
80 fpu_control_t _dl_fpu_control = _FPU_DEFAULT;
81 struct r_search_path *_dl_search_paths;
82 const char *_dl_profile;
83 const char *_dl_profile_output;
84 struct link_map *_dl_profile_map;
85 int _dl_debug_libs;
86 int _dl_debug_impcalls;
87 int _dl_debug_bindings;
88 int _dl_debug_symbols;
89 int _dl_debug_versions;
90 int _dl_debug_reloc;
91 int _dl_debug_files;
92 int _dl_debug_statistics;
93 const char *_dl_inhibit_rpath; /* RPATH values which should be
94 ignored. */
95 const char *_dl_origin_path;
97 /* This is a pointer to the map for the main object and through it to
98 all loaded objects. */
99 struct link_map *_dl_loaded;
100 /* Pointer to the l_searchlist element of the link map of the main object. */
101 struct r_scope_elem *_dl_main_searchlist;
102 /* Copy of the content of `_dl_main_searchlist'. */
103 struct r_scope_elem _dl_initial_searchlist;
104 /* Array which is used when looking up in the global scope. */
105 struct r_scope_elem *_dl_global_scope[2];
107 /* Set nonzero during loading and initialization of executable and
108 libraries, cleared before the executable's entry point runs. This
109 must not be initialized to nonzero, because the unused dynamic
110 linker loaded in for libc.so's "ld.so.1" dep will provide the
111 definition seen by libc.so's initializer; that value must be zero,
112 and will be since that dynamic linker's _dl_start and dl_main will
113 never be called. */
114 int _dl_starting_up;
117 static void dl_main (const ElfW(Phdr) *phdr,
118 ElfW(Half) phent,
119 ElfW(Addr) *user_entry);
121 struct link_map _dl_rtld_map;
122 struct libname_list _dl_rtld_libname;
123 struct libname_list _dl_rtld_libname2;
125 /* Variable for statistics. */
126 static hp_timing_t rtld_total_time;
127 static hp_timing_t relocate_time;
128 static hp_timing_t load_time;
129 extern unsigned long int _dl_num_relocations; /* in dl-lookup.c */
131 #ifdef RTLD_START
132 RTLD_START
133 #else
134 #error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
135 #endif
137 static ElfW(Addr)
138 _dl_start (void *arg)
140 struct link_map bootstrap_map;
141 hp_timing_t start_time;
142 ElfW(Addr) start_addr;
144 /* This #define produces dynamic linking inline functions for
145 bootstrap relocation instead of general-purpose relocation. */
146 #define RTLD_BOOTSTRAP
147 #define RESOLVE(sym, version, flags) \
148 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : bootstrap_map.l_addr)
149 #include "dynamic-link.h"
151 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
152 HP_TIMING_NOW (start_time);
154 /* Figure out the run-time load address of the dynamic linker itself. */
155 bootstrap_map.l_addr = elf_machine_load_address ();
157 /* Read our own dynamic section and fill in the info array. */
158 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
159 elf_get_dynamic_info (bootstrap_map.l_ld, bootstrap_map.l_info);
161 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
162 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
163 #endif
165 /* Relocate ourselves so we can do normal function calls and
166 data access using the global offset table. */
168 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
169 /* Please note that we don't allow profiling of this object and
170 therefore need not test whether we have to allocate the array
171 for the relocation results (as done in dl-reloc.c). */
173 /* Now life is sane; we can call functions and access global data.
174 Set up to use the operating system facilities, and find out from
175 the operating system's program loader where to find the program
176 header table in core. */
178 if (HP_TIMING_AVAIL)
180 /* If it hasn't happen yet record the startup time. */
181 if (! HP_TIMING_INLINE)
182 HP_TIMING_NOW (start_time);
184 /* Initialize the timing functions. */
185 HP_TIMING_DIFF_INIT ();
188 /* Transfer data about ourselves to the permanent link_map structure. */
189 _dl_rtld_map.l_addr = bootstrap_map.l_addr;
190 _dl_rtld_map.l_ld = bootstrap_map.l_ld;
191 _dl_rtld_map.l_opencount = 1;
192 memcpy (_dl_rtld_map.l_info, bootstrap_map.l_info,
193 sizeof _dl_rtld_map.l_info);
194 _dl_setup_hash (&_dl_rtld_map);
196 /* Don't bother trying to work out how ld.so is mapped in memory. */
197 _dl_rtld_map.l_map_start = ~0;
198 _dl_rtld_map.l_map_end = ~0;
200 /* Call the OS-dependent function to set up life so we can do things like
201 file access. It will call `dl_main' (below) to do all the real work
202 of the dynamic linker, and then unwind our frame and run the user
203 entry point on the same stack we entered on. */
204 start_addr = _dl_sysdep_start (arg, &dl_main);
206 if (HP_TIMING_AVAIL)
208 hp_timing_t end_time;
210 /* Get the current time. */
211 HP_TIMING_NOW (end_time);
213 /* Compute the difference. */
214 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
217 if (_dl_debug_statistics)
218 print_statistics ();
220 return start_addr;
223 /* Now life is peachy; we can do all normal operations.
224 On to the real work. */
226 void ENTRY_POINT (void);
228 /* Some helper functions. */
230 /* Arguments to relocate_doit. */
231 struct relocate_args
233 struct link_map *l;
234 int lazy;
237 struct map_args
239 /* Argument to map_doit. */
240 char *str;
241 /* Return value of map_doit. */
242 struct link_map *main_map;
245 /* Arguments to version_check_doit. */
246 struct version_check_args
248 int doexit;
251 static void
252 relocate_doit (void *a)
254 struct relocate_args *args = (struct relocate_args *) a;
256 _dl_relocate_object (args->l, args->l->l_scope,
257 args->lazy, 0);
260 static void
261 map_doit (void *a)
263 struct map_args *args = (struct map_args *) a;
264 args->main_map = _dl_map_object (NULL, args->str, 0, lt_library, 0);
267 static void
268 version_check_doit (void *a)
270 struct version_check_args *args = (struct version_check_args *) a;
271 if (_dl_check_all_versions (_dl_loaded, 1) && args->doexit)
272 /* We cannot start the application. Abort now. */
273 _exit (1);
277 static inline struct link_map *
278 find_needed (const char *name)
280 unsigned int n = _dl_loaded->l_searchlist.r_nlist;
282 while (n-- > 0)
283 if (_dl_name_match_p (name, _dl_loaded->l_searchlist.r_list[n]))
284 return _dl_loaded->l_searchlist.r_list[n];
286 /* Should never happen. */
287 return NULL;
290 static int
291 match_version (const char *string, struct link_map *map)
293 const char *strtab = (const char *) (map->l_addr
294 + map->l_info[DT_STRTAB]->d_un.d_ptr);
295 ElfW(Verdef) *def;
297 #define VERDEFTAG (DT_NUM + DT_PROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
298 if (map->l_info[VERDEFTAG] == NULL)
299 /* The file has no symbol versioning. */
300 return 0;
302 def = (ElfW(Verdef) *) ((char *) map->l_addr
303 + map->l_info[VERDEFTAG]->d_un.d_ptr);
304 while (1)
306 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
308 /* Compare the version strings. */
309 if (strcmp (string, strtab + aux->vda_name) == 0)
310 /* Bingo! */
311 return 1;
313 /* If no more definitions we failed to find what we want. */
314 if (def->vd_next == 0)
315 break;
317 /* Next definition. */
318 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
321 return 0;
324 static const char *library_path; /* The library search path. */
325 static const char *preloadlist; /* The list preloaded objects. */
326 static int version_info; /* Nonzero if information about
327 versions has to be printed. */
329 static void
330 dl_main (const ElfW(Phdr) *phdr,
331 ElfW(Half) phent,
332 ElfW(Addr) *user_entry)
334 const ElfW(Phdr) *ph;
335 int lazy;
336 enum mode mode;
337 struct link_map **preloads;
338 unsigned int npreloads;
339 size_t file_size;
340 char *file;
341 int has_interp = 0;
342 unsigned int i;
343 int paths_initialized = 0;
344 hp_timing_t start;
345 hp_timing_t stop;
346 hp_timing_t diff;
348 /* Process the environment variable which control the behaviour. */
349 process_envvars (&mode, &lazy);
351 /* Set up a flag which tells we are just starting. */
352 _dl_starting_up = 1;
354 if (*user_entry == (ElfW(Addr)) &ENTRY_POINT)
356 /* Ho ho. We are not the program interpreter! We are the program
357 itself! This means someone ran ld.so as a command. Well, that
358 might be convenient to do sometimes. We support it by
359 interpreting the args like this:
361 ld.so PROGRAM ARGS...
363 The first argument is the name of a file containing an ELF
364 executable we will load and run with the following arguments.
365 To simplify life here, PROGRAM is searched for using the
366 normal rules for shared objects, rather than $PATH or anything
367 like that. We just load it and use its entry point; we don't
368 pay attention to its PT_INTERP command (we are the interpreter
369 ourselves). This is an easy way to test a new ld.so before
370 installing it. */
372 /* Note the place where the dynamic linker actually came from. */
373 _dl_rtld_map.l_name = _dl_argv[0];
375 while (_dl_argc > 1)
376 if (! strcmp (_dl_argv[1], "--list"))
378 mode = list;
379 lazy = -1; /* This means do no dependency analysis. */
381 ++_dl_skip_args;
382 --_dl_argc;
383 ++_dl_argv;
385 else if (! strcmp (_dl_argv[1], "--verify"))
387 mode = verify;
389 ++_dl_skip_args;
390 --_dl_argc;
391 ++_dl_argv;
393 else if (! strcmp (_dl_argv[1], "--library-path") && _dl_argc > 2)
395 library_path = _dl_argv[2];
397 _dl_skip_args += 2;
398 _dl_argc -= 2;
399 _dl_argv += 2;
401 else if (! strcmp (_dl_argv[1], "--inhibit-rpath") && _dl_argc > 2)
403 _dl_inhibit_rpath = _dl_argv[2];
405 _dl_skip_args += 2;
406 _dl_argc -= 2;
407 _dl_argv += 2;
409 else
410 break;
412 /* If we have no further argument the program was called incorrectly.
413 Grant the user some education. */
414 if (_dl_argc < 2)
415 _dl_sysdep_fatal ("\
416 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
417 You have invoked `ld.so', the helper program for shared library executables.\n\
418 This program usually lives in the file `/lib/ld.so', and special directives\n\
419 in executable files using ELF shared libraries tell the system's program\n\
420 loader to load the helper program from this file. This helper program loads\n\
421 the shared libraries needed by the program executable, prepares the program\n\
422 to run, and runs it. You may invoke this helper program directly from the\n\
423 command line to load and run an ELF executable file; this is like executing\n\
424 that file itself, but always uses this helper program from the file you\n\
425 specified, instead of the helper program file specified in the executable\n\
426 file you run. This is mostly of use for maintainers to test new versions\n\
427 of this helper program; chances are you did not intend to run this program.\n\
429 --list list all dependencies and how they are resolved\n\
430 --verify verify that given object really is a dynamically linked\n\
431 object we get handle\n\
432 --library-path PATH use given PATH instead of content of the environment\n\
433 variable LD_LIBRARY_PATH\n\
434 --inhibit-rpath LIST ignore RPATH information in object names in LIST\n",
435 NULL);
437 ++_dl_skip_args;
438 --_dl_argc;
439 ++_dl_argv;
441 /* Initialize the data structures for the search paths for shared
442 objects. */
443 _dl_init_paths (library_path);
444 paths_initialized = 1;
446 if (__builtin_expect (mode, normal) == verify)
448 char *err_str = NULL;
449 struct map_args args;
451 args.str = _dl_argv[0];
452 (void) _dl_catch_error (&err_str, map_doit, &args);
453 if (err_str != NULL)
455 free (err_str);
456 _exit (EXIT_FAILURE);
459 else
461 HP_TIMING_NOW (start);
462 _dl_map_object (NULL, _dl_argv[0], 0, lt_library, 0);
463 HP_TIMING_NOW (stop);
465 HP_TIMING_DIFF (load_time, start, stop);
468 phdr = _dl_loaded->l_phdr;
469 phent = _dl_loaded->l_phnum;
470 /* We overwrite here a pointer to a malloc()ed string. But since
471 the malloc() implementation used at this point is the dummy
472 implementations which has no real free() function it does not
473 makes sense to free the old string first. */
474 _dl_loaded->l_name = (char *) "";
475 *user_entry = _dl_loaded->l_entry;
477 else
479 /* Create a link_map for the executable itself.
480 This will be what dlopen on "" returns. */
481 _dl_new_object ((char *) "", "", lt_executable, NULL);
482 if (_dl_loaded == NULL)
483 _dl_sysdep_fatal ("cannot allocate memory for link map\n", NULL);
484 _dl_loaded->l_phdr = phdr;
485 _dl_loaded->l_phnum = phent;
486 _dl_loaded->l_entry = *user_entry;
487 _dl_loaded->l_opencount = 1;
489 /* We delay initializing the path structure until we got the dynamic
490 information for the program. */
493 /* It is not safe to load stuff after the main program. */
494 _dl_loaded->l_map_end = ~0;
495 /* Perhaps the executable has no PT_LOAD header entries at all. */
496 _dl_loaded->l_map_start = ~0;
498 /* Scan the program header table for the dynamic section. */
499 for (ph = phdr; ph < &phdr[phent]; ++ph)
500 switch (ph->p_type)
502 case PT_PHDR:
503 /* Find out the load address. */
504 _dl_loaded->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
505 break;
506 case PT_DYNAMIC:
507 /* This tells us where to find the dynamic section,
508 which tells us everything we need to do. */
509 _dl_loaded->l_ld = (void *) _dl_loaded->l_addr + ph->p_vaddr;
510 break;
511 case PT_INTERP:
512 /* This "interpreter segment" was used by the program loader to
513 find the program interpreter, which is this program itself, the
514 dynamic linker. We note what name finds us, so that a future
515 dlopen call or DT_NEEDED entry, for something that wants to link
516 against the dynamic linker as a shared library, will know that
517 the shared object is already loaded. */
518 _dl_rtld_libname.name = ((const char *) _dl_loaded->l_addr
519 + ph->p_vaddr);
520 _dl_rtld_libname.next = NULL;
521 _dl_rtld_map.l_libname = &_dl_rtld_libname;
523 /* Ordinarilly, we would get additional names for the loader from
524 our DT_SONAME. This can't happen if we were actually linked as
525 a static executable (detect this case when we have no DYNAMIC).
526 If so, assume the filename component of the interpreter path to
527 be our SONAME, and add it to our name list. */
528 if (_dl_rtld_map.l_ld == NULL)
530 char *p = strrchr (_dl_rtld_libname.name, '/');
531 if (p)
533 _dl_rtld_libname2.name = p+1;
534 _dl_rtld_libname2.next = NULL;
535 _dl_rtld_libname.next = &_dl_rtld_libname2;
539 has_interp = 1;
540 break;
541 case PT_LOAD:
542 /* Remember where the main program starts in memory. */
544 ElfW(Addr) mapstart;
545 mapstart = _dl_loaded->l_addr + (ph->p_vaddr & ~(ph->p_align - 1));
546 if (_dl_loaded->l_map_start > mapstart)
547 _dl_loaded->l_map_start = mapstart;
549 break;
551 if (! _dl_rtld_map.l_libname && _dl_rtld_map.l_name)
553 /* We were invoked directly, so the program might not have a
554 PT_INTERP. */
555 _dl_rtld_libname.name = _dl_rtld_map.l_name;
556 _dl_rtld_libname.next = NULL;
557 _dl_rtld_map.l_libname = &_dl_rtld_libname;
559 else
560 assert (_dl_rtld_map.l_libname); /* How else did we get here? */
562 /* Extract the contents of the dynamic section for easy access. */
563 elf_get_dynamic_info (_dl_loaded->l_ld, _dl_loaded->l_info);
564 if (_dl_loaded->l_info[DT_HASH])
565 /* Set up our cache of pointers into the hash table. */
566 _dl_setup_hash (_dl_loaded);
568 if (__builtin_expect (mode, normal) == verify)
570 /* We were called just to verify that this is a dynamic
571 executable using us as the program interpreter. Exit with an
572 error if we were not able to load the binary or no interpreter
573 is specified (i.e., this is no dynamically linked binary. */
574 if (_dl_loaded->l_ld == NULL)
575 _exit (1);
577 /* We allow here some platform specific code. */
578 #ifdef DISTINGUISH_LIB_VERSIONS
579 DISTINGUISH_LIB_VERSIONS;
580 #endif
581 _exit (has_interp ? 0 : 2);
584 if (! paths_initialized)
585 /* Initialize the data structures for the search paths for shared
586 objects. */
587 _dl_init_paths (library_path);
589 /* Put the link_map for ourselves on the chain so it can be found by
590 name. Note that at this point the global chain of link maps contains
591 exactly one element, which is pointed to by _dl_loaded. */
592 if (! _dl_rtld_map.l_name)
593 /* If not invoked directly, the dynamic linker shared object file was
594 found by the PT_INTERP name. */
595 _dl_rtld_map.l_name = (char *) _dl_rtld_map.l_libname->name;
596 _dl_rtld_map.l_type = lt_library;
597 _dl_loaded->l_next = &_dl_rtld_map;
598 _dl_rtld_map.l_prev = _dl_loaded;
600 /* We have two ways to specify objects to preload: via environment
601 variable and via the file /etc/ld.so.preload. The later can also
602 be used when security is enabled. */
603 preloads = NULL;
604 npreloads = 0;
606 if (preloadlist)
608 /* The LD_PRELOAD environment variable gives list of libraries
609 separated by white space or colons that are loaded before the
610 executable's dependencies and prepended to the global scope
611 list. If the binary is running setuid all elements
612 containing a '/' are ignored since it is insecure. */
613 char *list = strdupa (preloadlist);
614 char *p;
616 HP_TIMING_NOW (start);
618 while ((p = strsep (&list, " :")) != NULL)
619 if (p[0] != '\0'
620 && (! __libc_enable_secure || strchr (p, '/') == NULL))
622 struct link_map *new_map = _dl_map_object (_dl_loaded, p, 1,
623 lt_library, 0);
624 if (new_map->l_opencount == 1)
625 /* It is no duplicate. */
626 ++npreloads;
629 HP_TIMING_NOW (stop);
630 HP_TIMING_DIFF (diff, start, stop);
631 HP_TIMING_ACCUM_NT (load_time, diff);
634 /* Read the contents of the file. */
635 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
636 PROT_READ | PROT_WRITE);
637 if (file)
639 /* Parse the file. It contains names of libraries to be loaded,
640 separated by white spaces or `:'. It may also contain
641 comments introduced by `#'. */
642 char *problem;
643 char *runp;
644 size_t rest;
646 /* Eliminate comments. */
647 runp = file;
648 rest = file_size;
649 while (rest > 0)
651 char *comment = memchr (runp, '#', rest);
652 if (comment == NULL)
653 break;
655 rest -= comment - runp;
657 *comment = ' ';
658 while (--rest > 0 && *++comment != '\n');
661 /* We have one problematic case: if we have a name at the end of
662 the file without a trailing terminating characters, we cannot
663 place the \0. Handle the case separately. */
664 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
665 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
667 problem = &file[file_size];
668 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
669 && problem[-1] != '\n' && problem[-1] != ':')
670 --problem;
672 if (problem > file)
673 problem[-1] = '\0';
675 else
677 problem = NULL;
678 file[file_size - 1] = '\0';
681 HP_TIMING_NOW (start);
683 if (file != problem)
685 char *p;
686 runp = file;
687 while ((p = strsep (&runp, ": \t\n")) != NULL)
688 if (p[0] != '\0')
690 struct link_map *new_map = _dl_map_object (_dl_loaded, p, 1,
691 lt_library, 0);
692 if (new_map->l_opencount == 1)
693 /* It is no duplicate. */
694 ++npreloads;
698 if (problem != NULL)
700 char *p = strndupa (problem, file_size - (problem - file));
701 struct link_map *new_map = _dl_map_object (_dl_loaded, p, 1,
702 lt_library, 0);
703 if (new_map->l_opencount == 1)
704 /* It is no duplicate. */
705 ++npreloads;
708 HP_TIMING_NOW (stop);
709 HP_TIMING_DIFF (diff, start, stop);
710 HP_TIMING_ACCUM_NT (load_time, diff);
712 /* We don't need the file anymore. */
713 __munmap (file, file_size);
716 if (npreloads != 0)
718 /* Set up PRELOADS with a vector of the preloaded libraries. */
719 struct link_map *l;
720 preloads = __alloca (npreloads * sizeof preloads[0]);
721 l = _dl_rtld_map.l_next; /* End of the chain before preloads. */
722 i = 0;
725 preloads[i++] = l;
726 l = l->l_next;
727 } while (l);
728 assert (i == npreloads);
731 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
732 specified some libraries to load, these are inserted before the actual
733 dependencies in the executable's searchlist for symbol resolution. */
734 HP_TIMING_NOW (start);
735 _dl_map_object_deps (_dl_loaded, preloads, npreloads, mode == trace, 0);
736 HP_TIMING_NOW (stop);
737 HP_TIMING_DIFF (diff, start, stop);
738 HP_TIMING_ACCUM_NT (load_time, diff);
740 /* Mark all objects as being in the global scope. */
741 for (i = _dl_loaded->l_searchlist.r_nlist; i > 0; )
742 _dl_loaded->l_searchlist.r_list[--i]->l_global = 1;
744 #ifndef MAP_ANON
745 /* We are done mapping things, so close the zero-fill descriptor. */
746 __close (_dl_zerofd);
747 _dl_zerofd = -1;
748 #endif
750 /* Remove _dl_rtld_map from the chain. */
751 _dl_rtld_map.l_prev->l_next = _dl_rtld_map.l_next;
752 if (_dl_rtld_map.l_next)
753 _dl_rtld_map.l_next->l_prev = _dl_rtld_map.l_prev;
755 if (__builtin_expect (_dl_rtld_map.l_opencount, 2) > 1)
757 /* Some DT_NEEDED entry referred to the interpreter object itself, so
758 put it back in the list of visible objects. We insert it into the
759 chain in symbol search order because gdb uses the chain's order as
760 its symbol search order. */
761 i = 1;
762 while (_dl_loaded->l_searchlist.r_list[i] != &_dl_rtld_map)
763 ++i;
764 _dl_rtld_map.l_prev = _dl_loaded->l_searchlist.r_list[i - 1];
765 _dl_rtld_map.l_next = (i + 1 < _dl_loaded->l_searchlist.r_nlist
766 ? _dl_loaded->l_searchlist.r_list[i + 1]
767 : NULL);
768 assert (_dl_rtld_map.l_prev->l_next == _dl_rtld_map.l_next);
769 _dl_rtld_map.l_prev->l_next = &_dl_rtld_map;
770 if (_dl_rtld_map.l_next)
772 assert (_dl_rtld_map.l_next->l_prev == _dl_rtld_map.l_prev);
773 _dl_rtld_map.l_next->l_prev = &_dl_rtld_map;
777 /* Now let us see whether all libraries are available in the
778 versions we need. */
780 struct version_check_args args;
781 args.doexit = mode == normal;
782 _dl_receive_error (print_missing_version, version_check_doit, &args);
785 if (__builtin_expect (mode, normal) != normal)
787 /* We were run just to list the shared libraries. It is
788 important that we do this before real relocation, because the
789 functions we call below for output may no longer work properly
790 after relocation. */
791 if (! _dl_loaded->l_info[DT_NEEDED])
792 _dl_sysdep_message ("\t", "statically linked\n", NULL);
793 else
795 struct link_map *l;
797 for (l = _dl_loaded->l_next; l; l = l->l_next)
798 if (l->l_opencount == 0)
799 /* The library was not found. */
800 _dl_sysdep_message ("\t", l->l_libname->name, " => not found\n",
801 NULL);
802 else
804 char buf[20], *bp;
805 buf[sizeof buf - 1] = '\0';
806 bp = _itoa_word (l->l_addr, &buf[sizeof buf - 1], 16, 0);
807 while ((size_t) (&buf[sizeof buf - 1] - bp)
808 < sizeof l->l_addr * 2)
809 *--bp = '0';
810 _dl_sysdep_message ("\t", l->l_libname->name, " => ",
811 l->l_name, " (0x", bp, ")\n", NULL);
815 if (__builtin_expect (mode, trace) != trace)
816 for (i = 1; i < _dl_argc; ++i)
818 const ElfW(Sym) *ref = NULL;
819 ElfW(Addr) loadbase = _dl_lookup_symbol (_dl_argv[i], &ref,
820 _dl_loaded->l_scope,
821 "argument",
822 ELF_MACHINE_JMP_SLOT);
823 char buf[20], *bp;
824 buf[sizeof buf - 1] = '\0';
825 bp = _itoa_word (ref->st_value, &buf[sizeof buf - 1], 16, 0);
826 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
827 *--bp = '0';
828 _dl_sysdep_message (_dl_argv[i], " found at 0x", bp, NULL);
829 buf[sizeof buf - 1] = '\0';
830 bp = _itoa_word (loadbase, &buf[sizeof buf - 1], 16, 0);
831 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
832 *--bp = '0';
833 _dl_sysdep_message (" in object at 0x", bp, "\n", NULL);
835 else
837 if (lazy >= 0)
839 /* We have to do symbol dependency testing. */
840 struct relocate_args args;
841 struct link_map *l;
843 args.lazy = lazy;
845 l = _dl_loaded;
846 while (l->l_next)
847 l = l->l_next;
850 if (l != &_dl_rtld_map && l->l_opencount > 0)
852 args.l = l;
853 _dl_receive_error (print_unresolved, relocate_doit,
854 &args);
856 l = l->l_prev;
857 } while (l);
860 #define VERNEEDTAG (DT_NUM + DT_PROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
861 if (version_info)
863 /* Print more information. This means here, print information
864 about the versions needed. */
865 int first = 1;
866 struct link_map *map = _dl_loaded;
868 for (map = _dl_loaded; map != NULL; map = map->l_next)
870 const char *strtab;
871 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
872 ElfW(Verneed) *ent;
874 if (dyn == NULL)
875 continue;
877 strtab = (const char *)
878 (map->l_addr + map->l_info[DT_STRTAB]->d_un.d_ptr);
879 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
881 if (first)
883 _dl_sysdep_message ("\n\tVersion information:\n", NULL);
884 first = 0;
887 _dl_sysdep_message ("\t", (map->l_name[0]
888 ? map->l_name : _dl_argv[0]),
889 ":\n", NULL);
891 while (1)
893 ElfW(Vernaux) *aux;
894 struct link_map *needed;
896 needed = find_needed (strtab + ent->vn_file);
897 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
899 while (1)
901 const char *fname = NULL;
903 _dl_sysdep_message ("\t\t",
904 strtab + ent->vn_file,
905 " (", strtab + aux->vna_name,
906 ") ",
907 (aux->vna_flags
908 & VER_FLG_WEAK
909 ? "[WEAK] " : ""),
910 "=> ", NULL);
912 if (needed != NULL
913 && match_version (strtab+aux->vna_name, needed))
914 fname = needed->l_name;
916 _dl_sysdep_message (fname ?: "not found", "\n",
917 NULL);
919 if (aux->vna_next == 0)
920 /* No more symbols. */
921 break;
923 /* Next symbol. */
924 aux = (ElfW(Vernaux) *) ((char *) aux
925 + aux->vna_next);
928 if (ent->vn_next == 0)
929 /* No more dependencies. */
930 break;
932 /* Next dependency. */
933 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
939 _exit (0);
943 /* Now we have all the objects loaded. Relocate them all except for
944 the dynamic linker itself. We do this in reverse order so that copy
945 relocs of earlier objects overwrite the data written by later
946 objects. We do not re-relocate the dynamic linker itself in this
947 loop because that could result in the GOT entries for functions we
948 call being changed, and that would break us. It is safe to relocate
949 the dynamic linker out of order because it has no copy relocs (we
950 know that because it is self-contained). */
952 struct link_map *l;
953 int consider_profiling = _dl_profile != NULL;
954 hp_timing_t start;
955 hp_timing_t stop;
956 hp_timing_t add;
958 /* If we are profiling we also must do lazy reloaction. */
959 lazy |= consider_profiling;
961 l = _dl_loaded;
962 while (l->l_next)
963 l = l->l_next;
965 HP_TIMING_NOW (start);
968 if (l != &_dl_rtld_map)
969 _dl_relocate_object (l, l->l_scope, lazy, consider_profiling);
971 l = l->l_prev;
973 while (l);
974 HP_TIMING_NOW (stop);
976 HP_TIMING_DIFF (relocate_time, start, stop);
978 /* Do any necessary cleanups for the startup OS interface code.
979 We do these now so that no calls are made after rtld re-relocation
980 which might be resolved to different functions than we expect.
981 We cannot do this before relocating the other objects because
982 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
983 _dl_sysdep_start_cleanup ();
985 if (_dl_rtld_map.l_opencount > 0)
987 /* There was an explicit ref to the dynamic linker as a shared lib.
988 Re-relocate ourselves with user-controlled symbol definitions. */
989 HP_TIMING_NOW (start);
990 _dl_relocate_object (&_dl_rtld_map, _dl_loaded->l_scope, 0, 0);
991 HP_TIMING_NOW (stop);
992 HP_TIMING_DIFF (add, start, stop);
993 HP_TIMING_ACCUM_NT (relocate_time, add);
997 /* Now set up the variable which helps the assembler startup code. */
998 _dl_main_searchlist = &_dl_loaded->l_searchlist;
999 _dl_global_scope[0] = &_dl_loaded->l_searchlist;
1001 /* Safe the information about the original global scope list since
1002 we need it in the memory handling later. */
1003 _dl_initial_searchlist = *_dl_main_searchlist;
1006 /* Initialize _r_debug. */
1007 struct r_debug *r = _dl_debug_initialize (_dl_rtld_map.l_addr);
1008 struct link_map *l;
1010 l = _dl_loaded;
1012 #ifdef ELF_MACHINE_DEBUG_SETUP
1014 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1016 ELF_MACHINE_DEBUG_SETUP (l, r);
1017 ELF_MACHINE_DEBUG_SETUP (&_dl_rtld_map, r);
1019 #else
1021 if (l->l_info[DT_DEBUG])
1022 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1023 with the run-time address of the r_debug structure */
1024 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1026 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1027 case you run gdb on the dynamic linker directly. */
1028 if (_dl_rtld_map.l_info[DT_DEBUG])
1029 _dl_rtld_map.l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1031 #endif
1033 /* Notify the debugger that all objects are now mapped in. */
1034 r->r_state = RT_ADD;
1035 _dl_debug_state ();
1038 #ifndef MAP_COPY
1039 /* We must munmap() the cache file. */
1040 _dl_unload_cache ();
1041 #endif
1043 /* Now enable profiling if needed. */
1044 if (_dl_profile_map != NULL)
1045 /* We must prepare the profiling. */
1046 _dl_start_profile (_dl_profile_map, _dl_profile_output);
1048 /* Once we return, _dl_sysdep_start will invoke
1049 the DT_INIT functions and then *USER_ENTRY. */
1052 /* This is a little helper function for resolving symbols while
1053 tracing the binary. */
1054 static void
1055 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
1056 const char *errstring)
1058 if (objname[0] == '\0')
1059 objname = _dl_argv[0] ?: "<main program>";
1060 _dl_sysdep_error (errstring, " (", objname, ")\n", NULL);
1063 /* This is a little helper function for resolving symbols while
1064 tracing the binary. */
1065 static void
1066 print_missing_version (int errcode __attribute__ ((unused)),
1067 const char *objname, const char *errstring)
1069 _dl_sysdep_error (_dl_argv[0] ?: "<program name unknown>", ": ",
1070 objname, ": ", errstring, "\n", NULL);
1073 /* Nonzero if any of the debugging options is enabled. */
1074 static int any_debug;
1076 /* Process the string given as the parameter which explains which debugging
1077 options are enabled. */
1078 static void
1079 process_dl_debug (const char *dl_debug)
1081 size_t len;
1082 #define separators " ,:"
1085 len = 0;
1086 /* Skip separating white spaces and commas. */
1087 dl_debug += strspn (dl_debug, separators);
1088 if (*dl_debug != '\0')
1090 len = strcspn (dl_debug, separators);
1092 switch (len)
1094 case 3:
1095 /* This option is not documented since it is not generally
1096 useful. */
1097 if (memcmp (dl_debug, "all", 3) == 0)
1099 _dl_debug_libs = 1;
1100 _dl_debug_impcalls = 1;
1101 _dl_debug_reloc = 1;
1102 _dl_debug_files = 1;
1103 _dl_debug_symbols = 1;
1104 _dl_debug_bindings = 1;
1105 _dl_debug_versions = 1;
1106 any_debug = 1;
1107 continue;
1109 break;
1111 case 4:
1112 if (memcmp (dl_debug, "help", 4) == 0)
1114 _dl_sysdep_message ("\
1115 Valid options for the LD_DEBUG environment variable are:\n\
1117 bindings display information about symbol binding\n\
1118 files display processing of files and libraries\n\
1119 help display this help message and exit\n\
1120 libs display library search paths\n\
1121 reloc display relocation processing\n\
1122 symbols display symbol table processing\n\
1123 versions display version dependencies\n\
1125 To direct the debugging output into a file instead of standard output\n\
1126 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n",
1127 NULL);
1128 _exit (0);
1131 if (memcmp (dl_debug, "libs", 4) == 0)
1133 _dl_debug_libs = 1;
1134 _dl_debug_impcalls = 1;
1135 any_debug = 1;
1136 continue;
1138 break;
1140 case 5:
1141 if (memcmp (dl_debug, "reloc", 5) == 0)
1143 _dl_debug_reloc = 1;
1144 _dl_debug_impcalls = 1;
1145 any_debug = 1;
1146 continue;
1149 if (memcmp (dl_debug, "files", 5) == 0)
1151 _dl_debug_files = 1;
1152 _dl_debug_impcalls = 1;
1153 any_debug = 1;
1154 continue;
1156 break;
1158 case 7:
1159 if (memcmp (dl_debug, "symbols", 7) == 0)
1161 _dl_debug_symbols = 1;
1162 _dl_debug_impcalls = 1;
1163 any_debug = 1;
1164 continue;
1166 break;
1168 case 8:
1169 if (memcmp (dl_debug, "bindings", 8) == 0)
1171 _dl_debug_bindings = 1;
1172 _dl_debug_impcalls = 1;
1173 any_debug = 1;
1174 continue;
1177 if (memcmp (dl_debug, "versions", 8) == 0)
1179 _dl_debug_versions = 1;
1180 _dl_debug_impcalls = 1;
1181 any_debug = 1;
1182 continue;
1184 break;
1186 case 10:
1187 if (memcmp (dl_debug, "statistics", 10) == 0)
1189 _dl_debug_statistics = 1;
1190 continue;
1192 break;
1194 default:
1195 break;
1199 /* Display a warning and skip everything until next separator. */
1200 char *startp = strndupa (dl_debug, len);
1201 _dl_sysdep_error ("warning: debug option `", startp,
1202 "' unknown; try LD_DEBUG=help\n", NULL);
1203 break;
1207 while (*(dl_debug += len) != '\0');
1210 /* Process all environments variables the dynamic linker must recognize.
1211 Since all of them start with `LD_' we are a bit smarter while finding
1212 all the entries. */
1213 static void
1214 process_envvars (enum mode *modep, int *lazyp)
1216 char **runp = NULL;
1217 char *envline;
1218 enum mode mode = normal;
1219 int bind_now = 0;
1220 char *debug_output = NULL;
1222 /* This is the default place for profiling data file. */
1223 _dl_profile_output = "/var/tmp";
1225 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
1227 size_t len = strcspn (envline, "=") - 3;
1229 switch (len)
1231 case 4:
1232 /* Warning level, verbose or not. */
1233 if (memcmp (&envline[3], "WARN", 4) == 0)
1234 _dl_verbose = envline[8] != '\0';
1235 break;
1237 case 5:
1238 /* Debugging of the dynamic linker? */
1239 if (memcmp (&envline[3], "DEBUG", 5) == 0)
1240 process_dl_debug (&envline[9]);
1241 break;
1243 case 7:
1244 /* Print information about versions. */
1245 if (memcmp (&envline[3], "VERBOSE", 7) == 0)
1247 version_info = envline[11] != '\0';
1248 break;
1251 /* List of objects to be preloaded. */
1252 if (memcmp (&envline[3], "PRELOAD", 7) == 0)
1254 preloadlist = &envline[11];
1255 break;
1258 /* Which shared object shall be profiled. */
1259 if (memcmp (&envline[3], "PROFILE", 7) == 0)
1261 _dl_profile = &envline[11];
1262 if (*_dl_profile == '\0')
1263 _dl_profile = NULL;
1265 break;
1267 case 8:
1268 /* Do we bind early? */
1269 if (memcmp (&envline[3], "BIND_NOW", 8) == 0)
1270 bind_now = envline[12] != '\0';
1271 break;
1273 case 9:
1274 /* Test whether we want to see the content of the auxiliary
1275 array passed up from the kernel. */
1276 if (memcmp (&envline[3], "SHOW_AUXV", 9) == 0)
1277 _dl_show_auxv ();
1278 break;
1280 case 10:
1281 /* Mask for the important hardware capabilities. */
1282 if (memcmp (&envline[3], "HWCAP_MASK", 10) == 0)
1283 _dl_hwcap_mask = strtoul (&envline[14], NULL, 0);
1284 break;
1286 case 11:
1287 /* Path where the binary is found. */
1288 if (!__libc_enable_secure
1289 && memcmp (&envline[3], "ORIGIN_PATH", 11) == 0)
1290 _dl_origin_path = &envline[15];
1291 break;
1293 case 12:
1294 /* Where to place the profiling data file. */
1295 if (memcmp (&envline[3], "DEBUG_OUTPUT", 12) == 0)
1297 debug_output = &envline[16];
1298 break;
1301 /* The library search path. */
1302 if (memcmp (&envline[3], "LIBRARY_PATH", 12) == 0)
1303 library_path = &envline[16];
1304 break;
1306 case 14:
1307 /* Where to place the profiling data file. */
1308 if (!__libc_enable_secure
1309 && memcmp (&envline[3], "PROFILE_OUTPUT", 14) == 0)
1311 _dl_profile_output = &envline[18];
1312 if (*_dl_profile_output == '\0')
1313 _dl_profile_output = "/var/tmp";
1315 break;
1317 case 20:
1318 /* The mode of the dynamic linker can be set. */
1319 if (memcmp (&envline[3], "TRACE_LOADED_OBJECTS", 20) == 0)
1320 mode = trace;
1321 break;
1323 /* We might have some extra environment variable to handle. This
1324 is tricky due to the pre-processing of the length of the name
1325 in the switch statement here. The code here assumes that added
1326 environment variables have a different length. */
1327 #ifdef EXTRA_LD_ENVVARS
1328 EXTRA_LD_ENVVARS
1329 #endif
1333 /* Extra security for SUID binaries. Remove all dangerous environment
1334 variables. */
1335 if (__libc_enable_secure)
1337 static const char *unsecure_envvars[] =
1339 #ifdef EXTRA_UNSECURE_ENVVARS
1340 EXTRA_UNSECURE_ENVVARS
1341 #endif
1343 size_t cnt;
1345 if (preloadlist != NULL)
1346 unsetenv ("LD_PRELOAD");
1347 if (library_path != NULL)
1348 unsetenv ("LD_LIBRARY_PATH");
1350 for (cnt = 0;
1351 cnt < sizeof (unsecure_envvars) / sizeof (unsecure_envvars[0]);
1352 ++cnt)
1353 unsetenv (unsecure_envvars[cnt]);
1356 /* If we have to run the dynamic linker in debugging mode and the
1357 LD_DEBUG_OUTPUT environment variable is given, we write the debug
1358 messages to this file. */
1359 if (any_debug && debug_output != NULL && !__libc_enable_secure)
1361 size_t name_len = strlen (debug_output);
1362 char buf[name_len + 12];
1363 char *startp;
1365 buf[name_len + 11] = '\0';
1366 startp = _itoa_word (__getpid (), &buf[name_len + 11], 10, 0);
1367 *--startp = '.';
1368 startp = memcpy (startp - name_len, debug_output, name_len);
1370 _dl_debug_fd = __open (startp, O_WRONLY | O_APPEND | O_CREAT, 0666);
1371 if (_dl_debug_fd == -1)
1372 /* We use standard output if opening the file failed. */
1373 _dl_debug_fd = STDOUT_FILENO;
1376 /* LAZY is determined by the environment variable LD_WARN and
1377 LD_BIND_NOW if we trace the binary. */
1378 if (__builtin_expect (mode, normal) == trace)
1379 *lazyp = _dl_verbose ? !bind_now : -1;
1380 else
1381 *lazyp = !__libc_enable_secure && !bind_now;
1383 *modep = mode;
1387 /* Print the various times we collected. */
1388 static void
1389 print_statistics (void)
1391 char buf[200];
1392 char *cp;
1393 char *wp;
1395 /* Total time rtld used. */
1396 if (HP_TIMING_AVAIL)
1398 HP_TIMING_PRINT (buf, sizeof (buf), rtld_total_time);
1399 _dl_debug_message (1, "\nruntime linker statistics:\n"
1400 " total startup time in dynamic loader: ",
1401 buf, "\n", NULL);
1404 /* Print relocation statistics. */
1405 if (HP_TIMING_AVAIL)
1407 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
1408 _dl_debug_message (1, " time needed for relocation: ", buf,
1409 NULL);
1410 cp = _itoa_word ((1000 * relocate_time) / rtld_total_time,
1411 buf + sizeof (buf), 10, 0);
1412 wp = buf;
1413 switch (buf + sizeof (buf) - cp)
1415 case 3:
1416 *wp++ = *cp++;
1417 case 2:
1418 *wp++ = *cp++;
1419 case 1:
1420 *wp++ = '.';
1421 *wp++ = *cp++;
1423 *wp = '\0';
1424 _dl_debug_message (0, " (", buf, "%)\n", NULL);
1427 buf[sizeof (buf) - 1] = '\0';
1428 _dl_debug_message (1, " number of relocations: ",
1429 _itoa_word (_dl_num_relocations,
1430 buf + sizeof (buf) - 1, 10, 0),
1431 "\n", NULL);
1433 /* Time spend while loading the object and the dependencies. */
1434 if (HP_TIMING_AVAIL)
1436 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
1437 _dl_debug_message (1, " time needed to load objects: ", buf,
1438 NULL);
1439 cp = _itoa_word ((1000 * load_time) / rtld_total_time,
1440 buf + sizeof (buf), 10, 0);
1441 wp = buf;
1442 switch (buf + sizeof (buf) - cp)
1444 case 3:
1445 *wp++ = *cp++;
1446 case 2:
1447 *wp++ = *cp++;
1448 case 1:
1449 *wp++ = '.';
1450 *wp++ = *cp++;
1452 *wp = '\0';
1453 _dl_debug_message (0, " (", buf, "%)\n", NULL);