Fix errno for IBM long double.
[glibc.git] / elf / rtld.c
blobf97de9ac08a2beb6753b13c4618f1397f066f58e
1 /* Run time dynamic linker.
2 Copyright (C) 1995-2006, 2007, 2008, 2009 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18 02111-1307 USA. */
20 #include <errno.h>
21 #include <dlfcn.h>
22 #include <fcntl.h>
23 #include <stdbool.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <sys/mman.h>
28 #include <sys/param.h>
29 #include <sys/stat.h>
30 #include <ldsodefs.h>
31 #include <stdio-common/_itoa.h>
32 #include <entry.h>
33 #include <fpu_control.h>
34 #include <hp-timing.h>
35 #include <bits/libc-lock.h>
36 #include "dynamic-link.h"
37 #include <dl-librecon.h>
38 #include <unsecvars.h>
39 #include <dl-cache.h>
40 #include <dl-osinfo.h>
41 #include <dl-procinfo.h>
42 #include <tls.h>
44 #include <assert.h>
46 /* Avoid PLT use for our local calls at startup. */
47 extern __typeof (__mempcpy) __mempcpy attribute_hidden;
49 /* GCC has mental blocks about _exit. */
50 extern __typeof (_exit) exit_internal asm ("_exit") attribute_hidden;
51 #define _exit exit_internal
53 /* Helper function to handle errors while resolving symbols. */
54 static void print_unresolved (int errcode, const char *objname,
55 const char *errsting);
57 /* Helper function to handle errors when a version is missing. */
58 static void print_missing_version (int errcode, const char *objname,
59 const char *errsting);
61 /* Print the various times we collected. */
62 static void print_statistics (hp_timing_t *total_timep);
64 /* Add audit objects. */
65 static void process_dl_audit (char *str);
67 /* This is a list of all the modes the dynamic loader can be in. */
68 enum mode { normal, list, verify, trace };
70 /* Process all environments variables the dynamic linker must recognize.
71 Since all of them start with `LD_' we are a bit smarter while finding
72 all the entries. */
73 static void process_envvars (enum mode *modep);
75 #ifdef DL_ARGV_NOT_RELRO
76 int _dl_argc attribute_hidden;
77 char **_dl_argv = NULL;
78 /* Nonzero if we were run directly. */
79 unsigned int _dl_skip_args attribute_hidden;
80 #else
81 int _dl_argc attribute_relro attribute_hidden;
82 char **_dl_argv attribute_relro = NULL;
83 unsigned int _dl_skip_args attribute_relro attribute_hidden;
84 #endif
85 INTDEF(_dl_argv)
87 #ifndef THREAD_SET_STACK_GUARD
88 /* Only exported for architectures that don't store the stack guard canary
89 in thread local area. */
90 uintptr_t __stack_chk_guard attribute_relro;
91 #endif
93 /* Only exported for architectures that don't store the pointer guard
94 value in thread local area. */
95 uintptr_t __pointer_chk_guard_local
96 attribute_relro attribute_hidden __attribute__ ((nocommon));
97 #ifndef THREAD_SET_POINTER_GUARD
98 strong_alias (__pointer_chk_guard_local, __pointer_chk_guard)
99 #endif
102 /* List of auditing DSOs. */
103 static struct audit_list
105 const char *name;
106 struct audit_list *next;
107 } *audit_list;
109 #ifndef HAVE_INLINED_SYSCALLS
110 /* Set nonzero during loading and initialization of executable and
111 libraries, cleared before the executable's entry point runs. This
112 must not be initialized to nonzero, because the unused dynamic
113 linker loaded in for libc.so's "ld.so.1" dep will provide the
114 definition seen by libc.so's initializer; that value must be zero,
115 and will be since that dynamic linker's _dl_start and dl_main will
116 never be called. */
117 int _dl_starting_up = 0;
118 INTVARDEF(_dl_starting_up)
119 #endif
121 /* This is the structure which defines all variables global to ld.so
122 (except those which cannot be added for some reason). */
123 struct rtld_global _rtld_global =
125 /* Default presumption without further information is executable stack. */
126 ._dl_stack_flags = PF_R|PF_W|PF_X,
127 #ifdef _LIBC_REENTRANT
128 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
129 #endif
130 ._dl_nns = 1
132 /* If we would use strong_alias here the compiler would see a
133 non-hidden definition. This would undo the effect of the previous
134 declaration. So spell out was strong_alias does plus add the
135 visibility attribute. */
136 extern struct rtld_global _rtld_local
137 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
140 /* This variable is similar to _rtld_local, but all values are
141 read-only after relocation. */
142 struct rtld_global_ro _rtld_global_ro attribute_relro =
144 /* Get architecture specific initializer. */
145 #include <dl-procinfo.c>
146 #ifdef NEED_DL_SYSINFO
147 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
148 #endif
149 ._dl_debug_fd = STDERR_FILENO,
150 ._dl_use_load_bias = -2,
151 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
152 ._dl_hwcap_mask = HWCAP_IMPORTANT,
153 ._dl_lazy = 1,
154 ._dl_fpu_control = _FPU_DEFAULT,
155 ._dl_pointer_guard = 1,
157 /* Function pointers. */
158 ._dl_debug_printf = _dl_debug_printf,
159 ._dl_catch_error = _dl_catch_error,
160 ._dl_signal_error = _dl_signal_error,
161 ._dl_mcount = _dl_mcount_internal,
162 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
163 ._dl_check_caller = _dl_check_caller,
164 ._dl_open = _dl_open,
165 ._dl_close = _dl_close,
166 ._dl_tls_get_addr_soft = _dl_tls_get_addr_soft,
167 #ifdef HAVE_DL_DISCOVER_OSVERSION
168 ._dl_discover_osversion = _dl_discover_osversion
169 #endif
171 /* If we would use strong_alias here the compiler would see a
172 non-hidden definition. This would undo the effect of the previous
173 declaration. So spell out was strong_alias does plus add the
174 visibility attribute. */
175 extern struct rtld_global_ro _rtld_local_ro
176 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
179 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
180 ElfW(Addr) *user_entry);
182 /* These two variables cannot be moved into .data.rel.ro. */
183 static struct libname_list _dl_rtld_libname;
184 static struct libname_list _dl_rtld_libname2;
186 /* We expect less than a second for relocation. */
187 #ifdef HP_SMALL_TIMING_AVAIL
188 # undef HP_TIMING_AVAIL
189 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
190 #endif
192 /* Variable for statistics. */
193 #ifndef HP_TIMING_NONAVAIL
194 static hp_timing_t relocate_time;
195 static hp_timing_t load_time attribute_relro;
196 static hp_timing_t start_time attribute_relro;
197 #endif
199 /* Additional definitions needed by TLS initialization. */
200 #ifdef TLS_INIT_HELPER
201 TLS_INIT_HELPER
202 #endif
204 /* Helper function for syscall implementation. */
205 #ifdef DL_SYSINFO_IMPLEMENTATION
206 DL_SYSINFO_IMPLEMENTATION
207 #endif
209 /* Before ld.so is relocated we must not access variables which need
210 relocations. This means variables which are exported. Variables
211 declared as static are fine. If we can mark a variable hidden this
212 is fine, too. The latter is important here. We can avoid setting
213 up a temporary link map for ld.so if we can mark _rtld_global as
214 hidden. */
215 #ifdef PI_STATIC_AND_HIDDEN
216 # define DONT_USE_BOOTSTRAP_MAP 1
217 #endif
219 #ifdef DONT_USE_BOOTSTRAP_MAP
220 static ElfW(Addr) _dl_start_final (void *arg);
221 #else
222 struct dl_start_final_info
224 struct link_map l;
225 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
226 hp_timing_t start_time;
227 #endif
229 static ElfW(Addr) _dl_start_final (void *arg,
230 struct dl_start_final_info *info);
231 #endif
233 /* These defined magically in the linker script. */
234 extern char _begin[] attribute_hidden;
235 extern char _etext[] attribute_hidden;
236 extern char _end[] attribute_hidden;
239 #ifdef RTLD_START
240 RTLD_START
241 #else
242 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
243 #endif
245 #ifndef VALIDX
246 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
247 + DT_EXTRANUM + DT_VALTAGIDX (tag))
248 #endif
249 #ifndef ADDRIDX
250 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
251 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
252 #endif
254 /* This is the second half of _dl_start (below). It can be inlined safely
255 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
256 references. When the tools don't permit us to avoid using a GOT entry
257 for _dl_rtld_global (no attribute_hidden support), we must make sure
258 this function is not inlined (see below). */
260 #ifdef DONT_USE_BOOTSTRAP_MAP
261 static inline ElfW(Addr) __attribute__ ((always_inline))
262 _dl_start_final (void *arg)
263 #else
264 static ElfW(Addr) __attribute__ ((noinline))
265 _dl_start_final (void *arg, struct dl_start_final_info *info)
266 #endif
268 ElfW(Addr) start_addr;
270 if (HP_TIMING_AVAIL)
272 /* If it hasn't happen yet record the startup time. */
273 if (! HP_TIMING_INLINE)
274 HP_TIMING_NOW (start_time);
275 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
276 else
277 start_time = info->start_time;
278 #endif
280 /* Initialize the timing functions. */
281 HP_TIMING_DIFF_INIT ();
284 /* Transfer data about ourselves to the permanent link_map structure. */
285 #ifndef DONT_USE_BOOTSTRAP_MAP
286 GL(dl_rtld_map).l_addr = info->l.l_addr;
287 GL(dl_rtld_map).l_ld = info->l.l_ld;
288 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
289 sizeof GL(dl_rtld_map).l_info);
290 GL(dl_rtld_map).l_mach = info->l.l_mach;
291 GL(dl_rtld_map).l_relocated = 1;
292 #endif
293 _dl_setup_hash (&GL(dl_rtld_map));
294 GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
295 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
296 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
297 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
298 /* Copy the TLS related data if necessary. */
299 #ifndef DONT_USE_BOOTSTRAP_MAP
300 # if USE___THREAD
301 assert (info->l.l_tls_modid != 0);
302 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
303 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
304 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
305 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
306 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
307 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
308 GL(dl_rtld_map).l_tls_modid = 1;
309 # else
310 # if NO_TLS_OFFSET != 0
311 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
312 # endif
313 # endif
315 #endif
317 #if HP_TIMING_AVAIL
318 HP_TIMING_NOW (GL(dl_cpuclock_offset));
319 #endif
321 /* Initialize the stack end variable. */
322 __libc_stack_end = __builtin_frame_address (0);
324 /* Call the OS-dependent function to set up life so we can do things like
325 file access. It will call `dl_main' (below) to do all the real work
326 of the dynamic linker, and then unwind our frame and run the user
327 entry point on the same stack we entered on. */
328 start_addr = _dl_sysdep_start (arg, &dl_main);
330 #ifndef HP_TIMING_NONAVAIL
331 hp_timing_t rtld_total_time;
332 if (HP_TIMING_AVAIL)
334 hp_timing_t end_time;
336 /* Get the current time. */
337 HP_TIMING_NOW (end_time);
339 /* Compute the difference. */
340 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
342 #endif
344 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
346 #ifndef HP_TIMING_NONAVAIL
347 print_statistics (&rtld_total_time);
348 #else
349 print_statistics (NULL);
350 #endif
353 return start_addr;
356 static ElfW(Addr) __attribute_used__ internal_function
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 reloc_mode;
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->reloc_mode, 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 (_dl_random);
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 uintptr_t pointer_chk_guard = _dl_setup_pointer_guard (_dl_random,
856 stack_chk_guard);
857 #ifdef THREAD_SET_POINTER_GUARD
858 THREAD_SET_POINTER_GUARD (pointer_chk_guard);
859 #endif
860 __pointer_chk_guard_local = pointer_chk_guard;
863 /* We do not need the _dl_random value anymore. The less
864 information we leave behind, the better, so clear the
865 variable. */
866 _dl_random = NULL;
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\
1016 --audit LIST use objects named in LIST as auditors\n");
1018 ++_dl_skip_args;
1019 --_dl_argc;
1020 ++INTUSE(_dl_argv);
1022 /* The initialization of _dl_stack_flags done below assumes the
1023 executable's PT_GNU_STACK may have been honored by the kernel, and
1024 so a PT_GNU_STACK with PF_X set means the stack started out with
1025 execute permission. However, this is not really true if the
1026 dynamic linker is the executable the kernel loaded. For this
1027 case, we must reinitialize _dl_stack_flags to match the dynamic
1028 linker itself. If the dynamic linker was built with a
1029 PT_GNU_STACK, then the kernel may have loaded us with a
1030 nonexecutable stack that we will have to make executable when we
1031 load the program below unless it has a PT_GNU_STACK indicating
1032 nonexecutable stack is ok. */
1034 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1035 if (ph->p_type == PT_GNU_STACK)
1037 GL(dl_stack_flags) = ph->p_flags;
1038 break;
1041 if (__builtin_expect (mode, normal) == verify)
1043 const char *objname;
1044 const char *err_str = NULL;
1045 struct map_args args;
1046 bool malloced;
1048 args.str = rtld_progname;
1049 args.loader = NULL;
1050 args.is_preloaded = 0;
1051 args.mode = __RTLD_OPENEXEC;
1052 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
1053 &args);
1054 if (__builtin_expect (err_str != NULL, 0))
1055 /* We don't free the returned string, the programs stops
1056 anyway. */
1057 _exit (EXIT_FAILURE);
1059 else
1061 HP_TIMING_NOW (start);
1062 _dl_map_object (NULL, rtld_progname, 0, lt_library, 0,
1063 __RTLD_OPENEXEC, LM_ID_BASE);
1064 HP_TIMING_NOW (stop);
1066 HP_TIMING_DIFF (load_time, start, stop);
1069 /* Now the map for the main executable is available. */
1070 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1072 phdr = main_map->l_phdr;
1073 phnum = main_map->l_phnum;
1074 /* We overwrite here a pointer to a malloc()ed string. But since
1075 the malloc() implementation used at this point is the dummy
1076 implementations which has no real free() function it does not
1077 makes sense to free the old string first. */
1078 main_map->l_name = (char *) "";
1079 *user_entry = main_map->l_entry;
1081 else
1083 /* Create a link_map for the executable itself.
1084 This will be what dlopen on "" returns. */
1085 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1086 __RTLD_OPENEXEC, LM_ID_BASE);
1087 assert (main_map != NULL);
1088 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
1089 main_map->l_phdr = phdr;
1090 main_map->l_phnum = phnum;
1091 main_map->l_entry = *user_entry;
1093 /* At this point we are in a bit of trouble. We would have to
1094 fill in the values for l_dev and l_ino. But in general we
1095 do not know where the file is. We also do not handle AT_EXECFD
1096 even if it would be passed up.
1098 We leave the values here defined to 0. This is normally no
1099 problem as the program code itself is normally no shared
1100 object and therefore cannot be loaded dynamically. Nothing
1101 prevent the use of dynamic binaries and in these situations
1102 we might get problems. We might not be able to find out
1103 whether the object is already loaded. But since there is no
1104 easy way out and because the dynamic binary must also not
1105 have an SONAME we ignore this program for now. If it becomes
1106 a problem we can force people using SONAMEs. */
1108 /* We delay initializing the path structure until we got the dynamic
1109 information for the program. */
1112 main_map->l_map_end = 0;
1113 main_map->l_text_end = 0;
1114 /* Perhaps the executable has no PT_LOAD header entries at all. */
1115 main_map->l_map_start = ~0;
1116 /* And it was opened directly. */
1117 ++main_map->l_direct_opencount;
1119 /* Scan the program header table for the dynamic section. */
1120 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1121 switch (ph->p_type)
1123 case PT_PHDR:
1124 /* Find out the load address. */
1125 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1126 break;
1127 case PT_DYNAMIC:
1128 /* This tells us where to find the dynamic section,
1129 which tells us everything we need to do. */
1130 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
1131 break;
1132 case PT_INTERP:
1133 /* This "interpreter segment" was used by the program loader to
1134 find the program interpreter, which is this program itself, the
1135 dynamic linker. We note what name finds us, so that a future
1136 dlopen call or DT_NEEDED entry, for something that wants to link
1137 against the dynamic linker as a shared library, will know that
1138 the shared object is already loaded. */
1139 _dl_rtld_libname.name = ((const char *) main_map->l_addr
1140 + ph->p_vaddr);
1141 /* _dl_rtld_libname.next = NULL; Already zero. */
1142 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1144 /* Ordinarilly, we would get additional names for the loader from
1145 our DT_SONAME. This can't happen if we were actually linked as
1146 a static executable (detect this case when we have no DYNAMIC).
1147 If so, assume the filename component of the interpreter path to
1148 be our SONAME, and add it to our name list. */
1149 if (GL(dl_rtld_map).l_ld == NULL)
1151 const char *p = NULL;
1152 const char *cp = _dl_rtld_libname.name;
1154 /* Find the filename part of the path. */
1155 while (*cp != '\0')
1156 if (*cp++ == '/')
1157 p = cp;
1159 if (p != NULL)
1161 _dl_rtld_libname2.name = p;
1162 /* _dl_rtld_libname2.next = NULL; Already zero. */
1163 _dl_rtld_libname.next = &_dl_rtld_libname2;
1167 has_interp = true;
1168 break;
1169 case PT_LOAD:
1171 ElfW(Addr) mapstart;
1172 ElfW(Addr) allocend;
1174 /* Remember where the main program starts in memory. */
1175 mapstart = (main_map->l_addr
1176 + (ph->p_vaddr & ~(GLRO(dl_pagesize) - 1)));
1177 if (main_map->l_map_start > mapstart)
1178 main_map->l_map_start = mapstart;
1180 /* Also where it ends. */
1181 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1182 if (main_map->l_map_end < allocend)
1183 main_map->l_map_end = allocend;
1184 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1185 main_map->l_text_end = allocend;
1187 break;
1189 case PT_TLS:
1190 if (ph->p_memsz > 0)
1192 /* Note that in the case the dynamic linker we duplicate work
1193 here since we read the PT_TLS entry already in
1194 _dl_start_final. But the result is repeatable so do not
1195 check for this special but unimportant case. */
1196 main_map->l_tls_blocksize = ph->p_memsz;
1197 main_map->l_tls_align = ph->p_align;
1198 if (ph->p_align == 0)
1199 main_map->l_tls_firstbyte_offset = 0;
1200 else
1201 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1202 & (ph->p_align - 1));
1203 main_map->l_tls_initimage_size = ph->p_filesz;
1204 main_map->l_tls_initimage = (void *) ph->p_vaddr;
1206 /* This image gets the ID one. */
1207 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1209 break;
1211 case PT_GNU_STACK:
1212 GL(dl_stack_flags) = ph->p_flags;
1213 break;
1215 case PT_GNU_RELRO:
1216 main_map->l_relro_addr = ph->p_vaddr;
1217 main_map->l_relro_size = ph->p_memsz;
1218 break;
1221 /* Adjust the address of the TLS initialization image in case
1222 the executable is actually an ET_DYN object. */
1223 if (main_map->l_tls_initimage != NULL)
1224 main_map->l_tls_initimage
1225 = (char *) main_map->l_tls_initimage + main_map->l_addr;
1226 if (! main_map->l_map_end)
1227 main_map->l_map_end = ~0;
1228 if (! main_map->l_text_end)
1229 main_map->l_text_end = ~0;
1230 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1232 /* We were invoked directly, so the program might not have a
1233 PT_INTERP. */
1234 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1235 /* _dl_rtld_libname.next = NULL; Already zero. */
1236 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1238 else
1239 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1241 /* If the current libname is different from the SONAME, add the
1242 latter as well. */
1243 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1244 && strcmp (GL(dl_rtld_map).l_libname->name,
1245 (const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1246 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1248 static struct libname_list newname;
1249 newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1250 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1251 newname.next = NULL;
1252 newname.dont_free = 1;
1254 assert (GL(dl_rtld_map).l_libname->next == NULL);
1255 GL(dl_rtld_map).l_libname->next = &newname;
1257 /* The ld.so must be relocated since otherwise loading audit modules
1258 will fail since they reuse the very same ld.so. */
1259 assert (GL(dl_rtld_map).l_relocated);
1261 if (! rtld_is_main)
1263 /* Extract the contents of the dynamic section for easy access. */
1264 elf_get_dynamic_info (main_map, NULL);
1265 /* Set up our cache of pointers into the hash table. */
1266 _dl_setup_hash (main_map);
1269 if (__builtin_expect (mode, normal) == verify)
1271 /* We were called just to verify that this is a dynamic
1272 executable using us as the program interpreter. Exit with an
1273 error if we were not able to load the binary or no interpreter
1274 is specified (i.e., this is no dynamically linked binary. */
1275 if (main_map->l_ld == NULL)
1276 _exit (1);
1278 /* We allow here some platform specific code. */
1279 #ifdef DISTINGUISH_LIB_VERSIONS
1280 DISTINGUISH_LIB_VERSIONS;
1281 #endif
1282 _exit (has_interp ? 0 : 2);
1285 struct link_map **first_preload = &GL(dl_rtld_map).l_next;
1286 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1287 /* Set up the data structures for the system-supplied DSO early,
1288 so they can influence _dl_init_paths. */
1289 if (GLRO(dl_sysinfo_dso) != NULL)
1291 /* Do an abridged version of the work _dl_map_object_from_fd would do
1292 to map in the object. It's already mapped and prelinked (and
1293 better be, since it's read-only and so we couldn't relocate it).
1294 We just want our data structures to describe it as if we had just
1295 mapped and relocated it normally. */
1296 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL,
1297 0, LM_ID_BASE);
1298 if (__builtin_expect (l != NULL, 1))
1300 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
1302 l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1303 + GLRO(dl_sysinfo_dso)->e_phoff);
1304 l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1305 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1307 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1308 if (ph->p_type == PT_DYNAMIC)
1310 l->l_ld = (void *) ph->p_vaddr;
1311 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1313 else if (ph->p_type == PT_LOAD)
1315 if (! l->l_addr)
1316 l->l_addr = ph->p_vaddr;
1317 if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1318 l->l_map_end = ph->p_vaddr + ph->p_memsz;
1319 if ((ph->p_flags & PF_X)
1320 && ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1321 l->l_text_end = ph->p_vaddr + ph->p_memsz;
1323 else
1324 /* There must be no TLS segment. */
1325 assert (ph->p_type != PT_TLS);
1327 l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1328 l->l_addr = l->l_map_start - l->l_addr;
1329 l->l_map_end += l->l_addr;
1330 l->l_text_end += l->l_addr;
1331 l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1332 elf_get_dynamic_info (l, dyn_temp);
1333 _dl_setup_hash (l);
1334 l->l_relocated = 1;
1336 /* Initialize l_local_scope to contain just this map. This allows
1337 the use of dl_lookup_symbol_x to resolve symbols within the vdso.
1338 So we create a single entry list pointing to l_real as its only
1339 element */
1340 l->l_local_scope[0]->r_nlist = 1;
1341 l->l_local_scope[0]->r_list = &l->l_real;
1343 /* Now that we have the info handy, use the DSO image's soname
1344 so this object can be looked up by name. Note that we do not
1345 set l_name here. That field gives the file name of the DSO,
1346 and this DSO is not associated with any file. */
1347 if (l->l_info[DT_SONAME] != NULL)
1349 /* Work around a kernel problem. The kernel cannot handle
1350 addresses in the vsyscall DSO pages in writev() calls. */
1351 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1352 + l->l_info[DT_SONAME]->d_un.d_val);
1353 size_t len = strlen (dsoname);
1354 char *copy = malloc (len);
1355 if (copy == NULL)
1356 _dl_fatal_printf ("out of memory\n");
1357 l->l_libname->name = memcpy (copy, dsoname, len);
1360 /* Rearrange the list so this DSO appears after rtld_map. */
1361 assert (l->l_next == NULL);
1362 assert (l->l_prev == main_map);
1363 GL(dl_rtld_map).l_next = l;
1364 l->l_prev = &GL(dl_rtld_map);
1365 first_preload = &l->l_next;
1367 /* We have a prelinked DSO preloaded by the system. */
1368 GLRO(dl_sysinfo_map) = l;
1369 # ifdef NEED_DL_SYSINFO
1370 if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1371 GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1372 # endif
1375 #endif
1377 #ifdef DL_SYSDEP_OSCHECK
1378 DL_SYSDEP_OSCHECK (dl_fatal);
1379 #endif
1381 /* Initialize the data structures for the search paths for shared
1382 objects. */
1383 _dl_init_paths (library_path);
1385 /* Initialize _r_debug. */
1386 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1387 LM_ID_BASE);
1388 r->r_state = RT_CONSISTENT;
1390 /* Put the link_map for ourselves on the chain so it can be found by
1391 name. Note that at this point the global chain of link maps contains
1392 exactly one element, which is pointed to by dl_loaded. */
1393 if (! GL(dl_rtld_map).l_name)
1394 /* If not invoked directly, the dynamic linker shared object file was
1395 found by the PT_INTERP name. */
1396 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1397 GL(dl_rtld_map).l_type = lt_library;
1398 main_map->l_next = &GL(dl_rtld_map);
1399 GL(dl_rtld_map).l_prev = main_map;
1400 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1401 ++GL(dl_load_adds);
1403 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1404 to not using bias for non-prelinked PIEs and libraries
1405 and using it for executables or prelinked PIEs or libraries. */
1406 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1407 GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
1409 /* Set up the program header information for the dynamic linker
1410 itself. It is needed in the dl_iterate_phdr() callbacks. */
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;
1428 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1429 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1430 /* Assign a module ID. Do this before loading any audit modules. */
1431 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1433 /* If we have auditing DSOs to load, do it now. */
1434 if (__builtin_expect (audit_list != NULL, 0))
1436 /* Iterate over all entries in the list. The order is important. */
1437 struct audit_ifaces *last_audit = NULL;
1438 struct audit_list *al = audit_list->next;
1440 /* Since we start using the auditing DSOs right away we need to
1441 initialize the data structures now. */
1442 tcbp = init_tls ();
1444 /* Initialize security features. We need to do it this early
1445 since otherwise the constructors of the audit libraries will
1446 use different values (especially the pointer guard) and will
1447 fail later on. */
1448 security_init ();
1452 int tls_idx = GL(dl_tls_max_dtv_idx);
1454 /* Now it is time to determine the layout of the static TLS
1455 block and allocate it for the initial thread. Note that we
1456 always allocate the static block, we never defer it even if
1457 no DF_STATIC_TLS bit is set. The reason is that we know
1458 glibc will use the static model. */
1459 struct dlmopen_args dlmargs;
1460 dlmargs.fname = al->name;
1461 dlmargs.map = NULL;
1463 const char *objname;
1464 const char *err_str = NULL;
1465 bool malloced;
1466 (void) _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit,
1467 &dlmargs);
1468 if (__builtin_expect (err_str != NULL, 0))
1470 not_loaded:
1471 _dl_error_printf ("\
1472 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
1473 al->name, err_str);
1474 if (malloced)
1475 free ((char *) err_str);
1477 else
1479 struct lookup_args largs;
1480 largs.name = "la_version";
1481 largs.map = dlmargs.map;
1483 /* Check whether the interface version matches. */
1484 (void) _dl_catch_error (&objname, &err_str, &malloced,
1485 lookup_doit, &largs);
1487 unsigned int (*laversion) (unsigned int);
1488 unsigned int lav;
1489 if (err_str == NULL
1490 && (laversion = largs.result) != NULL
1491 && (lav = laversion (LAV_CURRENT)) > 0
1492 && lav <= LAV_CURRENT)
1494 /* Allocate structure for the callback function pointers.
1495 This call can never fail. */
1496 union
1498 struct audit_ifaces ifaces;
1499 #define naudit_ifaces 8
1500 void (*fptr[naudit_ifaces]) (void);
1501 } *newp = malloc (sizeof (*newp));
1503 /* Names of the auditing interfaces. All in one
1504 long string. */
1505 static const char audit_iface_names[] =
1506 "la_activity\0"
1507 "la_objsearch\0"
1508 "la_objopen\0"
1509 "la_preinit\0"
1510 #if __ELF_NATIVE_CLASS == 32
1511 "la_symbind32\0"
1512 #elif __ELF_NATIVE_CLASS == 64
1513 "la_symbind64\0"
1514 #else
1515 # error "__ELF_NATIVE_CLASS must be defined"
1516 #endif
1517 #define STRING(s) __STRING (s)
1518 "la_" STRING (ARCH_LA_PLTENTER) "\0"
1519 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
1520 "la_objclose\0";
1521 unsigned int cnt = 0;
1522 const char *cp = audit_iface_names;
1525 largs.name = cp;
1526 (void) _dl_catch_error (&objname, &err_str, &malloced,
1527 lookup_doit, &largs);
1529 /* Store the pointer. */
1530 if (err_str == NULL && largs.result != NULL)
1532 newp->fptr[cnt] = largs.result;
1534 /* The dynamic linker link map is statically
1535 allocated, initialize the data now. */
1536 GL(dl_rtld_map).l_audit[cnt].cookie
1537 = (intptr_t) &GL(dl_rtld_map);
1539 else
1540 newp->fptr[cnt] = NULL;
1541 ++cnt;
1543 cp = (char *) rawmemchr (cp, '\0') + 1;
1545 while (*cp != '\0');
1546 assert (cnt == naudit_ifaces);
1548 /* Now append the new auditing interface to the list. */
1549 newp->ifaces.next = NULL;
1550 if (last_audit == NULL)
1551 last_audit = GLRO(dl_audit) = &newp->ifaces;
1552 else
1553 last_audit = last_audit->next = &newp->ifaces;
1554 ++GLRO(dl_naudit);
1556 /* Mark the DSO as being used for auditing. */
1557 dlmargs.map->l_auditing = 1;
1559 else
1561 /* We cannot use the DSO, it does not have the
1562 appropriate interfaces or it expects something
1563 more recent. */
1564 #ifndef NDEBUG
1565 Lmid_t ns = dlmargs.map->l_ns;
1566 #endif
1567 _dl_close (dlmargs.map);
1569 /* Make sure the namespace has been cleared entirely. */
1570 assert (GL(dl_ns)[ns]._ns_loaded == NULL);
1571 assert (GL(dl_ns)[ns]._ns_nloaded == 0);
1573 GL(dl_tls_max_dtv_idx) = tls_idx;
1574 goto not_loaded;
1578 al = al->next;
1580 while (al != audit_list->next);
1582 /* If we have any auditing modules, announce that we already
1583 have two objects loaded. */
1584 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1586 struct link_map *ls[2] = { main_map, &GL(dl_rtld_map) };
1588 for (unsigned int outer = 0; outer < 2; ++outer)
1590 struct audit_ifaces *afct = GLRO(dl_audit);
1591 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1593 if (afct->objopen != NULL)
1595 ls[outer]->l_audit[cnt].bindflags
1596 = afct->objopen (ls[outer], LM_ID_BASE,
1597 &ls[outer]->l_audit[cnt].cookie);
1599 ls[outer]->l_audit_any_plt
1600 |= ls[outer]->l_audit[cnt].bindflags != 0;
1603 afct = afct->next;
1609 /* Set up debugging before the debugger is notified for the first time. */
1610 #ifdef ELF_MACHINE_DEBUG_SETUP
1611 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1612 ELF_MACHINE_DEBUG_SETUP (main_map, r);
1613 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1614 #else
1615 if (main_map->l_info[DT_DEBUG] != NULL)
1616 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1617 with the run-time address of the r_debug structure */
1618 main_map->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1620 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1621 case you run gdb on the dynamic linker directly. */
1622 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1623 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1624 #endif
1626 /* We start adding objects. */
1627 r->r_state = RT_ADD;
1628 _dl_debug_state ();
1630 /* Auditing checkpoint: we are ready to signal that the initial map
1631 is being constructed. */
1632 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1634 struct audit_ifaces *afct = GLRO(dl_audit);
1635 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1637 if (afct->activity != NULL)
1638 afct->activity (&main_map->l_audit[cnt].cookie, LA_ACT_ADD);
1640 afct = afct->next;
1644 /* We have two ways to specify objects to preload: via environment
1645 variable and via the file /etc/ld.so.preload. The latter can also
1646 be used when security is enabled. */
1647 assert (*first_preload == NULL);
1648 struct link_map **preloads = NULL;
1649 unsigned int npreloads = 0;
1651 if (__builtin_expect (preloadlist != NULL, 0))
1653 /* The LD_PRELOAD environment variable gives list of libraries
1654 separated by white space or colons that are loaded before the
1655 executable's dependencies and prepended to the global scope
1656 list. If the binary is running setuid all elements
1657 containing a '/' are ignored since it is insecure. */
1658 char *list = strdupa (preloadlist);
1659 char *p;
1661 HP_TIMING_NOW (start);
1663 /* Prevent optimizing strsep. Speed is not important here. */
1664 while ((p = (strsep) (&list, " :")) != NULL)
1665 if (p[0] != '\0'
1666 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1667 || strchr (p, '/') == NULL))
1668 npreloads += do_preload (p, main_map, "LD_PRELOAD");
1670 HP_TIMING_NOW (stop);
1671 HP_TIMING_DIFF (diff, start, stop);
1672 HP_TIMING_ACCUM_NT (load_time, diff);
1675 /* There usually is no ld.so.preload file, it should only be used
1676 for emergencies and testing. So the open call etc should usually
1677 fail. Using access() on a non-existing file is faster than using
1678 open(). So we do this first. If it succeeds we do almost twice
1679 the work but this does not matter, since it is not for production
1680 use. */
1681 static const char preload_file[] = "/etc/ld.so.preload";
1682 if (__builtin_expect (__access (preload_file, R_OK) == 0, 0))
1684 /* Read the contents of the file. */
1685 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1686 PROT_READ | PROT_WRITE);
1687 if (__builtin_expect (file != MAP_FAILED, 0))
1689 /* Parse the file. It contains names of libraries to be loaded,
1690 separated by white spaces or `:'. It may also contain
1691 comments introduced by `#'. */
1692 char *problem;
1693 char *runp;
1694 size_t rest;
1696 /* Eliminate comments. */
1697 runp = file;
1698 rest = file_size;
1699 while (rest > 0)
1701 char *comment = memchr (runp, '#', rest);
1702 if (comment == NULL)
1703 break;
1705 rest -= comment - runp;
1707 *comment = ' ';
1708 while (--rest > 0 && *++comment != '\n');
1711 /* We have one problematic case: if we have a name at the end of
1712 the file without a trailing terminating characters, we cannot
1713 place the \0. Handle the case separately. */
1714 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1715 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1717 problem = &file[file_size];
1718 while (problem > file && problem[-1] != ' '
1719 && problem[-1] != '\t'
1720 && problem[-1] != '\n' && problem[-1] != ':')
1721 --problem;
1723 if (problem > file)
1724 problem[-1] = '\0';
1726 else
1728 problem = NULL;
1729 file[file_size - 1] = '\0';
1732 HP_TIMING_NOW (start);
1734 if (file != problem)
1736 char *p;
1737 runp = file;
1738 while ((p = strsep (&runp, ": \t\n")) != NULL)
1739 if (p[0] != '\0')
1740 npreloads += do_preload (p, main_map, preload_file);
1743 if (problem != NULL)
1745 char *p = strndupa (problem, file_size - (problem - file));
1747 npreloads += do_preload (p, main_map, preload_file);
1750 HP_TIMING_NOW (stop);
1751 HP_TIMING_DIFF (diff, start, stop);
1752 HP_TIMING_ACCUM_NT (load_time, diff);
1754 /* We don't need the file anymore. */
1755 __munmap (file, file_size);
1759 if (__builtin_expect (*first_preload != NULL, 0))
1761 /* Set up PRELOADS with a vector of the preloaded libraries. */
1762 struct link_map *l = *first_preload;
1763 preloads = __alloca (npreloads * sizeof preloads[0]);
1764 i = 0;
1767 preloads[i++] = l;
1768 l = l->l_next;
1769 } while (l);
1770 assert (i == npreloads);
1773 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1774 specified some libraries to load, these are inserted before the actual
1775 dependencies in the executable's searchlist for symbol resolution. */
1776 HP_TIMING_NOW (start);
1777 _dl_map_object_deps (main_map, preloads, npreloads, mode == trace, 0);
1778 HP_TIMING_NOW (stop);
1779 HP_TIMING_DIFF (diff, start, stop);
1780 HP_TIMING_ACCUM_NT (load_time, diff);
1782 /* Mark all objects as being in the global scope. */
1783 for (i = main_map->l_searchlist.r_nlist; i > 0; )
1784 main_map->l_searchlist.r_list[--i]->l_global = 1;
1786 /* Remove _dl_rtld_map from the chain. */
1787 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1788 if (GL(dl_rtld_map).l_next != NULL)
1789 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1791 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1792 if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1793 break;
1795 bool rtld_multiple_ref = false;
1796 if (__builtin_expect (i < main_map->l_searchlist.r_nlist, 1))
1798 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1799 put it back in the list of visible objects. We insert it into the
1800 chain in symbol search order because gdb uses the chain's order as
1801 its symbol search order. */
1802 rtld_multiple_ref = true;
1804 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1805 if (__builtin_expect (mode, normal) == normal)
1807 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1808 ? main_map->l_searchlist.r_list[i + 1]
1809 : NULL);
1810 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1811 if (GLRO(dl_sysinfo_map) != NULL
1812 && GL(dl_rtld_map).l_prev->l_next == GLRO(dl_sysinfo_map)
1813 && GL(dl_rtld_map).l_next != GLRO(dl_sysinfo_map))
1814 GL(dl_rtld_map).l_prev = GLRO(dl_sysinfo_map);
1815 #endif
1817 else
1818 /* In trace mode there might be an invisible object (which we
1819 could not find) after the previous one in the search list.
1820 In this case it doesn't matter much where we put the
1821 interpreter object, so we just initialize the list pointer so
1822 that the assertion below holds. */
1823 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1825 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1826 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1827 if (GL(dl_rtld_map).l_next != NULL)
1829 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1830 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1834 /* Now let us see whether all libraries are available in the
1835 versions we need. */
1837 struct version_check_args args;
1838 args.doexit = mode == normal;
1839 args.dotrace = mode == trace;
1840 _dl_receive_error (print_missing_version, version_check_doit, &args);
1843 /* We do not initialize any of the TLS functionality unless any of the
1844 initial modules uses TLS. This makes dynamic loading of modules with
1845 TLS impossible, but to support it requires either eagerly doing setup
1846 now or lazily doing it later. Doing it now makes us incompatible with
1847 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1848 used. Trying to do it lazily is too hairy to try when there could be
1849 multiple threads (from a non-TLS-using libpthread). */
1850 bool was_tls_init_tp_called = tls_init_tp_called;
1851 if (tcbp == NULL)
1852 tcbp = init_tls ();
1854 if (__builtin_expect (audit_list == NULL, 1))
1855 /* Initialize security features. But only if we have not done it
1856 earlier. */
1857 security_init ();
1859 if (__builtin_expect (mode, normal) != normal)
1861 /* We were run just to list the shared libraries. It is
1862 important that we do this before real relocation, because the
1863 functions we call below for output may no longer work properly
1864 after relocation. */
1865 struct link_map *l;
1867 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1869 struct r_scope_elem *scope = &main_map->l_searchlist;
1871 for (i = 0; i < scope->r_nlist; i++)
1873 l = scope->r_list [i];
1874 if (l->l_faked)
1876 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1877 continue;
1879 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1880 GLRO(dl_trace_prelink_map) = l;
1881 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1882 l->l_libname->name[0] ? l->l_libname->name
1883 : rtld_progname ?: "<main program>",
1884 l->l_name[0] ? l->l_name
1885 : rtld_progname ?: "<main program>",
1886 (int) sizeof l->l_map_start * 2,
1887 (size_t) l->l_map_start,
1888 (int) sizeof l->l_addr * 2,
1889 (size_t) l->l_addr);
1891 if (l->l_tls_modid)
1892 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1893 (int) sizeof l->l_tls_offset * 2,
1894 (size_t) l->l_tls_offset);
1895 else
1896 _dl_printf ("\n");
1899 else if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
1901 /* Look through the dependencies of the main executable
1902 and determine which of them is not actually
1903 required. */
1904 struct link_map *l = main_map;
1906 /* Relocate the main executable. */
1907 struct relocate_args args = { .l = l,
1908 .reloc_mode = (GLRO(dl_lazy)
1909 ? RTLD_LAZY : 0) };
1910 _dl_receive_error (print_unresolved, relocate_doit, &args);
1912 /* This loop depends on the dependencies of the executable to
1913 correspond in number and order to the DT_NEEDED entries. */
1914 ElfW(Dyn) *dyn = main_map->l_ld;
1915 bool first = true;
1916 while (dyn->d_tag != DT_NULL)
1918 if (dyn->d_tag == DT_NEEDED)
1920 l = l->l_next;
1922 if (!l->l_used)
1924 if (first)
1926 _dl_printf ("Unused direct dependencies:\n");
1927 first = false;
1930 _dl_printf ("\t%s\n", l->l_name);
1934 ++dyn;
1937 _exit (first != true);
1939 else if (! main_map->l_info[DT_NEEDED])
1940 _dl_printf ("\tstatically linked\n");
1941 else
1943 for (l = main_map->l_next; l; l = l->l_next)
1944 if (l->l_faked)
1945 /* The library was not found. */
1946 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1947 else if (strcmp (l->l_libname->name, l->l_name) == 0)
1948 _dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
1949 (int) sizeof l->l_map_start * 2,
1950 (size_t) l->l_map_start);
1951 else
1952 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1953 l->l_name, (int) sizeof l->l_map_start * 2,
1954 (size_t) l->l_map_start);
1957 if (__builtin_expect (mode, trace) != trace)
1958 for (i = 1; i < (unsigned int) _dl_argc; ++i)
1960 const ElfW(Sym) *ref = NULL;
1961 ElfW(Addr) loadbase;
1962 lookup_t result;
1964 result = _dl_lookup_symbol_x (INTUSE(_dl_argv)[i], main_map,
1965 &ref, main_map->l_scope,
1966 NULL, ELF_RTYPE_CLASS_PLT,
1967 DL_LOOKUP_ADD_DEPENDENCY, NULL);
1969 loadbase = LOOKUP_VALUE_ADDRESS (result);
1971 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
1972 INTUSE(_dl_argv)[i],
1973 (int) sizeof ref->st_value * 2,
1974 (size_t) ref->st_value,
1975 (int) sizeof loadbase * 2, (size_t) loadbase);
1977 else
1979 /* If LD_WARN is set, warn about undefined symbols. */
1980 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
1982 /* We have to do symbol dependency testing. */
1983 struct relocate_args args;
1984 struct link_map *l;
1986 args.reloc_mode = GLRO(dl_lazy) ? RTLD_LAZY : 0;
1988 l = main_map;
1989 while (l->l_next != NULL)
1990 l = l->l_next;
1993 if (l != &GL(dl_rtld_map) && ! l->l_faked)
1995 args.l = l;
1996 _dl_receive_error (print_unresolved, relocate_doit,
1997 &args);
1999 l = l->l_prev;
2001 while (l != NULL);
2003 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
2004 && rtld_multiple_ref)
2006 /* Mark the link map as not yet relocated again. */
2007 GL(dl_rtld_map).l_relocated = 0;
2008 _dl_relocate_object (&GL(dl_rtld_map),
2009 main_map->l_scope, 0, 0);
2012 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
2013 if (version_info)
2015 /* Print more information. This means here, print information
2016 about the versions needed. */
2017 int first = 1;
2018 struct link_map *map;
2020 for (map = main_map; map != NULL; map = map->l_next)
2022 const char *strtab;
2023 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
2024 ElfW(Verneed) *ent;
2026 if (dyn == NULL)
2027 continue;
2029 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
2030 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
2032 if (first)
2034 _dl_printf ("\n\tVersion information:\n");
2035 first = 0;
2038 _dl_printf ("\t%s:\n",
2039 map->l_name[0] ? map->l_name : rtld_progname);
2041 while (1)
2043 ElfW(Vernaux) *aux;
2044 struct link_map *needed;
2046 needed = find_needed (strtab + ent->vn_file);
2047 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
2049 while (1)
2051 const char *fname = NULL;
2053 if (needed != NULL
2054 && match_version (strtab + aux->vna_name,
2055 needed))
2056 fname = needed->l_name;
2058 _dl_printf ("\t\t%s (%s) %s=> %s\n",
2059 strtab + ent->vn_file,
2060 strtab + aux->vna_name,
2061 aux->vna_flags & VER_FLG_WEAK
2062 ? "[WEAK] " : "",
2063 fname ?: "not found");
2065 if (aux->vna_next == 0)
2066 /* No more symbols. */
2067 break;
2069 /* Next symbol. */
2070 aux = (ElfW(Vernaux) *) ((char *) aux
2071 + aux->vna_next);
2074 if (ent->vn_next == 0)
2075 /* No more dependencies. */
2076 break;
2078 /* Next dependency. */
2079 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
2085 _exit (0);
2088 if (main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]
2089 && ! __builtin_expect (GLRO(dl_profile) != NULL, 0)
2090 && ! __builtin_expect (GLRO(dl_dynamic_weak), 0))
2092 ElfW(Lib) *liblist, *liblistend;
2093 struct link_map **r_list, **r_listend, *l;
2094 const char *strtab = (const void *) D_PTR (main_map, l_info[DT_STRTAB]);
2096 assert (main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
2097 liblist = (ElfW(Lib) *)
2098 main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
2099 liblistend = (ElfW(Lib) *)
2100 ((char *) liblist +
2101 main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
2102 r_list = main_map->l_searchlist.r_list;
2103 r_listend = r_list + main_map->l_searchlist.r_nlist;
2105 for (; r_list < r_listend && liblist < liblistend; r_list++)
2107 l = *r_list;
2109 if (l == main_map)
2110 continue;
2112 /* If the library is not mapped where it should, fail. */
2113 if (l->l_addr)
2114 break;
2116 /* Next, check if checksum matches. */
2117 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
2118 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
2119 != liblist->l_checksum)
2120 break;
2122 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
2123 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
2124 != liblist->l_time_stamp)
2125 break;
2127 if (! _dl_name_match_p (strtab + liblist->l_name, l))
2128 break;
2130 ++liblist;
2134 if (r_list == r_listend && liblist == liblistend)
2135 prelinked = true;
2137 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
2138 _dl_debug_printf ("\nprelink checking: %s\n",
2139 prelinked ? "ok" : "failed");
2143 /* Now set up the variable which helps the assembler startup code. */
2144 GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
2146 /* Save the information about the original global scope list since
2147 we need it in the memory handling later. */
2148 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
2150 if (prelinked)
2152 if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
2154 ElfW(Rela) *conflict, *conflictend;
2155 #ifndef HP_TIMING_NONAVAIL
2156 hp_timing_t start;
2157 hp_timing_t stop;
2158 #endif
2160 HP_TIMING_NOW (start);
2161 assert (main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
2162 conflict = (ElfW(Rela) *)
2163 main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
2164 conflictend = (ElfW(Rela) *)
2165 ((char *) conflict
2166 + main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
2167 _dl_resolve_conflicts (main_map, conflict, conflictend);
2168 HP_TIMING_NOW (stop);
2169 HP_TIMING_DIFF (relocate_time, start, stop);
2173 /* Mark all the objects so we know they have been already relocated. */
2174 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2176 l->l_relocated = 1;
2177 if (l->l_relro_size)
2178 _dl_protect_relro (l);
2180 /* Add object to slot information data if necessasy. */
2181 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2182 _dl_add_to_slotinfo (l);
2185 else
2187 /* Now we have all the objects loaded. Relocate them all except for
2188 the dynamic linker itself. We do this in reverse order so that copy
2189 relocs of earlier objects overwrite the data written by later
2190 objects. We do not re-relocate the dynamic linker itself in this
2191 loop because that could result in the GOT entries for functions we
2192 call being changed, and that would break us. It is safe to relocate
2193 the dynamic linker out of order because it has no copy relocs (we
2194 know that because it is self-contained). */
2196 int consider_profiling = GLRO(dl_profile) != NULL;
2197 #ifndef HP_TIMING_NONAVAIL
2198 hp_timing_t start;
2199 hp_timing_t stop;
2200 #endif
2202 /* If we are profiling we also must do lazy reloaction. */
2203 GLRO(dl_lazy) |= consider_profiling;
2205 struct link_map *l = main_map;
2206 while (l->l_next)
2207 l = l->l_next;
2209 HP_TIMING_NOW (start);
2212 /* While we are at it, help the memory handling a bit. We have to
2213 mark some data structures as allocated with the fake malloc()
2214 implementation in ld.so. */
2215 struct libname_list *lnp = l->l_libname->next;
2217 while (__builtin_expect (lnp != NULL, 0))
2219 lnp->dont_free = 1;
2220 lnp = lnp->next;
2223 if (l != &GL(dl_rtld_map))
2224 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy) ? RTLD_LAZY : 0,
2225 consider_profiling);
2227 /* Add object to slot information data if necessasy. */
2228 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2229 _dl_add_to_slotinfo (l);
2231 l = l->l_prev;
2233 while (l);
2234 HP_TIMING_NOW (stop);
2236 HP_TIMING_DIFF (relocate_time, start, stop);
2238 /* Now enable profiling if needed. Like the previous call,
2239 this has to go here because the calls it makes should use the
2240 rtld versions of the functions (particularly calloc()), but it
2241 needs to have _dl_profile_map set up by the relocator. */
2242 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
2243 /* We must prepare the profiling. */
2244 _dl_start_profile ();
2247 #ifndef NONTLS_INIT_TP
2248 # define NONTLS_INIT_TP do { } while (0)
2249 #endif
2251 if (!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2252 ++GL(dl_tls_generation);
2254 /* Now that we have completed relocation, the initializer data
2255 for the TLS blocks has its final values and we can copy them
2256 into the main thread's TLS area, which we allocated above. */
2257 _dl_allocate_tls_init (tcbp);
2259 /* And finally install it for the main thread. If ld.so itself uses
2260 TLS we know the thread pointer was initialized earlier. */
2261 if (! tls_init_tp_called)
2263 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
2264 if (__builtin_expect (lossage != NULL, 0))
2265 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2266 lossage);
2269 if (! prelinked && rtld_multiple_ref)
2271 /* There was an explicit ref to the dynamic linker as a shared lib.
2272 Re-relocate ourselves with user-controlled symbol definitions.
2274 We must do this after TLS initialization in case after this
2275 re-relocation, we might call a user-supplied function
2276 (e.g. calloc from _dl_relocate_object) that uses TLS data. */
2278 #ifndef HP_TIMING_NONAVAIL
2279 hp_timing_t start;
2280 hp_timing_t stop;
2281 hp_timing_t add;
2282 #endif
2284 HP_TIMING_NOW (start);
2285 /* Mark the link map as not yet relocated again. */
2286 GL(dl_rtld_map).l_relocated = 0;
2287 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2288 HP_TIMING_NOW (stop);
2289 HP_TIMING_DIFF (add, start, stop);
2290 HP_TIMING_ACCUM_NT (relocate_time, add);
2293 /* Do any necessary cleanups for the startup OS interface code.
2294 We do these now so that no calls are made after rtld re-relocation
2295 which might be resolved to different functions than we expect.
2296 We cannot do this before relocating the other objects because
2297 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2298 _dl_sysdep_start_cleanup ();
2300 #ifdef SHARED
2301 /* Auditing checkpoint: we have added all objects. */
2302 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
2304 struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2305 /* Do not call the functions for any auditing object. */
2306 if (head->l_auditing == 0)
2308 struct audit_ifaces *afct = GLRO(dl_audit);
2309 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2311 if (afct->activity != NULL)
2312 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
2314 afct = afct->next;
2318 #endif
2320 /* Notify the debugger all new objects are now ready to go. We must re-get
2321 the address since by now the variable might be in another object. */
2322 r = _dl_debug_initialize (0, LM_ID_BASE);
2323 r->r_state = RT_CONSISTENT;
2324 _dl_debug_state ();
2326 #ifndef MAP_COPY
2327 /* We must munmap() the cache file. */
2328 _dl_unload_cache ();
2329 #endif
2331 /* Once we return, _dl_sysdep_start will invoke
2332 the DT_INIT functions and then *USER_ENTRY. */
2335 /* This is a little helper function for resolving symbols while
2336 tracing the binary. */
2337 static void
2338 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2339 const char *errstring)
2341 if (objname[0] == '\0')
2342 objname = rtld_progname ?: "<main program>";
2343 _dl_error_printf ("%s (%s)\n", errstring, objname);
2346 /* This is a little helper function for resolving symbols while
2347 tracing the binary. */
2348 static void
2349 print_missing_version (int errcode __attribute__ ((unused)),
2350 const char *objname, const char *errstring)
2352 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
2353 objname, errstring);
2356 /* Nonzero if any of the debugging options is enabled. */
2357 static int any_debug attribute_relro;
2359 /* Process the string given as the parameter which explains which debugging
2360 options are enabled. */
2361 static void
2362 process_dl_debug (const char *dl_debug)
2364 /* When adding new entries make sure that the maximal length of a name
2365 is correctly handled in the LD_DEBUG_HELP code below. */
2366 static const struct
2368 unsigned char len;
2369 const char name[10];
2370 const char helptext[41];
2371 unsigned short int mask;
2372 } debopts[] =
2374 #define LEN_AND_STR(str) sizeof (str) - 1, str
2375 { LEN_AND_STR ("libs"), "display library search paths",
2376 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2377 { LEN_AND_STR ("reloc"), "display relocation processing",
2378 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2379 { LEN_AND_STR ("files"), "display progress for input file",
2380 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2381 { LEN_AND_STR ("symbols"), "display symbol table processing",
2382 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2383 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2384 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2385 { LEN_AND_STR ("versions"), "display version dependencies",
2386 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2387 { LEN_AND_STR ("all"), "all previous options combined",
2388 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2389 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2390 { LEN_AND_STR ("statistics"), "display relocation statistics",
2391 DL_DEBUG_STATISTICS },
2392 { LEN_AND_STR ("unused"), "determined unused DSOs",
2393 DL_DEBUG_UNUSED },
2394 { LEN_AND_STR ("help"), "display this help message and exit",
2395 DL_DEBUG_HELP },
2397 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2399 /* Skip separating white spaces and commas. */
2400 while (*dl_debug != '\0')
2402 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2404 size_t cnt;
2405 size_t len = 1;
2407 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2408 && dl_debug[len] != ',' && dl_debug[len] != ':')
2409 ++len;
2411 for (cnt = 0; cnt < ndebopts; ++cnt)
2412 if (debopts[cnt].len == len
2413 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
2415 GLRO(dl_debug_mask) |= debopts[cnt].mask;
2416 any_debug = 1;
2417 break;
2420 if (cnt == ndebopts)
2422 /* Display a warning and skip everything until next
2423 separator. */
2424 char *copy = strndupa (dl_debug, len);
2425 _dl_error_printf ("\
2426 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2429 dl_debug += len;
2430 continue;
2433 ++dl_debug;
2436 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
2438 size_t cnt;
2440 _dl_printf ("\
2441 Valid options for the LD_DEBUG environment variable are:\n\n");
2443 for (cnt = 0; cnt < ndebopts; ++cnt)
2444 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2445 " " + debopts[cnt].len - 3,
2446 debopts[cnt].helptext);
2448 _dl_printf ("\n\
2449 To direct the debugging output into a file instead of standard output\n\
2450 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2451 _exit (0);
2455 static void
2456 process_dl_audit (char *str)
2458 /* The parameter is a colon separated list of DSO names. */
2459 char *p;
2461 while ((p = (strsep) (&str, ":")) != NULL)
2462 if (p[0] != '\0'
2463 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
2464 || strchr (p, '/') == NULL))
2466 /* This is using the local malloc, not the system malloc. The
2467 memory can never be freed. */
2468 struct audit_list *newp = malloc (sizeof (*newp));
2469 newp->name = p;
2471 if (audit_list == NULL)
2472 audit_list = newp->next = newp;
2473 else
2475 newp->next = audit_list->next;
2476 audit_list = audit_list->next = newp;
2481 /* Process all environments variables the dynamic linker must recognize.
2482 Since all of them start with `LD_' we are a bit smarter while finding
2483 all the entries. */
2484 extern char **_environ attribute_hidden;
2487 static void
2488 process_envvars (enum mode *modep)
2490 char **runp = _environ;
2491 char *envline;
2492 enum mode mode = normal;
2493 char *debug_output = NULL;
2495 /* This is the default place for profiling data file. */
2496 GLRO(dl_profile_output)
2497 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2499 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2501 size_t len = 0;
2503 while (envline[len] != '\0' && envline[len] != '=')
2504 ++len;
2506 if (envline[len] != '=')
2507 /* This is a "LD_" variable at the end of the string without
2508 a '=' character. Ignore it since otherwise we will access
2509 invalid memory below. */
2510 continue;
2512 switch (len)
2514 case 4:
2515 /* Warning level, verbose or not. */
2516 if (memcmp (envline, "WARN", 4) == 0)
2517 GLRO(dl_verbose) = envline[5] != '\0';
2518 break;
2520 case 5:
2521 /* Debugging of the dynamic linker? */
2522 if (memcmp (envline, "DEBUG", 5) == 0)
2524 process_dl_debug (&envline[6]);
2525 break;
2527 if (memcmp (envline, "AUDIT", 5) == 0)
2528 process_dl_audit (&envline[6]);
2529 break;
2531 case 7:
2532 /* Print information about versions. */
2533 if (memcmp (envline, "VERBOSE", 7) == 0)
2535 version_info = envline[8] != '\0';
2536 break;
2539 /* List of objects to be preloaded. */
2540 if (memcmp (envline, "PRELOAD", 7) == 0)
2542 preloadlist = &envline[8];
2543 break;
2546 /* Which shared object shall be profiled. */
2547 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2548 GLRO(dl_profile) = &envline[8];
2549 break;
2551 case 8:
2552 /* Do we bind early? */
2553 if (memcmp (envline, "BIND_NOW", 8) == 0)
2555 GLRO(dl_lazy) = envline[9] == '\0';
2556 break;
2558 if (memcmp (envline, "BIND_NOT", 8) == 0)
2559 GLRO(dl_bind_not) = envline[9] != '\0';
2560 break;
2562 case 9:
2563 /* Test whether we want to see the content of the auxiliary
2564 array passed up from the kernel. */
2565 if (!INTUSE(__libc_enable_secure)
2566 && memcmp (envline, "SHOW_AUXV", 9) == 0)
2567 _dl_show_auxv ();
2568 break;
2570 case 10:
2571 /* Mask for the important hardware capabilities. */
2572 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2573 GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2574 0, 0);
2575 break;
2577 case 11:
2578 /* Path where the binary is found. */
2579 if (!INTUSE(__libc_enable_secure)
2580 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2581 GLRO(dl_origin_path) = &envline[12];
2582 break;
2584 case 12:
2585 /* The library search path. */
2586 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2588 library_path = &envline[13];
2589 break;
2592 /* Where to place the profiling data file. */
2593 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2595 debug_output = &envline[13];
2596 break;
2599 if (!INTUSE(__libc_enable_secure)
2600 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2601 GLRO(dl_dynamic_weak) = 1;
2602 break;
2604 case 13:
2605 /* We might have some extra environment variable with length 13
2606 to handle. */
2607 #ifdef EXTRA_LD_ENVVARS_13
2608 EXTRA_LD_ENVVARS_13
2609 #endif
2610 if (!INTUSE(__libc_enable_secure)
2611 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2613 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2614 break;
2617 if (memcmp (envline, "POINTER_GUARD", 13) == 0)
2618 GLRO(dl_pointer_guard) = envline[14] != '0';
2619 break;
2621 case 14:
2622 /* Where to place the profiling data file. */
2623 if (!INTUSE(__libc_enable_secure)
2624 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2625 && envline[15] != '\0')
2626 GLRO(dl_profile_output) = &envline[15];
2627 break;
2629 case 16:
2630 /* The mode of the dynamic linker can be set. */
2631 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2633 mode = trace;
2634 GLRO(dl_verbose) = 1;
2635 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2636 GLRO(dl_trace_prelink) = &envline[17];
2638 break;
2640 case 20:
2641 /* The mode of the dynamic linker can be set. */
2642 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2643 mode = trace;
2644 break;
2646 /* We might have some extra environment variable to handle. This
2647 is tricky due to the pre-processing of the length of the name
2648 in the switch statement here. The code here assumes that added
2649 environment variables have a different length. */
2650 #ifdef EXTRA_LD_ENVVARS
2651 EXTRA_LD_ENVVARS
2652 #endif
2656 /* The caller wants this information. */
2657 *modep = mode;
2659 /* Extra security for SUID binaries. Remove all dangerous environment
2660 variables. */
2661 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2663 static const char unsecure_envvars[] =
2664 #ifdef EXTRA_UNSECURE_ENVVARS
2665 EXTRA_UNSECURE_ENVVARS
2666 #endif
2667 UNSECURE_ENVVARS;
2668 const char *nextp;
2670 nextp = unsecure_envvars;
2673 unsetenv (nextp);
2674 /* We could use rawmemchr but this need not be fast. */
2675 nextp = (char *) (strchr) (nextp, '\0') + 1;
2677 while (*nextp != '\0');
2679 if (__access ("/etc/suid-debug", F_OK) != 0)
2681 unsetenv ("MALLOC_CHECK_");
2682 GLRO(dl_debug_mask) = 0;
2685 if (mode != normal)
2686 _exit (5);
2688 /* If we have to run the dynamic linker in debugging mode and the
2689 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2690 messages to this file. */
2691 else if (any_debug && debug_output != NULL)
2693 #ifdef O_NOFOLLOW
2694 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2695 #else
2696 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2697 #endif
2698 size_t name_len = strlen (debug_output);
2699 char buf[name_len + 12];
2700 char *startp;
2702 buf[name_len + 11] = '\0';
2703 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2704 *--startp = '.';
2705 startp = memcpy (startp - name_len, debug_output, name_len);
2707 GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2708 if (GLRO(dl_debug_fd) == -1)
2709 /* We use standard output if opening the file failed. */
2710 GLRO(dl_debug_fd) = STDOUT_FILENO;
2715 /* Print the various times we collected. */
2716 static void
2717 __attribute ((noinline))
2718 print_statistics (hp_timing_t *rtld_total_timep)
2720 #ifndef HP_TIMING_NONAVAIL
2721 char buf[200];
2722 char *cp;
2723 char *wp;
2725 /* Total time rtld used. */
2726 if (HP_TIMING_AVAIL)
2728 HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2729 _dl_debug_printf ("\nruntime linker statistics:\n"
2730 " total startup time in dynamic loader: %s\n", buf);
2732 /* Print relocation statistics. */
2733 char pbuf[30];
2734 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2735 cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2736 pbuf + sizeof (pbuf), 10, 0);
2737 wp = pbuf;
2738 switch (pbuf + sizeof (pbuf) - cp)
2740 case 3:
2741 *wp++ = *cp++;
2742 case 2:
2743 *wp++ = *cp++;
2744 case 1:
2745 *wp++ = '.';
2746 *wp++ = *cp++;
2748 *wp = '\0';
2749 _dl_debug_printf ("\
2750 time needed for relocation: %s (%s%%)\n", buf, pbuf);
2752 #endif
2754 unsigned long int num_relative_relocations = 0;
2755 for (Lmid_t ns = 0; ns < GL(dl_nns); ++ns)
2757 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2758 continue;
2760 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2762 for (unsigned int i = 0; i < scope->r_nlist; i++)
2764 struct link_map *l = scope->r_list [i];
2766 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2767 num_relative_relocations
2768 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2769 #ifndef ELF_MACHINE_REL_RELATIVE
2770 /* Relative relocations are processed on these architectures if
2771 library is loaded to different address than p_vaddr or
2772 if not prelinked. */
2773 if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2774 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2775 #else
2776 /* On e.g. IA-64 or Alpha, relative relocations are processed
2777 only if library is loaded to different address than p_vaddr. */
2778 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2779 #endif
2780 num_relative_relocations
2781 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2785 _dl_debug_printf (" number of relocations: %lu\n"
2786 " number of relocations from cache: %lu\n"
2787 " number of relative relocations: %lu\n",
2788 GL(dl_num_relocations),
2789 GL(dl_num_cache_relocations),
2790 num_relative_relocations);
2792 #ifndef HP_TIMING_NONAVAIL
2793 /* Time spend while loading the object and the dependencies. */
2794 if (HP_TIMING_AVAIL)
2796 char pbuf[30];
2797 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2798 cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2799 pbuf + sizeof (pbuf), 10, 0);
2800 wp = pbuf;
2801 switch (pbuf + sizeof (pbuf) - cp)
2803 case 3:
2804 *wp++ = *cp++;
2805 case 2:
2806 *wp++ = *cp++;
2807 case 1:
2808 *wp++ = '.';
2809 *wp++ = *cp++;
2811 *wp = '\0';
2812 _dl_debug_printf ("\
2813 time needed to load objects: %s (%s%%)\n",
2814 buf, pbuf);
2816 #endif