[BZ #3273]
[glibc.git] / elf / rtld.c
blob718fa13b71cd164724cb21a4677bd38ca0352ca8
1 /* Run time dynamic linker.
2 Copyright (C) 1995-2002, 2003, 2004, 2005, 2006 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 #if defined PI_STATIC_AND_HIDDEN && defined HAVE_HIDDEN \
211 && defined HAVE_VISIBILITY_ATTRIBUTE
212 # define DONT_USE_BOOTSTRAP_MAP 1
213 #endif
215 #ifdef DONT_USE_BOOTSTRAP_MAP
216 static ElfW(Addr) _dl_start_final (void *arg);
217 #else
218 struct dl_start_final_info
220 struct link_map l;
221 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
222 hp_timing_t start_time;
223 #endif
225 static ElfW(Addr) _dl_start_final (void *arg,
226 struct dl_start_final_info *info);
227 #endif
229 /* These defined magically in the linker script. */
230 extern char _begin[] attribute_hidden;
231 extern char _etext[] attribute_hidden;
232 extern char _end[] attribute_hidden;
235 #ifdef RTLD_START
236 RTLD_START
237 #else
238 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
239 #endif
241 #ifndef VALIDX
242 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
243 + DT_EXTRANUM + DT_VALTAGIDX (tag))
244 #endif
245 #ifndef ADDRIDX
246 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
247 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
248 #endif
250 /* This is the second half of _dl_start (below). It can be inlined safely
251 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
252 references. When the tools don't permit us to avoid using a GOT entry
253 for _dl_rtld_global (no attribute_hidden support), we must make sure
254 this function is not inlined (see below). */
256 #ifdef DONT_USE_BOOTSTRAP_MAP
257 static inline ElfW(Addr) __attribute__ ((always_inline))
258 _dl_start_final (void *arg)
259 #else
260 static ElfW(Addr) __attribute__ ((noinline))
261 _dl_start_final (void *arg, struct dl_start_final_info *info)
262 #endif
264 ElfW(Addr) start_addr;
266 if (HP_TIMING_AVAIL)
268 /* If it hasn't happen yet record the startup time. */
269 if (! HP_TIMING_INLINE)
270 HP_TIMING_NOW (start_time);
271 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
272 else
273 start_time = info->start_time;
274 #endif
276 /* Initialize the timing functions. */
277 HP_TIMING_DIFF_INIT ();
280 /* Transfer data about ourselves to the permanent link_map structure. */
281 #ifndef DONT_USE_BOOTSTRAP_MAP
282 GL(dl_rtld_map).l_addr = info->l.l_addr;
283 GL(dl_rtld_map).l_ld = info->l.l_ld;
284 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
285 sizeof GL(dl_rtld_map).l_info);
286 GL(dl_rtld_map).l_mach = info->l.l_mach;
287 GL(dl_rtld_map).l_relocated = 1;
288 #endif
289 _dl_setup_hash (&GL(dl_rtld_map));
290 GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
291 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
292 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
293 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
294 /* Copy the TLS related data if necessary. */
295 #if USE_TLS && !defined DONT_USE_BOOTSTRAP_MAP
296 # if USE___THREAD
297 assert (info->l.l_tls_modid != 0);
298 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
299 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
300 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
301 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
302 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
303 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
304 GL(dl_rtld_map).l_tls_modid = 1;
305 # else
306 # if NO_TLS_OFFSET != 0
307 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
308 # endif
309 # endif
311 #endif
313 #if HP_TIMING_AVAIL
314 HP_TIMING_NOW (GL(dl_cpuclock_offset));
315 #endif
317 /* Initialize the stack end variable. */
318 __libc_stack_end = __builtin_frame_address (0);
320 /* Call the OS-dependent function to set up life so we can do things like
321 file access. It will call `dl_main' (below) to do all the real work
322 of the dynamic linker, and then unwind our frame and run the user
323 entry point on the same stack we entered on. */
324 start_addr = _dl_sysdep_start (arg, &dl_main);
326 #ifndef HP_TIMING_NONAVAIL
327 hp_timing_t rtld_total_time;
328 if (HP_TIMING_AVAIL)
330 hp_timing_t end_time;
332 /* Get the current time. */
333 HP_TIMING_NOW (end_time);
335 /* Compute the difference. */
336 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
338 #endif
340 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
342 #ifndef HP_TIMING_NONAVAIL
343 print_statistics (&rtld_total_time);
344 #else
345 print_statistics (NULL);
346 #endif
349 return start_addr;
352 static ElfW(Addr) __attribute_used__ internal_function
353 _dl_start (void *arg)
355 #ifdef DONT_USE_BOOTSTRAP_MAP
356 # define bootstrap_map GL(dl_rtld_map)
357 #else
358 struct dl_start_final_info info;
359 # define bootstrap_map info.l
360 #endif
362 /* This #define produces dynamic linking inline functions for
363 bootstrap relocation instead of general-purpose relocation. */
364 #define RTLD_BOOTSTRAP
365 #define RESOLVE_MAP(sym, version, flags) \
366 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : &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 defined USE_TLS && 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 #ifdef USE_TLS
705 static bool tls_init_tp_called;
707 static void *
708 init_tls (void)
710 /* Number of elements in the static TLS block. */
711 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
713 /* Do not do this twice. The audit interface might have required
714 the DTV interfaces to be set up early. */
715 if (GL(dl_initial_dtv) != NULL)
716 return NULL;
718 /* Allocate the array which contains the information about the
719 dtv slots. We allocate a few entries more than needed to
720 avoid the need for reallocation. */
721 size_t nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
723 /* Allocate. */
724 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
725 calloc (sizeof (struct dtv_slotinfo_list)
726 + nelem * sizeof (struct dtv_slotinfo), 1);
727 /* No need to check the return value. If memory allocation failed
728 the program would have been terminated. */
730 struct dtv_slotinfo *slotinfo = GL(dl_tls_dtv_slotinfo_list)->slotinfo;
731 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
732 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
734 /* Fill in the information from the loaded modules. No namespace
735 but the base one can be filled at this time. */
736 assert (GL(dl_ns)[LM_ID_BASE + 1]._ns_loaded == NULL);
737 int i = 0;
738 for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
739 l = l->l_next)
740 if (l->l_tls_blocksize != 0)
742 /* This is a module with TLS data. Store the map reference.
743 The generation counter is zero. */
744 slotinfo[i].map = l;
745 /* slotinfo[i].gen = 0; */
746 ++i;
748 assert (i == GL(dl_tls_max_dtv_idx));
750 /* Compute the TLS offsets for the various blocks. */
751 _dl_determine_tlsoffset ();
753 /* Construct the static TLS block and the dtv for the initial
754 thread. For some platforms this will include allocating memory
755 for the thread descriptor. The memory for the TLS block will
756 never be freed. It should be allocated accordingly. The dtv
757 array can be changed if dynamic loading requires it. */
758 void *tcbp = _dl_allocate_tls_storage ();
759 if (tcbp == NULL)
760 _dl_fatal_printf ("\
761 cannot allocate TLS data structures for initial thread");
763 /* Store for detection of the special case by __tls_get_addr
764 so it knows not to pass this dtv to the normal realloc. */
765 GL(dl_initial_dtv) = GET_DTV (tcbp);
767 /* And finally install it for the main thread. If ld.so itself uses
768 TLS we know the thread pointer was initialized earlier. */
769 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
770 if (__builtin_expect (lossage != NULL, 0))
771 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
772 tls_init_tp_called = true;
774 return tcbp;
776 #endif
778 #ifdef _LIBC_REENTRANT
779 /* _dl_error_catch_tsd points to this for the single-threaded case.
780 It's reset by the thread library for multithreaded programs. */
781 void ** __attribute__ ((const))
782 _dl_initial_error_catch_tsd (void)
784 static void *data;
785 return &data;
787 #endif
790 static unsigned int
791 do_preload (char *fname, struct link_map *main_map, const char *where)
793 const char *objname;
794 const char *err_str = NULL;
795 struct map_args args;
796 bool malloced;
798 args.str = fname;
799 args.loader = main_map;
800 args.is_preloaded = 1;
801 args.mode = 0;
803 unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
805 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
806 if (__builtin_expect (err_str != NULL, 0))
808 _dl_error_printf ("\
809 ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
810 fname, where);
811 /* No need to call free, this is still before
812 the libc's malloc is used. */
814 else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
815 /* It is no duplicate. */
816 return 1;
818 /* Nothing loaded. */
819 return 0;
822 #if defined SHARED && defined _LIBC_REENTRANT \
823 && defined __rtld_lock_default_lock_recursive
824 static void
825 rtld_lock_default_lock_recursive (void *lock)
827 __rtld_lock_default_lock_recursive (lock);
830 static void
831 rtld_lock_default_unlock_recursive (void *lock)
833 __rtld_lock_default_unlock_recursive (lock);
835 #endif
838 /* The library search path. */
839 static const char *library_path attribute_relro;
840 /* The list preloaded objects. */
841 static const char *preloadlist attribute_relro;
842 /* Nonzero if information about versions has to be printed. */
843 static int version_info attribute_relro;
845 static void
846 dl_main (const ElfW(Phdr) *phdr,
847 ElfW(Word) phnum,
848 ElfW(Addr) *user_entry)
850 const ElfW(Phdr) *ph;
851 enum mode mode;
852 struct link_map *main_map;
853 size_t file_size;
854 char *file;
855 bool has_interp = false;
856 unsigned int i;
857 bool prelinked = false;
858 bool rtld_is_main = false;
859 #ifndef HP_TIMING_NONAVAIL
860 hp_timing_t start;
861 hp_timing_t stop;
862 hp_timing_t diff;
863 #endif
864 #ifdef USE_TLS
865 void *tcbp = NULL;
866 #endif
868 #ifdef _LIBC_REENTRANT
869 /* Explicit initialization since the reloc would just be more work. */
870 GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
871 #endif
873 #ifdef USE_TLS
874 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
875 #endif
877 #if defined SHARED && defined _LIBC_REENTRANT \
878 && defined __rtld_lock_default_lock_recursive
879 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
880 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
881 #endif
883 /* The explicit initialization here is cheaper than processing the reloc
884 in the _rtld_local definition's initializer. */
885 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
887 /* Process the environment variable which control the behaviour. */
888 process_envvars (&mode);
890 #ifndef HAVE_INLINED_SYSCALLS
891 /* Set up a flag which tells we are just starting. */
892 INTUSE(_dl_starting_up) = 1;
893 #endif
895 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
897 /* Ho ho. We are not the program interpreter! We are the program
898 itself! This means someone ran ld.so as a command. Well, that
899 might be convenient to do sometimes. We support it by
900 interpreting the args like this:
902 ld.so PROGRAM ARGS...
904 The first argument is the name of a file containing an ELF
905 executable we will load and run with the following arguments.
906 To simplify life here, PROGRAM is searched for using the
907 normal rules for shared objects, rather than $PATH or anything
908 like that. We just load it and use its entry point; we don't
909 pay attention to its PT_INTERP command (we are the interpreter
910 ourselves). This is an easy way to test a new ld.so before
911 installing it. */
912 rtld_is_main = true;
914 /* Note the place where the dynamic linker actually came from. */
915 GL(dl_rtld_map).l_name = rtld_progname;
917 while (_dl_argc > 1)
918 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
920 mode = list;
921 GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
923 ++_dl_skip_args;
924 --_dl_argc;
925 ++INTUSE(_dl_argv);
927 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
929 mode = verify;
931 ++_dl_skip_args;
932 --_dl_argc;
933 ++INTUSE(_dl_argv);
935 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
936 && _dl_argc > 2)
938 library_path = INTUSE(_dl_argv)[2];
940 _dl_skip_args += 2;
941 _dl_argc -= 2;
942 INTUSE(_dl_argv) += 2;
944 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
945 && _dl_argc > 2)
947 GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
949 _dl_skip_args += 2;
950 _dl_argc -= 2;
951 INTUSE(_dl_argv) += 2;
953 else if (! strcmp (INTUSE(_dl_argv)[1], "--audit") && _dl_argc > 2)
955 process_dl_audit (INTUSE(_dl_argv)[2]);
957 _dl_skip_args += 2;
958 _dl_argc -= 2;
959 INTUSE(_dl_argv) += 2;
961 else
962 break;
964 /* If we have no further argument the program was called incorrectly.
965 Grant the user some education. */
966 if (_dl_argc < 2)
967 _dl_fatal_printf ("\
968 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
969 You have invoked `ld.so', the helper program for shared library executables.\n\
970 This program usually lives in the file `/lib/ld.so', and special directives\n\
971 in executable files using ELF shared libraries tell the system's program\n\
972 loader to load the helper program from this file. This helper program loads\n\
973 the shared libraries needed by the program executable, prepares the program\n\
974 to run, and runs it. You may invoke this helper program directly from the\n\
975 command line to load and run an ELF executable file; this is like executing\n\
976 that file itself, but always uses this helper program from the file you\n\
977 specified, instead of the helper program file specified in the executable\n\
978 file you run. This is mostly of use for maintainers to test new versions\n\
979 of this helper program; chances are you did not intend to run this program.\n\
981 --list list all dependencies and how they are resolved\n\
982 --verify verify that given object really is a dynamically linked\n\
983 object we can handle\n\
984 --library-path PATH use given PATH instead of content of the environment\n\
985 variable LD_LIBRARY_PATH\n\
986 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
987 in LIST\n");
989 ++_dl_skip_args;
990 --_dl_argc;
991 ++INTUSE(_dl_argv);
993 /* The initialization of _dl_stack_flags done below assumes the
994 executable's PT_GNU_STACK may have been honored by the kernel, and
995 so a PT_GNU_STACK with PF_X set means the stack started out with
996 execute permission. However, this is not really true if the
997 dynamic linker is the executable the kernel loaded. For this
998 case, we must reinitialize _dl_stack_flags to match the dynamic
999 linker itself. If the dynamic linker was built with a
1000 PT_GNU_STACK, then the kernel may have loaded us with a
1001 nonexecutable stack that we will have to make executable when we
1002 load the program below unless it has a PT_GNU_STACK indicating
1003 nonexecutable stack is ok. */
1005 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1006 if (ph->p_type == PT_GNU_STACK)
1008 GL(dl_stack_flags) = ph->p_flags;
1009 break;
1012 if (__builtin_expect (mode, normal) == verify)
1014 const char *objname;
1015 const char *err_str = NULL;
1016 struct map_args args;
1017 bool malloced;
1019 args.str = rtld_progname;
1020 args.loader = NULL;
1021 args.is_preloaded = 0;
1022 args.mode = __RTLD_OPENEXEC;
1023 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
1024 &args);
1025 if (__builtin_expect (err_str != NULL, 0))
1026 /* We don't free the returned string, the programs stops
1027 anyway. */
1028 _exit (EXIT_FAILURE);
1030 else
1032 HP_TIMING_NOW (start);
1033 _dl_map_object (NULL, rtld_progname, 0, lt_library, 0,
1034 __RTLD_OPENEXEC, LM_ID_BASE);
1035 HP_TIMING_NOW (stop);
1037 HP_TIMING_DIFF (load_time, start, stop);
1040 /* Now the map for the main executable is available. */
1041 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1043 phdr = main_map->l_phdr;
1044 phnum = main_map->l_phnum;
1045 /* We overwrite here a pointer to a malloc()ed string. But since
1046 the malloc() implementation used at this point is the dummy
1047 implementations which has no real free() function it does not
1048 makes sense to free the old string first. */
1049 main_map->l_name = (char *) "";
1050 *user_entry = main_map->l_entry;
1052 else
1054 /* Create a link_map for the executable itself.
1055 This will be what dlopen on "" returns. */
1056 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1057 __RTLD_OPENEXEC, LM_ID_BASE);
1058 assert (main_map != NULL);
1059 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
1060 main_map->l_phdr = phdr;
1061 main_map->l_phnum = phnum;
1062 main_map->l_entry = *user_entry;
1064 /* At this point we are in a bit of trouble. We would have to
1065 fill in the values for l_dev and l_ino. But in general we
1066 do not know where the file is. We also do not handle AT_EXECFD
1067 even if it would be passed up.
1069 We leave the values here defined to 0. This is normally no
1070 problem as the program code itself is normally no shared
1071 object and therefore cannot be loaded dynamically. Nothing
1072 prevent the use of dynamic binaries and in these situations
1073 we might get problems. We might not be able to find out
1074 whether the object is already loaded. But since there is no
1075 easy way out and because the dynamic binary must also not
1076 have an SONAME we ignore this program for now. If it becomes
1077 a problem we can force people using SONAMEs. */
1079 /* We delay initializing the path structure until we got the dynamic
1080 information for the program. */
1083 main_map->l_map_end = 0;
1084 main_map->l_text_end = 0;
1085 /* Perhaps the executable has no PT_LOAD header entries at all. */
1086 main_map->l_map_start = ~0;
1087 /* And it was opened directly. */
1088 ++main_map->l_direct_opencount;
1090 /* Scan the program header table for the dynamic section. */
1091 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1092 switch (ph->p_type)
1094 case PT_PHDR:
1095 /* Find out the load address. */
1096 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1097 break;
1098 case PT_DYNAMIC:
1099 /* This tells us where to find the dynamic section,
1100 which tells us everything we need to do. */
1101 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
1102 break;
1103 case PT_INTERP:
1104 /* This "interpreter segment" was used by the program loader to
1105 find the program interpreter, which is this program itself, the
1106 dynamic linker. We note what name finds us, so that a future
1107 dlopen call or DT_NEEDED entry, for something that wants to link
1108 against the dynamic linker as a shared library, will know that
1109 the shared object is already loaded. */
1110 _dl_rtld_libname.name = ((const char *) main_map->l_addr
1111 + ph->p_vaddr);
1112 /* _dl_rtld_libname.next = NULL; Already zero. */
1113 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1115 /* Ordinarilly, we would get additional names for the loader from
1116 our DT_SONAME. This can't happen if we were actually linked as
1117 a static executable (detect this case when we have no DYNAMIC).
1118 If so, assume the filename component of the interpreter path to
1119 be our SONAME, and add it to our name list. */
1120 if (GL(dl_rtld_map).l_ld == NULL)
1122 const char *p = NULL;
1123 const char *cp = _dl_rtld_libname.name;
1125 /* Find the filename part of the path. */
1126 while (*cp != '\0')
1127 if (*cp++ == '/')
1128 p = cp;
1130 if (p != NULL)
1132 _dl_rtld_libname2.name = p;
1133 /* _dl_rtld_libname2.next = NULL; Already zero. */
1134 _dl_rtld_libname.next = &_dl_rtld_libname2;
1138 has_interp = true;
1139 break;
1140 case PT_LOAD:
1142 ElfW(Addr) mapstart;
1143 ElfW(Addr) allocend;
1145 /* Remember where the main program starts in memory. */
1146 mapstart = (main_map->l_addr + (ph->p_vaddr & ~(ph->p_align - 1)));
1147 if (main_map->l_map_start > mapstart)
1148 main_map->l_map_start = mapstart;
1150 /* Also where it ends. */
1151 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1152 if (main_map->l_map_end < allocend)
1153 main_map->l_map_end = allocend;
1154 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1155 main_map->l_text_end = allocend;
1157 break;
1159 case PT_TLS:
1160 #ifdef USE_TLS
1161 if (ph->p_memsz > 0)
1163 /* Note that in the case the dynamic linker we duplicate work
1164 here since we read the PT_TLS entry already in
1165 _dl_start_final. But the result is repeatable so do not
1166 check for this special but unimportant case. */
1167 main_map->l_tls_blocksize = ph->p_memsz;
1168 main_map->l_tls_align = ph->p_align;
1169 if (ph->p_align == 0)
1170 main_map->l_tls_firstbyte_offset = 0;
1171 else
1172 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1173 & (ph->p_align - 1));
1174 main_map->l_tls_initimage_size = ph->p_filesz;
1175 main_map->l_tls_initimage = (void *) ph->p_vaddr;
1177 /* This image gets the ID one. */
1178 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1180 #else
1181 _dl_fatal_printf ("\
1182 ld.so does not support TLS, but program uses it!\n");
1183 #endif
1184 break;
1186 case PT_GNU_STACK:
1187 GL(dl_stack_flags) = ph->p_flags;
1188 break;
1190 case PT_GNU_RELRO:
1191 main_map->l_relro_addr = ph->p_vaddr;
1192 main_map->l_relro_size = ph->p_memsz;
1193 break;
1195 #ifdef USE_TLS
1196 /* Adjust the address of the TLS initialization image in case
1197 the executable is actually an ET_DYN object. */
1198 if (main_map->l_tls_initimage != NULL)
1199 main_map->l_tls_initimage
1200 = (char *) main_map->l_tls_initimage + main_map->l_addr;
1201 #endif
1202 if (! main_map->l_map_end)
1203 main_map->l_map_end = ~0;
1204 if (! main_map->l_text_end)
1205 main_map->l_text_end = ~0;
1206 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1208 /* We were invoked directly, so the program might not have a
1209 PT_INTERP. */
1210 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1211 /* _dl_rtld_libname.next = NULL; Already zero. */
1212 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1214 else
1215 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1217 /* If the current libname is different from the SONAME, add the
1218 latter as well. */
1219 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1220 && strcmp (GL(dl_rtld_map).l_libname->name,
1221 (const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1222 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1224 static struct libname_list newname;
1225 newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1226 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1227 newname.next = NULL;
1228 newname.dont_free = 1;
1230 assert (GL(dl_rtld_map).l_libname->next == NULL);
1231 GL(dl_rtld_map).l_libname->next = &newname;
1233 /* The ld.so must be relocated since otherwise loading audit modules
1234 will fail since they reuse the very same ld.so. */
1235 assert (GL(dl_rtld_map).l_relocated);
1237 if (! rtld_is_main)
1239 /* Extract the contents of the dynamic section for easy access. */
1240 elf_get_dynamic_info (main_map, NULL);
1241 /* Set up our cache of pointers into the hash table. */
1242 _dl_setup_hash (main_map);
1245 if (__builtin_expect (mode, normal) == verify)
1247 /* We were called just to verify that this is a dynamic
1248 executable using us as the program interpreter. Exit with an
1249 error if we were not able to load the binary or no interpreter
1250 is specified (i.e., this is no dynamically linked binary. */
1251 if (main_map->l_ld == NULL)
1252 _exit (1);
1254 /* We allow here some platform specific code. */
1255 #ifdef DISTINGUISH_LIB_VERSIONS
1256 DISTINGUISH_LIB_VERSIONS;
1257 #endif
1258 _exit (has_interp ? 0 : 2);
1261 struct link_map **first_preload = &GL(dl_rtld_map).l_next;
1262 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1263 /* Set up the data structures for the system-supplied DSO early,
1264 so they can influence _dl_init_paths. */
1265 if (GLRO(dl_sysinfo_dso) != NULL)
1267 /* Do an abridged version of the work _dl_map_object_from_fd would do
1268 to map in the object. It's already mapped and prelinked (and
1269 better be, since it's read-only and so we couldn't relocate it).
1270 We just want our data structures to describe it as if we had just
1271 mapped and relocated it normally. */
1272 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL,
1273 0, LM_ID_BASE);
1274 if (__builtin_expect (l != NULL, 1))
1276 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
1278 l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1279 + GLRO(dl_sysinfo_dso)->e_phoff);
1280 l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1281 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1283 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1284 if (ph->p_type == PT_DYNAMIC)
1286 l->l_ld = (void *) ph->p_vaddr;
1287 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1289 else if (ph->p_type == PT_LOAD)
1291 if (! l->l_addr)
1292 l->l_addr = ph->p_vaddr;
1293 if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1294 l->l_map_end = ph->p_vaddr + ph->p_memsz;
1295 if ((ph->p_flags & PF_X)
1296 && ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1297 l->l_text_end = ph->p_vaddr + ph->p_memsz;
1299 else
1300 /* There must be no TLS segment. */
1301 assert (ph->p_type != PT_TLS);
1303 l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1304 l->l_addr = l->l_map_start - l->l_addr;
1305 l->l_map_end += l->l_addr;
1306 l->l_text_end += l->l_addr;
1307 l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1308 elf_get_dynamic_info (l, dyn_temp);
1309 _dl_setup_hash (l);
1310 l->l_relocated = 1;
1312 /* Initialize l_local_scope to contain just this map. This allows
1313 the use of dl_lookup_symbol_x to resolve symbols within the vdso.
1314 So we create a single entry list pointing to l_real as its only
1315 element */
1316 l->l_local_scope[0]->r_nlist = 1;
1317 l->l_local_scope[0]->r_list = &l->l_real;
1319 /* Now that we have the info handy, use the DSO image's soname
1320 so this object can be looked up by name. Note that we do not
1321 set l_name here. That field gives the file name of the DSO,
1322 and this DSO is not associated with any file. */
1323 if (l->l_info[DT_SONAME] != NULL)
1325 /* Work around a kernel problem. The kernel cannot handle
1326 addresses in the vsyscall DSO pages in writev() calls. */
1327 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1328 + l->l_info[DT_SONAME]->d_un.d_val);
1329 size_t len = strlen (dsoname);
1330 char *copy = malloc (len);
1331 if (copy == NULL)
1332 _dl_fatal_printf ("out of memory\n");
1333 l->l_libname->name = memcpy (copy, dsoname, len);
1336 /* Rearrange the list so this DSO appears after rtld_map. */
1337 assert (l->l_next == NULL);
1338 assert (l->l_prev == main_map);
1339 GL(dl_rtld_map).l_next = l;
1340 l->l_prev = &GL(dl_rtld_map);
1341 first_preload = &l->l_next;
1343 /* We have a prelinked DSO preloaded by the system. */
1344 GLRO(dl_sysinfo_map) = l;
1345 # ifdef NEED_DL_SYSINFO
1346 if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1347 GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1348 # endif
1351 #endif
1353 #ifdef DL_SYSDEP_OSCHECK
1354 DL_SYSDEP_OSCHECK (dl_fatal);
1355 #endif
1357 /* Initialize the data structures for the search paths for shared
1358 objects. */
1359 _dl_init_paths (library_path);
1361 /* Initialize _r_debug. */
1362 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1363 LM_ID_BASE);
1364 r->r_state = RT_CONSISTENT;
1366 /* Put the link_map for ourselves on the chain so it can be found by
1367 name. Note that at this point the global chain of link maps contains
1368 exactly one element, which is pointed to by dl_loaded. */
1369 if (! GL(dl_rtld_map).l_name)
1370 /* If not invoked directly, the dynamic linker shared object file was
1371 found by the PT_INTERP name. */
1372 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1373 GL(dl_rtld_map).l_type = lt_library;
1374 main_map->l_next = &GL(dl_rtld_map);
1375 GL(dl_rtld_map).l_prev = main_map;
1376 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1377 ++GL(dl_load_adds);
1379 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1380 to not using bias for non-prelinked PIEs and libraries
1381 and using it for executables or prelinked PIEs or libraries. */
1382 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1383 GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
1385 /* Set up the program header information for the dynamic linker
1386 itself. It is needed in the dl_iterate_phdr() callbacks. */
1387 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1388 ElfW(Phdr) *rtld_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1389 + rtld_ehdr->e_phoff);
1390 GL(dl_rtld_map).l_phdr = rtld_phdr;
1391 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1394 /* PT_GNU_RELRO is usually the last phdr. */
1395 size_t cnt = rtld_ehdr->e_phnum;
1396 while (cnt-- > 0)
1397 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1399 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1400 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1401 break;
1404 #ifdef USE_TLS
1405 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1406 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1407 /* Assign a module ID. Do this before loading any audit modules. */
1408 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1409 #endif
1411 /* If we have auditing DSOs to load, do it now. */
1412 if (__builtin_expect (audit_list != NULL, 0))
1414 /* Iterate over all entries in the list. The order is important. */
1415 struct audit_ifaces *last_audit = NULL;
1416 struct audit_list *al = audit_list->next;
1419 #ifdef USE_TLS
1420 int tls_idx = GL(dl_tls_max_dtv_idx);
1422 /* Now it is time to determine the layout of the static TLS
1423 block and allocate it for the initial thread. Note that we
1424 always allocate the static block, we never defer it even if
1425 no DF_STATIC_TLS bit is set. The reason is that we know
1426 glibc will use the static model. */
1428 /* Since we start using the auditing DSOs right away we need to
1429 initialize the data structures now. */
1430 tcbp = init_tls ();
1431 #endif
1432 struct dlmopen_args dlmargs;
1433 dlmargs.fname = al->name;
1434 dlmargs.map = NULL;
1436 const char *objname;
1437 const char *err_str = NULL;
1438 bool malloced;
1439 (void) _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit,
1440 &dlmargs);
1441 if (__builtin_expect (err_str != NULL, 0))
1443 not_loaded:
1444 _dl_error_printf ("\
1445 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
1446 al->name, err_str);
1447 if (malloced)
1448 free ((char *) err_str);
1450 else
1452 struct lookup_args largs;
1453 largs.name = "la_version";
1454 largs.map = dlmargs.map;
1456 /* Check whether the interface version matches. */
1457 (void) _dl_catch_error (&objname, &err_str, &malloced,
1458 lookup_doit, &largs);
1460 unsigned int (*laversion) (unsigned int);
1461 unsigned int lav;
1462 if (err_str == NULL
1463 && (laversion = largs.result) != NULL
1464 && (lav = laversion (LAV_CURRENT)) > 0
1465 && lav <= LAV_CURRENT)
1467 /* Allocate structure for the callback function pointers.
1468 This call can never fail. */
1469 union
1471 struct audit_ifaces ifaces;
1472 #define naudit_ifaces 8
1473 void (*fptr[naudit_ifaces]) (void);
1474 } *newp = malloc (sizeof (*newp));
1476 /* Names of the auditing interfaces. All in one
1477 long string. */
1478 static const char audit_iface_names[] =
1479 "la_activity\0"
1480 "la_objsearch\0"
1481 "la_objopen\0"
1482 "la_preinit\0"
1483 #if __ELF_NATIVE_CLASS == 32
1484 "la_symbind32\0"
1485 #elif __ELF_NATIVE_CLASS == 64
1486 "la_symbind64\0"
1487 #else
1488 # error "__ELF_NATIVE_CLASS must be defined"
1489 #endif
1490 #define STRING(s) __STRING (s)
1491 "la_" STRING (ARCH_LA_PLTENTER) "\0"
1492 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
1493 "la_objclose\0";
1494 unsigned int cnt = 0;
1495 const char *cp = audit_iface_names;
1498 largs.name = cp;
1499 (void) _dl_catch_error (&objname, &err_str, &malloced,
1500 lookup_doit, &largs);
1502 /* Store the pointer. */
1503 if (err_str == NULL && largs.result != NULL)
1505 newp->fptr[cnt] = largs.result;
1507 /* The dynamic linker link map is statically
1508 allocated, initialize the data now. */
1509 GL(dl_rtld_map).l_audit[cnt].cookie
1510 = (intptr_t) &GL(dl_rtld_map);
1512 else
1513 newp->fptr[cnt] = NULL;
1514 ++cnt;
1516 cp = (char *) rawmemchr (cp, '\0') + 1;
1518 while (*cp != '\0');
1519 assert (cnt == naudit_ifaces);
1521 /* Now append the new auditing interface to the list. */
1522 newp->ifaces.next = NULL;
1523 if (last_audit == NULL)
1524 last_audit = GLRO(dl_audit) = &newp->ifaces;
1525 else
1526 last_audit = last_audit->next = &newp->ifaces;
1527 ++GLRO(dl_naudit);
1529 /* Mark the DSO as being used for auditing. */
1530 dlmargs.map->l_auditing = 1;
1532 else
1534 /* We cannot use the DSO, it does not have the
1535 appropriate interfaces or it expects something
1536 more recent. */
1537 #ifndef NDEBUG
1538 Lmid_t ns = dlmargs.map->l_ns;
1539 #endif
1540 _dl_close (dlmargs.map);
1542 /* Make sure the namespace has been cleared entirely. */
1543 assert (GL(dl_ns)[ns]._ns_loaded == NULL);
1544 assert (GL(dl_ns)[ns]._ns_nloaded == 0);
1546 #ifdef USE_TLS
1547 GL(dl_tls_max_dtv_idx) = tls_idx;
1548 #endif
1549 goto not_loaded;
1553 al = al->next;
1555 while (al != audit_list->next);
1557 /* If we have any auditing modules, announce that we already
1558 have two objects loaded. */
1559 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1561 struct link_map *ls[2] = { main_map, &GL(dl_rtld_map) };
1563 for (unsigned int outer = 0; outer < 2; ++outer)
1565 struct audit_ifaces *afct = GLRO(dl_audit);
1566 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1568 if (afct->objopen != NULL)
1570 ls[outer]->l_audit[cnt].bindflags
1571 = afct->objopen (ls[outer], LM_ID_BASE,
1572 &ls[outer]->l_audit[cnt].cookie);
1574 ls[outer]->l_audit_any_plt
1575 |= ls[outer]->l_audit[cnt].bindflags != 0;
1578 afct = afct->next;
1584 /* Set up debugging before the debugger is notified for the first time. */
1585 #ifdef ELF_MACHINE_DEBUG_SETUP
1586 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1587 ELF_MACHINE_DEBUG_SETUP (main_map, r);
1588 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1589 #else
1590 if (main_map->l_info[DT_DEBUG] != NULL)
1591 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1592 with the run-time address of the r_debug structure */
1593 main_map->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1595 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1596 case you run gdb on the dynamic linker directly. */
1597 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1598 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1599 #endif
1601 /* We start adding objects. */
1602 r->r_state = RT_ADD;
1603 _dl_debug_state ();
1605 /* Auditing checkpoint: we are ready to signal that the initial map
1606 is being constructed. */
1607 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1609 struct audit_ifaces *afct = GLRO(dl_audit);
1610 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1612 if (afct->activity != NULL)
1613 afct->activity (&main_map->l_audit[cnt].cookie, LA_ACT_ADD);
1615 afct = afct->next;
1619 /* We have two ways to specify objects to preload: via environment
1620 variable and via the file /etc/ld.so.preload. The latter can also
1621 be used when security is enabled. */
1622 assert (*first_preload == NULL);
1623 struct link_map **preloads = NULL;
1624 unsigned int npreloads = 0;
1626 if (__builtin_expect (preloadlist != NULL, 0))
1628 /* The LD_PRELOAD environment variable gives list of libraries
1629 separated by white space or colons that are loaded before the
1630 executable's dependencies and prepended to the global scope
1631 list. If the binary is running setuid all elements
1632 containing a '/' are ignored since it is insecure. */
1633 char *list = strdupa (preloadlist);
1634 char *p;
1636 HP_TIMING_NOW (start);
1638 /* Prevent optimizing strsep. Speed is not important here. */
1639 while ((p = (strsep) (&list, " :")) != NULL)
1640 if (p[0] != '\0'
1641 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1642 || strchr (p, '/') == NULL))
1643 npreloads += do_preload (p, main_map, "LD_PRELOAD");
1645 HP_TIMING_NOW (stop);
1646 HP_TIMING_DIFF (diff, start, stop);
1647 HP_TIMING_ACCUM_NT (load_time, diff);
1650 /* There usually is no ld.so.preload file, it should only be used
1651 for emergencies and testing. So the open call etc should usually
1652 fail. Using access() on a non-existing file is faster than using
1653 open(). So we do this first. If it succeeds we do almost twice
1654 the work but this does not matter, since it is not for production
1655 use. */
1656 static const char preload_file[] = "/etc/ld.so.preload";
1657 if (__builtin_expect (__access (preload_file, R_OK) == 0, 0))
1659 /* Read the contents of the file. */
1660 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1661 PROT_READ | PROT_WRITE);
1662 if (__builtin_expect (file != MAP_FAILED, 0))
1664 /* Parse the file. It contains names of libraries to be loaded,
1665 separated by white spaces or `:'. It may also contain
1666 comments introduced by `#'. */
1667 char *problem;
1668 char *runp;
1669 size_t rest;
1671 /* Eliminate comments. */
1672 runp = file;
1673 rest = file_size;
1674 while (rest > 0)
1676 char *comment = memchr (runp, '#', rest);
1677 if (comment == NULL)
1678 break;
1680 rest -= comment - runp;
1682 *comment = ' ';
1683 while (--rest > 0 && *++comment != '\n');
1686 /* We have one problematic case: if we have a name at the end of
1687 the file without a trailing terminating characters, we cannot
1688 place the \0. Handle the case separately. */
1689 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1690 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1692 problem = &file[file_size];
1693 while (problem > file && problem[-1] != ' '
1694 && problem[-1] != '\t'
1695 && problem[-1] != '\n' && problem[-1] != ':')
1696 --problem;
1698 if (problem > file)
1699 problem[-1] = '\0';
1701 else
1703 problem = NULL;
1704 file[file_size - 1] = '\0';
1707 HP_TIMING_NOW (start);
1709 if (file != problem)
1711 char *p;
1712 runp = file;
1713 while ((p = strsep (&runp, ": \t\n")) != NULL)
1714 if (p[0] != '\0')
1715 npreloads += do_preload (p, main_map, preload_file);
1718 if (problem != NULL)
1720 char *p = strndupa (problem, file_size - (problem - file));
1722 npreloads += do_preload (p, main_map, preload_file);
1725 HP_TIMING_NOW (stop);
1726 HP_TIMING_DIFF (diff, start, stop);
1727 HP_TIMING_ACCUM_NT (load_time, diff);
1729 /* We don't need the file anymore. */
1730 __munmap (file, file_size);
1734 if (__builtin_expect (*first_preload != NULL, 0))
1736 /* Set up PRELOADS with a vector of the preloaded libraries. */
1737 struct link_map *l = *first_preload;
1738 preloads = __alloca (npreloads * sizeof preloads[0]);
1739 i = 0;
1742 preloads[i++] = l;
1743 l = l->l_next;
1744 } while (l);
1745 assert (i == npreloads);
1748 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1749 specified some libraries to load, these are inserted before the actual
1750 dependencies in the executable's searchlist for symbol resolution. */
1751 HP_TIMING_NOW (start);
1752 _dl_map_object_deps (main_map, preloads, npreloads, mode == trace, 0);
1753 HP_TIMING_NOW (stop);
1754 HP_TIMING_DIFF (diff, start, stop);
1755 HP_TIMING_ACCUM_NT (load_time, diff);
1757 /* Mark all objects as being in the global scope. */
1758 for (i = main_map->l_searchlist.r_nlist; i > 0; )
1759 main_map->l_searchlist.r_list[--i]->l_global = 1;
1761 #ifndef MAP_ANON
1762 /* We are done mapping things, so close the zero-fill descriptor. */
1763 __close (_dl_zerofd);
1764 _dl_zerofd = -1;
1765 #endif
1767 /* Remove _dl_rtld_map from the chain. */
1768 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1769 if (GL(dl_rtld_map).l_next != NULL)
1770 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1772 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1773 if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1774 break;
1776 bool rtld_multiple_ref = false;
1777 if (__builtin_expect (i < main_map->l_searchlist.r_nlist, 1))
1779 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1780 put it back in the list of visible objects. We insert it into the
1781 chain in symbol search order because gdb uses the chain's order as
1782 its symbol search order. */
1783 rtld_multiple_ref = true;
1785 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1786 if (__builtin_expect (mode, normal) == normal)
1788 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1789 ? main_map->l_searchlist.r_list[i + 1]
1790 : NULL);
1791 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1792 if (GLRO(dl_sysinfo_map) != NULL
1793 && GL(dl_rtld_map).l_prev->l_next == GLRO(dl_sysinfo_map)
1794 && GL(dl_rtld_map).l_next != GLRO(dl_sysinfo_map))
1795 GL(dl_rtld_map).l_prev = GLRO(dl_sysinfo_map);
1796 #endif
1798 else
1799 /* In trace mode there might be an invisible object (which we
1800 could not find) after the previous one in the search list.
1801 In this case it doesn't matter much where we put the
1802 interpreter object, so we just initialize the list pointer so
1803 that the assertion below holds. */
1804 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1806 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1807 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1808 if (GL(dl_rtld_map).l_next != NULL)
1810 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1811 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1815 /* Now let us see whether all libraries are available in the
1816 versions we need. */
1818 struct version_check_args args;
1819 args.doexit = mode == normal;
1820 args.dotrace = mode == trace;
1821 _dl_receive_error (print_missing_version, version_check_doit, &args);
1824 #ifdef USE_TLS
1825 /* We do not initialize any of the TLS functionality unless any of the
1826 initial modules uses TLS. This makes dynamic loading of modules with
1827 TLS impossible, but to support it requires either eagerly doing setup
1828 now or lazily doing it later. Doing it now makes us incompatible with
1829 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1830 used. Trying to do it lazily is too hairy to try when there could be
1831 multiple threads (from a non-TLS-using libpthread). */
1832 bool was_tls_init_tp_called = tls_init_tp_called;
1833 if (tcbp == NULL)
1834 tcbp = init_tls ();
1835 #endif
1837 /* Set up the stack checker's canary. */
1838 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard ();
1839 #ifdef THREAD_SET_STACK_GUARD
1840 THREAD_SET_STACK_GUARD (stack_chk_guard);
1841 #else
1842 __stack_chk_guard = stack_chk_guard;
1843 #endif
1845 /* Set up the pointer guard as well, if necessary. */
1846 if (GLRO(dl_pointer_guard))
1848 // XXX If it is cheap, we should use a separate value.
1849 uintptr_t pointer_chk_guard = stack_chk_guard;
1850 #ifndef HP_TIMING_NONAVAIL
1851 hp_timing_t now;
1852 HP_TIMING_NOW (now);
1853 pointer_chk_guard ^= now;
1854 #endif
1855 #ifdef THREAD_SET_POINTER_GUARD
1856 THREAD_SET_POINTER_GUARD (pointer_chk_guard);
1857 #endif
1858 __pointer_chk_guard_local = pointer_chk_guard;
1861 if (__builtin_expect (mode, normal) != normal)
1863 /* We were run just to list the shared libraries. It is
1864 important that we do this before real relocation, because the
1865 functions we call below for output may no longer work properly
1866 after relocation. */
1867 struct link_map *l;
1869 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1871 struct r_scope_elem *scope = &main_map->l_searchlist;
1873 for (i = 0; i < scope->r_nlist; i++)
1875 l = scope->r_list [i];
1876 if (l->l_faked)
1878 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1879 continue;
1881 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1882 GLRO(dl_trace_prelink_map) = l;
1883 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1884 l->l_libname->name[0] ? l->l_libname->name
1885 : rtld_progname ?: "<main program>",
1886 l->l_name[0] ? l->l_name
1887 : rtld_progname ?: "<main program>",
1888 (int) sizeof l->l_map_start * 2,
1889 (size_t) l->l_map_start,
1890 (int) sizeof l->l_addr * 2,
1891 (size_t) l->l_addr);
1892 #ifdef USE_TLS
1893 if (l->l_tls_modid)
1894 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1895 (int) sizeof l->l_tls_offset * 2,
1896 (size_t) l->l_tls_offset);
1897 else
1898 #endif
1899 _dl_printf ("\n");
1902 else if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
1904 /* Look through the dependencies of the main executable
1905 and determine which of them is not actually
1906 required. */
1907 struct link_map *l = main_map;
1909 /* Relocate the main executable. */
1910 struct relocate_args args = { .l = l, .lazy = GLRO(dl_lazy) };
1911 _dl_receive_error (print_unresolved, relocate_doit, &args);
1913 /* This loop depends on the dependencies of the executable to
1914 correspond in number and order to the DT_NEEDED entries. */
1915 ElfW(Dyn) *dyn = main_map->l_ld;
1916 bool first = true;
1917 while (dyn->d_tag != DT_NULL)
1919 if (dyn->d_tag == DT_NEEDED)
1921 l = l->l_next;
1923 if (!l->l_used)
1925 if (first)
1927 _dl_printf ("Unused direct dependencies:\n");
1928 first = false;
1931 _dl_printf ("\t%s\n", l->l_name);
1935 ++dyn;
1938 _exit (first != true);
1940 else if (! main_map->l_info[DT_NEEDED])
1941 _dl_printf ("\tstatically linked\n");
1942 else
1944 for (l = main_map->l_next; l; l = l->l_next)
1945 if (l->l_faked)
1946 /* The library was not found. */
1947 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1948 else if (strcmp (l->l_libname->name, l->l_name) == 0)
1949 _dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
1950 (int) sizeof l->l_map_start * 2,
1951 (size_t) l->l_map_start);
1952 else
1953 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1954 l->l_name, (int) sizeof l->l_map_start * 2,
1955 (size_t) l->l_map_start);
1958 if (__builtin_expect (mode, trace) != trace)
1959 for (i = 1; i < (unsigned int) _dl_argc; ++i)
1961 const ElfW(Sym) *ref = NULL;
1962 ElfW(Addr) loadbase;
1963 lookup_t result;
1965 result = _dl_lookup_symbol_x (INTUSE(_dl_argv)[i], main_map,
1966 &ref, main_map->l_scope, NULL,
1967 ELF_RTYPE_CLASS_PLT,
1968 DL_LOOKUP_ADD_DEPENDENCY, NULL);
1970 loadbase = LOOKUP_VALUE_ADDRESS (result);
1972 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
1973 INTUSE(_dl_argv)[i],
1974 (int) sizeof ref->st_value * 2,
1975 (size_t) ref->st_value,
1976 (int) sizeof loadbase * 2, (size_t) loadbase);
1978 else
1980 /* If LD_WARN is set, warn about undefined symbols. */
1981 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
1983 /* We have to do symbol dependency testing. */
1984 struct relocate_args args;
1985 struct link_map *l;
1987 args.lazy = GLRO(dl_lazy);
1989 l = main_map;
1990 while (l->l_next != NULL)
1991 l = l->l_next;
1994 if (l != &GL(dl_rtld_map) && ! l->l_faked)
1996 args.l = l;
1997 _dl_receive_error (print_unresolved, relocate_doit,
1998 &args);
2000 l = l->l_prev;
2002 while (l != NULL);
2004 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
2005 && rtld_multiple_ref)
2007 /* Mark the link map as not yet relocated again. */
2008 GL(dl_rtld_map).l_relocated = 0;
2009 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope,
2010 0, 0);
2013 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
2014 if (version_info)
2016 /* Print more information. This means here, print information
2017 about the versions needed. */
2018 int first = 1;
2019 struct link_map *map;
2021 for (map = main_map; map != NULL; map = map->l_next)
2023 const char *strtab;
2024 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
2025 ElfW(Verneed) *ent;
2027 if (dyn == NULL)
2028 continue;
2030 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
2031 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
2033 if (first)
2035 _dl_printf ("\n\tVersion information:\n");
2036 first = 0;
2039 _dl_printf ("\t%s:\n",
2040 map->l_name[0] ? map->l_name : rtld_progname);
2042 while (1)
2044 ElfW(Vernaux) *aux;
2045 struct link_map *needed;
2047 needed = find_needed (strtab + ent->vn_file);
2048 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
2050 while (1)
2052 const char *fname = NULL;
2054 if (needed != NULL
2055 && match_version (strtab + aux->vna_name,
2056 needed))
2057 fname = needed->l_name;
2059 _dl_printf ("\t\t%s (%s) %s=> %s\n",
2060 strtab + ent->vn_file,
2061 strtab + aux->vna_name,
2062 aux->vna_flags & VER_FLG_WEAK
2063 ? "[WEAK] " : "",
2064 fname ?: "not found");
2066 if (aux->vna_next == 0)
2067 /* No more symbols. */
2068 break;
2070 /* Next symbol. */
2071 aux = (ElfW(Vernaux) *) ((char *) aux
2072 + aux->vna_next);
2075 if (ent->vn_next == 0)
2076 /* No more dependencies. */
2077 break;
2079 /* Next dependency. */
2080 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
2086 _exit (0);
2089 if (main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]
2090 && ! __builtin_expect (GLRO(dl_profile) != NULL, 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;
2145 GL(dl_ns)[LM_ID_BASE]._ns_global_scope[0] = &main_map->l_searchlist;
2147 /* Save the information about the original global scope list since
2148 we need it in the memory handling later. */
2149 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
2151 if (prelinked)
2153 if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
2155 ElfW(Rela) *conflict, *conflictend;
2156 #ifndef HP_TIMING_NONAVAIL
2157 hp_timing_t start;
2158 hp_timing_t stop;
2159 #endif
2161 HP_TIMING_NOW (start);
2162 assert (main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
2163 conflict = (ElfW(Rela) *)
2164 main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
2165 conflictend = (ElfW(Rela) *)
2166 ((char *) conflict
2167 + main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
2168 _dl_resolve_conflicts (main_map, conflict, conflictend);
2169 HP_TIMING_NOW (stop);
2170 HP_TIMING_DIFF (relocate_time, start, stop);
2174 /* Mark all the objects so we know they have been already relocated. */
2175 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2177 l->l_relocated = 1;
2178 if (l->l_relro_size)
2179 _dl_protect_relro (l);
2181 #ifdef USE_TLS
2182 /* Add object to slot information data if necessasy. */
2183 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2184 _dl_add_to_slotinfo (l);
2185 #endif
2188 _dl_sysdep_start_cleanup ();
2190 else
2192 /* Now we have all the objects loaded. Relocate them all except for
2193 the dynamic linker itself. We do this in reverse order so that copy
2194 relocs of earlier objects overwrite the data written by later
2195 objects. We do not re-relocate the dynamic linker itself in this
2196 loop because that could result in the GOT entries for functions we
2197 call being changed, and that would break us. It is safe to relocate
2198 the dynamic linker out of order because it has no copy relocs (we
2199 know that because it is self-contained). */
2201 int consider_profiling = GLRO(dl_profile) != NULL;
2202 #ifndef HP_TIMING_NONAVAIL
2203 hp_timing_t start;
2204 hp_timing_t stop;
2205 #endif
2207 /* If we are profiling we also must do lazy reloaction. */
2208 GLRO(dl_lazy) |= consider_profiling;
2210 struct link_map *l = main_map;
2211 while (l->l_next)
2212 l = l->l_next;
2214 HP_TIMING_NOW (start);
2217 /* While we are at it, help the memory handling a bit. We have to
2218 mark some data structures as allocated with the fake malloc()
2219 implementation in ld.so. */
2220 struct libname_list *lnp = l->l_libname->next;
2222 while (__builtin_expect (lnp != NULL, 0))
2224 lnp->dont_free = 1;
2225 lnp = lnp->next;
2228 if (l != &GL(dl_rtld_map))
2229 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy),
2230 consider_profiling);
2232 #ifdef USE_TLS
2233 /* Add object to slot information data if necessasy. */
2234 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2235 _dl_add_to_slotinfo (l);
2236 #endif
2238 l = l->l_prev;
2240 while (l);
2241 HP_TIMING_NOW (stop);
2243 HP_TIMING_DIFF (relocate_time, start, stop);
2245 /* Do any necessary cleanups for the startup OS interface code.
2246 We do these now so that no calls are made after rtld re-relocation
2247 which might be resolved to different functions than we expect.
2248 We cannot do this before relocating the other objects because
2249 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2250 _dl_sysdep_start_cleanup ();
2252 /* Now enable profiling if needed. Like the previous call,
2253 this has to go here because the calls it makes should use the
2254 rtld versions of the functions (particularly calloc()), but it
2255 needs to have _dl_profile_map set up by the relocator. */
2256 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
2257 /* We must prepare the profiling. */
2258 _dl_start_profile ();
2261 #ifndef NONTLS_INIT_TP
2262 # define NONTLS_INIT_TP do { } while (0)
2263 #endif
2265 #ifdef USE_TLS
2266 if (!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2267 ++GL(dl_tls_generation);
2269 /* Now that we have completed relocation, the initializer data
2270 for the TLS blocks has its final values and we can copy them
2271 into the main thread's TLS area, which we allocated above. */
2272 _dl_allocate_tls_init (tcbp);
2274 /* And finally install it for the main thread. If ld.so itself uses
2275 TLS we know the thread pointer was initialized earlier. */
2276 if (! tls_init_tp_called)
2278 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
2279 if (__builtin_expect (lossage != NULL, 0))
2280 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2281 lossage);
2283 #else
2284 NONTLS_INIT_TP;
2285 #endif
2287 if (! prelinked && rtld_multiple_ref)
2289 /* There was an explicit ref to the dynamic linker as a shared lib.
2290 Re-relocate ourselves with user-controlled symbol definitions.
2292 We must do this after TLS initialization in case after this
2293 re-relocation, we might call a user-supplied function
2294 (e.g. calloc from _dl_relocate_object) that uses TLS data. */
2296 #ifndef HP_TIMING_NONAVAIL
2297 hp_timing_t start;
2298 hp_timing_t stop;
2299 hp_timing_t add;
2300 #endif
2302 HP_TIMING_NOW (start);
2303 /* Mark the link map as not yet relocated again. */
2304 GL(dl_rtld_map).l_relocated = 0;
2305 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2306 HP_TIMING_NOW (stop);
2307 HP_TIMING_DIFF (add, start, stop);
2308 HP_TIMING_ACCUM_NT (relocate_time, add);
2311 #ifdef SHARED
2312 /* Auditing checkpoint: we have added all objects. */
2313 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
2315 struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2316 /* Do not call the functions for any auditing object. */
2317 if (head->l_auditing == 0)
2319 struct audit_ifaces *afct = GLRO(dl_audit);
2320 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2322 if (afct->activity != NULL)
2323 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
2325 afct = afct->next;
2329 #endif
2331 /* Notify the debugger all new objects are now ready to go. We must re-get
2332 the address since by now the variable might be in another object. */
2333 r = _dl_debug_initialize (0, LM_ID_BASE);
2334 r->r_state = RT_CONSISTENT;
2335 _dl_debug_state ();
2337 #ifndef MAP_COPY
2338 /* We must munmap() the cache file. */
2339 _dl_unload_cache ();
2340 #endif
2342 /* Once we return, _dl_sysdep_start will invoke
2343 the DT_INIT functions and then *USER_ENTRY. */
2346 /* This is a little helper function for resolving symbols while
2347 tracing the binary. */
2348 static void
2349 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2350 const char *errstring)
2352 if (objname[0] == '\0')
2353 objname = rtld_progname ?: "<main program>";
2354 _dl_error_printf ("%s (%s)\n", errstring, objname);
2357 /* This is a little helper function for resolving symbols while
2358 tracing the binary. */
2359 static void
2360 print_missing_version (int errcode __attribute__ ((unused)),
2361 const char *objname, const char *errstring)
2363 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
2364 objname, errstring);
2367 /* Nonzero if any of the debugging options is enabled. */
2368 static int any_debug attribute_relro;
2370 /* Process the string given as the parameter which explains which debugging
2371 options are enabled. */
2372 static void
2373 process_dl_debug (const char *dl_debug)
2375 /* When adding new entries make sure that the maximal length of a name
2376 is correctly handled in the LD_DEBUG_HELP code below. */
2377 static const struct
2379 unsigned char len;
2380 const char name[10];
2381 const char helptext[41];
2382 unsigned short int mask;
2383 } debopts[] =
2385 #define LEN_AND_STR(str) sizeof (str) - 1, str
2386 { LEN_AND_STR ("libs"), "display library search paths",
2387 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2388 { LEN_AND_STR ("reloc"), "display relocation processing",
2389 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2390 { LEN_AND_STR ("files"), "display progress for input file",
2391 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2392 { LEN_AND_STR ("symbols"), "display symbol table processing",
2393 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2394 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2395 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2396 { LEN_AND_STR ("versions"), "display version dependencies",
2397 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2398 { LEN_AND_STR ("all"), "all previous options combined",
2399 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2400 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2401 { LEN_AND_STR ("statistics"), "display relocation statistics",
2402 DL_DEBUG_STATISTICS },
2403 { LEN_AND_STR ("unused"), "determined unused DSOs",
2404 DL_DEBUG_UNUSED },
2405 { LEN_AND_STR ("help"), "display this help message and exit",
2406 DL_DEBUG_HELP },
2408 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2410 /* Skip separating white spaces and commas. */
2411 while (*dl_debug != '\0')
2413 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2415 size_t cnt;
2416 size_t len = 1;
2418 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2419 && dl_debug[len] != ',' && dl_debug[len] != ':')
2420 ++len;
2422 for (cnt = 0; cnt < ndebopts; ++cnt)
2423 if (debopts[cnt].len == len
2424 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
2426 GLRO(dl_debug_mask) |= debopts[cnt].mask;
2427 any_debug = 1;
2428 break;
2431 if (cnt == ndebopts)
2433 /* Display a warning and skip everything until next
2434 separator. */
2435 char *copy = strndupa (dl_debug, len);
2436 _dl_error_printf ("\
2437 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2440 dl_debug += len;
2441 continue;
2444 ++dl_debug;
2447 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
2449 size_t cnt;
2451 _dl_printf ("\
2452 Valid options for the LD_DEBUG environment variable are:\n\n");
2454 for (cnt = 0; cnt < ndebopts; ++cnt)
2455 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2456 " " + debopts[cnt].len - 3,
2457 debopts[cnt].helptext);
2459 _dl_printf ("\n\
2460 To direct the debugging output into a file instead of standard output\n\
2461 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2462 _exit (0);
2466 static void
2467 process_dl_audit (char *str)
2469 /* The parameter is a colon separated list of DSO names. */
2470 char *p;
2472 while ((p = (strsep) (&str, ":")) != NULL)
2473 if (p[0] != '\0'
2474 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
2475 || strchr (p, '/') == NULL))
2477 /* This is using the local malloc, not the system malloc. The
2478 memory can never be freed. */
2479 struct audit_list *newp = malloc (sizeof (*newp));
2480 newp->name = p;
2482 if (audit_list == NULL)
2483 audit_list = newp->next = newp;
2484 else
2486 newp->next = audit_list->next;
2487 audit_list = audit_list->next = newp;
2492 /* Process all environments variables the dynamic linker must recognize.
2493 Since all of them start with `LD_' we are a bit smarter while finding
2494 all the entries. */
2495 extern char **_environ attribute_hidden;
2498 static void
2499 process_envvars (enum mode *modep)
2501 char **runp = _environ;
2502 char *envline;
2503 enum mode mode = normal;
2504 char *debug_output = NULL;
2506 /* This is the default place for profiling data file. */
2507 GLRO(dl_profile_output)
2508 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2510 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2512 size_t len = 0;
2514 while (envline[len] != '\0' && envline[len] != '=')
2515 ++len;
2517 if (envline[len] != '=')
2518 /* This is a "LD_" variable at the end of the string without
2519 a '=' character. Ignore it since otherwise we will access
2520 invalid memory below. */
2521 continue;
2523 switch (len)
2525 case 4:
2526 /* Warning level, verbose or not. */
2527 if (memcmp (envline, "WARN", 4) == 0)
2528 GLRO(dl_verbose) = envline[5] != '\0';
2529 break;
2531 case 5:
2532 /* Debugging of the dynamic linker? */
2533 if (memcmp (envline, "DEBUG", 5) == 0)
2535 process_dl_debug (&envline[6]);
2536 break;
2538 if (memcmp (envline, "AUDIT", 5) == 0)
2539 process_dl_audit (&envline[6]);
2540 break;
2542 case 7:
2543 /* Print information about versions. */
2544 if (memcmp (envline, "VERBOSE", 7) == 0)
2546 version_info = envline[8] != '\0';
2547 break;
2550 /* List of objects to be preloaded. */
2551 if (memcmp (envline, "PRELOAD", 7) == 0)
2553 preloadlist = &envline[8];
2554 break;
2557 /* Which shared object shall be profiled. */
2558 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2559 GLRO(dl_profile) = &envline[8];
2560 break;
2562 case 8:
2563 /* Do we bind early? */
2564 if (memcmp (envline, "BIND_NOW", 8) == 0)
2566 GLRO(dl_lazy) = envline[9] == '\0';
2567 break;
2569 if (memcmp (envline, "BIND_NOT", 8) == 0)
2570 GLRO(dl_bind_not) = envline[9] != '\0';
2571 break;
2573 case 9:
2574 /* Test whether we want to see the content of the auxiliary
2575 array passed up from the kernel. */
2576 if (!INTUSE(__libc_enable_secure)
2577 && memcmp (envline, "SHOW_AUXV", 9) == 0)
2578 _dl_show_auxv ();
2579 break;
2581 case 10:
2582 /* Mask for the important hardware capabilities. */
2583 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2584 GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2585 0, 0);
2586 break;
2588 case 11:
2589 /* Path where the binary is found. */
2590 if (!INTUSE(__libc_enable_secure)
2591 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2592 GLRO(dl_origin_path) = &envline[12];
2593 break;
2595 case 12:
2596 /* The library search path. */
2597 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2599 library_path = &envline[13];
2600 break;
2603 /* Where to place the profiling data file. */
2604 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2606 debug_output = &envline[13];
2607 break;
2610 if (!INTUSE(__libc_enable_secure)
2611 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2612 GLRO(dl_dynamic_weak) = 1;
2613 break;
2615 case 13:
2616 /* We might have some extra environment variable with length 13
2617 to handle. */
2618 #ifdef EXTRA_LD_ENVVARS_13
2619 EXTRA_LD_ENVVARS_13
2620 #endif
2621 if (!INTUSE(__libc_enable_secure)
2622 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2624 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2625 break;
2628 if (memcmp (envline, "POINTER_GUARD", 13) == 0)
2629 GLRO(dl_pointer_guard) = envline[14] != '0';
2630 break;
2632 case 14:
2633 /* Where to place the profiling data file. */
2634 if (!INTUSE(__libc_enable_secure)
2635 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2636 && envline[15] != '\0')
2637 GLRO(dl_profile_output) = &envline[15];
2638 break;
2640 case 16:
2641 /* The mode of the dynamic linker can be set. */
2642 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2644 mode = trace;
2645 GLRO(dl_verbose) = 1;
2646 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2647 GLRO(dl_trace_prelink) = &envline[17];
2649 break;
2651 case 20:
2652 /* The mode of the dynamic linker can be set. */
2653 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2654 mode = trace;
2655 break;
2657 /* We might have some extra environment variable to handle. This
2658 is tricky due to the pre-processing of the length of the name
2659 in the switch statement here. The code here assumes that added
2660 environment variables have a different length. */
2661 #ifdef EXTRA_LD_ENVVARS
2662 EXTRA_LD_ENVVARS
2663 #endif
2667 /* The caller wants this information. */
2668 *modep = mode;
2670 /* Extra security for SUID binaries. Remove all dangerous environment
2671 variables. */
2672 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2674 static const char unsecure_envvars[] =
2675 #ifdef EXTRA_UNSECURE_ENVVARS
2676 EXTRA_UNSECURE_ENVVARS
2677 #endif
2678 UNSECURE_ENVVARS;
2679 const char *nextp;
2681 nextp = unsecure_envvars;
2684 unsetenv (nextp);
2685 /* We could use rawmemchr but this need not be fast. */
2686 nextp = (char *) (strchr) (nextp, '\0') + 1;
2688 while (*nextp != '\0');
2690 if (__access ("/etc/suid-debug", F_OK) != 0)
2692 unsetenv ("MALLOC_CHECK_");
2693 GLRO(dl_debug_mask) = 0;
2696 if (mode != normal)
2697 _exit (5);
2699 /* If we have to run the dynamic linker in debugging mode and the
2700 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2701 messages to this file. */
2702 else if (any_debug && debug_output != NULL)
2704 #ifdef O_NOFOLLOW
2705 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2706 #else
2707 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2708 #endif
2709 size_t name_len = strlen (debug_output);
2710 char buf[name_len + 12];
2711 char *startp;
2713 buf[name_len + 11] = '\0';
2714 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2715 *--startp = '.';
2716 startp = memcpy (startp - name_len, debug_output, name_len);
2718 GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2719 if (GLRO(dl_debug_fd) == -1)
2720 /* We use standard output if opening the file failed. */
2721 GLRO(dl_debug_fd) = STDOUT_FILENO;
2726 /* Print the various times we collected. */
2727 static void
2728 __attribute ((noinline))
2729 print_statistics (hp_timing_t *rtld_total_timep)
2731 #ifndef HP_TIMING_NONAVAIL
2732 char buf[200];
2733 char *cp;
2734 char *wp;
2736 /* Total time rtld used. */
2737 if (HP_TIMING_AVAIL)
2739 HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2740 _dl_debug_printf ("\nruntime linker statistics:\n"
2741 " total startup time in dynamic loader: %s\n", buf);
2743 /* Print relocation statistics. */
2744 char pbuf[30];
2745 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2746 cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2747 pbuf + sizeof (pbuf), 10, 0);
2748 wp = pbuf;
2749 switch (pbuf + sizeof (pbuf) - cp)
2751 case 3:
2752 *wp++ = *cp++;
2753 case 2:
2754 *wp++ = *cp++;
2755 case 1:
2756 *wp++ = '.';
2757 *wp++ = *cp++;
2759 *wp = '\0';
2760 _dl_debug_printf ("\
2761 time needed for relocation: %s (%s%%)\n", buf, pbuf);
2763 #endif
2765 unsigned long int num_relative_relocations = 0;
2766 for (Lmid_t ns = 0; ns < DL_NNS; ++ns)
2768 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2769 continue;
2771 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2773 for (unsigned int i = 0; i < scope->r_nlist; i++)
2775 struct link_map *l = scope->r_list [i];
2777 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2778 num_relative_relocations
2779 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2780 #ifndef ELF_MACHINE_REL_RELATIVE
2781 /* Relative relocations are processed on these architectures if
2782 library is loaded to different address than p_vaddr or
2783 if not prelinked. */
2784 if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2785 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2786 #else
2787 /* On e.g. IA-64 or Alpha, relative relocations are processed
2788 only if library is loaded to different address than p_vaddr. */
2789 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2790 #endif
2791 num_relative_relocations
2792 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2796 _dl_debug_printf (" number of relocations: %lu\n"
2797 " number of relocations from cache: %lu\n"
2798 " number of relative relocations: %lu\n",
2799 GL(dl_num_relocations),
2800 GL(dl_num_cache_relocations),
2801 num_relative_relocations);
2803 #ifndef HP_TIMING_NONAVAIL
2804 /* Time spend while loading the object and the dependencies. */
2805 if (HP_TIMING_AVAIL)
2807 char pbuf[30];
2808 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2809 cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2810 pbuf + sizeof (pbuf), 10, 0);
2811 wp = pbuf;
2812 switch (pbuf + sizeof (pbuf) - cp)
2814 case 3:
2815 *wp++ = *cp++;
2816 case 2:
2817 *wp++ = *cp++;
2818 case 1:
2819 *wp++ = '.';
2820 *wp++ = *cp++;
2822 *wp = '\0';
2823 _dl_debug_printf ("\
2824 time needed to load objects: %s (%s%%)\n",
2825 buf, pbuf);
2827 #endif