Merge remote branch 'origin/master' into fedora/master
[glibc.git] / elf / rtld.c
blob80fe0ab35b0655add485f912583a9d4e01bda935
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 /* Set nonzero during loading and initialization of executable and
110 libraries, cleared before the executable's entry point runs. This
111 must not be initialized to nonzero, because the unused dynamic
112 linker loaded in for libc.so's "ld.so.1" dep will provide the
113 definition seen by libc.so's initializer; that value must be zero,
114 and will be since that dynamic linker's _dl_start and dl_main will
115 never be called. */
116 int _dl_starting_up = 0;
117 INTVARDEF(_dl_starting_up)
119 /* This is the structure which defines all variables global to ld.so
120 (except those which cannot be added for some reason). */
121 struct rtld_global _rtld_global =
123 /* Default presumption without further information is executable stack. */
124 ._dl_stack_flags = PF_R|PF_W|PF_X,
125 #ifdef _LIBC_REENTRANT
126 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
127 ._dl_load_write_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
128 #endif
129 ._dl_nns = 1,
130 ._dl_ns =
132 [LM_ID_BASE] = { ._ns_unique_sym_table
133 = { .lock = _RTLD_LOCK_RECURSIVE_INITIALIZER } }
136 /* If we would use strong_alias here the compiler would see a
137 non-hidden definition. This would undo the effect of the previous
138 declaration. So spell out was strong_alias does plus add the
139 visibility attribute. */
140 extern struct rtld_global _rtld_local
141 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
144 /* This variable is similar to _rtld_local, but all values are
145 read-only after relocation. */
146 struct rtld_global_ro _rtld_global_ro attribute_relro =
148 /* Get architecture specific initializer. */
149 #include <dl-procinfo.c>
150 #ifdef NEED_DL_SYSINFO
151 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
152 #endif
153 ._dl_debug_fd = STDERR_FILENO,
154 ._dl_use_load_bias = -2,
155 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
156 ._dl_hwcap_mask = HWCAP_IMPORTANT,
157 ._dl_lazy = 1,
158 ._dl_fpu_control = _FPU_DEFAULT,
159 ._dl_pointer_guard = 1,
161 /* Function pointers. */
162 ._dl_debug_printf = _dl_debug_printf,
163 ._dl_catch_error = _dl_catch_error,
164 ._dl_signal_error = _dl_signal_error,
165 ._dl_mcount = _dl_mcount_internal,
166 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
167 ._dl_check_caller = _dl_check_caller,
168 ._dl_open = _dl_open,
169 ._dl_close = _dl_close,
170 ._dl_tls_get_addr_soft = _dl_tls_get_addr_soft,
171 #ifdef HAVE_DL_DISCOVER_OSVERSION
172 ._dl_discover_osversion = _dl_discover_osversion
173 #endif
175 /* If we would use strong_alias here the compiler would see a
176 non-hidden definition. This would undo the effect of the previous
177 declaration. So spell out was strong_alias does plus add the
178 visibility attribute. */
179 extern struct rtld_global_ro _rtld_local_ro
180 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
183 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
184 ElfW(Addr) *user_entry, ElfW(auxv_t) *auxv);
186 /* These two variables cannot be moved into .data.rel.ro. */
187 static struct libname_list _dl_rtld_libname;
188 static struct libname_list _dl_rtld_libname2;
190 /* We expect less than a second for relocation. */
191 #ifdef HP_SMALL_TIMING_AVAIL
192 # undef HP_TIMING_AVAIL
193 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
194 #endif
196 /* Variable for statistics. */
197 #ifndef HP_TIMING_NONAVAIL
198 static hp_timing_t relocate_time;
199 static hp_timing_t load_time attribute_relro;
200 static hp_timing_t start_time attribute_relro;
201 #endif
203 /* Additional definitions needed by TLS initialization. */
204 #ifdef TLS_INIT_HELPER
205 TLS_INIT_HELPER
206 #endif
208 /* Helper function for syscall implementation. */
209 #ifdef DL_SYSINFO_IMPLEMENTATION
210 DL_SYSINFO_IMPLEMENTATION
211 #endif
213 /* Before ld.so is relocated we must not access variables which need
214 relocations. This means variables which are exported. Variables
215 declared as static are fine. If we can mark a variable hidden this
216 is fine, too. The latter is important here. We can avoid setting
217 up a temporary link map for ld.so if we can mark _rtld_global as
218 hidden. */
219 #ifdef PI_STATIC_AND_HIDDEN
220 # define DONT_USE_BOOTSTRAP_MAP 1
221 #endif
223 #ifdef DONT_USE_BOOTSTRAP_MAP
224 static ElfW(Addr) _dl_start_final (void *arg);
225 #else
226 struct dl_start_final_info
228 struct link_map l;
229 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
230 hp_timing_t start_time;
231 #endif
233 static ElfW(Addr) _dl_start_final (void *arg,
234 struct dl_start_final_info *info);
235 #endif
237 /* These defined magically in the linker script. */
238 extern char _begin[] attribute_hidden;
239 extern char _etext[] attribute_hidden;
240 extern char _end[] attribute_hidden;
243 #ifdef RTLD_START
244 RTLD_START
245 #else
246 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
247 #endif
249 #ifndef VALIDX
250 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
251 + DT_EXTRANUM + DT_VALTAGIDX (tag))
252 #endif
253 #ifndef ADDRIDX
254 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
255 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
256 #endif
258 /* This is the second half of _dl_start (below). It can be inlined safely
259 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
260 references. When the tools don't permit us to avoid using a GOT entry
261 for _dl_rtld_global (no attribute_hidden support), we must make sure
262 this function is not inlined (see below). */
264 #ifdef DONT_USE_BOOTSTRAP_MAP
265 static inline ElfW(Addr) __attribute__ ((always_inline))
266 _dl_start_final (void *arg)
267 #else
268 static ElfW(Addr) __attribute__ ((noinline))
269 _dl_start_final (void *arg, struct dl_start_final_info *info)
270 #endif
272 ElfW(Addr) start_addr;
274 if (HP_TIMING_AVAIL)
276 /* If it hasn't happen yet record the startup time. */
277 if (! HP_TIMING_INLINE)
278 HP_TIMING_NOW (start_time);
279 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
280 else
281 start_time = info->start_time;
282 #endif
284 /* Initialize the timing functions. */
285 HP_TIMING_DIFF_INIT ();
288 /* Transfer data about ourselves to the permanent link_map structure. */
289 #ifndef DONT_USE_BOOTSTRAP_MAP
290 GL(dl_rtld_map).l_addr = info->l.l_addr;
291 GL(dl_rtld_map).l_ld = info->l.l_ld;
292 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
293 sizeof GL(dl_rtld_map).l_info);
294 GL(dl_rtld_map).l_mach = info->l.l_mach;
295 GL(dl_rtld_map).l_relocated = 1;
296 #endif
297 _dl_setup_hash (&GL(dl_rtld_map));
298 GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
299 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
300 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
301 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
302 /* Copy the TLS related data if necessary. */
303 #ifndef DONT_USE_BOOTSTRAP_MAP
304 # if USE___THREAD
305 assert (info->l.l_tls_modid != 0);
306 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
307 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
308 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
309 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
310 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
311 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
312 GL(dl_rtld_map).l_tls_modid = 1;
313 # else
314 # if NO_TLS_OFFSET != 0
315 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
316 # endif
317 # endif
319 #endif
321 #if HP_TIMING_AVAIL
322 HP_TIMING_NOW (GL(dl_cpuclock_offset));
323 #endif
325 /* Initialize the stack end variable. */
326 __libc_stack_end = __builtin_frame_address (0);
328 /* Call the OS-dependent function to set up life so we can do things like
329 file access. It will call `dl_main' (below) to do all the real work
330 of the dynamic linker, and then unwind our frame and run the user
331 entry point on the same stack we entered on. */
332 start_addr = _dl_sysdep_start (arg, &dl_main);
334 #ifndef HP_TIMING_NONAVAIL
335 hp_timing_t rtld_total_time;
336 if (HP_TIMING_AVAIL)
338 hp_timing_t end_time;
340 /* Get the current time. */
341 HP_TIMING_NOW (end_time);
343 /* Compute the difference. */
344 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
346 #endif
348 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
350 #ifndef HP_TIMING_NONAVAIL
351 print_statistics (&rtld_total_time);
352 #else
353 print_statistics (NULL);
354 #endif
357 return start_addr;
360 static ElfW(Addr) __attribute_used__ internal_function
361 _dl_start (void *arg)
363 #ifdef DONT_USE_BOOTSTRAP_MAP
364 # define bootstrap_map GL(dl_rtld_map)
365 #else
366 struct dl_start_final_info info;
367 # define bootstrap_map info.l
368 #endif
370 /* This #define produces dynamic linking inline functions for
371 bootstrap relocation instead of general-purpose relocation.
372 Since ld.so must not have any undefined symbols the result
373 is trivial: always the map of ld.so itself. */
374 #define RTLD_BOOTSTRAP
375 #define RESOLVE_MAP(sym, version, flags) (&bootstrap_map)
376 #include "dynamic-link.h"
378 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
379 #ifdef DONT_USE_BOOTSTRAP_MAP
380 HP_TIMING_NOW (start_time);
381 #else
382 HP_TIMING_NOW (info.start_time);
383 #endif
385 /* Partly clean the `bootstrap_map' structure up. Don't use
386 `memset' since it might not be built in or inlined and we cannot
387 make function calls at this point. Use '__builtin_memset' if we
388 know it is available. We do not have to clear the memory if we
389 do not have to use the temporary bootstrap_map. Global variables
390 are initialized to zero by default. */
391 #ifndef DONT_USE_BOOTSTRAP_MAP
392 # ifdef HAVE_BUILTIN_MEMSET
393 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
394 # else
395 for (size_t cnt = 0;
396 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
397 ++cnt)
398 bootstrap_map.l_info[cnt] = 0;
399 # endif
400 # if USE___THREAD
401 bootstrap_map.l_tls_modid = 0;
402 # endif
403 #endif
405 /* Figure out the run-time load address of the dynamic linker itself. */
406 bootstrap_map.l_addr = elf_machine_load_address ();
408 /* Read our own dynamic section and fill in the info array. */
409 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
410 elf_get_dynamic_info (&bootstrap_map, NULL);
412 #if NO_TLS_OFFSET != 0
413 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
414 #endif
416 /* Get the dynamic linker's own program header. First we need the ELF
417 file header. The `_begin' symbol created by the linker script points
418 to it. When we have something like GOTOFF relocs, we can use a plain
419 reference to find the runtime address. Without that, we have to rely
420 on the `l_addr' value, which is not the value we want when prelinked. */
421 #if USE___THREAD
422 dtv_t initdtv[3];
423 ElfW(Ehdr) *ehdr
424 # ifdef DONT_USE_BOOTSTRAP_MAP
425 = (ElfW(Ehdr) *) &_begin;
426 # else
427 # error This will not work with prelink.
428 = (ElfW(Ehdr) *) bootstrap_map.l_addr;
429 # endif
430 ElfW(Phdr) *phdr = (ElfW(Phdr) *) ((void *) ehdr + ehdr->e_phoff);
431 size_t cnt = ehdr->e_phnum; /* PT_TLS is usually the last phdr. */
432 while (cnt-- > 0)
433 if (phdr[cnt].p_type == PT_TLS)
435 void *tlsblock;
436 size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
437 char *p;
439 bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
440 bootstrap_map.l_tls_align = phdr[cnt].p_align;
441 if (phdr[cnt].p_align == 0)
442 bootstrap_map.l_tls_firstbyte_offset = 0;
443 else
444 bootstrap_map.l_tls_firstbyte_offset = (phdr[cnt].p_vaddr
445 & (phdr[cnt].p_align - 1));
446 assert (bootstrap_map.l_tls_blocksize != 0);
447 bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
448 bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
449 + phdr[cnt].p_vaddr);
451 /* We can now allocate the initial TLS block. This can happen
452 on the stack. We'll get the final memory later when we
453 know all about the various objects loaded at startup
454 time. */
455 # if TLS_TCB_AT_TP
456 tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
457 TLS_INIT_TCB_ALIGN)
458 + TLS_INIT_TCB_SIZE
459 + max_align);
460 # elif TLS_DTV_AT_TP
461 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
462 bootstrap_map.l_tls_align)
463 + bootstrap_map.l_tls_blocksize
464 + max_align);
465 # else
466 /* In case a model with a different layout for the TCB and DTV
467 is defined add another #elif here and in the following #ifs. */
468 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
469 # endif
470 /* Align the TLS block. */
471 tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
472 & ~(max_align - 1));
474 /* Initialize the dtv. [0] is the length, [1] the generation
475 counter. */
476 initdtv[0].counter = 1;
477 initdtv[1].counter = 0;
479 /* Initialize the TLS block. */
480 # if TLS_TCB_AT_TP
481 initdtv[2].pointer = tlsblock;
482 # elif TLS_DTV_AT_TP
483 bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
484 bootstrap_map.l_tls_align);
485 initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
486 # else
487 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
488 # endif
489 p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
490 bootstrap_map.l_tls_initimage_size);
491 # ifdef HAVE_BUILTIN_MEMSET
492 __builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
493 - bootstrap_map.l_tls_initimage_size));
494 # else
496 size_t remaining = (bootstrap_map.l_tls_blocksize
497 - bootstrap_map.l_tls_initimage_size);
498 while (remaining-- > 0)
499 *p++ = '\0';
501 # endif
503 /* Install the pointer to the dtv. */
505 /* Initialize the thread pointer. */
506 # if TLS_TCB_AT_TP
507 bootstrap_map.l_tls_offset
508 = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
510 INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
511 initdtv);
513 const char *lossage = TLS_INIT_TP ((char *) tlsblock
514 + bootstrap_map.l_tls_offset, 0);
515 # elif TLS_DTV_AT_TP
516 INSTALL_DTV (tlsblock, initdtv);
517 const char *lossage = TLS_INIT_TP (tlsblock, 0);
518 # else
519 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
520 # endif
521 if (__builtin_expect (lossage != NULL, 0))
522 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
523 lossage);
525 /* So far this is module number one. */
526 bootstrap_map.l_tls_modid = 1;
528 /* There can only be one PT_TLS entry. */
529 break;
531 #endif /* USE___THREAD */
533 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
534 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
535 #endif
537 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
539 /* Relocate ourselves so we can do normal function calls and
540 data access using the global offset table. */
542 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
544 bootstrap_map.l_relocated = 1;
546 /* Please note that we don't allow profiling of this object and
547 therefore need not test whether we have to allocate the array
548 for the relocation results (as done in dl-reloc.c). */
550 /* Now life is sane; we can call functions and access global data.
551 Set up to use the operating system facilities, and find out from
552 the operating system's program loader where to find the program
553 header table in core. Put the rest of _dl_start into a separate
554 function, that way the compiler cannot put accesses to the GOT
555 before ELF_DYNAMIC_RELOCATE. */
557 #ifdef DONT_USE_BOOTSTRAP_MAP
558 ElfW(Addr) entry = _dl_start_final (arg);
559 #else
560 ElfW(Addr) entry = _dl_start_final (arg, &info);
561 #endif
563 #ifndef ELF_MACHINE_START_ADDRESS
564 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
565 #endif
567 return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, entry);
573 /* Now life is peachy; we can do all normal operations.
574 On to the real work. */
576 /* Some helper functions. */
578 /* Arguments to relocate_doit. */
579 struct relocate_args
581 struct link_map *l;
582 int reloc_mode;
585 struct map_args
587 /* Argument to map_doit. */
588 char *str;
589 struct link_map *loader;
590 int is_preloaded;
591 int mode;
592 /* Return value of map_doit. */
593 struct link_map *map;
596 struct dlmopen_args
598 const char *fname;
599 struct link_map *map;
602 struct lookup_args
604 const char *name;
605 struct link_map *map;
606 void *result;
609 /* Arguments to version_check_doit. */
610 struct version_check_args
612 int doexit;
613 int dotrace;
616 static void
617 relocate_doit (void *a)
619 struct relocate_args *args = (struct relocate_args *) a;
621 _dl_relocate_object (args->l, args->l->l_scope, args->reloc_mode, 0);
624 static void
625 map_doit (void *a)
627 struct map_args *args = (struct map_args *) a;
628 args->map = _dl_map_object (args->loader, args->str,
629 args->is_preloaded, lt_library, 0, args->mode,
630 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, RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT,
638 dl_main, LM_ID_NEWLM, _dl_argc, INTUSE(_dl_argv),
639 __environ);
642 static void
643 lookup_doit (void *a)
645 struct lookup_args *args = (struct lookup_args *) a;
646 const ElfW(Sym) *ref = NULL;
647 args->result = NULL;
648 lookup_t l = _dl_lookup_symbol_x (args->name, args->map, &ref,
649 args->map->l_local_scope, NULL, 0,
650 DL_LOOKUP_RETURN_NEWEST, NULL);
651 if (ref != NULL)
652 args->result = DL_SYMBOL_ADDRESS (l, ref);
655 static void
656 version_check_doit (void *a)
658 struct version_check_args *args = (struct version_check_args *) a;
659 if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
660 args->dotrace) && args->doexit)
661 /* We cannot start the application. Abort now. */
662 _exit (1);
666 static inline struct link_map *
667 find_needed (const char *name)
669 struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
670 unsigned int n = scope->r_nlist;
672 while (n-- > 0)
673 if (_dl_name_match_p (name, scope->r_list[n]))
674 return scope->r_list[n];
676 /* Should never happen. */
677 return NULL;
680 static int
681 match_version (const char *string, struct link_map *map)
683 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
684 ElfW(Verdef) *def;
686 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
687 if (map->l_info[VERDEFTAG] == NULL)
688 /* The file has no symbol versioning. */
689 return 0;
691 def = (ElfW(Verdef) *) ((char *) map->l_addr
692 + map->l_info[VERDEFTAG]->d_un.d_ptr);
693 while (1)
695 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
697 /* Compare the version strings. */
698 if (strcmp (string, strtab + aux->vda_name) == 0)
699 /* Bingo! */
700 return 1;
702 /* If no more definitions we failed to find what we want. */
703 if (def->vd_next == 0)
704 break;
706 /* Next definition. */
707 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
710 return 0;
713 static bool tls_init_tp_called;
715 static void *
716 init_tls (void)
718 /* Number of elements in the static TLS block. */
719 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
721 /* Do not do this twice. The audit interface might have required
722 the DTV interfaces to be set up early. */
723 if (GL(dl_initial_dtv) != NULL)
724 return NULL;
726 /* Allocate the array which contains the information about the
727 dtv slots. We allocate a few entries more than needed to
728 avoid the need for reallocation. */
729 size_t nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
731 /* Allocate. */
732 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
733 calloc (sizeof (struct dtv_slotinfo_list)
734 + nelem * sizeof (struct dtv_slotinfo), 1);
735 /* No need to check the return value. If memory allocation failed
736 the program would have been terminated. */
738 struct dtv_slotinfo *slotinfo = GL(dl_tls_dtv_slotinfo_list)->slotinfo;
739 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
740 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
742 /* Fill in the information from the loaded modules. No namespace
743 but the base one can be filled at this time. */
744 assert (GL(dl_ns)[LM_ID_BASE + 1]._ns_loaded == NULL);
745 int i = 0;
746 for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
747 l = l->l_next)
748 if (l->l_tls_blocksize != 0)
750 /* This is a module with TLS data. Store the map reference.
751 The generation counter is zero. */
752 slotinfo[i].map = l;
753 /* slotinfo[i].gen = 0; */
754 ++i;
756 assert (i == GL(dl_tls_max_dtv_idx));
758 /* Compute the TLS offsets for the various blocks. */
759 _dl_determine_tlsoffset ();
761 /* Construct the static TLS block and the dtv for the initial
762 thread. For some platforms this will include allocating memory
763 for the thread descriptor. The memory for the TLS block will
764 never be freed. It should be allocated accordingly. The dtv
765 array can be changed if dynamic loading requires it. */
766 void *tcbp = _dl_allocate_tls_storage ();
767 if (tcbp == NULL)
768 _dl_fatal_printf ("\
769 cannot allocate TLS data structures for initial thread");
771 /* Store for detection of the special case by __tls_get_addr
772 so it knows not to pass this dtv to the normal realloc. */
773 GL(dl_initial_dtv) = GET_DTV (tcbp);
775 /* And finally install it for the main thread. If ld.so itself uses
776 TLS we know the thread pointer was initialized earlier. */
777 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
778 if (__builtin_expect (lossage != NULL, 0))
779 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
780 tls_init_tp_called = true;
782 return tcbp;
785 #ifdef _LIBC_REENTRANT
786 /* _dl_error_catch_tsd points to this for the single-threaded case.
787 It's reset by the thread library for multithreaded programs. */
788 void ** __attribute__ ((const))
789 _dl_initial_error_catch_tsd (void)
791 static void *data;
792 return &data;
794 #endif
797 static unsigned int
798 do_preload (char *fname, struct link_map *main_map, const char *where)
800 const char *objname;
801 const char *err_str = NULL;
802 struct map_args args;
803 bool malloced;
805 args.str = fname;
806 args.loader = main_map;
807 args.is_preloaded = 1;
808 args.mode = 0;
810 unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
812 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
813 if (__builtin_expect (err_str != NULL, 0))
815 _dl_error_printf ("\
816 ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
817 fname, where);
818 /* No need to call free, this is still before
819 the libc's malloc is used. */
821 else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
822 /* It is no duplicate. */
823 return 1;
825 /* Nothing loaded. */
826 return 0;
829 #if defined SHARED && defined _LIBC_REENTRANT \
830 && defined __rtld_lock_default_lock_recursive
831 static void
832 rtld_lock_default_lock_recursive (void *lock)
834 __rtld_lock_default_lock_recursive (lock);
837 static void
838 rtld_lock_default_unlock_recursive (void *lock)
840 __rtld_lock_default_unlock_recursive (lock);
842 #endif
845 static void
846 security_init (void)
848 /* Set up the stack checker's canary. */
849 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard (_dl_random);
850 #ifdef THREAD_SET_STACK_GUARD
851 THREAD_SET_STACK_GUARD (stack_chk_guard);
852 #else
853 __stack_chk_guard = stack_chk_guard;
854 #endif
856 /* Set up the pointer guard as well, if necessary. */
857 if (GLRO(dl_pointer_guard))
859 uintptr_t pointer_chk_guard = _dl_setup_pointer_guard (_dl_random,
860 stack_chk_guard);
861 #ifdef THREAD_SET_POINTER_GUARD
862 THREAD_SET_POINTER_GUARD (pointer_chk_guard);
863 #endif
864 __pointer_chk_guard_local = pointer_chk_guard;
867 /* We do not need the _dl_random value anymore. The less
868 information we leave behind, the better, so clear the
869 variable. */
870 _dl_random = NULL;
874 /* The library search path. */
875 static const char *library_path attribute_relro;
876 /* The list preloaded objects. */
877 static const char *preloadlist attribute_relro;
878 /* Nonzero if information about versions has to be printed. */
879 static int version_info attribute_relro;
881 static void
882 dl_main (const ElfW(Phdr) *phdr,
883 ElfW(Word) phnum,
884 ElfW(Addr) *user_entry,
885 ElfW(auxv_t) *auxv)
887 const ElfW(Phdr) *ph;
888 enum mode mode;
889 struct link_map *main_map;
890 size_t file_size;
891 char *file;
892 bool has_interp = false;
893 unsigned int i;
894 bool prelinked = false;
895 bool rtld_is_main = false;
896 #ifndef HP_TIMING_NONAVAIL
897 hp_timing_t start;
898 hp_timing_t stop;
899 hp_timing_t diff;
900 #endif
901 void *tcbp = NULL;
903 #ifdef _LIBC_REENTRANT
904 /* Explicit initialization since the reloc would just be more work. */
905 GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
906 #endif
908 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
910 #if defined SHARED && defined _LIBC_REENTRANT \
911 && defined __rtld_lock_default_lock_recursive
912 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
913 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
914 #endif
916 /* The explicit initialization here is cheaper than processing the reloc
917 in the _rtld_local definition's initializer. */
918 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
920 /* Process the environment variable which control the behaviour. */
921 process_envvars (&mode);
923 /* Set up a flag which tells we are just starting. */
924 INTUSE(_dl_starting_up) = 1;
926 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
928 /* Ho ho. We are not the program interpreter! We are the program
929 itself! This means someone ran ld.so as a command. Well, that
930 might be convenient to do sometimes. We support it by
931 interpreting the args like this:
933 ld.so PROGRAM ARGS...
935 The first argument is the name of a file containing an ELF
936 executable we will load and run with the following arguments.
937 To simplify life here, PROGRAM is searched for using the
938 normal rules for shared objects, rather than $PATH or anything
939 like that. We just load it and use its entry point; we don't
940 pay attention to its PT_INTERP command (we are the interpreter
941 ourselves). This is an easy way to test a new ld.so before
942 installing it. */
943 rtld_is_main = true;
945 /* Note the place where the dynamic linker actually came from. */
946 GL(dl_rtld_map).l_name = rtld_progname;
948 while (_dl_argc > 1)
949 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
951 mode = list;
952 GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
954 ++_dl_skip_args;
955 --_dl_argc;
956 ++INTUSE(_dl_argv);
958 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
960 mode = verify;
962 ++_dl_skip_args;
963 --_dl_argc;
964 ++INTUSE(_dl_argv);
966 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
967 && _dl_argc > 2)
969 library_path = INTUSE(_dl_argv)[2];
971 _dl_skip_args += 2;
972 _dl_argc -= 2;
973 INTUSE(_dl_argv) += 2;
975 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
976 && _dl_argc > 2)
978 GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
980 _dl_skip_args += 2;
981 _dl_argc -= 2;
982 INTUSE(_dl_argv) += 2;
984 else if (! strcmp (INTUSE(_dl_argv)[1], "--audit") && _dl_argc > 2)
986 process_dl_audit (INTUSE(_dl_argv)[2]);
988 _dl_skip_args += 2;
989 _dl_argc -= 2;
990 INTUSE(_dl_argv) += 2;
992 else
993 break;
995 /* If we have no further argument the program was called incorrectly.
996 Grant the user some education. */
997 if (_dl_argc < 2)
998 _dl_fatal_printf ("\
999 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
1000 You have invoked `ld.so', the helper program for shared library executables.\n\
1001 This program usually lives in the file `/lib/ld.so', and special directives\n\
1002 in executable files using ELF shared libraries tell the system's program\n\
1003 loader to load the helper program from this file. This helper program loads\n\
1004 the shared libraries needed by the program executable, prepares the program\n\
1005 to run, and runs it. You may invoke this helper program directly from the\n\
1006 command line to load and run an ELF executable file; this is like executing\n\
1007 that file itself, but always uses this helper program from the file you\n\
1008 specified, instead of the helper program file specified in the executable\n\
1009 file you run. This is mostly of use for maintainers to test new versions\n\
1010 of this helper program; chances are you did not intend to run this program.\n\
1012 --list list all dependencies and how they are resolved\n\
1013 --verify verify that given object really is a dynamically linked\n\
1014 object we can handle\n\
1015 --library-path PATH use given PATH instead of content of the environment\n\
1016 variable LD_LIBRARY_PATH\n\
1017 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
1018 in LIST\n\
1019 --audit LIST use objects named in LIST as auditors\n");
1021 ++_dl_skip_args;
1022 --_dl_argc;
1023 ++INTUSE(_dl_argv);
1025 /* The initialization of _dl_stack_flags done below assumes the
1026 executable's PT_GNU_STACK may have been honored by the kernel, and
1027 so a PT_GNU_STACK with PF_X set means the stack started out with
1028 execute permission. However, this is not really true if the
1029 dynamic linker is the executable the kernel loaded. For this
1030 case, we must reinitialize _dl_stack_flags to match the dynamic
1031 linker itself. If the dynamic linker was built with a
1032 PT_GNU_STACK, then the kernel may have loaded us with a
1033 nonexecutable stack that we will have to make executable when we
1034 load the program below unless it has a PT_GNU_STACK indicating
1035 nonexecutable stack is ok. */
1037 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1038 if (ph->p_type == PT_GNU_STACK)
1040 GL(dl_stack_flags) = ph->p_flags;
1041 break;
1044 if (__builtin_expect (mode, normal) == verify)
1046 const char *objname;
1047 const char *err_str = NULL;
1048 struct map_args args;
1049 bool malloced;
1051 args.str = rtld_progname;
1052 args.loader = NULL;
1053 args.is_preloaded = 0;
1054 args.mode = __RTLD_OPENEXEC;
1055 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
1056 &args);
1057 if (__builtin_expect (err_str != NULL, 0))
1058 /* We don't free the returned string, the programs stops
1059 anyway. */
1060 _exit (EXIT_FAILURE);
1062 else
1064 HP_TIMING_NOW (start);
1065 _dl_map_object (NULL, rtld_progname, 0, lt_library, 0,
1066 __RTLD_OPENEXEC, LM_ID_BASE);
1067 HP_TIMING_NOW (stop);
1069 HP_TIMING_DIFF (load_time, start, stop);
1072 /* Now the map for the main executable is available. */
1073 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1075 phdr = main_map->l_phdr;
1076 phnum = main_map->l_phnum;
1077 /* We overwrite here a pointer to a malloc()ed string. But since
1078 the malloc() implementation used at this point is the dummy
1079 implementations which has no real free() function it does not
1080 makes sense to free the old string first. */
1081 main_map->l_name = (char *) "";
1082 *user_entry = main_map->l_entry;
1084 #ifdef HAVE_AUX_VECTOR
1085 /* Adjust the on-stack auxiliary vector so that it looks like the
1086 binary was executed directly. */
1087 for (ElfW(auxv_t) *av = auxv; av->a_type != AT_NULL; av++)
1088 switch (av->a_type)
1090 case AT_PHDR:
1091 av->a_un.a_val = (uintptr_t) phdr;
1092 break;
1093 case AT_PHNUM:
1094 av->a_un.a_val = phnum;
1095 break;
1096 case AT_ENTRY:
1097 av->a_un.a_val = *user_entry;
1098 break;
1100 #endif
1102 else
1104 /* Create a link_map for the executable itself.
1105 This will be what dlopen on "" returns. */
1106 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1107 __RTLD_OPENEXEC, LM_ID_BASE);
1108 assert (main_map != NULL);
1109 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
1110 main_map->l_phdr = phdr;
1111 main_map->l_phnum = phnum;
1112 main_map->l_entry = *user_entry;
1114 /* At this point we are in a bit of trouble. We would have to
1115 fill in the values for l_dev and l_ino. But in general we
1116 do not know where the file is. We also do not handle AT_EXECFD
1117 even if it would be passed up.
1119 We leave the values here defined to 0. This is normally no
1120 problem as the program code itself is normally no shared
1121 object and therefore cannot be loaded dynamically. Nothing
1122 prevent the use of dynamic binaries and in these situations
1123 we might get problems. We might not be able to find out
1124 whether the object is already loaded. But since there is no
1125 easy way out and because the dynamic binary must also not
1126 have an SONAME we ignore this program for now. If it becomes
1127 a problem we can force people using SONAMEs. */
1129 /* We delay initializing the path structure until we got the dynamic
1130 information for the program. */
1133 main_map->l_map_end = 0;
1134 main_map->l_text_end = 0;
1135 /* Perhaps the executable has no PT_LOAD header entries at all. */
1136 main_map->l_map_start = ~0;
1137 /* And it was opened directly. */
1138 ++main_map->l_direct_opencount;
1140 /* Scan the program header table for the dynamic section. */
1141 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1142 switch (ph->p_type)
1144 case PT_PHDR:
1145 /* Find out the load address. */
1146 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1147 break;
1148 case PT_DYNAMIC:
1149 /* This tells us where to find the dynamic section,
1150 which tells us everything we need to do. */
1151 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
1152 break;
1153 case PT_INTERP:
1154 /* This "interpreter segment" was used by the program loader to
1155 find the program interpreter, which is this program itself, the
1156 dynamic linker. We note what name finds us, so that a future
1157 dlopen call or DT_NEEDED entry, for something that wants to link
1158 against the dynamic linker as a shared library, will know that
1159 the shared object is already loaded. */
1160 _dl_rtld_libname.name = ((const char *) main_map->l_addr
1161 + ph->p_vaddr);
1162 /* _dl_rtld_libname.next = NULL; Already zero. */
1163 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1165 /* Ordinarilly, we would get additional names for the loader from
1166 our DT_SONAME. This can't happen if we were actually linked as
1167 a static executable (detect this case when we have no DYNAMIC).
1168 If so, assume the filename component of the interpreter path to
1169 be our SONAME, and add it to our name list. */
1170 if (GL(dl_rtld_map).l_ld == NULL)
1172 const char *p = NULL;
1173 const char *cp = _dl_rtld_libname.name;
1175 /* Find the filename part of the path. */
1176 while (*cp != '\0')
1177 if (*cp++ == '/')
1178 p = cp;
1180 if (p != NULL)
1182 _dl_rtld_libname2.name = p;
1183 /* _dl_rtld_libname2.next = NULL; Already zero. */
1184 _dl_rtld_libname.next = &_dl_rtld_libname2;
1188 has_interp = true;
1189 break;
1190 case PT_LOAD:
1192 ElfW(Addr) mapstart;
1193 ElfW(Addr) allocend;
1195 /* Remember where the main program starts in memory. */
1196 mapstart = (main_map->l_addr
1197 + (ph->p_vaddr & ~(GLRO(dl_pagesize) - 1)));
1198 if (main_map->l_map_start > mapstart)
1199 main_map->l_map_start = mapstart;
1201 /* Also where it ends. */
1202 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1203 if (main_map->l_map_end < allocend)
1204 main_map->l_map_end = allocend;
1205 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1206 main_map->l_text_end = allocend;
1208 break;
1210 case PT_TLS:
1211 if (ph->p_memsz > 0)
1213 /* Note that in the case the dynamic linker we duplicate work
1214 here since we read the PT_TLS entry already in
1215 _dl_start_final. But the result is repeatable so do not
1216 check for this special but unimportant case. */
1217 main_map->l_tls_blocksize = ph->p_memsz;
1218 main_map->l_tls_align = ph->p_align;
1219 if (ph->p_align == 0)
1220 main_map->l_tls_firstbyte_offset = 0;
1221 else
1222 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1223 & (ph->p_align - 1));
1224 main_map->l_tls_initimage_size = ph->p_filesz;
1225 main_map->l_tls_initimage = (void *) ph->p_vaddr;
1227 /* This image gets the ID one. */
1228 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1230 break;
1232 case PT_GNU_STACK:
1233 GL(dl_stack_flags) = ph->p_flags;
1234 break;
1236 case PT_GNU_RELRO:
1237 main_map->l_relro_addr = ph->p_vaddr;
1238 main_map->l_relro_size = ph->p_memsz;
1239 break;
1242 /* Adjust the address of the TLS initialization image in case
1243 the executable is actually an ET_DYN object. */
1244 if (main_map->l_tls_initimage != NULL)
1245 main_map->l_tls_initimage
1246 = (char *) main_map->l_tls_initimage + main_map->l_addr;
1247 if (! main_map->l_map_end)
1248 main_map->l_map_end = ~0;
1249 if (! main_map->l_text_end)
1250 main_map->l_text_end = ~0;
1251 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1253 /* We were invoked directly, so the program might not have a
1254 PT_INTERP. */
1255 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1256 /* _dl_rtld_libname.next = NULL; Already zero. */
1257 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1259 else
1260 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1262 /* If the current libname is different from the SONAME, add the
1263 latter as well. */
1264 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1265 && strcmp (GL(dl_rtld_map).l_libname->name,
1266 (const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1267 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1269 static struct libname_list newname;
1270 newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1271 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1272 newname.next = NULL;
1273 newname.dont_free = 1;
1275 assert (GL(dl_rtld_map).l_libname->next == NULL);
1276 GL(dl_rtld_map).l_libname->next = &newname;
1278 /* The ld.so must be relocated since otherwise loading audit modules
1279 will fail since they reuse the very same ld.so. */
1280 assert (GL(dl_rtld_map).l_relocated);
1282 if (! rtld_is_main)
1284 /* Extract the contents of the dynamic section for easy access. */
1285 elf_get_dynamic_info (main_map, NULL);
1286 /* Set up our cache of pointers into the hash table. */
1287 _dl_setup_hash (main_map);
1290 if (__builtin_expect (mode, normal) == verify)
1292 /* We were called just to verify that this is a dynamic
1293 executable using us as the program interpreter. Exit with an
1294 error if we were not able to load the binary or no interpreter
1295 is specified (i.e., this is no dynamically linked binary. */
1296 if (main_map->l_ld == NULL)
1297 _exit (1);
1299 /* We allow here some platform specific code. */
1300 #ifdef DISTINGUISH_LIB_VERSIONS
1301 DISTINGUISH_LIB_VERSIONS;
1302 #endif
1303 _exit (has_interp ? 0 : 2);
1306 struct link_map **first_preload = &GL(dl_rtld_map).l_next;
1307 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1308 /* Set up the data structures for the system-supplied DSO early,
1309 so they can influence _dl_init_paths. */
1310 if (GLRO(dl_sysinfo_dso) != NULL)
1312 /* Do an abridged version of the work _dl_map_object_from_fd would do
1313 to map in the object. It's already mapped and prelinked (and
1314 better be, since it's read-only and so we couldn't relocate it).
1315 We just want our data structures to describe it as if we had just
1316 mapped and relocated it normally. */
1317 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL,
1318 0, LM_ID_BASE);
1319 if (__builtin_expect (l != NULL, 1))
1321 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
1323 l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1324 + GLRO(dl_sysinfo_dso)->e_phoff);
1325 l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1326 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1328 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1329 if (ph->p_type == PT_DYNAMIC)
1331 l->l_ld = (void *) ph->p_vaddr;
1332 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1334 else if (ph->p_type == PT_LOAD)
1336 if (! l->l_addr)
1337 l->l_addr = ph->p_vaddr;
1338 if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1339 l->l_map_end = ph->p_vaddr + ph->p_memsz;
1340 if ((ph->p_flags & PF_X)
1341 && ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1342 l->l_text_end = ph->p_vaddr + ph->p_memsz;
1344 else
1345 /* There must be no TLS segment. */
1346 assert (ph->p_type != PT_TLS);
1348 l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1349 l->l_addr = l->l_map_start - l->l_addr;
1350 l->l_map_end += l->l_addr;
1351 l->l_text_end += l->l_addr;
1352 l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1353 elf_get_dynamic_info (l, dyn_temp);
1354 _dl_setup_hash (l);
1355 l->l_relocated = 1;
1357 /* Initialize l_local_scope to contain just this map. This allows
1358 the use of dl_lookup_symbol_x to resolve symbols within the vdso.
1359 So we create a single entry list pointing to l_real as its only
1360 element */
1361 l->l_local_scope[0]->r_nlist = 1;
1362 l->l_local_scope[0]->r_list = &l->l_real;
1364 /* Now that we have the info handy, use the DSO image's soname
1365 so this object can be looked up by name. Note that we do not
1366 set l_name here. That field gives the file name of the DSO,
1367 and this DSO is not associated with any file. */
1368 if (l->l_info[DT_SONAME] != NULL)
1370 /* Work around a kernel problem. The kernel cannot handle
1371 addresses in the vsyscall DSO pages in writev() calls. */
1372 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1373 + l->l_info[DT_SONAME]->d_un.d_val);
1374 size_t len = strlen (dsoname);
1375 char *copy = malloc (len);
1376 if (copy == NULL)
1377 _dl_fatal_printf ("out of memory\n");
1378 l->l_libname->name = memcpy (copy, dsoname, len);
1381 /* Rearrange the list so this DSO appears after rtld_map. */
1382 assert (l->l_next == NULL);
1383 assert (l->l_prev == main_map);
1384 GL(dl_rtld_map).l_next = l;
1385 l->l_prev = &GL(dl_rtld_map);
1386 first_preload = &l->l_next;
1388 /* We have a prelinked DSO preloaded by the system. */
1389 GLRO(dl_sysinfo_map) = l;
1390 # ifdef NEED_DL_SYSINFO
1391 if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1392 GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1393 # endif
1396 #endif
1398 #ifdef DL_SYSDEP_OSCHECK
1399 DL_SYSDEP_OSCHECK (dl_fatal);
1400 #endif
1402 /* Initialize the data structures for the search paths for shared
1403 objects. */
1404 _dl_init_paths (library_path);
1406 /* Initialize _r_debug. */
1407 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1408 LM_ID_BASE);
1409 r->r_state = RT_CONSISTENT;
1411 /* Put the link_map for ourselves on the chain so it can be found by
1412 name. Note that at this point the global chain of link maps contains
1413 exactly one element, which is pointed to by dl_loaded. */
1414 if (! GL(dl_rtld_map).l_name)
1415 /* If not invoked directly, the dynamic linker shared object file was
1416 found by the PT_INTERP name. */
1417 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1418 GL(dl_rtld_map).l_type = lt_library;
1419 main_map->l_next = &GL(dl_rtld_map);
1420 GL(dl_rtld_map).l_prev = main_map;
1421 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1422 ++GL(dl_load_adds);
1424 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1425 to not using bias for non-prelinked PIEs and libraries
1426 and using it for executables or prelinked PIEs or libraries. */
1427 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1428 GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
1430 /* Set up the program header information for the dynamic linker
1431 itself. It is needed in the dl_iterate_phdr() callbacks. */
1432 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1433 ElfW(Phdr) *rtld_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1434 + rtld_ehdr->e_phoff);
1435 GL(dl_rtld_map).l_phdr = rtld_phdr;
1436 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1439 /* PT_GNU_RELRO is usually the last phdr. */
1440 size_t cnt = rtld_ehdr->e_phnum;
1441 while (cnt-- > 0)
1442 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1444 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1445 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1446 break;
1449 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1450 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1451 /* Assign a module ID. Do this before loading any audit modules. */
1452 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1454 /* If we have auditing DSOs to load, do it now. */
1455 if (__builtin_expect (audit_list != NULL, 0))
1457 /* Iterate over all entries in the list. The order is important. */
1458 struct audit_ifaces *last_audit = NULL;
1459 struct audit_list *al = audit_list->next;
1461 /* Since we start using the auditing DSOs right away we need to
1462 initialize the data structures now. */
1463 tcbp = init_tls ();
1465 /* Initialize security features. We need to do it this early
1466 since otherwise the constructors of the audit libraries will
1467 use different values (especially the pointer guard) and will
1468 fail later on. */
1469 security_init ();
1473 int tls_idx = GL(dl_tls_max_dtv_idx);
1475 /* Now it is time to determine the layout of the static TLS
1476 block and allocate it for the initial thread. Note that we
1477 always allocate the static block, we never defer it even if
1478 no DF_STATIC_TLS bit is set. The reason is that we know
1479 glibc will use the static model. */
1480 struct dlmopen_args dlmargs;
1481 dlmargs.fname = al->name;
1482 dlmargs.map = NULL;
1484 const char *objname;
1485 const char *err_str = NULL;
1486 bool malloced;
1487 (void) _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit,
1488 &dlmargs);
1489 if (__builtin_expect (err_str != NULL, 0))
1491 not_loaded:
1492 _dl_error_printf ("\
1493 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
1494 al->name, err_str);
1495 if (malloced)
1496 free ((char *) err_str);
1498 else
1500 struct lookup_args largs;
1501 largs.name = "la_version";
1502 largs.map = dlmargs.map;
1504 /* Check whether the interface version matches. */
1505 (void) _dl_catch_error (&objname, &err_str, &malloced,
1506 lookup_doit, &largs);
1508 unsigned int (*laversion) (unsigned int);
1509 unsigned int lav;
1510 if (err_str == NULL
1511 && (laversion = largs.result) != NULL
1512 && (lav = laversion (LAV_CURRENT)) > 0
1513 && lav <= LAV_CURRENT)
1515 /* Allocate structure for the callback function pointers.
1516 This call can never fail. */
1517 union
1519 struct audit_ifaces ifaces;
1520 #define naudit_ifaces 8
1521 void (*fptr[naudit_ifaces]) (void);
1522 } *newp = malloc (sizeof (*newp));
1524 /* Names of the auditing interfaces. All in one
1525 long string. */
1526 static const char audit_iface_names[] =
1527 "la_activity\0"
1528 "la_objsearch\0"
1529 "la_objopen\0"
1530 "la_preinit\0"
1531 #if __ELF_NATIVE_CLASS == 32
1532 "la_symbind32\0"
1533 #elif __ELF_NATIVE_CLASS == 64
1534 "la_symbind64\0"
1535 #else
1536 # error "__ELF_NATIVE_CLASS must be defined"
1537 #endif
1538 #define STRING(s) __STRING (s)
1539 "la_" STRING (ARCH_LA_PLTENTER) "\0"
1540 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
1541 "la_objclose\0";
1542 unsigned int cnt = 0;
1543 const char *cp = audit_iface_names;
1546 largs.name = cp;
1547 (void) _dl_catch_error (&objname, &err_str, &malloced,
1548 lookup_doit, &largs);
1550 /* Store the pointer. */
1551 if (err_str == NULL && largs.result != NULL)
1553 newp->fptr[cnt] = largs.result;
1555 /* The dynamic linker link map is statically
1556 allocated, initialize the data now. */
1557 GL(dl_rtld_map).l_audit[cnt].cookie
1558 = (intptr_t) &GL(dl_rtld_map);
1560 else
1561 newp->fptr[cnt] = NULL;
1562 ++cnt;
1564 cp = (char *) rawmemchr (cp, '\0') + 1;
1566 while (*cp != '\0');
1567 assert (cnt == naudit_ifaces);
1569 /* Now append the new auditing interface to the list. */
1570 newp->ifaces.next = NULL;
1571 if (last_audit == NULL)
1572 last_audit = GLRO(dl_audit) = &newp->ifaces;
1573 else
1574 last_audit = last_audit->next = &newp->ifaces;
1575 ++GLRO(dl_naudit);
1577 /* Mark the DSO as being used for auditing. */
1578 dlmargs.map->l_auditing = 1;
1580 else
1582 /* We cannot use the DSO, it does not have the
1583 appropriate interfaces or it expects something
1584 more recent. */
1585 #ifndef NDEBUG
1586 Lmid_t ns = dlmargs.map->l_ns;
1587 #endif
1588 _dl_close (dlmargs.map);
1590 /* Make sure the namespace has been cleared entirely. */
1591 assert (GL(dl_ns)[ns]._ns_loaded == NULL);
1592 assert (GL(dl_ns)[ns]._ns_nloaded == 0);
1594 GL(dl_tls_max_dtv_idx) = tls_idx;
1595 goto not_loaded;
1599 al = al->next;
1601 while (al != audit_list->next);
1603 /* If we have any auditing modules, announce that we already
1604 have two objects loaded. */
1605 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1607 struct link_map *ls[2] = { main_map, &GL(dl_rtld_map) };
1609 for (unsigned int outer = 0; outer < 2; ++outer)
1611 struct audit_ifaces *afct = GLRO(dl_audit);
1612 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1614 if (afct->objopen != NULL)
1616 ls[outer]->l_audit[cnt].bindflags
1617 = afct->objopen (ls[outer], LM_ID_BASE,
1618 &ls[outer]->l_audit[cnt].cookie);
1620 ls[outer]->l_audit_any_plt
1621 |= ls[outer]->l_audit[cnt].bindflags != 0;
1624 afct = afct->next;
1630 /* Set up debugging before the debugger is notified for the first time. */
1631 #ifdef ELF_MACHINE_DEBUG_SETUP
1632 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1633 ELF_MACHINE_DEBUG_SETUP (main_map, r);
1634 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1635 #else
1636 if (main_map->l_info[DT_DEBUG] != NULL)
1637 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1638 with the run-time address of the r_debug structure */
1639 main_map->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1641 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1642 case you run gdb on the dynamic linker directly. */
1643 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1644 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1645 #endif
1647 /* We start adding objects. */
1648 r->r_state = RT_ADD;
1649 _dl_debug_state ();
1651 /* Auditing checkpoint: we are ready to signal that the initial map
1652 is being constructed. */
1653 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1655 struct audit_ifaces *afct = GLRO(dl_audit);
1656 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1658 if (afct->activity != NULL)
1659 afct->activity (&main_map->l_audit[cnt].cookie, LA_ACT_ADD);
1661 afct = afct->next;
1665 /* We have two ways to specify objects to preload: via environment
1666 variable and via the file /etc/ld.so.preload. The latter can also
1667 be used when security is enabled. */
1668 assert (*first_preload == NULL);
1669 struct link_map **preloads = NULL;
1670 unsigned int npreloads = 0;
1672 if (__builtin_expect (preloadlist != NULL, 0))
1674 /* The LD_PRELOAD environment variable gives list of libraries
1675 separated by white space or colons that are loaded before the
1676 executable's dependencies and prepended to the global scope
1677 list. If the binary is running setuid all elements
1678 containing a '/' are ignored since it is insecure. */
1679 char *list = strdupa (preloadlist);
1680 char *p;
1682 HP_TIMING_NOW (start);
1684 /* Prevent optimizing strsep. Speed is not important here. */
1685 while ((p = (strsep) (&list, " :")) != NULL)
1686 if (p[0] != '\0'
1687 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1688 || strchr (p, '/') == NULL))
1689 npreloads += do_preload (p, main_map, "LD_PRELOAD");
1691 HP_TIMING_NOW (stop);
1692 HP_TIMING_DIFF (diff, start, stop);
1693 HP_TIMING_ACCUM_NT (load_time, diff);
1696 /* There usually is no ld.so.preload file, it should only be used
1697 for emergencies and testing. So the open call etc should usually
1698 fail. Using access() on a non-existing file is faster than using
1699 open(). So we do this first. If it succeeds we do almost twice
1700 the work but this does not matter, since it is not for production
1701 use. */
1702 static const char preload_file[] = "/etc/ld.so.preload";
1703 if (__builtin_expect (__access (preload_file, R_OK) == 0, 0))
1705 /* Read the contents of the file. */
1706 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1707 PROT_READ | PROT_WRITE);
1708 if (__builtin_expect (file != MAP_FAILED, 0))
1710 /* Parse the file. It contains names of libraries to be loaded,
1711 separated by white spaces or `:'. It may also contain
1712 comments introduced by `#'. */
1713 char *problem;
1714 char *runp;
1715 size_t rest;
1717 /* Eliminate comments. */
1718 runp = file;
1719 rest = file_size;
1720 while (rest > 0)
1722 char *comment = memchr (runp, '#', rest);
1723 if (comment == NULL)
1724 break;
1726 rest -= comment - runp;
1728 *comment = ' ';
1729 while (--rest > 0 && *++comment != '\n');
1732 /* We have one problematic case: if we have a name at the end of
1733 the file without a trailing terminating characters, we cannot
1734 place the \0. Handle the case separately. */
1735 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1736 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1738 problem = &file[file_size];
1739 while (problem > file && problem[-1] != ' '
1740 && problem[-1] != '\t'
1741 && problem[-1] != '\n' && problem[-1] != ':')
1742 --problem;
1744 if (problem > file)
1745 problem[-1] = '\0';
1747 else
1749 problem = NULL;
1750 file[file_size - 1] = '\0';
1753 HP_TIMING_NOW (start);
1755 if (file != problem)
1757 char *p;
1758 runp = file;
1759 while ((p = strsep (&runp, ": \t\n")) != NULL)
1760 if (p[0] != '\0')
1761 npreloads += do_preload (p, main_map, preload_file);
1764 if (problem != NULL)
1766 char *p = strndupa (problem, file_size - (problem - file));
1768 npreloads += do_preload (p, main_map, preload_file);
1771 HP_TIMING_NOW (stop);
1772 HP_TIMING_DIFF (diff, start, stop);
1773 HP_TIMING_ACCUM_NT (load_time, diff);
1775 /* We don't need the file anymore. */
1776 __munmap (file, file_size);
1780 if (__builtin_expect (*first_preload != NULL, 0))
1782 /* Set up PRELOADS with a vector of the preloaded libraries. */
1783 struct link_map *l = *first_preload;
1784 preloads = __alloca (npreloads * sizeof preloads[0]);
1785 i = 0;
1788 preloads[i++] = l;
1789 l = l->l_next;
1790 } while (l);
1791 assert (i == npreloads);
1794 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1795 specified some libraries to load, these are inserted before the actual
1796 dependencies in the executable's searchlist for symbol resolution. */
1797 HP_TIMING_NOW (start);
1798 _dl_map_object_deps (main_map, preloads, npreloads, mode == trace, 0);
1799 HP_TIMING_NOW (stop);
1800 HP_TIMING_DIFF (diff, start, stop);
1801 HP_TIMING_ACCUM_NT (load_time, diff);
1803 /* Mark all objects as being in the global scope. */
1804 for (i = main_map->l_searchlist.r_nlist; i > 0; )
1805 main_map->l_searchlist.r_list[--i]->l_global = 1;
1807 /* Remove _dl_rtld_map from the chain. */
1808 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1809 if (GL(dl_rtld_map).l_next != NULL)
1810 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1812 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1813 if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1814 break;
1816 bool rtld_multiple_ref = false;
1817 if (__builtin_expect (i < main_map->l_searchlist.r_nlist, 1))
1819 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1820 put it back in the list of visible objects. We insert it into the
1821 chain in symbol search order because gdb uses the chain's order as
1822 its symbol search order. */
1823 rtld_multiple_ref = true;
1825 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1826 if (__builtin_expect (mode, normal) == normal)
1828 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1829 ? main_map->l_searchlist.r_list[i + 1]
1830 : NULL);
1831 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1832 if (GLRO(dl_sysinfo_map) != NULL
1833 && GL(dl_rtld_map).l_prev->l_next == GLRO(dl_sysinfo_map)
1834 && GL(dl_rtld_map).l_next != GLRO(dl_sysinfo_map))
1835 GL(dl_rtld_map).l_prev = GLRO(dl_sysinfo_map);
1836 #endif
1838 else
1839 /* In trace mode there might be an invisible object (which we
1840 could not find) after the previous one in the search list.
1841 In this case it doesn't matter much where we put the
1842 interpreter object, so we just initialize the list pointer so
1843 that the assertion below holds. */
1844 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1846 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1847 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1848 if (GL(dl_rtld_map).l_next != NULL)
1850 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1851 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1855 /* Now let us see whether all libraries are available in the
1856 versions we need. */
1858 struct version_check_args args;
1859 args.doexit = mode == normal;
1860 args.dotrace = mode == trace;
1861 _dl_receive_error (print_missing_version, version_check_doit, &args);
1864 /* We do not initialize any of the TLS functionality unless any of the
1865 initial modules uses TLS. This makes dynamic loading of modules with
1866 TLS impossible, but to support it requires either eagerly doing setup
1867 now or lazily doing it later. Doing it now makes us incompatible with
1868 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1869 used. Trying to do it lazily is too hairy to try when there could be
1870 multiple threads (from a non-TLS-using libpthread). */
1871 bool was_tls_init_tp_called = tls_init_tp_called;
1872 if (tcbp == NULL)
1873 tcbp = init_tls ();
1875 if (__builtin_expect (audit_list == NULL, 1))
1876 /* Initialize security features. But only if we have not done it
1877 earlier. */
1878 security_init ();
1880 if (__builtin_expect (mode, normal) != normal)
1882 /* We were run just to list the shared libraries. It is
1883 important that we do this before real relocation, because the
1884 functions we call below for output may no longer work properly
1885 after relocation. */
1886 struct link_map *l;
1888 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1890 struct r_scope_elem *scope = &main_map->l_searchlist;
1892 for (i = 0; i < scope->r_nlist; i++)
1894 l = scope->r_list [i];
1895 if (l->l_faked)
1897 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1898 continue;
1900 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1901 GLRO(dl_trace_prelink_map) = l;
1902 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1903 l->l_libname->name[0] ? l->l_libname->name
1904 : rtld_progname ?: "<main program>",
1905 l->l_name[0] ? l->l_name
1906 : rtld_progname ?: "<main program>",
1907 (int) sizeof l->l_map_start * 2,
1908 (size_t) l->l_map_start,
1909 (int) sizeof l->l_addr * 2,
1910 (size_t) l->l_addr);
1912 if (l->l_tls_modid)
1913 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1914 (int) sizeof l->l_tls_offset * 2,
1915 (size_t) l->l_tls_offset);
1916 else
1917 _dl_printf ("\n");
1920 else if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
1922 /* Look through the dependencies of the main executable
1923 and determine which of them is not actually
1924 required. */
1925 struct link_map *l = main_map;
1927 /* Relocate the main executable. */
1928 struct relocate_args args = { .l = l,
1929 .reloc_mode = (GLRO(dl_lazy)
1930 ? RTLD_LAZY : 0) };
1931 _dl_receive_error (print_unresolved, relocate_doit, &args);
1933 /* This loop depends on the dependencies of the executable to
1934 correspond in number and order to the DT_NEEDED entries. */
1935 ElfW(Dyn) *dyn = main_map->l_ld;
1936 bool first = true;
1937 while (dyn->d_tag != DT_NULL)
1939 if (dyn->d_tag == DT_NEEDED)
1941 l = l->l_next;
1943 if (!l->l_used)
1945 if (first)
1947 _dl_printf ("Unused direct dependencies:\n");
1948 first = false;
1951 _dl_printf ("\t%s\n", l->l_name);
1955 ++dyn;
1958 _exit (first != true);
1960 else if (! main_map->l_info[DT_NEEDED])
1961 _dl_printf ("\tstatically linked\n");
1962 else
1964 for (l = main_map->l_next; l; l = l->l_next)
1965 if (l->l_faked)
1966 /* The library was not found. */
1967 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1968 else if (strcmp (l->l_libname->name, l->l_name) == 0)
1969 _dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
1970 (int) sizeof l->l_map_start * 2,
1971 (size_t) l->l_map_start);
1972 else
1973 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1974 l->l_name, (int) sizeof l->l_map_start * 2,
1975 (size_t) l->l_map_start);
1978 if (__builtin_expect (mode, trace) != trace)
1979 for (i = 1; i < (unsigned int) _dl_argc; ++i)
1981 const ElfW(Sym) *ref = NULL;
1982 ElfW(Addr) loadbase;
1983 lookup_t result;
1985 result = _dl_lookup_symbol_x (INTUSE(_dl_argv)[i], main_map,
1986 &ref, main_map->l_scope,
1987 NULL, ELF_RTYPE_CLASS_PLT,
1988 DL_LOOKUP_ADD_DEPENDENCY, NULL);
1990 loadbase = LOOKUP_VALUE_ADDRESS (result);
1992 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
1993 INTUSE(_dl_argv)[i],
1994 (int) sizeof ref->st_value * 2,
1995 (size_t) ref->st_value,
1996 (int) sizeof loadbase * 2, (size_t) loadbase);
1998 else
2000 /* If LD_WARN is set, warn about undefined symbols. */
2001 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
2003 /* We have to do symbol dependency testing. */
2004 struct relocate_args args;
2005 struct link_map *l;
2007 args.reloc_mode = GLRO(dl_lazy) ? RTLD_LAZY : 0;
2009 l = main_map;
2010 while (l->l_next != NULL)
2011 l = l->l_next;
2014 if (l != &GL(dl_rtld_map) && ! l->l_faked)
2016 args.l = l;
2017 _dl_receive_error (print_unresolved, relocate_doit,
2018 &args);
2020 l = l->l_prev;
2022 while (l != NULL);
2024 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
2025 && rtld_multiple_ref)
2027 /* Mark the link map as not yet relocated again. */
2028 GL(dl_rtld_map).l_relocated = 0;
2029 _dl_relocate_object (&GL(dl_rtld_map),
2030 main_map->l_scope, 0, 0);
2033 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
2034 if (version_info)
2036 /* Print more information. This means here, print information
2037 about the versions needed. */
2038 int first = 1;
2039 struct link_map *map;
2041 for (map = main_map; map != NULL; map = map->l_next)
2043 const char *strtab;
2044 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
2045 ElfW(Verneed) *ent;
2047 if (dyn == NULL)
2048 continue;
2050 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
2051 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
2053 if (first)
2055 _dl_printf ("\n\tVersion information:\n");
2056 first = 0;
2059 _dl_printf ("\t%s:\n",
2060 map->l_name[0] ? map->l_name : rtld_progname);
2062 while (1)
2064 ElfW(Vernaux) *aux;
2065 struct link_map *needed;
2067 needed = find_needed (strtab + ent->vn_file);
2068 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
2070 while (1)
2072 const char *fname = NULL;
2074 if (needed != NULL
2075 && match_version (strtab + aux->vna_name,
2076 needed))
2077 fname = needed->l_name;
2079 _dl_printf ("\t\t%s (%s) %s=> %s\n",
2080 strtab + ent->vn_file,
2081 strtab + aux->vna_name,
2082 aux->vna_flags & VER_FLG_WEAK
2083 ? "[WEAK] " : "",
2084 fname ?: "not found");
2086 if (aux->vna_next == 0)
2087 /* No more symbols. */
2088 break;
2090 /* Next symbol. */
2091 aux = (ElfW(Vernaux) *) ((char *) aux
2092 + aux->vna_next);
2095 if (ent->vn_next == 0)
2096 /* No more dependencies. */
2097 break;
2099 /* Next dependency. */
2100 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
2106 _exit (0);
2109 if (main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]
2110 && ! __builtin_expect (GLRO(dl_profile) != NULL, 0)
2111 && ! __builtin_expect (GLRO(dl_dynamic_weak), 0))
2113 ElfW(Lib) *liblist, *liblistend;
2114 struct link_map **r_list, **r_listend, *l;
2115 const char *strtab = (const void *) D_PTR (main_map, l_info[DT_STRTAB]);
2117 assert (main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
2118 liblist = (ElfW(Lib) *)
2119 main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
2120 liblistend = (ElfW(Lib) *)
2121 ((char *) liblist +
2122 main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
2123 r_list = main_map->l_searchlist.r_list;
2124 r_listend = r_list + main_map->l_searchlist.r_nlist;
2126 for (; r_list < r_listend && liblist < liblistend; r_list++)
2128 l = *r_list;
2130 if (l == main_map)
2131 continue;
2133 /* If the library is not mapped where it should, fail. */
2134 if (l->l_addr)
2135 break;
2137 /* Next, check if checksum matches. */
2138 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
2139 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
2140 != liblist->l_checksum)
2141 break;
2143 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
2144 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
2145 != liblist->l_time_stamp)
2146 break;
2148 if (! _dl_name_match_p (strtab + liblist->l_name, l))
2149 break;
2151 ++liblist;
2155 if (r_list == r_listend && liblist == liblistend)
2156 prelinked = true;
2158 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
2159 _dl_debug_printf ("\nprelink checking: %s\n",
2160 prelinked ? "ok" : "failed");
2164 /* Now set up the variable which helps the assembler startup code. */
2165 GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
2167 /* Save the information about the original global scope list since
2168 we need it in the memory handling later. */
2169 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
2171 if (prelinked)
2173 if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
2175 ElfW(Rela) *conflict, *conflictend;
2176 #ifndef HP_TIMING_NONAVAIL
2177 hp_timing_t start;
2178 hp_timing_t stop;
2179 #endif
2181 HP_TIMING_NOW (start);
2182 assert (main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
2183 conflict = (ElfW(Rela) *)
2184 main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
2185 conflictend = (ElfW(Rela) *)
2186 ((char *) conflict
2187 + main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
2188 _dl_resolve_conflicts (main_map, conflict, conflictend);
2189 HP_TIMING_NOW (stop);
2190 HP_TIMING_DIFF (relocate_time, start, stop);
2194 /* Mark all the objects so we know they have been already relocated. */
2195 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2197 l->l_relocated = 1;
2198 if (l->l_relro_size)
2199 _dl_protect_relro (l);
2201 /* Add object to slot information data if necessasy. */
2202 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2203 _dl_add_to_slotinfo (l);
2206 else
2208 /* Now we have all the objects loaded. Relocate them all except for
2209 the dynamic linker itself. We do this in reverse order so that copy
2210 relocs of earlier objects overwrite the data written by later
2211 objects. We do not re-relocate the dynamic linker itself in this
2212 loop because that could result in the GOT entries for functions we
2213 call being changed, and that would break us. It is safe to relocate
2214 the dynamic linker out of order because it has no copy relocs (we
2215 know that because it is self-contained). */
2217 int consider_profiling = GLRO(dl_profile) != NULL;
2218 #ifndef HP_TIMING_NONAVAIL
2219 hp_timing_t start;
2220 hp_timing_t stop;
2221 #endif
2223 /* If we are profiling we also must do lazy reloaction. */
2224 GLRO(dl_lazy) |= consider_profiling;
2226 struct link_map *l = main_map;
2227 while (l->l_next)
2228 l = l->l_next;
2230 HP_TIMING_NOW (start);
2233 /* While we are at it, help the memory handling a bit. We have to
2234 mark some data structures as allocated with the fake malloc()
2235 implementation in ld.so. */
2236 struct libname_list *lnp = l->l_libname->next;
2238 while (__builtin_expect (lnp != NULL, 0))
2240 lnp->dont_free = 1;
2241 lnp = lnp->next;
2244 if (l != &GL(dl_rtld_map))
2245 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy) ? RTLD_LAZY : 0,
2246 consider_profiling);
2248 /* Add object to slot information data if necessasy. */
2249 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2250 _dl_add_to_slotinfo (l);
2252 l = l->l_prev;
2254 while (l);
2255 HP_TIMING_NOW (stop);
2257 HP_TIMING_DIFF (relocate_time, start, stop);
2259 /* Now enable profiling if needed. Like the previous call,
2260 this has to go here because the calls it makes should use the
2261 rtld versions of the functions (particularly calloc()), but it
2262 needs to have _dl_profile_map set up by the relocator. */
2263 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
2264 /* We must prepare the profiling. */
2265 _dl_start_profile ();
2268 #ifndef NONTLS_INIT_TP
2269 # define NONTLS_INIT_TP do { } while (0)
2270 #endif
2272 if (!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2273 ++GL(dl_tls_generation);
2275 /* Now that we have completed relocation, the initializer data
2276 for the TLS blocks has its final values and we can copy them
2277 into the main thread's TLS area, which we allocated above. */
2278 _dl_allocate_tls_init (tcbp);
2280 /* And finally install it for the main thread. If ld.so itself uses
2281 TLS we know the thread pointer was initialized earlier. */
2282 if (! tls_init_tp_called)
2284 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
2285 if (__builtin_expect (lossage != NULL, 0))
2286 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2287 lossage);
2290 if (! prelinked && rtld_multiple_ref)
2292 /* There was an explicit ref to the dynamic linker as a shared lib.
2293 Re-relocate ourselves with user-controlled symbol definitions.
2295 We must do this after TLS initialization in case after this
2296 re-relocation, we might call a user-supplied function
2297 (e.g. calloc from _dl_relocate_object) that uses TLS data. */
2299 #ifndef HP_TIMING_NONAVAIL
2300 hp_timing_t start;
2301 hp_timing_t stop;
2302 hp_timing_t add;
2303 #endif
2305 HP_TIMING_NOW (start);
2306 /* Mark the link map as not yet relocated again. */
2307 GL(dl_rtld_map).l_relocated = 0;
2308 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2309 HP_TIMING_NOW (stop);
2310 HP_TIMING_DIFF (add, start, stop);
2311 HP_TIMING_ACCUM_NT (relocate_time, add);
2314 /* Do any necessary cleanups for the startup OS interface code.
2315 We do these now so that no calls are made after rtld re-relocation
2316 which might be resolved to different functions than we expect.
2317 We cannot do this before relocating the other objects because
2318 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2319 _dl_sysdep_start_cleanup ();
2321 #ifdef SHARED
2322 /* Auditing checkpoint: we have added all objects. */
2323 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
2325 struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2326 /* Do not call the functions for any auditing object. */
2327 if (head->l_auditing == 0)
2329 struct audit_ifaces *afct = GLRO(dl_audit);
2330 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2332 if (afct->activity != NULL)
2333 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
2335 afct = afct->next;
2339 #endif
2341 /* Notify the debugger all new objects are now ready to go. We must re-get
2342 the address since by now the variable might be in another object. */
2343 r = _dl_debug_initialize (0, LM_ID_BASE);
2344 r->r_state = RT_CONSISTENT;
2345 _dl_debug_state ();
2347 #ifndef MAP_COPY
2348 /* We must munmap() the cache file. */
2349 _dl_unload_cache ();
2350 #endif
2352 /* Once we return, _dl_sysdep_start will invoke
2353 the DT_INIT functions and then *USER_ENTRY. */
2356 /* This is a little helper function for resolving symbols while
2357 tracing the binary. */
2358 static void
2359 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2360 const char *errstring)
2362 if (objname[0] == '\0')
2363 objname = rtld_progname ?: "<main program>";
2364 _dl_error_printf ("%s (%s)\n", errstring, objname);
2367 /* This is a little helper function for resolving symbols while
2368 tracing the binary. */
2369 static void
2370 print_missing_version (int errcode __attribute__ ((unused)),
2371 const char *objname, const char *errstring)
2373 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
2374 objname, errstring);
2377 /* Nonzero if any of the debugging options is enabled. */
2378 static int any_debug attribute_relro;
2380 /* Process the string given as the parameter which explains which debugging
2381 options are enabled. */
2382 static void
2383 process_dl_debug (const char *dl_debug)
2385 /* When adding new entries make sure that the maximal length of a name
2386 is correctly handled in the LD_DEBUG_HELP code below. */
2387 static const struct
2389 unsigned char len;
2390 const char name[10];
2391 const char helptext[41];
2392 unsigned short int mask;
2393 } debopts[] =
2395 #define LEN_AND_STR(str) sizeof (str) - 1, str
2396 { LEN_AND_STR ("libs"), "display library search paths",
2397 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2398 { LEN_AND_STR ("reloc"), "display relocation processing",
2399 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2400 { LEN_AND_STR ("files"), "display progress for input file",
2401 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2402 { LEN_AND_STR ("symbols"), "display symbol table processing",
2403 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2404 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2405 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2406 { LEN_AND_STR ("versions"), "display version dependencies",
2407 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2408 { LEN_AND_STR ("all"), "all previous options combined",
2409 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2410 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2411 { LEN_AND_STR ("statistics"), "display relocation statistics",
2412 DL_DEBUG_STATISTICS },
2413 { LEN_AND_STR ("unused"), "determined unused DSOs",
2414 DL_DEBUG_UNUSED },
2415 { LEN_AND_STR ("help"), "display this help message and exit",
2416 DL_DEBUG_HELP },
2418 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2420 /* Skip separating white spaces and commas. */
2421 while (*dl_debug != '\0')
2423 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2425 size_t cnt;
2426 size_t len = 1;
2428 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2429 && dl_debug[len] != ',' && dl_debug[len] != ':')
2430 ++len;
2432 for (cnt = 0; cnt < ndebopts; ++cnt)
2433 if (debopts[cnt].len == len
2434 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
2436 GLRO(dl_debug_mask) |= debopts[cnt].mask;
2437 any_debug = 1;
2438 break;
2441 if (cnt == ndebopts)
2443 /* Display a warning and skip everything until next
2444 separator. */
2445 char *copy = strndupa (dl_debug, len);
2446 _dl_error_printf ("\
2447 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2450 dl_debug += len;
2451 continue;
2454 ++dl_debug;
2457 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
2459 size_t cnt;
2461 _dl_printf ("\
2462 Valid options for the LD_DEBUG environment variable are:\n\n");
2464 for (cnt = 0; cnt < ndebopts; ++cnt)
2465 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2466 " " + debopts[cnt].len - 3,
2467 debopts[cnt].helptext);
2469 _dl_printf ("\n\
2470 To direct the debugging output into a file instead of standard output\n\
2471 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2472 _exit (0);
2476 static void
2477 process_dl_audit (char *str)
2479 /* The parameter is a colon separated list of DSO names. */
2480 char *p;
2482 while ((p = (strsep) (&str, ":")) != NULL)
2483 if (p[0] != '\0'
2484 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
2485 || strchr (p, '/') == NULL))
2487 /* This is using the local malloc, not the system malloc. The
2488 memory can never be freed. */
2489 struct audit_list *newp = malloc (sizeof (*newp));
2490 newp->name = p;
2492 if (audit_list == NULL)
2493 audit_list = newp->next = newp;
2494 else
2496 newp->next = audit_list->next;
2497 audit_list = audit_list->next = newp;
2502 /* Process all environments variables the dynamic linker must recognize.
2503 Since all of them start with `LD_' we are a bit smarter while finding
2504 all the entries. */
2505 extern char **_environ attribute_hidden;
2508 static void
2509 process_envvars (enum mode *modep)
2511 char **runp = _environ;
2512 char *envline;
2513 enum mode mode = normal;
2514 char *debug_output = NULL;
2516 /* This is the default place for profiling data file. */
2517 GLRO(dl_profile_output)
2518 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2520 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2522 size_t len = 0;
2524 while (envline[len] != '\0' && envline[len] != '=')
2525 ++len;
2527 if (envline[len] != '=')
2528 /* This is a "LD_" variable at the end of the string without
2529 a '=' character. Ignore it since otherwise we will access
2530 invalid memory below. */
2531 continue;
2533 switch (len)
2535 case 4:
2536 /* Warning level, verbose or not. */
2537 if (memcmp (envline, "WARN", 4) == 0)
2538 GLRO(dl_verbose) = envline[5] != '\0';
2539 break;
2541 case 5:
2542 /* Debugging of the dynamic linker? */
2543 if (memcmp (envline, "DEBUG", 5) == 0)
2545 process_dl_debug (&envline[6]);
2546 break;
2548 if (memcmp (envline, "AUDIT", 5) == 0)
2549 process_dl_audit (&envline[6]);
2550 break;
2552 case 7:
2553 /* Print information about versions. */
2554 if (memcmp (envline, "VERBOSE", 7) == 0)
2556 version_info = envline[8] != '\0';
2557 break;
2560 /* List of objects to be preloaded. */
2561 if (memcmp (envline, "PRELOAD", 7) == 0)
2563 preloadlist = &envline[8];
2564 break;
2567 /* Which shared object shall be profiled. */
2568 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2569 GLRO(dl_profile) = &envline[8];
2570 break;
2572 case 8:
2573 /* Do we bind early? */
2574 if (memcmp (envline, "BIND_NOW", 8) == 0)
2576 GLRO(dl_lazy) = envline[9] == '\0';
2577 break;
2579 if (memcmp (envline, "BIND_NOT", 8) == 0)
2580 GLRO(dl_bind_not) = envline[9] != '\0';
2581 break;
2583 case 9:
2584 /* Test whether we want to see the content of the auxiliary
2585 array passed up from the kernel. */
2586 if (!INTUSE(__libc_enable_secure)
2587 && memcmp (envline, "SHOW_AUXV", 9) == 0)
2588 _dl_show_auxv ();
2589 break;
2591 case 10:
2592 /* Mask for the important hardware capabilities. */
2593 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2594 GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2595 0, 0);
2596 break;
2598 case 11:
2599 /* Path where the binary is found. */
2600 if (!INTUSE(__libc_enable_secure)
2601 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2602 GLRO(dl_origin_path) = &envline[12];
2603 break;
2605 case 12:
2606 /* The library search path. */
2607 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2609 library_path = &envline[13];
2610 break;
2613 /* Where to place the profiling data file. */
2614 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2616 debug_output = &envline[13];
2617 break;
2620 if (!INTUSE(__libc_enable_secure)
2621 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2622 GLRO(dl_dynamic_weak) = 1;
2623 break;
2625 case 13:
2626 /* We might have some extra environment variable with length 13
2627 to handle. */
2628 #ifdef EXTRA_LD_ENVVARS_13
2629 EXTRA_LD_ENVVARS_13
2630 #endif
2631 if (!INTUSE(__libc_enable_secure)
2632 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2634 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2635 break;
2638 if (memcmp (envline, "POINTER_GUARD", 13) == 0)
2639 GLRO(dl_pointer_guard) = envline[14] != '0';
2640 break;
2642 case 14:
2643 /* Where to place the profiling data file. */
2644 if (!INTUSE(__libc_enable_secure)
2645 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2646 && envline[15] != '\0')
2647 GLRO(dl_profile_output) = &envline[15];
2648 break;
2650 case 16:
2651 /* The mode of the dynamic linker can be set. */
2652 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2654 mode = trace;
2655 GLRO(dl_verbose) = 1;
2656 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2657 GLRO(dl_trace_prelink) = &envline[17];
2659 break;
2661 case 20:
2662 /* The mode of the dynamic linker can be set. */
2663 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2664 mode = trace;
2665 break;
2667 /* We might have some extra environment variable to handle. This
2668 is tricky due to the pre-processing of the length of the name
2669 in the switch statement here. The code here assumes that added
2670 environment variables have a different length. */
2671 #ifdef EXTRA_LD_ENVVARS
2672 EXTRA_LD_ENVVARS
2673 #endif
2677 /* The caller wants this information. */
2678 *modep = mode;
2680 /* Extra security for SUID binaries. Remove all dangerous environment
2681 variables. */
2682 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2684 static const char unsecure_envvars[] =
2685 #ifdef EXTRA_UNSECURE_ENVVARS
2686 EXTRA_UNSECURE_ENVVARS
2687 #endif
2688 UNSECURE_ENVVARS;
2689 const char *nextp;
2691 nextp = unsecure_envvars;
2694 unsetenv (nextp);
2695 /* We could use rawmemchr but this need not be fast. */
2696 nextp = (char *) (strchr) (nextp, '\0') + 1;
2698 while (*nextp != '\0');
2700 if (__access ("/etc/suid-debug", F_OK) != 0)
2702 unsetenv ("MALLOC_CHECK_");
2703 GLRO(dl_debug_mask) = 0;
2706 if (mode != normal)
2707 _exit (5);
2709 /* If we have to run the dynamic linker in debugging mode and the
2710 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2711 messages to this file. */
2712 else if (any_debug && debug_output != NULL)
2714 #ifdef O_NOFOLLOW
2715 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2716 #else
2717 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2718 #endif
2719 size_t name_len = strlen (debug_output);
2720 char buf[name_len + 12];
2721 char *startp;
2723 buf[name_len + 11] = '\0';
2724 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2725 *--startp = '.';
2726 startp = memcpy (startp - name_len, debug_output, name_len);
2728 GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2729 if (GLRO(dl_debug_fd) == -1)
2730 /* We use standard output if opening the file failed. */
2731 GLRO(dl_debug_fd) = STDOUT_FILENO;
2736 /* Print the various times we collected. */
2737 static void
2738 __attribute ((noinline))
2739 print_statistics (hp_timing_t *rtld_total_timep)
2741 #ifndef HP_TIMING_NONAVAIL
2742 char buf[200];
2743 char *cp;
2744 char *wp;
2746 /* Total time rtld used. */
2747 if (HP_TIMING_AVAIL)
2749 HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2750 _dl_debug_printf ("\nruntime linker statistics:\n"
2751 " total startup time in dynamic loader: %s\n", buf);
2753 /* Print relocation statistics. */
2754 char pbuf[30];
2755 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2756 cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2757 pbuf + sizeof (pbuf), 10, 0);
2758 wp = pbuf;
2759 switch (pbuf + sizeof (pbuf) - cp)
2761 case 3:
2762 *wp++ = *cp++;
2763 case 2:
2764 *wp++ = *cp++;
2765 case 1:
2766 *wp++ = '.';
2767 *wp++ = *cp++;
2769 *wp = '\0';
2770 _dl_debug_printf ("\
2771 time needed for relocation: %s (%s%%)\n", buf, pbuf);
2773 #endif
2775 unsigned long int num_relative_relocations = 0;
2776 for (Lmid_t ns = 0; ns < GL(dl_nns); ++ns)
2778 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2779 continue;
2781 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2783 for (unsigned int i = 0; i < scope->r_nlist; i++)
2785 struct link_map *l = scope->r_list [i];
2787 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2788 num_relative_relocations
2789 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2790 #ifndef ELF_MACHINE_REL_RELATIVE
2791 /* Relative relocations are processed on these architectures if
2792 library is loaded to different address than p_vaddr or
2793 if not prelinked. */
2794 if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2795 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2796 #else
2797 /* On e.g. IA-64 or Alpha, relative relocations are processed
2798 only if library is loaded to different address than p_vaddr. */
2799 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2800 #endif
2801 num_relative_relocations
2802 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2806 _dl_debug_printf (" number of relocations: %lu\n"
2807 " number of relocations from cache: %lu\n"
2808 " number of relative relocations: %lu\n",
2809 GL(dl_num_relocations),
2810 GL(dl_num_cache_relocations),
2811 num_relative_relocations);
2813 #ifndef HP_TIMING_NONAVAIL
2814 /* Time spend while loading the object and the dependencies. */
2815 if (HP_TIMING_AVAIL)
2817 char pbuf[30];
2818 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2819 cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2820 pbuf + sizeof (pbuf), 10, 0);
2821 wp = pbuf;
2822 switch (pbuf + sizeof (pbuf) - cp)
2824 case 3:
2825 *wp++ = *cp++;
2826 case 2:
2827 *wp++ = *cp++;
2828 case 1:
2829 *wp++ = '.';
2830 *wp++ = *cp++;
2832 *wp = '\0';
2833 _dl_debug_printf ("\
2834 time needed to load objects: %s (%s%%)\n",
2835 buf, pbuf);
2837 #endif