powerpc: Update libm-test-ulps
[glibc.git] / elf / rtld.c
blob94a00e204907bff732d68c43781ed37032a47a3f
1 /* Run time dynamic linker.
2 Copyright (C) 1995-2021 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, see
17 <https://www.gnu.org/licenses/>. */
19 #include <errno.h>
20 #include <dlfcn.h>
21 #include <fcntl.h>
22 #include <stdbool.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <sys/mman.h>
27 #include <sys/param.h>
28 #include <sys/stat.h>
29 #include <ldsodefs.h>
30 #include <_itoa.h>
31 #include <entry.h>
32 #include <fpu_control.h>
33 #include <hp-timing.h>
34 #include <libc-lock.h>
35 #include "dynamic-link.h"
36 #include <dl-librecon.h>
37 #include <unsecvars.h>
38 #include <dl-cache.h>
39 #include <dl-osinfo.h>
40 #include <dl-procinfo.h>
41 #include <dl-prop.h>
42 #include <dl-vdso.h>
43 #include <dl-vdso-setup.h>
44 #include <tls.h>
45 #include <stap-probe.h>
46 #include <stackinfo.h>
47 #include <not-cancel.h>
48 #include <array_length.h>
49 #include <libc-early-init.h>
50 #include <dl-main.h>
51 #include <list.h>
52 #include <gnu/lib-names.h>
53 #include <dl-tunables.h>
55 #include <assert.h>
57 /* Only enables rtld profiling for architectures which provides non generic
58 hp-timing support. The generic support requires either syscall
59 (clock_gettime), which will incur in extra overhead on loading time.
60 Using vDSO is also an option, but it will require extra support on loader
61 to setup the vDSO pointer before its usage. */
62 #if HP_TIMING_INLINE
63 # define RLTD_TIMING_DECLARE(var, classifier,...) \
64 classifier hp_timing_t var __VA_ARGS__
65 # define RTLD_TIMING_VAR(var) RLTD_TIMING_DECLARE (var, )
66 # define RTLD_TIMING_SET(var, value) (var) = (value)
67 # define RTLD_TIMING_REF(var) &(var)
69 static inline void
70 rtld_timer_start (hp_timing_t *var)
72 HP_TIMING_NOW (*var);
75 static inline void
76 rtld_timer_stop (hp_timing_t *var, hp_timing_t start)
78 hp_timing_t stop;
79 HP_TIMING_NOW (stop);
80 HP_TIMING_DIFF (*var, start, stop);
83 static inline void
84 rtld_timer_accum (hp_timing_t *sum, hp_timing_t start)
86 hp_timing_t stop;
87 rtld_timer_stop (&stop, start);
88 HP_TIMING_ACCUM_NT(*sum, stop);
90 #else
91 # define RLTD_TIMING_DECLARE(var, classifier...)
92 # define RTLD_TIMING_SET(var, value)
93 # define RTLD_TIMING_VAR(var)
94 # define RTLD_TIMING_REF(var) 0
95 # define rtld_timer_start(var)
96 # define rtld_timer_stop(var, start)
97 # define rtld_timer_accum(sum, start)
98 #endif
100 /* Avoid PLT use for our local calls at startup. */
101 extern __typeof (__mempcpy) __mempcpy attribute_hidden;
103 /* GCC has mental blocks about _exit. */
104 extern __typeof (_exit) exit_internal asm ("_exit") attribute_hidden;
105 #define _exit exit_internal
107 /* Helper function to handle errors while resolving symbols. */
108 static void print_unresolved (int errcode, const char *objname,
109 const char *errsting);
111 /* Helper function to handle errors when a version is missing. */
112 static void print_missing_version (int errcode, const char *objname,
113 const char *errsting);
115 /* Print the various times we collected. */
116 static void print_statistics (const hp_timing_t *total_timep);
118 /* Creates an empty audit list. */
119 static void audit_list_init (struct audit_list *);
121 /* Add a string to the end of the audit list, for later parsing. Must
122 not be called after audit_list_next. */
123 static void audit_list_add_string (struct audit_list *, const char *);
125 /* Add the audit strings from the link map, found in the dynamic
126 segment at TG (either DT_AUDIT and DT_DEPAUDIT). Must be called
127 before audit_list_next. */
128 static void audit_list_add_dynamic_tag (struct audit_list *,
129 struct link_map *,
130 unsigned int tag);
132 /* Extract the next audit module from the audit list. Only modules
133 for which dso_name_valid_for_suid is true are returned. Must be
134 called after all the audit_list_add_string,
135 audit_list_add_dynamic_tags calls. */
136 static const char *audit_list_next (struct audit_list *);
138 /* Initialize *STATE with the defaults. */
139 static void dl_main_state_init (struct dl_main_state *state);
141 /* Process all environments variables the dynamic linker must recognize.
142 Since all of them start with `LD_' we are a bit smarter while finding
143 all the entries. */
144 extern char **_environ attribute_hidden;
145 static void process_envvars (struct dl_main_state *state);
147 #ifdef DL_ARGV_NOT_RELRO
148 int _dl_argc attribute_hidden;
149 char **_dl_argv = NULL;
150 /* Nonzero if we were run directly. */
151 unsigned int _dl_skip_args attribute_hidden;
152 #else
153 int _dl_argc attribute_relro attribute_hidden;
154 char **_dl_argv attribute_relro = NULL;
155 unsigned int _dl_skip_args attribute_relro attribute_hidden;
156 #endif
157 rtld_hidden_data_def (_dl_argv)
159 #ifndef THREAD_SET_STACK_GUARD
160 /* Only exported for architectures that don't store the stack guard canary
161 in thread local area. */
162 uintptr_t __stack_chk_guard attribute_relro;
163 #endif
165 /* Only exported for architectures that don't store the pointer guard
166 value in thread local area. */
167 uintptr_t __pointer_chk_guard_local
168 attribute_relro attribute_hidden __attribute__ ((nocommon));
169 #ifndef THREAD_SET_POINTER_GUARD
170 strong_alias (__pointer_chk_guard_local, __pointer_chk_guard)
171 #endif
173 /* Check that AT_SECURE=0, or that the passed name does not contain
174 directories and is not overly long. Reject empty names
175 unconditionally. */
176 static bool
177 dso_name_valid_for_suid (const char *p)
179 if (__glibc_unlikely (__libc_enable_secure))
181 /* Ignore pathnames with directories for AT_SECURE=1
182 programs, and also skip overlong names. */
183 size_t len = strlen (p);
184 if (len >= SECURE_NAME_LIMIT || memchr (p, '/', len) != NULL)
185 return false;
187 return *p != '\0';
190 static void
191 audit_list_init (struct audit_list *list)
193 list->length = 0;
194 list->current_index = 0;
195 list->current_tail = NULL;
198 static void
199 audit_list_add_string (struct audit_list *list, const char *string)
201 /* Empty strings do not load anything. */
202 if (*string == '\0')
203 return;
205 if (list->length == array_length (list->audit_strings))
206 _dl_fatal_printf ("Fatal glibc error: Too many audit modules requested\n");
208 list->audit_strings[list->length++] = string;
210 /* Initialize processing of the first string for
211 audit_list_next. */
212 if (list->length == 1)
213 list->current_tail = string;
216 static void
217 audit_list_add_dynamic_tag (struct audit_list *list, struct link_map *main_map,
218 unsigned int tag)
220 ElfW(Dyn) *info = main_map->l_info[ADDRIDX (tag)];
221 const char *strtab = (const char *) D_PTR (main_map, l_info[DT_STRTAB]);
222 if (info != NULL)
223 audit_list_add_string (list, strtab + info->d_un.d_val);
226 static const char *
227 audit_list_next (struct audit_list *list)
229 if (list->current_tail == NULL)
230 return NULL;
232 while (true)
234 /* Advance to the next string in audit_strings if the current
235 string has been exhausted. */
236 while (*list->current_tail == '\0')
238 ++list->current_index;
239 if (list->current_index == list->length)
241 list->current_tail = NULL;
242 return NULL;
244 list->current_tail = list->audit_strings[list->current_index];
247 /* Split the in-string audit list at the next colon colon. */
248 size_t len = strcspn (list->current_tail, ":");
249 if (len > 0 && len < sizeof (list->fname))
251 memcpy (list->fname, list->current_tail, len);
252 list->fname[len] = '\0';
254 else
255 /* Mark the name as unusable for dso_name_valid_for_suid. */
256 list->fname[0] = '\0';
258 /* Skip over the substring and the following delimiter. */
259 list->current_tail += len;
260 if (*list->current_tail == ':')
261 ++list->current_tail;
263 /* If the name is valid, return it. */
264 if (dso_name_valid_for_suid (list->fname))
265 return list->fname;
267 /* Otherwise wrap around to find the next list element. . */
271 /* Count audit modules before they are loaded so GLRO(dl_naudit)
272 is not yet usable. */
273 static size_t
274 audit_list_count (struct audit_list *list)
276 /* Restore the audit_list iterator state at the end. */
277 const char *saved_tail = list->current_tail;
278 size_t naudit = 0;
280 assert (list->current_index == 0);
281 while (audit_list_next (list) != NULL)
282 naudit++;
283 list->current_tail = saved_tail;
284 list->current_index = 0;
285 return naudit;
288 static void
289 dl_main_state_init (struct dl_main_state *state)
291 audit_list_init (&state->audit_list);
292 state->library_path = NULL;
293 state->library_path_source = NULL;
294 state->preloadlist = NULL;
295 state->preloadarg = NULL;
296 state->glibc_hwcaps_prepend = NULL;
297 state->glibc_hwcaps_mask = NULL;
298 state->mode = rtld_mode_normal;
299 state->any_debug = false;
300 state->version_info = false;
303 #ifndef HAVE_INLINED_SYSCALLS
304 /* Set nonzero during loading and initialization of executable and
305 libraries, cleared before the executable's entry point runs. This
306 must not be initialized to nonzero, because the unused dynamic
307 linker loaded in for libc.so's "ld.so.1" dep will provide the
308 definition seen by libc.so's initializer; that value must be zero,
309 and will be since that dynamic linker's _dl_start and dl_main will
310 never be called. */
311 int _dl_starting_up = 0;
312 rtld_hidden_def (_dl_starting_up)
313 #endif
315 /* This is the structure which defines all variables global to ld.so
316 (except those which cannot be added for some reason). */
317 struct rtld_global _rtld_global =
319 /* Get architecture specific initializer. */
320 #include <dl-procruntime.c>
321 /* Generally the default presumption without further information is an
322 * executable stack but this is not true for all platforms. */
323 ._dl_stack_flags = DEFAULT_STACK_PERMS,
324 #ifdef _LIBC_REENTRANT
325 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
326 ._dl_load_write_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
327 #endif
328 ._dl_nns = 1,
329 ._dl_ns =
331 #ifdef _LIBC_REENTRANT
332 [LM_ID_BASE] = { ._ns_unique_sym_table
333 = { .lock = _RTLD_LOCK_RECURSIVE_INITIALIZER } }
334 #endif
337 /* If we would use strong_alias here the compiler would see a
338 non-hidden definition. This would undo the effect of the previous
339 declaration. So spell out what strong_alias does plus add the
340 visibility attribute. */
341 extern struct rtld_global _rtld_local
342 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
345 /* This variable is similar to _rtld_local, but all values are
346 read-only after relocation. */
347 struct rtld_global_ro _rtld_global_ro attribute_relro =
349 /* Get architecture specific initializer. */
350 #include <dl-procinfo.c>
351 #ifdef NEED_DL_SYSINFO
352 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
353 #endif
354 ._dl_debug_fd = STDERR_FILENO,
355 ._dl_use_load_bias = -2,
356 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
357 #if !HAVE_TUNABLES
358 ._dl_hwcap_mask = HWCAP_IMPORTANT,
359 #endif
360 ._dl_lazy = 1,
361 ._dl_fpu_control = _FPU_DEFAULT,
362 ._dl_pagesize = EXEC_PAGESIZE,
363 ._dl_inhibit_cache = 0,
365 /* Function pointers. */
366 ._dl_debug_printf = _dl_debug_printf,
367 ._dl_mcount = _dl_mcount,
368 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
369 ._dl_open = _dl_open,
370 ._dl_close = _dl_close,
371 ._dl_tls_get_addr_soft = _dl_tls_get_addr_soft,
372 #ifdef HAVE_DL_DISCOVER_OSVERSION
373 ._dl_discover_osversion = _dl_discover_osversion
374 #endif
376 /* If we would use strong_alias here the compiler would see a
377 non-hidden definition. This would undo the effect of the previous
378 declaration. So spell out was strong_alias does plus add the
379 visibility attribute. */
380 extern struct rtld_global_ro _rtld_local_ro
381 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
384 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
385 ElfW(Addr) *user_entry, ElfW(auxv_t) *auxv);
387 /* These two variables cannot be moved into .data.rel.ro. */
388 static struct libname_list _dl_rtld_libname;
389 static struct libname_list _dl_rtld_libname2;
391 /* Variable for statistics. */
392 RLTD_TIMING_DECLARE (relocate_time, static);
393 RLTD_TIMING_DECLARE (load_time, static, attribute_relro);
394 RLTD_TIMING_DECLARE (start_time, static, attribute_relro);
396 /* Additional definitions needed by TLS initialization. */
397 #ifdef TLS_INIT_HELPER
398 TLS_INIT_HELPER
399 #endif
401 /* Helper function for syscall implementation. */
402 #ifdef DL_SYSINFO_IMPLEMENTATION
403 DL_SYSINFO_IMPLEMENTATION
404 #endif
406 /* Before ld.so is relocated we must not access variables which need
407 relocations. This means variables which are exported. Variables
408 declared as static are fine. If we can mark a variable hidden this
409 is fine, too. The latter is important here. We can avoid setting
410 up a temporary link map for ld.so if we can mark _rtld_global as
411 hidden. */
412 #ifdef PI_STATIC_AND_HIDDEN
413 # define DONT_USE_BOOTSTRAP_MAP 1
414 #endif
416 #ifdef DONT_USE_BOOTSTRAP_MAP
417 static ElfW(Addr) _dl_start_final (void *arg);
418 #else
419 struct dl_start_final_info
421 struct link_map l;
422 RTLD_TIMING_VAR (start_time);
424 static ElfW(Addr) _dl_start_final (void *arg,
425 struct dl_start_final_info *info);
426 #endif
428 /* These defined magically in the linker script. */
429 extern char _begin[] attribute_hidden;
430 extern char _etext[] attribute_hidden;
431 extern char _end[] attribute_hidden;
434 #ifdef RTLD_START
435 RTLD_START
436 #else
437 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
438 #endif
440 /* This is the second half of _dl_start (below). It can be inlined safely
441 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
442 references. When the tools don't permit us to avoid using a GOT entry
443 for _dl_rtld_global (no attribute_hidden support), we must make sure
444 this function is not inlined (see below). */
446 #ifdef DONT_USE_BOOTSTRAP_MAP
447 static inline ElfW(Addr) __attribute__ ((always_inline))
448 _dl_start_final (void *arg)
449 #else
450 static ElfW(Addr) __attribute__ ((noinline))
451 _dl_start_final (void *arg, struct dl_start_final_info *info)
452 #endif
454 ElfW(Addr) start_addr;
456 /* If it hasn't happen yet record the startup time. */
457 rtld_timer_start (&start_time);
458 #if !defined DONT_USE_BOOTSTRAP_MAP
459 RTLD_TIMING_SET (start_time, info->start_time);
460 #endif
462 /* Transfer data about ourselves to the permanent link_map structure. */
463 #ifndef DONT_USE_BOOTSTRAP_MAP
464 GL(dl_rtld_map).l_addr = info->l.l_addr;
465 GL(dl_rtld_map).l_ld = info->l.l_ld;
466 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
467 sizeof GL(dl_rtld_map).l_info);
468 GL(dl_rtld_map).l_mach = info->l.l_mach;
469 GL(dl_rtld_map).l_relocated = 1;
470 #endif
471 _dl_setup_hash (&GL(dl_rtld_map));
472 GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
473 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
474 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
475 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
476 /* Copy the TLS related data if necessary. */
477 #ifndef DONT_USE_BOOTSTRAP_MAP
478 # if NO_TLS_OFFSET != 0
479 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
480 # endif
481 #endif
483 /* Initialize the stack end variable. */
484 __libc_stack_end = __builtin_frame_address (0);
486 /* Call the OS-dependent function to set up life so we can do things like
487 file access. It will call `dl_main' (below) to do all the real work
488 of the dynamic linker, and then unwind our frame and run the user
489 entry point on the same stack we entered on. */
490 start_addr = _dl_sysdep_start (arg, &dl_main);
492 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS))
494 RTLD_TIMING_VAR (rtld_total_time);
495 rtld_timer_stop (&rtld_total_time, start_time);
496 print_statistics (RTLD_TIMING_REF(rtld_total_time));
499 return start_addr;
502 static ElfW(Addr) __attribute_used__
503 _dl_start (void *arg)
505 #ifdef DONT_USE_BOOTSTRAP_MAP
506 # define bootstrap_map GL(dl_rtld_map)
507 #else
508 struct dl_start_final_info info;
509 # define bootstrap_map info.l
510 #endif
512 /* This #define produces dynamic linking inline functions for
513 bootstrap relocation instead of general-purpose relocation.
514 Since ld.so must not have any undefined symbols the result
515 is trivial: always the map of ld.so itself. */
516 #define RTLD_BOOTSTRAP
517 #define BOOTSTRAP_MAP (&bootstrap_map)
518 #define RESOLVE_MAP(sym, version, flags) BOOTSTRAP_MAP
519 #include "dynamic-link.h"
521 #ifdef DONT_USE_BOOTSTRAP_MAP
522 rtld_timer_start (&start_time);
523 #else
524 rtld_timer_start (&info.start_time);
525 #endif
527 /* Partly clean the `bootstrap_map' structure up. Don't use
528 `memset' since it might not be built in or inlined and we cannot
529 make function calls at this point. Use '__builtin_memset' if we
530 know it is available. We do not have to clear the memory if we
531 do not have to use the temporary bootstrap_map. Global variables
532 are initialized to zero by default. */
533 #ifndef DONT_USE_BOOTSTRAP_MAP
534 # ifdef HAVE_BUILTIN_MEMSET
535 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
536 # else
537 for (size_t cnt = 0;
538 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
539 ++cnt)
540 bootstrap_map.l_info[cnt] = 0;
541 # endif
542 #endif
544 /* Figure out the run-time load address of the dynamic linker itself. */
545 bootstrap_map.l_addr = elf_machine_load_address ();
547 /* Read our own dynamic section and fill in the info array. */
548 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
549 elf_get_dynamic_info (&bootstrap_map, NULL);
551 #if NO_TLS_OFFSET != 0
552 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
553 #endif
555 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
556 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
557 #endif
559 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
561 /* Relocate ourselves so we can do normal function calls and
562 data access using the global offset table. */
564 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0, 0);
566 bootstrap_map.l_relocated = 1;
568 /* Please note that we don't allow profiling of this object and
569 therefore need not test whether we have to allocate the array
570 for the relocation results (as done in dl-reloc.c). */
572 /* Now life is sane; we can call functions and access global data.
573 Set up to use the operating system facilities, and find out from
574 the operating system's program loader where to find the program
575 header table in core. Put the rest of _dl_start into a separate
576 function, that way the compiler cannot put accesses to the GOT
577 before ELF_DYNAMIC_RELOCATE. */
579 __rtld_malloc_init_stubs ();
582 #ifdef DONT_USE_BOOTSTRAP_MAP
583 ElfW(Addr) entry = _dl_start_final (arg);
584 #else
585 ElfW(Addr) entry = _dl_start_final (arg, &info);
586 #endif
588 #ifndef ELF_MACHINE_START_ADDRESS
589 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
590 #endif
592 return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, entry);
598 /* Now life is peachy; we can do all normal operations.
599 On to the real work. */
601 /* Some helper functions. */
603 /* Arguments to relocate_doit. */
604 struct relocate_args
606 struct link_map *l;
607 int reloc_mode;
610 struct map_args
612 /* Argument to map_doit. */
613 const char *str;
614 struct link_map *loader;
615 int mode;
616 /* Return value of map_doit. */
617 struct link_map *map;
620 struct dlmopen_args
622 const char *fname;
623 struct link_map *map;
626 struct lookup_args
628 const char *name;
629 struct link_map *map;
630 void *result;
633 /* Arguments to version_check_doit. */
634 struct version_check_args
636 int doexit;
637 int dotrace;
640 static void
641 relocate_doit (void *a)
643 struct relocate_args *args = (struct relocate_args *) a;
645 _dl_relocate_object (args->l, args->l->l_scope, args->reloc_mode, 0);
648 static void
649 map_doit (void *a)
651 struct map_args *args = (struct map_args *) a;
652 int type = (args->mode == __RTLD_OPENEXEC) ? lt_executable : lt_library;
653 args->map = _dl_map_object (args->loader, args->str, type, 0,
654 args->mode, LM_ID_BASE);
657 static void
658 dlmopen_doit (void *a)
660 struct dlmopen_args *args = (struct dlmopen_args *) a;
661 args->map = _dl_open (args->fname,
662 (RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT
663 | __RTLD_SECURE),
664 dl_main, LM_ID_NEWLM, _dl_argc, _dl_argv,
665 __environ);
668 static void
669 lookup_doit (void *a)
671 struct lookup_args *args = (struct lookup_args *) a;
672 const ElfW(Sym) *ref = NULL;
673 args->result = NULL;
674 lookup_t l = _dl_lookup_symbol_x (args->name, args->map, &ref,
675 args->map->l_local_scope, NULL, 0,
676 DL_LOOKUP_RETURN_NEWEST, NULL);
677 if (ref != NULL)
678 args->result = DL_SYMBOL_ADDRESS (l, ref);
681 static void
682 version_check_doit (void *a)
684 struct version_check_args *args = (struct version_check_args *) a;
685 if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
686 args->dotrace) && args->doexit)
687 /* We cannot start the application. Abort now. */
688 _exit (1);
692 static inline struct link_map *
693 find_needed (const char *name)
695 struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
696 unsigned int n = scope->r_nlist;
698 while (n-- > 0)
699 if (_dl_name_match_p (name, scope->r_list[n]))
700 return scope->r_list[n];
702 /* Should never happen. */
703 return NULL;
706 static int
707 match_version (const char *string, struct link_map *map)
709 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
710 ElfW(Verdef) *def;
712 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
713 if (map->l_info[VERDEFTAG] == NULL)
714 /* The file has no symbol versioning. */
715 return 0;
717 def = (ElfW(Verdef) *) ((char *) map->l_addr
718 + map->l_info[VERDEFTAG]->d_un.d_ptr);
719 while (1)
721 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
723 /* Compare the version strings. */
724 if (strcmp (string, strtab + aux->vda_name) == 0)
725 /* Bingo! */
726 return 1;
728 /* If no more definitions we failed to find what we want. */
729 if (def->vd_next == 0)
730 break;
732 /* Next definition. */
733 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
736 return 0;
739 static bool tls_init_tp_called;
741 static void *
742 init_tls (size_t naudit)
744 /* Number of elements in the static TLS block. */
745 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
747 /* Do not do this twice. The audit interface might have required
748 the DTV interfaces to be set up early. */
749 if (GL(dl_initial_dtv) != NULL)
750 return NULL;
752 /* Allocate the array which contains the information about the
753 dtv slots. We allocate a few entries more than needed to
754 avoid the need for reallocation. */
755 size_t nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
757 /* Allocate. */
758 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
759 calloc (sizeof (struct dtv_slotinfo_list)
760 + nelem * sizeof (struct dtv_slotinfo), 1);
761 /* No need to check the return value. If memory allocation failed
762 the program would have been terminated. */
764 struct dtv_slotinfo *slotinfo = GL(dl_tls_dtv_slotinfo_list)->slotinfo;
765 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
766 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
768 /* Fill in the information from the loaded modules. No namespace
769 but the base one can be filled at this time. */
770 assert (GL(dl_ns)[LM_ID_BASE + 1]._ns_loaded == NULL);
771 int i = 0;
772 for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
773 l = l->l_next)
774 if (l->l_tls_blocksize != 0)
776 /* This is a module with TLS data. Store the map reference.
777 The generation counter is zero. */
778 slotinfo[i].map = l;
779 /* slotinfo[i].gen = 0; */
780 ++i;
782 assert (i == GL(dl_tls_max_dtv_idx));
784 /* Calculate the size of the static TLS surplus. */
785 _dl_tls_static_surplus_init (naudit);
787 /* Compute the TLS offsets for the various blocks. */
788 _dl_determine_tlsoffset ();
790 /* Construct the static TLS block and the dtv for the initial
791 thread. For some platforms this will include allocating memory
792 for the thread descriptor. The memory for the TLS block will
793 never be freed. It should be allocated accordingly. The dtv
794 array can be changed if dynamic loading requires it. */
795 void *tcbp = _dl_allocate_tls_storage ();
796 if (tcbp == NULL)
797 _dl_fatal_printf ("\
798 cannot allocate TLS data structures for initial thread\n");
800 /* Store for detection of the special case by __tls_get_addr
801 so it knows not to pass this dtv to the normal realloc. */
802 GL(dl_initial_dtv) = GET_DTV (tcbp);
804 /* And finally install it for the main thread. */
805 const char *lossage = TLS_INIT_TP (tcbp);
806 if (__glibc_unlikely (lossage != NULL))
807 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
808 #if THREAD_GSCOPE_IN_TCB
809 list_add (&THREAD_SELF->list, &GL (dl_stack_user));
810 #endif
811 tls_init_tp_called = true;
813 return tcbp;
816 static unsigned int
817 do_preload (const char *fname, struct link_map *main_map, const char *where)
819 const char *objname;
820 const char *err_str = NULL;
821 struct map_args args;
822 bool malloced;
824 args.str = fname;
825 args.loader = main_map;
826 args.mode = __RTLD_SECURE;
828 unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
830 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
831 if (__glibc_unlikely (err_str != NULL))
833 _dl_error_printf ("\
834 ERROR: ld.so: object '%s' from %s cannot be preloaded (%s): ignored.\n",
835 fname, where, err_str);
836 /* No need to call free, this is still before
837 the libc's malloc is used. */
839 else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
840 /* It is no duplicate. */
841 return 1;
843 /* Nothing loaded. */
844 return 0;
847 #if defined SHARED && defined _LIBC_REENTRANT \
848 && defined __rtld_lock_default_lock_recursive
849 static void
850 rtld_lock_default_lock_recursive (void *lock)
852 __rtld_lock_default_lock_recursive (lock);
855 static void
856 rtld_lock_default_unlock_recursive (void *lock)
858 __rtld_lock_default_unlock_recursive (lock);
860 #endif
863 static void
864 security_init (void)
866 /* Set up the stack checker's canary. */
867 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard (_dl_random);
868 #ifdef THREAD_SET_STACK_GUARD
869 THREAD_SET_STACK_GUARD (stack_chk_guard);
870 #else
871 __stack_chk_guard = stack_chk_guard;
872 #endif
874 /* Set up the pointer guard as well, if necessary. */
875 uintptr_t pointer_chk_guard
876 = _dl_setup_pointer_guard (_dl_random, stack_chk_guard);
877 #ifdef THREAD_SET_POINTER_GUARD
878 THREAD_SET_POINTER_GUARD (pointer_chk_guard);
879 #endif
880 __pointer_chk_guard_local = pointer_chk_guard;
882 /* We do not need the _dl_random value anymore. The less
883 information we leave behind, the better, so clear the
884 variable. */
885 _dl_random = NULL;
888 #include <setup-vdso.h>
890 /* The LD_PRELOAD environment variable gives list of libraries
891 separated by white space or colons that are loaded before the
892 executable's dependencies and prepended to the global scope list.
893 (If the binary is running setuid all elements containing a '/' are
894 ignored since it is insecure.) Return the number of preloads
895 performed. Ditto for --preload command argument. */
896 unsigned int
897 handle_preload_list (const char *preloadlist, struct link_map *main_map,
898 const char *where)
900 unsigned int npreloads = 0;
901 const char *p = preloadlist;
902 char fname[SECURE_PATH_LIMIT];
904 while (*p != '\0')
906 /* Split preload list at space/colon. */
907 size_t len = strcspn (p, " :");
908 if (len > 0 && len < sizeof (fname))
910 memcpy (fname, p, len);
911 fname[len] = '\0';
913 else
914 fname[0] = '\0';
916 /* Skip over the substring and the following delimiter. */
917 p += len;
918 if (*p != '\0')
919 ++p;
921 if (dso_name_valid_for_suid (fname))
922 npreloads += do_preload (fname, main_map, where);
924 return npreloads;
927 /* Called if the audit DSO cannot be used: if it does not have the
928 appropriate interfaces, or it expects a more recent version library
929 version than what the dynamic linker provides. */
930 static void
931 unload_audit_module (struct link_map *map, int original_tls_idx)
933 #ifndef NDEBUG
934 Lmid_t ns = map->l_ns;
935 #endif
936 _dl_close (map);
938 /* Make sure the namespace has been cleared entirely. */
939 assert (GL(dl_ns)[ns]._ns_loaded == NULL);
940 assert (GL(dl_ns)[ns]._ns_nloaded == 0);
942 GL(dl_tls_max_dtv_idx) = original_tls_idx;
945 /* Called to print an error message if loading of an audit module
946 failed. */
947 static void
948 report_audit_module_load_error (const char *name, const char *err_str,
949 bool malloced)
951 _dl_error_printf ("\
952 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
953 name, err_str);
954 if (malloced)
955 free ((char *) err_str);
958 /* Load one audit module. */
959 static void
960 load_audit_module (const char *name, struct audit_ifaces **last_audit)
962 int original_tls_idx = GL(dl_tls_max_dtv_idx);
964 struct dlmopen_args dlmargs;
965 dlmargs.fname = name;
966 dlmargs.map = NULL;
968 const char *objname;
969 const char *err_str = NULL;
970 bool malloced;
971 _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit, &dlmargs);
972 if (__glibc_unlikely (err_str != NULL))
974 report_audit_module_load_error (name, err_str, malloced);
975 return;
978 struct lookup_args largs;
979 largs.name = "la_version";
980 largs.map = dlmargs.map;
981 _dl_catch_error (&objname, &err_str, &malloced, lookup_doit, &largs);
982 if (__glibc_likely (err_str != NULL))
984 unload_audit_module (dlmargs.map, original_tls_idx);
985 report_audit_module_load_error (name, err_str, malloced);
986 return;
989 unsigned int (*laversion) (unsigned int) = largs.result;
991 /* A null symbol indicates that something is very wrong with the
992 loaded object because defined symbols are supposed to have a
993 valid, non-null address. */
994 assert (laversion != NULL);
996 unsigned int lav = laversion (LAV_CURRENT);
997 if (lav == 0)
999 /* Only print an error message if debugging because this can
1000 happen deliberately. */
1001 if (GLRO(dl_debug_mask) & DL_DEBUG_FILES)
1002 _dl_debug_printf ("\
1003 file=%s [%lu]; audit interface function la_version returned zero; ignored.\n",
1004 dlmargs.map->l_name, dlmargs.map->l_ns);
1005 unload_audit_module (dlmargs.map, original_tls_idx);
1006 return;
1009 if (lav > LAV_CURRENT)
1011 _dl_debug_printf ("\
1012 ERROR: audit interface '%s' requires version %d (maximum supported version %d); ignored.\n",
1013 name, lav, LAV_CURRENT);
1014 unload_audit_module (dlmargs.map, original_tls_idx);
1015 return;
1018 enum { naudit_ifaces = 8 };
1019 union
1021 struct audit_ifaces ifaces;
1022 void (*fptr[naudit_ifaces]) (void);
1023 } *newp = malloc (sizeof (*newp));
1024 if (newp == NULL)
1025 _dl_fatal_printf ("Out of memory while loading audit modules\n");
1027 /* Names of the auditing interfaces. All in one
1028 long string. */
1029 static const char audit_iface_names[] =
1030 "la_activity\0"
1031 "la_objsearch\0"
1032 "la_objopen\0"
1033 "la_preinit\0"
1034 #if __ELF_NATIVE_CLASS == 32
1035 "la_symbind32\0"
1036 #elif __ELF_NATIVE_CLASS == 64
1037 "la_symbind64\0"
1038 #else
1039 # error "__ELF_NATIVE_CLASS must be defined"
1040 #endif
1041 #define STRING(s) __STRING (s)
1042 "la_" STRING (ARCH_LA_PLTENTER) "\0"
1043 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
1044 "la_objclose\0";
1045 unsigned int cnt = 0;
1046 const char *cp = audit_iface_names;
1049 largs.name = cp;
1050 _dl_catch_error (&objname, &err_str, &malloced, lookup_doit, &largs);
1052 /* Store the pointer. */
1053 if (err_str == NULL && largs.result != NULL)
1054 newp->fptr[cnt] = largs.result;
1055 else
1056 newp->fptr[cnt] = NULL;
1057 ++cnt;
1059 cp = rawmemchr (cp, '\0') + 1;
1061 while (*cp != '\0');
1062 assert (cnt == naudit_ifaces);
1064 /* Now append the new auditing interface to the list. */
1065 newp->ifaces.next = NULL;
1066 if (*last_audit == NULL)
1067 *last_audit = GLRO(dl_audit) = &newp->ifaces;
1068 else
1069 *last_audit = (*last_audit)->next = &newp->ifaces;
1071 /* The dynamic linker link map is statically allocated, so the
1072 cookie in _dl_new_object has not happened. */
1073 link_map_audit_state (&GL (dl_rtld_map), GLRO (dl_naudit))->cookie
1074 = (intptr_t) &GL (dl_rtld_map);
1076 ++GLRO(dl_naudit);
1078 /* Mark the DSO as being used for auditing. */
1079 dlmargs.map->l_auditing = 1;
1082 /* Notify the the audit modules that the object MAP has already been
1083 loaded. */
1084 static void
1085 notify_audit_modules_of_loaded_object (struct link_map *map)
1087 struct audit_ifaces *afct = GLRO(dl_audit);
1088 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1090 if (afct->objopen != NULL)
1092 struct auditstate *state = link_map_audit_state (map, cnt);
1093 state->bindflags = afct->objopen (map, LM_ID_BASE, &state->cookie);
1094 map->l_audit_any_plt |= state->bindflags != 0;
1097 afct = afct->next;
1101 /* Load all audit modules. */
1102 static void
1103 load_audit_modules (struct link_map *main_map, struct audit_list *audit_list)
1105 struct audit_ifaces *last_audit = NULL;
1107 while (true)
1109 const char *name = audit_list_next (audit_list);
1110 if (name == NULL)
1111 break;
1112 load_audit_module (name, &last_audit);
1115 /* Notify audit modules of the initially loaded modules (the main
1116 program and the dynamic linker itself). */
1117 if (GLRO(dl_naudit) > 0)
1119 notify_audit_modules_of_loaded_object (main_map);
1120 notify_audit_modules_of_loaded_object (&GL(dl_rtld_map));
1124 static void
1125 dl_main (const ElfW(Phdr) *phdr,
1126 ElfW(Word) phnum,
1127 ElfW(Addr) *user_entry,
1128 ElfW(auxv_t) *auxv)
1130 const ElfW(Phdr) *ph;
1131 struct link_map *main_map;
1132 size_t file_size;
1133 char *file;
1134 bool has_interp = false;
1135 unsigned int i;
1136 bool prelinked = false;
1137 bool rtld_is_main = false;
1138 void *tcbp = NULL;
1140 struct dl_main_state state;
1141 dl_main_state_init (&state);
1143 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
1145 #if defined SHARED && defined _LIBC_REENTRANT \
1146 && defined __rtld_lock_default_lock_recursive
1147 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
1148 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
1149 #endif
1151 #if THREAD_GSCOPE_IN_TCB
1152 INIT_LIST_HEAD (&GL (dl_stack_used));
1153 INIT_LIST_HEAD (&GL (dl_stack_user));
1154 #endif
1156 /* The explicit initialization here is cheaper than processing the reloc
1157 in the _rtld_local definition's initializer. */
1158 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
1160 /* Process the environment variable which control the behaviour. */
1161 process_envvars (&state);
1163 #ifndef HAVE_INLINED_SYSCALLS
1164 /* Set up a flag which tells we are just starting. */
1165 _dl_starting_up = 1;
1166 #endif
1168 const char *ld_so_name = _dl_argv[0];
1169 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
1171 /* Ho ho. We are not the program interpreter! We are the program
1172 itself! This means someone ran ld.so as a command. Well, that
1173 might be convenient to do sometimes. We support it by
1174 interpreting the args like this:
1176 ld.so PROGRAM ARGS...
1178 The first argument is the name of a file containing an ELF
1179 executable we will load and run with the following arguments.
1180 To simplify life here, PROGRAM is searched for using the
1181 normal rules for shared objects, rather than $PATH or anything
1182 like that. We just load it and use its entry point; we don't
1183 pay attention to its PT_INTERP command (we are the interpreter
1184 ourselves). This is an easy way to test a new ld.so before
1185 installing it. */
1186 rtld_is_main = true;
1188 char *argv0 = NULL;
1190 /* Note the place where the dynamic linker actually came from. */
1191 GL(dl_rtld_map).l_name = rtld_progname;
1193 while (_dl_argc > 1)
1194 if (! strcmp (_dl_argv[1], "--list"))
1196 if (state.mode != rtld_mode_help)
1198 state.mode = rtld_mode_list;
1199 /* This means do no dependency analysis. */
1200 GLRO(dl_lazy) = -1;
1203 ++_dl_skip_args;
1204 --_dl_argc;
1205 ++_dl_argv;
1207 else if (! strcmp (_dl_argv[1], "--verify"))
1209 if (state.mode != rtld_mode_help)
1210 state.mode = rtld_mode_verify;
1212 ++_dl_skip_args;
1213 --_dl_argc;
1214 ++_dl_argv;
1216 else if (! strcmp (_dl_argv[1], "--inhibit-cache"))
1218 GLRO(dl_inhibit_cache) = 1;
1219 ++_dl_skip_args;
1220 --_dl_argc;
1221 ++_dl_argv;
1223 else if (! strcmp (_dl_argv[1], "--library-path")
1224 && _dl_argc > 2)
1226 state.library_path = _dl_argv[2];
1227 state.library_path_source = "--library-path";
1229 _dl_skip_args += 2;
1230 _dl_argc -= 2;
1231 _dl_argv += 2;
1233 else if (! strcmp (_dl_argv[1], "--inhibit-rpath")
1234 && _dl_argc > 2)
1236 GLRO(dl_inhibit_rpath) = _dl_argv[2];
1238 _dl_skip_args += 2;
1239 _dl_argc -= 2;
1240 _dl_argv += 2;
1242 else if (! strcmp (_dl_argv[1], "--audit") && _dl_argc > 2)
1244 audit_list_add_string (&state.audit_list, _dl_argv[2]);
1246 _dl_skip_args += 2;
1247 _dl_argc -= 2;
1248 _dl_argv += 2;
1250 else if (! strcmp (_dl_argv[1], "--preload") && _dl_argc > 2)
1252 state.preloadarg = _dl_argv[2];
1253 _dl_skip_args += 2;
1254 _dl_argc -= 2;
1255 _dl_argv += 2;
1257 else if (! strcmp (_dl_argv[1], "--argv0") && _dl_argc > 2)
1259 argv0 = _dl_argv[2];
1261 _dl_skip_args += 2;
1262 _dl_argc -= 2;
1263 _dl_argv += 2;
1265 else if (strcmp (_dl_argv[1], "--glibc-hwcaps-prepend") == 0
1266 && _dl_argc > 2)
1268 state.glibc_hwcaps_prepend = _dl_argv[2];
1269 _dl_skip_args += 2;
1270 _dl_argc -= 2;
1271 _dl_argv += 2;
1273 else if (strcmp (_dl_argv[1], "--glibc-hwcaps-mask") == 0
1274 && _dl_argc > 2)
1276 state.glibc_hwcaps_mask = _dl_argv[2];
1277 _dl_skip_args += 2;
1278 _dl_argc -= 2;
1279 _dl_argv += 2;
1281 #if HAVE_TUNABLES
1282 else if (! strcmp (_dl_argv[1], "--list-tunables"))
1284 state.mode = rtld_mode_list_tunables;
1286 ++_dl_skip_args;
1287 --_dl_argc;
1288 ++_dl_argv;
1290 #endif
1291 else if (! strcmp (_dl_argv[1], "--list-diagnostics"))
1293 state.mode = rtld_mode_list_diagnostics;
1295 ++_dl_skip_args;
1296 --_dl_argc;
1297 ++_dl_argv;
1299 else if (strcmp (_dl_argv[1], "--help") == 0)
1301 state.mode = rtld_mode_help;
1302 --_dl_argc;
1303 ++_dl_argv;
1305 else if (strcmp (_dl_argv[1], "--version") == 0)
1306 _dl_version ();
1307 else if (_dl_argv[1][0] == '-' && _dl_argv[1][1] == '-')
1309 if (_dl_argv[1][1] == '\0')
1310 /* End of option list. */
1311 break;
1312 else
1313 /* Unrecognized option. */
1314 _dl_usage (ld_so_name, _dl_argv[1]);
1316 else
1317 break;
1319 #if HAVE_TUNABLES
1320 if (__glibc_unlikely (state.mode == rtld_mode_list_tunables))
1322 __tunables_print ();
1323 _exit (0);
1325 #endif
1327 if (state.mode == rtld_mode_list_diagnostics)
1328 _dl_print_diagnostics (_environ);
1330 /* If we have no further argument the program was called incorrectly.
1331 Grant the user some education. */
1332 if (_dl_argc < 2)
1334 if (state.mode == rtld_mode_help)
1335 /* --help without an executable is not an error. */
1336 _dl_help (ld_so_name, &state);
1337 else
1338 _dl_usage (ld_so_name, NULL);
1341 ++_dl_skip_args;
1342 --_dl_argc;
1343 ++_dl_argv;
1345 /* The initialization of _dl_stack_flags done below assumes the
1346 executable's PT_GNU_STACK may have been honored by the kernel, and
1347 so a PT_GNU_STACK with PF_X set means the stack started out with
1348 execute permission. However, this is not really true if the
1349 dynamic linker is the executable the kernel loaded. For this
1350 case, we must reinitialize _dl_stack_flags to match the dynamic
1351 linker itself. If the dynamic linker was built with a
1352 PT_GNU_STACK, then the kernel may have loaded us with a
1353 nonexecutable stack that we will have to make executable when we
1354 load the program below unless it has a PT_GNU_STACK indicating
1355 nonexecutable stack is ok. */
1357 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1358 if (ph->p_type == PT_GNU_STACK)
1360 GL(dl_stack_flags) = ph->p_flags;
1361 break;
1364 if (__glibc_unlikely (state.mode == rtld_mode_verify
1365 || state.mode == rtld_mode_help))
1367 const char *objname;
1368 const char *err_str = NULL;
1369 struct map_args args;
1370 bool malloced;
1372 args.str = rtld_progname;
1373 args.loader = NULL;
1374 args.mode = __RTLD_OPENEXEC;
1375 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
1376 &args);
1377 if (__glibc_unlikely (err_str != NULL))
1379 /* We don't free the returned string, the programs stops
1380 anyway. */
1381 if (state.mode == rtld_mode_help)
1382 /* Mask the failure to load the main object. The help
1383 message contains less information in this case. */
1384 _dl_help (ld_so_name, &state);
1385 else
1386 _exit (EXIT_FAILURE);
1389 else
1391 RTLD_TIMING_VAR (start);
1392 rtld_timer_start (&start);
1393 _dl_map_object (NULL, rtld_progname, lt_executable, 0,
1394 __RTLD_OPENEXEC, LM_ID_BASE);
1395 rtld_timer_stop (&load_time, start);
1398 /* Now the map for the main executable is available. */
1399 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1401 if (__glibc_likely (state.mode == rtld_mode_normal)
1402 && GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1403 && main_map->l_info[DT_SONAME] != NULL
1404 && strcmp ((const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1405 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val,
1406 (const char *) D_PTR (main_map, l_info[DT_STRTAB])
1407 + main_map->l_info[DT_SONAME]->d_un.d_val) == 0)
1408 _dl_fatal_printf ("loader cannot load itself\n");
1410 phdr = main_map->l_phdr;
1411 phnum = main_map->l_phnum;
1412 /* We overwrite here a pointer to a malloc()ed string. But since
1413 the malloc() implementation used at this point is the dummy
1414 implementations which has no real free() function it does not
1415 makes sense to free the old string first. */
1416 main_map->l_name = (char *) "";
1417 *user_entry = main_map->l_entry;
1419 #ifdef HAVE_AUX_VECTOR
1420 /* Adjust the on-stack auxiliary vector so that it looks like the
1421 binary was executed directly. */
1422 for (ElfW(auxv_t) *av = auxv; av->a_type != AT_NULL; av++)
1423 switch (av->a_type)
1425 case AT_PHDR:
1426 av->a_un.a_val = (uintptr_t) phdr;
1427 break;
1428 case AT_PHNUM:
1429 av->a_un.a_val = phnum;
1430 break;
1431 case AT_ENTRY:
1432 av->a_un.a_val = *user_entry;
1433 break;
1434 case AT_EXECFN:
1435 av->a_un.a_val = (uintptr_t) _dl_argv[0];
1436 break;
1438 #endif
1440 /* Set the argv[0] string now that we've processed the executable. */
1441 if (argv0 != NULL)
1442 _dl_argv[0] = argv0;
1444 else
1446 /* Create a link_map for the executable itself.
1447 This will be what dlopen on "" returns. */
1448 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1449 __RTLD_OPENEXEC, LM_ID_BASE);
1450 assert (main_map != NULL);
1451 main_map->l_phdr = phdr;
1452 main_map->l_phnum = phnum;
1453 main_map->l_entry = *user_entry;
1455 /* Even though the link map is not yet fully initialized we can add
1456 it to the map list since there are no possible users running yet. */
1457 _dl_add_to_namespace_list (main_map, LM_ID_BASE);
1458 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
1460 /* At this point we are in a bit of trouble. We would have to
1461 fill in the values for l_dev and l_ino. But in general we
1462 do not know where the file is. We also do not handle AT_EXECFD
1463 even if it would be passed up.
1465 We leave the values here defined to 0. This is normally no
1466 problem as the program code itself is normally no shared
1467 object and therefore cannot be loaded dynamically. Nothing
1468 prevent the use of dynamic binaries and in these situations
1469 we might get problems. We might not be able to find out
1470 whether the object is already loaded. But since there is no
1471 easy way out and because the dynamic binary must also not
1472 have an SONAME we ignore this program for now. If it becomes
1473 a problem we can force people using SONAMEs. */
1475 /* We delay initializing the path structure until we got the dynamic
1476 information for the program. */
1479 main_map->l_map_end = 0;
1480 main_map->l_text_end = 0;
1481 /* Perhaps the executable has no PT_LOAD header entries at all. */
1482 main_map->l_map_start = ~0;
1483 /* And it was opened directly. */
1484 ++main_map->l_direct_opencount;
1486 /* Scan the program header table for the dynamic section. */
1487 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1488 switch (ph->p_type)
1490 case PT_PHDR:
1491 /* Find out the load address. */
1492 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1493 break;
1494 case PT_DYNAMIC:
1495 /* This tells us where to find the dynamic section,
1496 which tells us everything we need to do. */
1497 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
1498 break;
1499 case PT_INTERP:
1500 /* This "interpreter segment" was used by the program loader to
1501 find the program interpreter, which is this program itself, the
1502 dynamic linker. We note what name finds us, so that a future
1503 dlopen call or DT_NEEDED entry, for something that wants to link
1504 against the dynamic linker as a shared library, will know that
1505 the shared object is already loaded. */
1506 _dl_rtld_libname.name = ((const char *) main_map->l_addr
1507 + ph->p_vaddr);
1508 /* _dl_rtld_libname.next = NULL; Already zero. */
1509 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1511 /* Ordinarilly, we would get additional names for the loader from
1512 our DT_SONAME. This can't happen if we were actually linked as
1513 a static executable (detect this case when we have no DYNAMIC).
1514 If so, assume the filename component of the interpreter path to
1515 be our SONAME, and add it to our name list. */
1516 if (GL(dl_rtld_map).l_ld == NULL)
1518 const char *p = NULL;
1519 const char *cp = _dl_rtld_libname.name;
1521 /* Find the filename part of the path. */
1522 while (*cp != '\0')
1523 if (*cp++ == '/')
1524 p = cp;
1526 if (p != NULL)
1528 _dl_rtld_libname2.name = p;
1529 /* _dl_rtld_libname2.next = NULL; Already zero. */
1530 _dl_rtld_libname.next = &_dl_rtld_libname2;
1534 has_interp = true;
1535 break;
1536 case PT_LOAD:
1538 ElfW(Addr) mapstart;
1539 ElfW(Addr) allocend;
1541 /* Remember where the main program starts in memory. */
1542 mapstart = (main_map->l_addr
1543 + (ph->p_vaddr & ~(GLRO(dl_pagesize) - 1)));
1544 if (main_map->l_map_start > mapstart)
1545 main_map->l_map_start = mapstart;
1547 /* Also where it ends. */
1548 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1549 if (main_map->l_map_end < allocend)
1550 main_map->l_map_end = allocend;
1551 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1552 main_map->l_text_end = allocend;
1554 break;
1556 case PT_TLS:
1557 if (ph->p_memsz > 0)
1559 /* Note that in the case the dynamic linker we duplicate work
1560 here since we read the PT_TLS entry already in
1561 _dl_start_final. But the result is repeatable so do not
1562 check for this special but unimportant case. */
1563 main_map->l_tls_blocksize = ph->p_memsz;
1564 main_map->l_tls_align = ph->p_align;
1565 if (ph->p_align == 0)
1566 main_map->l_tls_firstbyte_offset = 0;
1567 else
1568 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1569 & (ph->p_align - 1));
1570 main_map->l_tls_initimage_size = ph->p_filesz;
1571 main_map->l_tls_initimage = (void *) ph->p_vaddr;
1573 /* This image gets the ID one. */
1574 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1576 break;
1578 case PT_GNU_STACK:
1579 GL(dl_stack_flags) = ph->p_flags;
1580 break;
1582 case PT_GNU_RELRO:
1583 main_map->l_relro_addr = ph->p_vaddr;
1584 main_map->l_relro_size = ph->p_memsz;
1585 break;
1587 /* Process program headers again, but scan them backwards so
1588 that PT_NOTE can be skipped if PT_GNU_PROPERTY exits. */
1589 for (ph = &phdr[phnum]; ph != phdr; --ph)
1590 switch (ph[-1].p_type)
1592 case PT_NOTE:
1593 _dl_process_pt_note (main_map, -1, &ph[-1]);
1594 break;
1595 case PT_GNU_PROPERTY:
1596 _dl_process_pt_gnu_property (main_map, -1, &ph[-1]);
1597 break;
1600 /* Adjust the address of the TLS initialization image in case
1601 the executable is actually an ET_DYN object. */
1602 if (main_map->l_tls_initimage != NULL)
1603 main_map->l_tls_initimage
1604 = (char *) main_map->l_tls_initimage + main_map->l_addr;
1605 if (! main_map->l_map_end)
1606 main_map->l_map_end = ~0;
1607 if (! main_map->l_text_end)
1608 main_map->l_text_end = ~0;
1609 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1611 /* We were invoked directly, so the program might not have a
1612 PT_INTERP. */
1613 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1614 /* _dl_rtld_libname.next = NULL; Already zero. */
1615 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1617 else
1618 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1620 /* If the current libname is different from the SONAME, add the
1621 latter as well. */
1622 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1623 && strcmp (GL(dl_rtld_map).l_libname->name,
1624 (const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1625 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1627 static struct libname_list newname;
1628 newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1629 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1630 newname.next = NULL;
1631 newname.dont_free = 1;
1633 assert (GL(dl_rtld_map).l_libname->next == NULL);
1634 GL(dl_rtld_map).l_libname->next = &newname;
1636 /* The ld.so must be relocated since otherwise loading audit modules
1637 will fail since they reuse the very same ld.so. */
1638 assert (GL(dl_rtld_map).l_relocated);
1640 if (! rtld_is_main)
1642 /* Extract the contents of the dynamic section for easy access. */
1643 elf_get_dynamic_info (main_map, NULL);
1645 /* If the main map is libc.so, update the base namespace to
1646 refer to this map. If libc.so is loaded later, this happens
1647 in _dl_map_object_from_fd. */
1648 if (main_map->l_info[DT_SONAME] != NULL
1649 && (strcmp (((const char *) D_PTR (main_map, l_info[DT_STRTAB])
1650 + main_map->l_info[DT_SONAME]->d_un.d_val), LIBC_SO)
1651 == 0))
1652 GL(dl_ns)[LM_ID_BASE].libc_map = main_map;
1654 /* Set up our cache of pointers into the hash table. */
1655 _dl_setup_hash (main_map);
1658 if (__glibc_unlikely (state.mode == rtld_mode_verify))
1660 /* We were called just to verify that this is a dynamic
1661 executable using us as the program interpreter. Exit with an
1662 error if we were not able to load the binary or no interpreter
1663 is specified (i.e., this is no dynamically linked binary. */
1664 if (main_map->l_ld == NULL)
1665 _exit (1);
1667 /* We allow here some platform specific code. */
1668 #ifdef DISTINGUISH_LIB_VERSIONS
1669 DISTINGUISH_LIB_VERSIONS;
1670 #endif
1671 _exit (has_interp ? 0 : 2);
1674 struct link_map **first_preload = &GL(dl_rtld_map).l_next;
1675 /* Set up the data structures for the system-supplied DSO early,
1676 so they can influence _dl_init_paths. */
1677 setup_vdso (main_map, &first_preload);
1679 /* With vDSO setup we can initialize the function pointers. */
1680 setup_vdso_pointers ();
1682 #ifdef DL_SYSDEP_OSCHECK
1683 DL_SYSDEP_OSCHECK (_dl_fatal_printf);
1684 #endif
1686 /* Initialize the data structures for the search paths for shared
1687 objects. */
1688 call_init_paths (&state);
1690 /* Initialize _r_debug. */
1691 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1692 LM_ID_BASE);
1693 r->r_state = RT_CONSISTENT;
1695 /* Put the link_map for ourselves on the chain so it can be found by
1696 name. Note that at this point the global chain of link maps contains
1697 exactly one element, which is pointed to by dl_loaded. */
1698 if (! GL(dl_rtld_map).l_name)
1699 /* If not invoked directly, the dynamic linker shared object file was
1700 found by the PT_INTERP name. */
1701 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1702 GL(dl_rtld_map).l_type = lt_library;
1703 main_map->l_next = &GL(dl_rtld_map);
1704 GL(dl_rtld_map).l_prev = main_map;
1705 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1706 ++GL(dl_load_adds);
1708 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1709 to not using bias for non-prelinked PIEs and libraries
1710 and using it for executables or prelinked PIEs or libraries. */
1711 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1712 GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
1714 /* Set up the program header information for the dynamic linker
1715 itself. It is needed in the dl_iterate_phdr callbacks. */
1716 const ElfW(Ehdr) *rtld_ehdr;
1718 /* Starting from binutils-2.23, the linker will define the magic symbol
1719 __ehdr_start to point to our own ELF header if it is visible in a
1720 segment that also includes the phdrs. If that's not available, we use
1721 the old method that assumes the beginning of the file is part of the
1722 lowest-addressed PT_LOAD segment. */
1723 #ifdef HAVE_EHDR_START
1724 extern const ElfW(Ehdr) __ehdr_start __attribute__ ((visibility ("hidden")));
1725 rtld_ehdr = &__ehdr_start;
1726 #else
1727 rtld_ehdr = (void *) GL(dl_rtld_map).l_map_start;
1728 #endif
1729 assert (rtld_ehdr->e_ehsize == sizeof *rtld_ehdr);
1730 assert (rtld_ehdr->e_phentsize == sizeof (ElfW(Phdr)));
1732 const ElfW(Phdr) *rtld_phdr = (const void *) rtld_ehdr + rtld_ehdr->e_phoff;
1734 GL(dl_rtld_map).l_phdr = rtld_phdr;
1735 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1738 /* PT_GNU_RELRO is usually the last phdr. */
1739 size_t cnt = rtld_ehdr->e_phnum;
1740 while (cnt-- > 0)
1741 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1743 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1744 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1745 break;
1748 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1749 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1750 /* Assign a module ID. Do this before loading any audit modules. */
1751 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1753 audit_list_add_dynamic_tag (&state.audit_list, main_map, DT_AUDIT);
1754 audit_list_add_dynamic_tag (&state.audit_list, main_map, DT_DEPAUDIT);
1756 /* At this point, all data has been obtained that is included in the
1757 --help output. */
1758 if (__glibc_unlikely (state.mode == rtld_mode_help))
1759 _dl_help (ld_so_name, &state);
1761 /* If we have auditing DSOs to load, do it now. */
1762 bool need_security_init = true;
1763 if (state.audit_list.length > 0)
1765 size_t naudit = audit_list_count (&state.audit_list);
1767 /* Since we start using the auditing DSOs right away we need to
1768 initialize the data structures now. */
1769 tcbp = init_tls (naudit);
1771 /* Initialize security features. We need to do it this early
1772 since otherwise the constructors of the audit libraries will
1773 use different values (especially the pointer guard) and will
1774 fail later on. */
1775 security_init ();
1776 need_security_init = false;
1778 load_audit_modules (main_map, &state.audit_list);
1780 /* The count based on audit strings may overestimate the number
1781 of audit modules that got loaded, but not underestimate. */
1782 assert (GLRO(dl_naudit) <= naudit);
1785 /* Keep track of the currently loaded modules to count how many
1786 non-audit modules which use TLS are loaded. */
1787 size_t count_modids = _dl_count_modids ();
1789 /* Set up debugging before the debugger is notified for the first time. */
1790 #ifdef ELF_MACHINE_DEBUG_SETUP
1791 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1792 ELF_MACHINE_DEBUG_SETUP (main_map, r);
1793 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1794 #else
1795 if (main_map->l_info[DT_DEBUG] != NULL)
1796 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1797 with the run-time address of the r_debug structure */
1798 main_map->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1800 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1801 case you run gdb on the dynamic linker directly. */
1802 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1803 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1804 #endif
1806 /* We start adding objects. */
1807 r->r_state = RT_ADD;
1808 _dl_debug_state ();
1809 LIBC_PROBE (init_start, 2, LM_ID_BASE, r);
1811 /* Auditing checkpoint: we are ready to signal that the initial map
1812 is being constructed. */
1813 if (__glibc_unlikely (GLRO(dl_naudit) > 0))
1815 struct audit_ifaces *afct = GLRO(dl_audit);
1816 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1818 if (afct->activity != NULL)
1819 afct->activity (&link_map_audit_state (main_map, cnt)->cookie,
1820 LA_ACT_ADD);
1822 afct = afct->next;
1826 /* We have two ways to specify objects to preload: via environment
1827 variable and via the file /etc/ld.so.preload. The latter can also
1828 be used when security is enabled. */
1829 assert (*first_preload == NULL);
1830 struct link_map **preloads = NULL;
1831 unsigned int npreloads = 0;
1833 if (__glibc_unlikely (state.preloadlist != NULL))
1835 RTLD_TIMING_VAR (start);
1836 rtld_timer_start (&start);
1837 npreloads += handle_preload_list (state.preloadlist, main_map,
1838 "LD_PRELOAD");
1839 rtld_timer_accum (&load_time, start);
1842 if (__glibc_unlikely (state.preloadarg != NULL))
1844 RTLD_TIMING_VAR (start);
1845 rtld_timer_start (&start);
1846 npreloads += handle_preload_list (state.preloadarg, main_map,
1847 "--preload");
1848 rtld_timer_accum (&load_time, start);
1851 /* There usually is no ld.so.preload file, it should only be used
1852 for emergencies and testing. So the open call etc should usually
1853 fail. Using access() on a non-existing file is faster than using
1854 open(). So we do this first. If it succeeds we do almost twice
1855 the work but this does not matter, since it is not for production
1856 use. */
1857 static const char preload_file[] = "/etc/ld.so.preload";
1858 if (__glibc_unlikely (__access (preload_file, R_OK) == 0))
1860 /* Read the contents of the file. */
1861 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1862 PROT_READ | PROT_WRITE);
1863 if (__glibc_unlikely (file != MAP_FAILED))
1865 /* Parse the file. It contains names of libraries to be loaded,
1866 separated by white spaces or `:'. It may also contain
1867 comments introduced by `#'. */
1868 char *problem;
1869 char *runp;
1870 size_t rest;
1872 /* Eliminate comments. */
1873 runp = file;
1874 rest = file_size;
1875 while (rest > 0)
1877 char *comment = memchr (runp, '#', rest);
1878 if (comment == NULL)
1879 break;
1881 rest -= comment - runp;
1883 *comment = ' ';
1884 while (--rest > 0 && *++comment != '\n');
1887 /* We have one problematic case: if we have a name at the end of
1888 the file without a trailing terminating characters, we cannot
1889 place the \0. Handle the case separately. */
1890 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1891 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1893 problem = &file[file_size];
1894 while (problem > file && problem[-1] != ' '
1895 && problem[-1] != '\t'
1896 && problem[-1] != '\n' && problem[-1] != ':')
1897 --problem;
1899 if (problem > file)
1900 problem[-1] = '\0';
1902 else
1904 problem = NULL;
1905 file[file_size - 1] = '\0';
1908 RTLD_TIMING_VAR (start);
1909 rtld_timer_start (&start);
1911 if (file != problem)
1913 char *p;
1914 runp = file;
1915 while ((p = strsep (&runp, ": \t\n")) != NULL)
1916 if (p[0] != '\0')
1917 npreloads += do_preload (p, main_map, preload_file);
1920 if (problem != NULL)
1922 char *p = strndupa (problem, file_size - (problem - file));
1924 npreloads += do_preload (p, main_map, preload_file);
1927 rtld_timer_accum (&load_time, start);
1929 /* We don't need the file anymore. */
1930 __munmap (file, file_size);
1934 if (__glibc_unlikely (*first_preload != NULL))
1936 /* Set up PRELOADS with a vector of the preloaded libraries. */
1937 struct link_map *l = *first_preload;
1938 preloads = __alloca (npreloads * sizeof preloads[0]);
1939 i = 0;
1942 preloads[i++] = l;
1943 l = l->l_next;
1944 } while (l);
1945 assert (i == npreloads);
1948 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1949 specified some libraries to load, these are inserted before the actual
1950 dependencies in the executable's searchlist for symbol resolution. */
1952 RTLD_TIMING_VAR (start);
1953 rtld_timer_start (&start);
1954 _dl_map_object_deps (main_map, preloads, npreloads,
1955 state.mode == rtld_mode_trace, 0);
1956 rtld_timer_accum (&load_time, start);
1959 /* Mark all objects as being in the global scope. */
1960 for (i = main_map->l_searchlist.r_nlist; i > 0; )
1961 main_map->l_searchlist.r_list[--i]->l_global = 1;
1963 /* Remove _dl_rtld_map from the chain. */
1964 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1965 if (GL(dl_rtld_map).l_next != NULL)
1966 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1968 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1969 if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1970 break;
1972 bool rtld_multiple_ref = false;
1973 if (__glibc_likely (i < main_map->l_searchlist.r_nlist))
1975 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1976 put it back in the list of visible objects. We insert it into the
1977 chain in symbol search order because gdb uses the chain's order as
1978 its symbol search order. */
1979 rtld_multiple_ref = true;
1981 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1982 if (__glibc_likely (state.mode == rtld_mode_normal))
1984 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1985 ? main_map->l_searchlist.r_list[i + 1]
1986 : NULL);
1987 #ifdef NEED_DL_SYSINFO_DSO
1988 if (GLRO(dl_sysinfo_map) != NULL
1989 && GL(dl_rtld_map).l_prev->l_next == GLRO(dl_sysinfo_map)
1990 && GL(dl_rtld_map).l_next != GLRO(dl_sysinfo_map))
1991 GL(dl_rtld_map).l_prev = GLRO(dl_sysinfo_map);
1992 #endif
1994 else
1995 /* In trace mode there might be an invisible object (which we
1996 could not find) after the previous one in the search list.
1997 In this case it doesn't matter much where we put the
1998 interpreter object, so we just initialize the list pointer so
1999 that the assertion below holds. */
2000 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
2002 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
2003 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
2004 if (GL(dl_rtld_map).l_next != NULL)
2006 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
2007 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
2011 /* Now let us see whether all libraries are available in the
2012 versions we need. */
2014 struct version_check_args args;
2015 args.doexit = state.mode == rtld_mode_normal;
2016 args.dotrace = state.mode == rtld_mode_trace;
2017 _dl_receive_error (print_missing_version, version_check_doit, &args);
2020 /* We do not initialize any of the TLS functionality unless any of the
2021 initial modules uses TLS. This makes dynamic loading of modules with
2022 TLS impossible, but to support it requires either eagerly doing setup
2023 now or lazily doing it later. Doing it now makes us incompatible with
2024 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
2025 used. Trying to do it lazily is too hairy to try when there could be
2026 multiple threads (from a non-TLS-using libpthread). */
2027 bool was_tls_init_tp_called = tls_init_tp_called;
2028 if (tcbp == NULL)
2029 tcbp = init_tls (0);
2031 if (__glibc_likely (need_security_init))
2032 /* Initialize security features. But only if we have not done it
2033 earlier. */
2034 security_init ();
2036 if (__glibc_unlikely (state.mode != rtld_mode_normal))
2038 /* We were run just to list the shared libraries. It is
2039 important that we do this before real relocation, because the
2040 functions we call below for output may no longer work properly
2041 after relocation. */
2042 struct link_map *l;
2044 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
2046 struct r_scope_elem *scope = &main_map->l_searchlist;
2048 for (i = 0; i < scope->r_nlist; i++)
2050 l = scope->r_list [i];
2051 if (l->l_faked)
2053 _dl_printf ("\t%s => not found\n", l->l_libname->name);
2054 continue;
2056 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
2057 GLRO(dl_trace_prelink_map) = l;
2058 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
2059 DSO_FILENAME (l->l_libname->name),
2060 DSO_FILENAME (l->l_name),
2061 (int) sizeof l->l_map_start * 2,
2062 (size_t) l->l_map_start,
2063 (int) sizeof l->l_addr * 2,
2064 (size_t) l->l_addr);
2066 if (l->l_tls_modid)
2067 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
2068 (int) sizeof l->l_tls_offset * 2,
2069 (size_t) l->l_tls_offset);
2070 else
2071 _dl_printf ("\n");
2074 else if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
2076 /* Look through the dependencies of the main executable
2077 and determine which of them is not actually
2078 required. */
2079 struct link_map *l = main_map;
2081 /* Relocate the main executable. */
2082 struct relocate_args args = { .l = l,
2083 .reloc_mode = ((GLRO(dl_lazy)
2084 ? RTLD_LAZY : 0)
2085 | __RTLD_NOIFUNC) };
2086 _dl_receive_error (print_unresolved, relocate_doit, &args);
2088 /* This loop depends on the dependencies of the executable to
2089 correspond in number and order to the DT_NEEDED entries. */
2090 ElfW(Dyn) *dyn = main_map->l_ld;
2091 bool first = true;
2092 while (dyn->d_tag != DT_NULL)
2094 if (dyn->d_tag == DT_NEEDED)
2096 l = l->l_next;
2097 #ifdef NEED_DL_SYSINFO_DSO
2098 /* Skip the VDSO since it's not part of the list
2099 of objects we brought in via DT_NEEDED entries. */
2100 if (l == GLRO(dl_sysinfo_map))
2101 l = l->l_next;
2102 #endif
2103 if (!l->l_used)
2105 if (first)
2107 _dl_printf ("Unused direct dependencies:\n");
2108 first = false;
2111 _dl_printf ("\t%s\n", l->l_name);
2115 ++dyn;
2118 _exit (first != true);
2120 else if (! main_map->l_info[DT_NEEDED])
2121 _dl_printf ("\tstatically linked\n");
2122 else
2124 for (l = main_map->l_next; l; l = l->l_next)
2125 if (l->l_faked)
2126 /* The library was not found. */
2127 _dl_printf ("\t%s => not found\n", l->l_libname->name);
2128 else if (strcmp (l->l_libname->name, l->l_name) == 0)
2129 _dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
2130 (int) sizeof l->l_map_start * 2,
2131 (size_t) l->l_map_start);
2132 else
2133 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
2134 l->l_name, (int) sizeof l->l_map_start * 2,
2135 (size_t) l->l_map_start);
2138 if (__glibc_unlikely (state.mode != rtld_mode_trace))
2139 for (i = 1; i < (unsigned int) _dl_argc; ++i)
2141 const ElfW(Sym) *ref = NULL;
2142 ElfW(Addr) loadbase;
2143 lookup_t result;
2145 result = _dl_lookup_symbol_x (_dl_argv[i], main_map,
2146 &ref, main_map->l_scope,
2147 NULL, ELF_RTYPE_CLASS_PLT,
2148 DL_LOOKUP_ADD_DEPENDENCY, NULL);
2150 loadbase = LOOKUP_VALUE_ADDRESS (result, false);
2152 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
2153 _dl_argv[i],
2154 (int) sizeof ref->st_value * 2,
2155 (size_t) ref->st_value,
2156 (int) sizeof loadbase * 2, (size_t) loadbase);
2158 else
2160 /* If LD_WARN is set, warn about undefined symbols. */
2161 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
2163 /* We have to do symbol dependency testing. */
2164 struct relocate_args args;
2165 unsigned int i;
2167 args.reloc_mode = ((GLRO(dl_lazy) ? RTLD_LAZY : 0)
2168 | __RTLD_NOIFUNC);
2170 i = main_map->l_searchlist.r_nlist;
2171 while (i-- > 0)
2173 struct link_map *l = main_map->l_initfini[i];
2174 if (l != &GL(dl_rtld_map) && ! l->l_faked)
2176 args.l = l;
2177 _dl_receive_error (print_unresolved, relocate_doit,
2178 &args);
2182 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
2183 && rtld_multiple_ref)
2185 /* Mark the link map as not yet relocated again. */
2186 GL(dl_rtld_map).l_relocated = 0;
2187 _dl_relocate_object (&GL(dl_rtld_map),
2188 main_map->l_scope, __RTLD_NOIFUNC, 0);
2191 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
2192 if (state.version_info)
2194 /* Print more information. This means here, print information
2195 about the versions needed. */
2196 int first = 1;
2197 struct link_map *map;
2199 for (map = main_map; map != NULL; map = map->l_next)
2201 const char *strtab;
2202 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
2203 ElfW(Verneed) *ent;
2205 if (dyn == NULL)
2206 continue;
2208 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
2209 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
2211 if (first)
2213 _dl_printf ("\n\tVersion information:\n");
2214 first = 0;
2217 _dl_printf ("\t%s:\n", DSO_FILENAME (map->l_name));
2219 while (1)
2221 ElfW(Vernaux) *aux;
2222 struct link_map *needed;
2224 needed = find_needed (strtab + ent->vn_file);
2225 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
2227 while (1)
2229 const char *fname = NULL;
2231 if (needed != NULL
2232 && match_version (strtab + aux->vna_name,
2233 needed))
2234 fname = needed->l_name;
2236 _dl_printf ("\t\t%s (%s) %s=> %s\n",
2237 strtab + ent->vn_file,
2238 strtab + aux->vna_name,
2239 aux->vna_flags & VER_FLG_WEAK
2240 ? "[WEAK] " : "",
2241 fname ?: "not found");
2243 if (aux->vna_next == 0)
2244 /* No more symbols. */
2245 break;
2247 /* Next symbol. */
2248 aux = (ElfW(Vernaux) *) ((char *) aux
2249 + aux->vna_next);
2252 if (ent->vn_next == 0)
2253 /* No more dependencies. */
2254 break;
2256 /* Next dependency. */
2257 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
2263 _exit (0);
2266 if (main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]
2267 && ! __builtin_expect (GLRO(dl_profile) != NULL, 0)
2268 && ! __builtin_expect (GLRO(dl_dynamic_weak), 0))
2270 ElfW(Lib) *liblist, *liblistend;
2271 struct link_map **r_list, **r_listend, *l;
2272 const char *strtab = (const void *) D_PTR (main_map, l_info[DT_STRTAB]);
2274 assert (main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
2275 liblist = (ElfW(Lib) *)
2276 main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
2277 liblistend = (ElfW(Lib) *)
2278 ((char *) liblist
2279 + main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
2280 r_list = main_map->l_searchlist.r_list;
2281 r_listend = r_list + main_map->l_searchlist.r_nlist;
2283 for (; r_list < r_listend && liblist < liblistend; r_list++)
2285 l = *r_list;
2287 if (l == main_map)
2288 continue;
2290 /* If the library is not mapped where it should, fail. */
2291 if (l->l_addr)
2292 break;
2294 /* Next, check if checksum matches. */
2295 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
2296 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
2297 != liblist->l_checksum)
2298 break;
2300 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
2301 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
2302 != liblist->l_time_stamp)
2303 break;
2305 if (! _dl_name_match_p (strtab + liblist->l_name, l))
2306 break;
2308 ++liblist;
2312 if (r_list == r_listend && liblist == liblistend)
2313 prelinked = true;
2315 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_LIBS))
2316 _dl_debug_printf ("\nprelink checking: %s\n",
2317 prelinked ? "ok" : "failed");
2321 /* Now set up the variable which helps the assembler startup code. */
2322 GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
2324 /* Save the information about the original global scope list since
2325 we need it in the memory handling later. */
2326 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
2328 /* Remember the last search directory added at startup, now that
2329 malloc will no longer be the one from dl-minimal.c. As a side
2330 effect, this marks ld.so as initialized, so that the rtld_active
2331 function returns true from now on. */
2332 GLRO(dl_init_all_dirs) = GL(dl_all_dirs);
2334 /* Print scope information. */
2335 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_SCOPES))
2337 _dl_debug_printf ("\nInitial object scopes\n");
2339 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2340 _dl_show_scope (l, 0);
2343 _rtld_main_check (main_map, _dl_argv[0]);
2345 if (prelinked)
2347 if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
2349 ElfW(Rela) *conflict, *conflictend;
2351 RTLD_TIMING_VAR (start);
2352 rtld_timer_start (&start);
2354 assert (main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
2355 conflict = (ElfW(Rela) *)
2356 main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
2357 conflictend = (ElfW(Rela) *)
2358 ((char *) conflict
2359 + main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
2360 _dl_resolve_conflicts (main_map, conflict, conflictend);
2362 rtld_timer_stop (&relocate_time, start);
2365 /* The library defining malloc has already been relocated due to
2366 prelinking. Resolve the malloc symbols for the dynamic
2367 loader. */
2368 __rtld_malloc_init_real (main_map);
2370 /* Mark all the objects so we know they have been already relocated. */
2371 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2373 l->l_relocated = 1;
2374 if (l->l_relro_size)
2375 _dl_protect_relro (l);
2377 /* Add object to slot information data if necessasy. */
2378 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2379 _dl_add_to_slotinfo (l, true);
2382 else
2384 /* Now we have all the objects loaded. Relocate them all except for
2385 the dynamic linker itself. We do this in reverse order so that copy
2386 relocs of earlier objects overwrite the data written by later
2387 objects. We do not re-relocate the dynamic linker itself in this
2388 loop because that could result in the GOT entries for functions we
2389 call being changed, and that would break us. It is safe to relocate
2390 the dynamic linker out of order because it has no copy relocs (we
2391 know that because it is self-contained). */
2393 int consider_profiling = GLRO(dl_profile) != NULL;
2395 /* If we are profiling we also must do lazy reloaction. */
2396 GLRO(dl_lazy) |= consider_profiling;
2398 RTLD_TIMING_VAR (start);
2399 rtld_timer_start (&start);
2400 unsigned i = main_map->l_searchlist.r_nlist;
2401 while (i-- > 0)
2403 struct link_map *l = main_map->l_initfini[i];
2405 /* While we are at it, help the memory handling a bit. We have to
2406 mark some data structures as allocated with the fake malloc()
2407 implementation in ld.so. */
2408 struct libname_list *lnp = l->l_libname->next;
2410 while (__builtin_expect (lnp != NULL, 0))
2412 lnp->dont_free = 1;
2413 lnp = lnp->next;
2415 /* Also allocated with the fake malloc(). */
2416 l->l_free_initfini = 0;
2418 if (l != &GL(dl_rtld_map))
2419 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy) ? RTLD_LAZY : 0,
2420 consider_profiling);
2422 /* Add object to slot information data if necessasy. */
2423 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2424 _dl_add_to_slotinfo (l, true);
2426 rtld_timer_stop (&relocate_time, start);
2428 /* Now enable profiling if needed. Like the previous call,
2429 this has to go here because the calls it makes should use the
2430 rtld versions of the functions (particularly calloc()), but it
2431 needs to have _dl_profile_map set up by the relocator. */
2432 if (__glibc_unlikely (GL(dl_profile_map) != NULL))
2433 /* We must prepare the profiling. */
2434 _dl_start_profile ();
2437 if ((!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2438 || count_modids != _dl_count_modids ())
2439 ++GL(dl_tls_generation);
2441 /* Now that we have completed relocation, the initializer data
2442 for the TLS blocks has its final values and we can copy them
2443 into the main thread's TLS area, which we allocated above.
2444 Note: thread-local variables must only be accessed after completing
2445 the next step. */
2446 _dl_allocate_tls_init (tcbp);
2448 /* And finally install it for the main thread. */
2449 if (! tls_init_tp_called)
2451 const char *lossage = TLS_INIT_TP (tcbp);
2452 if (__glibc_unlikely (lossage != NULL))
2453 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2454 lossage);
2455 #if THREAD_GSCOPE_IN_TCB
2456 list_add (&THREAD_SELF->list, &GL (dl_stack_user));
2457 #endif
2460 /* Make sure no new search directories have been added. */
2461 assert (GLRO(dl_init_all_dirs) == GL(dl_all_dirs));
2463 if (! prelinked && rtld_multiple_ref)
2465 /* There was an explicit ref to the dynamic linker as a shared lib.
2466 Re-relocate ourselves with user-controlled symbol definitions.
2468 We must do this after TLS initialization in case after this
2469 re-relocation, we might call a user-supplied function
2470 (e.g. calloc from _dl_relocate_object) that uses TLS data. */
2472 /* The malloc implementation has been relocated, so resolving
2473 its symbols (and potentially calling IFUNC resolvers) is safe
2474 at this point. */
2475 __rtld_malloc_init_real (main_map);
2477 RTLD_TIMING_VAR (start);
2478 rtld_timer_start (&start);
2480 /* Mark the link map as not yet relocated again. */
2481 GL(dl_rtld_map).l_relocated = 0;
2482 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2484 rtld_timer_accum (&relocate_time, start);
2487 /* Relocation is complete. Perform early libc initialization. This
2488 is the initial libc, even if audit modules have been loaded with
2489 other libcs. */
2490 _dl_call_libc_early_init (GL(dl_ns)[LM_ID_BASE].libc_map, true);
2492 /* Do any necessary cleanups for the startup OS interface code.
2493 We do these now so that no calls are made after rtld re-relocation
2494 which might be resolved to different functions than we expect.
2495 We cannot do this before relocating the other objects because
2496 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2497 _dl_sysdep_start_cleanup ();
2499 #ifdef SHARED
2500 /* Auditing checkpoint: we have added all objects. */
2501 if (__glibc_unlikely (GLRO(dl_naudit) > 0))
2503 struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2504 /* Do not call the functions for any auditing object. */
2505 if (head->l_auditing == 0)
2507 struct audit_ifaces *afct = GLRO(dl_audit);
2508 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2510 if (afct->activity != NULL)
2511 afct->activity (&link_map_audit_state (head, cnt)->cookie,
2512 LA_ACT_CONSISTENT);
2514 afct = afct->next;
2518 #endif
2520 /* Notify the debugger all new objects are now ready to go. We must re-get
2521 the address since by now the variable might be in another object. */
2522 r = _dl_debug_initialize (0, LM_ID_BASE);
2523 r->r_state = RT_CONSISTENT;
2524 _dl_debug_state ();
2525 LIBC_PROBE (init_complete, 2, LM_ID_BASE, r);
2527 #if defined USE_LDCONFIG && !defined MAP_COPY
2528 /* We must munmap() the cache file. */
2529 _dl_unload_cache ();
2530 #endif
2532 /* Once we return, _dl_sysdep_start will invoke
2533 the DT_INIT functions and then *USER_ENTRY. */
2536 /* This is a little helper function for resolving symbols while
2537 tracing the binary. */
2538 static void
2539 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2540 const char *errstring)
2542 if (objname[0] == '\0')
2543 objname = RTLD_PROGNAME;
2544 _dl_error_printf ("%s (%s)\n", errstring, objname);
2547 /* This is a little helper function for resolving symbols while
2548 tracing the binary. */
2549 static void
2550 print_missing_version (int errcode __attribute__ ((unused)),
2551 const char *objname, const char *errstring)
2553 _dl_error_printf ("%s: %s: %s\n", RTLD_PROGNAME,
2554 objname, errstring);
2557 /* Process the string given as the parameter which explains which debugging
2558 options are enabled. */
2559 static void
2560 process_dl_debug (struct dl_main_state *state, const char *dl_debug)
2562 /* When adding new entries make sure that the maximal length of a name
2563 is correctly handled in the LD_DEBUG_HELP code below. */
2564 static const struct
2566 unsigned char len;
2567 const char name[10];
2568 const char helptext[41];
2569 unsigned short int mask;
2570 } debopts[] =
2572 #define LEN_AND_STR(str) sizeof (str) - 1, str
2573 { LEN_AND_STR ("libs"), "display library search paths",
2574 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2575 { LEN_AND_STR ("reloc"), "display relocation processing",
2576 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2577 { LEN_AND_STR ("files"), "display progress for input file",
2578 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2579 { LEN_AND_STR ("symbols"), "display symbol table processing",
2580 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2581 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2582 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2583 { LEN_AND_STR ("versions"), "display version dependencies",
2584 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2585 { LEN_AND_STR ("scopes"), "display scope information",
2586 DL_DEBUG_SCOPES },
2587 { LEN_AND_STR ("all"), "all previous options combined",
2588 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2589 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS
2590 | DL_DEBUG_SCOPES },
2591 { LEN_AND_STR ("statistics"), "display relocation statistics",
2592 DL_DEBUG_STATISTICS },
2593 { LEN_AND_STR ("unused"), "determined unused DSOs",
2594 DL_DEBUG_UNUSED },
2595 { LEN_AND_STR ("help"), "display this help message and exit",
2596 DL_DEBUG_HELP },
2598 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2600 /* Skip separating white spaces and commas. */
2601 while (*dl_debug != '\0')
2603 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2605 size_t cnt;
2606 size_t len = 1;
2608 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2609 && dl_debug[len] != ',' && dl_debug[len] != ':')
2610 ++len;
2612 for (cnt = 0; cnt < ndebopts; ++cnt)
2613 if (debopts[cnt].len == len
2614 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
2616 GLRO(dl_debug_mask) |= debopts[cnt].mask;
2617 state->any_debug = true;
2618 break;
2621 if (cnt == ndebopts)
2623 /* Display a warning and skip everything until next
2624 separator. */
2625 char *copy = strndupa (dl_debug, len);
2626 _dl_error_printf ("\
2627 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2630 dl_debug += len;
2631 continue;
2634 ++dl_debug;
2637 if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
2639 /* In order to get an accurate picture of whether a particular
2640 DT_NEEDED entry is actually used we have to process both
2641 the PLT and non-PLT relocation entries. */
2642 GLRO(dl_lazy) = 0;
2645 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
2647 size_t cnt;
2649 _dl_printf ("\
2650 Valid options for the LD_DEBUG environment variable are:\n\n");
2652 for (cnt = 0; cnt < ndebopts; ++cnt)
2653 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2654 " " + debopts[cnt].len - 3,
2655 debopts[cnt].helptext);
2657 _dl_printf ("\n\
2658 To direct the debugging output into a file instead of standard output\n\
2659 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2660 _exit (0);
2664 static void
2665 process_envvars (struct dl_main_state *state)
2667 char **runp = _environ;
2668 char *envline;
2669 char *debug_output = NULL;
2671 /* This is the default place for profiling data file. */
2672 GLRO(dl_profile_output)
2673 = &"/var/tmp\0/var/profile"[__libc_enable_secure ? 9 : 0];
2675 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2677 size_t len = 0;
2679 while (envline[len] != '\0' && envline[len] != '=')
2680 ++len;
2682 if (envline[len] != '=')
2683 /* This is a "LD_" variable at the end of the string without
2684 a '=' character. Ignore it since otherwise we will access
2685 invalid memory below. */
2686 continue;
2688 switch (len)
2690 case 4:
2691 /* Warning level, verbose or not. */
2692 if (memcmp (envline, "WARN", 4) == 0)
2693 GLRO(dl_verbose) = envline[5] != '\0';
2694 break;
2696 case 5:
2697 /* Debugging of the dynamic linker? */
2698 if (memcmp (envline, "DEBUG", 5) == 0)
2700 process_dl_debug (state, &envline[6]);
2701 break;
2703 if (memcmp (envline, "AUDIT", 5) == 0)
2704 audit_list_add_string (&state->audit_list, &envline[6]);
2705 break;
2707 case 7:
2708 /* Print information about versions. */
2709 if (memcmp (envline, "VERBOSE", 7) == 0)
2711 state->version_info = envline[8] != '\0';
2712 break;
2715 /* List of objects to be preloaded. */
2716 if (memcmp (envline, "PRELOAD", 7) == 0)
2718 state->preloadlist = &envline[8];
2719 break;
2722 /* Which shared object shall be profiled. */
2723 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2724 GLRO(dl_profile) = &envline[8];
2725 break;
2727 case 8:
2728 /* Do we bind early? */
2729 if (memcmp (envline, "BIND_NOW", 8) == 0)
2731 GLRO(dl_lazy) = envline[9] == '\0';
2732 break;
2734 if (memcmp (envline, "BIND_NOT", 8) == 0)
2735 GLRO(dl_bind_not) = envline[9] != '\0';
2736 break;
2738 case 9:
2739 /* Test whether we want to see the content of the auxiliary
2740 array passed up from the kernel. */
2741 if (!__libc_enable_secure
2742 && memcmp (envline, "SHOW_AUXV", 9) == 0)
2743 _dl_show_auxv ();
2744 break;
2746 #if !HAVE_TUNABLES
2747 case 10:
2748 /* Mask for the important hardware capabilities. */
2749 if (!__libc_enable_secure
2750 && memcmp (envline, "HWCAP_MASK", 10) == 0)
2751 GLRO(dl_hwcap_mask) = _dl_strtoul (&envline[11], NULL);
2752 break;
2753 #endif
2755 case 11:
2756 /* Path where the binary is found. */
2757 if (!__libc_enable_secure
2758 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2759 GLRO(dl_origin_path) = &envline[12];
2760 break;
2762 case 12:
2763 /* The library search path. */
2764 if (!__libc_enable_secure
2765 && memcmp (envline, "LIBRARY_PATH", 12) == 0)
2767 state->library_path = &envline[13];
2768 state->library_path_source = "LD_LIBRARY_PATH";
2769 break;
2772 /* Where to place the profiling data file. */
2773 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2775 debug_output = &envline[13];
2776 break;
2779 if (!__libc_enable_secure
2780 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2781 GLRO(dl_dynamic_weak) = 1;
2782 break;
2784 case 13:
2785 /* We might have some extra environment variable with length 13
2786 to handle. */
2787 #ifdef EXTRA_LD_ENVVARS_13
2788 EXTRA_LD_ENVVARS_13
2789 #endif
2790 if (!__libc_enable_secure
2791 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2793 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2794 break;
2796 break;
2798 case 14:
2799 /* Where to place the profiling data file. */
2800 if (!__libc_enable_secure
2801 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2802 && envline[15] != '\0')
2803 GLRO(dl_profile_output) = &envline[15];
2804 break;
2806 case 16:
2807 /* The mode of the dynamic linker can be set. */
2808 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2810 state->mode = rtld_mode_trace;
2811 GLRO(dl_verbose) = 1;
2812 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2813 GLRO(dl_trace_prelink) = &envline[17];
2815 break;
2817 case 20:
2818 /* The mode of the dynamic linker can be set. */
2819 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2820 state->mode = rtld_mode_trace;
2821 break;
2823 /* We might have some extra environment variable to handle. This
2824 is tricky due to the pre-processing of the length of the name
2825 in the switch statement here. The code here assumes that added
2826 environment variables have a different length. */
2827 #ifdef EXTRA_LD_ENVVARS
2828 EXTRA_LD_ENVVARS
2829 #endif
2833 /* Extra security for SUID binaries. Remove all dangerous environment
2834 variables. */
2835 if (__builtin_expect (__libc_enable_secure, 0))
2837 static const char unsecure_envvars[] =
2838 #ifdef EXTRA_UNSECURE_ENVVARS
2839 EXTRA_UNSECURE_ENVVARS
2840 #endif
2841 UNSECURE_ENVVARS;
2842 const char *nextp;
2844 nextp = unsecure_envvars;
2847 unsetenv (nextp);
2848 /* We could use rawmemchr but this need not be fast. */
2849 nextp = (char *) (strchr) (nextp, '\0') + 1;
2851 while (*nextp != '\0');
2853 if (__access ("/etc/suid-debug", F_OK) != 0)
2855 #if !HAVE_TUNABLES
2856 unsetenv ("MALLOC_CHECK_");
2857 #endif
2858 GLRO(dl_debug_mask) = 0;
2861 if (state->mode != rtld_mode_normal)
2862 _exit (5);
2864 /* If we have to run the dynamic linker in debugging mode and the
2865 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2866 messages to this file. */
2867 else if (state->any_debug && debug_output != NULL)
2869 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2870 size_t name_len = strlen (debug_output);
2871 char buf[name_len + 12];
2872 char *startp;
2874 buf[name_len + 11] = '\0';
2875 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2876 *--startp = '.';
2877 startp = memcpy (startp - name_len, debug_output, name_len);
2879 GLRO(dl_debug_fd) = __open64_nocancel (startp, flags, DEFFILEMODE);
2880 if (GLRO(dl_debug_fd) == -1)
2881 /* We use standard output if opening the file failed. */
2882 GLRO(dl_debug_fd) = STDOUT_FILENO;
2886 #if HP_TIMING_INLINE
2887 static void
2888 print_statistics_item (const char *title, hp_timing_t time,
2889 hp_timing_t total)
2891 char cycles[HP_TIMING_PRINT_SIZE];
2892 HP_TIMING_PRINT (cycles, sizeof (cycles), time);
2894 char relative[3 * sizeof (hp_timing_t) + 2];
2895 char *cp = _itoa ((1000ULL * time) / total, relative + sizeof (relative),
2896 10, 0);
2897 /* Sets the decimal point. */
2898 char *wp = relative;
2899 switch (relative + sizeof (relative) - cp)
2901 case 3:
2902 *wp++ = *cp++;
2903 /* Fall through. */
2904 case 2:
2905 *wp++ = *cp++;
2906 /* Fall through. */
2907 case 1:
2908 *wp++ = '.';
2909 *wp++ = *cp++;
2911 *wp = '\0';
2912 _dl_debug_printf ("%s: %s cycles (%s%%)\n", title, cycles, relative);
2914 #endif
2916 /* Print the various times we collected. */
2917 static void
2918 __attribute ((noinline))
2919 print_statistics (const hp_timing_t *rtld_total_timep)
2921 #if HP_TIMING_INLINE
2923 char cycles[HP_TIMING_PRINT_SIZE];
2924 HP_TIMING_PRINT (cycles, sizeof (cycles), *rtld_total_timep);
2925 _dl_debug_printf ("\nruntime linker statistics:\n"
2926 " total startup time in dynamic loader: %s cycles\n",
2927 cycles);
2928 print_statistics_item (" time needed for relocation",
2929 relocate_time, *rtld_total_timep);
2931 #endif
2933 unsigned long int num_relative_relocations = 0;
2934 for (Lmid_t ns = 0; ns < GL(dl_nns); ++ns)
2936 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2937 continue;
2939 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2941 for (unsigned int i = 0; i < scope->r_nlist; i++)
2943 struct link_map *l = scope->r_list [i];
2945 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2946 num_relative_relocations
2947 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2948 #ifndef ELF_MACHINE_REL_RELATIVE
2949 /* Relative relocations are processed on these architectures if
2950 library is loaded to different address than p_vaddr or
2951 if not prelinked. */
2952 if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2953 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2954 #else
2955 /* On e.g. IA-64 or Alpha, relative relocations are processed
2956 only if library is loaded to different address than p_vaddr. */
2957 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2958 #endif
2959 num_relative_relocations
2960 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2964 _dl_debug_printf (" number of relocations: %lu\n"
2965 " number of relocations from cache: %lu\n"
2966 " number of relative relocations: %lu\n",
2967 GL(dl_num_relocations),
2968 GL(dl_num_cache_relocations),
2969 num_relative_relocations);
2971 #if HP_TIMING_INLINE
2972 print_statistics_item (" time needed to load objects",
2973 load_time, *rtld_total_timep);
2974 #endif