Updated to fedora-glibc-20050627T0850
[glibc.git] / elf / rtld.c
blobcf0e415ce11fe48d7c370b893b87fce4b6862d6d
1 /* Run time dynamic linker.
2 Copyright (C) 1995-2002, 2003, 2004, 2005 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 int _dl_argc attribute_relro attribute_hidden;
76 #ifdef DL_ARGV_NOT_RELRO
77 char **_dl_argv = NULL;
78 #else
79 char **_dl_argv attribute_relro = NULL;
80 #endif
81 INTDEF(_dl_argv)
83 #ifndef THREAD_SET_STACK_GUARD
84 /* Only exported for architectures that don't store the stack guard canary
85 in thread local area. */
86 uintptr_t __stack_chk_guard attribute_relro;
87 #endif
89 /* Nonzero if we were run directly. */
90 unsigned int _dl_skip_args attribute_relro attribute_hidden;
92 /* List of auditing DSOs. */
93 static struct audit_list
95 const char *name;
96 struct audit_list *next;
97 } *audit_list;
99 #ifndef HAVE_INLINED_SYSCALLS
100 /* Set nonzero during loading and initialization of executable and
101 libraries, cleared before the executable's entry point runs. This
102 must not be initialized to nonzero, because the unused dynamic
103 linker loaded in for libc.so's "ld.so.1" dep will provide the
104 definition seen by libc.so's initializer; that value must be zero,
105 and will be since that dynamic linker's _dl_start and dl_main will
106 never be called. */
107 int _dl_starting_up = 0;
108 INTVARDEF(_dl_starting_up)
109 #endif
111 /* This is the structure which defines all variables global to ld.so
112 (except those which cannot be added for some reason). */
113 struct rtld_global _rtld_global =
115 /* Default presumption without further information is executable stack. */
116 ._dl_stack_flags = PF_R|PF_W|PF_X,
117 #ifdef _LIBC_REENTRANT
118 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER
119 #endif
121 /* If we would use strong_alias here the compiler would see a
122 non-hidden definition. This would undo the effect of the previous
123 declaration. So spell out was strong_alias does plus add the
124 visibility attribute. */
125 extern struct rtld_global _rtld_local
126 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
129 /* This variable is similar to _rtld_local, but all values are
130 read-only after relocation. */
131 struct rtld_global_ro _rtld_global_ro attribute_relro =
133 /* Get architecture specific initializer. */
134 #include <dl-procinfo.c>
135 #ifdef NEED_DL_SYSINFO
136 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
137 #endif
138 ._dl_debug_fd = STDERR_FILENO,
139 ._dl_use_load_bias = -2,
140 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
141 ._dl_hwcap_mask = HWCAP_IMPORTANT,
142 ._dl_lazy = 1,
143 ._dl_fpu_control = _FPU_DEFAULT,
145 /* Function pointers. */
146 ._dl_debug_printf = _dl_debug_printf,
147 ._dl_catch_error = _dl_catch_error,
148 ._dl_signal_error = _dl_signal_error,
149 ._dl_mcount = _dl_mcount_internal,
150 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
151 ._dl_check_caller = _dl_check_caller,
152 ._dl_open = _dl_open,
153 ._dl_close = _dl_close
155 /* If we would use strong_alias here the compiler would see a
156 non-hidden definition. This would undo the effect of the previous
157 declaration. So spell out was strong_alias does plus add the
158 visibility attribute. */
159 extern struct rtld_global_ro _rtld_local_ro
160 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
163 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
164 ElfW(Addr) *user_entry);
166 /* These two variables cannot be moved into .data.rel.ro. */
167 static struct libname_list _dl_rtld_libname;
168 static struct libname_list _dl_rtld_libname2;
170 /* We expect less than a second for relocation. */
171 #ifdef HP_SMALL_TIMING_AVAIL
172 # undef HP_TIMING_AVAIL
173 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
174 #endif
176 /* Variable for statistics. */
177 #ifndef HP_TIMING_NONAVAIL
178 static hp_timing_t relocate_time;
179 static hp_timing_t load_time attribute_relro;
180 static hp_timing_t start_time attribute_relro;
181 #endif
183 /* Additional definitions needed by TLS initialization. */
184 #ifdef TLS_INIT_HELPER
185 TLS_INIT_HELPER
186 #endif
188 /* Helper function for syscall implementation. */
189 #ifdef DL_SYSINFO_IMPLEMENTATION
190 DL_SYSINFO_IMPLEMENTATION
191 #endif
193 /* Before ld.so is relocated we must not access variables which need
194 relocations. This means variables which are exported. Variables
195 declared as static are fine. If we can mark a variable hidden this
196 is fine, too. The latter is important here. We can avoid setting
197 up a temporary link map for ld.so if we can mark _rtld_global as
198 hidden. */
199 #if defined PI_STATIC_AND_HIDDEN && defined HAVE_HIDDEN \
200 && defined HAVE_VISIBILITY_ATTRIBUTE
201 # define DONT_USE_BOOTSTRAP_MAP 1
202 #endif
204 #ifdef DONT_USE_BOOTSTRAP_MAP
205 static ElfW(Addr) _dl_start_final (void *arg);
206 #else
207 struct dl_start_final_info
209 struct link_map l;
210 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
211 hp_timing_t start_time;
212 #endif
214 static ElfW(Addr) _dl_start_final (void *arg,
215 struct dl_start_final_info *info);
216 #endif
218 /* These defined magically in the linker script. */
219 extern char _begin[] attribute_hidden;
220 extern char _etext[] attribute_hidden;
221 extern char _end[] attribute_hidden;
224 #ifdef RTLD_START
225 RTLD_START
226 #else
227 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
228 #endif
230 #ifndef VALIDX
231 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
232 + DT_EXTRANUM + DT_VALTAGIDX (tag))
233 #endif
234 #ifndef ADDRIDX
235 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
236 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
237 #endif
239 /* This is the second half of _dl_start (below). It can be inlined safely
240 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
241 references. When the tools don't permit us to avoid using a GOT entry
242 for _dl_rtld_global (no attribute_hidden support), we must make sure
243 this function is not inlined (see below). */
245 #ifdef DONT_USE_BOOTSTRAP_MAP
246 static inline ElfW(Addr) __attribute__ ((always_inline))
247 _dl_start_final (void *arg)
248 #else
249 static ElfW(Addr) __attribute__ ((noinline))
250 _dl_start_final (void *arg, struct dl_start_final_info *info)
251 #endif
253 ElfW(Addr) start_addr;
255 if (HP_TIMING_AVAIL)
257 /* If it hasn't happen yet record the startup time. */
258 if (! HP_TIMING_INLINE)
259 HP_TIMING_NOW (start_time);
260 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
261 else
262 start_time = info->start_time;
263 #endif
265 /* Initialize the timing functions. */
266 HP_TIMING_DIFF_INIT ();
269 /* Transfer data about ourselves to the permanent link_map structure. */
270 #ifndef DONT_USE_BOOTSTRAP_MAP
271 GL(dl_rtld_map).l_addr = info->l.l_addr;
272 GL(dl_rtld_map).l_ld = info->l.l_ld;
273 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
274 sizeof GL(dl_rtld_map).l_info);
275 GL(dl_rtld_map).l_mach = info->l.l_mach;
276 GL(dl_rtld_map).l_relocated = 1;
277 #endif
278 _dl_setup_hash (&GL(dl_rtld_map));
279 GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
280 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
281 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
282 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
283 /* Copy the TLS related data if necessary. */
284 #if USE_TLS && !defined DONT_USE_BOOTSTRAP_MAP
285 # if USE___THREAD
286 assert (info->l.l_tls_modid != 0);
287 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
288 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
289 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
290 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
291 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
292 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
293 GL(dl_rtld_map).l_tls_modid = 1;
294 # else
295 assert (info->l.l_tls_modid == 0);
296 # if NO_TLS_OFFSET != 0
297 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
298 # endif
299 # endif
301 #endif
303 #if HP_TIMING_AVAIL
304 HP_TIMING_NOW (GL(dl_cpuclock_offset));
305 #endif
307 /* Initialize the stack end variable. */
308 __libc_stack_end = __builtin_frame_address (0);
310 /* Call the OS-dependent function to set up life so we can do things like
311 file access. It will call `dl_main' (below) to do all the real work
312 of the dynamic linker, and then unwind our frame and run the user
313 entry point on the same stack we entered on. */
314 start_addr = _dl_sysdep_start (arg, &dl_main);
316 #ifndef HP_TIMING_NONAVAIL
317 hp_timing_t rtld_total_time;
318 if (HP_TIMING_AVAIL)
320 hp_timing_t end_time;
322 /* Get the current time. */
323 HP_TIMING_NOW (end_time);
325 /* Compute the difference. */
326 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
328 #endif
330 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
332 #ifndef HP_TIMING_NONAVAIL
333 print_statistics (&rtld_total_time);
334 #else
335 print_statistics (NULL);
336 #endif
339 return start_addr;
342 static ElfW(Addr) __attribute_used__ internal_function
343 _dl_start (void *arg)
345 #ifdef DONT_USE_BOOTSTRAP_MAP
346 # define bootstrap_map GL(dl_rtld_map)
347 #else
348 struct dl_start_final_info info;
349 # define bootstrap_map info.l
350 #endif
352 /* This #define produces dynamic linking inline functions for
353 bootstrap relocation instead of general-purpose relocation. */
354 #define RTLD_BOOTSTRAP
355 #define RESOLVE_MAP(sym, version, flags) \
356 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : &bootstrap_map)
357 #include "dynamic-link.h"
359 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
360 #ifdef DONT_USE_BOOTSTRAP_MAP
361 HP_TIMING_NOW (start_time);
362 #else
363 HP_TIMING_NOW (info.start_time);
364 #endif
366 /* Partly clean the `bootstrap_map' structure up. Don't use
367 `memset' since it might not be built in or inlined and we cannot
368 make function calls at this point. Use '__builtin_memset' if we
369 know it is available. We do not have to clear the memory if we
370 do not have to use the temporary bootstrap_map. Global variables
371 are initialized to zero by default. */
372 #ifndef DONT_USE_BOOTSTRAP_MAP
373 # ifdef HAVE_BUILTIN_MEMSET
374 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
375 # else
376 for (size_t cnt = 0;
377 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
378 ++cnt)
379 bootstrap_map.l_info[cnt] = 0;
380 # endif
381 #endif
383 /* Figure out the run-time load address of the dynamic linker itself. */
384 bootstrap_map.l_addr = elf_machine_load_address ();
386 /* Read our own dynamic section and fill in the info array. */
387 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
388 elf_get_dynamic_info (&bootstrap_map, NULL);
390 #if defined USE_TLS && NO_TLS_OFFSET != 0
391 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
392 #endif
394 /* Get the dynamic linker's own program header. First we need the ELF
395 file header. The `_begin' symbol created by the linker script points
396 to it. When we have something like GOTOFF relocs, we can use a plain
397 reference to find the runtime address. Without that, we have to rely
398 on the `l_addr' value, which is not the value we want when prelinked. */
399 #if USE___THREAD
400 dtv_t initdtv[3];
401 ElfW(Ehdr) *ehdr
402 # ifdef DONT_USE_BOOTSTRAP_MAP
403 = (ElfW(Ehdr) *) &_begin;
404 # else
405 # error This will not work with prelink.
406 = (ElfW(Ehdr) *) bootstrap_map.l_addr;
407 # endif
408 ElfW(Phdr) *phdr = (ElfW(Phdr) *) ((void *) ehdr + ehdr->e_phoff);
409 size_t cnt = ehdr->e_phnum; /* PT_TLS is usually the last phdr. */
410 while (cnt-- > 0)
411 if (phdr[cnt].p_type == PT_TLS)
413 void *tlsblock;
414 size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
415 char *p;
417 bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
418 bootstrap_map.l_tls_align = phdr[cnt].p_align;
419 if (phdr[cnt].p_align == 0)
420 bootstrap_map.l_tls_firstbyte_offset = 0;
421 else
422 bootstrap_map.l_tls_firstbyte_offset = (phdr[cnt].p_vaddr
423 & (phdr[cnt].p_align - 1));
424 assert (bootstrap_map.l_tls_blocksize != 0);
425 bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
426 bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
427 + phdr[cnt].p_vaddr);
429 /* We can now allocate the initial TLS block. This can happen
430 on the stack. We'll get the final memory later when we
431 know all about the various objects loaded at startup
432 time. */
433 # if TLS_TCB_AT_TP
434 tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
435 TLS_INIT_TCB_ALIGN)
436 + TLS_INIT_TCB_SIZE
437 + max_align);
438 # elif TLS_DTV_AT_TP
439 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
440 bootstrap_map.l_tls_align)
441 + bootstrap_map.l_tls_blocksize
442 + max_align);
443 # else
444 /* In case a model with a different layout for the TCB and DTV
445 is defined add another #elif here and in the following #ifs. */
446 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
447 # endif
448 /* Align the TLS block. */
449 tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
450 & ~(max_align - 1));
452 /* Initialize the dtv. [0] is the length, [1] the generation
453 counter. */
454 initdtv[0].counter = 1;
455 initdtv[1].counter = 0;
457 /* Initialize the TLS block. */
458 # if TLS_TCB_AT_TP
459 initdtv[2].pointer = tlsblock;
460 # elif TLS_DTV_AT_TP
461 bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
462 bootstrap_map.l_tls_align);
463 initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
464 # else
465 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
466 # endif
467 p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
468 bootstrap_map.l_tls_initimage_size);
469 # ifdef HAVE_BUILTIN_MEMSET
470 __builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
471 - bootstrap_map.l_tls_initimage_size));
472 # else
474 size_t remaining = (bootstrap_map.l_tls_blocksize
475 - bootstrap_map.l_tls_initimage_size);
476 while (remaining-- > 0)
477 *p++ = '\0';
479 # endif
481 /* Install the pointer to the dtv. */
483 /* Initialize the thread pointer. */
484 # if TLS_TCB_AT_TP
485 bootstrap_map.l_tls_offset
486 = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
488 INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
489 initdtv);
491 const char *lossage = TLS_INIT_TP ((char *) tlsblock
492 + bootstrap_map.l_tls_offset, 0);
493 # elif TLS_DTV_AT_TP
494 INSTALL_DTV (tlsblock, initdtv);
495 const char *lossage = TLS_INIT_TP (tlsblock, 0);
496 # else
497 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
498 # endif
499 if (__builtin_expect (lossage != NULL, 0))
500 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
501 lossage);
503 /* So far this is module number one. */
504 bootstrap_map.l_tls_modid = 1;
506 /* There can only be one PT_TLS entry. */
507 break;
509 #endif /* USE___THREAD */
511 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
512 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
513 #endif
515 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
517 /* Relocate ourselves so we can do normal function calls and
518 data access using the global offset table. */
520 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
522 bootstrap_map.l_relocated = 1;
524 /* Please note that we don't allow profiling of this object and
525 therefore need not test whether we have to allocate the array
526 for the relocation results (as done in dl-reloc.c). */
528 /* Now life is sane; we can call functions and access global data.
529 Set up to use the operating system facilities, and find out from
530 the operating system's program loader where to find the program
531 header table in core. Put the rest of _dl_start into a separate
532 function, that way the compiler cannot put accesses to the GOT
533 before ELF_DYNAMIC_RELOCATE. */
535 #ifdef DONT_USE_BOOTSTRAP_MAP
536 ElfW(Addr) entry = _dl_start_final (arg);
537 #else
538 ElfW(Addr) entry = _dl_start_final (arg, &info);
539 #endif
541 #ifndef ELF_MACHINE_START_ADDRESS
542 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
543 #endif
545 return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, entry);
551 /* Now life is peachy; we can do all normal operations.
552 On to the real work. */
554 /* Some helper functions. */
556 /* Arguments to relocate_doit. */
557 struct relocate_args
559 struct link_map *l;
560 int lazy;
563 struct map_args
565 /* Argument to map_doit. */
566 char *str;
567 struct link_map *loader;
568 int is_preloaded;
569 int mode;
570 /* Return value of map_doit. */
571 struct link_map *map;
574 struct dlmopen_args
576 const char *fname;
577 struct link_map *map;
580 struct lookup_args
582 const char *name;
583 struct link_map *map;
584 void *result;
587 /* Arguments to version_check_doit. */
588 struct version_check_args
590 int doexit;
591 int dotrace;
594 static void
595 relocate_doit (void *a)
597 struct relocate_args *args = (struct relocate_args *) a;
599 _dl_relocate_object (args->l, args->l->l_scope, args->lazy, 0);
602 static void
603 map_doit (void *a)
605 struct map_args *args = (struct map_args *) a;
606 args->map = _dl_map_object (args->loader, args->str,
607 args->is_preloaded, lt_library, 0, args->mode,
608 LM_ID_BASE);
611 static void
612 dlmopen_doit (void *a)
614 struct dlmopen_args *args = (struct dlmopen_args *) a;
615 args->map = _dl_open (args->fname, RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT,
616 dl_main, LM_ID_NEWLM, _dl_argc, INTUSE(_dl_argv),
617 __environ);
620 static void
621 lookup_doit (void *a)
623 struct lookup_args *args = (struct lookup_args *) a;
624 const ElfW(Sym) *ref = NULL;
625 args->result = NULL;
626 lookup_t l = _dl_lookup_symbol_x (args->name, args->map, &ref,
627 args->map->l_local_scope, NULL, 0,
628 DL_LOOKUP_RETURN_NEWEST, NULL);
629 if (ref != NULL)
630 args->result = DL_SYMBOL_ADDRESS (l, ref);
633 static void
634 version_check_doit (void *a)
636 struct version_check_args *args = (struct version_check_args *) a;
637 if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
638 args->dotrace) && args->doexit)
639 /* We cannot start the application. Abort now. */
640 _exit (1);
644 static inline struct link_map *
645 find_needed (const char *name)
647 struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
648 unsigned int n = scope->r_nlist;
650 while (n-- > 0)
651 if (_dl_name_match_p (name, scope->r_list[n]))
652 return scope->r_list[n];
654 /* Should never happen. */
655 return NULL;
658 static int
659 match_version (const char *string, struct link_map *map)
661 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
662 ElfW(Verdef) *def;
664 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
665 if (map->l_info[VERDEFTAG] == NULL)
666 /* The file has no symbol versioning. */
667 return 0;
669 def = (ElfW(Verdef) *) ((char *) map->l_addr
670 + map->l_info[VERDEFTAG]->d_un.d_ptr);
671 while (1)
673 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
675 /* Compare the version strings. */
676 if (strcmp (string, strtab + aux->vda_name) == 0)
677 /* Bingo! */
678 return 1;
680 /* If no more definitions we failed to find what we want. */
681 if (def->vd_next == 0)
682 break;
684 /* Next definition. */
685 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
688 return 0;
691 #ifdef USE_TLS
692 static bool tls_init_tp_called;
694 static void *
695 init_tls (void)
697 /* Number of elements in the static TLS block. */
698 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
700 /* Do not do this twice. The audit interface might have required
701 the DTV interfaces to be set up early. */
702 if (GL(dl_initial_dtv) != NULL)
703 return NULL;
705 /* Allocate the array which contains the information about the
706 dtv slots. We allocate a few entries more than needed to
707 avoid the need for reallocation. */
708 size_t nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
710 /* Allocate. */
711 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
712 calloc (sizeof (struct dtv_slotinfo_list)
713 + nelem * sizeof (struct dtv_slotinfo), 1);
714 /* No need to check the return value. If memory allocation failed
715 the program would have been terminated. */
717 struct dtv_slotinfo *slotinfo = GL(dl_tls_dtv_slotinfo_list)->slotinfo;
718 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
719 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
721 /* Fill in the information from the loaded modules. No namespace
722 but the base one can be filled at this time. */
723 assert (GL(dl_ns)[LM_ID_BASE + 1]._ns_loaded == NULL);
724 int i = 0;
725 for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
726 l = l->l_next)
727 if (l->l_tls_blocksize != 0)
729 /* This is a module with TLS data. Store the map reference.
730 The generation counter is zero. */
731 slotinfo[i].map = l;
732 /* slotinfo[i].gen = 0; */
733 ++i;
735 assert (i == GL(dl_tls_max_dtv_idx));
737 /* Compute the TLS offsets for the various blocks. */
738 _dl_determine_tlsoffset ();
740 /* Construct the static TLS block and the dtv for the initial
741 thread. For some platforms this will include allocating memory
742 for the thread descriptor. The memory for the TLS block will
743 never be freed. It should be allocated accordingly. The dtv
744 array can be changed if dynamic loading requires it. */
745 void *tcbp = _dl_allocate_tls_storage ();
746 if (tcbp == NULL)
747 _dl_fatal_printf ("\
748 cannot allocate TLS data structures for initial thread");
750 /* Store for detection of the special case by __tls_get_addr
751 so it knows not to pass this dtv to the normal realloc. */
752 GL(dl_initial_dtv) = GET_DTV (tcbp);
754 /* And finally install it for the main thread. If ld.so itself uses
755 TLS we know the thread pointer was initialized earlier. */
756 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
757 if (__builtin_expect (lossage != NULL, 0))
758 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
759 tls_init_tp_called = true;
761 return tcbp;
763 #endif
765 #ifdef _LIBC_REENTRANT
766 /* _dl_error_catch_tsd points to this for the single-threaded case.
767 It's reset by the thread library for multithreaded programs. */
768 void ** __attribute__ ((const))
769 _dl_initial_error_catch_tsd (void)
771 static void *data;
772 return &data;
774 #endif
777 static unsigned int
778 do_preload (char *fname, struct link_map *main_map, const char *where)
780 const char *objname;
781 const char *err_str = NULL;
782 struct map_args args;
783 bool malloced;
785 args.str = fname;
786 args.loader = main_map;
787 args.is_preloaded = 1;
788 args.mode = 0;
790 unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
792 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
793 if (__builtin_expect (err_str != NULL, 0))
795 _dl_error_printf ("\
796 ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
797 fname, where);
798 /* No need to call free, this is still before
799 the libc's malloc is used. */
801 else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
802 /* It is no duplicate. */
803 return 1;
805 /* Nothing loaded. */
806 return 0;
809 #if defined SHARED && defined _LIBC_REENTRANT \
810 && defined __rtld_lock_default_lock_recursive
811 static void
812 rtld_lock_default_lock_recursive (void *lock)
814 __rtld_lock_default_lock_recursive (lock);
817 static void
818 rtld_lock_default_unlock_recursive (void *lock)
820 __rtld_lock_default_unlock_recursive (lock);
822 #endif
825 /* The library search path. */
826 static const char *library_path attribute_relro;
827 /* The list preloaded objects. */
828 static const char *preloadlist attribute_relro;
829 /* Nonzero if information about versions has to be printed. */
830 static int version_info attribute_relro;
832 static void
833 dl_main (const ElfW(Phdr) *phdr,
834 ElfW(Word) phnum,
835 ElfW(Addr) *user_entry)
837 const ElfW(Phdr) *ph;
838 enum mode mode;
839 struct link_map *main_map;
840 size_t file_size;
841 char *file;
842 bool has_interp = false;
843 unsigned int i;
844 bool prelinked = false;
845 bool rtld_is_main = false;
846 #ifndef HP_TIMING_NONAVAIL
847 hp_timing_t start;
848 hp_timing_t stop;
849 hp_timing_t diff;
850 #endif
851 #ifdef USE_TLS
852 void *tcbp = NULL;
853 #endif
855 #ifdef _LIBC_REENTRANT
856 /* Explicit initialization since the reloc would just be more work. */
857 GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
858 #endif
860 #ifdef USE_TLS
861 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
862 #endif
864 #if defined SHARED && defined _LIBC_REENTRANT \
865 && defined __rtld_lock_default_lock_recursive
866 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
867 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
868 #endif
870 /* The explicit initialization here is cheaper than processing the reloc
871 in the _rtld_local definition's initializer. */
872 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
874 /* Process the environment variable which control the behaviour. */
875 process_envvars (&mode);
877 #ifndef HAVE_INLINED_SYSCALLS
878 /* Set up a flag which tells we are just starting. */
879 INTUSE(_dl_starting_up) = 1;
880 #endif
882 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
884 /* Ho ho. We are not the program interpreter! We are the program
885 itself! This means someone ran ld.so as a command. Well, that
886 might be convenient to do sometimes. We support it by
887 interpreting the args like this:
889 ld.so PROGRAM ARGS...
891 The first argument is the name of a file containing an ELF
892 executable we will load and run with the following arguments.
893 To simplify life here, PROGRAM is searched for using the
894 normal rules for shared objects, rather than $PATH or anything
895 like that. We just load it and use its entry point; we don't
896 pay attention to its PT_INTERP command (we are the interpreter
897 ourselves). This is an easy way to test a new ld.so before
898 installing it. */
899 rtld_is_main = true;
901 /* Note the place where the dynamic linker actually came from. */
902 GL(dl_rtld_map).l_name = rtld_progname;
904 while (_dl_argc > 1)
905 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
907 mode = list;
908 GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
910 ++_dl_skip_args;
911 --_dl_argc;
912 ++INTUSE(_dl_argv);
914 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
916 mode = verify;
918 ++_dl_skip_args;
919 --_dl_argc;
920 ++INTUSE(_dl_argv);
922 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
923 && _dl_argc > 2)
925 library_path = INTUSE(_dl_argv)[2];
927 _dl_skip_args += 2;
928 _dl_argc -= 2;
929 INTUSE(_dl_argv) += 2;
931 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
932 && _dl_argc > 2)
934 GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
936 _dl_skip_args += 2;
937 _dl_argc -= 2;
938 INTUSE(_dl_argv) += 2;
940 else if (! strcmp (INTUSE(_dl_argv)[1], "--audit") && _dl_argc > 2)
942 process_dl_audit (INTUSE(_dl_argv)[2]);
944 _dl_skip_args += 2;
945 _dl_argc -= 2;
946 INTUSE(_dl_argv) += 2;
948 else
949 break;
951 /* If we have no further argument the program was called incorrectly.
952 Grant the user some education. */
953 if (_dl_argc < 2)
954 _dl_fatal_printf ("\
955 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
956 You have invoked `ld.so', the helper program for shared library executables.\n\
957 This program usually lives in the file `/lib/ld.so', and special directives\n\
958 in executable files using ELF shared libraries tell the system's program\n\
959 loader to load the helper program from this file. This helper program loads\n\
960 the shared libraries needed by the program executable, prepares the program\n\
961 to run, and runs it. You may invoke this helper program directly from the\n\
962 command line to load and run an ELF executable file; this is like executing\n\
963 that file itself, but always uses this helper program from the file you\n\
964 specified, instead of the helper program file specified in the executable\n\
965 file you run. This is mostly of use for maintainers to test new versions\n\
966 of this helper program; chances are you did not intend to run this program.\n\
968 --list list all dependencies and how they are resolved\n\
969 --verify verify that given object really is a dynamically linked\n\
970 object we can handle\n\
971 --library-path PATH use given PATH instead of content of the environment\n\
972 variable LD_LIBRARY_PATH\n\
973 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
974 in LIST\n");
976 ++_dl_skip_args;
977 --_dl_argc;
978 ++INTUSE(_dl_argv);
980 /* The initialization of _dl_stack_flags done below assumes the
981 executable's PT_GNU_STACK may have been honored by the kernel, and
982 so a PT_GNU_STACK with PF_X set means the stack started out with
983 execute permission. However, this is not really true if the
984 dynamic linker is the executable the kernel loaded. For this
985 case, we must reinitialize _dl_stack_flags to match the dynamic
986 linker itself. If the dynamic linker was built with a
987 PT_GNU_STACK, then the kernel may have loaded us with a
988 nonexecutable stack that we will have to make executable when we
989 load the program below unless it has a PT_GNU_STACK indicating
990 nonexecutable stack is ok. */
992 for (ph = phdr; ph < &phdr[phnum]; ++ph)
993 if (ph->p_type == PT_GNU_STACK)
995 GL(dl_stack_flags) = ph->p_flags;
996 break;
999 if (__builtin_expect (mode, normal) == verify)
1001 const char *objname;
1002 const char *err_str = NULL;
1003 struct map_args args;
1004 bool malloced;
1006 args.str = rtld_progname;
1007 args.loader = NULL;
1008 args.is_preloaded = 0;
1009 args.mode = __RTLD_OPENEXEC;
1010 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
1011 &args);
1012 if (__builtin_expect (err_str != NULL, 0))
1013 /* We don't free the returned string, the programs stops
1014 anyway. */
1015 _exit (EXIT_FAILURE);
1017 else
1019 HP_TIMING_NOW (start);
1020 _dl_map_object (NULL, rtld_progname, 0, lt_library, 0,
1021 __RTLD_OPENEXEC, LM_ID_BASE);
1022 HP_TIMING_NOW (stop);
1024 HP_TIMING_DIFF (load_time, start, stop);
1027 /* Now the map for the main executable is available. */
1028 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1030 phdr = main_map->l_phdr;
1031 phnum = main_map->l_phnum;
1032 /* We overwrite here a pointer to a malloc()ed string. But since
1033 the malloc() implementation used at this point is the dummy
1034 implementations which has no real free() function it does not
1035 makes sense to free the old string first. */
1036 main_map->l_name = (char *) "";
1037 *user_entry = main_map->l_entry;
1039 else
1041 /* Create a link_map for the executable itself.
1042 This will be what dlopen on "" returns. */
1043 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1044 __RTLD_OPENEXEC, LM_ID_BASE);
1045 assert (main_map != NULL);
1046 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
1047 main_map->l_phdr = phdr;
1048 main_map->l_phnum = phnum;
1049 main_map->l_entry = *user_entry;
1051 /* At this point we are in a bit of trouble. We would have to
1052 fill in the values for l_dev and l_ino. But in general we
1053 do not know where the file is. We also do not handle AT_EXECFD
1054 even if it would be passed up.
1056 We leave the values here defined to 0. This is normally no
1057 problem as the program code itself is normally no shared
1058 object and therefore cannot be loaded dynamically. Nothing
1059 prevent the use of dynamic binaries and in these situations
1060 we might get problems. We might not be able to find out
1061 whether the object is already loaded. But since there is no
1062 easy way out and because the dynamic binary must also not
1063 have an SONAME we ignore this program for now. If it becomes
1064 a problem we can force people using SONAMEs. */
1066 /* We delay initializing the path structure until we got the dynamic
1067 information for the program. */
1070 main_map->l_map_end = 0;
1071 main_map->l_text_end = 0;
1072 /* Perhaps the executable has no PT_LOAD header entries at all. */
1073 main_map->l_map_start = ~0;
1074 /* And it was opened directly. */
1075 ++main_map->l_direct_opencount;
1077 /* Scan the program header table for the dynamic section. */
1078 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1079 switch (ph->p_type)
1081 case PT_PHDR:
1082 /* Find out the load address. */
1083 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1084 break;
1085 case PT_DYNAMIC:
1086 /* This tells us where to find the dynamic section,
1087 which tells us everything we need to do. */
1088 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
1089 break;
1090 case PT_INTERP:
1091 /* This "interpreter segment" was used by the program loader to
1092 find the program interpreter, which is this program itself, the
1093 dynamic linker. We note what name finds us, so that a future
1094 dlopen call or DT_NEEDED entry, for something that wants to link
1095 against the dynamic linker as a shared library, will know that
1096 the shared object is already loaded. */
1097 _dl_rtld_libname.name = ((const char *) main_map->l_addr
1098 + ph->p_vaddr);
1099 /* _dl_rtld_libname.next = NULL; Already zero. */
1100 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1102 /* Ordinarilly, we would get additional names for the loader from
1103 our DT_SONAME. This can't happen if we were actually linked as
1104 a static executable (detect this case when we have no DYNAMIC).
1105 If so, assume the filename component of the interpreter path to
1106 be our SONAME, and add it to our name list. */
1107 if (GL(dl_rtld_map).l_ld == NULL)
1109 const char *p = NULL;
1110 const char *cp = _dl_rtld_libname.name;
1112 /* Find the filename part of the path. */
1113 while (*cp != '\0')
1114 if (*cp++ == '/')
1115 p = cp;
1117 if (p != NULL)
1119 _dl_rtld_libname2.name = p;
1120 /* _dl_rtld_libname2.next = NULL; Already zero. */
1121 _dl_rtld_libname.next = &_dl_rtld_libname2;
1125 has_interp = true;
1126 break;
1127 case PT_LOAD:
1129 ElfW(Addr) mapstart;
1130 ElfW(Addr) allocend;
1132 /* Remember where the main program starts in memory. */
1133 mapstart = (main_map->l_addr + (ph->p_vaddr & ~(ph->p_align - 1)));
1134 if (main_map->l_map_start > mapstart)
1135 main_map->l_map_start = mapstart;
1137 /* Also where it ends. */
1138 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1139 if (main_map->l_map_end < allocend)
1140 main_map->l_map_end = allocend;
1141 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1142 main_map->l_text_end = allocend;
1144 break;
1146 case PT_TLS:
1147 #ifdef USE_TLS
1148 if (ph->p_memsz > 0)
1150 /* Note that in the case the dynamic linker we duplicate work
1151 here since we read the PT_TLS entry already in
1152 _dl_start_final. But the result is repeatable so do not
1153 check for this special but unimportant case. */
1154 main_map->l_tls_blocksize = ph->p_memsz;
1155 main_map->l_tls_align = ph->p_align;
1156 if (ph->p_align == 0)
1157 main_map->l_tls_firstbyte_offset = 0;
1158 else
1159 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1160 & (ph->p_align - 1));
1161 main_map->l_tls_initimage_size = ph->p_filesz;
1162 main_map->l_tls_initimage = (void *) ph->p_vaddr;
1164 /* This image gets the ID one. */
1165 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1167 #else
1168 _dl_fatal_printf ("\
1169 ld.so does not support TLS, but program uses it!\n");
1170 #endif
1171 break;
1173 case PT_GNU_STACK:
1174 GL(dl_stack_flags) = ph->p_flags;
1175 break;
1177 case PT_GNU_RELRO:
1178 main_map->l_relro_addr = ph->p_vaddr;
1179 main_map->l_relro_size = ph->p_memsz;
1180 break;
1182 #ifdef USE_TLS
1183 /* Adjust the address of the TLS initialization image in case
1184 the executable is actually an ET_DYN object. */
1185 if (main_map->l_tls_initimage != NULL)
1186 main_map->l_tls_initimage
1187 = (char *) main_map->l_tls_initimage + main_map->l_addr;
1188 #endif
1189 if (! main_map->l_map_end)
1190 main_map->l_map_end = ~0;
1191 if (! main_map->l_text_end)
1192 main_map->l_text_end = ~0;
1193 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1195 /* We were invoked directly, so the program might not have a
1196 PT_INTERP. */
1197 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1198 /* _dl_rtld_libname.next = NULL; Already zero. */
1199 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1201 else
1202 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1204 /* If the current libname is different from the SONAME, add the
1205 latter as well. */
1206 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1207 && strcmp (GL(dl_rtld_map).l_libname->name,
1208 (const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1209 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1211 static struct libname_list newname;
1212 newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1213 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1214 newname.next = NULL;
1215 newname.dont_free = 1;
1217 assert (GL(dl_rtld_map).l_libname->next == NULL);
1218 GL(dl_rtld_map).l_libname->next = &newname;
1220 /* The ld.so must be relocated since otherwise loading audit modules
1221 will fail since they reuse the very same ld.so. */
1222 assert (GL(dl_rtld_map).l_relocated);
1224 if (! rtld_is_main)
1226 /* Extract the contents of the dynamic section for easy access. */
1227 elf_get_dynamic_info (main_map, NULL);
1228 /* Set up our cache of pointers into the hash table. */
1229 _dl_setup_hash (main_map);
1232 if (__builtin_expect (mode, normal) == verify)
1234 /* We were called just to verify that this is a dynamic
1235 executable using us as the program interpreter. Exit with an
1236 error if we were not able to load the binary or no interpreter
1237 is specified (i.e., this is no dynamically linked binary. */
1238 if (main_map->l_ld == NULL)
1239 _exit (1);
1241 /* We allow here some platform specific code. */
1242 #ifdef DISTINGUISH_LIB_VERSIONS
1243 DISTINGUISH_LIB_VERSIONS;
1244 #endif
1245 _exit (has_interp ? 0 : 2);
1248 struct link_map **first_preload = &GL(dl_rtld_map).l_next;
1249 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1250 /* Set up the data structures for the system-supplied DSO early,
1251 so they can influence _dl_init_paths. */
1252 if (GLRO(dl_sysinfo_dso) != NULL)
1254 /* Do an abridged version of the work _dl_map_object_from_fd would do
1255 to map in the object. It's already mapped and prelinked (and
1256 better be, since it's read-only and so we couldn't relocate it).
1257 We just want our data structures to describe it as if we had just
1258 mapped and relocated it normally. */
1259 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL,
1260 0, LM_ID_BASE);
1261 if (__builtin_expect (l != NULL, 1))
1263 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
1265 l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1266 + GLRO(dl_sysinfo_dso)->e_phoff);
1267 l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1268 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1270 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1271 if (ph->p_type == PT_DYNAMIC)
1273 l->l_ld = (void *) ph->p_vaddr;
1274 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1276 else if (ph->p_type == PT_LOAD)
1278 if (! l->l_addr)
1279 l->l_addr = ph->p_vaddr;
1280 if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1281 l->l_map_end = ph->p_vaddr + ph->p_memsz;
1282 if ((ph->p_flags & PF_X)
1283 && ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1284 l->l_text_end = ph->p_vaddr + ph->p_memsz;
1286 else
1287 /* There must be no TLS segment. */
1288 assert (ph->p_type != PT_TLS);
1290 l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1291 l->l_addr = l->l_map_start - l->l_addr;
1292 l->l_map_end += l->l_addr;
1293 l->l_text_end += l->l_addr;
1294 l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1295 elf_get_dynamic_info (l, dyn_temp);
1296 _dl_setup_hash (l);
1297 l->l_relocated = 1;
1299 /* Now that we have the info handy, use the DSO image's soname
1300 so this object can be looked up by name. Note that we do not
1301 set l_name here. That field gives the file name of the DSO,
1302 and this DSO is not associated with any file. */
1303 if (l->l_info[DT_SONAME] != NULL)
1305 /* Work around a kernel problem. The kernel cannot handle
1306 addresses in the vsyscall DSO pages in writev() calls. */
1307 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1308 + l->l_info[DT_SONAME]->d_un.d_val);
1309 size_t len = strlen (dsoname);
1310 char *copy = malloc (len);
1311 if (copy == NULL)
1312 _dl_fatal_printf ("out of memory\n");
1313 l->l_libname->name = memcpy (copy, dsoname, len);
1316 /* Rearrange the list so this DSO appears after rtld_map. */
1317 assert (l->l_next == NULL);
1318 assert (l->l_prev == main_map);
1319 GL(dl_rtld_map).l_next = l;
1320 l->l_prev = &GL(dl_rtld_map);
1321 first_preload = &l->l_next;
1323 /* We have a prelinked DSO preloaded by the system. */
1324 GLRO(dl_sysinfo_map) = l;
1325 # ifdef NEED_DL_SYSINFO
1326 if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1327 GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1328 # endif
1331 #endif
1333 #ifdef DL_SYSDEP_OSCHECK
1334 DL_SYSDEP_OSCHECK (dl_fatal);
1335 #endif
1337 /* Initialize the data structures for the search paths for shared
1338 objects. */
1339 _dl_init_paths (library_path);
1341 /* Initialize _r_debug. */
1342 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1343 LM_ID_BASE);
1344 r->r_state = RT_CONSISTENT;
1346 /* Put the link_map for ourselves on the chain so it can be found by
1347 name. Note that at this point the global chain of link maps contains
1348 exactly one element, which is pointed to by dl_loaded. */
1349 if (! GL(dl_rtld_map).l_name)
1350 /* If not invoked directly, the dynamic linker shared object file was
1351 found by the PT_INTERP name. */
1352 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1353 GL(dl_rtld_map).l_type = lt_library;
1354 main_map->l_next = &GL(dl_rtld_map);
1355 GL(dl_rtld_map).l_prev = main_map;
1356 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1357 ++GL(dl_load_adds);
1359 #if defined(__i386__)
1360 /* Force non-TLS libraries for glibc 2.0 binaries
1361 or if a buggy binary references non-TLS errno or h_errno. */
1362 if (__builtin_expect (main_map->l_info[DT_NUM + DT_THISPROCNUM
1363 + DT_VERSIONTAGIDX (DT_VERNEED)]
1364 == NULL, 0)
1365 && main_map->l_info[DT_DEBUG])
1366 GLRO(dl_osversion) = 0x20205;
1367 else if ((__builtin_expect (mode, normal) != normal
1368 || main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)] == NULL)
1369 /* Only binaries have DT_DEBUG dynamic tags... */
1370 && main_map->l_info[DT_DEBUG])
1372 /* Workaround for buggy binaries. This doesn't handle buggy
1373 libraries. */
1374 bool buggy = false;
1375 const ElfW(Sym) *symtab = (const void *) D_PTR (main_map,
1376 l_info[DT_SYMTAB]);
1377 const char *strtab = (const void *) D_PTR (main_map,
1378 l_info[DT_STRTAB]);
1379 Elf_Symndx symidx;
1380 for (symidx = main_map->l_buckets[0x6c994f % main_map->l_nbuckets];
1381 symidx != STN_UNDEF;
1382 symidx = main_map->l_chain[symidx])
1384 if (__builtin_expect (strcmp (strtab + symtab[symidx].st_name,
1385 "errno") == 0, 0)
1386 && ELFW(ST_TYPE) (symtab[symidx].st_info) != STT_TLS)
1387 buggy = true;
1389 for (symidx = main_map->l_buckets[0xe5c992f % main_map->l_nbuckets];
1390 symidx != STN_UNDEF;
1391 symidx = main_map->l_chain[symidx])
1393 if (__builtin_expect (strcmp (strtab + symtab[symidx].st_name,
1394 "h_errno") == 0, 0)
1395 && ELFW(ST_TYPE) (symtab[symidx].st_info) != STT_TLS)
1396 buggy = true;
1398 if (__builtin_expect (buggy, false) && GLRO(dl_osversion) > 0x20401)
1400 GLRO(dl_osversion) = 0x20401;
1401 _dl_error_printf ("Incorrectly built binary which accesses errno or h_errno directly. Needs to be fixed.\n");
1404 #endif
1406 if (GLRO(dl_osversion) <= 0x20413)
1408 extern void internal_function _dl_init_linuxthreads_paths (void);
1409 _dl_init_linuxthreads_paths ();
1412 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1413 to not using bias for non-prelinked PIEs and libraries
1414 and using it for executables or prelinked PIEs or libraries. */
1415 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1416 GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
1418 /* Set up the program header information for the dynamic linker
1419 itself. It is needed in the dl_iterate_phdr() callbacks. */
1420 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1421 ElfW(Phdr) *rtld_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1422 + rtld_ehdr->e_phoff);
1423 GL(dl_rtld_map).l_phdr = rtld_phdr;
1424 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1427 /* PT_GNU_RELRO is usually the last phdr. */
1428 size_t cnt = rtld_ehdr->e_phnum;
1429 while (cnt-- > 0)
1430 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1432 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1433 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1434 break;
1437 #ifdef USE_TLS
1438 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1439 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1440 /* Assign a module ID. Do this before loading any audit modules. */
1441 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1442 #endif
1444 /* If we have auditing DSOs to load, do it now. */
1445 if (__builtin_expect (audit_list != NULL, 0))
1447 /* Iterate over all entries in the list. The order is important. */
1448 struct audit_ifaces *last_audit = NULL;
1449 struct audit_list *al = audit_list->next;
1452 #ifdef USE_TLS
1453 int tls_idx = GL(dl_tls_max_dtv_idx);
1455 /* Now it is time to determine the layout of the static TLS
1456 block and allocate it for the initial thread. Note that we
1457 always allocate the static block, we never defer it even if
1458 no DF_STATIC_TLS bit is set. The reason is that we know
1459 glibc will use the static model. */
1461 /* Since we start using the auditing DSOs right away we need to
1462 initialize the data structures now. */
1463 tcbp = init_tls ();
1464 #endif
1465 struct dlmopen_args dlmargs;
1466 dlmargs.fname = al->name;
1467 dlmargs.map = NULL;
1469 const char *objname;
1470 const char *err_str = NULL;
1471 bool malloced;
1472 (void) _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit,
1473 &dlmargs);
1474 if (__builtin_expect (err_str != NULL, 0))
1476 not_loaded:
1477 _dl_error_printf ("\
1478 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
1479 al->name, err_str);
1480 if (malloced)
1481 free ((char *) err_str);
1483 else
1485 struct lookup_args largs;
1486 largs.name = "la_version";
1487 largs.map = dlmargs.map;
1489 /* Check whether the interface version matches. */
1490 (void) _dl_catch_error (&objname, &err_str, &malloced,
1491 lookup_doit, &largs);
1493 unsigned int (*laversion) (unsigned int);
1494 unsigned int lav;
1495 if (err_str == NULL
1496 && (laversion = largs.result) != NULL
1497 && (lav = laversion (LAV_CURRENT)) > 0
1498 && lav <= LAV_CURRENT)
1500 /* Allocate structure for the callback function pointers.
1501 This call can never fail. */
1502 union
1504 struct audit_ifaces ifaces;
1505 #define naudit_ifaces 8
1506 void (*fptr[naudit_ifaces]) (void);
1507 } *newp = malloc (sizeof (*newp));
1509 /* Names of the auditing interfaces. All in one
1510 long string. */
1511 static const char audit_iface_names[] =
1512 "la_activity\0"
1513 "la_objsearch\0"
1514 "la_objopen\0"
1515 "la_preinit\0"
1516 #if __ELF_NATIVE_CLASS == 32
1517 "la_symbind32\0"
1518 #elif __ELF_NATIVE_CLASS == 64
1519 "la_symbind64\0"
1520 #else
1521 # error "__ELF_NATIVE_CLASS must be defined"
1522 #endif
1523 #define STRING(s) __STRING (s)
1524 "la_" STRING (ARCH_LA_PLTENTER) "\0"
1525 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
1526 "la_objclose\0";
1527 unsigned int cnt = 0;
1528 const char *cp = audit_iface_names;
1531 largs.name = cp;
1532 (void) _dl_catch_error (&objname, &err_str, &malloced,
1533 lookup_doit, &largs);
1535 /* Store the pointer. */
1536 if (err_str == NULL && largs.result != NULL)
1538 newp->fptr[cnt] = largs.result;
1540 /* The dynamic linker link map is statically
1541 allocated, initialize the data now. */
1542 GL(dl_rtld_map).l_audit[cnt].cookie
1543 = (intptr_t) &GL(dl_rtld_map);
1545 else
1546 newp->fptr[cnt] = NULL;
1547 ++cnt;
1549 cp = (char *) rawmemchr (cp, '\0') + 1;
1551 while (*cp != '\0');
1552 assert (cnt == naudit_ifaces);
1554 /* Now append the new auditing interface to the list. */
1555 newp->ifaces.next = NULL;
1556 if (last_audit == NULL)
1557 last_audit = GLRO(dl_audit) = &newp->ifaces;
1558 else
1559 last_audit = last_audit->next = &newp->ifaces;
1560 ++GLRO(dl_naudit);
1562 /* Mark the DSO as being used for auditing. */
1563 dlmargs.map->l_auditing = 1;
1565 else
1567 /* We cannot use the DSO, it does not have the
1568 appropriate interfaces or it expects something
1569 more recent. */
1570 #ifndef NDEBUG
1571 Lmid_t ns = dlmargs.map->l_ns;
1572 #endif
1573 _dl_close (dlmargs.map);
1575 /* Make sure the namespace has been cleared entirely. */
1576 assert (GL(dl_ns)[ns]._ns_loaded == NULL);
1577 assert (GL(dl_ns)[ns]._ns_nloaded == 0);
1579 #ifdef USE_TLS
1580 GL(dl_tls_max_dtv_idx) = tls_idx;
1581 #endif
1582 goto not_loaded;
1586 al = al->next;
1588 while (al != audit_list->next);
1590 /* If we have any auditing modules, announce that we already
1591 have two objects loaded. */
1592 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1594 struct link_map *ls[2] = { main_map, &GL(dl_rtld_map) };
1596 for (unsigned int outer = 0; outer < 2; ++outer)
1598 struct audit_ifaces *afct = GLRO(dl_audit);
1599 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1601 if (afct->objopen != NULL)
1603 ls[outer]->l_audit[cnt].bindflags
1604 = afct->objopen (ls[outer], LM_ID_BASE,
1605 &ls[outer]->l_audit[cnt].cookie);
1607 ls[outer]->l_audit_any_plt
1608 |= ls[outer]->l_audit[cnt].bindflags != 0;
1611 afct = afct->next;
1617 /* Set up debugging before the debugger is notified for the first time. */
1618 #ifdef ELF_MACHINE_DEBUG_SETUP
1619 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1620 ELF_MACHINE_DEBUG_SETUP (main_map, r);
1621 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1622 #else
1623 if (main_map->l_info[DT_DEBUG] != NULL)
1624 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1625 with the run-time address of the r_debug structure */
1626 main_map->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1628 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1629 case you run gdb on the dynamic linker directly. */
1630 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1631 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1632 #endif
1634 /* We start adding objects. */
1635 r->r_state = RT_ADD;
1636 _dl_debug_state ();
1638 /* Auditing checkpoint: we are ready to signal that the initial map
1639 is being constructed. */
1640 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1642 struct audit_ifaces *afct = GLRO(dl_audit);
1643 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1645 if (afct->activity != NULL)
1646 afct->activity (&main_map->l_audit[cnt].cookie, LA_ACT_ADD);
1648 afct = afct->next;
1652 /* We have two ways to specify objects to preload: via environment
1653 variable and via the file /etc/ld.so.preload. The latter can also
1654 be used when security is enabled. */
1655 assert (*first_preload == NULL);
1656 struct link_map **preloads = NULL;
1657 unsigned int npreloads = 0;
1659 if (__builtin_expect (preloadlist != NULL, 0))
1661 /* The LD_PRELOAD environment variable gives list of libraries
1662 separated by white space or colons that are loaded before the
1663 executable's dependencies and prepended to the global scope
1664 list. If the binary is running setuid all elements
1665 containing a '/' are ignored since it is insecure. */
1666 char *list = strdupa (preloadlist);
1667 char *p;
1669 HP_TIMING_NOW (start);
1671 /* Prevent optimizing strsep. Speed is not important here. */
1672 while ((p = (strsep) (&list, " :")) != NULL)
1673 if (p[0] != '\0'
1674 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1675 || strchr (p, '/') == NULL))
1676 npreloads += do_preload (p, main_map, "LD_PRELOAD");
1678 HP_TIMING_NOW (stop);
1679 HP_TIMING_DIFF (diff, start, stop);
1680 HP_TIMING_ACCUM_NT (load_time, diff);
1683 /* There usually is no ld.so.preload file, it should only be used
1684 for emergencies and testing. So the open call etc should usually
1685 fail. Using access() on a non-existing file is faster than using
1686 open(). So we do this first. If it succeeds we do almost twice
1687 the work but this does not matter, since it is not for production
1688 use. */
1689 static const char preload_file[] = "/etc/ld.so.preload";
1690 if (__builtin_expect (__access (preload_file, R_OK) == 0, 0))
1692 /* Read the contents of the file. */
1693 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1694 PROT_READ | PROT_WRITE);
1695 if (__builtin_expect (file != MAP_FAILED, 0))
1697 /* Parse the file. It contains names of libraries to be loaded,
1698 separated by white spaces or `:'. It may also contain
1699 comments introduced by `#'. */
1700 char *problem;
1701 char *runp;
1702 size_t rest;
1704 /* Eliminate comments. */
1705 runp = file;
1706 rest = file_size;
1707 while (rest > 0)
1709 char *comment = memchr (runp, '#', rest);
1710 if (comment == NULL)
1711 break;
1713 rest -= comment - runp;
1715 *comment = ' ';
1716 while (--rest > 0 && *++comment != '\n');
1719 /* We have one problematic case: if we have a name at the end of
1720 the file without a trailing terminating characters, we cannot
1721 place the \0. Handle the case separately. */
1722 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1723 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1725 problem = &file[file_size];
1726 while (problem > file && problem[-1] != ' '
1727 && problem[-1] != '\t'
1728 && problem[-1] != '\n' && problem[-1] != ':')
1729 --problem;
1731 if (problem > file)
1732 problem[-1] = '\0';
1734 else
1736 problem = NULL;
1737 file[file_size - 1] = '\0';
1740 HP_TIMING_NOW (start);
1742 if (file != problem)
1744 char *p;
1745 runp = file;
1746 while ((p = strsep (&runp, ": \t\n")) != NULL)
1747 if (p[0] != '\0')
1748 npreloads += do_preload (p, main_map, preload_file);
1751 if (problem != NULL)
1753 char *p = strndupa (problem, file_size - (problem - file));
1755 npreloads += do_preload (p, main_map, preload_file);
1758 HP_TIMING_NOW (stop);
1759 HP_TIMING_DIFF (diff, start, stop);
1760 HP_TIMING_ACCUM_NT (load_time, diff);
1762 /* We don't need the file anymore. */
1763 __munmap (file, file_size);
1767 #if defined(__i386__) || defined(__alpha__) || (defined(__sparc__) && !defined(__arch64__))
1769 * Modifications by Red Hat Software
1771 * Deal with the broken binaries from the non-versioned ages of glibc.
1772 * If a binary does not have version information enabled, we assume that
1773 * it is a glibc 2.0 binary and we load a compatibility library to try to
1774 * overcome binary incompatibilities.
1775 * Blame: gafton@redhat.com
1777 #define LIB_NOVERSION "/lib/libNoVersion.so.1"
1779 if (__builtin_expect (main_map->l_info[DT_NUM + DT_THISPROCNUM
1780 + DT_VERSIONTAGIDX (DT_VERNEED)]
1781 == NULL, 0)
1782 && (main_map->l_info[DT_DEBUG]
1783 || !(GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)))
1785 struct stat test_st;
1786 int test_fd;
1787 int can_load;
1789 HP_TIMING_NOW (start);
1791 /* _dl_sysdep_message("Loading compatibility library... ", NULL); */
1793 can_load = 1;
1794 test_fd = __open (LIB_NOVERSION, O_RDONLY);
1795 if (test_fd < 0) {
1796 can_load = 0;
1797 /* _dl_sysdep_message(" Can't find " LIB_NOVERSION "\n", NULL); */
1798 } else {
1799 if (__fxstat (_STAT_VER, test_fd, &test_st) < 0 || test_st.st_size == 0) {
1800 can_load = 0;
1801 /* _dl_sysdep_message(" Can't stat " LIB_NOVERSION "\n", NULL); */
1805 if (test_fd >= 0) /* open did no fail.. */
1806 __close(test_fd); /* avoid fd leaks */
1808 if (can_load != 0)
1809 npreloads += do_preload (LIB_NOVERSION, main_map,
1810 "nonversioned binary");
1812 HP_TIMING_NOW (stop);
1813 HP_TIMING_DIFF (diff, start, stop);
1814 HP_TIMING_ACCUM_NT (load_time, diff);
1816 #endif
1818 if (__builtin_expect (*first_preload != NULL, 0))
1820 /* Set up PRELOADS with a vector of the preloaded libraries. */
1821 struct link_map *l = *first_preload;
1822 preloads = __alloca (npreloads * sizeof preloads[0]);
1823 i = 0;
1826 preloads[i++] = l;
1827 l = l->l_next;
1828 } while (l);
1829 assert (i == npreloads);
1832 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1833 specified some libraries to load, these are inserted before the actual
1834 dependencies in the executable's searchlist for symbol resolution. */
1835 HP_TIMING_NOW (start);
1836 _dl_map_object_deps (main_map, preloads, npreloads, mode == trace, 0);
1837 HP_TIMING_NOW (stop);
1838 HP_TIMING_DIFF (diff, start, stop);
1839 HP_TIMING_ACCUM_NT (load_time, diff);
1841 /* Mark all objects as being in the global scope. */
1842 for (i = main_map->l_searchlist.r_nlist; i > 0; )
1843 main_map->l_searchlist.r_list[--i]->l_global = 1;
1845 #ifndef MAP_ANON
1846 /* We are done mapping things, so close the zero-fill descriptor. */
1847 __close (_dl_zerofd);
1848 _dl_zerofd = -1;
1849 #endif
1851 /* Remove _dl_rtld_map from the chain. */
1852 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1853 if (GL(dl_rtld_map).l_next != NULL)
1854 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1856 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1857 if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1858 break;
1860 bool rtld_multiple_ref = false;
1861 if (__builtin_expect (i < main_map->l_searchlist.r_nlist, 1))
1863 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1864 put it back in the list of visible objects. We insert it into the
1865 chain in symbol search order because gdb uses the chain's order as
1866 its symbol search order. */
1867 rtld_multiple_ref = true;
1869 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1870 if (__builtin_expect (mode, normal) == normal)
1872 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1873 ? main_map->l_searchlist.r_list[i + 1]
1874 : NULL);
1875 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1876 if (GLRO(dl_sysinfo_map) != NULL
1877 && GL(dl_rtld_map).l_prev->l_next == GLRO(dl_sysinfo_map)
1878 && GL(dl_rtld_map).l_next != GLRO(dl_sysinfo_map))
1879 GL(dl_rtld_map).l_prev = GLRO(dl_sysinfo_map);
1880 #endif
1882 else
1883 /* In trace mode there might be an invisible object (which we
1884 could not find) after the previous one in the search list.
1885 In this case it doesn't matter much where we put the
1886 interpreter object, so we just initialize the list pointer so
1887 that the assertion below holds. */
1888 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1890 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1891 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1892 if (GL(dl_rtld_map).l_next != NULL)
1894 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1895 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1899 /* Now let us see whether all libraries are available in the
1900 versions we need. */
1902 struct version_check_args args;
1903 args.doexit = mode == normal;
1904 args.dotrace = mode == trace;
1905 _dl_receive_error (print_missing_version, version_check_doit, &args);
1908 #ifdef USE_TLS
1909 /* We do not initialize any of the TLS functionality unless any of the
1910 initial modules uses TLS. This makes dynamic loading of modules with
1911 TLS impossible, but to support it requires either eagerly doing setup
1912 now or lazily doing it later. Doing it now makes us incompatible with
1913 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1914 used. Trying to do it lazily is too hairy to try when there could be
1915 multiple threads (from a non-TLS-using libpthread). */
1916 bool was_tls_init_tp_called = tls_init_tp_called;
1917 if (tcbp == NULL)
1918 tcbp = init_tls ();
1919 #endif
1921 /* Set up the stack checker's canary. */
1922 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard ();
1923 #ifdef THREAD_SET_STACK_GUARD
1924 THREAD_SET_STACK_GUARD (stack_chk_guard);
1925 #else
1926 __stack_chk_guard = stack_chk_guard;
1927 #endif
1929 if (__builtin_expect (mode, normal) != normal)
1931 /* We were run just to list the shared libraries. It is
1932 important that we do this before real relocation, because the
1933 functions we call below for output may no longer work properly
1934 after relocation. */
1935 struct link_map *l;
1937 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1939 struct r_scope_elem *scope = &main_map->l_searchlist;
1941 for (i = 0; i < scope->r_nlist; i++)
1943 l = scope->r_list [i];
1944 if (l->l_faked)
1946 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1947 continue;
1949 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1950 GLRO(dl_trace_prelink_map) = l;
1951 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1952 l->l_libname->name[0] ? l->l_libname->name
1953 : rtld_progname ?: "<main program>",
1954 l->l_name[0] ? l->l_name
1955 : rtld_progname ?: "<main program>",
1956 (int) sizeof l->l_map_start * 2,
1957 (size_t) l->l_map_start,
1958 (int) sizeof l->l_addr * 2,
1959 (size_t) l->l_addr);
1960 #ifdef USE_TLS
1961 if (l->l_tls_modid)
1962 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1963 (int) sizeof l->l_tls_offset * 2,
1964 (size_t) l->l_tls_offset);
1965 else
1966 #endif
1967 _dl_printf ("\n");
1970 else if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
1972 /* Look through the dependencies of the main executable
1973 and determine which of them is not actually
1974 required. */
1975 struct link_map *l = main_map;
1977 /* Relocate the main executable. */
1978 struct relocate_args args = { .l = l, .lazy = GLRO(dl_lazy) };
1979 _dl_receive_error (print_unresolved, relocate_doit, &args);
1981 /* This loop depends on the dependencies of the executable to
1982 correspond in number and order to the DT_NEEDED entries. */
1983 ElfW(Dyn) *dyn = main_map->l_ld;
1984 bool first = true;
1985 while (dyn->d_tag != DT_NULL)
1987 if (dyn->d_tag == DT_NEEDED)
1989 l = l->l_next;
1991 if (!l->l_used)
1993 if (first)
1995 _dl_printf ("Unused direct dependencies:\n");
1996 first = false;
1999 _dl_printf ("\t%s\n", l->l_name);
2003 ++dyn;
2006 _exit (first != true);
2008 else if (! main_map->l_info[DT_NEEDED])
2009 _dl_printf ("\tstatically linked\n");
2010 else
2012 for (l = main_map->l_next; l; l = l->l_next)
2013 if (l->l_faked)
2014 /* The library was not found. */
2015 _dl_printf ("\t%s => not found\n", l->l_libname->name);
2016 else if (strcmp (l->l_libname->name, l->l_name) == 0)
2017 _dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
2018 (int) sizeof l->l_map_start * 2,
2019 (size_t) l->l_map_start);
2020 else
2021 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
2022 l->l_name, (int) sizeof l->l_map_start * 2,
2023 (size_t) l->l_map_start);
2026 if (__builtin_expect (mode, trace) != trace)
2027 for (i = 1; i < (unsigned int) _dl_argc; ++i)
2029 const ElfW(Sym) *ref = NULL;
2030 ElfW(Addr) loadbase;
2031 lookup_t result;
2033 result = _dl_lookup_symbol_x (INTUSE(_dl_argv)[i], main_map,
2034 &ref, main_map->l_scope, NULL,
2035 ELF_RTYPE_CLASS_PLT,
2036 DL_LOOKUP_ADD_DEPENDENCY, NULL);
2038 loadbase = LOOKUP_VALUE_ADDRESS (result);
2040 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
2041 INTUSE(_dl_argv)[i],
2042 (int) sizeof ref->st_value * 2,
2043 (size_t) ref->st_value,
2044 (int) sizeof loadbase * 2, (size_t) loadbase);
2046 else
2048 /* If LD_WARN is set, warn about undefined symbols. */
2049 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
2051 /* We have to do symbol dependency testing. */
2052 struct relocate_args args;
2053 struct link_map *l;
2055 args.lazy = GLRO(dl_lazy);
2057 l = main_map;
2058 while (l->l_next != NULL)
2059 l = l->l_next;
2062 if (l != &GL(dl_rtld_map) && ! l->l_faked)
2064 args.l = l;
2065 _dl_receive_error (print_unresolved, relocate_doit,
2066 &args);
2068 l = l->l_prev;
2070 while (l != NULL);
2072 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
2073 && rtld_multiple_ref)
2075 /* Mark the link map as not yet relocated again. */
2076 GL(dl_rtld_map).l_relocated = 0;
2077 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope,
2078 0, 0);
2081 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
2082 if (version_info)
2084 /* Print more information. This means here, print information
2085 about the versions needed. */
2086 int first = 1;
2087 struct link_map *map;
2089 for (map = main_map; map != NULL; map = map->l_next)
2091 const char *strtab;
2092 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
2093 ElfW(Verneed) *ent;
2095 if (dyn == NULL)
2096 continue;
2098 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
2099 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
2101 if (first)
2103 _dl_printf ("\n\tVersion information:\n");
2104 first = 0;
2107 _dl_printf ("\t%s:\n",
2108 map->l_name[0] ? map->l_name : rtld_progname);
2110 while (1)
2112 ElfW(Vernaux) *aux;
2113 struct link_map *needed;
2115 needed = find_needed (strtab + ent->vn_file);
2116 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
2118 while (1)
2120 const char *fname = NULL;
2122 if (needed != NULL
2123 && match_version (strtab + aux->vna_name,
2124 needed))
2125 fname = needed->l_name;
2127 _dl_printf ("\t\t%s (%s) %s=> %s\n",
2128 strtab + ent->vn_file,
2129 strtab + aux->vna_name,
2130 aux->vna_flags & VER_FLG_WEAK
2131 ? "[WEAK] " : "",
2132 fname ?: "not found");
2134 if (aux->vna_next == 0)
2135 /* No more symbols. */
2136 break;
2138 /* Next symbol. */
2139 aux = (ElfW(Vernaux) *) ((char *) aux
2140 + aux->vna_next);
2143 if (ent->vn_next == 0)
2144 /* No more dependencies. */
2145 break;
2147 /* Next dependency. */
2148 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
2154 _exit (0);
2157 if (main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]
2158 && ! __builtin_expect (GLRO(dl_profile) != NULL, 0))
2160 ElfW(Lib) *liblist, *liblistend;
2161 struct link_map **r_list, **r_listend, *l;
2162 const char *strtab = (const void *) D_PTR (main_map, l_info[DT_STRTAB]);
2164 assert (main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
2165 liblist = (ElfW(Lib) *)
2166 main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
2167 liblistend = (ElfW(Lib) *)
2168 ((char *) liblist +
2169 main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
2170 r_list = main_map->l_searchlist.r_list;
2171 r_listend = r_list + main_map->l_searchlist.r_nlist;
2173 for (; r_list < r_listend && liblist < liblistend; r_list++)
2175 l = *r_list;
2177 if (l == main_map)
2178 continue;
2180 /* If the library is not mapped where it should, fail. */
2181 if (l->l_addr)
2182 break;
2184 /* Next, check if checksum matches. */
2185 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
2186 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
2187 != liblist->l_checksum)
2188 break;
2190 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
2191 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
2192 != liblist->l_time_stamp)
2193 break;
2195 if (! _dl_name_match_p (strtab + liblist->l_name, l))
2196 break;
2198 ++liblist;
2202 if (r_list == r_listend && liblist == liblistend)
2203 prelinked = true;
2205 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
2206 _dl_debug_printf ("\nprelink checking: %s\n",
2207 prelinked ? "ok" : "failed");
2211 /* Now set up the variable which helps the assembler startup code. */
2212 GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
2213 GL(dl_ns)[LM_ID_BASE]._ns_global_scope[0] = &main_map->l_searchlist;
2215 /* Save the information about the original global scope list since
2216 we need it in the memory handling later. */
2217 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
2219 if (prelinked)
2221 if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
2223 ElfW(Rela) *conflict, *conflictend;
2224 #ifndef HP_TIMING_NONAVAIL
2225 hp_timing_t start;
2226 hp_timing_t stop;
2227 #endif
2229 HP_TIMING_NOW (start);
2230 assert (main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
2231 conflict = (ElfW(Rela) *)
2232 main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
2233 conflictend = (ElfW(Rela) *)
2234 ((char *) conflict
2235 + main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
2236 _dl_resolve_conflicts (main_map, conflict, conflictend);
2237 HP_TIMING_NOW (stop);
2238 HP_TIMING_DIFF (relocate_time, start, stop);
2242 /* Mark all the objects so we know they have been already relocated. */
2243 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2245 l->l_relocated = 1;
2246 if (l->l_relro_size)
2247 _dl_protect_relro (l);
2249 #ifdef USE_TLS
2250 /* Add object to slot information data if necessasy. */
2251 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2252 _dl_add_to_slotinfo (l);
2253 #endif
2256 _dl_sysdep_start_cleanup ();
2258 else
2260 /* Now we have all the objects loaded. Relocate them all except for
2261 the dynamic linker itself. We do this in reverse order so that copy
2262 relocs of earlier objects overwrite the data written by later
2263 objects. We do not re-relocate the dynamic linker itself in this
2264 loop because that could result in the GOT entries for functions we
2265 call being changed, and that would break us. It is safe to relocate
2266 the dynamic linker out of order because it has no copy relocs (we
2267 know that because it is self-contained). */
2269 int consider_profiling = GLRO(dl_profile) != NULL;
2270 #ifndef HP_TIMING_NONAVAIL
2271 hp_timing_t start;
2272 hp_timing_t stop;
2273 hp_timing_t add;
2274 #endif
2276 /* If we are profiling we also must do lazy reloaction. */
2277 GLRO(dl_lazy) |= consider_profiling;
2279 struct link_map *l = main_map;
2280 while (l->l_next)
2281 l = l->l_next;
2283 HP_TIMING_NOW (start);
2286 /* While we are at it, help the memory handling a bit. We have to
2287 mark some data structures as allocated with the fake malloc()
2288 implementation in ld.so. */
2289 struct libname_list *lnp = l->l_libname->next;
2291 while (__builtin_expect (lnp != NULL, 0))
2293 lnp->dont_free = 1;
2294 lnp = lnp->next;
2297 if (l != &GL(dl_rtld_map))
2298 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy),
2299 consider_profiling);
2301 #ifdef USE_TLS
2302 /* Add object to slot information data if necessasy. */
2303 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2304 _dl_add_to_slotinfo (l);
2305 #endif
2307 l = l->l_prev;
2309 while (l);
2310 HP_TIMING_NOW (stop);
2312 HP_TIMING_DIFF (relocate_time, start, stop);
2314 /* Do any necessary cleanups for the startup OS interface code.
2315 We do these now so that no calls are made after rtld re-relocation
2316 which might be resolved to different functions than we expect.
2317 We cannot do this before relocating the other objects because
2318 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2319 _dl_sysdep_start_cleanup ();
2321 /* Now enable profiling if needed. Like the previous call,
2322 this has to go here because the calls it makes should use the
2323 rtld versions of the functions (particularly calloc()), but it
2324 needs to have _dl_profile_map set up by the relocator. */
2325 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
2326 /* We must prepare the profiling. */
2327 _dl_start_profile ();
2329 if (rtld_multiple_ref)
2331 /* There was an explicit ref to the dynamic linker as a shared lib.
2332 Re-relocate ourselves with user-controlled symbol definitions. */
2333 HP_TIMING_NOW (start);
2334 /* Mark the link map as not yet relocated again. */
2335 GL(dl_rtld_map).l_relocated = 0;
2336 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2337 HP_TIMING_NOW (stop);
2338 HP_TIMING_DIFF (add, start, stop);
2339 HP_TIMING_ACCUM_NT (relocate_time, add);
2343 #ifndef NONTLS_INIT_TP
2344 # define NONTLS_INIT_TP do { } while (0)
2345 #endif
2347 #ifdef USE_TLS
2348 if (!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2349 ++GL(dl_tls_generation);
2351 /* Now that we have completed relocation, the initializer data
2352 for the TLS blocks has its final values and we can copy them
2353 into the main thread's TLS area, which we allocated above. */
2354 _dl_allocate_tls_init (tcbp);
2356 /* And finally install it for the main thread. If ld.so itself uses
2357 TLS we know the thread pointer was initialized earlier. */
2358 if (! tls_init_tp_called)
2360 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
2361 if (__builtin_expect (lossage != NULL, 0))
2362 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2363 lossage);
2365 #else
2366 NONTLS_INIT_TP;
2367 #endif
2369 #ifdef SHARED
2370 /* Auditing checkpoint: we have added all objects. */
2371 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
2373 struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2374 /* Do not call the functions for any auditing object. */
2375 if (head->l_auditing == 0)
2377 struct audit_ifaces *afct = GLRO(dl_audit);
2378 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2380 if (afct->activity != NULL)
2381 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
2383 afct = afct->next;
2387 #endif
2389 /* Notify the debugger all new objects are now ready to go. We must re-get
2390 the address since by now the variable might be in another object. */
2391 r = _dl_debug_initialize (0, LM_ID_BASE);
2392 r->r_state = RT_CONSISTENT;
2393 _dl_debug_state ();
2395 #ifndef MAP_COPY
2396 /* We must munmap() the cache file. */
2397 _dl_unload_cache ();
2398 #endif
2400 /* Once we return, _dl_sysdep_start will invoke
2401 the DT_INIT functions and then *USER_ENTRY. */
2404 /* This is a little helper function for resolving symbols while
2405 tracing the binary. */
2406 static void
2407 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2408 const char *errstring)
2410 if (objname[0] == '\0')
2411 objname = rtld_progname ?: "<main program>";
2412 _dl_error_printf ("%s (%s)\n", errstring, objname);
2415 /* This is a little helper function for resolving symbols while
2416 tracing the binary. */
2417 static void
2418 print_missing_version (int errcode __attribute__ ((unused)),
2419 const char *objname, const char *errstring)
2421 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
2422 objname, errstring);
2425 /* Nonzero if any of the debugging options is enabled. */
2426 static int any_debug attribute_relro;
2428 /* Process the string given as the parameter which explains which debugging
2429 options are enabled. */
2430 static void
2431 process_dl_debug (const char *dl_debug)
2433 /* When adding new entries make sure that the maximal length of a name
2434 is correctly handled in the LD_DEBUG_HELP code below. */
2435 static const struct
2437 unsigned char len;
2438 const char name[10];
2439 const char helptext[41];
2440 unsigned short int mask;
2441 } debopts[] =
2443 #define LEN_AND_STR(str) sizeof (str) - 1, str
2444 { LEN_AND_STR ("libs"), "display library search paths",
2445 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2446 { LEN_AND_STR ("reloc"), "display relocation processing",
2447 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2448 { LEN_AND_STR ("files"), "display progress for input file",
2449 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2450 { LEN_AND_STR ("symbols"), "display symbol table processing",
2451 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2452 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2453 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2454 { LEN_AND_STR ("versions"), "display version dependencies",
2455 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2456 { LEN_AND_STR ("all"), "all previous options combined",
2457 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2458 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2459 { LEN_AND_STR ("statistics"), "display relocation statistics",
2460 DL_DEBUG_STATISTICS },
2461 { LEN_AND_STR ("unused"), "determined unused DSOs",
2462 DL_DEBUG_UNUSED },
2463 { LEN_AND_STR ("help"), "display this help message and exit",
2464 DL_DEBUG_HELP },
2466 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2468 /* Skip separating white spaces and commas. */
2469 while (*dl_debug != '\0')
2471 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2473 size_t cnt;
2474 size_t len = 1;
2476 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2477 && dl_debug[len] != ',' && dl_debug[len] != ':')
2478 ++len;
2480 for (cnt = 0; cnt < ndebopts; ++cnt)
2481 if (debopts[cnt].len == len
2482 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
2484 GLRO(dl_debug_mask) |= debopts[cnt].mask;
2485 any_debug = 1;
2486 break;
2489 if (cnt == ndebopts)
2491 /* Display a warning and skip everything until next
2492 separator. */
2493 char *copy = strndupa (dl_debug, len);
2494 _dl_error_printf ("\
2495 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2498 dl_debug += len;
2499 continue;
2502 ++dl_debug;
2505 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
2507 size_t cnt;
2509 _dl_printf ("\
2510 Valid options for the LD_DEBUG environment variable are:\n\n");
2512 for (cnt = 0; cnt < ndebopts; ++cnt)
2513 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2514 " " + debopts[cnt].len - 3,
2515 debopts[cnt].helptext);
2517 _dl_printf ("\n\
2518 To direct the debugging output into a file instead of standard output\n\
2519 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2520 _exit (0);
2524 static void
2525 process_dl_audit (char *str)
2527 /* The parameter is a colon separated list of DSO names. */
2528 char *p;
2530 while ((p = (strsep) (&str, ":")) != NULL)
2531 if (p[0] != '\0'
2532 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
2533 || strchr (p, '/') == NULL))
2535 /* This is using the local malloc, not the system malloc. The
2536 memory can never be freed. */
2537 struct audit_list *newp = malloc (sizeof (*newp));
2538 newp->name = p;
2540 if (audit_list == NULL)
2541 audit_list = newp->next = newp;
2542 else
2544 newp->next = audit_list->next;
2545 audit_list = audit_list->next = newp;
2550 /* Process all environments variables the dynamic linker must recognize.
2551 Since all of them start with `LD_' we are a bit smarter while finding
2552 all the entries. */
2553 extern char **_environ attribute_hidden;
2556 static void
2557 process_envvars (enum mode *modep)
2559 char **runp = _environ;
2560 char *envline;
2561 enum mode mode = normal;
2562 char *debug_output = NULL;
2564 /* This is the default place for profiling data file. */
2565 GLRO(dl_profile_output)
2566 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2568 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2570 size_t len = 0;
2572 while (envline[len] != '\0' && envline[len] != '=')
2573 ++len;
2575 if (envline[len] != '=')
2576 /* This is a "LD_" variable at the end of the string without
2577 a '=' character. Ignore it since otherwise we will access
2578 invalid memory below. */
2579 continue;
2581 switch (len)
2583 case 4:
2584 /* Warning level, verbose or not. */
2585 if (memcmp (envline, "WARN", 4) == 0)
2586 GLRO(dl_verbose) = envline[5] != '\0';
2587 break;
2589 case 5:
2590 /* Debugging of the dynamic linker? */
2591 if (memcmp (envline, "DEBUG", 5) == 0)
2593 process_dl_debug (&envline[6]);
2594 break;
2596 if (memcmp (envline, "AUDIT", 5) == 0)
2597 process_dl_audit (&envline[6]);
2598 break;
2600 case 7:
2601 /* Print information about versions. */
2602 if (memcmp (envline, "VERBOSE", 7) == 0)
2604 version_info = envline[8] != '\0';
2605 break;
2608 /* List of objects to be preloaded. */
2609 if (memcmp (envline, "PRELOAD", 7) == 0)
2611 preloadlist = &envline[8];
2612 break;
2615 /* Which shared object shall be profiled. */
2616 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2617 GLRO(dl_profile) = &envline[8];
2618 break;
2620 case 8:
2621 /* Do we bind early? */
2622 if (memcmp (envline, "BIND_NOW", 8) == 0)
2624 GLRO(dl_lazy) = envline[9] == '\0';
2625 break;
2627 if (memcmp (envline, "BIND_NOT", 8) == 0)
2628 GLRO(dl_bind_not) = envline[9] != '\0';
2629 break;
2631 case 9:
2632 /* Test whether we want to see the content of the auxiliary
2633 array passed up from the kernel. */
2634 if (!INTUSE(__libc_enable_secure)
2635 && memcmp (envline, "SHOW_AUXV", 9) == 0)
2636 _dl_show_auxv ();
2637 break;
2639 case 10:
2640 /* Mask for the important hardware capabilities. */
2641 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2642 GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2643 0, 0);
2644 break;
2646 case 11:
2647 /* Path where the binary is found. */
2648 if (!INTUSE(__libc_enable_secure)
2649 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2650 GLRO(dl_origin_path) = &envline[12];
2651 break;
2653 case 12:
2654 /* The library search path. */
2655 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2657 library_path = &envline[13];
2658 break;
2661 /* Where to place the profiling data file. */
2662 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2664 debug_output = &envline[13];
2665 break;
2668 if (!INTUSE(__libc_enable_secure)
2669 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2670 GLRO(dl_dynamic_weak) = 1;
2671 break;
2673 case 13:
2674 /* We might have some extra environment variable with length 13
2675 to handle. */
2676 #ifdef EXTRA_LD_ENVVARS_13
2677 EXTRA_LD_ENVVARS_13
2678 #endif
2679 if (!INTUSE(__libc_enable_secure)
2680 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2681 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2682 break;
2684 case 14:
2685 /* Where to place the profiling data file. */
2686 if (!INTUSE(__libc_enable_secure)
2687 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2688 && envline[15] != '\0')
2689 GLRO(dl_profile_output) = &envline[15];
2690 break;
2692 case 16:
2693 /* The mode of the dynamic linker can be set. */
2694 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2696 mode = trace;
2697 GLRO(dl_verbose) = 1;
2698 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2699 GLRO(dl_trace_prelink) = &envline[17];
2701 break;
2703 case 20:
2704 /* The mode of the dynamic linker can be set. */
2705 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2706 mode = trace;
2707 break;
2709 /* We might have some extra environment variable to handle. This
2710 is tricky due to the pre-processing of the length of the name
2711 in the switch statement here. The code here assumes that added
2712 environment variables have a different length. */
2713 #ifdef EXTRA_LD_ENVVARS
2714 EXTRA_LD_ENVVARS
2715 #endif
2719 /* The caller wants this information. */
2720 *modep = mode;
2722 /* Extra security for SUID binaries. Remove all dangerous environment
2723 variables. */
2724 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2726 static const char unsecure_envvars[] =
2727 #ifdef EXTRA_UNSECURE_ENVVARS
2728 EXTRA_UNSECURE_ENVVARS
2729 #endif
2730 UNSECURE_ENVVARS;
2731 const char *nextp;
2733 nextp = unsecure_envvars;
2736 unsetenv (nextp);
2737 /* We could use rawmemchr but this need not be fast. */
2738 nextp = (char *) (strchr) (nextp, '\0') + 1;
2740 while (*nextp != '\0');
2742 if (__access ("/etc/suid-debug", F_OK) != 0)
2744 unsetenv ("MALLOC_CHECK_");
2745 GLRO(dl_debug_mask) = 0;
2748 if (mode != normal)
2749 _exit (5);
2751 /* If we have to run the dynamic linker in debugging mode and the
2752 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2753 messages to this file. */
2754 else if (any_debug && debug_output != NULL)
2756 #ifdef O_NOFOLLOW
2757 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2758 #else
2759 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2760 #endif
2761 size_t name_len = strlen (debug_output);
2762 char buf[name_len + 12];
2763 char *startp;
2765 buf[name_len + 11] = '\0';
2766 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2767 *--startp = '.';
2768 startp = memcpy (startp - name_len, debug_output, name_len);
2770 GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2771 if (GLRO(dl_debug_fd) == -1)
2772 /* We use standard output if opening the file failed. */
2773 GLRO(dl_debug_fd) = STDOUT_FILENO;
2778 /* Print the various times we collected. */
2779 static void
2780 __attribute ((noinline))
2781 print_statistics (hp_timing_t *rtld_total_timep)
2783 #ifndef HP_TIMING_NONAVAIL
2784 char buf[200];
2785 char *cp;
2786 char *wp;
2788 /* Total time rtld used. */
2789 if (HP_TIMING_AVAIL)
2791 HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2792 _dl_debug_printf ("\nruntime linker statistics:\n"
2793 " total startup time in dynamic loader: %s\n", buf);
2795 /* Print relocation statistics. */
2796 char pbuf[30];
2797 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2798 cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2799 pbuf + sizeof (pbuf), 10, 0);
2800 wp = pbuf;
2801 switch (pbuf + sizeof (pbuf) - cp)
2803 case 3:
2804 *wp++ = *cp++;
2805 case 2:
2806 *wp++ = *cp++;
2807 case 1:
2808 *wp++ = '.';
2809 *wp++ = *cp++;
2811 *wp = '\0';
2812 _dl_debug_printf ("\
2813 time needed for relocation: %s (%s%%)\n", buf, pbuf);
2815 #endif
2817 unsigned long int num_relative_relocations = 0;
2818 for (Lmid_t ns = 0; ns < DL_NNS; ++ns)
2820 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2821 continue;
2823 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2825 for (unsigned int i = 0; i < scope->r_nlist; i++)
2827 struct link_map *l = scope->r_list [i];
2829 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2830 num_relative_relocations
2831 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2832 #ifndef ELF_MACHINE_REL_RELATIVE
2833 /* Relative relocations are processed on these architectures if
2834 library is loaded to different address than p_vaddr or
2835 if not prelinked. */
2836 if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2837 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2838 #else
2839 /* On e.g. IA-64 or Alpha, relative relocations are processed
2840 only if library is loaded to different address than p_vaddr. */
2841 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2842 #endif
2843 num_relative_relocations
2844 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2848 _dl_debug_printf (" number of relocations: %lu\n"
2849 " number of relocations from cache: %lu\n"
2850 " number of relative relocations: %lu\n",
2851 GL(dl_num_relocations),
2852 GL(dl_num_cache_relocations),
2853 num_relative_relocations);
2855 #ifndef HP_TIMING_NONAVAIL
2856 /* Time spend while loading the object and the dependencies. */
2857 if (HP_TIMING_AVAIL)
2859 char pbuf[30];
2860 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2861 cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2862 pbuf + sizeof (pbuf), 10, 0);
2863 wp = pbuf;
2864 switch (pbuf + sizeof (pbuf) - cp)
2866 case 3:
2867 *wp++ = *cp++;
2868 case 2:
2869 *wp++ = *cp++;
2870 case 1:
2871 *wp++ = '.';
2872 *wp++ = *cp++;
2874 *wp = '\0';
2875 _dl_debug_printf ("\
2876 time needed to load objects: %s (%s%%)\n",
2877 buf, pbuf);
2879 #endif