2.3.4-19
[glibc.git] / elf / rtld.c
blobb2122bb9d6fe6ad0a59c2d15e7aad875f6b56bf4
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-procinfo.h>
41 #include <tls.h>
43 #include <assert.h>
45 /* Avoid PLT use for our local calls at startup. */
46 extern __typeof (__mempcpy) __mempcpy attribute_hidden;
48 /* GCC has mental blocks about _exit. */
49 extern __typeof (_exit) exit_internal asm ("_exit") attribute_hidden;
50 #define _exit exit_internal
52 /* Helper function to handle errors while resolving symbols. */
53 static void print_unresolved (int errcode, const char *objname,
54 const char *errsting);
56 /* Helper function to handle errors when a version is missing. */
57 static void print_missing_version (int errcode, const char *objname,
58 const char *errsting);
60 /* Print the various times we collected. */
61 static void print_statistics (hp_timing_t *total_timep);
63 /* This is a list of all the modes the dynamic loader can be in. */
64 enum mode { normal, list, verify, trace };
66 /* Process all environments variables the dynamic linker must recognize.
67 Since all of them start with `LD_' we are a bit smarter while finding
68 all the entries. */
69 static void process_envvars (enum mode *modep);
71 int _dl_argc attribute_relro attribute_hidden;
72 #ifdef DL_ARGV_NOT_RELRO
73 char **_dl_argv = NULL;
74 #else
75 char **_dl_argv attribute_relro = NULL;
76 #endif
77 INTDEF(_dl_argv)
79 /* Nonzero if we were run directly. */
80 unsigned int _dl_skip_args attribute_relro attribute_hidden;
82 /* List of auditing DSOs. */
83 static struct audit_list
85 const char *name;
86 struct audit_list *next;
87 } *audit_list;
89 #ifndef HAVE_INLINED_SYSCALLS
90 /* Set nonzero during loading and initialization of executable and
91 libraries, cleared before the executable's entry point runs. This
92 must not be initialized to nonzero, because the unused dynamic
93 linker loaded in for libc.so's "ld.so.1" dep will provide the
94 definition seen by libc.so's initializer; that value must be zero,
95 and will be since that dynamic linker's _dl_start and dl_main will
96 never be called. */
97 int _dl_starting_up = 0;
98 INTVARDEF(_dl_starting_up)
99 #endif
101 /* This is the structure which defines all variables global to ld.so
102 (except those which cannot be added for some reason). */
103 struct rtld_global _rtld_global =
105 /* Default presumption without further information is executable stack. */
106 ._dl_stack_flags = PF_R|PF_W|PF_X,
107 #ifdef _LIBC_REENTRANT
108 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER
109 #endif
111 /* If we would use strong_alias here the compiler would see a
112 non-hidden definition. This would undo the effect of the previous
113 declaration. So spell out was strong_alias does plus add the
114 visibility attribute. */
115 extern struct rtld_global _rtld_local
116 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
119 /* This variable is similar to _rtld_local, but all values are
120 read-only after relocation. */
121 struct rtld_global_ro _rtld_global_ro attribute_relro =
123 /* Get architecture specific initializer. */
124 #include <dl-procinfo.c>
125 #ifdef NEED_DL_SYSINFO
126 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
127 #endif
128 ._dl_debug_fd = STDERR_FILENO,
129 ._dl_use_load_bias = -2,
130 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
131 ._dl_hwcap_mask = HWCAP_IMPORTANT,
132 ._dl_lazy = 1,
133 ._dl_fpu_control = _FPU_DEFAULT,
135 /* Function pointers. */
136 ._dl_debug_printf = _dl_debug_printf,
137 ._dl_catch_error = _dl_catch_error,
138 ._dl_signal_error = _dl_signal_error,
139 ._dl_mcount = _dl_mcount_internal,
140 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
141 ._dl_check_caller = _dl_check_caller,
142 ._dl_open = _dl_open,
143 ._dl_close = _dl_close
145 /* If we would use strong_alias here the compiler would see a
146 non-hidden definition. This would undo the effect of the previous
147 declaration. So spell out was strong_alias does plus add the
148 visibility attribute. */
149 extern struct rtld_global_ro _rtld_local_ro
150 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
153 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
154 ElfW(Addr) *user_entry);
156 /* These two variables cannot be moved into .data.rel.ro. */
157 static struct libname_list _dl_rtld_libname;
158 static struct libname_list _dl_rtld_libname2;
160 /* We expect less than a second for relocation. */
161 #ifdef HP_SMALL_TIMING_AVAIL
162 # undef HP_TIMING_AVAIL
163 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
164 #endif
166 /* Variable for statistics. */
167 #ifndef HP_TIMING_NONAVAIL
168 static hp_timing_t relocate_time;
169 static hp_timing_t load_time attribute_relro;
170 static hp_timing_t start_time attribute_relro;
171 #endif
173 /* Additional definitions needed by TLS initialization. */
174 #ifdef TLS_INIT_HELPER
175 TLS_INIT_HELPER
176 #endif
178 /* Helper function for syscall implementation. */
179 #ifdef DL_SYSINFO_IMPLEMENTATION
180 DL_SYSINFO_IMPLEMENTATION
181 #endif
183 /* Before ld.so is relocated we must not access variables which need
184 relocations. This means variables which are exported. Variables
185 declared as static are fine. If we can mark a variable hidden this
186 is fine, too. The latter is important here. We can avoid setting
187 up a temporary link map for ld.so if we can mark _rtld_global as
188 hidden. */
189 #if defined PI_STATIC_AND_HIDDEN && defined HAVE_HIDDEN \
190 && defined HAVE_VISIBILITY_ATTRIBUTE
191 # define DONT_USE_BOOTSTRAP_MAP 1
192 #endif
194 #ifdef DONT_USE_BOOTSTRAP_MAP
195 static ElfW(Addr) _dl_start_final (void *arg);
196 #else
197 struct dl_start_final_info
199 struct link_map l;
200 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
201 hp_timing_t start_time;
202 #endif
204 static ElfW(Addr) _dl_start_final (void *arg,
205 struct dl_start_final_info *info);
206 #endif
208 /* These defined magically in the linker script. */
209 extern char _begin[] attribute_hidden;
210 extern char _etext[] attribute_hidden;
211 extern char _end[] attribute_hidden;
214 #ifdef RTLD_START
215 RTLD_START
216 #else
217 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
218 #endif
220 #ifndef VALIDX
221 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
222 + DT_EXTRANUM + DT_VALTAGIDX (tag))
223 #endif
224 #ifndef ADDRIDX
225 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
226 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
227 #endif
229 /* This is the second half of _dl_start (below). It can be inlined safely
230 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
231 references. When the tools don't permit us to avoid using a GOT entry
232 for _dl_rtld_global (no attribute_hidden support), we must make sure
233 this function is not inlined (see below). */
235 #ifdef DONT_USE_BOOTSTRAP_MAP
236 static inline ElfW(Addr) __attribute__ ((always_inline))
237 _dl_start_final (void *arg)
238 #else
239 static ElfW(Addr) __attribute__ ((noinline))
240 _dl_start_final (void *arg, struct dl_start_final_info *info)
241 #endif
243 ElfW(Addr) start_addr;
245 if (HP_TIMING_AVAIL)
247 /* If it hasn't happen yet record the startup time. */
248 if (! HP_TIMING_INLINE)
249 HP_TIMING_NOW (start_time);
250 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
251 else
252 start_time = info->start_time;
253 #endif
255 /* Initialize the timing functions. */
256 HP_TIMING_DIFF_INIT ();
259 /* Transfer data about ourselves to the permanent link_map structure. */
260 #ifndef DONT_USE_BOOTSTRAP_MAP
261 GL(dl_rtld_map).l_addr = info->l.l_addr;
262 GL(dl_rtld_map).l_ld = info->l.l_ld;
263 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
264 sizeof GL(dl_rtld_map).l_info);
265 GL(dl_rtld_map).l_mach = info->l.l_mach;
266 GL(dl_rtld_map).l_relocated = 1;
267 #endif
268 _dl_setup_hash (&GL(dl_rtld_map));
269 GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
270 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
271 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
272 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
273 /* Copy the TLS related data if necessary. */
274 #if USE_TLS && !defined DONT_USE_BOOTSTRAP_MAP
275 # if USE___THREAD
276 assert (info->l.l_tls_modid != 0);
277 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
278 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
279 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
280 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
281 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
282 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
283 GL(dl_rtld_map).l_tls_modid = 1;
284 # else
285 assert (info->l.l_tls_modid == 0);
286 # if NO_TLS_OFFSET != 0
287 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
288 # endif
289 # endif
291 #endif
293 #if HP_TIMING_AVAIL
294 HP_TIMING_NOW (GL(dl_cpuclock_offset));
295 #endif
297 /* Initialize the stack end variable. */
298 __libc_stack_end = __builtin_frame_address (0);
300 /* Call the OS-dependent function to set up life so we can do things like
301 file access. It will call `dl_main' (below) to do all the real work
302 of the dynamic linker, and then unwind our frame and run the user
303 entry point on the same stack we entered on. */
304 start_addr = _dl_sysdep_start (arg, &dl_main);
306 #ifndef HP_TIMING_NONAVAIL
307 hp_timing_t rtld_total_time;
308 if (HP_TIMING_AVAIL)
310 hp_timing_t end_time;
312 /* Get the current time. */
313 HP_TIMING_NOW (end_time);
315 /* Compute the difference. */
316 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
318 #endif
320 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
322 #ifndef HP_TIMING_NONAVAIL
323 print_statistics (&rtld_total_time);
324 #else
325 print_statistics (NULL);
326 #endif
329 return start_addr;
332 static ElfW(Addr) __attribute_used__ internal_function
333 _dl_start (void *arg)
335 #ifdef DONT_USE_BOOTSTRAP_MAP
336 # define bootstrap_map GL(dl_rtld_map)
337 #else
338 struct dl_start_final_info info;
339 # define bootstrap_map info.l
340 #endif
342 /* This #define produces dynamic linking inline functions for
343 bootstrap relocation instead of general-purpose relocation. */
344 #define RTLD_BOOTSTRAP
345 #define RESOLVE_MAP(sym, version, flags) \
346 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : &bootstrap_map)
347 #include "dynamic-link.h"
349 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
350 #ifdef DONT_USE_BOOTSTRAP_MAP
351 HP_TIMING_NOW (start_time);
352 #else
353 HP_TIMING_NOW (info.start_time);
354 #endif
356 /* Partly clean the `bootstrap_map' structure up. Don't use
357 `memset' since it might not be built in or inlined and we cannot
358 make function calls at this point. Use '__builtin_memset' if we
359 know it is available. We do not have to clear the memory if we
360 do not have to use the temporary bootstrap_map. Global variables
361 are initialized to zero by default. */
362 #ifndef DONT_USE_BOOTSTRAP_MAP
363 # ifdef HAVE_BUILTIN_MEMSET
364 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
365 # else
366 for (size_t cnt = 0;
367 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
368 ++cnt)
369 bootstrap_map.l_info[cnt] = 0;
370 # endif
371 #endif
373 /* Figure out the run-time load address of the dynamic linker itself. */
374 bootstrap_map.l_addr = elf_machine_load_address ();
376 /* Read our own dynamic section and fill in the info array. */
377 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
378 elf_get_dynamic_info (&bootstrap_map, NULL);
380 #if defined USE_TLS && NO_TLS_OFFSET != 0
381 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
382 #endif
384 /* Get the dynamic linker's own program header. First we need the ELF
385 file header. The `_begin' symbol created by the linker script points
386 to it. When we have something like GOTOFF relocs, we can use a plain
387 reference to find the runtime address. Without that, we have to rely
388 on the `l_addr' value, which is not the value we want when prelinked. */
389 #if USE___THREAD
390 dtv_t initdtv[3];
391 ElfW(Ehdr) *ehdr
392 # ifdef DONT_USE_BOOTSTRAP_MAP
393 = (ElfW(Ehdr) *) &_begin;
394 # else
395 # error This will not work with prelink.
396 = (ElfW(Ehdr) *) bootstrap_map.l_addr;
397 # endif
398 ElfW(Phdr) *phdr = (ElfW(Phdr) *) ((void *) ehdr + ehdr->e_phoff);
399 size_t cnt = ehdr->e_phnum; /* PT_TLS is usually the last phdr. */
400 while (cnt-- > 0)
401 if (phdr[cnt].p_type == PT_TLS)
403 void *tlsblock;
404 size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
405 char *p;
407 bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
408 bootstrap_map.l_tls_align = phdr[cnt].p_align;
409 if (phdr[cnt].p_align == 0)
410 bootstrap_map.l_tls_firstbyte_offset = 0;
411 else
412 bootstrap_map.l_tls_firstbyte_offset = (phdr[cnt].p_vaddr
413 & (phdr[cnt].p_align - 1));
414 assert (bootstrap_map.l_tls_blocksize != 0);
415 bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
416 bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
417 + phdr[cnt].p_vaddr);
419 /* We can now allocate the initial TLS block. This can happen
420 on the stack. We'll get the final memory later when we
421 know all about the various objects loaded at startup
422 time. */
423 # if TLS_TCB_AT_TP
424 tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
425 TLS_INIT_TCB_ALIGN)
426 + TLS_INIT_TCB_SIZE
427 + max_align);
428 # elif TLS_DTV_AT_TP
429 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
430 bootstrap_map.l_tls_align)
431 + bootstrap_map.l_tls_blocksize
432 + max_align);
433 # else
434 /* In case a model with a different layout for the TCB and DTV
435 is defined add another #elif here and in the following #ifs. */
436 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
437 # endif
438 /* Align the TLS block. */
439 tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
440 & ~(max_align - 1));
442 /* Initialize the dtv. [0] is the length, [1] the generation
443 counter. */
444 initdtv[0].counter = 1;
445 initdtv[1].counter = 0;
447 /* Initialize the TLS block. */
448 # if TLS_TCB_AT_TP
449 initdtv[2].pointer = tlsblock;
450 # elif TLS_DTV_AT_TP
451 bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
452 bootstrap_map.l_tls_align);
453 initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
454 # else
455 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
456 # endif
457 p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
458 bootstrap_map.l_tls_initimage_size);
459 # ifdef HAVE_BUILTIN_MEMSET
460 __builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
461 - bootstrap_map.l_tls_initimage_size));
462 # else
464 size_t remaining = (bootstrap_map.l_tls_blocksize
465 - bootstrap_map.l_tls_initimage_size);
466 while (remaining-- > 0)
467 *p++ = '\0';
469 # endif
471 /* Install the pointer to the dtv. */
473 /* Initialize the thread pointer. */
474 # if TLS_TCB_AT_TP
475 bootstrap_map.l_tls_offset
476 = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
478 INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
479 initdtv);
481 const char *lossage = TLS_INIT_TP ((char *) tlsblock
482 + bootstrap_map.l_tls_offset, 0);
483 # elif TLS_DTV_AT_TP
484 INSTALL_DTV (tlsblock, initdtv);
485 const char *lossage = TLS_INIT_TP (tlsblock, 0);
486 # else
487 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
488 # endif
489 if (__builtin_expect (lossage != NULL, 0))
490 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
491 lossage);
493 /* So far this is module number one. */
494 bootstrap_map.l_tls_modid = 1;
496 /* There can only be one PT_TLS entry. */
497 break;
499 #endif /* USE___THREAD */
501 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
502 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
503 #endif
505 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
507 /* Relocate ourselves so we can do normal function calls and
508 data access using the global offset table. */
510 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
512 bootstrap_map.l_relocated = 1;
514 /* Please note that we don't allow profiling of this object and
515 therefore need not test whether we have to allocate the array
516 for the relocation results (as done in dl-reloc.c). */
518 /* Now life is sane; we can call functions and access global data.
519 Set up to use the operating system facilities, and find out from
520 the operating system's program loader where to find the program
521 header table in core. Put the rest of _dl_start into a separate
522 function, that way the compiler cannot put accesses to the GOT
523 before ELF_DYNAMIC_RELOCATE. */
525 #ifdef DONT_USE_BOOTSTRAP_MAP
526 ElfW(Addr) entry = _dl_start_final (arg);
527 #else
528 ElfW(Addr) entry = _dl_start_final (arg, &info);
529 #endif
531 #ifndef ELF_MACHINE_START_ADDRESS
532 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
533 #endif
535 return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, entry);
541 /* Now life is peachy; we can do all normal operations.
542 On to the real work. */
544 /* Some helper functions. */
546 /* Arguments to relocate_doit. */
547 struct relocate_args
549 struct link_map *l;
550 int lazy;
553 struct map_args
555 /* Argument to map_doit. */
556 char *str;
557 struct link_map *loader;
558 int is_preloaded;
559 int mode;
560 /* Return value of map_doit. */
561 struct link_map *map;
564 struct dlmopen_args
566 const char *fname;
567 struct link_map *map;
570 struct lookup_args
572 const char *name;
573 struct link_map *map;
574 void *result;
577 /* Arguments to version_check_doit. */
578 struct version_check_args
580 int doexit;
581 int dotrace;
584 static void
585 relocate_doit (void *a)
587 struct relocate_args *args = (struct relocate_args *) a;
589 _dl_relocate_object (args->l, args->l->l_scope, args->lazy, 0);
592 static void
593 map_doit (void *a)
595 struct map_args *args = (struct map_args *) a;
596 args->map = _dl_map_object (args->loader, args->str,
597 args->is_preloaded, lt_library, 0, args->mode,
598 LM_ID_BASE);
601 static void
602 dlmopen_doit (void *a)
604 struct dlmopen_args *args = (struct dlmopen_args *) a;
605 args->map = _dl_open (args->fname, RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT,
606 dl_main, LM_ID_NEWLM, _dl_argc, INTUSE(_dl_argv),
607 __environ);
610 static void
611 lookup_doit (void *a)
613 struct lookup_args *args = (struct lookup_args *) a;
614 const ElfW(Sym) *ref = NULL;
615 args->result = NULL;
616 lookup_t l = _dl_lookup_symbol_x (args->name, args->map, &ref,
617 args->map->l_local_scope, NULL, 0,
618 DL_LOOKUP_RETURN_NEWEST, NULL);
619 if (ref != NULL)
620 args->result = DL_SYMBOL_ADDRESS (l, ref);
623 static void
624 version_check_doit (void *a)
626 struct version_check_args *args = (struct version_check_args *) a;
627 if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
628 args->dotrace) && args->doexit)
629 /* We cannot start the application. Abort now. */
630 _exit (1);
634 static inline struct link_map *
635 find_needed (const char *name)
637 struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
638 unsigned int n = scope->r_nlist;
640 while (n-- > 0)
641 if (_dl_name_match_p (name, scope->r_list[n]))
642 return scope->r_list[n];
644 /* Should never happen. */
645 return NULL;
648 static int
649 match_version (const char *string, struct link_map *map)
651 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
652 ElfW(Verdef) *def;
654 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
655 if (map->l_info[VERDEFTAG] == NULL)
656 /* The file has no symbol versioning. */
657 return 0;
659 def = (ElfW(Verdef) *) ((char *) map->l_addr
660 + map->l_info[VERDEFTAG]->d_un.d_ptr);
661 while (1)
663 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
665 /* Compare the version strings. */
666 if (strcmp (string, strtab + aux->vda_name) == 0)
667 /* Bingo! */
668 return 1;
670 /* If no more definitions we failed to find what we want. */
671 if (def->vd_next == 0)
672 break;
674 /* Next definition. */
675 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
678 return 0;
681 #ifdef USE_TLS
682 static bool tls_init_tp_called;
684 static void *
685 init_tls (void)
687 /* Number of elements in the static TLS block. */
688 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
690 /* Do not do this twice. The audit interface might have required
691 the DTV interfaces to be set up early. */
692 if (GL(dl_initial_dtv) != NULL)
693 return NULL;
695 /* Allocate the array which contains the information about the
696 dtv slots. We allocate a few entries more than needed to
697 avoid the need for reallocation. */
698 size_t nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
700 /* Allocate. */
701 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
702 calloc (sizeof (struct dtv_slotinfo_list)
703 + nelem * sizeof (struct dtv_slotinfo), 1);
704 /* No need to check the return value. If memory allocation failed
705 the program would have been terminated. */
707 struct dtv_slotinfo *slotinfo = GL(dl_tls_dtv_slotinfo_list)->slotinfo;
708 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
709 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
711 /* Fill in the information from the loaded modules. No namespace
712 but the base one can be filled at this time. */
713 assert (GL(dl_ns)[LM_ID_BASE + 1]._ns_loaded == NULL);
714 int i = 0;
715 for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
716 l = l->l_next)
717 if (l->l_tls_blocksize != 0)
719 /* This is a module with TLS data. Store the map reference.
720 The generation counter is zero. */
721 slotinfo[i].map = l;
722 /* slotinfo[i].gen = 0; */
723 ++i;
725 assert (i == GL(dl_tls_max_dtv_idx));
727 /* Compute the TLS offsets for the various blocks. */
728 _dl_determine_tlsoffset ();
730 /* Construct the static TLS block and the dtv for the initial
731 thread. For some platforms this will include allocating memory
732 for the thread descriptor. The memory for the TLS block will
733 never be freed. It should be allocated accordingly. The dtv
734 array can be changed if dynamic loading requires it. */
735 void *tcbp = _dl_allocate_tls_storage ();
736 if (tcbp == NULL)
737 _dl_fatal_printf ("\
738 cannot allocate TLS data structures for initial thread");
740 /* Store for detection of the special case by __tls_get_addr
741 so it knows not to pass this dtv to the normal realloc. */
742 GL(dl_initial_dtv) = GET_DTV (tcbp);
744 /* And finally install it for the main thread. If ld.so itself uses
745 TLS we know the thread pointer was initialized earlier. */
746 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
747 if (__builtin_expect (lossage != NULL, 0))
748 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
749 tls_init_tp_called = true;
751 return tcbp;
753 #endif
755 #ifdef _LIBC_REENTRANT
756 /* _dl_error_catch_tsd points to this for the single-threaded case.
757 It's reset by the thread library for multithreaded programs. */
758 void ** __attribute__ ((const))
759 _dl_initial_error_catch_tsd (void)
761 static void *data;
762 return &data;
764 #endif
767 static unsigned int
768 do_preload (char *fname, struct link_map *main_map, const char *where)
770 const char *objname;
771 const char *err_str = NULL;
772 struct map_args args;
774 args.str = fname;
775 args.loader = main_map;
776 args.is_preloaded = 1;
777 args.mode = 0;
779 unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
781 (void) _dl_catch_error (&objname, &err_str, map_doit, &args);
782 if (__builtin_expect (err_str != NULL, 0))
784 _dl_error_printf ("\
785 ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
786 fname, where);
787 /* No need to call free, this is still before
788 the libc's malloc is used. */
790 else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
791 /* It is no duplicate. */
792 return 1;
794 /* Nothing loaded. */
795 return 0;
798 #if defined SHARED && defined _LIBC_REENTRANT \
799 && defined __rtld_lock_default_lock_recursive
800 static void
801 rtld_lock_default_lock_recursive (void *lock)
803 __rtld_lock_default_lock_recursive (lock);
806 static void
807 rtld_lock_default_unlock_recursive (void *lock)
809 __rtld_lock_default_unlock_recursive (lock);
811 #endif
814 /* The library search path. */
815 static const char *library_path attribute_relro;
816 /* The list preloaded objects. */
817 static const char *preloadlist attribute_relro;
818 /* Nonzero if information about versions has to be printed. */
819 static int version_info attribute_relro;
821 static void
822 dl_main (const ElfW(Phdr) *phdr,
823 ElfW(Word) phnum,
824 ElfW(Addr) *user_entry)
826 const ElfW(Phdr) *ph;
827 enum mode mode;
828 struct link_map *main_map;
829 size_t file_size;
830 char *file;
831 bool has_interp = false;
832 unsigned int i;
833 bool prelinked = false;
834 bool rtld_is_main = false;
835 #ifndef HP_TIMING_NONAVAIL
836 hp_timing_t start;
837 hp_timing_t stop;
838 hp_timing_t diff;
839 #endif
840 #ifdef USE_TLS
841 void *tcbp = NULL;
842 #endif
844 #ifdef _LIBC_REENTRANT
845 /* Explicit initialization since the reloc would just be more work. */
846 GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
847 #endif
849 #ifdef USE_TLS
850 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
851 #endif
853 #if defined SHARED && defined _LIBC_REENTRANT \
854 && defined __rtld_lock_default_lock_recursive
855 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
856 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
857 #endif
859 /* The explicit initialization here is cheaper than processing the reloc
860 in the _rtld_local definition's initializer. */
861 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
863 /* Process the environment variable which control the behaviour. */
864 process_envvars (&mode);
866 #ifndef HAVE_INLINED_SYSCALLS
867 /* Set up a flag which tells we are just starting. */
868 INTUSE(_dl_starting_up) = 1;
869 #endif
871 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
873 /* Ho ho. We are not the program interpreter! We are the program
874 itself! This means someone ran ld.so as a command. Well, that
875 might be convenient to do sometimes. We support it by
876 interpreting the args like this:
878 ld.so PROGRAM ARGS...
880 The first argument is the name of a file containing an ELF
881 executable we will load and run with the following arguments.
882 To simplify life here, PROGRAM is searched for using the
883 normal rules for shared objects, rather than $PATH or anything
884 like that. We just load it and use its entry point; we don't
885 pay attention to its PT_INTERP command (we are the interpreter
886 ourselves). This is an easy way to test a new ld.so before
887 installing it. */
888 rtld_is_main = true;
890 /* Note the place where the dynamic linker actually came from. */
891 GL(dl_rtld_map).l_name = rtld_progname;
893 while (_dl_argc > 1)
894 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
896 mode = list;
897 GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
899 ++_dl_skip_args;
900 --_dl_argc;
901 ++INTUSE(_dl_argv);
903 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
905 mode = verify;
907 ++_dl_skip_args;
908 --_dl_argc;
909 ++INTUSE(_dl_argv);
911 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
912 && _dl_argc > 2)
914 library_path = INTUSE(_dl_argv)[2];
916 _dl_skip_args += 2;
917 _dl_argc -= 2;
918 INTUSE(_dl_argv) += 2;
920 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
921 && _dl_argc > 2)
923 GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
925 _dl_skip_args += 2;
926 _dl_argc -= 2;
927 INTUSE(_dl_argv) += 2;
929 else
930 break;
932 /* If we have no further argument the program was called incorrectly.
933 Grant the user some education. */
934 if (_dl_argc < 2)
935 _dl_fatal_printf ("\
936 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
937 You have invoked `ld.so', the helper program for shared library executables.\n\
938 This program usually lives in the file `/lib/ld.so', and special directives\n\
939 in executable files using ELF shared libraries tell the system's program\n\
940 loader to load the helper program from this file. This helper program loads\n\
941 the shared libraries needed by the program executable, prepares the program\n\
942 to run, and runs it. You may invoke this helper program directly from the\n\
943 command line to load and run an ELF executable file; this is like executing\n\
944 that file itself, but always uses this helper program from the file you\n\
945 specified, instead of the helper program file specified in the executable\n\
946 file you run. This is mostly of use for maintainers to test new versions\n\
947 of this helper program; chances are you did not intend to run this program.\n\
949 --list list all dependencies and how they are resolved\n\
950 --verify verify that given object really is a dynamically linked\n\
951 object we can handle\n\
952 --library-path PATH use given PATH instead of content of the environment\n\
953 variable LD_LIBRARY_PATH\n\
954 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
955 in LIST\n");
957 ++_dl_skip_args;
958 --_dl_argc;
959 ++INTUSE(_dl_argv);
961 /* Initialize the data structures for the search paths for shared
962 objects. */
963 _dl_init_paths (library_path);
966 /* The initialization of _dl_stack_flags done below assumes the
967 executable's PT_GNU_STACK may have been honored by the kernel, and
968 so a PT_GNU_STACK with PF_X set means the stack started out with
969 execute permission. However, this is not really true if the
970 dynamic linker is the executable the kernel loaded. For this
971 case, we must reinitialize _dl_stack_flags to match the dynamic
972 linker itself. If the dynamic linker was built with a
973 PT_GNU_STACK, then the kernel may have loaded us with a
974 nonexecutable stack that we will have to make executable when we
975 load the program below unless it has a PT_GNU_STACK indicating
976 nonexecutable stack is ok. */
978 for (ph = phdr; ph < &phdr[phnum]; ++ph)
979 if (ph->p_type == PT_GNU_STACK)
981 GL(dl_stack_flags) = ph->p_flags;
982 break;
985 if (__builtin_expect (mode, normal) == verify)
987 const char *objname;
988 const char *err_str = NULL;
989 struct map_args args;
991 args.str = rtld_progname;
992 args.loader = NULL;
993 args.is_preloaded = 0;
994 args.mode = __RTLD_OPENEXEC;
995 (void) _dl_catch_error (&objname, &err_str, map_doit, &args);
996 if (__builtin_expect (err_str != NULL, 0))
997 /* We don't free the returned string, the programs stops
998 anyway. */
999 _exit (EXIT_FAILURE);
1001 else
1003 HP_TIMING_NOW (start);
1004 _dl_map_object (NULL, rtld_progname, 0, lt_library, 0,
1005 __RTLD_OPENEXEC, LM_ID_BASE);
1006 HP_TIMING_NOW (stop);
1008 HP_TIMING_DIFF (load_time, start, stop);
1011 /* Now the map for the main executable is available. */
1012 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1014 phdr = main_map->l_phdr;
1015 phnum = main_map->l_phnum;
1016 /* We overwrite here a pointer to a malloc()ed string. But since
1017 the malloc() implementation used at this point is the dummy
1018 implementations which has no real free() function it does not
1019 makes sense to free the old string first. */
1020 main_map->l_name = (char *) "";
1021 *user_entry = main_map->l_entry;
1023 else
1025 /* Create a link_map for the executable itself.
1026 This will be what dlopen on "" returns. */
1027 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1028 __RTLD_OPENEXEC, LM_ID_BASE);
1029 assert (main_map != NULL);
1030 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
1031 main_map->l_phdr = phdr;
1032 main_map->l_phnum = phnum;
1033 main_map->l_entry = *user_entry;
1035 /* At this point we are in a bit of trouble. We would have to
1036 fill in the values for l_dev and l_ino. But in general we
1037 do not know where the file is. We also do not handle AT_EXECFD
1038 even if it would be passed up.
1040 We leave the values here defined to 0. This is normally no
1041 problem as the program code itself is normally no shared
1042 object and therefore cannot be loaded dynamically. Nothing
1043 prevent the use of dynamic binaries and in these situations
1044 we might get problems. We might not be able to find out
1045 whether the object is already loaded. But since there is no
1046 easy way out and because the dynamic binary must also not
1047 have an SONAME we ignore this program for now. If it becomes
1048 a problem we can force people using SONAMEs. */
1050 /* We delay initializing the path structure until we got the dynamic
1051 information for the program. */
1054 main_map->l_map_end = 0;
1055 main_map->l_text_end = 0;
1056 /* Perhaps the executable has no PT_LOAD header entries at all. */
1057 main_map->l_map_start = ~0;
1058 /* And it was opened directly. */
1059 ++main_map->l_direct_opencount;
1061 /* Scan the program header table for the dynamic section. */
1062 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1063 switch (ph->p_type)
1065 case PT_PHDR:
1066 /* Find out the load address. */
1067 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1068 break;
1069 case PT_DYNAMIC:
1070 /* This tells us where to find the dynamic section,
1071 which tells us everything we need to do. */
1072 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
1073 break;
1074 case PT_INTERP:
1075 /* This "interpreter segment" was used by the program loader to
1076 find the program interpreter, which is this program itself, the
1077 dynamic linker. We note what name finds us, so that a future
1078 dlopen call or DT_NEEDED entry, for something that wants to link
1079 against the dynamic linker as a shared library, will know that
1080 the shared object is already loaded. */
1081 _dl_rtld_libname.name = ((const char *) main_map->l_addr
1082 + ph->p_vaddr);
1083 /* _dl_rtld_libname.next = NULL; Already zero. */
1084 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1086 /* Ordinarilly, we would get additional names for the loader from
1087 our DT_SONAME. This can't happen if we were actually linked as
1088 a static executable (detect this case when we have no DYNAMIC).
1089 If so, assume the filename component of the interpreter path to
1090 be our SONAME, and add it to our name list. */
1091 if (GL(dl_rtld_map).l_ld == NULL)
1093 const char *p = NULL;
1094 const char *cp = _dl_rtld_libname.name;
1096 /* Find the filename part of the path. */
1097 while (*cp != '\0')
1098 if (*cp++ == '/')
1099 p = cp;
1101 if (p != NULL)
1103 _dl_rtld_libname2.name = p;
1104 /* _dl_rtld_libname2.next = NULL; Already zero. */
1105 _dl_rtld_libname.next = &_dl_rtld_libname2;
1109 has_interp = true;
1110 break;
1111 case PT_LOAD:
1113 ElfW(Addr) mapstart;
1114 ElfW(Addr) allocend;
1116 /* Remember where the main program starts in memory. */
1117 mapstart = (main_map->l_addr + (ph->p_vaddr & ~(ph->p_align - 1)));
1118 if (main_map->l_map_start > mapstart)
1119 main_map->l_map_start = mapstart;
1121 /* Also where it ends. */
1122 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1123 if (main_map->l_map_end < allocend)
1124 main_map->l_map_end = allocend;
1125 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1126 main_map->l_text_end = allocend;
1128 break;
1130 case PT_TLS:
1131 #ifdef USE_TLS
1132 if (ph->p_memsz > 0)
1134 /* Note that in the case the dynamic linker we duplicate work
1135 here since we read the PT_TLS entry already in
1136 _dl_start_final. But the result is repeatable so do not
1137 check for this special but unimportant case. */
1138 main_map->l_tls_blocksize = ph->p_memsz;
1139 main_map->l_tls_align = ph->p_align;
1140 if (ph->p_align == 0)
1141 main_map->l_tls_firstbyte_offset = 0;
1142 else
1143 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1144 & (ph->p_align - 1));
1145 main_map->l_tls_initimage_size = ph->p_filesz;
1146 main_map->l_tls_initimage = (void *) ph->p_vaddr;
1148 /* This image gets the ID one. */
1149 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1151 #else
1152 _dl_fatal_printf ("\
1153 ld.so does not support TLS, but program uses it!\n");
1154 #endif
1155 break;
1157 case PT_GNU_STACK:
1158 GL(dl_stack_flags) = ph->p_flags;
1159 break;
1161 case PT_GNU_RELRO:
1162 main_map->l_relro_addr = ph->p_vaddr;
1163 main_map->l_relro_size = ph->p_memsz;
1164 break;
1166 #ifdef USE_TLS
1167 /* Adjust the address of the TLS initialization image in case
1168 the executable is actually an ET_DYN object. */
1169 if (main_map->l_tls_initimage != NULL)
1170 main_map->l_tls_initimage
1171 = (char *) main_map->l_tls_initimage + main_map->l_addr;
1172 #endif
1173 if (! main_map->l_map_end)
1174 main_map->l_map_end = ~0;
1175 if (! main_map->l_text_end)
1176 main_map->l_text_end = ~0;
1177 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1179 /* We were invoked directly, so the program might not have a
1180 PT_INTERP. */
1181 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1182 /* _dl_rtld_libname.next = NULL; Already zero. */
1183 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1185 else
1186 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1188 /* If the current libname is different from the SONAME, add the
1189 latter as well. */
1190 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1191 && strcmp (GL(dl_rtld_map).l_libname->name,
1192 (const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1193 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1195 static struct libname_list newname;
1196 newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1197 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1198 newname.next = NULL;
1199 newname.dont_free = 1;
1201 assert (GL(dl_rtld_map).l_libname->next == NULL);
1202 GL(dl_rtld_map).l_libname->next = &newname;
1204 /* The ld.so must be relocated since otherwise loading audit modules
1205 will fail since they reuse the very same ld.so. */
1206 assert (GL(dl_rtld_map).l_relocated);
1208 if (! rtld_is_main)
1210 /* Extract the contents of the dynamic section for easy access. */
1211 elf_get_dynamic_info (main_map, NULL);
1212 /* Set up our cache of pointers into the hash table. */
1213 _dl_setup_hash (main_map);
1216 if (__builtin_expect (mode, normal) == verify)
1218 /* We were called just to verify that this is a dynamic
1219 executable using us as the program interpreter. Exit with an
1220 error if we were not able to load the binary or no interpreter
1221 is specified (i.e., this is no dynamically linked binary. */
1222 if (main_map->l_ld == NULL)
1223 _exit (1);
1225 /* We allow here some platform specific code. */
1226 #ifdef DISTINGUISH_LIB_VERSIONS
1227 DISTINGUISH_LIB_VERSIONS;
1228 #endif
1229 _exit (has_interp ? 0 : 2);
1232 if (! rtld_is_main)
1233 /* Initialize the data structures for the search paths for shared
1234 objects. */
1235 _dl_init_paths (library_path);
1237 /* Initialize _r_debug. */
1238 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1239 LM_ID_BASE);
1240 r->r_state = RT_CONSISTENT;
1242 /* Put the link_map for ourselves on the chain so it can be found by
1243 name. Note that at this point the global chain of link maps contains
1244 exactly one element, which is pointed to by dl_loaded. */
1245 if (! GL(dl_rtld_map).l_name)
1246 /* If not invoked directly, the dynamic linker shared object file was
1247 found by the PT_INTERP name. */
1248 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1249 GL(dl_rtld_map).l_type = lt_library;
1250 main_map->l_next = &GL(dl_rtld_map);
1251 GL(dl_rtld_map).l_prev = main_map;
1252 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1253 ++GL(dl_load_adds);
1255 #if defined(__i386__)
1256 /* Force non-TLS libraries for glibc 2.0 binaries
1257 or if a buggy binary references non-TLS errno or h_errno. */
1258 if (__builtin_expect (main_map->l_info[DT_NUM + DT_THISPROCNUM
1259 + DT_VERSIONTAGIDX (DT_VERNEED)]
1260 == NULL, 0)
1261 && main_map->l_info[DT_DEBUG])
1262 GLRO(dl_osversion) = 0x20205;
1263 else if ((__builtin_expect (mode, normal) != normal
1264 || main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)] == NULL)
1265 /* Only binaries have DT_DEBUG dynamic tags... */
1266 && main_map->l_info[DT_DEBUG])
1268 /* Workaround for buggy binaries. This doesn't handle buggy
1269 libraries. */
1270 bool buggy = false;
1271 const ElfW(Sym) *symtab = (const void *) D_PTR (main_map,
1272 l_info[DT_SYMTAB]);
1273 const char *strtab = (const void *) D_PTR (main_map,
1274 l_info[DT_STRTAB]);
1275 Elf_Symndx symidx;
1276 for (symidx = main_map->l_buckets[0x6c994f % main_map->l_nbuckets];
1277 symidx != STN_UNDEF;
1278 symidx = main_map->l_chain[symidx])
1280 if (__builtin_expect (strcmp (strtab + symtab[symidx].st_name,
1281 "errno") == 0, 0)
1282 && ELFW(ST_TYPE) (symtab[symidx].st_info) != STT_TLS)
1283 buggy = true;
1285 for (symidx = main_map->l_buckets[0xe5c992f % main_map->l_nbuckets];
1286 symidx != STN_UNDEF;
1287 symidx = main_map->l_chain[symidx])
1289 if (__builtin_expect (strcmp (strtab + symtab[symidx].st_name,
1290 "h_errno") == 0, 0)
1291 && ELFW(ST_TYPE) (symtab[symidx].st_info) != STT_TLS)
1292 buggy = true;
1294 if (__builtin_expect (buggy, false) && GLRO(dl_osversion) > 0x20401)
1296 GLRO(dl_osversion) = 0x20401;
1297 _dl_error_printf ("Incorrectly built binary which accesses errno or h_errno directly. Needs to be fixed.\n");
1300 #endif
1302 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1303 to not using bias for non-prelinked PIEs and libraries
1304 and using it for executables or prelinked PIEs or libraries. */
1305 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1306 GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
1308 /* Set up the program header information for the dynamic linker
1309 itself. It is needed in the dl_iterate_phdr() callbacks. */
1310 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1311 ElfW(Phdr) *rtld_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1312 + rtld_ehdr->e_phoff);
1313 GL(dl_rtld_map).l_phdr = rtld_phdr;
1314 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1317 /* PT_GNU_RELRO is usually the last phdr. */
1318 size_t cnt = rtld_ehdr->e_phnum;
1319 while (cnt-- > 0)
1320 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1322 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1323 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1324 break;
1327 #ifdef USE_TLS
1328 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1329 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1330 /* Assign a module ID. Do this before loading any audit modules. */
1331 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1332 #endif
1334 /* If we have auditing DSOs to load, do it now. */
1335 if (__builtin_expect (audit_list != NULL, 0))
1337 /* Iterate over all entries in the list. The order is important. */
1338 struct audit_ifaces *last_audit = NULL;
1339 struct audit_list *al = audit_list->next;
1342 #ifdef USE_TLS
1343 int tls_idx = GL(dl_tls_max_dtv_idx);
1345 /* Now it is time to determine the layout of the static TLS
1346 block and allocate it for the initial thread. Note that we
1347 always allocate the static block, we never defer it even if
1348 no DF_STATIC_TLS bit is set. The reason is that we know
1349 glibc will use the static model. */
1350 # ifndef TLS_INIT_TP_EXPENSIVE
1351 # define TLS_INIT_TP_EXPENSIVE 0
1352 # endif
1354 /* Since we start using the auditing DSOs right away we need to
1355 initialize the data structures now. */
1356 tcbp = init_tls ();
1357 #endif
1358 struct dlmopen_args dlmargs;
1359 dlmargs.fname = al->name;
1360 dlmargs.map = NULL;
1362 const char *objname;
1363 const char *err_str = NULL;
1364 (void) _dl_catch_error (&objname, &err_str, dlmopen_doit, &dlmargs);
1365 if (__builtin_expect (err_str != NULL, 0))
1367 not_loaded:
1368 _dl_error_printf ("\
1369 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
1370 al->name, err_str);
1371 free ((char *) err_str);
1373 else
1375 struct lookup_args largs;
1376 largs.name = "la_version";
1377 largs.map = dlmargs.map;
1379 /* Check whether the interface version matches. */
1380 (void) _dl_catch_error (&objname, &err_str, lookup_doit, &largs);
1382 unsigned int (*laversion) (unsigned int);
1383 unsigned int lav;
1384 if (err_str == NULL
1385 && (laversion = largs.result) != NULL
1386 && (lav = laversion (LAV_CURRENT)) > 0
1387 && lav <= LAV_CURRENT)
1389 /* Allocate structure for the callback function pointers.
1390 This call can never fail. */
1391 union
1393 struct audit_ifaces ifaces;
1394 #define naudit_ifaces 8
1395 void (*fptr[naudit_ifaces]) (void);
1396 } *newp = malloc (sizeof (*newp));
1398 /* Names of the auditing interfaces. All in one
1399 long string. */
1400 static const char audit_iface_names[] =
1401 "la_activity\0"
1402 "la_objsearch\0"
1403 "la_objopen\0"
1404 "la_preinit\0"
1405 #if __ELF_NATIVE_CLASS == 32
1406 "la_symbind32\0"
1407 #elif __ELF_NATIVE_CLASS == 64
1408 "la_symbind64\0"
1409 #else
1410 # error "__ELF_NATIVE_CLASS must be defined"
1411 #endif
1412 #define STRING(s) __STRING (s)
1413 "la_" STRING (ARCH_LA_PLTENTER) "\0"
1414 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
1415 "la_objclose\0";
1416 unsigned int cnt = 0;
1417 const char *cp = audit_iface_names;
1420 largs.name = cp;
1421 (void) _dl_catch_error (&objname, &err_str, lookup_doit,
1422 &largs);
1424 /* Store the pointer. */
1425 if (err_str == NULL && largs.result != NULL)
1427 newp->fptr[cnt] = largs.result;
1429 /* The dynamic linker link map is statically
1430 allocated, initialize the data now. */
1431 GL(dl_rtld_map).l_audit[cnt].cookie
1432 = (intptr_t) &GL(dl_rtld_map);
1434 else
1435 newp->fptr[cnt] = NULL;
1436 ++cnt;
1438 cp = (char *) rawmemchr (cp, '\0') + 1;
1440 while (*cp != '\0');
1441 assert (cnt == naudit_ifaces);
1443 /* Now append the new auditing interface to the list. */
1444 newp->ifaces.next = NULL;
1445 if (last_audit == NULL)
1446 last_audit = GLRO(dl_audit) = &newp->ifaces;
1447 else
1448 last_audit = last_audit->next = &newp->ifaces;
1449 ++GLRO(dl_naudit);
1451 /* Mark the DSO as being used for auditing. */
1452 dlmargs.map->l_auditing = 1;
1454 else
1456 /* We cannot use the DSO, it does not have the
1457 appropriate interfaces or it expects something
1458 more recent. */
1459 #ifndef NDEBUG
1460 Lmid_t ns = dlmargs.map->l_ns;
1461 #endif
1462 _dl_close (dlmargs.map);
1464 /* Make sure the namespace has been cleared entirely. */
1465 assert (GL(dl_ns)[ns]._ns_loaded == NULL);
1466 assert (GL(dl_ns)[ns]._ns_nloaded == 0);
1468 #ifdef USE_TLS
1469 GL(dl_tls_max_dtv_idx) = tls_idx;
1470 #endif
1471 goto not_loaded;
1475 al = al->next;
1477 while (al != audit_list->next);
1479 /* If we have any auditing modules, announce that we already
1480 have two objects loaded. */
1481 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1483 struct link_map *ls[2] = { main_map, &GL(dl_rtld_map) };
1485 for (unsigned int outer = 0; outer < 2; ++outer)
1487 struct audit_ifaces *afct = GLRO(dl_audit);
1488 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1490 if (afct->objopen != NULL)
1492 ls[outer]->l_audit[cnt].bindflags
1493 = afct->objopen (ls[outer], LM_ID_BASE,
1494 &ls[outer]->l_audit[cnt].cookie);
1496 ls[outer]->l_audit_any_plt
1497 |= ls[outer]->l_audit[cnt].bindflags != 0;
1500 afct = afct->next;
1506 /* We start adding objects. */
1507 r->r_state = RT_ADD;
1508 _dl_debug_state ();
1510 /* Auditing checkpoint: we are ready to signal that the initial map
1511 is being constructed. */
1512 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1514 struct audit_ifaces *afct = GLRO(dl_audit);
1515 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1517 if (afct->activity != NULL)
1518 afct->activity (&main_map->l_audit[cnt].cookie, LA_ACT_ADD);
1520 afct = afct->next;
1524 /* We have two ways to specify objects to preload: via environment
1525 variable and via the file /etc/ld.so.preload. The latter can also
1526 be used when security is enabled. */
1527 assert (GL(dl_rtld_map).l_next == NULL);
1528 struct link_map **preloads = NULL;
1529 unsigned int npreloads = 0;
1531 if (__builtin_expect (preloadlist != NULL, 0))
1533 /* The LD_PRELOAD environment variable gives list of libraries
1534 separated by white space or colons that are loaded before the
1535 executable's dependencies and prepended to the global scope
1536 list. If the binary is running setuid all elements
1537 containing a '/' are ignored since it is insecure. */
1538 char *list = strdupa (preloadlist);
1539 char *p;
1541 HP_TIMING_NOW (start);
1543 /* Prevent optimizing strsep. Speed is not important here. */
1544 while ((p = (strsep) (&list, " :")) != NULL)
1545 if (p[0] != '\0'
1546 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1547 || strchr (p, '/') == NULL))
1548 npreloads += do_preload (p, main_map, "LD_PRELOAD");
1550 HP_TIMING_NOW (stop);
1551 HP_TIMING_DIFF (diff, start, stop);
1552 HP_TIMING_ACCUM_NT (load_time, diff);
1555 /* There usually is no ld.so.preload file, it should only be used
1556 for emergencies and testing. So the open call etc should usually
1557 fail. Using access() on a non-existing file is faster than using
1558 open(). So we do this first. If it succeeds we do almost twice
1559 the work but this does not matter, since it is not for production
1560 use. */
1561 static const char preload_file[] = "/etc/ld.so.preload";
1562 if (__builtin_expect (__access (preload_file, R_OK) == 0, 0))
1564 /* Read the contents of the file. */
1565 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1566 PROT_READ | PROT_WRITE);
1567 if (__builtin_expect (file != MAP_FAILED, 0))
1569 /* Parse the file. It contains names of libraries to be loaded,
1570 separated by white spaces or `:'. It may also contain
1571 comments introduced by `#'. */
1572 char *problem;
1573 char *runp;
1574 size_t rest;
1576 /* Eliminate comments. */
1577 runp = file;
1578 rest = file_size;
1579 while (rest > 0)
1581 char *comment = memchr (runp, '#', rest);
1582 if (comment == NULL)
1583 break;
1585 rest -= comment - runp;
1587 *comment = ' ';
1588 while (--rest > 0 && *++comment != '\n');
1591 /* We have one problematic case: if we have a name at the end of
1592 the file without a trailing terminating characters, we cannot
1593 place the \0. Handle the case separately. */
1594 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1595 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1597 problem = &file[file_size];
1598 while (problem > file && problem[-1] != ' '
1599 && problem[-1] != '\t'
1600 && problem[-1] != '\n' && problem[-1] != ':')
1601 --problem;
1603 if (problem > file)
1604 problem[-1] = '\0';
1606 else
1608 problem = NULL;
1609 file[file_size - 1] = '\0';
1612 HP_TIMING_NOW (start);
1614 if (file != problem)
1616 char *p;
1617 runp = file;
1618 while ((p = strsep (&runp, ": \t\n")) != NULL)
1619 if (p[0] != '\0')
1620 npreloads += do_preload (p, main_map, preload_file);
1623 if (problem != NULL)
1625 char *p = strndupa (problem, file_size - (problem - file));
1627 npreloads += do_preload (p, main_map, preload_file);
1630 HP_TIMING_NOW (stop);
1631 HP_TIMING_DIFF (diff, start, stop);
1632 HP_TIMING_ACCUM_NT (load_time, diff);
1634 /* We don't need the file anymore. */
1635 __munmap (file, file_size);
1639 #if defined(__i386__) || defined(__alpha__) || (defined(__sparc__) && !defined(__arch64__))
1641 * Modifications by Red Hat Software
1643 * Deal with the broken binaries from the non-versioned ages of glibc.
1644 * If a binary does not have version information enabled, we assume that
1645 * it is a glibc 2.0 binary and we load a compatibility library to try to
1646 * overcome binary incompatibilities.
1647 * Blame: gafton@redhat.com
1649 #define LIB_NOVERSION "/lib/libNoVersion.so.1"
1651 if (__builtin_expect (main_map->l_info[DT_NUM + DT_THISPROCNUM
1652 + DT_VERSIONTAGIDX (DT_VERNEED)]
1653 == NULL, 0)
1654 && (main_map->l_info[DT_DEBUG]
1655 || !(GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)))
1657 struct stat test_st;
1658 int test_fd;
1659 int can_load;
1661 HP_TIMING_NOW (start);
1663 /* _dl_sysdep_message("Loading compatibility library... ", NULL); */
1665 can_load = 1;
1666 test_fd = __open (LIB_NOVERSION, O_RDONLY);
1667 if (test_fd < 0) {
1668 can_load = 0;
1669 /* _dl_sysdep_message(" Can't find " LIB_NOVERSION "\n", NULL); */
1670 } else {
1671 if (__fxstat (_STAT_VER, test_fd, &test_st) < 0 || test_st.st_size == 0) {
1672 can_load = 0;
1673 /* _dl_sysdep_message(" Can't stat " LIB_NOVERSION "\n", NULL); */
1677 if (test_fd >= 0) /* open did no fail.. */
1678 __close(test_fd); /* avoid fd leaks */
1680 if (can_load != 0)
1681 npreloads += do_preload (LIB_NOVERSION, main_map,
1682 "nonversioned binary");
1684 HP_TIMING_NOW (stop);
1685 HP_TIMING_DIFF (diff, start, stop);
1686 HP_TIMING_ACCUM_NT (load_time, diff);
1688 #endif
1690 if (__builtin_expect (GL(dl_rtld_map).l_next != NULL, 0))
1692 /* Set up PRELOADS with a vector of the preloaded libraries. */
1693 struct link_map *l;
1694 preloads = __alloca (npreloads * sizeof preloads[0]);
1695 l = GL(dl_rtld_map).l_next; /* End of the chain before preloads. */
1696 i = 0;
1699 preloads[i++] = l;
1700 l = l->l_next;
1701 } while (l);
1702 assert (i == npreloads);
1705 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1706 struct link_map *sysinfo_map = NULL;
1707 if (GLRO(dl_sysinfo_dso) != NULL)
1709 /* Do an abridged version of the work _dl_map_object_from_fd would do
1710 to map in the object. It's already mapped and prelinked (and
1711 better be, since it's read-only and so we couldn't relocate it).
1712 We just want our data structures to describe it as if we had just
1713 mapped and relocated it normally. */
1714 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL,
1715 0, LM_ID_BASE);
1716 if (__builtin_expect (l != NULL, 1))
1718 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
1720 l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1721 + GLRO(dl_sysinfo_dso)->e_phoff);
1722 l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1723 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1725 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1726 if (ph->p_type == PT_DYNAMIC)
1728 l->l_ld = (void *) ph->p_vaddr;
1729 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1731 else if (ph->p_type == PT_LOAD)
1733 if (! l->l_addr)
1734 l->l_addr = ph->p_vaddr;
1735 if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1736 l->l_map_end = ph->p_vaddr + ph->p_memsz;
1737 if ((ph->p_flags & PF_X)
1738 && ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1739 l->l_text_end = ph->p_vaddr + ph->p_memsz;
1741 else
1742 /* There must be no TLS segment. */
1743 assert (ph->p_type != PT_TLS);
1745 l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1746 l->l_addr = l->l_map_start - l->l_addr;
1747 l->l_map_end += l->l_addr;
1748 l->l_text_end += l->l_addr;
1749 l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1750 elf_get_dynamic_info (l, dyn_temp);
1751 _dl_setup_hash (l);
1752 l->l_relocated = 1;
1754 /* Now that we have the info handy, use the DSO image's soname
1755 so this object can be looked up by name. Note that we do not
1756 set l_name here. That field gives the file name of the DSO,
1757 and this DSO is not associated with any file. */
1758 if (l->l_info[DT_SONAME] != NULL)
1760 /* Work around a kernel problem. The kernel cannot handle
1761 addresses in the vsyscall DSO pages in writev() calls. */
1762 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1763 + l->l_info[DT_SONAME]->d_un.d_val);
1764 size_t len = strlen (dsoname);
1765 char *copy = malloc (len);
1766 if (copy == NULL)
1767 _dl_fatal_printf ("out of memory\n");
1768 l->l_libname->name = memcpy (copy, dsoname, len);
1771 /* We have a prelinked DSO preloaded by the system. */
1772 sysinfo_map = l;
1773 # ifdef NEED_DL_SYSINFO
1774 if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1775 GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1776 # endif
1779 #endif
1781 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1782 specified some libraries to load, these are inserted before the actual
1783 dependencies in the executable's searchlist for symbol resolution. */
1784 HP_TIMING_NOW (start);
1785 _dl_map_object_deps (main_map, preloads, npreloads, mode == trace, 0);
1786 HP_TIMING_NOW (stop);
1787 HP_TIMING_DIFF (diff, start, stop);
1788 HP_TIMING_ACCUM_NT (load_time, diff);
1790 /* Mark all objects as being in the global scope. */
1791 for (i = main_map->l_searchlist.r_nlist; i > 0; )
1792 main_map->l_searchlist.r_list[--i]->l_global = 1;
1794 #ifndef MAP_ANON
1795 /* We are done mapping things, so close the zero-fill descriptor. */
1796 __close (_dl_zerofd);
1797 _dl_zerofd = -1;
1798 #endif
1800 /* Remove _dl_rtld_map from the chain. */
1801 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1802 if (GL(dl_rtld_map).l_next != NULL)
1803 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1805 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1806 if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1807 break;
1809 bool rtld_multiple_ref = false;
1810 if (__builtin_expect (i < main_map->l_searchlist.r_nlist, 1))
1812 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1813 put it back in the list of visible objects. We insert it into the
1814 chain in symbol search order because gdb uses the chain's order as
1815 its symbol search order. */
1816 rtld_multiple_ref = true;
1818 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1819 if (__builtin_expect (mode, normal) == normal)
1821 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1822 ? main_map->l_searchlist.r_list[i + 1]
1823 : NULL);
1824 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1825 if (sysinfo_map != NULL
1826 && GL(dl_rtld_map).l_prev->l_next == sysinfo_map
1827 && GL(dl_rtld_map).l_next != sysinfo_map)
1828 GL(dl_rtld_map).l_prev = sysinfo_map;
1829 #endif
1831 else
1832 /* In trace mode there might be an invisible object (which we
1833 could not find) after the previous one in the search list.
1834 In this case it doesn't matter much where we put the
1835 interpreter object, so we just initialize the list pointer so
1836 that the assertion below holds. */
1837 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1839 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1840 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1841 if (GL(dl_rtld_map).l_next != NULL)
1843 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1844 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1848 /* Now let us see whether all libraries are available in the
1849 versions we need. */
1851 struct version_check_args args;
1852 args.doexit = mode == normal;
1853 args.dotrace = mode == trace;
1854 _dl_receive_error (print_missing_version, version_check_doit, &args);
1857 #ifdef USE_TLS
1858 /* We do not initialize any of the TLS functionality unless any of the
1859 initial modules uses TLS. This makes dynamic loading of modules with
1860 TLS impossible, but to support it requires either eagerly doing setup
1861 now or lazily doing it later. Doing it now makes us incompatible with
1862 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1863 used. Trying to do it lazily is too hairy to try when there could be
1864 multiple threads (from a non-TLS-using libpthread). */
1865 bool was_tls_init_tp_called = tls_init_tp_called;
1866 if (tcbp == NULL && (!TLS_INIT_TP_EXPENSIVE || GL(dl_tls_max_dtv_idx) > 0))
1867 tcbp = init_tls ();
1868 #endif
1870 if (__builtin_expect (mode, normal) != normal)
1872 /* We were run just to list the shared libraries. It is
1873 important that we do this before real relocation, because the
1874 functions we call below for output may no longer work properly
1875 after relocation. */
1876 struct link_map *l;
1878 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1880 struct r_scope_elem *scope = &main_map->l_searchlist;
1882 for (i = 0; i < scope->r_nlist; i++)
1884 l = scope->r_list [i];
1885 if (l->l_faked)
1887 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1888 continue;
1890 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1891 GLRO(dl_trace_prelink_map) = l;
1892 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1893 l->l_libname->name[0] ? l->l_libname->name
1894 : rtld_progname ?: "<main program>",
1895 l->l_name[0] ? l->l_name
1896 : rtld_progname ?: "<main program>",
1897 (int) sizeof l->l_map_start * 2,
1898 (size_t) l->l_map_start,
1899 (int) sizeof l->l_addr * 2,
1900 (size_t) l->l_addr);
1901 #ifdef USE_TLS
1902 if (l->l_tls_modid)
1903 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1904 (int) sizeof l->l_tls_offset * 2,
1905 (size_t) l->l_tls_offset);
1906 else
1907 #endif
1908 _dl_printf ("\n");
1911 else if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
1913 /* Look through the dependencies of the main executable
1914 and determine which of them is not actually
1915 required. */
1916 struct link_map *l = main_map;
1918 /* Relocate the main executable. */
1919 struct relocate_args args = { .l = l, .lazy = GLRO(dl_lazy) };
1920 _dl_receive_error (print_unresolved, relocate_doit, &args);
1922 /* This loop depends on the dependencies of the executable to
1923 correspond in number and order to the DT_NEEDED entries. */
1924 ElfW(Dyn) *dyn = main_map->l_ld;
1925 bool first = true;
1926 while (dyn->d_tag != DT_NULL)
1928 if (dyn->d_tag == DT_NEEDED)
1930 l = l->l_next;
1932 if (!l->l_used)
1934 if (first)
1936 _dl_printf ("Unused direct dependencies:\n");
1937 first = false;
1940 _dl_printf ("\t%s\n", l->l_name);
1944 ++dyn;
1947 _exit (first != true);
1949 else if (! main_map->l_info[DT_NEEDED])
1950 _dl_printf ("\tstatically linked\n");
1951 else
1953 for (l = main_map->l_next; l; l = l->l_next)
1954 if (l->l_faked)
1955 /* The library was not found. */
1956 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1957 else if (strcmp (l->l_libname->name, l->l_name) == 0)
1958 _dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
1959 (int) sizeof l->l_map_start * 2,
1960 (size_t) l->l_map_start);
1961 else
1962 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1963 l->l_name, (int) sizeof l->l_map_start * 2,
1964 (size_t) l->l_map_start);
1967 if (__builtin_expect (mode, trace) != trace)
1968 for (i = 1; i < (unsigned int) _dl_argc; ++i)
1970 const ElfW(Sym) *ref = NULL;
1971 ElfW(Addr) loadbase;
1972 lookup_t result;
1974 result = _dl_lookup_symbol_x (INTUSE(_dl_argv)[i], main_map,
1975 &ref, main_map->l_scope, NULL,
1976 ELF_RTYPE_CLASS_PLT,
1977 DL_LOOKUP_ADD_DEPENDENCY, NULL);
1979 loadbase = LOOKUP_VALUE_ADDRESS (result);
1981 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
1982 INTUSE(_dl_argv)[i],
1983 (int) sizeof ref->st_value * 2,
1984 (size_t) ref->st_value,
1985 (int) sizeof loadbase * 2, (size_t) loadbase);
1987 else
1989 /* If LD_WARN is set, warn about undefined symbols. */
1990 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
1992 /* We have to do symbol dependency testing. */
1993 struct relocate_args args;
1994 struct link_map *l;
1996 args.lazy = GLRO(dl_lazy);
1998 l = main_map;
1999 while (l->l_next != NULL)
2000 l = l->l_next;
2003 if (l != &GL(dl_rtld_map) && ! l->l_faked)
2005 args.l = l;
2006 _dl_receive_error (print_unresolved, relocate_doit,
2007 &args);
2009 l = l->l_prev;
2011 while (l != NULL);
2013 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
2014 && rtld_multiple_ref)
2016 /* Mark the link map as not yet relocated again. */
2017 GL(dl_rtld_map).l_relocated = 0;
2018 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope,
2019 0, 0);
2022 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
2023 if (version_info)
2025 /* Print more information. This means here, print information
2026 about the versions needed. */
2027 int first = 1;
2028 struct link_map *map;
2030 for (map = main_map; map != NULL; map = map->l_next)
2032 const char *strtab;
2033 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
2034 ElfW(Verneed) *ent;
2036 if (dyn == NULL)
2037 continue;
2039 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
2040 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
2042 if (first)
2044 _dl_printf ("\n\tVersion information:\n");
2045 first = 0;
2048 _dl_printf ("\t%s:\n",
2049 map->l_name[0] ? map->l_name : rtld_progname);
2051 while (1)
2053 ElfW(Vernaux) *aux;
2054 struct link_map *needed;
2056 needed = find_needed (strtab + ent->vn_file);
2057 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
2059 while (1)
2061 const char *fname = NULL;
2063 if (needed != NULL
2064 && match_version (strtab + aux->vna_name,
2065 needed))
2066 fname = needed->l_name;
2068 _dl_printf ("\t\t%s (%s) %s=> %s\n",
2069 strtab + ent->vn_file,
2070 strtab + aux->vna_name,
2071 aux->vna_flags & VER_FLG_WEAK
2072 ? "[WEAK] " : "",
2073 fname ?: "not found");
2075 if (aux->vna_next == 0)
2076 /* No more symbols. */
2077 break;
2079 /* Next symbol. */
2080 aux = (ElfW(Vernaux) *) ((char *) aux
2081 + aux->vna_next);
2084 if (ent->vn_next == 0)
2085 /* No more dependencies. */
2086 break;
2088 /* Next dependency. */
2089 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
2095 _exit (0);
2098 if (main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]
2099 && ! __builtin_expect (GLRO(dl_profile) != NULL, 0))
2101 ElfW(Lib) *liblist, *liblistend;
2102 struct link_map **r_list, **r_listend, *l;
2103 const char *strtab = (const void *) D_PTR (main_map, l_info[DT_STRTAB]);
2105 assert (main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
2106 liblist = (ElfW(Lib) *)
2107 main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
2108 liblistend = (ElfW(Lib) *)
2109 ((char *) liblist +
2110 main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
2111 r_list = main_map->l_searchlist.r_list;
2112 r_listend = r_list + main_map->l_searchlist.r_nlist;
2114 for (; r_list < r_listend && liblist < liblistend; r_list++)
2116 l = *r_list;
2118 if (l == main_map)
2119 continue;
2121 /* If the library is not mapped where it should, fail. */
2122 if (l->l_addr)
2123 break;
2125 /* Next, check if checksum matches. */
2126 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
2127 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
2128 != liblist->l_checksum)
2129 break;
2131 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
2132 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
2133 != liblist->l_time_stamp)
2134 break;
2136 if (! _dl_name_match_p (strtab + liblist->l_name, l))
2137 break;
2139 ++liblist;
2143 if (r_list == r_listend && liblist == liblistend)
2144 prelinked = true;
2146 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
2147 _dl_debug_printf ("\nprelink checking: %s\n",
2148 prelinked ? "ok" : "failed");
2153 struct link_map *l = main_map;
2155 #ifdef ELF_MACHINE_DEBUG_SETUP
2157 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
2159 ELF_MACHINE_DEBUG_SETUP (l, r);
2160 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
2162 #else
2164 if (l->l_info[DT_DEBUG] != NULL)
2165 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
2166 with the run-time address of the r_debug structure */
2167 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
2169 /* Fill in the pointer in the dynamic linker's own dynamic section, in
2170 case you run gdb on the dynamic linker directly. */
2171 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
2172 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
2173 #endif
2176 /* Now set up the variable which helps the assembler startup code. */
2177 GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
2178 GL(dl_ns)[LM_ID_BASE]._ns_global_scope[0] = &main_map->l_searchlist;
2180 /* Save the information about the original global scope list since
2181 we need it in the memory handling later. */
2182 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
2184 if (prelinked)
2186 if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
2188 ElfW(Rela) *conflict, *conflictend;
2189 #ifndef HP_TIMING_NONAVAIL
2190 hp_timing_t start;
2191 hp_timing_t stop;
2192 #endif
2194 HP_TIMING_NOW (start);
2195 assert (main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
2196 conflict = (ElfW(Rela) *)
2197 main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
2198 conflictend = (ElfW(Rela) *)
2199 ((char *) conflict
2200 + main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
2201 _dl_resolve_conflicts (main_map, conflict, conflictend);
2202 HP_TIMING_NOW (stop);
2203 HP_TIMING_DIFF (relocate_time, start, stop);
2207 /* Mark all the objects so we know they have been already relocated. */
2208 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2210 l->l_relocated = 1;
2211 if (l->l_relro_size)
2212 _dl_protect_relro (l);
2214 #ifdef USE_TLS
2215 /* Add object to slot information data if necessasy. */
2216 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2217 _dl_add_to_slotinfo (l);
2218 #endif
2221 _dl_sysdep_start_cleanup ();
2223 else
2225 /* Now we have all the objects loaded. Relocate them all except for
2226 the dynamic linker itself. We do this in reverse order so that copy
2227 relocs of earlier objects overwrite the data written by later
2228 objects. We do not re-relocate the dynamic linker itself in this
2229 loop because that could result in the GOT entries for functions we
2230 call being changed, and that would break us. It is safe to relocate
2231 the dynamic linker out of order because it has no copy relocs (we
2232 know that because it is self-contained). */
2234 int consider_profiling = GLRO(dl_profile) != NULL;
2235 #ifndef HP_TIMING_NONAVAIL
2236 hp_timing_t start;
2237 hp_timing_t stop;
2238 hp_timing_t add;
2239 #endif
2241 /* If we are profiling we also must do lazy reloaction. */
2242 GLRO(dl_lazy) |= consider_profiling;
2244 struct link_map *l = main_map;
2245 while (l->l_next)
2246 l = l->l_next;
2248 HP_TIMING_NOW (start);
2251 /* While we are at it, help the memory handling a bit. We have to
2252 mark some data structures as allocated with the fake malloc()
2253 implementation in ld.so. */
2254 struct libname_list *lnp = l->l_libname->next;
2256 while (__builtin_expect (lnp != NULL, 0))
2258 lnp->dont_free = 1;
2259 lnp = lnp->next;
2262 if (l != &GL(dl_rtld_map))
2263 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy),
2264 consider_profiling);
2266 #ifdef USE_TLS
2267 /* Add object to slot information data if necessasy. */
2268 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2269 _dl_add_to_slotinfo (l);
2270 #endif
2272 l = l->l_prev;
2274 while (l);
2275 HP_TIMING_NOW (stop);
2277 HP_TIMING_DIFF (relocate_time, start, stop);
2279 /* Do any necessary cleanups for the startup OS interface code.
2280 We do these now so that no calls are made after rtld re-relocation
2281 which might be resolved to different functions than we expect.
2282 We cannot do this before relocating the other objects because
2283 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2284 _dl_sysdep_start_cleanup ();
2286 /* Now enable profiling if needed. Like the previous call,
2287 this has to go here because the calls it makes should use the
2288 rtld versions of the functions (particularly calloc()), but it
2289 needs to have _dl_profile_map set up by the relocator. */
2290 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
2291 /* We must prepare the profiling. */
2292 _dl_start_profile ();
2294 if (rtld_multiple_ref)
2296 /* There was an explicit ref to the dynamic linker as a shared lib.
2297 Re-relocate ourselves with user-controlled symbol definitions. */
2298 HP_TIMING_NOW (start);
2299 /* Mark the link map as not yet relocated again. */
2300 GL(dl_rtld_map).l_relocated = 0;
2301 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2302 HP_TIMING_NOW (stop);
2303 HP_TIMING_DIFF (add, start, stop);
2304 HP_TIMING_ACCUM_NT (relocate_time, add);
2308 #ifndef NONTLS_INIT_TP
2309 # define NONTLS_INIT_TP do { } while (0)
2310 #endif
2312 #ifdef USE_TLS
2313 if (GL(dl_tls_max_dtv_idx) > 0 || USE___THREAD || !TLS_INIT_TP_EXPENSIVE)
2315 if (!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2316 ++GL(dl_tls_generation);
2318 /* Now that we have completed relocation, the initializer data
2319 for the TLS blocks has its final values and we can copy them
2320 into the main thread's TLS area, which we allocated above. */
2321 _dl_allocate_tls_init (tcbp);
2323 /* And finally install it for the main thread. If ld.so itself uses
2324 TLS we know the thread pointer was initialized earlier. */
2325 if (! tls_init_tp_called)
2327 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
2328 if (__builtin_expect (lossage != NULL, 0))
2329 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2330 lossage);
2333 else
2334 #endif
2335 NONTLS_INIT_TP;
2337 #ifdef SHARED
2338 /* Auditing checkpoint: we have added all objects. */
2339 if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
2341 struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2342 /* Do not call the functions for any auditing object. */
2343 if (head->l_auditing == 0)
2345 struct audit_ifaces *afct = GLRO(dl_audit);
2346 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2348 if (afct->activity != NULL)
2349 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
2351 afct = afct->next;
2355 #endif
2357 /* Notify the debugger all new objects are now ready to go. We must re-get
2358 the address since by now the variable might be in another object. */
2359 r = _dl_debug_initialize (0, LM_ID_BASE);
2360 r->r_state = RT_CONSISTENT;
2361 _dl_debug_state ();
2363 #ifndef MAP_COPY
2364 /* We must munmap() the cache file. */
2365 _dl_unload_cache ();
2366 #endif
2368 /* Once we return, _dl_sysdep_start will invoke
2369 the DT_INIT functions and then *USER_ENTRY. */
2372 /* This is a little helper function for resolving symbols while
2373 tracing the binary. */
2374 static void
2375 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2376 const char *errstring)
2378 if (objname[0] == '\0')
2379 objname = rtld_progname ?: "<main program>";
2380 _dl_error_printf ("%s (%s)\n", errstring, objname);
2383 /* This is a little helper function for resolving symbols while
2384 tracing the binary. */
2385 static void
2386 print_missing_version (int errcode __attribute__ ((unused)),
2387 const char *objname, const char *errstring)
2389 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
2390 objname, errstring);
2393 /* Nonzero if any of the debugging options is enabled. */
2394 static int any_debug attribute_relro;
2396 /* Process the string given as the parameter which explains which debugging
2397 options are enabled. */
2398 static void
2399 process_dl_debug (const char *dl_debug)
2401 /* When adding new entries make sure that the maximal length of a name
2402 is correctly handled in the LD_DEBUG_HELP code below. */
2403 static const struct
2405 unsigned char len;
2406 const char name[10];
2407 const char helptext[41];
2408 unsigned short int mask;
2409 } debopts[] =
2411 #define LEN_AND_STR(str) sizeof (str) - 1, str
2412 { LEN_AND_STR ("libs"), "display library search paths",
2413 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2414 { LEN_AND_STR ("reloc"), "display relocation processing",
2415 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2416 { LEN_AND_STR ("files"), "display progress for input file",
2417 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2418 { LEN_AND_STR ("symbols"), "display symbol table processing",
2419 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2420 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2421 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2422 { LEN_AND_STR ("versions"), "display version dependencies",
2423 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2424 { LEN_AND_STR ("all"), "all previous options combined",
2425 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2426 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2427 { LEN_AND_STR ("statistics"), "display relocation statistics",
2428 DL_DEBUG_STATISTICS },
2429 { LEN_AND_STR ("unused"), "determined unused DSOs",
2430 DL_DEBUG_UNUSED },
2431 { LEN_AND_STR ("help"), "display this help message and exit",
2432 DL_DEBUG_HELP },
2434 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2436 /* Skip separating white spaces and commas. */
2437 while (*dl_debug != '\0')
2439 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2441 size_t cnt;
2442 size_t len = 1;
2444 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2445 && dl_debug[len] != ',' && dl_debug[len] != ':')
2446 ++len;
2448 for (cnt = 0; cnt < ndebopts; ++cnt)
2449 if (debopts[cnt].len == len
2450 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
2452 GLRO(dl_debug_mask) |= debopts[cnt].mask;
2453 any_debug = 1;
2454 break;
2457 if (cnt == ndebopts)
2459 /* Display a warning and skip everything until next
2460 separator. */
2461 char *copy = strndupa (dl_debug, len);
2462 _dl_error_printf ("\
2463 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2466 dl_debug += len;
2467 continue;
2470 ++dl_debug;
2473 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
2475 size_t cnt;
2477 _dl_printf ("\
2478 Valid options for the LD_DEBUG environment variable are:\n\n");
2480 for (cnt = 0; cnt < ndebopts; ++cnt)
2481 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2482 " " + debopts[cnt].len - 3,
2483 debopts[cnt].helptext);
2485 _dl_printf ("\n\
2486 To direct the debugging output into a file instead of standard output\n\
2487 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2488 _exit (0);
2492 static void
2493 process_dl_audit (char *str)
2495 /* The parameter is a colon separated list of DSO names. */
2496 char *p;
2498 while ((p = (strsep) (&str, ":")) != NULL)
2499 if (p[0] != '\0'
2500 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
2501 || strchr (p, '/') == NULL))
2503 /* This is using the local malloc, not the system malloc. The
2504 memory can never be freed. */
2505 struct audit_list *newp = malloc (sizeof (*newp));
2506 newp->name = p;
2508 if (audit_list == NULL)
2509 audit_list = newp->next = newp;
2510 else
2512 newp->next = audit_list->next;
2513 audit_list = audit_list->next = newp;
2518 /* Process all environments variables the dynamic linker must recognize.
2519 Since all of them start with `LD_' we are a bit smarter while finding
2520 all the entries. */
2521 extern char **_environ attribute_hidden;
2524 static void
2525 process_envvars (enum mode *modep)
2527 char **runp = _environ;
2528 char *envline;
2529 enum mode mode = normal;
2530 char *debug_output = NULL;
2532 /* This is the default place for profiling data file. */
2533 GLRO(dl_profile_output)
2534 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2536 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2538 size_t len = 0;
2540 while (envline[len] != '\0' && envline[len] != '=')
2541 ++len;
2543 if (envline[len] != '=')
2544 /* This is a "LD_" variable at the end of the string without
2545 a '=' character. Ignore it since otherwise we will access
2546 invalid memory below. */
2547 continue;
2549 switch (len)
2551 case 4:
2552 /* Warning level, verbose or not. */
2553 if (memcmp (envline, "WARN", 4) == 0)
2554 GLRO(dl_verbose) = envline[5] != '\0';
2555 break;
2557 case 5:
2558 /* Debugging of the dynamic linker? */
2559 if (memcmp (envline, "DEBUG", 5) == 0)
2561 process_dl_debug (&envline[6]);
2562 break;
2564 if (memcmp (envline, "AUDIT", 5) == 0)
2565 process_dl_audit (&envline[6]);
2566 break;
2568 case 7:
2569 /* Print information about versions. */
2570 if (memcmp (envline, "VERBOSE", 7) == 0)
2572 version_info = envline[8] != '\0';
2573 break;
2576 /* List of objects to be preloaded. */
2577 if (memcmp (envline, "PRELOAD", 7) == 0)
2579 preloadlist = &envline[8];
2580 break;
2583 /* Which shared object shall be profiled. */
2584 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2585 GLRO(dl_profile) = &envline[8];
2586 break;
2588 case 8:
2589 /* Do we bind early? */
2590 if (memcmp (envline, "BIND_NOW", 8) == 0)
2592 GLRO(dl_lazy) = envline[9] == '\0';
2593 break;
2595 if (memcmp (envline, "BIND_NOT", 8) == 0)
2596 GLRO(dl_bind_not) = envline[9] != '\0';
2597 break;
2599 case 9:
2600 /* Test whether we want to see the content of the auxiliary
2601 array passed up from the kernel. */
2602 if (!INTUSE(__libc_enable_secure)
2603 && memcmp (envline, "SHOW_AUXV", 9) == 0)
2604 _dl_show_auxv ();
2605 break;
2607 case 10:
2608 /* Mask for the important hardware capabilities. */
2609 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2610 GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2611 0, 0);
2612 break;
2614 case 11:
2615 /* Path where the binary is found. */
2616 if (!INTUSE(__libc_enable_secure)
2617 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2618 GLRO(dl_origin_path) = &envline[12];
2619 break;
2621 case 12:
2622 /* The library search path. */
2623 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2625 library_path = &envline[13];
2626 break;
2629 /* Where to place the profiling data file. */
2630 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2632 debug_output = &envline[13];
2633 break;
2636 if (!INTUSE(__libc_enable_secure)
2637 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2638 GLRO(dl_dynamic_weak) = 1;
2639 break;
2641 case 13:
2642 /* We might have some extra environment variable with length 13
2643 to handle. */
2644 #ifdef EXTRA_LD_ENVVARS_13
2645 EXTRA_LD_ENVVARS_13
2646 #endif
2647 if (!INTUSE(__libc_enable_secure)
2648 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2649 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2650 break;
2652 case 14:
2653 /* Where to place the profiling data file. */
2654 if (!INTUSE(__libc_enable_secure)
2655 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2656 && envline[15] != '\0')
2657 GLRO(dl_profile_output) = &envline[15];
2658 break;
2660 case 16:
2661 /* The mode of the dynamic linker can be set. */
2662 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2664 mode = trace;
2665 GLRO(dl_verbose) = 1;
2666 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2667 GLRO(dl_trace_prelink) = &envline[17];
2669 break;
2671 case 20:
2672 /* The mode of the dynamic linker can be set. */
2673 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2674 mode = trace;
2675 break;
2677 /* We might have some extra environment variable to handle. This
2678 is tricky due to the pre-processing of the length of the name
2679 in the switch statement here. The code here assumes that added
2680 environment variables have a different length. */
2681 #ifdef EXTRA_LD_ENVVARS
2682 EXTRA_LD_ENVVARS
2683 #endif
2687 /* The caller wants this information. */
2688 *modep = mode;
2690 /* Extra security for SUID binaries. Remove all dangerous environment
2691 variables. */
2692 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2694 static const char unsecure_envvars[] =
2695 #ifdef EXTRA_UNSECURE_ENVVARS
2696 EXTRA_UNSECURE_ENVVARS
2697 #endif
2698 UNSECURE_ENVVARS;
2699 const char *nextp;
2701 nextp = unsecure_envvars;
2704 unsetenv (nextp);
2705 /* We could use rawmemchr but this need not be fast. */
2706 nextp = (char *) (strchr) (nextp, '\0') + 1;
2708 while (*nextp != '\0');
2710 if (__access ("/etc/suid-debug", F_OK) != 0)
2712 unsetenv ("MALLOC_CHECK_");
2713 GLRO(dl_debug_mask) = 0;
2716 if (mode != normal)
2717 _exit (5);
2719 /* If we have to run the dynamic linker in debugging mode and the
2720 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2721 messages to this file. */
2722 else if (any_debug && debug_output != NULL)
2724 #ifdef O_NOFOLLOW
2725 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2726 #else
2727 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2728 #endif
2729 size_t name_len = strlen (debug_output);
2730 char buf[name_len + 12];
2731 char *startp;
2733 buf[name_len + 11] = '\0';
2734 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2735 *--startp = '.';
2736 startp = memcpy (startp - name_len, debug_output, name_len);
2738 GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2739 if (GLRO(dl_debug_fd) == -1)
2740 /* We use standard output if opening the file failed. */
2741 GLRO(dl_debug_fd) = STDOUT_FILENO;
2746 /* Print the various times we collected. */
2747 static void
2748 __attribute ((noinline))
2749 print_statistics (hp_timing_t *rtld_total_timep)
2751 #ifndef HP_TIMING_NONAVAIL
2752 char buf[200];
2753 char *cp;
2754 char *wp;
2756 /* Total time rtld used. */
2757 if (HP_TIMING_AVAIL)
2759 HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2760 _dl_debug_printf ("\nruntime linker statistics:\n"
2761 " total startup time in dynamic loader: %s\n", buf);
2763 /* Print relocation statistics. */
2764 char pbuf[30];
2765 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2766 cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2767 pbuf + sizeof (pbuf), 10, 0);
2768 wp = pbuf;
2769 switch (pbuf + sizeof (pbuf) - cp)
2771 case 3:
2772 *wp++ = *cp++;
2773 case 2:
2774 *wp++ = *cp++;
2775 case 1:
2776 *wp++ = '.';
2777 *wp++ = *cp++;
2779 *wp = '\0';
2780 _dl_debug_printf ("\
2781 time needed for relocation: %s (%s%%)\n", buf, pbuf);
2783 #endif
2785 unsigned long int num_relative_relocations = 0;
2786 for (Lmid_t ns = 0; ns < DL_NNS; ++ns)
2788 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2789 continue;
2791 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2793 for (unsigned int i = 0; i < scope->r_nlist; i++)
2795 struct link_map *l = scope->r_list [i];
2797 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2798 num_relative_relocations
2799 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2800 #ifndef ELF_MACHINE_REL_RELATIVE
2801 /* Relative relocations are processed on these architectures if
2802 library is loaded to different address than p_vaddr or
2803 if not prelinked. */
2804 if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2805 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2806 #else
2807 /* On e.g. IA-64 or Alpha, relative relocations are processed
2808 only if library is loaded to different address than p_vaddr. */
2809 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2810 #endif
2811 num_relative_relocations
2812 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2816 _dl_debug_printf (" number of relocations: %lu\n"
2817 " number of relocations from cache: %lu\n"
2818 " number of relative relocations: %lu\n",
2819 GL(dl_num_relocations),
2820 GL(dl_num_cache_relocations),
2821 num_relative_relocations);
2823 #ifndef HP_TIMING_NONAVAIL
2824 /* Time spend while loading the object and the dependencies. */
2825 if (HP_TIMING_AVAIL)
2827 char pbuf[30];
2828 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2829 cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2830 pbuf + sizeof (pbuf), 10, 0);
2831 wp = pbuf;
2832 switch (pbuf + sizeof (pbuf) - cp)
2834 case 3:
2835 *wp++ = *cp++;
2836 case 2:
2837 *wp++ = *cp++;
2838 case 1:
2839 *wp++ = '.';
2840 *wp++ = *cp++;
2842 *wp = '\0';
2843 _dl_debug_printf ("\
2844 time needed to load objects: %s (%s%%)\n",
2845 buf, pbuf);
2847 #endif