Sort sysdeps/powerpc/fpu/libm-test-ulps
[glibc.git] / elf / rtld.c
bloba5b0ab9815f3161fab83b0da5db89d302a6a7bad
1 /* Run time dynamic linker.
2 Copyright (C) 1995-2012 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, see
17 <http://www.gnu.org/licenses/>. */
19 #include <errno.h>
20 #include <dlfcn.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>
27 #include <sys/param.h>
28 #include <sys/stat.h>
29 #include <ldsodefs.h>
30 #include <_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-osinfo.h>
40 #include <dl-procinfo.h>
41 #include <tls.h>
42 #include <stackinfo.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 /* Generally the default presumption without further information is an
126 * executable stack but this is not true for all platforms. */
127 ._dl_stack_flags = DEFAULT_STACK_PERMS,
128 #ifdef _LIBC_REENTRANT
129 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
130 ._dl_load_write_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
131 #endif
132 ._dl_nns = 1,
133 ._dl_ns =
135 [LM_ID_BASE] = { ._ns_unique_sym_table
136 = { .lock = _RTLD_LOCK_RECURSIVE_INITIALIZER } }
139 /* If we would use strong_alias here the compiler would see a
140 non-hidden definition. This would undo the effect of the previous
141 declaration. So spell out was strong_alias does plus add the
142 visibility attribute. */
143 extern struct rtld_global _rtld_local
144 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
147 /* This variable is similar to _rtld_local, but all values are
148 read-only after relocation. */
149 struct rtld_global_ro _rtld_global_ro attribute_relro =
151 /* Get architecture specific initializer. */
152 #include <dl-procinfo.c>
153 #ifdef NEED_DL_SYSINFO
154 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
155 #endif
156 ._dl_debug_fd = STDERR_FILENO,
157 ._dl_use_load_bias = -2,
158 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
159 ._dl_hwcap_mask = HWCAP_IMPORTANT,
160 ._dl_lazy = 1,
161 ._dl_fpu_control = _FPU_DEFAULT,
162 ._dl_pointer_guard = 1,
163 ._dl_pagesize = EXEC_PAGESIZE,
164 ._dl_inhibit_cache = 0,
166 /* Function pointers. */
167 ._dl_debug_printf = _dl_debug_printf,
168 ._dl_catch_error = _dl_catch_error,
169 ._dl_signal_error = _dl_signal_error,
170 ._dl_mcount = _dl_mcount_internal,
171 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
172 ._dl_check_caller = _dl_check_caller,
173 ._dl_open = _dl_open,
174 ._dl_close = _dl_close,
175 ._dl_tls_get_addr_soft = _dl_tls_get_addr_soft,
176 #ifdef HAVE_DL_DISCOVER_OSVERSION
177 ._dl_discover_osversion = _dl_discover_osversion
178 #endif
180 /* If we would use strong_alias here the compiler would see a
181 non-hidden definition. This would undo the effect of the previous
182 declaration. So spell out was strong_alias does plus add the
183 visibility attribute. */
184 extern struct rtld_global_ro _rtld_local_ro
185 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
188 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
189 ElfW(Addr) *user_entry, ElfW(auxv_t) *auxv);
191 /* These two variables cannot be moved into .data.rel.ro. */
192 static struct libname_list _dl_rtld_libname;
193 static struct libname_list _dl_rtld_libname2;
195 /* We expect less than a second for relocation. */
196 #ifdef HP_SMALL_TIMING_AVAIL
197 # undef HP_TIMING_AVAIL
198 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
199 #endif
201 /* Variable for statistics. */
202 #ifndef HP_TIMING_NONAVAIL
203 static hp_timing_t relocate_time;
204 static hp_timing_t load_time attribute_relro;
205 static hp_timing_t start_time attribute_relro;
206 #endif
208 /* Additional definitions needed by TLS initialization. */
209 #ifdef TLS_INIT_HELPER
210 TLS_INIT_HELPER
211 #endif
213 /* Helper function for syscall implementation. */
214 #ifdef DL_SYSINFO_IMPLEMENTATION
215 DL_SYSINFO_IMPLEMENTATION
216 #endif
218 /* Before ld.so is relocated we must not access variables which need
219 relocations. This means variables which are exported. Variables
220 declared as static are fine. If we can mark a variable hidden this
221 is fine, too. The latter is important here. We can avoid setting
222 up a temporary link map for ld.so if we can mark _rtld_global as
223 hidden. */
224 #ifdef PI_STATIC_AND_HIDDEN
225 # define DONT_USE_BOOTSTRAP_MAP 1
226 #endif
228 #ifdef DONT_USE_BOOTSTRAP_MAP
229 static ElfW(Addr) _dl_start_final (void *arg);
230 #else
231 struct dl_start_final_info
233 struct link_map l;
234 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
235 hp_timing_t start_time;
236 #endif
238 static ElfW(Addr) _dl_start_final (void *arg,
239 struct dl_start_final_info *info);
240 #endif
242 /* These defined magically in the linker script. */
243 extern char _begin[] attribute_hidden;
244 extern char _etext[] attribute_hidden;
245 extern char _end[] attribute_hidden;
248 #ifdef RTLD_START
249 RTLD_START
250 #else
251 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
252 #endif
254 #ifndef VALIDX
255 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
256 + DT_EXTRANUM + DT_VALTAGIDX (tag))
257 #endif
258 #ifndef ADDRIDX
259 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
260 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
261 #endif
263 /* This is the second half of _dl_start (below). It can be inlined safely
264 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
265 references. When the tools don't permit us to avoid using a GOT entry
266 for _dl_rtld_global (no attribute_hidden support), we must make sure
267 this function is not inlined (see below). */
269 #ifdef DONT_USE_BOOTSTRAP_MAP
270 static inline ElfW(Addr) __attribute__ ((always_inline))
271 _dl_start_final (void *arg)
272 #else
273 static ElfW(Addr) __attribute__ ((noinline))
274 _dl_start_final (void *arg, struct dl_start_final_info *info)
275 #endif
277 ElfW(Addr) start_addr;
279 if (HP_TIMING_AVAIL)
281 /* If it hasn't happen yet record the startup time. */
282 if (! HP_TIMING_INLINE)
283 HP_TIMING_NOW (start_time);
284 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
285 else
286 start_time = info->start_time;
287 #endif
289 /* Initialize the timing functions. */
290 HP_TIMING_DIFF_INIT ();
293 /* Transfer data about ourselves to the permanent link_map structure. */
294 #ifndef DONT_USE_BOOTSTRAP_MAP
295 GL(dl_rtld_map).l_addr = info->l.l_addr;
296 GL(dl_rtld_map).l_ld = info->l.l_ld;
297 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
298 sizeof GL(dl_rtld_map).l_info);
299 GL(dl_rtld_map).l_mach = info->l.l_mach;
300 GL(dl_rtld_map).l_relocated = 1;
301 #endif
302 _dl_setup_hash (&GL(dl_rtld_map));
303 GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
304 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
305 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
306 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
307 /* Copy the TLS related data if necessary. */
308 #ifndef DONT_USE_BOOTSTRAP_MAP
309 # if USE___THREAD
310 assert (info->l.l_tls_modid != 0);
311 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
312 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
313 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
314 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
315 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
316 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
317 GL(dl_rtld_map).l_tls_modid = 1;
318 # else
319 # if NO_TLS_OFFSET != 0
320 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
321 # endif
322 # endif
324 #endif
326 #if HP_TIMING_AVAIL
327 HP_TIMING_NOW (GL(dl_cpuclock_offset));
328 #endif
330 /* Initialize the stack end variable. */
331 __libc_stack_end = __builtin_frame_address (0);
333 /* Call the OS-dependent function to set up life so we can do things like
334 file access. It will call `dl_main' (below) to do all the real work
335 of the dynamic linker, and then unwind our frame and run the user
336 entry point on the same stack we entered on. */
337 start_addr = _dl_sysdep_start (arg, &dl_main);
339 #ifndef HP_TIMING_NONAVAIL
340 hp_timing_t rtld_total_time;
341 if (HP_TIMING_AVAIL)
343 hp_timing_t end_time;
345 /* Get the current time. */
346 HP_TIMING_NOW (end_time);
348 /* Compute the difference. */
349 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
351 #endif
353 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
355 #ifndef HP_TIMING_NONAVAIL
356 print_statistics (&rtld_total_time);
357 #else
358 print_statistics (NULL);
359 #endif
362 return start_addr;
365 static ElfW(Addr) __attribute_used__ internal_function
366 _dl_start (void *arg)
368 #ifdef DONT_USE_BOOTSTRAP_MAP
369 # define bootstrap_map GL(dl_rtld_map)
370 #else
371 struct dl_start_final_info info;
372 # define bootstrap_map info.l
373 #endif
375 /* This #define produces dynamic linking inline functions for
376 bootstrap relocation instead of general-purpose relocation.
377 Since ld.so must not have any undefined symbols the result
378 is trivial: always the map of ld.so itself. */
379 #define RTLD_BOOTSTRAP
380 #define RESOLVE_MAP(sym, version, flags) (&bootstrap_map)
381 #include "dynamic-link.h"
383 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
384 #ifdef DONT_USE_BOOTSTRAP_MAP
385 HP_TIMING_NOW (start_time);
386 #else
387 HP_TIMING_NOW (info.start_time);
388 #endif
390 /* Partly clean the `bootstrap_map' structure up. Don't use
391 `memset' since it might not be built in or inlined and we cannot
392 make function calls at this point. Use '__builtin_memset' if we
393 know it is available. We do not have to clear the memory if we
394 do not have to use the temporary bootstrap_map. Global variables
395 are initialized to zero by default. */
396 #ifndef DONT_USE_BOOTSTRAP_MAP
397 # ifdef HAVE_BUILTIN_MEMSET
398 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
399 # else
400 for (size_t cnt = 0;
401 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
402 ++cnt)
403 bootstrap_map.l_info[cnt] = 0;
404 # endif
405 # if USE___THREAD
406 bootstrap_map.l_tls_modid = 0;
407 # endif
408 #endif
410 /* Figure out the run-time load address of the dynamic linker itself. */
411 bootstrap_map.l_addr = elf_machine_load_address ();
413 /* Read our own dynamic section and fill in the info array. */
414 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
415 elf_get_dynamic_info (&bootstrap_map, NULL);
417 #if NO_TLS_OFFSET != 0
418 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
419 #endif
421 /* Get the dynamic linker's own program header. First we need the ELF
422 file header. The `_begin' symbol created by the linker script points
423 to it. When we have something like GOTOFF relocs, we can use a plain
424 reference to find the runtime address. Without that, we have to rely
425 on the `l_addr' value, which is not the value we want when prelinked. */
426 #if USE___THREAD
427 dtv_t initdtv[3];
428 ElfW(Ehdr) *ehdr
429 # ifdef DONT_USE_BOOTSTRAP_MAP
430 = (ElfW(Ehdr) *) &_begin;
431 # else
432 # error This will not work with prelink.
433 = (ElfW(Ehdr) *) bootstrap_map.l_addr;
434 # endif
435 ElfW(Phdr) *phdr = (ElfW(Phdr) *) ((void *) ehdr + ehdr->e_phoff);
436 size_t cnt = ehdr->e_phnum; /* PT_TLS is usually the last phdr. */
437 while (cnt-- > 0)
438 if (phdr[cnt].p_type == PT_TLS)
440 void *tlsblock;
441 size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
442 char *p;
444 bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
445 bootstrap_map.l_tls_align = phdr[cnt].p_align;
446 if (phdr[cnt].p_align == 0)
447 bootstrap_map.l_tls_firstbyte_offset = 0;
448 else
449 bootstrap_map.l_tls_firstbyte_offset = (phdr[cnt].p_vaddr
450 & (phdr[cnt].p_align - 1));
451 assert (bootstrap_map.l_tls_blocksize != 0);
452 bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
453 bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
454 + phdr[cnt].p_vaddr);
456 /* We can now allocate the initial TLS block. This can happen
457 on the stack. We'll get the final memory later when we
458 know all about the various objects loaded at startup
459 time. */
460 # if TLS_TCB_AT_TP
461 tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
462 TLS_INIT_TCB_ALIGN)
463 + TLS_INIT_TCB_SIZE
464 + max_align);
465 # elif TLS_DTV_AT_TP
466 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
467 bootstrap_map.l_tls_align)
468 + bootstrap_map.l_tls_blocksize
469 + max_align);
470 # else
471 /* In case a model with a different layout for the TCB and DTV
472 is defined add another #elif here and in the following #ifs. */
473 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
474 # endif
475 /* Align the TLS block. */
476 tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
477 & ~(max_align - 1));
479 /* Initialize the dtv. [0] is the length, [1] the generation
480 counter. */
481 initdtv[0].counter = 1;
482 initdtv[1].counter = 0;
484 /* Initialize the TLS block. */
485 # if TLS_TCB_AT_TP
486 initdtv[2].pointer = tlsblock;
487 # elif TLS_DTV_AT_TP
488 bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
489 bootstrap_map.l_tls_align);
490 initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
491 # else
492 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
493 # endif
494 p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
495 bootstrap_map.l_tls_initimage_size);
496 # ifdef HAVE_BUILTIN_MEMSET
497 __builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
498 - bootstrap_map.l_tls_initimage_size));
499 # else
501 size_t remaining = (bootstrap_map.l_tls_blocksize
502 - bootstrap_map.l_tls_initimage_size);
503 while (remaining-- > 0)
504 *p++ = '\0';
506 # endif
508 /* Install the pointer to the dtv. */
510 /* Initialize the thread pointer. */
511 # if TLS_TCB_AT_TP
512 bootstrap_map.l_tls_offset
513 = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
515 INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
516 initdtv);
518 const char *lossage = TLS_INIT_TP ((char *) tlsblock
519 + bootstrap_map.l_tls_offset, 0);
520 # elif TLS_DTV_AT_TP
521 INSTALL_DTV (tlsblock, initdtv);
522 const char *lossage = TLS_INIT_TP (tlsblock, 0);
523 # else
524 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
525 # endif
526 if (__builtin_expect (lossage != NULL, 0))
527 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
528 lossage);
530 /* So far this is module number one. */
531 bootstrap_map.l_tls_modid = 1;
533 /* There can only be one PT_TLS entry. */
534 break;
536 #endif /* USE___THREAD */
538 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
539 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
540 #endif
542 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
544 /* Relocate ourselves so we can do normal function calls and
545 data access using the global offset table. */
547 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0, 0);
549 bootstrap_map.l_relocated = 1;
551 /* Please note that we don't allow profiling of this object and
552 therefore need not test whether we have to allocate the array
553 for the relocation results (as done in dl-reloc.c). */
555 /* Now life is sane; we can call functions and access global data.
556 Set up to use the operating system facilities, and find out from
557 the operating system's program loader where to find the program
558 header table in core. Put the rest of _dl_start into a separate
559 function, that way the compiler cannot put accesses to the GOT
560 before ELF_DYNAMIC_RELOCATE. */
562 #ifdef DONT_USE_BOOTSTRAP_MAP
563 ElfW(Addr) entry = _dl_start_final (arg);
564 #else
565 ElfW(Addr) entry = _dl_start_final (arg, &info);
566 #endif
568 #ifndef ELF_MACHINE_START_ADDRESS
569 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
570 #endif
572 return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, entry);
578 /* Now life is peachy; we can do all normal operations.
579 On to the real work. */
581 /* Some helper functions. */
583 /* Arguments to relocate_doit. */
584 struct relocate_args
586 struct link_map *l;
587 int reloc_mode;
590 struct map_args
592 /* Argument to map_doit. */
593 char *str;
594 struct link_map *loader;
595 int mode;
596 /* Return value of map_doit. */
597 struct link_map *map;
600 struct dlmopen_args
602 const char *fname;
603 struct link_map *map;
606 struct lookup_args
608 const char *name;
609 struct link_map *map;
610 void *result;
613 /* Arguments to version_check_doit. */
614 struct version_check_args
616 int doexit;
617 int dotrace;
620 static void
621 relocate_doit (void *a)
623 struct relocate_args *args = (struct relocate_args *) a;
625 _dl_relocate_object (args->l, args->l->l_scope, args->reloc_mode, 0);
628 static void
629 map_doit (void *a)
631 struct map_args *args = (struct map_args *) a;
632 args->map = _dl_map_object (args->loader, args->str, lt_library, 0,
633 args->mode, LM_ID_BASE);
636 static void
637 dlmopen_doit (void *a)
639 struct dlmopen_args *args = (struct dlmopen_args *) a;
640 args->map = _dl_open (args->fname,
641 (RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT
642 | __RTLD_SECURE),
643 dl_main, LM_ID_NEWLM, _dl_argc, INTUSE(_dl_argv),
644 __environ);
647 static void
648 lookup_doit (void *a)
650 struct lookup_args *args = (struct lookup_args *) a;
651 const ElfW(Sym) *ref = NULL;
652 args->result = NULL;
653 lookup_t l = _dl_lookup_symbol_x (args->name, args->map, &ref,
654 args->map->l_local_scope, NULL, 0,
655 DL_LOOKUP_RETURN_NEWEST, NULL);
656 if (ref != NULL)
657 args->result = DL_SYMBOL_ADDRESS (l, ref);
660 static void
661 version_check_doit (void *a)
663 struct version_check_args *args = (struct version_check_args *) a;
664 if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
665 args->dotrace) && args->doexit)
666 /* We cannot start the application. Abort now. */
667 _exit (1);
671 static inline struct link_map *
672 find_needed (const char *name)
674 struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
675 unsigned int n = scope->r_nlist;
677 while (n-- > 0)
678 if (_dl_name_match_p (name, scope->r_list[n]))
679 return scope->r_list[n];
681 /* Should never happen. */
682 return NULL;
685 static int
686 match_version (const char *string, struct link_map *map)
688 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
689 ElfW(Verdef) *def;
691 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
692 if (map->l_info[VERDEFTAG] == NULL)
693 /* The file has no symbol versioning. */
694 return 0;
696 def = (ElfW(Verdef) *) ((char *) map->l_addr
697 + map->l_info[VERDEFTAG]->d_un.d_ptr);
698 while (1)
700 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
702 /* Compare the version strings. */
703 if (strcmp (string, strtab + aux->vda_name) == 0)
704 /* Bingo! */
705 return 1;
707 /* If no more definitions we failed to find what we want. */
708 if (def->vd_next == 0)
709 break;
711 /* Next definition. */
712 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
715 return 0;
718 static bool tls_init_tp_called;
720 static void *
721 init_tls (void)
723 /* Number of elements in the static TLS block. */
724 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
726 /* Do not do this twice. The audit interface might have required
727 the DTV interfaces to be set up early. */
728 if (GL(dl_initial_dtv) != NULL)
729 return NULL;
731 /* Allocate the array which contains the information about the
732 dtv slots. We allocate a few entries more than needed to
733 avoid the need for reallocation. */
734 size_t nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
736 /* Allocate. */
737 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
738 calloc (sizeof (struct dtv_slotinfo_list)
739 + nelem * sizeof (struct dtv_slotinfo), 1);
740 /* No need to check the return value. If memory allocation failed
741 the program would have been terminated. */
743 struct dtv_slotinfo *slotinfo = GL(dl_tls_dtv_slotinfo_list)->slotinfo;
744 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
745 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
747 /* Fill in the information from the loaded modules. No namespace
748 but the base one can be filled at this time. */
749 assert (GL(dl_ns)[LM_ID_BASE + 1]._ns_loaded == NULL);
750 int i = 0;
751 for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
752 l = l->l_next)
753 if (l->l_tls_blocksize != 0)
755 /* This is a module with TLS data. Store the map reference.
756 The generation counter is zero. */
757 slotinfo[i].map = l;
758 /* slotinfo[i].gen = 0; */
759 ++i;
761 assert (i == GL(dl_tls_max_dtv_idx));
763 /* Compute the TLS offsets for the various blocks. */
764 _dl_determine_tlsoffset ();
766 /* Construct the static TLS block and the dtv for the initial
767 thread. For some platforms this will include allocating memory
768 for the thread descriptor. The memory for the TLS block will
769 never be freed. It should be allocated accordingly. The dtv
770 array can be changed if dynamic loading requires it. */
771 void *tcbp = _dl_allocate_tls_storage ();
772 if (tcbp == NULL)
773 _dl_fatal_printf ("\
774 cannot allocate TLS data structures for initial thread");
776 /* Store for detection of the special case by __tls_get_addr
777 so it knows not to pass this dtv to the normal realloc. */
778 GL(dl_initial_dtv) = GET_DTV (tcbp);
780 /* And finally install it for the main thread. If ld.so itself uses
781 TLS we know the thread pointer was initialized earlier. */
782 const char *lossage
783 #ifdef USE___THREAD
784 = TLS_INIT_TP (tcbp, USE___THREAD);
785 #else
786 = TLS_INIT_TP (tcbp, 0);
787 #endif
788 if (__builtin_expect (lossage != NULL, 0))
789 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
790 tls_init_tp_called = true;
792 return tcbp;
795 #ifdef _LIBC_REENTRANT
796 /* _dl_error_catch_tsd points to this for the single-threaded case.
797 It's reset by the thread library for multithreaded programs. */
798 void ** __attribute__ ((const))
799 _dl_initial_error_catch_tsd (void)
801 static void *data;
802 return &data;
804 #endif
807 static unsigned int
808 do_preload (char *fname, struct link_map *main_map, const char *where)
810 const char *objname;
811 const char *err_str = NULL;
812 struct map_args args;
813 bool malloced;
815 args.str = fname;
816 args.loader = main_map;
817 args.mode = __RTLD_SECURE;
819 unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
821 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
822 if (__builtin_expect (err_str != NULL, 0))
824 _dl_error_printf ("\
825 ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
826 fname, where);
827 /* No need to call free, this is still before
828 the libc's malloc is used. */
830 else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
831 /* It is no duplicate. */
832 return 1;
834 /* Nothing loaded. */
835 return 0;
838 #if defined SHARED && defined _LIBC_REENTRANT \
839 && defined __rtld_lock_default_lock_recursive
840 static void
841 rtld_lock_default_lock_recursive (void *lock)
843 __rtld_lock_default_lock_recursive (lock);
846 static void
847 rtld_lock_default_unlock_recursive (void *lock)
849 __rtld_lock_default_unlock_recursive (lock);
851 #endif
854 static void
855 security_init (void)
857 /* Set up the stack checker's canary. */
858 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard (_dl_random);
859 #ifdef THREAD_SET_STACK_GUARD
860 THREAD_SET_STACK_GUARD (stack_chk_guard);
861 #else
862 __stack_chk_guard = stack_chk_guard;
863 #endif
865 /* Set up the pointer guard as well, if necessary. */
866 if (GLRO(dl_pointer_guard))
868 uintptr_t pointer_chk_guard = _dl_setup_pointer_guard (_dl_random,
869 stack_chk_guard);
870 #ifdef THREAD_SET_POINTER_GUARD
871 THREAD_SET_POINTER_GUARD (pointer_chk_guard);
872 #endif
873 __pointer_chk_guard_local = pointer_chk_guard;
876 /* We do not need the _dl_random value anymore. The less
877 information we leave behind, the better, so clear the
878 variable. */
879 _dl_random = NULL;
883 /* The library search path. */
884 static const char *library_path attribute_relro;
885 /* The list preloaded objects. */
886 static const char *preloadlist attribute_relro;
887 /* Nonzero if information about versions has to be printed. */
888 static int version_info attribute_relro;
890 static void
891 dl_main (const ElfW(Phdr) *phdr,
892 ElfW(Word) phnum,
893 ElfW(Addr) *user_entry,
894 ElfW(auxv_t) *auxv)
896 const ElfW(Phdr) *ph;
897 enum mode mode;
898 struct link_map *main_map;
899 size_t file_size;
900 char *file;
901 bool has_interp = false;
902 unsigned int i;
903 bool prelinked = false;
904 bool rtld_is_main = false;
905 #ifndef HP_TIMING_NONAVAIL
906 hp_timing_t start;
907 hp_timing_t stop;
908 hp_timing_t diff;
909 #endif
910 void *tcbp = NULL;
912 #ifdef _LIBC_REENTRANT
913 /* Explicit initialization since the reloc would just be more work. */
914 GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
915 #endif
917 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
919 #if defined SHARED && defined _LIBC_REENTRANT \
920 && defined __rtld_lock_default_lock_recursive
921 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
922 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
923 #endif
925 /* The explicit initialization here is cheaper than processing the reloc
926 in the _rtld_local definition's initializer. */
927 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
929 /* Process the environment variable which control the behaviour. */
930 process_envvars (&mode);
932 #ifndef HAVE_INLINED_SYSCALLS
933 /* Set up a flag which tells we are just starting. */
934 INTUSE(_dl_starting_up) = 1;
935 #endif
937 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
939 /* Ho ho. We are not the program interpreter! We are the program
940 itself! This means someone ran ld.so as a command. Well, that
941 might be convenient to do sometimes. We support it by
942 interpreting the args like this:
944 ld.so PROGRAM ARGS...
946 The first argument is the name of a file containing an ELF
947 executable we will load and run with the following arguments.
948 To simplify life here, PROGRAM is searched for using the
949 normal rules for shared objects, rather than $PATH or anything
950 like that. We just load it and use its entry point; we don't
951 pay attention to its PT_INTERP command (we are the interpreter
952 ourselves). This is an easy way to test a new ld.so before
953 installing it. */
954 rtld_is_main = true;
956 /* Note the place where the dynamic linker actually came from. */
957 GL(dl_rtld_map).l_name = rtld_progname;
959 while (_dl_argc > 1)
960 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
962 mode = list;
963 GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
965 ++_dl_skip_args;
966 --_dl_argc;
967 ++INTUSE(_dl_argv);
969 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
971 mode = verify;
973 ++_dl_skip_args;
974 --_dl_argc;
975 ++INTUSE(_dl_argv);
977 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-cache"))
979 GLRO(dl_inhibit_cache) = 1;
980 ++_dl_skip_args;
981 --_dl_argc;
982 ++INTUSE(_dl_argv);
984 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
985 && _dl_argc > 2)
987 library_path = INTUSE(_dl_argv)[2];
989 _dl_skip_args += 2;
990 _dl_argc -= 2;
991 INTUSE(_dl_argv) += 2;
993 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
994 && _dl_argc > 2)
996 GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
998 _dl_skip_args += 2;
999 _dl_argc -= 2;
1000 INTUSE(_dl_argv) += 2;
1002 else if (! strcmp (INTUSE(_dl_argv)[1], "--audit") && _dl_argc > 2)
1004 process_dl_audit (INTUSE(_dl_argv)[2]);
1006 _dl_skip_args += 2;
1007 _dl_argc -= 2;
1008 INTUSE(_dl_argv) += 2;
1010 else
1011 break;
1013 /* If we have no further argument the program was called incorrectly.
1014 Grant the user some education. */
1015 if (_dl_argc < 2)
1016 _dl_fatal_printf ("\
1017 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
1018 You have invoked `ld.so', the helper program for shared library executables.\n\
1019 This program usually lives in the file `/lib/ld.so', and special directives\n\
1020 in executable files using ELF shared libraries tell the system's program\n\
1021 loader to load the helper program from this file. This helper program loads\n\
1022 the shared libraries needed by the program executable, prepares the program\n\
1023 to run, and runs it. You may invoke this helper program directly from the\n\
1024 command line to load and run an ELF executable file; this is like executing\n\
1025 that file itself, but always uses this helper program from the file you\n\
1026 specified, instead of the helper program file specified in the executable\n\
1027 file you run. This is mostly of use for maintainers to test new versions\n\
1028 of this helper program; chances are you did not intend to run this program.\n\
1030 --list list all dependencies and how they are resolved\n\
1031 --verify verify that given object really is a dynamically linked\n\
1032 object we can handle\n\
1033 --inhibit-cache Do not use " LD_SO_CACHE "\n\
1034 --library-path PATH use given PATH instead of content of the environment\n\
1035 variable LD_LIBRARY_PATH\n\
1036 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
1037 in LIST\n\
1038 --audit LIST use objects named in LIST as auditors\n");
1040 ++_dl_skip_args;
1041 --_dl_argc;
1042 ++INTUSE(_dl_argv);
1044 /* The initialization of _dl_stack_flags done below assumes the
1045 executable's PT_GNU_STACK may have been honored by the kernel, and
1046 so a PT_GNU_STACK with PF_X set means the stack started out with
1047 execute permission. However, this is not really true if the
1048 dynamic linker is the executable the kernel loaded. For this
1049 case, we must reinitialize _dl_stack_flags to match the dynamic
1050 linker itself. If the dynamic linker was built with a
1051 PT_GNU_STACK, then the kernel may have loaded us with a
1052 nonexecutable stack that we will have to make executable when we
1053 load the program below unless it has a PT_GNU_STACK indicating
1054 nonexecutable stack is ok. */
1056 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1057 if (ph->p_type == PT_GNU_STACK)
1059 GL(dl_stack_flags) = ph->p_flags;
1060 break;
1063 if (__builtin_expect (mode, normal) == verify)
1065 const char *objname;
1066 const char *err_str = NULL;
1067 struct map_args args;
1068 bool malloced;
1070 args.str = rtld_progname;
1071 args.loader = NULL;
1072 args.mode = __RTLD_OPENEXEC;
1073 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
1074 &args);
1075 if (__builtin_expect (err_str != NULL, 0))
1076 /* We don't free the returned string, the programs stops
1077 anyway. */
1078 _exit (EXIT_FAILURE);
1080 else
1082 HP_TIMING_NOW (start);
1083 _dl_map_object (NULL, rtld_progname, lt_library, 0,
1084 __RTLD_OPENEXEC, LM_ID_BASE);
1085 HP_TIMING_NOW (stop);
1087 HP_TIMING_DIFF (load_time, start, stop);
1090 /* Now the map for the main executable is available. */
1091 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1093 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1094 && main_map->l_info[DT_SONAME] != NULL
1095 && strcmp ((const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1096 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val,
1097 (const char *) D_PTR (main_map, l_info[DT_STRTAB])
1098 + main_map->l_info[DT_SONAME]->d_un.d_val) == 0)
1099 _dl_fatal_printf ("loader cannot load itself\n");
1101 phdr = main_map->l_phdr;
1102 phnum = main_map->l_phnum;
1103 /* We overwrite here a pointer to a malloc()ed string. But since
1104 the malloc() implementation used at this point is the dummy
1105 implementations which has no real free() function it does not
1106 makes sense to free the old string first. */
1107 main_map->l_name = (char *) "";
1108 *user_entry = main_map->l_entry;
1110 #ifdef HAVE_AUX_VECTOR
1111 /* Adjust the on-stack auxiliary vector so that it looks like the
1112 binary was executed directly. */
1113 for (ElfW(auxv_t) *av = auxv; av->a_type != AT_NULL; av++)
1114 switch (av->a_type)
1116 case AT_PHDR:
1117 av->a_un.a_val = (uintptr_t) phdr;
1118 break;
1119 case AT_PHNUM:
1120 av->a_un.a_val = phnum;
1121 break;
1122 case AT_ENTRY:
1123 av->a_un.a_val = *user_entry;
1124 break;
1126 #endif
1128 else
1130 /* Create a link_map for the executable itself.
1131 This will be what dlopen on "" returns. */
1132 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1133 __RTLD_OPENEXEC, LM_ID_BASE);
1134 assert (main_map != NULL);
1135 main_map->l_phdr = phdr;
1136 main_map->l_phnum = phnum;
1137 main_map->l_entry = *user_entry;
1139 /* Even though the link map is not yet fully initialized we can add
1140 it to the map list since there are no possible users running yet. */
1141 _dl_add_to_namespace_list (main_map, LM_ID_BASE);
1142 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
1144 /* At this point we are in a bit of trouble. We would have to
1145 fill in the values for l_dev and l_ino. But in general we
1146 do not know where the file is. We also do not handle AT_EXECFD
1147 even if it would be passed up.
1149 We leave the values here defined to 0. This is normally no
1150 problem as the program code itself is normally no shared
1151 object and therefore cannot be loaded dynamically. Nothing
1152 prevent the use of dynamic binaries and in these situations
1153 we might get problems. We might not be able to find out
1154 whether the object is already loaded. But since there is no
1155 easy way out and because the dynamic binary must also not
1156 have an SONAME we ignore this program for now. If it becomes
1157 a problem we can force people using SONAMEs. */
1159 /* We delay initializing the path structure until we got the dynamic
1160 information for the program. */
1163 main_map->l_map_end = 0;
1164 main_map->l_text_end = 0;
1165 /* Perhaps the executable has no PT_LOAD header entries at all. */
1166 main_map->l_map_start = ~0;
1167 /* And it was opened directly. */
1168 ++main_map->l_direct_opencount;
1170 /* Scan the program header table for the dynamic section. */
1171 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1172 switch (ph->p_type)
1174 case PT_PHDR:
1175 /* Find out the load address. */
1176 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1177 break;
1178 case PT_DYNAMIC:
1179 /* This tells us where to find the dynamic section,
1180 which tells us everything we need to do. */
1181 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
1182 break;
1183 case PT_INTERP:
1184 /* This "interpreter segment" was used by the program loader to
1185 find the program interpreter, which is this program itself, the
1186 dynamic linker. We note what name finds us, so that a future
1187 dlopen call or DT_NEEDED entry, for something that wants to link
1188 against the dynamic linker as a shared library, will know that
1189 the shared object is already loaded. */
1190 _dl_rtld_libname.name = ((const char *) main_map->l_addr
1191 + ph->p_vaddr);
1192 /* _dl_rtld_libname.next = NULL; Already zero. */
1193 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1195 /* Ordinarilly, we would get additional names for the loader from
1196 our DT_SONAME. This can't happen if we were actually linked as
1197 a static executable (detect this case when we have no DYNAMIC).
1198 If so, assume the filename component of the interpreter path to
1199 be our SONAME, and add it to our name list. */
1200 if (GL(dl_rtld_map).l_ld == NULL)
1202 const char *p = NULL;
1203 const char *cp = _dl_rtld_libname.name;
1205 /* Find the filename part of the path. */
1206 while (*cp != '\0')
1207 if (*cp++ == '/')
1208 p = cp;
1210 if (p != NULL)
1212 _dl_rtld_libname2.name = p;
1213 /* _dl_rtld_libname2.next = NULL; Already zero. */
1214 _dl_rtld_libname.next = &_dl_rtld_libname2;
1218 has_interp = true;
1219 break;
1220 case PT_LOAD:
1222 ElfW(Addr) mapstart;
1223 ElfW(Addr) allocend;
1225 /* Remember where the main program starts in memory. */
1226 mapstart = (main_map->l_addr
1227 + (ph->p_vaddr & ~(GLRO(dl_pagesize) - 1)));
1228 if (main_map->l_map_start > mapstart)
1229 main_map->l_map_start = mapstart;
1231 /* Also where it ends. */
1232 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1233 if (main_map->l_map_end < allocend)
1234 main_map->l_map_end = allocend;
1235 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1236 main_map->l_text_end = allocend;
1238 break;
1240 case PT_TLS:
1241 if (ph->p_memsz > 0)
1243 /* Note that in the case the dynamic linker we duplicate work
1244 here since we read the PT_TLS entry already in
1245 _dl_start_final. But the result is repeatable so do not
1246 check for this special but unimportant case. */
1247 main_map->l_tls_blocksize = ph->p_memsz;
1248 main_map->l_tls_align = ph->p_align;
1249 if (ph->p_align == 0)
1250 main_map->l_tls_firstbyte_offset = 0;
1251 else
1252 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1253 & (ph->p_align - 1));
1254 main_map->l_tls_initimage_size = ph->p_filesz;
1255 main_map->l_tls_initimage = (void *) ph->p_vaddr;
1257 /* This image gets the ID one. */
1258 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1260 break;
1262 case PT_GNU_STACK:
1263 GL(dl_stack_flags) = ph->p_flags;
1264 break;
1266 case PT_GNU_RELRO:
1267 main_map->l_relro_addr = ph->p_vaddr;
1268 main_map->l_relro_size = ph->p_memsz;
1269 break;
1272 /* Adjust the address of the TLS initialization image in case
1273 the executable is actually an ET_DYN object. */
1274 if (main_map->l_tls_initimage != NULL)
1275 main_map->l_tls_initimage
1276 = (char *) main_map->l_tls_initimage + main_map->l_addr;
1277 if (! main_map->l_map_end)
1278 main_map->l_map_end = ~0;
1279 if (! main_map->l_text_end)
1280 main_map->l_text_end = ~0;
1281 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1283 /* We were invoked directly, so the program might not have a
1284 PT_INTERP. */
1285 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1286 /* _dl_rtld_libname.next = NULL; Already zero. */
1287 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1289 else
1290 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1292 /* If the current libname is different from the SONAME, add the
1293 latter as well. */
1294 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1295 && strcmp (GL(dl_rtld_map).l_libname->name,
1296 (const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1297 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1299 static struct libname_list newname;
1300 newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1301 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1302 newname.next = NULL;
1303 newname.dont_free = 1;
1305 assert (GL(dl_rtld_map).l_libname->next == NULL);
1306 GL(dl_rtld_map).l_libname->next = &newname;
1308 /* The ld.so must be relocated since otherwise loading audit modules
1309 will fail since they reuse the very same ld.so. */
1310 assert (GL(dl_rtld_map).l_relocated);
1312 if (! rtld_is_main)
1314 /* Extract the contents of the dynamic section for easy access. */
1315 elf_get_dynamic_info (main_map, NULL);
1316 /* Set up our cache of pointers into the hash table. */
1317 _dl_setup_hash (main_map);
1320 if (__builtin_expect (mode, normal) == verify)
1322 /* We were called just to verify that this is a dynamic
1323 executable using us as the program interpreter. Exit with an
1324 error if we were not able to load the binary or no interpreter
1325 is specified (i.e., this is no dynamically linked binary. */
1326 if (main_map->l_ld == NULL)
1327 _exit (1);
1329 /* We allow here some platform specific code. */
1330 #ifdef DISTINGUISH_LIB_VERSIONS
1331 DISTINGUISH_LIB_VERSIONS;
1332 #endif
1333 _exit (has_interp ? 0 : 2);
1336 struct link_map **first_preload = &GL(dl_rtld_map).l_next;
1337 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1338 /* Set up the data structures for the system-supplied DSO early,
1339 so they can influence _dl_init_paths. */
1340 if (GLRO(dl_sysinfo_dso) != NULL)
1342 /* Do an abridged version of the work _dl_map_object_from_fd would do
1343 to map in the object. It's already mapped and prelinked (and
1344 better be, since it's read-only and so we couldn't relocate it).
1345 We just want our data structures to describe it as if we had just
1346 mapped and relocated it normally. */
1347 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL,
1348 0, LM_ID_BASE);
1349 if (__builtin_expect (l != NULL, 1))
1351 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
1353 l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1354 + GLRO(dl_sysinfo_dso)->e_phoff);
1355 l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1356 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1358 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1359 if (ph->p_type == PT_DYNAMIC)
1361 l->l_ld = (void *) ph->p_vaddr;
1362 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1364 else if (ph->p_type == PT_LOAD)
1366 if (! l->l_addr)
1367 l->l_addr = ph->p_vaddr;
1368 if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1369 l->l_map_end = ph->p_vaddr + ph->p_memsz;
1370 if ((ph->p_flags & PF_X)
1371 && ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1372 l->l_text_end = ph->p_vaddr + ph->p_memsz;
1374 else
1375 /* There must be no TLS segment. */
1376 assert (ph->p_type != PT_TLS);
1378 l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1379 l->l_addr = l->l_map_start - l->l_addr;
1380 l->l_map_end += l->l_addr;
1381 l->l_text_end += l->l_addr;
1382 l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1383 elf_get_dynamic_info (l, dyn_temp);
1384 _dl_setup_hash (l);
1385 l->l_relocated = 1;
1387 /* The vDSO is always used. */
1388 l->l_used = 1;
1390 /* Initialize l_local_scope to contain just this map. This allows
1391 the use of dl_lookup_symbol_x to resolve symbols within the vdso.
1392 So we create a single entry list pointing to l_real as its only
1393 element */
1394 l->l_local_scope[0]->r_nlist = 1;
1395 l->l_local_scope[0]->r_list = &l->l_real;
1397 /* Now that we have the info handy, use the DSO image's soname
1398 so this object can be looked up by name. Note that we do not
1399 set l_name here. That field gives the file name of the DSO,
1400 and this DSO is not associated with any file. */
1401 if (l->l_info[DT_SONAME] != NULL)
1403 /* Work around a kernel problem. The kernel cannot handle
1404 addresses in the vsyscall DSO pages in writev() calls. */
1405 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1406 + l->l_info[DT_SONAME]->d_un.d_val);
1407 size_t len = strlen (dsoname);
1408 char *copy = malloc (len);
1409 if (copy == NULL)
1410 _dl_fatal_printf ("out of memory\n");
1411 l->l_libname->name = l->l_name = memcpy (copy, dsoname, len);
1414 /* Add the vDSO to the object list. */
1415 _dl_add_to_namespace_list (l, LM_ID_BASE);
1417 /* Rearrange the list so this DSO appears after rtld_map. */
1418 assert (l->l_next == NULL);
1419 assert (l->l_prev == main_map);
1420 GL(dl_rtld_map).l_next = l;
1421 l->l_prev = &GL(dl_rtld_map);
1422 first_preload = &l->l_next;
1424 /* We have a prelinked DSO preloaded by the system. */
1425 GLRO(dl_sysinfo_map) = l;
1426 # ifdef NEED_DL_SYSINFO
1427 if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1428 GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1429 # endif
1432 #endif
1434 #ifdef DL_SYSDEP_OSCHECK
1435 DL_SYSDEP_OSCHECK (_dl_fatal_printf);
1436 #endif
1438 /* Initialize the data structures for the search paths for shared
1439 objects. */
1440 _dl_init_paths (library_path);
1442 /* Initialize _r_debug. */
1443 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1444 LM_ID_BASE);
1445 r->r_state = RT_CONSISTENT;
1447 /* Put the link_map for ourselves on the chain so it can be found by
1448 name. Note that at this point the global chain of link maps contains
1449 exactly one element, which is pointed to by dl_loaded. */
1450 if (! GL(dl_rtld_map).l_name)
1451 /* If not invoked directly, the dynamic linker shared object file was
1452 found by the PT_INTERP name. */
1453 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1454 GL(dl_rtld_map).l_type = lt_library;
1455 main_map->l_next = &GL(dl_rtld_map);
1456 GL(dl_rtld_map).l_prev = main_map;
1457 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1458 ++GL(dl_load_adds);
1460 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1461 to not using bias for non-prelinked PIEs and libraries
1462 and using it for executables or prelinked PIEs or libraries. */
1463 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1464 GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
1466 /* Set up the program header information for the dynamic linker
1467 itself. It is needed in the dl_iterate_phdr() callbacks. */
1468 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1469 ElfW(Phdr) *rtld_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1470 + rtld_ehdr->e_phoff);
1471 GL(dl_rtld_map).l_phdr = rtld_phdr;
1472 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1475 /* PT_GNU_RELRO is usually the last phdr. */
1476 size_t cnt = rtld_ehdr->e_phnum;
1477 while (cnt-- > 0)
1478 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1480 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1481 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1482 break;
1485 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1486 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1487 /* Assign a module ID. Do this before loading any audit modules. */
1488 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1490 /* If we have auditing DSOs to load, do it now. */
1491 if (__builtin_expect (audit_list != NULL, 0))
1493 /* Iterate over all entries in the list. The order is important. */
1494 struct audit_ifaces *last_audit = NULL;
1495 struct audit_list *al = audit_list->next;
1497 /* Since we start using the auditing DSOs right away we need to
1498 initialize the data structures now. */
1499 tcbp = init_tls ();
1501 /* Initialize security features. We need to do it this early
1502 since otherwise the constructors of the audit libraries will
1503 use different values (especially the pointer guard) and will
1504 fail later on. */
1505 security_init ();
1509 int tls_idx = GL(dl_tls_max_dtv_idx);
1511 /* Now it is time to determine the layout of the static TLS
1512 block and allocate it for the initial thread. Note that we
1513 always allocate the static block, we never defer it even if
1514 no DF_STATIC_TLS bit is set. The reason is that we know
1515 glibc will use the static model. */
1516 struct dlmopen_args dlmargs;
1517 dlmargs.fname = al->name;
1518 dlmargs.map = NULL;
1520 const char *objname;
1521 const char *err_str = NULL;
1522 bool malloced;
1523 (void) _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit,
1524 &dlmargs);
1525 if (__builtin_expect (err_str != NULL, 0))
1527 not_loaded:
1528 _dl_error_printf ("\
1529 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
1530 al->name, err_str);
1531 if (malloced)
1532 free ((char *) err_str);
1534 else
1536 struct lookup_args largs;
1537 largs.name = "la_version";
1538 largs.map = dlmargs.map;
1540 /* Check whether the interface version matches. */
1541 (void) _dl_catch_error (&objname, &err_str, &malloced,
1542 lookup_doit, &largs);
1544 unsigned int (*laversion) (unsigned int);
1545 unsigned int lav;
1546 if (err_str == NULL
1547 && (laversion = largs.result) != NULL
1548 && (lav = laversion (LAV_CURRENT)) > 0
1549 && lav <= LAV_CURRENT)
1551 /* Allocate structure for the callback function pointers.
1552 This call can never fail. */
1553 union
1555 struct audit_ifaces ifaces;
1556 #define naudit_ifaces 8
1557 void (*fptr[naudit_ifaces]) (void);
1558 } *newp = malloc (sizeof (*newp));
1560 /* Names of the auditing interfaces. All in one
1561 long string. */
1562 static const char audit_iface_names[] =
1563 "la_activity\0"
1564 "la_objsearch\0"
1565 "la_objopen\0"
1566 "la_preinit\0"
1567 #if __ELF_NATIVE_CLASS == 32
1568 "la_symbind32\0"
1569 #elif __ELF_NATIVE_CLASS == 64
1570 "la_symbind64\0"
1571 #else
1572 # error "__ELF_NATIVE_CLASS must be defined"
1573 #endif
1574 #define STRING(s) __STRING (s)
1575 "la_" STRING (ARCH_LA_PLTENTER) "\0"
1576 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
1577 "la_objclose\0";
1578 unsigned int cnt = 0;
1579 const char *cp = audit_iface_names;
1582 largs.name = cp;
1583 (void) _dl_catch_error (&objname, &err_str, &malloced,
1584 lookup_doit, &largs);
1586 /* Store the pointer. */
1587 if (err_str == NULL && largs.result != NULL)
1589 newp->fptr[cnt] = largs.result;
1591 /* The dynamic linker link map is statically
1592 allocated, initialize the data now. */
1593 GL(dl_rtld_map).l_audit[cnt].cookie
1594 = (intptr_t) &GL(dl_rtld_map);
1596 else
1597 newp->fptr[cnt] = NULL;
1598 ++cnt;
1600 cp = (char *) rawmemchr (cp, '\0') + 1;
1602 while (*cp != '\0');
1603 assert (cnt == naudit_ifaces);
1605 /* Now append the new auditing interface to the list. */
1606 newp->ifaces.next = NULL;
1607 if (last_audit == NULL)
1608 last_audit = GLRO(dl_audit) = &newp->ifaces;
1609 else
1610 last_audit = last_audit->next = &newp->ifaces;
1611 ++GLRO(dl_naudit);
1613 /* Mark the DSO as being used for auditing. */
1614 dlmargs.map->l_auditing = 1;
1616 else
1618 /* We cannot use the DSO, it does not have the
1619 appropriate interfaces or it expects something
1620 more recent. */
1621 #ifndef NDEBUG
1622 Lmid_t ns = dlmargs.map->l_ns;
1623 #endif
1624 _dl_close (dlmargs.map);
1626 /* Make sure the namespace has been cleared entirely. */
1627 assert (GL(dl_ns)[ns]._ns_loaded == NULL);
1628 assert (GL(dl_ns)[ns]._ns_nloaded == 0);
1630 GL(dl_tls_max_dtv_idx) = tls_idx;
1631 goto not_loaded;
1635 al = al->next;
1637 while (al != audit_list->next);
1639 /* If we have any auditing modules, announce that we already
1640 have two objects loaded. */
1641 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1643 struct link_map *ls[2] = { main_map, &GL(dl_rtld_map) };
1645 for (unsigned int outer = 0; outer < 2; ++outer)
1647 struct audit_ifaces *afct = GLRO(dl_audit);
1648 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1650 if (afct->objopen != NULL)
1652 ls[outer]->l_audit[cnt].bindflags
1653 = afct->objopen (ls[outer], LM_ID_BASE,
1654 &ls[outer]->l_audit[cnt].cookie);
1656 ls[outer]->l_audit_any_plt
1657 |= ls[outer]->l_audit[cnt].bindflags != 0;
1660 afct = afct->next;
1666 /* Set up debugging before the debugger is notified for the first time. */
1667 #ifdef ELF_MACHINE_DEBUG_SETUP
1668 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1669 ELF_MACHINE_DEBUG_SETUP (main_map, r);
1670 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1671 #else
1672 if (main_map->l_info[DT_DEBUG] != NULL)
1673 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1674 with the run-time address of the r_debug structure */
1675 main_map->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1677 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1678 case you run gdb on the dynamic linker directly. */
1679 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1680 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1681 #endif
1683 /* We start adding objects. */
1684 r->r_state = RT_ADD;
1685 _dl_debug_state ();
1687 /* Auditing checkpoint: we are ready to signal that the initial map
1688 is being constructed. */
1689 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1691 struct audit_ifaces *afct = GLRO(dl_audit);
1692 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1694 if (afct->activity != NULL)
1695 afct->activity (&main_map->l_audit[cnt].cookie, LA_ACT_ADD);
1697 afct = afct->next;
1701 /* We have two ways to specify objects to preload: via environment
1702 variable and via the file /etc/ld.so.preload. The latter can also
1703 be used when security is enabled. */
1704 assert (*first_preload == NULL);
1705 struct link_map **preloads = NULL;
1706 unsigned int npreloads = 0;
1708 if (__builtin_expect (preloadlist != NULL, 0))
1710 /* The LD_PRELOAD environment variable gives list of libraries
1711 separated by white space or colons that are loaded before the
1712 executable's dependencies and prepended to the global scope
1713 list. If the binary is running setuid all elements
1714 containing a '/' are ignored since it is insecure. */
1715 char *list = strdupa (preloadlist);
1716 char *p;
1718 HP_TIMING_NOW (start);
1720 /* Prevent optimizing strsep. Speed is not important here. */
1721 while ((p = (strsep) (&list, " :")) != NULL)
1722 if (p[0] != '\0'
1723 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1724 || strchr (p, '/') == NULL))
1725 npreloads += do_preload (p, main_map, "LD_PRELOAD");
1727 HP_TIMING_NOW (stop);
1728 HP_TIMING_DIFF (diff, start, stop);
1729 HP_TIMING_ACCUM_NT (load_time, diff);
1732 /* There usually is no ld.so.preload file, it should only be used
1733 for emergencies and testing. So the open call etc should usually
1734 fail. Using access() on a non-existing file is faster than using
1735 open(). So we do this first. If it succeeds we do almost twice
1736 the work but this does not matter, since it is not for production
1737 use. */
1738 static const char preload_file[] = "/etc/ld.so.preload";
1739 if (__builtin_expect (__access (preload_file, R_OK) == 0, 0))
1741 /* Read the contents of the file. */
1742 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1743 PROT_READ | PROT_WRITE);
1744 if (__builtin_expect (file != MAP_FAILED, 0))
1746 /* Parse the file. It contains names of libraries to be loaded,
1747 separated by white spaces or `:'. It may also contain
1748 comments introduced by `#'. */
1749 char *problem;
1750 char *runp;
1751 size_t rest;
1753 /* Eliminate comments. */
1754 runp = file;
1755 rest = file_size;
1756 while (rest > 0)
1758 char *comment = memchr (runp, '#', rest);
1759 if (comment == NULL)
1760 break;
1762 rest -= comment - runp;
1764 *comment = ' ';
1765 while (--rest > 0 && *++comment != '\n');
1768 /* We have one problematic case: if we have a name at the end of
1769 the file without a trailing terminating characters, we cannot
1770 place the \0. Handle the case separately. */
1771 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1772 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1774 problem = &file[file_size];
1775 while (problem > file && problem[-1] != ' '
1776 && problem[-1] != '\t'
1777 && problem[-1] != '\n' && problem[-1] != ':')
1778 --problem;
1780 if (problem > file)
1781 problem[-1] = '\0';
1783 else
1785 problem = NULL;
1786 file[file_size - 1] = '\0';
1789 HP_TIMING_NOW (start);
1791 if (file != problem)
1793 char *p;
1794 runp = file;
1795 while ((p = strsep (&runp, ": \t\n")) != NULL)
1796 if (p[0] != '\0')
1797 npreloads += do_preload (p, main_map, preload_file);
1800 if (problem != NULL)
1802 char *p = strndupa (problem, file_size - (problem - file));
1804 npreloads += do_preload (p, main_map, preload_file);
1807 HP_TIMING_NOW (stop);
1808 HP_TIMING_DIFF (diff, start, stop);
1809 HP_TIMING_ACCUM_NT (load_time, diff);
1811 /* We don't need the file anymore. */
1812 __munmap (file, file_size);
1816 if (__builtin_expect (*first_preload != NULL, 0))
1818 /* Set up PRELOADS with a vector of the preloaded libraries. */
1819 struct link_map *l = *first_preload;
1820 preloads = __alloca (npreloads * sizeof preloads[0]);
1821 i = 0;
1824 preloads[i++] = l;
1825 l = l->l_next;
1826 } while (l);
1827 assert (i == npreloads);
1830 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1831 specified some libraries to load, these are inserted before the actual
1832 dependencies in the executable's searchlist for symbol resolution. */
1833 HP_TIMING_NOW (start);
1834 _dl_map_object_deps (main_map, preloads, npreloads, mode == trace, 0);
1835 HP_TIMING_NOW (stop);
1836 HP_TIMING_DIFF (diff, start, stop);
1837 HP_TIMING_ACCUM_NT (load_time, diff);
1839 /* Mark all objects as being in the global scope. */
1840 for (i = main_map->l_searchlist.r_nlist; i > 0; )
1841 main_map->l_searchlist.r_list[--i]->l_global = 1;
1843 /* Remove _dl_rtld_map from the chain. */
1844 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1845 if (GL(dl_rtld_map).l_next != NULL)
1846 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1848 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1849 if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1850 break;
1852 bool rtld_multiple_ref = false;
1853 if (__builtin_expect (i < main_map->l_searchlist.r_nlist, 1))
1855 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1856 put it back in the list of visible objects. We insert it into the
1857 chain in symbol search order because gdb uses the chain's order as
1858 its symbol search order. */
1859 rtld_multiple_ref = true;
1861 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1862 if (__builtin_expect (mode, normal) == normal)
1864 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1865 ? main_map->l_searchlist.r_list[i + 1]
1866 : NULL);
1867 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1868 if (GLRO(dl_sysinfo_map) != NULL
1869 && GL(dl_rtld_map).l_prev->l_next == GLRO(dl_sysinfo_map)
1870 && GL(dl_rtld_map).l_next != GLRO(dl_sysinfo_map))
1871 GL(dl_rtld_map).l_prev = GLRO(dl_sysinfo_map);
1872 #endif
1874 else
1875 /* In trace mode there might be an invisible object (which we
1876 could not find) after the previous one in the search list.
1877 In this case it doesn't matter much where we put the
1878 interpreter object, so we just initialize the list pointer so
1879 that the assertion below holds. */
1880 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1882 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1883 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1884 if (GL(dl_rtld_map).l_next != NULL)
1886 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1887 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1891 /* Now let us see whether all libraries are available in the
1892 versions we need. */
1894 struct version_check_args args;
1895 args.doexit = mode == normal;
1896 args.dotrace = mode == trace;
1897 _dl_receive_error (print_missing_version, version_check_doit, &args);
1900 /* We do not initialize any of the TLS functionality unless any of the
1901 initial modules uses TLS. This makes dynamic loading of modules with
1902 TLS impossible, but to support it requires either eagerly doing setup
1903 now or lazily doing it later. Doing it now makes us incompatible with
1904 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1905 used. Trying to do it lazily is too hairy to try when there could be
1906 multiple threads (from a non-TLS-using libpthread). */
1907 bool was_tls_init_tp_called = tls_init_tp_called;
1908 if (tcbp == NULL)
1909 tcbp = init_tls ();
1911 if (__builtin_expect (audit_list == NULL, 1))
1912 /* Initialize security features. But only if we have not done it
1913 earlier. */
1914 security_init ();
1916 if (__builtin_expect (mode, normal) != normal)
1918 /* We were run just to list the shared libraries. It is
1919 important that we do this before real relocation, because the
1920 functions we call below for output may no longer work properly
1921 after relocation. */
1922 struct link_map *l;
1924 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1926 struct r_scope_elem *scope = &main_map->l_searchlist;
1928 for (i = 0; i < scope->r_nlist; i++)
1930 l = scope->r_list [i];
1931 if (l->l_faked)
1933 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1934 continue;
1936 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1937 GLRO(dl_trace_prelink_map) = l;
1938 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1939 l->l_libname->name[0] ? l->l_libname->name
1940 : rtld_progname ?: "<main program>",
1941 l->l_name[0] ? l->l_name
1942 : rtld_progname ?: "<main program>",
1943 (int) sizeof l->l_map_start * 2,
1944 (size_t) l->l_map_start,
1945 (int) sizeof l->l_addr * 2,
1946 (size_t) l->l_addr);
1948 if (l->l_tls_modid)
1949 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1950 (int) sizeof l->l_tls_offset * 2,
1951 (size_t) l->l_tls_offset);
1952 else
1953 _dl_printf ("\n");
1956 else if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
1958 /* Look through the dependencies of the main executable
1959 and determine which of them is not actually
1960 required. */
1961 struct link_map *l = main_map;
1963 /* Relocate the main executable. */
1964 struct relocate_args args = { .l = l,
1965 .reloc_mode = ((GLRO(dl_lazy)
1966 ? RTLD_LAZY : 0)
1967 | __RTLD_NOIFUNC) };
1968 _dl_receive_error (print_unresolved, relocate_doit, &args);
1970 /* This loop depends on the dependencies of the executable to
1971 correspond in number and order to the DT_NEEDED entries. */
1972 ElfW(Dyn) *dyn = main_map->l_ld;
1973 bool first = true;
1974 while (dyn->d_tag != DT_NULL)
1976 if (dyn->d_tag == DT_NEEDED)
1978 l = l->l_next;
1979 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1980 /* Skip the VDSO since it's not part of the list
1981 of objects we brought in via DT_NEEDED entries. */
1982 if (l == GLRO(dl_sysinfo_map))
1983 l = l->l_next;
1984 #endif
1985 if (!l->l_used)
1987 if (first)
1989 _dl_printf ("Unused direct dependencies:\n");
1990 first = false;
1993 _dl_printf ("\t%s\n", l->l_name);
1997 ++dyn;
2000 _exit (first != true);
2002 else if (! main_map->l_info[DT_NEEDED])
2003 _dl_printf ("\tstatically linked\n");
2004 else
2006 for (l = main_map->l_next; l; l = l->l_next)
2007 if (l->l_faked)
2008 /* The library was not found. */
2009 _dl_printf ("\t%s => not found\n", l->l_libname->name);
2010 else if (strcmp (l->l_libname->name, l->l_name) == 0)
2011 _dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
2012 (int) sizeof l->l_map_start * 2,
2013 (size_t) l->l_map_start);
2014 else
2015 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
2016 l->l_name, (int) sizeof l->l_map_start * 2,
2017 (size_t) l->l_map_start);
2020 if (__builtin_expect (mode, trace) != trace)
2021 for (i = 1; i < (unsigned int) _dl_argc; ++i)
2023 const ElfW(Sym) *ref = NULL;
2024 ElfW(Addr) loadbase;
2025 lookup_t result;
2027 result = _dl_lookup_symbol_x (INTUSE(_dl_argv)[i], main_map,
2028 &ref, main_map->l_scope,
2029 NULL, ELF_RTYPE_CLASS_PLT,
2030 DL_LOOKUP_ADD_DEPENDENCY, NULL);
2032 loadbase = LOOKUP_VALUE_ADDRESS (result);
2034 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
2035 INTUSE(_dl_argv)[i],
2036 (int) sizeof ref->st_value * 2,
2037 (size_t) ref->st_value,
2038 (int) sizeof loadbase * 2, (size_t) loadbase);
2040 else
2042 /* If LD_WARN is set, warn about undefined symbols. */
2043 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
2045 /* We have to do symbol dependency testing. */
2046 struct relocate_args args;
2047 unsigned int i;
2049 args.reloc_mode = ((GLRO(dl_lazy) ? RTLD_LAZY : 0)
2050 | __RTLD_NOIFUNC);
2052 i = main_map->l_searchlist.r_nlist;
2053 while (i-- > 0)
2055 struct link_map *l = main_map->l_initfini[i];
2056 if (l != &GL(dl_rtld_map) && ! l->l_faked)
2058 args.l = l;
2059 _dl_receive_error (print_unresolved, relocate_doit,
2060 &args);
2064 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
2065 && rtld_multiple_ref)
2067 /* Mark the link map as not yet relocated again. */
2068 GL(dl_rtld_map).l_relocated = 0;
2069 _dl_relocate_object (&GL(dl_rtld_map),
2070 main_map->l_scope, __RTLD_NOIFUNC, 0);
2073 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
2074 if (version_info)
2076 /* Print more information. This means here, print information
2077 about the versions needed. */
2078 int first = 1;
2079 struct link_map *map;
2081 for (map = main_map; map != NULL; map = map->l_next)
2083 const char *strtab;
2084 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
2085 ElfW(Verneed) *ent;
2087 if (dyn == NULL)
2088 continue;
2090 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
2091 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
2093 if (first)
2095 _dl_printf ("\n\tVersion information:\n");
2096 first = 0;
2099 _dl_printf ("\t%s:\n",
2100 map->l_name[0] ? map->l_name : rtld_progname);
2102 while (1)
2104 ElfW(Vernaux) *aux;
2105 struct link_map *needed;
2107 needed = find_needed (strtab + ent->vn_file);
2108 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
2110 while (1)
2112 const char *fname = NULL;
2114 if (needed != NULL
2115 && match_version (strtab + aux->vna_name,
2116 needed))
2117 fname = needed->l_name;
2119 _dl_printf ("\t\t%s (%s) %s=> %s\n",
2120 strtab + ent->vn_file,
2121 strtab + aux->vna_name,
2122 aux->vna_flags & VER_FLG_WEAK
2123 ? "[WEAK] " : "",
2124 fname ?: "not found");
2126 if (aux->vna_next == 0)
2127 /* No more symbols. */
2128 break;
2130 /* Next symbol. */
2131 aux = (ElfW(Vernaux) *) ((char *) aux
2132 + aux->vna_next);
2135 if (ent->vn_next == 0)
2136 /* No more dependencies. */
2137 break;
2139 /* Next dependency. */
2140 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
2146 _exit (0);
2149 if (main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]
2150 && ! __builtin_expect (GLRO(dl_profile) != NULL, 0)
2151 && ! __builtin_expect (GLRO(dl_dynamic_weak), 0))
2153 ElfW(Lib) *liblist, *liblistend;
2154 struct link_map **r_list, **r_listend, *l;
2155 const char *strtab = (const void *) D_PTR (main_map, l_info[DT_STRTAB]);
2157 assert (main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
2158 liblist = (ElfW(Lib) *)
2159 main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
2160 liblistend = (ElfW(Lib) *)
2161 ((char *) liblist +
2162 main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
2163 r_list = main_map->l_searchlist.r_list;
2164 r_listend = r_list + main_map->l_searchlist.r_nlist;
2166 for (; r_list < r_listend && liblist < liblistend; r_list++)
2168 l = *r_list;
2170 if (l == main_map)
2171 continue;
2173 /* If the library is not mapped where it should, fail. */
2174 if (l->l_addr)
2175 break;
2177 /* Next, check if checksum matches. */
2178 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
2179 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
2180 != liblist->l_checksum)
2181 break;
2183 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
2184 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
2185 != liblist->l_time_stamp)
2186 break;
2188 if (! _dl_name_match_p (strtab + liblist->l_name, l))
2189 break;
2191 ++liblist;
2195 if (r_list == r_listend && liblist == liblistend)
2196 prelinked = true;
2198 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
2199 _dl_debug_printf ("\nprelink checking: %s\n",
2200 prelinked ? "ok" : "failed");
2204 /* Now set up the variable which helps the assembler startup code. */
2205 GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
2207 /* Save the information about the original global scope list since
2208 we need it in the memory handling later. */
2209 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
2211 /* Remember the last search directory added at startup, now that
2212 malloc will no longer be the one from dl-minimal.c. */
2213 GLRO(dl_init_all_dirs) = GL(dl_all_dirs);
2215 /* Print scope information. */
2216 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_SCOPES, 0))
2218 _dl_debug_printf ("\nInitial object scopes\n");
2220 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2221 _dl_show_scope (l, 0);
2224 if (prelinked)
2226 if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
2228 ElfW(Rela) *conflict, *conflictend;
2229 #ifndef HP_TIMING_NONAVAIL
2230 hp_timing_t start;
2231 hp_timing_t stop;
2232 #endif
2234 HP_TIMING_NOW (start);
2235 assert (main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
2236 conflict = (ElfW(Rela) *)
2237 main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
2238 conflictend = (ElfW(Rela) *)
2239 ((char *) conflict
2240 + main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
2241 _dl_resolve_conflicts (main_map, conflict, conflictend);
2242 HP_TIMING_NOW (stop);
2243 HP_TIMING_DIFF (relocate_time, start, stop);
2247 /* Mark all the objects so we know they have been already relocated. */
2248 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2250 l->l_relocated = 1;
2251 if (l->l_relro_size)
2252 _dl_protect_relro (l);
2254 /* Add object to slot information data if necessasy. */
2255 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2256 _dl_add_to_slotinfo (l);
2259 else
2261 /* Now we have all the objects loaded. Relocate them all except for
2262 the dynamic linker itself. We do this in reverse order so that copy
2263 relocs of earlier objects overwrite the data written by later
2264 objects. We do not re-relocate the dynamic linker itself in this
2265 loop because that could result in the GOT entries for functions we
2266 call being changed, and that would break us. It is safe to relocate
2267 the dynamic linker out of order because it has no copy relocs (we
2268 know that because it is self-contained). */
2270 int consider_profiling = GLRO(dl_profile) != NULL;
2271 #ifndef HP_TIMING_NONAVAIL
2272 hp_timing_t start;
2273 hp_timing_t stop;
2274 #endif
2276 /* If we are profiling we also must do lazy reloaction. */
2277 GLRO(dl_lazy) |= consider_profiling;
2279 HP_TIMING_NOW (start);
2280 unsigned i = main_map->l_searchlist.r_nlist;
2281 while (i-- > 0)
2283 struct link_map *l = main_map->l_initfini[i];
2285 /* While we are at it, help the memory handling a bit. We have to
2286 mark some data structures as allocated with the fake malloc()
2287 implementation in ld.so. */
2288 struct libname_list *lnp = l->l_libname->next;
2290 while (__builtin_expect (lnp != NULL, 0))
2292 lnp->dont_free = 1;
2293 lnp = lnp->next;
2296 if (l != &GL(dl_rtld_map))
2297 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy) ? RTLD_LAZY : 0,
2298 consider_profiling);
2300 /* Add object to slot information data if necessasy. */
2301 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2302 _dl_add_to_slotinfo (l);
2304 HP_TIMING_NOW (stop);
2306 HP_TIMING_DIFF (relocate_time, start, stop);
2308 /* Now enable profiling if needed. Like the previous call,
2309 this has to go here because the calls it makes should use the
2310 rtld versions of the functions (particularly calloc()), but it
2311 needs to have _dl_profile_map set up by the relocator. */
2312 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
2313 /* We must prepare the profiling. */
2314 _dl_start_profile ();
2317 #ifndef NONTLS_INIT_TP
2318 # define NONTLS_INIT_TP do { } while (0)
2319 #endif
2321 if (!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2322 ++GL(dl_tls_generation);
2324 /* Now that we have completed relocation, the initializer data
2325 for the TLS blocks has its final values and we can copy them
2326 into the main thread's TLS area, which we allocated above. */
2327 _dl_allocate_tls_init (tcbp);
2329 /* And finally install it for the main thread. If ld.so itself uses
2330 TLS we know the thread pointer was initialized earlier. */
2331 if (! tls_init_tp_called)
2333 const char *lossage
2334 #ifdef USE___THREAD
2335 = TLS_INIT_TP (tcbp, USE___THREAD);
2336 #else
2337 = TLS_INIT_TP (tcbp, 0);
2338 #endif
2339 if (__builtin_expect (lossage != NULL, 0))
2340 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2341 lossage);
2344 /* Make sure no new search directories have been added. */
2345 assert (GLRO(dl_init_all_dirs) == GL(dl_all_dirs));
2347 if (! prelinked && rtld_multiple_ref)
2349 /* There was an explicit ref to the dynamic linker as a shared lib.
2350 Re-relocate ourselves with user-controlled symbol definitions.
2352 We must do this after TLS initialization in case after this
2353 re-relocation, we might call a user-supplied function
2354 (e.g. calloc from _dl_relocate_object) that uses TLS data. */
2356 #ifndef HP_TIMING_NONAVAIL
2357 hp_timing_t start;
2358 hp_timing_t stop;
2359 hp_timing_t add;
2360 #endif
2362 HP_TIMING_NOW (start);
2363 /* Mark the link map as not yet relocated again. */
2364 GL(dl_rtld_map).l_relocated = 0;
2365 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2366 HP_TIMING_NOW (stop);
2367 HP_TIMING_DIFF (add, start, stop);
2368 HP_TIMING_ACCUM_NT (relocate_time, add);
2371 /* Do any necessary cleanups for the startup OS interface code.
2372 We do these now so that no calls are made after rtld re-relocation
2373 which might be resolved to different functions than we expect.
2374 We cannot do this before relocating the other objects because
2375 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2376 _dl_sysdep_start_cleanup ();
2378 #ifdef SHARED
2379 /* Auditing checkpoint: we have added all objects. */
2380 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
2382 struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2383 /* Do not call the functions for any auditing object. */
2384 if (head->l_auditing == 0)
2386 struct audit_ifaces *afct = GLRO(dl_audit);
2387 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2389 if (afct->activity != NULL)
2390 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
2392 afct = afct->next;
2396 #endif
2398 /* Notify the debugger all new objects are now ready to go. We must re-get
2399 the address since by now the variable might be in another object. */
2400 r = _dl_debug_initialize (0, LM_ID_BASE);
2401 r->r_state = RT_CONSISTENT;
2402 _dl_debug_state ();
2404 #ifndef MAP_COPY
2405 /* We must munmap() the cache file. */
2406 _dl_unload_cache ();
2407 #endif
2409 /* Once we return, _dl_sysdep_start will invoke
2410 the DT_INIT functions and then *USER_ENTRY. */
2413 /* This is a little helper function for resolving symbols while
2414 tracing the binary. */
2415 static void
2416 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2417 const char *errstring)
2419 if (objname[0] == '\0')
2420 objname = rtld_progname ?: "<main program>";
2421 _dl_error_printf ("%s (%s)\n", errstring, objname);
2424 /* This is a little helper function for resolving symbols while
2425 tracing the binary. */
2426 static void
2427 print_missing_version (int errcode __attribute__ ((unused)),
2428 const char *objname, const char *errstring)
2430 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
2431 objname, errstring);
2434 /* Nonzero if any of the debugging options is enabled. */
2435 static int any_debug attribute_relro;
2437 /* Process the string given as the parameter which explains which debugging
2438 options are enabled. */
2439 static void
2440 process_dl_debug (const char *dl_debug)
2442 /* When adding new entries make sure that the maximal length of a name
2443 is correctly handled in the LD_DEBUG_HELP code below. */
2444 static const struct
2446 unsigned char len;
2447 const char name[10];
2448 const char helptext[41];
2449 unsigned short int mask;
2450 } debopts[] =
2452 #define LEN_AND_STR(str) sizeof (str) - 1, str
2453 { LEN_AND_STR ("libs"), "display library search paths",
2454 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2455 { LEN_AND_STR ("reloc"), "display relocation processing",
2456 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2457 { LEN_AND_STR ("files"), "display progress for input file",
2458 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2459 { LEN_AND_STR ("symbols"), "display symbol table processing",
2460 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2461 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2462 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2463 { LEN_AND_STR ("versions"), "display version dependencies",
2464 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2465 { LEN_AND_STR ("scopes"), "display scope information",
2466 DL_DEBUG_SCOPES },
2467 { LEN_AND_STR ("all"), "all previous options combined",
2468 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2469 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS
2470 | DL_DEBUG_SCOPES },
2471 { LEN_AND_STR ("statistics"), "display relocation statistics",
2472 DL_DEBUG_STATISTICS },
2473 { LEN_AND_STR ("unused"), "determined unused DSOs",
2474 DL_DEBUG_UNUSED },
2475 { LEN_AND_STR ("help"), "display this help message and exit",
2476 DL_DEBUG_HELP },
2478 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2480 /* Skip separating white spaces and commas. */
2481 while (*dl_debug != '\0')
2483 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2485 size_t cnt;
2486 size_t len = 1;
2488 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2489 && dl_debug[len] != ',' && dl_debug[len] != ':')
2490 ++len;
2492 for (cnt = 0; cnt < ndebopts; ++cnt)
2493 if (debopts[cnt].len == len
2494 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
2496 GLRO(dl_debug_mask) |= debopts[cnt].mask;
2497 any_debug = 1;
2498 break;
2501 if (cnt == ndebopts)
2503 /* Display a warning and skip everything until next
2504 separator. */
2505 char *copy = strndupa (dl_debug, len);
2506 _dl_error_printf ("\
2507 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2510 dl_debug += len;
2511 continue;
2514 ++dl_debug;
2517 if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
2519 /* In order to get an accurate picture of whether a particular
2520 DT_NEEDED entry is actually used we have to process both
2521 the PLT and non-PLT relocation entries. */
2522 GLRO(dl_lazy) = 0;
2525 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
2527 size_t cnt;
2529 _dl_printf ("\
2530 Valid options for the LD_DEBUG environment variable are:\n\n");
2532 for (cnt = 0; cnt < ndebopts; ++cnt)
2533 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2534 " " + debopts[cnt].len - 3,
2535 debopts[cnt].helptext);
2537 _dl_printf ("\n\
2538 To direct the debugging output into a file instead of standard output\n\
2539 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2540 _exit (0);
2544 static void
2545 process_dl_audit (char *str)
2547 /* The parameter is a colon separated list of DSO names. */
2548 char *p;
2550 while ((p = (strsep) (&str, ":")) != NULL)
2551 if (p[0] != '\0'
2552 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
2553 || strchr (p, '/') == NULL))
2555 /* This is using the local malloc, not the system malloc. The
2556 memory can never be freed. */
2557 struct audit_list *newp = malloc (sizeof (*newp));
2558 newp->name = p;
2560 if (audit_list == NULL)
2561 audit_list = newp->next = newp;
2562 else
2564 newp->next = audit_list->next;
2565 audit_list = audit_list->next = newp;
2570 /* Process all environments variables the dynamic linker must recognize.
2571 Since all of them start with `LD_' we are a bit smarter while finding
2572 all the entries. */
2573 extern char **_environ attribute_hidden;
2576 static void
2577 process_envvars (enum mode *modep)
2579 char **runp = _environ;
2580 char *envline;
2581 enum mode mode = normal;
2582 char *debug_output = NULL;
2584 /* This is the default place for profiling data file. */
2585 GLRO(dl_profile_output)
2586 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2588 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2590 size_t len = 0;
2592 while (envline[len] != '\0' && envline[len] != '=')
2593 ++len;
2595 if (envline[len] != '=')
2596 /* This is a "LD_" variable at the end of the string without
2597 a '=' character. Ignore it since otherwise we will access
2598 invalid memory below. */
2599 continue;
2601 switch (len)
2603 case 4:
2604 /* Warning level, verbose or not. */
2605 if (memcmp (envline, "WARN", 4) == 0)
2606 GLRO(dl_verbose) = envline[5] != '\0';
2607 break;
2609 case 5:
2610 /* Debugging of the dynamic linker? */
2611 if (memcmp (envline, "DEBUG", 5) == 0)
2613 process_dl_debug (&envline[6]);
2614 break;
2616 if (memcmp (envline, "AUDIT", 5) == 0)
2617 process_dl_audit (&envline[6]);
2618 break;
2620 case 7:
2621 /* Print information about versions. */
2622 if (memcmp (envline, "VERBOSE", 7) == 0)
2624 version_info = envline[8] != '\0';
2625 break;
2628 /* List of objects to be preloaded. */
2629 if (memcmp (envline, "PRELOAD", 7) == 0)
2631 preloadlist = &envline[8];
2632 break;
2635 /* Which shared object shall be profiled. */
2636 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2637 GLRO(dl_profile) = &envline[8];
2638 break;
2640 case 8:
2641 /* Do we bind early? */
2642 if (memcmp (envline, "BIND_NOW", 8) == 0)
2644 GLRO(dl_lazy) = envline[9] == '\0';
2645 break;
2647 if (memcmp (envline, "BIND_NOT", 8) == 0)
2648 GLRO(dl_bind_not) = envline[9] != '\0';
2649 break;
2651 case 9:
2652 /* Test whether we want to see the content of the auxiliary
2653 array passed up from the kernel. */
2654 if (!INTUSE(__libc_enable_secure)
2655 && memcmp (envline, "SHOW_AUXV", 9) == 0)
2656 _dl_show_auxv ();
2657 break;
2659 case 10:
2660 /* Mask for the important hardware capabilities. */
2661 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2662 GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2663 0, 0);
2664 break;
2666 case 11:
2667 /* Path where the binary is found. */
2668 if (!INTUSE(__libc_enable_secure)
2669 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2670 GLRO(dl_origin_path) = &envline[12];
2671 break;
2673 case 12:
2674 /* The library search path. */
2675 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2677 library_path = &envline[13];
2678 break;
2681 /* Where to place the profiling data file. */
2682 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2684 debug_output = &envline[13];
2685 break;
2688 if (!INTUSE(__libc_enable_secure)
2689 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2690 GLRO(dl_dynamic_weak) = 1;
2691 break;
2693 case 13:
2694 /* We might have some extra environment variable with length 13
2695 to handle. */
2696 #ifdef EXTRA_LD_ENVVARS_13
2697 EXTRA_LD_ENVVARS_13
2698 #endif
2699 if (!INTUSE(__libc_enable_secure)
2700 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2702 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2703 break;
2706 if (memcmp (envline, "POINTER_GUARD", 13) == 0)
2707 GLRO(dl_pointer_guard) = envline[14] != '0';
2708 break;
2710 case 14:
2711 /* Where to place the profiling data file. */
2712 if (!INTUSE(__libc_enable_secure)
2713 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2714 && envline[15] != '\0')
2715 GLRO(dl_profile_output) = &envline[15];
2716 break;
2718 case 16:
2719 /* The mode of the dynamic linker can be set. */
2720 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2722 mode = trace;
2723 GLRO(dl_verbose) = 1;
2724 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2725 GLRO(dl_trace_prelink) = &envline[17];
2727 break;
2729 case 20:
2730 /* The mode of the dynamic linker can be set. */
2731 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2732 mode = trace;
2733 break;
2735 /* We might have some extra environment variable to handle. This
2736 is tricky due to the pre-processing of the length of the name
2737 in the switch statement here. The code here assumes that added
2738 environment variables have a different length. */
2739 #ifdef EXTRA_LD_ENVVARS
2740 EXTRA_LD_ENVVARS
2741 #endif
2745 /* The caller wants this information. */
2746 *modep = mode;
2748 /* Extra security for SUID binaries. Remove all dangerous environment
2749 variables. */
2750 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2752 static const char unsecure_envvars[] =
2753 #ifdef EXTRA_UNSECURE_ENVVARS
2754 EXTRA_UNSECURE_ENVVARS
2755 #endif
2756 UNSECURE_ENVVARS;
2757 const char *nextp;
2759 nextp = unsecure_envvars;
2762 unsetenv (nextp);
2763 /* We could use rawmemchr but this need not be fast. */
2764 nextp = (char *) (strchr) (nextp, '\0') + 1;
2766 while (*nextp != '\0');
2768 if (__access ("/etc/suid-debug", F_OK) != 0)
2770 unsetenv ("MALLOC_CHECK_");
2771 GLRO(dl_debug_mask) = 0;
2774 if (mode != normal)
2775 _exit (5);
2777 /* If we have to run the dynamic linker in debugging mode and the
2778 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2779 messages to this file. */
2780 else if (any_debug && debug_output != NULL)
2782 #ifdef O_NOFOLLOW
2783 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2784 #else
2785 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2786 #endif
2787 size_t name_len = strlen (debug_output);
2788 char buf[name_len + 12];
2789 char *startp;
2791 buf[name_len + 11] = '\0';
2792 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2793 *--startp = '.';
2794 startp = memcpy (startp - name_len, debug_output, name_len);
2796 GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2797 if (GLRO(dl_debug_fd) == -1)
2798 /* We use standard output if opening the file failed. */
2799 GLRO(dl_debug_fd) = STDOUT_FILENO;
2804 /* Print the various times we collected. */
2805 static void
2806 __attribute ((noinline))
2807 print_statistics (hp_timing_t *rtld_total_timep)
2809 #ifndef HP_TIMING_NONAVAIL
2810 char buf[200];
2811 char *cp;
2812 char *wp;
2814 /* Total time rtld used. */
2815 if (HP_TIMING_AVAIL)
2817 HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2818 _dl_debug_printf ("\nruntime linker statistics:\n"
2819 " total startup time in dynamic loader: %s\n", buf);
2821 /* Print relocation statistics. */
2822 char pbuf[30];
2823 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2824 cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2825 pbuf + sizeof (pbuf), 10, 0);
2826 wp = pbuf;
2827 switch (pbuf + sizeof (pbuf) - cp)
2829 case 3:
2830 *wp++ = *cp++;
2831 case 2:
2832 *wp++ = *cp++;
2833 case 1:
2834 *wp++ = '.';
2835 *wp++ = *cp++;
2837 *wp = '\0';
2838 _dl_debug_printf ("\
2839 time needed for relocation: %s (%s%%)\n", buf, pbuf);
2841 #endif
2843 unsigned long int num_relative_relocations = 0;
2844 for (Lmid_t ns = 0; ns < GL(dl_nns); ++ns)
2846 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2847 continue;
2849 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2851 for (unsigned int i = 0; i < scope->r_nlist; i++)
2853 struct link_map *l = scope->r_list [i];
2855 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2856 num_relative_relocations
2857 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2858 #ifndef ELF_MACHINE_REL_RELATIVE
2859 /* Relative relocations are processed on these architectures if
2860 library is loaded to different address than p_vaddr or
2861 if not prelinked. */
2862 if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2863 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2864 #else
2865 /* On e.g. IA-64 or Alpha, relative relocations are processed
2866 only if library is loaded to different address than p_vaddr. */
2867 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2868 #endif
2869 num_relative_relocations
2870 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2874 _dl_debug_printf (" number of relocations: %lu\n"
2875 " number of relocations from cache: %lu\n"
2876 " number of relative relocations: %lu\n",
2877 GL(dl_num_relocations),
2878 GL(dl_num_cache_relocations),
2879 num_relative_relocations);
2881 #ifndef HP_TIMING_NONAVAIL
2882 /* Time spend while loading the object and the dependencies. */
2883 if (HP_TIMING_AVAIL)
2885 char pbuf[30];
2886 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2887 cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2888 pbuf + sizeof (pbuf), 10, 0);
2889 wp = pbuf;
2890 switch (pbuf + sizeof (pbuf) - cp)
2892 case 3:
2893 *wp++ = *cp++;
2894 case 2:
2895 *wp++ = *cp++;
2896 case 1:
2897 *wp++ = '.';
2898 *wp++ = *cp++;
2900 *wp = '\0';
2901 _dl_debug_printf ("\
2902 time needed to load objects: %s (%s%%)\n",
2903 buf, pbuf);
2905 #endif