posix/glob.c: update from gnulib
[glibc.git] / elf / rtld.c
blobbe6daa1c4432f379a77e19fd76a13e491fe6de75
1 /* Run time dynamic linker.
2 Copyright (C) 1995-2022 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 <dl-librecon.h>
36 #include <unsecvars.h>
37 #include <dl-cache.h>
38 #include <dl-osinfo.h>
39 #include <dl-procinfo.h>
40 #include <dl-prop.h>
41 #include <dl-vdso.h>
42 #include <dl-vdso-setup.h>
43 #include <tls.h>
44 #include <stap-probe.h>
45 #include <stackinfo.h>
46 #include <not-cancel.h>
47 #include <array_length.h>
48 #include <libc-early-init.h>
49 #include <dl-main.h>
50 #include <gnu/lib-names.h>
51 #include <dl-tunables.h>
52 #include <get-dynamic-info.h>
53 #include <dl-execve.h>
54 #include <dl-find_object.h>
55 #include <dl-audit-check.h>
57 #include <assert.h>
59 /* This #define produces dynamic linking inline functions for
60 bootstrap relocation instead of general-purpose relocation.
61 Since ld.so must not have any undefined symbols the result
62 is trivial: always the map of ld.so itself. */
63 #define RTLD_BOOTSTRAP
64 #define RESOLVE_MAP(map, scope, sym, version, flags) map
65 #include "dynamic-link.h"
67 /* Must include after <dl-machine.h> for DT_MIPS definition. */
68 #include <dl-debug.h>
70 /* Only enables rtld profiling for architectures which provides non generic
71 hp-timing support. The generic support requires either syscall
72 (clock_gettime), which will incur in extra overhead on loading time.
73 Using vDSO is also an option, but it will require extra support on loader
74 to setup the vDSO pointer before its usage. */
75 #if HP_TIMING_INLINE
76 # define RLTD_TIMING_DECLARE(var, classifier,...) \
77 classifier hp_timing_t var __VA_ARGS__
78 # define RTLD_TIMING_VAR(var) RLTD_TIMING_DECLARE (var, )
79 # define RTLD_TIMING_SET(var, value) (var) = (value)
80 # define RTLD_TIMING_REF(var) &(var)
82 static inline void
83 rtld_timer_start (hp_timing_t *var)
85 HP_TIMING_NOW (*var);
88 static inline void
89 rtld_timer_stop (hp_timing_t *var, hp_timing_t start)
91 hp_timing_t stop;
92 HP_TIMING_NOW (stop);
93 HP_TIMING_DIFF (*var, start, stop);
96 static inline void
97 rtld_timer_accum (hp_timing_t *sum, hp_timing_t start)
99 hp_timing_t stop;
100 rtld_timer_stop (&stop, start);
101 HP_TIMING_ACCUM_NT(*sum, stop);
103 #else
104 # define RLTD_TIMING_DECLARE(var, classifier...)
105 # define RTLD_TIMING_SET(var, value)
106 # define RTLD_TIMING_VAR(var)
107 # define RTLD_TIMING_REF(var) 0
108 # define rtld_timer_start(var)
109 # define rtld_timer_stop(var, start)
110 # define rtld_timer_accum(sum, start)
111 #endif
113 /* Avoid PLT use for our local calls at startup. */
114 extern __typeof (__mempcpy) __mempcpy attribute_hidden;
116 /* GCC has mental blocks about _exit. */
117 extern __typeof (_exit) exit_internal asm ("_exit") attribute_hidden;
118 #define _exit exit_internal
120 /* Helper function to handle errors while resolving symbols. */
121 static void print_unresolved (int errcode, const char *objname,
122 const char *errsting);
124 /* Helper function to handle errors when a version is missing. */
125 static void print_missing_version (int errcode, const char *objname,
126 const char *errsting);
128 /* Print the various times we collected. */
129 static void print_statistics (const hp_timing_t *total_timep);
131 /* Creates an empty audit list. */
132 static void audit_list_init (struct audit_list *);
134 /* Add a string to the end of the audit list, for later parsing. Must
135 not be called after audit_list_next. */
136 static void audit_list_add_string (struct audit_list *, const char *);
138 /* Add the audit strings from the link map, found in the dynamic
139 segment at TG (either DT_AUDIT and DT_DEPAUDIT). Must be called
140 before audit_list_next. */
141 static void audit_list_add_dynamic_tag (struct audit_list *,
142 struct link_map *,
143 unsigned int tag);
145 /* Extract the next audit module from the audit list. Only modules
146 for which dso_name_valid_for_suid is true are returned. Must be
147 called after all the audit_list_add_string,
148 audit_list_add_dynamic_tags calls. */
149 static const char *audit_list_next (struct audit_list *);
151 /* Initialize *STATE with the defaults. */
152 static void dl_main_state_init (struct dl_main_state *state);
154 /* Process all environments variables the dynamic linker must recognize.
155 Since all of them start with `LD_' we are a bit smarter while finding
156 all the entries. */
157 extern char **_environ attribute_hidden;
158 static void process_envvars (struct dl_main_state *state);
160 #ifdef DL_ARGV_NOT_RELRO
161 int _dl_argc attribute_hidden;
162 char **_dl_argv = NULL;
163 /* Nonzero if we were run directly. */
164 unsigned int _dl_skip_args attribute_hidden;
165 #else
166 int _dl_argc attribute_relro attribute_hidden;
167 char **_dl_argv attribute_relro = NULL;
168 unsigned int _dl_skip_args attribute_relro attribute_hidden;
169 #endif
170 rtld_hidden_data_def (_dl_argv)
172 #ifndef THREAD_SET_STACK_GUARD
173 /* Only exported for architectures that don't store the stack guard canary
174 in thread local area. */
175 uintptr_t __stack_chk_guard attribute_relro;
176 #endif
178 /* Only exported for architectures that don't store the pointer guard
179 value in thread local area. */
180 uintptr_t __pointer_chk_guard_local attribute_relro attribute_hidden;
181 #ifndef THREAD_SET_POINTER_GUARD
182 strong_alias (__pointer_chk_guard_local, __pointer_chk_guard)
183 #endif
185 /* Check that AT_SECURE=0, or that the passed name does not contain
186 directories and is not overly long. Reject empty names
187 unconditionally. */
188 static bool
189 dso_name_valid_for_suid (const char *p)
191 if (__glibc_unlikely (__libc_enable_secure))
193 /* Ignore pathnames with directories for AT_SECURE=1
194 programs, and also skip overlong names. */
195 size_t len = strlen (p);
196 if (len >= SECURE_NAME_LIMIT || memchr (p, '/', len) != NULL)
197 return false;
199 return *p != '\0';
202 static void
203 audit_list_init (struct audit_list *list)
205 list->length = 0;
206 list->current_index = 0;
207 list->current_tail = NULL;
210 static void
211 audit_list_add_string (struct audit_list *list, const char *string)
213 /* Empty strings do not load anything. */
214 if (*string == '\0')
215 return;
217 if (list->length == array_length (list->audit_strings))
218 _dl_fatal_printf ("Fatal glibc error: Too many audit modules requested\n");
220 list->audit_strings[list->length++] = string;
222 /* Initialize processing of the first string for
223 audit_list_next. */
224 if (list->length == 1)
225 list->current_tail = string;
228 static void
229 audit_list_add_dynamic_tag (struct audit_list *list, struct link_map *main_map,
230 unsigned int tag)
232 ElfW(Dyn) *info = main_map->l_info[ADDRIDX (tag)];
233 const char *strtab = (const char *) D_PTR (main_map, l_info[DT_STRTAB]);
234 if (info != NULL)
235 audit_list_add_string (list, strtab + info->d_un.d_val);
238 static const char *
239 audit_list_next (struct audit_list *list)
241 if (list->current_tail == NULL)
242 return NULL;
244 while (true)
246 /* Advance to the next string in audit_strings if the current
247 string has been exhausted. */
248 while (*list->current_tail == '\0')
250 ++list->current_index;
251 if (list->current_index == list->length)
253 list->current_tail = NULL;
254 return NULL;
256 list->current_tail = list->audit_strings[list->current_index];
259 /* Split the in-string audit list at the next colon colon. */
260 size_t len = strcspn (list->current_tail, ":");
261 if (len > 0 && len < sizeof (list->fname))
263 memcpy (list->fname, list->current_tail, len);
264 list->fname[len] = '\0';
266 else
267 /* Mark the name as unusable for dso_name_valid_for_suid. */
268 list->fname[0] = '\0';
270 /* Skip over the substring and the following delimiter. */
271 list->current_tail += len;
272 if (*list->current_tail == ':')
273 ++list->current_tail;
275 /* If the name is valid, return it. */
276 if (dso_name_valid_for_suid (list->fname))
277 return list->fname;
279 /* Otherwise wrap around to find the next list element. . */
283 /* Count audit modules before they are loaded so GLRO(dl_naudit)
284 is not yet usable. */
285 static size_t
286 audit_list_count (struct audit_list *list)
288 /* Restore the audit_list iterator state at the end. */
289 const char *saved_tail = list->current_tail;
290 size_t naudit = 0;
292 assert (list->current_index == 0);
293 while (audit_list_next (list) != NULL)
294 naudit++;
295 list->current_tail = saved_tail;
296 list->current_index = 0;
297 return naudit;
300 static void
301 dl_main_state_init (struct dl_main_state *state)
303 audit_list_init (&state->audit_list);
304 state->library_path = NULL;
305 state->library_path_source = NULL;
306 state->preloadlist = NULL;
307 state->preloadarg = NULL;
308 state->glibc_hwcaps_prepend = NULL;
309 state->glibc_hwcaps_mask = NULL;
310 state->mode = rtld_mode_normal;
311 state->any_debug = false;
312 state->version_info = false;
315 #ifndef HAVE_INLINED_SYSCALLS
316 /* Set nonzero during loading and initialization of executable and
317 libraries, cleared before the executable's entry point runs. This
318 must not be initialized to nonzero, because the unused dynamic
319 linker loaded in for libc.so's "ld.so.1" dep will provide the
320 definition seen by libc.so's initializer; that value must be zero,
321 and will be since that dynamic linker's _dl_start and dl_main will
322 never be called. */
323 int _dl_starting_up = 0;
324 rtld_hidden_def (_dl_starting_up)
325 #endif
327 /* This is the structure which defines all variables global to ld.so
328 (except those which cannot be added for some reason). */
329 struct rtld_global _rtld_global =
331 /* Get architecture specific initializer. */
332 #include <dl-procruntime.c>
333 /* Generally the default presumption without further information is an
334 * executable stack but this is not true for all platforms. */
335 ._dl_stack_flags = DEFAULT_STACK_PERMS,
336 #ifdef _LIBC_REENTRANT
337 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
338 ._dl_load_write_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
339 ._dl_load_tls_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
340 #endif
341 ._dl_nns = 1,
342 ._dl_ns =
344 #ifdef _LIBC_REENTRANT
345 [LM_ID_BASE] = { ._ns_unique_sym_table
346 = { .lock = _RTLD_LOCK_RECURSIVE_INITIALIZER } }
347 #endif
350 /* If we would use strong_alias here the compiler would see a
351 non-hidden definition. This would undo the effect of the previous
352 declaration. So spell out what strong_alias does plus add the
353 visibility attribute. */
354 extern struct rtld_global _rtld_local
355 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
358 /* This variable is similar to _rtld_local, but all values are
359 read-only after relocation. */
360 struct rtld_global_ro _rtld_global_ro attribute_relro =
362 /* Get architecture specific initializer. */
363 #include <dl-procinfo.c>
364 #ifdef NEED_DL_SYSINFO
365 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
366 #endif
367 ._dl_debug_fd = STDERR_FILENO,
368 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
369 #if !HAVE_TUNABLES
370 ._dl_hwcap_mask = HWCAP_IMPORTANT,
371 #endif
372 ._dl_lazy = 1,
373 ._dl_fpu_control = _FPU_DEFAULT,
374 ._dl_pagesize = EXEC_PAGESIZE,
375 ._dl_inhibit_cache = 0,
377 /* Function pointers. */
378 ._dl_debug_printf = _dl_debug_printf,
379 ._dl_mcount = _dl_mcount,
380 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
381 ._dl_open = _dl_open,
382 ._dl_close = _dl_close,
383 ._dl_catch_error = _rtld_catch_error,
384 ._dl_error_free = _dl_error_free,
385 ._dl_tls_get_addr_soft = _dl_tls_get_addr_soft,
386 ._dl_libc_freeres = __rtld_libc_freeres,
387 #ifdef HAVE_DL_DISCOVER_OSVERSION
388 ._dl_discover_osversion = _dl_discover_osversion
389 #endif
391 /* If we would use strong_alias here the compiler would see a
392 non-hidden definition. This would undo the effect of the previous
393 declaration. So spell out was strong_alias does plus add the
394 visibility attribute. */
395 extern struct rtld_global_ro _rtld_local_ro
396 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
399 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
400 ElfW(Addr) *user_entry, ElfW(auxv_t) *auxv);
402 /* These two variables cannot be moved into .data.rel.ro. */
403 static struct libname_list _dl_rtld_libname;
404 static struct libname_list _dl_rtld_libname2;
406 /* Variable for statistics. */
407 RLTD_TIMING_DECLARE (relocate_time, static);
408 RLTD_TIMING_DECLARE (load_time, static, attribute_relro);
409 RLTD_TIMING_DECLARE (start_time, static, attribute_relro);
411 /* Additional definitions needed by TLS initialization. */
412 #ifdef TLS_INIT_HELPER
413 TLS_INIT_HELPER
414 #endif
416 /* Helper function for syscall implementation. */
417 #ifdef DL_SYSINFO_IMPLEMENTATION
418 DL_SYSINFO_IMPLEMENTATION
419 #endif
421 /* Before ld.so is relocated we must not access variables which need
422 relocations. This means variables which are exported. Variables
423 declared as static are fine. If we can mark a variable hidden this
424 is fine, too. The latter is important here. We can avoid setting
425 up a temporary link map for ld.so if we can mark _rtld_global as
426 hidden. */
427 #ifndef HIDDEN_VAR_NEEDS_DYNAMIC_RELOC
428 # define DONT_USE_BOOTSTRAP_MAP 1
429 #endif
431 #ifdef DONT_USE_BOOTSTRAP_MAP
432 static ElfW(Addr) _dl_start_final (void *arg);
433 #else
434 struct dl_start_final_info
436 struct link_map l;
437 RTLD_TIMING_VAR (start_time);
439 static ElfW(Addr) _dl_start_final (void *arg,
440 struct dl_start_final_info *info);
441 #endif
443 /* These defined magically in the linker script. */
444 extern char _begin[] attribute_hidden;
445 extern char _etext[] attribute_hidden;
446 extern char _end[] attribute_hidden;
449 #ifdef RTLD_START
450 RTLD_START
451 #else
452 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
453 #endif
455 /* This is the second half of _dl_start (below). It can be inlined safely
456 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
457 references. When the tools don't permit us to avoid using a GOT entry
458 for _dl_rtld_global (no attribute_hidden support), we must make sure
459 this function is not inlined (see below). */
461 #ifdef DONT_USE_BOOTSTRAP_MAP
462 static inline ElfW(Addr) __attribute__ ((always_inline))
463 _dl_start_final (void *arg)
464 #else
465 static ElfW(Addr) __attribute__ ((noinline))
466 _dl_start_final (void *arg, struct dl_start_final_info *info)
467 #endif
469 ElfW(Addr) start_addr;
471 /* Do not use an initializer for these members because it would
472 intefere with __rtld_static_init. */
473 GLRO (dl_find_object) = &_dl_find_object;
475 /* If it hasn't happen yet record the startup time. */
476 rtld_timer_start (&start_time);
477 #if !defined DONT_USE_BOOTSTRAP_MAP
478 RTLD_TIMING_SET (start_time, info->start_time);
479 #endif
481 /* Transfer data about ourselves to the permanent link_map structure. */
482 #ifndef DONT_USE_BOOTSTRAP_MAP
483 GL(dl_rtld_map).l_addr = info->l.l_addr;
484 GL(dl_rtld_map).l_ld = info->l.l_ld;
485 GL(dl_rtld_map).l_ld_readonly = info->l.l_ld_readonly;
486 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
487 sizeof GL(dl_rtld_map).l_info);
488 GL(dl_rtld_map).l_mach = info->l.l_mach;
489 GL(dl_rtld_map).l_relocated = 1;
490 #endif
491 _dl_setup_hash (&GL(dl_rtld_map));
492 GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
493 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
494 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
495 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
496 /* Copy the TLS related data if necessary. */
497 #ifndef DONT_USE_BOOTSTRAP_MAP
498 # if NO_TLS_OFFSET != 0
499 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
500 # endif
501 #endif
503 /* Initialize the stack end variable. */
504 __libc_stack_end = __builtin_frame_address (0);
506 /* Call the OS-dependent function to set up life so we can do things like
507 file access. It will call `dl_main' (below) to do all the real work
508 of the dynamic linker, and then unwind our frame and run the user
509 entry point on the same stack we entered on. */
510 start_addr = _dl_sysdep_start (arg, &dl_main);
512 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS))
514 RTLD_TIMING_VAR (rtld_total_time);
515 rtld_timer_stop (&rtld_total_time, start_time);
516 print_statistics (RTLD_TIMING_REF(rtld_total_time));
519 #ifndef ELF_MACHINE_START_ADDRESS
520 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
521 #endif
522 return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, start_addr);
525 #ifdef DONT_USE_BOOTSTRAP_MAP
526 # define bootstrap_map GL(dl_rtld_map)
527 #else
528 # define bootstrap_map info.l
529 #endif
531 static ElfW(Addr) __attribute_used__
532 _dl_start (void *arg)
534 #ifdef DONT_USE_BOOTSTRAP_MAP
535 rtld_timer_start (&start_time);
536 #else
537 struct dl_start_final_info info;
538 rtld_timer_start (&info.start_time);
539 #endif
541 /* Partly clean the `bootstrap_map' structure up. Don't use
542 `memset' since it might not be built in or inlined and we cannot
543 make function calls at this point. Use '__builtin_memset' if we
544 know it is available. We do not have to clear the memory if we
545 do not have to use the temporary bootstrap_map. Global variables
546 are initialized to zero by default. */
547 #ifndef DONT_USE_BOOTSTRAP_MAP
548 # ifdef HAVE_BUILTIN_MEMSET
549 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
550 # else
551 for (size_t cnt = 0;
552 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
553 ++cnt)
554 bootstrap_map.l_info[cnt] = 0;
555 # endif
556 #endif
558 /* Figure out the run-time load address of the dynamic linker itself. */
559 bootstrap_map.l_addr = elf_machine_load_address ();
561 /* Read our own dynamic section and fill in the info array. */
562 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
563 bootstrap_map.l_ld_readonly = DL_RO_DYN_SECTION;
564 elf_get_dynamic_info (&bootstrap_map, true, false);
566 #if NO_TLS_OFFSET != 0
567 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
568 #endif
570 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
571 ELF_MACHINE_BEFORE_RTLD_RELOC (&bootstrap_map, bootstrap_map.l_info);
572 #endif
574 if (bootstrap_map.l_addr)
576 /* Relocate ourselves so we can do normal function calls and
577 data access using the global offset table. */
579 ELF_DYNAMIC_RELOCATE (&bootstrap_map, NULL, 0, 0, 0);
581 bootstrap_map.l_relocated = 1;
583 /* Please note that we don't allow profiling of this object and
584 therefore need not test whether we have to allocate the array
585 for the relocation results (as done in dl-reloc.c). */
587 /* Now life is sane; we can call functions and access global data.
588 Set up to use the operating system facilities, and find out from
589 the operating system's program loader where to find the program
590 header table in core. Put the rest of _dl_start into a separate
591 function, that way the compiler cannot put accesses to the GOT
592 before ELF_DYNAMIC_RELOCATE. */
594 __rtld_malloc_init_stubs ();
596 #ifdef DONT_USE_BOOTSTRAP_MAP
597 return _dl_start_final (arg);
598 #else
599 return _dl_start_final (arg, &info);
600 #endif
605 /* Now life is peachy; we can do all normal operations.
606 On to the real work. */
608 /* Some helper functions. */
610 /* Arguments to relocate_doit. */
611 struct relocate_args
613 struct link_map *l;
614 int reloc_mode;
617 struct map_args
619 /* Argument to map_doit. */
620 const char *str;
621 struct link_map *loader;
622 int mode;
623 /* Return value of map_doit. */
624 struct link_map *map;
627 struct dlmopen_args
629 const char *fname;
630 struct link_map *map;
633 struct lookup_args
635 const char *name;
636 struct link_map *map;
637 void *result;
640 /* Arguments to version_check_doit. */
641 struct version_check_args
643 int doexit;
644 int dotrace;
647 static void
648 relocate_doit (void *a)
650 struct relocate_args *args = (struct relocate_args *) a;
652 _dl_relocate_object (args->l, args->l->l_scope, args->reloc_mode, 0);
655 static void
656 map_doit (void *a)
658 struct map_args *args = (struct map_args *) a;
659 int type = (args->mode == __RTLD_OPENEXEC) ? lt_executable : lt_library;
660 args->map = _dl_map_object (args->loader, args->str, type, 0,
661 args->mode, LM_ID_BASE);
664 static void
665 dlmopen_doit (void *a)
667 struct dlmopen_args *args = (struct dlmopen_args *) a;
668 args->map = _dl_open (args->fname,
669 (RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT
670 | __RTLD_SECURE),
671 dl_main, LM_ID_NEWLM, _dl_argc, _dl_argv,
672 __environ);
675 static void
676 lookup_doit (void *a)
678 struct lookup_args *args = (struct lookup_args *) a;
679 const ElfW(Sym) *ref = NULL;
680 args->result = NULL;
681 lookup_t l = _dl_lookup_symbol_x (args->name, args->map, &ref,
682 args->map->l_local_scope, NULL, 0,
683 DL_LOOKUP_RETURN_NEWEST, NULL);
684 if (ref != NULL)
685 args->result = DL_SYMBOL_ADDRESS (l, ref);
688 static void
689 version_check_doit (void *a)
691 struct version_check_args *args = (struct version_check_args *) a;
692 if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
693 args->dotrace) && args->doexit)
694 /* We cannot start the application. Abort now. */
695 _exit (1);
699 static inline struct link_map *
700 find_needed (const char *name)
702 struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
703 unsigned int n = scope->r_nlist;
705 while (n-- > 0)
706 if (_dl_name_match_p (name, scope->r_list[n]))
707 return scope->r_list[n];
709 /* Should never happen. */
710 return NULL;
713 static int
714 match_version (const char *string, struct link_map *map)
716 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
717 ElfW(Verdef) *def;
719 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
720 if (map->l_info[VERDEFTAG] == NULL)
721 /* The file has no symbol versioning. */
722 return 0;
724 def = (ElfW(Verdef) *) ((char *) map->l_addr
725 + map->l_info[VERDEFTAG]->d_un.d_ptr);
726 while (1)
728 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
730 /* Compare the version strings. */
731 if (strcmp (string, strtab + aux->vda_name) == 0)
732 /* Bingo! */
733 return 1;
735 /* If no more definitions we failed to find what we want. */
736 if (def->vd_next == 0)
737 break;
739 /* Next definition. */
740 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
743 return 0;
746 static bool tls_init_tp_called;
748 static void *
749 init_tls (size_t naudit)
751 /* Number of elements in the static TLS block. */
752 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
754 /* Do not do this twice. The audit interface might have required
755 the DTV interfaces to be set up early. */
756 if (GL(dl_initial_dtv) != NULL)
757 return NULL;
759 /* Allocate the array which contains the information about the
760 dtv slots. We allocate a few entries more than needed to
761 avoid the need for reallocation. */
762 size_t nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
764 /* Allocate. */
765 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
766 calloc (sizeof (struct dtv_slotinfo_list)
767 + nelem * sizeof (struct dtv_slotinfo), 1);
768 /* No need to check the return value. If memory allocation failed
769 the program would have been terminated. */
771 struct dtv_slotinfo *slotinfo = GL(dl_tls_dtv_slotinfo_list)->slotinfo;
772 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
773 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
775 /* Fill in the information from the loaded modules. No namespace
776 but the base one can be filled at this time. */
777 assert (GL(dl_ns)[LM_ID_BASE + 1]._ns_loaded == NULL);
778 int i = 0;
779 for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
780 l = l->l_next)
781 if (l->l_tls_blocksize != 0)
783 /* This is a module with TLS data. Store the map reference.
784 The generation counter is zero. */
785 slotinfo[i].map = l;
786 /* slotinfo[i].gen = 0; */
787 ++i;
789 assert (i == GL(dl_tls_max_dtv_idx));
791 /* Calculate the size of the static TLS surplus. */
792 _dl_tls_static_surplus_init (naudit);
794 /* Compute the TLS offsets for the various blocks. */
795 _dl_determine_tlsoffset ();
797 /* Construct the static TLS block and the dtv for the initial
798 thread. For some platforms this will include allocating memory
799 for the thread descriptor. The memory for the TLS block will
800 never be freed. It should be allocated accordingly. The dtv
801 array can be changed if dynamic loading requires it. */
802 void *tcbp = _dl_allocate_tls_storage ();
803 if (tcbp == NULL)
804 _dl_fatal_printf ("\
805 cannot allocate TLS data structures for initial thread\n");
807 /* Store for detection of the special case by __tls_get_addr
808 so it knows not to pass this dtv to the normal realloc. */
809 GL(dl_initial_dtv) = GET_DTV (tcbp);
811 /* And finally install it for the main thread. */
812 const char *lossage = TLS_INIT_TP (tcbp);
813 if (__glibc_unlikely (lossage != NULL))
814 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
815 __tls_init_tp ();
816 tls_init_tp_called = true;
818 return tcbp;
821 static unsigned int
822 do_preload (const char *fname, struct link_map *main_map, const char *where)
824 const char *objname;
825 const char *err_str = NULL;
826 struct map_args args;
827 bool malloced;
829 args.str = fname;
830 args.loader = main_map;
831 args.mode = __RTLD_SECURE;
833 unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
835 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
836 if (__glibc_unlikely (err_str != NULL))
838 _dl_error_printf ("\
839 ERROR: ld.so: object '%s' from %s cannot be preloaded (%s): ignored.\n",
840 fname, where, err_str);
841 /* No need to call free, this is still before
842 the libc's malloc is used. */
844 else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
845 /* It is no duplicate. */
846 return 1;
848 /* Nothing loaded. */
849 return 0;
852 static void
853 security_init (void)
855 /* Set up the stack checker's canary. */
856 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard (_dl_random);
857 #ifdef THREAD_SET_STACK_GUARD
858 THREAD_SET_STACK_GUARD (stack_chk_guard);
859 #else
860 __stack_chk_guard = stack_chk_guard;
861 #endif
863 /* Set up the pointer guard as well, if necessary. */
864 uintptr_t pointer_chk_guard
865 = _dl_setup_pointer_guard (_dl_random, stack_chk_guard);
866 #ifdef THREAD_SET_POINTER_GUARD
867 THREAD_SET_POINTER_GUARD (pointer_chk_guard);
868 #endif
869 __pointer_chk_guard_local = pointer_chk_guard;
871 /* We do not need the _dl_random value anymore. The less
872 information we leave behind, the better, so clear the
873 variable. */
874 _dl_random = NULL;
877 #include <setup-vdso.h>
879 /* The LD_PRELOAD environment variable gives list of libraries
880 separated by white space or colons that are loaded before the
881 executable's dependencies and prepended to the global scope list.
882 (If the binary is running setuid all elements containing a '/' are
883 ignored since it is insecure.) Return the number of preloads
884 performed. Ditto for --preload command argument. */
885 unsigned int
886 handle_preload_list (const char *preloadlist, struct link_map *main_map,
887 const char *where)
889 unsigned int npreloads = 0;
890 const char *p = preloadlist;
891 char fname[SECURE_PATH_LIMIT];
893 while (*p != '\0')
895 /* Split preload list at space/colon. */
896 size_t len = strcspn (p, " :");
897 if (len > 0 && len < sizeof (fname))
899 memcpy (fname, p, len);
900 fname[len] = '\0';
902 else
903 fname[0] = '\0';
905 /* Skip over the substring and the following delimiter. */
906 p += len;
907 if (*p != '\0')
908 ++p;
910 if (dso_name_valid_for_suid (fname))
911 npreloads += do_preload (fname, main_map, where);
913 return npreloads;
916 /* Called if the audit DSO cannot be used: if it does not have the
917 appropriate interfaces, or it expects a more recent version library
918 version than what the dynamic linker provides. */
919 static void
920 unload_audit_module (struct link_map *map, int original_tls_idx)
922 #ifndef NDEBUG
923 Lmid_t ns = map->l_ns;
924 #endif
925 _dl_close (map);
927 /* Make sure the namespace has been cleared entirely. */
928 assert (GL(dl_ns)[ns]._ns_loaded == NULL);
929 assert (GL(dl_ns)[ns]._ns_nloaded == 0);
931 GL(dl_tls_max_dtv_idx) = original_tls_idx;
934 /* Called to print an error message if loading of an audit module
935 failed. */
936 static void
937 report_audit_module_load_error (const char *name, const char *err_str,
938 bool malloced)
940 _dl_error_printf ("\
941 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
942 name, err_str);
943 if (malloced)
944 free ((char *) err_str);
947 /* Load one audit module. */
948 static void
949 load_audit_module (const char *name, struct audit_ifaces **last_audit)
951 int original_tls_idx = GL(dl_tls_max_dtv_idx);
953 struct dlmopen_args dlmargs;
954 dlmargs.fname = name;
955 dlmargs.map = NULL;
957 const char *objname;
958 const char *err_str = NULL;
959 bool malloced;
960 _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit, &dlmargs);
961 if (__glibc_unlikely (err_str != NULL))
963 report_audit_module_load_error (name, err_str, malloced);
964 return;
967 struct lookup_args largs;
968 largs.name = "la_version";
969 largs.map = dlmargs.map;
970 _dl_catch_error (&objname, &err_str, &malloced, lookup_doit, &largs);
971 if (__glibc_likely (err_str != NULL))
973 unload_audit_module (dlmargs.map, original_tls_idx);
974 report_audit_module_load_error (name, err_str, malloced);
975 return;
978 unsigned int (*laversion) (unsigned int) = largs.result;
980 /* A null symbol indicates that something is very wrong with the
981 loaded object because defined symbols are supposed to have a
982 valid, non-null address. */
983 assert (laversion != NULL);
985 unsigned int lav = laversion (LAV_CURRENT);
986 if (lav == 0)
988 /* Only print an error message if debugging because this can
989 happen deliberately. */
990 if (GLRO(dl_debug_mask) & DL_DEBUG_FILES)
991 _dl_debug_printf ("\
992 file=%s [%lu]; audit interface function la_version returned zero; ignored.\n",
993 dlmargs.map->l_name, dlmargs.map->l_ns);
994 unload_audit_module (dlmargs.map, original_tls_idx);
995 return;
998 if (!_dl_audit_check_version (lav))
1000 _dl_debug_printf ("\
1001 ERROR: audit interface '%s' requires version %d (maximum supported version %d); ignored.\n",
1002 name, lav, LAV_CURRENT);
1003 unload_audit_module (dlmargs.map, original_tls_idx);
1004 return;
1007 enum { naudit_ifaces = 8 };
1008 union
1010 struct audit_ifaces ifaces;
1011 void (*fptr[naudit_ifaces]) (void);
1012 } *newp = malloc (sizeof (*newp));
1013 if (newp == NULL)
1014 _dl_fatal_printf ("Out of memory while loading audit modules\n");
1016 /* Names of the auditing interfaces. All in one
1017 long string. */
1018 static const char audit_iface_names[] =
1019 "la_activity\0"
1020 "la_objsearch\0"
1021 "la_objopen\0"
1022 "la_preinit\0"
1023 LA_SYMBIND "\0"
1024 #define STRING(s) __STRING (s)
1025 "la_" STRING (ARCH_LA_PLTENTER) "\0"
1026 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
1027 "la_objclose\0";
1028 unsigned int cnt = 0;
1029 const char *cp = audit_iface_names;
1032 largs.name = cp;
1033 _dl_catch_error (&objname, &err_str, &malloced, lookup_doit, &largs);
1035 /* Store the pointer. */
1036 if (err_str == NULL && largs.result != NULL)
1037 newp->fptr[cnt] = largs.result;
1038 else
1039 newp->fptr[cnt] = NULL;
1040 ++cnt;
1042 cp = rawmemchr (cp, '\0') + 1;
1044 while (*cp != '\0');
1045 assert (cnt == naudit_ifaces);
1047 /* Now append the new auditing interface to the list. */
1048 newp->ifaces.next = NULL;
1049 if (*last_audit == NULL)
1050 *last_audit = GLRO(dl_audit) = &newp->ifaces;
1051 else
1052 *last_audit = (*last_audit)->next = &newp->ifaces;
1054 /* The dynamic linker link map is statically allocated, so the
1055 cookie in _dl_new_object has not happened. */
1056 link_map_audit_state (&GL (dl_rtld_map), GLRO (dl_naudit))->cookie
1057 = (intptr_t) &GL (dl_rtld_map);
1059 ++GLRO(dl_naudit);
1061 /* Mark the DSO as being used for auditing. */
1062 dlmargs.map->l_auditing = 1;
1065 /* Load all audit modules. */
1066 static void
1067 load_audit_modules (struct link_map *main_map, struct audit_list *audit_list)
1069 struct audit_ifaces *last_audit = NULL;
1071 while (true)
1073 const char *name = audit_list_next (audit_list);
1074 if (name == NULL)
1075 break;
1076 load_audit_module (name, &last_audit);
1079 /* Notify audit modules of the initially loaded modules (the main
1080 program and the dynamic linker itself). */
1081 if (GLRO(dl_naudit) > 0)
1083 _dl_audit_objopen (main_map, LM_ID_BASE);
1084 _dl_audit_objopen (&GL(dl_rtld_map), LM_ID_BASE);
1088 /* Check if the executable is not actualy dynamically linked, and
1089 invoke it directly in that case. */
1090 static void
1091 rtld_chain_load (struct link_map *main_map, char *argv0)
1093 /* The dynamic loader run against itself. */
1094 const char *rtld_soname
1095 = ((const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1096 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val);
1097 if (main_map->l_info[DT_SONAME] != NULL
1098 && strcmp (rtld_soname,
1099 ((const char *) D_PTR (main_map, l_info[DT_STRTAB])
1100 + main_map->l_info[DT_SONAME]->d_un.d_val)) == 0)
1101 _dl_fatal_printf ("%s: loader cannot load itself\n", rtld_soname);
1103 /* With DT_NEEDED dependencies, the executable is dynamically
1104 linked. */
1105 if (__glibc_unlikely (main_map->l_info[DT_NEEDED] != NULL))
1106 return;
1108 /* If the executable has program interpreter, it is dynamically
1109 linked. */
1110 for (size_t i = 0; i < main_map->l_phnum; ++i)
1111 if (main_map->l_phdr[i].p_type == PT_INTERP)
1112 return;
1114 const char *pathname = _dl_argv[0];
1115 if (argv0 != NULL)
1116 _dl_argv[0] = argv0;
1117 int errcode = __rtld_execve (pathname, _dl_argv, _environ);
1118 const char *errname = strerrorname_np (errcode);
1119 if (errname != NULL)
1120 _dl_fatal_printf("%s: cannot execute %s: %s\n",
1121 rtld_soname, pathname, errname);
1122 else
1123 _dl_fatal_printf("%s: cannot execute %s: %d\n",
1124 rtld_soname, pathname, errcode);
1127 /* Called to complete the initialization of the link map for the main
1128 executable. Returns true if there is a PT_INTERP segment. */
1129 static bool
1130 rtld_setup_main_map (struct link_map *main_map)
1132 /* This have already been filled in right after _dl_new_object, or
1133 as part of _dl_map_object. */
1134 const ElfW(Phdr) *phdr = main_map->l_phdr;
1135 ElfW(Word) phnum = main_map->l_phnum;
1137 bool has_interp = false;
1139 main_map->l_map_end = 0;
1140 main_map->l_text_end = 0;
1141 /* Perhaps the executable has no PT_LOAD header entries at all. */
1142 main_map->l_map_start = ~0;
1143 /* And it was opened directly. */
1144 ++main_map->l_direct_opencount;
1145 main_map->l_contiguous = 1;
1147 /* A PT_LOAD segment at an unexpected address will clear the
1148 l_contiguous flag. The ELF specification says that PT_LOAD
1149 segments need to be sorted in in increasing order, but perhaps
1150 not all executables follow this requirement. Having l_contiguous
1151 equal to 1 is just an optimization, so the code below does not
1152 try to sort the segments in case they are unordered.
1154 There is one corner case in which l_contiguous is not set to 1,
1155 but where it could be set: If a PIE (ET_DYN) binary is loaded by
1156 glibc itself (not the kernel), it is always contiguous due to the
1157 way the glibc loader works. However, the kernel loader may still
1158 create holes in this case, and the code here still uses 0
1159 conservatively for the glibc-loaded case, too. */
1160 ElfW(Addr) expected_load_address = 0;
1162 /* Scan the program header table for the dynamic section. */
1163 for (const ElfW(Phdr) *ph = phdr; ph < &phdr[phnum]; ++ph)
1164 switch (ph->p_type)
1166 case PT_PHDR:
1167 /* Find out the load address. */
1168 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1169 break;
1170 case PT_DYNAMIC:
1171 /* This tells us where to find the dynamic section,
1172 which tells us everything we need to do. */
1173 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
1174 main_map->l_ld_readonly = (ph->p_flags & PF_W) == 0;
1175 break;
1176 case PT_INTERP:
1177 /* This "interpreter segment" was used by the program loader to
1178 find the program interpreter, which is this program itself, the
1179 dynamic linker. We note what name finds us, so that a future
1180 dlopen call or DT_NEEDED entry, for something that wants to link
1181 against the dynamic linker as a shared library, will know that
1182 the shared object is already loaded. */
1183 _dl_rtld_libname.name = ((const char *) main_map->l_addr
1184 + ph->p_vaddr);
1185 /* _dl_rtld_libname.next = NULL; Already zero. */
1186 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1188 /* Ordinarilly, we would get additional names for the loader from
1189 our DT_SONAME. This can't happen if we were actually linked as
1190 a static executable (detect this case when we have no DYNAMIC).
1191 If so, assume the filename component of the interpreter path to
1192 be our SONAME, and add it to our name list. */
1193 if (GL(dl_rtld_map).l_ld == NULL)
1195 const char *p = NULL;
1196 const char *cp = _dl_rtld_libname.name;
1198 /* Find the filename part of the path. */
1199 while (*cp != '\0')
1200 if (*cp++ == '/')
1201 p = cp;
1203 if (p != NULL)
1205 _dl_rtld_libname2.name = p;
1206 /* _dl_rtld_libname2.next = NULL; Already zero. */
1207 _dl_rtld_libname.next = &_dl_rtld_libname2;
1211 has_interp = true;
1212 break;
1213 case PT_LOAD:
1215 ElfW(Addr) mapstart;
1216 ElfW(Addr) allocend;
1218 /* Remember where the main program starts in memory. */
1219 mapstart = (main_map->l_addr
1220 + (ph->p_vaddr & ~(GLRO(dl_pagesize) - 1)));
1221 if (main_map->l_map_start > mapstart)
1222 main_map->l_map_start = mapstart;
1224 if (main_map->l_contiguous && expected_load_address != 0
1225 && expected_load_address != mapstart)
1226 main_map->l_contiguous = 0;
1228 /* Also where it ends. */
1229 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1230 if (main_map->l_map_end < allocend)
1231 main_map->l_map_end = allocend;
1232 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1233 main_map->l_text_end = allocend;
1235 /* The next expected address is the page following this load
1236 segment. */
1237 expected_load_address = ((allocend + GLRO(dl_pagesize) - 1)
1238 & ~(GLRO(dl_pagesize) - 1));
1240 break;
1242 case PT_TLS:
1243 if (ph->p_memsz > 0)
1245 /* Note that in the case the dynamic linker we duplicate work
1246 here since we read the PT_TLS entry already in
1247 _dl_start_final. But the result is repeatable so do not
1248 check for this special but unimportant case. */
1249 main_map->l_tls_blocksize = ph->p_memsz;
1250 main_map->l_tls_align = ph->p_align;
1251 if (ph->p_align == 0)
1252 main_map->l_tls_firstbyte_offset = 0;
1253 else
1254 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1255 & (ph->p_align - 1));
1256 main_map->l_tls_initimage_size = ph->p_filesz;
1257 main_map->l_tls_initimage = (void *) ph->p_vaddr;
1259 /* This image gets the ID one. */
1260 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1262 break;
1264 case PT_GNU_STACK:
1265 GL(dl_stack_flags) = ph->p_flags;
1266 break;
1268 case PT_GNU_RELRO:
1269 main_map->l_relro_addr = ph->p_vaddr;
1270 main_map->l_relro_size = ph->p_memsz;
1271 break;
1273 /* Process program headers again, but scan them backwards so
1274 that PT_NOTE can be skipped if PT_GNU_PROPERTY exits. */
1275 for (const ElfW(Phdr) *ph = &phdr[phnum]; ph != phdr; --ph)
1276 switch (ph[-1].p_type)
1278 case PT_NOTE:
1279 _dl_process_pt_note (main_map, -1, &ph[-1]);
1280 break;
1281 case PT_GNU_PROPERTY:
1282 _dl_process_pt_gnu_property (main_map, -1, &ph[-1]);
1283 break;
1286 /* Adjust the address of the TLS initialization image in case
1287 the executable is actually an ET_DYN object. */
1288 if (main_map->l_tls_initimage != NULL)
1289 main_map->l_tls_initimage
1290 = (char *) main_map->l_tls_initimage + main_map->l_addr;
1291 if (! main_map->l_map_end)
1292 main_map->l_map_end = ~0;
1293 if (! main_map->l_text_end)
1294 main_map->l_text_end = ~0;
1295 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1297 /* We were invoked directly, so the program might not have a
1298 PT_INTERP. */
1299 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1300 /* _dl_rtld_libname.next = NULL; Already zero. */
1301 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1303 else
1304 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1306 return has_interp;
1309 static void
1310 dl_main (const ElfW(Phdr) *phdr,
1311 ElfW(Word) phnum,
1312 ElfW(Addr) *user_entry,
1313 ElfW(auxv_t) *auxv)
1315 struct link_map *main_map;
1316 size_t file_size;
1317 char *file;
1318 unsigned int i;
1319 bool rtld_is_main = false;
1320 void *tcbp = NULL;
1322 struct dl_main_state state;
1323 dl_main_state_init (&state);
1325 __tls_pre_init_tp ();
1327 #if !PTHREAD_IN_LIBC
1328 /* The explicit initialization here is cheaper than processing the reloc
1329 in the _rtld_local definition's initializer. */
1330 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
1331 #endif
1333 /* Process the environment variable which control the behaviour. */
1334 process_envvars (&state);
1336 #ifndef HAVE_INLINED_SYSCALLS
1337 /* Set up a flag which tells we are just starting. */
1338 _dl_starting_up = 1;
1339 #endif
1341 const char *ld_so_name = _dl_argv[0];
1342 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
1344 /* Ho ho. We are not the program interpreter! We are the program
1345 itself! This means someone ran ld.so as a command. Well, that
1346 might be convenient to do sometimes. We support it by
1347 interpreting the args like this:
1349 ld.so PROGRAM ARGS...
1351 The first argument is the name of a file containing an ELF
1352 executable we will load and run with the following arguments.
1353 To simplify life here, PROGRAM is searched for using the
1354 normal rules for shared objects, rather than $PATH or anything
1355 like that. We just load it and use its entry point; we don't
1356 pay attention to its PT_INTERP command (we are the interpreter
1357 ourselves). This is an easy way to test a new ld.so before
1358 installing it. */
1359 rtld_is_main = true;
1361 char *argv0 = NULL;
1363 /* Note the place where the dynamic linker actually came from. */
1364 GL(dl_rtld_map).l_name = rtld_progname;
1366 while (_dl_argc > 1)
1367 if (! strcmp (_dl_argv[1], "--list"))
1369 if (state.mode != rtld_mode_help)
1371 state.mode = rtld_mode_list;
1372 /* This means do no dependency analysis. */
1373 GLRO(dl_lazy) = -1;
1376 ++_dl_skip_args;
1377 --_dl_argc;
1378 ++_dl_argv;
1380 else if (! strcmp (_dl_argv[1], "--verify"))
1382 if (state.mode != rtld_mode_help)
1383 state.mode = rtld_mode_verify;
1385 ++_dl_skip_args;
1386 --_dl_argc;
1387 ++_dl_argv;
1389 else if (! strcmp (_dl_argv[1], "--inhibit-cache"))
1391 GLRO(dl_inhibit_cache) = 1;
1392 ++_dl_skip_args;
1393 --_dl_argc;
1394 ++_dl_argv;
1396 else if (! strcmp (_dl_argv[1], "--library-path")
1397 && _dl_argc > 2)
1399 state.library_path = _dl_argv[2];
1400 state.library_path_source = "--library-path";
1402 _dl_skip_args += 2;
1403 _dl_argc -= 2;
1404 _dl_argv += 2;
1406 else if (! strcmp (_dl_argv[1], "--inhibit-rpath")
1407 && _dl_argc > 2)
1409 GLRO(dl_inhibit_rpath) = _dl_argv[2];
1411 _dl_skip_args += 2;
1412 _dl_argc -= 2;
1413 _dl_argv += 2;
1415 else if (! strcmp (_dl_argv[1], "--audit") && _dl_argc > 2)
1417 audit_list_add_string (&state.audit_list, _dl_argv[2]);
1419 _dl_skip_args += 2;
1420 _dl_argc -= 2;
1421 _dl_argv += 2;
1423 else if (! strcmp (_dl_argv[1], "--preload") && _dl_argc > 2)
1425 state.preloadarg = _dl_argv[2];
1426 _dl_skip_args += 2;
1427 _dl_argc -= 2;
1428 _dl_argv += 2;
1430 else if (! strcmp (_dl_argv[1], "--argv0") && _dl_argc > 2)
1432 argv0 = _dl_argv[2];
1434 _dl_skip_args += 2;
1435 _dl_argc -= 2;
1436 _dl_argv += 2;
1438 else if (strcmp (_dl_argv[1], "--glibc-hwcaps-prepend") == 0
1439 && _dl_argc > 2)
1441 state.glibc_hwcaps_prepend = _dl_argv[2];
1442 _dl_skip_args += 2;
1443 _dl_argc -= 2;
1444 _dl_argv += 2;
1446 else if (strcmp (_dl_argv[1], "--glibc-hwcaps-mask") == 0
1447 && _dl_argc > 2)
1449 state.glibc_hwcaps_mask = _dl_argv[2];
1450 _dl_skip_args += 2;
1451 _dl_argc -= 2;
1452 _dl_argv += 2;
1454 #if HAVE_TUNABLES
1455 else if (! strcmp (_dl_argv[1], "--list-tunables"))
1457 state.mode = rtld_mode_list_tunables;
1459 ++_dl_skip_args;
1460 --_dl_argc;
1461 ++_dl_argv;
1463 #endif
1464 else if (! strcmp (_dl_argv[1], "--list-diagnostics"))
1466 state.mode = rtld_mode_list_diagnostics;
1468 ++_dl_skip_args;
1469 --_dl_argc;
1470 ++_dl_argv;
1472 else if (strcmp (_dl_argv[1], "--help") == 0)
1474 state.mode = rtld_mode_help;
1475 --_dl_argc;
1476 ++_dl_argv;
1478 else if (strcmp (_dl_argv[1], "--version") == 0)
1479 _dl_version ();
1480 else if (_dl_argv[1][0] == '-' && _dl_argv[1][1] == '-')
1482 if (_dl_argv[1][1] == '\0')
1483 /* End of option list. */
1484 break;
1485 else
1486 /* Unrecognized option. */
1487 _dl_usage (ld_so_name, _dl_argv[1]);
1489 else
1490 break;
1492 #if HAVE_TUNABLES
1493 if (__glibc_unlikely (state.mode == rtld_mode_list_tunables))
1495 __tunables_print ();
1496 _exit (0);
1498 #endif
1500 if (state.mode == rtld_mode_list_diagnostics)
1501 _dl_print_diagnostics (_environ);
1503 /* If we have no further argument the program was called incorrectly.
1504 Grant the user some education. */
1505 if (_dl_argc < 2)
1507 if (state.mode == rtld_mode_help)
1508 /* --help without an executable is not an error. */
1509 _dl_help (ld_so_name, &state);
1510 else
1511 _dl_usage (ld_so_name, NULL);
1514 ++_dl_skip_args;
1515 --_dl_argc;
1516 ++_dl_argv;
1518 /* The initialization of _dl_stack_flags done below assumes the
1519 executable's PT_GNU_STACK may have been honored by the kernel, and
1520 so a PT_GNU_STACK with PF_X set means the stack started out with
1521 execute permission. However, this is not really true if the
1522 dynamic linker is the executable the kernel loaded. For this
1523 case, we must reinitialize _dl_stack_flags to match the dynamic
1524 linker itself. If the dynamic linker was built with a
1525 PT_GNU_STACK, then the kernel may have loaded us with a
1526 nonexecutable stack that we will have to make executable when we
1527 load the program below unless it has a PT_GNU_STACK indicating
1528 nonexecutable stack is ok. */
1530 for (const ElfW(Phdr) *ph = phdr; ph < &phdr[phnum]; ++ph)
1531 if (ph->p_type == PT_GNU_STACK)
1533 GL(dl_stack_flags) = ph->p_flags;
1534 break;
1537 if (__glibc_unlikely (state.mode == rtld_mode_verify
1538 || state.mode == rtld_mode_help))
1540 const char *objname;
1541 const char *err_str = NULL;
1542 struct map_args args;
1543 bool malloced;
1545 args.str = rtld_progname;
1546 args.loader = NULL;
1547 args.mode = __RTLD_OPENEXEC;
1548 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
1549 &args);
1550 if (__glibc_unlikely (err_str != NULL))
1552 /* We don't free the returned string, the programs stops
1553 anyway. */
1554 if (state.mode == rtld_mode_help)
1555 /* Mask the failure to load the main object. The help
1556 message contains less information in this case. */
1557 _dl_help (ld_so_name, &state);
1558 else
1559 _exit (EXIT_FAILURE);
1562 else
1564 RTLD_TIMING_VAR (start);
1565 rtld_timer_start (&start);
1566 _dl_map_object (NULL, rtld_progname, lt_executable, 0,
1567 __RTLD_OPENEXEC, LM_ID_BASE);
1568 rtld_timer_stop (&load_time, start);
1571 /* Now the map for the main executable is available. */
1572 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1574 if (__glibc_likely (state.mode == rtld_mode_normal))
1575 rtld_chain_load (main_map, argv0);
1577 phdr = main_map->l_phdr;
1578 phnum = main_map->l_phnum;
1579 /* We overwrite here a pointer to a malloc()ed string. But since
1580 the malloc() implementation used at this point is the dummy
1581 implementations which has no real free() function it does not
1582 makes sense to free the old string first. */
1583 main_map->l_name = (char *) "";
1584 *user_entry = main_map->l_entry;
1586 /* Set bit indicating this is the main program map. */
1587 main_map->l_main_map = 1;
1589 #ifdef HAVE_AUX_VECTOR
1590 /* Adjust the on-stack auxiliary vector so that it looks like the
1591 binary was executed directly. */
1592 for (ElfW(auxv_t) *av = auxv; av->a_type != AT_NULL; av++)
1593 switch (av->a_type)
1595 case AT_PHDR:
1596 av->a_un.a_val = (uintptr_t) phdr;
1597 break;
1598 case AT_PHNUM:
1599 av->a_un.a_val = phnum;
1600 break;
1601 case AT_ENTRY:
1602 av->a_un.a_val = *user_entry;
1603 break;
1604 case AT_EXECFN:
1605 av->a_un.a_val = (uintptr_t) _dl_argv[0];
1606 break;
1608 #endif
1610 /* Set the argv[0] string now that we've processed the executable. */
1611 if (argv0 != NULL)
1612 _dl_argv[0] = argv0;
1614 else
1616 /* Create a link_map for the executable itself.
1617 This will be what dlopen on "" returns. */
1618 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1619 __RTLD_OPENEXEC, LM_ID_BASE);
1620 assert (main_map != NULL);
1621 main_map->l_phdr = phdr;
1622 main_map->l_phnum = phnum;
1623 main_map->l_entry = *user_entry;
1625 /* Even though the link map is not yet fully initialized we can add
1626 it to the map list since there are no possible users running yet. */
1627 _dl_add_to_namespace_list (main_map, LM_ID_BASE);
1628 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
1630 /* At this point we are in a bit of trouble. We would have to
1631 fill in the values for l_dev and l_ino. But in general we
1632 do not know where the file is. We also do not handle AT_EXECFD
1633 even if it would be passed up.
1635 We leave the values here defined to 0. This is normally no
1636 problem as the program code itself is normally no shared
1637 object and therefore cannot be loaded dynamically. Nothing
1638 prevent the use of dynamic binaries and in these situations
1639 we might get problems. We might not be able to find out
1640 whether the object is already loaded. But since there is no
1641 easy way out and because the dynamic binary must also not
1642 have an SONAME we ignore this program for now. If it becomes
1643 a problem we can force people using SONAMEs. */
1645 /* We delay initializing the path structure until we got the dynamic
1646 information for the program. */
1649 bool has_interp = rtld_setup_main_map (main_map);
1651 /* If the current libname is different from the SONAME, add the
1652 latter as well. */
1653 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1654 && strcmp (GL(dl_rtld_map).l_libname->name,
1655 (const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1656 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1658 static struct libname_list newname;
1659 newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1660 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1661 newname.next = NULL;
1662 newname.dont_free = 1;
1664 assert (GL(dl_rtld_map).l_libname->next == NULL);
1665 GL(dl_rtld_map).l_libname->next = &newname;
1667 /* The ld.so must be relocated since otherwise loading audit modules
1668 will fail since they reuse the very same ld.so. */
1669 assert (GL(dl_rtld_map).l_relocated);
1671 if (! rtld_is_main)
1673 /* Extract the contents of the dynamic section for easy access. */
1674 elf_get_dynamic_info (main_map, false, false);
1676 /* If the main map is libc.so, update the base namespace to
1677 refer to this map. If libc.so is loaded later, this happens
1678 in _dl_map_object_from_fd. */
1679 if (main_map->l_info[DT_SONAME] != NULL
1680 && (strcmp (((const char *) D_PTR (main_map, l_info[DT_STRTAB])
1681 + main_map->l_info[DT_SONAME]->d_un.d_val), LIBC_SO)
1682 == 0))
1683 GL(dl_ns)[LM_ID_BASE].libc_map = main_map;
1685 /* Set up our cache of pointers into the hash table. */
1686 _dl_setup_hash (main_map);
1689 if (__glibc_unlikely (state.mode == rtld_mode_verify))
1691 /* We were called just to verify that this is a dynamic
1692 executable using us as the program interpreter. Exit with an
1693 error if we were not able to load the binary or no interpreter
1694 is specified (i.e., this is no dynamically linked binary. */
1695 if (main_map->l_ld == NULL)
1696 _exit (1);
1698 /* We allow here some platform specific code. */
1699 #ifdef DISTINGUISH_LIB_VERSIONS
1700 DISTINGUISH_LIB_VERSIONS;
1701 #endif
1702 _exit (has_interp ? 0 : 2);
1705 struct link_map **first_preload = &GL(dl_rtld_map).l_next;
1706 /* Set up the data structures for the system-supplied DSO early,
1707 so they can influence _dl_init_paths. */
1708 setup_vdso (main_map, &first_preload);
1710 /* With vDSO setup we can initialize the function pointers. */
1711 setup_vdso_pointers ();
1713 #ifdef DL_SYSDEP_OSCHECK
1714 DL_SYSDEP_OSCHECK (_dl_fatal_printf);
1715 #endif
1717 /* Initialize the data structures for the search paths for shared
1718 objects. */
1719 call_init_paths (&state);
1721 /* Initialize _r_debug_extended. */
1722 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1723 LM_ID_BASE);
1724 r->r_state = RT_CONSISTENT;
1726 /* Put the link_map for ourselves on the chain so it can be found by
1727 name. Note that at this point the global chain of link maps contains
1728 exactly one element, which is pointed to by dl_loaded. */
1729 if (! GL(dl_rtld_map).l_name)
1730 /* If not invoked directly, the dynamic linker shared object file was
1731 found by the PT_INTERP name. */
1732 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1733 GL(dl_rtld_map).l_type = lt_library;
1734 main_map->l_next = &GL(dl_rtld_map);
1735 GL(dl_rtld_map).l_prev = main_map;
1736 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1737 ++GL(dl_load_adds);
1739 /* Starting from binutils-2.23, the linker will define the magic symbol
1740 __ehdr_start to point to our own ELF header if it is visible in a
1741 segment that also includes the phdrs. If that's not available, we use
1742 the old method that assumes the beginning of the file is part of the
1743 lowest-addressed PT_LOAD segment. */
1744 extern const ElfW(Ehdr) __ehdr_start __attribute__ ((visibility ("hidden")));
1746 /* Set up the program header information for the dynamic linker
1747 itself. It is needed in the dl_iterate_phdr callbacks. */
1748 const ElfW(Ehdr) *rtld_ehdr = &__ehdr_start;
1749 assert (rtld_ehdr->e_ehsize == sizeof *rtld_ehdr);
1750 assert (rtld_ehdr->e_phentsize == sizeof (ElfW(Phdr)));
1752 const ElfW(Phdr) *rtld_phdr = (const void *) rtld_ehdr + rtld_ehdr->e_phoff;
1754 GL(dl_rtld_map).l_phdr = rtld_phdr;
1755 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1758 /* PT_GNU_RELRO is usually the last phdr. */
1759 size_t cnt = rtld_ehdr->e_phnum;
1760 while (cnt-- > 0)
1761 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1763 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1764 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1765 break;
1768 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1769 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1770 /* Assign a module ID. Do this before loading any audit modules. */
1771 _dl_assign_tls_modid (&GL(dl_rtld_map));
1773 audit_list_add_dynamic_tag (&state.audit_list, main_map, DT_AUDIT);
1774 audit_list_add_dynamic_tag (&state.audit_list, main_map, DT_DEPAUDIT);
1776 /* At this point, all data has been obtained that is included in the
1777 --help output. */
1778 if (__glibc_unlikely (state.mode == rtld_mode_help))
1779 _dl_help (ld_so_name, &state);
1781 /* If we have auditing DSOs to load, do it now. */
1782 bool need_security_init = true;
1783 if (state.audit_list.length > 0)
1785 size_t naudit = audit_list_count (&state.audit_list);
1787 /* Since we start using the auditing DSOs right away we need to
1788 initialize the data structures now. */
1789 tcbp = init_tls (naudit);
1791 /* Initialize security features. We need to do it this early
1792 since otherwise the constructors of the audit libraries will
1793 use different values (especially the pointer guard) and will
1794 fail later on. */
1795 security_init ();
1796 need_security_init = false;
1798 load_audit_modules (main_map, &state.audit_list);
1800 /* The count based on audit strings may overestimate the number
1801 of audit modules that got loaded, but not underestimate. */
1802 assert (GLRO(dl_naudit) <= naudit);
1805 /* Keep track of the currently loaded modules to count how many
1806 non-audit modules which use TLS are loaded. */
1807 size_t count_modids = _dl_count_modids ();
1809 /* Set up debugging before the debugger is notified for the first time. */
1810 elf_setup_debug_entry (main_map, r);
1812 /* We start adding objects. */
1813 r->r_state = RT_ADD;
1814 _dl_debug_state ();
1815 LIBC_PROBE (init_start, 2, LM_ID_BASE, r);
1817 /* Auditing checkpoint: we are ready to signal that the initial map
1818 is being constructed. */
1819 _dl_audit_activity_map (main_map, LA_ACT_ADD);
1821 /* We have two ways to specify objects to preload: via environment
1822 variable and via the file /etc/ld.so.preload. The latter can also
1823 be used when security is enabled. */
1824 assert (*first_preload == NULL);
1825 struct link_map **preloads = NULL;
1826 unsigned int npreloads = 0;
1828 if (__glibc_unlikely (state.preloadlist != NULL))
1830 RTLD_TIMING_VAR (start);
1831 rtld_timer_start (&start);
1832 npreloads += handle_preload_list (state.preloadlist, main_map,
1833 "LD_PRELOAD");
1834 rtld_timer_accum (&load_time, start);
1837 if (__glibc_unlikely (state.preloadarg != NULL))
1839 RTLD_TIMING_VAR (start);
1840 rtld_timer_start (&start);
1841 npreloads += handle_preload_list (state.preloadarg, main_map,
1842 "--preload");
1843 rtld_timer_accum (&load_time, start);
1846 /* There usually is no ld.so.preload file, it should only be used
1847 for emergencies and testing. So the open call etc should usually
1848 fail. Using access() on a non-existing file is faster than using
1849 open(). So we do this first. If it succeeds we do almost twice
1850 the work but this does not matter, since it is not for production
1851 use. */
1852 static const char preload_file[] = "/etc/ld.so.preload";
1853 if (__glibc_unlikely (__access (preload_file, R_OK) == 0))
1855 /* Read the contents of the file. */
1856 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1857 PROT_READ | PROT_WRITE);
1858 if (__glibc_unlikely (file != MAP_FAILED))
1860 /* Parse the file. It contains names of libraries to be loaded,
1861 separated by white spaces or `:'. It may also contain
1862 comments introduced by `#'. */
1863 char *problem;
1864 char *runp;
1865 size_t rest;
1867 /* Eliminate comments. */
1868 runp = file;
1869 rest = file_size;
1870 while (rest > 0)
1872 char *comment = memchr (runp, '#', rest);
1873 if (comment == NULL)
1874 break;
1876 rest -= comment - runp;
1878 *comment = ' ';
1879 while (--rest > 0 && *++comment != '\n');
1882 /* We have one problematic case: if we have a name at the end of
1883 the file without a trailing terminating characters, we cannot
1884 place the \0. Handle the case separately. */
1885 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1886 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1888 problem = &file[file_size];
1889 while (problem > file && problem[-1] != ' '
1890 && problem[-1] != '\t'
1891 && problem[-1] != '\n' && problem[-1] != ':')
1892 --problem;
1894 if (problem > file)
1895 problem[-1] = '\0';
1897 else
1899 problem = NULL;
1900 file[file_size - 1] = '\0';
1903 RTLD_TIMING_VAR (start);
1904 rtld_timer_start (&start);
1906 if (file != problem)
1908 char *p;
1909 runp = file;
1910 while ((p = strsep (&runp, ": \t\n")) != NULL)
1911 if (p[0] != '\0')
1912 npreloads += do_preload (p, main_map, preload_file);
1915 if (problem != NULL)
1917 char *p = strndupa (problem, file_size - (problem - file));
1919 npreloads += do_preload (p, main_map, preload_file);
1922 rtld_timer_accum (&load_time, start);
1924 /* We don't need the file anymore. */
1925 __munmap (file, file_size);
1929 if (__glibc_unlikely (*first_preload != NULL))
1931 /* Set up PRELOADS with a vector of the preloaded libraries. */
1932 struct link_map *l = *first_preload;
1933 preloads = __alloca (npreloads * sizeof preloads[0]);
1934 i = 0;
1937 preloads[i++] = l;
1938 l = l->l_next;
1939 } while (l);
1940 assert (i == npreloads);
1943 #ifdef NEED_DL_SYSINFO_DSO
1944 /* Now that the audit modules are opened, call la_objopen for the vDSO. */
1945 if (GLRO(dl_sysinfo_map) != NULL)
1946 _dl_audit_objopen (GLRO(dl_sysinfo_map), LM_ID_BASE);
1947 #endif
1949 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1950 specified some libraries to load, these are inserted before the actual
1951 dependencies in the executable's searchlist for symbol resolution. */
1953 RTLD_TIMING_VAR (start);
1954 rtld_timer_start (&start);
1955 _dl_map_object_deps (main_map, preloads, npreloads,
1956 state.mode == rtld_mode_trace, 0);
1957 rtld_timer_accum (&load_time, start);
1960 /* Mark all objects as being in the global scope. */
1961 for (i = main_map->l_searchlist.r_nlist; i > 0; )
1962 main_map->l_searchlist.r_list[--i]->l_global = 1;
1964 /* Remove _dl_rtld_map from the chain. */
1965 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1966 if (GL(dl_rtld_map).l_next != NULL)
1967 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1969 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1970 if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1971 break;
1973 bool rtld_multiple_ref = false;
1974 if (__glibc_likely (i < main_map->l_searchlist.r_nlist))
1976 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1977 put it back in the list of visible objects. We insert it into the
1978 chain in symbol search order because gdb uses the chain's order as
1979 its symbol search order. */
1980 rtld_multiple_ref = true;
1982 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1983 if (__glibc_likely (state.mode == rtld_mode_normal))
1985 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1986 ? main_map->l_searchlist.r_list[i + 1]
1987 : NULL);
1988 #ifdef NEED_DL_SYSINFO_DSO
1989 if (GLRO(dl_sysinfo_map) != NULL
1990 && GL(dl_rtld_map).l_prev->l_next == GLRO(dl_sysinfo_map)
1991 && GL(dl_rtld_map).l_next != GLRO(dl_sysinfo_map))
1992 GL(dl_rtld_map).l_prev = GLRO(dl_sysinfo_map);
1993 #endif
1995 else
1996 /* In trace mode there might be an invisible object (which we
1997 could not find) after the previous one in the search list.
1998 In this case it doesn't matter much where we put the
1999 interpreter object, so we just initialize the list pointer so
2000 that the assertion below holds. */
2001 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
2003 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
2004 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
2005 if (GL(dl_rtld_map).l_next != NULL)
2007 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
2008 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
2012 /* Now let us see whether all libraries are available in the
2013 versions we need. */
2015 struct version_check_args args;
2016 args.doexit = state.mode == rtld_mode_normal;
2017 args.dotrace = state.mode == rtld_mode_trace;
2018 _dl_receive_error (print_missing_version, version_check_doit, &args);
2021 /* We do not initialize any of the TLS functionality unless any of the
2022 initial modules uses TLS. This makes dynamic loading of modules with
2023 TLS impossible, but to support it requires either eagerly doing setup
2024 now or lazily doing it later. Doing it now makes us incompatible with
2025 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
2026 used. Trying to do it lazily is too hairy to try when there could be
2027 multiple threads (from a non-TLS-using libpthread). */
2028 bool was_tls_init_tp_called = tls_init_tp_called;
2029 if (tcbp == NULL)
2030 tcbp = init_tls (0);
2032 if (__glibc_likely (need_security_init))
2033 /* Initialize security features. But only if we have not done it
2034 earlier. */
2035 security_init ();
2037 if (__glibc_unlikely (state.mode != rtld_mode_normal))
2039 /* We were run just to list the shared libraries. It is
2040 important that we do this before real relocation, because the
2041 functions we call below for output may no longer work properly
2042 after relocation. */
2043 struct link_map *l;
2045 if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
2047 /* Look through the dependencies of the main executable
2048 and determine which of them is not actually
2049 required. */
2050 struct link_map *l = main_map;
2052 /* Relocate the main executable. */
2053 struct relocate_args args = { .l = l,
2054 .reloc_mode = ((GLRO(dl_lazy)
2055 ? RTLD_LAZY : 0)
2056 | __RTLD_NOIFUNC) };
2057 _dl_receive_error (print_unresolved, relocate_doit, &args);
2059 /* This loop depends on the dependencies of the executable to
2060 correspond in number and order to the DT_NEEDED entries. */
2061 ElfW(Dyn) *dyn = main_map->l_ld;
2062 bool first = true;
2063 while (dyn->d_tag != DT_NULL)
2065 if (dyn->d_tag == DT_NEEDED)
2067 l = l->l_next;
2068 #ifdef NEED_DL_SYSINFO_DSO
2069 /* Skip the VDSO since it's not part of the list
2070 of objects we brought in via DT_NEEDED entries. */
2071 if (l == GLRO(dl_sysinfo_map))
2072 l = l->l_next;
2073 #endif
2074 if (!l->l_used)
2076 if (first)
2078 _dl_printf ("Unused direct dependencies:\n");
2079 first = false;
2082 _dl_printf ("\t%s\n", l->l_name);
2086 ++dyn;
2089 _exit (first != true);
2091 else if (! main_map->l_info[DT_NEEDED])
2092 _dl_printf ("\tstatically linked\n");
2093 else
2095 for (l = state.mode_trace_program ? main_map : main_map->l_next;
2096 l; l = l->l_next) {
2097 if (l->l_faked)
2098 /* The library was not found. */
2099 _dl_printf ("\t%s => not found\n", l->l_libname->name);
2100 else
2101 _dl_printf ("\t%s => %s (0x%0*Zx)\n",
2102 DSO_FILENAME (l->l_libname->name),
2103 DSO_FILENAME (l->l_name),
2104 (int) sizeof l->l_map_start * 2,
2105 (size_t) l->l_map_start);
2109 if (__glibc_unlikely (state.mode != rtld_mode_trace))
2110 for (i = 1; i < (unsigned int) _dl_argc; ++i)
2112 const ElfW(Sym) *ref = NULL;
2113 ElfW(Addr) loadbase;
2114 lookup_t result;
2116 result = _dl_lookup_symbol_x (_dl_argv[i], main_map,
2117 &ref, main_map->l_scope,
2118 NULL, ELF_RTYPE_CLASS_PLT,
2119 DL_LOOKUP_ADD_DEPENDENCY, NULL);
2121 loadbase = LOOKUP_VALUE_ADDRESS (result, false);
2123 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
2124 _dl_argv[i],
2125 (int) sizeof ref->st_value * 2,
2126 (size_t) ref->st_value,
2127 (int) sizeof loadbase * 2, (size_t) loadbase);
2129 else
2131 /* If LD_WARN is set, warn about undefined symbols. */
2132 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
2134 /* We have to do symbol dependency testing. */
2135 struct relocate_args args;
2136 unsigned int i;
2138 args.reloc_mode = ((GLRO(dl_lazy) ? RTLD_LAZY : 0)
2139 | __RTLD_NOIFUNC);
2141 i = main_map->l_searchlist.r_nlist;
2142 while (i-- > 0)
2144 struct link_map *l = main_map->l_initfini[i];
2145 if (l != &GL(dl_rtld_map) && ! l->l_faked)
2147 args.l = l;
2148 _dl_receive_error (print_unresolved, relocate_doit,
2149 &args);
2154 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
2155 if (state.version_info)
2157 /* Print more information. This means here, print information
2158 about the versions needed. */
2159 int first = 1;
2160 struct link_map *map;
2162 for (map = main_map; map != NULL; map = map->l_next)
2164 const char *strtab;
2165 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
2166 ElfW(Verneed) *ent;
2168 if (dyn == NULL)
2169 continue;
2171 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
2172 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
2174 if (first)
2176 _dl_printf ("\n\tVersion information:\n");
2177 first = 0;
2180 _dl_printf ("\t%s:\n", DSO_FILENAME (map->l_name));
2182 while (1)
2184 ElfW(Vernaux) *aux;
2185 struct link_map *needed;
2187 needed = find_needed (strtab + ent->vn_file);
2188 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
2190 while (1)
2192 const char *fname = NULL;
2194 if (needed != NULL
2195 && match_version (strtab + aux->vna_name,
2196 needed))
2197 fname = needed->l_name;
2199 _dl_printf ("\t\t%s (%s) %s=> %s\n",
2200 strtab + ent->vn_file,
2201 strtab + aux->vna_name,
2202 aux->vna_flags & VER_FLG_WEAK
2203 ? "[WEAK] " : "",
2204 fname ?: "not found");
2206 if (aux->vna_next == 0)
2207 /* No more symbols. */
2208 break;
2210 /* Next symbol. */
2211 aux = (ElfW(Vernaux) *) ((char *) aux
2212 + aux->vna_next);
2215 if (ent->vn_next == 0)
2216 /* No more dependencies. */
2217 break;
2219 /* Next dependency. */
2220 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
2226 _exit (0);
2229 /* Now set up the variable which helps the assembler startup code. */
2230 GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
2232 /* Save the information about the original global scope list since
2233 we need it in the memory handling later. */
2234 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
2236 /* Remember the last search directory added at startup, now that
2237 malloc will no longer be the one from dl-minimal.c. As a side
2238 effect, this marks ld.so as initialized, so that the rtld_active
2239 function returns true from now on. */
2240 GLRO(dl_init_all_dirs) = GL(dl_all_dirs);
2242 /* Print scope information. */
2243 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_SCOPES))
2245 _dl_debug_printf ("\nInitial object scopes\n");
2247 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2248 _dl_show_scope (l, 0);
2251 _rtld_main_check (main_map, _dl_argv[0]);
2253 /* Now we have all the objects loaded. Relocate them all except for
2254 the dynamic linker itself. We do this in reverse order so that copy
2255 relocs of earlier objects overwrite the data written by later
2256 objects. We do not re-relocate the dynamic linker itself in this
2257 loop because that could result in the GOT entries for functions we
2258 call being changed, and that would break us. It is safe to relocate
2259 the dynamic linker out of order because it has no copy relocs (we
2260 know that because it is self-contained). */
2262 int consider_profiling = GLRO(dl_profile) != NULL;
2264 /* If we are profiling we also must do lazy reloaction. */
2265 GLRO(dl_lazy) |= consider_profiling;
2267 RTLD_TIMING_VAR (start);
2268 rtld_timer_start (&start);
2270 unsigned i = main_map->l_searchlist.r_nlist;
2271 while (i-- > 0)
2273 struct link_map *l = main_map->l_initfini[i];
2275 /* While we are at it, help the memory handling a bit. We have to
2276 mark some data structures as allocated with the fake malloc()
2277 implementation in ld.so. */
2278 struct libname_list *lnp = l->l_libname->next;
2280 while (__builtin_expect (lnp != NULL, 0))
2282 lnp->dont_free = 1;
2283 lnp = lnp->next;
2285 /* Also allocated with the fake malloc(). */
2286 l->l_free_initfini = 0;
2288 if (l != &GL(dl_rtld_map))
2289 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy) ? RTLD_LAZY : 0,
2290 consider_profiling);
2292 /* Add object to slot information data if necessasy. */
2293 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2294 _dl_add_to_slotinfo (l, true);
2297 rtld_timer_stop (&relocate_time, start);
2299 /* Now enable profiling if needed. Like the previous call,
2300 this has to go here because the calls it makes should use the
2301 rtld versions of the functions (particularly calloc()), but it
2302 needs to have _dl_profile_map set up by the relocator. */
2303 if (__glibc_unlikely (GL(dl_profile_map) != NULL))
2304 /* We must prepare the profiling. */
2305 _dl_start_profile ();
2307 if ((!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2308 || count_modids != _dl_count_modids ())
2309 ++GL(dl_tls_generation);
2311 /* Now that we have completed relocation, the initializer data
2312 for the TLS blocks has its final values and we can copy them
2313 into the main thread's TLS area, which we allocated above.
2314 Note: thread-local variables must only be accessed after completing
2315 the next step. */
2316 _dl_allocate_tls_init (tcbp, false);
2318 /* And finally install it for the main thread. */
2319 if (! tls_init_tp_called)
2321 const char *lossage = TLS_INIT_TP (tcbp);
2322 if (__glibc_unlikely (lossage != NULL))
2323 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2324 lossage);
2325 __tls_init_tp ();
2328 /* Make sure no new search directories have been added. */
2329 assert (GLRO(dl_init_all_dirs) == GL(dl_all_dirs));
2331 if (rtld_multiple_ref)
2333 /* There was an explicit ref to the dynamic linker as a shared lib.
2334 Re-relocate ourselves with user-controlled symbol definitions.
2336 We must do this after TLS initialization in case after this
2337 re-relocation, we might call a user-supplied function
2338 (e.g. calloc from _dl_relocate_object) that uses TLS data. */
2340 /* Set up the object lookup structures. */
2341 _dl_find_object_init ();
2343 /* The malloc implementation has been relocated, so resolving
2344 its symbols (and potentially calling IFUNC resolvers) is safe
2345 at this point. */
2346 __rtld_malloc_init_real (main_map);
2348 /* Likewise for the locking implementation. */
2349 __rtld_mutex_init ();
2351 RTLD_TIMING_VAR (start);
2352 rtld_timer_start (&start);
2354 /* Mark the link map as not yet relocated again. */
2355 GL(dl_rtld_map).l_relocated = 0;
2356 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2358 rtld_timer_accum (&relocate_time, start);
2361 /* Relocation is complete. Perform early libc initialization. This
2362 is the initial libc, even if audit modules have been loaded with
2363 other libcs. */
2364 _dl_call_libc_early_init (GL(dl_ns)[LM_ID_BASE].libc_map, true);
2366 /* Do any necessary cleanups for the startup OS interface code.
2367 We do these now so that no calls are made after rtld re-relocation
2368 which might be resolved to different functions than we expect.
2369 We cannot do this before relocating the other objects because
2370 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2371 _dl_sysdep_start_cleanup ();
2373 #ifdef SHARED
2374 /* Auditing checkpoint: we have added all objects. */
2375 _dl_audit_activity_nsid (LM_ID_BASE, LA_ACT_CONSISTENT);
2376 #endif
2378 /* Notify the debugger all new objects are now ready to go. We must re-get
2379 the address since by now the variable might be in another object. */
2380 r = _dl_debug_update (LM_ID_BASE);
2381 r->r_state = RT_CONSISTENT;
2382 _dl_debug_state ();
2383 LIBC_PROBE (init_complete, 2, LM_ID_BASE, r);
2385 #if defined USE_LDCONFIG && !defined MAP_COPY
2386 /* We must munmap() the cache file. */
2387 _dl_unload_cache ();
2388 #endif
2390 /* Once we return, _dl_sysdep_start will invoke
2391 the DT_INIT functions and then *USER_ENTRY. */
2394 /* This is a little helper function for resolving symbols while
2395 tracing the binary. */
2396 static void
2397 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2398 const char *errstring)
2400 if (objname[0] == '\0')
2401 objname = RTLD_PROGNAME;
2402 _dl_error_printf ("%s (%s)\n", errstring, objname);
2405 /* This is a little helper function for resolving symbols while
2406 tracing the binary. */
2407 static void
2408 print_missing_version (int errcode __attribute__ ((unused)),
2409 const char *objname, const char *errstring)
2411 _dl_error_printf ("%s: %s: %s\n", RTLD_PROGNAME,
2412 objname, errstring);
2415 /* Process the string given as the parameter which explains which debugging
2416 options are enabled. */
2417 static void
2418 process_dl_debug (struct dl_main_state *state, const char *dl_debug)
2420 /* When adding new entries make sure that the maximal length of a name
2421 is correctly handled in the LD_DEBUG_HELP code below. */
2422 static const struct
2424 unsigned char len;
2425 const char name[10];
2426 const char helptext[41];
2427 unsigned short int mask;
2428 } debopts[] =
2430 #define LEN_AND_STR(str) sizeof (str) - 1, str
2431 { LEN_AND_STR ("libs"), "display library search paths",
2432 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2433 { LEN_AND_STR ("reloc"), "display relocation processing",
2434 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2435 { LEN_AND_STR ("files"), "display progress for input file",
2436 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2437 { LEN_AND_STR ("symbols"), "display symbol table processing",
2438 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2439 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2440 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2441 { LEN_AND_STR ("versions"), "display version dependencies",
2442 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2443 { LEN_AND_STR ("scopes"), "display scope information",
2444 DL_DEBUG_SCOPES },
2445 { LEN_AND_STR ("all"), "all previous options combined",
2446 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2447 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS
2448 | DL_DEBUG_SCOPES },
2449 { LEN_AND_STR ("statistics"), "display relocation statistics",
2450 DL_DEBUG_STATISTICS },
2451 { LEN_AND_STR ("unused"), "determined unused DSOs",
2452 DL_DEBUG_UNUSED },
2453 { LEN_AND_STR ("help"), "display this help message and exit",
2454 DL_DEBUG_HELP },
2456 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2458 /* Skip separating white spaces and commas. */
2459 while (*dl_debug != '\0')
2461 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2463 size_t cnt;
2464 size_t len = 1;
2466 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2467 && dl_debug[len] != ',' && dl_debug[len] != ':')
2468 ++len;
2470 for (cnt = 0; cnt < ndebopts; ++cnt)
2471 if (debopts[cnt].len == len
2472 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
2474 GLRO(dl_debug_mask) |= debopts[cnt].mask;
2475 state->any_debug = true;
2476 break;
2479 if (cnt == ndebopts)
2481 /* Display a warning and skip everything until next
2482 separator. */
2483 char *copy = strndupa (dl_debug, len);
2484 _dl_error_printf ("\
2485 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2488 dl_debug += len;
2489 continue;
2492 ++dl_debug;
2495 if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
2497 /* In order to get an accurate picture of whether a particular
2498 DT_NEEDED entry is actually used we have to process both
2499 the PLT and non-PLT relocation entries. */
2500 GLRO(dl_lazy) = 0;
2503 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
2505 size_t cnt;
2507 _dl_printf ("\
2508 Valid options for the LD_DEBUG environment variable are:\n\n");
2510 for (cnt = 0; cnt < ndebopts; ++cnt)
2511 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2512 " " + debopts[cnt].len - 3,
2513 debopts[cnt].helptext);
2515 _dl_printf ("\n\
2516 To direct the debugging output into a file instead of standard output\n\
2517 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2518 _exit (0);
2522 static void
2523 process_envvars (struct dl_main_state *state)
2525 char **runp = _environ;
2526 char *envline;
2527 char *debug_output = NULL;
2529 /* This is the default place for profiling data file. */
2530 GLRO(dl_profile_output)
2531 = &"/var/tmp\0/var/profile"[__libc_enable_secure ? 9 : 0];
2533 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2535 size_t len = 0;
2537 while (envline[len] != '\0' && envline[len] != '=')
2538 ++len;
2540 if (envline[len] != '=')
2541 /* This is a "LD_" variable at the end of the string without
2542 a '=' character. Ignore it since otherwise we will access
2543 invalid memory below. */
2544 continue;
2546 switch (len)
2548 case 4:
2549 /* Warning level, verbose or not. */
2550 if (memcmp (envline, "WARN", 4) == 0)
2551 GLRO(dl_verbose) = envline[5] != '\0';
2552 break;
2554 case 5:
2555 /* Debugging of the dynamic linker? */
2556 if (memcmp (envline, "DEBUG", 5) == 0)
2558 process_dl_debug (state, &envline[6]);
2559 break;
2561 if (memcmp (envline, "AUDIT", 5) == 0)
2562 audit_list_add_string (&state->audit_list, &envline[6]);
2563 break;
2565 case 7:
2566 /* Print information about versions. */
2567 if (memcmp (envline, "VERBOSE", 7) == 0)
2569 state->version_info = envline[8] != '\0';
2570 break;
2573 /* List of objects to be preloaded. */
2574 if (memcmp (envline, "PRELOAD", 7) == 0)
2576 state->preloadlist = &envline[8];
2577 break;
2580 /* Which shared object shall be profiled. */
2581 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2582 GLRO(dl_profile) = &envline[8];
2583 break;
2585 case 8:
2586 /* Do we bind early? */
2587 if (memcmp (envline, "BIND_NOW", 8) == 0)
2589 GLRO(dl_lazy) = envline[9] == '\0';
2590 break;
2592 if (memcmp (envline, "BIND_NOT", 8) == 0)
2593 GLRO(dl_bind_not) = envline[9] != '\0';
2594 break;
2596 case 9:
2597 /* Test whether we want to see the content of the auxiliary
2598 array passed up from the kernel. */
2599 if (!__libc_enable_secure
2600 && memcmp (envline, "SHOW_AUXV", 9) == 0)
2601 _dl_show_auxv ();
2602 break;
2604 #if !HAVE_TUNABLES
2605 case 10:
2606 /* Mask for the important hardware capabilities. */
2607 if (!__libc_enable_secure
2608 && memcmp (envline, "HWCAP_MASK", 10) == 0)
2609 GLRO(dl_hwcap_mask) = _dl_strtoul (&envline[11], NULL);
2610 break;
2611 #endif
2613 case 11:
2614 /* Path where the binary is found. */
2615 if (!__libc_enable_secure
2616 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2617 GLRO(dl_origin_path) = &envline[12];
2618 break;
2620 case 12:
2621 /* The library search path. */
2622 if (!__libc_enable_secure
2623 && memcmp (envline, "LIBRARY_PATH", 12) == 0)
2625 state->library_path = &envline[13];
2626 state->library_path_source = "LD_LIBRARY_PATH";
2627 break;
2630 /* Where to place the profiling data file. */
2631 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2633 debug_output = &envline[13];
2634 break;
2637 if (!__libc_enable_secure
2638 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2639 GLRO(dl_dynamic_weak) = 1;
2640 break;
2642 case 13:
2643 /* We might have some extra environment variable with length 13
2644 to handle. */
2645 #ifdef EXTRA_LD_ENVVARS_13
2646 EXTRA_LD_ENVVARS_13
2647 #endif
2648 break;
2650 case 14:
2651 /* Where to place the profiling data file. */
2652 if (!__libc_enable_secure
2653 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2654 && envline[15] != '\0')
2655 GLRO(dl_profile_output) = &envline[15];
2656 break;
2658 case 20:
2659 /* The mode of the dynamic linker can be set. */
2660 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2662 state->mode = rtld_mode_trace;
2663 state->mode_trace_program
2664 = _dl_strtoul (&envline[21], NULL) > 1;
2666 break;
2668 /* We might have some extra environment variable to handle. This
2669 is tricky due to the pre-processing of the length of the name
2670 in the switch statement here. The code here assumes that added
2671 environment variables have a different length. */
2672 #ifdef EXTRA_LD_ENVVARS
2673 EXTRA_LD_ENVVARS
2674 #endif
2678 /* Extra security for SUID binaries. Remove all dangerous environment
2679 variables. */
2680 if (__builtin_expect (__libc_enable_secure, 0))
2682 static const char unsecure_envvars[] =
2683 #ifdef EXTRA_UNSECURE_ENVVARS
2684 EXTRA_UNSECURE_ENVVARS
2685 #endif
2686 UNSECURE_ENVVARS;
2687 const char *nextp;
2689 nextp = unsecure_envvars;
2692 unsetenv (nextp);
2693 /* We could use rawmemchr but this need not be fast. */
2694 nextp = (char *) (strchr) (nextp, '\0') + 1;
2696 while (*nextp != '\0');
2698 if (__access ("/etc/suid-debug", F_OK) != 0)
2700 #if !HAVE_TUNABLES
2701 unsetenv ("MALLOC_CHECK_");
2702 #endif
2703 GLRO(dl_debug_mask) = 0;
2706 if (state->mode != rtld_mode_normal)
2707 _exit (5);
2709 /* If we have to run the dynamic linker in debugging mode and the
2710 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2711 messages to this file. */
2712 else if (state->any_debug && debug_output != NULL)
2714 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2715 size_t name_len = strlen (debug_output);
2716 char buf[name_len + 12];
2717 char *startp;
2719 buf[name_len + 11] = '\0';
2720 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2721 *--startp = '.';
2722 startp = memcpy (startp - name_len, debug_output, name_len);
2724 GLRO(dl_debug_fd) = __open64_nocancel (startp, flags, DEFFILEMODE);
2725 if (GLRO(dl_debug_fd) == -1)
2726 /* We use standard output if opening the file failed. */
2727 GLRO(dl_debug_fd) = STDOUT_FILENO;
2731 #if HP_TIMING_INLINE
2732 static void
2733 print_statistics_item (const char *title, hp_timing_t time,
2734 hp_timing_t total)
2736 char cycles[HP_TIMING_PRINT_SIZE];
2737 HP_TIMING_PRINT (cycles, sizeof (cycles), time);
2739 char relative[3 * sizeof (hp_timing_t) + 2];
2740 char *cp = _itoa ((1000ULL * time) / total, relative + sizeof (relative),
2741 10, 0);
2742 /* Sets the decimal point. */
2743 char *wp = relative;
2744 switch (relative + sizeof (relative) - cp)
2746 case 3:
2747 *wp++ = *cp++;
2748 /* Fall through. */
2749 case 2:
2750 *wp++ = *cp++;
2751 /* Fall through. */
2752 case 1:
2753 *wp++ = '.';
2754 *wp++ = *cp++;
2756 *wp = '\0';
2757 _dl_debug_printf ("%s: %s cycles (%s%%)\n", title, cycles, relative);
2759 #endif
2761 /* Print the various times we collected. */
2762 static void
2763 __attribute ((noinline))
2764 print_statistics (const hp_timing_t *rtld_total_timep)
2766 #if HP_TIMING_INLINE
2768 char cycles[HP_TIMING_PRINT_SIZE];
2769 HP_TIMING_PRINT (cycles, sizeof (cycles), *rtld_total_timep);
2770 _dl_debug_printf ("\nruntime linker statistics:\n"
2771 " total startup time in dynamic loader: %s cycles\n",
2772 cycles);
2773 print_statistics_item (" time needed for relocation",
2774 relocate_time, *rtld_total_timep);
2776 #endif
2778 unsigned long int num_relative_relocations = 0;
2779 for (Lmid_t ns = 0; ns < GL(dl_nns); ++ns)
2781 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2782 continue;
2784 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2786 for (unsigned int i = 0; i < scope->r_nlist; i++)
2788 struct link_map *l = scope->r_list [i];
2790 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2791 num_relative_relocations
2792 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2793 #ifndef ELF_MACHINE_REL_RELATIVE
2794 /* Relative relocations are processed on these architectures if
2795 library is loaded to different address than p_vaddr. */
2796 if ((l->l_addr != 0)
2797 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2798 #else
2799 /* On e.g. IA-64 or Alpha, relative relocations are processed
2800 only if library is loaded to different address than p_vaddr. */
2801 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2802 #endif
2803 num_relative_relocations
2804 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2808 _dl_debug_printf (" number of relocations: %lu\n"
2809 " number of relocations from cache: %lu\n"
2810 " number of relative relocations: %lu\n",
2811 GL(dl_num_relocations),
2812 GL(dl_num_cache_relocations),
2813 num_relative_relocations);
2815 #if HP_TIMING_INLINE
2816 print_statistics_item (" time needed to load objects",
2817 load_time, *rtld_total_timep);
2818 #endif