Update.
[glibc.git] / elf / rtld.c
blobb49d11026700aca29a0d7b8c6454b09c73ad4ff8
1 /* Run time dynamic linker.
2 Copyright (C) 1995-1999, 2000, 2001, 2002 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 Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the 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 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18 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 <sys/param.h>
26 #include <sys/stat.h>
27 #include <ldsodefs.h>
28 #include <stdio-common/_itoa.h>
29 #include <entry.h>
30 #include <fpu_control.h>
31 #include <hp-timing.h>
32 #include <bits/libc-lock.h>
33 #include "dynamic-link.h"
34 #include "dl-librecon.h"
35 #include <unsecvars.h>
36 #include <dl-cache.h>
37 #include <dl-procinfo.h>
39 #include <assert.h>
41 /* Helper function to handle errors while resolving symbols. */
42 static void print_unresolved (int errcode, const char *objname,
43 const char *errsting);
45 /* Helper function to handle errors when a version is missing. */
46 static void print_missing_version (int errcode, const char *objname,
47 const char *errsting);
49 /* Print the various times we collected. */
50 static void print_statistics (void);
52 /* This is a list of all the modes the dynamic loader can be in. */
53 enum mode { normal, list, verify, trace };
55 /* Process all environments variables the dynamic linker must recognize.
56 Since all of them start with `LD_' we are a bit smarter while finding
57 all the entries. */
58 static void process_envvars (enum mode *modep);
60 int _dl_argc;
61 char **_dl_argv;
62 unsigned int _dl_skip_args; /* Nonzero if we were run directly. */
64 /* Set nonzero during loading and initialization of executable and
65 libraries, cleared before the executable's entry point runs. This
66 must not be initialized to nonzero, because the unused dynamic
67 linker loaded in for libc.so's "ld.so.1" dep will provide the
68 definition seen by libc.so's initializer; that value must be zero,
69 and will be since that dynamic linker's _dl_start and dl_main will
70 never be called. */
71 int _dl_starting_up;
73 /* This is the structure which defines all variables global to ld.so
74 (except those which cannot be added for some reason). */
75 struct rtld_global _rtld_global =
77 /* Get architecture specific initializer. */
78 #include <dl-procinfo.c>
79 ._dl_debug_fd = STDERR_FILENO,
80 #if 1
81 /* XXX I know about at least one case where we depend on the old
82 weak behavior (it has to do with librt). Until we get DSO
83 groups implemented we have to make this the default.
84 Bummer. --drepper */
85 ._dl_dynamic_weak = 1,
86 #endif
87 ._dl_lazy = 1,
88 ._dl_fpu_control = _FPU_DEFAULT,
89 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
90 ._dl_hwcap_mask = HWCAP_IMPORTANT,
91 ._dl_load_lock = _LIBC_LOCK_RECURSIVE_INITIALIZER
93 /* There must only be the definition in ld.so itself. */
94 #ifdef HAVE_PROTECTED
95 asm (".protected _rtld_global");
96 #endif
99 static void dl_main (const ElfW(Phdr) *phdr,
100 ElfW(Word) phnum,
101 ElfW(Addr) *user_entry);
103 static struct libname_list _dl_rtld_libname;
104 static struct libname_list _dl_rtld_libname2;
106 /* We expect less than a second for relocation. */
107 #ifdef HP_SMALL_TIMING_AVAIL
108 # undef HP_TIMING_AVAIL
109 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
110 #endif
112 /* Variable for statistics. */
113 #ifndef HP_TIMING_NONAVAIL
114 static hp_timing_t rtld_total_time;
115 static hp_timing_t relocate_time;
116 static hp_timing_t load_time;
117 #endif
119 static ElfW(Addr) _dl_start_final (void *arg, struct link_map *bootstrap_map_p,
120 hp_timing_t start_time);
122 #ifdef RTLD_START
123 RTLD_START
124 #else
125 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
126 #endif
128 static ElfW(Addr) __attribute_used__ internal_function
129 _dl_start (void *arg)
131 struct link_map bootstrap_map;
132 hp_timing_t start_time;
133 #if !__GNUC_PREREQ (2, 96)
134 size_t cnt;
135 #endif
137 /* This #define produces dynamic linking inline functions for
138 bootstrap relocation instead of general-purpose relocation. */
139 #define RTLD_BOOTSTRAP
140 #define RESOLVE_MAP(sym, version, flags) \
141 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : &bootstrap_map)
142 #define RESOLVE(sym, version, flags) \
143 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : bootstrap_map.l_addr)
144 #include "dynamic-link.h"
146 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
147 HP_TIMING_NOW (start_time);
149 /* Partly clean the `bootstrap_map' structure up. Don't use
150 `memset' since it might not be built in or inlined and we cannot
151 make function calls at this point. Use '__builtin_memset' if we
152 know it is available. */
153 #if __GNUC_PREREQ (2, 96)
154 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
155 #else
156 for (cnt = 0;
157 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
158 ++cnt)
159 bootstrap_map.l_info[cnt] = 0;
160 #endif
162 /* Figure out the run-time load address of the dynamic linker itself. */
163 bootstrap_map.l_addr = elf_machine_load_address ();
165 /* Read our own dynamic section and fill in the info array. */
166 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
167 elf_get_dynamic_info (&bootstrap_map);
169 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
170 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
171 #endif
173 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
175 /* Relocate ourselves so we can do normal function calls and
176 data access using the global offset table. */
178 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
181 /* Please note that we don't allow profiling of this object and
182 therefore need not test whether we have to allocate the array
183 for the relocation results (as done in dl-reloc.c). */
185 /* Now life is sane; we can call functions and access global data.
186 Set up to use the operating system facilities, and find out from
187 the operating system's program loader where to find the program
188 header table in core. Put the rest of _dl_start into a separate
189 function, that way the compiler cannot put accesses to the GOT
190 before ELF_DYNAMIC_RELOCATE. */
192 ElfW(Addr) entry = _dl_start_final (arg, &bootstrap_map, start_time);
194 #ifndef ELF_MACHINE_START_ADDRESS
195 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
196 #endif
198 return ELF_MACHINE_START_ADDRESS (GL(dl_loaded), entry);
203 #ifndef VALIDX
204 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
205 + DT_EXTRANUM + DT_VALTAGIDX (tag))
206 #endif
207 #ifndef ADDRIDX
208 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
209 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
210 #endif
212 static ElfW(Addr)
213 _dl_start_final (void *arg, struct link_map *bootstrap_map_p,
214 hp_timing_t start_time)
216 /* The use of `alloca' here looks ridiculous but it helps. The goal
217 is to avoid the function from being inlined. There is no official
218 way to do this so we use this trick. gcc never inlines functions
219 which use `alloca'. */
220 ElfW(Addr) *start_addr = alloca (sizeof (ElfW(Addr)));
221 extern char _begin[], _end[];
223 if (HP_TIMING_AVAIL)
225 /* If it hasn't happen yet record the startup time. */
226 if (! HP_TIMING_INLINE)
227 HP_TIMING_NOW (start_time);
229 /* Initialize the timing functions. */
230 HP_TIMING_DIFF_INIT ();
233 /* Transfer data about ourselves to the permanent link_map structure. */
234 GL(dl_rtld_map).l_addr = bootstrap_map_p->l_addr;
235 GL(dl_rtld_map).l_ld = bootstrap_map_p->l_ld;
236 GL(dl_rtld_map).l_opencount = 1;
237 memcpy (GL(dl_rtld_map).l_info, bootstrap_map_p->l_info,
238 sizeof GL(dl_rtld_map).l_info);
239 _dl_setup_hash (&GL(dl_rtld_map));
240 GL(dl_rtld_map).l_mach = bootstrap_map_p->l_mach;
241 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
242 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
244 /* Call the OS-dependent function to set up life so we can do things like
245 file access. It will call `dl_main' (below) to do all the real work
246 of the dynamic linker, and then unwind our frame and run the user
247 entry point on the same stack we entered on. */
248 *start_addr = _dl_sysdep_start (arg, &dl_main);
249 #ifndef HP_TIMING_NONAVAIL
250 if (HP_TIMING_AVAIL)
252 hp_timing_t end_time;
254 /* Get the current time. */
255 HP_TIMING_NOW (end_time);
257 /* Compute the difference. */
258 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
260 #endif
262 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
263 print_statistics ();
265 return *start_addr;
268 /* Now life is peachy; we can do all normal operations.
269 On to the real work. */
271 /* Some helper functions. */
273 /* Arguments to relocate_doit. */
274 struct relocate_args
276 struct link_map *l;
277 int lazy;
280 struct map_args
282 /* Argument to map_doit. */
283 char *str;
284 /* Return value of map_doit. */
285 struct link_map *main_map;
288 /* Arguments to version_check_doit. */
289 struct version_check_args
291 int doexit;
292 int dotrace;
295 static void
296 relocate_doit (void *a)
298 struct relocate_args *args = (struct relocate_args *) a;
300 INT(_dl_relocate_object) (args->l, args->l->l_scope, args->lazy, 0);
303 static void
304 map_doit (void *a)
306 struct map_args *args = (struct map_args *) a;
307 args->main_map = INT(_dl_map_object) (NULL, args->str, 0, lt_library, 0, 0);
310 static void
311 version_check_doit (void *a)
313 struct version_check_args *args = (struct version_check_args *) a;
314 if (_dl_check_all_versions (GL(dl_loaded), 1, args->dotrace) && args->doexit)
315 /* We cannot start the application. Abort now. */
316 _exit (1);
320 static inline struct link_map *
321 find_needed (const char *name)
323 unsigned int n = GL(dl_loaded)->l_searchlist.r_nlist;
325 while (n-- > 0)
326 if (_dl_name_match_p (name, GL(dl_loaded)->l_searchlist.r_list[n]))
327 return GL(dl_loaded)->l_searchlist.r_list[n];
329 /* Should never happen. */
330 return NULL;
333 static int
334 match_version (const char *string, struct link_map *map)
336 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
337 ElfW(Verdef) *def;
339 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
340 if (map->l_info[VERDEFTAG] == NULL)
341 /* The file has no symbol versioning. */
342 return 0;
344 def = (ElfW(Verdef) *) ((char *) map->l_addr
345 + map->l_info[VERDEFTAG]->d_un.d_ptr);
346 while (1)
348 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
350 /* Compare the version strings. */
351 if (strcmp (string, strtab + aux->vda_name) == 0)
352 /* Bingo! */
353 return 1;
355 /* If no more definitions we failed to find what we want. */
356 if (def->vd_next == 0)
357 break;
359 /* Next definition. */
360 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
363 return 0;
366 static const char *library_path; /* The library search path. */
367 static const char *preloadlist; /* The list preloaded objects. */
368 static int version_info; /* Nonzero if information about
369 versions has to be printed. */
371 static void
372 dl_main (const ElfW(Phdr) *phdr,
373 ElfW(Word) phnum,
374 ElfW(Addr) *user_entry)
376 const ElfW(Phdr) *ph;
377 enum mode mode;
378 struct link_map **preloads;
379 unsigned int npreloads;
380 size_t file_size;
381 char *file;
382 int has_interp = 0;
383 unsigned int i;
384 int prelinked = 0;
385 int rtld_is_main = 0;
386 #ifndef HP_TIMING_NONAVAIL
387 hp_timing_t start;
388 hp_timing_t stop;
389 hp_timing_t diff;
390 #endif
392 /* Process the environment variable which control the behaviour. */
393 process_envvars (&mode);
395 /* Set up a flag which tells we are just starting. */
396 _dl_starting_up = 1;
398 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
400 /* Ho ho. We are not the program interpreter! We are the program
401 itself! This means someone ran ld.so as a command. Well, that
402 might be convenient to do sometimes. We support it by
403 interpreting the args like this:
405 ld.so PROGRAM ARGS...
407 The first argument is the name of a file containing an ELF
408 executable we will load and run with the following arguments.
409 To simplify life here, PROGRAM is searched for using the
410 normal rules for shared objects, rather than $PATH or anything
411 like that. We just load it and use its entry point; we don't
412 pay attention to its PT_INTERP command (we are the interpreter
413 ourselves). This is an easy way to test a new ld.so before
414 installing it. */
415 rtld_is_main = 1;
417 /* Note the place where the dynamic linker actually came from. */
418 GL(dl_rtld_map).l_name = _dl_argv[0];
420 while (_dl_argc > 1)
421 if (! strcmp (_dl_argv[1], "--list"))
423 mode = list;
424 GL(dl_lazy) = -1; /* This means do no dependency analysis. */
426 ++_dl_skip_args;
427 --_dl_argc;
428 ++_dl_argv;
430 else if (! strcmp (_dl_argv[1], "--verify"))
432 mode = verify;
434 ++_dl_skip_args;
435 --_dl_argc;
436 ++_dl_argv;
438 else if (! strcmp (_dl_argv[1], "--library-path") && _dl_argc > 2)
440 library_path = _dl_argv[2];
442 _dl_skip_args += 2;
443 _dl_argc -= 2;
444 _dl_argv += 2;
446 else if (! strcmp (_dl_argv[1], "--inhibit-rpath") && _dl_argc > 2)
448 GL(dl_inhibit_rpath) = _dl_argv[2];
450 _dl_skip_args += 2;
451 _dl_argc -= 2;
452 _dl_argv += 2;
454 else
455 break;
457 /* If we have no further argument the program was called incorrectly.
458 Grant the user some education. */
459 if (_dl_argc < 2)
460 _dl_fatal_printf ("\
461 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
462 You have invoked `ld.so', the helper program for shared library executables.\n\
463 This program usually lives in the file `/lib/ld.so', and special directives\n\
464 in executable files using ELF shared libraries tell the system's program\n\
465 loader to load the helper program from this file. This helper program loads\n\
466 the shared libraries needed by the program executable, prepares the program\n\
467 to run, and runs it. You may invoke this helper program directly from the\n\
468 command line to load and run an ELF executable file; this is like executing\n\
469 that file itself, but always uses this helper program from the file you\n\
470 specified, instead of the helper program file specified in the executable\n\
471 file you run. This is mostly of use for maintainers to test new versions\n\
472 of this helper program; chances are you did not intend to run this program.\n\
474 --list list all dependencies and how they are resolved\n\
475 --verify verify that given object really is a dynamically linked\n\
476 object we can handle\n\
477 --library-path PATH use given PATH instead of content of the environment\n\
478 variable LD_LIBRARY_PATH\n\
479 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
480 in LIST\n");
482 ++_dl_skip_args;
483 --_dl_argc;
484 ++_dl_argv;
486 /* Initialize the data structures for the search paths for shared
487 objects. */
488 _dl_init_paths (library_path);
490 if (__builtin_expect (mode, normal) == verify)
492 const char *objname;
493 const char *err_str = NULL;
494 struct map_args args;
496 args.str = _dl_argv[0];
497 (void) INT(_dl_catch_error) (&objname, &err_str, map_doit, &args);
498 if (__builtin_expect (err_str != NULL, 0))
500 if (err_str != _dl_out_of_memory)
501 free ((char *) err_str);
502 _exit (EXIT_FAILURE);
505 else
507 HP_TIMING_NOW (start);
508 INT(_dl_map_object) (NULL, _dl_argv[0], 0, lt_library, 0, 0);
509 HP_TIMING_NOW (stop);
511 HP_TIMING_DIFF (load_time, start, stop);
514 phdr = GL(dl_loaded)->l_phdr;
515 phnum = GL(dl_loaded)->l_phnum;
516 /* We overwrite here a pointer to a malloc()ed string. But since
517 the malloc() implementation used at this point is the dummy
518 implementations which has no real free() function it does not
519 makes sense to free the old string first. */
520 GL(dl_loaded)->l_name = (char *) "";
521 *user_entry = GL(dl_loaded)->l_entry;
523 else
525 /* Create a link_map for the executable itself.
526 This will be what dlopen on "" returns. */
527 _dl_new_object ((char *) "", "", lt_executable, NULL);
528 if (GL(dl_loaded) == NULL)
529 _dl_fatal_printf ("cannot allocate memory for link map\n");
530 GL(dl_loaded)->l_phdr = phdr;
531 GL(dl_loaded)->l_phnum = phnum;
532 GL(dl_loaded)->l_entry = *user_entry;
534 /* At this point we are in a bit of trouble. We would have to
535 fill in the values for l_dev and l_ino. But in general we
536 do not know where the file is. We also do not handle AT_EXECFD
537 even if it would be passed up.
539 We leave the values here defined to 0. This is normally no
540 problem as the program code itself is normally no shared
541 object and therefore cannot be loaded dynamically. Nothing
542 prevent the use of dynamic binaries and in these situations
543 we might get problems. We might not be able to find out
544 whether the object is already loaded. But since there is no
545 easy way out and because the dynamic binary must also not
546 have an SONAME we ignore this program for now. If it becomes
547 a problem we can force people using SONAMEs. */
549 /* We delay initializing the path structure until we got the dynamic
550 information for the program. */
553 GL(dl_loaded)->l_map_end = 0;
554 /* Perhaps the executable has no PT_LOAD header entries at all. */
555 GL(dl_loaded)->l_map_start = ~0;
556 /* We opened the file, account for it. */
557 ++GL(dl_loaded)->l_opencount;
559 /* Scan the program header table for the dynamic section. */
560 for (ph = phdr; ph < &phdr[phnum]; ++ph)
561 switch (ph->p_type)
563 case PT_PHDR:
564 /* Find out the load address. */
565 GL(dl_loaded)->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
566 break;
567 case PT_DYNAMIC:
568 /* This tells us where to find the dynamic section,
569 which tells us everything we need to do. */
570 GL(dl_loaded)->l_ld = (void *) GL(dl_loaded)->l_addr + ph->p_vaddr;
571 break;
572 case PT_INTERP:
573 /* This "interpreter segment" was used by the program loader to
574 find the program interpreter, which is this program itself, the
575 dynamic linker. We note what name finds us, so that a future
576 dlopen call or DT_NEEDED entry, for something that wants to link
577 against the dynamic linker as a shared library, will know that
578 the shared object is already loaded. */
579 _dl_rtld_libname.name = ((const char *) GL(dl_loaded)->l_addr
580 + ph->p_vaddr);
581 /* _dl_rtld_libname.next = NULL; Already zero. */
582 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
584 /* Ordinarilly, we would get additional names for the loader from
585 our DT_SONAME. This can't happen if we were actually linked as
586 a static executable (detect this case when we have no DYNAMIC).
587 If so, assume the filename component of the interpreter path to
588 be our SONAME, and add it to our name list. */
589 if (GL(dl_rtld_map).l_ld == NULL)
591 const char *p = NULL;
592 const char *cp = _dl_rtld_libname.name;
594 /* Find the filename part of the path. */
595 while (*cp != '\0')
596 if (*cp++ == '/')
597 p = cp;
599 if (p != NULL)
601 _dl_rtld_libname2.name = p;
602 /* _dl_rtld_libname2.next = NULL; Already zero. */
603 _dl_rtld_libname.next = &_dl_rtld_libname2;
607 has_interp = 1;
608 break;
609 case PT_LOAD:
611 ElfW(Addr) mapstart;
612 ElfW(Addr) allocend;
614 /* Remember where the main program starts in memory. */
615 mapstart = (GL(dl_loaded)->l_addr
616 + (ph->p_vaddr & ~(ph->p_align - 1)));
617 if (GL(dl_loaded)->l_map_start > mapstart)
618 GL(dl_loaded)->l_map_start = mapstart;
620 /* Also where it ends. */
621 allocend = GL(dl_loaded)->l_addr + ph->p_vaddr + ph->p_memsz;
622 if (GL(dl_loaded)->l_map_end < allocend)
623 GL(dl_loaded)->l_map_end = allocend;
625 break;
627 if (! GL(dl_loaded)->l_map_end)
628 GL(dl_loaded)->l_map_end = ~0;
629 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
631 /* We were invoked directly, so the program might not have a
632 PT_INTERP. */
633 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
634 /* _dl_rtld_libname.next = NULL; Alread zero. */
635 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
637 else
638 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
640 if (! rtld_is_main)
642 /* Extract the contents of the dynamic section for easy access. */
643 elf_get_dynamic_info (GL(dl_loaded));
644 if (GL(dl_loaded)->l_info[DT_HASH])
645 /* Set up our cache of pointers into the hash table. */
646 _dl_setup_hash (GL(dl_loaded));
649 if (__builtin_expect (mode, normal) == verify)
651 /* We were called just to verify that this is a dynamic
652 executable using us as the program interpreter. Exit with an
653 error if we were not able to load the binary or no interpreter
654 is specified (i.e., this is no dynamically linked binary. */
655 if (GL(dl_loaded)->l_ld == NULL)
656 _exit (1);
658 /* We allow here some platform specific code. */
659 #ifdef DISTINGUISH_LIB_VERSIONS
660 DISTINGUISH_LIB_VERSIONS;
661 #endif
662 _exit (has_interp ? 0 : 2);
665 if (! rtld_is_main)
666 /* Initialize the data structures for the search paths for shared
667 objects. */
668 _dl_init_paths (library_path);
670 /* Put the link_map for ourselves on the chain so it can be found by
671 name. Note that at this point the global chain of link maps contains
672 exactly one element, which is pointed to by dl_loaded. */
673 if (! GL(dl_rtld_map).l_name)
674 /* If not invoked directly, the dynamic linker shared object file was
675 found by the PT_INTERP name. */
676 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
677 GL(dl_rtld_map).l_type = lt_library;
678 GL(dl_loaded)->l_next = &GL(dl_rtld_map);
679 GL(dl_rtld_map).l_prev = GL(dl_loaded);
680 ++GL(dl_nloaded);
682 /* We have two ways to specify objects to preload: via environment
683 variable and via the file /etc/ld.so.preload. The latter can also
684 be used when security is enabled. */
685 preloads = NULL;
686 npreloads = 0;
688 if (__builtin_expect (preloadlist != NULL, 0))
690 /* The LD_PRELOAD environment variable gives list of libraries
691 separated by white space or colons that are loaded before the
692 executable's dependencies and prepended to the global scope
693 list. If the binary is running setuid all elements
694 containing a '/' are ignored since it is insecure. */
695 char *list = strdupa (preloadlist);
696 char *p;
698 HP_TIMING_NOW (start);
700 /* Prevent optimizing strsep. Speed is not important here. */
701 while ((p = (strsep) (&list, " :")) != NULL)
702 if (p[0] != '\0'
703 && (__builtin_expect (! __libc_enable_secure, 1)
704 || strchr (p, '/') == NULL))
706 struct link_map *new_map = INT(_dl_map_object) (GL(dl_loaded), p,
707 1, lt_library,
708 0, 0);
709 if (++new_map->l_opencount == 1)
710 /* It is no duplicate. */
711 ++npreloads;
714 HP_TIMING_NOW (stop);
715 HP_TIMING_DIFF (diff, start, stop);
716 HP_TIMING_ACCUM_NT (load_time, diff);
719 /* Read the contents of the file. */
720 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
721 PROT_READ | PROT_WRITE);
722 if (__builtin_expect (file != MAP_FAILED, 0))
724 /* Parse the file. It contains names of libraries to be loaded,
725 separated by white spaces or `:'. It may also contain
726 comments introduced by `#'. */
727 char *problem;
728 char *runp;
729 size_t rest;
731 /* Eliminate comments. */
732 runp = file;
733 rest = file_size;
734 while (rest > 0)
736 char *comment = memchr (runp, '#', rest);
737 if (comment == NULL)
738 break;
740 rest -= comment - runp;
742 *comment = ' ';
743 while (--rest > 0 && *++comment != '\n');
746 /* We have one problematic case: if we have a name at the end of
747 the file without a trailing terminating characters, we cannot
748 place the \0. Handle the case separately. */
749 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
750 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
752 problem = &file[file_size];
753 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
754 && problem[-1] != '\n' && problem[-1] != ':')
755 --problem;
757 if (problem > file)
758 problem[-1] = '\0';
760 else
762 problem = NULL;
763 file[file_size - 1] = '\0';
766 HP_TIMING_NOW (start);
768 if (file != problem)
770 char *p;
771 runp = file;
772 while ((p = strsep (&runp, ": \t\n")) != NULL)
773 if (p[0] != '\0')
775 struct link_map *new_map = INT(_dl_map_object) (GL(dl_loaded),
776 p, 1,
777 lt_library,
778 0, 0);
779 if (++new_map->l_opencount == 1)
780 /* It is no duplicate. */
781 ++npreloads;
785 if (problem != NULL)
787 char *p = strndupa (problem, file_size - (problem - file));
788 struct link_map *new_map = INT(_dl_map_object) (GL(dl_loaded), p, 1,
789 lt_library, 0, 0);
790 if (++new_map->l_opencount == 1)
791 /* It is no duplicate. */
792 ++npreloads;
795 HP_TIMING_NOW (stop);
796 HP_TIMING_DIFF (diff, start, stop);
797 HP_TIMING_ACCUM_NT (load_time, diff);
799 /* We don't need the file anymore. */
800 __munmap (file, file_size);
803 if (__builtin_expect (npreloads, 0) != 0)
805 /* Set up PRELOADS with a vector of the preloaded libraries. */
806 struct link_map *l;
807 preloads = __alloca (npreloads * sizeof preloads[0]);
808 l = GL(dl_rtld_map).l_next; /* End of the chain before preloads. */
809 i = 0;
812 preloads[i++] = l;
813 l = l->l_next;
814 } while (l);
815 assert (i == npreloads);
818 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
819 specified some libraries to load, these are inserted before the actual
820 dependencies in the executable's searchlist for symbol resolution. */
821 HP_TIMING_NOW (start);
822 INT(_dl_map_object_deps) (GL(dl_loaded), preloads, npreloads, mode == trace);
823 HP_TIMING_NOW (stop);
824 HP_TIMING_DIFF (diff, start, stop);
825 HP_TIMING_ACCUM_NT (load_time, diff);
827 /* Mark all objects as being in the global scope and set the open
828 counter. */
829 for (i = GL(dl_loaded)->l_searchlist.r_nlist; i > 0; )
831 --i;
832 GL(dl_loaded)->l_searchlist.r_list[i]->l_global = 1;
833 ++GL(dl_loaded)->l_searchlist.r_list[i]->l_opencount;
836 #ifndef MAP_ANON
837 /* We are done mapping things, so close the zero-fill descriptor. */
838 __close (_dl_zerofd);
839 _dl_zerofd = -1;
840 #endif
842 /* Remove _dl_rtld_map from the chain. */
843 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
844 if (GL(dl_rtld_map).l_next)
845 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
847 if (__builtin_expect (GL(dl_rtld_map).l_opencount > 1, 1))
849 /* Some DT_NEEDED entry referred to the interpreter object itself, so
850 put it back in the list of visible objects. We insert it into the
851 chain in symbol search order because gdb uses the chain's order as
852 its symbol search order. */
853 i = 1;
854 while (GL(dl_loaded)->l_searchlist.r_list[i] != &GL(dl_rtld_map))
855 ++i;
856 GL(dl_rtld_map).l_prev = GL(dl_loaded)->l_searchlist.r_list[i - 1];
857 if (__builtin_expect (mode, normal) == normal)
858 GL(dl_rtld_map).l_next = (i + 1 < GL(dl_loaded)->l_searchlist.r_nlist
859 ? GL(dl_loaded)->l_searchlist.r_list[i + 1]
860 : NULL);
861 else
862 /* In trace mode there might be an invisible object (which we
863 could not find) after the previous one in the search list.
864 In this case it doesn't matter much where we put the
865 interpreter object, so we just initialize the list pointer so
866 that the assertion below holds. */
867 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
869 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
870 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
871 if (GL(dl_rtld_map).l_next)
873 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
874 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
878 /* Now let us see whether all libraries are available in the
879 versions we need. */
881 struct version_check_args args;
882 args.doexit = mode == normal;
883 args.dotrace = mode == trace;
884 _dl_receive_error (print_missing_version, version_check_doit, &args);
887 if (__builtin_expect (mode, normal) != normal)
889 /* We were run just to list the shared libraries. It is
890 important that we do this before real relocation, because the
891 functions we call below for output may no longer work properly
892 after relocation. */
893 if (! GL(dl_loaded)->l_info[DT_NEEDED])
894 _dl_printf ("\tstatically linked\n");
895 else
897 struct link_map *l;
899 if (GL(dl_debug_mask) & DL_DEBUG_PRELINK)
901 struct r_scope_elem *scope = &GL(dl_loaded)->l_searchlist;
903 for (i = 0; i < scope->r_nlist; i++)
905 l = scope->r_list [i];
906 if (l->l_faked)
908 _dl_printf ("\t%s => not found\n", l->l_libname->name);
909 continue;
911 if (_dl_name_match_p (GL(dl_trace_prelink), l))
912 GL(dl_trace_prelink_map) = l;
913 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)\n",
914 l->l_libname->name[0] ? l->l_libname->name
915 : _dl_argv[0] ?: "<main program>",
916 l->l_name[0] ? l->l_name
917 : _dl_argv[0] ?: "<main program>",
918 (int) sizeof l->l_map_start * 2,
919 l->l_map_start,
920 (int) sizeof l->l_addr * 2,
921 l->l_addr);
924 else
926 for (l = GL(dl_loaded)->l_next; l; l = l->l_next)
927 if (l->l_faked)
928 /* The library was not found. */
929 _dl_printf ("\t%s => not found\n", l->l_libname->name);
930 else
931 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
932 l->l_name, (int) sizeof l->l_map_start * 2,
933 l->l_map_start);
937 if (__builtin_expect (mode, trace) != trace)
938 for (i = 1; i < _dl_argc; ++i)
940 const ElfW(Sym) *ref = NULL;
941 ElfW(Addr) loadbase;
942 lookup_t result;
944 result = INT(_dl_lookup_symbol) (_dl_argv[i], GL(dl_loaded),
945 &ref, GL(dl_loaded)->l_scope,
946 ELF_RTYPE_CLASS_PLT, 1);
948 loadbase = LOOKUP_VALUE_ADDRESS (result);
950 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
951 _dl_argv[i],
952 (int) sizeof ref->st_value * 2, ref->st_value,
953 (int) sizeof loadbase * 2, loadbase);
955 else
957 /* If LD_WARN is set warn about undefined symbols. */
958 if (GL(dl_lazy) >= 0 && GL(dl_verbose))
960 /* We have to do symbol dependency testing. */
961 struct relocate_args args;
962 struct link_map *l;
964 args.lazy = GL(dl_lazy);
966 l = GL(dl_loaded);
967 while (l->l_next)
968 l = l->l_next;
971 if (l != &GL(dl_rtld_map) && ! l->l_faked)
973 args.l = l;
974 _dl_receive_error (print_unresolved, relocate_doit,
975 &args);
977 l = l->l_prev;
978 } while (l);
980 if ((GL(dl_debug_mask) & DL_DEBUG_PRELINK)
981 && GL(dl_rtld_map).l_opencount > 1)
982 INT(_dl_relocate_object) (&GL(dl_rtld_map),
983 GL(dl_loaded)->l_scope, 0, 0);
986 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
987 if (version_info)
989 /* Print more information. This means here, print information
990 about the versions needed. */
991 int first = 1;
992 struct link_map *map = GL(dl_loaded);
994 for (map = GL(dl_loaded); map != NULL; map = map->l_next)
996 const char *strtab;
997 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
998 ElfW(Verneed) *ent;
1000 if (dyn == NULL)
1001 continue;
1003 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
1004 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
1006 if (first)
1008 _dl_printf ("\n\tVersion information:\n");
1009 first = 0;
1012 _dl_printf ("\t%s:\n",
1013 map->l_name[0] ? map->l_name : _dl_argv[0]);
1015 while (1)
1017 ElfW(Vernaux) *aux;
1018 struct link_map *needed;
1020 needed = find_needed (strtab + ent->vn_file);
1021 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
1023 while (1)
1025 const char *fname = NULL;
1027 if (needed != NULL
1028 && match_version (strtab + aux->vna_name,
1029 needed))
1030 fname = needed->l_name;
1032 _dl_printf ("\t\t%s (%s) %s=> %s\n",
1033 strtab + ent->vn_file,
1034 strtab + aux->vna_name,
1035 aux->vna_flags & VER_FLG_WEAK
1036 ? "[WEAK] " : "",
1037 fname ?: "not found");
1039 if (aux->vna_next == 0)
1040 /* No more symbols. */
1041 break;
1043 /* Next symbol. */
1044 aux = (ElfW(Vernaux) *) ((char *) aux
1045 + aux->vna_next);
1048 if (ent->vn_next == 0)
1049 /* No more dependencies. */
1050 break;
1052 /* Next dependency. */
1053 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
1059 _exit (0);
1062 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]
1063 && ! __builtin_expect (GL(dl_profile) != NULL, 0))
1065 ElfW(Lib) *liblist, *liblistend;
1066 struct link_map **r_list, **r_listend, *l;
1067 const char *strtab = (const void *) D_PTR (GL(dl_loaded),
1068 l_info[DT_STRTAB]);
1070 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
1071 liblist = (ElfW(Lib) *)
1072 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
1073 liblistend = (ElfW(Lib) *)
1074 ((char *) liblist
1075 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
1076 r_list = GL(dl_loaded)->l_searchlist.r_list;
1077 r_listend = r_list + GL(dl_loaded)->l_searchlist.r_nlist;
1079 for (; r_list < r_listend && liblist < liblistend; r_list++)
1081 l = *r_list;
1083 if (l == GL(dl_loaded))
1084 continue;
1086 /* If the library is not mapped where it should, fail. */
1087 if (l->l_addr)
1088 break;
1090 /* Next, check if checksum matches. */
1091 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
1092 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
1093 != liblist->l_checksum)
1094 break;
1096 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
1097 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
1098 != liblist->l_time_stamp)
1099 break;
1101 if (! _dl_name_match_p (strtab + liblist->l_name, l))
1102 break;
1104 ++liblist;
1108 if (r_list == r_listend && liblist == liblistend)
1109 prelinked = 1;
1111 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1112 _dl_printf ("\nprelink checking: %s\n", prelinked ? "ok" : "failed");
1115 if (prelinked)
1117 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
1119 ElfW(Rela) *conflict, *conflictend;
1120 #ifndef HP_TIMING_NONAVAIL
1121 hp_timing_t start;
1122 hp_timing_t stop;
1123 #endif
1125 HP_TIMING_NOW (start);
1126 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
1127 conflict = (ElfW(Rela) *)
1128 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
1129 conflictend = (ElfW(Rela) *)
1130 ((char *) conflict
1131 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
1132 _dl_resolve_conflicts (GL(dl_loaded), conflict, conflictend);
1133 HP_TIMING_NOW (stop);
1134 HP_TIMING_DIFF (relocate_time, start, stop);
1137 _dl_sysdep_start_cleanup ();
1139 else
1141 /* Now we have all the objects loaded. Relocate them all except for
1142 the dynamic linker itself. We do this in reverse order so that copy
1143 relocs of earlier objects overwrite the data written by later
1144 objects. We do not re-relocate the dynamic linker itself in this
1145 loop because that could result in the GOT entries for functions we
1146 call being changed, and that would break us. It is safe to relocate
1147 the dynamic linker out of order because it has no copy relocs (we
1148 know that because it is self-contained). */
1150 struct link_map *l;
1151 int consider_profiling = GL(dl_profile) != NULL;
1152 #ifndef HP_TIMING_NONAVAIL
1153 hp_timing_t start;
1154 hp_timing_t stop;
1155 hp_timing_t add;
1156 #endif
1158 /* If we are profiling we also must do lazy reloaction. */
1159 GL(dl_lazy) |= consider_profiling;
1161 l = GL(dl_loaded);
1162 while (l->l_next)
1163 l = l->l_next;
1165 HP_TIMING_NOW (start);
1168 /* While we are at it, help the memory handling a bit. We have to
1169 mark some data structures as allocated with the fake malloc()
1170 implementation in ld.so. */
1171 struct libname_list *lnp = l->l_libname->next;
1173 while (__builtin_expect (lnp != NULL, 0))
1175 lnp->dont_free = 1;
1176 lnp = lnp->next;
1179 if (l != &GL(dl_rtld_map))
1180 INT(_dl_relocate_object) (l, l->l_scope, GL(dl_lazy),
1181 consider_profiling);
1183 l = l->l_prev;
1185 while (l);
1186 HP_TIMING_NOW (stop);
1188 HP_TIMING_DIFF (relocate_time, start, stop);
1190 /* Do any necessary cleanups for the startup OS interface code.
1191 We do these now so that no calls are made after rtld re-relocation
1192 which might be resolved to different functions than we expect.
1193 We cannot do this before relocating the other objects because
1194 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
1195 _dl_sysdep_start_cleanup ();
1197 /* Now enable profiling if needed. Like the previous call,
1198 this has to go here because the calls it makes should use the
1199 rtld versions of the functions (particularly calloc()), but it
1200 needs to have _dl_profile_map set up by the relocator. */
1201 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
1202 /* We must prepare the profiling. */
1203 INT(_dl_start_profile) (GL(dl_profile_map), GL(dl_profile_output));
1205 if (GL(dl_rtld_map).l_opencount > 1)
1207 /* There was an explicit ref to the dynamic linker as a shared lib.
1208 Re-relocate ourselves with user-controlled symbol definitions. */
1209 HP_TIMING_NOW (start);
1210 INT(_dl_relocate_object) (&GL(dl_rtld_map), GL(dl_loaded)->l_scope,
1211 0, 0);
1212 HP_TIMING_NOW (stop);
1213 HP_TIMING_DIFF (add, start, stop);
1214 HP_TIMING_ACCUM_NT (relocate_time, add);
1218 /* Now set up the variable which helps the assembler startup code. */
1219 GL(dl_main_searchlist) = &GL(dl_loaded)->l_searchlist;
1220 GL(dl_global_scope)[0] = &GL(dl_loaded)->l_searchlist;
1222 /* Save the information about the original global scope list since
1223 we need it in the memory handling later. */
1224 GL(dl_initial_searchlist) = *GL(dl_main_searchlist);
1227 /* Initialize _r_debug. */
1228 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr);
1229 struct link_map *l;
1231 l = GL(dl_loaded);
1233 #ifdef ELF_MACHINE_DEBUG_SETUP
1235 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1237 ELF_MACHINE_DEBUG_SETUP (l, r);
1238 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1240 #else
1242 if (l->l_info[DT_DEBUG])
1243 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1244 with the run-time address of the r_debug structure */
1245 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1247 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1248 case you run gdb on the dynamic linker directly. */
1249 if (GL(dl_rtld_map).l_info[DT_DEBUG])
1250 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1252 #endif
1254 /* Notify the debugger that all objects are now mapped in. */
1255 r->r_state = RT_ADD;
1256 INT(_dl_debug_state) ();
1259 #ifndef MAP_COPY
1260 /* We must munmap() the cache file. */
1261 INT(_dl_unload_cache) ();
1262 #endif
1264 /* Once we return, _dl_sysdep_start will invoke
1265 the DT_INIT functions and then *USER_ENTRY. */
1268 /* This is a little helper function for resolving symbols while
1269 tracing the binary. */
1270 static void
1271 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
1272 const char *errstring)
1274 if (objname[0] == '\0')
1275 objname = _dl_argv[0] ?: "<main program>";
1276 _dl_error_printf ("%s (%s)\n", errstring, objname);
1279 /* This is a little helper function for resolving symbols while
1280 tracing the binary. */
1281 static void
1282 print_missing_version (int errcode __attribute__ ((unused)),
1283 const char *objname, const char *errstring)
1285 _dl_error_printf ("%s: %s: %s\n", _dl_argv[0] ?: "<program name unknown>",
1286 objname, errstring);
1289 /* Nonzero if any of the debugging options is enabled. */
1290 static int any_debug;
1292 /* Process the string given as the parameter which explains which debugging
1293 options are enabled. */
1294 static void
1295 process_dl_debug (const char *dl_debug)
1297 /* When adding new entries make sure that the maximal length of a name
1298 is correctly handled in the LD_DEBUG_HELP code below. */
1299 static const struct
1301 unsigned char len;
1302 const char name[10];
1303 const char helptext[41];
1304 unsigned short int mask;
1305 } debopts[] =
1307 #define LEN_AND_STR(str) sizeof (str) - 1, str
1308 { LEN_AND_STR ("libs"), "display library search paths",
1309 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
1310 { LEN_AND_STR ("reloc"), "display relocation processing",
1311 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
1312 { LEN_AND_STR ("files"), "display progress for input file",
1313 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
1314 { LEN_AND_STR ("symbols"), "display symbol table processing",
1315 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
1316 { LEN_AND_STR ("bindings"), "display information about symbol binding",
1317 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
1318 { LEN_AND_STR ("versions"), "display version dependencies",
1319 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1320 { LEN_AND_STR ("all"), "all previous options combined",
1321 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
1322 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1323 { LEN_AND_STR ("statistics"), "display relocation statistics",
1324 DL_DEBUG_STATISTICS },
1325 { LEN_AND_STR ("help"), "display this help message and exit",
1326 DL_DEBUG_HELP },
1328 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
1330 /* Skip separating white spaces and commas. */
1331 while (*dl_debug != '\0')
1333 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
1335 size_t cnt;
1336 size_t len = 1;
1338 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
1339 && dl_debug[len] != ',' && dl_debug[len] != ':')
1340 ++len;
1342 for (cnt = 0; cnt < ndebopts; ++cnt)
1343 if (debopts[cnt].len == len
1344 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
1346 GL(dl_debug_mask) |= debopts[cnt].mask;
1347 any_debug = 1;
1348 break;
1351 if (cnt == ndebopts)
1353 /* Display a warning and skip everything until next
1354 separator. */
1355 char *copy = strndupa (dl_debug, len);
1356 _dl_error_printf ("\
1357 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
1360 dl_debug += len;
1361 continue;
1364 ++dl_debug;
1367 if (GL(dl_debug_mask) & DL_DEBUG_HELP)
1369 size_t cnt;
1371 _dl_printf ("\
1372 Valid options for the LD_DEBUG environment variable are:\n\n");
1374 for (cnt = 0; cnt < ndebopts; ++cnt)
1375 _dl_printf (" %s%s %s\n", debopts[cnt].name,
1376 " " + strlen (debopts[cnt].name) - 3,
1377 debopts[cnt].helptext);
1379 _dl_printf ("\n\
1380 To direct the debugging output into a file instead of standard output\n\
1381 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
1382 _exit (0);
1386 /* Process all environments variables the dynamic linker must recognize.
1387 Since all of them start with `LD_' we are a bit smarter while finding
1388 all the entries. */
1389 extern char **_environ;
1392 static void
1393 process_envvars (enum mode *modep)
1395 char **runp = _environ;
1396 char *envline;
1397 enum mode mode = normal;
1398 char *debug_output = NULL;
1400 /* This is the default place for profiling data file. */
1401 GL(dl_profile_output) = &"/var/tmp\0/var/profile"[__libc_enable_secure
1402 ? 9 : 0];
1404 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
1406 size_t len = 0;
1408 while (envline[len] != '\0' && envline[len] != '=')
1409 ++len;
1411 if (envline[len] != '=')
1412 /* This is a "LD_" variable at the end of the string without
1413 a '=' character. Ignore it since otherwise we will access
1414 invalid memory below. */
1415 continue;
1417 switch (len)
1419 case 4:
1420 /* Warning level, verbose or not. */
1421 if (memcmp (envline, "WARN", 4) == 0)
1422 GL(dl_verbose) = envline[5] != '\0';
1423 break;
1425 case 5:
1426 /* Debugging of the dynamic linker? */
1427 if (memcmp (envline, "DEBUG", 5) == 0)
1428 process_dl_debug (&envline[6]);
1429 break;
1431 case 7:
1432 /* Print information about versions. */
1433 if (memcmp (envline, "VERBOSE", 7) == 0)
1435 version_info = envline[8] != '\0';
1436 break;
1439 /* List of objects to be preloaded. */
1440 if (memcmp (envline, "PRELOAD", 7) == 0)
1442 preloadlist = &envline[8];
1443 break;
1446 /* Which shared object shall be profiled. */
1447 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
1448 GL(dl_profile) = &envline[8];
1449 break;
1451 case 8:
1452 /* Do we bind early? */
1453 if (memcmp (envline, "BIND_NOW", 8) == 0)
1455 GL(dl_lazy) = envline[9] == '\0';
1456 break;
1458 if (memcmp (envline, "BIND_NOT", 8) == 0)
1459 GL(dl_bind_not) = envline[9] != '\0';
1460 break;
1462 case 9:
1463 /* Test whether we want to see the content of the auxiliary
1464 array passed up from the kernel. */
1465 if (memcmp (envline, "SHOW_AUXV", 9) == 0)
1466 _dl_show_auxv ();
1467 break;
1469 case 10:
1470 /* Mask for the important hardware capabilities. */
1471 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
1472 GL(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL, 0, 0);
1473 break;
1475 case 11:
1476 /* Path where the binary is found. */
1477 if (!__libc_enable_secure
1478 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
1479 GL(dl_origin_path) = &envline[12];
1480 break;
1482 case 12:
1483 /* The library search path. */
1484 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
1486 library_path = &envline[13];
1487 break;
1490 /* Where to place the profiling data file. */
1491 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
1493 debug_output = &envline[13];
1494 break;
1497 if (memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
1498 GL(dl_dynamic_weak) = 1;
1499 break;
1501 case 14:
1502 /* Where to place the profiling data file. */
1503 if (!__libc_enable_secure
1504 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
1505 && envline[15] != '\0')
1506 GL(dl_profile_output) = &envline[15];
1507 break;
1509 case 16:
1510 /* The mode of the dynamic linker can be set. */
1511 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
1513 mode = trace;
1514 GL(dl_verbose) = 1;
1515 GL(dl_debug_mask) |= DL_DEBUG_PRELINK;
1516 GL(dl_trace_prelink) = &envline[17];
1518 break;
1520 case 20:
1521 /* The mode of the dynamic linker can be set. */
1522 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
1523 mode = trace;
1524 break;
1526 /* We might have some extra environment variable to handle. This
1527 is tricky due to the pre-processing of the length of the name
1528 in the switch statement here. The code here assumes that added
1529 environment variables have a different length. */
1530 #ifdef EXTRA_LD_ENVVARS
1531 EXTRA_LD_ENVVARS
1532 #endif
1536 /* The caller wants this information. */
1537 *modep = mode;
1539 /* Extra security for SUID binaries. Remove all dangerous environment
1540 variables. */
1541 if (__builtin_expect (__libc_enable_secure, 0))
1543 static const char unsecure_envvars[] =
1544 #ifdef EXTRA_UNSECURE_ENVVARS
1545 EXTRA_UNSECURE_ENVVARS
1546 #endif
1547 UNSECURE_ENVVARS;
1548 const char *nextp;
1550 nextp = unsecure_envvars;
1553 unsetenv (nextp);
1554 /* We could use rawmemchr but this need not be fast. */
1555 nextp = (char *) (strchr) (nextp, '\0') + 1;
1557 while (*nextp != '\0');
1559 if (__access ("/etc/suid-debug", F_OK) != 0)
1560 unsetenv ("MALLOC_CHECK_");
1562 /* If we have to run the dynamic linker in debugging mode and the
1563 LD_DEBUG_OUTPUT environment variable is given, we write the debug
1564 messages to this file. */
1565 else if (any_debug && debug_output != NULL)
1567 #ifdef O_NOFOLLOW
1568 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
1569 #else
1570 const int flags = O_WRONLY | O_APPEND | O_CREAT;
1571 #endif
1572 size_t name_len = strlen (debug_output);
1573 char buf[name_len + 12];
1574 char *startp;
1576 buf[name_len + 11] = '\0';
1577 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
1578 *--startp = '.';
1579 startp = memcpy (startp - name_len, debug_output, name_len);
1581 GL(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
1582 if (GL(dl_debug_fd) == -1)
1583 /* We use standard output if opening the file failed. */
1584 GL(dl_debug_fd) = STDOUT_FILENO;
1589 /* Print the various times we collected. */
1590 static void
1591 print_statistics (void)
1593 #ifndef HP_TIMING_NONAVAIL
1594 char buf[200];
1595 char *cp;
1596 char *wp;
1598 /* Total time rtld used. */
1599 if (HP_TIMING_AVAIL)
1601 HP_TIMING_PRINT (buf, sizeof (buf), rtld_total_time);
1602 INT(_dl_debug_printf) ("\nruntime linker statistics:\n"
1603 " total startup time in dynamic loader: %s\n",
1604 buf);
1607 /* Print relocation statistics. */
1608 if (HP_TIMING_AVAIL)
1610 char pbuf[30];
1611 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
1612 cp = _itoa ((1000ULL * relocate_time) / rtld_total_time,
1613 pbuf + sizeof (pbuf), 10, 0);
1614 wp = pbuf;
1615 switch (pbuf + sizeof (pbuf) - cp)
1617 case 3:
1618 *wp++ = *cp++;
1619 case 2:
1620 *wp++ = *cp++;
1621 case 1:
1622 *wp++ = '.';
1623 *wp++ = *cp++;
1625 *wp = '\0';
1626 INT(_dl_debug_printf) ("\
1627 time needed for relocation: %s (%s%%)\n",
1628 buf, pbuf);
1630 #endif
1631 INT(_dl_debug_printf) (" number of relocations: %lu\n",
1632 GL(dl_num_relocations));
1633 INT(_dl_debug_printf) (" number of relocations from cache: %lu\n",
1634 GL(dl_num_cache_relocations));
1636 #ifndef HP_TIMING_NONAVAIL
1637 /* Time spend while loading the object and the dependencies. */
1638 if (HP_TIMING_AVAIL)
1640 char pbuf[30];
1641 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
1642 cp = _itoa ((1000ULL * load_time) / rtld_total_time,
1643 pbuf + sizeof (pbuf), 10, 0);
1644 wp = pbuf;
1645 switch (pbuf + sizeof (pbuf) - cp)
1647 case 3:
1648 *wp++ = *cp++;
1649 case 2:
1650 *wp++ = *cp++;
1651 case 1:
1652 *wp++ = '.';
1653 *wp++ = *cp++;
1655 *wp = '\0';
1656 INT(_dl_debug_printf) ("\
1657 time needed to load objects: %s (%s%%)\n",
1658 buf, pbuf);
1660 #endif