Update.
[glibc.git] / elf / rtld.c
blobb835bd5dda95901c6b2c00b27841506d24ad966f
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 _dl_relocate_object (args->l, args->l->l_scope,
301 args->lazy, 0);
304 static void
305 map_doit (void *a)
307 struct map_args *args = (struct map_args *) a;
308 args->main_map = _dl_map_object (NULL, args->str, 0, lt_library, 0, 0);
311 static void
312 version_check_doit (void *a)
314 struct version_check_args *args = (struct version_check_args *) a;
315 if (_dl_check_all_versions (GL(dl_loaded), 1, args->dotrace) && args->doexit)
316 /* We cannot start the application. Abort now. */
317 _exit (1);
321 static inline struct link_map *
322 find_needed (const char *name)
324 unsigned int n = GL(dl_loaded)->l_searchlist.r_nlist;
326 while (n-- > 0)
327 if (_dl_name_match_p (name, GL(dl_loaded)->l_searchlist.r_list[n]))
328 return GL(dl_loaded)->l_searchlist.r_list[n];
330 /* Should never happen. */
331 return NULL;
334 static int
335 match_version (const char *string, struct link_map *map)
337 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
338 ElfW(Verdef) *def;
340 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
341 if (map->l_info[VERDEFTAG] == NULL)
342 /* The file has no symbol versioning. */
343 return 0;
345 def = (ElfW(Verdef) *) ((char *) map->l_addr
346 + map->l_info[VERDEFTAG]->d_un.d_ptr);
347 while (1)
349 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
351 /* Compare the version strings. */
352 if (strcmp (string, strtab + aux->vda_name) == 0)
353 /* Bingo! */
354 return 1;
356 /* If no more definitions we failed to find what we want. */
357 if (def->vd_next == 0)
358 break;
360 /* Next definition. */
361 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
364 return 0;
367 static const char *library_path; /* The library search path. */
368 static const char *preloadlist; /* The list preloaded objects. */
369 static int version_info; /* Nonzero if information about
370 versions has to be printed. */
372 static void
373 dl_main (const ElfW(Phdr) *phdr,
374 ElfW(Word) phnum,
375 ElfW(Addr) *user_entry)
377 const ElfW(Phdr) *ph;
378 enum mode mode;
379 struct link_map **preloads;
380 unsigned int npreloads;
381 size_t file_size;
382 char *file;
383 int has_interp = 0;
384 unsigned int i;
385 int prelinked = 0;
386 int rtld_is_main = 0;
387 #ifndef HP_TIMING_NONAVAIL
388 hp_timing_t start;
389 hp_timing_t stop;
390 hp_timing_t diff;
391 #endif
393 /* Process the environment variable which control the behaviour. */
394 process_envvars (&mode);
396 /* Set up a flag which tells we are just starting. */
397 _dl_starting_up = 1;
399 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
401 /* Ho ho. We are not the program interpreter! We are the program
402 itself! This means someone ran ld.so as a command. Well, that
403 might be convenient to do sometimes. We support it by
404 interpreting the args like this:
406 ld.so PROGRAM ARGS...
408 The first argument is the name of a file containing an ELF
409 executable we will load and run with the following arguments.
410 To simplify life here, PROGRAM is searched for using the
411 normal rules for shared objects, rather than $PATH or anything
412 like that. We just load it and use its entry point; we don't
413 pay attention to its PT_INTERP command (we are the interpreter
414 ourselves). This is an easy way to test a new ld.so before
415 installing it. */
416 rtld_is_main = 1;
418 /* Note the place where the dynamic linker actually came from. */
419 GL(dl_rtld_map).l_name = _dl_argv[0];
421 while (_dl_argc > 1)
422 if (! strcmp (_dl_argv[1], "--list"))
424 mode = list;
425 GL(dl_lazy) = -1; /* This means do no dependency analysis. */
427 ++_dl_skip_args;
428 --_dl_argc;
429 ++_dl_argv;
431 else if (! strcmp (_dl_argv[1], "--verify"))
433 mode = verify;
435 ++_dl_skip_args;
436 --_dl_argc;
437 ++_dl_argv;
439 else if (! strcmp (_dl_argv[1], "--library-path") && _dl_argc > 2)
441 library_path = _dl_argv[2];
443 _dl_skip_args += 2;
444 _dl_argc -= 2;
445 _dl_argv += 2;
447 else if (! strcmp (_dl_argv[1], "--inhibit-rpath") && _dl_argc > 2)
449 GL(dl_inhibit_rpath) = _dl_argv[2];
451 _dl_skip_args += 2;
452 _dl_argc -= 2;
453 _dl_argv += 2;
455 else
456 break;
458 /* If we have no further argument the program was called incorrectly.
459 Grant the user some education. */
460 if (_dl_argc < 2)
461 _dl_fatal_printf ("\
462 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
463 You have invoked `ld.so', the helper program for shared library executables.\n\
464 This program usually lives in the file `/lib/ld.so', and special directives\n\
465 in executable files using ELF shared libraries tell the system's program\n\
466 loader to load the helper program from this file. This helper program loads\n\
467 the shared libraries needed by the program executable, prepares the program\n\
468 to run, and runs it. You may invoke this helper program directly from the\n\
469 command line to load and run an ELF executable file; this is like executing\n\
470 that file itself, but always uses this helper program from the file you\n\
471 specified, instead of the helper program file specified in the executable\n\
472 file you run. This is mostly of use for maintainers to test new versions\n\
473 of this helper program; chances are you did not intend to run this program.\n\
475 --list list all dependencies and how they are resolved\n\
476 --verify verify that given object really is a dynamically linked\n\
477 object we can handle\n\
478 --library-path PATH use given PATH instead of content of the environment\n\
479 variable LD_LIBRARY_PATH\n\
480 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
481 in LIST\n");
483 ++_dl_skip_args;
484 --_dl_argc;
485 ++_dl_argv;
487 /* Initialize the data structures for the search paths for shared
488 objects. */
489 _dl_init_paths (library_path);
491 if (__builtin_expect (mode, normal) == verify)
493 const char *objname;
494 const char *err_str = NULL;
495 struct map_args args;
497 args.str = _dl_argv[0];
498 (void) _dl_catch_error (&objname, &err_str, map_doit, &args);
499 if (__builtin_expect (err_str != NULL, 0))
501 if (err_str != _dl_out_of_memory)
502 free ((char *) err_str);
503 _exit (EXIT_FAILURE);
506 else
508 HP_TIMING_NOW (start);
509 _dl_map_object (NULL, _dl_argv[0], 0, lt_library, 0, 0);
510 HP_TIMING_NOW (stop);
512 HP_TIMING_DIFF (load_time, start, stop);
515 phdr = GL(dl_loaded)->l_phdr;
516 phnum = GL(dl_loaded)->l_phnum;
517 /* We overwrite here a pointer to a malloc()ed string. But since
518 the malloc() implementation used at this point is the dummy
519 implementations which has no real free() function it does not
520 makes sense to free the old string first. */
521 GL(dl_loaded)->l_name = (char *) "";
522 *user_entry = GL(dl_loaded)->l_entry;
524 else
526 /* Create a link_map for the executable itself.
527 This will be what dlopen on "" returns. */
528 _dl_new_object ((char *) "", "", lt_executable, NULL);
529 if (GL(dl_loaded) == NULL)
530 _dl_fatal_printf ("cannot allocate memory for link map\n");
531 GL(dl_loaded)->l_phdr = phdr;
532 GL(dl_loaded)->l_phnum = phnum;
533 GL(dl_loaded)->l_entry = *user_entry;
535 /* At this point we are in a bit of trouble. We would have to
536 fill in the values for l_dev and l_ino. But in general we
537 do not know where the file is. We also do not handle AT_EXECFD
538 even if it would be passed up.
540 We leave the values here defined to 0. This is normally no
541 problem as the program code itself is normally no shared
542 object and therefore cannot be loaded dynamically. Nothing
543 prevent the use of dynamic binaries and in these situations
544 we might get problems. We might not be able to find out
545 whether the object is already loaded. But since there is no
546 easy way out and because the dynamic binary must also not
547 have an SONAME we ignore this program for now. If it becomes
548 a problem we can force people using SONAMEs. */
550 /* We delay initializing the path structure until we got the dynamic
551 information for the program. */
554 GL(dl_loaded)->l_map_end = 0;
555 /* Perhaps the executable has no PT_LOAD header entries at all. */
556 GL(dl_loaded)->l_map_start = ~0;
557 /* We opened the file, account for it. */
558 ++GL(dl_loaded)->l_opencount;
560 /* Scan the program header table for the dynamic section. */
561 for (ph = phdr; ph < &phdr[phnum]; ++ph)
562 switch (ph->p_type)
564 case PT_PHDR:
565 /* Find out the load address. */
566 GL(dl_loaded)->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
567 break;
568 case PT_DYNAMIC:
569 /* This tells us where to find the dynamic section,
570 which tells us everything we need to do. */
571 GL(dl_loaded)->l_ld = (void *) GL(dl_loaded)->l_addr + ph->p_vaddr;
572 break;
573 case PT_INTERP:
574 /* This "interpreter segment" was used by the program loader to
575 find the program interpreter, which is this program itself, the
576 dynamic linker. We note what name finds us, so that a future
577 dlopen call or DT_NEEDED entry, for something that wants to link
578 against the dynamic linker as a shared library, will know that
579 the shared object is already loaded. */
580 _dl_rtld_libname.name = ((const char *) GL(dl_loaded)->l_addr
581 + ph->p_vaddr);
582 /* _dl_rtld_libname.next = NULL; Already zero. */
583 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
585 /* Ordinarilly, we would get additional names for the loader from
586 our DT_SONAME. This can't happen if we were actually linked as
587 a static executable (detect this case when we have no DYNAMIC).
588 If so, assume the filename component of the interpreter path to
589 be our SONAME, and add it to our name list. */
590 if (GL(dl_rtld_map).l_ld == NULL)
592 const char *p = NULL;
593 const char *cp = _dl_rtld_libname.name;
595 /* Find the filename part of the path. */
596 while (*cp != '\0')
597 if (*cp++ == '/')
598 p = cp;
600 if (p != NULL)
602 _dl_rtld_libname2.name = p;
603 /* _dl_rtld_libname2.next = NULL; Already zero. */
604 _dl_rtld_libname.next = &_dl_rtld_libname2;
608 has_interp = 1;
609 break;
610 case PT_LOAD:
612 ElfW(Addr) mapstart;
613 ElfW(Addr) allocend;
615 /* Remember where the main program starts in memory. */
616 mapstart = (GL(dl_loaded)->l_addr
617 + (ph->p_vaddr & ~(ph->p_align - 1)));
618 if (GL(dl_loaded)->l_map_start > mapstart)
619 GL(dl_loaded)->l_map_start = mapstart;
621 /* Also where it ends. */
622 allocend = GL(dl_loaded)->l_addr + ph->p_vaddr + ph->p_memsz;
623 if (GL(dl_loaded)->l_map_end < allocend)
624 GL(dl_loaded)->l_map_end = allocend;
626 break;
628 if (! GL(dl_loaded)->l_map_end)
629 GL(dl_loaded)->l_map_end = ~0;
630 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
632 /* We were invoked directly, so the program might not have a
633 PT_INTERP. */
634 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
635 /* _dl_rtld_libname.next = NULL; Alread zero. */
636 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
638 else
639 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
641 if (! rtld_is_main)
643 /* Extract the contents of the dynamic section for easy access. */
644 elf_get_dynamic_info (GL(dl_loaded));
645 if (GL(dl_loaded)->l_info[DT_HASH])
646 /* Set up our cache of pointers into the hash table. */
647 _dl_setup_hash (GL(dl_loaded));
650 if (__builtin_expect (mode, normal) == verify)
652 /* We were called just to verify that this is a dynamic
653 executable using us as the program interpreter. Exit with an
654 error if we were not able to load the binary or no interpreter
655 is specified (i.e., this is no dynamically linked binary. */
656 if (GL(dl_loaded)->l_ld == NULL)
657 _exit (1);
659 /* We allow here some platform specific code. */
660 #ifdef DISTINGUISH_LIB_VERSIONS
661 DISTINGUISH_LIB_VERSIONS;
662 #endif
663 _exit (has_interp ? 0 : 2);
666 if (! rtld_is_main)
667 /* Initialize the data structures for the search paths for shared
668 objects. */
669 _dl_init_paths (library_path);
671 /* Put the link_map for ourselves on the chain so it can be found by
672 name. Note that at this point the global chain of link maps contains
673 exactly one element, which is pointed to by dl_loaded. */
674 if (! GL(dl_rtld_map).l_name)
675 /* If not invoked directly, the dynamic linker shared object file was
676 found by the PT_INTERP name. */
677 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
678 GL(dl_rtld_map).l_type = lt_library;
679 GL(dl_loaded)->l_next = &GL(dl_rtld_map);
680 GL(dl_rtld_map).l_prev = GL(dl_loaded);
681 ++GL(dl_nloaded);
683 /* We have two ways to specify objects to preload: via environment
684 variable and via the file /etc/ld.so.preload. The latter can also
685 be used when security is enabled. */
686 preloads = NULL;
687 npreloads = 0;
689 if (__builtin_expect (preloadlist != NULL, 0))
691 /* The LD_PRELOAD environment variable gives list of libraries
692 separated by white space or colons that are loaded before the
693 executable's dependencies and prepended to the global scope
694 list. If the binary is running setuid all elements
695 containing a '/' are ignored since it is insecure. */
696 char *list = strdupa (preloadlist);
697 char *p;
699 HP_TIMING_NOW (start);
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 = _dl_map_object (GL(dl_loaded), p, 1,
707 lt_library, 0, 0);
708 if (++new_map->l_opencount == 1)
709 /* It is no duplicate. */
710 ++npreloads;
713 HP_TIMING_NOW (stop);
714 HP_TIMING_DIFF (diff, start, stop);
715 HP_TIMING_ACCUM_NT (load_time, diff);
718 /* Read the contents of the file. */
719 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
720 PROT_READ | PROT_WRITE);
721 if (__builtin_expect (file != MAP_FAILED, 0))
723 /* Parse the file. It contains names of libraries to be loaded,
724 separated by white spaces or `:'. It may also contain
725 comments introduced by `#'. */
726 char *problem;
727 char *runp;
728 size_t rest;
730 /* Eliminate comments. */
731 runp = file;
732 rest = file_size;
733 while (rest > 0)
735 char *comment = memchr (runp, '#', rest);
736 if (comment == NULL)
737 break;
739 rest -= comment - runp;
741 *comment = ' ';
742 while (--rest > 0 && *++comment != '\n');
745 /* We have one problematic case: if we have a name at the end of
746 the file without a trailing terminating characters, we cannot
747 place the \0. Handle the case separately. */
748 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
749 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
751 problem = &file[file_size];
752 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
753 && problem[-1] != '\n' && problem[-1] != ':')
754 --problem;
756 if (problem > file)
757 problem[-1] = '\0';
759 else
761 problem = NULL;
762 file[file_size - 1] = '\0';
765 HP_TIMING_NOW (start);
767 if (file != problem)
769 char *p;
770 runp = file;
771 while ((p = strsep (&runp, ": \t\n")) != NULL)
772 if (p[0] != '\0')
774 struct link_map *new_map = _dl_map_object (GL(dl_loaded), p, 1,
775 lt_library, 0, 0);
776 if (++new_map->l_opencount == 1)
777 /* It is no duplicate. */
778 ++npreloads;
782 if (problem != NULL)
784 char *p = strndupa (problem, file_size - (problem - file));
785 struct link_map *new_map = _dl_map_object (GL(dl_loaded), p, 1,
786 lt_library, 0, 0);
787 if (++new_map->l_opencount == 1)
788 /* It is no duplicate. */
789 ++npreloads;
792 HP_TIMING_NOW (stop);
793 HP_TIMING_DIFF (diff, start, stop);
794 HP_TIMING_ACCUM_NT (load_time, diff);
796 /* We don't need the file anymore. */
797 __munmap (file, file_size);
800 if (__builtin_expect (npreloads, 0) != 0)
802 /* Set up PRELOADS with a vector of the preloaded libraries. */
803 struct link_map *l;
804 preloads = __alloca (npreloads * sizeof preloads[0]);
805 l = GL(dl_rtld_map).l_next; /* End of the chain before preloads. */
806 i = 0;
809 preloads[i++] = l;
810 l = l->l_next;
811 } while (l);
812 assert (i == npreloads);
815 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
816 specified some libraries to load, these are inserted before the actual
817 dependencies in the executable's searchlist for symbol resolution. */
818 HP_TIMING_NOW (start);
819 _dl_map_object_deps (GL(dl_loaded), preloads, npreloads, mode == trace);
820 HP_TIMING_NOW (stop);
821 HP_TIMING_DIFF (diff, start, stop);
822 HP_TIMING_ACCUM_NT (load_time, diff);
824 /* Mark all objects as being in the global scope and set the open
825 counter. */
826 for (i = GL(dl_loaded)->l_searchlist.r_nlist; i > 0; )
828 --i;
829 GL(dl_loaded)->l_searchlist.r_list[i]->l_global = 1;
830 ++GL(dl_loaded)->l_searchlist.r_list[i]->l_opencount;
833 #ifndef MAP_ANON
834 /* We are done mapping things, so close the zero-fill descriptor. */
835 __close (_dl_zerofd);
836 _dl_zerofd = -1;
837 #endif
839 /* Remove _dl_rtld_map from the chain. */
840 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
841 if (GL(dl_rtld_map).l_next)
842 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
844 if (__builtin_expect (GL(dl_rtld_map).l_opencount > 1, 1))
846 /* Some DT_NEEDED entry referred to the interpreter object itself, so
847 put it back in the list of visible objects. We insert it into the
848 chain in symbol search order because gdb uses the chain's order as
849 its symbol search order. */
850 i = 1;
851 while (GL(dl_loaded)->l_searchlist.r_list[i] != &GL(dl_rtld_map))
852 ++i;
853 GL(dl_rtld_map).l_prev = GL(dl_loaded)->l_searchlist.r_list[i - 1];
854 if (__builtin_expect (mode, normal) == normal)
855 GL(dl_rtld_map).l_next = (i + 1 < GL(dl_loaded)->l_searchlist.r_nlist
856 ? GL(dl_loaded)->l_searchlist.r_list[i + 1]
857 : NULL);
858 else
859 /* In trace mode there might be an invisible object (which we
860 could not find) after the previous one in the search list.
861 In this case it doesn't matter much where we put the
862 interpreter object, so we just initialize the list pointer so
863 that the assertion below holds. */
864 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
866 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
867 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
868 if (GL(dl_rtld_map).l_next)
870 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
871 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
875 /* Now let us see whether all libraries are available in the
876 versions we need. */
878 struct version_check_args args;
879 args.doexit = mode == normal;
880 args.dotrace = mode == trace;
881 _dl_receive_error (print_missing_version, version_check_doit, &args);
884 if (__builtin_expect (mode, normal) != normal)
886 /* We were run just to list the shared libraries. It is
887 important that we do this before real relocation, because the
888 functions we call below for output may no longer work properly
889 after relocation. */
890 if (! GL(dl_loaded)->l_info[DT_NEEDED])
891 _dl_printf ("\tstatically linked\n");
892 else
894 struct link_map *l;
896 if (GL(dl_debug_mask) & DL_DEBUG_PRELINK)
898 struct r_scope_elem *scope = &GL(dl_loaded)->l_searchlist;
900 for (i = 0; i < scope->r_nlist; i++)
902 l = scope->r_list [i];
903 if (l->l_faked)
905 _dl_printf ("\t%s => not found\n", l->l_libname->name);
906 continue;
908 if (_dl_name_match_p (GL(dl_trace_prelink), l))
909 GL(dl_trace_prelink_map) = l;
910 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)\n",
911 l->l_libname->name[0] ? l->l_libname->name
912 : _dl_argv[0] ?: "<main program>",
913 l->l_name[0] ? l->l_name
914 : _dl_argv[0] ?: "<main program>",
915 (int) sizeof l->l_map_start * 2,
916 l->l_map_start,
917 (int) sizeof l->l_addr * 2,
918 l->l_addr);
921 else
923 for (l = GL(dl_loaded)->l_next; l; l = l->l_next)
924 if (l->l_faked)
925 /* The library was not found. */
926 _dl_printf ("\t%s => not found\n", l->l_libname->name);
927 else
928 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
929 l->l_name, (int) sizeof l->l_map_start * 2,
930 l->l_map_start);
934 if (__builtin_expect (mode, trace) != trace)
935 for (i = 1; i < _dl_argc; ++i)
937 const ElfW(Sym) *ref = NULL;
938 ElfW(Addr) loadbase;
939 lookup_t result;
941 result = _dl_lookup_symbol (_dl_argv[i], GL(dl_loaded),
942 &ref, GL(dl_loaded)->l_scope,
943 ELF_RTYPE_CLASS_PLT, 1);
945 loadbase = LOOKUP_VALUE_ADDRESS (result);
947 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
948 _dl_argv[i],
949 (int) sizeof ref->st_value * 2, ref->st_value,
950 (int) sizeof loadbase * 2, loadbase);
952 else
954 /* If LD_WARN is set warn about undefined symbols. */
955 if (GL(dl_lazy) >= 0 && GL(dl_verbose))
957 /* We have to do symbol dependency testing. */
958 struct relocate_args args;
959 struct link_map *l;
961 args.lazy = GL(dl_lazy);
963 l = GL(dl_loaded);
964 while (l->l_next)
965 l = l->l_next;
968 if (l != &GL(dl_rtld_map) && ! l->l_faked)
970 args.l = l;
971 _dl_receive_error (print_unresolved, relocate_doit,
972 &args);
974 l = l->l_prev;
975 } while (l);
977 if ((GL(dl_debug_mask) & DL_DEBUG_PRELINK)
978 && GL(dl_rtld_map).l_opencount > 1)
979 _dl_relocate_object (&GL(dl_rtld_map), GL(dl_loaded)->l_scope,
980 0, 0);
983 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
984 if (version_info)
986 /* Print more information. This means here, print information
987 about the versions needed. */
988 int first = 1;
989 struct link_map *map = GL(dl_loaded);
991 for (map = GL(dl_loaded); map != NULL; map = map->l_next)
993 const char *strtab;
994 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
995 ElfW(Verneed) *ent;
997 if (dyn == NULL)
998 continue;
1000 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
1001 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
1003 if (first)
1005 _dl_printf ("\n\tVersion information:\n");
1006 first = 0;
1009 _dl_printf ("\t%s:\n",
1010 map->l_name[0] ? map->l_name : _dl_argv[0]);
1012 while (1)
1014 ElfW(Vernaux) *aux;
1015 struct link_map *needed;
1017 needed = find_needed (strtab + ent->vn_file);
1018 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
1020 while (1)
1022 const char *fname = NULL;
1024 if (needed != NULL
1025 && match_version (strtab + aux->vna_name,
1026 needed))
1027 fname = needed->l_name;
1029 _dl_printf ("\t\t%s (%s) %s=> %s\n",
1030 strtab + ent->vn_file,
1031 strtab + aux->vna_name,
1032 aux->vna_flags & VER_FLG_WEAK
1033 ? "[WEAK] " : "",
1034 fname ?: "not found");
1036 if (aux->vna_next == 0)
1037 /* No more symbols. */
1038 break;
1040 /* Next symbol. */
1041 aux = (ElfW(Vernaux) *) ((char *) aux
1042 + aux->vna_next);
1045 if (ent->vn_next == 0)
1046 /* No more dependencies. */
1047 break;
1049 /* Next dependency. */
1050 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
1056 _exit (0);
1059 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]
1060 && ! __builtin_expect (GL(dl_profile) != NULL, 0))
1062 ElfW(Lib) *liblist, *liblistend;
1063 struct link_map **r_list, **r_listend, *l;
1064 const char *strtab = (const void *)
1065 D_PTR (GL(dl_loaded), l_info[DT_STRTAB]);
1067 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
1068 liblist = (ElfW(Lib) *)
1069 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
1070 liblistend = (ElfW(Lib) *)
1071 ((char *) liblist
1072 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
1073 r_list = GL(dl_loaded)->l_searchlist.r_list;
1074 r_listend = r_list + GL(dl_loaded)->l_searchlist.r_nlist;
1076 for (; r_list < r_listend && liblist < liblistend; r_list++)
1078 l = *r_list;
1080 if (l == GL(dl_loaded))
1081 continue;
1083 /* If the library is not mapped where it should, fail. */
1084 if (l->l_addr)
1085 break;
1087 /* Next, check if checksum matches. */
1088 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
1089 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
1090 != liblist->l_checksum)
1091 break;
1093 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
1094 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
1095 != liblist->l_time_stamp)
1096 break;
1098 if (! _dl_name_match_p (strtab + liblist->l_name, l))
1099 break;
1101 ++liblist;
1105 if (r_list == r_listend && liblist == liblistend)
1106 prelinked = 1;
1108 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1109 _dl_printf ("\nprelink checking: %s\n", prelinked ? "ok" : "failed");
1112 if (prelinked)
1114 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
1116 ElfW(Rela) *conflict, *conflictend;
1117 #ifndef HP_TIMING_NONAVAIL
1118 hp_timing_t start;
1119 hp_timing_t stop;
1120 #endif
1122 HP_TIMING_NOW (start);
1123 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
1124 conflict = (ElfW(Rela) *)
1125 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
1126 conflictend = (ElfW(Rela) *)
1127 ((char *) conflict
1128 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
1129 _dl_resolve_conflicts (GL(dl_loaded), conflict, conflictend);
1130 HP_TIMING_NOW (stop);
1131 HP_TIMING_DIFF (relocate_time, start, stop);
1134 _dl_sysdep_start_cleanup ();
1136 else
1138 /* Now we have all the objects loaded. Relocate them all except for
1139 the dynamic linker itself. We do this in reverse order so that copy
1140 relocs of earlier objects overwrite the data written by later
1141 objects. We do not re-relocate the dynamic linker itself in this
1142 loop because that could result in the GOT entries for functions we
1143 call being changed, and that would break us. It is safe to relocate
1144 the dynamic linker out of order because it has no copy relocs (we
1145 know that because it is self-contained). */
1147 struct link_map *l;
1148 int consider_profiling = GL(dl_profile) != NULL;
1149 #ifndef HP_TIMING_NONAVAIL
1150 hp_timing_t start;
1151 hp_timing_t stop;
1152 hp_timing_t add;
1153 #endif
1155 /* If we are profiling we also must do lazy reloaction. */
1156 GL(dl_lazy) |= consider_profiling;
1158 l = GL(dl_loaded);
1159 while (l->l_next)
1160 l = l->l_next;
1162 HP_TIMING_NOW (start);
1165 /* While we are at it, help the memory handling a bit. We have to
1166 mark some data structures as allocated with the fake malloc()
1167 implementation in ld.so. */
1168 struct libname_list *lnp = l->l_libname->next;
1170 while (__builtin_expect (lnp != NULL, 0))
1172 lnp->dont_free = 1;
1173 lnp = lnp->next;
1176 if (l != &GL(dl_rtld_map))
1177 _dl_relocate_object (l, l->l_scope, GL(dl_lazy), consider_profiling);
1179 l = l->l_prev;
1181 while (l);
1182 HP_TIMING_NOW (stop);
1184 HP_TIMING_DIFF (relocate_time, start, stop);
1186 /* Do any necessary cleanups for the startup OS interface code.
1187 We do these now so that no calls are made after rtld re-relocation
1188 which might be resolved to different functions than we expect.
1189 We cannot do this before relocating the other objects because
1190 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
1191 _dl_sysdep_start_cleanup ();
1193 /* Now enable profiling if needed. Like the previous call,
1194 this has to go here because the calls it makes should use the
1195 rtld versions of the functions (particularly calloc()), but it
1196 needs to have _dl_profile_map set up by the relocator. */
1197 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
1198 /* We must prepare the profiling. */
1199 _dl_start_profile (GL(dl_profile_map), GL(dl_profile_output));
1201 if (GL(dl_rtld_map).l_opencount > 1)
1203 /* There was an explicit ref to the dynamic linker as a shared lib.
1204 Re-relocate ourselves with user-controlled symbol definitions. */
1205 HP_TIMING_NOW (start);
1206 _dl_relocate_object (&GL(dl_rtld_map), GL(dl_loaded)->l_scope, 0, 0);
1207 HP_TIMING_NOW (stop);
1208 HP_TIMING_DIFF (add, start, stop);
1209 HP_TIMING_ACCUM_NT (relocate_time, add);
1213 /* Now set up the variable which helps the assembler startup code. */
1214 GL(dl_main_searchlist) = &GL(dl_loaded)->l_searchlist;
1215 GL(dl_global_scope)[0] = &GL(dl_loaded)->l_searchlist;
1217 /* Save the information about the original global scope list since
1218 we need it in the memory handling later. */
1219 GL(dl_initial_searchlist) = *GL(dl_main_searchlist);
1222 /* Initialize _r_debug. */
1223 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr);
1224 struct link_map *l;
1226 l = GL(dl_loaded);
1228 #ifdef ELF_MACHINE_DEBUG_SETUP
1230 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1232 ELF_MACHINE_DEBUG_SETUP (l, r);
1233 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1235 #else
1237 if (l->l_info[DT_DEBUG])
1238 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1239 with the run-time address of the r_debug structure */
1240 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1242 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1243 case you run gdb on the dynamic linker directly. */
1244 if (GL(dl_rtld_map).l_info[DT_DEBUG])
1245 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1247 #endif
1249 /* Notify the debugger that all objects are now mapped in. */
1250 r->r_state = RT_ADD;
1251 _dl_debug_state ();
1254 #ifndef MAP_COPY
1255 /* We must munmap() the cache file. */
1256 _dl_unload_cache ();
1257 #endif
1259 /* Once we return, _dl_sysdep_start will invoke
1260 the DT_INIT functions and then *USER_ENTRY. */
1263 /* This is a little helper function for resolving symbols while
1264 tracing the binary. */
1265 static void
1266 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
1267 const char *errstring)
1269 if (objname[0] == '\0')
1270 objname = _dl_argv[0] ?: "<main program>";
1271 _dl_error_printf ("%s (%s)\n", errstring, objname);
1274 /* This is a little helper function for resolving symbols while
1275 tracing the binary. */
1276 static void
1277 print_missing_version (int errcode __attribute__ ((unused)),
1278 const char *objname, const char *errstring)
1280 _dl_error_printf ("%s: %s: %s\n", _dl_argv[0] ?: "<program name unknown>",
1281 objname, errstring);
1284 /* Nonzero if any of the debugging options is enabled. */
1285 static int any_debug;
1287 /* Process the string given as the parameter which explains which debugging
1288 options are enabled. */
1289 static void
1290 process_dl_debug (const char *dl_debug)
1292 /* When adding new entries make sure that the maximal length of a name
1293 is correctly handled in the LD_DEBUG_HELP code below. */
1294 static const struct
1296 unsigned char len;
1297 const char name[10];
1298 const char helptext[41];
1299 unsigned short int mask;
1300 } debopts[] =
1302 #define LEN_AND_STR(str) sizeof (str) - 1, str
1303 { LEN_AND_STR ("libs"), "display library search paths",
1304 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
1305 { LEN_AND_STR ("reloc"), "display relocation processing",
1306 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
1307 { LEN_AND_STR ("files"), "display progress for input file",
1308 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
1309 { LEN_AND_STR ("symbols"), "display symbol table processing",
1310 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
1311 { LEN_AND_STR ("bindings"), "display information about symbol binding",
1312 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
1313 { LEN_AND_STR ("versions"), "display version dependencies",
1314 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1315 { LEN_AND_STR ("all"), "all previous options combined",
1316 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
1317 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1318 { LEN_AND_STR ("statistics"), "display relocation statistics",
1319 DL_DEBUG_STATISTICS },
1320 { LEN_AND_STR ("help"), "display this help message and exit",
1321 DL_DEBUG_HELP },
1323 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
1325 /* Skip separating white spaces and commas. */
1326 while (*dl_debug != '\0')
1328 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
1330 size_t cnt;
1331 size_t len = 1;
1333 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
1334 && dl_debug[len] != ',' && dl_debug[len] != ':')
1335 ++len;
1337 for (cnt = 0; cnt < ndebopts; ++cnt)
1338 if (debopts[cnt].len == len
1339 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
1341 GL(dl_debug_mask) |= debopts[cnt].mask;
1342 any_debug = 1;
1343 break;
1346 if (cnt == ndebopts)
1348 /* Display a warning and skip everything until next
1349 separator. */
1350 char *copy = strndupa (dl_debug, len);
1351 _dl_error_printf ("\
1352 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
1355 dl_debug += len;
1356 continue;
1359 ++dl_debug;
1362 if (GL(dl_debug_mask) & DL_DEBUG_HELP)
1364 size_t cnt;
1366 _dl_printf ("\
1367 Valid options for the LD_DEBUG environment variable are:\n\n");
1369 for (cnt = 0; cnt < ndebopts; ++cnt)
1370 _dl_printf (" %s%s %s\n", debopts[cnt].name,
1371 " " + strlen (debopts[cnt].name) - 3,
1372 debopts[cnt].helptext);
1374 _dl_printf ("\n\
1375 To direct the debugging output into a file instead of standard output\n\
1376 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
1377 _exit (0);
1381 /* Process all environments variables the dynamic linker must recognize.
1382 Since all of them start with `LD_' we are a bit smarter while finding
1383 all the entries. */
1384 extern char **_environ;
1387 static void
1388 process_envvars (enum mode *modep)
1390 char **runp = _environ;
1391 char *envline;
1392 enum mode mode = normal;
1393 char *debug_output = NULL;
1395 /* This is the default place for profiling data file. */
1396 GL(dl_profile_output) = &"/var/tmp\0/var/profile"[__libc_enable_secure
1397 ? 9 : 0];
1399 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
1401 size_t len = 0;
1403 while (envline[len] != '\0' && envline[len] != '=')
1404 ++len;
1406 if (envline[len] != '=')
1407 /* This is a "LD_" variable at the end of the string without
1408 a '=' character. Ignore it since otherwise we will access
1409 invalid memory below. */
1410 continue;
1412 switch (len)
1414 case 4:
1415 /* Warning level, verbose or not. */
1416 if (memcmp (envline, "WARN", 4) == 0)
1417 GL(dl_verbose) = envline[5] != '\0';
1418 break;
1420 case 5:
1421 /* Debugging of the dynamic linker? */
1422 if (memcmp (envline, "DEBUG", 5) == 0)
1423 process_dl_debug (&envline[6]);
1424 break;
1426 case 7:
1427 /* Print information about versions. */
1428 if (memcmp (envline, "VERBOSE", 7) == 0)
1430 version_info = envline[8] != '\0';
1431 break;
1434 /* List of objects to be preloaded. */
1435 if (memcmp (envline, "PRELOAD", 7) == 0)
1437 preloadlist = &envline[8];
1438 break;
1441 /* Which shared object shall be profiled. */
1442 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
1443 GL(dl_profile) = &envline[8];
1444 break;
1446 case 8:
1447 /* Do we bind early? */
1448 if (memcmp (envline, "BIND_NOW", 8) == 0)
1450 GL(dl_lazy) = envline[9] == '\0';
1451 break;
1453 if (memcmp (envline, "BIND_NOT", 8) == 0)
1454 GL(dl_bind_not) = envline[9] != '\0';
1455 break;
1457 case 9:
1458 /* Test whether we want to see the content of the auxiliary
1459 array passed up from the kernel. */
1460 if (memcmp (envline, "SHOW_AUXV", 9) == 0)
1461 _dl_show_auxv ();
1462 break;
1464 case 10:
1465 /* Mask for the important hardware capabilities. */
1466 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
1467 GL(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL, 0, 0);
1468 break;
1470 case 11:
1471 /* Path where the binary is found. */
1472 if (!__libc_enable_secure
1473 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
1474 GL(dl_origin_path) = &envline[12];
1475 break;
1477 case 12:
1478 /* The library search path. */
1479 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
1481 library_path = &envline[13];
1482 break;
1485 /* Where to place the profiling data file. */
1486 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
1488 debug_output = &envline[13];
1489 break;
1492 if (memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
1493 GL(dl_dynamic_weak) = 1;
1494 break;
1496 case 14:
1497 /* Where to place the profiling data file. */
1498 if (!__libc_enable_secure
1499 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
1500 && envline[15] != '\0')
1501 GL(dl_profile_output) = &envline[15];
1502 break;
1504 case 16:
1505 /* The mode of the dynamic linker can be set. */
1506 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
1508 mode = trace;
1509 GL(dl_verbose) = 1;
1510 GL(dl_debug_mask) |= DL_DEBUG_PRELINK;
1511 GL(dl_trace_prelink) = &envline[17];
1513 break;
1515 case 20:
1516 /* The mode of the dynamic linker can be set. */
1517 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
1518 mode = trace;
1519 break;
1521 /* We might have some extra environment variable to handle. This
1522 is tricky due to the pre-processing of the length of the name
1523 in the switch statement here. The code here assumes that added
1524 environment variables have a different length. */
1525 #ifdef EXTRA_LD_ENVVARS
1526 EXTRA_LD_ENVVARS
1527 #endif
1531 /* The caller wants this information. */
1532 *modep = mode;
1534 /* Extra security for SUID binaries. Remove all dangerous environment
1535 variables. */
1536 if (__builtin_expect (__libc_enable_secure, 0))
1538 static const char unsecure_envvars[] =
1539 #ifdef EXTRA_UNSECURE_ENVVARS
1540 EXTRA_UNSECURE_ENVVARS
1541 #endif
1542 UNSECURE_ENVVARS;
1543 const char *nextp;
1545 nextp = unsecure_envvars;
1548 unsetenv (nextp);
1549 nextp = (char *) rawmemchr (nextp, '\0') + 1;
1551 while (*nextp != '\0');
1553 if (__access ("/etc/suid-debug", F_OK) != 0)
1554 unsetenv ("MALLOC_CHECK_");
1556 /* If we have to run the dynamic linker in debugging mode and the
1557 LD_DEBUG_OUTPUT environment variable is given, we write the debug
1558 messages to this file. */
1559 else if (any_debug && debug_output != NULL)
1561 #ifdef O_NOFOLLOW
1562 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
1563 #else
1564 const int flags = O_WRONLY | O_APPEND | O_CREAT;
1565 #endif
1566 size_t name_len = strlen (debug_output);
1567 char buf[name_len + 12];
1568 char *startp;
1570 buf[name_len + 11] = '\0';
1571 startp = _itoa_word (__getpid (), &buf[name_len + 11], 10, 0);
1572 *--startp = '.';
1573 startp = memcpy (startp - name_len, debug_output, name_len);
1575 GL(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
1576 if (GL(dl_debug_fd) == -1)
1577 /* We use standard output if opening the file failed. */
1578 GL(dl_debug_fd) = STDOUT_FILENO;
1583 /* Print the various times we collected. */
1584 static void
1585 print_statistics (void)
1587 #ifndef HP_TIMING_NONAVAIL
1588 char buf[200];
1589 char *cp;
1590 char *wp;
1592 /* Total time rtld used. */
1593 if (HP_TIMING_AVAIL)
1595 HP_TIMING_PRINT (buf, sizeof (buf), rtld_total_time);
1596 _dl_debug_printf ("\nruntime linker statistics:\n"
1597 " total startup time in dynamic loader: %s\n", buf);
1600 /* Print relocation statistics. */
1601 if (HP_TIMING_AVAIL)
1603 char pbuf[30];
1604 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
1605 cp = _itoa_word ((1000ULL * relocate_time) / rtld_total_time,
1606 pbuf + sizeof (pbuf), 10, 0);
1607 wp = pbuf;
1608 switch (pbuf + sizeof (pbuf) - cp)
1610 case 3:
1611 *wp++ = *cp++;
1612 case 2:
1613 *wp++ = *cp++;
1614 case 1:
1615 *wp++ = '.';
1616 *wp++ = *cp++;
1618 *wp = '\0';
1619 _dl_debug_printf (" time needed for relocation: %s (%s%%)\n",
1620 buf, pbuf);
1622 #endif
1623 _dl_debug_printf (" number of relocations: %lu\n",
1624 GL(dl_num_relocations));
1625 _dl_debug_printf (" number of relocations from cache: %lu\n",
1626 GL(dl_num_cache_relocations));
1628 #ifndef HP_TIMING_NONAVAIL
1629 /* Time spend while loading the object and the dependencies. */
1630 if (HP_TIMING_AVAIL)
1632 char pbuf[30];
1633 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
1634 cp = _itoa_word ((1000ULL * load_time) / rtld_total_time,
1635 pbuf + sizeof (pbuf), 10, 0);
1636 wp = pbuf;
1637 switch (pbuf + sizeof (pbuf) - cp)
1639 case 3:
1640 *wp++ = *cp++;
1641 case 2:
1642 *wp++ = *cp++;
1643 case 1:
1644 *wp++ = '.';
1645 *wp++ = *cp++;
1647 *wp = '\0';
1648 _dl_debug_printf (" time needed to load objects: %s (%s%%)\n",
1649 buf, pbuf);
1651 #endif