* elf/rtld.c (dl_main): In rtld_is_main case, reinitialize
[glibc.git] / elf / rtld.c
blobd57d8838aca40254085adcd4ed5f1ba39693522e
1 /* Run time dynamic linker.
2 Copyright (C) 1995-2002, 2003 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 <errno.h>
21 #include <fcntl.h>
22 #include <stdbool.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <sys/mman.h> /* Check if MAP_ANON is defined. */
27 #include <sys/param.h>
28 #include <sys/stat.h>
29 #include <ldsodefs.h>
30 #include <stdio-common/_itoa.h>
31 #include <entry.h>
32 #include <fpu_control.h>
33 #include <hp-timing.h>
34 #include <bits/libc-lock.h>
35 #include "dynamic-link.h"
36 #include "dl-librecon.h"
37 #include <unsecvars.h>
38 #include <dl-cache.h>
39 #include <dl-procinfo.h>
40 #include <tls.h>
42 #include <assert.h>
44 /* Avoid PLT use for our local calls at startup. */
45 extern __typeof (__mempcpy) __mempcpy attribute_hidden;
47 /* GCC has mental blocks about _exit. */
48 extern __typeof (_exit) exit_internal asm ("_exit") attribute_hidden;
49 #define _exit exit_internal
51 /* Helper function to handle errors while resolving symbols. */
52 static void print_unresolved (int errcode, const char *objname,
53 const char *errsting);
55 /* Helper function to handle errors when a version is missing. */
56 static void print_missing_version (int errcode, const char *objname,
57 const char *errsting);
59 /* Print the various times we collected. */
60 static void print_statistics (void);
62 /* This is a list of all the modes the dynamic loader can be in. */
63 enum mode { normal, list, verify, trace };
65 /* Process all environments variables the dynamic linker must recognize.
66 Since all of them start with `LD_' we are a bit smarter while finding
67 all the entries. */
68 static void process_envvars (enum mode *modep);
70 int _dl_argc attribute_hidden;
71 char **_dl_argv = NULL;
72 INTDEF(_dl_argv)
74 /* Nonzero if we were run directly. */
75 unsigned int _dl_skip_args attribute_hidden;
77 /* Set nonzero during loading and initialization of executable and
78 libraries, cleared before the executable's entry point runs. This
79 must not be initialized to nonzero, because the unused dynamic
80 linker loaded in for libc.so's "ld.so.1" dep will provide the
81 definition seen by libc.so's initializer; that value must be zero,
82 and will be since that dynamic linker's _dl_start and dl_main will
83 never be called. */
84 int _dl_starting_up = 0;
85 INTVARDEF(_dl_starting_up)
87 /* This is the structure which defines all variables global to ld.so
88 (except those which cannot be added for some reason). */
89 struct rtld_global _rtld_global =
91 /* Get architecture specific initializer. */
92 #include <dl-procinfo.c>
93 ._dl_debug_fd = STDERR_FILENO,
94 #ifdef NEED_DL_SYSINFO
95 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
96 #endif
97 ._dl_lazy = 1,
98 ._dl_fpu_control = _FPU_DEFAULT,
99 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
100 ._dl_hwcap_mask = HWCAP_IMPORTANT,
101 /* Default presumption without further information is executable stack. */
102 ._dl_stack_flags = PF_R|PF_W|PF_X,
103 #ifdef _LIBC_REENTRANT
104 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER
105 #endif
107 strong_alias (_rtld_global, _rtld_local);
109 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
110 ElfW(Addr) *user_entry);
112 static struct libname_list _dl_rtld_libname;
113 static struct libname_list _dl_rtld_libname2;
115 /* We expect less than a second for relocation. */
116 #ifdef HP_SMALL_TIMING_AVAIL
117 # undef HP_TIMING_AVAIL
118 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
119 #endif
121 /* Variable for statistics. */
122 #ifndef HP_TIMING_NONAVAIL
123 static hp_timing_t rtld_total_time;
124 static hp_timing_t relocate_time;
125 static hp_timing_t load_time;
126 static hp_timing_t start_time;
127 #endif
129 /* Additional definitions needed by TLS initialization. */
130 #ifdef TLS_INIT_HELPER
131 TLS_INIT_HELPER
132 #endif
134 /* Helper function for syscall implementation. */
135 #ifdef DL_SYSINFO_IMPLEMENTATION
136 DL_SYSINFO_IMPLEMENTATION
137 #endif
139 /* Before ld.so is relocated we must not access variables which need
140 relocations. This means variables which are exported. Variables
141 declared as static are fine. If we can mark a variable hidden this
142 is fine, too. The latter is impotant here. We can avoid setting
143 up a temporary link map for ld.so if we can mark _rtld_global as
144 hidden. */
145 #if defined PI_STATIC_AND_HIDDEN && defined HAVE_HIDDEN \
146 && defined HAVE_VISIBILITY_ATTRIBUTE
147 # define DONT_USE_BOOTSTRAP_MAP 1
148 #endif
150 #ifdef DONT_USE_BOOTSTRAP_MAP
151 static ElfW(Addr) _dl_start_final (void *arg);
152 #else
153 struct dl_start_final_info
155 struct link_map l;
156 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
157 hp_timing_t start_time;
158 #endif
160 static ElfW(Addr) _dl_start_final (void *arg,
161 struct dl_start_final_info *info);
162 #endif
164 /* These defined magically in the linker script. */
165 extern char _begin[] attribute_hidden;
166 extern char _end[] attribute_hidden;
169 #ifdef RTLD_START
170 RTLD_START
171 #else
172 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
173 #endif
175 #ifndef VALIDX
176 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
177 + DT_EXTRANUM + DT_VALTAGIDX (tag))
178 #endif
179 #ifndef ADDRIDX
180 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
181 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
182 #endif
184 /* This is the second half of _dl_start (below). It can be inlined safely
185 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
186 references. When the tools don't permit us to avoid using a GOT entry
187 for _dl_rtld_global (no attribute_hidden support), we must make sure
188 this function is not inlined (see below). */
190 #ifdef DONT_USE_BOOTSTRAP_MAP
191 static inline ElfW(Addr) __attribute__ ((always_inline))
192 _dl_start_final (void *arg)
193 #else
194 static ElfW(Addr) __attribute__ ((noinline))
195 _dl_start_final (void *arg, struct dl_start_final_info *info)
196 #endif
198 ElfW(Addr) start_addr;
200 if (HP_TIMING_AVAIL)
202 /* If it hasn't happen yet record the startup time. */
203 if (! HP_TIMING_INLINE)
204 HP_TIMING_NOW (start_time);
205 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
206 else
207 start_time = info->start_time;
208 #endif
210 /* Initialize the timing functions. */
211 HP_TIMING_DIFF_INIT ();
214 /* Transfer data about ourselves to the permanent link_map structure. */
215 #ifndef DONT_USE_BOOTSTRAP_MAP
216 GL(dl_rtld_map).l_addr = info->l.l_addr;
217 GL(dl_rtld_map).l_ld = info->l.l_ld;
218 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
219 sizeof GL(dl_rtld_map).l_info);
220 GL(dl_rtld_map).l_mach = info->l.l_mach;
221 #endif
222 _dl_setup_hash (&GL(dl_rtld_map));
223 GL(dl_rtld_map).l_opencount = 1;
224 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
225 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
226 /* Copy the TLS related data if necessary. */
227 #if USE_TLS && !defined DONT_USE_BOOTSTRAP_MAP
228 # if USE___THREAD
229 assert (info->l.l_tls_modid != 0);
230 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
231 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
232 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
233 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
234 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
235 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
236 GL(dl_rtld_map).l_tls_modid = 1;
237 # else
238 assert (info->l.l_tls_modid == 0);
239 # if NO_TLS_OFFSET != 0
240 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
241 # endif
242 # endif
244 #endif
246 #if HP_TIMING_AVAIL
247 HP_TIMING_NOW (GL(dl_cpuclock_offset));
248 #endif
250 /* Call the OS-dependent function to set up life so we can do things like
251 file access. It will call `dl_main' (below) to do all the real work
252 of the dynamic linker, and then unwind our frame and run the user
253 entry point on the same stack we entered on. */
254 start_addr = _dl_sysdep_start (arg, &dl_main);
256 #ifndef HP_TIMING_NONAVAIL
257 if (HP_TIMING_AVAIL)
259 hp_timing_t end_time;
261 /* Get the current time. */
262 HP_TIMING_NOW (end_time);
264 /* Compute the difference. */
265 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
267 #endif
269 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
270 print_statistics ();
272 return start_addr;
275 static ElfW(Addr) __attribute_used__ internal_function
276 _dl_start (void *arg)
278 #ifdef DONT_USE_BOOTSTRAP_MAP
279 # define bootstrap_map GL(dl_rtld_map)
280 #else
281 struct dl_start_final_info info;
282 # define bootstrap_map info.l
283 #endif
285 /* This #define produces dynamic linking inline functions for
286 bootstrap relocation instead of general-purpose relocation. */
287 #define RTLD_BOOTSTRAP
288 #define RESOLVE_MAP(sym, version, flags) \
289 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : &bootstrap_map)
290 #define RESOLVE(sym, version, flags) \
291 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : bootstrap_map.l_addr)
292 #include "dynamic-link.h"
294 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
295 #ifdef DONT_USE_BOOTSTRAP_MAP
296 HP_TIMING_NOW (start_time);
297 #else
298 HP_TIMING_NOW (info.start_time);
299 #endif
301 /* Partly clean the `bootstrap_map' structure up. Don't use
302 `memset' since it might not be built in or inlined and we cannot
303 make function calls at this point. Use '__builtin_memset' if we
304 know it is available. We do not have to clear the memory if we
305 do not have to use the temporary bootstrap_map. Global variables
306 are initialized to zero by default. */
307 #ifndef DONT_USE_BOOTSTRAP_MAP
308 # ifdef HAVE_BUILTIN_MEMSET
309 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
310 # else
311 for (size_t cnt = 0;
312 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
313 ++cnt)
314 bootstrap_map.l_info[cnt] = 0;
315 # endif
316 #endif
318 /* Figure out the run-time load address of the dynamic linker itself. */
319 bootstrap_map.l_addr = elf_machine_load_address ();
321 /* Read our own dynamic section and fill in the info array. */
322 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
323 elf_get_dynamic_info (&bootstrap_map, NULL);
325 #if defined USE_TLS && NO_TLS_OFFSET != 0
326 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
327 #endif
329 #if USE___THREAD
330 /* Get the dynamic linker's own program header. First we need the ELF
331 file header. The `_begin' symbol created by the linker script points
332 to it. When we have something like GOTOFF relocs, we can use a plain
333 reference to find the runtime address. Without that, we have to rely
334 on the `l_addr' value, which is not the value we want when prelinked. */
335 dtv_t initdtv[3];
336 ElfW(Ehdr) *ehdr
337 # ifdef DONT_USE_BOOTSTRAP_MAP
338 = (ElfW(Ehdr) *) &_begin;
339 # else
340 = (ElfW(Ehdr) *) bootstrap_map.l_addr;
341 # endif
342 ElfW(Phdr) *phdr = (ElfW(Phdr) *) ((void *) ehdr + ehdr->e_phoff);
343 size_t cnt = ehdr->e_phnum; /* PT_TLS is usually the last phdr. */
344 while (cnt-- > 0)
345 if (phdr[cnt].p_type == PT_TLS)
347 void *tlsblock;
348 size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
349 char *p;
351 bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
352 bootstrap_map.l_tls_align = phdr[cnt].p_align;
353 if (phdr[cnt].p_align == 0)
354 bootstrap_map.l_tls_firstbyte_offset = 0;
355 else
356 bootstrap_map.l_tls_firstbyte_offset = (phdr[cnt].p_vaddr
357 & (phdr[cnt].p_align - 1));
358 assert (bootstrap_map.l_tls_blocksize != 0);
359 bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
360 bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
361 + phdr[cnt].p_vaddr);
363 /* We can now allocate the initial TLS block. This can happen
364 on the stack. We'll get the final memory later when we
365 know all about the various objects loaded at startup
366 time. */
367 # if TLS_TCB_AT_TP
368 tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
369 TLS_INIT_TCB_ALIGN)
370 + TLS_INIT_TCB_SIZE
371 + max_align);
372 # elif TLS_DTV_AT_TP
373 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
374 bootstrap_map.l_tls_align)
375 + bootstrap_map.l_tls_blocksize
376 + max_align);
377 # else
378 /* In case a model with a different layout for the TCB and DTV
379 is defined add another #elif here and in the following #ifs. */
380 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
381 # endif
382 /* Align the TLS block. */
383 tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
384 & ~(max_align - 1));
386 /* Initialize the dtv. [0] is the length, [1] the generation
387 counter. */
388 initdtv[0].counter = 1;
389 initdtv[1].counter = 0;
391 /* Initialize the TLS block. */
392 # if TLS_TCB_AT_TP
393 initdtv[2].pointer = tlsblock;
394 # elif TLS_DTV_AT_TP
395 bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
396 bootstrap_map.l_tls_align);
397 initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
398 # else
399 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
400 # endif
401 p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
402 bootstrap_map.l_tls_initimage_size);
403 # ifdef HAVE_BUILTIN_MEMSET
404 __builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
405 - bootstrap_map.l_tls_initimage_size));
406 # else
408 size_t remaining = (bootstrap_map.l_tls_blocksize
409 - bootstrap_map.l_tls_initimage_size);
410 while (remaining-- > 0)
411 *p++ = '\0';
413 #endif
415 /* Install the pointer to the dtv. */
417 /* Initialize the thread pointer. */
418 # if TLS_TCB_AT_TP
419 bootstrap_map.l_tls_offset
420 = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
422 INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
423 initdtv);
425 const char *lossage = TLS_INIT_TP ((char *) tlsblock
426 + bootstrap_map.l_tls_offset, 0);
427 # elif TLS_DTV_AT_TP
428 INSTALL_DTV (tlsblock, initdtv);
429 const char *lossage = TLS_INIT_TP (tlsblock, 0);
430 # else
431 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
432 # endif
433 if (__builtin_expect (lossage != NULL, 0))
434 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
435 lossage);
437 /* So far this is module number one. */
438 bootstrap_map.l_tls_modid = 1;
440 /* There can only be one PT_TLS entry. */
441 break;
443 #endif /* USE___THREAD */
445 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
446 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
447 #endif
449 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
451 /* Relocate ourselves so we can do normal function calls and
452 data access using the global offset table. */
454 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
457 /* Please note that we don't allow profiling of this object and
458 therefore need not test whether we have to allocate the array
459 for the relocation results (as done in dl-reloc.c). */
461 /* Now life is sane; we can call functions and access global data.
462 Set up to use the operating system facilities, and find out from
463 the operating system's program loader where to find the program
464 header table in core. Put the rest of _dl_start into a separate
465 function, that way the compiler cannot put accesses to the GOT
466 before ELF_DYNAMIC_RELOCATE. */
468 #ifdef DONT_USE_BOOTSTRAP_MAP
469 ElfW(Addr) entry = _dl_start_final (arg);
470 #else
471 ElfW(Addr) entry = _dl_start_final (arg, &info);
472 #endif
474 #ifndef ELF_MACHINE_START_ADDRESS
475 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
476 #endif
478 return ELF_MACHINE_START_ADDRESS (GL(dl_loaded), entry);
484 /* Now life is peachy; we can do all normal operations.
485 On to the real work. */
487 /* Some helper functions. */
489 /* Arguments to relocate_doit. */
490 struct relocate_args
492 struct link_map *l;
493 int lazy;
496 struct map_args
498 /* Argument to map_doit. */
499 char *str;
500 /* Return value of map_doit. */
501 struct link_map *main_map;
504 /* Arguments to version_check_doit. */
505 struct version_check_args
507 int doexit;
508 int dotrace;
511 static void
512 relocate_doit (void *a)
514 struct relocate_args *args = (struct relocate_args *) a;
516 INTUSE(_dl_relocate_object) (args->l, args->l->l_scope, args->lazy, 0);
519 static void
520 map_doit (void *a)
522 struct map_args *args = (struct map_args *) a;
523 args->main_map = INTUSE(_dl_map_object) (NULL, args->str, 0, lt_library, 0, 0);
526 static void
527 version_check_doit (void *a)
529 struct version_check_args *args = (struct version_check_args *) a;
530 if (_dl_check_all_versions (GL(dl_loaded), 1, args->dotrace) && args->doexit)
531 /* We cannot start the application. Abort now. */
532 _exit (1);
536 static inline struct link_map *
537 find_needed (const char *name)
539 unsigned int n = GL(dl_loaded)->l_searchlist.r_nlist;
541 while (n-- > 0)
542 if (_dl_name_match_p (name, GL(dl_loaded)->l_searchlist.r_list[n]))
543 return GL(dl_loaded)->l_searchlist.r_list[n];
545 /* Should never happen. */
546 return NULL;
549 static int
550 match_version (const char *string, struct link_map *map)
552 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
553 ElfW(Verdef) *def;
555 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
556 if (map->l_info[VERDEFTAG] == NULL)
557 /* The file has no symbol versioning. */
558 return 0;
560 def = (ElfW(Verdef) *) ((char *) map->l_addr
561 + map->l_info[VERDEFTAG]->d_un.d_ptr);
562 while (1)
564 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
566 /* Compare the version strings. */
567 if (strcmp (string, strtab + aux->vda_name) == 0)
568 /* Bingo! */
569 return 1;
571 /* If no more definitions we failed to find what we want. */
572 if (def->vd_next == 0)
573 break;
575 /* Next definition. */
576 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
579 return 0;
582 #ifdef _LIBC_REENTRANT
583 /* _dl_error_catch_tsd points to this for the single-threaded case.
584 It's reset by the thread library for multithreaded programs. */
585 void ** __attribute__ ((const))
586 _dl_initial_error_catch_tsd (void)
588 static void *data;
589 return &data;
591 #endif
593 #if defined SHARED && defined _LIBC_REENTRANT \
594 && defined __rtld_lock_default_lock_recursive
595 static void rtld_lock_default_lock_recursive (void *lock)
597 __rtld_lock_default_lock_recursive (lock);
600 static void rtld_lock_default_unlock_recursive (void *lock)
602 __rtld_lock_default_unlock_recursive (lock);
604 #endif
607 static const char *library_path; /* The library search path. */
608 static const char *preloadlist; /* The list preloaded objects. */
609 static int version_info; /* Nonzero if information about
610 versions has to be printed. */
612 static void
613 dl_main (const ElfW(Phdr) *phdr,
614 ElfW(Word) phnum,
615 ElfW(Addr) *user_entry)
617 const ElfW(Phdr) *ph;
618 enum mode mode;
619 struct link_map **preloads;
620 unsigned int npreloads;
621 size_t file_size;
622 char *file;
623 bool has_interp = false;
624 unsigned int i;
625 bool prelinked = false;
626 bool rtld_is_main = false;
627 #ifndef HP_TIMING_NONAVAIL
628 hp_timing_t start;
629 hp_timing_t stop;
630 hp_timing_t diff;
631 #endif
632 #ifdef USE_TLS
633 void *tcbp;
634 #endif
636 #ifdef _LIBC_REENTRANT
637 /* Explicit initialization since the reloc would just be more work. */
638 GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
639 #endif
641 #ifdef USE_TLS
642 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
643 #endif
645 #if defined SHARED && defined _LIBC_REENTRANT \
646 && defined __rtld_lock_default_lock_recursive
647 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
648 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
649 #endif
651 /* The explicit initialization here is cheaper than processing the reloc
652 in the _rtld_local definition's initializer. */
653 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
655 /* Process the environment variable which control the behaviour. */
656 process_envvars (&mode);
658 /* Set up a flag which tells we are just starting. */
659 INTUSE(_dl_starting_up) = 1;
661 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
663 /* Ho ho. We are not the program interpreter! We are the program
664 itself! This means someone ran ld.so as a command. Well, that
665 might be convenient to do sometimes. We support it by
666 interpreting the args like this:
668 ld.so PROGRAM ARGS...
670 The first argument is the name of a file containing an ELF
671 executable we will load and run with the following arguments.
672 To simplify life here, PROGRAM is searched for using the
673 normal rules for shared objects, rather than $PATH or anything
674 like that. We just load it and use its entry point; we don't
675 pay attention to its PT_INTERP command (we are the interpreter
676 ourselves). This is an easy way to test a new ld.so before
677 installing it. */
678 rtld_is_main = true;
680 /* Note the place where the dynamic linker actually came from. */
681 GL(dl_rtld_map).l_name = rtld_progname;
683 while (_dl_argc > 1)
684 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
686 mode = list;
687 GL(dl_lazy) = -1; /* This means do no dependency analysis. */
689 ++_dl_skip_args;
690 --_dl_argc;
691 ++INTUSE(_dl_argv);
693 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
695 mode = verify;
697 ++_dl_skip_args;
698 --_dl_argc;
699 ++INTUSE(_dl_argv);
701 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
702 && _dl_argc > 2)
704 library_path = INTUSE(_dl_argv)[2];
706 _dl_skip_args += 2;
707 _dl_argc -= 2;
708 INTUSE(_dl_argv) += 2;
710 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
711 && _dl_argc > 2)
713 GL(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
715 _dl_skip_args += 2;
716 _dl_argc -= 2;
717 INTUSE(_dl_argv) += 2;
719 else
720 break;
722 /* If we have no further argument the program was called incorrectly.
723 Grant the user some education. */
724 if (_dl_argc < 2)
725 _dl_fatal_printf ("\
726 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
727 You have invoked `ld.so', the helper program for shared library executables.\n\
728 This program usually lives in the file `/lib/ld.so', and special directives\n\
729 in executable files using ELF shared libraries tell the system's program\n\
730 loader to load the helper program from this file. This helper program loads\n\
731 the shared libraries needed by the program executable, prepares the program\n\
732 to run, and runs it. You may invoke this helper program directly from the\n\
733 command line to load and run an ELF executable file; this is like executing\n\
734 that file itself, but always uses this helper program from the file you\n\
735 specified, instead of the helper program file specified in the executable\n\
736 file you run. This is mostly of use for maintainers to test new versions\n\
737 of this helper program; chances are you did not intend to run this program.\n\
739 --list list all dependencies and how they are resolved\n\
740 --verify verify that given object really is a dynamically linked\n\
741 object we can handle\n\
742 --library-path PATH use given PATH instead of content of the environment\n\
743 variable LD_LIBRARY_PATH\n\
744 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
745 in LIST\n");
747 ++_dl_skip_args;
748 --_dl_argc;
749 ++INTUSE(_dl_argv);
751 /* Initialize the data structures for the search paths for shared
752 objects. */
753 _dl_init_paths (library_path);
755 /* The initialization of _dl_stack_flags done below assumes the
756 executable's PT_GNU_STACK may have been honored by the kernel, and
757 so a PT_GNU_STACK with PF_X set means the stack started out with
758 execute permission. However, this is not really true if the
759 dynamic linker is the executable the kernel loaded. For this
760 case, we must reinitialize _dl_stack_flags to match the dynamic
761 linker itself. If the dynamic linker was built with a
762 PT_GNU_STACK, then the kernel may have loaded us with a
763 nonexecutable stack that we will have to make executable when we
764 load the program below unless it has a PT_GNU_STACK indicating
765 nonexecutable stack is ok. */
767 for (ph = phdr; ph < &phdr[phnum]; ++ph)
768 if (ph->p_type == PT_GNU_STACK)
770 GL(dl_stack_flags) = ph->p_flags;
771 break;
774 if (__builtin_expect (mode, normal) == verify)
776 const char *objname;
777 const char *err_str = NULL;
778 struct map_args args;
780 args.str = rtld_progname;
781 (void) INTUSE(_dl_catch_error) (&objname, &err_str, map_doit, &args);
782 if (__builtin_expect (err_str != NULL, 0))
783 /* We don't free the returned string, the programs stops
784 anyway. */
785 _exit (EXIT_FAILURE);
787 else
789 HP_TIMING_NOW (start);
790 INTUSE(_dl_map_object) (NULL, rtld_progname, 0, lt_library, 0, 0);
791 HP_TIMING_NOW (stop);
793 HP_TIMING_DIFF (load_time, start, stop);
796 phdr = GL(dl_loaded)->l_phdr;
797 phnum = GL(dl_loaded)->l_phnum;
798 /* We overwrite here a pointer to a malloc()ed string. But since
799 the malloc() implementation used at this point is the dummy
800 implementations which has no real free() function it does not
801 makes sense to free the old string first. */
802 GL(dl_loaded)->l_name = (char *) "";
803 *user_entry = GL(dl_loaded)->l_entry;
805 else
807 /* Create a link_map for the executable itself.
808 This will be what dlopen on "" returns. */
809 _dl_new_object ((char *) "", "", lt_executable, NULL);
810 if (GL(dl_loaded) == NULL)
811 _dl_fatal_printf ("cannot allocate memory for link map\n");
812 GL(dl_loaded)->l_phdr = phdr;
813 GL(dl_loaded)->l_phnum = phnum;
814 GL(dl_loaded)->l_entry = *user_entry;
816 /* At this point we are in a bit of trouble. We would have to
817 fill in the values for l_dev and l_ino. But in general we
818 do not know where the file is. We also do not handle AT_EXECFD
819 even if it would be passed up.
821 We leave the values here defined to 0. This is normally no
822 problem as the program code itself is normally no shared
823 object and therefore cannot be loaded dynamically. Nothing
824 prevent the use of dynamic binaries and in these situations
825 we might get problems. We might not be able to find out
826 whether the object is already loaded. But since there is no
827 easy way out and because the dynamic binary must also not
828 have an SONAME we ignore this program for now. If it becomes
829 a problem we can force people using SONAMEs. */
831 /* We delay initializing the path structure until we got the dynamic
832 information for the program. */
835 GL(dl_loaded)->l_map_end = 0;
836 /* Perhaps the executable has no PT_LOAD header entries at all. */
837 GL(dl_loaded)->l_map_start = ~0;
838 /* We opened the file, account for it. */
839 ++GL(dl_loaded)->l_opencount;
841 /* Scan the program header table for the dynamic section. */
842 for (ph = phdr; ph < &phdr[phnum]; ++ph)
843 switch (ph->p_type)
845 case PT_PHDR:
846 /* Find out the load address. */
847 GL(dl_loaded)->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
848 break;
849 case PT_DYNAMIC:
850 /* This tells us where to find the dynamic section,
851 which tells us everything we need to do. */
852 GL(dl_loaded)->l_ld = (void *) GL(dl_loaded)->l_addr + ph->p_vaddr;
853 break;
854 case PT_INTERP:
855 /* This "interpreter segment" was used by the program loader to
856 find the program interpreter, which is this program itself, the
857 dynamic linker. We note what name finds us, so that a future
858 dlopen call or DT_NEEDED entry, for something that wants to link
859 against the dynamic linker as a shared library, will know that
860 the shared object is already loaded. */
861 _dl_rtld_libname.name = ((const char *) GL(dl_loaded)->l_addr
862 + ph->p_vaddr);
863 /* _dl_rtld_libname.next = NULL; Already zero. */
864 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
866 /* Ordinarilly, we would get additional names for the loader from
867 our DT_SONAME. This can't happen if we were actually linked as
868 a static executable (detect this case when we have no DYNAMIC).
869 If so, assume the filename component of the interpreter path to
870 be our SONAME, and add it to our name list. */
871 if (GL(dl_rtld_map).l_ld == NULL)
873 const char *p = NULL;
874 const char *cp = _dl_rtld_libname.name;
876 /* Find the filename part of the path. */
877 while (*cp != '\0')
878 if (*cp++ == '/')
879 p = cp;
881 if (p != NULL)
883 _dl_rtld_libname2.name = p;
884 /* _dl_rtld_libname2.next = NULL; Already zero. */
885 _dl_rtld_libname.next = &_dl_rtld_libname2;
889 has_interp = true;
890 break;
891 case PT_LOAD:
893 ElfW(Addr) mapstart;
894 ElfW(Addr) allocend;
896 /* Remember where the main program starts in memory. */
897 mapstart = (GL(dl_loaded)->l_addr
898 + (ph->p_vaddr & ~(ph->p_align - 1)));
899 if (GL(dl_loaded)->l_map_start > mapstart)
900 GL(dl_loaded)->l_map_start = mapstart;
902 /* Also where it ends. */
903 allocend = GL(dl_loaded)->l_addr + ph->p_vaddr + ph->p_memsz;
904 if (GL(dl_loaded)->l_map_end < allocend)
905 GL(dl_loaded)->l_map_end = allocend;
907 break;
908 #ifdef USE_TLS
909 case PT_TLS:
910 if (ph->p_memsz > 0)
912 /* Note that in the case the dynamic linker we duplicate work
913 here since we read the PT_TLS entry already in
914 _dl_start_final. But the result is repeatable so do not
915 check for this special but unimportant case. */
916 GL(dl_loaded)->l_tls_blocksize = ph->p_memsz;
917 GL(dl_loaded)->l_tls_align = ph->p_align;
918 if (ph->p_align == 0)
919 GL(dl_loaded)->l_tls_firstbyte_offset = 0;
920 else
921 GL(dl_loaded)->l_tls_firstbyte_offset = (ph->p_vaddr
922 & (ph->p_align - 1));
923 GL(dl_loaded)->l_tls_initimage_size = ph->p_filesz;
924 GL(dl_loaded)->l_tls_initimage = (void *) ph->p_vaddr;
926 /* This image gets the ID one. */
927 GL(dl_tls_max_dtv_idx) = GL(dl_loaded)->l_tls_modid = 1;
929 break;
930 #endif
931 case PT_GNU_STACK:
932 GL(dl_stack_flags) = ph->p_flags;
933 break;
935 #ifdef USE_TLS
936 /* Adjust the address of the TLS initialization image in case
937 the executable is actually an ET_DYN object. */
938 if (GL(dl_loaded)->l_tls_initimage != NULL)
939 GL(dl_loaded)->l_tls_initimage
940 = (char *) GL(dl_loaded)->l_tls_initimage + GL(dl_loaded)->l_addr;
941 #endif
942 if (! GL(dl_loaded)->l_map_end)
943 GL(dl_loaded)->l_map_end = ~0;
944 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
946 /* We were invoked directly, so the program might not have a
947 PT_INTERP. */
948 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
949 /* _dl_rtld_libname.next = NULL; Already zero. */
950 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
952 else
953 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
955 if (! rtld_is_main)
957 /* Extract the contents of the dynamic section for easy access. */
958 elf_get_dynamic_info (GL(dl_loaded), NULL);
959 if (GL(dl_loaded)->l_info[DT_HASH])
960 /* Set up our cache of pointers into the hash table. */
961 _dl_setup_hash (GL(dl_loaded));
964 if (__builtin_expect (mode, normal) == verify)
966 /* We were called just to verify that this is a dynamic
967 executable using us as the program interpreter. Exit with an
968 error if we were not able to load the binary or no interpreter
969 is specified (i.e., this is no dynamically linked binary. */
970 if (GL(dl_loaded)->l_ld == NULL)
971 _exit (1);
973 /* We allow here some platform specific code. */
974 #ifdef DISTINGUISH_LIB_VERSIONS
975 DISTINGUISH_LIB_VERSIONS;
976 #endif
977 _exit (has_interp ? 0 : 2);
980 if (! rtld_is_main)
981 /* Initialize the data structures for the search paths for shared
982 objects. */
983 _dl_init_paths (library_path);
985 /* Put the link_map for ourselves on the chain so it can be found by
986 name. Note that at this point the global chain of link maps contains
987 exactly one element, which is pointed to by dl_loaded. */
988 if (! GL(dl_rtld_map).l_name)
989 /* If not invoked directly, the dynamic linker shared object file was
990 found by the PT_INTERP name. */
991 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
992 GL(dl_rtld_map).l_type = lt_library;
993 GL(dl_loaded)->l_next = &GL(dl_rtld_map);
994 GL(dl_rtld_map).l_prev = GL(dl_loaded);
995 ++GL(dl_nloaded);
997 /* Set up the program header information for the dynamic linker
998 itself. It is needed in the dl_iterate_phdr() callbacks. */
999 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1000 GL(dl_rtld_map).l_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1001 + rtld_ehdr->e_phoff);
1002 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1004 /* We have two ways to specify objects to preload: via environment
1005 variable and via the file /etc/ld.so.preload. The latter can also
1006 be used when security is enabled. */
1007 preloads = NULL;
1008 npreloads = 0;
1010 if (__builtin_expect (preloadlist != NULL, 0))
1012 /* The LD_PRELOAD environment variable gives list of libraries
1013 separated by white space or colons that are loaded before the
1014 executable's dependencies and prepended to the global scope
1015 list. If the binary is running setuid all elements
1016 containing a '/' are ignored since it is insecure. */
1017 char *list = strdupa (preloadlist);
1018 char *p;
1020 HP_TIMING_NOW (start);
1022 /* Prevent optimizing strsep. Speed is not important here. */
1023 while ((p = (strsep) (&list, " :")) != NULL)
1024 if (p[0] != '\0'
1025 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1026 || strchr (p, '/') == NULL))
1028 struct link_map *new_map = INTUSE(_dl_map_object) (GL(dl_loaded),
1029 p, 1,
1030 lt_library,
1031 0, 0);
1032 if (++new_map->l_opencount == 1)
1033 /* It is no duplicate. */
1034 ++npreloads;
1037 HP_TIMING_NOW (stop);
1038 HP_TIMING_DIFF (diff, start, stop);
1039 HP_TIMING_ACCUM_NT (load_time, diff);
1042 /* Read the contents of the file. */
1043 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
1044 PROT_READ | PROT_WRITE);
1045 if (__builtin_expect (file != MAP_FAILED, 0))
1047 /* Parse the file. It contains names of libraries to be loaded,
1048 separated by white spaces or `:'. It may also contain
1049 comments introduced by `#'. */
1050 char *problem;
1051 char *runp;
1052 size_t rest;
1054 /* Eliminate comments. */
1055 runp = file;
1056 rest = file_size;
1057 while (rest > 0)
1059 char *comment = memchr (runp, '#', rest);
1060 if (comment == NULL)
1061 break;
1063 rest -= comment - runp;
1065 *comment = ' ';
1066 while (--rest > 0 && *++comment != '\n');
1069 /* We have one problematic case: if we have a name at the end of
1070 the file without a trailing terminating characters, we cannot
1071 place the \0. Handle the case separately. */
1072 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1073 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1075 problem = &file[file_size];
1076 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
1077 && problem[-1] != '\n' && problem[-1] != ':')
1078 --problem;
1080 if (problem > file)
1081 problem[-1] = '\0';
1083 else
1085 problem = NULL;
1086 file[file_size - 1] = '\0';
1089 HP_TIMING_NOW (start);
1091 if (file != problem)
1093 char *p;
1094 runp = file;
1095 while ((p = strsep (&runp, ": \t\n")) != NULL)
1096 if (p[0] != '\0')
1098 struct link_map *new_map = INTUSE(_dl_map_object) (GL(dl_loaded),
1099 p, 1,
1100 lt_library,
1101 0, 0);
1102 if (++new_map->l_opencount == 1)
1103 /* It is no duplicate. */
1104 ++npreloads;
1108 if (problem != NULL)
1110 char *p = strndupa (problem, file_size - (problem - file));
1111 struct link_map *new_map = INTUSE(_dl_map_object) (GL(dl_loaded), p,
1112 1, lt_library,
1113 0, 0);
1114 if (++new_map->l_opencount == 1)
1115 /* It is no duplicate. */
1116 ++npreloads;
1119 HP_TIMING_NOW (stop);
1120 HP_TIMING_DIFF (diff, start, stop);
1121 HP_TIMING_ACCUM_NT (load_time, diff);
1123 /* We don't need the file anymore. */
1124 __munmap (file, file_size);
1127 if (__builtin_expect (npreloads, 0) != 0)
1129 /* Set up PRELOADS with a vector of the preloaded libraries. */
1130 struct link_map *l;
1131 preloads = __alloca (npreloads * sizeof preloads[0]);
1132 l = GL(dl_rtld_map).l_next; /* End of the chain before preloads. */
1133 i = 0;
1136 preloads[i++] = l;
1137 l = l->l_next;
1138 } while (l);
1139 assert (i == npreloads);
1142 #ifdef NEED_DL_SYSINFO
1143 if (GL(dl_sysinfo_dso) != NULL)
1145 /* We have a prelinked DSO preloaded by the system. */
1146 GL(dl_sysinfo) = GL(dl_sysinfo_dso)->e_entry;
1148 /* Do an abridged version of the work _dl_map_object_from_fd would do
1149 to map in the object. It's already mapped and prelinked (and
1150 better be, since it's read-only and so we couldn't relocate it).
1151 We just want our data structures to describe it as if we had just
1152 mapped and relocated it normally. */
1153 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL);
1154 if (__builtin_expect (l != NULL, 1))
1156 static ElfW(Dyn) dyn_temp [DL_RO_DYN_TEMP_CNT];
1158 l->l_phdr = ((const void *) GL(dl_sysinfo_dso)
1159 + GL(dl_sysinfo_dso)->e_phoff);
1160 l->l_phnum = GL(dl_sysinfo_dso)->e_phnum;
1161 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1163 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1164 if (ph->p_type == PT_DYNAMIC)
1166 l->l_ld = (void *) ph->p_vaddr;
1167 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1168 break;
1170 if (ph->p_type == PT_LOAD)
1171 assert ((void *) ph->p_vaddr == GL(dl_sysinfo_dso));
1173 elf_get_dynamic_info (l, dyn_temp);
1174 _dl_setup_hash (l);
1175 l->l_relocated = 1;
1177 /* Now that we have the info handy, use the DSO image's soname
1178 so this object can be looked up by name. */
1179 if (l->l_info[DT_SONAME] != NULL)
1180 l->l_libname->name = ((char *) D_PTR (l, l_info[DT_STRTAB])
1181 + l->l_info[DT_SONAME]->d_un.d_val);
1184 #endif
1186 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1187 specified some libraries to load, these are inserted before the actual
1188 dependencies in the executable's searchlist for symbol resolution. */
1189 HP_TIMING_NOW (start);
1190 INTUSE(_dl_map_object_deps) (GL(dl_loaded), preloads, npreloads,
1191 mode == trace, 0);
1192 HP_TIMING_NOW (stop);
1193 HP_TIMING_DIFF (diff, start, stop);
1194 HP_TIMING_ACCUM_NT (load_time, diff);
1196 /* Mark all objects as being in the global scope and set the open
1197 counter. */
1198 for (i = GL(dl_loaded)->l_searchlist.r_nlist; i > 0; )
1200 --i;
1201 GL(dl_loaded)->l_searchlist.r_list[i]->l_global = 1;
1202 ++GL(dl_loaded)->l_searchlist.r_list[i]->l_opencount;
1205 #ifndef MAP_ANON
1206 /* We are done mapping things, so close the zero-fill descriptor. */
1207 __close (_dl_zerofd);
1208 _dl_zerofd = -1;
1209 #endif
1211 /* Remove _dl_rtld_map from the chain. */
1212 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1213 if (GL(dl_rtld_map).l_next)
1214 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1216 if (__builtin_expect (GL(dl_rtld_map).l_opencount > 1, 1))
1218 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1219 put it back in the list of visible objects. We insert it into the
1220 chain in symbol search order because gdb uses the chain's order as
1221 its symbol search order. */
1222 i = 1;
1223 while (GL(dl_loaded)->l_searchlist.r_list[i] != &GL(dl_rtld_map))
1224 ++i;
1225 GL(dl_rtld_map).l_prev = GL(dl_loaded)->l_searchlist.r_list[i - 1];
1226 if (__builtin_expect (mode, normal) == normal)
1227 GL(dl_rtld_map).l_next = (i + 1 < GL(dl_loaded)->l_searchlist.r_nlist
1228 ? GL(dl_loaded)->l_searchlist.r_list[i + 1]
1229 : NULL);
1230 else
1231 /* In trace mode there might be an invisible object (which we
1232 could not find) after the previous one in the search list.
1233 In this case it doesn't matter much where we put the
1234 interpreter object, so we just initialize the list pointer so
1235 that the assertion below holds. */
1236 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1238 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1239 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1240 if (GL(dl_rtld_map).l_next != NULL)
1242 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1243 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1247 /* Now let us see whether all libraries are available in the
1248 versions we need. */
1250 struct version_check_args args;
1251 args.doexit = mode == normal;
1252 args.dotrace = mode == trace;
1253 _dl_receive_error (print_missing_version, version_check_doit, &args);
1256 #ifdef USE_TLS
1257 /* Now it is time to determine the layout of the static TLS block
1258 and allocate it for the initial thread. Note that we always
1259 allocate the static block, we never defer it even if no
1260 DF_STATIC_TLS bit is set. The reason is that we know glibc will
1261 use the static model. First add the dynamic linker to the list
1262 if it also uses TLS. */
1263 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1264 /* Assign a module ID. */
1265 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1267 # ifndef TLS_INIT_TP_EXPENSIVE
1268 # define TLS_INIT_TP_EXPENSIVE 0
1269 # endif
1271 /* We do not initialize any of the TLS functionality unless any of the
1272 initial modules uses TLS. This makes dynamic loading of modules with
1273 TLS impossible, but to support it requires either eagerly doing setup
1274 now or lazily doing it later. Doing it now makes us incompatible with
1275 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1276 used. Trying to do it lazily is too hairy to try when there could be
1277 multiple threads (from a non-TLS-using libpthread). */
1278 if (GL(dl_tls_max_dtv_idx) > 0 || !TLS_INIT_TP_EXPENSIVE)
1280 struct link_map *l;
1281 size_t nelem;
1282 struct dtv_slotinfo *slotinfo;
1284 /* Number of elements in the static TLS block. */
1285 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
1287 /* Allocate the array which contains the information about the
1288 dtv slots. We allocate a few entries more than needed to
1289 avoid the need for reallocation. */
1290 nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
1292 /* Allocate. */
1293 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
1294 malloc (sizeof (struct dtv_slotinfo_list)
1295 + nelem * sizeof (struct dtv_slotinfo));
1296 /* No need to check the return value. If memory allocation failed
1297 the program would have been terminated. */
1299 slotinfo = memset (GL(dl_tls_dtv_slotinfo_list)->slotinfo, '\0',
1300 nelem * sizeof (struct dtv_slotinfo));
1301 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
1302 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
1304 /* Fill in the information from the loaded modules. */
1305 for (l = GL(dl_loaded), i = 0; l != NULL; l = l->l_next)
1306 if (l->l_tls_blocksize != 0)
1307 /* This is a module with TLS data. Store the map reference.
1308 The generation counter is zero. */
1309 slotinfo[++i].map = l;
1310 assert (i == GL(dl_tls_max_dtv_idx));
1312 /* Compute the TLS offsets for the various blocks. */
1313 _dl_determine_tlsoffset ();
1315 /* Construct the static TLS block and the dtv for the initial
1316 thread. For some platforms this will include allocating memory
1317 for the thread descriptor. The memory for the TLS block will
1318 never be freed. It should be allocated accordingly. The dtv
1319 array can be changed if dynamic loading requires it. */
1320 tcbp = _dl_allocate_tls_storage ();
1321 if (tcbp == NULL)
1322 _dl_fatal_printf ("\
1323 cannot allocate TLS data structures for initial thread");
1325 /* Store for detection of the special case by __tls_get_addr
1326 so it knows not to pass this dtv to the normal realloc. */
1327 GL(dl_initial_dtv) = GET_DTV (tcbp);
1329 #endif
1331 if (__builtin_expect (mode, normal) != normal)
1333 /* We were run just to list the shared libraries. It is
1334 important that we do this before real relocation, because the
1335 functions we call below for output may no longer work properly
1336 after relocation. */
1337 struct link_map *l;
1339 if (GL(dl_debug_mask) & DL_DEBUG_PRELINK)
1341 struct r_scope_elem *scope = &GL(dl_loaded)->l_searchlist;
1343 for (i = 0; i < scope->r_nlist; i++)
1345 l = scope->r_list [i];
1346 if (l->l_faked)
1348 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1349 continue;
1351 if (_dl_name_match_p (GL(dl_trace_prelink), l))
1352 GL(dl_trace_prelink_map) = l;
1353 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1354 l->l_libname->name[0] ? l->l_libname->name
1355 : rtld_progname ?: "<main program>",
1356 l->l_name[0] ? l->l_name
1357 : rtld_progname ?: "<main program>",
1358 (int) sizeof l->l_map_start * 2,
1359 (size_t) l->l_map_start,
1360 (int) sizeof l->l_addr * 2,
1361 (size_t) l->l_addr);
1362 #ifdef USE_TLS
1363 if (l->l_tls_modid)
1364 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1365 (int) sizeof l->l_tls_offset * 2,
1366 (size_t) l->l_tls_offset);
1367 else
1368 #endif
1369 _dl_printf ("\n");
1372 else if (! GL(dl_loaded)->l_info[DT_NEEDED])
1373 _dl_printf ("\tstatically linked\n");
1374 else
1376 for (l = GL(dl_loaded)->l_next; l; l = l->l_next)
1377 if (l->l_faked)
1378 /* The library was not found. */
1379 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1380 else
1381 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1382 l->l_name, (int) sizeof l->l_map_start * 2,
1383 (size_t) l->l_map_start);
1386 if (__builtin_expect (mode, trace) != trace)
1387 for (i = 1; i < (unsigned int) _dl_argc; ++i)
1389 const ElfW(Sym) *ref = NULL;
1390 ElfW(Addr) loadbase;
1391 lookup_t result;
1393 result = INTUSE(_dl_lookup_symbol) (INTUSE(_dl_argv)[i],
1394 GL(dl_loaded),
1395 &ref, GL(dl_loaded)->l_scope,
1396 ELF_RTYPE_CLASS_PLT, 1);
1398 loadbase = LOOKUP_VALUE_ADDRESS (result);
1400 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
1401 INTUSE(_dl_argv)[i],
1402 (int) sizeof ref->st_value * 2,
1403 (size_t) ref->st_value,
1404 (int) sizeof loadbase * 2, (size_t) loadbase);
1406 else
1408 /* If LD_WARN is set warn about undefined symbols. */
1409 if (GL(dl_lazy) >= 0 && GL(dl_verbose))
1411 /* We have to do symbol dependency testing. */
1412 struct relocate_args args;
1413 struct link_map *l;
1415 args.lazy = GL(dl_lazy);
1417 l = GL(dl_loaded);
1418 while (l->l_next)
1419 l = l->l_next;
1422 if (l != &GL(dl_rtld_map) && ! l->l_faked)
1424 args.l = l;
1425 _dl_receive_error (print_unresolved, relocate_doit,
1426 &args);
1428 l = l->l_prev;
1429 } while (l);
1431 if ((GL(dl_debug_mask) & DL_DEBUG_PRELINK)
1432 && GL(dl_rtld_map).l_opencount > 1)
1433 INTUSE(_dl_relocate_object) (&GL(dl_rtld_map),
1434 GL(dl_loaded)->l_scope, 0, 0);
1437 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
1438 if (version_info)
1440 /* Print more information. This means here, print information
1441 about the versions needed. */
1442 int first = 1;
1443 struct link_map *map = GL(dl_loaded);
1445 for (map = GL(dl_loaded); map != NULL; map = map->l_next)
1447 const char *strtab;
1448 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
1449 ElfW(Verneed) *ent;
1451 if (dyn == NULL)
1452 continue;
1454 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
1455 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
1457 if (first)
1459 _dl_printf ("\n\tVersion information:\n");
1460 first = 0;
1463 _dl_printf ("\t%s:\n",
1464 map->l_name[0] ? map->l_name : rtld_progname);
1466 while (1)
1468 ElfW(Vernaux) *aux;
1469 struct link_map *needed;
1471 needed = find_needed (strtab + ent->vn_file);
1472 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
1474 while (1)
1476 const char *fname = NULL;
1478 if (needed != NULL
1479 && match_version (strtab + aux->vna_name,
1480 needed))
1481 fname = needed->l_name;
1483 _dl_printf ("\t\t%s (%s) %s=> %s\n",
1484 strtab + ent->vn_file,
1485 strtab + aux->vna_name,
1486 aux->vna_flags & VER_FLG_WEAK
1487 ? "[WEAK] " : "",
1488 fname ?: "not found");
1490 if (aux->vna_next == 0)
1491 /* No more symbols. */
1492 break;
1494 /* Next symbol. */
1495 aux = (ElfW(Vernaux) *) ((char *) aux
1496 + aux->vna_next);
1499 if (ent->vn_next == 0)
1500 /* No more dependencies. */
1501 break;
1503 /* Next dependency. */
1504 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
1510 _exit (0);
1513 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]
1514 && ! __builtin_expect (GL(dl_profile) != NULL, 0))
1516 ElfW(Lib) *liblist, *liblistend;
1517 struct link_map **r_list, **r_listend, *l;
1518 const char *strtab = (const void *) D_PTR (GL(dl_loaded),
1519 l_info[DT_STRTAB]);
1521 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
1522 liblist = (ElfW(Lib) *)
1523 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
1524 liblistend = (ElfW(Lib) *)
1525 ((char *) liblist
1526 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
1527 r_list = GL(dl_loaded)->l_searchlist.r_list;
1528 r_listend = r_list + GL(dl_loaded)->l_searchlist.r_nlist;
1530 for (; r_list < r_listend && liblist < liblistend; r_list++)
1532 l = *r_list;
1534 if (l == GL(dl_loaded))
1535 continue;
1537 /* If the library is not mapped where it should, fail. */
1538 if (l->l_addr)
1539 break;
1541 /* Next, check if checksum matches. */
1542 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
1543 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
1544 != liblist->l_checksum)
1545 break;
1547 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
1548 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
1549 != liblist->l_time_stamp)
1550 break;
1552 if (! _dl_name_match_p (strtab + liblist->l_name, l))
1553 break;
1555 ++liblist;
1559 if (r_list == r_listend && liblist == liblistend)
1560 prelinked = true;
1562 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1563 _dl_printf ("\nprelink checking: %s\n", prelinked ? "ok" : "failed");
1566 if (prelinked)
1568 struct link_map *l;
1570 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
1572 ElfW(Rela) *conflict, *conflictend;
1573 #ifndef HP_TIMING_NONAVAIL
1574 hp_timing_t start;
1575 hp_timing_t stop;
1576 #endif
1578 HP_TIMING_NOW (start);
1579 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
1580 conflict = (ElfW(Rela) *)
1581 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
1582 conflictend = (ElfW(Rela) *)
1583 ((char *) conflict
1584 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
1585 _dl_resolve_conflicts (GL(dl_loaded), conflict, conflictend);
1586 HP_TIMING_NOW (stop);
1587 HP_TIMING_DIFF (relocate_time, start, stop);
1591 /* Mark all the objects so we know they have been already relocated. */
1592 for (l = GL(dl_loaded); l != NULL; l = l->l_next)
1593 l->l_relocated = 1;
1595 _dl_sysdep_start_cleanup ();
1597 else
1599 /* Now we have all the objects loaded. Relocate them all except for
1600 the dynamic linker itself. We do this in reverse order so that copy
1601 relocs of earlier objects overwrite the data written by later
1602 objects. We do not re-relocate the dynamic linker itself in this
1603 loop because that could result in the GOT entries for functions we
1604 call being changed, and that would break us. It is safe to relocate
1605 the dynamic linker out of order because it has no copy relocs (we
1606 know that because it is self-contained). */
1608 struct link_map *l;
1609 int consider_profiling = GL(dl_profile) != NULL;
1610 #ifndef HP_TIMING_NONAVAIL
1611 hp_timing_t start;
1612 hp_timing_t stop;
1613 hp_timing_t add;
1614 #endif
1616 /* If we are profiling we also must do lazy reloaction. */
1617 GL(dl_lazy) |= consider_profiling;
1619 l = GL(dl_loaded);
1620 while (l->l_next)
1621 l = l->l_next;
1623 HP_TIMING_NOW (start);
1626 /* While we are at it, help the memory handling a bit. We have to
1627 mark some data structures as allocated with the fake malloc()
1628 implementation in ld.so. */
1629 struct libname_list *lnp = l->l_libname->next;
1631 while (__builtin_expect (lnp != NULL, 0))
1633 lnp->dont_free = 1;
1634 lnp = lnp->next;
1637 if (l != &GL(dl_rtld_map))
1638 INTUSE(_dl_relocate_object) (l, l->l_scope, GL(dl_lazy),
1639 consider_profiling);
1641 l = l->l_prev;
1643 while (l);
1644 HP_TIMING_NOW (stop);
1646 HP_TIMING_DIFF (relocate_time, start, stop);
1648 /* Do any necessary cleanups for the startup OS interface code.
1649 We do these now so that no calls are made after rtld re-relocation
1650 which might be resolved to different functions than we expect.
1651 We cannot do this before relocating the other objects because
1652 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
1653 _dl_sysdep_start_cleanup ();
1655 /* Now enable profiling if needed. Like the previous call,
1656 this has to go here because the calls it makes should use the
1657 rtld versions of the functions (particularly calloc()), but it
1658 needs to have _dl_profile_map set up by the relocator. */
1659 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
1660 /* We must prepare the profiling. */
1661 INTUSE(_dl_start_profile) (GL(dl_profile_map), GL(dl_profile_output));
1663 if (GL(dl_rtld_map).l_opencount > 1)
1665 /* There was an explicit ref to the dynamic linker as a shared lib.
1666 Re-relocate ourselves with user-controlled symbol definitions. */
1667 HP_TIMING_NOW (start);
1668 INTUSE(_dl_relocate_object) (&GL(dl_rtld_map), GL(dl_loaded)->l_scope,
1669 0, 0);
1670 HP_TIMING_NOW (stop);
1671 HP_TIMING_DIFF (add, start, stop);
1672 HP_TIMING_ACCUM_NT (relocate_time, add);
1676 /* Now set up the variable which helps the assembler startup code. */
1677 GL(dl_main_searchlist) = &GL(dl_loaded)->l_searchlist;
1678 GL(dl_global_scope)[0] = &GL(dl_loaded)->l_searchlist;
1680 /* Save the information about the original global scope list since
1681 we need it in the memory handling later. */
1682 GL(dl_initial_searchlist) = *GL(dl_main_searchlist);
1684 #ifndef NONTLS_INIT_TP
1685 # define NONTLS_INIT_TP do { } while (0)
1686 #endif
1688 #ifdef USE_TLS
1689 if (GL(dl_tls_max_dtv_idx) > 0 || USE___THREAD || !TLS_INIT_TP_EXPENSIVE)
1691 /* Now that we have completed relocation, the initializer data
1692 for the TLS blocks has its final values and we can copy them
1693 into the main thread's TLS area, which we allocated above. */
1694 _dl_allocate_tls_init (tcbp);
1696 /* And finally install it for the main thread. If ld.so itself uses
1697 TLS we know the thread pointer was initialized earlier. */
1698 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
1699 if (__builtin_expect (lossage != NULL, 0))
1700 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
1702 else
1703 #endif
1704 NONTLS_INIT_TP;
1707 /* Initialize _r_debug. */
1708 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr);
1709 struct link_map *l;
1711 l = GL(dl_loaded);
1713 #ifdef ELF_MACHINE_DEBUG_SETUP
1715 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1717 ELF_MACHINE_DEBUG_SETUP (l, r);
1718 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1720 #else
1722 if (l->l_info[DT_DEBUG] != NULL)
1723 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1724 with the run-time address of the r_debug structure */
1725 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1727 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1728 case you run gdb on the dynamic linker directly. */
1729 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1730 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1732 #endif
1734 /* Notify the debugger that all objects are now mapped in. */
1735 r->r_state = RT_ADD;
1736 INTUSE(_dl_debug_state) ();
1739 #ifndef MAP_COPY
1740 /* We must munmap() the cache file. */
1741 INTUSE(_dl_unload_cache) ();
1742 #endif
1744 /* Once we return, _dl_sysdep_start will invoke
1745 the DT_INIT functions and then *USER_ENTRY. */
1748 /* This is a little helper function for resolving symbols while
1749 tracing the binary. */
1750 static void
1751 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
1752 const char *errstring)
1754 if (objname[0] == '\0')
1755 objname = rtld_progname ?: "<main program>";
1756 _dl_error_printf ("%s (%s)\n", errstring, objname);
1759 /* This is a little helper function for resolving symbols while
1760 tracing the binary. */
1761 static void
1762 print_missing_version (int errcode __attribute__ ((unused)),
1763 const char *objname, const char *errstring)
1765 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
1766 objname, errstring);
1769 /* Nonzero if any of the debugging options is enabled. */
1770 static int any_debug;
1772 /* Process the string given as the parameter which explains which debugging
1773 options are enabled. */
1774 static void
1775 process_dl_debug (const char *dl_debug)
1777 /* When adding new entries make sure that the maximal length of a name
1778 is correctly handled in the LD_DEBUG_HELP code below. */
1779 static const struct
1781 unsigned char len;
1782 const char name[10];
1783 const char helptext[41];
1784 unsigned short int mask;
1785 } debopts[] =
1787 #define LEN_AND_STR(str) sizeof (str) - 1, str
1788 { LEN_AND_STR ("libs"), "display library search paths",
1789 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
1790 { LEN_AND_STR ("reloc"), "display relocation processing",
1791 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
1792 { LEN_AND_STR ("files"), "display progress for input file",
1793 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
1794 { LEN_AND_STR ("symbols"), "display symbol table processing",
1795 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
1796 { LEN_AND_STR ("bindings"), "display information about symbol binding",
1797 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
1798 { LEN_AND_STR ("versions"), "display version dependencies",
1799 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1800 { LEN_AND_STR ("all"), "all previous options combined",
1801 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
1802 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1803 { LEN_AND_STR ("statistics"), "display relocation statistics",
1804 DL_DEBUG_STATISTICS },
1805 { LEN_AND_STR ("help"), "display this help message and exit",
1806 DL_DEBUG_HELP },
1808 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
1810 /* Skip separating white spaces and commas. */
1811 while (*dl_debug != '\0')
1813 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
1815 size_t cnt;
1816 size_t len = 1;
1818 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
1819 && dl_debug[len] != ',' && dl_debug[len] != ':')
1820 ++len;
1822 for (cnt = 0; cnt < ndebopts; ++cnt)
1823 if (debopts[cnt].len == len
1824 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
1826 GL(dl_debug_mask) |= debopts[cnt].mask;
1827 any_debug = 1;
1828 break;
1831 if (cnt == ndebopts)
1833 /* Display a warning and skip everything until next
1834 separator. */
1835 char *copy = strndupa (dl_debug, len);
1836 _dl_error_printf ("\
1837 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
1840 dl_debug += len;
1841 continue;
1844 ++dl_debug;
1847 if (GL(dl_debug_mask) & DL_DEBUG_HELP)
1849 size_t cnt;
1851 _dl_printf ("\
1852 Valid options for the LD_DEBUG environment variable are:\n\n");
1854 for (cnt = 0; cnt < ndebopts; ++cnt)
1855 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
1856 " " + debopts[cnt].len - 3,
1857 debopts[cnt].helptext);
1859 _dl_printf ("\n\
1860 To direct the debugging output into a file instead of standard output\n\
1861 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
1862 _exit (0);
1866 /* Process all environments variables the dynamic linker must recognize.
1867 Since all of them start with `LD_' we are a bit smarter while finding
1868 all the entries. */
1869 extern char **_environ attribute_hidden;
1872 static void
1873 process_envvars (enum mode *modep)
1875 char **runp = _environ;
1876 char *envline;
1877 enum mode mode = normal;
1878 char *debug_output = NULL;
1880 /* This is the default place for profiling data file. */
1881 GL(dl_profile_output)
1882 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
1884 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
1886 size_t len = 0;
1888 while (envline[len] != '\0' && envline[len] != '=')
1889 ++len;
1891 if (envline[len] != '=')
1892 /* This is a "LD_" variable at the end of the string without
1893 a '=' character. Ignore it since otherwise we will access
1894 invalid memory below. */
1895 continue;
1897 switch (len)
1899 case 4:
1900 /* Warning level, verbose or not. */
1901 if (memcmp (envline, "WARN", 4) == 0)
1902 GL(dl_verbose) = envline[5] != '\0';
1903 break;
1905 case 5:
1906 /* Debugging of the dynamic linker? */
1907 if (memcmp (envline, "DEBUG", 5) == 0)
1908 process_dl_debug (&envline[6]);
1909 break;
1911 case 7:
1912 /* Print information about versions. */
1913 if (memcmp (envline, "VERBOSE", 7) == 0)
1915 version_info = envline[8] != '\0';
1916 break;
1919 /* List of objects to be preloaded. */
1920 if (memcmp (envline, "PRELOAD", 7) == 0)
1922 preloadlist = &envline[8];
1923 break;
1926 /* Which shared object shall be profiled. */
1927 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
1928 GL(dl_profile) = &envline[8];
1929 break;
1931 case 8:
1932 /* Do we bind early? */
1933 if (memcmp (envline, "BIND_NOW", 8) == 0)
1935 GL(dl_lazy) = envline[9] == '\0';
1936 break;
1938 if (memcmp (envline, "BIND_NOT", 8) == 0)
1939 GL(dl_bind_not) = envline[9] != '\0';
1940 break;
1942 case 9:
1943 /* Test whether we want to see the content of the auxiliary
1944 array passed up from the kernel. */
1945 if (memcmp (envline, "SHOW_AUXV", 9) == 0)
1946 _dl_show_auxv ();
1947 break;
1949 case 10:
1950 /* Mask for the important hardware capabilities. */
1951 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
1952 GL(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL, 0, 0);
1953 break;
1955 case 11:
1956 /* Path where the binary is found. */
1957 if (!INTUSE(__libc_enable_secure)
1958 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
1959 GL(dl_origin_path) = &envline[12];
1960 break;
1962 case 12:
1963 /* The library search path. */
1964 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
1966 library_path = &envline[13];
1967 break;
1970 /* Where to place the profiling data file. */
1971 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
1973 debug_output = &envline[13];
1974 break;
1977 if (memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
1978 GL(dl_dynamic_weak) = 1;
1979 break;
1981 case 14:
1982 /* Where to place the profiling data file. */
1983 if (!INTUSE(__libc_enable_secure)
1984 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
1985 && envline[15] != '\0')
1986 GL(dl_profile_output) = &envline[15];
1987 break;
1989 case 16:
1990 /* The mode of the dynamic linker can be set. */
1991 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
1993 mode = trace;
1994 GL(dl_verbose) = 1;
1995 GL(dl_debug_mask) |= DL_DEBUG_PRELINK;
1996 GL(dl_trace_prelink) = &envline[17];
1998 break;
2000 case 20:
2001 /* The mode of the dynamic linker can be set. */
2002 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2003 mode = trace;
2004 break;
2006 /* We might have some extra environment variable to handle. This
2007 is tricky due to the pre-processing of the length of the name
2008 in the switch statement here. The code here assumes that added
2009 environment variables have a different length. */
2010 #ifdef EXTRA_LD_ENVVARS
2011 EXTRA_LD_ENVVARS
2012 #endif
2016 /* The caller wants this information. */
2017 *modep = mode;
2019 /* Extra security for SUID binaries. Remove all dangerous environment
2020 variables. */
2021 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2023 static const char unsecure_envvars[] =
2024 #ifdef EXTRA_UNSECURE_ENVVARS
2025 EXTRA_UNSECURE_ENVVARS
2026 #endif
2027 UNSECURE_ENVVARS;
2028 const char *nextp;
2030 nextp = unsecure_envvars;
2033 unsetenv (nextp);
2034 /* We could use rawmemchr but this need not be fast. */
2035 nextp = (char *) (strchr) (nextp, '\0') + 1;
2037 while (*nextp != '\0');
2039 if (__access ("/etc/suid-debug", F_OK) != 0)
2040 unsetenv ("MALLOC_CHECK_");
2042 /* If we have to run the dynamic linker in debugging mode and the
2043 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2044 messages to this file. */
2045 else if (any_debug && debug_output != NULL)
2047 #ifdef O_NOFOLLOW
2048 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2049 #else
2050 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2051 #endif
2052 size_t name_len = strlen (debug_output);
2053 char buf[name_len + 12];
2054 char *startp;
2056 buf[name_len + 11] = '\0';
2057 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2058 *--startp = '.';
2059 startp = memcpy (startp - name_len, debug_output, name_len);
2061 GL(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2062 if (GL(dl_debug_fd) == -1)
2063 /* We use standard output if opening the file failed. */
2064 GL(dl_debug_fd) = STDOUT_FILENO;
2069 /* Print the various times we collected. */
2070 static void
2071 print_statistics (void)
2073 #ifndef HP_TIMING_NONAVAIL
2074 char buf[200];
2075 char *cp;
2076 char *wp;
2078 /* Total time rtld used. */
2079 if (HP_TIMING_AVAIL)
2081 HP_TIMING_PRINT (buf, sizeof (buf), rtld_total_time);
2082 INTUSE(_dl_debug_printf) ("\nruntime linker statistics:\n"
2083 " total startup time in dynamic loader: %s\n",
2084 buf);
2087 /* Print relocation statistics. */
2088 if (HP_TIMING_AVAIL)
2090 char pbuf[30];
2091 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2092 cp = _itoa ((1000ULL * relocate_time) / rtld_total_time,
2093 pbuf + sizeof (pbuf), 10, 0);
2094 wp = pbuf;
2095 switch (pbuf + sizeof (pbuf) - cp)
2097 case 3:
2098 *wp++ = *cp++;
2099 case 2:
2100 *wp++ = *cp++;
2101 case 1:
2102 *wp++ = '.';
2103 *wp++ = *cp++;
2105 *wp = '\0';
2106 INTUSE(_dl_debug_printf) ("\
2107 time needed for relocation: %s (%s%%)\n",
2108 buf, pbuf);
2110 #endif
2111 INTUSE(_dl_debug_printf) (" number of relocations: %lu\n",
2112 GL(dl_num_relocations));
2113 INTUSE(_dl_debug_printf) (" number of relocations from cache: %lu\n",
2114 GL(dl_num_cache_relocations));
2116 #ifndef HP_TIMING_NONAVAIL
2117 /* Time spend while loading the object and the dependencies. */
2118 if (HP_TIMING_AVAIL)
2120 char pbuf[30];
2121 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2122 cp = _itoa ((1000ULL * load_time) / rtld_total_time,
2123 pbuf + sizeof (pbuf), 10, 0);
2124 wp = pbuf;
2125 switch (pbuf + sizeof (pbuf) - cp)
2127 case 3:
2128 *wp++ = *cp++;
2129 case 2:
2130 *wp++ = *cp++;
2131 case 1:
2132 *wp++ = '.';
2133 *wp++ = *cp++;
2135 *wp = '\0';
2136 INTUSE(_dl_debug_printf) ("\
2137 time needed to load objects: %s (%s%%)\n",
2138 buf, pbuf);
2140 #endif