Make unistd.h pre-c((-safe.
[glibc.git] / elf / rtld.c
blob55b84c3bf49f569c612af58f886b2e8df6293f06
1 /* Run time dynamic linker.
2 Copyright (C) 1995-2006, 2007, 2008, 2009 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18 02111-1307 USA. */
20 #include <errno.h>
21 #include <dlfcn.h>
22 #include <fcntl.h>
23 #include <stdbool.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <sys/mman.h>
28 #include <sys/param.h>
29 #include <sys/stat.h>
30 #include <ldsodefs.h>
31 #include <stdio-common/_itoa.h>
32 #include <entry.h>
33 #include <fpu_control.h>
34 #include <hp-timing.h>
35 #include <bits/libc-lock.h>
36 #include "dynamic-link.h"
37 #include <dl-librecon.h>
38 #include <unsecvars.h>
39 #include <dl-cache.h>
40 #include <dl-osinfo.h>
41 #include <dl-procinfo.h>
42 #include <tls.h>
44 #include <assert.h>
46 /* Avoid PLT use for our local calls at startup. */
47 extern __typeof (__mempcpy) __mempcpy attribute_hidden;
49 /* GCC has mental blocks about _exit. */
50 extern __typeof (_exit) exit_internal asm ("_exit") attribute_hidden;
51 #define _exit exit_internal
53 /* Helper function to handle errors while resolving symbols. */
54 static void print_unresolved (int errcode, const char *objname,
55 const char *errsting);
57 /* Helper function to handle errors when a version is missing. */
58 static void print_missing_version (int errcode, const char *objname,
59 const char *errsting);
61 /* Print the various times we collected. */
62 static void print_statistics (hp_timing_t *total_timep);
64 /* Add audit objects. */
65 static void process_dl_audit (char *str);
67 /* This is a list of all the modes the dynamic loader can be in. */
68 enum mode { normal, list, verify, trace };
70 /* Process all environments variables the dynamic linker must recognize.
71 Since all of them start with `LD_' we are a bit smarter while finding
72 all the entries. */
73 static void process_envvars (enum mode *modep);
75 #ifdef DL_ARGV_NOT_RELRO
76 int _dl_argc attribute_hidden;
77 char **_dl_argv = NULL;
78 /* Nonzero if we were run directly. */
79 unsigned int _dl_skip_args attribute_hidden;
80 #else
81 int _dl_argc attribute_relro attribute_hidden;
82 char **_dl_argv attribute_relro = NULL;
83 unsigned int _dl_skip_args attribute_relro attribute_hidden;
84 #endif
85 INTDEF(_dl_argv)
87 #ifndef THREAD_SET_STACK_GUARD
88 /* Only exported for architectures that don't store the stack guard canary
89 in thread local area. */
90 uintptr_t __stack_chk_guard attribute_relro;
91 #endif
93 /* Only exported for architectures that don't store the pointer guard
94 value in thread local area. */
95 uintptr_t __pointer_chk_guard_local
96 attribute_relro attribute_hidden __attribute__ ((nocommon));
97 #ifndef THREAD_SET_POINTER_GUARD
98 strong_alias (__pointer_chk_guard_local, __pointer_chk_guard)
99 #endif
102 /* List of auditing DSOs. */
103 static struct audit_list
105 const char *name;
106 struct audit_list *next;
107 } *audit_list;
109 #ifndef HAVE_INLINED_SYSCALLS
110 /* Set nonzero during loading and initialization of executable and
111 libraries, cleared before the executable's entry point runs. This
112 must not be initialized to nonzero, because the unused dynamic
113 linker loaded in for libc.so's "ld.so.1" dep will provide the
114 definition seen by libc.so's initializer; that value must be zero,
115 and will be since that dynamic linker's _dl_start and dl_main will
116 never be called. */
117 int _dl_starting_up = 0;
118 INTVARDEF(_dl_starting_up)
119 #endif
121 /* This is the structure which defines all variables global to ld.so
122 (except those which cannot be added for some reason). */
123 struct rtld_global _rtld_global =
125 /* Default presumption without further information is executable stack. */
126 ._dl_stack_flags = PF_R|PF_W|PF_X,
127 #ifdef _LIBC_REENTRANT
128 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
129 #endif
130 ._dl_nns = 1,
131 ._dl_ns =
133 [LM_ID_BASE] = { ._ns_unique_sym_table
134 = { .lock = _RTLD_LOCK_RECURSIVE_INITIALIZER } }
137 /* If we would use strong_alias here the compiler would see a
138 non-hidden definition. This would undo the effect of the previous
139 declaration. So spell out was strong_alias does plus add the
140 visibility attribute. */
141 extern struct rtld_global _rtld_local
142 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
145 /* This variable is similar to _rtld_local, but all values are
146 read-only after relocation. */
147 struct rtld_global_ro _rtld_global_ro attribute_relro =
149 /* Get architecture specific initializer. */
150 #include <dl-procinfo.c>
151 #ifdef NEED_DL_SYSINFO
152 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
153 #endif
154 ._dl_debug_fd = STDERR_FILENO,
155 ._dl_use_load_bias = -2,
156 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
157 ._dl_hwcap_mask = HWCAP_IMPORTANT,
158 ._dl_lazy = 1,
159 ._dl_fpu_control = _FPU_DEFAULT,
160 ._dl_pointer_guard = 1,
162 /* Function pointers. */
163 ._dl_debug_printf = _dl_debug_printf,
164 ._dl_catch_error = _dl_catch_error,
165 ._dl_signal_error = _dl_signal_error,
166 ._dl_mcount = _dl_mcount_internal,
167 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
168 ._dl_check_caller = _dl_check_caller,
169 ._dl_open = _dl_open,
170 ._dl_close = _dl_close,
171 ._dl_tls_get_addr_soft = _dl_tls_get_addr_soft,
172 #ifdef HAVE_DL_DISCOVER_OSVERSION
173 ._dl_discover_osversion = _dl_discover_osversion
174 #endif
176 /* If we would use strong_alias here the compiler would see a
177 non-hidden definition. This would undo the effect of the previous
178 declaration. So spell out was strong_alias does plus add the
179 visibility attribute. */
180 extern struct rtld_global_ro _rtld_local_ro
181 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
184 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
185 ElfW(Addr) *user_entry);
187 /* These two variables cannot be moved into .data.rel.ro. */
188 static struct libname_list _dl_rtld_libname;
189 static struct libname_list _dl_rtld_libname2;
191 /* We expect less than a second for relocation. */
192 #ifdef HP_SMALL_TIMING_AVAIL
193 # undef HP_TIMING_AVAIL
194 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
195 #endif
197 /* Variable for statistics. */
198 #ifndef HP_TIMING_NONAVAIL
199 static hp_timing_t relocate_time;
200 static hp_timing_t load_time attribute_relro;
201 static hp_timing_t start_time attribute_relro;
202 #endif
204 /* Additional definitions needed by TLS initialization. */
205 #ifdef TLS_INIT_HELPER
206 TLS_INIT_HELPER
207 #endif
209 /* Helper function for syscall implementation. */
210 #ifdef DL_SYSINFO_IMPLEMENTATION
211 DL_SYSINFO_IMPLEMENTATION
212 #endif
214 /* Before ld.so is relocated we must not access variables which need
215 relocations. This means variables which are exported. Variables
216 declared as static are fine. If we can mark a variable hidden this
217 is fine, too. The latter is important here. We can avoid setting
218 up a temporary link map for ld.so if we can mark _rtld_global as
219 hidden. */
220 #ifdef PI_STATIC_AND_HIDDEN
221 # define DONT_USE_BOOTSTRAP_MAP 1
222 #endif
224 #ifdef DONT_USE_BOOTSTRAP_MAP
225 static ElfW(Addr) _dl_start_final (void *arg);
226 #else
227 struct dl_start_final_info
229 struct link_map l;
230 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
231 hp_timing_t start_time;
232 #endif
234 static ElfW(Addr) _dl_start_final (void *arg,
235 struct dl_start_final_info *info);
236 #endif
238 /* These defined magically in the linker script. */
239 extern char _begin[] attribute_hidden;
240 extern char _etext[] attribute_hidden;
241 extern char _end[] attribute_hidden;
244 #ifdef RTLD_START
245 RTLD_START
246 #else
247 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
248 #endif
250 #ifndef VALIDX
251 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
252 + DT_EXTRANUM + DT_VALTAGIDX (tag))
253 #endif
254 #ifndef ADDRIDX
255 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
256 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
257 #endif
259 /* This is the second half of _dl_start (below). It can be inlined safely
260 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
261 references. When the tools don't permit us to avoid using a GOT entry
262 for _dl_rtld_global (no attribute_hidden support), we must make sure
263 this function is not inlined (see below). */
265 #ifdef DONT_USE_BOOTSTRAP_MAP
266 static inline ElfW(Addr) __attribute__ ((always_inline))
267 _dl_start_final (void *arg)
268 #else
269 static ElfW(Addr) __attribute__ ((noinline))
270 _dl_start_final (void *arg, struct dl_start_final_info *info)
271 #endif
273 ElfW(Addr) start_addr;
275 if (HP_TIMING_AVAIL)
277 /* If it hasn't happen yet record the startup time. */
278 if (! HP_TIMING_INLINE)
279 HP_TIMING_NOW (start_time);
280 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
281 else
282 start_time = info->start_time;
283 #endif
285 /* Initialize the timing functions. */
286 HP_TIMING_DIFF_INIT ();
289 /* Transfer data about ourselves to the permanent link_map structure. */
290 #ifndef DONT_USE_BOOTSTRAP_MAP
291 GL(dl_rtld_map).l_addr = info->l.l_addr;
292 GL(dl_rtld_map).l_ld = info->l.l_ld;
293 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
294 sizeof GL(dl_rtld_map).l_info);
295 GL(dl_rtld_map).l_mach = info->l.l_mach;
296 GL(dl_rtld_map).l_relocated = 1;
297 #endif
298 _dl_setup_hash (&GL(dl_rtld_map));
299 GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
300 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
301 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
302 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
303 /* Copy the TLS related data if necessary. */
304 #ifndef DONT_USE_BOOTSTRAP_MAP
305 # if USE___THREAD
306 assert (info->l.l_tls_modid != 0);
307 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
308 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
309 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
310 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
311 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
312 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
313 GL(dl_rtld_map).l_tls_modid = 1;
314 # else
315 # if NO_TLS_OFFSET != 0
316 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
317 # endif
318 # endif
320 #endif
322 #if HP_TIMING_AVAIL
323 HP_TIMING_NOW (GL(dl_cpuclock_offset));
324 #endif
326 /* Initialize the stack end variable. */
327 __libc_stack_end = __builtin_frame_address (0);
329 /* Call the OS-dependent function to set up life so we can do things like
330 file access. It will call `dl_main' (below) to do all the real work
331 of the dynamic linker, and then unwind our frame and run the user
332 entry point on the same stack we entered on. */
333 start_addr = _dl_sysdep_start (arg, &dl_main);
335 #ifndef HP_TIMING_NONAVAIL
336 hp_timing_t rtld_total_time;
337 if (HP_TIMING_AVAIL)
339 hp_timing_t end_time;
341 /* Get the current time. */
342 HP_TIMING_NOW (end_time);
344 /* Compute the difference. */
345 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
347 #endif
349 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
351 #ifndef HP_TIMING_NONAVAIL
352 print_statistics (&rtld_total_time);
353 #else
354 print_statistics (NULL);
355 #endif
358 return start_addr;
361 static ElfW(Addr) __attribute_used__ internal_function
362 _dl_start (void *arg)
364 #ifdef DONT_USE_BOOTSTRAP_MAP
365 # define bootstrap_map GL(dl_rtld_map)
366 #else
367 struct dl_start_final_info info;
368 # define bootstrap_map info.l
369 #endif
371 /* This #define produces dynamic linking inline functions for
372 bootstrap relocation instead of general-purpose relocation.
373 Since ld.so must not have any undefined symbols the result
374 is trivial: always the map of ld.so itself. */
375 #define RTLD_BOOTSTRAP
376 #define RESOLVE_MAP(sym, version, flags) (&bootstrap_map)
377 #include "dynamic-link.h"
379 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
380 #ifdef DONT_USE_BOOTSTRAP_MAP
381 HP_TIMING_NOW (start_time);
382 #else
383 HP_TIMING_NOW (info.start_time);
384 #endif
386 /* Partly clean the `bootstrap_map' structure up. Don't use
387 `memset' since it might not be built in or inlined and we cannot
388 make function calls at this point. Use '__builtin_memset' if we
389 know it is available. We do not have to clear the memory if we
390 do not have to use the temporary bootstrap_map. Global variables
391 are initialized to zero by default. */
392 #ifndef DONT_USE_BOOTSTRAP_MAP
393 # ifdef HAVE_BUILTIN_MEMSET
394 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
395 # else
396 for (size_t cnt = 0;
397 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
398 ++cnt)
399 bootstrap_map.l_info[cnt] = 0;
400 # endif
401 # if USE___THREAD
402 bootstrap_map.l_tls_modid = 0;
403 # endif
404 #endif
406 /* Figure out the run-time load address of the dynamic linker itself. */
407 bootstrap_map.l_addr = elf_machine_load_address ();
409 /* Read our own dynamic section and fill in the info array. */
410 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
411 elf_get_dynamic_info (&bootstrap_map, NULL);
413 #if NO_TLS_OFFSET != 0
414 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
415 #endif
417 /* Get the dynamic linker's own program header. First we need the ELF
418 file header. The `_begin' symbol created by the linker script points
419 to it. When we have something like GOTOFF relocs, we can use a plain
420 reference to find the runtime address. Without that, we have to rely
421 on the `l_addr' value, which is not the value we want when prelinked. */
422 #if USE___THREAD
423 dtv_t initdtv[3];
424 ElfW(Ehdr) *ehdr
425 # ifdef DONT_USE_BOOTSTRAP_MAP
426 = (ElfW(Ehdr) *) &_begin;
427 # else
428 # error This will not work with prelink.
429 = (ElfW(Ehdr) *) bootstrap_map.l_addr;
430 # endif
431 ElfW(Phdr) *phdr = (ElfW(Phdr) *) ((void *) ehdr + ehdr->e_phoff);
432 size_t cnt = ehdr->e_phnum; /* PT_TLS is usually the last phdr. */
433 while (cnt-- > 0)
434 if (phdr[cnt].p_type == PT_TLS)
436 void *tlsblock;
437 size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
438 char *p;
440 bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
441 bootstrap_map.l_tls_align = phdr[cnt].p_align;
442 if (phdr[cnt].p_align == 0)
443 bootstrap_map.l_tls_firstbyte_offset = 0;
444 else
445 bootstrap_map.l_tls_firstbyte_offset = (phdr[cnt].p_vaddr
446 & (phdr[cnt].p_align - 1));
447 assert (bootstrap_map.l_tls_blocksize != 0);
448 bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
449 bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
450 + phdr[cnt].p_vaddr);
452 /* We can now allocate the initial TLS block. This can happen
453 on the stack. We'll get the final memory later when we
454 know all about the various objects loaded at startup
455 time. */
456 # if TLS_TCB_AT_TP
457 tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
458 TLS_INIT_TCB_ALIGN)
459 + TLS_INIT_TCB_SIZE
460 + max_align);
461 # elif TLS_DTV_AT_TP
462 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
463 bootstrap_map.l_tls_align)
464 + bootstrap_map.l_tls_blocksize
465 + max_align);
466 # else
467 /* In case a model with a different layout for the TCB and DTV
468 is defined add another #elif here and in the following #ifs. */
469 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
470 # endif
471 /* Align the TLS block. */
472 tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
473 & ~(max_align - 1));
475 /* Initialize the dtv. [0] is the length, [1] the generation
476 counter. */
477 initdtv[0].counter = 1;
478 initdtv[1].counter = 0;
480 /* Initialize the TLS block. */
481 # if TLS_TCB_AT_TP
482 initdtv[2].pointer = tlsblock;
483 # elif TLS_DTV_AT_TP
484 bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
485 bootstrap_map.l_tls_align);
486 initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
487 # else
488 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
489 # endif
490 p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
491 bootstrap_map.l_tls_initimage_size);
492 # ifdef HAVE_BUILTIN_MEMSET
493 __builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
494 - bootstrap_map.l_tls_initimage_size));
495 # else
497 size_t remaining = (bootstrap_map.l_tls_blocksize
498 - bootstrap_map.l_tls_initimage_size);
499 while (remaining-- > 0)
500 *p++ = '\0';
502 # endif
504 /* Install the pointer to the dtv. */
506 /* Initialize the thread pointer. */
507 # if TLS_TCB_AT_TP
508 bootstrap_map.l_tls_offset
509 = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
511 INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
512 initdtv);
514 const char *lossage = TLS_INIT_TP ((char *) tlsblock
515 + bootstrap_map.l_tls_offset, 0);
516 # elif TLS_DTV_AT_TP
517 INSTALL_DTV (tlsblock, initdtv);
518 const char *lossage = TLS_INIT_TP (tlsblock, 0);
519 # else
520 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
521 # endif
522 if (__builtin_expect (lossage != NULL, 0))
523 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
524 lossage);
526 /* So far this is module number one. */
527 bootstrap_map.l_tls_modid = 1;
529 /* There can only be one PT_TLS entry. */
530 break;
532 #endif /* USE___THREAD */
534 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
535 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
536 #endif
538 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
540 /* Relocate ourselves so we can do normal function calls and
541 data access using the global offset table. */
543 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
545 bootstrap_map.l_relocated = 1;
547 /* Please note that we don't allow profiling of this object and
548 therefore need not test whether we have to allocate the array
549 for the relocation results (as done in dl-reloc.c). */
551 /* Now life is sane; we can call functions and access global data.
552 Set up to use the operating system facilities, and find out from
553 the operating system's program loader where to find the program
554 header table in core. Put the rest of _dl_start into a separate
555 function, that way the compiler cannot put accesses to the GOT
556 before ELF_DYNAMIC_RELOCATE. */
558 #ifdef DONT_USE_BOOTSTRAP_MAP
559 ElfW(Addr) entry = _dl_start_final (arg);
560 #else
561 ElfW(Addr) entry = _dl_start_final (arg, &info);
562 #endif
564 #ifndef ELF_MACHINE_START_ADDRESS
565 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
566 #endif
568 return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, entry);
574 /* Now life is peachy; we can do all normal operations.
575 On to the real work. */
577 /* Some helper functions. */
579 /* Arguments to relocate_doit. */
580 struct relocate_args
582 struct link_map *l;
583 int reloc_mode;
586 struct map_args
588 /* Argument to map_doit. */
589 char *str;
590 struct link_map *loader;
591 int is_preloaded;
592 int mode;
593 /* Return value of map_doit. */
594 struct link_map *map;
597 struct dlmopen_args
599 const char *fname;
600 struct link_map *map;
603 struct lookup_args
605 const char *name;
606 struct link_map *map;
607 void *result;
610 /* Arguments to version_check_doit. */
611 struct version_check_args
613 int doexit;
614 int dotrace;
617 static void
618 relocate_doit (void *a)
620 struct relocate_args *args = (struct relocate_args *) a;
622 _dl_relocate_object (args->l, args->l->l_scope, args->reloc_mode, 0);
625 static void
626 map_doit (void *a)
628 struct map_args *args = (struct map_args *) a;
629 args->map = _dl_map_object (args->loader, args->str,
630 args->is_preloaded, lt_library, 0, args->mode,
631 LM_ID_BASE);
634 static void
635 dlmopen_doit (void *a)
637 struct dlmopen_args *args = (struct dlmopen_args *) a;
638 args->map = _dl_open (args->fname, RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT,
639 dl_main, LM_ID_NEWLM, _dl_argc, INTUSE(_dl_argv),
640 __environ);
643 static void
644 lookup_doit (void *a)
646 struct lookup_args *args = (struct lookup_args *) a;
647 const ElfW(Sym) *ref = NULL;
648 args->result = NULL;
649 lookup_t l = _dl_lookup_symbol_x (args->name, args->map, &ref,
650 args->map->l_local_scope, NULL, 0,
651 DL_LOOKUP_RETURN_NEWEST, NULL);
652 if (ref != NULL)
653 args->result = DL_SYMBOL_ADDRESS (l, ref);
656 static void
657 version_check_doit (void *a)
659 struct version_check_args *args = (struct version_check_args *) a;
660 if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
661 args->dotrace) && args->doexit)
662 /* We cannot start the application. Abort now. */
663 _exit (1);
667 static inline struct link_map *
668 find_needed (const char *name)
670 struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
671 unsigned int n = scope->r_nlist;
673 while (n-- > 0)
674 if (_dl_name_match_p (name, scope->r_list[n]))
675 return scope->r_list[n];
677 /* Should never happen. */
678 return NULL;
681 static int
682 match_version (const char *string, struct link_map *map)
684 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
685 ElfW(Verdef) *def;
687 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
688 if (map->l_info[VERDEFTAG] == NULL)
689 /* The file has no symbol versioning. */
690 return 0;
692 def = (ElfW(Verdef) *) ((char *) map->l_addr
693 + map->l_info[VERDEFTAG]->d_un.d_ptr);
694 while (1)
696 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
698 /* Compare the version strings. */
699 if (strcmp (string, strtab + aux->vda_name) == 0)
700 /* Bingo! */
701 return 1;
703 /* If no more definitions we failed to find what we want. */
704 if (def->vd_next == 0)
705 break;
707 /* Next definition. */
708 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
711 return 0;
714 static bool tls_init_tp_called;
716 static void *
717 init_tls (void)
719 /* Number of elements in the static TLS block. */
720 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
722 /* Do not do this twice. The audit interface might have required
723 the DTV interfaces to be set up early. */
724 if (GL(dl_initial_dtv) != NULL)
725 return NULL;
727 /* Allocate the array which contains the information about the
728 dtv slots. We allocate a few entries more than needed to
729 avoid the need for reallocation. */
730 size_t nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
732 /* Allocate. */
733 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
734 calloc (sizeof (struct dtv_slotinfo_list)
735 + nelem * sizeof (struct dtv_slotinfo), 1);
736 /* No need to check the return value. If memory allocation failed
737 the program would have been terminated. */
739 struct dtv_slotinfo *slotinfo = GL(dl_tls_dtv_slotinfo_list)->slotinfo;
740 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
741 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
743 /* Fill in the information from the loaded modules. No namespace
744 but the base one can be filled at this time. */
745 assert (GL(dl_ns)[LM_ID_BASE + 1]._ns_loaded == NULL);
746 int i = 0;
747 for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
748 l = l->l_next)
749 if (l->l_tls_blocksize != 0)
751 /* This is a module with TLS data. Store the map reference.
752 The generation counter is zero. */
753 slotinfo[i].map = l;
754 /* slotinfo[i].gen = 0; */
755 ++i;
757 assert (i == GL(dl_tls_max_dtv_idx));
759 /* Compute the TLS offsets for the various blocks. */
760 _dl_determine_tlsoffset ();
762 /* Construct the static TLS block and the dtv for the initial
763 thread. For some platforms this will include allocating memory
764 for the thread descriptor. The memory for the TLS block will
765 never be freed. It should be allocated accordingly. The dtv
766 array can be changed if dynamic loading requires it. */
767 void *tcbp = _dl_allocate_tls_storage ();
768 if (tcbp == NULL)
769 _dl_fatal_printf ("\
770 cannot allocate TLS data structures for initial thread");
772 /* Store for detection of the special case by __tls_get_addr
773 so it knows not to pass this dtv to the normal realloc. */
774 GL(dl_initial_dtv) = GET_DTV (tcbp);
776 /* And finally install it for the main thread. If ld.so itself uses
777 TLS we know the thread pointer was initialized earlier. */
778 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
779 if (__builtin_expect (lossage != NULL, 0))
780 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
781 tls_init_tp_called = true;
783 return tcbp;
786 #ifdef _LIBC_REENTRANT
787 /* _dl_error_catch_tsd points to this for the single-threaded case.
788 It's reset by the thread library for multithreaded programs. */
789 void ** __attribute__ ((const))
790 _dl_initial_error_catch_tsd (void)
792 static void *data;
793 return &data;
795 #endif
798 static unsigned int
799 do_preload (char *fname, struct link_map *main_map, const char *where)
801 const char *objname;
802 const char *err_str = NULL;
803 struct map_args args;
804 bool malloced;
806 args.str = fname;
807 args.loader = main_map;
808 args.is_preloaded = 1;
809 args.mode = 0;
811 unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
813 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
814 if (__builtin_expect (err_str != NULL, 0))
816 _dl_error_printf ("\
817 ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
818 fname, where);
819 /* No need to call free, this is still before
820 the libc's malloc is used. */
822 else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
823 /* It is no duplicate. */
824 return 1;
826 /* Nothing loaded. */
827 return 0;
830 #if defined SHARED && defined _LIBC_REENTRANT \
831 && defined __rtld_lock_default_lock_recursive
832 static void
833 rtld_lock_default_lock_recursive (void *lock)
835 __rtld_lock_default_lock_recursive (lock);
838 static void
839 rtld_lock_default_unlock_recursive (void *lock)
841 __rtld_lock_default_unlock_recursive (lock);
843 #endif
846 static void
847 security_init (void)
849 /* Set up the stack checker's canary. */
850 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard (_dl_random);
851 #ifdef THREAD_SET_STACK_GUARD
852 THREAD_SET_STACK_GUARD (stack_chk_guard);
853 #else
854 __stack_chk_guard = stack_chk_guard;
855 #endif
857 /* Set up the pointer guard as well, if necessary. */
858 if (GLRO(dl_pointer_guard))
860 uintptr_t pointer_chk_guard = _dl_setup_pointer_guard (_dl_random,
861 stack_chk_guard);
862 #ifdef THREAD_SET_POINTER_GUARD
863 THREAD_SET_POINTER_GUARD (pointer_chk_guard);
864 #endif
865 __pointer_chk_guard_local = pointer_chk_guard;
868 /* We do not need the _dl_random value anymore. The less
869 information we leave behind, the better, so clear the
870 variable. */
871 _dl_random = NULL;
875 /* The library search path. */
876 static const char *library_path attribute_relro;
877 /* The list preloaded objects. */
878 static const char *preloadlist attribute_relro;
879 /* Nonzero if information about versions has to be printed. */
880 static int version_info attribute_relro;
882 static void
883 dl_main (const ElfW(Phdr) *phdr,
884 ElfW(Word) phnum,
885 ElfW(Addr) *user_entry)
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 #ifndef HAVE_INLINED_SYSCALLS
924 /* Set up a flag which tells we are just starting. */
925 INTUSE(_dl_starting_up) = 1;
926 #endif
928 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
930 /* Ho ho. We are not the program interpreter! We are the program
931 itself! This means someone ran ld.so as a command. Well, that
932 might be convenient to do sometimes. We support it by
933 interpreting the args like this:
935 ld.so PROGRAM ARGS...
937 The first argument is the name of a file containing an ELF
938 executable we will load and run with the following arguments.
939 To simplify life here, PROGRAM is searched for using the
940 normal rules for shared objects, rather than $PATH or anything
941 like that. We just load it and use its entry point; we don't
942 pay attention to its PT_INTERP command (we are the interpreter
943 ourselves). This is an easy way to test a new ld.so before
944 installing it. */
945 rtld_is_main = true;
947 /* Note the place where the dynamic linker actually came from. */
948 GL(dl_rtld_map).l_name = rtld_progname;
950 while (_dl_argc > 1)
951 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
953 mode = list;
954 GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
956 ++_dl_skip_args;
957 --_dl_argc;
958 ++INTUSE(_dl_argv);
960 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
962 mode = verify;
964 ++_dl_skip_args;
965 --_dl_argc;
966 ++INTUSE(_dl_argv);
968 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
969 && _dl_argc > 2)
971 library_path = INTUSE(_dl_argv)[2];
973 _dl_skip_args += 2;
974 _dl_argc -= 2;
975 INTUSE(_dl_argv) += 2;
977 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
978 && _dl_argc > 2)
980 GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
982 _dl_skip_args += 2;
983 _dl_argc -= 2;
984 INTUSE(_dl_argv) += 2;
986 else if (! strcmp (INTUSE(_dl_argv)[1], "--audit") && _dl_argc > 2)
988 process_dl_audit (INTUSE(_dl_argv)[2]);
990 _dl_skip_args += 2;
991 _dl_argc -= 2;
992 INTUSE(_dl_argv) += 2;
994 else
995 break;
997 /* If we have no further argument the program was called incorrectly.
998 Grant the user some education. */
999 if (_dl_argc < 2)
1000 _dl_fatal_printf ("\
1001 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
1002 You have invoked `ld.so', the helper program for shared library executables.\n\
1003 This program usually lives in the file `/lib/ld.so', and special directives\n\
1004 in executable files using ELF shared libraries tell the system's program\n\
1005 loader to load the helper program from this file. This helper program loads\n\
1006 the shared libraries needed by the program executable, prepares the program\n\
1007 to run, and runs it. You may invoke this helper program directly from the\n\
1008 command line to load and run an ELF executable file; this is like executing\n\
1009 that file itself, but always uses this helper program from the file you\n\
1010 specified, instead of the helper program file specified in the executable\n\
1011 file you run. This is mostly of use for maintainers to test new versions\n\
1012 of this helper program; chances are you did not intend to run this program.\n\
1014 --list list all dependencies and how they are resolved\n\
1015 --verify verify that given object really is a dynamically linked\n\
1016 object we can handle\n\
1017 --library-path PATH use given PATH instead of content of the environment\n\
1018 variable LD_LIBRARY_PATH\n\
1019 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
1020 in LIST\n\
1021 --audit LIST use objects named in LIST as auditors\n");
1023 ++_dl_skip_args;
1024 --_dl_argc;
1025 ++INTUSE(_dl_argv);
1027 /* The initialization of _dl_stack_flags done below assumes the
1028 executable's PT_GNU_STACK may have been honored by the kernel, and
1029 so a PT_GNU_STACK with PF_X set means the stack started out with
1030 execute permission. However, this is not really true if the
1031 dynamic linker is the executable the kernel loaded. For this
1032 case, we must reinitialize _dl_stack_flags to match the dynamic
1033 linker itself. If the dynamic linker was built with a
1034 PT_GNU_STACK, then the kernel may have loaded us with a
1035 nonexecutable stack that we will have to make executable when we
1036 load the program below unless it has a PT_GNU_STACK indicating
1037 nonexecutable stack is ok. */
1039 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1040 if (ph->p_type == PT_GNU_STACK)
1042 GL(dl_stack_flags) = ph->p_flags;
1043 break;
1046 if (__builtin_expect (mode, normal) == verify)
1048 const char *objname;
1049 const char *err_str = NULL;
1050 struct map_args args;
1051 bool malloced;
1053 args.str = rtld_progname;
1054 args.loader = NULL;
1055 args.is_preloaded = 0;
1056 args.mode = __RTLD_OPENEXEC;
1057 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
1058 &args);
1059 if (__builtin_expect (err_str != NULL, 0))
1060 /* We don't free the returned string, the programs stops
1061 anyway. */
1062 _exit (EXIT_FAILURE);
1064 else
1066 HP_TIMING_NOW (start);
1067 _dl_map_object (NULL, rtld_progname, 0, lt_library, 0,
1068 __RTLD_OPENEXEC, LM_ID_BASE);
1069 HP_TIMING_NOW (stop);
1071 HP_TIMING_DIFF (load_time, start, stop);
1074 /* Now the map for the main executable is available. */
1075 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1077 phdr = main_map->l_phdr;
1078 phnum = main_map->l_phnum;
1079 /* We overwrite here a pointer to a malloc()ed string. But since
1080 the malloc() implementation used at this point is the dummy
1081 implementations which has no real free() function it does not
1082 makes sense to free the old string first. */
1083 main_map->l_name = (char *) "";
1084 *user_entry = main_map->l_entry;
1086 else
1088 /* Create a link_map for the executable itself.
1089 This will be what dlopen on "" returns. */
1090 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1091 __RTLD_OPENEXEC, LM_ID_BASE);
1092 assert (main_map != NULL);
1093 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
1094 main_map->l_phdr = phdr;
1095 main_map->l_phnum = phnum;
1096 main_map->l_entry = *user_entry;
1098 /* At this point we are in a bit of trouble. We would have to
1099 fill in the values for l_dev and l_ino. But in general we
1100 do not know where the file is. We also do not handle AT_EXECFD
1101 even if it would be passed up.
1103 We leave the values here defined to 0. This is normally no
1104 problem as the program code itself is normally no shared
1105 object and therefore cannot be loaded dynamically. Nothing
1106 prevent the use of dynamic binaries and in these situations
1107 we might get problems. We might not be able to find out
1108 whether the object is already loaded. But since there is no
1109 easy way out and because the dynamic binary must also not
1110 have an SONAME we ignore this program for now. If it becomes
1111 a problem we can force people using SONAMEs. */
1113 /* We delay initializing the path structure until we got the dynamic
1114 information for the program. */
1117 main_map->l_map_end = 0;
1118 main_map->l_text_end = 0;
1119 /* Perhaps the executable has no PT_LOAD header entries at all. */
1120 main_map->l_map_start = ~0;
1121 /* And it was opened directly. */
1122 ++main_map->l_direct_opencount;
1124 /* Scan the program header table for the dynamic section. */
1125 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1126 switch (ph->p_type)
1128 case PT_PHDR:
1129 /* Find out the load address. */
1130 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1131 break;
1132 case PT_DYNAMIC:
1133 /* This tells us where to find the dynamic section,
1134 which tells us everything we need to do. */
1135 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
1136 break;
1137 case PT_INTERP:
1138 /* This "interpreter segment" was used by the program loader to
1139 find the program interpreter, which is this program itself, the
1140 dynamic linker. We note what name finds us, so that a future
1141 dlopen call or DT_NEEDED entry, for something that wants to link
1142 against the dynamic linker as a shared library, will know that
1143 the shared object is already loaded. */
1144 _dl_rtld_libname.name = ((const char *) main_map->l_addr
1145 + ph->p_vaddr);
1146 /* _dl_rtld_libname.next = NULL; Already zero. */
1147 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1149 /* Ordinarilly, we would get additional names for the loader from
1150 our DT_SONAME. This can't happen if we were actually linked as
1151 a static executable (detect this case when we have no DYNAMIC).
1152 If so, assume the filename component of the interpreter path to
1153 be our SONAME, and add it to our name list. */
1154 if (GL(dl_rtld_map).l_ld == NULL)
1156 const char *p = NULL;
1157 const char *cp = _dl_rtld_libname.name;
1159 /* Find the filename part of the path. */
1160 while (*cp != '\0')
1161 if (*cp++ == '/')
1162 p = cp;
1164 if (p != NULL)
1166 _dl_rtld_libname2.name = p;
1167 /* _dl_rtld_libname2.next = NULL; Already zero. */
1168 _dl_rtld_libname.next = &_dl_rtld_libname2;
1172 has_interp = true;
1173 break;
1174 case PT_LOAD:
1176 ElfW(Addr) mapstart;
1177 ElfW(Addr) allocend;
1179 /* Remember where the main program starts in memory. */
1180 mapstart = (main_map->l_addr
1181 + (ph->p_vaddr & ~(GLRO(dl_pagesize) - 1)));
1182 if (main_map->l_map_start > mapstart)
1183 main_map->l_map_start = mapstart;
1185 /* Also where it ends. */
1186 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1187 if (main_map->l_map_end < allocend)
1188 main_map->l_map_end = allocend;
1189 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1190 main_map->l_text_end = allocend;
1192 break;
1194 case PT_TLS:
1195 if (ph->p_memsz > 0)
1197 /* Note that in the case the dynamic linker we duplicate work
1198 here since we read the PT_TLS entry already in
1199 _dl_start_final. But the result is repeatable so do not
1200 check for this special but unimportant case. */
1201 main_map->l_tls_blocksize = ph->p_memsz;
1202 main_map->l_tls_align = ph->p_align;
1203 if (ph->p_align == 0)
1204 main_map->l_tls_firstbyte_offset = 0;
1205 else
1206 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1207 & (ph->p_align - 1));
1208 main_map->l_tls_initimage_size = ph->p_filesz;
1209 main_map->l_tls_initimage = (void *) ph->p_vaddr;
1211 /* This image gets the ID one. */
1212 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1214 break;
1216 case PT_GNU_STACK:
1217 GL(dl_stack_flags) = ph->p_flags;
1218 break;
1220 case PT_GNU_RELRO:
1221 main_map->l_relro_addr = ph->p_vaddr;
1222 main_map->l_relro_size = ph->p_memsz;
1223 break;
1226 /* Adjust the address of the TLS initialization image in case
1227 the executable is actually an ET_DYN object. */
1228 if (main_map->l_tls_initimage != NULL)
1229 main_map->l_tls_initimage
1230 = (char *) main_map->l_tls_initimage + main_map->l_addr;
1231 if (! main_map->l_map_end)
1232 main_map->l_map_end = ~0;
1233 if (! main_map->l_text_end)
1234 main_map->l_text_end = ~0;
1235 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1237 /* We were invoked directly, so the program might not have a
1238 PT_INTERP. */
1239 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1240 /* _dl_rtld_libname.next = NULL; Already zero. */
1241 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1243 else
1244 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1246 /* If the current libname is different from the SONAME, add the
1247 latter as well. */
1248 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1249 && strcmp (GL(dl_rtld_map).l_libname->name,
1250 (const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1251 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1253 static struct libname_list newname;
1254 newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1255 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1256 newname.next = NULL;
1257 newname.dont_free = 1;
1259 assert (GL(dl_rtld_map).l_libname->next == NULL);
1260 GL(dl_rtld_map).l_libname->next = &newname;
1262 /* The ld.so must be relocated since otherwise loading audit modules
1263 will fail since they reuse the very same ld.so. */
1264 assert (GL(dl_rtld_map).l_relocated);
1266 if (! rtld_is_main)
1268 /* Extract the contents of the dynamic section for easy access. */
1269 elf_get_dynamic_info (main_map, NULL);
1270 /* Set up our cache of pointers into the hash table. */
1271 _dl_setup_hash (main_map);
1274 if (__builtin_expect (mode, normal) == verify)
1276 /* We were called just to verify that this is a dynamic
1277 executable using us as the program interpreter. Exit with an
1278 error if we were not able to load the binary or no interpreter
1279 is specified (i.e., this is no dynamically linked binary. */
1280 if (main_map->l_ld == NULL)
1281 _exit (1);
1283 /* We allow here some platform specific code. */
1284 #ifdef DISTINGUISH_LIB_VERSIONS
1285 DISTINGUISH_LIB_VERSIONS;
1286 #endif
1287 _exit (has_interp ? 0 : 2);
1290 struct link_map **first_preload = &GL(dl_rtld_map).l_next;
1291 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1292 /* Set up the data structures for the system-supplied DSO early,
1293 so they can influence _dl_init_paths. */
1294 if (GLRO(dl_sysinfo_dso) != NULL)
1296 /* Do an abridged version of the work _dl_map_object_from_fd would do
1297 to map in the object. It's already mapped and prelinked (and
1298 better be, since it's read-only and so we couldn't relocate it).
1299 We just want our data structures to describe it as if we had just
1300 mapped and relocated it normally. */
1301 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL,
1302 0, LM_ID_BASE);
1303 if (__builtin_expect (l != NULL, 1))
1305 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
1307 l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1308 + GLRO(dl_sysinfo_dso)->e_phoff);
1309 l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1310 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1312 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1313 if (ph->p_type == PT_DYNAMIC)
1315 l->l_ld = (void *) ph->p_vaddr;
1316 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1318 else if (ph->p_type == PT_LOAD)
1320 if (! l->l_addr)
1321 l->l_addr = ph->p_vaddr;
1322 if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1323 l->l_map_end = ph->p_vaddr + ph->p_memsz;
1324 if ((ph->p_flags & PF_X)
1325 && ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1326 l->l_text_end = ph->p_vaddr + ph->p_memsz;
1328 else
1329 /* There must be no TLS segment. */
1330 assert (ph->p_type != PT_TLS);
1332 l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1333 l->l_addr = l->l_map_start - l->l_addr;
1334 l->l_map_end += l->l_addr;
1335 l->l_text_end += l->l_addr;
1336 l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1337 elf_get_dynamic_info (l, dyn_temp);
1338 _dl_setup_hash (l);
1339 l->l_relocated = 1;
1341 /* Initialize l_local_scope to contain just this map. This allows
1342 the use of dl_lookup_symbol_x to resolve symbols within the vdso.
1343 So we create a single entry list pointing to l_real as its only
1344 element */
1345 l->l_local_scope[0]->r_nlist = 1;
1346 l->l_local_scope[0]->r_list = &l->l_real;
1348 /* Now that we have the info handy, use the DSO image's soname
1349 so this object can be looked up by name. Note that we do not
1350 set l_name here. That field gives the file name of the DSO,
1351 and this DSO is not associated with any file. */
1352 if (l->l_info[DT_SONAME] != NULL)
1354 /* Work around a kernel problem. The kernel cannot handle
1355 addresses in the vsyscall DSO pages in writev() calls. */
1356 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1357 + l->l_info[DT_SONAME]->d_un.d_val);
1358 size_t len = strlen (dsoname);
1359 char *copy = malloc (len);
1360 if (copy == NULL)
1361 _dl_fatal_printf ("out of memory\n");
1362 l->l_libname->name = memcpy (copy, dsoname, len);
1365 /* Rearrange the list so this DSO appears after rtld_map. */
1366 assert (l->l_next == NULL);
1367 assert (l->l_prev == main_map);
1368 GL(dl_rtld_map).l_next = l;
1369 l->l_prev = &GL(dl_rtld_map);
1370 first_preload = &l->l_next;
1372 /* We have a prelinked DSO preloaded by the system. */
1373 GLRO(dl_sysinfo_map) = l;
1374 # ifdef NEED_DL_SYSINFO
1375 if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1376 GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1377 # endif
1380 #endif
1382 #ifdef DL_SYSDEP_OSCHECK
1383 DL_SYSDEP_OSCHECK (dl_fatal);
1384 #endif
1386 /* Initialize the data structures for the search paths for shared
1387 objects. */
1388 _dl_init_paths (library_path);
1390 /* Initialize _r_debug. */
1391 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1392 LM_ID_BASE);
1393 r->r_state = RT_CONSISTENT;
1395 /* Put the link_map for ourselves on the chain so it can be found by
1396 name. Note that at this point the global chain of link maps contains
1397 exactly one element, which is pointed to by dl_loaded. */
1398 if (! GL(dl_rtld_map).l_name)
1399 /* If not invoked directly, the dynamic linker shared object file was
1400 found by the PT_INTERP name. */
1401 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1402 GL(dl_rtld_map).l_type = lt_library;
1403 main_map->l_next = &GL(dl_rtld_map);
1404 GL(dl_rtld_map).l_prev = main_map;
1405 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1406 ++GL(dl_load_adds);
1408 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1409 to not using bias for non-prelinked PIEs and libraries
1410 and using it for executables or prelinked PIEs or libraries. */
1411 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1412 GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
1414 /* Set up the program header information for the dynamic linker
1415 itself. It is needed in the dl_iterate_phdr() callbacks. */
1416 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1417 ElfW(Phdr) *rtld_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1418 + rtld_ehdr->e_phoff);
1419 GL(dl_rtld_map).l_phdr = rtld_phdr;
1420 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1423 /* PT_GNU_RELRO is usually the last phdr. */
1424 size_t cnt = rtld_ehdr->e_phnum;
1425 while (cnt-- > 0)
1426 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1428 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1429 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1430 break;
1433 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1434 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1435 /* Assign a module ID. Do this before loading any audit modules. */
1436 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1438 /* If we have auditing DSOs to load, do it now. */
1439 if (__builtin_expect (audit_list != NULL, 0))
1441 /* Iterate over all entries in the list. The order is important. */
1442 struct audit_ifaces *last_audit = NULL;
1443 struct audit_list *al = audit_list->next;
1445 /* Since we start using the auditing DSOs right away we need to
1446 initialize the data structures now. */
1447 tcbp = init_tls ();
1449 /* Initialize security features. We need to do it this early
1450 since otherwise the constructors of the audit libraries will
1451 use different values (especially the pointer guard) and will
1452 fail later on. */
1453 security_init ();
1457 int tls_idx = GL(dl_tls_max_dtv_idx);
1459 /* Now it is time to determine the layout of the static TLS
1460 block and allocate it for the initial thread. Note that we
1461 always allocate the static block, we never defer it even if
1462 no DF_STATIC_TLS bit is set. The reason is that we know
1463 glibc will use the static model. */
1464 struct dlmopen_args dlmargs;
1465 dlmargs.fname = al->name;
1466 dlmargs.map = NULL;
1468 const char *objname;
1469 const char *err_str = NULL;
1470 bool malloced;
1471 (void) _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit,
1472 &dlmargs);
1473 if (__builtin_expect (err_str != NULL, 0))
1475 not_loaded:
1476 _dl_error_printf ("\
1477 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
1478 al->name, err_str);
1479 if (malloced)
1480 free ((char *) err_str);
1482 else
1484 struct lookup_args largs;
1485 largs.name = "la_version";
1486 largs.map = dlmargs.map;
1488 /* Check whether the interface version matches. */
1489 (void) _dl_catch_error (&objname, &err_str, &malloced,
1490 lookup_doit, &largs);
1492 unsigned int (*laversion) (unsigned int);
1493 unsigned int lav;
1494 if (err_str == NULL
1495 && (laversion = largs.result) != NULL
1496 && (lav = laversion (LAV_CURRENT)) > 0
1497 && lav <= LAV_CURRENT)
1499 /* Allocate structure for the callback function pointers.
1500 This call can never fail. */
1501 union
1503 struct audit_ifaces ifaces;
1504 #define naudit_ifaces 8
1505 void (*fptr[naudit_ifaces]) (void);
1506 } *newp = malloc (sizeof (*newp));
1508 /* Names of the auditing interfaces. All in one
1509 long string. */
1510 static const char audit_iface_names[] =
1511 "la_activity\0"
1512 "la_objsearch\0"
1513 "la_objopen\0"
1514 "la_preinit\0"
1515 #if __ELF_NATIVE_CLASS == 32
1516 "la_symbind32\0"
1517 #elif __ELF_NATIVE_CLASS == 64
1518 "la_symbind64\0"
1519 #else
1520 # error "__ELF_NATIVE_CLASS must be defined"
1521 #endif
1522 #define STRING(s) __STRING (s)
1523 "la_" STRING (ARCH_LA_PLTENTER) "\0"
1524 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
1525 "la_objclose\0";
1526 unsigned int cnt = 0;
1527 const char *cp = audit_iface_names;
1530 largs.name = cp;
1531 (void) _dl_catch_error (&objname, &err_str, &malloced,
1532 lookup_doit, &largs);
1534 /* Store the pointer. */
1535 if (err_str == NULL && largs.result != NULL)
1537 newp->fptr[cnt] = largs.result;
1539 /* The dynamic linker link map is statically
1540 allocated, initialize the data now. */
1541 GL(dl_rtld_map).l_audit[cnt].cookie
1542 = (intptr_t) &GL(dl_rtld_map);
1544 else
1545 newp->fptr[cnt] = NULL;
1546 ++cnt;
1548 cp = (char *) rawmemchr (cp, '\0') + 1;
1550 while (*cp != '\0');
1551 assert (cnt == naudit_ifaces);
1553 /* Now append the new auditing interface to the list. */
1554 newp->ifaces.next = NULL;
1555 if (last_audit == NULL)
1556 last_audit = GLRO(dl_audit) = &newp->ifaces;
1557 else
1558 last_audit = last_audit->next = &newp->ifaces;
1559 ++GLRO(dl_naudit);
1561 /* Mark the DSO as being used for auditing. */
1562 dlmargs.map->l_auditing = 1;
1564 else
1566 /* We cannot use the DSO, it does not have the
1567 appropriate interfaces or it expects something
1568 more recent. */
1569 #ifndef NDEBUG
1570 Lmid_t ns = dlmargs.map->l_ns;
1571 #endif
1572 _dl_close (dlmargs.map);
1574 /* Make sure the namespace has been cleared entirely. */
1575 assert (GL(dl_ns)[ns]._ns_loaded == NULL);
1576 assert (GL(dl_ns)[ns]._ns_nloaded == 0);
1578 GL(dl_tls_max_dtv_idx) = tls_idx;
1579 goto not_loaded;
1583 al = al->next;
1585 while (al != audit_list->next);
1587 /* If we have any auditing modules, announce that we already
1588 have two objects loaded. */
1589 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1591 struct link_map *ls[2] = { main_map, &GL(dl_rtld_map) };
1593 for (unsigned int outer = 0; outer < 2; ++outer)
1595 struct audit_ifaces *afct = GLRO(dl_audit);
1596 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1598 if (afct->objopen != NULL)
1600 ls[outer]->l_audit[cnt].bindflags
1601 = afct->objopen (ls[outer], LM_ID_BASE,
1602 &ls[outer]->l_audit[cnt].cookie);
1604 ls[outer]->l_audit_any_plt
1605 |= ls[outer]->l_audit[cnt].bindflags != 0;
1608 afct = afct->next;
1614 /* Set up debugging before the debugger is notified for the first time. */
1615 #ifdef ELF_MACHINE_DEBUG_SETUP
1616 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1617 ELF_MACHINE_DEBUG_SETUP (main_map, r);
1618 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1619 #else
1620 if (main_map->l_info[DT_DEBUG] != NULL)
1621 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1622 with the run-time address of the r_debug structure */
1623 main_map->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1625 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1626 case you run gdb on the dynamic linker directly. */
1627 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1628 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1629 #endif
1631 /* We start adding objects. */
1632 r->r_state = RT_ADD;
1633 _dl_debug_state ();
1635 /* Auditing checkpoint: we are ready to signal that the initial map
1636 is being constructed. */
1637 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1639 struct audit_ifaces *afct = GLRO(dl_audit);
1640 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1642 if (afct->activity != NULL)
1643 afct->activity (&main_map->l_audit[cnt].cookie, LA_ACT_ADD);
1645 afct = afct->next;
1649 /* We have two ways to specify objects to preload: via environment
1650 variable and via the file /etc/ld.so.preload. The latter can also
1651 be used when security is enabled. */
1652 assert (*first_preload == NULL);
1653 struct link_map **preloads = NULL;
1654 unsigned int npreloads = 0;
1656 if (__builtin_expect (preloadlist != NULL, 0))
1658 /* The LD_PRELOAD environment variable gives list of libraries
1659 separated by white space or colons that are loaded before the
1660 executable's dependencies and prepended to the global scope
1661 list. If the binary is running setuid all elements
1662 containing a '/' are ignored since it is insecure. */
1663 char *list = strdupa (preloadlist);
1664 char *p;
1666 HP_TIMING_NOW (start);
1668 /* Prevent optimizing strsep. Speed is not important here. */
1669 while ((p = (strsep) (&list, " :")) != NULL)
1670 if (p[0] != '\0'
1671 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1672 || strchr (p, '/') == NULL))
1673 npreloads += do_preload (p, main_map, "LD_PRELOAD");
1675 HP_TIMING_NOW (stop);
1676 HP_TIMING_DIFF (diff, start, stop);
1677 HP_TIMING_ACCUM_NT (load_time, diff);
1680 /* There usually is no ld.so.preload file, it should only be used
1681 for emergencies and testing. So the open call etc should usually
1682 fail. Using access() on a non-existing file is faster than using
1683 open(). So we do this first. If it succeeds we do almost twice
1684 the work but this does not matter, since it is not for production
1685 use. */
1686 static const char preload_file[] = "/etc/ld.so.preload";
1687 if (__builtin_expect (__access (preload_file, R_OK) == 0, 0))
1689 /* Read the contents of the file. */
1690 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1691 PROT_READ | PROT_WRITE);
1692 if (__builtin_expect (file != MAP_FAILED, 0))
1694 /* Parse the file. It contains names of libraries to be loaded,
1695 separated by white spaces or `:'. It may also contain
1696 comments introduced by `#'. */
1697 char *problem;
1698 char *runp;
1699 size_t rest;
1701 /* Eliminate comments. */
1702 runp = file;
1703 rest = file_size;
1704 while (rest > 0)
1706 char *comment = memchr (runp, '#', rest);
1707 if (comment == NULL)
1708 break;
1710 rest -= comment - runp;
1712 *comment = ' ';
1713 while (--rest > 0 && *++comment != '\n');
1716 /* We have one problematic case: if we have a name at the end of
1717 the file without a trailing terminating characters, we cannot
1718 place the \0. Handle the case separately. */
1719 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1720 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1722 problem = &file[file_size];
1723 while (problem > file && problem[-1] != ' '
1724 && problem[-1] != '\t'
1725 && problem[-1] != '\n' && problem[-1] != ':')
1726 --problem;
1728 if (problem > file)
1729 problem[-1] = '\0';
1731 else
1733 problem = NULL;
1734 file[file_size - 1] = '\0';
1737 HP_TIMING_NOW (start);
1739 if (file != problem)
1741 char *p;
1742 runp = file;
1743 while ((p = strsep (&runp, ": \t\n")) != NULL)
1744 if (p[0] != '\0')
1745 npreloads += do_preload (p, main_map, preload_file);
1748 if (problem != NULL)
1750 char *p = strndupa (problem, file_size - (problem - file));
1752 npreloads += do_preload (p, main_map, preload_file);
1755 HP_TIMING_NOW (stop);
1756 HP_TIMING_DIFF (diff, start, stop);
1757 HP_TIMING_ACCUM_NT (load_time, diff);
1759 /* We don't need the file anymore. */
1760 __munmap (file, file_size);
1764 if (__builtin_expect (*first_preload != NULL, 0))
1766 /* Set up PRELOADS with a vector of the preloaded libraries. */
1767 struct link_map *l = *first_preload;
1768 preloads = __alloca (npreloads * sizeof preloads[0]);
1769 i = 0;
1772 preloads[i++] = l;
1773 l = l->l_next;
1774 } while (l);
1775 assert (i == npreloads);
1778 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1779 specified some libraries to load, these are inserted before the actual
1780 dependencies in the executable's searchlist for symbol resolution. */
1781 HP_TIMING_NOW (start);
1782 _dl_map_object_deps (main_map, preloads, npreloads, mode == trace, 0);
1783 HP_TIMING_NOW (stop);
1784 HP_TIMING_DIFF (diff, start, stop);
1785 HP_TIMING_ACCUM_NT (load_time, diff);
1787 /* Mark all objects as being in the global scope. */
1788 for (i = main_map->l_searchlist.r_nlist; i > 0; )
1789 main_map->l_searchlist.r_list[--i]->l_global = 1;
1791 /* Remove _dl_rtld_map from the chain. */
1792 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1793 if (GL(dl_rtld_map).l_next != NULL)
1794 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1796 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1797 if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1798 break;
1800 bool rtld_multiple_ref = false;
1801 if (__builtin_expect (i < main_map->l_searchlist.r_nlist, 1))
1803 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1804 put it back in the list of visible objects. We insert it into the
1805 chain in symbol search order because gdb uses the chain's order as
1806 its symbol search order. */
1807 rtld_multiple_ref = true;
1809 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1810 if (__builtin_expect (mode, normal) == normal)
1812 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1813 ? main_map->l_searchlist.r_list[i + 1]
1814 : NULL);
1815 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1816 if (GLRO(dl_sysinfo_map) != NULL
1817 && GL(dl_rtld_map).l_prev->l_next == GLRO(dl_sysinfo_map)
1818 && GL(dl_rtld_map).l_next != GLRO(dl_sysinfo_map))
1819 GL(dl_rtld_map).l_prev = GLRO(dl_sysinfo_map);
1820 #endif
1822 else
1823 /* In trace mode there might be an invisible object (which we
1824 could not find) after the previous one in the search list.
1825 In this case it doesn't matter much where we put the
1826 interpreter object, so we just initialize the list pointer so
1827 that the assertion below holds. */
1828 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1830 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1831 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1832 if (GL(dl_rtld_map).l_next != NULL)
1834 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1835 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1839 /* Now let us see whether all libraries are available in the
1840 versions we need. */
1842 struct version_check_args args;
1843 args.doexit = mode == normal;
1844 args.dotrace = mode == trace;
1845 _dl_receive_error (print_missing_version, version_check_doit, &args);
1848 /* We do not initialize any of the TLS functionality unless any of the
1849 initial modules uses TLS. This makes dynamic loading of modules with
1850 TLS impossible, but to support it requires either eagerly doing setup
1851 now or lazily doing it later. Doing it now makes us incompatible with
1852 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1853 used. Trying to do it lazily is too hairy to try when there could be
1854 multiple threads (from a non-TLS-using libpthread). */
1855 bool was_tls_init_tp_called = tls_init_tp_called;
1856 if (tcbp == NULL)
1857 tcbp = init_tls ();
1859 if (__builtin_expect (audit_list == NULL, 1))
1860 /* Initialize security features. But only if we have not done it
1861 earlier. */
1862 security_init ();
1864 if (__builtin_expect (mode, normal) != normal)
1866 /* We were run just to list the shared libraries. It is
1867 important that we do this before real relocation, because the
1868 functions we call below for output may no longer work properly
1869 after relocation. */
1870 struct link_map *l;
1872 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1874 struct r_scope_elem *scope = &main_map->l_searchlist;
1876 for (i = 0; i < scope->r_nlist; i++)
1878 l = scope->r_list [i];
1879 if (l->l_faked)
1881 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1882 continue;
1884 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1885 GLRO(dl_trace_prelink_map) = l;
1886 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1887 l->l_libname->name[0] ? l->l_libname->name
1888 : rtld_progname ?: "<main program>",
1889 l->l_name[0] ? l->l_name
1890 : rtld_progname ?: "<main program>",
1891 (int) sizeof l->l_map_start * 2,
1892 (size_t) l->l_map_start,
1893 (int) sizeof l->l_addr * 2,
1894 (size_t) l->l_addr);
1896 if (l->l_tls_modid)
1897 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1898 (int) sizeof l->l_tls_offset * 2,
1899 (size_t) l->l_tls_offset);
1900 else
1901 _dl_printf ("\n");
1904 else if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
1906 /* Look through the dependencies of the main executable
1907 and determine which of them is not actually
1908 required. */
1909 struct link_map *l = main_map;
1911 /* Relocate the main executable. */
1912 struct relocate_args args = { .l = l,
1913 .reloc_mode = (GLRO(dl_lazy)
1914 ? RTLD_LAZY : 0) };
1915 _dl_receive_error (print_unresolved, relocate_doit, &args);
1917 /* This loop depends on the dependencies of the executable to
1918 correspond in number and order to the DT_NEEDED entries. */
1919 ElfW(Dyn) *dyn = main_map->l_ld;
1920 bool first = true;
1921 while (dyn->d_tag != DT_NULL)
1923 if (dyn->d_tag == DT_NEEDED)
1925 l = l->l_next;
1927 if (!l->l_used)
1929 if (first)
1931 _dl_printf ("Unused direct dependencies:\n");
1932 first = false;
1935 _dl_printf ("\t%s\n", l->l_name);
1939 ++dyn;
1942 _exit (first != true);
1944 else if (! main_map->l_info[DT_NEEDED])
1945 _dl_printf ("\tstatically linked\n");
1946 else
1948 for (l = main_map->l_next; l; l = l->l_next)
1949 if (l->l_faked)
1950 /* The library was not found. */
1951 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1952 else if (strcmp (l->l_libname->name, l->l_name) == 0)
1953 _dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
1954 (int) sizeof l->l_map_start * 2,
1955 (size_t) l->l_map_start);
1956 else
1957 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1958 l->l_name, (int) sizeof l->l_map_start * 2,
1959 (size_t) l->l_map_start);
1962 if (__builtin_expect (mode, trace) != trace)
1963 for (i = 1; i < (unsigned int) _dl_argc; ++i)
1965 const ElfW(Sym) *ref = NULL;
1966 ElfW(Addr) loadbase;
1967 lookup_t result;
1969 result = _dl_lookup_symbol_x (INTUSE(_dl_argv)[i], main_map,
1970 &ref, main_map->l_scope,
1971 NULL, ELF_RTYPE_CLASS_PLT,
1972 DL_LOOKUP_ADD_DEPENDENCY, NULL);
1974 loadbase = LOOKUP_VALUE_ADDRESS (result);
1976 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
1977 INTUSE(_dl_argv)[i],
1978 (int) sizeof ref->st_value * 2,
1979 (size_t) ref->st_value,
1980 (int) sizeof loadbase * 2, (size_t) loadbase);
1982 else
1984 /* If LD_WARN is set, warn about undefined symbols. */
1985 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
1987 /* We have to do symbol dependency testing. */
1988 struct relocate_args args;
1989 struct link_map *l;
1991 args.reloc_mode = GLRO(dl_lazy) ? RTLD_LAZY : 0;
1993 l = main_map;
1994 while (l->l_next != NULL)
1995 l = l->l_next;
1998 if (l != &GL(dl_rtld_map) && ! l->l_faked)
2000 args.l = l;
2001 _dl_receive_error (print_unresolved, relocate_doit,
2002 &args);
2004 l = l->l_prev;
2006 while (l != NULL);
2008 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
2009 && rtld_multiple_ref)
2011 /* Mark the link map as not yet relocated again. */
2012 GL(dl_rtld_map).l_relocated = 0;
2013 _dl_relocate_object (&GL(dl_rtld_map),
2014 main_map->l_scope, 0, 0);
2017 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
2018 if (version_info)
2020 /* Print more information. This means here, print information
2021 about the versions needed. */
2022 int first = 1;
2023 struct link_map *map;
2025 for (map = main_map; map != NULL; map = map->l_next)
2027 const char *strtab;
2028 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
2029 ElfW(Verneed) *ent;
2031 if (dyn == NULL)
2032 continue;
2034 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
2035 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
2037 if (first)
2039 _dl_printf ("\n\tVersion information:\n");
2040 first = 0;
2043 _dl_printf ("\t%s:\n",
2044 map->l_name[0] ? map->l_name : rtld_progname);
2046 while (1)
2048 ElfW(Vernaux) *aux;
2049 struct link_map *needed;
2051 needed = find_needed (strtab + ent->vn_file);
2052 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
2054 while (1)
2056 const char *fname = NULL;
2058 if (needed != NULL
2059 && match_version (strtab + aux->vna_name,
2060 needed))
2061 fname = needed->l_name;
2063 _dl_printf ("\t\t%s (%s) %s=> %s\n",
2064 strtab + ent->vn_file,
2065 strtab + aux->vna_name,
2066 aux->vna_flags & VER_FLG_WEAK
2067 ? "[WEAK] " : "",
2068 fname ?: "not found");
2070 if (aux->vna_next == 0)
2071 /* No more symbols. */
2072 break;
2074 /* Next symbol. */
2075 aux = (ElfW(Vernaux) *) ((char *) aux
2076 + aux->vna_next);
2079 if (ent->vn_next == 0)
2080 /* No more dependencies. */
2081 break;
2083 /* Next dependency. */
2084 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
2090 _exit (0);
2093 if (main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]
2094 && ! __builtin_expect (GLRO(dl_profile) != NULL, 0)
2095 && ! __builtin_expect (GLRO(dl_dynamic_weak), 0))
2097 ElfW(Lib) *liblist, *liblistend;
2098 struct link_map **r_list, **r_listend, *l;
2099 const char *strtab = (const void *) D_PTR (main_map, l_info[DT_STRTAB]);
2101 assert (main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
2102 liblist = (ElfW(Lib) *)
2103 main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
2104 liblistend = (ElfW(Lib) *)
2105 ((char *) liblist +
2106 main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
2107 r_list = main_map->l_searchlist.r_list;
2108 r_listend = r_list + main_map->l_searchlist.r_nlist;
2110 for (; r_list < r_listend && liblist < liblistend; r_list++)
2112 l = *r_list;
2114 if (l == main_map)
2115 continue;
2117 /* If the library is not mapped where it should, fail. */
2118 if (l->l_addr)
2119 break;
2121 /* Next, check if checksum matches. */
2122 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
2123 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
2124 != liblist->l_checksum)
2125 break;
2127 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
2128 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
2129 != liblist->l_time_stamp)
2130 break;
2132 if (! _dl_name_match_p (strtab + liblist->l_name, l))
2133 break;
2135 ++liblist;
2139 if (r_list == r_listend && liblist == liblistend)
2140 prelinked = true;
2142 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
2143 _dl_debug_printf ("\nprelink checking: %s\n",
2144 prelinked ? "ok" : "failed");
2148 /* Now set up the variable which helps the assembler startup code. */
2149 GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
2151 /* Save the information about the original global scope list since
2152 we need it in the memory handling later. */
2153 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
2155 if (prelinked)
2157 if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
2159 ElfW(Rela) *conflict, *conflictend;
2160 #ifndef HP_TIMING_NONAVAIL
2161 hp_timing_t start;
2162 hp_timing_t stop;
2163 #endif
2165 HP_TIMING_NOW (start);
2166 assert (main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
2167 conflict = (ElfW(Rela) *)
2168 main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
2169 conflictend = (ElfW(Rela) *)
2170 ((char *) conflict
2171 + main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
2172 _dl_resolve_conflicts (main_map, conflict, conflictend);
2173 HP_TIMING_NOW (stop);
2174 HP_TIMING_DIFF (relocate_time, start, stop);
2178 /* Mark all the objects so we know they have been already relocated. */
2179 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2181 l->l_relocated = 1;
2182 if (l->l_relro_size)
2183 _dl_protect_relro (l);
2185 /* Add object to slot information data if necessasy. */
2186 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2187 _dl_add_to_slotinfo (l);
2190 else
2192 /* Now we have all the objects loaded. Relocate them all except for
2193 the dynamic linker itself. We do this in reverse order so that copy
2194 relocs of earlier objects overwrite the data written by later
2195 objects. We do not re-relocate the dynamic linker itself in this
2196 loop because that could result in the GOT entries for functions we
2197 call being changed, and that would break us. It is safe to relocate
2198 the dynamic linker out of order because it has no copy relocs (we
2199 know that because it is self-contained). */
2201 int consider_profiling = GLRO(dl_profile) != NULL;
2202 #ifndef HP_TIMING_NONAVAIL
2203 hp_timing_t start;
2204 hp_timing_t stop;
2205 #endif
2207 /* If we are profiling we also must do lazy reloaction. */
2208 GLRO(dl_lazy) |= consider_profiling;
2210 struct link_map *l = main_map;
2211 while (l->l_next)
2212 l = l->l_next;
2214 HP_TIMING_NOW (start);
2217 /* While we are at it, help the memory handling a bit. We have to
2218 mark some data structures as allocated with the fake malloc()
2219 implementation in ld.so. */
2220 struct libname_list *lnp = l->l_libname->next;
2222 while (__builtin_expect (lnp != NULL, 0))
2224 lnp->dont_free = 1;
2225 lnp = lnp->next;
2228 if (l != &GL(dl_rtld_map))
2229 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy) ? RTLD_LAZY : 0,
2230 consider_profiling);
2232 /* Add object to slot information data if necessasy. */
2233 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2234 _dl_add_to_slotinfo (l);
2236 l = l->l_prev;
2238 while (l);
2239 HP_TIMING_NOW (stop);
2241 HP_TIMING_DIFF (relocate_time, start, stop);
2243 /* Now enable profiling if needed. Like the previous call,
2244 this has to go here because the calls it makes should use the
2245 rtld versions of the functions (particularly calloc()), but it
2246 needs to have _dl_profile_map set up by the relocator. */
2247 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
2248 /* We must prepare the profiling. */
2249 _dl_start_profile ();
2252 #ifndef NONTLS_INIT_TP
2253 # define NONTLS_INIT_TP do { } while (0)
2254 #endif
2256 if (!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2257 ++GL(dl_tls_generation);
2259 /* Now that we have completed relocation, the initializer data
2260 for the TLS blocks has its final values and we can copy them
2261 into the main thread's TLS area, which we allocated above. */
2262 _dl_allocate_tls_init (tcbp);
2264 /* And finally install it for the main thread. If ld.so itself uses
2265 TLS we know the thread pointer was initialized earlier. */
2266 if (! tls_init_tp_called)
2268 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
2269 if (__builtin_expect (lossage != NULL, 0))
2270 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2271 lossage);
2274 if (! prelinked && rtld_multiple_ref)
2276 /* There was an explicit ref to the dynamic linker as a shared lib.
2277 Re-relocate ourselves with user-controlled symbol definitions.
2279 We must do this after TLS initialization in case after this
2280 re-relocation, we might call a user-supplied function
2281 (e.g. calloc from _dl_relocate_object) that uses TLS data. */
2283 #ifndef HP_TIMING_NONAVAIL
2284 hp_timing_t start;
2285 hp_timing_t stop;
2286 hp_timing_t add;
2287 #endif
2289 HP_TIMING_NOW (start);
2290 /* Mark the link map as not yet relocated again. */
2291 GL(dl_rtld_map).l_relocated = 0;
2292 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2293 HP_TIMING_NOW (stop);
2294 HP_TIMING_DIFF (add, start, stop);
2295 HP_TIMING_ACCUM_NT (relocate_time, add);
2298 /* Do any necessary cleanups for the startup OS interface code.
2299 We do these now so that no calls are made after rtld re-relocation
2300 which might be resolved to different functions than we expect.
2301 We cannot do this before relocating the other objects because
2302 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2303 _dl_sysdep_start_cleanup ();
2305 #ifdef SHARED
2306 /* Auditing checkpoint: we have added all objects. */
2307 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
2309 struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2310 /* Do not call the functions for any auditing object. */
2311 if (head->l_auditing == 0)
2313 struct audit_ifaces *afct = GLRO(dl_audit);
2314 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2316 if (afct->activity != NULL)
2317 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
2319 afct = afct->next;
2323 #endif
2325 /* Notify the debugger all new objects are now ready to go. We must re-get
2326 the address since by now the variable might be in another object. */
2327 r = _dl_debug_initialize (0, LM_ID_BASE);
2328 r->r_state = RT_CONSISTENT;
2329 _dl_debug_state ();
2331 #ifndef MAP_COPY
2332 /* We must munmap() the cache file. */
2333 _dl_unload_cache ();
2334 #endif
2336 /* Once we return, _dl_sysdep_start will invoke
2337 the DT_INIT functions and then *USER_ENTRY. */
2340 /* This is a little helper function for resolving symbols while
2341 tracing the binary. */
2342 static void
2343 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2344 const char *errstring)
2346 if (objname[0] == '\0')
2347 objname = rtld_progname ?: "<main program>";
2348 _dl_error_printf ("%s (%s)\n", errstring, objname);
2351 /* This is a little helper function for resolving symbols while
2352 tracing the binary. */
2353 static void
2354 print_missing_version (int errcode __attribute__ ((unused)),
2355 const char *objname, const char *errstring)
2357 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
2358 objname, errstring);
2361 /* Nonzero if any of the debugging options is enabled. */
2362 static int any_debug attribute_relro;
2364 /* Process the string given as the parameter which explains which debugging
2365 options are enabled. */
2366 static void
2367 process_dl_debug (const char *dl_debug)
2369 /* When adding new entries make sure that the maximal length of a name
2370 is correctly handled in the LD_DEBUG_HELP code below. */
2371 static const struct
2373 unsigned char len;
2374 const char name[10];
2375 const char helptext[41];
2376 unsigned short int mask;
2377 } debopts[] =
2379 #define LEN_AND_STR(str) sizeof (str) - 1, str
2380 { LEN_AND_STR ("libs"), "display library search paths",
2381 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2382 { LEN_AND_STR ("reloc"), "display relocation processing",
2383 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2384 { LEN_AND_STR ("files"), "display progress for input file",
2385 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2386 { LEN_AND_STR ("symbols"), "display symbol table processing",
2387 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2388 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2389 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2390 { LEN_AND_STR ("versions"), "display version dependencies",
2391 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2392 { LEN_AND_STR ("all"), "all previous options combined",
2393 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2394 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2395 { LEN_AND_STR ("statistics"), "display relocation statistics",
2396 DL_DEBUG_STATISTICS },
2397 { LEN_AND_STR ("unused"), "determined unused DSOs",
2398 DL_DEBUG_UNUSED },
2399 { LEN_AND_STR ("help"), "display this help message and exit",
2400 DL_DEBUG_HELP },
2402 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2404 /* Skip separating white spaces and commas. */
2405 while (*dl_debug != '\0')
2407 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2409 size_t cnt;
2410 size_t len = 1;
2412 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2413 && dl_debug[len] != ',' && dl_debug[len] != ':')
2414 ++len;
2416 for (cnt = 0; cnt < ndebopts; ++cnt)
2417 if (debopts[cnt].len == len
2418 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
2420 GLRO(dl_debug_mask) |= debopts[cnt].mask;
2421 any_debug = 1;
2422 break;
2425 if (cnt == ndebopts)
2427 /* Display a warning and skip everything until next
2428 separator. */
2429 char *copy = strndupa (dl_debug, len);
2430 _dl_error_printf ("\
2431 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2434 dl_debug += len;
2435 continue;
2438 ++dl_debug;
2441 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
2443 size_t cnt;
2445 _dl_printf ("\
2446 Valid options for the LD_DEBUG environment variable are:\n\n");
2448 for (cnt = 0; cnt < ndebopts; ++cnt)
2449 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2450 " " + debopts[cnt].len - 3,
2451 debopts[cnt].helptext);
2453 _dl_printf ("\n\
2454 To direct the debugging output into a file instead of standard output\n\
2455 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2456 _exit (0);
2460 static void
2461 process_dl_audit (char *str)
2463 /* The parameter is a colon separated list of DSO names. */
2464 char *p;
2466 while ((p = (strsep) (&str, ":")) != NULL)
2467 if (p[0] != '\0'
2468 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
2469 || strchr (p, '/') == NULL))
2471 /* This is using the local malloc, not the system malloc. The
2472 memory can never be freed. */
2473 struct audit_list *newp = malloc (sizeof (*newp));
2474 newp->name = p;
2476 if (audit_list == NULL)
2477 audit_list = newp->next = newp;
2478 else
2480 newp->next = audit_list->next;
2481 audit_list = audit_list->next = newp;
2486 /* Process all environments variables the dynamic linker must recognize.
2487 Since all of them start with `LD_' we are a bit smarter while finding
2488 all the entries. */
2489 extern char **_environ attribute_hidden;
2492 static void
2493 process_envvars (enum mode *modep)
2495 char **runp = _environ;
2496 char *envline;
2497 enum mode mode = normal;
2498 char *debug_output = NULL;
2500 /* This is the default place for profiling data file. */
2501 GLRO(dl_profile_output)
2502 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2504 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2506 size_t len = 0;
2508 while (envline[len] != '\0' && envline[len] != '=')
2509 ++len;
2511 if (envline[len] != '=')
2512 /* This is a "LD_" variable at the end of the string without
2513 a '=' character. Ignore it since otherwise we will access
2514 invalid memory below. */
2515 continue;
2517 switch (len)
2519 case 4:
2520 /* Warning level, verbose or not. */
2521 if (memcmp (envline, "WARN", 4) == 0)
2522 GLRO(dl_verbose) = envline[5] != '\0';
2523 break;
2525 case 5:
2526 /* Debugging of the dynamic linker? */
2527 if (memcmp (envline, "DEBUG", 5) == 0)
2529 process_dl_debug (&envline[6]);
2530 break;
2532 if (memcmp (envline, "AUDIT", 5) == 0)
2533 process_dl_audit (&envline[6]);
2534 break;
2536 case 7:
2537 /* Print information about versions. */
2538 if (memcmp (envline, "VERBOSE", 7) == 0)
2540 version_info = envline[8] != '\0';
2541 break;
2544 /* List of objects to be preloaded. */
2545 if (memcmp (envline, "PRELOAD", 7) == 0)
2547 preloadlist = &envline[8];
2548 break;
2551 /* Which shared object shall be profiled. */
2552 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2553 GLRO(dl_profile) = &envline[8];
2554 break;
2556 case 8:
2557 /* Do we bind early? */
2558 if (memcmp (envline, "BIND_NOW", 8) == 0)
2560 GLRO(dl_lazy) = envline[9] == '\0';
2561 break;
2563 if (memcmp (envline, "BIND_NOT", 8) == 0)
2564 GLRO(dl_bind_not) = envline[9] != '\0';
2565 break;
2567 case 9:
2568 /* Test whether we want to see the content of the auxiliary
2569 array passed up from the kernel. */
2570 if (!INTUSE(__libc_enable_secure)
2571 && memcmp (envline, "SHOW_AUXV", 9) == 0)
2572 _dl_show_auxv ();
2573 break;
2575 case 10:
2576 /* Mask for the important hardware capabilities. */
2577 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2578 GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2579 0, 0);
2580 break;
2582 case 11:
2583 /* Path where the binary is found. */
2584 if (!INTUSE(__libc_enable_secure)
2585 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2586 GLRO(dl_origin_path) = &envline[12];
2587 break;
2589 case 12:
2590 /* The library search path. */
2591 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2593 library_path = &envline[13];
2594 break;
2597 /* Where to place the profiling data file. */
2598 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2600 debug_output = &envline[13];
2601 break;
2604 if (!INTUSE(__libc_enable_secure)
2605 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2606 GLRO(dl_dynamic_weak) = 1;
2607 break;
2609 case 13:
2610 /* We might have some extra environment variable with length 13
2611 to handle. */
2612 #ifdef EXTRA_LD_ENVVARS_13
2613 EXTRA_LD_ENVVARS_13
2614 #endif
2615 if (!INTUSE(__libc_enable_secure)
2616 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2618 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2619 break;
2622 if (memcmp (envline, "POINTER_GUARD", 13) == 0)
2623 GLRO(dl_pointer_guard) = envline[14] != '0';
2624 break;
2626 case 14:
2627 /* Where to place the profiling data file. */
2628 if (!INTUSE(__libc_enable_secure)
2629 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2630 && envline[15] != '\0')
2631 GLRO(dl_profile_output) = &envline[15];
2632 break;
2634 case 16:
2635 /* The mode of the dynamic linker can be set. */
2636 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2638 mode = trace;
2639 GLRO(dl_verbose) = 1;
2640 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2641 GLRO(dl_trace_prelink) = &envline[17];
2643 break;
2645 case 20:
2646 /* The mode of the dynamic linker can be set. */
2647 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2648 mode = trace;
2649 break;
2651 /* We might have some extra environment variable to handle. This
2652 is tricky due to the pre-processing of the length of the name
2653 in the switch statement here. The code here assumes that added
2654 environment variables have a different length. */
2655 #ifdef EXTRA_LD_ENVVARS
2656 EXTRA_LD_ENVVARS
2657 #endif
2661 /* The caller wants this information. */
2662 *modep = mode;
2664 /* Extra security for SUID binaries. Remove all dangerous environment
2665 variables. */
2666 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2668 static const char unsecure_envvars[] =
2669 #ifdef EXTRA_UNSECURE_ENVVARS
2670 EXTRA_UNSECURE_ENVVARS
2671 #endif
2672 UNSECURE_ENVVARS;
2673 const char *nextp;
2675 nextp = unsecure_envvars;
2678 unsetenv (nextp);
2679 /* We could use rawmemchr but this need not be fast. */
2680 nextp = (char *) (strchr) (nextp, '\0') + 1;
2682 while (*nextp != '\0');
2684 if (__access ("/etc/suid-debug", F_OK) != 0)
2686 unsetenv ("MALLOC_CHECK_");
2687 GLRO(dl_debug_mask) = 0;
2690 if (mode != normal)
2691 _exit (5);
2693 /* If we have to run the dynamic linker in debugging mode and the
2694 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2695 messages to this file. */
2696 else if (any_debug && debug_output != NULL)
2698 #ifdef O_NOFOLLOW
2699 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2700 #else
2701 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2702 #endif
2703 size_t name_len = strlen (debug_output);
2704 char buf[name_len + 12];
2705 char *startp;
2707 buf[name_len + 11] = '\0';
2708 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2709 *--startp = '.';
2710 startp = memcpy (startp - name_len, debug_output, name_len);
2712 GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2713 if (GLRO(dl_debug_fd) == -1)
2714 /* We use standard output if opening the file failed. */
2715 GLRO(dl_debug_fd) = STDOUT_FILENO;
2720 /* Print the various times we collected. */
2721 static void
2722 __attribute ((noinline))
2723 print_statistics (hp_timing_t *rtld_total_timep)
2725 #ifndef HP_TIMING_NONAVAIL
2726 char buf[200];
2727 char *cp;
2728 char *wp;
2730 /* Total time rtld used. */
2731 if (HP_TIMING_AVAIL)
2733 HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2734 _dl_debug_printf ("\nruntime linker statistics:\n"
2735 " total startup time in dynamic loader: %s\n", buf);
2737 /* Print relocation statistics. */
2738 char pbuf[30];
2739 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2740 cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2741 pbuf + sizeof (pbuf), 10, 0);
2742 wp = pbuf;
2743 switch (pbuf + sizeof (pbuf) - cp)
2745 case 3:
2746 *wp++ = *cp++;
2747 case 2:
2748 *wp++ = *cp++;
2749 case 1:
2750 *wp++ = '.';
2751 *wp++ = *cp++;
2753 *wp = '\0';
2754 _dl_debug_printf ("\
2755 time needed for relocation: %s (%s%%)\n", buf, pbuf);
2757 #endif
2759 unsigned long int num_relative_relocations = 0;
2760 for (Lmid_t ns = 0; ns < GL(dl_nns); ++ns)
2762 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2763 continue;
2765 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2767 for (unsigned int i = 0; i < scope->r_nlist; i++)
2769 struct link_map *l = scope->r_list [i];
2771 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2772 num_relative_relocations
2773 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2774 #ifndef ELF_MACHINE_REL_RELATIVE
2775 /* Relative relocations are processed on these architectures if
2776 library is loaded to different address than p_vaddr or
2777 if not prelinked. */
2778 if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2779 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2780 #else
2781 /* On e.g. IA-64 or Alpha, relative relocations are processed
2782 only if library is loaded to different address than p_vaddr. */
2783 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2784 #endif
2785 num_relative_relocations
2786 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2790 _dl_debug_printf (" number of relocations: %lu\n"
2791 " number of relocations from cache: %lu\n"
2792 " number of relative relocations: %lu\n",
2793 GL(dl_num_relocations),
2794 GL(dl_num_cache_relocations),
2795 num_relative_relocations);
2797 #ifndef HP_TIMING_NONAVAIL
2798 /* Time spend while loading the object and the dependencies. */
2799 if (HP_TIMING_AVAIL)
2801 char pbuf[30];
2802 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2803 cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2804 pbuf + sizeof (pbuf), 10, 0);
2805 wp = pbuf;
2806 switch (pbuf + sizeof (pbuf) - cp)
2808 case 3:
2809 *wp++ = *cp++;
2810 case 2:
2811 *wp++ = *cp++;
2812 case 1:
2813 *wp++ = '.';
2814 *wp++ = *cp++;
2816 *wp = '\0';
2817 _dl_debug_printf ("\
2818 time needed to load objects: %s (%s%%)\n",
2819 buf, pbuf);
2821 #endif