* pthreadP.h (PTHREAD_RWLOCK_PREFER_READER_P): Define.
[glibc/pb-stable.git] / elf / rtld.c
blobc57ef17e139dcf98ea9caf980bebf793f1162426
1 /* Run time dynamic linker.
2 Copyright (C) 1995-2006, 2007 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
166 /* If we would use strong_alias here the compiler would see a
167 non-hidden definition. This would undo the effect of the previous
168 declaration. So spell out was strong_alias does plus add the
169 visibility attribute. */
170 extern struct rtld_global_ro _rtld_local_ro
171 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
174 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
175 ElfW(Addr) *user_entry);
177 /* These two variables cannot be moved into .data.rel.ro. */
178 static struct libname_list _dl_rtld_libname;
179 static struct libname_list _dl_rtld_libname2;
181 /* We expect less than a second for relocation. */
182 #ifdef HP_SMALL_TIMING_AVAIL
183 # undef HP_TIMING_AVAIL
184 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
185 #endif
187 /* Variable for statistics. */
188 #ifndef HP_TIMING_NONAVAIL
189 static hp_timing_t relocate_time;
190 static hp_timing_t load_time attribute_relro;
191 static hp_timing_t start_time attribute_relro;
192 #endif
194 /* Additional definitions needed by TLS initialization. */
195 #ifdef TLS_INIT_HELPER
196 TLS_INIT_HELPER
197 #endif
199 /* Helper function for syscall implementation. */
200 #ifdef DL_SYSINFO_IMPLEMENTATION
201 DL_SYSINFO_IMPLEMENTATION
202 #endif
204 /* Before ld.so is relocated we must not access variables which need
205 relocations. This means variables which are exported. Variables
206 declared as static are fine. If we can mark a variable hidden this
207 is fine, too. The latter is important here. We can avoid setting
208 up a temporary link map for ld.so if we can mark _rtld_global as
209 hidden. */
210 #ifdef PI_STATIC_AND_HIDDEN
211 # define DONT_USE_BOOTSTRAP_MAP 1
212 #endif
214 #ifdef DONT_USE_BOOTSTRAP_MAP
215 static ElfW(Addr) _dl_start_final (void *arg);
216 #else
217 struct dl_start_final_info
219 struct link_map l;
220 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
221 hp_timing_t start_time;
222 #endif
224 static ElfW(Addr) _dl_start_final (void *arg,
225 struct dl_start_final_info *info);
226 #endif
228 /* These defined magically in the linker script. */
229 extern char _begin[] attribute_hidden;
230 extern char _etext[] attribute_hidden;
231 extern char _end[] attribute_hidden;
234 #ifdef RTLD_START
235 RTLD_START
236 #else
237 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
238 #endif
240 #ifndef VALIDX
241 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
242 + DT_EXTRANUM + DT_VALTAGIDX (tag))
243 #endif
244 #ifndef ADDRIDX
245 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
246 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
247 #endif
249 /* This is the second half of _dl_start (below). It can be inlined safely
250 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
251 references. When the tools don't permit us to avoid using a GOT entry
252 for _dl_rtld_global (no attribute_hidden support), we must make sure
253 this function is not inlined (see below). */
255 #ifdef DONT_USE_BOOTSTRAP_MAP
256 static inline ElfW(Addr) __attribute__ ((always_inline))
257 _dl_start_final (void *arg)
258 #else
259 static ElfW(Addr) __attribute__ ((noinline))
260 _dl_start_final (void *arg, struct dl_start_final_info *info)
261 #endif
263 ElfW(Addr) start_addr;
265 if (HP_TIMING_AVAIL)
267 /* If it hasn't happen yet record the startup time. */
268 if (! HP_TIMING_INLINE)
269 HP_TIMING_NOW (start_time);
270 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
271 else
272 start_time = info->start_time;
273 #endif
275 /* Initialize the timing functions. */
276 HP_TIMING_DIFF_INIT ();
279 /* Transfer data about ourselves to the permanent link_map structure. */
280 #ifndef DONT_USE_BOOTSTRAP_MAP
281 GL(dl_rtld_map).l_addr = info->l.l_addr;
282 GL(dl_rtld_map).l_ld = info->l.l_ld;
283 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
284 sizeof GL(dl_rtld_map).l_info);
285 GL(dl_rtld_map).l_mach = info->l.l_mach;
286 GL(dl_rtld_map).l_relocated = 1;
287 #endif
288 _dl_setup_hash (&GL(dl_rtld_map));
289 GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
290 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
291 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
292 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
293 /* Copy the TLS related data if necessary. */
294 #ifndef DONT_USE_BOOTSTRAP_MAP
295 # if USE___THREAD
296 assert (info->l.l_tls_modid != 0);
297 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
298 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
299 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
300 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
301 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
302 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
303 GL(dl_rtld_map).l_tls_modid = 1;
304 # else
305 # if NO_TLS_OFFSET != 0
306 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
307 # endif
308 # endif
310 #endif
312 #if HP_TIMING_AVAIL
313 HP_TIMING_NOW (GL(dl_cpuclock_offset));
314 #endif
316 /* Initialize the stack end variable. */
317 __libc_stack_end = __builtin_frame_address (0);
319 /* Call the OS-dependent function to set up life so we can do things like
320 file access. It will call `dl_main' (below) to do all the real work
321 of the dynamic linker, and then unwind our frame and run the user
322 entry point on the same stack we entered on. */
323 start_addr = _dl_sysdep_start (arg, &dl_main);
325 #ifndef HP_TIMING_NONAVAIL
326 hp_timing_t rtld_total_time;
327 if (HP_TIMING_AVAIL)
329 hp_timing_t end_time;
331 /* Get the current time. */
332 HP_TIMING_NOW (end_time);
334 /* Compute the difference. */
335 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
337 #endif
339 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
341 #ifndef HP_TIMING_NONAVAIL
342 print_statistics (&rtld_total_time);
343 #else
344 print_statistics (NULL);
345 #endif
348 return start_addr;
351 static ElfW(Addr) __attribute_used__ internal_function
352 _dl_start (void *arg)
354 #ifdef DONT_USE_BOOTSTRAP_MAP
355 # define bootstrap_map GL(dl_rtld_map)
356 #else
357 struct dl_start_final_info info;
358 # define bootstrap_map info.l
359 #endif
361 /* This #define produces dynamic linking inline functions for
362 bootstrap relocation instead of general-purpose relocation.
363 Since ld.so must not have any undefined symbols the result
364 is trivial: always the map of ld.so itself. */
365 #define RTLD_BOOTSTRAP
366 #define RESOLVE_MAP(sym, version, flags) (&bootstrap_map)
367 #include "dynamic-link.h"
369 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
370 #ifdef DONT_USE_BOOTSTRAP_MAP
371 HP_TIMING_NOW (start_time);
372 #else
373 HP_TIMING_NOW (info.start_time);
374 #endif
376 /* Partly clean the `bootstrap_map' structure up. Don't use
377 `memset' since it might not be built in or inlined and we cannot
378 make function calls at this point. Use '__builtin_memset' if we
379 know it is available. We do not have to clear the memory if we
380 do not have to use the temporary bootstrap_map. Global variables
381 are initialized to zero by default. */
382 #ifndef DONT_USE_BOOTSTRAP_MAP
383 # ifdef HAVE_BUILTIN_MEMSET
384 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
385 # else
386 for (size_t cnt = 0;
387 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
388 ++cnt)
389 bootstrap_map.l_info[cnt] = 0;
390 # endif
391 # if USE___THREAD
392 bootstrap_map.l_tls_modid = 0;
393 # endif
394 #endif
396 /* Figure out the run-time load address of the dynamic linker itself. */
397 bootstrap_map.l_addr = elf_machine_load_address ();
399 /* Read our own dynamic section and fill in the info array. */
400 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
401 elf_get_dynamic_info (&bootstrap_map, NULL);
403 #if NO_TLS_OFFSET != 0
404 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
405 #endif
407 /* Get the dynamic linker's own program header. First we need the ELF
408 file header. The `_begin' symbol created by the linker script points
409 to it. When we have something like GOTOFF relocs, we can use a plain
410 reference to find the runtime address. Without that, we have to rely
411 on the `l_addr' value, which is not the value we want when prelinked. */
412 #if USE___THREAD
413 dtv_t initdtv[3];
414 ElfW(Ehdr) *ehdr
415 # ifdef DONT_USE_BOOTSTRAP_MAP
416 = (ElfW(Ehdr) *) &_begin;
417 # else
418 # error This will not work with prelink.
419 = (ElfW(Ehdr) *) bootstrap_map.l_addr;
420 # endif
421 ElfW(Phdr) *phdr = (ElfW(Phdr) *) ((void *) ehdr + ehdr->e_phoff);
422 size_t cnt = ehdr->e_phnum; /* PT_TLS is usually the last phdr. */
423 while (cnt-- > 0)
424 if (phdr[cnt].p_type == PT_TLS)
426 void *tlsblock;
427 size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
428 char *p;
430 bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
431 bootstrap_map.l_tls_align = phdr[cnt].p_align;
432 if (phdr[cnt].p_align == 0)
433 bootstrap_map.l_tls_firstbyte_offset = 0;
434 else
435 bootstrap_map.l_tls_firstbyte_offset = (phdr[cnt].p_vaddr
436 & (phdr[cnt].p_align - 1));
437 assert (bootstrap_map.l_tls_blocksize != 0);
438 bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
439 bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
440 + phdr[cnt].p_vaddr);
442 /* We can now allocate the initial TLS block. This can happen
443 on the stack. We'll get the final memory later when we
444 know all about the various objects loaded at startup
445 time. */
446 # if TLS_TCB_AT_TP
447 tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
448 TLS_INIT_TCB_ALIGN)
449 + TLS_INIT_TCB_SIZE
450 + max_align);
451 # elif TLS_DTV_AT_TP
452 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
453 bootstrap_map.l_tls_align)
454 + bootstrap_map.l_tls_blocksize
455 + max_align);
456 # else
457 /* In case a model with a different layout for the TCB and DTV
458 is defined add another #elif here and in the following #ifs. */
459 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
460 # endif
461 /* Align the TLS block. */
462 tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
463 & ~(max_align - 1));
465 /* Initialize the dtv. [0] is the length, [1] the generation
466 counter. */
467 initdtv[0].counter = 1;
468 initdtv[1].counter = 0;
470 /* Initialize the TLS block. */
471 # if TLS_TCB_AT_TP
472 initdtv[2].pointer = tlsblock;
473 # elif TLS_DTV_AT_TP
474 bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
475 bootstrap_map.l_tls_align);
476 initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
477 # else
478 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
479 # endif
480 p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
481 bootstrap_map.l_tls_initimage_size);
482 # ifdef HAVE_BUILTIN_MEMSET
483 __builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
484 - bootstrap_map.l_tls_initimage_size));
485 # else
487 size_t remaining = (bootstrap_map.l_tls_blocksize
488 - bootstrap_map.l_tls_initimage_size);
489 while (remaining-- > 0)
490 *p++ = '\0';
492 # endif
494 /* Install the pointer to the dtv. */
496 /* Initialize the thread pointer. */
497 # if TLS_TCB_AT_TP
498 bootstrap_map.l_tls_offset
499 = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
501 INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
502 initdtv);
504 const char *lossage = TLS_INIT_TP ((char *) tlsblock
505 + bootstrap_map.l_tls_offset, 0);
506 # elif TLS_DTV_AT_TP
507 INSTALL_DTV (tlsblock, initdtv);
508 const char *lossage = TLS_INIT_TP (tlsblock, 0);
509 # else
510 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
511 # endif
512 if (__builtin_expect (lossage != NULL, 0))
513 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
514 lossage);
516 /* So far this is module number one. */
517 bootstrap_map.l_tls_modid = 1;
519 /* There can only be one PT_TLS entry. */
520 break;
522 #endif /* USE___THREAD */
524 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
525 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
526 #endif
528 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
530 /* Relocate ourselves so we can do normal function calls and
531 data access using the global offset table. */
533 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
535 bootstrap_map.l_relocated = 1;
537 /* Please note that we don't allow profiling of this object and
538 therefore need not test whether we have to allocate the array
539 for the relocation results (as done in dl-reloc.c). */
541 /* Now life is sane; we can call functions and access global data.
542 Set up to use the operating system facilities, and find out from
543 the operating system's program loader where to find the program
544 header table in core. Put the rest of _dl_start into a separate
545 function, that way the compiler cannot put accesses to the GOT
546 before ELF_DYNAMIC_RELOCATE. */
548 #ifdef DONT_USE_BOOTSTRAP_MAP
549 ElfW(Addr) entry = _dl_start_final (arg);
550 #else
551 ElfW(Addr) entry = _dl_start_final (arg, &info);
552 #endif
554 #ifndef ELF_MACHINE_START_ADDRESS
555 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
556 #endif
558 return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, entry);
564 /* Now life is peachy; we can do all normal operations.
565 On to the real work. */
567 /* Some helper functions. */
569 /* Arguments to relocate_doit. */
570 struct relocate_args
572 struct link_map *l;
573 int lazy;
576 struct map_args
578 /* Argument to map_doit. */
579 char *str;
580 struct link_map *loader;
581 int is_preloaded;
582 int mode;
583 /* Return value of map_doit. */
584 struct link_map *map;
587 struct dlmopen_args
589 const char *fname;
590 struct link_map *map;
593 struct lookup_args
595 const char *name;
596 struct link_map *map;
597 void *result;
600 /* Arguments to version_check_doit. */
601 struct version_check_args
603 int doexit;
604 int dotrace;
607 static void
608 relocate_doit (void *a)
610 struct relocate_args *args = (struct relocate_args *) a;
612 _dl_relocate_object (args->l, args->l->l_scope, args->lazy, 0);
615 static void
616 map_doit (void *a)
618 struct map_args *args = (struct map_args *) a;
619 args->map = _dl_map_object (args->loader, args->str,
620 args->is_preloaded, lt_library, 0, args->mode,
621 LM_ID_BASE);
624 static void
625 dlmopen_doit (void *a)
627 struct dlmopen_args *args = (struct dlmopen_args *) a;
628 args->map = _dl_open (args->fname, RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT,
629 dl_main, LM_ID_NEWLM, _dl_argc, INTUSE(_dl_argv),
630 __environ);
633 static void
634 lookup_doit (void *a)
636 struct lookup_args *args = (struct lookup_args *) a;
637 const ElfW(Sym) *ref = NULL;
638 args->result = NULL;
639 lookup_t l = _dl_lookup_symbol_x (args->name, args->map, &ref,
640 args->map->l_local_scope, NULL, 0,
641 DL_LOOKUP_RETURN_NEWEST, NULL);
642 if (ref != NULL)
643 args->result = DL_SYMBOL_ADDRESS (l, ref);
646 static void
647 version_check_doit (void *a)
649 struct version_check_args *args = (struct version_check_args *) a;
650 if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
651 args->dotrace) && args->doexit)
652 /* We cannot start the application. Abort now. */
653 _exit (1);
657 static inline struct link_map *
658 find_needed (const char *name)
660 struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
661 unsigned int n = scope->r_nlist;
663 while (n-- > 0)
664 if (_dl_name_match_p (name, scope->r_list[n]))
665 return scope->r_list[n];
667 /* Should never happen. */
668 return NULL;
671 static int
672 match_version (const char *string, struct link_map *map)
674 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
675 ElfW(Verdef) *def;
677 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
678 if (map->l_info[VERDEFTAG] == NULL)
679 /* The file has no symbol versioning. */
680 return 0;
682 def = (ElfW(Verdef) *) ((char *) map->l_addr
683 + map->l_info[VERDEFTAG]->d_un.d_ptr);
684 while (1)
686 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
688 /* Compare the version strings. */
689 if (strcmp (string, strtab + aux->vda_name) == 0)
690 /* Bingo! */
691 return 1;
693 /* If no more definitions we failed to find what we want. */
694 if (def->vd_next == 0)
695 break;
697 /* Next definition. */
698 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
701 return 0;
704 static bool tls_init_tp_called;
706 static void *
707 init_tls (void)
709 /* Number of elements in the static TLS block. */
710 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
712 /* Do not do this twice. The audit interface might have required
713 the DTV interfaces to be set up early. */
714 if (GL(dl_initial_dtv) != NULL)
715 return NULL;
717 /* Allocate the array which contains the information about the
718 dtv slots. We allocate a few entries more than needed to
719 avoid the need for reallocation. */
720 size_t nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
722 /* Allocate. */
723 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
724 calloc (sizeof (struct dtv_slotinfo_list)
725 + nelem * sizeof (struct dtv_slotinfo), 1);
726 /* No need to check the return value. If memory allocation failed
727 the program would have been terminated. */
729 struct dtv_slotinfo *slotinfo = GL(dl_tls_dtv_slotinfo_list)->slotinfo;
730 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
731 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
733 /* Fill in the information from the loaded modules. No namespace
734 but the base one can be filled at this time. */
735 assert (GL(dl_ns)[LM_ID_BASE + 1]._ns_loaded == NULL);
736 int i = 0;
737 for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
738 l = l->l_next)
739 if (l->l_tls_blocksize != 0)
741 /* This is a module with TLS data. Store the map reference.
742 The generation counter is zero. */
743 slotinfo[i].map = l;
744 /* slotinfo[i].gen = 0; */
745 ++i;
747 assert (i == GL(dl_tls_max_dtv_idx));
749 /* Compute the TLS offsets for the various blocks. */
750 _dl_determine_tlsoffset ();
752 /* Construct the static TLS block and the dtv for the initial
753 thread. For some platforms this will include allocating memory
754 for the thread descriptor. The memory for the TLS block will
755 never be freed. It should be allocated accordingly. The dtv
756 array can be changed if dynamic loading requires it. */
757 void *tcbp = _dl_allocate_tls_storage ();
758 if (tcbp == NULL)
759 _dl_fatal_printf ("\
760 cannot allocate TLS data structures for initial thread");
762 /* Store for detection of the special case by __tls_get_addr
763 so it knows not to pass this dtv to the normal realloc. */
764 GL(dl_initial_dtv) = GET_DTV (tcbp);
766 /* And finally install it for the main thread. If ld.so itself uses
767 TLS we know the thread pointer was initialized earlier. */
768 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
769 if (__builtin_expect (lossage != NULL, 0))
770 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
771 tls_init_tp_called = true;
773 return tcbp;
776 #ifdef _LIBC_REENTRANT
777 /* _dl_error_catch_tsd points to this for the single-threaded case.
778 It's reset by the thread library for multithreaded programs. */
779 void ** __attribute__ ((const))
780 _dl_initial_error_catch_tsd (void)
782 static void *data;
783 return &data;
785 #endif
788 static unsigned int
789 do_preload (char *fname, struct link_map *main_map, const char *where)
791 const char *objname;
792 const char *err_str = NULL;
793 struct map_args args;
794 bool malloced;
796 args.str = fname;
797 args.loader = main_map;
798 args.is_preloaded = 1;
799 args.mode = 0;
801 unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
803 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
804 if (__builtin_expect (err_str != NULL, 0))
806 _dl_error_printf ("\
807 ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
808 fname, where);
809 /* No need to call free, this is still before
810 the libc's malloc is used. */
812 else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
813 /* It is no duplicate. */
814 return 1;
816 /* Nothing loaded. */
817 return 0;
820 #if defined SHARED && defined _LIBC_REENTRANT \
821 && defined __rtld_lock_default_lock_recursive
822 static void
823 rtld_lock_default_lock_recursive (void *lock)
825 __rtld_lock_default_lock_recursive (lock);
828 static void
829 rtld_lock_default_unlock_recursive (void *lock)
831 __rtld_lock_default_unlock_recursive (lock);
833 #endif
836 /* The library search path. */
837 static const char *library_path attribute_relro;
838 /* The list preloaded objects. */
839 static const char *preloadlist attribute_relro;
840 /* Nonzero if information about versions has to be printed. */
841 static int version_info attribute_relro;
843 static void
844 dl_main (const ElfW(Phdr) *phdr,
845 ElfW(Word) phnum,
846 ElfW(Addr) *user_entry)
848 const ElfW(Phdr) *ph;
849 enum mode mode;
850 struct link_map *main_map;
851 size_t file_size;
852 char *file;
853 bool has_interp = false;
854 unsigned int i;
855 bool prelinked = false;
856 bool rtld_is_main = false;
857 #ifndef HP_TIMING_NONAVAIL
858 hp_timing_t start;
859 hp_timing_t stop;
860 hp_timing_t diff;
861 #endif
862 void *tcbp = NULL;
864 #ifdef _LIBC_REENTRANT
865 /* Explicit initialization since the reloc would just be more work. */
866 GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
867 #endif
869 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
871 #if defined SHARED && defined _LIBC_REENTRANT \
872 && defined __rtld_lock_default_lock_recursive
873 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
874 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
875 #endif
877 /* The explicit initialization here is cheaper than processing the reloc
878 in the _rtld_local definition's initializer. */
879 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
881 /* Process the environment variable which control the behaviour. */
882 process_envvars (&mode);
884 #ifndef HAVE_INLINED_SYSCALLS
885 /* Set up a flag which tells we are just starting. */
886 INTUSE(_dl_starting_up) = 1;
887 #endif
889 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
891 /* Ho ho. We are not the program interpreter! We are the program
892 itself! This means someone ran ld.so as a command. Well, that
893 might be convenient to do sometimes. We support it by
894 interpreting the args like this:
896 ld.so PROGRAM ARGS...
898 The first argument is the name of a file containing an ELF
899 executable we will load and run with the following arguments.
900 To simplify life here, PROGRAM is searched for using the
901 normal rules for shared objects, rather than $PATH or anything
902 like that. We just load it and use its entry point; we don't
903 pay attention to its PT_INTERP command (we are the interpreter
904 ourselves). This is an easy way to test a new ld.so before
905 installing it. */
906 rtld_is_main = true;
908 /* Note the place where the dynamic linker actually came from. */
909 GL(dl_rtld_map).l_name = rtld_progname;
911 while (_dl_argc > 1)
912 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
914 mode = list;
915 GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
917 ++_dl_skip_args;
918 --_dl_argc;
919 ++INTUSE(_dl_argv);
921 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
923 mode = verify;
925 ++_dl_skip_args;
926 --_dl_argc;
927 ++INTUSE(_dl_argv);
929 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
930 && _dl_argc > 2)
932 library_path = INTUSE(_dl_argv)[2];
934 _dl_skip_args += 2;
935 _dl_argc -= 2;
936 INTUSE(_dl_argv) += 2;
938 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
939 && _dl_argc > 2)
941 GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
943 _dl_skip_args += 2;
944 _dl_argc -= 2;
945 INTUSE(_dl_argv) += 2;
947 else if (! strcmp (INTUSE(_dl_argv)[1], "--audit") && _dl_argc > 2)
949 process_dl_audit (INTUSE(_dl_argv)[2]);
951 _dl_skip_args += 2;
952 _dl_argc -= 2;
953 INTUSE(_dl_argv) += 2;
955 else
956 break;
958 /* If we have no further argument the program was called incorrectly.
959 Grant the user some education. */
960 if (_dl_argc < 2)
961 _dl_fatal_printf ("\
962 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
963 You have invoked `ld.so', the helper program for shared library executables.\n\
964 This program usually lives in the file `/lib/ld.so', and special directives\n\
965 in executable files using ELF shared libraries tell the system's program\n\
966 loader to load the helper program from this file. This helper program loads\n\
967 the shared libraries needed by the program executable, prepares the program\n\
968 to run, and runs it. You may invoke this helper program directly from the\n\
969 command line to load and run an ELF executable file; this is like executing\n\
970 that file itself, but always uses this helper program from the file you\n\
971 specified, instead of the helper program file specified in the executable\n\
972 file you run. This is mostly of use for maintainers to test new versions\n\
973 of this helper program; chances are you did not intend to run this program.\n\
975 --list list all dependencies and how they are resolved\n\
976 --verify verify that given object really is a dynamically linked\n\
977 object we can handle\n\
978 --library-path PATH use given PATH instead of content of the environment\n\
979 variable LD_LIBRARY_PATH\n\
980 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
981 in LIST\n");
983 ++_dl_skip_args;
984 --_dl_argc;
985 ++INTUSE(_dl_argv);
987 /* The initialization of _dl_stack_flags done below assumes the
988 executable's PT_GNU_STACK may have been honored by the kernel, and
989 so a PT_GNU_STACK with PF_X set means the stack started out with
990 execute permission. However, this is not really true if the
991 dynamic linker is the executable the kernel loaded. For this
992 case, we must reinitialize _dl_stack_flags to match the dynamic
993 linker itself. If the dynamic linker was built with a
994 PT_GNU_STACK, then the kernel may have loaded us with a
995 nonexecutable stack that we will have to make executable when we
996 load the program below unless it has a PT_GNU_STACK indicating
997 nonexecutable stack is ok. */
999 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1000 if (ph->p_type == PT_GNU_STACK)
1002 GL(dl_stack_flags) = ph->p_flags;
1003 break;
1006 if (__builtin_expect (mode, normal) == verify)
1008 const char *objname;
1009 const char *err_str = NULL;
1010 struct map_args args;
1011 bool malloced;
1013 args.str = rtld_progname;
1014 args.loader = NULL;
1015 args.is_preloaded = 0;
1016 args.mode = __RTLD_OPENEXEC;
1017 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
1018 &args);
1019 if (__builtin_expect (err_str != NULL, 0))
1020 /* We don't free the returned string, the programs stops
1021 anyway. */
1022 _exit (EXIT_FAILURE);
1024 else
1026 HP_TIMING_NOW (start);
1027 _dl_map_object (NULL, rtld_progname, 0, lt_library, 0,
1028 __RTLD_OPENEXEC, LM_ID_BASE);
1029 HP_TIMING_NOW (stop);
1031 HP_TIMING_DIFF (load_time, start, stop);
1034 /* Now the map for the main executable is available. */
1035 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1037 phdr = main_map->l_phdr;
1038 phnum = main_map->l_phnum;
1039 /* We overwrite here a pointer to a malloc()ed string. But since
1040 the malloc() implementation used at this point is the dummy
1041 implementations which has no real free() function it does not
1042 makes sense to free the old string first. */
1043 main_map->l_name = (char *) "";
1044 *user_entry = main_map->l_entry;
1046 else
1048 /* Create a link_map for the executable itself.
1049 This will be what dlopen on "" returns. */
1050 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1051 __RTLD_OPENEXEC, LM_ID_BASE);
1052 assert (main_map != NULL);
1053 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
1054 main_map->l_phdr = phdr;
1055 main_map->l_phnum = phnum;
1056 main_map->l_entry = *user_entry;
1058 /* At this point we are in a bit of trouble. We would have to
1059 fill in the values for l_dev and l_ino. But in general we
1060 do not know where the file is. We also do not handle AT_EXECFD
1061 even if it would be passed up.
1063 We leave the values here defined to 0. This is normally no
1064 problem as the program code itself is normally no shared
1065 object and therefore cannot be loaded dynamically. Nothing
1066 prevent the use of dynamic binaries and in these situations
1067 we might get problems. We might not be able to find out
1068 whether the object is already loaded. But since there is no
1069 easy way out and because the dynamic binary must also not
1070 have an SONAME we ignore this program for now. If it becomes
1071 a problem we can force people using SONAMEs. */
1073 /* We delay initializing the path structure until we got the dynamic
1074 information for the program. */
1077 main_map->l_map_end = 0;
1078 main_map->l_text_end = 0;
1079 /* Perhaps the executable has no PT_LOAD header entries at all. */
1080 main_map->l_map_start = ~0;
1081 /* And it was opened directly. */
1082 ++main_map->l_direct_opencount;
1084 /* Scan the program header table for the dynamic section. */
1085 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1086 switch (ph->p_type)
1088 case PT_PHDR:
1089 /* Find out the load address. */
1090 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1091 break;
1092 case PT_DYNAMIC:
1093 /* This tells us where to find the dynamic section,
1094 which tells us everything we need to do. */
1095 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
1096 break;
1097 case PT_INTERP:
1098 /* This "interpreter segment" was used by the program loader to
1099 find the program interpreter, which is this program itself, the
1100 dynamic linker. We note what name finds us, so that a future
1101 dlopen call or DT_NEEDED entry, for something that wants to link
1102 against the dynamic linker as a shared library, will know that
1103 the shared object is already loaded. */
1104 _dl_rtld_libname.name = ((const char *) main_map->l_addr
1105 + ph->p_vaddr);
1106 /* _dl_rtld_libname.next = NULL; Already zero. */
1107 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1109 /* Ordinarilly, we would get additional names for the loader from
1110 our DT_SONAME. This can't happen if we were actually linked as
1111 a static executable (detect this case when we have no DYNAMIC).
1112 If so, assume the filename component of the interpreter path to
1113 be our SONAME, and add it to our name list. */
1114 if (GL(dl_rtld_map).l_ld == NULL)
1116 const char *p = NULL;
1117 const char *cp = _dl_rtld_libname.name;
1119 /* Find the filename part of the path. */
1120 while (*cp != '\0')
1121 if (*cp++ == '/')
1122 p = cp;
1124 if (p != NULL)
1126 _dl_rtld_libname2.name = p;
1127 /* _dl_rtld_libname2.next = NULL; Already zero. */
1128 _dl_rtld_libname.next = &_dl_rtld_libname2;
1132 has_interp = true;
1133 break;
1134 case PT_LOAD:
1136 ElfW(Addr) mapstart;
1137 ElfW(Addr) allocend;
1139 /* Remember where the main program starts in memory. */
1140 mapstart = (main_map->l_addr + (ph->p_vaddr & ~(ph->p_align - 1)));
1141 if (main_map->l_map_start > mapstart)
1142 main_map->l_map_start = mapstart;
1144 /* Also where it ends. */
1145 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1146 if (main_map->l_map_end < allocend)
1147 main_map->l_map_end = allocend;
1148 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1149 main_map->l_text_end = allocend;
1151 break;
1153 case PT_TLS:
1154 if (ph->p_memsz > 0)
1156 /* Note that in the case the dynamic linker we duplicate work
1157 here since we read the PT_TLS entry already in
1158 _dl_start_final. But the result is repeatable so do not
1159 check for this special but unimportant case. */
1160 main_map->l_tls_blocksize = ph->p_memsz;
1161 main_map->l_tls_align = ph->p_align;
1162 if (ph->p_align == 0)
1163 main_map->l_tls_firstbyte_offset = 0;
1164 else
1165 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1166 & (ph->p_align - 1));
1167 main_map->l_tls_initimage_size = ph->p_filesz;
1168 main_map->l_tls_initimage = (void *) ph->p_vaddr;
1170 /* This image gets the ID one. */
1171 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1173 break;
1175 case PT_GNU_STACK:
1176 GL(dl_stack_flags) = ph->p_flags;
1177 break;
1179 case PT_GNU_RELRO:
1180 main_map->l_relro_addr = ph->p_vaddr;
1181 main_map->l_relro_size = ph->p_memsz;
1182 break;
1185 /* Adjust the address of the TLS initialization image in case
1186 the executable is actually an ET_DYN object. */
1187 if (main_map->l_tls_initimage != NULL)
1188 main_map->l_tls_initimage
1189 = (char *) main_map->l_tls_initimage + main_map->l_addr;
1190 if (! main_map->l_map_end)
1191 main_map->l_map_end = ~0;
1192 if (! main_map->l_text_end)
1193 main_map->l_text_end = ~0;
1194 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1196 /* We were invoked directly, so the program might not have a
1197 PT_INTERP. */
1198 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1199 /* _dl_rtld_libname.next = NULL; Already zero. */
1200 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1202 else
1203 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1205 /* If the current libname is different from the SONAME, add the
1206 latter as well. */
1207 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1208 && strcmp (GL(dl_rtld_map).l_libname->name,
1209 (const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1210 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1212 static struct libname_list newname;
1213 newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1214 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1215 newname.next = NULL;
1216 newname.dont_free = 1;
1218 assert (GL(dl_rtld_map).l_libname->next == NULL);
1219 GL(dl_rtld_map).l_libname->next = &newname;
1221 /* The ld.so must be relocated since otherwise loading audit modules
1222 will fail since they reuse the very same ld.so. */
1223 assert (GL(dl_rtld_map).l_relocated);
1225 if (! rtld_is_main)
1227 /* Extract the contents of the dynamic section for easy access. */
1228 elf_get_dynamic_info (main_map, NULL);
1229 /* Set up our cache of pointers into the hash table. */
1230 _dl_setup_hash (main_map);
1233 if (__builtin_expect (mode, normal) == verify)
1235 /* We were called just to verify that this is a dynamic
1236 executable using us as the program interpreter. Exit with an
1237 error if we were not able to load the binary or no interpreter
1238 is specified (i.e., this is no dynamically linked binary. */
1239 if (main_map->l_ld == NULL)
1240 _exit (1);
1242 /* We allow here some platform specific code. */
1243 #ifdef DISTINGUISH_LIB_VERSIONS
1244 DISTINGUISH_LIB_VERSIONS;
1245 #endif
1246 _exit (has_interp ? 0 : 2);
1249 struct link_map **first_preload = &GL(dl_rtld_map).l_next;
1250 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1251 /* Set up the data structures for the system-supplied DSO early,
1252 so they can influence _dl_init_paths. */
1253 if (GLRO(dl_sysinfo_dso) != NULL)
1255 /* Do an abridged version of the work _dl_map_object_from_fd would do
1256 to map in the object. It's already mapped and prelinked (and
1257 better be, since it's read-only and so we couldn't relocate it).
1258 We just want our data structures to describe it as if we had just
1259 mapped and relocated it normally. */
1260 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL,
1261 0, LM_ID_BASE);
1262 if (__builtin_expect (l != NULL, 1))
1264 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
1266 l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1267 + GLRO(dl_sysinfo_dso)->e_phoff);
1268 l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1269 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1271 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1272 if (ph->p_type == PT_DYNAMIC)
1274 l->l_ld = (void *) ph->p_vaddr;
1275 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1277 else if (ph->p_type == PT_LOAD)
1279 if (! l->l_addr)
1280 l->l_addr = ph->p_vaddr;
1281 if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1282 l->l_map_end = ph->p_vaddr + ph->p_memsz;
1283 if ((ph->p_flags & PF_X)
1284 && ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1285 l->l_text_end = ph->p_vaddr + ph->p_memsz;
1287 else
1288 /* There must be no TLS segment. */
1289 assert (ph->p_type != PT_TLS);
1291 l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1292 l->l_addr = l->l_map_start - l->l_addr;
1293 l->l_map_end += l->l_addr;
1294 l->l_text_end += l->l_addr;
1295 l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1296 elf_get_dynamic_info (l, dyn_temp);
1297 _dl_setup_hash (l);
1298 l->l_relocated = 1;
1300 /* Initialize l_local_scope to contain just this map. This allows
1301 the use of dl_lookup_symbol_x to resolve symbols within the vdso.
1302 So we create a single entry list pointing to l_real as its only
1303 element */
1304 l->l_local_scope[0]->r_nlist = 1;
1305 l->l_local_scope[0]->r_list = &l->l_real;
1307 /* Now that we have the info handy, use the DSO image's soname
1308 so this object can be looked up by name. Note that we do not
1309 set l_name here. That field gives the file name of the DSO,
1310 and this DSO is not associated with any file. */
1311 if (l->l_info[DT_SONAME] != NULL)
1313 /* Work around a kernel problem. The kernel cannot handle
1314 addresses in the vsyscall DSO pages in writev() calls. */
1315 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1316 + l->l_info[DT_SONAME]->d_un.d_val);
1317 size_t len = strlen (dsoname);
1318 char *copy = malloc (len);
1319 if (copy == NULL)
1320 _dl_fatal_printf ("out of memory\n");
1321 l->l_libname->name = memcpy (copy, dsoname, len);
1324 /* Rearrange the list so this DSO appears after rtld_map. */
1325 assert (l->l_next == NULL);
1326 assert (l->l_prev == main_map);
1327 GL(dl_rtld_map).l_next = l;
1328 l->l_prev = &GL(dl_rtld_map);
1329 first_preload = &l->l_next;
1331 /* We have a prelinked DSO preloaded by the system. */
1332 GLRO(dl_sysinfo_map) = l;
1333 # ifdef NEED_DL_SYSINFO
1334 if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1335 GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1336 # endif
1339 #endif
1341 #ifdef DL_SYSDEP_OSCHECK
1342 DL_SYSDEP_OSCHECK (dl_fatal);
1343 #endif
1345 /* Initialize the data structures for the search paths for shared
1346 objects. */
1347 _dl_init_paths (library_path);
1349 /* Initialize _r_debug. */
1350 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1351 LM_ID_BASE);
1352 r->r_state = RT_CONSISTENT;
1354 /* Put the link_map for ourselves on the chain so it can be found by
1355 name. Note that at this point the global chain of link maps contains
1356 exactly one element, which is pointed to by dl_loaded. */
1357 if (! GL(dl_rtld_map).l_name)
1358 /* If not invoked directly, the dynamic linker shared object file was
1359 found by the PT_INTERP name. */
1360 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1361 GL(dl_rtld_map).l_type = lt_library;
1362 main_map->l_next = &GL(dl_rtld_map);
1363 GL(dl_rtld_map).l_prev = main_map;
1364 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1365 ++GL(dl_load_adds);
1367 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1368 to not using bias for non-prelinked PIEs and libraries
1369 and using it for executables or prelinked PIEs or libraries. */
1370 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1371 GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
1373 /* Set up the program header information for the dynamic linker
1374 itself. It is needed in the dl_iterate_phdr() callbacks. */
1375 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1376 ElfW(Phdr) *rtld_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1377 + rtld_ehdr->e_phoff);
1378 GL(dl_rtld_map).l_phdr = rtld_phdr;
1379 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1382 /* PT_GNU_RELRO is usually the last phdr. */
1383 size_t cnt = rtld_ehdr->e_phnum;
1384 while (cnt-- > 0)
1385 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1387 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1388 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1389 break;
1392 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1393 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1394 /* Assign a module ID. Do this before loading any audit modules. */
1395 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1397 /* If we have auditing DSOs to load, do it now. */
1398 if (__builtin_expect (audit_list != NULL, 0))
1400 /* Iterate over all entries in the list. The order is important. */
1401 struct audit_ifaces *last_audit = NULL;
1402 struct audit_list *al = audit_list->next;
1405 int tls_idx = GL(dl_tls_max_dtv_idx);
1407 /* Now it is time to determine the layout of the static TLS
1408 block and allocate it for the initial thread. Note that we
1409 always allocate the static block, we never defer it even if
1410 no DF_STATIC_TLS bit is set. The reason is that we know
1411 glibc will use the static model. */
1413 /* Since we start using the auditing DSOs right away we need to
1414 initialize the data structures now. */
1415 tcbp = init_tls ();
1417 struct dlmopen_args dlmargs;
1418 dlmargs.fname = al->name;
1419 dlmargs.map = NULL;
1421 const char *objname;
1422 const char *err_str = NULL;
1423 bool malloced;
1424 (void) _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit,
1425 &dlmargs);
1426 if (__builtin_expect (err_str != NULL, 0))
1428 not_loaded:
1429 _dl_error_printf ("\
1430 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
1431 al->name, err_str);
1432 if (malloced)
1433 free ((char *) err_str);
1435 else
1437 struct lookup_args largs;
1438 largs.name = "la_version";
1439 largs.map = dlmargs.map;
1441 /* Check whether the interface version matches. */
1442 (void) _dl_catch_error (&objname, &err_str, &malloced,
1443 lookup_doit, &largs);
1445 unsigned int (*laversion) (unsigned int);
1446 unsigned int lav;
1447 if (err_str == NULL
1448 && (laversion = largs.result) != NULL
1449 && (lav = laversion (LAV_CURRENT)) > 0
1450 && lav <= LAV_CURRENT)
1452 /* Allocate structure for the callback function pointers.
1453 This call can never fail. */
1454 union
1456 struct audit_ifaces ifaces;
1457 #define naudit_ifaces 8
1458 void (*fptr[naudit_ifaces]) (void);
1459 } *newp = malloc (sizeof (*newp));
1461 /* Names of the auditing interfaces. All in one
1462 long string. */
1463 static const char audit_iface_names[] =
1464 "la_activity\0"
1465 "la_objsearch\0"
1466 "la_objopen\0"
1467 "la_preinit\0"
1468 #if __ELF_NATIVE_CLASS == 32
1469 "la_symbind32\0"
1470 #elif __ELF_NATIVE_CLASS == 64
1471 "la_symbind64\0"
1472 #else
1473 # error "__ELF_NATIVE_CLASS must be defined"
1474 #endif
1475 #define STRING(s) __STRING (s)
1476 "la_" STRING (ARCH_LA_PLTENTER) "\0"
1477 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
1478 "la_objclose\0";
1479 unsigned int cnt = 0;
1480 const char *cp = audit_iface_names;
1483 largs.name = cp;
1484 (void) _dl_catch_error (&objname, &err_str, &malloced,
1485 lookup_doit, &largs);
1487 /* Store the pointer. */
1488 if (err_str == NULL && largs.result != NULL)
1490 newp->fptr[cnt] = largs.result;
1492 /* The dynamic linker link map is statically
1493 allocated, initialize the data now. */
1494 GL(dl_rtld_map).l_audit[cnt].cookie
1495 = (intptr_t) &GL(dl_rtld_map);
1497 else
1498 newp->fptr[cnt] = NULL;
1499 ++cnt;
1501 cp = (char *) rawmemchr (cp, '\0') + 1;
1503 while (*cp != '\0');
1504 assert (cnt == naudit_ifaces);
1506 /* Now append the new auditing interface to the list. */
1507 newp->ifaces.next = NULL;
1508 if (last_audit == NULL)
1509 last_audit = GLRO(dl_audit) = &newp->ifaces;
1510 else
1511 last_audit = last_audit->next = &newp->ifaces;
1512 ++GLRO(dl_naudit);
1514 /* Mark the DSO as being used for auditing. */
1515 dlmargs.map->l_auditing = 1;
1517 else
1519 /* We cannot use the DSO, it does not have the
1520 appropriate interfaces or it expects something
1521 more recent. */
1522 #ifndef NDEBUG
1523 Lmid_t ns = dlmargs.map->l_ns;
1524 #endif
1525 _dl_close (dlmargs.map);
1527 /* Make sure the namespace has been cleared entirely. */
1528 assert (GL(dl_ns)[ns]._ns_loaded == NULL);
1529 assert (GL(dl_ns)[ns]._ns_nloaded == 0);
1531 GL(dl_tls_max_dtv_idx) = tls_idx;
1532 goto not_loaded;
1536 al = al->next;
1538 while (al != audit_list->next);
1540 /* If we have any auditing modules, announce that we already
1541 have two objects loaded. */
1542 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1544 struct link_map *ls[2] = { main_map, &GL(dl_rtld_map) };
1546 for (unsigned int outer = 0; outer < 2; ++outer)
1548 struct audit_ifaces *afct = GLRO(dl_audit);
1549 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1551 if (afct->objopen != NULL)
1553 ls[outer]->l_audit[cnt].bindflags
1554 = afct->objopen (ls[outer], LM_ID_BASE,
1555 &ls[outer]->l_audit[cnt].cookie);
1557 ls[outer]->l_audit_any_plt
1558 |= ls[outer]->l_audit[cnt].bindflags != 0;
1561 afct = afct->next;
1567 /* Set up debugging before the debugger is notified for the first time. */
1568 #ifdef ELF_MACHINE_DEBUG_SETUP
1569 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1570 ELF_MACHINE_DEBUG_SETUP (main_map, r);
1571 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1572 #else
1573 if (main_map->l_info[DT_DEBUG] != NULL)
1574 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1575 with the run-time address of the r_debug structure */
1576 main_map->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1578 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1579 case you run gdb on the dynamic linker directly. */
1580 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1581 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1582 #endif
1584 /* We start adding objects. */
1585 r->r_state = RT_ADD;
1586 _dl_debug_state ();
1588 /* Auditing checkpoint: we are ready to signal that the initial map
1589 is being constructed. */
1590 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1592 struct audit_ifaces *afct = GLRO(dl_audit);
1593 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1595 if (afct->activity != NULL)
1596 afct->activity (&main_map->l_audit[cnt].cookie, LA_ACT_ADD);
1598 afct = afct->next;
1602 /* We have two ways to specify objects to preload: via environment
1603 variable and via the file /etc/ld.so.preload. The latter can also
1604 be used when security is enabled. */
1605 assert (*first_preload == NULL);
1606 struct link_map **preloads = NULL;
1607 unsigned int npreloads = 0;
1609 if (__builtin_expect (preloadlist != NULL, 0))
1611 /* The LD_PRELOAD environment variable gives list of libraries
1612 separated by white space or colons that are loaded before the
1613 executable's dependencies and prepended to the global scope
1614 list. If the binary is running setuid all elements
1615 containing a '/' are ignored since it is insecure. */
1616 char *list = strdupa (preloadlist);
1617 char *p;
1619 HP_TIMING_NOW (start);
1621 /* Prevent optimizing strsep. Speed is not important here. */
1622 while ((p = (strsep) (&list, " :")) != NULL)
1623 if (p[0] != '\0'
1624 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1625 || strchr (p, '/') == NULL))
1626 npreloads += do_preload (p, main_map, "LD_PRELOAD");
1628 HP_TIMING_NOW (stop);
1629 HP_TIMING_DIFF (diff, start, stop);
1630 HP_TIMING_ACCUM_NT (load_time, diff);
1633 /* There usually is no ld.so.preload file, it should only be used
1634 for emergencies and testing. So the open call etc should usually
1635 fail. Using access() on a non-existing file is faster than using
1636 open(). So we do this first. If it succeeds we do almost twice
1637 the work but this does not matter, since it is not for production
1638 use. */
1639 static const char preload_file[] = "/etc/ld.so.preload";
1640 if (__builtin_expect (__access (preload_file, R_OK) == 0, 0))
1642 /* Read the contents of the file. */
1643 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1644 PROT_READ | PROT_WRITE);
1645 if (__builtin_expect (file != MAP_FAILED, 0))
1647 /* Parse the file. It contains names of libraries to be loaded,
1648 separated by white spaces or `:'. It may also contain
1649 comments introduced by `#'. */
1650 char *problem;
1651 char *runp;
1652 size_t rest;
1654 /* Eliminate comments. */
1655 runp = file;
1656 rest = file_size;
1657 while (rest > 0)
1659 char *comment = memchr (runp, '#', rest);
1660 if (comment == NULL)
1661 break;
1663 rest -= comment - runp;
1665 *comment = ' ';
1666 while (--rest > 0 && *++comment != '\n');
1669 /* We have one problematic case: if we have a name at the end of
1670 the file without a trailing terminating characters, we cannot
1671 place the \0. Handle the case separately. */
1672 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1673 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1675 problem = &file[file_size];
1676 while (problem > file && problem[-1] != ' '
1677 && problem[-1] != '\t'
1678 && problem[-1] != '\n' && problem[-1] != ':')
1679 --problem;
1681 if (problem > file)
1682 problem[-1] = '\0';
1684 else
1686 problem = NULL;
1687 file[file_size - 1] = '\0';
1690 HP_TIMING_NOW (start);
1692 if (file != problem)
1694 char *p;
1695 runp = file;
1696 while ((p = strsep (&runp, ": \t\n")) != NULL)
1697 if (p[0] != '\0')
1698 npreloads += do_preload (p, main_map, preload_file);
1701 if (problem != NULL)
1703 char *p = strndupa (problem, file_size - (problem - file));
1705 npreloads += do_preload (p, main_map, preload_file);
1708 HP_TIMING_NOW (stop);
1709 HP_TIMING_DIFF (diff, start, stop);
1710 HP_TIMING_ACCUM_NT (load_time, diff);
1712 /* We don't need the file anymore. */
1713 __munmap (file, file_size);
1717 if (__builtin_expect (*first_preload != NULL, 0))
1719 /* Set up PRELOADS with a vector of the preloaded libraries. */
1720 struct link_map *l = *first_preload;
1721 preloads = __alloca (npreloads * sizeof preloads[0]);
1722 i = 0;
1725 preloads[i++] = l;
1726 l = l->l_next;
1727 } while (l);
1728 assert (i == npreloads);
1731 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1732 specified some libraries to load, these are inserted before the actual
1733 dependencies in the executable's searchlist for symbol resolution. */
1734 HP_TIMING_NOW (start);
1735 _dl_map_object_deps (main_map, preloads, npreloads, mode == trace, 0);
1736 HP_TIMING_NOW (stop);
1737 HP_TIMING_DIFF (diff, start, stop);
1738 HP_TIMING_ACCUM_NT (load_time, diff);
1740 /* Mark all objects as being in the global scope. */
1741 for (i = main_map->l_searchlist.r_nlist; i > 0; )
1742 main_map->l_searchlist.r_list[--i]->l_global = 1;
1744 #ifndef MAP_ANON
1745 /* We are done mapping things, so close the zero-fill descriptor. */
1746 __close (_dl_zerofd);
1747 _dl_zerofd = -1;
1748 #endif
1750 /* Remove _dl_rtld_map from the chain. */
1751 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1752 if (GL(dl_rtld_map).l_next != NULL)
1753 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1755 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1756 if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1757 break;
1759 bool rtld_multiple_ref = false;
1760 if (__builtin_expect (i < main_map->l_searchlist.r_nlist, 1))
1762 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1763 put it back in the list of visible objects. We insert it into the
1764 chain in symbol search order because gdb uses the chain's order as
1765 its symbol search order. */
1766 rtld_multiple_ref = true;
1768 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1769 if (__builtin_expect (mode, normal) == normal)
1771 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1772 ? main_map->l_searchlist.r_list[i + 1]
1773 : NULL);
1774 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1775 if (GLRO(dl_sysinfo_map) != NULL
1776 && GL(dl_rtld_map).l_prev->l_next == GLRO(dl_sysinfo_map)
1777 && GL(dl_rtld_map).l_next != GLRO(dl_sysinfo_map))
1778 GL(dl_rtld_map).l_prev = GLRO(dl_sysinfo_map);
1779 #endif
1781 else
1782 /* In trace mode there might be an invisible object (which we
1783 could not find) after the previous one in the search list.
1784 In this case it doesn't matter much where we put the
1785 interpreter object, so we just initialize the list pointer so
1786 that the assertion below holds. */
1787 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1789 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1790 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1791 if (GL(dl_rtld_map).l_next != NULL)
1793 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1794 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1798 /* Now let us see whether all libraries are available in the
1799 versions we need. */
1801 struct version_check_args args;
1802 args.doexit = mode == normal;
1803 args.dotrace = mode == trace;
1804 _dl_receive_error (print_missing_version, version_check_doit, &args);
1807 /* We do not initialize any of the TLS functionality unless any of the
1808 initial modules uses TLS. This makes dynamic loading of modules with
1809 TLS impossible, but to support it requires either eagerly doing setup
1810 now or lazily doing it later. Doing it now makes us incompatible with
1811 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1812 used. Trying to do it lazily is too hairy to try when there could be
1813 multiple threads (from a non-TLS-using libpthread). */
1814 bool was_tls_init_tp_called = tls_init_tp_called;
1815 if (tcbp == NULL)
1816 tcbp = init_tls ();
1818 /* Set up the stack checker's canary. */
1819 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard ();
1820 #ifdef THREAD_SET_STACK_GUARD
1821 THREAD_SET_STACK_GUARD (stack_chk_guard);
1822 #else
1823 __stack_chk_guard = stack_chk_guard;
1824 #endif
1826 /* Set up the pointer guard as well, if necessary. */
1827 if (GLRO(dl_pointer_guard))
1829 // XXX If it is cheap, we should use a separate value.
1830 uintptr_t pointer_chk_guard = stack_chk_guard;
1831 #ifndef HP_TIMING_NONAVAIL
1832 hp_timing_t now;
1833 HP_TIMING_NOW (now);
1834 pointer_chk_guard ^= now;
1835 #endif
1836 #ifdef THREAD_SET_POINTER_GUARD
1837 THREAD_SET_POINTER_GUARD (pointer_chk_guard);
1838 #endif
1839 __pointer_chk_guard_local = pointer_chk_guard;
1842 if (__builtin_expect (mode, normal) != normal)
1844 /* We were run just to list the shared libraries. It is
1845 important that we do this before real relocation, because the
1846 functions we call below for output may no longer work properly
1847 after relocation. */
1848 struct link_map *l;
1850 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1852 struct r_scope_elem *scope = &main_map->l_searchlist;
1854 for (i = 0; i < scope->r_nlist; i++)
1856 l = scope->r_list [i];
1857 if (l->l_faked)
1859 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1860 continue;
1862 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1863 GLRO(dl_trace_prelink_map) = l;
1864 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1865 l->l_libname->name[0] ? l->l_libname->name
1866 : rtld_progname ?: "<main program>",
1867 l->l_name[0] ? l->l_name
1868 : rtld_progname ?: "<main program>",
1869 (int) sizeof l->l_map_start * 2,
1870 (size_t) l->l_map_start,
1871 (int) sizeof l->l_addr * 2,
1872 (size_t) l->l_addr);
1874 if (l->l_tls_modid)
1875 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1876 (int) sizeof l->l_tls_offset * 2,
1877 (size_t) l->l_tls_offset);
1878 else
1879 _dl_printf ("\n");
1882 else if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
1884 /* Look through the dependencies of the main executable
1885 and determine which of them is not actually
1886 required. */
1887 struct link_map *l = main_map;
1889 /* Relocate the main executable. */
1890 struct relocate_args args = { .l = l, .lazy = GLRO(dl_lazy) };
1891 _dl_receive_error (print_unresolved, relocate_doit, &args);
1893 /* This loop depends on the dependencies of the executable to
1894 correspond in number and order to the DT_NEEDED entries. */
1895 ElfW(Dyn) *dyn = main_map->l_ld;
1896 bool first = true;
1897 while (dyn->d_tag != DT_NULL)
1899 if (dyn->d_tag == DT_NEEDED)
1901 l = l->l_next;
1903 if (!l->l_used)
1905 if (first)
1907 _dl_printf ("Unused direct dependencies:\n");
1908 first = false;
1911 _dl_printf ("\t%s\n", l->l_name);
1915 ++dyn;
1918 _exit (first != true);
1920 else if (! main_map->l_info[DT_NEEDED])
1921 _dl_printf ("\tstatically linked\n");
1922 else
1924 for (l = main_map->l_next; l; l = l->l_next)
1925 if (l->l_faked)
1926 /* The library was not found. */
1927 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1928 else if (strcmp (l->l_libname->name, l->l_name) == 0)
1929 _dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
1930 (int) sizeof l->l_map_start * 2,
1931 (size_t) l->l_map_start);
1932 else
1933 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1934 l->l_name, (int) sizeof l->l_map_start * 2,
1935 (size_t) l->l_map_start);
1938 if (__builtin_expect (mode, trace) != trace)
1939 for (i = 1; i < (unsigned int) _dl_argc; ++i)
1941 const ElfW(Sym) *ref = NULL;
1942 ElfW(Addr) loadbase;
1943 lookup_t result;
1945 result = _dl_lookup_symbol_x (INTUSE(_dl_argv)[i], main_map,
1946 &ref, main_map->l_scope,
1947 NULL, ELF_RTYPE_CLASS_PLT,
1948 DL_LOOKUP_ADD_DEPENDENCY, NULL);
1950 loadbase = LOOKUP_VALUE_ADDRESS (result);
1952 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
1953 INTUSE(_dl_argv)[i],
1954 (int) sizeof ref->st_value * 2,
1955 (size_t) ref->st_value,
1956 (int) sizeof loadbase * 2, (size_t) loadbase);
1958 else
1960 /* If LD_WARN is set, warn about undefined symbols. */
1961 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
1963 /* We have to do symbol dependency testing. */
1964 struct relocate_args args;
1965 struct link_map *l;
1967 args.lazy = GLRO(dl_lazy);
1969 l = main_map;
1970 while (l->l_next != NULL)
1971 l = l->l_next;
1974 if (l != &GL(dl_rtld_map) && ! l->l_faked)
1976 args.l = l;
1977 _dl_receive_error (print_unresolved, relocate_doit,
1978 &args);
1980 l = l->l_prev;
1982 while (l != NULL);
1984 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1985 && rtld_multiple_ref)
1987 /* Mark the link map as not yet relocated again. */
1988 GL(dl_rtld_map).l_relocated = 0;
1989 _dl_relocate_object (&GL(dl_rtld_map),
1990 main_map->l_scope, 0, 0);
1993 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
1994 if (version_info)
1996 /* Print more information. This means here, print information
1997 about the versions needed. */
1998 int first = 1;
1999 struct link_map *map;
2001 for (map = main_map; map != NULL; map = map->l_next)
2003 const char *strtab;
2004 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
2005 ElfW(Verneed) *ent;
2007 if (dyn == NULL)
2008 continue;
2010 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
2011 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
2013 if (first)
2015 _dl_printf ("\n\tVersion information:\n");
2016 first = 0;
2019 _dl_printf ("\t%s:\n",
2020 map->l_name[0] ? map->l_name : rtld_progname);
2022 while (1)
2024 ElfW(Vernaux) *aux;
2025 struct link_map *needed;
2027 needed = find_needed (strtab + ent->vn_file);
2028 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
2030 while (1)
2032 const char *fname = NULL;
2034 if (needed != NULL
2035 && match_version (strtab + aux->vna_name,
2036 needed))
2037 fname = needed->l_name;
2039 _dl_printf ("\t\t%s (%s) %s=> %s\n",
2040 strtab + ent->vn_file,
2041 strtab + aux->vna_name,
2042 aux->vna_flags & VER_FLG_WEAK
2043 ? "[WEAK] " : "",
2044 fname ?: "not found");
2046 if (aux->vna_next == 0)
2047 /* No more symbols. */
2048 break;
2050 /* Next symbol. */
2051 aux = (ElfW(Vernaux) *) ((char *) aux
2052 + aux->vna_next);
2055 if (ent->vn_next == 0)
2056 /* No more dependencies. */
2057 break;
2059 /* Next dependency. */
2060 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
2066 _exit (0);
2069 if (main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]
2070 && ! __builtin_expect (GLRO(dl_profile) != NULL, 0)
2071 && ! __builtin_expect (GLRO(dl_dynamic_weak), 0))
2073 ElfW(Lib) *liblist, *liblistend;
2074 struct link_map **r_list, **r_listend, *l;
2075 const char *strtab = (const void *) D_PTR (main_map, l_info[DT_STRTAB]);
2077 assert (main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
2078 liblist = (ElfW(Lib) *)
2079 main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
2080 liblistend = (ElfW(Lib) *)
2081 ((char *) liblist +
2082 main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
2083 r_list = main_map->l_searchlist.r_list;
2084 r_listend = r_list + main_map->l_searchlist.r_nlist;
2086 for (; r_list < r_listend && liblist < liblistend; r_list++)
2088 l = *r_list;
2090 if (l == main_map)
2091 continue;
2093 /* If the library is not mapped where it should, fail. */
2094 if (l->l_addr)
2095 break;
2097 /* Next, check if checksum matches. */
2098 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
2099 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
2100 != liblist->l_checksum)
2101 break;
2103 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
2104 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
2105 != liblist->l_time_stamp)
2106 break;
2108 if (! _dl_name_match_p (strtab + liblist->l_name, l))
2109 break;
2111 ++liblist;
2115 if (r_list == r_listend && liblist == liblistend)
2116 prelinked = true;
2118 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
2119 _dl_debug_printf ("\nprelink checking: %s\n",
2120 prelinked ? "ok" : "failed");
2124 /* Now set up the variable which helps the assembler startup code. */
2125 GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
2127 /* Save the information about the original global scope list since
2128 we need it in the memory handling later. */
2129 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
2131 if (prelinked)
2133 if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
2135 ElfW(Rela) *conflict, *conflictend;
2136 #ifndef HP_TIMING_NONAVAIL
2137 hp_timing_t start;
2138 hp_timing_t stop;
2139 #endif
2141 HP_TIMING_NOW (start);
2142 assert (main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
2143 conflict = (ElfW(Rela) *)
2144 main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
2145 conflictend = (ElfW(Rela) *)
2146 ((char *) conflict
2147 + main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
2148 _dl_resolve_conflicts (main_map, conflict, conflictend);
2149 HP_TIMING_NOW (stop);
2150 HP_TIMING_DIFF (relocate_time, start, stop);
2154 /* Mark all the objects so we know they have been already relocated. */
2155 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2157 l->l_relocated = 1;
2158 if (l->l_relro_size)
2159 _dl_protect_relro (l);
2161 /* Add object to slot information data if necessasy. */
2162 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2163 _dl_add_to_slotinfo (l);
2166 _dl_sysdep_start_cleanup ();
2168 else
2170 /* Now we have all the objects loaded. Relocate them all except for
2171 the dynamic linker itself. We do this in reverse order so that copy
2172 relocs of earlier objects overwrite the data written by later
2173 objects. We do not re-relocate the dynamic linker itself in this
2174 loop because that could result in the GOT entries for functions we
2175 call being changed, and that would break us. It is safe to relocate
2176 the dynamic linker out of order because it has no copy relocs (we
2177 know that because it is self-contained). */
2179 int consider_profiling = GLRO(dl_profile) != NULL;
2180 #ifndef HP_TIMING_NONAVAIL
2181 hp_timing_t start;
2182 hp_timing_t stop;
2183 #endif
2185 /* If we are profiling we also must do lazy reloaction. */
2186 GLRO(dl_lazy) |= consider_profiling;
2188 struct link_map *l = main_map;
2189 while (l->l_next)
2190 l = l->l_next;
2192 HP_TIMING_NOW (start);
2195 /* While we are at it, help the memory handling a bit. We have to
2196 mark some data structures as allocated with the fake malloc()
2197 implementation in ld.so. */
2198 struct libname_list *lnp = l->l_libname->next;
2200 while (__builtin_expect (lnp != NULL, 0))
2202 lnp->dont_free = 1;
2203 lnp = lnp->next;
2206 if (l != &GL(dl_rtld_map))
2207 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy),
2208 consider_profiling);
2210 /* Add object to slot information data if necessasy. */
2211 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2212 _dl_add_to_slotinfo (l);
2214 l = l->l_prev;
2216 while (l);
2217 HP_TIMING_NOW (stop);
2219 HP_TIMING_DIFF (relocate_time, start, stop);
2221 /* Do any necessary cleanups for the startup OS interface code.
2222 We do these now so that no calls are made after rtld re-relocation
2223 which might be resolved to different functions than we expect.
2224 We cannot do this before relocating the other objects because
2225 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2226 _dl_sysdep_start_cleanup ();
2228 /* Now enable profiling if needed. Like the previous call,
2229 this has to go here because the calls it makes should use the
2230 rtld versions of the functions (particularly calloc()), but it
2231 needs to have _dl_profile_map set up by the relocator. */
2232 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
2233 /* We must prepare the profiling. */
2234 _dl_start_profile ();
2237 #ifndef NONTLS_INIT_TP
2238 # define NONTLS_INIT_TP do { } while (0)
2239 #endif
2241 if (!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2242 ++GL(dl_tls_generation);
2244 /* Now that we have completed relocation, the initializer data
2245 for the TLS blocks has its final values and we can copy them
2246 into the main thread's TLS area, which we allocated above. */
2247 _dl_allocate_tls_init (tcbp);
2249 /* And finally install it for the main thread. If ld.so itself uses
2250 TLS we know the thread pointer was initialized earlier. */
2251 if (! tls_init_tp_called)
2253 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
2254 if (__builtin_expect (lossage != NULL, 0))
2255 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2256 lossage);
2259 if (! prelinked && rtld_multiple_ref)
2261 /* There was an explicit ref to the dynamic linker as a shared lib.
2262 Re-relocate ourselves with user-controlled symbol definitions.
2264 We must do this after TLS initialization in case after this
2265 re-relocation, we might call a user-supplied function
2266 (e.g. calloc from _dl_relocate_object) that uses TLS data. */
2268 #ifndef HP_TIMING_NONAVAIL
2269 hp_timing_t start;
2270 hp_timing_t stop;
2271 hp_timing_t add;
2272 #endif
2274 HP_TIMING_NOW (start);
2275 /* Mark the link map as not yet relocated again. */
2276 GL(dl_rtld_map).l_relocated = 0;
2277 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2278 HP_TIMING_NOW (stop);
2279 HP_TIMING_DIFF (add, start, stop);
2280 HP_TIMING_ACCUM_NT (relocate_time, add);
2283 #ifdef SHARED
2284 /* Auditing checkpoint: we have added all objects. */
2285 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
2287 struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2288 /* Do not call the functions for any auditing object. */
2289 if (head->l_auditing == 0)
2291 struct audit_ifaces *afct = GLRO(dl_audit);
2292 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2294 if (afct->activity != NULL)
2295 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
2297 afct = afct->next;
2301 #endif
2303 /* Notify the debugger all new objects are now ready to go. We must re-get
2304 the address since by now the variable might be in another object. */
2305 r = _dl_debug_initialize (0, LM_ID_BASE);
2306 r->r_state = RT_CONSISTENT;
2307 _dl_debug_state ();
2309 #ifndef MAP_COPY
2310 /* We must munmap() the cache file. */
2311 _dl_unload_cache ();
2312 #endif
2314 /* Once we return, _dl_sysdep_start will invoke
2315 the DT_INIT functions and then *USER_ENTRY. */
2318 /* This is a little helper function for resolving symbols while
2319 tracing the binary. */
2320 static void
2321 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2322 const char *errstring)
2324 if (objname[0] == '\0')
2325 objname = rtld_progname ?: "<main program>";
2326 _dl_error_printf ("%s (%s)\n", errstring, objname);
2329 /* This is a little helper function for resolving symbols while
2330 tracing the binary. */
2331 static void
2332 print_missing_version (int errcode __attribute__ ((unused)),
2333 const char *objname, const char *errstring)
2335 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
2336 objname, errstring);
2339 /* Nonzero if any of the debugging options is enabled. */
2340 static int any_debug attribute_relro;
2342 /* Process the string given as the parameter which explains which debugging
2343 options are enabled. */
2344 static void
2345 process_dl_debug (const char *dl_debug)
2347 /* When adding new entries make sure that the maximal length of a name
2348 is correctly handled in the LD_DEBUG_HELP code below. */
2349 static const struct
2351 unsigned char len;
2352 const char name[10];
2353 const char helptext[41];
2354 unsigned short int mask;
2355 } debopts[] =
2357 #define LEN_AND_STR(str) sizeof (str) - 1, str
2358 { LEN_AND_STR ("libs"), "display library search paths",
2359 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2360 { LEN_AND_STR ("reloc"), "display relocation processing",
2361 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2362 { LEN_AND_STR ("files"), "display progress for input file",
2363 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2364 { LEN_AND_STR ("symbols"), "display symbol table processing",
2365 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2366 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2367 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2368 { LEN_AND_STR ("versions"), "display version dependencies",
2369 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2370 { LEN_AND_STR ("all"), "all previous options combined",
2371 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2372 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2373 { LEN_AND_STR ("statistics"), "display relocation statistics",
2374 DL_DEBUG_STATISTICS },
2375 { LEN_AND_STR ("unused"), "determined unused DSOs",
2376 DL_DEBUG_UNUSED },
2377 { LEN_AND_STR ("help"), "display this help message and exit",
2378 DL_DEBUG_HELP },
2380 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2382 /* Skip separating white spaces and commas. */
2383 while (*dl_debug != '\0')
2385 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2387 size_t cnt;
2388 size_t len = 1;
2390 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2391 && dl_debug[len] != ',' && dl_debug[len] != ':')
2392 ++len;
2394 for (cnt = 0; cnt < ndebopts; ++cnt)
2395 if (debopts[cnt].len == len
2396 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
2398 GLRO(dl_debug_mask) |= debopts[cnt].mask;
2399 any_debug = 1;
2400 break;
2403 if (cnt == ndebopts)
2405 /* Display a warning and skip everything until next
2406 separator. */
2407 char *copy = strndupa (dl_debug, len);
2408 _dl_error_printf ("\
2409 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2412 dl_debug += len;
2413 continue;
2416 ++dl_debug;
2419 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
2421 size_t cnt;
2423 _dl_printf ("\
2424 Valid options for the LD_DEBUG environment variable are:\n\n");
2426 for (cnt = 0; cnt < ndebopts; ++cnt)
2427 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2428 " " + debopts[cnt].len - 3,
2429 debopts[cnt].helptext);
2431 _dl_printf ("\n\
2432 To direct the debugging output into a file instead of standard output\n\
2433 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2434 _exit (0);
2438 static void
2439 process_dl_audit (char *str)
2441 /* The parameter is a colon separated list of DSO names. */
2442 char *p;
2444 while ((p = (strsep) (&str, ":")) != NULL)
2445 if (p[0] != '\0'
2446 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
2447 || strchr (p, '/') == NULL))
2449 /* This is using the local malloc, not the system malloc. The
2450 memory can never be freed. */
2451 struct audit_list *newp = malloc (sizeof (*newp));
2452 newp->name = p;
2454 if (audit_list == NULL)
2455 audit_list = newp->next = newp;
2456 else
2458 newp->next = audit_list->next;
2459 audit_list = audit_list->next = newp;
2464 /* Process all environments variables the dynamic linker must recognize.
2465 Since all of them start with `LD_' we are a bit smarter while finding
2466 all the entries. */
2467 extern char **_environ attribute_hidden;
2470 static void
2471 process_envvars (enum mode *modep)
2473 char **runp = _environ;
2474 char *envline;
2475 enum mode mode = normal;
2476 char *debug_output = NULL;
2478 /* This is the default place for profiling data file. */
2479 GLRO(dl_profile_output)
2480 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2482 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2484 size_t len = 0;
2486 while (envline[len] != '\0' && envline[len] != '=')
2487 ++len;
2489 if (envline[len] != '=')
2490 /* This is a "LD_" variable at the end of the string without
2491 a '=' character. Ignore it since otherwise we will access
2492 invalid memory below. */
2493 continue;
2495 switch (len)
2497 case 4:
2498 /* Warning level, verbose or not. */
2499 if (memcmp (envline, "WARN", 4) == 0)
2500 GLRO(dl_verbose) = envline[5] != '\0';
2501 break;
2503 case 5:
2504 /* Debugging of the dynamic linker? */
2505 if (memcmp (envline, "DEBUG", 5) == 0)
2507 process_dl_debug (&envline[6]);
2508 break;
2510 if (memcmp (envline, "AUDIT", 5) == 0)
2511 process_dl_audit (&envline[6]);
2512 break;
2514 case 7:
2515 /* Print information about versions. */
2516 if (memcmp (envline, "VERBOSE", 7) == 0)
2518 version_info = envline[8] != '\0';
2519 break;
2522 /* List of objects to be preloaded. */
2523 if (memcmp (envline, "PRELOAD", 7) == 0)
2525 preloadlist = &envline[8];
2526 break;
2529 /* Which shared object shall be profiled. */
2530 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2531 GLRO(dl_profile) = &envline[8];
2532 break;
2534 case 8:
2535 /* Do we bind early? */
2536 if (memcmp (envline, "BIND_NOW", 8) == 0)
2538 GLRO(dl_lazy) = envline[9] == '\0';
2539 break;
2541 if (memcmp (envline, "BIND_NOT", 8) == 0)
2542 GLRO(dl_bind_not) = envline[9] != '\0';
2543 break;
2545 case 9:
2546 /* Test whether we want to see the content of the auxiliary
2547 array passed up from the kernel. */
2548 if (!INTUSE(__libc_enable_secure)
2549 && memcmp (envline, "SHOW_AUXV", 9) == 0)
2550 _dl_show_auxv ();
2551 break;
2553 case 10:
2554 /* Mask for the important hardware capabilities. */
2555 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2556 GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2557 0, 0);
2558 break;
2560 case 11:
2561 /* Path where the binary is found. */
2562 if (!INTUSE(__libc_enable_secure)
2563 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2564 GLRO(dl_origin_path) = &envline[12];
2565 break;
2567 case 12:
2568 /* The library search path. */
2569 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2571 library_path = &envline[13];
2572 break;
2575 /* Where to place the profiling data file. */
2576 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2578 debug_output = &envline[13];
2579 break;
2582 if (!INTUSE(__libc_enable_secure)
2583 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2584 GLRO(dl_dynamic_weak) = 1;
2585 break;
2587 case 13:
2588 /* We might have some extra environment variable with length 13
2589 to handle. */
2590 #ifdef EXTRA_LD_ENVVARS_13
2591 EXTRA_LD_ENVVARS_13
2592 #endif
2593 if (!INTUSE(__libc_enable_secure)
2594 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2596 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2597 break;
2600 if (memcmp (envline, "POINTER_GUARD", 13) == 0)
2601 GLRO(dl_pointer_guard) = envline[14] != '0';
2602 break;
2604 case 14:
2605 /* Where to place the profiling data file. */
2606 if (!INTUSE(__libc_enable_secure)
2607 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2608 && envline[15] != '\0')
2609 GLRO(dl_profile_output) = &envline[15];
2610 break;
2612 case 16:
2613 /* The mode of the dynamic linker can be set. */
2614 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2616 mode = trace;
2617 GLRO(dl_verbose) = 1;
2618 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2619 GLRO(dl_trace_prelink) = &envline[17];
2621 break;
2623 case 20:
2624 /* The mode of the dynamic linker can be set. */
2625 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2626 mode = trace;
2627 break;
2629 /* We might have some extra environment variable to handle. This
2630 is tricky due to the pre-processing of the length of the name
2631 in the switch statement here. The code here assumes that added
2632 environment variables have a different length. */
2633 #ifdef EXTRA_LD_ENVVARS
2634 EXTRA_LD_ENVVARS
2635 #endif
2639 /* The caller wants this information. */
2640 *modep = mode;
2642 /* Extra security for SUID binaries. Remove all dangerous environment
2643 variables. */
2644 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2646 static const char unsecure_envvars[] =
2647 #ifdef EXTRA_UNSECURE_ENVVARS
2648 EXTRA_UNSECURE_ENVVARS
2649 #endif
2650 UNSECURE_ENVVARS;
2651 const char *nextp;
2653 nextp = unsecure_envvars;
2656 unsetenv (nextp);
2657 /* We could use rawmemchr but this need not be fast. */
2658 nextp = (char *) (strchr) (nextp, '\0') + 1;
2660 while (*nextp != '\0');
2662 if (__access ("/etc/suid-debug", F_OK) != 0)
2664 unsetenv ("MALLOC_CHECK_");
2665 GLRO(dl_debug_mask) = 0;
2668 if (mode != normal)
2669 _exit (5);
2671 /* If we have to run the dynamic linker in debugging mode and the
2672 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2673 messages to this file. */
2674 else if (any_debug && debug_output != NULL)
2676 #ifdef O_NOFOLLOW
2677 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2678 #else
2679 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2680 #endif
2681 size_t name_len = strlen (debug_output);
2682 char buf[name_len + 12];
2683 char *startp;
2685 buf[name_len + 11] = '\0';
2686 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2687 *--startp = '.';
2688 startp = memcpy (startp - name_len, debug_output, name_len);
2690 GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2691 if (GLRO(dl_debug_fd) == -1)
2692 /* We use standard output if opening the file failed. */
2693 GLRO(dl_debug_fd) = STDOUT_FILENO;
2698 /* Print the various times we collected. */
2699 static void
2700 __attribute ((noinline))
2701 print_statistics (hp_timing_t *rtld_total_timep)
2703 #ifndef HP_TIMING_NONAVAIL
2704 char buf[200];
2705 char *cp;
2706 char *wp;
2708 /* Total time rtld used. */
2709 if (HP_TIMING_AVAIL)
2711 HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2712 _dl_debug_printf ("\nruntime linker statistics:\n"
2713 " total startup time in dynamic loader: %s\n", buf);
2715 /* Print relocation statistics. */
2716 char pbuf[30];
2717 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2718 cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2719 pbuf + sizeof (pbuf), 10, 0);
2720 wp = pbuf;
2721 switch (pbuf + sizeof (pbuf) - cp)
2723 case 3:
2724 *wp++ = *cp++;
2725 case 2:
2726 *wp++ = *cp++;
2727 case 1:
2728 *wp++ = '.';
2729 *wp++ = *cp++;
2731 *wp = '\0';
2732 _dl_debug_printf ("\
2733 time needed for relocation: %s (%s%%)\n", buf, pbuf);
2735 #endif
2737 unsigned long int num_relative_relocations = 0;
2738 for (Lmid_t ns = 0; ns < DL_NNS; ++ns)
2740 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2741 continue;
2743 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2745 for (unsigned int i = 0; i < scope->r_nlist; i++)
2747 struct link_map *l = scope->r_list [i];
2749 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2750 num_relative_relocations
2751 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2752 #ifndef ELF_MACHINE_REL_RELATIVE
2753 /* Relative relocations are processed on these architectures if
2754 library is loaded to different address than p_vaddr or
2755 if not prelinked. */
2756 if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2757 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2758 #else
2759 /* On e.g. IA-64 or Alpha, relative relocations are processed
2760 only if library is loaded to different address than p_vaddr. */
2761 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2762 #endif
2763 num_relative_relocations
2764 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2768 _dl_debug_printf (" number of relocations: %lu\n"
2769 " number of relocations from cache: %lu\n"
2770 " number of relative relocations: %lu\n",
2771 GL(dl_num_relocations),
2772 GL(dl_num_cache_relocations),
2773 num_relative_relocations);
2775 #ifndef HP_TIMING_NONAVAIL
2776 /* Time spend while loading the object and the dependencies. */
2777 if (HP_TIMING_AVAIL)
2779 char pbuf[30];
2780 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2781 cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2782 pbuf + sizeof (pbuf), 10, 0);
2783 wp = pbuf;
2784 switch (pbuf + sizeof (pbuf) - cp)
2786 case 3:
2787 *wp++ = *cp++;
2788 case 2:
2789 *wp++ = *cp++;
2790 case 1:
2791 *wp++ = '.';
2792 *wp++ = *cp++;
2794 *wp = '\0';
2795 _dl_debug_printf ("\
2796 time needed to load objects: %s (%s%%)\n",
2797 buf, pbuf);
2799 #endif