]> git.ipfire.org Git - thirdparty/glibc.git/blame - elf/rtld.c
manual: Remove '.info' suffix in manual names passed to @ref [BZ #32962].
[thirdparty/glibc.git] / elf / rtld.c
CommitLineData
d66e34cd 1/* Run time dynamic linker.
26420023 2 Copyright (C) 1995-2025 Free Software Foundation, Inc.
afd4eb37 3 This file is part of the GNU C Library.
d66e34cd 4
afd4eb37 5 The GNU C Library is free software; you can redistribute it and/or
41bdb6e2
AJ
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.
d66e34cd 9
afd4eb37
UD
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
41bdb6e2 13 Lesser General Public License for more details.
d66e34cd 14
41bdb6e2 15 You should have received a copy of the GNU Lesser General Public
59ba27a6 16 License along with the GNU C Library; if not, see
5a82c748 17 <https://www.gnu.org/licenses/>. */
d66e34cd 18
7d0b1164 19#include <errno.h>
154d10bd 20#include <dlfcn.h>
7dea968e 21#include <fcntl.h>
164a7164 22#include <stdbool.h>
d66e34cd 23#include <stdlib.h>
f51d1dfd 24#include <string.h>
d66e34cd 25#include <unistd.h>
20739e54 26#include <sys/mman.h>
af8bf6bd 27#include <sys/param.h>
ba9fcb3f 28#include <sys/stat.h>
a42195db 29#include <ldsodefs.h>
eb96ffb0 30#include <_itoa.h>
f21acc89 31#include <entry.h>
c94a8080 32#include <fpu_control.h>
db276fa1 33#include <hp-timing.h>
ec999b8e 34#include <libc-lock.h>
74955460 35#include <unsecvars.h>
5688da55 36#include <dl-cache.h>
2f4db0df 37#include <dl-osinfo.h>
f753fa7d 38#include <dl-prop.h>
1bdda52f
AZ
39#include <dl-vdso.h>
40#include <dl-vdso-setup.h>
5f5843e3 41#include <tls.h>
815e6fa3 42#include <stap-probe.h>
30950a5f 43#include <stackinfo.h>
329ea513 44#include <not-cancel.h>
4c6e0415 45#include <array_length.h>
ec935dea 46#include <libc-early-init.h>
2bf9e641 47#include <dl-main.h>
4d098554 48#include <gnu/lib-names.h>
86f65dff 49#include <dl-tunables.h>
d6d89608 50#include <get-dynamic-info.h>
c1cb2dee 51#include <dl-execve.h>
5d28a896 52#include <dl-find_object.h>
ce9a68c5 53#include <dl-audit-check.h>
1f34a232 54#include <dl-call_tls_init_tp.h>
f5348425 55
a853022c 56#include <assert.h>
f5348425 57
d6d89608
AZ
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"
65
9288c92d
L
66/* Must include after <dl-machine.h> for DT_MIPS definition. */
67#include <dl-debug.h>
68
1e372ded
AZ
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. */
74#if HP_TIMING_INLINE
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)
80
81static inline void
82rtld_timer_start (hp_timing_t *var)
83{
84 HP_TIMING_NOW (*var);
85}
86
87static inline void
88rtld_timer_stop (hp_timing_t *var, hp_timing_t start)
89{
90 hp_timing_t stop;
91 HP_TIMING_NOW (stop);
92 HP_TIMING_DIFF (*var, start, stop);
93}
94
95static inline void
96rtld_timer_accum (hp_timing_t *sum, hp_timing_t start)
97{
98 hp_timing_t stop;
99 rtld_timer_stop (&stop, start);
100 HP_TIMING_ACCUM_NT(*sum, stop);
101}
102#else
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)
110#endif
111
6ce3881d
RM
112/* Avoid PLT use for our local calls at startup. */
113extern __typeof (__mempcpy) __mempcpy attribute_hidden;
114
115/* GCC has mental blocks about _exit. */
116extern __typeof (_exit) exit_internal asm ("_exit") attribute_hidden;
117#define _exit exit_internal
118
fd26970f 119/* Helper function to handle errors while resolving symbols. */
c84142e8
UD
120static void print_unresolved (int errcode, const char *objname,
121 const char *errsting);
122
123/* Helper function to handle errors when a version is missing. */
124static void print_missing_version (int errcode, const char *objname,
125 const char *errsting);
fd26970f 126
db276fa1 127/* Print the various times we collected. */
1e372ded 128static void print_statistics (const hp_timing_t *total_timep);
ea278354 129
4c6e0415
FW
130/* Creates an empty audit list. */
131static void audit_list_init (struct audit_list *);
132
133/* Add a string to the end of the audit list, for later parsing. Must
134 not be called after audit_list_next. */
135static void audit_list_add_string (struct audit_list *, const char *);
136
8f7a75d7
FW
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. */
140static void audit_list_add_dynamic_tag (struct audit_list *,
141 struct link_map *,
142 unsigned int tag);
143
4c6e0415
FW
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
8f7a75d7
FW
146 called after all the audit_list_add_string,
147 audit_list_add_dynamic_tags calls. */
4c6e0415 148static const char *audit_list_next (struct audit_list *);
74780cf6 149
2bf9e641
FW
150/* Initialize *STATE with the defaults. */
151static void dl_main_state_init (struct dl_main_state *state);
ea278354
UD
152
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
155 all the entries. */
851f32cf 156extern char **_environ attribute_hidden;
59974938 157static int process_envvars (struct dl_main_state *state);
ea278354 158
22aa06a5 159int _dl_argc attribute_relro attribute_hidden;
697afbe1 160char **_dl_argv attribute_relro = NULL;
4243cbea 161rtld_hidden_data_def (_dl_argv)
5c82e15e 162
35f1e827
UD
163#ifndef THREAD_SET_STACK_GUARD
164/* Only exported for architectures that don't store the stack guard canary
165 in thread local area. */
166uintptr_t __stack_chk_guard attribute_relro;
167#endif
168
827b7087
UD
169/* Only exported for architectures that don't store the pointer guard
170 value in thread local area. */
7c241325 171uintptr_t __pointer_chk_guard_local attribute_relro attribute_hidden;
827b7087
UD
172#ifndef THREAD_SET_POINTER_GUARD
173strong_alias (__pointer_chk_guard_local, __pointer_chk_guard)
174#endif
175
6d0ba622
FW
176/* Check that AT_SECURE=0, or that the passed name does not contain
177 directories and is not overly long. Reject empty names
178 unconditionally. */
179static bool
180dso_name_valid_for_suid (const char *p)
181{
182 if (__glibc_unlikely (__libc_enable_secure))
183 {
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)
188 return false;
189 }
190 return *p != '\0';
191}
827b7087 192
4c6e0415
FW
193static void
194audit_list_init (struct audit_list *list)
9dcafc55 195{
4c6e0415
FW
196 list->length = 0;
197 list->current_index = 0;
198 list->current_tail = NULL;
199}
9dcafc55 200
4c6e0415
FW
201static void
202audit_list_add_string (struct audit_list *list, const char *string)
81b82fb9 203{
4c6e0415
FW
204 /* Empty strings do not load anything. */
205 if (*string == '\0')
206 return;
81b82fb9 207
4c6e0415
FW
208 if (list->length == array_length (list->audit_strings))
209 _dl_fatal_printf ("Fatal glibc error: Too many audit modules requested\n");
81b82fb9 210
4c6e0415 211 list->audit_strings[list->length++] = string;
81b82fb9 212
4c6e0415
FW
213 /* Initialize processing of the first string for
214 audit_list_next. */
215 if (list->length == 1)
216 list->current_tail = string;
81b82fb9
FW
217}
218
8f7a75d7
FW
219static void
220audit_list_add_dynamic_tag (struct audit_list *list, struct link_map *main_map,
221 unsigned int tag)
222{
223 ElfW(Dyn) *info = main_map->l_info[ADDRIDX (tag)];
224 const char *strtab = (const char *) D_PTR (main_map, l_info[DT_STRTAB]);
225 if (info != NULL)
226 audit_list_add_string (list, strtab + info->d_un.d_val);
227}
228
81b82fb9 229static const char *
4c6e0415 230audit_list_next (struct audit_list *list)
81b82fb9 231{
4c6e0415
FW
232 if (list->current_tail == NULL)
233 return NULL;
234
235 while (true)
81b82fb9 236 {
4c6e0415
FW
237 /* Advance to the next string in audit_strings if the current
238 string has been exhausted. */
239 while (*list->current_tail == '\0')
81b82fb9 240 {
4c6e0415
FW
241 ++list->current_index;
242 if (list->current_index == list->length)
81b82fb9 243 {
4c6e0415
FW
244 list->current_tail = NULL;
245 return NULL;
81b82fb9 246 }
4c6e0415 247 list->current_tail = list->audit_strings[list->current_index];
81b82fb9 248 }
81b82fb9 249
4c6e0415
FW
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))
253 {
254 memcpy (list->fname, list->current_tail, len);
255 list->fname[len] = '\0';
256 }
257 else
258 /* Mark the name as unusable for dso_name_valid_for_suid. */
259 list->fname[0] = '\0';
260
261 /* Skip over the substring and the following delimiter. */
262 list->current_tail += len;
263 if (*list->current_tail == ':')
264 ++list->current_tail;
265
266 /* If the name is valid, return it. */
267 if (dso_name_valid_for_suid (list->fname))
268 return list->fname;
269
270 /* Otherwise wrap around to find the next list element. . */
81b82fb9 271 }
81b82fb9
FW
272}
273
17796419
SN
274/* Count audit modules before they are loaded so GLRO(dl_naudit)
275 is not yet usable. */
276static size_t
277audit_list_count (struct audit_list *list)
278{
279 /* Restore the audit_list iterator state at the end. */
280 const char *saved_tail = list->current_tail;
281 size_t naudit = 0;
282
283 assert (list->current_index == 0);
284 while (audit_list_next (list) != NULL)
285 naudit++;
286 list->current_tail = saved_tail;
287 list->current_index = 0;
288 return naudit;
289}
290
2bf9e641
FW
291static void
292dl_main_state_init (struct dl_main_state *state)
293{
294 audit_list_init (&state->audit_list);
295 state->library_path = NULL;
27316f4a 296 state->library_path_source = NULL;
2bf9e641
FW
297 state->preloadlist = NULL;
298 state->preloadarg = NULL;
dad90d52
FW
299 state->glibc_hwcaps_prepend = NULL;
300 state->glibc_hwcaps_mask = NULL;
2bf9e641 301 state->mode = rtld_mode_normal;
2bf9e641
FW
302 state->version_info = false;
303}
304
ce6e047f 305#ifndef HAVE_INLINED_SYSCALLS
39778c6c
UD
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
312 never be called. */
e6caf4e1 313int _dl_starting_up = 0;
9cf27b8d 314rtld_hidden_def (_dl_starting_up)
ce6e047f 315#endif
39778c6c 316
d6b5d570
UD
317/* This is the structure which defines all variables global to ld.so
318 (except those which cannot be added for some reason). */
5688da55
UD
319struct rtld_global _rtld_global =
320 {
674ea882
L
321 /* Get architecture specific initializer. */
322#include <dl-procruntime.c>
30950a5f
RA
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,
ffa8d2a0 326#ifdef _LIBC_REENTRANT
22c83193 327 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
5a2a1d75 328 ._dl_load_write_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
83b53232 329 ._dl_load_tls_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
ffa8d2a0 330#endif
415ac3df
UD
331 ._dl_nns = 1,
332 ._dl_ns =
333 {
bea9b193 334#ifdef _LIBC_REENTRANT
415ac3df
UD
335 [LM_ID_BASE] = { ._ns_unique_sym_table
336 = { .lock = _RTLD_LOCK_RECURSIVE_INITIALIZER } }
bea9b193 337#endif
415ac3df 338 }
5688da55 339 };
27a754a9
UD
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
7ee881f1 342 declaration. So spell out what strong_alias does plus add the
27a754a9
UD
343 visibility attribute. */
344extern struct rtld_global _rtld_local
345 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
c0fb8a56 346
afdca0f2
UD
347
348/* This variable is similar to _rtld_local, but all values are
349 read-only after relocation. */
350struct rtld_global_ro _rtld_global_ro attribute_relro =
351 {
c31e278f
UD
352 /* Get architecture specific initializer. */
353#include <dl-procinfo.c>
afdca0f2
UD
354#ifdef NEED_DL_SYSINFO
355 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
356#endif
dd70526e 357 ._dl_debug_fd = STDERR_FILENO,
afdca0f2
UD
358 ._dl_lazy = 1,
359 ._dl_fpu_control = _FPU_DEFAULT,
02d46fc4 360 ._dl_pagesize = EXEC_PAGESIZE,
73d65cc3 361 ._dl_inhibit_cache = 0,
4a133885 362 ._dl_profile_output = "/var/tmp",
154d10bd
UD
363
364 /* Function pointers. */
154d10bd 365 ._dl_debug_printf = _dl_debug_printf,
ab97ee8f 366 ._dl_mcount = _dl_mcount,
021723ab 367 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
9dcafc55 368 ._dl_open = _dl_open,
93025f93 369 ._dl_close = _dl_close,
ee1ada1b 370 ._dl_catch_error = _dl_catch_error,
fada9018 371 ._dl_error_free = _dl_error_free,
7c22c7ec 372 ._dl_tls_get_addr_soft = _dl_tls_get_addr_soft,
f1d333b5 373 ._dl_libc_freeres = __rtld_libc_freeres,
ed6a68ba 374 ._dl_readonly_area = _dl_readonly_area,
afdca0f2
UD
375 };
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. */
380extern struct rtld_global_ro _rtld_local_ro
381 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
382
ef5823d9
FW
383struct link_map _dl_rtld_map;
384struct auditstate _dl_rtld_auditstate[DL_NNS];
afdca0f2 385
67ddea92 386static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
3a56ea26 387 ElfW(Addr) *user_entry, ElfW(auxv_t) *auxv);
d66e34cd 388
392a6b52 389/* These two variables cannot be moved into .data.rel.ro. */
d6b5d570 390static struct libname_list _dl_rtld_libname;
86d2c878 391
db276fa1 392/* Variable for statistics. */
1e372ded
AZ
393RLTD_TIMING_DECLARE (relocate_time, static);
394RLTD_TIMING_DECLARE (load_time, static, attribute_relro);
395RLTD_TIMING_DECLARE (start_time, static, attribute_relro);
db276fa1 396
2a76f7ef
UD
397/* Additional definitions needed by TLS initialization. */
398#ifdef TLS_INIT_HELPER
399TLS_INIT_HELPER
5e289179
UD
400#endif
401
402/* Helper function for syscall implementation. */
403#ifdef DL_SYSINFO_IMPLEMENTATION
404DL_SYSINFO_IMPLEMENTATION
2a76f7ef
UD
405#endif
406
01d8e36d
UD
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
27a754a9 410 is fine, too. The latter is important here. We can avoid setting
01d8e36d
UD
411 up a temporary link map for ld.so if we can mark _rtld_global as
412 hidden. */
098a657f 413#ifndef HIDDEN_VAR_NEEDS_DYNAMIC_RELOC
01d8e36d
UD
414# define DONT_USE_BOOTSTRAP_MAP 1
415#endif
416
417#ifdef DONT_USE_BOOTSTRAP_MAP
418static ElfW(Addr) _dl_start_final (void *arg);
419#else
4874b009
RM
420struct dl_start_final_info
421{
422 struct link_map l;
1e372ded 423 RTLD_TIMING_VAR (start_time);
4874b009 424};
01d8e36d 425static ElfW(Addr) _dl_start_final (void *arg,
4874b009 426 struct dl_start_final_info *info);
01d8e36d 427#endif
6a1db4ff 428
6f043e0e
AM
429/* These are defined magically by the linker. */
430extern const ElfW(Ehdr) __ehdr_start attribute_hidden;
65da9563
RM
431extern char _end[] attribute_hidden;
432
433
b1dbbaa4
RM
434#ifdef RTLD_START
435RTLD_START
436#else
eaad82e0 437# error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
b1dbbaa4
RM
438#endif
439
c2248c44
RM
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). */
445
446#ifdef DONT_USE_BOOTSTRAP_MAP
447static inline ElfW(Addr) __attribute__ ((always_inline))
448_dl_start_final (void *arg)
449#else
450static ElfW(Addr) __attribute__ ((noinline))
4874b009 451_dl_start_final (void *arg, struct dl_start_final_info *info)
c2248c44
RM
452#endif
453{
454 ElfW(Addr) start_addr;
c2248c44 455
2abfa190
FW
456 __rtld_malloc_init_stubs ();
457
1305edd4 458 /* Do not use an initializer for these members because it would
630da022 459 interfere with __rtld_static_init. */
1305edd4
FS
460 GLRO (dl_find_object) = &_dl_find_object;
461
1e372ded
AZ
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);
4874b009 466#endif
c2248c44
RM
467
468 /* Transfer data about ourselves to the permanent link_map structure. */
469#ifndef DONT_USE_BOOTSTRAP_MAP
ef5823d9
FW
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;
c2248c44 476#endif
ef5823d9
FW
477 _dl_setup_hash (&_dl_rtld_map);
478 _dl_rtld_map.l_real = &_dl_rtld_map;
632d895f
L
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);
c2248c44 483 /* Copy the TLS related data if necessary. */
11bf311e 484#ifndef DONT_USE_BOOTSTRAP_MAP
3d8c8bff 485# if NO_TLS_OFFSET != 0
ef5823d9 486 _dl_rtld_map.l_tls_offset = NO_TLS_OFFSET;
c2248c44 487# endif
c2248c44
RM
488#endif
489
ea4f25a7
UD
490 /* Initialize the stack end variable. */
491 __libc_stack_end = __builtin_frame_address (0);
492
c2248c44
RM
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. */
ecdeaac0 497 start_addr = _dl_sysdep_start (arg, &dl_main);
c2248c44 498
a1ffb40e 499 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS))
39b04aa3 500 {
1e372ded
AZ
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));
39b04aa3 504 }
c2248c44 505
1305edd4
FS
506#ifndef ELF_MACHINE_START_ADDRESS
507# define ELF_MACHINE_START_ADDRESS(map, start) (start)
508#endif
509 return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, start_addr);
c2248c44
RM
510}
511
01d8e36d 512#ifdef DONT_USE_BOOTSTRAP_MAP
ef5823d9 513# define bootstrap_map _dl_rtld_map
01d8e36d 514#else
4874b009 515# define bootstrap_map info.l
739d440d 516#endif
d66e34cd 517
490e6c62
FS
518static ElfW(Addr) __attribute_used__
519_dl_start (void *arg)
520{
4874b009 521#ifdef DONT_USE_BOOTSTRAP_MAP
1e372ded 522 rtld_timer_start (&start_time);
4874b009 523#else
490e6c62 524 struct dl_start_final_info info;
1e372ded 525 rtld_timer_start (&info.start_time);
4874b009 526#endif
db276fa1 527
e66d0a4c
UD
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
01d8e36d
UD
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
e66d0a4c 536 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
01d8e36d 537# else
ce460d04 538 for (size_t cnt = 0;
264ec183
UD
539 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
540 ++cnt)
541 bootstrap_map.l_info[cnt] = 0;
01d8e36d 542# endif
e66d0a4c 543#endif
264ec183 544
d66e34cd 545 /* Figure out the run-time load address of the dynamic linker itself. */
86d2c878 546 bootstrap_map.l_addr = elf_machine_load_address ();
d66e34cd 547
47707456
UD
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 ();
2ec99d8c 550 bootstrap_map.l_ld_readonly = DL_RO_DYN_SECTION;
5118dcac 551 elf_get_dynamic_info (&bootstrap_map, true, false);
d66e34cd 552
11bf311e 553#if NO_TLS_OFFSET != 0
299601a1
UD
554 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
555#endif
556
d66e34cd 557#ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
490e6c62 558 ELF_MACHINE_BEFORE_RTLD_RELOC (&bootstrap_map, bootstrap_map.l_info);
d66e34cd
RM
559#endif
560
6628c742 561 if (bootstrap_map.l_addr)
32e6df36
UD
562 {
563 /* Relocate ourselves so we can do normal function calls and
564 data access using the global offset table. */
565
490e6c62 566 ELF_DYNAMIC_RELOCATE (&bootstrap_map, NULL, 0, 0, 0);
32e6df36 567 }
f85f3563 568 bootstrap_map.l_relocated = 1;
421f82e5 569
ea7eb7e3
UD
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). */
421f82e5 573
d66e34cd
RM
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
6a1db4ff
UD
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. */
3a0ecccb 580
01d8e36d 581#ifdef DONT_USE_BOOTSTRAP_MAP
1305edd4 582 return _dl_start_final (arg);
01d8e36d 583#else
1305edd4 584 return _dl_start_final (arg, &info);
c0282c06 585#endif
6a1db4ff
UD
586}
587
588
d66e34cd 589
d66e34cd
RM
590/* Now life is peachy; we can do all normal operations.
591 On to the real work. */
592
993b3242
UD
593/* Some helper functions. */
594
595/* Arguments to relocate_doit. */
596struct relocate_args
597{
598 struct link_map *l;
2ca285b0 599 int reloc_mode;
993b3242
UD
600};
601
602struct map_args
603{
604 /* Argument to map_doit. */
acf869f4 605 const char *str;
f04b9a68 606 struct link_map *loader;
f04b9a68 607 int mode;
993b3242 608 /* Return value of map_doit. */
f04b9a68 609 struct link_map *map;
993b3242
UD
610};
611
9dcafc55
UD
612struct dlmopen_args
613{
614 const char *fname;
615 struct link_map *map;
616};
617
618struct lookup_args
619{
620 const char *name;
621 struct link_map *map;
622 void *result;
623};
624
993b3242
UD
625/* Arguments to version_check_doit. */
626struct version_check_args
627{
993b3242 628 int doexit;
145b8413 629 int dotrace;
993b3242
UD
630};
631
632static void
633relocate_doit (void *a)
634{
635 struct relocate_args *args = (struct relocate_args *) a;
636
2ca285b0 637 _dl_relocate_object (args->l, args->l->l_scope, args->reloc_mode, 0);
993b3242
UD
638}
639
640static void
641map_doit (void *a)
642{
be935610 643 struct map_args *args = (struct map_args *) a;
798212a0
PP
644 int type = (args->mode == __RTLD_OPENEXEC) ? lt_executable : lt_library;
645 args->map = _dl_map_object (args->loader, args->str, type, 0,
8e9f92e9 646 args->mode, LM_ID_BASE);
993b3242
UD
647}
648
9dcafc55
UD
649static void
650dlmopen_doit (void *a)
651{
652 struct dlmopen_args *args = (struct dlmopen_args *) a;
8e9f92e9
AS
653 args->map = _dl_open (args->fname,
654 (RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT
655 | __RTLD_SECURE),
4243cbea 656 dl_main, LM_ID_NEWLM, _dl_argc, _dl_argv,
9dcafc55
UD
657 __environ);
658}
659
660static void
661lookup_doit (void *a)
662{
663 struct lookup_args *args = (struct lookup_args *) a;
664 const ElfW(Sym) *ref = NULL;
665 args->result = 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);
669 if (ref != NULL)
670 args->result = DL_SYMBOL_ADDRESS (l, ref);
671}
672
993b3242
UD
673static void
674version_check_doit (void *a)
675{
be935610 676 struct version_check_args *args = (struct version_check_args *) a;
c0f62c56
UD
677 if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
678 args->dotrace) && args->doexit)
993b3242
UD
679 /* We cannot start the application. Abort now. */
680 _exit (1);
681}
682
ce37fa88
UD
683
684static inline struct link_map *
685find_needed (const char *name)
686{
c0f62c56
UD
687 struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
688 unsigned int n = scope->r_nlist;
ce37fa88 689
be935610 690 while (n-- > 0)
c0f62c56
UD
691 if (_dl_name_match_p (name, scope->r_list[n]))
692 return scope->r_list[n];
ce37fa88
UD
693
694 /* Should never happen. */
695 return NULL;
696}
697
698static int
699match_version (const char *string, struct link_map *map)
700{
a42195db 701 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
ce37fa88
UD
702 ElfW(Verdef) *def;
703
b0982c4a 704#define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
ce37fa88
UD
705 if (map->l_info[VERDEFTAG] == NULL)
706 /* The file has no symbol versioning. */
707 return 0;
708
709 def = (ElfW(Verdef) *) ((char *) map->l_addr
710 + map->l_info[VERDEFTAG]->d_un.d_ptr);
711 while (1)
712 {
713 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
714
715 /* Compare the version strings. */
716 if (strcmp (string, strtab + aux->vda_name) == 0)
717 /* Bingo! */
718 return 1;
719
720 /* If no more definitions we failed to find what we want. */
721 if (def->vd_next == 0)
722 break;
723
724 /* Next definition. */
725 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
726 }
727
728 return 0;
729}
730
a65ff76c 731bool __rtld_tls_init_tp_called;
9dcafc55
UD
732
733static void *
17796419 734init_tls (size_t naudit)
9dcafc55
UD
735{
736 /* Number of elements in the static TLS block. */
737 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
738
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)
742 return NULL;
743
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;
748
749 /* Allocate. */
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. */
755
9dcafc55
UD
756 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
757 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
758
0c7b002f 759 /* Calculate the size of the static TLS surplus. */
17796419 760 _dl_tls_static_surplus_init (naudit);
0c7b002f 761
9dcafc55
UD
762 /* Compute the TLS offsets for the various blocks. */
763 _dl_determine_tlsoffset ();
764
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 ();
771 if (tcbp == NULL)
772 _dl_fatal_printf ("\
f648728c 773cannot allocate TLS data structures for initial thread\n");
9dcafc55
UD
774
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);
778
3d8c8bff 779 /* And finally install it for the main thread. */
1f34a232 780 call_tls_init_tp (tcbp);
a65ff76c 781 __rtld_tls_init_tp_called = true;
9dcafc55
UD
782
783 return tcbp;
784}
9dcafc55 785
20fe49b9 786static unsigned int
acf869f4 787do_preload (const char *fname, struct link_map *main_map, const char *where)
20fe49b9
UD
788{
789 const char *objname;
790 const char *err_str = NULL;
791 struct map_args args;
74780cf6 792 bool malloced;
20fe49b9
UD
793
794 args.str = fname;
795 args.loader = main_map;
8e9f92e9 796 args.mode = __RTLD_SECURE;
20fe49b9
UD
797
798 unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
799
74780cf6 800 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
a1ffb40e 801 if (__glibc_unlikely (err_str != NULL))
20fe49b9
UD
802 {
803 _dl_error_printf ("\
4db5b08f
MS
804ERROR: ld.so: object '%s' from %s cannot be preloaded (%s): ignored.\n",
805 fname, where, err_str);
20fe49b9
UD
806 /* No need to call free, this is still before
807 the libc's malloc is used. */
808 }
809 else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
810 /* It is no duplicate. */
811 return 1;
812
813 /* Nothing loaded. */
814 return 0;
815}
816
4c48ef06
UD
817static void
818security_init (void)
819{
820 /* Set up the stack checker's canary. */
965cb60a 821 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard (_dl_random);
4c48ef06
UD
822#ifdef THREAD_SET_STACK_GUARD
823 THREAD_SET_STACK_GUARD (stack_chk_guard);
824#else
825 __stack_chk_guard = stack_chk_guard;
826#endif
827
828 /* Set up the pointer guard as well, if necessary. */
a014cecd
FW
829 uintptr_t pointer_chk_guard
830 = _dl_setup_pointer_guard (_dl_random, stack_chk_guard);
4c48ef06 831#ifdef THREAD_SET_POINTER_GUARD
a014cecd 832 THREAD_SET_POINTER_GUARD (pointer_chk_guard);
4c48ef06 833#endif
a014cecd 834 __pointer_chk_guard_local = pointer_chk_guard;
965cb60a
UD
835
836 /* We do not need the _dl_random value anymore. The less
837 information we leave behind, the better, so clear the
838 variable. */
839 _dl_random = NULL;
4c48ef06
UD
840}
841
1bdda52f 842#include <setup-vdso.h>
4c48ef06 843
6d0ba622
FW
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
8692ebdb 849 performed. Ditto for --preload command argument. */
6d0ba622 850unsigned int
8692ebdb
DN
851handle_preload_list (const char *preloadlist, struct link_map *main_map,
852 const char *where)
6d0ba622
FW
853{
854 unsigned int npreloads = 0;
855 const char *p = preloadlist;
856 char fname[SECURE_PATH_LIMIT];
857
858 while (*p != '\0')
859 {
860 /* Split preload list at space/colon. */
861 size_t len = strcspn (p, " :");
862 if (len > 0 && len < sizeof (fname))
863 {
864 memcpy (fname, p, len);
865 fname[len] = '\0';
866 }
867 else
868 fname[0] = '\0';
869
870 /* Skip over the substring and the following delimiter. */
871 p += len;
872 if (*p != '\0')
873 ++p;
874
875 if (dso_name_valid_for_suid (fname))
8692ebdb 876 npreloads += do_preload (fname, main_map, where);
6d0ba622
FW
877 }
878 return npreloads;
879}
880
3b856d09
FW
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. */
884static void
885unload_audit_module (struct link_map *map, int original_tls_idx)
886{
887#ifndef NDEBUG
888 Lmid_t ns = map->l_ns;
889#endif
890 _dl_close (map);
891
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);
895
896 GL(dl_tls_max_dtv_idx) = original_tls_idx;
897}
898
899/* Called to print an error message if loading of an audit module
900 failed. */
901static void
902report_audit_module_load_error (const char *name, const char *err_str,
903 bool malloced)
904{
905 _dl_error_printf ("\
906ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
907 name, err_str);
908 if (malloced)
909 free ((char *) err_str);
910}
911
912/* Load one audit module. */
913static void
914load_audit_module (const char *name, struct audit_ifaces **last_audit)
915{
916 int original_tls_idx = GL(dl_tls_max_dtv_idx);
917
918 struct dlmopen_args dlmargs;
919 dlmargs.fname = name;
920 dlmargs.map = NULL;
921
922 const char *objname;
923 const char *err_str = NULL;
924 bool malloced;
925 _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit, &dlmargs);
926 if (__glibc_unlikely (err_str != NULL))
927 {
928 report_audit_module_load_error (name, err_str, malloced);
929 return;
930 }
931
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))
937 {
938 unload_audit_module (dlmargs.map, original_tls_idx);
939 report_audit_module_load_error (name, err_str, malloced);
940 return;
941 }
942
943 unsigned int (*laversion) (unsigned int) = largs.result;
944
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);
949
950 unsigned int lav = laversion (LAV_CURRENT);
951 if (lav == 0)
952 {
953 /* Only print an error message if debugging because this can
954 happen deliberately. */
955 if (GLRO(dl_debug_mask) & DL_DEBUG_FILES)
956 _dl_debug_printf ("\
957file=%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);
960 return;
961 }
962
ce9a68c5 963 if (!_dl_audit_check_version (lav))
3b856d09
FW
964 {
965 _dl_debug_printf ("\
966ERROR: 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);
969 return;
970 }
971
972 enum { naudit_ifaces = 8 };
973 union
974 {
975 struct audit_ifaces ifaces;
976 void (*fptr[naudit_ifaces]) (void);
977 } *newp = malloc (sizeof (*newp));
978 if (newp == NULL)
979 _dl_fatal_printf ("Out of memory while loading audit modules\n");
980
981 /* Names of the auditing interfaces. All in one
982 long string. */
983 static const char audit_iface_names[] =
984 "la_activity\0"
985 "la_objsearch\0"
986 "la_objopen\0"
987 "la_preinit\0"
063f9ba2 988 LA_SYMBIND "\0"
3b856d09
FW
989#define STRING(s) __STRING (s)
990 "la_" STRING (ARCH_LA_PLTENTER) "\0"
991 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
992 "la_objclose\0";
993 unsigned int cnt = 0;
994 const char *cp = audit_iface_names;
995 do
996 {
997 largs.name = cp;
998 _dl_catch_error (&objname, &err_str, &malloced, lookup_doit, &largs);
999
1000 /* Store the pointer. */
1001 if (err_str == NULL && largs.result != NULL)
c7bf5cea 1002 newp->fptr[cnt] = largs.result;
3b856d09
FW
1003 else
1004 newp->fptr[cnt] = NULL;
1005 ++cnt;
1006
32c7acd4 1007 cp = strchr (cp, '\0') + 1;
3b856d09
FW
1008 }
1009 while (*cp != '\0');
1010 assert (cnt == naudit_ifaces);
1011
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;
1016 else
1017 *last_audit = (*last_audit)->next = &newp->ifaces;
c7bf5cea 1018
e1d559f3
FW
1019 /* The dynamic linker link map is statically allocated, so the
1020 cookie in _dl_new_object has not happened. */
ef5823d9
FW
1021 link_map_audit_state (&_dl_rtld_map, GLRO (dl_naudit))->cookie
1022 = (intptr_t) &_dl_rtld_map;
c7bf5cea 1023
3b856d09
FW
1024 ++GLRO(dl_naudit);
1025
1026 /* Mark the DSO as being used for auditing. */
1027 dlmargs.map->l_auditing = 1;
1028}
1029
3b856d09
FW
1030/* Load all audit modules. */
1031static void
4c6e0415 1032load_audit_modules (struct link_map *main_map, struct audit_list *audit_list)
3b856d09
FW
1033{
1034 struct audit_ifaces *last_audit = NULL;
3b856d09
FW
1035
1036 while (true)
1037 {
4c6e0415 1038 const char *name = audit_list_next (audit_list);
3b856d09
FW
1039 if (name == NULL)
1040 break;
1041 load_audit_module (name, &last_audit);
1042 }
1043
1044 /* Notify audit modules of the initially loaded modules (the main
1045 program and the dynamic linker itself). */
1046 if (GLRO(dl_naudit) > 0)
1047 {
aee6e90f 1048 _dl_audit_objopen (main_map, LM_ID_BASE);
ef5823d9 1049 _dl_audit_objopen (&_dl_rtld_map, LM_ID_BASE);
3b856d09
FW
1050 }
1051}
1052
630da022 1053/* Check if the executable is not actually dynamically linked, and
c1cb2dee
FW
1054 invoke it directly in that case. */
1055static void
1056rtld_chain_load (struct link_map *main_map, char *argv0)
1057{
1058 /* The dynamic loader run against itself. */
749310c6
FW
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)
c1cb2dee
FW
1062 _dl_fatal_printf ("%s: loader cannot load itself\n", rtld_soname);
1063
1064 /* With DT_NEEDED dependencies, the executable is dynamically
1065 linked. */
1066 if (__glibc_unlikely (main_map->l_info[DT_NEEDED] != NULL))
1067 return;
1068
1069 /* If the executable has program interpreter, it is dynamically
1070 linked. */
1071 for (size_t i = 0; i < main_map->l_phnum; ++i)
1072 if (main_map->l_phdr[i].p_type == PT_INTERP)
1073 return;
1074
1075 const char *pathname = _dl_argv[0];
1076 if (argv0 != NULL)
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);
1083 else
1084 _dl_fatal_printf("%s: cannot execute %s: %d\n",
f1eeef94 1085 rtld_soname, pathname, errcode);
c1cb2dee
FW
1086}
1087
b4d4ff89
FW
1088/* Called to complete the initialization of the link map for the main
1089 executable. Returns true if there is a PT_INTERP segment. */
1090static bool
1091rtld_setup_main_map (struct link_map *main_map)
1092{
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;
1097
1098 bool has_interp = false;
1099
1100 main_map->l_map_end = 0;
b4d4ff89
FW
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;
8eb2510d
FW
1105 main_map->l_contiguous = 1;
1106
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.
1113
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;
b4d4ff89
FW
1121
1122 /* Scan the program header table for the dynamic section. */
1123 for (const ElfW(Phdr) *ph = phdr; ph < &phdr[phnum]; ++ph)
1124 switch (ph->p_type)
1125 {
1126 case PT_PHDR:
1127 /* Find out the load address. */
1128 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1129 break;
1130 case PT_DYNAMIC:
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;
1135 break;
1136 case PT_INTERP:
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
1144 + ph->p_vaddr);
1145 /* _dl_rtld_libname.next = NULL; Already zero. */
ef5823d9 1146 _dl_rtld_map.l_libname = &_dl_rtld_libname;
b4d4ff89 1147
b4d4ff89
FW
1148 has_interp = true;
1149 break;
1150 case PT_LOAD:
1151 {
1152 ElfW(Addr) mapstart;
1153 ElfW(Addr) allocend;
1154
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;
1160
8eb2510d
FW
1161 if (main_map->l_contiguous && expected_load_address != 0
1162 && expected_load_address != mapstart)
1163 main_map->l_contiguous = 0;
1164
b4d4ff89
FW
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;
8eb2510d
FW
1169
1170 /* The next expected address is the page following this load
1171 segment. */
1172 expected_load_address = ((allocend + GLRO(dl_pagesize) - 1)
1173 & ~(GLRO(dl_pagesize) - 1));
b4d4ff89
FW
1174 }
1175 break;
1176
1177 case PT_TLS:
1178 if (ph->p_memsz > 0)
1179 {
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;
1188 else
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;
1193
1194 /* This image gets the ID one. */
1195 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1196 }
1197 break;
1198
1199 case PT_GNU_STACK:
1200 GL(dl_stack_flags) = ph->p_flags;
1201 break;
1202
1203 case PT_GNU_RELRO:
1204 main_map->l_relro_addr = ph->p_vaddr;
1205 main_map->l_relro_size = ph->p_memsz;
1206 break;
1207 }
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)
1212 {
1213 case PT_NOTE:
1214 _dl_process_pt_note (main_map, -1, &ph[-1]);
1215 break;
1216 case PT_GNU_PROPERTY:
1217 _dl_process_pt_gnu_property (main_map, -1, &ph[-1]);
1218 break;
1219 }
1220
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;
ef5823d9 1228 if (! _dl_rtld_map.l_libname && _dl_rtld_map.l_name)
b4d4ff89
FW
1229 {
1230 /* We were invoked directly, so the program might not have a
1231 PT_INTERP. */
ef5823d9 1232 _dl_rtld_libname.name = _dl_rtld_map.l_name;
b4d4ff89 1233 /* _dl_rtld_libname.next = NULL; Already zero. */
ef5823d9 1234 _dl_rtld_map.l_libname = &_dl_rtld_libname;
b4d4ff89
FW
1235 }
1236 else
ef5823d9 1237 assert (_dl_rtld_map.l_libname); /* How else did we get here? */
b4d4ff89
FW
1238
1239 return has_interp;
1240}
1241
ad43cac4
SN
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
1245 argv here. */
1246static void
59974938 1247_dl_start_args_adjust (int skip_args, int skip_env)
ad43cac4
SN
1248{
1249 void **sp = (void **) (_dl_argv - skip_args - 1);
1250 void **p = sp + skip_args;
1251
1252 if (skip_args == 0)
1253 return;
1254
1255 /* Sanity check. */
c1ada668 1256 intptr_t argc __attribute__ ((unused)) = (intptr_t) sp[0] - skip_args;
ad43cac4
SN
1257 assert (argc == _dl_argc);
1258
1259 /* Adjust argc on stack. */
1260 sp[0] = (void *) (intptr_t) _dl_argc;
1261
1262 /* Update globals in rtld. */
1263 _dl_argv -= skip_args;
1264 _environ -= skip_args;
1265
1266 /* Shuffle argv down. */
1267 do
1268 *++sp = *++p;
1269 while (*p != NULL);
1270
1271 assert (_environ == (char **) (sp + 1));
1272
1273 /* Shuffle envp down. */
1274 do
1275 *++sp = *++p;
1276 while (*p != NULL);
1277
1278#ifdef HAVE_AUX_VECTOR
59974938 1279 void **auxv = (void **) GLRO(dl_auxv) - skip_args - skip_env;
ad43cac4
SN
1280 GLRO(dl_auxv) = (ElfW(auxv_t) *) auxv; /* Aliasing violation. */
1281 assert (auxv == sp + 1);
1282
1283 /* Shuffle auxv down. */
1284 ElfW(auxv_t) ax;
d2f6ceac 1285 char *oldp = (char *) (p + 1 + skip_env);
ad43cac4
SN
1286 char *newp = (char *) (sp + 1);
1287 do
1288 {
1289 memcpy (&ax, oldp, sizeof (ax));
1290 memcpy (newp, &ax, sizeof (ax));
1291 oldp += sizeof (ax);
1292 newp += sizeof (ax);
1293 }
1294 while (ax.a_type != AT_NULL);
1295#endif
1296}
1297
d66e34cd 1298static void
266180eb 1299dl_main (const ElfW(Phdr) *phdr,
72f70279 1300 ElfW(Word) phnum,
3a56ea26
AK
1301 ElfW(Addr) *user_entry,
1302 ElfW(auxv_t) *auxv)
d66e34cd 1303{
c0f62c56 1304 struct link_map *main_map;
14bab8de
UD
1305 size_t file_size;
1306 char *file;
77aba05b 1307 unsigned int i;
164a7164 1308 bool rtld_is_main = false;
9dcafc55 1309 void *tcbp = NULL;
59974938 1310 int skip_env = 0;
d66e34cd 1311
2bf9e641
FW
1312 struct dl_main_state state;
1313 dl_main_state_init (&state);
4c6e0415 1314
d017b0ab 1315 __tls_pre_init_tp ();
334fcf2a 1316
ea278354 1317 /* Process the environment variable which control the behaviour. */
59974938 1318 skip_env = process_envvars (&state);
3996f34b 1319
ce6e047f 1320#ifndef HAVE_INLINED_SYSCALLS
46ec036d 1321 /* Set up a flag which tells we are just starting. */
9cf27b8d 1322 _dl_starting_up = 1;
ce6e047f 1323#endif
46ec036d 1324
e0f1a58f 1325 const char *ld_so_name = _dl_argv[0];
a16956f3 1326 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
0200214b
RM
1327 {
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:
1332
1333 ld.so PROGRAM ARGS...
1334
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
1342 installing it. */
164a7164 1343 rtld_is_main = true;
421f82e5 1344
c6702789 1345 char *argv0 = NULL;
ad43cac4 1346 char **orig_argv = _dl_argv;
c6702789 1347
ffee1316 1348 /* Note the place where the dynamic linker actually came from. */
ef5823d9 1349 _dl_rtld_map.l_name = rtld_progname;
6a76c115 1350
fd26970f 1351 while (_dl_argc > 1)
4243cbea 1352 if (! strcmp (_dl_argv[1], "--list"))
fd26970f 1353 {
e0f1a58f
FW
1354 if (state.mode != rtld_mode_help)
1355 {
1356 state.mode = rtld_mode_list;
1357 /* This means do no dependency analysis. */
1358 GLRO(dl_lazy) = -1;
1359 }
61965e9b 1360
fd26970f 1361 --_dl_argc;
4243cbea 1362 ++_dl_argv;
fd26970f 1363 }
4243cbea 1364 else if (! strcmp (_dl_argv[1], "--verify"))
fd26970f 1365 {
e0f1a58f
FW
1366 if (state.mode != rtld_mode_help)
1367 state.mode = rtld_mode_verify;
6a76c115 1368
73d65cc3 1369 --_dl_argc;
4243cbea 1370 ++_dl_argv;
73d65cc3 1371 }
4243cbea 1372 else if (! strcmp (_dl_argv[1], "--inhibit-cache"))
73d65cc3
SP
1373 {
1374 GLRO(dl_inhibit_cache) = 1;
fd26970f 1375 --_dl_argc;
4243cbea 1376 ++_dl_argv;
fd26970f 1377 }
4243cbea 1378 else if (! strcmp (_dl_argv[1], "--library-path")
e6caf4e1 1379 && _dl_argc > 2)
880f421f 1380 {
2bf9e641 1381 state.library_path = _dl_argv[2];
27316f4a 1382 state.library_path_source = "--library-path";
880f421f 1383
310930c1 1384 _dl_argc -= 2;
4243cbea 1385 _dl_argv += 2;
310930c1 1386 }
4243cbea 1387 else if (! strcmp (_dl_argv[1], "--inhibit-rpath")
e6caf4e1 1388 && _dl_argc > 2)
310930c1 1389 {
4243cbea 1390 GLRO(dl_inhibit_rpath) = _dl_argv[2];
310930c1 1391
74780cf6 1392 _dl_argc -= 2;
4243cbea 1393 _dl_argv += 2;
74780cf6 1394 }
4243cbea 1395 else if (! strcmp (_dl_argv[1], "--audit") && _dl_argc > 2)
74780cf6 1396 {
2bf9e641 1397 audit_list_add_string (&state.audit_list, _dl_argv[2]);
74780cf6 1398
8692ebdb
DN
1399 _dl_argc -= 2;
1400 _dl_argv += 2;
1401 }
1402 else if (! strcmp (_dl_argv[1], "--preload") && _dl_argc > 2)
1403 {
2bf9e641 1404 state.preloadarg = _dl_argv[2];
c6702789
VM
1405 _dl_argc -= 2;
1406 _dl_argv += 2;
1407 }
1408 else if (! strcmp (_dl_argv[1], "--argv0") && _dl_argc > 2)
1409 {
1410 argv0 = _dl_argv[2];
1411
dad90d52
FW
1412 _dl_argc -= 2;
1413 _dl_argv += 2;
1414 }
1415 else if (strcmp (_dl_argv[1], "--glibc-hwcaps-prepend") == 0
1416 && _dl_argc > 2)
1417 {
1418 state.glibc_hwcaps_prepend = _dl_argv[2];
dad90d52
FW
1419 _dl_argc -= 2;
1420 _dl_argv += 2;
1421 }
1422 else if (strcmp (_dl_argv[1], "--glibc-hwcaps-mask") == 0
1423 && _dl_argc > 2)
1424 {
1425 state.glibc_hwcaps_mask = _dl_argv[2];
880f421f 1426 _dl_argc -= 2;
4243cbea 1427 _dl_argv += 2;
880f421f 1428 }
86f65dff
L
1429 else if (! strcmp (_dl_argv[1], "--list-tunables"))
1430 {
1431 state.mode = rtld_mode_list_tunables;
1432
86f65dff
L
1433 --_dl_argc;
1434 ++_dl_argv;
1435 }
851f32cf
FW
1436 else if (! strcmp (_dl_argv[1], "--list-diagnostics"))
1437 {
1438 state.mode = rtld_mode_list_diagnostics;
1439
851f32cf
FW
1440 --_dl_argc;
1441 ++_dl_argv;
1442 }
e0f1a58f
FW
1443 else if (strcmp (_dl_argv[1], "--help") == 0)
1444 {
1445 state.mode = rtld_mode_help;
1446 --_dl_argc;
1447 ++_dl_argv;
1448 }
542923d9
FW
1449 else if (strcmp (_dl_argv[1], "--version") == 0)
1450 _dl_version ();
e0f1a58f
FW
1451 else if (_dl_argv[1][0] == '-' && _dl_argv[1][1] == '-')
1452 {
22271957
HL
1453 if (_dl_argv[1][2] == '\0')
1454 {
1455 /* End of option list. */
1456 --_dl_argc;
1457 ++_dl_argv;
1458 break;
1459 }
1460 else
1461 /* Unrecognized option. */
1462 _dl_usage (ld_so_name, _dl_argv[1]);
e0f1a58f 1463 }
fd26970f
UD
1464 else
1465 break;
d66e34cd 1466
86f65dff
L
1467 if (__glibc_unlikely (state.mode == rtld_mode_list_tunables))
1468 {
1469 __tunables_print ();
1470 _exit (0);
1471 }
86f65dff 1472
851f32cf
FW
1473 if (state.mode == rtld_mode_list_diagnostics)
1474 _dl_print_diagnostics (_environ);
1475
61eb22d3
UD
1476 /* If we have no further argument the program was called incorrectly.
1477 Grant the user some education. */
1478 if (_dl_argc < 2)
e0f1a58f
FW
1479 {
1480 if (state.mode == rtld_mode_help)
1481 /* --help without an executable is not an error. */
1482 _dl_help (ld_so_name, &state);
1483 else
1484 _dl_usage (ld_so_name, NULL);
1485 }
61eb22d3 1486
0200214b 1487 --_dl_argc;
4243cbea 1488 ++_dl_argv;
91f62ce6 1489
c70ba488
RM
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. */
1501
b4d4ff89 1502 for (const ElfW(Phdr) *ph = phdr; ph < &phdr[phnum]; ++ph)
c70ba488
RM
1503 if (ph->p_type == PT_GNU_STACK)
1504 {
1505 GL(dl_stack_flags) = ph->p_flags;
1506 break;
1507 }
1508
e0f1a58f
FW
1509 if (__glibc_unlikely (state.mode == rtld_mode_verify
1510 || state.mode == rtld_mode_help))
2de99474 1511 {
8e17ea58
UD
1512 const char *objname;
1513 const char *err_str = NULL;
993b3242 1514 struct map_args args;
74780cf6 1515 bool malloced;
2de99474 1516
e6caf4e1 1517 args.str = rtld_progname;
f04b9a68 1518 args.loader = NULL;
f04b9a68 1519 args.mode = __RTLD_OPENEXEC;
74780cf6
UD
1520 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
1521 &args);
a1ffb40e 1522 if (__glibc_unlikely (err_str != NULL))
e0f1a58f
FW
1523 {
1524 /* We don't free the returned string, the programs stops
1525 anyway. */
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);
1530 else
1531 _exit (EXIT_FAILURE);
1532 }
2de99474
UD
1533 }
1534 else
db276fa1 1535 {
1e372ded
AZ
1536 RTLD_TIMING_VAR (start);
1537 rtld_timer_start (&start);
798212a0 1538 _dl_map_object (NULL, rtld_progname, lt_executable, 0,
c0f62c56 1539 __RTLD_OPENEXEC, LM_ID_BASE);
1e372ded 1540 rtld_timer_stop (&load_time, start);
db276fa1 1541 }
2de99474 1542
c0f62c56
UD
1543 /* Now the map for the main executable is available. */
1544 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1545
c1cb2dee
FW
1546 if (__glibc_likely (state.mode == rtld_mode_normal))
1547 rtld_chain_load (main_map, argv0);
01f16ab0 1548
c0f62c56
UD
1549 phdr = main_map->l_phdr;
1550 phnum = main_map->l_phnum;
143e2b96
UD
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. */
c0f62c56
UD
1555 main_map->l_name = (char *) "";
1556 *user_entry = main_map->l_entry;
3a56ea26 1557
15a0c573
CLT
1558 /* Set bit indicating this is the main program map. */
1559 main_map->l_main_map = 1;
1560
bc58236c 1561#ifdef HAVE_AUX_VECTOR
3a56ea26
AK
1562 /* Adjust the on-stack auxiliary vector so that it looks like the
1563 binary was executed directly. */
bc58236c 1564 for (ElfW(auxv_t) *av = auxv; av->a_type != AT_NULL; av++)
3a56ea26
AK
1565 switch (av->a_type)
1566 {
1567 case AT_PHDR:
4dd019e3 1568 av->a_un.a_val = (uintptr_t) phdr;
3a56ea26
AK
1569 break;
1570 case AT_PHNUM:
1571 av->a_un.a_val = phnum;
1572 break;
1573 case AT_ENTRY:
1574 av->a_un.a_val = *user_entry;
1575 break;
5c349950
PP
1576 case AT_EXECFN:
1577 av->a_un.a_val = (uintptr_t) _dl_argv[0];
1578 break;
3a56ea26 1579 }
bc58236c 1580#endif
c6702789
VM
1581
1582 /* Set the argv[0] string now that we've processed the executable. */
1583 if (argv0 != NULL)
1584 _dl_argv[0] = argv0;
ad43cac4
SN
1585
1586 /* Adjust arguments for the application entry point. */
59974938 1587 _dl_start_args_adjust (_dl_argv - orig_argv, skip_env);
0200214b
RM
1588 }
1589 else
1590 {
1591 /* Create a link_map for the executable itself.
1592 This will be what dlopen on "" returns. */
9fbdeb41
UD
1593 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1594 __RTLD_OPENEXEC, LM_ID_BASE);
9dcafc55 1595 assert (main_map != NULL);
c0f62c56
UD
1596 main_map->l_phdr = phdr;
1597 main_map->l_phnum = phnum;
1598 main_map->l_entry = *user_entry;
da832465 1599
f0967738
AK
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);
fa41c84d 1603 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
f0967738 1604
61e0617a
UD
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.
1609
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. */
1619
97a51d8a
UD
1620 /* We delay initializing the path structure until we got the dynamic
1621 information for the program. */
0200214b
RM
1622 }
1623
b4d4ff89 1624 bool has_interp = rtld_setup_main_map (main_map);
0200214b 1625
12a497c7
AZ
1626 /* Handle this after PT_GNU_STACK parse, because it updates dl_stack_flags
1627 if required. */
1628 _dl_handle_execstack_tunable ();
58272284 1629
9dcafc55
UD
1630 /* If the current libname is different from the SONAME, add the
1631 latter as well. */
749310c6
FW
1632 {
1633 const char *soname = l_soname (&_dl_rtld_map);
1634 if (soname != NULL
1635 && strcmp (_dl_rtld_map.l_libname->name, soname) != 0)
1636 {
1637 static struct libname_list newname;
1638 newname.name = soname;
1639 newname.next = NULL;
1640 newname.dont_free = 1;
1641
1642 assert (_dl_rtld_map.l_libname->next == NULL);
1643 _dl_rtld_map.l_libname->next = &newname;
1644 }
1645 }
9dcafc55
UD
1646 /* The ld.so must be relocated since otherwise loading audit modules
1647 will fail since they reuse the very same ld.so. */
ef5823d9 1648 assert (_dl_rtld_map.l_relocated);
9dcafc55 1649
9a51759b
UD
1650 if (! rtld_is_main)
1651 {
1652 /* Extract the contents of the dynamic section for easy access. */
5118dcac 1653 elf_get_dynamic_info (main_map, false, false);
4d098554 1654
89baed0b
FW
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. */
749310c6
FW
1658 if (l_soname (main_map) != NULL
1659 && strcmp (l_soname (main_map), LIBC_SO) == 0)
89baed0b
FW
1660 GL(dl_ns)[LM_ID_BASE].libc_map = main_map;
1661
efec5079 1662 /* Set up our cache of pointers into the hash table. */
c0f62c56 1663 _dl_setup_hash (main_map);
9a51759b 1664 }
0200214b 1665
2bf9e641 1666 if (__glibc_unlikely (state.mode == rtld_mode_verify))
e2102c14
UD
1667 {
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. */
c0f62c56 1672 if (main_map->l_ld == NULL)
e2102c14 1673 _exit (1);
e2102c14 1674
eb406346 1675 _exit (has_interp ? 0 : 2);
e2102c14
UD
1676 }
1677
ef5823d9 1678 struct link_map **first_preload = &_dl_rtld_map.l_next;
ab1d521d
RM
1679 /* Set up the data structures for the system-supplied DSO early,
1680 so they can influence _dl_init_paths. */
9cee5585 1681 setup_vdso (main_map, &first_preload);
ab1d521d 1682
1bdda52f
AZ
1683 /* With vDSO setup we can initialize the function pointers. */
1684 setup_vdso_pointers ();
1685
ab1d521d
RM
1686 /* Initialize the data structures for the search paths for shared
1687 objects. */
2bf9e641 1688 call_init_paths (&state);
97a51d8a 1689
a93d9e03 1690 /* Initialize _r_debug_extended. */
ef5823d9 1691 struct r_debug *r = _dl_debug_initialize (_dl_rtld_map.l_addr,
29f97654 1692 LM_ID_BASE);
9dcafc55
UD
1693 r->r_state = RT_CONSISTENT;
1694
0200214b 1695 /* Put the link_map for ourselves on the chain so it can be found by
ceb2d9aa 1696 name. Note that at this point the global chain of link maps contains
d6b5d570 1697 exactly one element, which is pointed to by dl_loaded. */
ef5823d9 1698 if (! _dl_rtld_map.l_name)
ffee1316
RM
1699 /* If not invoked directly, the dynamic linker shared object file was
1700 found by the PT_INTERP name. */
ef5823d9
FW
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;
c0f62c56 1705 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
e8ed861d 1706 ++GL(dl_load_adds);
0200214b 1707
44c4e5d5
RM
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. */
302247c8
FS
1713
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;
44c4e5d5
RM
1717 assert (rtld_ehdr->e_ehsize == sizeof *rtld_ehdr);
1718 assert (rtld_ehdr->e_phentsize == sizeof (ElfW(Phdr)));
1719
1720 const ElfW(Phdr) *rtld_phdr = (const void *) rtld_ehdr + rtld_ehdr->e_phoff;
1721
ef5823d9
FW
1722 _dl_rtld_map.l_phdr = rtld_phdr;
1723 _dl_rtld_map.l_phnum = rtld_ehdr->e_phnum;
553eca26 1724
9dcafc55 1725
e8ed861d
UD
1726 /* PT_GNU_RELRO is usually the last phdr. */
1727 size_t cnt = rtld_ehdr->e_phnum;
1728 while (cnt-- > 0)
1729 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1730 {
ef5823d9
FW
1731 _dl_rtld_map.l_relro_addr = rtld_phdr[cnt].p_vaddr;
1732 _dl_rtld_map.l_relro_size = rtld_phdr[cnt].p_memsz;
e8ed861d
UD
1733 break;
1734 }
1735
9dcafc55 1736 /* Add the dynamic linker to the TLS list if it also uses TLS. */
ef5823d9 1737 if (_dl_rtld_map.l_tls_blocksize != 0)
9dcafc55 1738 /* Assign a module ID. Do this before loading any audit modules. */
ef5823d9 1739 _dl_assign_tls_modid (&_dl_rtld_map);
9dcafc55 1740
2bf9e641
FW
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);
8f7a75d7 1743
e0f1a58f
FW
1744 /* At this point, all data has been obtained that is included in the
1745 --help output. */
1746 if (__glibc_unlikely (state.mode == rtld_mode_help))
1747 _dl_help (ld_so_name, &state);
1748
9dcafc55 1749 /* If we have auditing DSOs to load, do it now. */
81b82fb9 1750 bool need_security_init = true;
2bf9e641 1751 if (state.audit_list.length > 0)
9dcafc55 1752 {
2bf9e641 1753 size_t naudit = audit_list_count (&state.audit_list);
17796419 1754
3abee0b7
UD
1755 /* Since we start using the auditing DSOs right away we need to
1756 initialize the data structures now. */
17796419 1757 tcbp = init_tls (naudit);
3abee0b7 1758
4c48ef06
UD
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
1762 fail later on. */
1763 security_init ();
81b82fb9 1764 need_security_init = false;
4c48ef06 1765
2bf9e641 1766 load_audit_modules (main_map, &state.audit_list);
17796419
SN
1767
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);
9dcafc55
UD
1771 }
1772
d0503676
CD
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 ();
1776
c63d8f80 1777 /* Set up debugging before the debugger is notified for the first time. */
9288c92d 1778 elf_setup_debug_entry (main_map, r);
c63d8f80 1779
9dcafc55
UD
1780 /* We start adding objects. */
1781 r->r_state = RT_ADD;
1782 _dl_debug_state ();
815e6fa3 1783 LIBC_PROBE (init_start, 2, LM_ID_BASE, r);
9dcafc55
UD
1784
1785 /* Auditing checkpoint: we are ready to signal that the initial map
1786 is being constructed. */
3dac3959 1787 _dl_audit_activity_map (main_map, LA_ACT_ADD);
9dcafc55 1788
14bab8de 1789 /* We have two ways to specify objects to preload: via environment
49c091e5 1790 variable and via the file /etc/ld.so.preload. The latter can also
14bab8de 1791 be used when security is enabled. */
ab1d521d 1792 assert (*first_preload == NULL);
20fe49b9
UD
1793 struct link_map **preloads = NULL;
1794 unsigned int npreloads = 0;
14bab8de 1795
2bf9e641 1796 if (__glibc_unlikely (state.preloadlist != NULL))
c4029823 1797 {
1e372ded
AZ
1798 RTLD_TIMING_VAR (start);
1799 rtld_timer_start (&start);
2bf9e641
FW
1800 npreloads += handle_preload_list (state.preloadlist, main_map,
1801 "LD_PRELOAD");
1e372ded 1802 rtld_timer_accum (&load_time, start);
8692ebdb
DN
1803 }
1804
2bf9e641 1805 if (__glibc_unlikely (state.preloadarg != NULL))
8692ebdb 1806 {
1e372ded
AZ
1807 RTLD_TIMING_VAR (start);
1808 rtld_timer_start (&start);
2bf9e641
FW
1809 npreloads += handle_preload_list (state.preloadarg, main_map,
1810 "--preload");
1e372ded 1811 rtld_timer_accum (&load_time, start);
c4029823
UD
1812 }
1813
761490a1
UD
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
1819 use. */
1820 static const char preload_file[] = "/etc/ld.so.preload";
a1ffb40e 1821 if (__glibc_unlikely (__access (preload_file, R_OK) == 0))
14bab8de 1822 {
761490a1
UD
1823 /* Read the contents of the file. */
1824 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1825 PROT_READ | PROT_WRITE);
a1ffb40e 1826 if (__glibc_unlikely (file != MAP_FAILED))
14bab8de 1827 {
761490a1
UD
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 `#'. */
1831 char *problem;
1832 char *runp;
1833 size_t rest;
1834
1835 /* Eliminate comments. */
e2102c14 1836 runp = file;
761490a1
UD
1837 rest = file_size;
1838 while (rest > 0)
1839 {
1840 char *comment = memchr (runp, '#', rest);
1841 if (comment == NULL)
1842 break;
1843
1844 rest -= comment - runp;
1845 do
1846 *comment = ' ';
1847 while (--rest > 0 && *++comment != '\n');
1848 }
1849
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] != ':')
1855 {
1856 problem = &file[file_size];
1857 while (problem > file && problem[-1] != ' '
1858 && problem[-1] != '\t'
1859 && problem[-1] != '\n' && problem[-1] != ':')
1860 --problem;
1861
1862 if (problem > file)
1863 problem[-1] = '\0';
1864 }
1865 else
1866 {
1867 problem = NULL;
1868 file[file_size - 1] = '\0';
1869 }
f04b9a68 1870
1e372ded
AZ
1871 RTLD_TIMING_VAR (start);
1872 rtld_timer_start (&start);
f04b9a68 1873
761490a1
UD
1874 if (file != problem)
1875 {
1876 char *p;
1877 runp = file;
1878 while ((p = strsep (&runp, ": \t\n")) != NULL)
1879 if (p[0] != '\0')
20fe49b9 1880 npreloads += do_preload (p, main_map, preload_file);
761490a1
UD
1881 }
1882
1883 if (problem != NULL)
1884 {
1885 char *p = strndupa (problem, file_size - (problem - file));
20fe49b9
UD
1886
1887 npreloads += do_preload (p, main_map, preload_file);
761490a1 1888 }
14bab8de 1889
1e372ded 1890 rtld_timer_accum (&load_time, start);
db276fa1 1891
761490a1
UD
1892 /* We don't need the file anymore. */
1893 __munmap (file, file_size);
1894 }
14bab8de
UD
1895 }
1896
a1ffb40e 1897 if (__glibc_unlikely (*first_preload != NULL))
14bab8de
UD
1898 {
1899 /* Set up PRELOADS with a vector of the preloaded libraries. */
ab1d521d 1900 struct link_map *l = *first_preload;
14bab8de 1901 preloads = __alloca (npreloads * sizeof preloads[0]);
14bab8de
UD
1902 i = 0;
1903 do
1904 {
1905 preloads[i++] = l;
1906 l = l->l_next;
1907 } while (l);
1908 assert (i == npreloads);
1909 }
1910
f0e23d34
AZ
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);
1915#endif
1916
2064087b
RM
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. */
1e372ded
AZ
1920 {
1921 RTLD_TIMING_VAR (start);
1922 rtld_timer_start (&start);
2bf9e641
FW
1923 _dl_map_object_deps (main_map, preloads, npreloads,
1924 state.mode == rtld_mode_trace, 0);
1e372ded
AZ
1925 rtld_timer_accum (&load_time, start);
1926 }
e3e35cfc 1927
20fe49b9 1928 /* Mark all objects as being in the global scope. */
c0f62c56 1929 for (i = main_map->l_searchlist.r_nlist; i > 0; )
20fe49b9 1930 main_map->l_searchlist.r_list[--i]->l_global = 1;
d66e34cd 1931
f9496a7b 1932 /* Remove _dl_rtld_map from the chain. */
ef5823d9
FW
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;
f9496a7b 1936
20fe49b9 1937 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
2b1dba3e 1938 if (is_rtld_link_map (main_map->l_searchlist.r_list[i]))
20fe49b9
UD
1939 break;
1940
8f8dd904
FW
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. */
20fe49b9 1944
ef5823d9 1945 _dl_rtld_map.l_prev = main_map->l_searchlist.r_list[i - 1];
8f8dd904
FW
1946 if (__glibc_likely (state.mode == rtld_mode_normal))
1947 {
ef5823d9 1948 _dl_rtld_map.l_next = (i + 1 < main_map->l_searchlist.r_nlist
8f8dd904
FW
1949 ? main_map->l_searchlist.r_list[i + 1]
1950 : NULL);
7775448e 1951#ifdef NEED_DL_SYSINFO_DSO
8f8dd904 1952 if (GLRO(dl_sysinfo_map) != NULL
ef5823d9
FW
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);
3b3ddb4f 1956#endif
8f8dd904
FW
1957 }
1958 else
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. */
ef5823d9 1964 _dl_rtld_map.l_next = _dl_rtld_map.l_prev->l_next;
8f8dd904 1965
ef5823d9
FW
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)
8f8dd904 1969 {
ef5823d9
FW
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;
0200214b 1972 }
d66e34cd 1973
c84142e8
UD
1974 /* Now let us see whether all libraries are available in the
1975 versions we need. */
1976 {
993b3242 1977 struct version_check_args args;
2bf9e641
FW
1978 args.doexit = state.mode == rtld_mode_normal;
1979 args.dotrace = state.mode == rtld_mode_trace;
993b3242 1980 _dl_receive_error (print_missing_version, version_check_doit, &args);
c84142e8
UD
1981 }
1982
2d148689
RM
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). */
a65ff76c 1990 bool was_tls_init_tp_called = __rtld_tls_init_tp_called;
35f1e827 1991 if (tcbp == NULL)
17796419 1992 tcbp = init_tls (0);
0ecb606c 1993
81b82fb9 1994 if (__glibc_likely (need_security_init))
4c48ef06
UD
1995 /* Initialize security features. But only if we have not done it
1996 earlier. */
1997 security_init ();
827b7087 1998
2bf9e641 1999 if (__glibc_unlikely (state.mode != rtld_mode_normal))
0200214b
RM
2000 {
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. */
81f3ac4c
UD
2005 struct link_map *l;
2006
6628c742 2007 if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
7a11603d
UD
2008 {
2009 /* Look through the dependencies of the main executable
2010 and determine which of them is not actually
2011 required. */
c0f62c56 2012 struct link_map *l = main_map;
7a11603d
UD
2013
2014 /* Relocate the main executable. */
2ca285b0 2015 struct relocate_args args = { .l = l,
3a62d00d
AS
2016 .reloc_mode = ((GLRO(dl_lazy)
2017 ? RTLD_LAZY : 0)
2018 | __RTLD_NOIFUNC) };
7a11603d
UD
2019 _dl_receive_error (print_unresolved, relocate_doit, &args);
2020
2021 /* This loop depends on the dependencies of the executable to
2022 correspond in number and order to the DT_NEEDED entries. */
c0f62c56 2023 ElfW(Dyn) *dyn = main_map->l_ld;
7a11603d
UD
2024 bool first = true;
2025 while (dyn->d_tag != DT_NULL)
2026 {
2027 if (dyn->d_tag == DT_NEEDED)
2028 {
2029 l = l->l_next;
7775448e 2030#ifdef NEED_DL_SYSINFO_DSO
ff9f1c5f
DM
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))
2034 l = l->l_next;
2035#endif
7a11603d
UD
2036 if (!l->l_used)
2037 {
2038 if (first)
2039 {
2040 _dl_printf ("Unused direct dependencies:\n");
2041 first = false;
2042 }
2043
2044 _dl_printf ("\t%s\n", l->l_name);
2045 }
2046 }
2047
2048 ++dyn;
2049 }
2050
2051 _exit (first != true);
2052 }
c0f62c56 2053 else if (! main_map->l_info[DT_NEEDED])
81f3ac4c
UD
2054 _dl_printf ("\tstatically linked\n");
2055 else
2056 {
d7703d31
AZ
2057 for (l = state.mode_trace_program ? main_map : main_map->l_next;
2058 l; l = l->l_next) {
81f3ac4c
UD
2059 if (l->l_faked)
2060 /* The library was not found. */
d7703d31 2061 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1e903124
AZ
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. */
de477abc 2065 _dl_printf ("\t%s (0x%0*zx)\n", l->l_libname->name,
1e903124
AZ
2066 (int) sizeof l->l_map_start * 2,
2067 (size_t) l->l_map_start);
81f3ac4c 2068 else
de477abc 2069 _dl_printf ("\t%s => %s (0x%0*zx)\n",
d7703d31
AZ
2070 DSO_FILENAME (l->l_libname->name),
2071 DSO_FILENAME (l->l_name),
2072 (int) sizeof l->l_map_start * 2,
d347a4ab 2073 (size_t) l->l_map_start);
d7703d31 2074 }
81f3ac4c 2075 }
1a3a58fd 2076
2bf9e641 2077 if (__glibc_unlikely (state.mode != rtld_mode_trace))
5a47e7f2 2078 for (i = 1; i < (unsigned int) _dl_argc; ++i)
cddcfecf
RM
2079 {
2080 const ElfW(Sym) *ref = NULL;
c0282c06
UD
2081 ElfW(Addr) loadbase;
2082 lookup_t result;
c0282c06 2083
4243cbea 2084 result = _dl_lookup_symbol_x (_dl_argv[i], main_map,
11bf311e
UD
2085 &ref, main_map->l_scope,
2086 NULL, ELF_RTYPE_CLASS_PLT,
021723ab 2087 DL_LOOKUP_ADD_DEPENDENCY, NULL);
c0282c06 2088
10a446dd 2089 loadbase = LOOKUP_VALUE_ADDRESS (result, false);
c0282c06 2090
de477abc 2091 _dl_printf ("%s found at 0x%0*zd in object at 0x%0*zd\n",
4243cbea 2092 _dl_argv[i],
d347a4ab
UD
2093 (int) sizeof ref->st_value * 2,
2094 (size_t) ref->st_value,
2095 (int) sizeof loadbase * 2, (size_t) loadbase);
cddcfecf 2096 }
ce37fa88 2097 else
fd26970f 2098 {
20fe49b9 2099 /* If LD_WARN is set, warn about undefined symbols. */
afdca0f2 2100 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
ce37fa88
UD
2101 {
2102 /* We have to do symbol dependency testing. */
2103 struct relocate_args args;
48b67d71 2104 unsigned int i;
993b3242 2105
3a62d00d
AS
2106 args.reloc_mode = ((GLRO(dl_lazy) ? RTLD_LAZY : 0)
2107 | __RTLD_NOIFUNC);
fd26970f 2108
48b67d71
AS
2109 i = main_map->l_searchlist.r_nlist;
2110 while (i-- > 0)
ce37fa88 2111 {
48b67d71 2112 struct link_map *l = main_map->l_initfini[i];
ef5823d9 2113 if (l != &_dl_rtld_map && ! l->l_faked)
ce37fa88
UD
2114 {
2115 args.l = l;
2116 _dl_receive_error (print_unresolved, relocate_doit,
2117 &args);
ce37fa88 2118 }
20fe49b9 2119 }
32e6df36 2120
3a56ea26 2121 }
b0982c4a 2122#define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
2bf9e641 2123 if (state.version_info)
fd26970f 2124 {
ce37fa88
UD
2125 /* Print more information. This means here, print information
2126 about the versions needed. */
2127 int first = 1;
c0f62c56 2128 struct link_map *map;
ce37fa88 2129
c0f62c56 2130 for (map = main_map; map != NULL; map = map->l_next)
fd26970f 2131 {
f41c8091 2132 const char *strtab;
ce37fa88 2133 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
f41c8091
UD
2134 ElfW(Verneed) *ent;
2135
2136 if (dyn == NULL)
2137 continue;
2138
a42195db 2139 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
f41c8091 2140 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
ce37fa88 2141
f41c8091 2142 if (first)
ce37fa88 2143 {
35fc382a 2144 _dl_printf ("\n\tVersion information:\n");
f41c8091
UD
2145 first = 0;
2146 }
ce37fa88 2147
b9375348 2148 _dl_printf ("\t%s:\n", DSO_FILENAME (map->l_name));
f41c8091
UD
2149
2150 while (1)
2151 {
2152 ElfW(Vernaux) *aux;
2153 struct link_map *needed;
ce37fa88 2154
f41c8091
UD
2155 needed = find_needed (strtab + ent->vn_file);
2156 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
ce37fa88
UD
2157
2158 while (1)
2159 {
f41c8091
UD
2160 const char *fname = NULL;
2161
f41c8091 2162 if (needed != NULL
ba9fcb3f
UD
2163 && match_version (strtab + aux->vna_name,
2164 needed))
f41c8091
UD
2165 fname = needed->l_name;
2166
35fc382a
UD
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
2171 ? "[WEAK] " : "",
2172 fname ?: "not found");
ce37fa88 2173
f41c8091
UD
2174 if (aux->vna_next == 0)
2175 /* No more symbols. */
ce37fa88
UD
2176 break;
2177
f41c8091
UD
2178 /* Next symbol. */
2179 aux = (ElfW(Vernaux) *) ((char *) aux
2180 + aux->vna_next);
ce37fa88 2181 }
f41c8091
UD
2182
2183 if (ent->vn_next == 0)
2184 /* No more dependencies. */
2185 break;
2186
2187 /* Next dependency. */
2188 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
ce37fa88 2189 }
fd26970f 2190 }
ce37fa88 2191 }
fd26970f 2192 }
d66e34cd 2193
0200214b
RM
2194 _exit (0);
2195 }
86d2c878 2196
c31e278f 2197 /* Now set up the variable which helps the assembler startup code. */
c0f62c56 2198 GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
c31e278f
UD
2199
2200 /* Save the information about the original global scope list since
2201 we need it in the memory handling later. */
c0f62c56 2202 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
c31e278f 2203
e23fe25b 2204 /* Remember the last search directory added at startup, now that
8e1472d2
FW
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. */
e23fe25b
AS
2208 GLRO(dl_init_all_dirs) = GL(dl_all_dirs);
2209
73d7af4f 2210 /* Print scope information. */
a1ffb40e 2211 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_SCOPES))
73d7af4f
UD
2212 {
2213 _dl_debug_printf ("\nInitial object scopes\n");
2214
2215 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
174baab3 2216 _dl_show_scope (l, 0);
73d7af4f
UD
2217 }
2218
f753fa7d
L
2219 _rtld_main_check (main_map, _dl_argv[0]);
2220
70620986 2221 /* Now we have all the objects loaded. */
32e6df36 2222
6628c742 2223 int consider_profiling = GLRO(dl_profile) != NULL;
1e372ded 2224
b3bee76c
FW
2225 /* If we are profiling we also must do lazy reloaction. */
2226 GLRO(dl_lazy) |= consider_profiling;
2227
70620986
FW
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. */
78ca44da 2231 if (GL(dl_ns)[LM_ID_BASE].libc_map != NULL)
70620986
FW
2232 {
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);
2239 }
78ca44da 2240
6628c742
AZ
2241 RTLD_TIMING_VAR (start);
2242 rtld_timer_start (&start);
2243 {
2244 unsigned i = main_map->l_searchlist.r_nlist;
2245 while (i-- > 0)
2246 {
2247 struct link_map *l = main_map->l_initfini[i];
c0fb8a56 2248
6628c742
AZ
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;
2bc17433 2253
6628c742
AZ
2254 while (__builtin_expect (lnp != NULL, 0))
2255 {
2256 lnp->dont_free = 1;
2257 lnp = lnp->next;
2258 }
2259 /* Also allocated with the fake malloc(). */
2260 l->l_free_initfini = 0;
752a2a50 2261
70620986
FW
2262 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy) ? RTLD_LAZY : 0,
2263 consider_profiling);
752a2a50 2264
6628c742 2265 /* Add object to slot information data if necessasy. */
a65ff76c 2266 if (l->l_tls_blocksize != 0 && __rtld_tls_init_tp_called)
6628c742
AZ
2267 _dl_add_to_slotinfo (l, true);
2268 }
2269 }
2270 rtld_timer_stop (&relocate_time, start);
be935610 2271
7f784ffc
FW
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 ();
2275
6628c742
AZ
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 ();
ac16e905 2283
d0503676
CD
2284 if ((!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2285 || count_modids != _dl_count_modids ())
35f1e827 2286 ++GL(dl_tls_generation);
9dcafc55 2287
35f1e827
UD
2288 /* Now that we have completed relocation, the initializer data
2289 for the TLS blocks has its final values and we can copy them
91ac3a7d
TMQMF
2290 into the main thread's TLS area, which we allocated above.
2291 Note: thread-local variables must only be accessed after completing
2292 the next step. */
fe06fb31 2293 _dl_allocate_tls_init (tcbp, true);
a334319f 2294
3d8c8bff 2295 /* And finally install it for the main thread. */
a65ff76c 2296 if (! __rtld_tls_init_tp_called)
1f34a232 2297 call_tls_init_tp (tcbp);
0ecb606c 2298
e23fe25b
AS
2299 /* Make sure no new search directories have been added. */
2300 assert (GLRO(dl_init_all_dirs) == GL(dl_all_dirs));
bc5fb037 2301
8f8dd904
FW
2302 /* Set up the object lookup structures. */
2303 _dl_find_object_init ();
5d28a896 2304
70620986
FW
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)
2309 {
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);
c1560f3f 2314
70620986
FW
2315 __rtld_mutex_init ();
2316 __rtld_malloc_init_real (main_map);
2317 }
1e372ded 2318
70620986
FW
2319 /* All ld.so initialization is complete. Apply RELRO. */
2320 _dl_protect_relro (&_dl_rtld_map);
cafdfdb6 2321
03e187a4
FW
2322 /* Relocation is complete. Perform early libc initialization. This
2323 is the initial libc, even if audit modules have been loaded with
2324 other libcs. */
89baed0b 2325 _dl_call_libc_early_init (GL(dl_ns)[LM_ID_BASE].libc_map, true);
ec935dea 2326
bf8523c8
RM
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 ();
2333
9dcafc55
UD
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. */
a93d9e03 2336 r = _dl_debug_update (LM_ID_BASE);
9dcafc55 2337 r->r_state = RT_CONSISTENT;
154d10bd 2338 _dl_debug_state ();
815e6fa3 2339 LIBC_PROBE (init_complete, 2, LM_ID_BASE, r);
0200214b 2340
e096b7a1
FW
2341 /* Auditing checkpoint: we have added all objects. */
2342 _dl_audit_activity_nsid (LM_ID_BASE, LA_ACT_CONSISTENT);
2343
f57f8055 2344#if defined USE_LDCONFIG && !defined MAP_COPY
08cac4ac 2345 /* We must munmap() the cache file. */
154d10bd 2346 _dl_unload_cache ();
08cac4ac
UD
2347#endif
2348
d66e34cd
RM
2349 /* Once we return, _dl_sysdep_start will invoke
2350 the DT_INIT functions and then *USER_ENTRY. */
2351}
fd26970f
UD
2352\f
2353/* This is a little helper function for resolving symbols while
2354 tracing the binary. */
2355static void
c84142e8
UD
2356print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2357 const char *errstring)
fd26970f 2358{
3996f34b 2359 if (objname[0] == '\0')
b9375348 2360 objname = RTLD_PROGNAME;
35fc382a 2361 _dl_error_printf ("%s (%s)\n", errstring, objname);
fd26970f 2362}
c84142e8
UD
2363\f
2364/* This is a little helper function for resolving symbols while
2365 tracing the binary. */
2366static void
2367print_missing_version (int errcode __attribute__ ((unused)),
2368 const char *objname, const char *errstring)
2369{
b9375348 2370 _dl_error_printf ("%s: %s: %s\n", RTLD_PROGNAME,
35fc382a 2371 objname, errstring);
c84142e8 2372}
ea278354 2373\f
b5efde2f
UD
2374/* Process the string given as the parameter which explains which debugging
2375 options are enabled. */
2376static void
2bf9e641 2377process_dl_debug (struct dl_main_state *state, const char *dl_debug)
b5efde2f 2378{
3e2040c8
UD
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. */
2381 static const struct
2382 {
379d4ec4
UD
2383 unsigned char len;
2384 const char name[10];
3e2040c8
UD
2385 const char helptext[41];
2386 unsigned short int mask;
2387 } debopts[] =
2388 {
379d4ec4
UD
2389#define LEN_AND_STR(str) sizeof (str) - 1, str
2390 { LEN_AND_STR ("libs"), "display library search paths",
3e2040c8 2391 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
379d4ec4 2392 { LEN_AND_STR ("reloc"), "display relocation processing",
3e2040c8 2393 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
379d4ec4 2394 { LEN_AND_STR ("files"), "display progress for input file",
3e2040c8 2395 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
379d4ec4 2396 { LEN_AND_STR ("symbols"), "display symbol table processing",
3e2040c8 2397 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
379d4ec4 2398 { LEN_AND_STR ("bindings"), "display information about symbol binding",
3e2040c8 2399 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
379d4ec4 2400 { LEN_AND_STR ("versions"), "display version dependencies",
3e2040c8 2401 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
73d7af4f
UD
2402 { LEN_AND_STR ("scopes"), "display scope information",
2403 DL_DEBUG_SCOPES },
379d4ec4 2404 { LEN_AND_STR ("all"), "all previous options combined",
3e2040c8 2405 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
73d7af4f
UD
2406 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS
2407 | DL_DEBUG_SCOPES },
379d4ec4 2408 { LEN_AND_STR ("statistics"), "display relocation statistics",
3e2040c8 2409 DL_DEBUG_STATISTICS },
7a11603d
UD
2410 { LEN_AND_STR ("unused"), "determined unused DSOs",
2411 DL_DEBUG_UNUSED },
379d4ec4 2412 { LEN_AND_STR ("help"), "display this help message and exit",
3e2040c8
UD
2413 DL_DEBUG_HELP },
2414 };
2415#define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
3e2040c8 2416
379d4ec4
UD
2417 /* Skip separating white spaces and commas. */
2418 while (*dl_debug != '\0')
b5efde2f 2419 {
379d4ec4 2420 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
b5efde2f 2421 {
3e2040c8 2422 size_t cnt;
379d4ec4 2423 size_t len = 1;
77aba05b 2424
379d4ec4
UD
2425 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2426 && dl_debug[len] != ',' && dl_debug[len] != ':')
2427 ++len;
14c44e2e 2428
3e2040c8 2429 for (cnt = 0; cnt < ndebopts; ++cnt)
379d4ec4
UD
2430 if (debopts[cnt].len == len
2431 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
3e2040c8 2432 {
afdca0f2 2433 GLRO(dl_debug_mask) |= debopts[cnt].mask;
3e2040c8
UD
2434 break;
2435 }
77aba05b 2436
3e2040c8
UD
2437 if (cnt == ndebopts)
2438 {
2439 /* Display a warning and skip everything until next
2440 separator. */
2441 char *copy = strndupa (dl_debug, len);
2442 _dl_error_printf ("\
2443warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
379d4ec4
UD
2444 }
2445
2446 dl_debug += len;
2447 continue;
3e2040c8 2448 }
379d4ec4
UD
2449
2450 ++dl_debug;
3e2040c8 2451 }
77aba05b 2452
ff9f1c5f
DM
2453 if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
2454 {
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. */
2458 GLRO(dl_lazy) = 0;
2459 }
2460
afdca0f2 2461 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
3e2040c8
UD
2462 {
2463 size_t cnt;
14c44e2e 2464
3e2040c8
UD
2465 _dl_printf ("\
2466Valid options for the LD_DEBUG environment variable are:\n\n");
db276fa1 2467
3e2040c8 2468 for (cnt = 0; cnt < ndebopts; ++cnt)
37d8b778
UD
2469 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2470 " " + debopts[cnt].len - 3,
3e2040c8 2471 debopts[cnt].helptext);
14c44e2e 2472
3e2040c8
UD
2473 _dl_printf ("\n\
2474To direct the debugging output into a file instead of standard output\n\
2475a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2476 _exit (0);
b5efde2f 2477 }
b5efde2f
UD
2478}
2479\f
59974938 2480static int
43690195
AZ
2481process_envvars_secure (struct dl_main_state *state)
2482{
2483 char **runp = _environ;
2484 char *envline;
59974938 2485 int skip_env = 0;
43690195
AZ
2486
2487 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2488 {
2489 size_t len = 0;
2490
2491 while (envline[len] != '\0' && envline[len] != '=')
2492 ++len;
2493
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. */
2498 continue;
2499
2500 switch (len)
2501 {
2502 case 5:
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]);
2509 break;
2510
2511 case 7:
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
2515 bit enabled. */
2516 if (memcmp (envline, "PRELOAD", 7) == 0)
2517 state->preloadlist = &envline[8];
2518 break;
2519 }
2520 }
2521
2522 /* Extra security for SUID binaries. Remove all dangerous environment
2523 variables. */
2524 const char *nextp = UNSECURE_ENVVARS;
2525 do
2526 {
59974938
JST
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)
2533 skip_env++;
2534
43690195
AZ
2535 unsetenv (nextp);
2536 nextp = strchr (nextp, '\0') + 1;
2537 }
2538 while (*nextp != '\0');
2539
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)
2546 _exit (5);
59974938
JST
2547
2548 return skip_env;
43690195
AZ
2549}
2550
2551static void
2552process_envvars_default (struct dl_main_state *state)
ea278354 2553{
67c94753 2554 char **runp = _environ;
ea278354 2555 char *envline;
7dea968e 2556 char *debug_output = NULL;
ea278354 2557
ea278354
UD
2558 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2559 {
379d4ec4
UD
2560 size_t len = 0;
2561
2562 while (envline[len] != '\0' && envline[len] != '=')
2563 ++len;
ea278354 2564
75e8d1f5
UD
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. */
67c94753 2569 continue;
75e8d1f5 2570
67c94753 2571 switch (len)
ea278354 2572 {
14c44e2e
UD
2573 case 4:
2574 /* Warning level, verbose or not. */
43690195 2575 if (memcmp (envline, "WARN", 4) == 0)
afdca0f2 2576 GLRO(dl_verbose) = envline[5] != '\0';
14c44e2e 2577 break;
ea278354 2578
14c44e2e
UD
2579 case 5:
2580 /* Debugging of the dynamic linker? */
43690195 2581 if (memcmp (envline, "DEBUG", 5) == 0)
9dcafc55 2582 {
2bf9e641 2583 process_dl_debug (state, &envline[6]);
9dcafc55
UD
2584 break;
2585 }
780c3392
AZ
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. */
9dcafc55 2590 if (memcmp (envline, "AUDIT", 5) == 0)
2bf9e641 2591 audit_list_add_string (&state->audit_list, &envline[6]);
14c44e2e 2592 break;
b5efde2f 2593
14c44e2e
UD
2594 case 7:
2595 /* Print information about versions. */
43690195 2596 if (memcmp (envline, "VERBOSE", 7) == 0)
14c44e2e 2597 {
2bf9e641 2598 state->version_info = envline[8] != '\0';
14c44e2e
UD
2599 break;
2600 }
7dea968e 2601
780c3392
AZ
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
2605 bit enabled. */
67c94753 2606 if (memcmp (envline, "PRELOAD", 7) == 0)
14c44e2e 2607 {
2bf9e641 2608 state->preloadlist = &envline[8];
14c44e2e
UD
2609 break;
2610 }
120b4c49 2611
14c44e2e 2612 /* Which shared object shall be profiled. */
43690195 2613 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
afdca0f2 2614 GLRO(dl_profile) = &envline[8];
14c44e2e 2615 break;
120b4c49 2616
14c44e2e
UD
2617 case 8:
2618 /* Do we bind early? */
43690195 2619 if (memcmp (envline, "BIND_NOW", 8) == 0)
f53c03c2 2620 {
afdca0f2 2621 GLRO(dl_lazy) = envline[9] == '\0';
f53c03c2
UD
2622 break;
2623 }
43690195 2624 if (memcmp (envline, "BIND_NOT", 8) == 0)
afdca0f2 2625 GLRO(dl_bind_not) = envline[9] != '\0';
14c44e2e 2626 break;
ea278354 2627
14c44e2e
UD
2628 case 9:
2629 /* Test whether we want to see the content of the auxiliary
2630 array passed up from the kernel. */
43690195 2631 if (memcmp (envline, "SHOW_AUXV", 9) == 0)
14c44e2e
UD
2632 _dl_show_auxv ();
2633 break;
ea278354 2634
f787edde
UD
2635 case 11:
2636 /* Path where the binary is found. */
43690195 2637 if (memcmp (envline, "ORIGIN_PATH", 11) == 0)
afdca0f2 2638 GLRO(dl_origin_path) = &envline[12];
f787edde
UD
2639 break;
2640
14c44e2e 2641 case 12:
dec126b4 2642 /* The library search path. */
43690195 2643 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
dec126b4 2644 {
2bf9e641 2645 state->library_path = &envline[13];
27316f4a 2646 state->library_path_source = "LD_LIBRARY_PATH";
dec126b4
UD
2647 break;
2648 }
2649
14c44e2e 2650 /* Where to place the profiling data file. */
43690195 2651 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
14c44e2e 2652 {
67c94753 2653 debug_output = &envline[13];
14c44e2e
UD
2654 break;
2655 }
ea278354 2656
43690195 2657 if (memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
afdca0f2 2658 GLRO(dl_dynamic_weak) = 1;
14c44e2e 2659 break;
ea278354 2660
14c44e2e
UD
2661 case 14:
2662 /* Where to place the profiling data file. */
43690195 2663 if (memcmp (envline, "PROFILE_OUTPUT", 14) == 0
3e2040c8 2664 && envline[15] != '\0')
afdca0f2 2665 GLRO(dl_profile_output) = &envline[15];
14c44e2e 2666 break;
120b4c49 2667
14c44e2e
UD
2668 case 20:
2669 /* The mode of the dynamic linker can be set. */
43690195 2670 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
d7703d31
AZ
2671 {
2672 state->mode = rtld_mode_trace;
2673 state->mode_trace_program
2674 = _dl_strtoul (&envline[21], NULL) > 1;
2675 }
14c44e2e 2676 break;
ea278354
UD
2677 }
2678 }
2679
7dea968e
UD
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. */
43690195 2683 if (GLRO(dl_debug_mask) != 0 && debug_output != NULL)
7dea968e 2684 {
5f2de337 2685 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
7a2fd787
UD
2686 size_t name_len = strlen (debug_output);
2687 char buf[name_len + 12];
2688 char *startp;
2689
2690 buf[name_len + 11] = '\0';
9710f75d 2691 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
7a2fd787
UD
2692 *--startp = '.';
2693 startp = memcpy (startp - name_len, debug_output, name_len);
2694
329ea513 2695 GLRO(dl_debug_fd) = __open64_nocancel (startp, flags, DEFFILEMODE);
dd70526e 2696 if (GLRO(dl_debug_fd) == -1)
7dea968e 2697 /* We use standard output if opening the file failed. */
dd70526e 2698 GLRO(dl_debug_fd) = STDOUT_FILENO;
7dea968e 2699 }
ea278354 2700}
db276fa1 2701
59974938 2702static int
43690195
AZ
2703process_envvars (struct dl_main_state *state)
2704{
59974938 2705 int skip_env = 0;
43690195 2706 if (__glibc_unlikely (__libc_enable_secure))
59974938 2707 skip_env += process_envvars_secure (state);
43690195
AZ
2708 else
2709 process_envvars_default (state);
59974938
JST
2710
2711 return skip_env;
43690195
AZ
2712}
2713
1e372ded
AZ
2714#if HP_TIMING_INLINE
2715static void
2716print_statistics_item (const char *title, hp_timing_t time,
2717 hp_timing_t total)
2718{
2719 char cycles[HP_TIMING_PRINT_SIZE];
2720 HP_TIMING_PRINT (cycles, sizeof (cycles), time);
2721
2722 char relative[3 * sizeof (hp_timing_t) + 2];
2723 char *cp = _itoa ((1000ULL * time) / total, relative + sizeof (relative),
2724 10, 0);
2725 /* Sets the decimal point. */
2726 char *wp = relative;
2727 switch (relative + sizeof (relative) - cp)
2728 {
2729 case 3:
2730 *wp++ = *cp++;
2731 /* Fall through. */
2732 case 2:
2733 *wp++ = *cp++;
2734 /* Fall through. */
2735 case 1:
2736 *wp++ = '.';
2737 *wp++ = *cp++;
2738 }
2739 *wp = '\0';
2740 _dl_debug_printf ("%s: %s cycles (%s%%)\n", title, cycles, relative);
2741}
2742#endif
db276fa1
UD
2743
2744/* Print the various times we collected. */
2745static void
ee600e3f 2746__attribute ((noinline))
1e372ded 2747print_statistics (const hp_timing_t *rtld_total_timep)
db276fa1 2748{
1e372ded
AZ
2749#if HP_TIMING_INLINE
2750 {
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",
2755 cycles);
2756 print_statistics_item (" time needed for relocation",
2757 relocate_time, *rtld_total_timep);
2758 }
1531e094 2759#endif
a21a20a3
UD
2760
2761 unsigned long int num_relative_relocations = 0;
22c83193 2762 for (Lmid_t ns = 0; ns < GL(dl_nns); ++ns)
a21a20a3 2763 {
c120d94d
UD
2764 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2765 continue;
2766
c0f62c56 2767 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
a21a20a3 2768
c0f62c56
UD
2769 for (unsigned int i = 0; i < scope->r_nlist; i++)
2770 {
2771 struct link_map *l = scope->r_list [i];
2772
c120d94d 2773 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
c0f62c56
UD
2774 num_relative_relocations
2775 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
c120d94d 2776#ifndef ELF_MACHINE_REL_RELATIVE
9c72830e
AS
2777 /* Relative relocations are always processed on these
2778 architectures. */
2779 if (l->l_info[VERSYMIDX (DT_RELACOUNT)])
c120d94d
UD
2780#else
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)])
2784#endif
c0f62c56
UD
2785 num_relative_relocations
2786 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2787 }
a21a20a3
UD
2788 }
2789
42af49f8
UD
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),
154d10bd 2795 num_relative_relocations);
db276fa1 2796
1e372ded
AZ
2797#if HP_TIMING_INLINE
2798 print_statistics_item (" time needed to load objects",
2799 load_time, *rtld_total_timep);
1531e094 2800#endif
db276fa1 2801}