Fix grouping and reuse other locales in various locales
[glibc.git] / elf / rtld.c
blobe4e413f601b8fefabb376f76554c98859a59d114
1 /* Run time dynamic linker.
2 Copyright (C) 1995-2010, 2011 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>
43 #include <stackinfo.h>
45 #include <assert.h>
47 /* Avoid PLT use for our local calls at startup. */
48 extern __typeof (__mempcpy) __mempcpy attribute_hidden;
50 /* GCC has mental blocks about _exit. */
51 extern __typeof (_exit) exit_internal asm ("_exit") attribute_hidden;
52 #define _exit exit_internal
54 /* Helper function to handle errors while resolving symbols. */
55 static void print_unresolved (int errcode, const char *objname,
56 const char *errsting);
58 /* Helper function to handle errors when a version is missing. */
59 static void print_missing_version (int errcode, const char *objname,
60 const char *errsting);
62 /* Print the various times we collected. */
63 static void print_statistics (hp_timing_t *total_timep);
65 /* Add audit objects. */
66 static void process_dl_audit (char *str);
68 /* This is a list of all the modes the dynamic loader can be in. */
69 enum mode { normal, list, verify, trace };
71 /* Process all environments variables the dynamic linker must recognize.
72 Since all of them start with `LD_' we are a bit smarter while finding
73 all the entries. */
74 static void process_envvars (enum mode *modep);
76 #ifdef DL_ARGV_NOT_RELRO
77 int _dl_argc attribute_hidden;
78 char **_dl_argv = NULL;
79 /* Nonzero if we were run directly. */
80 unsigned int _dl_skip_args attribute_hidden;
81 #else
82 int _dl_argc attribute_relro attribute_hidden;
83 char **_dl_argv attribute_relro = NULL;
84 unsigned int _dl_skip_args attribute_relro attribute_hidden;
85 #endif
86 INTDEF(_dl_argv)
88 #ifndef THREAD_SET_STACK_GUARD
89 /* Only exported for architectures that don't store the stack guard canary
90 in thread local area. */
91 uintptr_t __stack_chk_guard attribute_relro;
92 #endif
94 /* Only exported for architectures that don't store the pointer guard
95 value in thread local area. */
96 uintptr_t __pointer_chk_guard_local
97 attribute_relro attribute_hidden __attribute__ ((nocommon));
98 #ifndef THREAD_SET_POINTER_GUARD
99 strong_alias (__pointer_chk_guard_local, __pointer_chk_guard)
100 #endif
103 /* List of auditing DSOs. */
104 static struct audit_list
106 const char *name;
107 struct audit_list *next;
108 } *audit_list;
110 #ifndef HAVE_INLINED_SYSCALLS
111 /* Set nonzero during loading and initialization of executable and
112 libraries, cleared before the executable's entry point runs. This
113 must not be initialized to nonzero, because the unused dynamic
114 linker loaded in for libc.so's "ld.so.1" dep will provide the
115 definition seen by libc.so's initializer; that value must be zero,
116 and will be since that dynamic linker's _dl_start and dl_main will
117 never be called. */
118 int _dl_starting_up = 0;
119 INTVARDEF(_dl_starting_up)
120 #endif
122 /* This is the structure which defines all variables global to ld.so
123 (except those which cannot be added for some reason). */
124 struct rtld_global _rtld_global =
126 /* Generally the default presumption without further information is an
127 * executable stack but this is not true for all platforms. */
128 ._dl_stack_flags = DEFAULT_STACK_PERMS,
129 #ifdef _LIBC_REENTRANT
130 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
131 ._dl_load_write_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
132 #endif
133 ._dl_nns = 1,
134 ._dl_ns =
136 [LM_ID_BASE] = { ._ns_unique_sym_table
137 = { .lock = _RTLD_LOCK_RECURSIVE_INITIALIZER } }
140 /* If we would use strong_alias here the compiler would see a
141 non-hidden definition. This would undo the effect of the previous
142 declaration. So spell out was strong_alias does plus add the
143 visibility attribute. */
144 extern struct rtld_global _rtld_local
145 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
148 /* This variable is similar to _rtld_local, but all values are
149 read-only after relocation. */
150 struct rtld_global_ro _rtld_global_ro attribute_relro =
152 /* Get architecture specific initializer. */
153 #include <dl-procinfo.c>
154 #ifdef NEED_DL_SYSINFO
155 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
156 #endif
157 ._dl_debug_fd = STDERR_FILENO,
158 ._dl_use_load_bias = -2,
159 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
160 ._dl_hwcap_mask = HWCAP_IMPORTANT,
161 ._dl_lazy = 1,
162 ._dl_fpu_control = _FPU_DEFAULT,
163 ._dl_pointer_guard = 1,
164 ._dl_pagesize = EXEC_PAGESIZE,
166 /* Function pointers. */
167 ._dl_debug_printf = _dl_debug_printf,
168 ._dl_catch_error = _dl_catch_error,
169 ._dl_signal_error = _dl_signal_error,
170 ._dl_mcount = _dl_mcount_internal,
171 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
172 ._dl_check_caller = _dl_check_caller,
173 ._dl_open = _dl_open,
174 ._dl_close = _dl_close,
175 ._dl_tls_get_addr_soft = _dl_tls_get_addr_soft,
176 #ifdef HAVE_DL_DISCOVER_OSVERSION
177 ._dl_discover_osversion = _dl_discover_osversion
178 #endif
180 /* If we would use strong_alias here the compiler would see a
181 non-hidden definition. This would undo the effect of the previous
182 declaration. So spell out was strong_alias does plus add the
183 visibility attribute. */
184 extern struct rtld_global_ro _rtld_local_ro
185 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
188 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
189 ElfW(Addr) *user_entry, ElfW(auxv_t) *auxv);
191 /* These two variables cannot be moved into .data.rel.ro. */
192 static struct libname_list _dl_rtld_libname;
193 static struct libname_list _dl_rtld_libname2;
195 /* We expect less than a second for relocation. */
196 #ifdef HP_SMALL_TIMING_AVAIL
197 # undef HP_TIMING_AVAIL
198 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
199 #endif
201 /* Variable for statistics. */
202 #ifndef HP_TIMING_NONAVAIL
203 static hp_timing_t relocate_time;
204 static hp_timing_t load_time attribute_relro;
205 static hp_timing_t start_time attribute_relro;
206 #endif
208 /* Additional definitions needed by TLS initialization. */
209 #ifdef TLS_INIT_HELPER
210 TLS_INIT_HELPER
211 #endif
213 /* Helper function for syscall implementation. */
214 #ifdef DL_SYSINFO_IMPLEMENTATION
215 DL_SYSINFO_IMPLEMENTATION
216 #endif
218 /* Before ld.so is relocated we must not access variables which need
219 relocations. This means variables which are exported. Variables
220 declared as static are fine. If we can mark a variable hidden this
221 is fine, too. The latter is important here. We can avoid setting
222 up a temporary link map for ld.so if we can mark _rtld_global as
223 hidden. */
224 #ifdef PI_STATIC_AND_HIDDEN
225 # define DONT_USE_BOOTSTRAP_MAP 1
226 #endif
228 #ifdef DONT_USE_BOOTSTRAP_MAP
229 static ElfW(Addr) _dl_start_final (void *arg);
230 #else
231 struct dl_start_final_info
233 struct link_map l;
234 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
235 hp_timing_t start_time;
236 #endif
238 static ElfW(Addr) _dl_start_final (void *arg,
239 struct dl_start_final_info *info);
240 #endif
242 /* These defined magically in the linker script. */
243 extern char _begin[] attribute_hidden;
244 extern char _etext[] attribute_hidden;
245 extern char _end[] attribute_hidden;
248 #ifdef RTLD_START
249 RTLD_START
250 #else
251 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
252 #endif
254 #ifndef VALIDX
255 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
256 + DT_EXTRANUM + DT_VALTAGIDX (tag))
257 #endif
258 #ifndef ADDRIDX
259 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
260 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
261 #endif
263 /* This is the second half of _dl_start (below). It can be inlined safely
264 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
265 references. When the tools don't permit us to avoid using a GOT entry
266 for _dl_rtld_global (no attribute_hidden support), we must make sure
267 this function is not inlined (see below). */
269 #ifdef DONT_USE_BOOTSTRAP_MAP
270 static inline ElfW(Addr) __attribute__ ((always_inline))
271 _dl_start_final (void *arg)
272 #else
273 static ElfW(Addr) __attribute__ ((noinline))
274 _dl_start_final (void *arg, struct dl_start_final_info *info)
275 #endif
277 ElfW(Addr) start_addr;
279 if (HP_TIMING_AVAIL)
281 /* If it hasn't happen yet record the startup time. */
282 if (! HP_TIMING_INLINE)
283 HP_TIMING_NOW (start_time);
284 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
285 else
286 start_time = info->start_time;
287 #endif
289 /* Initialize the timing functions. */
290 HP_TIMING_DIFF_INIT ();
293 /* Transfer data about ourselves to the permanent link_map structure. */
294 #ifndef DONT_USE_BOOTSTRAP_MAP
295 GL(dl_rtld_map).l_addr = info->l.l_addr;
296 GL(dl_rtld_map).l_ld = info->l.l_ld;
297 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
298 sizeof GL(dl_rtld_map).l_info);
299 GL(dl_rtld_map).l_mach = info->l.l_mach;
300 GL(dl_rtld_map).l_relocated = 1;
301 #endif
302 _dl_setup_hash (&GL(dl_rtld_map));
303 GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
304 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
305 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
306 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
307 /* Copy the TLS related data if necessary. */
308 #ifndef DONT_USE_BOOTSTRAP_MAP
309 # if USE___THREAD
310 assert (info->l.l_tls_modid != 0);
311 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
312 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
313 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
314 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
315 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
316 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
317 GL(dl_rtld_map).l_tls_modid = 1;
318 # else
319 # if NO_TLS_OFFSET != 0
320 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
321 # endif
322 # endif
324 #endif
326 #if HP_TIMING_AVAIL
327 HP_TIMING_NOW (GL(dl_cpuclock_offset));
328 #endif
330 /* Initialize the stack end variable. */
331 __libc_stack_end = __builtin_frame_address (0);
333 /* Call the OS-dependent function to set up life so we can do things like
334 file access. It will call `dl_main' (below) to do all the real work
335 of the dynamic linker, and then unwind our frame and run the user
336 entry point on the same stack we entered on. */
337 start_addr = _dl_sysdep_start (arg, &dl_main);
339 #ifndef HP_TIMING_NONAVAIL
340 hp_timing_t rtld_total_time;
341 if (HP_TIMING_AVAIL)
343 hp_timing_t end_time;
345 /* Get the current time. */
346 HP_TIMING_NOW (end_time);
348 /* Compute the difference. */
349 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
351 #endif
353 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
355 #ifndef HP_TIMING_NONAVAIL
356 print_statistics (&rtld_total_time);
357 #else
358 print_statistics (NULL);
359 #endif
362 return start_addr;
365 static ElfW(Addr) __attribute_used__ internal_function
366 _dl_start (void *arg)
368 #ifdef DONT_USE_BOOTSTRAP_MAP
369 # define bootstrap_map GL(dl_rtld_map)
370 #else
371 struct dl_start_final_info info;
372 # define bootstrap_map info.l
373 #endif
375 /* This #define produces dynamic linking inline functions for
376 bootstrap relocation instead of general-purpose relocation.
377 Since ld.so must not have any undefined symbols the result
378 is trivial: always the map of ld.so itself. */
379 #define RTLD_BOOTSTRAP
380 #define RESOLVE_MAP(sym, version, flags) (&bootstrap_map)
381 #include "dynamic-link.h"
383 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
384 #ifdef DONT_USE_BOOTSTRAP_MAP
385 HP_TIMING_NOW (start_time);
386 #else
387 HP_TIMING_NOW (info.start_time);
388 #endif
390 /* Partly clean the `bootstrap_map' structure up. Don't use
391 `memset' since it might not be built in or inlined and we cannot
392 make function calls at this point. Use '__builtin_memset' if we
393 know it is available. We do not have to clear the memory if we
394 do not have to use the temporary bootstrap_map. Global variables
395 are initialized to zero by default. */
396 #ifndef DONT_USE_BOOTSTRAP_MAP
397 # ifdef HAVE_BUILTIN_MEMSET
398 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
399 # else
400 for (size_t cnt = 0;
401 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
402 ++cnt)
403 bootstrap_map.l_info[cnt] = 0;
404 # endif
405 # if USE___THREAD
406 bootstrap_map.l_tls_modid = 0;
407 # endif
408 #endif
410 /* Figure out the run-time load address of the dynamic linker itself. */
411 bootstrap_map.l_addr = elf_machine_load_address ();
413 /* Read our own dynamic section and fill in the info array. */
414 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
415 elf_get_dynamic_info (&bootstrap_map, NULL);
417 #if NO_TLS_OFFSET != 0
418 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
419 #endif
421 /* Get the dynamic linker's own program header. First we need the ELF
422 file header. The `_begin' symbol created by the linker script points
423 to it. When we have something like GOTOFF relocs, we can use a plain
424 reference to find the runtime address. Without that, we have to rely
425 on the `l_addr' value, which is not the value we want when prelinked. */
426 #if USE___THREAD
427 dtv_t initdtv[3];
428 ElfW(Ehdr) *ehdr
429 # ifdef DONT_USE_BOOTSTRAP_MAP
430 = (ElfW(Ehdr) *) &_begin;
431 # else
432 # error This will not work with prelink.
433 = (ElfW(Ehdr) *) bootstrap_map.l_addr;
434 # endif
435 ElfW(Phdr) *phdr = (ElfW(Phdr) *) ((void *) ehdr + ehdr->e_phoff);
436 size_t cnt = ehdr->e_phnum; /* PT_TLS is usually the last phdr. */
437 while (cnt-- > 0)
438 if (phdr[cnt].p_type == PT_TLS)
440 void *tlsblock;
441 size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
442 char *p;
444 bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
445 bootstrap_map.l_tls_align = phdr[cnt].p_align;
446 if (phdr[cnt].p_align == 0)
447 bootstrap_map.l_tls_firstbyte_offset = 0;
448 else
449 bootstrap_map.l_tls_firstbyte_offset = (phdr[cnt].p_vaddr
450 & (phdr[cnt].p_align - 1));
451 assert (bootstrap_map.l_tls_blocksize != 0);
452 bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
453 bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
454 + phdr[cnt].p_vaddr);
456 /* We can now allocate the initial TLS block. This can happen
457 on the stack. We'll get the final memory later when we
458 know all about the various objects loaded at startup
459 time. */
460 # if TLS_TCB_AT_TP
461 tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
462 TLS_INIT_TCB_ALIGN)
463 + TLS_INIT_TCB_SIZE
464 + max_align);
465 # elif TLS_DTV_AT_TP
466 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
467 bootstrap_map.l_tls_align)
468 + bootstrap_map.l_tls_blocksize
469 + max_align);
470 # else
471 /* In case a model with a different layout for the TCB and DTV
472 is defined add another #elif here and in the following #ifs. */
473 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
474 # endif
475 /* Align the TLS block. */
476 tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
477 & ~(max_align - 1));
479 /* Initialize the dtv. [0] is the length, [1] the generation
480 counter. */
481 initdtv[0].counter = 1;
482 initdtv[1].counter = 0;
484 /* Initialize the TLS block. */
485 # if TLS_TCB_AT_TP
486 initdtv[2].pointer = tlsblock;
487 # elif TLS_DTV_AT_TP
488 bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
489 bootstrap_map.l_tls_align);
490 initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
491 # else
492 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
493 # endif
494 p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
495 bootstrap_map.l_tls_initimage_size);
496 # ifdef HAVE_BUILTIN_MEMSET
497 __builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
498 - bootstrap_map.l_tls_initimage_size));
499 # else
501 size_t remaining = (bootstrap_map.l_tls_blocksize
502 - bootstrap_map.l_tls_initimage_size);
503 while (remaining-- > 0)
504 *p++ = '\0';
506 # endif
508 /* Install the pointer to the dtv. */
510 /* Initialize the thread pointer. */
511 # if TLS_TCB_AT_TP
512 bootstrap_map.l_tls_offset
513 = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
515 INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
516 initdtv);
518 const char *lossage = TLS_INIT_TP ((char *) tlsblock
519 + bootstrap_map.l_tls_offset, 0);
520 # elif TLS_DTV_AT_TP
521 INSTALL_DTV (tlsblock, initdtv);
522 const char *lossage = TLS_INIT_TP (tlsblock, 0);
523 # else
524 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
525 # endif
526 if (__builtin_expect (lossage != NULL, 0))
527 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
528 lossage);
530 /* So far this is module number one. */
531 bootstrap_map.l_tls_modid = 1;
533 /* There can only be one PT_TLS entry. */
534 break;
536 #endif /* USE___THREAD */
538 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
539 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
540 #endif
542 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
544 /* Relocate ourselves so we can do normal function calls and
545 data access using the global offset table. */
547 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0, 0);
549 bootstrap_map.l_relocated = 1;
551 /* Please note that we don't allow profiling of this object and
552 therefore need not test whether we have to allocate the array
553 for the relocation results (as done in dl-reloc.c). */
555 /* Now life is sane; we can call functions and access global data.
556 Set up to use the operating system facilities, and find out from
557 the operating system's program loader where to find the program
558 header table in core. Put the rest of _dl_start into a separate
559 function, that way the compiler cannot put accesses to the GOT
560 before ELF_DYNAMIC_RELOCATE. */
562 #ifdef DONT_USE_BOOTSTRAP_MAP
563 ElfW(Addr) entry = _dl_start_final (arg);
564 #else
565 ElfW(Addr) entry = _dl_start_final (arg, &info);
566 #endif
568 #ifndef ELF_MACHINE_START_ADDRESS
569 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
570 #endif
572 return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, entry);
578 /* Now life is peachy; we can do all normal operations.
579 On to the real work. */
581 /* Some helper functions. */
583 /* Arguments to relocate_doit. */
584 struct relocate_args
586 struct link_map *l;
587 int reloc_mode;
590 struct map_args
592 /* Argument to map_doit. */
593 char *str;
594 struct link_map *loader;
595 int mode;
596 /* Return value of map_doit. */
597 struct link_map *map;
600 struct dlmopen_args
602 const char *fname;
603 struct link_map *map;
606 struct lookup_args
608 const char *name;
609 struct link_map *map;
610 void *result;
613 /* Arguments to version_check_doit. */
614 struct version_check_args
616 int doexit;
617 int dotrace;
620 static void
621 relocate_doit (void *a)
623 struct relocate_args *args = (struct relocate_args *) a;
625 _dl_relocate_object (args->l, args->l->l_scope, args->reloc_mode, 0);
628 static void
629 map_doit (void *a)
631 struct map_args *args = (struct map_args *) a;
632 args->map = _dl_map_object (args->loader, args->str, lt_library, 0,
633 args->mode, LM_ID_BASE);
636 static void
637 dlmopen_doit (void *a)
639 struct dlmopen_args *args = (struct dlmopen_args *) a;
640 args->map = _dl_open (args->fname,
641 (RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT
642 | __RTLD_SECURE),
643 dl_main, LM_ID_NEWLM, _dl_argc, INTUSE(_dl_argv),
644 __environ);
647 static void
648 lookup_doit (void *a)
650 struct lookup_args *args = (struct lookup_args *) a;
651 const ElfW(Sym) *ref = NULL;
652 args->result = NULL;
653 lookup_t l = _dl_lookup_symbol_x (args->name, args->map, &ref,
654 args->map->l_local_scope, NULL, 0,
655 DL_LOOKUP_RETURN_NEWEST, NULL);
656 if (ref != NULL)
657 args->result = DL_SYMBOL_ADDRESS (l, ref);
660 static void
661 version_check_doit (void *a)
663 struct version_check_args *args = (struct version_check_args *) a;
664 if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
665 args->dotrace) && args->doexit)
666 /* We cannot start the application. Abort now. */
667 _exit (1);
671 static inline struct link_map *
672 find_needed (const char *name)
674 struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
675 unsigned int n = scope->r_nlist;
677 while (n-- > 0)
678 if (_dl_name_match_p (name, scope->r_list[n]))
679 return scope->r_list[n];
681 /* Should never happen. */
682 return NULL;
685 static int
686 match_version (const char *string, struct link_map *map)
688 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
689 ElfW(Verdef) *def;
691 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
692 if (map->l_info[VERDEFTAG] == NULL)
693 /* The file has no symbol versioning. */
694 return 0;
696 def = (ElfW(Verdef) *) ((char *) map->l_addr
697 + map->l_info[VERDEFTAG]->d_un.d_ptr);
698 while (1)
700 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
702 /* Compare the version strings. */
703 if (strcmp (string, strtab + aux->vda_name) == 0)
704 /* Bingo! */
705 return 1;
707 /* If no more definitions we failed to find what we want. */
708 if (def->vd_next == 0)
709 break;
711 /* Next definition. */
712 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
715 return 0;
718 static bool tls_init_tp_called;
720 static void *
721 init_tls (void)
723 /* Number of elements in the static TLS block. */
724 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
726 /* Do not do this twice. The audit interface might have required
727 the DTV interfaces to be set up early. */
728 if (GL(dl_initial_dtv) != NULL)
729 return NULL;
731 /* Allocate the array which contains the information about the
732 dtv slots. We allocate a few entries more than needed to
733 avoid the need for reallocation. */
734 size_t nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
736 /* Allocate. */
737 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
738 calloc (sizeof (struct dtv_slotinfo_list)
739 + nelem * sizeof (struct dtv_slotinfo), 1);
740 /* No need to check the return value. If memory allocation failed
741 the program would have been terminated. */
743 struct dtv_slotinfo *slotinfo = GL(dl_tls_dtv_slotinfo_list)->slotinfo;
744 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
745 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
747 /* Fill in the information from the loaded modules. No namespace
748 but the base one can be filled at this time. */
749 assert (GL(dl_ns)[LM_ID_BASE + 1]._ns_loaded == NULL);
750 int i = 0;
751 for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
752 l = l->l_next)
753 if (l->l_tls_blocksize != 0)
755 /* This is a module with TLS data. Store the map reference.
756 The generation counter is zero. */
757 slotinfo[i].map = l;
758 /* slotinfo[i].gen = 0; */
759 ++i;
761 assert (i == GL(dl_tls_max_dtv_idx));
763 /* Compute the TLS offsets for the various blocks. */
764 _dl_determine_tlsoffset ();
766 /* Construct the static TLS block and the dtv for the initial
767 thread. For some platforms this will include allocating memory
768 for the thread descriptor. The memory for the TLS block will
769 never be freed. It should be allocated accordingly. The dtv
770 array can be changed if dynamic loading requires it. */
771 void *tcbp = _dl_allocate_tls_storage ();
772 if (tcbp == NULL)
773 _dl_fatal_printf ("\
774 cannot allocate TLS data structures for initial thread");
776 /* Store for detection of the special case by __tls_get_addr
777 so it knows not to pass this dtv to the normal realloc. */
778 GL(dl_initial_dtv) = GET_DTV (tcbp);
780 /* And finally install it for the main thread. If ld.so itself uses
781 TLS we know the thread pointer was initialized earlier. */
782 const char *lossage
783 #ifdef USE___THREAD
784 = TLS_INIT_TP (tcbp, USE___THREAD);
785 #else
786 = TLS_INIT_TP (tcbp, 0);
787 #endif
788 if (__builtin_expect (lossage != NULL, 0))
789 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
790 tls_init_tp_called = true;
792 return tcbp;
795 #ifdef _LIBC_REENTRANT
796 /* _dl_error_catch_tsd points to this for the single-threaded case.
797 It's reset by the thread library for multithreaded programs. */
798 void ** __attribute__ ((const))
799 _dl_initial_error_catch_tsd (void)
801 static void *data;
802 return &data;
804 #endif
807 static unsigned int
808 do_preload (char *fname, struct link_map *main_map, const char *where)
810 const char *objname;
811 const char *err_str = NULL;
812 struct map_args args;
813 bool malloced;
815 args.str = fname;
816 args.loader = main_map;
817 args.mode = __RTLD_SECURE;
819 unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
821 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
822 if (__builtin_expect (err_str != NULL, 0))
824 _dl_error_printf ("\
825 ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
826 fname, where);
827 /* No need to call free, this is still before
828 the libc's malloc is used. */
830 else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
831 /* It is no duplicate. */
832 return 1;
834 /* Nothing loaded. */
835 return 0;
838 #if defined SHARED && defined _LIBC_REENTRANT \
839 && defined __rtld_lock_default_lock_recursive
840 static void
841 rtld_lock_default_lock_recursive (void *lock)
843 __rtld_lock_default_lock_recursive (lock);
846 static void
847 rtld_lock_default_unlock_recursive (void *lock)
849 __rtld_lock_default_unlock_recursive (lock);
851 #endif
854 static void
855 security_init (void)
857 /* Set up the stack checker's canary. */
858 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard (_dl_random);
859 #ifdef THREAD_SET_STACK_GUARD
860 THREAD_SET_STACK_GUARD (stack_chk_guard);
861 #else
862 __stack_chk_guard = stack_chk_guard;
863 #endif
865 /* Set up the pointer guard as well, if necessary. */
866 if (GLRO(dl_pointer_guard))
868 uintptr_t pointer_chk_guard = _dl_setup_pointer_guard (_dl_random,
869 stack_chk_guard);
870 #ifdef THREAD_SET_POINTER_GUARD
871 THREAD_SET_POINTER_GUARD (pointer_chk_guard);
872 #endif
873 __pointer_chk_guard_local = pointer_chk_guard;
876 /* We do not need the _dl_random value anymore. The less
877 information we leave behind, the better, so clear the
878 variable. */
879 _dl_random = NULL;
883 /* The library search path. */
884 static const char *library_path attribute_relro;
885 /* The list preloaded objects. */
886 static const char *preloadlist attribute_relro;
887 /* Nonzero if information about versions has to be printed. */
888 static int version_info attribute_relro;
890 static void
891 dl_main (const ElfW(Phdr) *phdr,
892 ElfW(Word) phnum,
893 ElfW(Addr) *user_entry,
894 ElfW(auxv_t) *auxv)
896 const ElfW(Phdr) *ph;
897 enum mode mode;
898 struct link_map *main_map;
899 size_t file_size;
900 char *file;
901 bool has_interp = false;
902 unsigned int i;
903 bool prelinked = false;
904 bool rtld_is_main = false;
905 #ifndef HP_TIMING_NONAVAIL
906 hp_timing_t start;
907 hp_timing_t stop;
908 hp_timing_t diff;
909 #endif
910 void *tcbp = NULL;
912 #ifdef _LIBC_REENTRANT
913 /* Explicit initialization since the reloc would just be more work. */
914 GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
915 #endif
917 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
919 #if defined SHARED && defined _LIBC_REENTRANT \
920 && defined __rtld_lock_default_lock_recursive
921 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
922 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
923 #endif
925 /* The explicit initialization here is cheaper than processing the reloc
926 in the _rtld_local definition's initializer. */
927 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
929 /* Process the environment variable which control the behaviour. */
930 process_envvars (&mode);
932 #ifndef HAVE_INLINED_SYSCALLS
933 /* Set up a flag which tells we are just starting. */
934 INTUSE(_dl_starting_up) = 1;
935 #endif
937 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
939 /* Ho ho. We are not the program interpreter! We are the program
940 itself! This means someone ran ld.so as a command. Well, that
941 might be convenient to do sometimes. We support it by
942 interpreting the args like this:
944 ld.so PROGRAM ARGS...
946 The first argument is the name of a file containing an ELF
947 executable we will load and run with the following arguments.
948 To simplify life here, PROGRAM is searched for using the
949 normal rules for shared objects, rather than $PATH or anything
950 like that. We just load it and use its entry point; we don't
951 pay attention to its PT_INTERP command (we are the interpreter
952 ourselves). This is an easy way to test a new ld.so before
953 installing it. */
954 rtld_is_main = true;
956 /* Note the place where the dynamic linker actually came from. */
957 GL(dl_rtld_map).l_name = rtld_progname;
959 while (_dl_argc > 1)
960 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
962 mode = list;
963 GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
965 ++_dl_skip_args;
966 --_dl_argc;
967 ++INTUSE(_dl_argv);
969 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
971 mode = verify;
973 ++_dl_skip_args;
974 --_dl_argc;
975 ++INTUSE(_dl_argv);
977 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
978 && _dl_argc > 2)
980 library_path = 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], "--inhibit-rpath")
987 && _dl_argc > 2)
989 GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
991 _dl_skip_args += 2;
992 _dl_argc -= 2;
993 INTUSE(_dl_argv) += 2;
995 else if (! strcmp (INTUSE(_dl_argv)[1], "--audit") && _dl_argc > 2)
997 process_dl_audit (INTUSE(_dl_argv)[2]);
999 _dl_skip_args += 2;
1000 _dl_argc -= 2;
1001 INTUSE(_dl_argv) += 2;
1003 else
1004 break;
1006 /* If we have no further argument the program was called incorrectly.
1007 Grant the user some education. */
1008 if (_dl_argc < 2)
1009 _dl_fatal_printf ("\
1010 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
1011 You have invoked `ld.so', the helper program for shared library executables.\n\
1012 This program usually lives in the file `/lib/ld.so', and special directives\n\
1013 in executable files using ELF shared libraries tell the system's program\n\
1014 loader to load the helper program from this file. This helper program loads\n\
1015 the shared libraries needed by the program executable, prepares the program\n\
1016 to run, and runs it. You may invoke this helper program directly from the\n\
1017 command line to load and run an ELF executable file; this is like executing\n\
1018 that file itself, but always uses this helper program from the file you\n\
1019 specified, instead of the helper program file specified in the executable\n\
1020 file you run. This is mostly of use for maintainers to test new versions\n\
1021 of this helper program; chances are you did not intend to run this program.\n\
1023 --list list all dependencies and how they are resolved\n\
1024 --verify verify that given object really is a dynamically linked\n\
1025 object we can handle\n\
1026 --library-path PATH use given PATH instead of content of the environment\n\
1027 variable LD_LIBRARY_PATH\n\
1028 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
1029 in LIST\n\
1030 --audit LIST use objects named in LIST as auditors\n");
1032 ++_dl_skip_args;
1033 --_dl_argc;
1034 ++INTUSE(_dl_argv);
1036 /* The initialization of _dl_stack_flags done below assumes the
1037 executable's PT_GNU_STACK may have been honored by the kernel, and
1038 so a PT_GNU_STACK with PF_X set means the stack started out with
1039 execute permission. However, this is not really true if the
1040 dynamic linker is the executable the kernel loaded. For this
1041 case, we must reinitialize _dl_stack_flags to match the dynamic
1042 linker itself. If the dynamic linker was built with a
1043 PT_GNU_STACK, then the kernel may have loaded us with a
1044 nonexecutable stack that we will have to make executable when we
1045 load the program below unless it has a PT_GNU_STACK indicating
1046 nonexecutable stack is ok. */
1048 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1049 if (ph->p_type == PT_GNU_STACK)
1051 GL(dl_stack_flags) = ph->p_flags;
1052 break;
1055 if (__builtin_expect (mode, normal) == verify)
1057 const char *objname;
1058 const char *err_str = NULL;
1059 struct map_args args;
1060 bool malloced;
1062 args.str = rtld_progname;
1063 args.loader = NULL;
1064 args.mode = __RTLD_OPENEXEC;
1065 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
1066 &args);
1067 if (__builtin_expect (err_str != NULL, 0))
1068 /* We don't free the returned string, the programs stops
1069 anyway. */
1070 _exit (EXIT_FAILURE);
1072 else
1074 HP_TIMING_NOW (start);
1075 _dl_map_object (NULL, rtld_progname, lt_library, 0,
1076 __RTLD_OPENEXEC, LM_ID_BASE);
1077 HP_TIMING_NOW (stop);
1079 HP_TIMING_DIFF (load_time, start, stop);
1082 /* Now the map for the main executable is available. */
1083 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1085 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1086 && main_map->l_info[DT_SONAME] != NULL
1087 && strcmp ((const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1088 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val,
1089 (const char *) D_PTR (main_map, l_info[DT_STRTAB])
1090 + main_map->l_info[DT_SONAME]->d_un.d_val) == 0)
1091 _dl_fatal_printf ("loader cannot load itself\n");
1093 phdr = main_map->l_phdr;
1094 phnum = main_map->l_phnum;
1095 /* We overwrite here a pointer to a malloc()ed string. But since
1096 the malloc() implementation used at this point is the dummy
1097 implementations which has no real free() function it does not
1098 makes sense to free the old string first. */
1099 main_map->l_name = (char *) "";
1100 *user_entry = main_map->l_entry;
1102 #ifdef HAVE_AUX_VECTOR
1103 /* Adjust the on-stack auxiliary vector so that it looks like the
1104 binary was executed directly. */
1105 for (ElfW(auxv_t) *av = auxv; av->a_type != AT_NULL; av++)
1106 switch (av->a_type)
1108 case AT_PHDR:
1109 av->a_un.a_val = (uintptr_t) phdr;
1110 break;
1111 case AT_PHNUM:
1112 av->a_un.a_val = phnum;
1113 break;
1114 case AT_ENTRY:
1115 av->a_un.a_val = *user_entry;
1116 break;
1118 #endif
1120 else
1122 /* Create a link_map for the executable itself.
1123 This will be what dlopen on "" returns. */
1124 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1125 __RTLD_OPENEXEC, LM_ID_BASE);
1126 assert (main_map != NULL);
1127 main_map->l_phdr = phdr;
1128 main_map->l_phnum = phnum;
1129 main_map->l_entry = *user_entry;
1131 /* Even though the link map is not yet fully initialized we can add
1132 it to the map list since there are no possible users running yet. */
1133 _dl_add_to_namespace_list (main_map, LM_ID_BASE);
1134 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
1136 /* At this point we are in a bit of trouble. We would have to
1137 fill in the values for l_dev and l_ino. But in general we
1138 do not know where the file is. We also do not handle AT_EXECFD
1139 even if it would be passed up.
1141 We leave the values here defined to 0. This is normally no
1142 problem as the program code itself is normally no shared
1143 object and therefore cannot be loaded dynamically. Nothing
1144 prevent the use of dynamic binaries and in these situations
1145 we might get problems. We might not be able to find out
1146 whether the object is already loaded. But since there is no
1147 easy way out and because the dynamic binary must also not
1148 have an SONAME we ignore this program for now. If it becomes
1149 a problem we can force people using SONAMEs. */
1151 /* We delay initializing the path structure until we got the dynamic
1152 information for the program. */
1155 main_map->l_map_end = 0;
1156 main_map->l_text_end = 0;
1157 /* Perhaps the executable has no PT_LOAD header entries at all. */
1158 main_map->l_map_start = ~0;
1159 /* And it was opened directly. */
1160 ++main_map->l_direct_opencount;
1162 /* Scan the program header table for the dynamic section. */
1163 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1164 switch (ph->p_type)
1166 case PT_PHDR:
1167 /* Find out the load address. */
1168 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1169 break;
1170 case PT_DYNAMIC:
1171 /* This tells us where to find the dynamic section,
1172 which tells us everything we need to do. */
1173 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
1174 break;
1175 case PT_INTERP:
1176 /* This "interpreter segment" was used by the program loader to
1177 find the program interpreter, which is this program itself, the
1178 dynamic linker. We note what name finds us, so that a future
1179 dlopen call or DT_NEEDED entry, for something that wants to link
1180 against the dynamic linker as a shared library, will know that
1181 the shared object is already loaded. */
1182 _dl_rtld_libname.name = ((const char *) main_map->l_addr
1183 + ph->p_vaddr);
1184 /* _dl_rtld_libname.next = NULL; Already zero. */
1185 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1187 /* Ordinarilly, we would get additional names for the loader from
1188 our DT_SONAME. This can't happen if we were actually linked as
1189 a static executable (detect this case when we have no DYNAMIC).
1190 If so, assume the filename component of the interpreter path to
1191 be our SONAME, and add it to our name list. */
1192 if (GL(dl_rtld_map).l_ld == NULL)
1194 const char *p = NULL;
1195 const char *cp = _dl_rtld_libname.name;
1197 /* Find the filename part of the path. */
1198 while (*cp != '\0')
1199 if (*cp++ == '/')
1200 p = cp;
1202 if (p != NULL)
1204 _dl_rtld_libname2.name = p;
1205 /* _dl_rtld_libname2.next = NULL; Already zero. */
1206 _dl_rtld_libname.next = &_dl_rtld_libname2;
1210 has_interp = true;
1211 break;
1212 case PT_LOAD:
1214 ElfW(Addr) mapstart;
1215 ElfW(Addr) allocend;
1217 /* Remember where the main program starts in memory. */
1218 mapstart = (main_map->l_addr
1219 + (ph->p_vaddr & ~(GLRO(dl_pagesize) - 1)));
1220 if (main_map->l_map_start > mapstart)
1221 main_map->l_map_start = mapstart;
1223 /* Also where it ends. */
1224 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1225 if (main_map->l_map_end < allocend)
1226 main_map->l_map_end = allocend;
1227 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1228 main_map->l_text_end = allocend;
1230 break;
1232 case PT_TLS:
1233 if (ph->p_memsz > 0)
1235 /* Note that in the case the dynamic linker we duplicate work
1236 here since we read the PT_TLS entry already in
1237 _dl_start_final. But the result is repeatable so do not
1238 check for this special but unimportant case. */
1239 main_map->l_tls_blocksize = ph->p_memsz;
1240 main_map->l_tls_align = ph->p_align;
1241 if (ph->p_align == 0)
1242 main_map->l_tls_firstbyte_offset = 0;
1243 else
1244 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1245 & (ph->p_align - 1));
1246 main_map->l_tls_initimage_size = ph->p_filesz;
1247 main_map->l_tls_initimage = (void *) ph->p_vaddr;
1249 /* This image gets the ID one. */
1250 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1252 break;
1254 case PT_GNU_STACK:
1255 GL(dl_stack_flags) = ph->p_flags;
1256 break;
1258 case PT_GNU_RELRO:
1259 main_map->l_relro_addr = ph->p_vaddr;
1260 main_map->l_relro_size = ph->p_memsz;
1261 break;
1264 /* Adjust the address of the TLS initialization image in case
1265 the executable is actually an ET_DYN object. */
1266 if (main_map->l_tls_initimage != NULL)
1267 main_map->l_tls_initimage
1268 = (char *) main_map->l_tls_initimage + main_map->l_addr;
1269 if (! main_map->l_map_end)
1270 main_map->l_map_end = ~0;
1271 if (! main_map->l_text_end)
1272 main_map->l_text_end = ~0;
1273 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1275 /* We were invoked directly, so the program might not have a
1276 PT_INTERP. */
1277 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1278 /* _dl_rtld_libname.next = NULL; Already zero. */
1279 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1281 else
1282 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1284 /* If the current libname is different from the SONAME, add the
1285 latter as well. */
1286 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1287 && strcmp (GL(dl_rtld_map).l_libname->name,
1288 (const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1289 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1291 static struct libname_list newname;
1292 newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1293 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1294 newname.next = NULL;
1295 newname.dont_free = 1;
1297 assert (GL(dl_rtld_map).l_libname->next == NULL);
1298 GL(dl_rtld_map).l_libname->next = &newname;
1300 /* The ld.so must be relocated since otherwise loading audit modules
1301 will fail since they reuse the very same ld.so. */
1302 assert (GL(dl_rtld_map).l_relocated);
1304 if (! rtld_is_main)
1306 /* Extract the contents of the dynamic section for easy access. */
1307 elf_get_dynamic_info (main_map, NULL);
1308 /* Set up our cache of pointers into the hash table. */
1309 _dl_setup_hash (main_map);
1312 if (__builtin_expect (mode, normal) == verify)
1314 /* We were called just to verify that this is a dynamic
1315 executable using us as the program interpreter. Exit with an
1316 error if we were not able to load the binary or no interpreter
1317 is specified (i.e., this is no dynamically linked binary. */
1318 if (main_map->l_ld == NULL)
1319 _exit (1);
1321 /* We allow here some platform specific code. */
1322 #ifdef DISTINGUISH_LIB_VERSIONS
1323 DISTINGUISH_LIB_VERSIONS;
1324 #endif
1325 _exit (has_interp ? 0 : 2);
1328 struct link_map **first_preload = &GL(dl_rtld_map).l_next;
1329 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1330 /* Set up the data structures for the system-supplied DSO early,
1331 so they can influence _dl_init_paths. */
1332 if (GLRO(dl_sysinfo_dso) != NULL)
1334 /* Do an abridged version of the work _dl_map_object_from_fd would do
1335 to map in the object. It's already mapped and prelinked (and
1336 better be, since it's read-only and so we couldn't relocate it).
1337 We just want our data structures to describe it as if we had just
1338 mapped and relocated it normally. */
1339 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL,
1340 0, LM_ID_BASE);
1341 if (__builtin_expect (l != NULL, 1))
1343 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
1345 l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1346 + GLRO(dl_sysinfo_dso)->e_phoff);
1347 l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1348 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1350 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1351 if (ph->p_type == PT_DYNAMIC)
1353 l->l_ld = (void *) ph->p_vaddr;
1354 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1356 else if (ph->p_type == PT_LOAD)
1358 if (! l->l_addr)
1359 l->l_addr = ph->p_vaddr;
1360 if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1361 l->l_map_end = ph->p_vaddr + ph->p_memsz;
1362 if ((ph->p_flags & PF_X)
1363 && ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1364 l->l_text_end = ph->p_vaddr + ph->p_memsz;
1366 else
1367 /* There must be no TLS segment. */
1368 assert (ph->p_type != PT_TLS);
1370 l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1371 l->l_addr = l->l_map_start - l->l_addr;
1372 l->l_map_end += l->l_addr;
1373 l->l_text_end += l->l_addr;
1374 l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1375 elf_get_dynamic_info (l, dyn_temp);
1376 _dl_setup_hash (l);
1377 l->l_relocated = 1;
1379 /* Initialize l_local_scope to contain just this map. This allows
1380 the use of dl_lookup_symbol_x to resolve symbols within the vdso.
1381 So we create a single entry list pointing to l_real as its only
1382 element */
1383 l->l_local_scope[0]->r_nlist = 1;
1384 l->l_local_scope[0]->r_list = &l->l_real;
1386 /* Now that we have the info handy, use the DSO image's soname
1387 so this object can be looked up by name. Note that we do not
1388 set l_name here. That field gives the file name of the DSO,
1389 and this DSO is not associated with any file. */
1390 if (l->l_info[DT_SONAME] != NULL)
1392 /* Work around a kernel problem. The kernel cannot handle
1393 addresses in the vsyscall DSO pages in writev() calls. */
1394 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1395 + l->l_info[DT_SONAME]->d_un.d_val);
1396 size_t len = strlen (dsoname);
1397 char *copy = malloc (len);
1398 if (copy == NULL)
1399 _dl_fatal_printf ("out of memory\n");
1400 l->l_libname->name = l->l_name = memcpy (copy, dsoname, len);
1403 /* Add the vDSO to the object list. */
1404 _dl_add_to_namespace_list (l, LM_ID_BASE);
1406 /* Rearrange the list so this DSO appears after rtld_map. */
1407 assert (l->l_next == NULL);
1408 assert (l->l_prev == main_map);
1409 GL(dl_rtld_map).l_next = l;
1410 l->l_prev = &GL(dl_rtld_map);
1411 first_preload = &l->l_next;
1413 /* We have a prelinked DSO preloaded by the system. */
1414 GLRO(dl_sysinfo_map) = l;
1415 # ifdef NEED_DL_SYSINFO
1416 if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1417 GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1418 # endif
1421 #endif
1423 #ifdef DL_SYSDEP_OSCHECK
1424 DL_SYSDEP_OSCHECK (dl_fatal);
1425 #endif
1427 /* Initialize the data structures for the search paths for shared
1428 objects. */
1429 _dl_init_paths (library_path);
1431 /* Initialize _r_debug. */
1432 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1433 LM_ID_BASE);
1434 r->r_state = RT_CONSISTENT;
1436 /* Put the link_map for ourselves on the chain so it can be found by
1437 name. Note that at this point the global chain of link maps contains
1438 exactly one element, which is pointed to by dl_loaded. */
1439 if (! GL(dl_rtld_map).l_name)
1440 /* If not invoked directly, the dynamic linker shared object file was
1441 found by the PT_INTERP name. */
1442 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1443 GL(dl_rtld_map).l_type = lt_library;
1444 main_map->l_next = &GL(dl_rtld_map);
1445 GL(dl_rtld_map).l_prev = main_map;
1446 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1447 ++GL(dl_load_adds);
1449 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1450 to not using bias for non-prelinked PIEs and libraries
1451 and using it for executables or prelinked PIEs or libraries. */
1452 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1453 GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
1455 /* Set up the program header information for the dynamic linker
1456 itself. It is needed in the dl_iterate_phdr() callbacks. */
1457 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1458 ElfW(Phdr) *rtld_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1459 + rtld_ehdr->e_phoff);
1460 GL(dl_rtld_map).l_phdr = rtld_phdr;
1461 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1464 /* PT_GNU_RELRO is usually the last phdr. */
1465 size_t cnt = rtld_ehdr->e_phnum;
1466 while (cnt-- > 0)
1467 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1469 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1470 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1471 break;
1474 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1475 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1476 /* Assign a module ID. Do this before loading any audit modules. */
1477 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1479 /* If we have auditing DSOs to load, do it now. */
1480 if (__builtin_expect (audit_list != NULL, 0))
1482 /* Iterate over all entries in the list. The order is important. */
1483 struct audit_ifaces *last_audit = NULL;
1484 struct audit_list *al = audit_list->next;
1486 /* Since we start using the auditing DSOs right away we need to
1487 initialize the data structures now. */
1488 tcbp = init_tls ();
1490 /* Initialize security features. We need to do it this early
1491 since otherwise the constructors of the audit libraries will
1492 use different values (especially the pointer guard) and will
1493 fail later on. */
1494 security_init ();
1498 int tls_idx = GL(dl_tls_max_dtv_idx);
1500 /* Now it is time to determine the layout of the static TLS
1501 block and allocate it for the initial thread. Note that we
1502 always allocate the static block, we never defer it even if
1503 no DF_STATIC_TLS bit is set. The reason is that we know
1504 glibc will use the static model. */
1505 struct dlmopen_args dlmargs;
1506 dlmargs.fname = al->name;
1507 dlmargs.map = NULL;
1509 const char *objname;
1510 const char *err_str = NULL;
1511 bool malloced;
1512 (void) _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit,
1513 &dlmargs);
1514 if (__builtin_expect (err_str != NULL, 0))
1516 not_loaded:
1517 _dl_error_printf ("\
1518 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
1519 al->name, err_str);
1520 if (malloced)
1521 free ((char *) err_str);
1523 else
1525 struct lookup_args largs;
1526 largs.name = "la_version";
1527 largs.map = dlmargs.map;
1529 /* Check whether the interface version matches. */
1530 (void) _dl_catch_error (&objname, &err_str, &malloced,
1531 lookup_doit, &largs);
1533 unsigned int (*laversion) (unsigned int);
1534 unsigned int lav;
1535 if (err_str == NULL
1536 && (laversion = largs.result) != NULL
1537 && (lav = laversion (LAV_CURRENT)) > 0
1538 && lav <= LAV_CURRENT)
1540 /* Allocate structure for the callback function pointers.
1541 This call can never fail. */
1542 union
1544 struct audit_ifaces ifaces;
1545 #define naudit_ifaces 8
1546 void (*fptr[naudit_ifaces]) (void);
1547 } *newp = malloc (sizeof (*newp));
1549 /* Names of the auditing interfaces. All in one
1550 long string. */
1551 static const char audit_iface_names[] =
1552 "la_activity\0"
1553 "la_objsearch\0"
1554 "la_objopen\0"
1555 "la_preinit\0"
1556 #if __ELF_NATIVE_CLASS == 32
1557 "la_symbind32\0"
1558 #elif __ELF_NATIVE_CLASS == 64
1559 "la_symbind64\0"
1560 #else
1561 # error "__ELF_NATIVE_CLASS must be defined"
1562 #endif
1563 #define STRING(s) __STRING (s)
1564 "la_" STRING (ARCH_LA_PLTENTER) "\0"
1565 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
1566 "la_objclose\0";
1567 unsigned int cnt = 0;
1568 const char *cp = audit_iface_names;
1571 largs.name = cp;
1572 (void) _dl_catch_error (&objname, &err_str, &malloced,
1573 lookup_doit, &largs);
1575 /* Store the pointer. */
1576 if (err_str == NULL && largs.result != NULL)
1578 newp->fptr[cnt] = largs.result;
1580 /* The dynamic linker link map is statically
1581 allocated, initialize the data now. */
1582 GL(dl_rtld_map).l_audit[cnt].cookie
1583 = (intptr_t) &GL(dl_rtld_map);
1585 else
1586 newp->fptr[cnt] = NULL;
1587 ++cnt;
1589 cp = (char *) rawmemchr (cp, '\0') + 1;
1591 while (*cp != '\0');
1592 assert (cnt == naudit_ifaces);
1594 /* Now append the new auditing interface to the list. */
1595 newp->ifaces.next = NULL;
1596 if (last_audit == NULL)
1597 last_audit = GLRO(dl_audit) = &newp->ifaces;
1598 else
1599 last_audit = last_audit->next = &newp->ifaces;
1600 ++GLRO(dl_naudit);
1602 /* Mark the DSO as being used for auditing. */
1603 dlmargs.map->l_auditing = 1;
1605 else
1607 /* We cannot use the DSO, it does not have the
1608 appropriate interfaces or it expects something
1609 more recent. */
1610 #ifndef NDEBUG
1611 Lmid_t ns = dlmargs.map->l_ns;
1612 #endif
1613 _dl_close (dlmargs.map);
1615 /* Make sure the namespace has been cleared entirely. */
1616 assert (GL(dl_ns)[ns]._ns_loaded == NULL);
1617 assert (GL(dl_ns)[ns]._ns_nloaded == 0);
1619 GL(dl_tls_max_dtv_idx) = tls_idx;
1620 goto not_loaded;
1624 al = al->next;
1626 while (al != audit_list->next);
1628 /* If we have any auditing modules, announce that we already
1629 have two objects loaded. */
1630 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1632 struct link_map *ls[2] = { main_map, &GL(dl_rtld_map) };
1634 for (unsigned int outer = 0; outer < 2; ++outer)
1636 struct audit_ifaces *afct = GLRO(dl_audit);
1637 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1639 if (afct->objopen != NULL)
1641 ls[outer]->l_audit[cnt].bindflags
1642 = afct->objopen (ls[outer], LM_ID_BASE,
1643 &ls[outer]->l_audit[cnt].cookie);
1645 ls[outer]->l_audit_any_plt
1646 |= ls[outer]->l_audit[cnt].bindflags != 0;
1649 afct = afct->next;
1655 /* Set up debugging before the debugger is notified for the first time. */
1656 #ifdef ELF_MACHINE_DEBUG_SETUP
1657 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1658 ELF_MACHINE_DEBUG_SETUP (main_map, r);
1659 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1660 #else
1661 if (main_map->l_info[DT_DEBUG] != NULL)
1662 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1663 with the run-time address of the r_debug structure */
1664 main_map->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1666 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1667 case you run gdb on the dynamic linker directly. */
1668 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1669 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1670 #endif
1672 /* We start adding objects. */
1673 r->r_state = RT_ADD;
1674 _dl_debug_state ();
1676 /* Auditing checkpoint: we are ready to signal that the initial map
1677 is being constructed. */
1678 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1680 struct audit_ifaces *afct = GLRO(dl_audit);
1681 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1683 if (afct->activity != NULL)
1684 afct->activity (&main_map->l_audit[cnt].cookie, LA_ACT_ADD);
1686 afct = afct->next;
1690 /* We have two ways to specify objects to preload: via environment
1691 variable and via the file /etc/ld.so.preload. The latter can also
1692 be used when security is enabled. */
1693 assert (*first_preload == NULL);
1694 struct link_map **preloads = NULL;
1695 unsigned int npreloads = 0;
1697 if (__builtin_expect (preloadlist != NULL, 0))
1699 /* The LD_PRELOAD environment variable gives list of libraries
1700 separated by white space or colons that are loaded before the
1701 executable's dependencies and prepended to the global scope
1702 list. If the binary is running setuid all elements
1703 containing a '/' are ignored since it is insecure. */
1704 char *list = strdupa (preloadlist);
1705 char *p;
1707 HP_TIMING_NOW (start);
1709 /* Prevent optimizing strsep. Speed is not important here. */
1710 while ((p = (strsep) (&list, " :")) != NULL)
1711 if (p[0] != '\0'
1712 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1713 || strchr (p, '/') == NULL))
1714 npreloads += do_preload (p, main_map, "LD_PRELOAD");
1716 HP_TIMING_NOW (stop);
1717 HP_TIMING_DIFF (diff, start, stop);
1718 HP_TIMING_ACCUM_NT (load_time, diff);
1721 /* There usually is no ld.so.preload file, it should only be used
1722 for emergencies and testing. So the open call etc should usually
1723 fail. Using access() on a non-existing file is faster than using
1724 open(). So we do this first. If it succeeds we do almost twice
1725 the work but this does not matter, since it is not for production
1726 use. */
1727 static const char preload_file[] = "/etc/ld.so.preload";
1728 if (__builtin_expect (__access (preload_file, R_OK) == 0, 0))
1730 /* Read the contents of the file. */
1731 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1732 PROT_READ | PROT_WRITE);
1733 if (__builtin_expect (file != MAP_FAILED, 0))
1735 /* Parse the file. It contains names of libraries to be loaded,
1736 separated by white spaces or `:'. It may also contain
1737 comments introduced by `#'. */
1738 char *problem;
1739 char *runp;
1740 size_t rest;
1742 /* Eliminate comments. */
1743 runp = file;
1744 rest = file_size;
1745 while (rest > 0)
1747 char *comment = memchr (runp, '#', rest);
1748 if (comment == NULL)
1749 break;
1751 rest -= comment - runp;
1753 *comment = ' ';
1754 while (--rest > 0 && *++comment != '\n');
1757 /* We have one problematic case: if we have a name at the end of
1758 the file without a trailing terminating characters, we cannot
1759 place the \0. Handle the case separately. */
1760 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1761 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1763 problem = &file[file_size];
1764 while (problem > file && problem[-1] != ' '
1765 && problem[-1] != '\t'
1766 && problem[-1] != '\n' && problem[-1] != ':')
1767 --problem;
1769 if (problem > file)
1770 problem[-1] = '\0';
1772 else
1774 problem = NULL;
1775 file[file_size - 1] = '\0';
1778 HP_TIMING_NOW (start);
1780 if (file != problem)
1782 char *p;
1783 runp = file;
1784 while ((p = strsep (&runp, ": \t\n")) != NULL)
1785 if (p[0] != '\0')
1786 npreloads += do_preload (p, main_map, preload_file);
1789 if (problem != NULL)
1791 char *p = strndupa (problem, file_size - (problem - file));
1793 npreloads += do_preload (p, main_map, preload_file);
1796 HP_TIMING_NOW (stop);
1797 HP_TIMING_DIFF (diff, start, stop);
1798 HP_TIMING_ACCUM_NT (load_time, diff);
1800 /* We don't need the file anymore. */
1801 __munmap (file, file_size);
1805 if (__builtin_expect (*first_preload != NULL, 0))
1807 /* Set up PRELOADS with a vector of the preloaded libraries. */
1808 struct link_map *l = *first_preload;
1809 preloads = __alloca (npreloads * sizeof preloads[0]);
1810 i = 0;
1813 preloads[i++] = l;
1814 l = l->l_next;
1815 } while (l);
1816 assert (i == npreloads);
1819 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1820 specified some libraries to load, these are inserted before the actual
1821 dependencies in the executable's searchlist for symbol resolution. */
1822 HP_TIMING_NOW (start);
1823 _dl_map_object_deps (main_map, preloads, npreloads, mode == trace, 0);
1824 HP_TIMING_NOW (stop);
1825 HP_TIMING_DIFF (diff, start, stop);
1826 HP_TIMING_ACCUM_NT (load_time, diff);
1828 /* Mark all objects as being in the global scope. */
1829 for (i = main_map->l_searchlist.r_nlist; i > 0; )
1830 main_map->l_searchlist.r_list[--i]->l_global = 1;
1832 /* Remove _dl_rtld_map from the chain. */
1833 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1834 if (GL(dl_rtld_map).l_next != NULL)
1835 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1837 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1838 if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1839 break;
1841 bool rtld_multiple_ref = false;
1842 if (__builtin_expect (i < main_map->l_searchlist.r_nlist, 1))
1844 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1845 put it back in the list of visible objects. We insert it into the
1846 chain in symbol search order because gdb uses the chain's order as
1847 its symbol search order. */
1848 rtld_multiple_ref = true;
1850 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1851 if (__builtin_expect (mode, normal) == normal)
1853 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1854 ? main_map->l_searchlist.r_list[i + 1]
1855 : NULL);
1856 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1857 if (GLRO(dl_sysinfo_map) != NULL
1858 && GL(dl_rtld_map).l_prev->l_next == GLRO(dl_sysinfo_map)
1859 && GL(dl_rtld_map).l_next != GLRO(dl_sysinfo_map))
1860 GL(dl_rtld_map).l_prev = GLRO(dl_sysinfo_map);
1861 #endif
1863 else
1864 /* In trace mode there might be an invisible object (which we
1865 could not find) after the previous one in the search list.
1866 In this case it doesn't matter much where we put the
1867 interpreter object, so we just initialize the list pointer so
1868 that the assertion below holds. */
1869 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1871 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1872 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1873 if (GL(dl_rtld_map).l_next != NULL)
1875 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1876 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1880 /* Now let us see whether all libraries are available in the
1881 versions we need. */
1883 struct version_check_args args;
1884 args.doexit = mode == normal;
1885 args.dotrace = mode == trace;
1886 _dl_receive_error (print_missing_version, version_check_doit, &args);
1889 /* We do not initialize any of the TLS functionality unless any of the
1890 initial modules uses TLS. This makes dynamic loading of modules with
1891 TLS impossible, but to support it requires either eagerly doing setup
1892 now or lazily doing it later. Doing it now makes us incompatible with
1893 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1894 used. Trying to do it lazily is too hairy to try when there could be
1895 multiple threads (from a non-TLS-using libpthread). */
1896 bool was_tls_init_tp_called = tls_init_tp_called;
1897 if (tcbp == NULL)
1898 tcbp = init_tls ();
1900 if (__builtin_expect (audit_list == NULL, 1))
1901 /* Initialize security features. But only if we have not done it
1902 earlier. */
1903 security_init ();
1905 if (__builtin_expect (mode, normal) != normal)
1907 /* We were run just to list the shared libraries. It is
1908 important that we do this before real relocation, because the
1909 functions we call below for output may no longer work properly
1910 after relocation. */
1911 struct link_map *l;
1913 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1915 struct r_scope_elem *scope = &main_map->l_searchlist;
1917 for (i = 0; i < scope->r_nlist; i++)
1919 l = scope->r_list [i];
1920 if (l->l_faked)
1922 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1923 continue;
1925 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1926 GLRO(dl_trace_prelink_map) = l;
1927 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1928 l->l_libname->name[0] ? l->l_libname->name
1929 : rtld_progname ?: "<main program>",
1930 l->l_name[0] ? l->l_name
1931 : rtld_progname ?: "<main program>",
1932 (int) sizeof l->l_map_start * 2,
1933 (size_t) l->l_map_start,
1934 (int) sizeof l->l_addr * 2,
1935 (size_t) l->l_addr);
1937 if (l->l_tls_modid)
1938 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1939 (int) sizeof l->l_tls_offset * 2,
1940 (size_t) l->l_tls_offset);
1941 else
1942 _dl_printf ("\n");
1945 else if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
1947 /* Look through the dependencies of the main executable
1948 and determine which of them is not actually
1949 required. */
1950 struct link_map *l = main_map;
1952 /* Relocate the main executable. */
1953 struct relocate_args args = { .l = l,
1954 .reloc_mode = ((GLRO(dl_lazy)
1955 ? RTLD_LAZY : 0)
1956 | __RTLD_NOIFUNC) };
1957 _dl_receive_error (print_unresolved, relocate_doit, &args);
1959 /* This loop depends on the dependencies of the executable to
1960 correspond in number and order to the DT_NEEDED entries. */
1961 ElfW(Dyn) *dyn = main_map->l_ld;
1962 bool first = true;
1963 while (dyn->d_tag != DT_NULL)
1965 if (dyn->d_tag == DT_NEEDED)
1967 l = l->l_next;
1969 if (!l->l_used)
1971 if (first)
1973 _dl_printf ("Unused direct dependencies:\n");
1974 first = false;
1977 _dl_printf ("\t%s\n", l->l_name);
1981 ++dyn;
1984 _exit (first != true);
1986 else if (! main_map->l_info[DT_NEEDED])
1987 _dl_printf ("\tstatically linked\n");
1988 else
1990 for (l = main_map->l_next; l; l = l->l_next)
1991 if (l->l_faked)
1992 /* The library was not found. */
1993 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1994 else if (strcmp (l->l_libname->name, l->l_name) == 0)
1995 _dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
1996 (int) sizeof l->l_map_start * 2,
1997 (size_t) l->l_map_start);
1998 else
1999 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
2000 l->l_name, (int) sizeof l->l_map_start * 2,
2001 (size_t) l->l_map_start);
2004 if (__builtin_expect (mode, trace) != trace)
2005 for (i = 1; i < (unsigned int) _dl_argc; ++i)
2007 const ElfW(Sym) *ref = NULL;
2008 ElfW(Addr) loadbase;
2009 lookup_t result;
2011 result = _dl_lookup_symbol_x (INTUSE(_dl_argv)[i], main_map,
2012 &ref, main_map->l_scope,
2013 NULL, ELF_RTYPE_CLASS_PLT,
2014 DL_LOOKUP_ADD_DEPENDENCY, NULL);
2016 loadbase = LOOKUP_VALUE_ADDRESS (result);
2018 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
2019 INTUSE(_dl_argv)[i],
2020 (int) sizeof ref->st_value * 2,
2021 (size_t) ref->st_value,
2022 (int) sizeof loadbase * 2, (size_t) loadbase);
2024 else
2026 /* If LD_WARN is set, warn about undefined symbols. */
2027 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
2029 /* We have to do symbol dependency testing. */
2030 struct relocate_args args;
2031 unsigned int i;
2033 args.reloc_mode = ((GLRO(dl_lazy) ? RTLD_LAZY : 0)
2034 | __RTLD_NOIFUNC);
2036 i = main_map->l_searchlist.r_nlist;
2037 while (i-- > 0)
2039 struct link_map *l = main_map->l_initfini[i];
2040 if (l != &GL(dl_rtld_map) && ! l->l_faked)
2042 args.l = l;
2043 _dl_receive_error (print_unresolved, relocate_doit,
2044 &args);
2048 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
2049 && rtld_multiple_ref)
2051 /* Mark the link map as not yet relocated again. */
2052 GL(dl_rtld_map).l_relocated = 0;
2053 _dl_relocate_object (&GL(dl_rtld_map),
2054 main_map->l_scope, __RTLD_NOIFUNC, 0);
2057 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
2058 if (version_info)
2060 /* Print more information. This means here, print information
2061 about the versions needed. */
2062 int first = 1;
2063 struct link_map *map;
2065 for (map = main_map; map != NULL; map = map->l_next)
2067 const char *strtab;
2068 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
2069 ElfW(Verneed) *ent;
2071 if (dyn == NULL)
2072 continue;
2074 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
2075 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
2077 if (first)
2079 _dl_printf ("\n\tVersion information:\n");
2080 first = 0;
2083 _dl_printf ("\t%s:\n",
2084 map->l_name[0] ? map->l_name : rtld_progname);
2086 while (1)
2088 ElfW(Vernaux) *aux;
2089 struct link_map *needed;
2091 needed = find_needed (strtab + ent->vn_file);
2092 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
2094 while (1)
2096 const char *fname = NULL;
2098 if (needed != NULL
2099 && match_version (strtab + aux->vna_name,
2100 needed))
2101 fname = needed->l_name;
2103 _dl_printf ("\t\t%s (%s) %s=> %s\n",
2104 strtab + ent->vn_file,
2105 strtab + aux->vna_name,
2106 aux->vna_flags & VER_FLG_WEAK
2107 ? "[WEAK] " : "",
2108 fname ?: "not found");
2110 if (aux->vna_next == 0)
2111 /* No more symbols. */
2112 break;
2114 /* Next symbol. */
2115 aux = (ElfW(Vernaux) *) ((char *) aux
2116 + aux->vna_next);
2119 if (ent->vn_next == 0)
2120 /* No more dependencies. */
2121 break;
2123 /* Next dependency. */
2124 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
2130 _exit (0);
2133 if (main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]
2134 && ! __builtin_expect (GLRO(dl_profile) != NULL, 0)
2135 && ! __builtin_expect (GLRO(dl_dynamic_weak), 0))
2137 ElfW(Lib) *liblist, *liblistend;
2138 struct link_map **r_list, **r_listend, *l;
2139 const char *strtab = (const void *) D_PTR (main_map, l_info[DT_STRTAB]);
2141 assert (main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
2142 liblist = (ElfW(Lib) *)
2143 main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
2144 liblistend = (ElfW(Lib) *)
2145 ((char *) liblist +
2146 main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
2147 r_list = main_map->l_searchlist.r_list;
2148 r_listend = r_list + main_map->l_searchlist.r_nlist;
2150 for (; r_list < r_listend && liblist < liblistend; r_list++)
2152 l = *r_list;
2154 if (l == main_map)
2155 continue;
2157 /* If the library is not mapped where it should, fail. */
2158 if (l->l_addr)
2159 break;
2161 /* Next, check if checksum matches. */
2162 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
2163 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
2164 != liblist->l_checksum)
2165 break;
2167 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
2168 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
2169 != liblist->l_time_stamp)
2170 break;
2172 if (! _dl_name_match_p (strtab + liblist->l_name, l))
2173 break;
2175 ++liblist;
2179 if (r_list == r_listend && liblist == liblistend)
2180 prelinked = true;
2182 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
2183 _dl_debug_printf ("\nprelink checking: %s\n",
2184 prelinked ? "ok" : "failed");
2188 /* Now set up the variable which helps the assembler startup code. */
2189 GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
2191 /* Save the information about the original global scope list since
2192 we need it in the memory handling later. */
2193 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
2195 /* Remember the last search directory added at startup, now that
2196 malloc will no longer be the one from dl-minimal.c. */
2197 GLRO(dl_init_all_dirs) = GL(dl_all_dirs);
2199 /* Print scope information. */
2200 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_SCOPES, 0))
2202 _dl_debug_printf ("\nInitial object scopes\n");
2204 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2205 _dl_show_scope (l, 0);
2208 if (prelinked)
2210 if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
2212 ElfW(Rela) *conflict, *conflictend;
2213 #ifndef HP_TIMING_NONAVAIL
2214 hp_timing_t start;
2215 hp_timing_t stop;
2216 #endif
2218 HP_TIMING_NOW (start);
2219 assert (main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
2220 conflict = (ElfW(Rela) *)
2221 main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
2222 conflictend = (ElfW(Rela) *)
2223 ((char *) conflict
2224 + main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
2225 _dl_resolve_conflicts (main_map, conflict, conflictend);
2226 HP_TIMING_NOW (stop);
2227 HP_TIMING_DIFF (relocate_time, start, stop);
2231 /* Mark all the objects so we know they have been already relocated. */
2232 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2234 l->l_relocated = 1;
2235 if (l->l_relro_size)
2236 _dl_protect_relro (l);
2238 /* Add object to slot information data if necessasy. */
2239 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2240 _dl_add_to_slotinfo (l);
2243 else
2245 /* Now we have all the objects loaded. Relocate them all except for
2246 the dynamic linker itself. We do this in reverse order so that copy
2247 relocs of earlier objects overwrite the data written by later
2248 objects. We do not re-relocate the dynamic linker itself in this
2249 loop because that could result in the GOT entries for functions we
2250 call being changed, and that would break us. It is safe to relocate
2251 the dynamic linker out of order because it has no copy relocs (we
2252 know that because it is self-contained). */
2254 int consider_profiling = GLRO(dl_profile) != NULL;
2255 #ifndef HP_TIMING_NONAVAIL
2256 hp_timing_t start;
2257 hp_timing_t stop;
2258 #endif
2260 /* If we are profiling we also must do lazy reloaction. */
2261 GLRO(dl_lazy) |= consider_profiling;
2263 HP_TIMING_NOW (start);
2264 unsigned i = main_map->l_searchlist.r_nlist;
2265 while (i-- > 0)
2267 struct link_map *l = main_map->l_initfini[i];
2269 /* While we are at it, help the memory handling a bit. We have to
2270 mark some data structures as allocated with the fake malloc()
2271 implementation in ld.so. */
2272 struct libname_list *lnp = l->l_libname->next;
2274 while (__builtin_expect (lnp != NULL, 0))
2276 lnp->dont_free = 1;
2277 lnp = lnp->next;
2280 if (l != &GL(dl_rtld_map))
2281 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy) ? RTLD_LAZY : 0,
2282 consider_profiling);
2284 /* Add object to slot information data if necessasy. */
2285 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2286 _dl_add_to_slotinfo (l);
2288 HP_TIMING_NOW (stop);
2290 HP_TIMING_DIFF (relocate_time, start, stop);
2292 /* Now enable profiling if needed. Like the previous call,
2293 this has to go here because the calls it makes should use the
2294 rtld versions of the functions (particularly calloc()), but it
2295 needs to have _dl_profile_map set up by the relocator. */
2296 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
2297 /* We must prepare the profiling. */
2298 _dl_start_profile ();
2301 #ifndef NONTLS_INIT_TP
2302 # define NONTLS_INIT_TP do { } while (0)
2303 #endif
2305 if (!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2306 ++GL(dl_tls_generation);
2308 /* Now that we have completed relocation, the initializer data
2309 for the TLS blocks has its final values and we can copy them
2310 into the main thread's TLS area, which we allocated above. */
2311 _dl_allocate_tls_init (tcbp);
2313 /* And finally install it for the main thread. If ld.so itself uses
2314 TLS we know the thread pointer was initialized earlier. */
2315 if (! tls_init_tp_called)
2317 const char *lossage
2318 #ifdef USE___THREAD
2319 = TLS_INIT_TP (tcbp, USE___THREAD);
2320 #else
2321 = TLS_INIT_TP (tcbp, 0);
2322 #endif
2323 if (__builtin_expect (lossage != NULL, 0))
2324 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2325 lossage);
2328 /* Make sure no new search directories have been added. */
2329 assert (GLRO(dl_init_all_dirs) == GL(dl_all_dirs));
2331 if (! prelinked && rtld_multiple_ref)
2333 /* There was an explicit ref to the dynamic linker as a shared lib.
2334 Re-relocate ourselves with user-controlled symbol definitions.
2336 We must do this after TLS initialization in case after this
2337 re-relocation, we might call a user-supplied function
2338 (e.g. calloc from _dl_relocate_object) that uses TLS data. */
2340 #ifndef HP_TIMING_NONAVAIL
2341 hp_timing_t start;
2342 hp_timing_t stop;
2343 hp_timing_t add;
2344 #endif
2346 HP_TIMING_NOW (start);
2347 /* Mark the link map as not yet relocated again. */
2348 GL(dl_rtld_map).l_relocated = 0;
2349 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2350 HP_TIMING_NOW (stop);
2351 HP_TIMING_DIFF (add, start, stop);
2352 HP_TIMING_ACCUM_NT (relocate_time, add);
2355 /* Do any necessary cleanups for the startup OS interface code.
2356 We do these now so that no calls are made after rtld re-relocation
2357 which might be resolved to different functions than we expect.
2358 We cannot do this before relocating the other objects because
2359 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2360 _dl_sysdep_start_cleanup ();
2362 #ifdef SHARED
2363 /* Auditing checkpoint: we have added all objects. */
2364 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
2366 struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2367 /* Do not call the functions for any auditing object. */
2368 if (head->l_auditing == 0)
2370 struct audit_ifaces *afct = GLRO(dl_audit);
2371 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2373 if (afct->activity != NULL)
2374 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
2376 afct = afct->next;
2380 #endif
2382 /* Notify the debugger all new objects are now ready to go. We must re-get
2383 the address since by now the variable might be in another object. */
2384 r = _dl_debug_initialize (0, LM_ID_BASE);
2385 r->r_state = RT_CONSISTENT;
2386 _dl_debug_state ();
2388 #ifndef MAP_COPY
2389 /* We must munmap() the cache file. */
2390 _dl_unload_cache ();
2391 #endif
2393 /* Once we return, _dl_sysdep_start will invoke
2394 the DT_INIT functions and then *USER_ENTRY. */
2397 /* This is a little helper function for resolving symbols while
2398 tracing the binary. */
2399 static void
2400 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2401 const char *errstring)
2403 if (objname[0] == '\0')
2404 objname = rtld_progname ?: "<main program>";
2405 _dl_error_printf ("%s (%s)\n", errstring, objname);
2408 /* This is a little helper function for resolving symbols while
2409 tracing the binary. */
2410 static void
2411 print_missing_version (int errcode __attribute__ ((unused)),
2412 const char *objname, const char *errstring)
2414 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
2415 objname, errstring);
2418 /* Nonzero if any of the debugging options is enabled. */
2419 static int any_debug attribute_relro;
2421 /* Process the string given as the parameter which explains which debugging
2422 options are enabled. */
2423 static void
2424 process_dl_debug (const char *dl_debug)
2426 /* When adding new entries make sure that the maximal length of a name
2427 is correctly handled in the LD_DEBUG_HELP code below. */
2428 static const struct
2430 unsigned char len;
2431 const char name[10];
2432 const char helptext[41];
2433 unsigned short int mask;
2434 } debopts[] =
2436 #define LEN_AND_STR(str) sizeof (str) - 1, str
2437 { LEN_AND_STR ("libs"), "display library search paths",
2438 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2439 { LEN_AND_STR ("reloc"), "display relocation processing",
2440 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2441 { LEN_AND_STR ("files"), "display progress for input file",
2442 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2443 { LEN_AND_STR ("symbols"), "display symbol table processing",
2444 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2445 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2446 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2447 { LEN_AND_STR ("versions"), "display version dependencies",
2448 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2449 { LEN_AND_STR ("scopes"), "display scope information",
2450 DL_DEBUG_SCOPES },
2451 { LEN_AND_STR ("all"), "all previous options combined",
2452 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2453 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS
2454 | DL_DEBUG_SCOPES },
2455 { LEN_AND_STR ("statistics"), "display relocation statistics",
2456 DL_DEBUG_STATISTICS },
2457 { LEN_AND_STR ("unused"), "determined unused DSOs",
2458 DL_DEBUG_UNUSED },
2459 { LEN_AND_STR ("help"), "display this help message and exit",
2460 DL_DEBUG_HELP },
2462 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2464 /* Skip separating white spaces and commas. */
2465 while (*dl_debug != '\0')
2467 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2469 size_t cnt;
2470 size_t len = 1;
2472 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2473 && dl_debug[len] != ',' && dl_debug[len] != ':')
2474 ++len;
2476 for (cnt = 0; cnt < ndebopts; ++cnt)
2477 if (debopts[cnt].len == len
2478 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
2480 GLRO(dl_debug_mask) |= debopts[cnt].mask;
2481 any_debug = 1;
2482 break;
2485 if (cnt == ndebopts)
2487 /* Display a warning and skip everything until next
2488 separator. */
2489 char *copy = strndupa (dl_debug, len);
2490 _dl_error_printf ("\
2491 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2494 dl_debug += len;
2495 continue;
2498 ++dl_debug;
2501 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
2503 size_t cnt;
2505 _dl_printf ("\
2506 Valid options for the LD_DEBUG environment variable are:\n\n");
2508 for (cnt = 0; cnt < ndebopts; ++cnt)
2509 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2510 " " + debopts[cnt].len - 3,
2511 debopts[cnt].helptext);
2513 _dl_printf ("\n\
2514 To direct the debugging output into a file instead of standard output\n\
2515 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2516 _exit (0);
2520 static void
2521 process_dl_audit (char *str)
2523 /* The parameter is a colon separated list of DSO names. */
2524 char *p;
2526 while ((p = (strsep) (&str, ":")) != NULL)
2527 if (p[0] != '\0'
2528 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
2529 || strchr (p, '/') == NULL))
2531 /* This is using the local malloc, not the system malloc. The
2532 memory can never be freed. */
2533 struct audit_list *newp = malloc (sizeof (*newp));
2534 newp->name = p;
2536 if (audit_list == NULL)
2537 audit_list = newp->next = newp;
2538 else
2540 newp->next = audit_list->next;
2541 audit_list = audit_list->next = newp;
2546 /* Process all environments variables the dynamic linker must recognize.
2547 Since all of them start with `LD_' we are a bit smarter while finding
2548 all the entries. */
2549 extern char **_environ attribute_hidden;
2552 static void
2553 process_envvars (enum mode *modep)
2555 char **runp = _environ;
2556 char *envline;
2557 enum mode mode = normal;
2558 char *debug_output = NULL;
2560 /* This is the default place for profiling data file. */
2561 GLRO(dl_profile_output)
2562 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2564 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2566 size_t len = 0;
2568 while (envline[len] != '\0' && envline[len] != '=')
2569 ++len;
2571 if (envline[len] != '=')
2572 /* This is a "LD_" variable at the end of the string without
2573 a '=' character. Ignore it since otherwise we will access
2574 invalid memory below. */
2575 continue;
2577 switch (len)
2579 case 4:
2580 /* Warning level, verbose or not. */
2581 if (memcmp (envline, "WARN", 4) == 0)
2582 GLRO(dl_verbose) = envline[5] != '\0';
2583 break;
2585 case 5:
2586 /* Debugging of the dynamic linker? */
2587 if (memcmp (envline, "DEBUG", 5) == 0)
2589 process_dl_debug (&envline[6]);
2590 break;
2592 if (memcmp (envline, "AUDIT", 5) == 0)
2593 process_dl_audit (&envline[6]);
2594 break;
2596 case 7:
2597 /* Print information about versions. */
2598 if (memcmp (envline, "VERBOSE", 7) == 0)
2600 version_info = envline[8] != '\0';
2601 break;
2604 /* List of objects to be preloaded. */
2605 if (memcmp (envline, "PRELOAD", 7) == 0)
2607 preloadlist = &envline[8];
2608 break;
2611 /* Which shared object shall be profiled. */
2612 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2613 GLRO(dl_profile) = &envline[8];
2614 break;
2616 case 8:
2617 /* Do we bind early? */
2618 if (memcmp (envline, "BIND_NOW", 8) == 0)
2620 GLRO(dl_lazy) = envline[9] == '\0';
2621 break;
2623 if (memcmp (envline, "BIND_NOT", 8) == 0)
2624 GLRO(dl_bind_not) = envline[9] != '\0';
2625 break;
2627 case 9:
2628 /* Test whether we want to see the content of the auxiliary
2629 array passed up from the kernel. */
2630 if (!INTUSE(__libc_enable_secure)
2631 && memcmp (envline, "SHOW_AUXV", 9) == 0)
2632 _dl_show_auxv ();
2633 break;
2635 case 10:
2636 /* Mask for the important hardware capabilities. */
2637 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2638 GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2639 0, 0);
2640 break;
2642 case 11:
2643 /* Path where the binary is found. */
2644 if (!INTUSE(__libc_enable_secure)
2645 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2646 GLRO(dl_origin_path) = &envline[12];
2647 break;
2649 case 12:
2650 /* The library search path. */
2651 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2653 library_path = &envline[13];
2654 break;
2657 /* Where to place the profiling data file. */
2658 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2660 debug_output = &envline[13];
2661 break;
2664 if (!INTUSE(__libc_enable_secure)
2665 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2666 GLRO(dl_dynamic_weak) = 1;
2667 break;
2669 case 13:
2670 /* We might have some extra environment variable with length 13
2671 to handle. */
2672 #ifdef EXTRA_LD_ENVVARS_13
2673 EXTRA_LD_ENVVARS_13
2674 #endif
2675 if (!INTUSE(__libc_enable_secure)
2676 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2678 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2679 break;
2682 if (memcmp (envline, "POINTER_GUARD", 13) == 0)
2683 GLRO(dl_pointer_guard) = envline[14] != '0';
2684 break;
2686 case 14:
2687 /* Where to place the profiling data file. */
2688 if (!INTUSE(__libc_enable_secure)
2689 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2690 && envline[15] != '\0')
2691 GLRO(dl_profile_output) = &envline[15];
2692 break;
2694 case 16:
2695 /* The mode of the dynamic linker can be set. */
2696 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2698 mode = trace;
2699 GLRO(dl_verbose) = 1;
2700 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2701 GLRO(dl_trace_prelink) = &envline[17];
2703 break;
2705 case 20:
2706 /* The mode of the dynamic linker can be set. */
2707 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2708 mode = trace;
2709 break;
2711 /* We might have some extra environment variable to handle. This
2712 is tricky due to the pre-processing of the length of the name
2713 in the switch statement here. The code here assumes that added
2714 environment variables have a different length. */
2715 #ifdef EXTRA_LD_ENVVARS
2716 EXTRA_LD_ENVVARS
2717 #endif
2721 /* The caller wants this information. */
2722 *modep = mode;
2724 /* Extra security for SUID binaries. Remove all dangerous environment
2725 variables. */
2726 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2728 static const char unsecure_envvars[] =
2729 #ifdef EXTRA_UNSECURE_ENVVARS
2730 EXTRA_UNSECURE_ENVVARS
2731 #endif
2732 UNSECURE_ENVVARS;
2733 const char *nextp;
2735 nextp = unsecure_envvars;
2738 unsetenv (nextp);
2739 /* We could use rawmemchr but this need not be fast. */
2740 nextp = (char *) (strchr) (nextp, '\0') + 1;
2742 while (*nextp != '\0');
2744 if (__access ("/etc/suid-debug", F_OK) != 0)
2746 unsetenv ("MALLOC_CHECK_");
2747 GLRO(dl_debug_mask) = 0;
2750 if (mode != normal)
2751 _exit (5);
2753 /* If we have to run the dynamic linker in debugging mode and the
2754 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2755 messages to this file. */
2756 else if (any_debug && debug_output != NULL)
2758 #ifdef O_NOFOLLOW
2759 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2760 #else
2761 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2762 #endif
2763 size_t name_len = strlen (debug_output);
2764 char buf[name_len + 12];
2765 char *startp;
2767 buf[name_len + 11] = '\0';
2768 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2769 *--startp = '.';
2770 startp = memcpy (startp - name_len, debug_output, name_len);
2772 GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2773 if (GLRO(dl_debug_fd) == -1)
2774 /* We use standard output if opening the file failed. */
2775 GLRO(dl_debug_fd) = STDOUT_FILENO;
2780 /* Print the various times we collected. */
2781 static void
2782 __attribute ((noinline))
2783 print_statistics (hp_timing_t *rtld_total_timep)
2785 #ifndef HP_TIMING_NONAVAIL
2786 char buf[200];
2787 char *cp;
2788 char *wp;
2790 /* Total time rtld used. */
2791 if (HP_TIMING_AVAIL)
2793 HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2794 _dl_debug_printf ("\nruntime linker statistics:\n"
2795 " total startup time in dynamic loader: %s\n", buf);
2797 /* Print relocation statistics. */
2798 char pbuf[30];
2799 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2800 cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2801 pbuf + sizeof (pbuf), 10, 0);
2802 wp = pbuf;
2803 switch (pbuf + sizeof (pbuf) - cp)
2805 case 3:
2806 *wp++ = *cp++;
2807 case 2:
2808 *wp++ = *cp++;
2809 case 1:
2810 *wp++ = '.';
2811 *wp++ = *cp++;
2813 *wp = '\0';
2814 _dl_debug_printf ("\
2815 time needed for relocation: %s (%s%%)\n", buf, pbuf);
2817 #endif
2819 unsigned long int num_relative_relocations = 0;
2820 for (Lmid_t ns = 0; ns < GL(dl_nns); ++ns)
2822 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2823 continue;
2825 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2827 for (unsigned int i = 0; i < scope->r_nlist; i++)
2829 struct link_map *l = scope->r_list [i];
2831 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2832 num_relative_relocations
2833 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2834 #ifndef ELF_MACHINE_REL_RELATIVE
2835 /* Relative relocations are processed on these architectures if
2836 library is loaded to different address than p_vaddr or
2837 if not prelinked. */
2838 if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2839 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2840 #else
2841 /* On e.g. IA-64 or Alpha, relative relocations are processed
2842 only if library is loaded to different address than p_vaddr. */
2843 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2844 #endif
2845 num_relative_relocations
2846 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2850 _dl_debug_printf (" number of relocations: %lu\n"
2851 " number of relocations from cache: %lu\n"
2852 " number of relative relocations: %lu\n",
2853 GL(dl_num_relocations),
2854 GL(dl_num_cache_relocations),
2855 num_relative_relocations);
2857 #ifndef HP_TIMING_NONAVAIL
2858 /* Time spend while loading the object and the dependencies. */
2859 if (HP_TIMING_AVAIL)
2861 char pbuf[30];
2862 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2863 cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2864 pbuf + sizeof (pbuf), 10, 0);
2865 wp = pbuf;
2866 switch (pbuf + sizeof (pbuf) - cp)
2868 case 3:
2869 *wp++ = *cp++;
2870 case 2:
2871 *wp++ = *cp++;
2872 case 1:
2873 *wp++ = '.';
2874 *wp++ = *cp++;
2876 *wp = '\0';
2877 _dl_debug_printf ("\
2878 time needed to load objects: %s (%s%%)\n",
2879 buf, pbuf);
2881 #endif