Update.
[glibc.git] / elf / rtld.c
blob3241cc9d102ecc5fa89fcd8aef2cfa5058ef04ee
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) *) GL(dl_rtld_map).l_map_start;
256 phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start + 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;
711 #ifdef USE_TLS
712 case PT_TLS:
713 /* Note that in the case the dynamic linker we duplicate work
714 here since we read the PT_TLS entry already in
715 _dl_start_final. But the result is repeatable so do not
716 check for this special but unimportant case. */
717 GL(dl_loaded)->l_tls_blocksize = ph->p_memsz;
718 GL(dl_loaded)->l_tls_initimage_size = ph->p_filesz;
719 GL(dl_loaded)->l_tls_initimage = (void *) (GL(dl_loaded)->l_addr
720 + ph->p_offset);
721 /* This is the first element of the initialization image list.
722 It is created as a circular list so that we can easily
723 append to it. */
724 GL(dl_initimage_list) = GL(dl_loaded)->l_tls_nextimage = GL(dl_loaded);
726 /* This image get the ID one. */
727 GL(dl_tls_module_cnt) = GL(dl_loaded)->l_tls_modid = 1;
728 break;
729 #endif
731 if (! GL(dl_loaded)->l_map_end)
732 GL(dl_loaded)->l_map_end = ~0;
733 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
735 /* We were invoked directly, so the program might not have a
736 PT_INTERP. */
737 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
738 /* _dl_rtld_libname.next = NULL; Alread zero. */
739 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
741 else
742 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
744 if (! rtld_is_main)
746 /* Extract the contents of the dynamic section for easy access. */
747 elf_get_dynamic_info (GL(dl_loaded));
748 if (GL(dl_loaded)->l_info[DT_HASH])
749 /* Set up our cache of pointers into the hash table. */
750 _dl_setup_hash (GL(dl_loaded));
753 if (__builtin_expect (mode, normal) == verify)
755 /* We were called just to verify that this is a dynamic
756 executable using us as the program interpreter. Exit with an
757 error if we were not able to load the binary or no interpreter
758 is specified (i.e., this is no dynamically linked binary. */
759 if (GL(dl_loaded)->l_ld == NULL)
760 _exit (1);
762 /* We allow here some platform specific code. */
763 #ifdef DISTINGUISH_LIB_VERSIONS
764 DISTINGUISH_LIB_VERSIONS;
765 #endif
766 _exit (has_interp ? 0 : 2);
769 if (! rtld_is_main)
770 /* Initialize the data structures for the search paths for shared
771 objects. */
772 _dl_init_paths (library_path);
774 /* Put the link_map for ourselves on the chain so it can be found by
775 name. Note that at this point the global chain of link maps contains
776 exactly one element, which is pointed to by dl_loaded. */
777 if (! GL(dl_rtld_map).l_name)
778 /* If not invoked directly, the dynamic linker shared object file was
779 found by the PT_INTERP name. */
780 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
781 GL(dl_rtld_map).l_type = lt_library;
782 GL(dl_loaded)->l_next = &GL(dl_rtld_map);
783 GL(dl_rtld_map).l_prev = GL(dl_loaded);
784 ++GL(dl_nloaded);
786 /* We have two ways to specify objects to preload: via environment
787 variable and via the file /etc/ld.so.preload. The latter can also
788 be used when security is enabled. */
789 preloads = NULL;
790 npreloads = 0;
792 if (__builtin_expect (preloadlist != NULL, 0))
794 /* The LD_PRELOAD environment variable gives list of libraries
795 separated by white space or colons that are loaded before the
796 executable's dependencies and prepended to the global scope
797 list. If the binary is running setuid all elements
798 containing a '/' are ignored since it is insecure. */
799 char *list = strdupa (preloadlist);
800 char *p;
802 HP_TIMING_NOW (start);
804 /* Prevent optimizing strsep. Speed is not important here. */
805 while ((p = (strsep) (&list, " :")) != NULL)
806 if (p[0] != '\0'
807 && (__builtin_expect (! __libc_enable_secure, 1)
808 || strchr (p, '/') == NULL))
810 struct link_map *new_map = INT(_dl_map_object) (GL(dl_loaded), p,
811 1, lt_library,
812 0, 0);
813 if (++new_map->l_opencount == 1)
814 /* It is no duplicate. */
815 ++npreloads;
818 HP_TIMING_NOW (stop);
819 HP_TIMING_DIFF (diff, start, stop);
820 HP_TIMING_ACCUM_NT (load_time, diff);
823 /* Read the contents of the file. */
824 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
825 PROT_READ | PROT_WRITE);
826 if (__builtin_expect (file != MAP_FAILED, 0))
828 /* Parse the file. It contains names of libraries to be loaded,
829 separated by white spaces or `:'. It may also contain
830 comments introduced by `#'. */
831 char *problem;
832 char *runp;
833 size_t rest;
835 /* Eliminate comments. */
836 runp = file;
837 rest = file_size;
838 while (rest > 0)
840 char *comment = memchr (runp, '#', rest);
841 if (comment == NULL)
842 break;
844 rest -= comment - runp;
846 *comment = ' ';
847 while (--rest > 0 && *++comment != '\n');
850 /* We have one problematic case: if we have a name at the end of
851 the file without a trailing terminating characters, we cannot
852 place the \0. Handle the case separately. */
853 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
854 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
856 problem = &file[file_size];
857 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
858 && problem[-1] != '\n' && problem[-1] != ':')
859 --problem;
861 if (problem > file)
862 problem[-1] = '\0';
864 else
866 problem = NULL;
867 file[file_size - 1] = '\0';
870 HP_TIMING_NOW (start);
872 if (file != problem)
874 char *p;
875 runp = file;
876 while ((p = strsep (&runp, ": \t\n")) != NULL)
877 if (p[0] != '\0')
879 struct link_map *new_map = INT(_dl_map_object) (GL(dl_loaded),
880 p, 1,
881 lt_library,
882 0, 0);
883 if (++new_map->l_opencount == 1)
884 /* It is no duplicate. */
885 ++npreloads;
889 if (problem != NULL)
891 char *p = strndupa (problem, file_size - (problem - file));
892 struct link_map *new_map = INT(_dl_map_object) (GL(dl_loaded), p, 1,
893 lt_library, 0, 0);
894 if (++new_map->l_opencount == 1)
895 /* It is no duplicate. */
896 ++npreloads;
899 HP_TIMING_NOW (stop);
900 HP_TIMING_DIFF (diff, start, stop);
901 HP_TIMING_ACCUM_NT (load_time, diff);
903 /* We don't need the file anymore. */
904 __munmap (file, file_size);
907 if (__builtin_expect (npreloads, 0) != 0)
909 /* Set up PRELOADS with a vector of the preloaded libraries. */
910 struct link_map *l;
911 preloads = __alloca (npreloads * sizeof preloads[0]);
912 l = GL(dl_rtld_map).l_next; /* End of the chain before preloads. */
913 i = 0;
916 preloads[i++] = l;
917 l = l->l_next;
918 } while (l);
919 assert (i == npreloads);
922 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
923 specified some libraries to load, these are inserted before the actual
924 dependencies in the executable's searchlist for symbol resolution. */
925 HP_TIMING_NOW (start);
926 INT(_dl_map_object_deps) (GL(dl_loaded), preloads, npreloads, mode == trace);
927 HP_TIMING_NOW (stop);
928 HP_TIMING_DIFF (diff, start, stop);
929 HP_TIMING_ACCUM_NT (load_time, diff);
931 /* Mark all objects as being in the global scope and set the open
932 counter. */
933 for (i = GL(dl_loaded)->l_searchlist.r_nlist; i > 0; )
935 --i;
936 GL(dl_loaded)->l_searchlist.r_list[i]->l_global = 1;
937 ++GL(dl_loaded)->l_searchlist.r_list[i]->l_opencount;
940 #ifndef MAP_ANON
941 /* We are done mapping things, so close the zero-fill descriptor. */
942 __close (_dl_zerofd);
943 _dl_zerofd = -1;
944 #endif
946 /* Remove _dl_rtld_map from the chain. */
947 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
948 if (GL(dl_rtld_map).l_next)
949 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
951 if (__builtin_expect (GL(dl_rtld_map).l_opencount > 1, 1))
953 /* Some DT_NEEDED entry referred to the interpreter object itself, so
954 put it back in the list of visible objects. We insert it into the
955 chain in symbol search order because gdb uses the chain's order as
956 its symbol search order. */
957 i = 1;
958 while (GL(dl_loaded)->l_searchlist.r_list[i] != &GL(dl_rtld_map))
959 ++i;
960 GL(dl_rtld_map).l_prev = GL(dl_loaded)->l_searchlist.r_list[i - 1];
961 if (__builtin_expect (mode, normal) == normal)
962 GL(dl_rtld_map).l_next = (i + 1 < GL(dl_loaded)->l_searchlist.r_nlist
963 ? GL(dl_loaded)->l_searchlist.r_list[i + 1]
964 : NULL);
965 else
966 /* In trace mode there might be an invisible object (which we
967 could not find) after the previous one in the search list.
968 In this case it doesn't matter much where we put the
969 interpreter object, so we just initialize the list pointer so
970 that the assertion below holds. */
971 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
973 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
974 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
975 if (GL(dl_rtld_map).l_next)
977 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
978 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
982 /* Now let us see whether all libraries are available in the
983 versions we need. */
985 struct version_check_args args;
986 args.doexit = mode == normal;
987 args.dotrace = mode == trace;
988 _dl_receive_error (print_missing_version, version_check_doit, &args);
991 if (__builtin_expect (mode, normal) != normal)
993 /* We were run just to list the shared libraries. It is
994 important that we do this before real relocation, because the
995 functions we call below for output may no longer work properly
996 after relocation. */
997 if (! GL(dl_loaded)->l_info[DT_NEEDED])
998 _dl_printf ("\tstatically linked\n");
999 else
1001 struct link_map *l;
1003 if (GL(dl_debug_mask) & DL_DEBUG_PRELINK)
1005 struct r_scope_elem *scope = &GL(dl_loaded)->l_searchlist;
1007 for (i = 0; i < scope->r_nlist; i++)
1009 l = scope->r_list [i];
1010 if (l->l_faked)
1012 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1013 continue;
1015 if (_dl_name_match_p (GL(dl_trace_prelink), l))
1016 GL(dl_trace_prelink_map) = l;
1017 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)\n",
1018 l->l_libname->name[0] ? l->l_libname->name
1019 : _dl_argv[0] ?: "<main program>",
1020 l->l_name[0] ? l->l_name
1021 : _dl_argv[0] ?: "<main program>",
1022 (int) sizeof l->l_map_start * 2,
1023 l->l_map_start,
1024 (int) sizeof l->l_addr * 2,
1025 l->l_addr);
1028 else
1030 for (l = GL(dl_loaded)->l_next; l; l = l->l_next)
1031 if (l->l_faked)
1032 /* The library was not found. */
1033 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1034 else
1035 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1036 l->l_name, (int) sizeof l->l_map_start * 2,
1037 l->l_map_start);
1041 if (__builtin_expect (mode, trace) != trace)
1042 for (i = 1; i < _dl_argc; ++i)
1044 const ElfW(Sym) *ref = NULL;
1045 ElfW(Addr) loadbase;
1046 lookup_t result;
1048 result = INT(_dl_lookup_symbol) (_dl_argv[i], GL(dl_loaded),
1049 &ref, GL(dl_loaded)->l_scope,
1050 ELF_RTYPE_CLASS_PLT, 1);
1052 loadbase = LOOKUP_VALUE_ADDRESS (result);
1054 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
1055 _dl_argv[i],
1056 (int) sizeof ref->st_value * 2, ref->st_value,
1057 (int) sizeof loadbase * 2, loadbase);
1059 else
1061 /* If LD_WARN is set warn about undefined symbols. */
1062 if (GL(dl_lazy) >= 0 && GL(dl_verbose))
1064 /* We have to do symbol dependency testing. */
1065 struct relocate_args args;
1066 struct link_map *l;
1068 args.lazy = GL(dl_lazy);
1070 l = GL(dl_loaded);
1071 while (l->l_next)
1072 l = l->l_next;
1075 if (l != &GL(dl_rtld_map) && ! l->l_faked)
1077 args.l = l;
1078 _dl_receive_error (print_unresolved, relocate_doit,
1079 &args);
1081 l = l->l_prev;
1082 } while (l);
1084 if ((GL(dl_debug_mask) & DL_DEBUG_PRELINK)
1085 && GL(dl_rtld_map).l_opencount > 1)
1086 INT(_dl_relocate_object) (&GL(dl_rtld_map),
1087 GL(dl_loaded)->l_scope, 0, 0);
1090 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
1091 if (version_info)
1093 /* Print more information. This means here, print information
1094 about the versions needed. */
1095 int first = 1;
1096 struct link_map *map = GL(dl_loaded);
1098 for (map = GL(dl_loaded); map != NULL; map = map->l_next)
1100 const char *strtab;
1101 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
1102 ElfW(Verneed) *ent;
1104 if (dyn == NULL)
1105 continue;
1107 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
1108 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
1110 if (first)
1112 _dl_printf ("\n\tVersion information:\n");
1113 first = 0;
1116 _dl_printf ("\t%s:\n",
1117 map->l_name[0] ? map->l_name : _dl_argv[0]);
1119 while (1)
1121 ElfW(Vernaux) *aux;
1122 struct link_map *needed;
1124 needed = find_needed (strtab + ent->vn_file);
1125 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
1127 while (1)
1129 const char *fname = NULL;
1131 if (needed != NULL
1132 && match_version (strtab + aux->vna_name,
1133 needed))
1134 fname = needed->l_name;
1136 _dl_printf ("\t\t%s (%s) %s=> %s\n",
1137 strtab + ent->vn_file,
1138 strtab + aux->vna_name,
1139 aux->vna_flags & VER_FLG_WEAK
1140 ? "[WEAK] " : "",
1141 fname ?: "not found");
1143 if (aux->vna_next == 0)
1144 /* No more symbols. */
1145 break;
1147 /* Next symbol. */
1148 aux = (ElfW(Vernaux) *) ((char *) aux
1149 + aux->vna_next);
1152 if (ent->vn_next == 0)
1153 /* No more dependencies. */
1154 break;
1156 /* Next dependency. */
1157 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
1163 _exit (0);
1166 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]
1167 && ! __builtin_expect (GL(dl_profile) != NULL, 0))
1169 ElfW(Lib) *liblist, *liblistend;
1170 struct link_map **r_list, **r_listend, *l;
1171 const char *strtab = (const void *) D_PTR (GL(dl_loaded),
1172 l_info[DT_STRTAB]);
1174 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
1175 liblist = (ElfW(Lib) *)
1176 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
1177 liblistend = (ElfW(Lib) *)
1178 ((char *) liblist
1179 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
1180 r_list = GL(dl_loaded)->l_searchlist.r_list;
1181 r_listend = r_list + GL(dl_loaded)->l_searchlist.r_nlist;
1183 for (; r_list < r_listend && liblist < liblistend; r_list++)
1185 l = *r_list;
1187 if (l == GL(dl_loaded))
1188 continue;
1190 /* If the library is not mapped where it should, fail. */
1191 if (l->l_addr)
1192 break;
1194 /* Next, check if checksum matches. */
1195 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
1196 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
1197 != liblist->l_checksum)
1198 break;
1200 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
1201 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
1202 != liblist->l_time_stamp)
1203 break;
1205 if (! _dl_name_match_p (strtab + liblist->l_name, l))
1206 break;
1208 ++liblist;
1212 if (r_list == r_listend && liblist == liblistend)
1213 prelinked = 1;
1215 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1216 _dl_printf ("\nprelink checking: %s\n", prelinked ? "ok" : "failed");
1219 if (prelinked)
1221 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
1223 ElfW(Rela) *conflict, *conflictend;
1224 #ifndef HP_TIMING_NONAVAIL
1225 hp_timing_t start;
1226 hp_timing_t stop;
1227 #endif
1229 HP_TIMING_NOW (start);
1230 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
1231 conflict = (ElfW(Rela) *)
1232 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
1233 conflictend = (ElfW(Rela) *)
1234 ((char *) conflict
1235 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
1236 _dl_resolve_conflicts (GL(dl_loaded), conflict, conflictend);
1237 HP_TIMING_NOW (stop);
1238 HP_TIMING_DIFF (relocate_time, start, stop);
1241 _dl_sysdep_start_cleanup ();
1243 else
1245 /* Now we have all the objects loaded. Relocate them all except for
1246 the dynamic linker itself. We do this in reverse order so that copy
1247 relocs of earlier objects overwrite the data written by later
1248 objects. We do not re-relocate the dynamic linker itself in this
1249 loop because that could result in the GOT entries for functions we
1250 call being changed, and that would break us. It is safe to relocate
1251 the dynamic linker out of order because it has no copy relocs (we
1252 know that because it is self-contained). */
1254 struct link_map *l;
1255 int consider_profiling = GL(dl_profile) != NULL;
1256 #ifndef HP_TIMING_NONAVAIL
1257 hp_timing_t start;
1258 hp_timing_t stop;
1259 hp_timing_t add;
1260 #endif
1262 /* If we are profiling we also must do lazy reloaction. */
1263 GL(dl_lazy) |= consider_profiling;
1265 l = GL(dl_loaded);
1266 while (l->l_next)
1267 l = l->l_next;
1269 HP_TIMING_NOW (start);
1272 /* While we are at it, help the memory handling a bit. We have to
1273 mark some data structures as allocated with the fake malloc()
1274 implementation in ld.so. */
1275 struct libname_list *lnp = l->l_libname->next;
1277 while (__builtin_expect (lnp != NULL, 0))
1279 lnp->dont_free = 1;
1280 lnp = lnp->next;
1283 if (l != &GL(dl_rtld_map))
1284 INT(_dl_relocate_object) (l, l->l_scope, GL(dl_lazy),
1285 consider_profiling);
1287 l = l->l_prev;
1289 while (l);
1290 HP_TIMING_NOW (stop);
1292 HP_TIMING_DIFF (relocate_time, start, stop);
1294 /* Do any necessary cleanups for the startup OS interface code.
1295 We do these now so that no calls are made after rtld re-relocation
1296 which might be resolved to different functions than we expect.
1297 We cannot do this before relocating the other objects because
1298 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
1299 _dl_sysdep_start_cleanup ();
1301 /* Now enable profiling if needed. Like the previous call,
1302 this has to go here because the calls it makes should use the
1303 rtld versions of the functions (particularly calloc()), but it
1304 needs to have _dl_profile_map set up by the relocator. */
1305 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
1306 /* We must prepare the profiling. */
1307 INT(_dl_start_profile) (GL(dl_profile_map), GL(dl_profile_output));
1309 if (GL(dl_rtld_map).l_opencount > 1)
1311 /* There was an explicit ref to the dynamic linker as a shared lib.
1312 Re-relocate ourselves with user-controlled symbol definitions. */
1313 HP_TIMING_NOW (start);
1314 INT(_dl_relocate_object) (&GL(dl_rtld_map), GL(dl_loaded)->l_scope,
1315 0, 0);
1316 HP_TIMING_NOW (stop);
1317 HP_TIMING_DIFF (add, start, stop);
1318 HP_TIMING_ACCUM_NT (relocate_time, add);
1322 /* Now set up the variable which helps the assembler startup code. */
1323 GL(dl_main_searchlist) = &GL(dl_loaded)->l_searchlist;
1324 GL(dl_global_scope)[0] = &GL(dl_loaded)->l_searchlist;
1326 /* Save the information about the original global scope list since
1327 we need it in the memory handling later. */
1328 GL(dl_initial_searchlist) = *GL(dl_main_searchlist);
1331 /* Initialize _r_debug. */
1332 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr);
1333 struct link_map *l;
1335 l = GL(dl_loaded);
1337 #ifdef ELF_MACHINE_DEBUG_SETUP
1339 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1341 ELF_MACHINE_DEBUG_SETUP (l, r);
1342 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1344 #else
1346 if (l->l_info[DT_DEBUG])
1347 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1348 with the run-time address of the r_debug structure */
1349 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1351 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1352 case you run gdb on the dynamic linker directly. */
1353 if (GL(dl_rtld_map).l_info[DT_DEBUG])
1354 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1356 #endif
1358 /* Notify the debugger that all objects are now mapped in. */
1359 r->r_state = RT_ADD;
1360 INT(_dl_debug_state) ();
1363 #ifndef MAP_COPY
1364 /* We must munmap() the cache file. */
1365 INT(_dl_unload_cache) ();
1366 #endif
1368 /* Once we return, _dl_sysdep_start will invoke
1369 the DT_INIT functions and then *USER_ENTRY. */
1372 /* This is a little helper function for resolving symbols while
1373 tracing the binary. */
1374 static void
1375 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
1376 const char *errstring)
1378 if (objname[0] == '\0')
1379 objname = _dl_argv[0] ?: "<main program>";
1380 _dl_error_printf ("%s (%s)\n", errstring, objname);
1383 /* This is a little helper function for resolving symbols while
1384 tracing the binary. */
1385 static void
1386 print_missing_version (int errcode __attribute__ ((unused)),
1387 const char *objname, const char *errstring)
1389 _dl_error_printf ("%s: %s: %s\n", _dl_argv[0] ?: "<program name unknown>",
1390 objname, errstring);
1393 /* Nonzero if any of the debugging options is enabled. */
1394 static int any_debug;
1396 /* Process the string given as the parameter which explains which debugging
1397 options are enabled. */
1398 static void
1399 process_dl_debug (const char *dl_debug)
1401 /* When adding new entries make sure that the maximal length of a name
1402 is correctly handled in the LD_DEBUG_HELP code below. */
1403 static const struct
1405 unsigned char len;
1406 const char name[10];
1407 const char helptext[41];
1408 unsigned short int mask;
1409 } debopts[] =
1411 #define LEN_AND_STR(str) sizeof (str) - 1, str
1412 { LEN_AND_STR ("libs"), "display library search paths",
1413 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
1414 { LEN_AND_STR ("reloc"), "display relocation processing",
1415 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
1416 { LEN_AND_STR ("files"), "display progress for input file",
1417 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
1418 { LEN_AND_STR ("symbols"), "display symbol table processing",
1419 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
1420 { LEN_AND_STR ("bindings"), "display information about symbol binding",
1421 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
1422 { LEN_AND_STR ("versions"), "display version dependencies",
1423 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1424 { LEN_AND_STR ("all"), "all previous options combined",
1425 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
1426 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1427 { LEN_AND_STR ("statistics"), "display relocation statistics",
1428 DL_DEBUG_STATISTICS },
1429 { LEN_AND_STR ("help"), "display this help message and exit",
1430 DL_DEBUG_HELP },
1432 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
1434 /* Skip separating white spaces and commas. */
1435 while (*dl_debug != '\0')
1437 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
1439 size_t cnt;
1440 size_t len = 1;
1442 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
1443 && dl_debug[len] != ',' && dl_debug[len] != ':')
1444 ++len;
1446 for (cnt = 0; cnt < ndebopts; ++cnt)
1447 if (debopts[cnt].len == len
1448 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
1450 GL(dl_debug_mask) |= debopts[cnt].mask;
1451 any_debug = 1;
1452 break;
1455 if (cnt == ndebopts)
1457 /* Display a warning and skip everything until next
1458 separator. */
1459 char *copy = strndupa (dl_debug, len);
1460 _dl_error_printf ("\
1461 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
1464 dl_debug += len;
1465 continue;
1468 ++dl_debug;
1471 if (GL(dl_debug_mask) & DL_DEBUG_HELP)
1473 size_t cnt;
1475 _dl_printf ("\
1476 Valid options for the LD_DEBUG environment variable are:\n\n");
1478 for (cnt = 0; cnt < ndebopts; ++cnt)
1479 _dl_printf (" %s%s %s\n", debopts[cnt].name,
1480 " " + strlen (debopts[cnt].name) - 3,
1481 debopts[cnt].helptext);
1483 _dl_printf ("\n\
1484 To direct the debugging output into a file instead of standard output\n\
1485 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
1486 _exit (0);
1490 /* Process all environments variables the dynamic linker must recognize.
1491 Since all of them start with `LD_' we are a bit smarter while finding
1492 all the entries. */
1493 extern char **_environ;
1496 static void
1497 process_envvars (enum mode *modep)
1499 char **runp = _environ;
1500 char *envline;
1501 enum mode mode = normal;
1502 char *debug_output = NULL;
1504 /* This is the default place for profiling data file. */
1505 GL(dl_profile_output) = &"/var/tmp\0/var/profile"[__libc_enable_secure
1506 ? 9 : 0];
1508 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
1510 size_t len = 0;
1512 while (envline[len] != '\0' && envline[len] != '=')
1513 ++len;
1515 if (envline[len] != '=')
1516 /* This is a "LD_" variable at the end of the string without
1517 a '=' character. Ignore it since otherwise we will access
1518 invalid memory below. */
1519 continue;
1521 switch (len)
1523 case 4:
1524 /* Warning level, verbose or not. */
1525 if (memcmp (envline, "WARN", 4) == 0)
1526 GL(dl_verbose) = envline[5] != '\0';
1527 break;
1529 case 5:
1530 /* Debugging of the dynamic linker? */
1531 if (memcmp (envline, "DEBUG", 5) == 0)
1532 process_dl_debug (&envline[6]);
1533 break;
1535 case 7:
1536 /* Print information about versions. */
1537 if (memcmp (envline, "VERBOSE", 7) == 0)
1539 version_info = envline[8] != '\0';
1540 break;
1543 /* List of objects to be preloaded. */
1544 if (memcmp (envline, "PRELOAD", 7) == 0)
1546 preloadlist = &envline[8];
1547 break;
1550 /* Which shared object shall be profiled. */
1551 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
1552 GL(dl_profile) = &envline[8];
1553 break;
1555 case 8:
1556 /* Do we bind early? */
1557 if (memcmp (envline, "BIND_NOW", 8) == 0)
1559 GL(dl_lazy) = envline[9] == '\0';
1560 break;
1562 if (memcmp (envline, "BIND_NOT", 8) == 0)
1563 GL(dl_bind_not) = envline[9] != '\0';
1564 break;
1566 case 9:
1567 /* Test whether we want to see the content of the auxiliary
1568 array passed up from the kernel. */
1569 if (memcmp (envline, "SHOW_AUXV", 9) == 0)
1570 _dl_show_auxv ();
1571 break;
1573 case 10:
1574 /* Mask for the important hardware capabilities. */
1575 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
1576 GL(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL, 0, 0);
1577 break;
1579 case 11:
1580 /* Path where the binary is found. */
1581 if (!__libc_enable_secure
1582 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
1583 GL(dl_origin_path) = &envline[12];
1584 break;
1586 case 12:
1587 /* The library search path. */
1588 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
1590 library_path = &envline[13];
1591 break;
1594 /* Where to place the profiling data file. */
1595 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
1597 debug_output = &envline[13];
1598 break;
1601 if (memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
1602 GL(dl_dynamic_weak) = 1;
1603 break;
1605 case 14:
1606 /* Where to place the profiling data file. */
1607 if (!__libc_enable_secure
1608 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
1609 && envline[15] != '\0')
1610 GL(dl_profile_output) = &envline[15];
1611 break;
1613 case 16:
1614 /* The mode of the dynamic linker can be set. */
1615 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
1617 mode = trace;
1618 GL(dl_verbose) = 1;
1619 GL(dl_debug_mask) |= DL_DEBUG_PRELINK;
1620 GL(dl_trace_prelink) = &envline[17];
1622 break;
1624 case 20:
1625 /* The mode of the dynamic linker can be set. */
1626 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
1627 mode = trace;
1628 break;
1630 /* We might have some extra environment variable to handle. This
1631 is tricky due to the pre-processing of the length of the name
1632 in the switch statement here. The code here assumes that added
1633 environment variables have a different length. */
1634 #ifdef EXTRA_LD_ENVVARS
1635 EXTRA_LD_ENVVARS
1636 #endif
1640 /* The caller wants this information. */
1641 *modep = mode;
1643 /* Extra security for SUID binaries. Remove all dangerous environment
1644 variables. */
1645 if (__builtin_expect (__libc_enable_secure, 0))
1647 static const char unsecure_envvars[] =
1648 #ifdef EXTRA_UNSECURE_ENVVARS
1649 EXTRA_UNSECURE_ENVVARS
1650 #endif
1651 UNSECURE_ENVVARS;
1652 const char *nextp;
1654 nextp = unsecure_envvars;
1657 unsetenv (nextp);
1658 /* We could use rawmemchr but this need not be fast. */
1659 nextp = (char *) (strchr) (nextp, '\0') + 1;
1661 while (*nextp != '\0');
1663 if (__access ("/etc/suid-debug", F_OK) != 0)
1664 unsetenv ("MALLOC_CHECK_");
1666 /* If we have to run the dynamic linker in debugging mode and the
1667 LD_DEBUG_OUTPUT environment variable is given, we write the debug
1668 messages to this file. */
1669 else if (any_debug && debug_output != NULL)
1671 #ifdef O_NOFOLLOW
1672 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
1673 #else
1674 const int flags = O_WRONLY | O_APPEND | O_CREAT;
1675 #endif
1676 size_t name_len = strlen (debug_output);
1677 char buf[name_len + 12];
1678 char *startp;
1680 buf[name_len + 11] = '\0';
1681 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
1682 *--startp = '.';
1683 startp = memcpy (startp - name_len, debug_output, name_len);
1685 GL(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
1686 if (GL(dl_debug_fd) == -1)
1687 /* We use standard output if opening the file failed. */
1688 GL(dl_debug_fd) = STDOUT_FILENO;
1693 /* Print the various times we collected. */
1694 static void
1695 print_statistics (void)
1697 #ifndef HP_TIMING_NONAVAIL
1698 char buf[200];
1699 char *cp;
1700 char *wp;
1702 /* Total time rtld used. */
1703 if (HP_TIMING_AVAIL)
1705 HP_TIMING_PRINT (buf, sizeof (buf), rtld_total_time);
1706 INT(_dl_debug_printf) ("\nruntime linker statistics:\n"
1707 " total startup time in dynamic loader: %s\n",
1708 buf);
1711 /* Print relocation statistics. */
1712 if (HP_TIMING_AVAIL)
1714 char pbuf[30];
1715 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
1716 cp = _itoa ((1000ULL * relocate_time) / rtld_total_time,
1717 pbuf + sizeof (pbuf), 10, 0);
1718 wp = pbuf;
1719 switch (pbuf + sizeof (pbuf) - cp)
1721 case 3:
1722 *wp++ = *cp++;
1723 case 2:
1724 *wp++ = *cp++;
1725 case 1:
1726 *wp++ = '.';
1727 *wp++ = *cp++;
1729 *wp = '\0';
1730 INT(_dl_debug_printf) ("\
1731 time needed for relocation: %s (%s%%)\n",
1732 buf, pbuf);
1734 #endif
1735 INT(_dl_debug_printf) (" number of relocations: %lu\n",
1736 GL(dl_num_relocations));
1737 INT(_dl_debug_printf) (" number of relocations from cache: %lu\n",
1738 GL(dl_num_cache_relocations));
1740 #ifndef HP_TIMING_NONAVAIL
1741 /* Time spend while loading the object and the dependencies. */
1742 if (HP_TIMING_AVAIL)
1744 char pbuf[30];
1745 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
1746 cp = _itoa ((1000ULL * load_time) / rtld_total_time,
1747 pbuf + sizeof (pbuf), 10, 0);
1748 wp = pbuf;
1749 switch (pbuf + sizeof (pbuf) - cp)
1751 case 3:
1752 *wp++ = *cp++;
1753 case 2:
1754 *wp++ = *cp++;
1755 case 1:
1756 *wp++ = '.';
1757 *wp++ = *cp++;
1759 *wp = '\0';
1760 INT(_dl_debug_printf) ("\
1761 time needed to load objects: %s (%s%%)\n",
1762 buf, pbuf);
1764 #endif