ld.so: Don't try to read own ELF headers on startup
[glibc/nacl-glibc.git] / elf / rtld.c
blobde902981320429c6d76c27e1112ed188f646f62a
1 /* Run time dynamic linker.
2 Copyright (C) 1995-2006, 2007, 2008 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> /* Check if MAP_ANON is defined. */
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
131 /* If we would use strong_alias here the compiler would see a
132 non-hidden definition. This would undo the effect of the previous
133 declaration. So spell out was strong_alias does plus add the
134 visibility attribute. */
135 extern struct rtld_global _rtld_local
136 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
139 /* This variable is similar to _rtld_local, but all values are
140 read-only after relocation. */
141 struct rtld_global_ro _rtld_global_ro attribute_relro =
143 /* Get architecture specific initializer. */
144 #include <dl-procinfo.c>
145 #ifdef NEED_DL_SYSINFO
146 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
147 #endif
148 ._dl_debug_fd = STDERR_FILENO,
149 ._dl_use_load_bias = -2,
150 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
151 ._dl_hwcap_mask = HWCAP_IMPORTANT,
152 ._dl_lazy = 1,
153 ._dl_fpu_control = _FPU_DEFAULT,
154 ._dl_pointer_guard = 1,
156 /* Function pointers. */
157 ._dl_debug_printf = _dl_debug_printf,
158 ._dl_catch_error = _dl_catch_error,
159 ._dl_signal_error = _dl_signal_error,
160 ._dl_mcount = _dl_mcount_internal,
161 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
162 ._dl_check_caller = _dl_check_caller,
163 ._dl_open = _dl_open,
164 ._dl_close = _dl_close,
165 ._dl_tls_get_addr_soft = _dl_tls_get_addr_soft,
166 #ifdef HAVE_DL_DISCOVER_OSVERSION
167 ._dl_discover_osversion = _dl_discover_osversion
168 #endif
170 /* If we would use strong_alias here the compiler would see a
171 non-hidden definition. This would undo the effect of the previous
172 declaration. So spell out was strong_alias does plus add the
173 visibility attribute. */
174 extern struct rtld_global_ro _rtld_local_ro
175 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
178 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
179 ElfW(Addr) *user_entry);
181 /* These two variables cannot be moved into .data.rel.ro. */
182 static struct libname_list _dl_rtld_libname;
183 static struct libname_list _dl_rtld_libname2;
185 /* We expect less than a second for relocation. */
186 #ifdef HP_SMALL_TIMING_AVAIL
187 # undef HP_TIMING_AVAIL
188 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
189 #endif
191 /* Variable for statistics. */
192 #ifndef HP_TIMING_NONAVAIL
193 static hp_timing_t relocate_time;
194 static hp_timing_t load_time attribute_relro;
195 static hp_timing_t start_time attribute_relro;
196 #endif
198 /* Additional definitions needed by TLS initialization. */
199 #ifdef TLS_INIT_HELPER
200 TLS_INIT_HELPER
201 #endif
203 /* Helper function for syscall implementation. */
204 #ifdef DL_SYSINFO_IMPLEMENTATION
205 DL_SYSINFO_IMPLEMENTATION
206 #endif
208 /* Before ld.so is relocated we must not access variables which need
209 relocations. This means variables which are exported. Variables
210 declared as static are fine. If we can mark a variable hidden this
211 is fine, too. The latter is important here. We can avoid setting
212 up a temporary link map for ld.so if we can mark _rtld_global as
213 hidden. */
214 #ifdef PI_STATIC_AND_HIDDEN
215 # define DONT_USE_BOOTSTRAP_MAP 1
216 #endif
218 #ifdef DONT_USE_BOOTSTRAP_MAP
219 static ElfW(Addr) _dl_start_final (void *arg);
220 #else
221 struct dl_start_final_info
223 struct link_map l;
224 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
225 hp_timing_t start_time;
226 #endif
228 static ElfW(Addr) _dl_start_final (void *arg,
229 struct dl_start_final_info *info);
230 #endif
232 /* These defined magically in the linker script. */
233 extern char _begin[] attribute_hidden;
234 extern char _etext[] attribute_hidden;
235 extern char _end[] attribute_hidden;
238 #ifdef RTLD_START
239 RTLD_START
240 #else
241 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
242 #endif
244 #ifndef VALIDX
245 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
246 + DT_EXTRANUM + DT_VALTAGIDX (tag))
247 #endif
248 #ifndef ADDRIDX
249 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
250 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
251 #endif
253 /* This is the second half of _dl_start (below). It can be inlined safely
254 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
255 references. When the tools don't permit us to avoid using a GOT entry
256 for _dl_rtld_global (no attribute_hidden support), we must make sure
257 this function is not inlined (see below). */
259 #ifdef DONT_USE_BOOTSTRAP_MAP
260 static inline ElfW(Addr) __attribute__ ((always_inline))
261 _dl_start_final (void *arg)
262 #else
263 static ElfW(Addr) __attribute__ ((noinline))
264 _dl_start_final (void *arg, struct dl_start_final_info *info)
265 #endif
267 ElfW(Addr) start_addr;
269 if (HP_TIMING_AVAIL)
271 /* If it hasn't happen yet record the startup time. */
272 if (! HP_TIMING_INLINE)
273 HP_TIMING_NOW (start_time);
274 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
275 else
276 start_time = info->start_time;
277 #endif
279 /* Initialize the timing functions. */
280 HP_TIMING_DIFF_INIT ();
283 /* Transfer data about ourselves to the permanent link_map structure. */
284 #ifndef DONT_USE_BOOTSTRAP_MAP
285 GL(dl_rtld_map).l_addr = info->l.l_addr;
286 GL(dl_rtld_map).l_ld = info->l.l_ld;
287 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
288 sizeof GL(dl_rtld_map).l_info);
289 GL(dl_rtld_map).l_mach = info->l.l_mach;
290 GL(dl_rtld_map).l_relocated = 1;
291 #endif
292 _dl_setup_hash (&GL(dl_rtld_map));
293 GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
294 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
295 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
296 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
297 /* Copy the TLS related data if necessary. */
298 #ifndef DONT_USE_BOOTSTRAP_MAP
299 # if USE___THREAD
300 assert (info->l.l_tls_modid != 0);
301 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
302 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
303 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
304 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
305 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
306 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
307 GL(dl_rtld_map).l_tls_modid = 1;
308 # else
309 # if NO_TLS_OFFSET != 0
310 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
311 # endif
312 # endif
314 #endif
316 #if HP_TIMING_AVAIL
317 HP_TIMING_NOW (GL(dl_cpuclock_offset));
318 #endif
320 /* Initialize the stack end variable. */
321 __libc_stack_end = __builtin_frame_address (0);
323 /* Call the OS-dependent function to set up life so we can do things like
324 file access. It will call `dl_main' (below) to do all the real work
325 of the dynamic linker, and then unwind our frame and run the user
326 entry point on the same stack we entered on. */
327 start_addr = _dl_sysdep_start (arg, &dl_main);
329 #ifndef HP_TIMING_NONAVAIL
330 hp_timing_t rtld_total_time;
331 if (HP_TIMING_AVAIL)
333 hp_timing_t end_time;
335 /* Get the current time. */
336 HP_TIMING_NOW (end_time);
338 /* Compute the difference. */
339 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
341 #endif
343 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
345 #ifndef HP_TIMING_NONAVAIL
346 print_statistics (&rtld_total_time);
347 #else
348 print_statistics (NULL);
349 #endif
352 return start_addr;
355 static ElfW(Addr) __attribute_used__ internal_function
356 __attribute__ ((regparm (3), stdcall))
357 _dl_start (void *arg)
359 #ifdef DONT_USE_BOOTSTRAP_MAP
360 # define bootstrap_map GL(dl_rtld_map)
361 #else
362 struct dl_start_final_info info;
363 # define bootstrap_map info.l
364 #endif
366 /* This #define produces dynamic linking inline functions for
367 bootstrap relocation instead of general-purpose relocation.
368 Since ld.so must not have any undefined symbols the result
369 is trivial: always the map of ld.so itself. */
370 #define RTLD_BOOTSTRAP
371 #define RESOLVE_MAP(sym, version, flags) (&bootstrap_map)
372 #include "dynamic-link.h"
374 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
375 #ifdef DONT_USE_BOOTSTRAP_MAP
376 HP_TIMING_NOW (start_time);
377 #else
378 HP_TIMING_NOW (info.start_time);
379 #endif
381 /* Partly clean the `bootstrap_map' structure up. Don't use
382 `memset' since it might not be built in or inlined and we cannot
383 make function calls at this point. Use '__builtin_memset' if we
384 know it is available. We do not have to clear the memory if we
385 do not have to use the temporary bootstrap_map. Global variables
386 are initialized to zero by default. */
387 #ifndef DONT_USE_BOOTSTRAP_MAP
388 # ifdef HAVE_BUILTIN_MEMSET
389 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
390 # else
391 for (size_t cnt = 0;
392 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
393 ++cnt)
394 bootstrap_map.l_info[cnt] = 0;
395 # endif
396 # if USE___THREAD
397 bootstrap_map.l_tls_modid = 0;
398 # endif
399 #endif
401 /* Figure out the run-time load address of the dynamic linker itself. */
402 bootstrap_map.l_addr = elf_machine_load_address ();
404 /* Read our own dynamic section and fill in the info array. */
405 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
406 elf_get_dynamic_info (&bootstrap_map, NULL);
408 #if NO_TLS_OFFSET != 0
409 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
410 #endif
412 /* Get the dynamic linker's own program header. First we need the ELF
413 file header. The `_begin' symbol created by the linker script points
414 to it. When we have something like GOTOFF relocs, we can use a plain
415 reference to find the runtime address. Without that, we have to rely
416 on the `l_addr' value, which is not the value we want when prelinked. */
417 #if USE___THREAD
418 dtv_t initdtv[3];
419 ElfW(Ehdr) *ehdr
420 # ifdef DONT_USE_BOOTSTRAP_MAP
421 = (ElfW(Ehdr) *) &_begin;
422 # else
423 # error This will not work with prelink.
424 = (ElfW(Ehdr) *) bootstrap_map.l_addr;
425 # endif
426 ElfW(Phdr) *phdr = (ElfW(Phdr) *) ((void *) ehdr + ehdr->e_phoff);
427 size_t cnt = ehdr->e_phnum; /* PT_TLS is usually the last phdr. */
428 while (cnt-- > 0)
429 if (phdr[cnt].p_type == PT_TLS)
431 void *tlsblock;
432 size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
433 char *p;
435 bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
436 bootstrap_map.l_tls_align = phdr[cnt].p_align;
437 if (phdr[cnt].p_align == 0)
438 bootstrap_map.l_tls_firstbyte_offset = 0;
439 else
440 bootstrap_map.l_tls_firstbyte_offset = (phdr[cnt].p_vaddr
441 & (phdr[cnt].p_align - 1));
442 assert (bootstrap_map.l_tls_blocksize != 0);
443 bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
444 bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
445 + phdr[cnt].p_vaddr);
447 /* We can now allocate the initial TLS block. This can happen
448 on the stack. We'll get the final memory later when we
449 know all about the various objects loaded at startup
450 time. */
451 # if TLS_TCB_AT_TP
452 tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
453 TLS_INIT_TCB_ALIGN)
454 + TLS_INIT_TCB_SIZE
455 + max_align);
456 # elif TLS_DTV_AT_TP
457 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
458 bootstrap_map.l_tls_align)
459 + bootstrap_map.l_tls_blocksize
460 + max_align);
461 # else
462 /* In case a model with a different layout for the TCB and DTV
463 is defined add another #elif here and in the following #ifs. */
464 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
465 # endif
466 /* Align the TLS block. */
467 tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
468 & ~(max_align - 1));
470 /* Initialize the dtv. [0] is the length, [1] the generation
471 counter. */
472 initdtv[0].counter = 1;
473 initdtv[1].counter = 0;
475 /* Initialize the TLS block. */
476 # if TLS_TCB_AT_TP
477 initdtv[2].pointer = tlsblock;
478 # elif TLS_DTV_AT_TP
479 bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
480 bootstrap_map.l_tls_align);
481 initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
482 # else
483 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
484 # endif
485 p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
486 bootstrap_map.l_tls_initimage_size);
487 # ifdef HAVE_BUILTIN_MEMSET
488 __builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
489 - bootstrap_map.l_tls_initimage_size));
490 # else
492 size_t remaining = (bootstrap_map.l_tls_blocksize
493 - bootstrap_map.l_tls_initimage_size);
494 while (remaining-- > 0)
495 *p++ = '\0';
497 # endif
499 /* Install the pointer to the dtv. */
501 /* Initialize the thread pointer. */
502 # if TLS_TCB_AT_TP
503 bootstrap_map.l_tls_offset
504 = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
506 INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
507 initdtv);
509 const char *lossage = TLS_INIT_TP ((char *) tlsblock
510 + bootstrap_map.l_tls_offset, 0);
511 # elif TLS_DTV_AT_TP
512 INSTALL_DTV (tlsblock, initdtv);
513 const char *lossage = TLS_INIT_TP (tlsblock, 0);
514 # else
515 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
516 # endif
517 if (__builtin_expect (lossage != NULL, 0))
518 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
519 lossage);
521 /* So far this is module number one. */
522 bootstrap_map.l_tls_modid = 1;
524 /* There can only be one PT_TLS entry. */
525 break;
527 #endif /* USE___THREAD */
529 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
530 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
531 #endif
533 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
535 /* Relocate ourselves so we can do normal function calls and
536 data access using the global offset table. */
538 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
540 bootstrap_map.l_relocated = 1;
542 /* Please note that we don't allow profiling of this object and
543 therefore need not test whether we have to allocate the array
544 for the relocation results (as done in dl-reloc.c). */
546 /* Now life is sane; we can call functions and access global data.
547 Set up to use the operating system facilities, and find out from
548 the operating system's program loader where to find the program
549 header table in core. Put the rest of _dl_start into a separate
550 function, that way the compiler cannot put accesses to the GOT
551 before ELF_DYNAMIC_RELOCATE. */
553 #ifdef DONT_USE_BOOTSTRAP_MAP
554 ElfW(Addr) entry = _dl_start_final (arg);
555 #else
556 ElfW(Addr) entry = _dl_start_final (arg, &info);
557 #endif
559 #ifndef ELF_MACHINE_START_ADDRESS
560 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
561 #endif
563 return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, entry);
569 /* Now life is peachy; we can do all normal operations.
570 On to the real work. */
572 /* Some helper functions. */
574 /* Arguments to relocate_doit. */
575 struct relocate_args
577 struct link_map *l;
578 int lazy;
581 struct map_args
583 /* Argument to map_doit. */
584 char *str;
585 struct link_map *loader;
586 int is_preloaded;
587 int mode;
588 /* Return value of map_doit. */
589 struct link_map *map;
592 struct dlmopen_args
594 const char *fname;
595 struct link_map *map;
598 struct lookup_args
600 const char *name;
601 struct link_map *map;
602 void *result;
605 /* Arguments to version_check_doit. */
606 struct version_check_args
608 int doexit;
609 int dotrace;
612 static void
613 relocate_doit (void *a)
615 struct relocate_args *args = (struct relocate_args *) a;
617 _dl_relocate_object (args->l, args->l->l_scope, args->lazy, 0);
620 static void
621 map_doit (void *a)
623 struct map_args *args = (struct map_args *) a;
624 args->map = _dl_map_object (args->loader, args->str,
625 args->is_preloaded, lt_library, 0, args->mode,
626 LM_ID_BASE);
629 static void
630 dlmopen_doit (void *a)
632 struct dlmopen_args *args = (struct dlmopen_args *) a;
633 args->map = _dl_open (args->fname, RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT,
634 dl_main, LM_ID_NEWLM, _dl_argc, INTUSE(_dl_argv),
635 __environ);
638 static void
639 lookup_doit (void *a)
641 struct lookup_args *args = (struct lookup_args *) a;
642 const ElfW(Sym) *ref = NULL;
643 args->result = NULL;
644 lookup_t l = _dl_lookup_symbol_x (args->name, args->map, &ref,
645 args->map->l_local_scope, NULL, 0,
646 DL_LOOKUP_RETURN_NEWEST, NULL);
647 if (ref != NULL)
648 args->result = DL_SYMBOL_ADDRESS (l, ref);
651 static void
652 version_check_doit (void *a)
654 struct version_check_args *args = (struct version_check_args *) a;
655 if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
656 args->dotrace) && args->doexit)
657 /* We cannot start the application. Abort now. */
658 _exit (1);
662 static inline struct link_map *
663 find_needed (const char *name)
665 struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
666 unsigned int n = scope->r_nlist;
668 while (n-- > 0)
669 if (_dl_name_match_p (name, scope->r_list[n]))
670 return scope->r_list[n];
672 /* Should never happen. */
673 return NULL;
676 static int
677 match_version (const char *string, struct link_map *map)
679 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
680 ElfW(Verdef) *def;
682 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
683 if (map->l_info[VERDEFTAG] == NULL)
684 /* The file has no symbol versioning. */
685 return 0;
687 def = (ElfW(Verdef) *) ((char *) map->l_addr
688 + map->l_info[VERDEFTAG]->d_un.d_ptr);
689 while (1)
691 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
693 /* Compare the version strings. */
694 if (strcmp (string, strtab + aux->vda_name) == 0)
695 /* Bingo! */
696 return 1;
698 /* If no more definitions we failed to find what we want. */
699 if (def->vd_next == 0)
700 break;
702 /* Next definition. */
703 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
706 return 0;
709 static bool tls_init_tp_called;
711 static void *
712 init_tls (void)
714 /* Number of elements in the static TLS block. */
715 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
717 /* Do not do this twice. The audit interface might have required
718 the DTV interfaces to be set up early. */
719 if (GL(dl_initial_dtv) != NULL)
720 return NULL;
722 /* Allocate the array which contains the information about the
723 dtv slots. We allocate a few entries more than needed to
724 avoid the need for reallocation. */
725 size_t nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
727 /* Allocate. */
728 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
729 calloc (sizeof (struct dtv_slotinfo_list)
730 + nelem * sizeof (struct dtv_slotinfo), 1);
731 /* No need to check the return value. If memory allocation failed
732 the program would have been terminated. */
734 struct dtv_slotinfo *slotinfo = GL(dl_tls_dtv_slotinfo_list)->slotinfo;
735 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
736 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
738 /* Fill in the information from the loaded modules. No namespace
739 but the base one can be filled at this time. */
740 assert (GL(dl_ns)[LM_ID_BASE + 1]._ns_loaded == NULL);
741 int i = 0;
742 for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
743 l = l->l_next)
744 if (l->l_tls_blocksize != 0)
746 /* This is a module with TLS data. Store the map reference.
747 The generation counter is zero. */
748 slotinfo[i].map = l;
749 /* slotinfo[i].gen = 0; */
750 ++i;
752 assert (i == GL(dl_tls_max_dtv_idx));
754 /* Compute the TLS offsets for the various blocks. */
755 _dl_determine_tlsoffset ();
757 /* Construct the static TLS block and the dtv for the initial
758 thread. For some platforms this will include allocating memory
759 for the thread descriptor. The memory for the TLS block will
760 never be freed. It should be allocated accordingly. The dtv
761 array can be changed if dynamic loading requires it. */
762 void *tcbp = _dl_allocate_tls_storage ();
763 if (tcbp == NULL)
764 _dl_fatal_printf ("\
765 cannot allocate TLS data structures for initial thread");
767 /* Store for detection of the special case by __tls_get_addr
768 so it knows not to pass this dtv to the normal realloc. */
769 GL(dl_initial_dtv) = GET_DTV (tcbp);
771 /* And finally install it for the main thread. If ld.so itself uses
772 TLS we know the thread pointer was initialized earlier. */
773 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
774 if (__builtin_expect (lossage != NULL, 0))
775 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
776 tls_init_tp_called = true;
778 return tcbp;
781 #ifdef _LIBC_REENTRANT
782 /* _dl_error_catch_tsd points to this for the single-threaded case.
783 It's reset by the thread library for multithreaded programs. */
784 void ** __attribute__ ((const))
785 _dl_initial_error_catch_tsd (void)
787 static void *data;
788 return &data;
790 #endif
793 static unsigned int
794 do_preload (char *fname, struct link_map *main_map, const char *where)
796 const char *objname;
797 const char *err_str = NULL;
798 struct map_args args;
799 bool malloced;
801 args.str = fname;
802 args.loader = main_map;
803 args.is_preloaded = 1;
804 args.mode = 0;
806 unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
808 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
809 if (__builtin_expect (err_str != NULL, 0))
811 _dl_error_printf ("\
812 ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
813 fname, where);
814 /* No need to call free, this is still before
815 the libc's malloc is used. */
817 else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
818 /* It is no duplicate. */
819 return 1;
821 /* Nothing loaded. */
822 return 0;
825 #if defined SHARED && defined _LIBC_REENTRANT \
826 && defined __rtld_lock_default_lock_recursive
827 static void
828 rtld_lock_default_lock_recursive (void *lock)
830 __rtld_lock_default_lock_recursive (lock);
833 static void
834 rtld_lock_default_unlock_recursive (void *lock)
836 __rtld_lock_default_unlock_recursive (lock);
838 #endif
841 static void
842 security_init (void)
844 /* Set up the stack checker's canary. */
845 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard ();
846 #ifdef THREAD_SET_STACK_GUARD
847 THREAD_SET_STACK_GUARD (stack_chk_guard);
848 #else
849 __stack_chk_guard = stack_chk_guard;
850 #endif
852 /* Set up the pointer guard as well, if necessary. */
853 if (GLRO(dl_pointer_guard))
855 // XXX If it is cheap, we should use a separate value.
856 uintptr_t pointer_chk_guard = stack_chk_guard;
857 #ifndef HP_TIMING_NONAVAIL
858 hp_timing_t now;
859 HP_TIMING_NOW (now);
860 pointer_chk_guard ^= now;
861 #endif
862 #ifdef THREAD_SET_POINTER_GUARD
863 THREAD_SET_POINTER_GUARD (pointer_chk_guard);
864 #endif
865 __pointer_chk_guard_local = pointer_chk_guard;
870 /* The library search path. */
871 static const char *library_path attribute_relro;
872 /* The list preloaded objects. */
873 static const char *preloadlist attribute_relro;
874 /* Nonzero if information about versions has to be printed. */
875 static int version_info attribute_relro;
877 static void
878 dl_main (const ElfW(Phdr) *phdr,
879 ElfW(Word) phnum,
880 ElfW(Addr) *user_entry)
882 const ElfW(Phdr) *ph;
883 enum mode mode;
884 struct link_map *main_map;
885 size_t file_size;
886 char *file;
887 bool has_interp = false;
888 unsigned int i;
889 bool prelinked = false;
890 bool rtld_is_main = false;
891 #ifndef HP_TIMING_NONAVAIL
892 hp_timing_t start;
893 hp_timing_t stop;
894 hp_timing_t diff;
895 #endif
896 void *tcbp = NULL;
898 #ifdef _LIBC_REENTRANT
899 /* Explicit initialization since the reloc would just be more work. */
900 GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
901 #endif
903 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
905 #if defined SHARED && defined _LIBC_REENTRANT \
906 && defined __rtld_lock_default_lock_recursive
907 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
908 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
909 #endif
911 /* The explicit initialization here is cheaper than processing the reloc
912 in the _rtld_local definition's initializer. */
913 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
915 /* Process the environment variable which control the behaviour. */
916 process_envvars (&mode);
918 #ifndef HAVE_INLINED_SYSCALLS
919 /* Set up a flag which tells we are just starting. */
920 INTUSE(_dl_starting_up) = 1;
921 #endif
923 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
925 /* Ho ho. We are not the program interpreter! We are the program
926 itself! This means someone ran ld.so as a command. Well, that
927 might be convenient to do sometimes. We support it by
928 interpreting the args like this:
930 ld.so PROGRAM ARGS...
932 The first argument is the name of a file containing an ELF
933 executable we will load and run with the following arguments.
934 To simplify life here, PROGRAM is searched for using the
935 normal rules for shared objects, rather than $PATH or anything
936 like that. We just load it and use its entry point; we don't
937 pay attention to its PT_INTERP command (we are the interpreter
938 ourselves). This is an easy way to test a new ld.so before
939 installing it. */
940 rtld_is_main = true;
942 /* Note the place where the dynamic linker actually came from. */
943 GL(dl_rtld_map).l_name = rtld_progname;
945 while (_dl_argc > 1)
946 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
948 mode = list;
949 GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
951 ++_dl_skip_args;
952 --_dl_argc;
953 ++INTUSE(_dl_argv);
955 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
957 mode = verify;
959 ++_dl_skip_args;
960 --_dl_argc;
961 ++INTUSE(_dl_argv);
963 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
964 && _dl_argc > 2)
966 library_path = INTUSE(_dl_argv)[2];
968 _dl_skip_args += 2;
969 _dl_argc -= 2;
970 INTUSE(_dl_argv) += 2;
972 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
973 && _dl_argc > 2)
975 GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
977 _dl_skip_args += 2;
978 _dl_argc -= 2;
979 INTUSE(_dl_argv) += 2;
981 else if (! strcmp (INTUSE(_dl_argv)[1], "--audit") && _dl_argc > 2)
983 process_dl_audit (INTUSE(_dl_argv)[2]);
985 _dl_skip_args += 2;
986 _dl_argc -= 2;
987 INTUSE(_dl_argv) += 2;
989 else
990 break;
992 /* If we have no further argument the program was called incorrectly.
993 Grant the user some education. */
994 if (_dl_argc < 2)
995 _dl_fatal_printf ("\
996 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
997 You have invoked `ld.so', the helper program for shared library executables.\n\
998 This program usually lives in the file `/lib/ld.so', and special directives\n\
999 in executable files using ELF shared libraries tell the system's program\n\
1000 loader to load the helper program from this file. This helper program loads\n\
1001 the shared libraries needed by the program executable, prepares the program\n\
1002 to run, and runs it. You may invoke this helper program directly from the\n\
1003 command line to load and run an ELF executable file; this is like executing\n\
1004 that file itself, but always uses this helper program from the file you\n\
1005 specified, instead of the helper program file specified in the executable\n\
1006 file you run. This is mostly of use for maintainers to test new versions\n\
1007 of this helper program; chances are you did not intend to run this program.\n\
1009 --list list all dependencies and how they are resolved\n\
1010 --verify verify that given object really is a dynamically linked\n\
1011 object we can handle\n\
1012 --library-path PATH use given PATH instead of content of the environment\n\
1013 variable LD_LIBRARY_PATH\n\
1014 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
1015 in LIST\n");
1017 ++_dl_skip_args;
1018 --_dl_argc;
1019 ++INTUSE(_dl_argv);
1021 /* The initialization of _dl_stack_flags done below assumes the
1022 executable's PT_GNU_STACK may have been honored by the kernel, and
1023 so a PT_GNU_STACK with PF_X set means the stack started out with
1024 execute permission. However, this is not really true if the
1025 dynamic linker is the executable the kernel loaded. For this
1026 case, we must reinitialize _dl_stack_flags to match the dynamic
1027 linker itself. If the dynamic linker was built with a
1028 PT_GNU_STACK, then the kernel may have loaded us with a
1029 nonexecutable stack that we will have to make executable when we
1030 load the program below unless it has a PT_GNU_STACK indicating
1031 nonexecutable stack is ok. */
1033 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1034 if (ph->p_type == PT_GNU_STACK)
1036 GL(dl_stack_flags) = ph->p_flags;
1037 break;
1040 if (__builtin_expect (mode, normal) == verify)
1042 const char *objname;
1043 const char *err_str = NULL;
1044 struct map_args args;
1045 bool malloced;
1047 args.str = rtld_progname;
1048 args.loader = NULL;
1049 args.is_preloaded = 0;
1050 args.mode = __RTLD_OPENEXEC;
1051 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
1052 &args);
1053 if (__builtin_expect (err_str != NULL, 0))
1054 /* We don't free the returned string, the programs stops
1055 anyway. */
1056 _exit (EXIT_FAILURE);
1058 else
1060 HP_TIMING_NOW (start);
1061 _dl_map_object (NULL, rtld_progname, 0, lt_library, 0,
1062 __RTLD_OPENEXEC, LM_ID_BASE);
1063 HP_TIMING_NOW (stop);
1065 HP_TIMING_DIFF (load_time, start, stop);
1068 /* Now the map for the main executable is available. */
1069 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1071 phdr = main_map->l_phdr;
1072 phnum = main_map->l_phnum;
1073 /* We overwrite here a pointer to a malloc()ed string. But since
1074 the malloc() implementation used at this point is the dummy
1075 implementations which has no real free() function it does not
1076 makes sense to free the old string first. */
1077 main_map->l_name = (char *) "";
1078 *user_entry = main_map->l_entry;
1080 else
1082 /* Create a link_map for the executable itself.
1083 This will be what dlopen on "" returns. */
1084 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1085 __RTLD_OPENEXEC, LM_ID_BASE);
1086 assert (main_map != NULL);
1087 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
1088 main_map->l_phdr = phdr;
1089 main_map->l_phnum = phnum;
1090 main_map->l_entry = *user_entry;
1092 /* At this point we are in a bit of trouble. We would have to
1093 fill in the values for l_dev and l_ino. But in general we
1094 do not know where the file is. We also do not handle AT_EXECFD
1095 even if it would be passed up.
1097 We leave the values here defined to 0. This is normally no
1098 problem as the program code itself is normally no shared
1099 object and therefore cannot be loaded dynamically. Nothing
1100 prevent the use of dynamic binaries and in these situations
1101 we might get problems. We might not be able to find out
1102 whether the object is already loaded. But since there is no
1103 easy way out and because the dynamic binary must also not
1104 have an SONAME we ignore this program for now. If it becomes
1105 a problem we can force people using SONAMEs. */
1107 /* We delay initializing the path structure until we got the dynamic
1108 information for the program. */
1111 main_map->l_map_end = 0;
1112 main_map->l_text_end = 0;
1113 /* Perhaps the executable has no PT_LOAD header entries at all. */
1114 main_map->l_map_start = ~0;
1115 /* And it was opened directly. */
1116 ++main_map->l_direct_opencount;
1118 /* Scan the program header table for the dynamic section. */
1119 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1120 switch (ph->p_type)
1122 case PT_PHDR:
1123 /* Find out the load address. */
1124 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1125 break;
1126 case PT_DYNAMIC:
1127 /* This tells us where to find the dynamic section,
1128 which tells us everything we need to do. */
1129 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
1130 break;
1131 case PT_INTERP:
1132 /* This "interpreter segment" was used by the program loader to
1133 find the program interpreter, which is this program itself, the
1134 dynamic linker. We note what name finds us, so that a future
1135 dlopen call or DT_NEEDED entry, for something that wants to link
1136 against the dynamic linker as a shared library, will know that
1137 the shared object is already loaded. */
1138 _dl_rtld_libname.name = ((const char *) main_map->l_addr
1139 + ph->p_vaddr);
1140 /* _dl_rtld_libname.next = NULL; Already zero. */
1141 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1143 /* Ordinarilly, we would get additional names for the loader from
1144 our DT_SONAME. This can't happen if we were actually linked as
1145 a static executable (detect this case when we have no DYNAMIC).
1146 If so, assume the filename component of the interpreter path to
1147 be our SONAME, and add it to our name list. */
1148 if (GL(dl_rtld_map).l_ld == NULL)
1150 const char *p = NULL;
1151 const char *cp = _dl_rtld_libname.name;
1153 /* Find the filename part of the path. */
1154 while (*cp != '\0')
1155 if (*cp++ == '/')
1156 p = cp;
1158 if (p != NULL)
1160 _dl_rtld_libname2.name = p;
1161 /* _dl_rtld_libname2.next = NULL; Already zero. */
1162 _dl_rtld_libname.next = &_dl_rtld_libname2;
1166 has_interp = true;
1167 break;
1168 case PT_LOAD:
1170 ElfW(Addr) mapstart;
1171 ElfW(Addr) allocend;
1173 /* Remember where the main program starts in memory. */
1174 mapstart = (main_map->l_addr
1175 + (ph->p_vaddr & ~(GLRO(dl_pagesize) - 1)));
1176 if (main_map->l_map_start > mapstart)
1177 main_map->l_map_start = mapstart;
1179 /* Also where it ends. */
1180 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1181 if (main_map->l_map_end < allocend)
1182 main_map->l_map_end = allocend;
1183 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1184 main_map->l_text_end = allocend;
1186 break;
1188 case PT_TLS:
1189 if (ph->p_memsz > 0)
1191 /* Note that in the case the dynamic linker we duplicate work
1192 here since we read the PT_TLS entry already in
1193 _dl_start_final. But the result is repeatable so do not
1194 check for this special but unimportant case. */
1195 main_map->l_tls_blocksize = ph->p_memsz;
1196 main_map->l_tls_align = ph->p_align;
1197 if (ph->p_align == 0)
1198 main_map->l_tls_firstbyte_offset = 0;
1199 else
1200 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1201 & (ph->p_align - 1));
1202 main_map->l_tls_initimage_size = ph->p_filesz;
1203 main_map->l_tls_initimage = (void *) ph->p_vaddr;
1205 /* This image gets the ID one. */
1206 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1208 break;
1210 case PT_GNU_STACK:
1211 GL(dl_stack_flags) = ph->p_flags;
1212 break;
1214 case PT_GNU_RELRO:
1215 main_map->l_relro_addr = ph->p_vaddr;
1216 main_map->l_relro_size = ph->p_memsz;
1217 break;
1220 /* Adjust the address of the TLS initialization image in case
1221 the executable is actually an ET_DYN object. */
1222 if (main_map->l_tls_initimage != NULL)
1223 main_map->l_tls_initimage
1224 = (char *) main_map->l_tls_initimage + main_map->l_addr;
1225 if (! main_map->l_map_end)
1226 main_map->l_map_end = ~0;
1227 if (! main_map->l_text_end)
1228 main_map->l_text_end = ~0;
1229 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1231 /* We were invoked directly, so the program might not have a
1232 PT_INTERP. */
1233 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1234 /* _dl_rtld_libname.next = NULL; Already zero. */
1235 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1237 else
1238 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1240 /* If the current libname is different from the SONAME, add the
1241 latter as well. */
1242 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1243 && strcmp (GL(dl_rtld_map).l_libname->name,
1244 (const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1245 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1247 static struct libname_list newname;
1248 newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1249 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1250 newname.next = NULL;
1251 newname.dont_free = 1;
1253 assert (GL(dl_rtld_map).l_libname->next == NULL);
1254 GL(dl_rtld_map).l_libname->next = &newname;
1256 /* The ld.so must be relocated since otherwise loading audit modules
1257 will fail since they reuse the very same ld.so. */
1258 assert (GL(dl_rtld_map).l_relocated);
1260 if (! rtld_is_main)
1262 /* Extract the contents of the dynamic section for easy access. */
1263 elf_get_dynamic_info (main_map, NULL);
1264 /* Set up our cache of pointers into the hash table. */
1265 _dl_setup_hash (main_map);
1268 if (__builtin_expect (mode, normal) == verify)
1270 /* We were called just to verify that this is a dynamic
1271 executable using us as the program interpreter. Exit with an
1272 error if we were not able to load the binary or no interpreter
1273 is specified (i.e., this is no dynamically linked binary. */
1274 if (main_map->l_ld == NULL)
1275 _exit (1);
1277 /* We allow here some platform specific code. */
1278 #ifdef DISTINGUISH_LIB_VERSIONS
1279 DISTINGUISH_LIB_VERSIONS;
1280 #endif
1281 _exit (has_interp ? 0 : 2);
1284 struct link_map **first_preload = &GL(dl_rtld_map).l_next;
1285 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1286 /* Set up the data structures for the system-supplied DSO early,
1287 so they can influence _dl_init_paths. */
1288 if (GLRO(dl_sysinfo_dso) != NULL)
1290 /* Do an abridged version of the work _dl_map_object_from_fd would do
1291 to map in the object. It's already mapped and prelinked (and
1292 better be, since it's read-only and so we couldn't relocate it).
1293 We just want our data structures to describe it as if we had just
1294 mapped and relocated it normally. */
1295 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL,
1296 0, LM_ID_BASE);
1297 if (__builtin_expect (l != NULL, 1))
1299 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
1301 l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1302 + GLRO(dl_sysinfo_dso)->e_phoff);
1303 l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1304 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1306 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1307 if (ph->p_type == PT_DYNAMIC)
1309 l->l_ld = (void *) ph->p_vaddr;
1310 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1312 else if (ph->p_type == PT_LOAD)
1314 if (! l->l_addr)
1315 l->l_addr = ph->p_vaddr;
1316 if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1317 l->l_map_end = ph->p_vaddr + ph->p_memsz;
1318 if ((ph->p_flags & PF_X)
1319 && ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1320 l->l_text_end = ph->p_vaddr + ph->p_memsz;
1322 else
1323 /* There must be no TLS segment. */
1324 assert (ph->p_type != PT_TLS);
1326 l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1327 l->l_addr = l->l_map_start - l->l_addr;
1328 l->l_map_end += l->l_addr;
1329 l->l_text_end += l->l_addr;
1330 l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1331 elf_get_dynamic_info (l, dyn_temp);
1332 _dl_setup_hash (l);
1333 l->l_relocated = 1;
1335 /* Initialize l_local_scope to contain just this map. This allows
1336 the use of dl_lookup_symbol_x to resolve symbols within the vdso.
1337 So we create a single entry list pointing to l_real as its only
1338 element */
1339 l->l_local_scope[0]->r_nlist = 1;
1340 l->l_local_scope[0]->r_list = &l->l_real;
1342 /* Now that we have the info handy, use the DSO image's soname
1343 so this object can be looked up by name. Note that we do not
1344 set l_name here. That field gives the file name of the DSO,
1345 and this DSO is not associated with any file. */
1346 if (l->l_info[DT_SONAME] != NULL)
1348 /* Work around a kernel problem. The kernel cannot handle
1349 addresses in the vsyscall DSO pages in writev() calls. */
1350 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1351 + l->l_info[DT_SONAME]->d_un.d_val);
1352 size_t len = strlen (dsoname);
1353 char *copy = malloc (len);
1354 if (copy == NULL)
1355 _dl_fatal_printf ("out of memory\n");
1356 l->l_libname->name = memcpy (copy, dsoname, len);
1359 /* Rearrange the list so this DSO appears after rtld_map. */
1360 assert (l->l_next == NULL);
1361 assert (l->l_prev == main_map);
1362 GL(dl_rtld_map).l_next = l;
1363 l->l_prev = &GL(dl_rtld_map);
1364 first_preload = &l->l_next;
1366 /* We have a prelinked DSO preloaded by the system. */
1367 GLRO(dl_sysinfo_map) = l;
1368 # ifdef NEED_DL_SYSINFO
1369 if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1370 GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1371 # endif
1374 #endif
1376 #ifdef DL_SYSDEP_OSCHECK
1377 DL_SYSDEP_OSCHECK (dl_fatal);
1378 #endif
1380 /* Initialize the data structures for the search paths for shared
1381 objects. */
1382 _dl_init_paths (library_path);
1384 /* Initialize _r_debug. */
1385 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1386 LM_ID_BASE);
1387 r->r_state = RT_CONSISTENT;
1389 /* Put the link_map for ourselves on the chain so it can be found by
1390 name. Note that at this point the global chain of link maps contains
1391 exactly one element, which is pointed to by dl_loaded. */
1392 if (! GL(dl_rtld_map).l_name)
1393 /* If not invoked directly, the dynamic linker shared object file was
1394 found by the PT_INTERP name. */
1395 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1396 GL(dl_rtld_map).l_type = lt_library;
1397 main_map->l_next = &GL(dl_rtld_map);
1398 GL(dl_rtld_map).l_prev = main_map;
1399 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1400 ++GL(dl_load_adds);
1402 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1403 to not using bias for non-prelinked PIEs and libraries
1404 and using it for executables or prelinked PIEs or libraries. */
1405 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1406 GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
1408 /* Set up the program header information for the dynamic linker
1409 itself. It is needed in the dl_iterate_phdr() callbacks. */
1410 #ifndef __native_client__
1411 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1412 ElfW(Phdr) *rtld_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1413 + rtld_ehdr->e_phoff);
1414 GL(dl_rtld_map).l_phdr = rtld_phdr;
1415 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1418 /* PT_GNU_RELRO is usually the last phdr. */
1419 size_t cnt = rtld_ehdr->e_phnum;
1420 while (cnt-- > 0)
1421 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1423 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1424 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1425 break;
1427 #endif
1429 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1430 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1431 /* Assign a module ID. Do this before loading any audit modules. */
1432 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1434 /* If we have auditing DSOs to load, do it now. */
1435 if (__builtin_expect (audit_list != NULL, 0))
1437 /* Iterate over all entries in the list. The order is important. */
1438 struct audit_ifaces *last_audit = NULL;
1439 struct audit_list *al = audit_list->next;
1441 /* Since we start using the auditing DSOs right away we need to
1442 initialize the data structures now. */
1443 tcbp = init_tls ();
1445 /* Initialize security features. We need to do it this early
1446 since otherwise the constructors of the audit libraries will
1447 use different values (especially the pointer guard) and will
1448 fail later on. */
1449 security_init ();
1453 int tls_idx = GL(dl_tls_max_dtv_idx);
1455 /* Now it is time to determine the layout of the static TLS
1456 block and allocate it for the initial thread. Note that we
1457 always allocate the static block, we never defer it even if
1458 no DF_STATIC_TLS bit is set. The reason is that we know
1459 glibc will use the static model. */
1460 struct dlmopen_args dlmargs;
1461 dlmargs.fname = al->name;
1462 dlmargs.map = NULL;
1464 const char *objname;
1465 const char *err_str = NULL;
1466 bool malloced;
1467 (void) _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit,
1468 &dlmargs);
1469 if (__builtin_expect (err_str != NULL, 0))
1471 not_loaded:
1472 _dl_error_printf ("\
1473 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
1474 al->name, err_str);
1475 if (malloced)
1476 free ((char *) err_str);
1478 else
1480 struct lookup_args largs;
1481 largs.name = "la_version";
1482 largs.map = dlmargs.map;
1484 /* Check whether the interface version matches. */
1485 (void) _dl_catch_error (&objname, &err_str, &malloced,
1486 lookup_doit, &largs);
1488 unsigned int (*laversion) (unsigned int);
1489 unsigned int lav;
1490 if (err_str == NULL
1491 && (laversion = largs.result) != NULL
1492 && (lav = laversion (LAV_CURRENT)) > 0
1493 && lav <= LAV_CURRENT)
1495 /* Allocate structure for the callback function pointers.
1496 This call can never fail. */
1497 union
1499 struct audit_ifaces ifaces;
1500 #define naudit_ifaces 8
1501 void (*fptr[naudit_ifaces]) (void);
1502 } *newp = malloc (sizeof (*newp));
1504 /* Names of the auditing interfaces. All in one
1505 long string. */
1506 static const char audit_iface_names[] =
1507 "la_activity\0"
1508 "la_objsearch\0"
1509 "la_objopen\0"
1510 "la_preinit\0"
1511 #if __ELF_NATIVE_CLASS == 32
1512 "la_symbind32\0"
1513 #elif __ELF_NATIVE_CLASS == 64
1514 "la_symbind64\0"
1515 #else
1516 # error "__ELF_NATIVE_CLASS must be defined"
1517 #endif
1518 #define STRING(s) __STRING (s)
1519 "la_" STRING (ARCH_LA_PLTENTER) "\0"
1520 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
1521 "la_objclose\0";
1522 unsigned int cnt = 0;
1523 const char *cp = audit_iface_names;
1526 largs.name = cp;
1527 (void) _dl_catch_error (&objname, &err_str, &malloced,
1528 lookup_doit, &largs);
1530 /* Store the pointer. */
1531 if (err_str == NULL && largs.result != NULL)
1533 newp->fptr[cnt] = largs.result;
1535 /* The dynamic linker link map is statically
1536 allocated, initialize the data now. */
1537 GL(dl_rtld_map).l_audit[cnt].cookie
1538 = (intptr_t) &GL(dl_rtld_map);
1540 else
1541 newp->fptr[cnt] = NULL;
1542 ++cnt;
1544 cp = (char *) rawmemchr (cp, '\0') + 1;
1546 while (*cp != '\0');
1547 assert (cnt == naudit_ifaces);
1549 /* Now append the new auditing interface to the list. */
1550 newp->ifaces.next = NULL;
1551 if (last_audit == NULL)
1552 last_audit = GLRO(dl_audit) = &newp->ifaces;
1553 else
1554 last_audit = last_audit->next = &newp->ifaces;
1555 ++GLRO(dl_naudit);
1557 /* Mark the DSO as being used for auditing. */
1558 dlmargs.map->l_auditing = 1;
1560 else
1562 /* We cannot use the DSO, it does not have the
1563 appropriate interfaces or it expects something
1564 more recent. */
1565 #ifndef NDEBUG
1566 Lmid_t ns = dlmargs.map->l_ns;
1567 #endif
1568 _dl_close (dlmargs.map);
1570 /* Make sure the namespace has been cleared entirely. */
1571 assert (GL(dl_ns)[ns]._ns_loaded == NULL);
1572 assert (GL(dl_ns)[ns]._ns_nloaded == 0);
1574 GL(dl_tls_max_dtv_idx) = tls_idx;
1575 goto not_loaded;
1579 al = al->next;
1581 while (al != audit_list->next);
1583 /* If we have any auditing modules, announce that we already
1584 have two objects loaded. */
1585 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1587 struct link_map *ls[2] = { main_map, &GL(dl_rtld_map) };
1589 for (unsigned int outer = 0; outer < 2; ++outer)
1591 struct audit_ifaces *afct = GLRO(dl_audit);
1592 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1594 if (afct->objopen != NULL)
1596 ls[outer]->l_audit[cnt].bindflags
1597 = afct->objopen (ls[outer], LM_ID_BASE,
1598 &ls[outer]->l_audit[cnt].cookie);
1600 ls[outer]->l_audit_any_plt
1601 |= ls[outer]->l_audit[cnt].bindflags != 0;
1604 afct = afct->next;
1610 /* Set up debugging before the debugger is notified for the first time. */
1611 #ifdef ELF_MACHINE_DEBUG_SETUP
1612 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1613 ELF_MACHINE_DEBUG_SETUP (main_map, r);
1614 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1615 #else
1616 if (main_map->l_info[DT_DEBUG] != NULL)
1617 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1618 with the run-time address of the r_debug structure */
1619 main_map->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1621 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1622 case you run gdb on the dynamic linker directly. */
1623 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1624 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1625 #endif
1627 /* We start adding objects. */
1628 r->r_state = RT_ADD;
1629 _dl_debug_state ();
1631 /* Auditing checkpoint: we are ready to signal that the initial map
1632 is being constructed. */
1633 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1635 struct audit_ifaces *afct = GLRO(dl_audit);
1636 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1638 if (afct->activity != NULL)
1639 afct->activity (&main_map->l_audit[cnt].cookie, LA_ACT_ADD);
1641 afct = afct->next;
1645 /* We have two ways to specify objects to preload: via environment
1646 variable and via the file /etc/ld.so.preload. The latter can also
1647 be used when security is enabled. */
1648 assert (*first_preload == NULL);
1649 struct link_map **preloads = NULL;
1650 unsigned int npreloads = 0;
1652 if (__builtin_expect (preloadlist != NULL, 0))
1654 /* The LD_PRELOAD environment variable gives list of libraries
1655 separated by white space or colons that are loaded before the
1656 executable's dependencies and prepended to the global scope
1657 list. If the binary is running setuid all elements
1658 containing a '/' are ignored since it is insecure. */
1659 char *list = strdupa (preloadlist);
1660 char *p;
1662 HP_TIMING_NOW (start);
1664 /* Prevent optimizing strsep. Speed is not important here. */
1665 while ((p = (strsep) (&list, " :")) != NULL)
1666 if (p[0] != '\0'
1667 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1668 || strchr (p, '/') == NULL))
1669 npreloads += do_preload (p, main_map, "LD_PRELOAD");
1671 HP_TIMING_NOW (stop);
1672 HP_TIMING_DIFF (diff, start, stop);
1673 HP_TIMING_ACCUM_NT (load_time, diff);
1676 /* There usually is no ld.so.preload file, it should only be used
1677 for emergencies and testing. So the open call etc should usually
1678 fail. Using access() on a non-existing file is faster than using
1679 open(). So we do this first. If it succeeds we do almost twice
1680 the work but this does not matter, since it is not for production
1681 use. */
1682 static const char preload_file[] = "/etc/ld.so.preload";
1683 if (__builtin_expect (__access (preload_file, R_OK) == 0, 0))
1685 /* Read the contents of the file. */
1686 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1687 PROT_READ | PROT_WRITE);
1688 if (__builtin_expect (file != MAP_FAILED, 0))
1690 /* Parse the file. It contains names of libraries to be loaded,
1691 separated by white spaces or `:'. It may also contain
1692 comments introduced by `#'. */
1693 char *problem;
1694 char *runp;
1695 size_t rest;
1697 /* Eliminate comments. */
1698 runp = file;
1699 rest = file_size;
1700 while (rest > 0)
1702 char *comment = memchr (runp, '#', rest);
1703 if (comment == NULL)
1704 break;
1706 rest -= comment - runp;
1708 *comment = ' ';
1709 while (--rest > 0 && *++comment != '\n');
1712 /* We have one problematic case: if we have a name at the end of
1713 the file without a trailing terminating characters, we cannot
1714 place the \0. Handle the case separately. */
1715 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1716 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1718 problem = &file[file_size];
1719 while (problem > file && problem[-1] != ' '
1720 && problem[-1] != '\t'
1721 && problem[-1] != '\n' && problem[-1] != ':')
1722 --problem;
1724 if (problem > file)
1725 problem[-1] = '\0';
1727 else
1729 problem = NULL;
1730 file[file_size - 1] = '\0';
1733 HP_TIMING_NOW (start);
1735 if (file != problem)
1737 char *p;
1738 runp = file;
1739 while ((p = strsep (&runp, ": \t\n")) != NULL)
1740 if (p[0] != '\0')
1741 npreloads += do_preload (p, main_map, preload_file);
1744 if (problem != NULL)
1746 char *p = strndupa (problem, file_size - (problem - file));
1748 npreloads += do_preload (p, main_map, preload_file);
1751 HP_TIMING_NOW (stop);
1752 HP_TIMING_DIFF (diff, start, stop);
1753 HP_TIMING_ACCUM_NT (load_time, diff);
1755 /* We don't need the file anymore. */
1756 __munmap (file, file_size);
1760 if (__builtin_expect (*first_preload != NULL, 0))
1762 /* Set up PRELOADS with a vector of the preloaded libraries. */
1763 struct link_map *l = *first_preload;
1764 preloads = __alloca (npreloads * sizeof preloads[0]);
1765 i = 0;
1768 preloads[i++] = l;
1769 l = l->l_next;
1770 } while (l);
1771 assert (i == npreloads);
1774 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1775 specified some libraries to load, these are inserted before the actual
1776 dependencies in the executable's searchlist for symbol resolution. */
1777 HP_TIMING_NOW (start);
1778 _dl_map_object_deps (main_map, preloads, npreloads, mode == trace, 0);
1779 HP_TIMING_NOW (stop);
1780 HP_TIMING_DIFF (diff, start, stop);
1781 HP_TIMING_ACCUM_NT (load_time, diff);
1783 /* Mark all objects as being in the global scope. */
1784 for (i = main_map->l_searchlist.r_nlist; i > 0; )
1785 main_map->l_searchlist.r_list[--i]->l_global = 1;
1787 #ifndef MAP_ANON
1788 /* We are done mapping things, so close the zero-fill descriptor. */
1789 __close (_dl_zerofd);
1790 _dl_zerofd = -1;
1791 #endif
1793 /* Remove _dl_rtld_map from the chain. */
1794 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1795 if (GL(dl_rtld_map).l_next != NULL)
1796 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1798 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1799 if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1800 break;
1802 bool rtld_multiple_ref = false;
1803 if (__builtin_expect (i < main_map->l_searchlist.r_nlist, 1))
1805 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1806 put it back in the list of visible objects. We insert it into the
1807 chain in symbol search order because gdb uses the chain's order as
1808 its symbol search order. */
1809 rtld_multiple_ref = true;
1811 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1812 if (__builtin_expect (mode, normal) == normal)
1814 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1815 ? main_map->l_searchlist.r_list[i + 1]
1816 : NULL);
1817 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1818 if (GLRO(dl_sysinfo_map) != NULL
1819 && GL(dl_rtld_map).l_prev->l_next == GLRO(dl_sysinfo_map)
1820 && GL(dl_rtld_map).l_next != GLRO(dl_sysinfo_map))
1821 GL(dl_rtld_map).l_prev = GLRO(dl_sysinfo_map);
1822 #endif
1824 else
1825 /* In trace mode there might be an invisible object (which we
1826 could not find) after the previous one in the search list.
1827 In this case it doesn't matter much where we put the
1828 interpreter object, so we just initialize the list pointer so
1829 that the assertion below holds. */
1830 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1832 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1833 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1834 if (GL(dl_rtld_map).l_next != NULL)
1836 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1837 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1841 /* Now let us see whether all libraries are available in the
1842 versions we need. */
1844 struct version_check_args args;
1845 args.doexit = mode == normal;
1846 args.dotrace = mode == trace;
1847 _dl_receive_error (print_missing_version, version_check_doit, &args);
1850 /* We do not initialize any of the TLS functionality unless any of the
1851 initial modules uses TLS. This makes dynamic loading of modules with
1852 TLS impossible, but to support it requires either eagerly doing setup
1853 now or lazily doing it later. Doing it now makes us incompatible with
1854 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1855 used. Trying to do it lazily is too hairy to try when there could be
1856 multiple threads (from a non-TLS-using libpthread). */
1857 bool was_tls_init_tp_called = tls_init_tp_called;
1858 if (tcbp == NULL)
1859 tcbp = init_tls ();
1861 if (__builtin_expect (audit_list == NULL, 1))
1862 /* Initialize security features. But only if we have not done it
1863 earlier. */
1864 security_init ();
1866 if (__builtin_expect (mode, normal) != normal)
1868 /* We were run just to list the shared libraries. It is
1869 important that we do this before real relocation, because the
1870 functions we call below for output may no longer work properly
1871 after relocation. */
1872 struct link_map *l;
1874 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1876 struct r_scope_elem *scope = &main_map->l_searchlist;
1878 for (i = 0; i < scope->r_nlist; i++)
1880 l = scope->r_list [i];
1881 if (l->l_faked)
1883 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1884 continue;
1886 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1887 GLRO(dl_trace_prelink_map) = l;
1888 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1889 l->l_libname->name[0] ? l->l_libname->name
1890 : rtld_progname ?: "<main program>",
1891 l->l_name[0] ? l->l_name
1892 : rtld_progname ?: "<main program>",
1893 (int) sizeof l->l_map_start * 2,
1894 (size_t) l->l_map_start,
1895 (int) sizeof l->l_addr * 2,
1896 (size_t) l->l_addr);
1898 if (l->l_tls_modid)
1899 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1900 (int) sizeof l->l_tls_offset * 2,
1901 (size_t) l->l_tls_offset);
1902 else
1903 _dl_printf ("\n");
1906 else if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
1908 /* Look through the dependencies of the main executable
1909 and determine which of them is not actually
1910 required. */
1911 struct link_map *l = main_map;
1913 /* Relocate the main executable. */
1914 struct relocate_args args = { .l = l, .lazy = GLRO(dl_lazy) };
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.lazy = GLRO(dl_lazy);
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 _dl_sysdep_start_cleanup ();
2192 else
2194 /* Now we have all the objects loaded. Relocate them all except for
2195 the dynamic linker itself. We do this in reverse order so that copy
2196 relocs of earlier objects overwrite the data written by later
2197 objects. We do not re-relocate the dynamic linker itself in this
2198 loop because that could result in the GOT entries for functions we
2199 call being changed, and that would break us. It is safe to relocate
2200 the dynamic linker out of order because it has no copy relocs (we
2201 know that because it is self-contained). */
2203 int consider_profiling = GLRO(dl_profile) != NULL;
2204 #ifndef HP_TIMING_NONAVAIL
2205 hp_timing_t start;
2206 hp_timing_t stop;
2207 #endif
2209 /* If we are profiling we also must do lazy reloaction. */
2210 GLRO(dl_lazy) |= consider_profiling;
2212 struct link_map *l = main_map;
2213 while (l->l_next)
2214 l = l->l_next;
2216 HP_TIMING_NOW (start);
2219 /* While we are at it, help the memory handling a bit. We have to
2220 mark some data structures as allocated with the fake malloc()
2221 implementation in ld.so. */
2222 struct libname_list *lnp = l->l_libname->next;
2224 while (__builtin_expect (lnp != NULL, 0))
2226 lnp->dont_free = 1;
2227 lnp = lnp->next;
2230 if (l != &GL(dl_rtld_map))
2231 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy),
2232 consider_profiling);
2234 /* Add object to slot information data if necessasy. */
2235 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2236 _dl_add_to_slotinfo (l);
2238 l = l->l_prev;
2240 while (l);
2241 HP_TIMING_NOW (stop);
2243 HP_TIMING_DIFF (relocate_time, start, stop);
2245 /* Do any necessary cleanups for the startup OS interface code.
2246 We do these now so that no calls are made after rtld re-relocation
2247 which might be resolved to different functions than we expect.
2248 We cannot do this before relocating the other objects because
2249 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2250 _dl_sysdep_start_cleanup ();
2252 /* Now enable profiling if needed. Like the previous call,
2253 this has to go here because the calls it makes should use the
2254 rtld versions of the functions (particularly calloc()), but it
2255 needs to have _dl_profile_map set up by the relocator. */
2256 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
2257 /* We must prepare the profiling. */
2258 _dl_start_profile ();
2261 #ifndef NONTLS_INIT_TP
2262 # define NONTLS_INIT_TP do { } while (0)
2263 #endif
2265 if (!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2266 ++GL(dl_tls_generation);
2268 /* Now that we have completed relocation, the initializer data
2269 for the TLS blocks has its final values and we can copy them
2270 into the main thread's TLS area, which we allocated above. */
2271 _dl_allocate_tls_init (tcbp);
2273 /* And finally install it for the main thread. If ld.so itself uses
2274 TLS we know the thread pointer was initialized earlier. */
2275 if (! tls_init_tp_called)
2277 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
2278 if (__builtin_expect (lossage != NULL, 0))
2279 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2280 lossage);
2283 if (! prelinked && rtld_multiple_ref)
2285 /* There was an explicit ref to the dynamic linker as a shared lib.
2286 Re-relocate ourselves with user-controlled symbol definitions.
2288 We must do this after TLS initialization in case after this
2289 re-relocation, we might call a user-supplied function
2290 (e.g. calloc from _dl_relocate_object) that uses TLS data. */
2292 #ifndef HP_TIMING_NONAVAIL
2293 hp_timing_t start;
2294 hp_timing_t stop;
2295 hp_timing_t add;
2296 #endif
2298 HP_TIMING_NOW (start);
2299 /* Mark the link map as not yet relocated again. */
2300 GL(dl_rtld_map).l_relocated = 0;
2301 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2302 HP_TIMING_NOW (stop);
2303 HP_TIMING_DIFF (add, start, stop);
2304 HP_TIMING_ACCUM_NT (relocate_time, add);
2307 #ifdef SHARED
2308 /* Auditing checkpoint: we have added all objects. */
2309 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
2311 struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2312 /* Do not call the functions for any auditing object. */
2313 if (head->l_auditing == 0)
2315 struct audit_ifaces *afct = GLRO(dl_audit);
2316 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2318 if (afct->activity != NULL)
2319 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
2321 afct = afct->next;
2325 #endif
2327 /* Notify the debugger all new objects are now ready to go. We must re-get
2328 the address since by now the variable might be in another object. */
2329 r = _dl_debug_initialize (0, LM_ID_BASE);
2330 r->r_state = RT_CONSISTENT;
2331 _dl_debug_state ();
2333 #ifndef MAP_COPY
2334 /* We must munmap() the cache file. */
2335 _dl_unload_cache ();
2336 #endif
2338 /* Once we return, _dl_sysdep_start will invoke
2339 the DT_INIT functions and then *USER_ENTRY. */
2342 /* This is a little helper function for resolving symbols while
2343 tracing the binary. */
2344 static void
2345 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2346 const char *errstring)
2348 if (objname[0] == '\0')
2349 objname = rtld_progname ?: "<main program>";
2350 _dl_error_printf ("%s (%s)\n", errstring, objname);
2353 /* This is a little helper function for resolving symbols while
2354 tracing the binary. */
2355 static void
2356 print_missing_version (int errcode __attribute__ ((unused)),
2357 const char *objname, const char *errstring)
2359 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
2360 objname, errstring);
2363 /* Nonzero if any of the debugging options is enabled. */
2364 static int any_debug attribute_relro;
2366 /* Process the string given as the parameter which explains which debugging
2367 options are enabled. */
2368 static void
2369 process_dl_debug (const char *dl_debug)
2371 /* When adding new entries make sure that the maximal length of a name
2372 is correctly handled in the LD_DEBUG_HELP code below. */
2373 static const struct
2375 unsigned char len;
2376 const char name[10];
2377 const char helptext[41];
2378 unsigned short int mask;
2379 } debopts[] =
2381 #define LEN_AND_STR(str) sizeof (str) - 1, str
2382 { LEN_AND_STR ("libs"), "display library search paths",
2383 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2384 { LEN_AND_STR ("reloc"), "display relocation processing",
2385 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2386 { LEN_AND_STR ("files"), "display progress for input file",
2387 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2388 { LEN_AND_STR ("symbols"), "display symbol table processing",
2389 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2390 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2391 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2392 { LEN_AND_STR ("versions"), "display version dependencies",
2393 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2394 { LEN_AND_STR ("all"), "all previous options combined",
2395 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2396 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2397 { LEN_AND_STR ("statistics"), "display relocation statistics",
2398 DL_DEBUG_STATISTICS },
2399 { LEN_AND_STR ("unused"), "determined unused DSOs",
2400 DL_DEBUG_UNUSED },
2401 { LEN_AND_STR ("help"), "display this help message and exit",
2402 DL_DEBUG_HELP },
2404 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2406 /* Skip separating white spaces and commas. */
2407 while (*dl_debug != '\0')
2409 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2411 size_t cnt;
2412 size_t len = 1;
2414 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2415 && dl_debug[len] != ',' && dl_debug[len] != ':')
2416 ++len;
2418 for (cnt = 0; cnt < ndebopts; ++cnt)
2419 if (debopts[cnt].len == len
2420 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
2422 GLRO(dl_debug_mask) |= debopts[cnt].mask;
2423 any_debug = 1;
2424 break;
2427 if (cnt == ndebopts)
2429 /* Display a warning and skip everything until next
2430 separator. */
2431 char *copy = strndupa (dl_debug, len);
2432 _dl_error_printf ("\
2433 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2436 dl_debug += len;
2437 continue;
2440 ++dl_debug;
2443 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
2445 size_t cnt;
2447 _dl_printf ("\
2448 Valid options for the LD_DEBUG environment variable are:\n\n");
2450 for (cnt = 0; cnt < ndebopts; ++cnt)
2451 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2452 " " + debopts[cnt].len - 3,
2453 debopts[cnt].helptext);
2455 _dl_printf ("\n\
2456 To direct the debugging output into a file instead of standard output\n\
2457 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2458 _exit (0);
2462 static void
2463 process_dl_audit (char *str)
2465 /* The parameter is a colon separated list of DSO names. */
2466 char *p;
2468 while ((p = (strsep) (&str, ":")) != NULL)
2469 if (p[0] != '\0'
2470 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
2471 || strchr (p, '/') == NULL))
2473 /* This is using the local malloc, not the system malloc. The
2474 memory can never be freed. */
2475 struct audit_list *newp = malloc (sizeof (*newp));
2476 newp->name = p;
2478 if (audit_list == NULL)
2479 audit_list = newp->next = newp;
2480 else
2482 newp->next = audit_list->next;
2483 audit_list = audit_list->next = newp;
2488 /* Process all environments variables the dynamic linker must recognize.
2489 Since all of them start with `LD_' we are a bit smarter while finding
2490 all the entries. */
2491 extern char **_environ attribute_hidden;
2494 static void
2495 process_envvars (enum mode *modep)
2497 char **runp = _environ;
2498 char *envline;
2499 enum mode mode = normal;
2500 char *debug_output = NULL;
2502 /* This is the default place for profiling data file. */
2503 GLRO(dl_profile_output)
2504 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2506 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2508 size_t len = 0;
2510 while (envline[len] != '\0' && envline[len] != '=')
2511 ++len;
2513 if (envline[len] != '=')
2514 /* This is a "LD_" variable at the end of the string without
2515 a '=' character. Ignore it since otherwise we will access
2516 invalid memory below. */
2517 continue;
2519 switch (len)
2521 case 4:
2522 /* Warning level, verbose or not. */
2523 if (memcmp (envline, "WARN", 4) == 0)
2524 GLRO(dl_verbose) = envline[5] != '\0';
2525 break;
2527 case 5:
2528 /* Debugging of the dynamic linker? */
2529 if (memcmp (envline, "DEBUG", 5) == 0)
2531 process_dl_debug (&envline[6]);
2532 break;
2534 if (memcmp (envline, "AUDIT", 5) == 0)
2535 process_dl_audit (&envline[6]);
2536 break;
2538 case 7:
2539 /* Print information about versions. */
2540 if (memcmp (envline, "VERBOSE", 7) == 0)
2542 version_info = envline[8] != '\0';
2543 break;
2546 /* List of objects to be preloaded. */
2547 if (memcmp (envline, "PRELOAD", 7) == 0)
2549 preloadlist = &envline[8];
2550 break;
2553 /* Which shared object shall be profiled. */
2554 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2555 GLRO(dl_profile) = &envline[8];
2556 break;
2558 case 8:
2559 /* Do we bind early? */
2560 if (memcmp (envline, "BIND_NOW", 8) == 0)
2562 GLRO(dl_lazy) = envline[9] == '\0';
2563 break;
2565 if (memcmp (envline, "BIND_NOT", 8) == 0)
2566 GLRO(dl_bind_not) = envline[9] != '\0';
2567 break;
2569 case 9:
2570 /* Test whether we want to see the content of the auxiliary
2571 array passed up from the kernel. */
2572 if (!INTUSE(__libc_enable_secure)
2573 && memcmp (envline, "SHOW_AUXV", 9) == 0)
2574 _dl_show_auxv ();
2575 break;
2577 case 10:
2578 /* Mask for the important hardware capabilities. */
2579 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2580 GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2581 0, 0);
2582 break;
2584 case 11:
2585 /* Path where the binary is found. */
2586 if (!INTUSE(__libc_enable_secure)
2587 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2588 GLRO(dl_origin_path) = &envline[12];
2589 break;
2591 case 12:
2592 /* The library search path. */
2593 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2595 library_path = &envline[13];
2596 break;
2599 /* Where to place the profiling data file. */
2600 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2602 debug_output = &envline[13];
2603 break;
2606 if (!INTUSE(__libc_enable_secure)
2607 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2608 GLRO(dl_dynamic_weak) = 1;
2609 break;
2611 case 13:
2612 /* We might have some extra environment variable with length 13
2613 to handle. */
2614 #ifdef EXTRA_LD_ENVVARS_13
2615 EXTRA_LD_ENVVARS_13
2616 #endif
2617 if (!INTUSE(__libc_enable_secure)
2618 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2620 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2621 break;
2624 if (memcmp (envline, "POINTER_GUARD", 13) == 0)
2625 GLRO(dl_pointer_guard) = envline[14] != '0';
2626 break;
2628 case 14:
2629 /* Where to place the profiling data file. */
2630 if (!INTUSE(__libc_enable_secure)
2631 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2632 && envline[15] != '\0')
2633 GLRO(dl_profile_output) = &envline[15];
2634 break;
2636 case 16:
2637 /* The mode of the dynamic linker can be set. */
2638 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2640 mode = trace;
2641 GLRO(dl_verbose) = 1;
2642 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2643 GLRO(dl_trace_prelink) = &envline[17];
2645 break;
2647 case 20:
2648 /* The mode of the dynamic linker can be set. */
2649 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2650 mode = trace;
2651 break;
2653 /* We might have some extra environment variable to handle. This
2654 is tricky due to the pre-processing of the length of the name
2655 in the switch statement here. The code here assumes that added
2656 environment variables have a different length. */
2657 #ifdef EXTRA_LD_ENVVARS
2658 EXTRA_LD_ENVVARS
2659 #endif
2663 /* The caller wants this information. */
2664 *modep = mode;
2666 /* Extra security for SUID binaries. Remove all dangerous environment
2667 variables. */
2668 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2670 static const char unsecure_envvars[] =
2671 #ifdef EXTRA_UNSECURE_ENVVARS
2672 EXTRA_UNSECURE_ENVVARS
2673 #endif
2674 UNSECURE_ENVVARS;
2675 const char *nextp;
2677 nextp = unsecure_envvars;
2680 unsetenv (nextp);
2681 /* We could use rawmemchr but this need not be fast. */
2682 nextp = (char *) (strchr) (nextp, '\0') + 1;
2684 while (*nextp != '\0');
2686 if (__access ("/etc/suid-debug", F_OK) != 0)
2688 unsetenv ("MALLOC_CHECK_");
2689 GLRO(dl_debug_mask) = 0;
2692 if (mode != normal)
2693 _exit (5);
2695 /* If we have to run the dynamic linker in debugging mode and the
2696 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2697 messages to this file. */
2698 else if (any_debug && debug_output != NULL)
2700 #ifdef O_NOFOLLOW
2701 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2702 #else
2703 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2704 #endif
2705 size_t name_len = strlen (debug_output);
2706 char buf[name_len + 12];
2707 char *startp;
2709 buf[name_len + 11] = '\0';
2710 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2711 *--startp = '.';
2712 startp = memcpy (startp - name_len, debug_output, name_len);
2714 GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2715 if (GLRO(dl_debug_fd) == -1)
2716 /* We use standard output if opening the file failed. */
2717 GLRO(dl_debug_fd) = STDOUT_FILENO;
2722 /* Print the various times we collected. */
2723 static void
2724 __attribute ((noinline))
2725 print_statistics (hp_timing_t *rtld_total_timep)
2727 #ifndef HP_TIMING_NONAVAIL
2728 char buf[200];
2729 char *cp;
2730 char *wp;
2732 /* Total time rtld used. */
2733 if (HP_TIMING_AVAIL)
2735 HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2736 _dl_debug_printf ("\nruntime linker statistics:\n"
2737 " total startup time in dynamic loader: %s\n", buf);
2739 /* Print relocation statistics. */
2740 char pbuf[30];
2741 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2742 cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2743 pbuf + sizeof (pbuf), 10, 0);
2744 wp = pbuf;
2745 switch (pbuf + sizeof (pbuf) - cp)
2747 case 3:
2748 *wp++ = *cp++;
2749 case 2:
2750 *wp++ = *cp++;
2751 case 1:
2752 *wp++ = '.';
2753 *wp++ = *cp++;
2755 *wp = '\0';
2756 _dl_debug_printf ("\
2757 time needed for relocation: %s (%s%%)\n", buf, pbuf);
2759 #endif
2761 unsigned long int num_relative_relocations = 0;
2762 for (Lmid_t ns = 0; ns < DL_NNS; ++ns)
2764 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2765 continue;
2767 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2769 for (unsigned int i = 0; i < scope->r_nlist; i++)
2771 struct link_map *l = scope->r_list [i];
2773 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2774 num_relative_relocations
2775 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2776 #ifndef ELF_MACHINE_REL_RELATIVE
2777 /* Relative relocations are processed on these architectures if
2778 library is loaded to different address than p_vaddr or
2779 if not prelinked. */
2780 if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2781 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2782 #else
2783 /* On e.g. IA-64 or Alpha, relative relocations are processed
2784 only if library is loaded to different address than p_vaddr. */
2785 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2786 #endif
2787 num_relative_relocations
2788 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2792 _dl_debug_printf (" number of relocations: %lu\n"
2793 " number of relocations from cache: %lu\n"
2794 " number of relative relocations: %lu\n",
2795 GL(dl_num_relocations),
2796 GL(dl_num_cache_relocations),
2797 num_relative_relocations);
2799 #ifndef HP_TIMING_NONAVAIL
2800 /* Time spend while loading the object and the dependencies. */
2801 if (HP_TIMING_AVAIL)
2803 char pbuf[30];
2804 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2805 cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2806 pbuf + sizeof (pbuf), 10, 0);
2807 wp = pbuf;
2808 switch (pbuf + sizeof (pbuf) - cp)
2810 case 3:
2811 *wp++ = *cp++;
2812 case 2:
2813 *wp++ = *cp++;
2814 case 1:
2815 *wp++ = '.';
2816 *wp++ = *cp++;
2818 *wp = '\0';
2819 _dl_debug_printf ("\
2820 time needed to load objects: %s (%s%%)\n",
2821 buf, pbuf);
2823 #endif