Update.
[glibc.git] / elf / rtld.c
blobbdd12b4f81c86ed209d3f2a7adde1582711163b6
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, ElfW(Word) phnum,
100 ElfW(Addr) *user_entry);
102 static struct libname_list _dl_rtld_libname;
103 static struct libname_list _dl_rtld_libname2;
105 /* We expect less than a second for relocation. */
106 #ifdef HP_SMALL_TIMING_AVAIL
107 # undef HP_TIMING_AVAIL
108 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
109 #endif
111 /* Variable for statistics. */
112 #ifndef HP_TIMING_NONAVAIL
113 static hp_timing_t rtld_total_time;
114 static hp_timing_t relocate_time;
115 static hp_timing_t load_time;
116 #endif
118 static ElfW(Addr) _dl_start_final (void *arg, struct link_map *bootstrap_map_p,
119 hp_timing_t start_time);
121 #ifdef RTLD_START
122 RTLD_START
123 #else
124 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
125 #endif
127 static ElfW(Addr) __attribute_used__ internal_function
128 _dl_start (void *arg)
130 struct link_map bootstrap_map;
131 hp_timing_t start_time;
132 #if !__GNUC_PREREQ (2, 96)
133 size_t cnt;
134 #endif
136 /* This #define produces dynamic linking inline functions for
137 bootstrap relocation instead of general-purpose relocation. */
138 #define RTLD_BOOTSTRAP
139 #define RESOLVE_MAP(sym, version, flags) \
140 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : &bootstrap_map)
141 #define RESOLVE(sym, version, flags) \
142 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : bootstrap_map.l_addr)
143 #include "dynamic-link.h"
145 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
146 HP_TIMING_NOW (start_time);
148 /* Partly clean the `bootstrap_map' structure up. Don't use
149 `memset' since it might not be built in or inlined and we cannot
150 make function calls at this point. Use '__builtin_memset' if we
151 know it is available. */
152 #if __GNUC_PREREQ (2, 96)
153 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
154 #else
155 for (cnt = 0;
156 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
157 ++cnt)
158 bootstrap_map.l_info[cnt] = 0;
159 #endif
161 /* Figure out the run-time load address of the dynamic linker itself. */
162 bootstrap_map.l_addr = elf_machine_load_address ();
164 /* Read our own dynamic section and fill in the info array. */
165 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
166 elf_get_dynamic_info (&bootstrap_map);
168 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
169 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
170 #endif
172 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
174 /* Relocate ourselves so we can do normal function calls and
175 data access using the global offset table. */
177 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
180 /* Please note that we don't allow profiling of this object and
181 therefore need not test whether we have to allocate the array
182 for the relocation results (as done in dl-reloc.c). */
184 /* Now life is sane; we can call functions and access global data.
185 Set up to use the operating system facilities, and find out from
186 the operating system's program loader where to find the program
187 header table in core. Put the rest of _dl_start into a separate
188 function, that way the compiler cannot put accesses to the GOT
189 before ELF_DYNAMIC_RELOCATE. */
191 ElfW(Addr) entry = _dl_start_final (arg, &bootstrap_map, start_time);
193 #ifndef ELF_MACHINE_START_ADDRESS
194 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
195 #endif
197 return ELF_MACHINE_START_ADDRESS (GL(dl_loaded), entry);
202 #ifndef VALIDX
203 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
204 + DT_EXTRANUM + DT_VALTAGIDX (tag))
205 #endif
206 #ifndef ADDRIDX
207 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
208 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
209 #endif
211 static ElfW(Addr)
212 _dl_start_final (void *arg, struct link_map *bootstrap_map_p,
213 hp_timing_t start_time)
215 /* The use of `alloca' here looks ridiculous but it helps. The goal
216 is to avoid the function from being inlined. There is no official
217 way to do this so we use this trick. gcc never inlines functions
218 which use `alloca'. */
219 ElfW(Addr) *start_addr = alloca (sizeof (ElfW(Addr)));
220 extern char _begin[], _end[];
221 #ifdef USE_TLS
222 ElfW(Ehdr) *ehdr;
223 ElfW(Phdr) *phdr;
224 size_t cnt;
225 dtv_t initdtv[2];
226 #endif
228 if (HP_TIMING_AVAIL)
230 /* If it hasn't happen yet record the startup time. */
231 if (! HP_TIMING_INLINE)
232 HP_TIMING_NOW (start_time);
234 /* Initialize the timing functions. */
235 HP_TIMING_DIFF_INIT ();
238 /* Transfer data about ourselves to the permanent link_map structure. */
239 GL(dl_rtld_map).l_addr = bootstrap_map_p->l_addr;
240 GL(dl_rtld_map).l_ld = bootstrap_map_p->l_ld;
241 GL(dl_rtld_map).l_opencount = 1;
242 memcpy (GL(dl_rtld_map).l_info, bootstrap_map_p->l_info,
243 sizeof GL(dl_rtld_map).l_info);
244 _dl_setup_hash (&GL(dl_rtld_map));
245 GL(dl_rtld_map).l_mach = bootstrap_map_p->l_mach;
246 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
247 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
249 #if HP_TIMING_AVAIL
250 HP_TIMING_NOW (GL(dl_cpuclock_offset));
251 #endif
253 #if USE_TLS
254 /* Get the dynamic linkers program header. */
255 ehdr = (ElfW(Ehdr) *) bootstrap_map_p->l_addr;
256 phdr = (ElfW(Phdr) *) (bootstrap_map_p->l_addr + ehdr->e_phoff);
257 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt)
258 if (phdr[cnt].p_type == PT_TLS)
260 void *tlsblock;
261 size_t align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
263 GL(dl_rtld_map).l_tls_blocksize = phdr[cnt].p_memsz;
264 GL(dl_rtld_map).l_tls_initimage_size = phdr[cnt].p_filesz;
265 GL(dl_rtld_map).l_tls_initimage = (void *) (bootstrap_map_p->l_addr
266 + phdr[cnt].p_offset);
268 /* We can now allocate the initial TLS block. This can happen
269 on the stack. We'll get the final memory later when we
270 know all about the various objects loaded at startup
271 time. */
272 # if TLS_TCB_AT_TP
273 tlsblock = alloca (roundup (GL(dl_rtld_map).l_tls_blocksize,
274 TLS_INIT_TCB_ALIGN)
275 + TLS_INIT_TCB_SIZE
276 + align);
277 # elif TLS_DTV_AT_TP
278 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE, phdr[cnt].p_align)
279 + GL(dl_rtld_map).l_tls_blocksize
280 + align);
281 # else
282 /* In case a model with a different layout for the TCB and DTV
283 is defined add another #elif here and in the following #ifs. */
284 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
285 # endif
286 /* Align the TLS block. */
287 tlsblock = (void *) (((uintptr_t) tlsblock + align - 1)
288 & ~(align - 1));
290 /* Initialize the dtv. */
291 initdtv[0].counter = 1;
293 /* Initialize the TLS block. */
294 # if TLS_TCB_AT_TP
295 initdtv[1].pointer = tlsblock;
296 # elif TLS_DTV_AT_TP
297 GL(dl_rtld_map).l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
298 phdr[cnt].p_align);
299 initdtv[1].pointer = (char *) tlsblock + GL(dl_rtld_map).l_tls_offset);
300 # else
301 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
302 # endif
303 memset (__mempcpy (initdtv[1].pointer, GL(dl_rtld_map).l_tls_initimage,
304 GL(dl_rtld_map).l_tls_initimage_size),
305 '\0', (GL(dl_rtld_map).l_tls_blocksize
306 - GL(dl_rtld_map).l_tls_initimage_size));
308 /* Initialize the thread pointer. */
309 # if TLS_TCB_AT_TP
310 GL(dl_rtld_map).l_tls_offset
311 = roundup (GL(dl_rtld_map).l_tls_blocksize, TLS_INIT_TCB_ALIGN);
312 TLS_INIT_TP ((char *) tlsblock + GL(dl_rtld_map).l_tls_offset,
313 initdtv);
314 # elif TLS_DTV_AT_TP
315 TLS_INIT_TP (tlsblock, initdtv);
316 # else
317 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
318 # endif
320 /* So far this is module number one. */
321 GL(dl_rtld_map).l_tls_modid = 1;
323 /* There can only be one PT_TLS entry. */
324 break;
326 #endif /* use TLS */
328 /* Call the OS-dependent function to set up life so we can do things like
329 file access. It will call `dl_main' (below) to do all the real work
330 of the dynamic linker, and then unwind our frame and run the user
331 entry point on the same stack we entered on. */
332 *start_addr = _dl_sysdep_start (arg, &dl_main);
334 #ifndef HP_TIMING_NONAVAIL
335 if (HP_TIMING_AVAIL)
337 hp_timing_t end_time;
339 /* Get the current time. */
340 HP_TIMING_NOW (end_time);
342 /* Compute the difference. */
343 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
345 #endif
347 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
348 print_statistics ();
350 return *start_addr;
353 /* Now life is peachy; we can do all normal operations.
354 On to the real work. */
356 /* Some helper functions. */
358 /* Arguments to relocate_doit. */
359 struct relocate_args
361 struct link_map *l;
362 int lazy;
365 struct map_args
367 /* Argument to map_doit. */
368 char *str;
369 /* Return value of map_doit. */
370 struct link_map *main_map;
373 /* Arguments to version_check_doit. */
374 struct version_check_args
376 int doexit;
377 int dotrace;
380 static void
381 relocate_doit (void *a)
383 struct relocate_args *args = (struct relocate_args *) a;
385 INT(_dl_relocate_object) (args->l, args->l->l_scope, args->lazy, 0);
388 static void
389 map_doit (void *a)
391 struct map_args *args = (struct map_args *) a;
392 args->main_map = INT(_dl_map_object) (NULL, args->str, 0, lt_library, 0, 0);
395 static void
396 version_check_doit (void *a)
398 struct version_check_args *args = (struct version_check_args *) a;
399 if (_dl_check_all_versions (GL(dl_loaded), 1, args->dotrace) && args->doexit)
400 /* We cannot start the application. Abort now. */
401 _exit (1);
405 static inline struct link_map *
406 find_needed (const char *name)
408 unsigned int n = GL(dl_loaded)->l_searchlist.r_nlist;
410 while (n-- > 0)
411 if (_dl_name_match_p (name, GL(dl_loaded)->l_searchlist.r_list[n]))
412 return GL(dl_loaded)->l_searchlist.r_list[n];
414 /* Should never happen. */
415 return NULL;
418 static int
419 match_version (const char *string, struct link_map *map)
421 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
422 ElfW(Verdef) *def;
424 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
425 if (map->l_info[VERDEFTAG] == NULL)
426 /* The file has no symbol versioning. */
427 return 0;
429 def = (ElfW(Verdef) *) ((char *) map->l_addr
430 + map->l_info[VERDEFTAG]->d_un.d_ptr);
431 while (1)
433 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
435 /* Compare the version strings. */
436 if (strcmp (string, strtab + aux->vda_name) == 0)
437 /* Bingo! */
438 return 1;
440 /* If no more definitions we failed to find what we want. */
441 if (def->vd_next == 0)
442 break;
444 /* Next definition. */
445 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
448 return 0;
451 static const char *library_path; /* The library search path. */
452 static const char *preloadlist; /* The list preloaded objects. */
453 static int version_info; /* Nonzero if information about
454 versions has to be printed. */
456 static void
457 dl_main (const ElfW(Phdr) *phdr,
458 ElfW(Word) phnum,
459 ElfW(Addr) *user_entry)
461 const ElfW(Phdr) *ph;
462 enum mode mode;
463 struct link_map **preloads;
464 unsigned int npreloads;
465 size_t file_size;
466 char *file;
467 int has_interp = 0;
468 unsigned int i;
469 int prelinked = 0;
470 int rtld_is_main = 0;
471 #ifndef HP_TIMING_NONAVAIL
472 hp_timing_t start;
473 hp_timing_t stop;
474 hp_timing_t diff;
475 #endif
477 /* Process the environment variable which control the behaviour. */
478 process_envvars (&mode);
480 /* Set up a flag which tells we are just starting. */
481 _dl_starting_up = 1;
483 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
485 /* Ho ho. We are not the program interpreter! We are the program
486 itself! This means someone ran ld.so as a command. Well, that
487 might be convenient to do sometimes. We support it by
488 interpreting the args like this:
490 ld.so PROGRAM ARGS...
492 The first argument is the name of a file containing an ELF
493 executable we will load and run with the following arguments.
494 To simplify life here, PROGRAM is searched for using the
495 normal rules for shared objects, rather than $PATH or anything
496 like that. We just load it and use its entry point; we don't
497 pay attention to its PT_INTERP command (we are the interpreter
498 ourselves). This is an easy way to test a new ld.so before
499 installing it. */
500 rtld_is_main = 1;
502 /* Note the place where the dynamic linker actually came from. */
503 GL(dl_rtld_map).l_name = _dl_argv[0];
505 while (_dl_argc > 1)
506 if (! strcmp (_dl_argv[1], "--list"))
508 mode = list;
509 GL(dl_lazy) = -1; /* This means do no dependency analysis. */
511 ++_dl_skip_args;
512 --_dl_argc;
513 ++_dl_argv;
515 else if (! strcmp (_dl_argv[1], "--verify"))
517 mode = verify;
519 ++_dl_skip_args;
520 --_dl_argc;
521 ++_dl_argv;
523 else if (! strcmp (_dl_argv[1], "--library-path") && _dl_argc > 2)
525 library_path = _dl_argv[2];
527 _dl_skip_args += 2;
528 _dl_argc -= 2;
529 _dl_argv += 2;
531 else if (! strcmp (_dl_argv[1], "--inhibit-rpath") && _dl_argc > 2)
533 GL(dl_inhibit_rpath) = _dl_argv[2];
535 _dl_skip_args += 2;
536 _dl_argc -= 2;
537 _dl_argv += 2;
539 else
540 break;
542 /* If we have no further argument the program was called incorrectly.
543 Grant the user some education. */
544 if (_dl_argc < 2)
545 _dl_fatal_printf ("\
546 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
547 You have invoked `ld.so', the helper program for shared library executables.\n\
548 This program usually lives in the file `/lib/ld.so', and special directives\n\
549 in executable files using ELF shared libraries tell the system's program\n\
550 loader to load the helper program from this file. This helper program loads\n\
551 the shared libraries needed by the program executable, prepares the program\n\
552 to run, and runs it. You may invoke this helper program directly from the\n\
553 command line to load and run an ELF executable file; this is like executing\n\
554 that file itself, but always uses this helper program from the file you\n\
555 specified, instead of the helper program file specified in the executable\n\
556 file you run. This is mostly of use for maintainers to test new versions\n\
557 of this helper program; chances are you did not intend to run this program.\n\
559 --list list all dependencies and how they are resolved\n\
560 --verify verify that given object really is a dynamically linked\n\
561 object we can handle\n\
562 --library-path PATH use given PATH instead of content of the environment\n\
563 variable LD_LIBRARY_PATH\n\
564 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
565 in LIST\n");
567 ++_dl_skip_args;
568 --_dl_argc;
569 ++_dl_argv;
571 /* Initialize the data structures for the search paths for shared
572 objects. */
573 _dl_init_paths (library_path);
575 if (__builtin_expect (mode, normal) == verify)
577 const char *objname;
578 const char *err_str = NULL;
579 struct map_args args;
581 args.str = _dl_argv[0];
582 (void) INT(_dl_catch_error) (&objname, &err_str, map_doit, &args);
583 if (__builtin_expect (err_str != NULL, 0))
585 if (err_str != _dl_out_of_memory)
586 free ((char *) err_str);
587 _exit (EXIT_FAILURE);
590 else
592 HP_TIMING_NOW (start);
593 INT(_dl_map_object) (NULL, _dl_argv[0], 0, lt_library, 0, 0);
594 HP_TIMING_NOW (stop);
596 HP_TIMING_DIFF (load_time, start, stop);
599 phdr = GL(dl_loaded)->l_phdr;
600 phnum = GL(dl_loaded)->l_phnum;
601 /* We overwrite here a pointer to a malloc()ed string. But since
602 the malloc() implementation used at this point is the dummy
603 implementations which has no real free() function it does not
604 makes sense to free the old string first. */
605 GL(dl_loaded)->l_name = (char *) "";
606 *user_entry = GL(dl_loaded)->l_entry;
608 else
610 /* Create a link_map for the executable itself.
611 This will be what dlopen on "" returns. */
612 _dl_new_object ((char *) "", "", lt_executable, NULL);
613 if (GL(dl_loaded) == NULL)
614 _dl_fatal_printf ("cannot allocate memory for link map\n");
615 GL(dl_loaded)->l_phdr = phdr;
616 GL(dl_loaded)->l_phnum = phnum;
617 GL(dl_loaded)->l_entry = *user_entry;
619 /* At this point we are in a bit of trouble. We would have to
620 fill in the values for l_dev and l_ino. But in general we
621 do not know where the file is. We also do not handle AT_EXECFD
622 even if it would be passed up.
624 We leave the values here defined to 0. This is normally no
625 problem as the program code itself is normally no shared
626 object and therefore cannot be loaded dynamically. Nothing
627 prevent the use of dynamic binaries and in these situations
628 we might get problems. We might not be able to find out
629 whether the object is already loaded. But since there is no
630 easy way out and because the dynamic binary must also not
631 have an SONAME we ignore this program for now. If it becomes
632 a problem we can force people using SONAMEs. */
634 /* We delay initializing the path structure until we got the dynamic
635 information for the program. */
638 GL(dl_loaded)->l_map_end = 0;
639 /* Perhaps the executable has no PT_LOAD header entries at all. */
640 GL(dl_loaded)->l_map_start = ~0;
641 /* We opened the file, account for it. */
642 ++GL(dl_loaded)->l_opencount;
644 /* Scan the program header table for the dynamic section. */
645 for (ph = phdr; ph < &phdr[phnum]; ++ph)
646 switch (ph->p_type)
648 case PT_PHDR:
649 /* Find out the load address. */
650 GL(dl_loaded)->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
651 break;
652 case PT_DYNAMIC:
653 /* This tells us where to find the dynamic section,
654 which tells us everything we need to do. */
655 GL(dl_loaded)->l_ld = (void *) GL(dl_loaded)->l_addr + ph->p_vaddr;
656 break;
657 case PT_INTERP:
658 /* This "interpreter segment" was used by the program loader to
659 find the program interpreter, which is this program itself, the
660 dynamic linker. We note what name finds us, so that a future
661 dlopen call or DT_NEEDED entry, for something that wants to link
662 against the dynamic linker as a shared library, will know that
663 the shared object is already loaded. */
664 _dl_rtld_libname.name = ((const char *) GL(dl_loaded)->l_addr
665 + ph->p_vaddr);
666 /* _dl_rtld_libname.next = NULL; Already zero. */
667 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
669 /* Ordinarilly, we would get additional names for the loader from
670 our DT_SONAME. This can't happen if we were actually linked as
671 a static executable (detect this case when we have no DYNAMIC).
672 If so, assume the filename component of the interpreter path to
673 be our SONAME, and add it to our name list. */
674 if (GL(dl_rtld_map).l_ld == NULL)
676 const char *p = NULL;
677 const char *cp = _dl_rtld_libname.name;
679 /* Find the filename part of the path. */
680 while (*cp != '\0')
681 if (*cp++ == '/')
682 p = cp;
684 if (p != NULL)
686 _dl_rtld_libname2.name = p;
687 /* _dl_rtld_libname2.next = NULL; Already zero. */
688 _dl_rtld_libname.next = &_dl_rtld_libname2;
692 has_interp = 1;
693 break;
694 case PT_LOAD:
696 ElfW(Addr) mapstart;
697 ElfW(Addr) allocend;
699 /* Remember where the main program starts in memory. */
700 mapstart = (GL(dl_loaded)->l_addr
701 + (ph->p_vaddr & ~(ph->p_align - 1)));
702 if (GL(dl_loaded)->l_map_start > mapstart)
703 GL(dl_loaded)->l_map_start = mapstart;
705 /* Also where it ends. */
706 allocend = GL(dl_loaded)->l_addr + ph->p_vaddr + ph->p_memsz;
707 if (GL(dl_loaded)->l_map_end < allocend)
708 GL(dl_loaded)->l_map_end = allocend;
710 break;
712 if (! GL(dl_loaded)->l_map_end)
713 GL(dl_loaded)->l_map_end = ~0;
714 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
716 /* We were invoked directly, so the program might not have a
717 PT_INTERP. */
718 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
719 /* _dl_rtld_libname.next = NULL; Alread zero. */
720 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
722 else
723 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
725 if (! rtld_is_main)
727 /* Extract the contents of the dynamic section for easy access. */
728 elf_get_dynamic_info (GL(dl_loaded));
729 if (GL(dl_loaded)->l_info[DT_HASH])
730 /* Set up our cache of pointers into the hash table. */
731 _dl_setup_hash (GL(dl_loaded));
734 if (__builtin_expect (mode, normal) == verify)
736 /* We were called just to verify that this is a dynamic
737 executable using us as the program interpreter. Exit with an
738 error if we were not able to load the binary or no interpreter
739 is specified (i.e., this is no dynamically linked binary. */
740 if (GL(dl_loaded)->l_ld == NULL)
741 _exit (1);
743 /* We allow here some platform specific code. */
744 #ifdef DISTINGUISH_LIB_VERSIONS
745 DISTINGUISH_LIB_VERSIONS;
746 #endif
747 _exit (has_interp ? 0 : 2);
750 if (! rtld_is_main)
751 /* Initialize the data structures for the search paths for shared
752 objects. */
753 _dl_init_paths (library_path);
755 /* Put the link_map for ourselves on the chain so it can be found by
756 name. Note that at this point the global chain of link maps contains
757 exactly one element, which is pointed to by dl_loaded. */
758 if (! GL(dl_rtld_map).l_name)
759 /* If not invoked directly, the dynamic linker shared object file was
760 found by the PT_INTERP name. */
761 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
762 GL(dl_rtld_map).l_type = lt_library;
763 GL(dl_loaded)->l_next = &GL(dl_rtld_map);
764 GL(dl_rtld_map).l_prev = GL(dl_loaded);
765 ++GL(dl_nloaded);
767 /* We have two ways to specify objects to preload: via environment
768 variable and via the file /etc/ld.so.preload. The latter can also
769 be used when security is enabled. */
770 preloads = NULL;
771 npreloads = 0;
773 if (__builtin_expect (preloadlist != NULL, 0))
775 /* The LD_PRELOAD environment variable gives list of libraries
776 separated by white space or colons that are loaded before the
777 executable's dependencies and prepended to the global scope
778 list. If the binary is running setuid all elements
779 containing a '/' are ignored since it is insecure. */
780 char *list = strdupa (preloadlist);
781 char *p;
783 HP_TIMING_NOW (start);
785 /* Prevent optimizing strsep. Speed is not important here. */
786 while ((p = (strsep) (&list, " :")) != NULL)
787 if (p[0] != '\0'
788 && (__builtin_expect (! __libc_enable_secure, 1)
789 || strchr (p, '/') == NULL))
791 struct link_map *new_map = INT(_dl_map_object) (GL(dl_loaded), p,
792 1, lt_library,
793 0, 0);
794 if (++new_map->l_opencount == 1)
795 /* It is no duplicate. */
796 ++npreloads;
799 HP_TIMING_NOW (stop);
800 HP_TIMING_DIFF (diff, start, stop);
801 HP_TIMING_ACCUM_NT (load_time, diff);
804 /* Read the contents of the file. */
805 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
806 PROT_READ | PROT_WRITE);
807 if (__builtin_expect (file != MAP_FAILED, 0))
809 /* Parse the file. It contains names of libraries to be loaded,
810 separated by white spaces or `:'. It may also contain
811 comments introduced by `#'. */
812 char *problem;
813 char *runp;
814 size_t rest;
816 /* Eliminate comments. */
817 runp = file;
818 rest = file_size;
819 while (rest > 0)
821 char *comment = memchr (runp, '#', rest);
822 if (comment == NULL)
823 break;
825 rest -= comment - runp;
827 *comment = ' ';
828 while (--rest > 0 && *++comment != '\n');
831 /* We have one problematic case: if we have a name at the end of
832 the file without a trailing terminating characters, we cannot
833 place the \0. Handle the case separately. */
834 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
835 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
837 problem = &file[file_size];
838 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
839 && problem[-1] != '\n' && problem[-1] != ':')
840 --problem;
842 if (problem > file)
843 problem[-1] = '\0';
845 else
847 problem = NULL;
848 file[file_size - 1] = '\0';
851 HP_TIMING_NOW (start);
853 if (file != problem)
855 char *p;
856 runp = file;
857 while ((p = strsep (&runp, ": \t\n")) != NULL)
858 if (p[0] != '\0')
860 struct link_map *new_map = INT(_dl_map_object) (GL(dl_loaded),
861 p, 1,
862 lt_library,
863 0, 0);
864 if (++new_map->l_opencount == 1)
865 /* It is no duplicate. */
866 ++npreloads;
870 if (problem != NULL)
872 char *p = strndupa (problem, file_size - (problem - file));
873 struct link_map *new_map = INT(_dl_map_object) (GL(dl_loaded), p, 1,
874 lt_library, 0, 0);
875 if (++new_map->l_opencount == 1)
876 /* It is no duplicate. */
877 ++npreloads;
880 HP_TIMING_NOW (stop);
881 HP_TIMING_DIFF (diff, start, stop);
882 HP_TIMING_ACCUM_NT (load_time, diff);
884 /* We don't need the file anymore. */
885 __munmap (file, file_size);
888 if (__builtin_expect (npreloads, 0) != 0)
890 /* Set up PRELOADS with a vector of the preloaded libraries. */
891 struct link_map *l;
892 preloads = __alloca (npreloads * sizeof preloads[0]);
893 l = GL(dl_rtld_map).l_next; /* End of the chain before preloads. */
894 i = 0;
897 preloads[i++] = l;
898 l = l->l_next;
899 } while (l);
900 assert (i == npreloads);
903 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
904 specified some libraries to load, these are inserted before the actual
905 dependencies in the executable's searchlist for symbol resolution. */
906 HP_TIMING_NOW (start);
907 INT(_dl_map_object_deps) (GL(dl_loaded), preloads, npreloads, mode == trace);
908 HP_TIMING_NOW (stop);
909 HP_TIMING_DIFF (diff, start, stop);
910 HP_TIMING_ACCUM_NT (load_time, diff);
912 /* Mark all objects as being in the global scope and set the open
913 counter. */
914 for (i = GL(dl_loaded)->l_searchlist.r_nlist; i > 0; )
916 --i;
917 GL(dl_loaded)->l_searchlist.r_list[i]->l_global = 1;
918 ++GL(dl_loaded)->l_searchlist.r_list[i]->l_opencount;
921 #ifndef MAP_ANON
922 /* We are done mapping things, so close the zero-fill descriptor. */
923 __close (_dl_zerofd);
924 _dl_zerofd = -1;
925 #endif
927 /* Remove _dl_rtld_map from the chain. */
928 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
929 if (GL(dl_rtld_map).l_next)
930 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
932 if (__builtin_expect (GL(dl_rtld_map).l_opencount > 1, 1))
934 /* Some DT_NEEDED entry referred to the interpreter object itself, so
935 put it back in the list of visible objects. We insert it into the
936 chain in symbol search order because gdb uses the chain's order as
937 its symbol search order. */
938 i = 1;
939 while (GL(dl_loaded)->l_searchlist.r_list[i] != &GL(dl_rtld_map))
940 ++i;
941 GL(dl_rtld_map).l_prev = GL(dl_loaded)->l_searchlist.r_list[i - 1];
942 if (__builtin_expect (mode, normal) == normal)
943 GL(dl_rtld_map).l_next = (i + 1 < GL(dl_loaded)->l_searchlist.r_nlist
944 ? GL(dl_loaded)->l_searchlist.r_list[i + 1]
945 : NULL);
946 else
947 /* In trace mode there might be an invisible object (which we
948 could not find) after the previous one in the search list.
949 In this case it doesn't matter much where we put the
950 interpreter object, so we just initialize the list pointer so
951 that the assertion below holds. */
952 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
954 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
955 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
956 if (GL(dl_rtld_map).l_next)
958 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
959 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
963 /* Now let us see whether all libraries are available in the
964 versions we need. */
966 struct version_check_args args;
967 args.doexit = mode == normal;
968 args.dotrace = mode == trace;
969 _dl_receive_error (print_missing_version, version_check_doit, &args);
972 if (__builtin_expect (mode, normal) != normal)
974 /* We were run just to list the shared libraries. It is
975 important that we do this before real relocation, because the
976 functions we call below for output may no longer work properly
977 after relocation. */
978 if (! GL(dl_loaded)->l_info[DT_NEEDED])
979 _dl_printf ("\tstatically linked\n");
980 else
982 struct link_map *l;
984 if (GL(dl_debug_mask) & DL_DEBUG_PRELINK)
986 struct r_scope_elem *scope = &GL(dl_loaded)->l_searchlist;
988 for (i = 0; i < scope->r_nlist; i++)
990 l = scope->r_list [i];
991 if (l->l_faked)
993 _dl_printf ("\t%s => not found\n", l->l_libname->name);
994 continue;
996 if (_dl_name_match_p (GL(dl_trace_prelink), l))
997 GL(dl_trace_prelink_map) = l;
998 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)\n",
999 l->l_libname->name[0] ? l->l_libname->name
1000 : _dl_argv[0] ?: "<main program>",
1001 l->l_name[0] ? l->l_name
1002 : _dl_argv[0] ?: "<main program>",
1003 (int) sizeof l->l_map_start * 2,
1004 l->l_map_start,
1005 (int) sizeof l->l_addr * 2,
1006 l->l_addr);
1009 else
1011 for (l = GL(dl_loaded)->l_next; l; l = l->l_next)
1012 if (l->l_faked)
1013 /* The library was not found. */
1014 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1015 else
1016 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1017 l->l_name, (int) sizeof l->l_map_start * 2,
1018 l->l_map_start);
1022 if (__builtin_expect (mode, trace) != trace)
1023 for (i = 1; i < _dl_argc; ++i)
1025 const ElfW(Sym) *ref = NULL;
1026 ElfW(Addr) loadbase;
1027 lookup_t result;
1029 result = INT(_dl_lookup_symbol) (_dl_argv[i], GL(dl_loaded),
1030 &ref, GL(dl_loaded)->l_scope,
1031 ELF_RTYPE_CLASS_PLT, 1);
1033 loadbase = LOOKUP_VALUE_ADDRESS (result);
1035 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
1036 _dl_argv[i],
1037 (int) sizeof ref->st_value * 2, ref->st_value,
1038 (int) sizeof loadbase * 2, loadbase);
1040 else
1042 /* If LD_WARN is set warn about undefined symbols. */
1043 if (GL(dl_lazy) >= 0 && GL(dl_verbose))
1045 /* We have to do symbol dependency testing. */
1046 struct relocate_args args;
1047 struct link_map *l;
1049 args.lazy = GL(dl_lazy);
1051 l = GL(dl_loaded);
1052 while (l->l_next)
1053 l = l->l_next;
1056 if (l != &GL(dl_rtld_map) && ! l->l_faked)
1058 args.l = l;
1059 _dl_receive_error (print_unresolved, relocate_doit,
1060 &args);
1062 l = l->l_prev;
1063 } while (l);
1065 if ((GL(dl_debug_mask) & DL_DEBUG_PRELINK)
1066 && GL(dl_rtld_map).l_opencount > 1)
1067 INT(_dl_relocate_object) (&GL(dl_rtld_map),
1068 GL(dl_loaded)->l_scope, 0, 0);
1071 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
1072 if (version_info)
1074 /* Print more information. This means here, print information
1075 about the versions needed. */
1076 int first = 1;
1077 struct link_map *map = GL(dl_loaded);
1079 for (map = GL(dl_loaded); map != NULL; map = map->l_next)
1081 const char *strtab;
1082 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
1083 ElfW(Verneed) *ent;
1085 if (dyn == NULL)
1086 continue;
1088 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
1089 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
1091 if (first)
1093 _dl_printf ("\n\tVersion information:\n");
1094 first = 0;
1097 _dl_printf ("\t%s:\n",
1098 map->l_name[0] ? map->l_name : _dl_argv[0]);
1100 while (1)
1102 ElfW(Vernaux) *aux;
1103 struct link_map *needed;
1105 needed = find_needed (strtab + ent->vn_file);
1106 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
1108 while (1)
1110 const char *fname = NULL;
1112 if (needed != NULL
1113 && match_version (strtab + aux->vna_name,
1114 needed))
1115 fname = needed->l_name;
1117 _dl_printf ("\t\t%s (%s) %s=> %s\n",
1118 strtab + ent->vn_file,
1119 strtab + aux->vna_name,
1120 aux->vna_flags & VER_FLG_WEAK
1121 ? "[WEAK] " : "",
1122 fname ?: "not found");
1124 if (aux->vna_next == 0)
1125 /* No more symbols. */
1126 break;
1128 /* Next symbol. */
1129 aux = (ElfW(Vernaux) *) ((char *) aux
1130 + aux->vna_next);
1133 if (ent->vn_next == 0)
1134 /* No more dependencies. */
1135 break;
1137 /* Next dependency. */
1138 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
1144 _exit (0);
1147 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]
1148 && ! __builtin_expect (GL(dl_profile) != NULL, 0))
1150 ElfW(Lib) *liblist, *liblistend;
1151 struct link_map **r_list, **r_listend, *l;
1152 const char *strtab = (const void *) D_PTR (GL(dl_loaded),
1153 l_info[DT_STRTAB]);
1155 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
1156 liblist = (ElfW(Lib) *)
1157 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
1158 liblistend = (ElfW(Lib) *)
1159 ((char *) liblist
1160 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
1161 r_list = GL(dl_loaded)->l_searchlist.r_list;
1162 r_listend = r_list + GL(dl_loaded)->l_searchlist.r_nlist;
1164 for (; r_list < r_listend && liblist < liblistend; r_list++)
1166 l = *r_list;
1168 if (l == GL(dl_loaded))
1169 continue;
1171 /* If the library is not mapped where it should, fail. */
1172 if (l->l_addr)
1173 break;
1175 /* Next, check if checksum matches. */
1176 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
1177 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
1178 != liblist->l_checksum)
1179 break;
1181 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
1182 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
1183 != liblist->l_time_stamp)
1184 break;
1186 if (! _dl_name_match_p (strtab + liblist->l_name, l))
1187 break;
1189 ++liblist;
1193 if (r_list == r_listend && liblist == liblistend)
1194 prelinked = 1;
1196 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1197 _dl_printf ("\nprelink checking: %s\n", prelinked ? "ok" : "failed");
1200 if (prelinked)
1202 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
1204 ElfW(Rela) *conflict, *conflictend;
1205 #ifndef HP_TIMING_NONAVAIL
1206 hp_timing_t start;
1207 hp_timing_t stop;
1208 #endif
1210 HP_TIMING_NOW (start);
1211 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
1212 conflict = (ElfW(Rela) *)
1213 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
1214 conflictend = (ElfW(Rela) *)
1215 ((char *) conflict
1216 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
1217 _dl_resolve_conflicts (GL(dl_loaded), conflict, conflictend);
1218 HP_TIMING_NOW (stop);
1219 HP_TIMING_DIFF (relocate_time, start, stop);
1222 _dl_sysdep_start_cleanup ();
1224 else
1226 /* Now we have all the objects loaded. Relocate them all except for
1227 the dynamic linker itself. We do this in reverse order so that copy
1228 relocs of earlier objects overwrite the data written by later
1229 objects. We do not re-relocate the dynamic linker itself in this
1230 loop because that could result in the GOT entries for functions we
1231 call being changed, and that would break us. It is safe to relocate
1232 the dynamic linker out of order because it has no copy relocs (we
1233 know that because it is self-contained). */
1235 struct link_map *l;
1236 int consider_profiling = GL(dl_profile) != NULL;
1237 #ifndef HP_TIMING_NONAVAIL
1238 hp_timing_t start;
1239 hp_timing_t stop;
1240 hp_timing_t add;
1241 #endif
1243 /* If we are profiling we also must do lazy reloaction. */
1244 GL(dl_lazy) |= consider_profiling;
1246 l = GL(dl_loaded);
1247 while (l->l_next)
1248 l = l->l_next;
1250 HP_TIMING_NOW (start);
1253 /* While we are at it, help the memory handling a bit. We have to
1254 mark some data structures as allocated with the fake malloc()
1255 implementation in ld.so. */
1256 struct libname_list *lnp = l->l_libname->next;
1258 while (__builtin_expect (lnp != NULL, 0))
1260 lnp->dont_free = 1;
1261 lnp = lnp->next;
1264 if (l != &GL(dl_rtld_map))
1265 INT(_dl_relocate_object) (l, l->l_scope, GL(dl_lazy),
1266 consider_profiling);
1268 l = l->l_prev;
1270 while (l);
1271 HP_TIMING_NOW (stop);
1273 HP_TIMING_DIFF (relocate_time, start, stop);
1275 /* Do any necessary cleanups for the startup OS interface code.
1276 We do these now so that no calls are made after rtld re-relocation
1277 which might be resolved to different functions than we expect.
1278 We cannot do this before relocating the other objects because
1279 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
1280 _dl_sysdep_start_cleanup ();
1282 /* Now enable profiling if needed. Like the previous call,
1283 this has to go here because the calls it makes should use the
1284 rtld versions of the functions (particularly calloc()), but it
1285 needs to have _dl_profile_map set up by the relocator. */
1286 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
1287 /* We must prepare the profiling. */
1288 INT(_dl_start_profile) (GL(dl_profile_map), GL(dl_profile_output));
1290 if (GL(dl_rtld_map).l_opencount > 1)
1292 /* There was an explicit ref to the dynamic linker as a shared lib.
1293 Re-relocate ourselves with user-controlled symbol definitions. */
1294 HP_TIMING_NOW (start);
1295 INT(_dl_relocate_object) (&GL(dl_rtld_map), GL(dl_loaded)->l_scope,
1296 0, 0);
1297 HP_TIMING_NOW (stop);
1298 HP_TIMING_DIFF (add, start, stop);
1299 HP_TIMING_ACCUM_NT (relocate_time, add);
1303 /* Now set up the variable which helps the assembler startup code. */
1304 GL(dl_main_searchlist) = &GL(dl_loaded)->l_searchlist;
1305 GL(dl_global_scope)[0] = &GL(dl_loaded)->l_searchlist;
1307 /* Save the information about the original global scope list since
1308 we need it in the memory handling later. */
1309 GL(dl_initial_searchlist) = *GL(dl_main_searchlist);
1312 /* Initialize _r_debug. */
1313 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr);
1314 struct link_map *l;
1316 l = GL(dl_loaded);
1318 #ifdef ELF_MACHINE_DEBUG_SETUP
1320 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1322 ELF_MACHINE_DEBUG_SETUP (l, r);
1323 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1325 #else
1327 if (l->l_info[DT_DEBUG])
1328 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1329 with the run-time address of the r_debug structure */
1330 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1332 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1333 case you run gdb on the dynamic linker directly. */
1334 if (GL(dl_rtld_map).l_info[DT_DEBUG])
1335 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1337 #endif
1339 /* Notify the debugger that all objects are now mapped in. */
1340 r->r_state = RT_ADD;
1341 INT(_dl_debug_state) ();
1344 #ifndef MAP_COPY
1345 /* We must munmap() the cache file. */
1346 INT(_dl_unload_cache) ();
1347 #endif
1349 /* Once we return, _dl_sysdep_start will invoke
1350 the DT_INIT functions and then *USER_ENTRY. */
1353 /* This is a little helper function for resolving symbols while
1354 tracing the binary. */
1355 static void
1356 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
1357 const char *errstring)
1359 if (objname[0] == '\0')
1360 objname = _dl_argv[0] ?: "<main program>";
1361 _dl_error_printf ("%s (%s)\n", errstring, objname);
1364 /* This is a little helper function for resolving symbols while
1365 tracing the binary. */
1366 static void
1367 print_missing_version (int errcode __attribute__ ((unused)),
1368 const char *objname, const char *errstring)
1370 _dl_error_printf ("%s: %s: %s\n", _dl_argv[0] ?: "<program name unknown>",
1371 objname, errstring);
1374 /* Nonzero if any of the debugging options is enabled. */
1375 static int any_debug;
1377 /* Process the string given as the parameter which explains which debugging
1378 options are enabled. */
1379 static void
1380 process_dl_debug (const char *dl_debug)
1382 /* When adding new entries make sure that the maximal length of a name
1383 is correctly handled in the LD_DEBUG_HELP code below. */
1384 static const struct
1386 unsigned char len;
1387 const char name[10];
1388 const char helptext[41];
1389 unsigned short int mask;
1390 } debopts[] =
1392 #define LEN_AND_STR(str) sizeof (str) - 1, str
1393 { LEN_AND_STR ("libs"), "display library search paths",
1394 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
1395 { LEN_AND_STR ("reloc"), "display relocation processing",
1396 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
1397 { LEN_AND_STR ("files"), "display progress for input file",
1398 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
1399 { LEN_AND_STR ("symbols"), "display symbol table processing",
1400 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
1401 { LEN_AND_STR ("bindings"), "display information about symbol binding",
1402 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
1403 { LEN_AND_STR ("versions"), "display version dependencies",
1404 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1405 { LEN_AND_STR ("all"), "all previous options combined",
1406 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
1407 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1408 { LEN_AND_STR ("statistics"), "display relocation statistics",
1409 DL_DEBUG_STATISTICS },
1410 { LEN_AND_STR ("help"), "display this help message and exit",
1411 DL_DEBUG_HELP },
1413 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
1415 /* Skip separating white spaces and commas. */
1416 while (*dl_debug != '\0')
1418 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
1420 size_t cnt;
1421 size_t len = 1;
1423 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
1424 && dl_debug[len] != ',' && dl_debug[len] != ':')
1425 ++len;
1427 for (cnt = 0; cnt < ndebopts; ++cnt)
1428 if (debopts[cnt].len == len
1429 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
1431 GL(dl_debug_mask) |= debopts[cnt].mask;
1432 any_debug = 1;
1433 break;
1436 if (cnt == ndebopts)
1438 /* Display a warning and skip everything until next
1439 separator. */
1440 char *copy = strndupa (dl_debug, len);
1441 _dl_error_printf ("\
1442 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
1445 dl_debug += len;
1446 continue;
1449 ++dl_debug;
1452 if (GL(dl_debug_mask) & DL_DEBUG_HELP)
1454 size_t cnt;
1456 _dl_printf ("\
1457 Valid options for the LD_DEBUG environment variable are:\n\n");
1459 for (cnt = 0; cnt < ndebopts; ++cnt)
1460 _dl_printf (" %s%s %s\n", debopts[cnt].name,
1461 " " + strlen (debopts[cnt].name) - 3,
1462 debopts[cnt].helptext);
1464 _dl_printf ("\n\
1465 To direct the debugging output into a file instead of standard output\n\
1466 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
1467 _exit (0);
1471 /* Process all environments variables the dynamic linker must recognize.
1472 Since all of them start with `LD_' we are a bit smarter while finding
1473 all the entries. */
1474 extern char **_environ;
1477 static void
1478 process_envvars (enum mode *modep)
1480 char **runp = _environ;
1481 char *envline;
1482 enum mode mode = normal;
1483 char *debug_output = NULL;
1485 /* This is the default place for profiling data file. */
1486 GL(dl_profile_output) = &"/var/tmp\0/var/profile"[__libc_enable_secure
1487 ? 9 : 0];
1489 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
1491 size_t len = 0;
1493 while (envline[len] != '\0' && envline[len] != '=')
1494 ++len;
1496 if (envline[len] != '=')
1497 /* This is a "LD_" variable at the end of the string without
1498 a '=' character. Ignore it since otherwise we will access
1499 invalid memory below. */
1500 continue;
1502 switch (len)
1504 case 4:
1505 /* Warning level, verbose or not. */
1506 if (memcmp (envline, "WARN", 4) == 0)
1507 GL(dl_verbose) = envline[5] != '\0';
1508 break;
1510 case 5:
1511 /* Debugging of the dynamic linker? */
1512 if (memcmp (envline, "DEBUG", 5) == 0)
1513 process_dl_debug (&envline[6]);
1514 break;
1516 case 7:
1517 /* Print information about versions. */
1518 if (memcmp (envline, "VERBOSE", 7) == 0)
1520 version_info = envline[8] != '\0';
1521 break;
1524 /* List of objects to be preloaded. */
1525 if (memcmp (envline, "PRELOAD", 7) == 0)
1527 preloadlist = &envline[8];
1528 break;
1531 /* Which shared object shall be profiled. */
1532 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
1533 GL(dl_profile) = &envline[8];
1534 break;
1536 case 8:
1537 /* Do we bind early? */
1538 if (memcmp (envline, "BIND_NOW", 8) == 0)
1540 GL(dl_lazy) = envline[9] == '\0';
1541 break;
1543 if (memcmp (envline, "BIND_NOT", 8) == 0)
1544 GL(dl_bind_not) = envline[9] != '\0';
1545 break;
1547 case 9:
1548 /* Test whether we want to see the content of the auxiliary
1549 array passed up from the kernel. */
1550 if (memcmp (envline, "SHOW_AUXV", 9) == 0)
1551 _dl_show_auxv ();
1552 break;
1554 case 10:
1555 /* Mask for the important hardware capabilities. */
1556 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
1557 GL(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL, 0, 0);
1558 break;
1560 case 11:
1561 /* Path where the binary is found. */
1562 if (!__libc_enable_secure
1563 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
1564 GL(dl_origin_path) = &envline[12];
1565 break;
1567 case 12:
1568 /* The library search path. */
1569 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
1571 library_path = &envline[13];
1572 break;
1575 /* Where to place the profiling data file. */
1576 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
1578 debug_output = &envline[13];
1579 break;
1582 if (memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
1583 GL(dl_dynamic_weak) = 1;
1584 break;
1586 case 14:
1587 /* Where to place the profiling data file. */
1588 if (!__libc_enable_secure
1589 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
1590 && envline[15] != '\0')
1591 GL(dl_profile_output) = &envline[15];
1592 break;
1594 case 16:
1595 /* The mode of the dynamic linker can be set. */
1596 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
1598 mode = trace;
1599 GL(dl_verbose) = 1;
1600 GL(dl_debug_mask) |= DL_DEBUG_PRELINK;
1601 GL(dl_trace_prelink) = &envline[17];
1603 break;
1605 case 20:
1606 /* The mode of the dynamic linker can be set. */
1607 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
1608 mode = trace;
1609 break;
1611 /* We might have some extra environment variable to handle. This
1612 is tricky due to the pre-processing of the length of the name
1613 in the switch statement here. The code here assumes that added
1614 environment variables have a different length. */
1615 #ifdef EXTRA_LD_ENVVARS
1616 EXTRA_LD_ENVVARS
1617 #endif
1621 /* The caller wants this information. */
1622 *modep = mode;
1624 /* Extra security for SUID binaries. Remove all dangerous environment
1625 variables. */
1626 if (__builtin_expect (__libc_enable_secure, 0))
1628 static const char unsecure_envvars[] =
1629 #ifdef EXTRA_UNSECURE_ENVVARS
1630 EXTRA_UNSECURE_ENVVARS
1631 #endif
1632 UNSECURE_ENVVARS;
1633 const char *nextp;
1635 nextp = unsecure_envvars;
1638 unsetenv (nextp);
1639 /* We could use rawmemchr but this need not be fast. */
1640 nextp = (char *) (strchr) (nextp, '\0') + 1;
1642 while (*nextp != '\0');
1644 if (__access ("/etc/suid-debug", F_OK) != 0)
1645 unsetenv ("MALLOC_CHECK_");
1647 /* If we have to run the dynamic linker in debugging mode and the
1648 LD_DEBUG_OUTPUT environment variable is given, we write the debug
1649 messages to this file. */
1650 else if (any_debug && debug_output != NULL)
1652 #ifdef O_NOFOLLOW
1653 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
1654 #else
1655 const int flags = O_WRONLY | O_APPEND | O_CREAT;
1656 #endif
1657 size_t name_len = strlen (debug_output);
1658 char buf[name_len + 12];
1659 char *startp;
1661 buf[name_len + 11] = '\0';
1662 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
1663 *--startp = '.';
1664 startp = memcpy (startp - name_len, debug_output, name_len);
1666 GL(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
1667 if (GL(dl_debug_fd) == -1)
1668 /* We use standard output if opening the file failed. */
1669 GL(dl_debug_fd) = STDOUT_FILENO;
1674 /* Print the various times we collected. */
1675 static void
1676 print_statistics (void)
1678 #ifndef HP_TIMING_NONAVAIL
1679 char buf[200];
1680 char *cp;
1681 char *wp;
1683 /* Total time rtld used. */
1684 if (HP_TIMING_AVAIL)
1686 HP_TIMING_PRINT (buf, sizeof (buf), rtld_total_time);
1687 INT(_dl_debug_printf) ("\nruntime linker statistics:\n"
1688 " total startup time in dynamic loader: %s\n",
1689 buf);
1692 /* Print relocation statistics. */
1693 if (HP_TIMING_AVAIL)
1695 char pbuf[30];
1696 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
1697 cp = _itoa ((1000ULL * relocate_time) / rtld_total_time,
1698 pbuf + sizeof (pbuf), 10, 0);
1699 wp = pbuf;
1700 switch (pbuf + sizeof (pbuf) - cp)
1702 case 3:
1703 *wp++ = *cp++;
1704 case 2:
1705 *wp++ = *cp++;
1706 case 1:
1707 *wp++ = '.';
1708 *wp++ = *cp++;
1710 *wp = '\0';
1711 INT(_dl_debug_printf) ("\
1712 time needed for relocation: %s (%s%%)\n",
1713 buf, pbuf);
1715 #endif
1716 INT(_dl_debug_printf) (" number of relocations: %lu\n",
1717 GL(dl_num_relocations));
1718 INT(_dl_debug_printf) (" number of relocations from cache: %lu\n",
1719 GL(dl_num_cache_relocations));
1721 #ifndef HP_TIMING_NONAVAIL
1722 /* Time spend while loading the object and the dependencies. */
1723 if (HP_TIMING_AVAIL)
1725 char pbuf[30];
1726 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
1727 cp = _itoa ((1000ULL * load_time) / rtld_total_time,
1728 pbuf + sizeof (pbuf), 10, 0);
1729 wp = pbuf;
1730 switch (pbuf + sizeof (pbuf) - cp)
1732 case 3:
1733 *wp++ = *cp++;
1734 case 2:
1735 *wp++ = *cp++;
1736 case 1:
1737 *wp++ = '.';
1738 *wp++ = *cp++;
1740 *wp = '\0';
1741 INT(_dl_debug_printf) ("\
1742 time needed to load objects: %s (%s%%)\n",
1743 buf, pbuf);
1745 #endif