Use IFUNC on x86-64 memset
[glibc.git] / elf / rtld.c
blobd53730fe308d046819d1cab8e0cc06194037e584
1 /* Run time dynamic linker.
2 Copyright (C) 1995-2006, 2007, 2008, 2009, 2010 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 <dlfcn.h>
22 #include <fcntl.h>
23 #include <stdbool.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <sys/mman.h>
28 #include <sys/param.h>
29 #include <sys/stat.h>
30 #include <ldsodefs.h>
31 #include <stdio-common/_itoa.h>
32 #include <entry.h>
33 #include <fpu_control.h>
34 #include <hp-timing.h>
35 #include <bits/libc-lock.h>
36 #include "dynamic-link.h"
37 #include <dl-librecon.h>
38 #include <unsecvars.h>
39 #include <dl-cache.h>
40 #include <dl-osinfo.h>
41 #include <dl-procinfo.h>
42 #include <tls.h>
44 #include <assert.h>
46 /* Avoid PLT use for our local calls at startup. */
47 extern __typeof (__mempcpy) __mempcpy attribute_hidden;
49 /* GCC has mental blocks about _exit. */
50 extern __typeof (_exit) exit_internal asm ("_exit") attribute_hidden;
51 #define _exit exit_internal
53 /* Helper function to handle errors while resolving symbols. */
54 static void print_unresolved (int errcode, const char *objname,
55 const char *errsting);
57 /* Helper function to handle errors when a version is missing. */
58 static void print_missing_version (int errcode, const char *objname,
59 const char *errsting);
61 /* Print the various times we collected. */
62 static void print_statistics (hp_timing_t *total_timep);
64 /* Add audit objects. */
65 static void process_dl_audit (char *str);
67 /* This is a list of all the modes the dynamic loader can be in. */
68 enum mode { normal, list, verify, trace };
70 /* Process all environments variables the dynamic linker must recognize.
71 Since all of them start with `LD_' we are a bit smarter while finding
72 all the entries. */
73 static void process_envvars (enum mode *modep);
75 #ifdef DL_ARGV_NOT_RELRO
76 int _dl_argc attribute_hidden;
77 char **_dl_argv = NULL;
78 /* Nonzero if we were run directly. */
79 unsigned int _dl_skip_args attribute_hidden;
80 #else
81 int _dl_argc attribute_relro attribute_hidden;
82 char **_dl_argv attribute_relro = NULL;
83 unsigned int _dl_skip_args attribute_relro attribute_hidden;
84 #endif
85 INTDEF(_dl_argv)
87 #ifndef THREAD_SET_STACK_GUARD
88 /* Only exported for architectures that don't store the stack guard canary
89 in thread local area. */
90 uintptr_t __stack_chk_guard attribute_relro;
91 #endif
93 /* Only exported for architectures that don't store the pointer guard
94 value in thread local area. */
95 uintptr_t __pointer_chk_guard_local
96 attribute_relro attribute_hidden __attribute__ ((nocommon));
97 #ifndef THREAD_SET_POINTER_GUARD
98 strong_alias (__pointer_chk_guard_local, __pointer_chk_guard)
99 #endif
102 /* List of auditing DSOs. */
103 static struct audit_list
105 const char *name;
106 struct audit_list *next;
107 } *audit_list;
109 #ifndef HAVE_INLINED_SYSCALLS
110 /* Set nonzero during loading and initialization of executable and
111 libraries, cleared before the executable's entry point runs. This
112 must not be initialized to nonzero, because the unused dynamic
113 linker loaded in for libc.so's "ld.so.1" dep will provide the
114 definition seen by libc.so's initializer; that value must be zero,
115 and will be since that dynamic linker's _dl_start and dl_main will
116 never be called. */
117 int _dl_starting_up = 0;
118 INTVARDEF(_dl_starting_up)
119 #endif
121 /* This is the structure which defines all variables global to ld.so
122 (except those which cannot be added for some reason). */
123 struct rtld_global _rtld_global =
125 /* Default presumption without further information is executable stack. */
126 ._dl_stack_flags = PF_R|PF_W|PF_X,
127 #ifdef _LIBC_REENTRANT
128 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
129 ._dl_load_write_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
130 #endif
131 ._dl_nns = 1,
132 ._dl_ns =
134 [LM_ID_BASE] = { ._ns_unique_sym_table
135 = { .lock = _RTLD_LOCK_RECURSIVE_INITIALIZER } }
138 /* If we would use strong_alias here the compiler would see a
139 non-hidden definition. This would undo the effect of the previous
140 declaration. So spell out was strong_alias does plus add the
141 visibility attribute. */
142 extern struct rtld_global _rtld_local
143 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
146 /* This variable is similar to _rtld_local, but all values are
147 read-only after relocation. */
148 struct rtld_global_ro _rtld_global_ro attribute_relro =
150 /* Get architecture specific initializer. */
151 #include <dl-procinfo.c>
152 #ifdef NEED_DL_SYSINFO
153 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
154 #endif
155 ._dl_debug_fd = STDERR_FILENO,
156 ._dl_use_load_bias = -2,
157 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
158 ._dl_hwcap_mask = HWCAP_IMPORTANT,
159 ._dl_lazy = 1,
160 ._dl_fpu_control = _FPU_DEFAULT,
161 ._dl_pointer_guard = 1,
163 /* Function pointers. */
164 ._dl_debug_printf = _dl_debug_printf,
165 ._dl_catch_error = _dl_catch_error,
166 ._dl_signal_error = _dl_signal_error,
167 ._dl_mcount = _dl_mcount_internal,
168 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
169 ._dl_check_caller = _dl_check_caller,
170 ._dl_open = _dl_open,
171 ._dl_close = _dl_close,
172 ._dl_tls_get_addr_soft = _dl_tls_get_addr_soft,
173 #ifdef HAVE_DL_DISCOVER_OSVERSION
174 ._dl_discover_osversion = _dl_discover_osversion
175 #endif
177 /* If we would use strong_alias here the compiler would see a
178 non-hidden definition. This would undo the effect of the previous
179 declaration. So spell out was strong_alias does plus add the
180 visibility attribute. */
181 extern struct rtld_global_ro _rtld_local_ro
182 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
185 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
186 ElfW(Addr) *user_entry, ElfW(auxv_t) *auxv);
188 /* These two variables cannot be moved into .data.rel.ro. */
189 static struct libname_list _dl_rtld_libname;
190 static struct libname_list _dl_rtld_libname2;
192 /* We expect less than a second for relocation. */
193 #ifdef HP_SMALL_TIMING_AVAIL
194 # undef HP_TIMING_AVAIL
195 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
196 #endif
198 /* Variable for statistics. */
199 #ifndef HP_TIMING_NONAVAIL
200 static hp_timing_t relocate_time;
201 static hp_timing_t load_time attribute_relro;
202 static hp_timing_t start_time attribute_relro;
203 #endif
205 /* Additional definitions needed by TLS initialization. */
206 #ifdef TLS_INIT_HELPER
207 TLS_INIT_HELPER
208 #endif
210 /* Helper function for syscall implementation. */
211 #ifdef DL_SYSINFO_IMPLEMENTATION
212 DL_SYSINFO_IMPLEMENTATION
213 #endif
215 /* Before ld.so is relocated we must not access variables which need
216 relocations. This means variables which are exported. Variables
217 declared as static are fine. If we can mark a variable hidden this
218 is fine, too. The latter is important here. We can avoid setting
219 up a temporary link map for ld.so if we can mark _rtld_global as
220 hidden. */
221 #ifdef PI_STATIC_AND_HIDDEN
222 # define DONT_USE_BOOTSTRAP_MAP 1
223 #endif
225 #ifdef DONT_USE_BOOTSTRAP_MAP
226 static ElfW(Addr) _dl_start_final (void *arg);
227 #else
228 struct dl_start_final_info
230 struct link_map l;
231 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
232 hp_timing_t start_time;
233 #endif
235 static ElfW(Addr) _dl_start_final (void *arg,
236 struct dl_start_final_info *info);
237 #endif
239 /* These defined magically in the linker script. */
240 extern char _begin[] attribute_hidden;
241 extern char _etext[] attribute_hidden;
242 extern char _end[] attribute_hidden;
245 #ifdef RTLD_START
246 RTLD_START
247 #else
248 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
249 #endif
251 #ifndef VALIDX
252 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
253 + DT_EXTRANUM + DT_VALTAGIDX (tag))
254 #endif
255 #ifndef ADDRIDX
256 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
257 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
258 #endif
260 /* This is the second half of _dl_start (below). It can be inlined safely
261 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
262 references. When the tools don't permit us to avoid using a GOT entry
263 for _dl_rtld_global (no attribute_hidden support), we must make sure
264 this function is not inlined (see below). */
266 #ifdef DONT_USE_BOOTSTRAP_MAP
267 static inline ElfW(Addr) __attribute__ ((always_inline))
268 _dl_start_final (void *arg)
269 #else
270 static ElfW(Addr) __attribute__ ((noinline))
271 _dl_start_final (void *arg, struct dl_start_final_info *info)
272 #endif
274 ElfW(Addr) start_addr;
276 if (HP_TIMING_AVAIL)
278 /* If it hasn't happen yet record the startup time. */
279 if (! HP_TIMING_INLINE)
280 HP_TIMING_NOW (start_time);
281 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
282 else
283 start_time = info->start_time;
284 #endif
286 /* Initialize the timing functions. */
287 HP_TIMING_DIFF_INIT ();
290 /* Transfer data about ourselves to the permanent link_map structure. */
291 #ifndef DONT_USE_BOOTSTRAP_MAP
292 GL(dl_rtld_map).l_addr = info->l.l_addr;
293 GL(dl_rtld_map).l_ld = info->l.l_ld;
294 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
295 sizeof GL(dl_rtld_map).l_info);
296 GL(dl_rtld_map).l_mach = info->l.l_mach;
297 GL(dl_rtld_map).l_relocated = 1;
298 #endif
299 _dl_setup_hash (&GL(dl_rtld_map));
300 GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
301 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
302 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
303 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
304 /* Copy the TLS related data if necessary. */
305 #ifndef DONT_USE_BOOTSTRAP_MAP
306 # if USE___THREAD
307 assert (info->l.l_tls_modid != 0);
308 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
309 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
310 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
311 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
312 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
313 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
314 GL(dl_rtld_map).l_tls_modid = 1;
315 # else
316 # if NO_TLS_OFFSET != 0
317 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
318 # endif
319 # endif
321 #endif
323 #if HP_TIMING_AVAIL
324 HP_TIMING_NOW (GL(dl_cpuclock_offset));
325 #endif
327 /* Initialize the stack end variable. */
328 __libc_stack_end = __builtin_frame_address (0);
330 /* Call the OS-dependent function to set up life so we can do things like
331 file access. It will call `dl_main' (below) to do all the real work
332 of the dynamic linker, and then unwind our frame and run the user
333 entry point on the same stack we entered on. */
334 start_addr = _dl_sysdep_start (arg, &dl_main);
336 #ifndef HP_TIMING_NONAVAIL
337 hp_timing_t rtld_total_time;
338 if (HP_TIMING_AVAIL)
340 hp_timing_t end_time;
342 /* Get the current time. */
343 HP_TIMING_NOW (end_time);
345 /* Compute the difference. */
346 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
348 #endif
350 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
352 #ifndef HP_TIMING_NONAVAIL
353 print_statistics (&rtld_total_time);
354 #else
355 print_statistics (NULL);
356 #endif
359 return start_addr;
362 static ElfW(Addr) __attribute_used__ internal_function
363 _dl_start (void *arg)
365 #ifdef DONT_USE_BOOTSTRAP_MAP
366 # define bootstrap_map GL(dl_rtld_map)
367 #else
368 struct dl_start_final_info info;
369 # define bootstrap_map info.l
370 #endif
372 /* This #define produces dynamic linking inline functions for
373 bootstrap relocation instead of general-purpose relocation.
374 Since ld.so must not have any undefined symbols the result
375 is trivial: always the map of ld.so itself. */
376 #define RTLD_BOOTSTRAP
377 #define RESOLVE_MAP(sym, version, flags) (&bootstrap_map)
378 #include "dynamic-link.h"
380 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
381 #ifdef DONT_USE_BOOTSTRAP_MAP
382 HP_TIMING_NOW (start_time);
383 #else
384 HP_TIMING_NOW (info.start_time);
385 #endif
387 /* Partly clean the `bootstrap_map' structure up. Don't use
388 `memset' since it might not be built in or inlined and we cannot
389 make function calls at this point. Use '__builtin_memset' if we
390 know it is available. We do not have to clear the memory if we
391 do not have to use the temporary bootstrap_map. Global variables
392 are initialized to zero by default. */
393 #ifndef DONT_USE_BOOTSTRAP_MAP
394 # ifdef HAVE_BUILTIN_MEMSET
395 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
396 # else
397 for (size_t cnt = 0;
398 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
399 ++cnt)
400 bootstrap_map.l_info[cnt] = 0;
401 # endif
402 # if USE___THREAD
403 bootstrap_map.l_tls_modid = 0;
404 # endif
405 #endif
407 /* Figure out the run-time load address of the dynamic linker itself. */
408 bootstrap_map.l_addr = elf_machine_load_address ();
410 /* Read our own dynamic section and fill in the info array. */
411 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
412 elf_get_dynamic_info (&bootstrap_map, NULL);
414 #if NO_TLS_OFFSET != 0
415 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
416 #endif
418 /* Get the dynamic linker's own program header. First we need the ELF
419 file header. The `_begin' symbol created by the linker script points
420 to it. When we have something like GOTOFF relocs, we can use a plain
421 reference to find the runtime address. Without that, we have to rely
422 on the `l_addr' value, which is not the value we want when prelinked. */
423 #if USE___THREAD
424 dtv_t initdtv[3];
425 ElfW(Ehdr) *ehdr
426 # ifdef DONT_USE_BOOTSTRAP_MAP
427 = (ElfW(Ehdr) *) &_begin;
428 # else
429 # error This will not work with prelink.
430 = (ElfW(Ehdr) *) bootstrap_map.l_addr;
431 # endif
432 ElfW(Phdr) *phdr = (ElfW(Phdr) *) ((void *) ehdr + ehdr->e_phoff);
433 size_t cnt = ehdr->e_phnum; /* PT_TLS is usually the last phdr. */
434 while (cnt-- > 0)
435 if (phdr[cnt].p_type == PT_TLS)
437 void *tlsblock;
438 size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
439 char *p;
441 bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
442 bootstrap_map.l_tls_align = phdr[cnt].p_align;
443 if (phdr[cnt].p_align == 0)
444 bootstrap_map.l_tls_firstbyte_offset = 0;
445 else
446 bootstrap_map.l_tls_firstbyte_offset = (phdr[cnt].p_vaddr
447 & (phdr[cnt].p_align - 1));
448 assert (bootstrap_map.l_tls_blocksize != 0);
449 bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
450 bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
451 + phdr[cnt].p_vaddr);
453 /* We can now allocate the initial TLS block. This can happen
454 on the stack. We'll get the final memory later when we
455 know all about the various objects loaded at startup
456 time. */
457 # if TLS_TCB_AT_TP
458 tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
459 TLS_INIT_TCB_ALIGN)
460 + TLS_INIT_TCB_SIZE
461 + max_align);
462 # elif TLS_DTV_AT_TP
463 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
464 bootstrap_map.l_tls_align)
465 + bootstrap_map.l_tls_blocksize
466 + max_align);
467 # else
468 /* In case a model with a different layout for the TCB and DTV
469 is defined add another #elif here and in the following #ifs. */
470 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
471 # endif
472 /* Align the TLS block. */
473 tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
474 & ~(max_align - 1));
476 /* Initialize the dtv. [0] is the length, [1] the generation
477 counter. */
478 initdtv[0].counter = 1;
479 initdtv[1].counter = 0;
481 /* Initialize the TLS block. */
482 # if TLS_TCB_AT_TP
483 initdtv[2].pointer = tlsblock;
484 # elif TLS_DTV_AT_TP
485 bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
486 bootstrap_map.l_tls_align);
487 initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
488 # else
489 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
490 # endif
491 p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
492 bootstrap_map.l_tls_initimage_size);
493 # ifdef HAVE_BUILTIN_MEMSET
494 __builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
495 - bootstrap_map.l_tls_initimage_size));
496 # else
498 size_t remaining = (bootstrap_map.l_tls_blocksize
499 - bootstrap_map.l_tls_initimage_size);
500 while (remaining-- > 0)
501 *p++ = '\0';
503 # endif
505 /* Install the pointer to the dtv. */
507 /* Initialize the thread pointer. */
508 # if TLS_TCB_AT_TP
509 bootstrap_map.l_tls_offset
510 = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
512 INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
513 initdtv);
515 const char *lossage = TLS_INIT_TP ((char *) tlsblock
516 + bootstrap_map.l_tls_offset, 0);
517 # elif TLS_DTV_AT_TP
518 INSTALL_DTV (tlsblock, initdtv);
519 const char *lossage = TLS_INIT_TP (tlsblock, 0);
520 # else
521 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
522 # endif
523 if (__builtin_expect (lossage != NULL, 0))
524 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
525 lossage);
527 /* So far this is module number one. */
528 bootstrap_map.l_tls_modid = 1;
530 /* There can only be one PT_TLS entry. */
531 break;
533 #endif /* USE___THREAD */
535 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
536 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
537 #endif
539 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
541 /* Relocate ourselves so we can do normal function calls and
542 data access using the global offset table. */
544 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
546 bootstrap_map.l_relocated = 1;
548 /* Please note that we don't allow profiling of this object and
549 therefore need not test whether we have to allocate the array
550 for the relocation results (as done in dl-reloc.c). */
552 /* Now life is sane; we can call functions and access global data.
553 Set up to use the operating system facilities, and find out from
554 the operating system's program loader where to find the program
555 header table in core. Put the rest of _dl_start into a separate
556 function, that way the compiler cannot put accesses to the GOT
557 before ELF_DYNAMIC_RELOCATE. */
559 #ifdef DONT_USE_BOOTSTRAP_MAP
560 ElfW(Addr) entry = _dl_start_final (arg);
561 #else
562 ElfW(Addr) entry = _dl_start_final (arg, &info);
563 #endif
565 #ifndef ELF_MACHINE_START_ADDRESS
566 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
567 #endif
569 return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, entry);
575 /* Now life is peachy; we can do all normal operations.
576 On to the real work. */
578 /* Some helper functions. */
580 /* Arguments to relocate_doit. */
581 struct relocate_args
583 struct link_map *l;
584 int reloc_mode;
587 struct map_args
589 /* Argument to map_doit. */
590 char *str;
591 struct link_map *loader;
592 int mode;
593 /* Return value of map_doit. */
594 struct link_map *map;
597 struct dlmopen_args
599 const char *fname;
600 struct link_map *map;
603 struct lookup_args
605 const char *name;
606 struct link_map *map;
607 void *result;
610 /* Arguments to version_check_doit. */
611 struct version_check_args
613 int doexit;
614 int dotrace;
617 static void
618 relocate_doit (void *a)
620 struct relocate_args *args = (struct relocate_args *) a;
622 _dl_relocate_object (args->l, args->l->l_scope, args->reloc_mode, 0);
625 static void
626 map_doit (void *a)
628 struct map_args *args = (struct map_args *) a;
629 args->map = _dl_map_object (args->loader, args->str, lt_library, 0,
630 args->mode, LM_ID_BASE);
633 static void
634 dlmopen_doit (void *a)
636 struct dlmopen_args *args = (struct dlmopen_args *) a;
637 args->map = _dl_open (args->fname,
638 (RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT
639 | __RTLD_SECURE),
640 dl_main, LM_ID_NEWLM, _dl_argc, INTUSE(_dl_argv),
641 __environ);
644 static void
645 lookup_doit (void *a)
647 struct lookup_args *args = (struct lookup_args *) a;
648 const ElfW(Sym) *ref = NULL;
649 args->result = NULL;
650 lookup_t l = _dl_lookup_symbol_x (args->name, args->map, &ref,
651 args->map->l_local_scope, NULL, 0,
652 DL_LOOKUP_RETURN_NEWEST, NULL);
653 if (ref != NULL)
654 args->result = DL_SYMBOL_ADDRESS (l, ref);
657 static void
658 version_check_doit (void *a)
660 struct version_check_args *args = (struct version_check_args *) a;
661 if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
662 args->dotrace) && args->doexit)
663 /* We cannot start the application. Abort now. */
664 _exit (1);
668 static inline struct link_map *
669 find_needed (const char *name)
671 struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
672 unsigned int n = scope->r_nlist;
674 while (n-- > 0)
675 if (_dl_name_match_p (name, scope->r_list[n]))
676 return scope->r_list[n];
678 /* Should never happen. */
679 return NULL;
682 static int
683 match_version (const char *string, struct link_map *map)
685 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
686 ElfW(Verdef) *def;
688 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
689 if (map->l_info[VERDEFTAG] == NULL)
690 /* The file has no symbol versioning. */
691 return 0;
693 def = (ElfW(Verdef) *) ((char *) map->l_addr
694 + map->l_info[VERDEFTAG]->d_un.d_ptr);
695 while (1)
697 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
699 /* Compare the version strings. */
700 if (strcmp (string, strtab + aux->vda_name) == 0)
701 /* Bingo! */
702 return 1;
704 /* If no more definitions we failed to find what we want. */
705 if (def->vd_next == 0)
706 break;
708 /* Next definition. */
709 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
712 return 0;
715 static bool tls_init_tp_called;
717 static void *
718 init_tls (void)
720 /* Number of elements in the static TLS block. */
721 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
723 /* Do not do this twice. The audit interface might have required
724 the DTV interfaces to be set up early. */
725 if (GL(dl_initial_dtv) != NULL)
726 return NULL;
728 /* Allocate the array which contains the information about the
729 dtv slots. We allocate a few entries more than needed to
730 avoid the need for reallocation. */
731 size_t nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
733 /* Allocate. */
734 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
735 calloc (sizeof (struct dtv_slotinfo_list)
736 + nelem * sizeof (struct dtv_slotinfo), 1);
737 /* No need to check the return value. If memory allocation failed
738 the program would have been terminated. */
740 struct dtv_slotinfo *slotinfo = GL(dl_tls_dtv_slotinfo_list)->slotinfo;
741 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
742 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
744 /* Fill in the information from the loaded modules. No namespace
745 but the base one can be filled at this time. */
746 assert (GL(dl_ns)[LM_ID_BASE + 1]._ns_loaded == NULL);
747 int i = 0;
748 for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
749 l = l->l_next)
750 if (l->l_tls_blocksize != 0)
752 /* This is a module with TLS data. Store the map reference.
753 The generation counter is zero. */
754 slotinfo[i].map = l;
755 /* slotinfo[i].gen = 0; */
756 ++i;
758 assert (i == GL(dl_tls_max_dtv_idx));
760 /* Compute the TLS offsets for the various blocks. */
761 _dl_determine_tlsoffset ();
763 /* Construct the static TLS block and the dtv for the initial
764 thread. For some platforms this will include allocating memory
765 for the thread descriptor. The memory for the TLS block will
766 never be freed. It should be allocated accordingly. The dtv
767 array can be changed if dynamic loading requires it. */
768 void *tcbp = _dl_allocate_tls_storage ();
769 if (tcbp == NULL)
770 _dl_fatal_printf ("\
771 cannot allocate TLS data structures for initial thread");
773 /* Store for detection of the special case by __tls_get_addr
774 so it knows not to pass this dtv to the normal realloc. */
775 GL(dl_initial_dtv) = GET_DTV (tcbp);
777 /* And finally install it for the main thread. If ld.so itself uses
778 TLS we know the thread pointer was initialized earlier. */
779 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
780 if (__builtin_expect (lossage != NULL, 0))
781 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
782 tls_init_tp_called = true;
784 return tcbp;
787 #ifdef _LIBC_REENTRANT
788 /* _dl_error_catch_tsd points to this for the single-threaded case.
789 It's reset by the thread library for multithreaded programs. */
790 void ** __attribute__ ((const))
791 _dl_initial_error_catch_tsd (void)
793 static void *data;
794 return &data;
796 #endif
799 static unsigned int
800 do_preload (char *fname, struct link_map *main_map, const char *where)
802 const char *objname;
803 const char *err_str = NULL;
804 struct map_args args;
805 bool malloced;
807 args.str = fname;
808 args.loader = main_map;
809 args.mode = __RTLD_SECURE;
811 unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
813 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
814 if (__builtin_expect (err_str != NULL, 0))
816 _dl_error_printf ("\
817 ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
818 fname, where);
819 /* No need to call free, this is still before
820 the libc's malloc is used. */
822 else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
823 /* It is no duplicate. */
824 return 1;
826 /* Nothing loaded. */
827 return 0;
830 #if defined SHARED && defined _LIBC_REENTRANT \
831 && defined __rtld_lock_default_lock_recursive
832 static void
833 rtld_lock_default_lock_recursive (void *lock)
835 __rtld_lock_default_lock_recursive (lock);
838 static void
839 rtld_lock_default_unlock_recursive (void *lock)
841 __rtld_lock_default_unlock_recursive (lock);
843 #endif
846 static void
847 security_init (void)
849 /* Set up the stack checker's canary. */
850 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard (_dl_random);
851 #ifdef THREAD_SET_STACK_GUARD
852 THREAD_SET_STACK_GUARD (stack_chk_guard);
853 #else
854 __stack_chk_guard = stack_chk_guard;
855 #endif
857 /* Set up the pointer guard as well, if necessary. */
858 if (GLRO(dl_pointer_guard))
860 uintptr_t pointer_chk_guard = _dl_setup_pointer_guard (_dl_random,
861 stack_chk_guard);
862 #ifdef THREAD_SET_POINTER_GUARD
863 THREAD_SET_POINTER_GUARD (pointer_chk_guard);
864 #endif
865 __pointer_chk_guard_local = pointer_chk_guard;
868 /* We do not need the _dl_random value anymore. The less
869 information we leave behind, the better, so clear the
870 variable. */
871 _dl_random = NULL;
875 /* The library search path. */
876 static const char *library_path attribute_relro;
877 /* The list preloaded objects. */
878 static const char *preloadlist attribute_relro;
879 /* Nonzero if information about versions has to be printed. */
880 static int version_info attribute_relro;
882 static void
883 dl_main (const ElfW(Phdr) *phdr,
884 ElfW(Word) phnum,
885 ElfW(Addr) *user_entry,
886 ElfW(auxv_t) *auxv)
888 const ElfW(Phdr) *ph;
889 enum mode mode;
890 struct link_map *main_map;
891 size_t file_size;
892 char *file;
893 bool has_interp = false;
894 unsigned int i;
895 bool prelinked = false;
896 bool rtld_is_main = false;
897 #ifndef HP_TIMING_NONAVAIL
898 hp_timing_t start;
899 hp_timing_t stop;
900 hp_timing_t diff;
901 #endif
902 void *tcbp = NULL;
904 #ifdef _LIBC_REENTRANT
905 /* Explicit initialization since the reloc would just be more work. */
906 GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
907 #endif
909 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
911 #if defined SHARED && defined _LIBC_REENTRANT \
912 && defined __rtld_lock_default_lock_recursive
913 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
914 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
915 #endif
917 /* The explicit initialization here is cheaper than processing the reloc
918 in the _rtld_local definition's initializer. */
919 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
921 /* Process the environment variable which control the behaviour. */
922 process_envvars (&mode);
924 #ifndef HAVE_INLINED_SYSCALLS
925 /* Set up a flag which tells we are just starting. */
926 INTUSE(_dl_starting_up) = 1;
927 #endif
929 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
931 /* Ho ho. We are not the program interpreter! We are the program
932 itself! This means someone ran ld.so as a command. Well, that
933 might be convenient to do sometimes. We support it by
934 interpreting the args like this:
936 ld.so PROGRAM ARGS...
938 The first argument is the name of a file containing an ELF
939 executable we will load and run with the following arguments.
940 To simplify life here, PROGRAM is searched for using the
941 normal rules for shared objects, rather than $PATH or anything
942 like that. We just load it and use its entry point; we don't
943 pay attention to its PT_INTERP command (we are the interpreter
944 ourselves). This is an easy way to test a new ld.so before
945 installing it. */
946 rtld_is_main = true;
948 /* Note the place where the dynamic linker actually came from. */
949 GL(dl_rtld_map).l_name = rtld_progname;
951 while (_dl_argc > 1)
952 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
954 mode = list;
955 GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
957 ++_dl_skip_args;
958 --_dl_argc;
959 ++INTUSE(_dl_argv);
961 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
963 mode = verify;
965 ++_dl_skip_args;
966 --_dl_argc;
967 ++INTUSE(_dl_argv);
969 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
970 && _dl_argc > 2)
972 library_path = INTUSE(_dl_argv)[2];
974 _dl_skip_args += 2;
975 _dl_argc -= 2;
976 INTUSE(_dl_argv) += 2;
978 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
979 && _dl_argc > 2)
981 GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
983 _dl_skip_args += 2;
984 _dl_argc -= 2;
985 INTUSE(_dl_argv) += 2;
987 else if (! strcmp (INTUSE(_dl_argv)[1], "--audit") && _dl_argc > 2)
989 process_dl_audit (INTUSE(_dl_argv)[2]);
991 _dl_skip_args += 2;
992 _dl_argc -= 2;
993 INTUSE(_dl_argv) += 2;
995 else
996 break;
998 /* If we have no further argument the program was called incorrectly.
999 Grant the user some education. */
1000 if (_dl_argc < 2)
1001 _dl_fatal_printf ("\
1002 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
1003 You have invoked `ld.so', the helper program for shared library executables.\n\
1004 This program usually lives in the file `/lib/ld.so', and special directives\n\
1005 in executable files using ELF shared libraries tell the system's program\n\
1006 loader to load the helper program from this file. This helper program loads\n\
1007 the shared libraries needed by the program executable, prepares the program\n\
1008 to run, and runs it. You may invoke this helper program directly from the\n\
1009 command line to load and run an ELF executable file; this is like executing\n\
1010 that file itself, but always uses this helper program from the file you\n\
1011 specified, instead of the helper program file specified in the executable\n\
1012 file you run. This is mostly of use for maintainers to test new versions\n\
1013 of this helper program; chances are you did not intend to run this program.\n\
1015 --list list all dependencies and how they are resolved\n\
1016 --verify verify that given object really is a dynamically linked\n\
1017 object we can handle\n\
1018 --library-path PATH use given PATH instead of content of the environment\n\
1019 variable LD_LIBRARY_PATH\n\
1020 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
1021 in LIST\n\
1022 --audit LIST use objects named in LIST as auditors\n");
1024 ++_dl_skip_args;
1025 --_dl_argc;
1026 ++INTUSE(_dl_argv);
1028 /* The initialization of _dl_stack_flags done below assumes the
1029 executable's PT_GNU_STACK may have been honored by the kernel, and
1030 so a PT_GNU_STACK with PF_X set means the stack started out with
1031 execute permission. However, this is not really true if the
1032 dynamic linker is the executable the kernel loaded. For this
1033 case, we must reinitialize _dl_stack_flags to match the dynamic
1034 linker itself. If the dynamic linker was built with a
1035 PT_GNU_STACK, then the kernel may have loaded us with a
1036 nonexecutable stack that we will have to make executable when we
1037 load the program below unless it has a PT_GNU_STACK indicating
1038 nonexecutable stack is ok. */
1040 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1041 if (ph->p_type == PT_GNU_STACK)
1043 GL(dl_stack_flags) = ph->p_flags;
1044 break;
1047 if (__builtin_expect (mode, normal) == verify)
1049 const char *objname;
1050 const char *err_str = NULL;
1051 struct map_args args;
1052 bool malloced;
1054 args.str = rtld_progname;
1055 args.loader = NULL;
1056 args.mode = __RTLD_OPENEXEC;
1057 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
1058 &args);
1059 if (__builtin_expect (err_str != NULL, 0))
1060 /* We don't free the returned string, the programs stops
1061 anyway. */
1062 _exit (EXIT_FAILURE);
1064 else
1066 HP_TIMING_NOW (start);
1067 _dl_map_object (NULL, rtld_progname, lt_library, 0,
1068 __RTLD_OPENEXEC, LM_ID_BASE);
1069 HP_TIMING_NOW (stop);
1071 HP_TIMING_DIFF (load_time, start, stop);
1074 /* Now the map for the main executable is available. */
1075 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1077 phdr = main_map->l_phdr;
1078 phnum = main_map->l_phnum;
1079 /* We overwrite here a pointer to a malloc()ed string. But since
1080 the malloc() implementation used at this point is the dummy
1081 implementations which has no real free() function it does not
1082 makes sense to free the old string first. */
1083 main_map->l_name = (char *) "";
1084 *user_entry = main_map->l_entry;
1086 #ifdef HAVE_AUX_VECTOR
1087 /* Adjust the on-stack auxiliary vector so that it looks like the
1088 binary was executed directly. */
1089 for (ElfW(auxv_t) *av = auxv; av->a_type != AT_NULL; av++)
1090 switch (av->a_type)
1092 case AT_PHDR:
1093 av->a_un.a_val = (uintptr_t) phdr;
1094 break;
1095 case AT_PHNUM:
1096 av->a_un.a_val = phnum;
1097 break;
1098 case AT_ENTRY:
1099 av->a_un.a_val = *user_entry;
1100 break;
1102 #endif
1104 else
1106 /* Create a link_map for the executable itself.
1107 This will be what dlopen on "" returns. */
1108 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1109 __RTLD_OPENEXEC, LM_ID_BASE);
1110 assert (main_map != NULL);
1111 main_map->l_phdr = phdr;
1112 main_map->l_phnum = phnum;
1113 main_map->l_entry = *user_entry;
1115 /* Even though the link map is not yet fully initialized we can add
1116 it to the map list since there are no possible users running yet. */
1117 _dl_add_to_namespace_list (main_map, LM_ID_BASE);
1118 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
1120 /* At this point we are in a bit of trouble. We would have to
1121 fill in the values for l_dev and l_ino. But in general we
1122 do not know where the file is. We also do not handle AT_EXECFD
1123 even if it would be passed up.
1125 We leave the values here defined to 0. This is normally no
1126 problem as the program code itself is normally no shared
1127 object and therefore cannot be loaded dynamically. Nothing
1128 prevent the use of dynamic binaries and in these situations
1129 we might get problems. We might not be able to find out
1130 whether the object is already loaded. But since there is no
1131 easy way out and because the dynamic binary must also not
1132 have an SONAME we ignore this program for now. If it becomes
1133 a problem we can force people using SONAMEs. */
1135 /* We delay initializing the path structure until we got the dynamic
1136 information for the program. */
1139 main_map->l_map_end = 0;
1140 main_map->l_text_end = 0;
1141 /* Perhaps the executable has no PT_LOAD header entries at all. */
1142 main_map->l_map_start = ~0;
1143 /* And it was opened directly. */
1144 ++main_map->l_direct_opencount;
1146 /* Scan the program header table for the dynamic section. */
1147 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1148 switch (ph->p_type)
1150 case PT_PHDR:
1151 /* Find out the load address. */
1152 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1153 break;
1154 case PT_DYNAMIC:
1155 /* This tells us where to find the dynamic section,
1156 which tells us everything we need to do. */
1157 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
1158 break;
1159 case PT_INTERP:
1160 /* This "interpreter segment" was used by the program loader to
1161 find the program interpreter, which is this program itself, the
1162 dynamic linker. We note what name finds us, so that a future
1163 dlopen call or DT_NEEDED entry, for something that wants to link
1164 against the dynamic linker as a shared library, will know that
1165 the shared object is already loaded. */
1166 _dl_rtld_libname.name = ((const char *) main_map->l_addr
1167 + ph->p_vaddr);
1168 /* _dl_rtld_libname.next = NULL; Already zero. */
1169 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1171 /* Ordinarilly, we would get additional names for the loader from
1172 our DT_SONAME. This can't happen if we were actually linked as
1173 a static executable (detect this case when we have no DYNAMIC).
1174 If so, assume the filename component of the interpreter path to
1175 be our SONAME, and add it to our name list. */
1176 if (GL(dl_rtld_map).l_ld == NULL)
1178 const char *p = NULL;
1179 const char *cp = _dl_rtld_libname.name;
1181 /* Find the filename part of the path. */
1182 while (*cp != '\0')
1183 if (*cp++ == '/')
1184 p = cp;
1186 if (p != NULL)
1188 _dl_rtld_libname2.name = p;
1189 /* _dl_rtld_libname2.next = NULL; Already zero. */
1190 _dl_rtld_libname.next = &_dl_rtld_libname2;
1194 has_interp = true;
1195 break;
1196 case PT_LOAD:
1198 ElfW(Addr) mapstart;
1199 ElfW(Addr) allocend;
1201 /* Remember where the main program starts in memory. */
1202 mapstart = (main_map->l_addr
1203 + (ph->p_vaddr & ~(GLRO(dl_pagesize) - 1)));
1204 if (main_map->l_map_start > mapstart)
1205 main_map->l_map_start = mapstart;
1207 /* Also where it ends. */
1208 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1209 if (main_map->l_map_end < allocend)
1210 main_map->l_map_end = allocend;
1211 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1212 main_map->l_text_end = allocend;
1214 break;
1216 case PT_TLS:
1217 if (ph->p_memsz > 0)
1219 /* Note that in the case the dynamic linker we duplicate work
1220 here since we read the PT_TLS entry already in
1221 _dl_start_final. But the result is repeatable so do not
1222 check for this special but unimportant case. */
1223 main_map->l_tls_blocksize = ph->p_memsz;
1224 main_map->l_tls_align = ph->p_align;
1225 if (ph->p_align == 0)
1226 main_map->l_tls_firstbyte_offset = 0;
1227 else
1228 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1229 & (ph->p_align - 1));
1230 main_map->l_tls_initimage_size = ph->p_filesz;
1231 main_map->l_tls_initimage = (void *) ph->p_vaddr;
1233 /* This image gets the ID one. */
1234 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1236 break;
1238 case PT_GNU_STACK:
1239 GL(dl_stack_flags) = ph->p_flags;
1240 break;
1242 case PT_GNU_RELRO:
1243 main_map->l_relro_addr = ph->p_vaddr;
1244 main_map->l_relro_size = ph->p_memsz;
1245 break;
1248 /* Adjust the address of the TLS initialization image in case
1249 the executable is actually an ET_DYN object. */
1250 if (main_map->l_tls_initimage != NULL)
1251 main_map->l_tls_initimage
1252 = (char *) main_map->l_tls_initimage + main_map->l_addr;
1253 if (! main_map->l_map_end)
1254 main_map->l_map_end = ~0;
1255 if (! main_map->l_text_end)
1256 main_map->l_text_end = ~0;
1257 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1259 /* We were invoked directly, so the program might not have a
1260 PT_INTERP. */
1261 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1262 /* _dl_rtld_libname.next = NULL; Already zero. */
1263 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1265 else
1266 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1268 /* If the current libname is different from the SONAME, add the
1269 latter as well. */
1270 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1271 && strcmp (GL(dl_rtld_map).l_libname->name,
1272 (const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1273 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1275 static struct libname_list newname;
1276 newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1277 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1278 newname.next = NULL;
1279 newname.dont_free = 1;
1281 assert (GL(dl_rtld_map).l_libname->next == NULL);
1282 GL(dl_rtld_map).l_libname->next = &newname;
1284 /* The ld.so must be relocated since otherwise loading audit modules
1285 will fail since they reuse the very same ld.so. */
1286 assert (GL(dl_rtld_map).l_relocated);
1288 if (! rtld_is_main)
1290 /* Extract the contents of the dynamic section for easy access. */
1291 elf_get_dynamic_info (main_map, NULL);
1292 /* Set up our cache of pointers into the hash table. */
1293 _dl_setup_hash (main_map);
1296 if (__builtin_expect (mode, normal) == verify)
1298 /* We were called just to verify that this is a dynamic
1299 executable using us as the program interpreter. Exit with an
1300 error if we were not able to load the binary or no interpreter
1301 is specified (i.e., this is no dynamically linked binary. */
1302 if (main_map->l_ld == NULL)
1303 _exit (1);
1305 /* We allow here some platform specific code. */
1306 #ifdef DISTINGUISH_LIB_VERSIONS
1307 DISTINGUISH_LIB_VERSIONS;
1308 #endif
1309 _exit (has_interp ? 0 : 2);
1312 struct link_map **first_preload = &GL(dl_rtld_map).l_next;
1313 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1314 /* Set up the data structures for the system-supplied DSO early,
1315 so they can influence _dl_init_paths. */
1316 if (GLRO(dl_sysinfo_dso) != NULL)
1318 /* Do an abridged version of the work _dl_map_object_from_fd would do
1319 to map in the object. It's already mapped and prelinked (and
1320 better be, since it's read-only and so we couldn't relocate it).
1321 We just want our data structures to describe it as if we had just
1322 mapped and relocated it normally. */
1323 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL,
1324 0, LM_ID_BASE);
1325 if (__builtin_expect (l != NULL, 1))
1327 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
1329 l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1330 + GLRO(dl_sysinfo_dso)->e_phoff);
1331 l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1332 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1334 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1335 if (ph->p_type == PT_DYNAMIC)
1337 l->l_ld = (void *) ph->p_vaddr;
1338 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1340 else if (ph->p_type == PT_LOAD)
1342 if (! l->l_addr)
1343 l->l_addr = ph->p_vaddr;
1344 if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1345 l->l_map_end = ph->p_vaddr + ph->p_memsz;
1346 if ((ph->p_flags & PF_X)
1347 && ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1348 l->l_text_end = ph->p_vaddr + ph->p_memsz;
1350 else
1351 /* There must be no TLS segment. */
1352 assert (ph->p_type != PT_TLS);
1354 l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1355 l->l_addr = l->l_map_start - l->l_addr;
1356 l->l_map_end += l->l_addr;
1357 l->l_text_end += l->l_addr;
1358 l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1359 elf_get_dynamic_info (l, dyn_temp);
1360 _dl_setup_hash (l);
1361 l->l_relocated = 1;
1363 /* Initialize l_local_scope to contain just this map. This allows
1364 the use of dl_lookup_symbol_x to resolve symbols within the vdso.
1365 So we create a single entry list pointing to l_real as its only
1366 element */
1367 l->l_local_scope[0]->r_nlist = 1;
1368 l->l_local_scope[0]->r_list = &l->l_real;
1370 /* Now that we have the info handy, use the DSO image's soname
1371 so this object can be looked up by name. Note that we do not
1372 set l_name here. That field gives the file name of the DSO,
1373 and this DSO is not associated with any file. */
1374 if (l->l_info[DT_SONAME] != NULL)
1376 /* Work around a kernel problem. The kernel cannot handle
1377 addresses in the vsyscall DSO pages in writev() calls. */
1378 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1379 + l->l_info[DT_SONAME]->d_un.d_val);
1380 size_t len = strlen (dsoname);
1381 char *copy = malloc (len);
1382 if (copy == NULL)
1383 _dl_fatal_printf ("out of memory\n");
1384 l->l_libname->name = memcpy (copy, dsoname, len);
1387 /* Add the vDSO to the object list. */
1388 _dl_add_to_namespace_list (l, LM_ID_BASE);
1390 /* Rearrange the list so this DSO appears after rtld_map. */
1391 assert (l->l_next == NULL);
1392 assert (l->l_prev == main_map);
1393 GL(dl_rtld_map).l_next = l;
1394 l->l_prev = &GL(dl_rtld_map);
1395 first_preload = &l->l_next;
1397 /* We have a prelinked DSO preloaded by the system. */
1398 GLRO(dl_sysinfo_map) = l;
1399 # ifdef NEED_DL_SYSINFO
1400 if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1401 GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1402 # endif
1405 #endif
1407 #ifdef DL_SYSDEP_OSCHECK
1408 DL_SYSDEP_OSCHECK (dl_fatal);
1409 #endif
1411 /* Initialize the data structures for the search paths for shared
1412 objects. */
1413 _dl_init_paths (library_path);
1415 /* Initialize _r_debug. */
1416 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1417 LM_ID_BASE);
1418 r->r_state = RT_CONSISTENT;
1420 /* Put the link_map for ourselves on the chain so it can be found by
1421 name. Note that at this point the global chain of link maps contains
1422 exactly one element, which is pointed to by dl_loaded. */
1423 if (! GL(dl_rtld_map).l_name)
1424 /* If not invoked directly, the dynamic linker shared object file was
1425 found by the PT_INTERP name. */
1426 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1427 GL(dl_rtld_map).l_type = lt_library;
1428 main_map->l_next = &GL(dl_rtld_map);
1429 GL(dl_rtld_map).l_prev = main_map;
1430 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1431 ++GL(dl_load_adds);
1433 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1434 to not using bias for non-prelinked PIEs and libraries
1435 and using it for executables or prelinked PIEs or libraries. */
1436 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1437 GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
1439 /* Set up the program header information for the dynamic linker
1440 itself. It is needed in the dl_iterate_phdr() callbacks. */
1441 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1442 ElfW(Phdr) *rtld_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1443 + rtld_ehdr->e_phoff);
1444 GL(dl_rtld_map).l_phdr = rtld_phdr;
1445 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1448 /* PT_GNU_RELRO is usually the last phdr. */
1449 size_t cnt = rtld_ehdr->e_phnum;
1450 while (cnt-- > 0)
1451 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1453 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1454 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1455 break;
1458 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1459 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1460 /* Assign a module ID. Do this before loading any audit modules. */
1461 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1463 /* If we have auditing DSOs to load, do it now. */
1464 if (__builtin_expect (audit_list != NULL, 0))
1466 /* Iterate over all entries in the list. The order is important. */
1467 struct audit_ifaces *last_audit = NULL;
1468 struct audit_list *al = audit_list->next;
1470 /* Since we start using the auditing DSOs right away we need to
1471 initialize the data structures now. */
1472 tcbp = init_tls ();
1474 /* Initialize security features. We need to do it this early
1475 since otherwise the constructors of the audit libraries will
1476 use different values (especially the pointer guard) and will
1477 fail later on. */
1478 security_init ();
1482 int tls_idx = GL(dl_tls_max_dtv_idx);
1484 /* Now it is time to determine the layout of the static TLS
1485 block and allocate it for the initial thread. Note that we
1486 always allocate the static block, we never defer it even if
1487 no DF_STATIC_TLS bit is set. The reason is that we know
1488 glibc will use the static model. */
1489 struct dlmopen_args dlmargs;
1490 dlmargs.fname = al->name;
1491 dlmargs.map = NULL;
1493 const char *objname;
1494 const char *err_str = NULL;
1495 bool malloced;
1496 (void) _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit,
1497 &dlmargs);
1498 if (__builtin_expect (err_str != NULL, 0))
1500 not_loaded:
1501 _dl_error_printf ("\
1502 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
1503 al->name, err_str);
1504 if (malloced)
1505 free ((char *) err_str);
1507 else
1509 struct lookup_args largs;
1510 largs.name = "la_version";
1511 largs.map = dlmargs.map;
1513 /* Check whether the interface version matches. */
1514 (void) _dl_catch_error (&objname, &err_str, &malloced,
1515 lookup_doit, &largs);
1517 unsigned int (*laversion) (unsigned int);
1518 unsigned int lav;
1519 if (err_str == NULL
1520 && (laversion = largs.result) != NULL
1521 && (lav = laversion (LAV_CURRENT)) > 0
1522 && lav <= LAV_CURRENT)
1524 /* Allocate structure for the callback function pointers.
1525 This call can never fail. */
1526 union
1528 struct audit_ifaces ifaces;
1529 #define naudit_ifaces 8
1530 void (*fptr[naudit_ifaces]) (void);
1531 } *newp = malloc (sizeof (*newp));
1533 /* Names of the auditing interfaces. All in one
1534 long string. */
1535 static const char audit_iface_names[] =
1536 "la_activity\0"
1537 "la_objsearch\0"
1538 "la_objopen\0"
1539 "la_preinit\0"
1540 #if __ELF_NATIVE_CLASS == 32
1541 "la_symbind32\0"
1542 #elif __ELF_NATIVE_CLASS == 64
1543 "la_symbind64\0"
1544 #else
1545 # error "__ELF_NATIVE_CLASS must be defined"
1546 #endif
1547 #define STRING(s) __STRING (s)
1548 "la_" STRING (ARCH_LA_PLTENTER) "\0"
1549 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
1550 "la_objclose\0";
1551 unsigned int cnt = 0;
1552 const char *cp = audit_iface_names;
1555 largs.name = cp;
1556 (void) _dl_catch_error (&objname, &err_str, &malloced,
1557 lookup_doit, &largs);
1559 /* Store the pointer. */
1560 if (err_str == NULL && largs.result != NULL)
1562 newp->fptr[cnt] = largs.result;
1564 /* The dynamic linker link map is statically
1565 allocated, initialize the data now. */
1566 GL(dl_rtld_map).l_audit[cnt].cookie
1567 = (intptr_t) &GL(dl_rtld_map);
1569 else
1570 newp->fptr[cnt] = NULL;
1571 ++cnt;
1573 cp = (char *) rawmemchr (cp, '\0') + 1;
1575 while (*cp != '\0');
1576 assert (cnt == naudit_ifaces);
1578 /* Now append the new auditing interface to the list. */
1579 newp->ifaces.next = NULL;
1580 if (last_audit == NULL)
1581 last_audit = GLRO(dl_audit) = &newp->ifaces;
1582 else
1583 last_audit = last_audit->next = &newp->ifaces;
1584 ++GLRO(dl_naudit);
1586 /* Mark the DSO as being used for auditing. */
1587 dlmargs.map->l_auditing = 1;
1589 else
1591 /* We cannot use the DSO, it does not have the
1592 appropriate interfaces or it expects something
1593 more recent. */
1594 #ifndef NDEBUG
1595 Lmid_t ns = dlmargs.map->l_ns;
1596 #endif
1597 _dl_close (dlmargs.map);
1599 /* Make sure the namespace has been cleared entirely. */
1600 assert (GL(dl_ns)[ns]._ns_loaded == NULL);
1601 assert (GL(dl_ns)[ns]._ns_nloaded == 0);
1603 GL(dl_tls_max_dtv_idx) = tls_idx;
1604 goto not_loaded;
1608 al = al->next;
1610 while (al != audit_list->next);
1612 /* If we have any auditing modules, announce that we already
1613 have two objects loaded. */
1614 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1616 struct link_map *ls[2] = { main_map, &GL(dl_rtld_map) };
1618 for (unsigned int outer = 0; outer < 2; ++outer)
1620 struct audit_ifaces *afct = GLRO(dl_audit);
1621 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1623 if (afct->objopen != NULL)
1625 ls[outer]->l_audit[cnt].bindflags
1626 = afct->objopen (ls[outer], LM_ID_BASE,
1627 &ls[outer]->l_audit[cnt].cookie);
1629 ls[outer]->l_audit_any_plt
1630 |= ls[outer]->l_audit[cnt].bindflags != 0;
1633 afct = afct->next;
1639 /* Set up debugging before the debugger is notified for the first time. */
1640 #ifdef ELF_MACHINE_DEBUG_SETUP
1641 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1642 ELF_MACHINE_DEBUG_SETUP (main_map, r);
1643 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1644 #else
1645 if (main_map->l_info[DT_DEBUG] != NULL)
1646 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1647 with the run-time address of the r_debug structure */
1648 main_map->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1650 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1651 case you run gdb on the dynamic linker directly. */
1652 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1653 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1654 #endif
1656 /* We start adding objects. */
1657 r->r_state = RT_ADD;
1658 _dl_debug_state ();
1660 /* Auditing checkpoint: we are ready to signal that the initial map
1661 is being constructed. */
1662 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1664 struct audit_ifaces *afct = GLRO(dl_audit);
1665 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1667 if (afct->activity != NULL)
1668 afct->activity (&main_map->l_audit[cnt].cookie, LA_ACT_ADD);
1670 afct = afct->next;
1674 /* We have two ways to specify objects to preload: via environment
1675 variable and via the file /etc/ld.so.preload. The latter can also
1676 be used when security is enabled. */
1677 assert (*first_preload == NULL);
1678 struct link_map **preloads = NULL;
1679 unsigned int npreloads = 0;
1681 if (__builtin_expect (preloadlist != NULL, 0))
1683 /* The LD_PRELOAD environment variable gives list of libraries
1684 separated by white space or colons that are loaded before the
1685 executable's dependencies and prepended to the global scope
1686 list. If the binary is running setuid all elements
1687 containing a '/' are ignored since it is insecure. */
1688 char *list = strdupa (preloadlist);
1689 char *p;
1691 HP_TIMING_NOW (start);
1693 /* Prevent optimizing strsep. Speed is not important here. */
1694 while ((p = (strsep) (&list, " :")) != NULL)
1695 if (p[0] != '\0'
1696 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1697 || strchr (p, '/') == NULL))
1698 npreloads += do_preload (p, main_map, "LD_PRELOAD");
1700 HP_TIMING_NOW (stop);
1701 HP_TIMING_DIFF (diff, start, stop);
1702 HP_TIMING_ACCUM_NT (load_time, diff);
1705 /* There usually is no ld.so.preload file, it should only be used
1706 for emergencies and testing. So the open call etc should usually
1707 fail. Using access() on a non-existing file is faster than using
1708 open(). So we do this first. If it succeeds we do almost twice
1709 the work but this does not matter, since it is not for production
1710 use. */
1711 static const char preload_file[] = "/etc/ld.so.preload";
1712 if (__builtin_expect (__access (preload_file, R_OK) == 0, 0))
1714 /* Read the contents of the file. */
1715 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1716 PROT_READ | PROT_WRITE);
1717 if (__builtin_expect (file != MAP_FAILED, 0))
1719 /* Parse the file. It contains names of libraries to be loaded,
1720 separated by white spaces or `:'. It may also contain
1721 comments introduced by `#'. */
1722 char *problem;
1723 char *runp;
1724 size_t rest;
1726 /* Eliminate comments. */
1727 runp = file;
1728 rest = file_size;
1729 while (rest > 0)
1731 char *comment = memchr (runp, '#', rest);
1732 if (comment == NULL)
1733 break;
1735 rest -= comment - runp;
1737 *comment = ' ';
1738 while (--rest > 0 && *++comment != '\n');
1741 /* We have one problematic case: if we have a name at the end of
1742 the file without a trailing terminating characters, we cannot
1743 place the \0. Handle the case separately. */
1744 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1745 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1747 problem = &file[file_size];
1748 while (problem > file && problem[-1] != ' '
1749 && problem[-1] != '\t'
1750 && problem[-1] != '\n' && problem[-1] != ':')
1751 --problem;
1753 if (problem > file)
1754 problem[-1] = '\0';
1756 else
1758 problem = NULL;
1759 file[file_size - 1] = '\0';
1762 HP_TIMING_NOW (start);
1764 if (file != problem)
1766 char *p;
1767 runp = file;
1768 while ((p = strsep (&runp, ": \t\n")) != NULL)
1769 if (p[0] != '\0')
1770 npreloads += do_preload (p, main_map, preload_file);
1773 if (problem != NULL)
1775 char *p = strndupa (problem, file_size - (problem - file));
1777 npreloads += do_preload (p, main_map, preload_file);
1780 HP_TIMING_NOW (stop);
1781 HP_TIMING_DIFF (diff, start, stop);
1782 HP_TIMING_ACCUM_NT (load_time, diff);
1784 /* We don't need the file anymore. */
1785 __munmap (file, file_size);
1789 if (__builtin_expect (*first_preload != NULL, 0))
1791 /* Set up PRELOADS with a vector of the preloaded libraries. */
1792 struct link_map *l = *first_preload;
1793 preloads = __alloca (npreloads * sizeof preloads[0]);
1794 i = 0;
1797 preloads[i++] = l;
1798 l = l->l_next;
1799 } while (l);
1800 assert (i == npreloads);
1803 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1804 specified some libraries to load, these are inserted before the actual
1805 dependencies in the executable's searchlist for symbol resolution. */
1806 HP_TIMING_NOW (start);
1807 _dl_map_object_deps (main_map, preloads, npreloads, mode == trace, 0);
1808 HP_TIMING_NOW (stop);
1809 HP_TIMING_DIFF (diff, start, stop);
1810 HP_TIMING_ACCUM_NT (load_time, diff);
1812 /* Mark all objects as being in the global scope. */
1813 for (i = main_map->l_searchlist.r_nlist; i > 0; )
1814 main_map->l_searchlist.r_list[--i]->l_global = 1;
1816 /* Remove _dl_rtld_map from the chain. */
1817 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1818 if (GL(dl_rtld_map).l_next != NULL)
1819 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1821 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1822 if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1823 break;
1825 bool rtld_multiple_ref = false;
1826 if (__builtin_expect (i < main_map->l_searchlist.r_nlist, 1))
1828 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1829 put it back in the list of visible objects. We insert it into the
1830 chain in symbol search order because gdb uses the chain's order as
1831 its symbol search order. */
1832 rtld_multiple_ref = true;
1834 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1835 if (__builtin_expect (mode, normal) == normal)
1837 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1838 ? main_map->l_searchlist.r_list[i + 1]
1839 : NULL);
1840 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1841 if (GLRO(dl_sysinfo_map) != NULL
1842 && GL(dl_rtld_map).l_prev->l_next == GLRO(dl_sysinfo_map)
1843 && GL(dl_rtld_map).l_next != GLRO(dl_sysinfo_map))
1844 GL(dl_rtld_map).l_prev = GLRO(dl_sysinfo_map);
1845 #endif
1847 else
1848 /* In trace mode there might be an invisible object (which we
1849 could not find) after the previous one in the search list.
1850 In this case it doesn't matter much where we put the
1851 interpreter object, so we just initialize the list pointer so
1852 that the assertion below holds. */
1853 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1855 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1856 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1857 if (GL(dl_rtld_map).l_next != NULL)
1859 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1860 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1864 /* Now let us see whether all libraries are available in the
1865 versions we need. */
1867 struct version_check_args args;
1868 args.doexit = mode == normal;
1869 args.dotrace = mode == trace;
1870 _dl_receive_error (print_missing_version, version_check_doit, &args);
1873 /* We do not initialize any of the TLS functionality unless any of the
1874 initial modules uses TLS. This makes dynamic loading of modules with
1875 TLS impossible, but to support it requires either eagerly doing setup
1876 now or lazily doing it later. Doing it now makes us incompatible with
1877 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1878 used. Trying to do it lazily is too hairy to try when there could be
1879 multiple threads (from a non-TLS-using libpthread). */
1880 bool was_tls_init_tp_called = tls_init_tp_called;
1881 if (tcbp == NULL)
1882 tcbp = init_tls ();
1884 if (__builtin_expect (audit_list == NULL, 1))
1885 /* Initialize security features. But only if we have not done it
1886 earlier. */
1887 security_init ();
1889 if (__builtin_expect (mode, normal) != normal)
1891 /* We were run just to list the shared libraries. It is
1892 important that we do this before real relocation, because the
1893 functions we call below for output may no longer work properly
1894 after relocation. */
1895 struct link_map *l;
1897 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1899 struct r_scope_elem *scope = &main_map->l_searchlist;
1901 for (i = 0; i < scope->r_nlist; i++)
1903 l = scope->r_list [i];
1904 if (l->l_faked)
1906 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1907 continue;
1909 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1910 GLRO(dl_trace_prelink_map) = l;
1911 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1912 l->l_libname->name[0] ? l->l_libname->name
1913 : rtld_progname ?: "<main program>",
1914 l->l_name[0] ? l->l_name
1915 : rtld_progname ?: "<main program>",
1916 (int) sizeof l->l_map_start * 2,
1917 (size_t) l->l_map_start,
1918 (int) sizeof l->l_addr * 2,
1919 (size_t) l->l_addr);
1921 if (l->l_tls_modid)
1922 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1923 (int) sizeof l->l_tls_offset * 2,
1924 (size_t) l->l_tls_offset);
1925 else
1926 _dl_printf ("\n");
1929 else if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
1931 /* Look through the dependencies of the main executable
1932 and determine which of them is not actually
1933 required. */
1934 struct link_map *l = main_map;
1936 /* Relocate the main executable. */
1937 struct relocate_args args = { .l = l,
1938 .reloc_mode = (GLRO(dl_lazy)
1939 ? RTLD_LAZY : 0) };
1940 _dl_receive_error (print_unresolved, relocate_doit, &args);
1942 /* This loop depends on the dependencies of the executable to
1943 correspond in number and order to the DT_NEEDED entries. */
1944 ElfW(Dyn) *dyn = main_map->l_ld;
1945 bool first = true;
1946 while (dyn->d_tag != DT_NULL)
1948 if (dyn->d_tag == DT_NEEDED)
1950 l = l->l_next;
1952 if (!l->l_used)
1954 if (first)
1956 _dl_printf ("Unused direct dependencies:\n");
1957 first = false;
1960 _dl_printf ("\t%s\n", l->l_name);
1964 ++dyn;
1967 _exit (first != true);
1969 else if (! main_map->l_info[DT_NEEDED])
1970 _dl_printf ("\tstatically linked\n");
1971 else
1973 for (l = main_map->l_next; l; l = l->l_next)
1974 if (l->l_faked)
1975 /* The library was not found. */
1976 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1977 else if (strcmp (l->l_libname->name, l->l_name) == 0)
1978 _dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
1979 (int) sizeof l->l_map_start * 2,
1980 (size_t) l->l_map_start);
1981 else
1982 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1983 l->l_name, (int) sizeof l->l_map_start * 2,
1984 (size_t) l->l_map_start);
1987 if (__builtin_expect (mode, trace) != trace)
1988 for (i = 1; i < (unsigned int) _dl_argc; ++i)
1990 const ElfW(Sym) *ref = NULL;
1991 ElfW(Addr) loadbase;
1992 lookup_t result;
1994 result = _dl_lookup_symbol_x (INTUSE(_dl_argv)[i], main_map,
1995 &ref, main_map->l_scope,
1996 NULL, ELF_RTYPE_CLASS_PLT,
1997 DL_LOOKUP_ADD_DEPENDENCY, NULL);
1999 loadbase = LOOKUP_VALUE_ADDRESS (result);
2001 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
2002 INTUSE(_dl_argv)[i],
2003 (int) sizeof ref->st_value * 2,
2004 (size_t) ref->st_value,
2005 (int) sizeof loadbase * 2, (size_t) loadbase);
2007 else
2009 /* If LD_WARN is set, warn about undefined symbols. */
2010 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
2012 /* We have to do symbol dependency testing. */
2013 struct relocate_args args;
2014 struct link_map *l;
2016 args.reloc_mode = GLRO(dl_lazy) ? RTLD_LAZY : 0;
2018 l = main_map;
2019 while (l->l_next != NULL)
2020 l = l->l_next;
2023 if (l != &GL(dl_rtld_map) && ! l->l_faked)
2025 args.l = l;
2026 _dl_receive_error (print_unresolved, relocate_doit,
2027 &args);
2029 l = l->l_prev;
2031 while (l != NULL);
2033 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
2034 && rtld_multiple_ref)
2036 /* Mark the link map as not yet relocated again. */
2037 GL(dl_rtld_map).l_relocated = 0;
2038 _dl_relocate_object (&GL(dl_rtld_map),
2039 main_map->l_scope, 0, 0);
2042 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
2043 if (version_info)
2045 /* Print more information. This means here, print information
2046 about the versions needed. */
2047 int first = 1;
2048 struct link_map *map;
2050 for (map = main_map; map != NULL; map = map->l_next)
2052 const char *strtab;
2053 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
2054 ElfW(Verneed) *ent;
2056 if (dyn == NULL)
2057 continue;
2059 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
2060 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
2062 if (first)
2064 _dl_printf ("\n\tVersion information:\n");
2065 first = 0;
2068 _dl_printf ("\t%s:\n",
2069 map->l_name[0] ? map->l_name : rtld_progname);
2071 while (1)
2073 ElfW(Vernaux) *aux;
2074 struct link_map *needed;
2076 needed = find_needed (strtab + ent->vn_file);
2077 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
2079 while (1)
2081 const char *fname = NULL;
2083 if (needed != NULL
2084 && match_version (strtab + aux->vna_name,
2085 needed))
2086 fname = needed->l_name;
2088 _dl_printf ("\t\t%s (%s) %s=> %s\n",
2089 strtab + ent->vn_file,
2090 strtab + aux->vna_name,
2091 aux->vna_flags & VER_FLG_WEAK
2092 ? "[WEAK] " : "",
2093 fname ?: "not found");
2095 if (aux->vna_next == 0)
2096 /* No more symbols. */
2097 break;
2099 /* Next symbol. */
2100 aux = (ElfW(Vernaux) *) ((char *) aux
2101 + aux->vna_next);
2104 if (ent->vn_next == 0)
2105 /* No more dependencies. */
2106 break;
2108 /* Next dependency. */
2109 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
2115 _exit (0);
2118 if (main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]
2119 && ! __builtin_expect (GLRO(dl_profile) != NULL, 0)
2120 && ! __builtin_expect (GLRO(dl_dynamic_weak), 0))
2122 ElfW(Lib) *liblist, *liblistend;
2123 struct link_map **r_list, **r_listend, *l;
2124 const char *strtab = (const void *) D_PTR (main_map, l_info[DT_STRTAB]);
2126 assert (main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
2127 liblist = (ElfW(Lib) *)
2128 main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
2129 liblistend = (ElfW(Lib) *)
2130 ((char *) liblist +
2131 main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
2132 r_list = main_map->l_searchlist.r_list;
2133 r_listend = r_list + main_map->l_searchlist.r_nlist;
2135 for (; r_list < r_listend && liblist < liblistend; r_list++)
2137 l = *r_list;
2139 if (l == main_map)
2140 continue;
2142 /* If the library is not mapped where it should, fail. */
2143 if (l->l_addr)
2144 break;
2146 /* Next, check if checksum matches. */
2147 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
2148 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
2149 != liblist->l_checksum)
2150 break;
2152 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
2153 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
2154 != liblist->l_time_stamp)
2155 break;
2157 if (! _dl_name_match_p (strtab + liblist->l_name, l))
2158 break;
2160 ++liblist;
2164 if (r_list == r_listend && liblist == liblistend)
2165 prelinked = true;
2167 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
2168 _dl_debug_printf ("\nprelink checking: %s\n",
2169 prelinked ? "ok" : "failed");
2173 /* Now set up the variable which helps the assembler startup code. */
2174 GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
2176 /* Save the information about the original global scope list since
2177 we need it in the memory handling later. */
2178 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
2180 if (prelinked)
2182 if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
2184 ElfW(Rela) *conflict, *conflictend;
2185 #ifndef HP_TIMING_NONAVAIL
2186 hp_timing_t start;
2187 hp_timing_t stop;
2188 #endif
2190 HP_TIMING_NOW (start);
2191 assert (main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
2192 conflict = (ElfW(Rela) *)
2193 main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
2194 conflictend = (ElfW(Rela) *)
2195 ((char *) conflict
2196 + main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
2197 _dl_resolve_conflicts (main_map, conflict, conflictend);
2198 HP_TIMING_NOW (stop);
2199 HP_TIMING_DIFF (relocate_time, start, stop);
2203 /* Mark all the objects so we know they have been already relocated. */
2204 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2206 l->l_relocated = 1;
2207 if (l->l_relro_size)
2208 _dl_protect_relro (l);
2210 /* Add object to slot information data if necessasy. */
2211 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2212 _dl_add_to_slotinfo (l);
2215 else
2217 /* Now we have all the objects loaded. Relocate them all except for
2218 the dynamic linker itself. We do this in reverse order so that copy
2219 relocs of earlier objects overwrite the data written by later
2220 objects. We do not re-relocate the dynamic linker itself in this
2221 loop because that could result in the GOT entries for functions we
2222 call being changed, and that would break us. It is safe to relocate
2223 the dynamic linker out of order because it has no copy relocs (we
2224 know that because it is self-contained). */
2226 int consider_profiling = GLRO(dl_profile) != NULL;
2227 #ifndef HP_TIMING_NONAVAIL
2228 hp_timing_t start;
2229 hp_timing_t stop;
2230 #endif
2232 /* If we are profiling we also must do lazy reloaction. */
2233 GLRO(dl_lazy) |= consider_profiling;
2235 struct link_map *l = main_map;
2236 while (l->l_next)
2237 l = l->l_next;
2239 HP_TIMING_NOW (start);
2242 /* While we are at it, help the memory handling a bit. We have to
2243 mark some data structures as allocated with the fake malloc()
2244 implementation in ld.so. */
2245 struct libname_list *lnp = l->l_libname->next;
2247 while (__builtin_expect (lnp != NULL, 0))
2249 lnp->dont_free = 1;
2250 lnp = lnp->next;
2253 if (l != &GL(dl_rtld_map))
2254 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy) ? RTLD_LAZY : 0,
2255 consider_profiling);
2257 /* Add object to slot information data if necessasy. */
2258 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2259 _dl_add_to_slotinfo (l);
2261 l = l->l_prev;
2263 while (l);
2264 HP_TIMING_NOW (stop);
2266 HP_TIMING_DIFF (relocate_time, start, stop);
2268 /* Now enable profiling if needed. Like the previous call,
2269 this has to go here because the calls it makes should use the
2270 rtld versions of the functions (particularly calloc()), but it
2271 needs to have _dl_profile_map set up by the relocator. */
2272 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
2273 /* We must prepare the profiling. */
2274 _dl_start_profile ();
2277 #ifndef NONTLS_INIT_TP
2278 # define NONTLS_INIT_TP do { } while (0)
2279 #endif
2281 if (!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2282 ++GL(dl_tls_generation);
2284 /* Now that we have completed relocation, the initializer data
2285 for the TLS blocks has its final values and we can copy them
2286 into the main thread's TLS area, which we allocated above. */
2287 _dl_allocate_tls_init (tcbp);
2289 /* And finally install it for the main thread. If ld.so itself uses
2290 TLS we know the thread pointer was initialized earlier. */
2291 if (! tls_init_tp_called)
2293 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
2294 if (__builtin_expect (lossage != NULL, 0))
2295 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2296 lossage);
2299 /* Remember the last search directory added at startup, now that
2300 malloc will no longer be the one from dl-minimal.c. */
2301 GLRO(dl_init_all_dirs) = GL(dl_all_dirs);
2303 if (! prelinked && rtld_multiple_ref)
2305 /* There was an explicit ref to the dynamic linker as a shared lib.
2306 Re-relocate ourselves with user-controlled symbol definitions.
2308 We must do this after TLS initialization in case after this
2309 re-relocation, we might call a user-supplied function
2310 (e.g. calloc from _dl_relocate_object) that uses TLS data. */
2312 #ifndef HP_TIMING_NONAVAIL
2313 hp_timing_t start;
2314 hp_timing_t stop;
2315 hp_timing_t add;
2316 #endif
2318 HP_TIMING_NOW (start);
2319 /* Mark the link map as not yet relocated again. */
2320 GL(dl_rtld_map).l_relocated = 0;
2321 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2322 HP_TIMING_NOW (stop);
2323 HP_TIMING_DIFF (add, start, stop);
2324 HP_TIMING_ACCUM_NT (relocate_time, add);
2327 /* Do any necessary cleanups for the startup OS interface code.
2328 We do these now so that no calls are made after rtld re-relocation
2329 which might be resolved to different functions than we expect.
2330 We cannot do this before relocating the other objects because
2331 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2332 _dl_sysdep_start_cleanup ();
2334 #ifdef SHARED
2335 /* Auditing checkpoint: we have added all objects. */
2336 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
2338 struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2339 /* Do not call the functions for any auditing object. */
2340 if (head->l_auditing == 0)
2342 struct audit_ifaces *afct = GLRO(dl_audit);
2343 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2345 if (afct->activity != NULL)
2346 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
2348 afct = afct->next;
2352 #endif
2354 /* Notify the debugger all new objects are now ready to go. We must re-get
2355 the address since by now the variable might be in another object. */
2356 r = _dl_debug_initialize (0, LM_ID_BASE);
2357 r->r_state = RT_CONSISTENT;
2358 _dl_debug_state ();
2360 #ifndef MAP_COPY
2361 /* We must munmap() the cache file. */
2362 _dl_unload_cache ();
2363 #endif
2365 /* Once we return, _dl_sysdep_start will invoke
2366 the DT_INIT functions and then *USER_ENTRY. */
2369 /* This is a little helper function for resolving symbols while
2370 tracing the binary. */
2371 static void
2372 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2373 const char *errstring)
2375 if (objname[0] == '\0')
2376 objname = rtld_progname ?: "<main program>";
2377 _dl_error_printf ("%s (%s)\n", errstring, objname);
2380 /* This is a little helper function for resolving symbols while
2381 tracing the binary. */
2382 static void
2383 print_missing_version (int errcode __attribute__ ((unused)),
2384 const char *objname, const char *errstring)
2386 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
2387 objname, errstring);
2390 /* Nonzero if any of the debugging options is enabled. */
2391 static int any_debug attribute_relro;
2393 /* Process the string given as the parameter which explains which debugging
2394 options are enabled. */
2395 static void
2396 process_dl_debug (const char *dl_debug)
2398 /* When adding new entries make sure that the maximal length of a name
2399 is correctly handled in the LD_DEBUG_HELP code below. */
2400 static const struct
2402 unsigned char len;
2403 const char name[10];
2404 const char helptext[41];
2405 unsigned short int mask;
2406 } debopts[] =
2408 #define LEN_AND_STR(str) sizeof (str) - 1, str
2409 { LEN_AND_STR ("libs"), "display library search paths",
2410 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2411 { LEN_AND_STR ("reloc"), "display relocation processing",
2412 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2413 { LEN_AND_STR ("files"), "display progress for input file",
2414 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2415 { LEN_AND_STR ("symbols"), "display symbol table processing",
2416 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2417 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2418 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2419 { LEN_AND_STR ("versions"), "display version dependencies",
2420 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2421 { LEN_AND_STR ("all"), "all previous options combined",
2422 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2423 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2424 { LEN_AND_STR ("statistics"), "display relocation statistics",
2425 DL_DEBUG_STATISTICS },
2426 { LEN_AND_STR ("unused"), "determined unused DSOs",
2427 DL_DEBUG_UNUSED },
2428 { LEN_AND_STR ("help"), "display this help message and exit",
2429 DL_DEBUG_HELP },
2431 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2433 /* Skip separating white spaces and commas. */
2434 while (*dl_debug != '\0')
2436 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2438 size_t cnt;
2439 size_t len = 1;
2441 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2442 && dl_debug[len] != ',' && dl_debug[len] != ':')
2443 ++len;
2445 for (cnt = 0; cnt < ndebopts; ++cnt)
2446 if (debopts[cnt].len == len
2447 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
2449 GLRO(dl_debug_mask) |= debopts[cnt].mask;
2450 any_debug = 1;
2451 break;
2454 if (cnt == ndebopts)
2456 /* Display a warning and skip everything until next
2457 separator. */
2458 char *copy = strndupa (dl_debug, len);
2459 _dl_error_printf ("\
2460 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2463 dl_debug += len;
2464 continue;
2467 ++dl_debug;
2470 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
2472 size_t cnt;
2474 _dl_printf ("\
2475 Valid options for the LD_DEBUG environment variable are:\n\n");
2477 for (cnt = 0; cnt < ndebopts; ++cnt)
2478 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2479 " " + debopts[cnt].len - 3,
2480 debopts[cnt].helptext);
2482 _dl_printf ("\n\
2483 To direct the debugging output into a file instead of standard output\n\
2484 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2485 _exit (0);
2489 static void
2490 process_dl_audit (char *str)
2492 /* The parameter is a colon separated list of DSO names. */
2493 char *p;
2495 while ((p = (strsep) (&str, ":")) != NULL)
2496 if (p[0] != '\0'
2497 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
2498 || strchr (p, '/') == NULL))
2500 /* This is using the local malloc, not the system malloc. The
2501 memory can never be freed. */
2502 struct audit_list *newp = malloc (sizeof (*newp));
2503 newp->name = p;
2505 if (audit_list == NULL)
2506 audit_list = newp->next = newp;
2507 else
2509 newp->next = audit_list->next;
2510 audit_list = audit_list->next = newp;
2515 /* Process all environments variables the dynamic linker must recognize.
2516 Since all of them start with `LD_' we are a bit smarter while finding
2517 all the entries. */
2518 extern char **_environ attribute_hidden;
2521 static void
2522 process_envvars (enum mode *modep)
2524 char **runp = _environ;
2525 char *envline;
2526 enum mode mode = normal;
2527 char *debug_output = NULL;
2529 /* This is the default place for profiling data file. */
2530 GLRO(dl_profile_output)
2531 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2533 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2535 size_t len = 0;
2537 while (envline[len] != '\0' && envline[len] != '=')
2538 ++len;
2540 if (envline[len] != '=')
2541 /* This is a "LD_" variable at the end of the string without
2542 a '=' character. Ignore it since otherwise we will access
2543 invalid memory below. */
2544 continue;
2546 switch (len)
2548 case 4:
2549 /* Warning level, verbose or not. */
2550 if (memcmp (envline, "WARN", 4) == 0)
2551 GLRO(dl_verbose) = envline[5] != '\0';
2552 break;
2554 case 5:
2555 /* Debugging of the dynamic linker? */
2556 if (memcmp (envline, "DEBUG", 5) == 0)
2558 process_dl_debug (&envline[6]);
2559 break;
2561 if (memcmp (envline, "AUDIT", 5) == 0)
2562 process_dl_audit (&envline[6]);
2563 break;
2565 case 7:
2566 /* Print information about versions. */
2567 if (memcmp (envline, "VERBOSE", 7) == 0)
2569 version_info = envline[8] != '\0';
2570 break;
2573 /* List of objects to be preloaded. */
2574 if (memcmp (envline, "PRELOAD", 7) == 0)
2576 preloadlist = &envline[8];
2577 break;
2580 /* Which shared object shall be profiled. */
2581 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2582 GLRO(dl_profile) = &envline[8];
2583 break;
2585 case 8:
2586 /* Do we bind early? */
2587 if (memcmp (envline, "BIND_NOW", 8) == 0)
2589 GLRO(dl_lazy) = envline[9] == '\0';
2590 break;
2592 if (memcmp (envline, "BIND_NOT", 8) == 0)
2593 GLRO(dl_bind_not) = envline[9] != '\0';
2594 break;
2596 case 9:
2597 /* Test whether we want to see the content of the auxiliary
2598 array passed up from the kernel. */
2599 if (!INTUSE(__libc_enable_secure)
2600 && memcmp (envline, "SHOW_AUXV", 9) == 0)
2601 _dl_show_auxv ();
2602 break;
2604 case 10:
2605 /* Mask for the important hardware capabilities. */
2606 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2607 GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2608 0, 0);
2609 break;
2611 case 11:
2612 /* Path where the binary is found. */
2613 if (!INTUSE(__libc_enable_secure)
2614 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2615 GLRO(dl_origin_path) = &envline[12];
2616 break;
2618 case 12:
2619 /* The library search path. */
2620 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2622 library_path = &envline[13];
2623 break;
2626 /* Where to place the profiling data file. */
2627 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2629 debug_output = &envline[13];
2630 break;
2633 if (!INTUSE(__libc_enable_secure)
2634 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2635 GLRO(dl_dynamic_weak) = 1;
2636 break;
2638 case 13:
2639 /* We might have some extra environment variable with length 13
2640 to handle. */
2641 #ifdef EXTRA_LD_ENVVARS_13
2642 EXTRA_LD_ENVVARS_13
2643 #endif
2644 if (!INTUSE(__libc_enable_secure)
2645 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2647 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2648 break;
2651 if (memcmp (envline, "POINTER_GUARD", 13) == 0)
2652 GLRO(dl_pointer_guard) = envline[14] != '0';
2653 break;
2655 case 14:
2656 /* Where to place the profiling data file. */
2657 if (!INTUSE(__libc_enable_secure)
2658 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2659 && envline[15] != '\0')
2660 GLRO(dl_profile_output) = &envline[15];
2661 break;
2663 case 16:
2664 /* The mode of the dynamic linker can be set. */
2665 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2667 mode = trace;
2668 GLRO(dl_verbose) = 1;
2669 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2670 GLRO(dl_trace_prelink) = &envline[17];
2672 break;
2674 case 20:
2675 /* The mode of the dynamic linker can be set. */
2676 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2677 mode = trace;
2678 break;
2680 /* We might have some extra environment variable to handle. This
2681 is tricky due to the pre-processing of the length of the name
2682 in the switch statement here. The code here assumes that added
2683 environment variables have a different length. */
2684 #ifdef EXTRA_LD_ENVVARS
2685 EXTRA_LD_ENVVARS
2686 #endif
2690 /* The caller wants this information. */
2691 *modep = mode;
2693 /* Extra security for SUID binaries. Remove all dangerous environment
2694 variables. */
2695 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2697 static const char unsecure_envvars[] =
2698 #ifdef EXTRA_UNSECURE_ENVVARS
2699 EXTRA_UNSECURE_ENVVARS
2700 #endif
2701 UNSECURE_ENVVARS;
2702 const char *nextp;
2704 nextp = unsecure_envvars;
2707 unsetenv (nextp);
2708 /* We could use rawmemchr but this need not be fast. */
2709 nextp = (char *) (strchr) (nextp, '\0') + 1;
2711 while (*nextp != '\0');
2713 if (__access ("/etc/suid-debug", F_OK) != 0)
2715 unsetenv ("MALLOC_CHECK_");
2716 GLRO(dl_debug_mask) = 0;
2719 if (mode != normal)
2720 _exit (5);
2722 /* If we have to run the dynamic linker in debugging mode and the
2723 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2724 messages to this file. */
2725 else if (any_debug && debug_output != NULL)
2727 #ifdef O_NOFOLLOW
2728 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2729 #else
2730 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2731 #endif
2732 size_t name_len = strlen (debug_output);
2733 char buf[name_len + 12];
2734 char *startp;
2736 buf[name_len + 11] = '\0';
2737 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2738 *--startp = '.';
2739 startp = memcpy (startp - name_len, debug_output, name_len);
2741 GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2742 if (GLRO(dl_debug_fd) == -1)
2743 /* We use standard output if opening the file failed. */
2744 GLRO(dl_debug_fd) = STDOUT_FILENO;
2749 /* Print the various times we collected. */
2750 static void
2751 __attribute ((noinline))
2752 print_statistics (hp_timing_t *rtld_total_timep)
2754 #ifndef HP_TIMING_NONAVAIL
2755 char buf[200];
2756 char *cp;
2757 char *wp;
2759 /* Total time rtld used. */
2760 if (HP_TIMING_AVAIL)
2762 HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2763 _dl_debug_printf ("\nruntime linker statistics:\n"
2764 " total startup time in dynamic loader: %s\n", buf);
2766 /* Print relocation statistics. */
2767 char pbuf[30];
2768 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2769 cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2770 pbuf + sizeof (pbuf), 10, 0);
2771 wp = pbuf;
2772 switch (pbuf + sizeof (pbuf) - cp)
2774 case 3:
2775 *wp++ = *cp++;
2776 case 2:
2777 *wp++ = *cp++;
2778 case 1:
2779 *wp++ = '.';
2780 *wp++ = *cp++;
2782 *wp = '\0';
2783 _dl_debug_printf ("\
2784 time needed for relocation: %s (%s%%)\n", buf, pbuf);
2786 #endif
2788 unsigned long int num_relative_relocations = 0;
2789 for (Lmid_t ns = 0; ns < GL(dl_nns); ++ns)
2791 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2792 continue;
2794 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2796 for (unsigned int i = 0; i < scope->r_nlist; i++)
2798 struct link_map *l = scope->r_list [i];
2800 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2801 num_relative_relocations
2802 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2803 #ifndef ELF_MACHINE_REL_RELATIVE
2804 /* Relative relocations are processed on these architectures if
2805 library is loaded to different address than p_vaddr or
2806 if not prelinked. */
2807 if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2808 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2809 #else
2810 /* On e.g. IA-64 or Alpha, relative relocations are processed
2811 only if library is loaded to different address than p_vaddr. */
2812 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2813 #endif
2814 num_relative_relocations
2815 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2819 _dl_debug_printf (" number of relocations: %lu\n"
2820 " number of relocations from cache: %lu\n"
2821 " number of relative relocations: %lu\n",
2822 GL(dl_num_relocations),
2823 GL(dl_num_cache_relocations),
2824 num_relative_relocations);
2826 #ifndef HP_TIMING_NONAVAIL
2827 /* Time spend while loading the object and the dependencies. */
2828 if (HP_TIMING_AVAIL)
2830 char pbuf[30];
2831 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2832 cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2833 pbuf + sizeof (pbuf), 10, 0);
2834 wp = pbuf;
2835 switch (pbuf + sizeof (pbuf) - cp)
2837 case 3:
2838 *wp++ = *cp++;
2839 case 2:
2840 *wp++ = *cp++;
2841 case 1:
2842 *wp++ = '.';
2843 *wp++ = *cp++;
2845 *wp = '\0';
2846 _dl_debug_printf ("\
2847 time needed to load objects: %s (%s%%)\n",
2848 buf, pbuf);
2850 #endif