1 /* Run time dynamic linker.
2 Copyright (C) 1995-2025 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/>. */
27 #include <sys/param.h>
32 #include <fpu_control.h>
33 #include <hp-timing.h>
34 #include <libc-lock.h>
35 #include <unsecvars.h>
37 #include <dl-osinfo.h>
40 #include <dl-vdso-setup.h>
42 #include <stap-probe.h>
43 #include <stackinfo.h>
44 #include <not-cancel.h>
45 #include <array_length.h>
46 #include <libc-early-init.h>
48 #include <gnu/lib-names.h>
49 #include <dl-tunables.h>
50 #include <get-dynamic-info.h>
51 #include <dl-execve.h>
52 #include <dl-find_object.h>
53 #include <dl-audit-check.h>
54 #include <dl-call_tls_init_tp.h>
58 /* This #define produces dynamic linking inline functions for
59 bootstrap relocation instead of general-purpose relocation.
60 Since ld.so must not have any undefined symbols the result
61 is trivial: always the map of ld.so itself. */
62 #define RTLD_BOOTSTRAP
63 #define RESOLVE_MAP(map, scope, sym, version, flags) map
64 #include "dynamic-link.h"
66 /* Must include after <dl-machine.h> for DT_MIPS definition. */
69 /* Only enables rtld profiling for architectures which provides non generic
70 hp-timing support. The generic support requires either syscall
71 (clock_gettime), which will incur in extra overhead on loading time.
72 Using vDSO is also an option, but it will require extra support on loader
73 to setup the vDSO pointer before its usage. */
75 # define RLTD_TIMING_DECLARE(var, classifier,...) \
76 classifier hp_timing_t var __VA_ARGS__
77 # define RTLD_TIMING_VAR(var) RLTD_TIMING_DECLARE (var, )
78 # define RTLD_TIMING_SET(var, value) (var) = (value)
79 # define RTLD_TIMING_REF(var) &(var)
82 rtld_timer_start (hp_timing_t
*var
)
88 rtld_timer_stop (hp_timing_t
*var
, hp_timing_t start
)
92 HP_TIMING_DIFF (*var
, start
, stop
);
96 rtld_timer_accum (hp_timing_t
*sum
, hp_timing_t start
)
99 rtld_timer_stop (&stop
, start
);
100 HP_TIMING_ACCUM_NT(*sum
, stop
);
103 # define RLTD_TIMING_DECLARE(var, classifier...)
104 # define RTLD_TIMING_SET(var, value)
105 # define RTLD_TIMING_VAR(var)
106 # define RTLD_TIMING_REF(var) 0
107 # define rtld_timer_start(var)
108 # define rtld_timer_stop(var, start)
109 # define rtld_timer_accum(sum, start)
112 /* Avoid PLT use for our local calls at startup. */
113 extern __typeof (__mempcpy
) __mempcpy attribute_hidden
;
115 /* GCC has mental blocks about _exit. */
116 extern __typeof (_exit
) exit_internal
asm ("_exit") attribute_hidden
;
117 #define _exit exit_internal
119 /* Helper function to handle errors while resolving symbols. */
120 static void print_unresolved (int errcode
, const char *objname
,
121 const char *errsting
);
123 /* Helper function to handle errors when a version is missing. */
124 static void print_missing_version (int errcode
, const char *objname
,
125 const char *errsting
);
127 /* Print the various times we collected. */
128 static void print_statistics (const hp_timing_t
*total_timep
);
130 /* Creates an empty audit list. */
131 static void audit_list_init (struct audit_list
*);
133 /* Add a string to the end of the audit list, for later parsing. Must
134 not be called after audit_list_next. */
135 static void audit_list_add_string (struct audit_list
*, const char *);
137 /* Add the audit strings from the link map, found in the dynamic
138 segment at TG (either DT_AUDIT and DT_DEPAUDIT). Must be called
139 before audit_list_next. */
140 static void audit_list_add_dynamic_tag (struct audit_list
*,
144 /* Extract the next audit module from the audit list. Only modules
145 for which dso_name_valid_for_suid is true are returned. Must be
146 called after all the audit_list_add_string,
147 audit_list_add_dynamic_tags calls. */
148 static const char *audit_list_next (struct audit_list
*);
150 /* Initialize *STATE with the defaults. */
151 static void dl_main_state_init (struct dl_main_state
*state
);
153 /* Process all environments variables the dynamic linker must recognize.
154 Since all of them start with `LD_' we are a bit smarter while finding
156 extern char **_environ attribute_hidden
;
157 static int process_envvars (struct dl_main_state
*state
);
159 int _dl_argc attribute_relro attribute_hidden
;
160 char **_dl_argv attribute_relro
= NULL
;
161 rtld_hidden_data_def (_dl_argv
)
163 #ifndef THREAD_SET_STACK_GUARD
164 /* Only exported for architectures that don't store the stack guard canary
165 in thread local area. */
166 uintptr_t __stack_chk_guard attribute_relro
;
169 /* Only exported for architectures that don't store the pointer guard
170 value in thread local area. */
171 uintptr_t __pointer_chk_guard_local attribute_relro attribute_hidden
;
172 #ifndef THREAD_SET_POINTER_GUARD
173 strong_alias (__pointer_chk_guard_local
, __pointer_chk_guard
)
176 /* Check that AT_SECURE=0, or that the passed name does not contain
177 directories and is not overly long. Reject empty names
180 dso_name_valid_for_suid (const char *p
)
182 if (__glibc_unlikely (__libc_enable_secure
))
184 /* Ignore pathnames with directories for AT_SECURE=1
185 programs, and also skip overlong names. */
186 size_t len
= strlen (p
);
187 if (len
>= SECURE_NAME_LIMIT
|| memchr (p
, '/', len
) != NULL
)
194 audit_list_init (struct audit_list
*list
)
197 list
->current_index
= 0;
198 list
->current_tail
= NULL
;
202 audit_list_add_string (struct audit_list
*list
, const char *string
)
204 /* Empty strings do not load anything. */
208 if (list
->length
== array_length (list
->audit_strings
))
209 _dl_fatal_printf ("Fatal glibc error: Too many audit modules requested\n");
211 list
->audit_strings
[list
->length
++] = string
;
213 /* Initialize processing of the first string for
215 if (list
->length
== 1)
216 list
->current_tail
= string
;
220 audit_list_add_dynamic_tag (struct audit_list
*list
, struct link_map
*main_map
,
223 ElfW(Dyn
) *info
= main_map
->l_info
[ADDRIDX (tag
)];
224 const char *strtab
= (const char *) D_PTR (main_map
, l_info
[DT_STRTAB
]);
226 audit_list_add_string (list
, strtab
+ info
->d_un
.d_val
);
230 audit_list_next (struct audit_list
*list
)
232 if (list
->current_tail
== NULL
)
237 /* Advance to the next string in audit_strings if the current
238 string has been exhausted. */
239 while (*list
->current_tail
== '\0')
241 ++list
->current_index
;
242 if (list
->current_index
== list
->length
)
244 list
->current_tail
= NULL
;
247 list
->current_tail
= list
->audit_strings
[list
->current_index
];
250 /* Split the in-string audit list at the next colon colon. */
251 size_t len
= strcspn (list
->current_tail
, ":");
252 if (len
> 0 && len
< sizeof (list
->fname
))
254 memcpy (list
->fname
, list
->current_tail
, len
);
255 list
->fname
[len
] = '\0';
258 /* Mark the name as unusable for dso_name_valid_for_suid. */
259 list
->fname
[0] = '\0';
261 /* Skip over the substring and the following delimiter. */
262 list
->current_tail
+= len
;
263 if (*list
->current_tail
== ':')
264 ++list
->current_tail
;
266 /* If the name is valid, return it. */
267 if (dso_name_valid_for_suid (list
->fname
))
270 /* Otherwise wrap around to find the next list element. . */
274 /* Count audit modules before they are loaded so GLRO(dl_naudit)
275 is not yet usable. */
277 audit_list_count (struct audit_list
*list
)
279 /* Restore the audit_list iterator state at the end. */
280 const char *saved_tail
= list
->current_tail
;
283 assert (list
->current_index
== 0);
284 while (audit_list_next (list
) != NULL
)
286 list
->current_tail
= saved_tail
;
287 list
->current_index
= 0;
292 dl_main_state_init (struct dl_main_state
*state
)
294 audit_list_init (&state
->audit_list
);
295 state
->library_path
= NULL
;
296 state
->library_path_source
= NULL
;
297 state
->preloadlist
= NULL
;
298 state
->preloadarg
= NULL
;
299 state
->glibc_hwcaps_prepend
= NULL
;
300 state
->glibc_hwcaps_mask
= NULL
;
301 state
->mode
= rtld_mode_normal
;
302 state
->version_info
= false;
305 #ifndef HAVE_INLINED_SYSCALLS
306 /* Set nonzero during loading and initialization of executable and
307 libraries, cleared before the executable's entry point runs. This
308 must not be initialized to nonzero, because the unused dynamic
309 linker loaded in for libc.so's "ld.so.1" dep will provide the
310 definition seen by libc.so's initializer; that value must be zero,
311 and will be since that dynamic linker's _dl_start and dl_main will
313 int _dl_starting_up
= 0;
314 rtld_hidden_def (_dl_starting_up
)
317 /* This is the structure which defines all variables global to ld.so
318 (except those which cannot be added for some reason). */
319 struct rtld_global _rtld_global
=
321 /* Get architecture specific initializer. */
322 #include <dl-procruntime.c>
323 /* Generally the default presumption without further information is an
324 * executable stack but this is not true for all platforms. */
325 ._dl_stack_flags
= DEFAULT_STACK_PERMS
,
326 #ifdef _LIBC_REENTRANT
327 ._dl_load_lock
= _RTLD_LOCK_RECURSIVE_INITIALIZER
,
328 ._dl_load_write_lock
= _RTLD_LOCK_RECURSIVE_INITIALIZER
,
329 ._dl_load_tls_lock
= _RTLD_LOCK_RECURSIVE_INITIALIZER
,
334 #ifdef _LIBC_REENTRANT
335 [LM_ID_BASE
] = { ._ns_unique_sym_table
336 = { .lock
= _RTLD_LOCK_RECURSIVE_INITIALIZER
} }
340 /* If we would use strong_alias here the compiler would see a
341 non-hidden definition. This would undo the effect of the previous
342 declaration. So spell out what strong_alias does plus add the
343 visibility attribute. */
344 extern struct rtld_global _rtld_local
345 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
348 /* This variable is similar to _rtld_local, but all values are
349 read-only after relocation. */
350 struct rtld_global_ro _rtld_global_ro attribute_relro
=
352 /* Get architecture specific initializer. */
353 #include <dl-procinfo.c>
354 #ifdef NEED_DL_SYSINFO
355 ._dl_sysinfo
= DL_SYSINFO_DEFAULT
,
357 ._dl_debug_fd
= STDERR_FILENO
,
359 ._dl_fpu_control
= _FPU_DEFAULT
,
360 ._dl_pagesize
= EXEC_PAGESIZE
,
361 ._dl_inhibit_cache
= 0,
362 ._dl_profile_output
= "/var/tmp",
364 /* Function pointers. */
365 ._dl_debug_printf
= _dl_debug_printf
,
366 ._dl_mcount
= _dl_mcount
,
367 ._dl_lookup_symbol_x
= _dl_lookup_symbol_x
,
368 ._dl_open
= _dl_open
,
369 ._dl_close
= _dl_close
,
370 ._dl_catch_error
= _dl_catch_error
,
371 ._dl_error_free
= _dl_error_free
,
372 ._dl_tls_get_addr_soft
= _dl_tls_get_addr_soft
,
373 ._dl_libc_freeres
= __rtld_libc_freeres
,
374 ._dl_readonly_area
= _dl_readonly_area
,
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")));
383 struct link_map _dl_rtld_map
;
384 struct auditstate _dl_rtld_auditstate
[DL_NNS
];
386 static void dl_main (const ElfW(Phdr
) *phdr
, ElfW(Word
) phnum
,
387 ElfW(Addr
) *user_entry
, ElfW(auxv_t
) *auxv
);
389 /* These two variables cannot be moved into .data.rel.ro. */
390 static struct libname_list _dl_rtld_libname
;
392 /* Variable for statistics. */
393 RLTD_TIMING_DECLARE (relocate_time
, static);
394 RLTD_TIMING_DECLARE (load_time
, static, attribute_relro
);
395 RLTD_TIMING_DECLARE (start_time
, static, attribute_relro
);
397 /* Additional definitions needed by TLS initialization. */
398 #ifdef TLS_INIT_HELPER
402 /* Helper function for syscall implementation. */
403 #ifdef DL_SYSINFO_IMPLEMENTATION
404 DL_SYSINFO_IMPLEMENTATION
407 /* Before ld.so is relocated we must not access variables which need
408 relocations. This means variables which are exported. Variables
409 declared as static are fine. If we can mark a variable hidden this
410 is fine, too. The latter is important here. We can avoid setting
411 up a temporary link map for ld.so if we can mark _rtld_global as
413 #ifndef HIDDEN_VAR_NEEDS_DYNAMIC_RELOC
414 # define DONT_USE_BOOTSTRAP_MAP 1
417 #ifdef DONT_USE_BOOTSTRAP_MAP
418 static ElfW(Addr
) _dl_start_final (void *arg
);
420 struct dl_start_final_info
423 RTLD_TIMING_VAR (start_time
);
425 static ElfW(Addr
) _dl_start_final (void *arg
,
426 struct dl_start_final_info
*info
);
429 /* These are defined magically by the linker. */
430 extern const ElfW(Ehdr
) __ehdr_start attribute_hidden
;
431 extern char _end
[] attribute_hidden
;
437 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
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
)
450 static ElfW(Addr
) __attribute__ ((noinline
))
451 _dl_start_final (void *arg
, struct dl_start_final_info
*info
)
454 ElfW(Addr
) start_addr
;
456 __rtld_malloc_init_stubs ();
458 /* Do not use an initializer for these members because it would
459 interfere with __rtld_static_init. */
460 GLRO (dl_find_object
) = &_dl_find_object
;
462 /* If it hasn't happen yet record the startup time. */
463 rtld_timer_start (&start_time
);
464 #if !defined DONT_USE_BOOTSTRAP_MAP
465 RTLD_TIMING_SET (start_time
, info
->start_time
);
468 /* Transfer data about ourselves to the permanent link_map structure. */
469 #ifndef DONT_USE_BOOTSTRAP_MAP
470 _dl_rtld_map
.l_addr
= info
->l
.l_addr
;
471 _dl_rtld_map
.l_ld
= info
->l
.l_ld
;
472 _dl_rtld_map
.l_ld_readonly
= info
->l
.l_ld_readonly
;
473 memcpy (_dl_rtld_map
.l_info
, info
->l
.l_info
, sizeof _dl_rtld_map
.l_info
);
474 _dl_rtld_map
.l_mach
= info
->l
.l_mach
;
475 _dl_rtld_map
.l_relocated
= 1;
477 _dl_setup_hash (&_dl_rtld_map
);
478 _dl_rtld_map
.l_real
= &_dl_rtld_map
;
479 _dl_rtld_map
.l_map_start
480 = (ElfW(Addr
)) DL_ADDRESS_WITHOUT_RELOC (&__ehdr_start
);
481 _dl_rtld_map
.l_map_end
482 = (ElfW(Addr
)) DL_ADDRESS_WITHOUT_RELOC (_end
);
483 /* Copy the TLS related data if necessary. */
484 #ifndef DONT_USE_BOOTSTRAP_MAP
485 # if NO_TLS_OFFSET != 0
486 _dl_rtld_map
.l_tls_offset
= NO_TLS_OFFSET
;
490 /* Initialize the stack end variable. */
491 __libc_stack_end
= __builtin_frame_address (0);
493 /* Call the OS-dependent function to set up life so we can do things like
494 file access. It will call `dl_main' (below) to do all the real work
495 of the dynamic linker, and then unwind our frame and run the user
496 entry point on the same stack we entered on. */
497 start_addr
= _dl_sysdep_start (arg
, &dl_main
);
499 if (__glibc_unlikely (GLRO(dl_debug_mask
) & DL_DEBUG_STATISTICS
))
501 RTLD_TIMING_VAR (rtld_total_time
);
502 rtld_timer_stop (&rtld_total_time
, start_time
);
503 print_statistics (RTLD_TIMING_REF(rtld_total_time
));
506 #ifndef ELF_MACHINE_START_ADDRESS
507 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
509 return ELF_MACHINE_START_ADDRESS (GL(dl_ns
)[LM_ID_BASE
]._ns_loaded
, start_addr
);
512 #ifdef DONT_USE_BOOTSTRAP_MAP
513 # define bootstrap_map _dl_rtld_map
515 # define bootstrap_map info.l
518 static ElfW(Addr
) __attribute_used__
519 _dl_start (void *arg
)
521 #ifdef DONT_USE_BOOTSTRAP_MAP
522 rtld_timer_start (&start_time
);
524 struct dl_start_final_info info
;
525 rtld_timer_start (&info
.start_time
);
528 /* Partly clean the `bootstrap_map' structure up. Don't use
529 `memset' since it might not be built in or inlined and we cannot
530 make function calls at this point. Use '__builtin_memset' if we
531 know it is available. We do not have to clear the memory if we
532 do not have to use the temporary bootstrap_map. Global variables
533 are initialized to zero by default. */
534 #ifndef DONT_USE_BOOTSTRAP_MAP
535 # ifdef HAVE_BUILTIN_MEMSET
536 __builtin_memset (bootstrap_map
.l_info
, '\0', sizeof (bootstrap_map
.l_info
));
539 cnt
< sizeof (bootstrap_map
.l_info
) / sizeof (bootstrap_map
.l_info
[0]);
541 bootstrap_map
.l_info
[cnt
] = 0;
545 /* Figure out the run-time load address of the dynamic linker itself. */
546 bootstrap_map
.l_addr
= elf_machine_load_address ();
548 /* Read our own dynamic section and fill in the info array. */
549 bootstrap_map
.l_ld
= (void *) bootstrap_map
.l_addr
+ elf_machine_dynamic ();
550 bootstrap_map
.l_ld_readonly
= DL_RO_DYN_SECTION
;
551 elf_get_dynamic_info (&bootstrap_map
, true, false);
553 #if NO_TLS_OFFSET != 0
554 bootstrap_map
.l_tls_offset
= NO_TLS_OFFSET
;
557 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
558 ELF_MACHINE_BEFORE_RTLD_RELOC (&bootstrap_map
, bootstrap_map
.l_info
);
561 if (bootstrap_map
.l_addr
)
563 /* Relocate ourselves so we can do normal function calls and
564 data access using the global offset table. */
566 ELF_DYNAMIC_RELOCATE (&bootstrap_map
, NULL
, 0, 0, 0);
568 bootstrap_map
.l_relocated
= 1;
570 /* Please note that we don't allow profiling of this object and
571 therefore need not test whether we have to allocate the array
572 for the relocation results (as done in dl-reloc.c). */
574 /* Now life is sane; we can call functions and access global data.
575 Set up to use the operating system facilities, and find out from
576 the operating system's program loader where to find the program
577 header table in core. Put the rest of _dl_start into a separate
578 function, that way the compiler cannot put accesses to the GOT
579 before ELF_DYNAMIC_RELOCATE. */
581 #ifdef DONT_USE_BOOTSTRAP_MAP
582 return _dl_start_final (arg
);
584 return _dl_start_final (arg
, &info
);
590 /* Now life is peachy; we can do all normal operations.
591 On to the real work. */
593 /* Some helper functions. */
595 /* Arguments to relocate_doit. */
604 /* Argument to map_doit. */
606 struct link_map
*loader
;
608 /* Return value of map_doit. */
609 struct link_map
*map
;
615 struct link_map
*map
;
621 struct link_map
*map
;
625 /* Arguments to version_check_doit. */
626 struct version_check_args
633 relocate_doit (void *a
)
635 struct relocate_args
*args
= (struct relocate_args
*) a
;
637 _dl_relocate_object (args
->l
, args
->l
->l_scope
, args
->reloc_mode
, 0);
643 struct map_args
*args
= (struct map_args
*) a
;
644 int type
= (args
->mode
== __RTLD_OPENEXEC
) ? lt_executable
: lt_library
;
645 args
->map
= _dl_map_object (args
->loader
, args
->str
, type
, 0,
646 args
->mode
, LM_ID_BASE
);
650 dlmopen_doit (void *a
)
652 struct dlmopen_args
*args
= (struct dlmopen_args
*) a
;
653 args
->map
= _dl_open (args
->fname
,
654 (RTLD_LAZY
| __RTLD_DLOPEN
| __RTLD_AUDIT
656 dl_main
, LM_ID_NEWLM
, _dl_argc
, _dl_argv
,
661 lookup_doit (void *a
)
663 struct lookup_args
*args
= (struct lookup_args
*) a
;
664 const ElfW(Sym
) *ref
= NULL
;
666 lookup_t l
= _dl_lookup_symbol_x (args
->name
, args
->map
, &ref
,
667 args
->map
->l_local_scope
, NULL
, 0,
668 DL_LOOKUP_RETURN_NEWEST
, NULL
);
670 args
->result
= DL_SYMBOL_ADDRESS (l
, ref
);
674 version_check_doit (void *a
)
676 struct version_check_args
*args
= (struct version_check_args
*) a
;
677 if (_dl_check_all_versions (GL(dl_ns
)[LM_ID_BASE
]._ns_loaded
, 1,
678 args
->dotrace
) && args
->doexit
)
679 /* We cannot start the application. Abort now. */
684 static inline struct link_map
*
685 find_needed (const char *name
)
687 struct r_scope_elem
*scope
= &GL(dl_ns
)[LM_ID_BASE
]._ns_loaded
->l_searchlist
;
688 unsigned int n
= scope
->r_nlist
;
691 if (_dl_name_match_p (name
, scope
->r_list
[n
]))
692 return scope
->r_list
[n
];
694 /* Should never happen. */
699 match_version (const char *string
, struct link_map
*map
)
701 const char *strtab
= (const void *) D_PTR (map
, l_info
[DT_STRTAB
]);
704 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
705 if (map
->l_info
[VERDEFTAG
] == NULL
)
706 /* The file has no symbol versioning. */
709 def
= (ElfW(Verdef
) *) ((char *) map
->l_addr
710 + map
->l_info
[VERDEFTAG
]->d_un
.d_ptr
);
713 ElfW(Verdaux
) *aux
= (ElfW(Verdaux
) *) ((char *) def
+ def
->vd_aux
);
715 /* Compare the version strings. */
716 if (strcmp (string
, strtab
+ aux
->vda_name
) == 0)
720 /* If no more definitions we failed to find what we want. */
721 if (def
->vd_next
== 0)
724 /* Next definition. */
725 def
= (ElfW(Verdef
) *) ((char *) def
+ def
->vd_next
);
731 bool __rtld_tls_init_tp_called
;
734 init_tls (size_t naudit
)
736 /* Number of elements in the static TLS block. */
737 GL(dl_tls_static_nelem
) = GL(dl_tls_max_dtv_idx
);
739 /* Do not do this twice. The audit interface might have required
740 the DTV interfaces to be set up early. */
741 if (GL(dl_initial_dtv
) != NULL
)
744 /* Allocate the array which contains the information about the
745 dtv slots. We allocate a few entries more than needed to
746 avoid the need for reallocation. */
747 size_t nelem
= GL(dl_tls_max_dtv_idx
) + 1 + TLS_SLOTINFO_SURPLUS
;
750 GL(dl_tls_dtv_slotinfo_list
) = (struct dtv_slotinfo_list
*)
751 calloc (sizeof (struct dtv_slotinfo_list
)
752 + nelem
* sizeof (struct dtv_slotinfo
), 1);
753 /* No need to check the return value. If memory allocation failed
754 the program would have been terminated. */
756 GL(dl_tls_dtv_slotinfo_list
)->len
= nelem
;
757 GL(dl_tls_dtv_slotinfo_list
)->next
= NULL
;
759 /* Calculate the size of the static TLS surplus. */
760 _dl_tls_static_surplus_init (naudit
);
762 /* Compute the TLS offsets for the various blocks. */
763 _dl_determine_tlsoffset ();
765 /* Construct the static TLS block and the dtv for the initial
766 thread. For some platforms this will include allocating memory
767 for the thread descriptor. The memory for the TLS block will
768 never be freed. It should be allocated accordingly. The dtv
769 array can be changed if dynamic loading requires it. */
770 void *tcbp
= _dl_allocate_tls_storage ();
773 cannot allocate TLS data structures for initial thread\n");
775 /* Store for detection of the special case by __tls_get_addr
776 so it knows not to pass this dtv to the normal realloc. */
777 GL(dl_initial_dtv
) = GET_DTV (tcbp
);
779 /* And finally install it for the main thread. */
780 call_tls_init_tp (tcbp
);
781 __rtld_tls_init_tp_called
= true;
787 do_preload (const char *fname
, struct link_map
*main_map
, const char *where
)
790 const char *err_str
= NULL
;
791 struct map_args args
;
795 args
.loader
= main_map
;
796 args
.mode
= __RTLD_SECURE
;
798 unsigned int old_nloaded
= GL(dl_ns
)[LM_ID_BASE
]._ns_nloaded
;
800 (void) _dl_catch_error (&objname
, &err_str
, &malloced
, map_doit
, &args
);
801 if (__glibc_unlikely (err_str
!= NULL
))
804 ERROR: ld.so: object '%s' from %s cannot be preloaded (%s): ignored.\n",
805 fname
, where
, err_str
);
806 /* No need to call free, this is still before
807 the libc's malloc is used. */
809 else if (GL(dl_ns
)[LM_ID_BASE
]._ns_nloaded
!= old_nloaded
)
810 /* It is no duplicate. */
813 /* Nothing loaded. */
820 /* Set up the stack checker's canary. */
821 uintptr_t stack_chk_guard
= _dl_setup_stack_chk_guard (_dl_random
);
822 #ifdef THREAD_SET_STACK_GUARD
823 THREAD_SET_STACK_GUARD (stack_chk_guard
);
825 __stack_chk_guard
= stack_chk_guard
;
828 /* Set up the pointer guard as well, if necessary. */
829 uintptr_t pointer_chk_guard
830 = _dl_setup_pointer_guard (_dl_random
, stack_chk_guard
);
831 #ifdef THREAD_SET_POINTER_GUARD
832 THREAD_SET_POINTER_GUARD (pointer_chk_guard
);
834 __pointer_chk_guard_local
= pointer_chk_guard
;
836 /* We do not need the _dl_random value anymore. The less
837 information we leave behind, the better, so clear the
842 #include <setup-vdso.h>
844 /* The LD_PRELOAD environment variable gives list of libraries
845 separated by white space or colons that are loaded before the
846 executable's dependencies and prepended to the global scope list.
847 (If the binary is running setuid all elements containing a '/' are
848 ignored since it is insecure.) Return the number of preloads
849 performed. Ditto for --preload command argument. */
851 handle_preload_list (const char *preloadlist
, struct link_map
*main_map
,
854 unsigned int npreloads
= 0;
855 const char *p
= preloadlist
;
856 char fname
[SECURE_PATH_LIMIT
];
860 /* Split preload list at space/colon. */
861 size_t len
= strcspn (p
, " :");
862 if (len
> 0 && len
< sizeof (fname
))
864 memcpy (fname
, p
, len
);
870 /* Skip over the substring and the following delimiter. */
875 if (dso_name_valid_for_suid (fname
))
876 npreloads
+= do_preload (fname
, main_map
, where
);
881 /* Called if the audit DSO cannot be used: if it does not have the
882 appropriate interfaces, or it expects a more recent version library
883 version than what the dynamic linker provides. */
885 unload_audit_module (struct link_map
*map
, int original_tls_idx
)
888 Lmid_t ns
= map
->l_ns
;
892 /* Make sure the namespace has been cleared entirely. */
893 assert (GL(dl_ns
)[ns
]._ns_loaded
== NULL
);
894 assert (GL(dl_ns
)[ns
]._ns_nloaded
== 0);
896 GL(dl_tls_max_dtv_idx
) = original_tls_idx
;
899 /* Called to print an error message if loading of an audit module
902 report_audit_module_load_error (const char *name
, const char *err_str
,
906 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
909 free ((char *) err_str
);
912 /* Load one audit module. */
914 load_audit_module (const char *name
, struct audit_ifaces
**last_audit
)
916 int original_tls_idx
= GL(dl_tls_max_dtv_idx
);
918 struct dlmopen_args dlmargs
;
919 dlmargs
.fname
= name
;
923 const char *err_str
= NULL
;
925 _dl_catch_error (&objname
, &err_str
, &malloced
, dlmopen_doit
, &dlmargs
);
926 if (__glibc_unlikely (err_str
!= NULL
))
928 report_audit_module_load_error (name
, err_str
, malloced
);
932 struct lookup_args largs
;
933 largs
.name
= "la_version";
934 largs
.map
= dlmargs
.map
;
935 _dl_catch_error (&objname
, &err_str
, &malloced
, lookup_doit
, &largs
);
936 if (__glibc_likely (err_str
!= NULL
))
938 unload_audit_module (dlmargs
.map
, original_tls_idx
);
939 report_audit_module_load_error (name
, err_str
, malloced
);
943 unsigned int (*laversion
) (unsigned int) = largs
.result
;
945 /* A null symbol indicates that something is very wrong with the
946 loaded object because defined symbols are supposed to have a
947 valid, non-null address. */
948 assert (laversion
!= NULL
);
950 unsigned int lav
= laversion (LAV_CURRENT
);
953 /* Only print an error message if debugging because this can
954 happen deliberately. */
955 if (GLRO(dl_debug_mask
) & DL_DEBUG_FILES
)
957 file=%s [%lu]; audit interface function la_version returned zero; ignored.\n",
958 dlmargs
.map
->l_name
, dlmargs
.map
->l_ns
);
959 unload_audit_module (dlmargs
.map
, original_tls_idx
);
963 if (!_dl_audit_check_version (lav
))
966 ERROR: audit interface '%s' requires version %d (maximum supported version %d); ignored.\n",
967 name
, lav
, LAV_CURRENT
);
968 unload_audit_module (dlmargs
.map
, original_tls_idx
);
972 enum { naudit_ifaces
= 8 };
975 struct audit_ifaces ifaces
;
976 void (*fptr
[naudit_ifaces
]) (void);
977 } *newp
= malloc (sizeof (*newp
));
979 _dl_fatal_printf ("Out of memory while loading audit modules\n");
981 /* Names of the auditing interfaces. All in one
983 static const char audit_iface_names
[] =
989 #define STRING(s) __STRING (s)
990 "la_" STRING (ARCH_LA_PLTENTER
) "\0"
991 "la_" STRING (ARCH_LA_PLTEXIT
) "\0"
993 unsigned int cnt
= 0;
994 const char *cp
= audit_iface_names
;
998 _dl_catch_error (&objname
, &err_str
, &malloced
, lookup_doit
, &largs
);
1000 /* Store the pointer. */
1001 if (err_str
== NULL
&& largs
.result
!= NULL
)
1002 newp
->fptr
[cnt
] = largs
.result
;
1004 newp
->fptr
[cnt
] = NULL
;
1007 cp
= strchr (cp
, '\0') + 1;
1009 while (*cp
!= '\0');
1010 assert (cnt
== naudit_ifaces
);
1012 /* Now append the new auditing interface to the list. */
1013 newp
->ifaces
.next
= NULL
;
1014 if (*last_audit
== NULL
)
1015 *last_audit
= GLRO(dl_audit
) = &newp
->ifaces
;
1017 *last_audit
= (*last_audit
)->next
= &newp
->ifaces
;
1019 /* The dynamic linker link map is statically allocated, so the
1020 cookie in _dl_new_object has not happened. */
1021 link_map_audit_state (&_dl_rtld_map
, GLRO (dl_naudit
))->cookie
1022 = (intptr_t) &_dl_rtld_map
;
1026 /* Mark the DSO as being used for auditing. */
1027 dlmargs
.map
->l_auditing
= 1;
1030 /* Load all audit modules. */
1032 load_audit_modules (struct link_map
*main_map
, struct audit_list
*audit_list
)
1034 struct audit_ifaces
*last_audit
= NULL
;
1038 const char *name
= audit_list_next (audit_list
);
1041 load_audit_module (name
, &last_audit
);
1044 /* Notify audit modules of the initially loaded modules (the main
1045 program and the dynamic linker itself). */
1046 if (GLRO(dl_naudit
) > 0)
1048 _dl_audit_objopen (main_map
, LM_ID_BASE
);
1049 _dl_audit_objopen (&_dl_rtld_map
, LM_ID_BASE
);
1053 /* Check if the executable is not actually dynamically linked, and
1054 invoke it directly in that case. */
1056 rtld_chain_load (struct link_map
*main_map
, char *argv0
)
1058 /* The dynamic loader run against itself. */
1059 const char *rtld_soname
= l_soname (&_dl_rtld_map
);
1060 if (l_soname (main_map
) != NULL
1061 && strcmp (rtld_soname
, l_soname (main_map
)) == 0)
1062 _dl_fatal_printf ("%s: loader cannot load itself\n", rtld_soname
);
1064 /* With DT_NEEDED dependencies, the executable is dynamically
1066 if (__glibc_unlikely (main_map
->l_info
[DT_NEEDED
] != NULL
))
1069 /* If the executable has program interpreter, it is dynamically
1071 for (size_t i
= 0; i
< main_map
->l_phnum
; ++i
)
1072 if (main_map
->l_phdr
[i
].p_type
== PT_INTERP
)
1075 const char *pathname
= _dl_argv
[0];
1077 _dl_argv
[0] = argv0
;
1078 int errcode
= __rtld_execve (pathname
, _dl_argv
, _environ
);
1079 const char *errname
= strerrorname_np (errcode
);
1080 if (errname
!= NULL
)
1081 _dl_fatal_printf("%s: cannot execute %s: %s\n",
1082 rtld_soname
, pathname
, errname
);
1084 _dl_fatal_printf("%s: cannot execute %s: %d\n",
1085 rtld_soname
, pathname
, errcode
);
1088 /* Called to complete the initialization of the link map for the main
1089 executable. Returns true if there is a PT_INTERP segment. */
1091 rtld_setup_main_map (struct link_map
*main_map
)
1093 /* This have already been filled in right after _dl_new_object, or
1094 as part of _dl_map_object. */
1095 const ElfW(Phdr
) *phdr
= main_map
->l_phdr
;
1096 ElfW(Word
) phnum
= main_map
->l_phnum
;
1098 bool has_interp
= false;
1100 main_map
->l_map_end
= 0;
1101 /* Perhaps the executable has no PT_LOAD header entries at all. */
1102 main_map
->l_map_start
= ~0;
1103 /* And it was opened directly. */
1104 ++main_map
->l_direct_opencount
;
1105 main_map
->l_contiguous
= 1;
1107 /* A PT_LOAD segment at an unexpected address will clear the
1108 l_contiguous flag. The ELF specification says that PT_LOAD
1109 segments need to be sorted in in increasing order, but perhaps
1110 not all executables follow this requirement. Having l_contiguous
1111 equal to 1 is just an optimization, so the code below does not
1112 try to sort the segments in case they are unordered.
1114 There is one corner case in which l_contiguous is not set to 1,
1115 but where it could be set: If a PIE (ET_DYN) binary is loaded by
1116 glibc itself (not the kernel), it is always contiguous due to the
1117 way the glibc loader works. However, the kernel loader may still
1118 create holes in this case, and the code here still uses 0
1119 conservatively for the glibc-loaded case, too. */
1120 ElfW(Addr
) expected_load_address
= 0;
1122 /* Scan the program header table for the dynamic section. */
1123 for (const ElfW(Phdr
) *ph
= phdr
; ph
< &phdr
[phnum
]; ++ph
)
1127 /* Find out the load address. */
1128 main_map
->l_addr
= (ElfW(Addr
)) phdr
- ph
->p_vaddr
;
1131 /* This tells us where to find the dynamic section,
1132 which tells us everything we need to do. */
1133 main_map
->l_ld
= (void *) main_map
->l_addr
+ ph
->p_vaddr
;
1134 main_map
->l_ld_readonly
= (ph
->p_flags
& PF_W
) == 0;
1137 /* This "interpreter segment" was used by the program loader to
1138 find the program interpreter, which is this program itself, the
1139 dynamic linker. We note what name finds us, so that a future
1140 dlopen call or DT_NEEDED entry, for something that wants to link
1141 against the dynamic linker as a shared library, will know that
1142 the shared object is already loaded. */
1143 _dl_rtld_libname
.name
= ((const char *) main_map
->l_addr
1145 /* _dl_rtld_libname.next = NULL; Already zero. */
1146 _dl_rtld_map
.l_libname
= &_dl_rtld_libname
;
1152 ElfW(Addr
) mapstart
;
1153 ElfW(Addr
) allocend
;
1155 /* Remember where the main program starts in memory. */
1156 mapstart
= (main_map
->l_addr
1157 + (ph
->p_vaddr
& ~(GLRO(dl_pagesize
) - 1)));
1158 if (main_map
->l_map_start
> mapstart
)
1159 main_map
->l_map_start
= mapstart
;
1161 if (main_map
->l_contiguous
&& expected_load_address
!= 0
1162 && expected_load_address
!= mapstart
)
1163 main_map
->l_contiguous
= 0;
1165 /* Also where it ends. */
1166 allocend
= main_map
->l_addr
+ ph
->p_vaddr
+ ph
->p_memsz
;
1167 if (main_map
->l_map_end
< allocend
)
1168 main_map
->l_map_end
= allocend
;
1170 /* The next expected address is the page following this load
1172 expected_load_address
= ((allocend
+ GLRO(dl_pagesize
) - 1)
1173 & ~(GLRO(dl_pagesize
) - 1));
1178 if (ph
->p_memsz
> 0)
1180 /* Note that in the case the dynamic linker we duplicate work
1181 here since we read the PT_TLS entry already in
1182 _dl_start_final. But the result is repeatable so do not
1183 check for this special but unimportant case. */
1184 main_map
->l_tls_blocksize
= ph
->p_memsz
;
1185 main_map
->l_tls_align
= ph
->p_align
;
1186 if (ph
->p_align
== 0)
1187 main_map
->l_tls_firstbyte_offset
= 0;
1189 main_map
->l_tls_firstbyte_offset
= (ph
->p_vaddr
1190 & (ph
->p_align
- 1));
1191 main_map
->l_tls_initimage_size
= ph
->p_filesz
;
1192 main_map
->l_tls_initimage
= (void *) ph
->p_vaddr
;
1194 /* This image gets the ID one. */
1195 GL(dl_tls_max_dtv_idx
) = main_map
->l_tls_modid
= 1;
1200 GL(dl_stack_flags
) = ph
->p_flags
;
1204 main_map
->l_relro_addr
= ph
->p_vaddr
;
1205 main_map
->l_relro_size
= ph
->p_memsz
;
1208 /* Process program headers again, but scan them backwards so
1209 that PT_NOTE can be skipped if PT_GNU_PROPERTY exits. */
1210 for (const ElfW(Phdr
) *ph
= &phdr
[phnum
]; ph
!= phdr
; --ph
)
1211 switch (ph
[-1].p_type
)
1214 _dl_process_pt_note (main_map
, -1, &ph
[-1]);
1216 case PT_GNU_PROPERTY
:
1217 _dl_process_pt_gnu_property (main_map
, -1, &ph
[-1]);
1221 /* Adjust the address of the TLS initialization image in case
1222 the executable is actually an ET_DYN object. */
1223 if (main_map
->l_tls_initimage
!= NULL
)
1224 main_map
->l_tls_initimage
1225 = (char *) main_map
->l_tls_initimage
+ main_map
->l_addr
;
1226 if (! main_map
->l_map_end
)
1227 main_map
->l_map_end
= ~0;
1228 if (! _dl_rtld_map
.l_libname
&& _dl_rtld_map
.l_name
)
1230 /* We were invoked directly, so the program might not have a
1232 _dl_rtld_libname
.name
= _dl_rtld_map
.l_name
;
1233 /* _dl_rtld_libname.next = NULL; Already zero. */
1234 _dl_rtld_map
.l_libname
= &_dl_rtld_libname
;
1237 assert (_dl_rtld_map
.l_libname
); /* How else did we get here? */
1242 /* Adjusts the contents of the stack and related globals for the user
1243 entry point. The ld.so processed skip_args arguments and bumped
1244 _dl_argv and _dl_argc accordingly. Those arguments are removed from
1247 _dl_start_args_adjust (int skip_args
, int skip_env
)
1249 void **sp
= (void **) (_dl_argv
- skip_args
- 1);
1250 void **p
= sp
+ skip_args
;
1256 intptr_t argc
__attribute__ ((unused
)) = (intptr_t) sp
[0] - skip_args
;
1257 assert (argc
== _dl_argc
);
1259 /* Adjust argc on stack. */
1260 sp
[0] = (void *) (intptr_t) _dl_argc
;
1262 /* Update globals in rtld. */
1263 _dl_argv
-= skip_args
;
1264 _environ
-= skip_args
;
1266 /* Shuffle argv down. */
1271 assert (_environ
== (char **) (sp
+ 1));
1273 /* Shuffle envp down. */
1278 #ifdef HAVE_AUX_VECTOR
1279 void **auxv
= (void **) GLRO(dl_auxv
) - skip_args
- skip_env
;
1280 GLRO(dl_auxv
) = (ElfW(auxv_t
) *) auxv
; /* Aliasing violation. */
1281 assert (auxv
== sp
+ 1);
1283 /* Shuffle auxv down. */
1285 char *oldp
= (char *) (p
+ 1 + skip_env
);
1286 char *newp
= (char *) (sp
+ 1);
1289 memcpy (&ax
, oldp
, sizeof (ax
));
1290 memcpy (newp
, &ax
, sizeof (ax
));
1291 oldp
+= sizeof (ax
);
1292 newp
+= sizeof (ax
);
1294 while (ax
.a_type
!= AT_NULL
);
1299 dl_main (const ElfW(Phdr
) *phdr
,
1301 ElfW(Addr
) *user_entry
,
1304 struct link_map
*main_map
;
1308 bool rtld_is_main
= false;
1312 struct dl_main_state state
;
1313 dl_main_state_init (&state
);
1315 __tls_pre_init_tp ();
1317 /* Process the environment variable which control the behaviour. */
1318 skip_env
= process_envvars (&state
);
1320 #ifndef HAVE_INLINED_SYSCALLS
1321 /* Set up a flag which tells we are just starting. */
1322 _dl_starting_up
= 1;
1325 const char *ld_so_name
= _dl_argv
[0];
1326 if (*user_entry
== (ElfW(Addr
)) ENTRY_POINT
)
1328 /* Ho ho. We are not the program interpreter! We are the program
1329 itself! This means someone ran ld.so as a command. Well, that
1330 might be convenient to do sometimes. We support it by
1331 interpreting the args like this:
1333 ld.so PROGRAM ARGS...
1335 The first argument is the name of a file containing an ELF
1336 executable we will load and run with the following arguments.
1337 To simplify life here, PROGRAM is searched for using the
1338 normal rules for shared objects, rather than $PATH or anything
1339 like that. We just load it and use its entry point; we don't
1340 pay attention to its PT_INTERP command (we are the interpreter
1341 ourselves). This is an easy way to test a new ld.so before
1343 rtld_is_main
= true;
1346 char **orig_argv
= _dl_argv
;
1348 /* Note the place where the dynamic linker actually came from. */
1349 _dl_rtld_map
.l_name
= rtld_progname
;
1351 while (_dl_argc
> 1)
1352 if (! strcmp (_dl_argv
[1], "--list"))
1354 if (state
.mode
!= rtld_mode_help
)
1356 state
.mode
= rtld_mode_list
;
1357 /* This means do no dependency analysis. */
1364 else if (! strcmp (_dl_argv
[1], "--verify"))
1366 if (state
.mode
!= rtld_mode_help
)
1367 state
.mode
= rtld_mode_verify
;
1372 else if (! strcmp (_dl_argv
[1], "--inhibit-cache"))
1374 GLRO(dl_inhibit_cache
) = 1;
1378 else if (! strcmp (_dl_argv
[1], "--library-path")
1381 state
.library_path
= _dl_argv
[2];
1382 state
.library_path_source
= "--library-path";
1387 else if (! strcmp (_dl_argv
[1], "--inhibit-rpath")
1390 GLRO(dl_inhibit_rpath
) = _dl_argv
[2];
1395 else if (! strcmp (_dl_argv
[1], "--audit") && _dl_argc
> 2)
1397 audit_list_add_string (&state
.audit_list
, _dl_argv
[2]);
1402 else if (! strcmp (_dl_argv
[1], "--preload") && _dl_argc
> 2)
1404 state
.preloadarg
= _dl_argv
[2];
1408 else if (! strcmp (_dl_argv
[1], "--argv0") && _dl_argc
> 2)
1410 argv0
= _dl_argv
[2];
1415 else if (strcmp (_dl_argv
[1], "--glibc-hwcaps-prepend") == 0
1418 state
.glibc_hwcaps_prepend
= _dl_argv
[2];
1422 else if (strcmp (_dl_argv
[1], "--glibc-hwcaps-mask") == 0
1425 state
.glibc_hwcaps_mask
= _dl_argv
[2];
1429 else if (! strcmp (_dl_argv
[1], "--list-tunables"))
1431 state
.mode
= rtld_mode_list_tunables
;
1436 else if (! strcmp (_dl_argv
[1], "--list-diagnostics"))
1438 state
.mode
= rtld_mode_list_diagnostics
;
1443 else if (strcmp (_dl_argv
[1], "--help") == 0)
1445 state
.mode
= rtld_mode_help
;
1449 else if (strcmp (_dl_argv
[1], "--version") == 0)
1451 else if (_dl_argv
[1][0] == '-' && _dl_argv
[1][1] == '-')
1453 if (_dl_argv
[1][2] == '\0')
1455 /* End of option list. */
1461 /* Unrecognized option. */
1462 _dl_usage (ld_so_name
, _dl_argv
[1]);
1467 if (__glibc_unlikely (state
.mode
== rtld_mode_list_tunables
))
1469 __tunables_print ();
1473 if (state
.mode
== rtld_mode_list_diagnostics
)
1474 _dl_print_diagnostics (_environ
);
1476 /* If we have no further argument the program was called incorrectly.
1477 Grant the user some education. */
1480 if (state
.mode
== rtld_mode_help
)
1481 /* --help without an executable is not an error. */
1482 _dl_help (ld_so_name
, &state
);
1484 _dl_usage (ld_so_name
, NULL
);
1490 /* The initialization of _dl_stack_flags done below assumes the
1491 executable's PT_GNU_STACK may have been honored by the kernel, and
1492 so a PT_GNU_STACK with PF_X set means the stack started out with
1493 execute permission. However, this is not really true if the
1494 dynamic linker is the executable the kernel loaded. For this
1495 case, we must reinitialize _dl_stack_flags to match the dynamic
1496 linker itself. If the dynamic linker was built with a
1497 PT_GNU_STACK, then the kernel may have loaded us with a
1498 nonexecutable stack that we will have to make executable when we
1499 load the program below unless it has a PT_GNU_STACK indicating
1500 nonexecutable stack is ok. */
1502 for (const ElfW(Phdr
) *ph
= phdr
; ph
< &phdr
[phnum
]; ++ph
)
1503 if (ph
->p_type
== PT_GNU_STACK
)
1505 GL(dl_stack_flags
) = ph
->p_flags
;
1509 if (__glibc_unlikely (state
.mode
== rtld_mode_verify
1510 || state
.mode
== rtld_mode_help
))
1512 const char *objname
;
1513 const char *err_str
= NULL
;
1514 struct map_args args
;
1517 args
.str
= rtld_progname
;
1519 args
.mode
= __RTLD_OPENEXEC
;
1520 (void) _dl_catch_error (&objname
, &err_str
, &malloced
, map_doit
,
1522 if (__glibc_unlikely (err_str
!= NULL
))
1524 /* We don't free the returned string, the programs stops
1526 if (state
.mode
== rtld_mode_help
)
1527 /* Mask the failure to load the main object. The help
1528 message contains less information in this case. */
1529 _dl_help (ld_so_name
, &state
);
1531 _exit (EXIT_FAILURE
);
1536 RTLD_TIMING_VAR (start
);
1537 rtld_timer_start (&start
);
1538 _dl_map_object (NULL
, rtld_progname
, lt_executable
, 0,
1539 __RTLD_OPENEXEC
, LM_ID_BASE
);
1540 rtld_timer_stop (&load_time
, start
);
1543 /* Now the map for the main executable is available. */
1544 main_map
= GL(dl_ns
)[LM_ID_BASE
]._ns_loaded
;
1546 if (__glibc_likely (state
.mode
== rtld_mode_normal
))
1547 rtld_chain_load (main_map
, argv0
);
1549 phdr
= main_map
->l_phdr
;
1550 phnum
= main_map
->l_phnum
;
1551 /* We overwrite here a pointer to a malloc()ed string. But since
1552 the malloc() implementation used at this point is the dummy
1553 implementations which has no real free() function it does not
1554 makes sense to free the old string first. */
1555 main_map
->l_name
= (char *) "";
1556 *user_entry
= main_map
->l_entry
;
1558 /* Set bit indicating this is the main program map. */
1559 main_map
->l_main_map
= 1;
1561 #ifdef HAVE_AUX_VECTOR
1562 /* Adjust the on-stack auxiliary vector so that it looks like the
1563 binary was executed directly. */
1564 for (ElfW(auxv_t
) *av
= auxv
; av
->a_type
!= AT_NULL
; av
++)
1568 av
->a_un
.a_val
= (uintptr_t) phdr
;
1571 av
->a_un
.a_val
= phnum
;
1574 av
->a_un
.a_val
= *user_entry
;
1577 av
->a_un
.a_val
= (uintptr_t) _dl_argv
[0];
1582 /* Set the argv[0] string now that we've processed the executable. */
1584 _dl_argv
[0] = argv0
;
1586 /* Adjust arguments for the application entry point. */
1587 _dl_start_args_adjust (_dl_argv
- orig_argv
, skip_env
);
1591 /* Create a link_map for the executable itself.
1592 This will be what dlopen on "" returns. */
1593 main_map
= _dl_new_object ((char *) "", "", lt_executable
, NULL
,
1594 __RTLD_OPENEXEC
, LM_ID_BASE
);
1595 assert (main_map
!= NULL
);
1596 main_map
->l_phdr
= phdr
;
1597 main_map
->l_phnum
= phnum
;
1598 main_map
->l_entry
= *user_entry
;
1600 /* Even though the link map is not yet fully initialized we can add
1601 it to the map list since there are no possible users running yet. */
1602 _dl_add_to_namespace_list (main_map
, LM_ID_BASE
);
1603 assert (main_map
== GL(dl_ns
)[LM_ID_BASE
]._ns_loaded
);
1605 /* At this point we are in a bit of trouble. We would have to
1606 fill in the values for l_dev and l_ino. But in general we
1607 do not know where the file is. We also do not handle AT_EXECFD
1608 even if it would be passed up.
1610 We leave the values here defined to 0. This is normally no
1611 problem as the program code itself is normally no shared
1612 object and therefore cannot be loaded dynamically. Nothing
1613 prevent the use of dynamic binaries and in these situations
1614 we might get problems. We might not be able to find out
1615 whether the object is already loaded. But since there is no
1616 easy way out and because the dynamic binary must also not
1617 have an SONAME we ignore this program for now. If it becomes
1618 a problem we can force people using SONAMEs. */
1620 /* We delay initializing the path structure until we got the dynamic
1621 information for the program. */
1624 bool has_interp
= rtld_setup_main_map (main_map
);
1626 /* Handle this after PT_GNU_STACK parse, because it updates dl_stack_flags
1628 _dl_handle_execstack_tunable ();
1630 /* If the current libname is different from the SONAME, add the
1633 const char *soname
= l_soname (&_dl_rtld_map
);
1635 && strcmp (_dl_rtld_map
.l_libname
->name
, soname
) != 0)
1637 static struct libname_list newname
;
1638 newname
.name
= soname
;
1639 newname
.next
= NULL
;
1640 newname
.dont_free
= 1;
1642 assert (_dl_rtld_map
.l_libname
->next
== NULL
);
1643 _dl_rtld_map
.l_libname
->next
= &newname
;
1646 /* The ld.so must be relocated since otherwise loading audit modules
1647 will fail since they reuse the very same ld.so. */
1648 assert (_dl_rtld_map
.l_relocated
);
1652 /* Extract the contents of the dynamic section for easy access. */
1653 elf_get_dynamic_info (main_map
, false, false);
1655 /* If the main map is libc.so, update the base namespace to
1656 refer to this map. If libc.so is loaded later, this happens
1657 in _dl_map_object_from_fd. */
1658 if (l_soname (main_map
) != NULL
1659 && strcmp (l_soname (main_map
), LIBC_SO
) == 0)
1660 GL(dl_ns
)[LM_ID_BASE
].libc_map
= main_map
;
1662 /* Set up our cache of pointers into the hash table. */
1663 _dl_setup_hash (main_map
);
1666 if (__glibc_unlikely (state
.mode
== rtld_mode_verify
))
1668 /* We were called just to verify that this is a dynamic
1669 executable using us as the program interpreter. Exit with an
1670 error if we were not able to load the binary or no interpreter
1671 is specified (i.e., this is no dynamically linked binary. */
1672 if (main_map
->l_ld
== NULL
)
1675 _exit (has_interp
? 0 : 2);
1678 struct link_map
**first_preload
= &_dl_rtld_map
.l_next
;
1679 /* Set up the data structures for the system-supplied DSO early,
1680 so they can influence _dl_init_paths. */
1681 setup_vdso (main_map
, &first_preload
);
1683 /* With vDSO setup we can initialize the function pointers. */
1684 setup_vdso_pointers ();
1686 /* Initialize the data structures for the search paths for shared
1688 call_init_paths (&state
);
1690 /* Initialize _r_debug_extended. */
1691 struct r_debug
*r
= _dl_debug_initialize (_dl_rtld_map
.l_addr
,
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 (! _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 _dl_rtld_map
.l_name
= (char *) _dl_rtld_map
.l_libname
->name
;
1702 _dl_rtld_map
.l_type
= lt_library
;
1703 main_map
->l_next
= &_dl_rtld_map
;
1704 _dl_rtld_map
.l_prev
= main_map
;
1705 ++GL(dl_ns
)[LM_ID_BASE
]._ns_nloaded
;
1708 /* Starting from binutils-2.23, the linker will define the magic symbol
1709 __ehdr_start to point to our own ELF header if it is visible in a
1710 segment that also includes the phdrs. If that's not available, we use
1711 the old method that assumes the beginning of the file is part of the
1712 lowest-addressed PT_LOAD segment. */
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
= &__ehdr_start
;
1717 assert (rtld_ehdr
->e_ehsize
== sizeof *rtld_ehdr
);
1718 assert (rtld_ehdr
->e_phentsize
== sizeof (ElfW(Phdr
)));
1720 const ElfW(Phdr
) *rtld_phdr
= (const void *) rtld_ehdr
+ rtld_ehdr
->e_phoff
;
1722 _dl_rtld_map
.l_phdr
= rtld_phdr
;
1723 _dl_rtld_map
.l_phnum
= rtld_ehdr
->e_phnum
;
1726 /* PT_GNU_RELRO is usually the last phdr. */
1727 size_t cnt
= rtld_ehdr
->e_phnum
;
1729 if (rtld_phdr
[cnt
].p_type
== PT_GNU_RELRO
)
1731 _dl_rtld_map
.l_relro_addr
= rtld_phdr
[cnt
].p_vaddr
;
1732 _dl_rtld_map
.l_relro_size
= rtld_phdr
[cnt
].p_memsz
;
1736 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1737 if (_dl_rtld_map
.l_tls_blocksize
!= 0)
1738 /* Assign a module ID. Do this before loading any audit modules. */
1739 _dl_assign_tls_modid (&_dl_rtld_map
);
1741 audit_list_add_dynamic_tag (&state
.audit_list
, main_map
, DT_AUDIT
);
1742 audit_list_add_dynamic_tag (&state
.audit_list
, main_map
, DT_DEPAUDIT
);
1744 /* At this point, all data has been obtained that is included in the
1746 if (__glibc_unlikely (state
.mode
== rtld_mode_help
))
1747 _dl_help (ld_so_name
, &state
);
1749 /* If we have auditing DSOs to load, do it now. */
1750 bool need_security_init
= true;
1751 if (state
.audit_list
.length
> 0)
1753 size_t naudit
= audit_list_count (&state
.audit_list
);
1755 /* Since we start using the auditing DSOs right away we need to
1756 initialize the data structures now. */
1757 tcbp
= init_tls (naudit
);
1759 /* Initialize security features. We need to do it this early
1760 since otherwise the constructors of the audit libraries will
1761 use different values (especially the pointer guard) and will
1764 need_security_init
= false;
1766 load_audit_modules (main_map
, &state
.audit_list
);
1768 /* The count based on audit strings may overestimate the number
1769 of audit modules that got loaded, but not underestimate. */
1770 assert (GLRO(dl_naudit
) <= naudit
);
1773 /* Keep track of the currently loaded modules to count how many
1774 non-audit modules which use TLS are loaded. */
1775 size_t count_modids
= _dl_count_modids ();
1777 /* Set up debugging before the debugger is notified for the first time. */
1778 elf_setup_debug_entry (main_map
, r
);
1780 /* We start adding objects. */
1781 r
->r_state
= RT_ADD
;
1783 LIBC_PROBE (init_start
, 2, LM_ID_BASE
, r
);
1785 /* Auditing checkpoint: we are ready to signal that the initial map
1786 is being constructed. */
1787 _dl_audit_activity_map (main_map
, LA_ACT_ADD
);
1789 /* We have two ways to specify objects to preload: via environment
1790 variable and via the file /etc/ld.so.preload. The latter can also
1791 be used when security is enabled. */
1792 assert (*first_preload
== NULL
);
1793 struct link_map
**preloads
= NULL
;
1794 unsigned int npreloads
= 0;
1796 if (__glibc_unlikely (state
.preloadlist
!= NULL
))
1798 RTLD_TIMING_VAR (start
);
1799 rtld_timer_start (&start
);
1800 npreloads
+= handle_preload_list (state
.preloadlist
, main_map
,
1802 rtld_timer_accum (&load_time
, start
);
1805 if (__glibc_unlikely (state
.preloadarg
!= NULL
))
1807 RTLD_TIMING_VAR (start
);
1808 rtld_timer_start (&start
);
1809 npreloads
+= handle_preload_list (state
.preloadarg
, main_map
,
1811 rtld_timer_accum (&load_time
, start
);
1814 /* There usually is no ld.so.preload file, it should only be used
1815 for emergencies and testing. So the open call etc should usually
1816 fail. Using access() on a non-existing file is faster than using
1817 open(). So we do this first. If it succeeds we do almost twice
1818 the work but this does not matter, since it is not for production
1820 static const char preload_file
[] = "/etc/ld.so.preload";
1821 if (__glibc_unlikely (__access (preload_file
, R_OK
) == 0))
1823 /* Read the contents of the file. */
1824 file
= _dl_sysdep_read_whole_file (preload_file
, &file_size
,
1825 PROT_READ
| PROT_WRITE
);
1826 if (__glibc_unlikely (file
!= MAP_FAILED
))
1828 /* Parse the file. It contains names of libraries to be loaded,
1829 separated by white spaces or `:'. It may also contain
1830 comments introduced by `#'. */
1835 /* Eliminate comments. */
1840 char *comment
= memchr (runp
, '#', rest
);
1841 if (comment
== NULL
)
1844 rest
-= comment
- runp
;
1847 while (--rest
> 0 && *++comment
!= '\n');
1850 /* We have one problematic case: if we have a name at the end of
1851 the file without a trailing terminating characters, we cannot
1852 place the \0. Handle the case separately. */
1853 if (file
[file_size
- 1] != ' ' && file
[file_size
- 1] != '\t'
1854 && file
[file_size
- 1] != '\n' && file
[file_size
- 1] != ':')
1856 problem
= &file
[file_size
];
1857 while (problem
> file
&& problem
[-1] != ' '
1858 && problem
[-1] != '\t'
1859 && problem
[-1] != '\n' && problem
[-1] != ':')
1868 file
[file_size
- 1] = '\0';
1871 RTLD_TIMING_VAR (start
);
1872 rtld_timer_start (&start
);
1874 if (file
!= problem
)
1878 while ((p
= strsep (&runp
, ": \t\n")) != NULL
)
1880 npreloads
+= do_preload (p
, main_map
, preload_file
);
1883 if (problem
!= NULL
)
1885 char *p
= strndupa (problem
, file_size
- (problem
- file
));
1887 npreloads
+= do_preload (p
, main_map
, preload_file
);
1890 rtld_timer_accum (&load_time
, start
);
1892 /* We don't need the file anymore. */
1893 __munmap (file
, file_size
);
1897 if (__glibc_unlikely (*first_preload
!= NULL
))
1899 /* Set up PRELOADS with a vector of the preloaded libraries. */
1900 struct link_map
*l
= *first_preload
;
1901 preloads
= __alloca (npreloads
* sizeof preloads
[0]);
1908 assert (i
== npreloads
);
1911 #ifdef NEED_DL_SYSINFO_DSO
1912 /* Now that the audit modules are opened, call la_objopen for the vDSO. */
1913 if (GLRO(dl_sysinfo_map
) != NULL
)
1914 _dl_audit_objopen (GLRO(dl_sysinfo_map
), LM_ID_BASE
);
1917 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1918 specified some libraries to load, these are inserted before the actual
1919 dependencies in the executable's searchlist for symbol resolution. */
1921 RTLD_TIMING_VAR (start
);
1922 rtld_timer_start (&start
);
1923 _dl_map_object_deps (main_map
, preloads
, npreloads
,
1924 state
.mode
== rtld_mode_trace
, 0);
1925 rtld_timer_accum (&load_time
, start
);
1928 /* Mark all objects as being in the global scope. */
1929 for (i
= main_map
->l_searchlist
.r_nlist
; i
> 0; )
1930 main_map
->l_searchlist
.r_list
[--i
]->l_global
= 1;
1932 /* Remove _dl_rtld_map from the chain. */
1933 _dl_rtld_map
.l_prev
->l_next
= _dl_rtld_map
.l_next
;
1934 if (_dl_rtld_map
.l_next
!= NULL
)
1935 _dl_rtld_map
.l_next
->l_prev
= _dl_rtld_map
.l_prev
;
1937 for (i
= 1; i
< main_map
->l_searchlist
.r_nlist
; ++i
)
1938 if (is_rtld_link_map (main_map
->l_searchlist
.r_list
[i
]))
1941 /* Insert the link map for the dynamic loader into the chain in
1942 symbol search order because gdb uses the chain's order as its
1943 symbol search order. */
1945 _dl_rtld_map
.l_prev
= main_map
->l_searchlist
.r_list
[i
- 1];
1946 if (__glibc_likely (state
.mode
== rtld_mode_normal
))
1948 _dl_rtld_map
.l_next
= (i
+ 1 < main_map
->l_searchlist
.r_nlist
1949 ? main_map
->l_searchlist
.r_list
[i
+ 1]
1951 #ifdef NEED_DL_SYSINFO_DSO
1952 if (GLRO(dl_sysinfo_map
) != NULL
1953 && _dl_rtld_map
.l_prev
->l_next
== GLRO(dl_sysinfo_map
)
1954 && _dl_rtld_map
.l_next
!= GLRO(dl_sysinfo_map
))
1955 _dl_rtld_map
.l_prev
= GLRO(dl_sysinfo_map
);
1959 /* In trace mode there might be an invisible object (which we
1960 could not find) after the previous one in the search list.
1961 In this case it doesn't matter much where we put the
1962 interpreter object, so we just initialize the list pointer so
1963 that the assertion below holds. */
1964 _dl_rtld_map
.l_next
= _dl_rtld_map
.l_prev
->l_next
;
1966 assert (_dl_rtld_map
.l_prev
->l_next
== _dl_rtld_map
.l_next
);
1967 _dl_rtld_map
.l_prev
->l_next
= &_dl_rtld_map
;
1968 if (_dl_rtld_map
.l_next
!= NULL
)
1970 assert (_dl_rtld_map
.l_next
->l_prev
== _dl_rtld_map
.l_prev
);
1971 _dl_rtld_map
.l_next
->l_prev
= &_dl_rtld_map
;
1974 /* Now let us see whether all libraries are available in the
1975 versions we need. */
1977 struct version_check_args args
;
1978 args
.doexit
= state
.mode
== rtld_mode_normal
;
1979 args
.dotrace
= state
.mode
== rtld_mode_trace
;
1980 _dl_receive_error (print_missing_version
, version_check_doit
, &args
);
1983 /* We do not initialize any of the TLS functionality unless any of the
1984 initial modules uses TLS. This makes dynamic loading of modules with
1985 TLS impossible, but to support it requires either eagerly doing setup
1986 now or lazily doing it later. Doing it now makes us incompatible with
1987 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1988 used. Trying to do it lazily is too hairy to try when there could be
1989 multiple threads (from a non-TLS-using libpthread). */
1990 bool was_tls_init_tp_called
= __rtld_tls_init_tp_called
;
1992 tcbp
= init_tls (0);
1994 if (__glibc_likely (need_security_init
))
1995 /* Initialize security features. But only if we have not done it
1999 if (__glibc_unlikely (state
.mode
!= rtld_mode_normal
))
2001 /* We were run just to list the shared libraries. It is
2002 important that we do this before real relocation, because the
2003 functions we call below for output may no longer work properly
2004 after relocation. */
2007 if (GLRO(dl_debug_mask
) & DL_DEBUG_UNUSED
)
2009 /* Look through the dependencies of the main executable
2010 and determine which of them is not actually
2012 struct link_map
*l
= main_map
;
2014 /* Relocate the main executable. */
2015 struct relocate_args args
= { .l
= l
,
2016 .reloc_mode
= ((GLRO(dl_lazy
)
2018 | __RTLD_NOIFUNC
) };
2019 _dl_receive_error (print_unresolved
, relocate_doit
, &args
);
2021 /* This loop depends on the dependencies of the executable to
2022 correspond in number and order to the DT_NEEDED entries. */
2023 ElfW(Dyn
) *dyn
= main_map
->l_ld
;
2025 while (dyn
->d_tag
!= DT_NULL
)
2027 if (dyn
->d_tag
== DT_NEEDED
)
2030 #ifdef NEED_DL_SYSINFO_DSO
2031 /* Skip the VDSO since it's not part of the list
2032 of objects we brought in via DT_NEEDED entries. */
2033 if (l
== GLRO(dl_sysinfo_map
))
2040 _dl_printf ("Unused direct dependencies:\n");
2044 _dl_printf ("\t%s\n", l
->l_name
);
2051 _exit (first
!= true);
2053 else if (! main_map
->l_info
[DT_NEEDED
])
2054 _dl_printf ("\tstatically linked\n");
2057 for (l
= state
.mode_trace_program
? main_map
: main_map
->l_next
;
2060 /* The library was not found. */
2061 _dl_printf ("\t%s => not found\n", l
->l_libname
->name
);
2062 else if (strcmp (l
->l_libname
->name
, l
->l_name
) == 0)
2063 /* Print vDSO like libraries without duplicate name. Some
2064 consumers depend of this format. */
2065 _dl_printf ("\t%s (0x%0*zx)\n", l
->l_libname
->name
,
2066 (int) sizeof l
->l_map_start
* 2,
2067 (size_t) l
->l_map_start
);
2069 _dl_printf ("\t%s => %s (0x%0*zx)\n",
2070 DSO_FILENAME (l
->l_libname
->name
),
2071 DSO_FILENAME (l
->l_name
),
2072 (int) sizeof l
->l_map_start
* 2,
2073 (size_t) l
->l_map_start
);
2077 if (__glibc_unlikely (state
.mode
!= rtld_mode_trace
))
2078 for (i
= 1; i
< (unsigned int) _dl_argc
; ++i
)
2080 const ElfW(Sym
) *ref
= NULL
;
2081 ElfW(Addr
) loadbase
;
2084 result
= _dl_lookup_symbol_x (_dl_argv
[i
], main_map
,
2085 &ref
, main_map
->l_scope
,
2086 NULL
, ELF_RTYPE_CLASS_PLT
,
2087 DL_LOOKUP_ADD_DEPENDENCY
, NULL
);
2089 loadbase
= LOOKUP_VALUE_ADDRESS (result
, false);
2091 _dl_printf ("%s found at 0x%0*zd in object at 0x%0*zd\n",
2093 (int) sizeof ref
->st_value
* 2,
2094 (size_t) ref
->st_value
,
2095 (int) sizeof loadbase
* 2, (size_t) loadbase
);
2099 /* If LD_WARN is set, warn about undefined symbols. */
2100 if (GLRO(dl_lazy
) >= 0 && GLRO(dl_verbose
))
2102 /* We have to do symbol dependency testing. */
2103 struct relocate_args args
;
2106 args
.reloc_mode
= ((GLRO(dl_lazy
) ? RTLD_LAZY
: 0)
2109 i
= main_map
->l_searchlist
.r_nlist
;
2112 struct link_map
*l
= main_map
->l_initfini
[i
];
2113 if (l
!= &_dl_rtld_map
&& ! l
->l_faked
)
2116 _dl_receive_error (print_unresolved
, relocate_doit
,
2122 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
2123 if (state
.version_info
)
2125 /* Print more information. This means here, print information
2126 about the versions needed. */
2128 struct link_map
*map
;
2130 for (map
= main_map
; map
!= NULL
; map
= map
->l_next
)
2133 ElfW(Dyn
) *dyn
= map
->l_info
[VERNEEDTAG
];
2139 strtab
= (const void *) D_PTR (map
, l_info
[DT_STRTAB
]);
2140 ent
= (ElfW(Verneed
) *) (map
->l_addr
+ dyn
->d_un
.d_ptr
);
2144 _dl_printf ("\n\tVersion information:\n");
2148 _dl_printf ("\t%s:\n", DSO_FILENAME (map
->l_name
));
2153 struct link_map
*needed
;
2155 needed
= find_needed (strtab
+ ent
->vn_file
);
2156 aux
= (ElfW(Vernaux
) *) ((char *) ent
+ ent
->vn_aux
);
2160 const char *fname
= NULL
;
2163 && match_version (strtab
+ aux
->vna_name
,
2165 fname
= needed
->l_name
;
2167 _dl_printf ("\t\t%s (%s) %s=> %s\n",
2168 strtab
+ ent
->vn_file
,
2169 strtab
+ aux
->vna_name
,
2170 aux
->vna_flags
& VER_FLG_WEAK
2172 fname
?: "not found");
2174 if (aux
->vna_next
== 0)
2175 /* No more symbols. */
2179 aux
= (ElfW(Vernaux
) *) ((char *) aux
2183 if (ent
->vn_next
== 0)
2184 /* No more dependencies. */
2187 /* Next dependency. */
2188 ent
= (ElfW(Verneed
) *) ((char *) ent
+ ent
->vn_next
);
2197 /* Now set up the variable which helps the assembler startup code. */
2198 GL(dl_ns
)[LM_ID_BASE
]._ns_main_searchlist
= &main_map
->l_searchlist
;
2200 /* Save the information about the original global scope list since
2201 we need it in the memory handling later. */
2202 GLRO(dl_initial_searchlist
) = *GL(dl_ns
)[LM_ID_BASE
]._ns_main_searchlist
;
2204 /* Remember the last search directory added at startup, now that
2205 malloc will no longer be the one from dl-minimal.c. As a side
2206 effect, this marks ld.so as initialized, so that the rtld_active
2207 function returns true from now on. */
2208 GLRO(dl_init_all_dirs
) = GL(dl_all_dirs
);
2210 /* Print scope information. */
2211 if (__glibc_unlikely (GLRO(dl_debug_mask
) & DL_DEBUG_SCOPES
))
2213 _dl_debug_printf ("\nInitial object scopes\n");
2215 for (struct link_map
*l
= main_map
; l
!= NULL
; l
= l
->l_next
)
2216 _dl_show_scope (l
, 0);
2219 _rtld_main_check (main_map
, _dl_argv
[0]);
2221 /* Now we have all the objects loaded. */
2223 int consider_profiling
= GLRO(dl_profile
) != NULL
;
2225 /* If we are profiling we also must do lazy reloaction. */
2226 GLRO(dl_lazy
) |= consider_profiling
;
2228 /* If libc.so has been loaded, relocate it early, after the dynamic
2229 loader itself. The initial self-relocation of ld.so should be
2230 sufficient for IFUNC resolvers in libc.so. */
2231 if (GL(dl_ns
)[LM_ID_BASE
].libc_map
!= NULL
)
2233 RTLD_TIMING_VAR (start
);
2234 rtld_timer_start (&start
);
2235 _dl_relocate_object (GL(dl_ns
)[LM_ID_BASE
].libc_map
,
2236 GL(dl_ns
)[LM_ID_BASE
].libc_map
->l_scope
,
2237 GLRO(dl_lazy
) ? RTLD_LAZY
: 0, consider_profiling
);
2238 rtld_timer_accum (&relocate_time
, start
);
2241 RTLD_TIMING_VAR (start
);
2242 rtld_timer_start (&start
);
2244 unsigned i
= main_map
->l_searchlist
.r_nlist
;
2247 struct link_map
*l
= main_map
->l_initfini
[i
];
2249 /* While we are at it, help the memory handling a bit. We have to
2250 mark some data structures as allocated with the fake malloc()
2251 implementation in ld.so. */
2252 struct libname_list
*lnp
= l
->l_libname
->next
;
2254 while (__builtin_expect (lnp
!= NULL
, 0))
2259 /* Also allocated with the fake malloc(). */
2260 l
->l_free_initfini
= 0;
2262 _dl_relocate_object (l
, l
->l_scope
, GLRO(dl_lazy
) ? RTLD_LAZY
: 0,
2263 consider_profiling
);
2265 /* Add object to slot information data if necessasy. */
2266 if (l
->l_tls_blocksize
!= 0 && __rtld_tls_init_tp_called
)
2267 _dl_add_to_slotinfo (l
, true);
2270 rtld_timer_stop (&relocate_time
, start
);
2272 /* This call must come after the slotinfo array has been filled in
2273 using _dl_add_to_slotinfo. */
2274 _dl_tls_initial_modid_limit_setup ();
2276 /* Now enable profiling if needed. Like the previous call,
2277 this has to go here because the calls it makes should use the
2278 rtld versions of the functions (particularly calloc()), but it
2279 needs to have _dl_profile_map set up by the relocator. */
2280 if (__glibc_unlikely (GL(dl_profile_map
) != NULL
))
2281 /* We must prepare the profiling. */
2282 _dl_start_profile ();
2284 if ((!was_tls_init_tp_called
&& GL(dl_tls_max_dtv_idx
) > 0)
2285 || count_modids
!= _dl_count_modids ())
2286 ++GL(dl_tls_generation
);
2288 /* Now that we have completed relocation, the initializer data
2289 for the TLS blocks has its final values and we can copy them
2290 into the main thread's TLS area, which we allocated above.
2291 Note: thread-local variables must only be accessed after completing
2293 _dl_allocate_tls_init (tcbp
, true);
2295 /* And finally install it for the main thread. */
2296 if (! __rtld_tls_init_tp_called
)
2297 call_tls_init_tp (tcbp
);
2299 /* Make sure no new search directories have been added. */
2300 assert (GLRO(dl_init_all_dirs
) == GL(dl_all_dirs
));
2302 /* Set up the object lookup structures. */
2303 _dl_find_object_init ();
2305 /* If libc.so was loaded, relocate ld.so against it. Complete ld.so
2306 initialization with mutex symbols from libc.so and malloc symbols
2307 from the global scope. */
2308 if (GL(dl_ns
)[LM_ID_BASE
].libc_map
!= NULL
)
2310 RTLD_TIMING_VAR (start
);
2311 rtld_timer_start (&start
);
2312 _dl_relocate_object_no_relro (&_dl_rtld_map
, main_map
->l_scope
, 0, 0);
2313 rtld_timer_accum (&relocate_time
, start
);
2315 __rtld_mutex_init ();
2316 __rtld_malloc_init_real (main_map
);
2319 /* All ld.so initialization is complete. Apply RELRO. */
2320 _dl_protect_relro (&_dl_rtld_map
);
2322 /* Relocation is complete. Perform early libc initialization. This
2323 is the initial libc, even if audit modules have been loaded with
2325 _dl_call_libc_early_init (GL(dl_ns
)[LM_ID_BASE
].libc_map
, true);
2327 /* Do any necessary cleanups for the startup OS interface code.
2328 We do these now so that no calls are made after rtld re-relocation
2329 which might be resolved to different functions than we expect.
2330 We cannot do this before relocating the other objects because
2331 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2332 _dl_sysdep_start_cleanup ();
2334 /* Notify the debugger all new objects are now ready to go. We must re-get
2335 the address since by now the variable might be in another object. */
2336 r
= _dl_debug_update (LM_ID_BASE
);
2337 r
->r_state
= RT_CONSISTENT
;
2339 LIBC_PROBE (init_complete
, 2, LM_ID_BASE
, r
);
2341 /* Auditing checkpoint: we have added all objects. */
2342 _dl_audit_activity_nsid (LM_ID_BASE
, LA_ACT_CONSISTENT
);
2344 #if defined USE_LDCONFIG && !defined MAP_COPY
2345 /* We must munmap() the cache file. */
2346 _dl_unload_cache ();
2349 /* Once we return, _dl_sysdep_start will invoke
2350 the DT_INIT functions and then *USER_ENTRY. */
2353 /* This is a little helper function for resolving symbols while
2354 tracing the binary. */
2356 print_unresolved (int errcode
__attribute__ ((unused
)), const char *objname
,
2357 const char *errstring
)
2359 if (objname
[0] == '\0')
2360 objname
= RTLD_PROGNAME
;
2361 _dl_error_printf ("%s (%s)\n", errstring
, objname
);
2364 /* This is a little helper function for resolving symbols while
2365 tracing the binary. */
2367 print_missing_version (int errcode
__attribute__ ((unused
)),
2368 const char *objname
, const char *errstring
)
2370 _dl_error_printf ("%s: %s: %s\n", RTLD_PROGNAME
,
2371 objname
, errstring
);
2374 /* Process the string given as the parameter which explains which debugging
2375 options are enabled. */
2377 process_dl_debug (struct dl_main_state
*state
, const char *dl_debug
)
2379 /* When adding new entries make sure that the maximal length of a name
2380 is correctly handled in the LD_DEBUG_HELP code below. */
2384 const char name
[10];
2385 const char helptext
[41];
2386 unsigned short int mask
;
2389 #define LEN_AND_STR(str) sizeof (str) - 1, str
2390 { LEN_AND_STR ("libs"), "display library search paths",
2391 DL_DEBUG_LIBS
| DL_DEBUG_IMPCALLS
},
2392 { LEN_AND_STR ("reloc"), "display relocation processing",
2393 DL_DEBUG_RELOC
| DL_DEBUG_IMPCALLS
},
2394 { LEN_AND_STR ("files"), "display progress for input file",
2395 DL_DEBUG_FILES
| DL_DEBUG_IMPCALLS
},
2396 { LEN_AND_STR ("symbols"), "display symbol table processing",
2397 DL_DEBUG_SYMBOLS
| DL_DEBUG_IMPCALLS
},
2398 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2399 DL_DEBUG_BINDINGS
| DL_DEBUG_IMPCALLS
},
2400 { LEN_AND_STR ("versions"), "display version dependencies",
2401 DL_DEBUG_VERSIONS
| DL_DEBUG_IMPCALLS
},
2402 { LEN_AND_STR ("scopes"), "display scope information",
2404 { LEN_AND_STR ("all"), "all previous options combined",
2405 DL_DEBUG_LIBS
| DL_DEBUG_RELOC
| DL_DEBUG_FILES
| DL_DEBUG_SYMBOLS
2406 | DL_DEBUG_BINDINGS
| DL_DEBUG_VERSIONS
| DL_DEBUG_IMPCALLS
2407 | DL_DEBUG_SCOPES
},
2408 { LEN_AND_STR ("statistics"), "display relocation statistics",
2409 DL_DEBUG_STATISTICS
},
2410 { LEN_AND_STR ("unused"), "determined unused DSOs",
2412 { LEN_AND_STR ("help"), "display this help message and exit",
2415 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2417 /* Skip separating white spaces and commas. */
2418 while (*dl_debug
!= '\0')
2420 if (*dl_debug
!= ' ' && *dl_debug
!= ',' && *dl_debug
!= ':')
2425 while (dl_debug
[len
] != '\0' && dl_debug
[len
] != ' '
2426 && dl_debug
[len
] != ',' && dl_debug
[len
] != ':')
2429 for (cnt
= 0; cnt
< ndebopts
; ++cnt
)
2430 if (debopts
[cnt
].len
== len
2431 && memcmp (dl_debug
, debopts
[cnt
].name
, len
) == 0)
2433 GLRO(dl_debug_mask
) |= debopts
[cnt
].mask
;
2437 if (cnt
== ndebopts
)
2439 /* Display a warning and skip everything until next
2441 char *copy
= strndupa (dl_debug
, len
);
2442 _dl_error_printf ("\
2443 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy
);
2453 if (GLRO(dl_debug_mask
) & DL_DEBUG_UNUSED
)
2455 /* In order to get an accurate picture of whether a particular
2456 DT_NEEDED entry is actually used we have to process both
2457 the PLT and non-PLT relocation entries. */
2461 if (GLRO(dl_debug_mask
) & DL_DEBUG_HELP
)
2466 Valid options for the LD_DEBUG environment variable are:\n\n");
2468 for (cnt
= 0; cnt
< ndebopts
; ++cnt
)
2469 _dl_printf (" %.*s%s%s\n", debopts
[cnt
].len
, debopts
[cnt
].name
,
2470 " " + debopts
[cnt
].len
- 3,
2471 debopts
[cnt
].helptext
);
2474 To direct the debugging output into a file instead of standard output\n\
2475 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2481 process_envvars_secure (struct dl_main_state
*state
)
2483 char **runp
= _environ
;
2487 while ((envline
= _dl_next_ld_env_entry (&runp
)) != NULL
)
2491 while (envline
[len
] != '\0' && envline
[len
] != '=')
2494 if (envline
[len
] != '=')
2495 /* This is a "LD_" variable at the end of the string without
2496 a '=' character. Ignore it since otherwise we will access
2497 invalid memory below. */
2503 /* For __libc_enable_secure mode, audit pathnames containing slashes
2504 are ignored. Also, shared audit objects are only loaded only from
2505 the standard search directories and only if they have set-user-ID
2506 mode bit enabled. */
2507 if (memcmp (envline
, "AUDIT", 5) == 0)
2508 audit_list_add_string (&state
->audit_list
, &envline
[6]);
2512 /* For __libc_enable_secure mode, preload pathnames containing slashes
2513 are ignored. Also, shared objects are only preloaded from the
2514 standard search directories and only if they have set-user-ID mode
2516 if (memcmp (envline
, "PRELOAD", 7) == 0)
2517 state
->preloadlist
= &envline
[8];
2522 /* Extra security for SUID binaries. Remove all dangerous environment
2524 const char *nextp
= UNSECURE_ENVVARS
;
2527 /* Keep track of the number of environment variables that were set in
2528 the environment and are unset below. Use getenv() which returns
2529 non-NULL if the variable is set in the environment. This count is
2530 needed if we need to adjust the location of the AUX vector on the
2531 stack when running ld.so directly. */
2532 if (getenv (nextp
) != NULL
)
2536 nextp
= strchr (nextp
, '\0') + 1;
2538 while (*nextp
!= '\0');
2540 if (GLRO(dl_debug_mask
) != 0
2541 || GLRO(dl_verbose
) != 0
2542 || GLRO(dl_lazy
) != 1
2543 || GLRO(dl_bind_not
) != 0
2544 || state
->mode
!= rtld_mode_normal
2545 || state
->version_info
)
2552 process_envvars_default (struct dl_main_state
*state
)
2554 char **runp
= _environ
;
2556 char *debug_output
= NULL
;
2558 while ((envline
= _dl_next_ld_env_entry (&runp
)) != NULL
)
2562 while (envline
[len
] != '\0' && envline
[len
] != '=')
2565 if (envline
[len
] != '=')
2566 /* This is a "LD_" variable at the end of the string without
2567 a '=' character. Ignore it since otherwise we will access
2568 invalid memory below. */
2574 /* Warning level, verbose or not. */
2575 if (memcmp (envline
, "WARN", 4) == 0)
2576 GLRO(dl_verbose
) = envline
[5] != '\0';
2580 /* Debugging of the dynamic linker? */
2581 if (memcmp (envline
, "DEBUG", 5) == 0)
2583 process_dl_debug (state
, &envline
[6]);
2586 /* For __libc_enable_secure mode, audit pathnames containing slashes
2587 are ignored. Also, shared audit objects are only loaded only from
2588 the standard search directories and only if they have set-user-ID
2589 mode bit enabled. */
2590 if (memcmp (envline
, "AUDIT", 5) == 0)
2591 audit_list_add_string (&state
->audit_list
, &envline
[6]);
2595 /* Print information about versions. */
2596 if (memcmp (envline
, "VERBOSE", 7) == 0)
2598 state
->version_info
= envline
[8] != '\0';
2602 /* For __libc_enable_secure mode, preload pathnames containing slashes
2603 are ignored. Also, shared objects are only preloaded from the
2604 standard search directories and only if they have set-user-ID mode
2606 if (memcmp (envline
, "PRELOAD", 7) == 0)
2608 state
->preloadlist
= &envline
[8];
2612 /* Which shared object shall be profiled. */
2613 if (memcmp (envline
, "PROFILE", 7) == 0 && envline
[8] != '\0')
2614 GLRO(dl_profile
) = &envline
[8];
2618 /* Do we bind early? */
2619 if (memcmp (envline
, "BIND_NOW", 8) == 0)
2621 GLRO(dl_lazy
) = envline
[9] == '\0';
2624 if (memcmp (envline
, "BIND_NOT", 8) == 0)
2625 GLRO(dl_bind_not
) = envline
[9] != '\0';
2629 /* Test whether we want to see the content of the auxiliary
2630 array passed up from the kernel. */
2631 if (memcmp (envline
, "SHOW_AUXV", 9) == 0)
2636 /* Path where the binary is found. */
2637 if (memcmp (envline
, "ORIGIN_PATH", 11) == 0)
2638 GLRO(dl_origin_path
) = &envline
[12];
2642 /* The library search path. */
2643 if (memcmp (envline
, "LIBRARY_PATH", 12) == 0)
2645 state
->library_path
= &envline
[13];
2646 state
->library_path_source
= "LD_LIBRARY_PATH";
2650 /* Where to place the profiling data file. */
2651 if (memcmp (envline
, "DEBUG_OUTPUT", 12) == 0)
2653 debug_output
= &envline
[13];
2657 if (memcmp (envline
, "DYNAMIC_WEAK", 12) == 0)
2658 GLRO(dl_dynamic_weak
) = 1;
2662 /* Where to place the profiling data file. */
2663 if (memcmp (envline
, "PROFILE_OUTPUT", 14) == 0
2664 && envline
[15] != '\0')
2665 GLRO(dl_profile_output
) = &envline
[15];
2669 /* The mode of the dynamic linker can be set. */
2670 if (memcmp (envline
, "TRACE_LOADED_OBJECTS", 20) == 0)
2672 state
->mode
= rtld_mode_trace
;
2673 state
->mode_trace_program
2674 = _dl_strtoul (&envline
[21], NULL
) > 1;
2680 /* If we have to run the dynamic linker in debugging mode and the
2681 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2682 messages to this file. */
2683 if (GLRO(dl_debug_mask
) != 0 && debug_output
!= NULL
)
2685 const int flags
= O_WRONLY
| O_APPEND
| O_CREAT
| O_NOFOLLOW
;
2686 size_t name_len
= strlen (debug_output
);
2687 char buf
[name_len
+ 12];
2690 buf
[name_len
+ 11] = '\0';
2691 startp
= _itoa (__getpid (), &buf
[name_len
+ 11], 10, 0);
2693 startp
= memcpy (startp
- name_len
, debug_output
, name_len
);
2695 GLRO(dl_debug_fd
) = __open64_nocancel (startp
, flags
, DEFFILEMODE
);
2696 if (GLRO(dl_debug_fd
) == -1)
2697 /* We use standard output if opening the file failed. */
2698 GLRO(dl_debug_fd
) = STDOUT_FILENO
;
2703 process_envvars (struct dl_main_state
*state
)
2706 if (__glibc_unlikely (__libc_enable_secure
))
2707 skip_env
+= process_envvars_secure (state
);
2709 process_envvars_default (state
);
2714 #if HP_TIMING_INLINE
2716 print_statistics_item (const char *title
, hp_timing_t time
,
2719 char cycles
[HP_TIMING_PRINT_SIZE
];
2720 HP_TIMING_PRINT (cycles
, sizeof (cycles
), time
);
2722 char relative
[3 * sizeof (hp_timing_t
) + 2];
2723 char *cp
= _itoa ((1000ULL * time
) / total
, relative
+ sizeof (relative
),
2725 /* Sets the decimal point. */
2726 char *wp
= relative
;
2727 switch (relative
+ sizeof (relative
) - cp
)
2740 _dl_debug_printf ("%s: %s cycles (%s%%)\n", title
, cycles
, relative
);
2744 /* Print the various times we collected. */
2746 __attribute ((noinline
))
2747 print_statistics (const hp_timing_t
*rtld_total_timep
)
2749 #if HP_TIMING_INLINE
2751 char cycles
[HP_TIMING_PRINT_SIZE
];
2752 HP_TIMING_PRINT (cycles
, sizeof (cycles
), *rtld_total_timep
);
2753 _dl_debug_printf ("\nruntime linker statistics:\n"
2754 " total startup time in dynamic loader: %s cycles\n",
2756 print_statistics_item (" time needed for relocation",
2757 relocate_time
, *rtld_total_timep
);
2761 unsigned long int num_relative_relocations
= 0;
2762 for (Lmid_t ns
= 0; ns
< GL(dl_nns
); ++ns
)
2764 if (GL(dl_ns
)[ns
]._ns_loaded
== NULL
)
2767 struct r_scope_elem
*scope
= &GL(dl_ns
)[ns
]._ns_loaded
->l_searchlist
;
2769 for (unsigned int i
= 0; i
< scope
->r_nlist
; i
++)
2771 struct link_map
*l
= scope
->r_list
[i
];
2773 if (l
->l_addr
!= 0 && l
->l_info
[VERSYMIDX (DT_RELCOUNT
)])
2774 num_relative_relocations
2775 += l
->l_info
[VERSYMIDX (DT_RELCOUNT
)]->d_un
.d_val
;
2776 #ifndef ELF_MACHINE_REL_RELATIVE
2777 /* Relative relocations are always processed on these
2779 if (l
->l_info
[VERSYMIDX (DT_RELACOUNT
)])
2781 /* On e.g. IA-64 or Alpha, relative relocations are processed
2782 only if library is loaded to different address than p_vaddr. */
2783 if (l
->l_addr
!= 0 && l
->l_info
[VERSYMIDX (DT_RELACOUNT
)])
2785 num_relative_relocations
2786 += l
->l_info
[VERSYMIDX (DT_RELACOUNT
)]->d_un
.d_val
;
2790 _dl_debug_printf (" number of relocations: %lu\n"
2791 " number of relocations from cache: %lu\n"
2792 " number of relative relocations: %lu\n",
2793 GL(dl_num_relocations
),
2794 GL(dl_num_cache_relocations
),
2795 num_relative_relocations
);
2797 #if HP_TIMING_INLINE
2798 print_statistics_item (" time needed to load objects",
2799 load_time
, *rtld_total_timep
);