]> git.ipfire.org Git - thirdparty/glibc.git/blame - elf/rtld.c
Use __attribute_pure__ macro in bits/mathcalls.h
[thirdparty/glibc.git] / elf / rtld.c
CommitLineData
d66e34cd 1/* Run time dynamic linker.
04277e02 2 Copyright (C) 1995-2019 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
PE
16 License along with the GNU C Library; if not, see
17 <http://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>
f5348425 35#include "dynamic-link.h"
8f480b4b 36#include <dl-librecon.h>
74955460 37#include <unsecvars.h>
5688da55 38#include <dl-cache.h>
2f4db0df 39#include <dl-osinfo.h>
5688da55 40#include <dl-procinfo.h>
f753fa7d 41#include <dl-prop.h>
5f5843e3 42#include <tls.h>
815e6fa3 43#include <stap-probe.h>
30950a5f 44#include <stackinfo.h>
329ea513 45#include <not-cancel.h>
f5348425 46
a853022c 47#include <assert.h>
f5348425 48
1e372ded
AZ
49/* Only enables rtld profiling for architectures which provides non generic
50 hp-timing support. The generic support requires either syscall
51 (clock_gettime), which will incur in extra overhead on loading time.
52 Using vDSO is also an option, but it will require extra support on loader
53 to setup the vDSO pointer before its usage. */
54#if HP_TIMING_INLINE
55# define RLTD_TIMING_DECLARE(var, classifier,...) \
56 classifier hp_timing_t var __VA_ARGS__
57# define RTLD_TIMING_VAR(var) RLTD_TIMING_DECLARE (var, )
58# define RTLD_TIMING_SET(var, value) (var) = (value)
59# define RTLD_TIMING_REF(var) &(var)
60
61static inline void
62rtld_timer_start (hp_timing_t *var)
63{
64 HP_TIMING_NOW (*var);
65}
66
67static inline void
68rtld_timer_stop (hp_timing_t *var, hp_timing_t start)
69{
70 hp_timing_t stop;
71 HP_TIMING_NOW (stop);
72 HP_TIMING_DIFF (*var, start, stop);
73}
74
75static inline void
76rtld_timer_accum (hp_timing_t *sum, hp_timing_t start)
77{
78 hp_timing_t stop;
79 rtld_timer_stop (&stop, start);
80 HP_TIMING_ACCUM_NT(*sum, stop);
81}
82#else
83# define RLTD_TIMING_DECLARE(var, classifier...)
84# define RTLD_TIMING_SET(var, value)
85# define RTLD_TIMING_VAR(var)
86# define RTLD_TIMING_REF(var) 0
87# define rtld_timer_start(var)
88# define rtld_timer_stop(var, start)
89# define rtld_timer_accum(sum, start)
90#endif
91
6ce3881d
RM
92/* Avoid PLT use for our local calls at startup. */
93extern __typeof (__mempcpy) __mempcpy attribute_hidden;
94
95/* GCC has mental blocks about _exit. */
96extern __typeof (_exit) exit_internal asm ("_exit") attribute_hidden;
97#define _exit exit_internal
98
fd26970f 99/* Helper function to handle errors while resolving symbols. */
c84142e8
UD
100static void print_unresolved (int errcode, const char *objname,
101 const char *errsting);
102
103/* Helper function to handle errors when a version is missing. */
104static void print_missing_version (int errcode, const char *objname,
105 const char *errsting);
fd26970f 106
db276fa1 107/* Print the various times we collected. */
1e372ded 108static void print_statistics (const hp_timing_t *total_timep);
ea278354 109
74780cf6
UD
110/* Add audit objects. */
111static void process_dl_audit (char *str);
112
ea278354
UD
113/* This is a list of all the modes the dynamic loader can be in. */
114enum mode { normal, list, verify, trace };
115
116/* Process all environments variables the dynamic linker must recognize.
117 Since all of them start with `LD_' we are a bit smarter while finding
118 all the entries. */
ba9fcb3f 119static void process_envvars (enum mode *modep);
ea278354 120
11986c68 121#ifdef DL_ARGV_NOT_RELRO
22aa06a5 122int _dl_argc attribute_hidden;
11986c68 123char **_dl_argv = NULL;
22aa06a5
RM
124/* Nonzero if we were run directly. */
125unsigned int _dl_skip_args attribute_hidden;
11986c68 126#else
22aa06a5 127int _dl_argc attribute_relro attribute_hidden;
697afbe1 128char **_dl_argv attribute_relro = NULL;
22aa06a5 129unsigned int _dl_skip_args attribute_relro attribute_hidden;
11986c68 130#endif
4243cbea 131rtld_hidden_data_def (_dl_argv)
5c82e15e 132
35f1e827
UD
133#ifndef THREAD_SET_STACK_GUARD
134/* Only exported for architectures that don't store the stack guard canary
135 in thread local area. */
136uintptr_t __stack_chk_guard attribute_relro;
137#endif
138
827b7087
UD
139/* Only exported for architectures that don't store the pointer guard
140 value in thread local area. */
141uintptr_t __pointer_chk_guard_local
142 attribute_relro attribute_hidden __attribute__ ((nocommon));
143#ifndef THREAD_SET_POINTER_GUARD
144strong_alias (__pointer_chk_guard_local, __pointer_chk_guard)
145#endif
146
6d0ba622
FW
147/* Length limits for names and paths, to protect the dynamic linker,
148 particularly when __libc_enable_secure is active. */
149#ifdef NAME_MAX
150# define SECURE_NAME_LIMIT NAME_MAX
151#else
152# define SECURE_NAME_LIMIT 255
153#endif
154#ifdef PATH_MAX
155# define SECURE_PATH_LIMIT PATH_MAX
156#else
157# define SECURE_PATH_LIMIT 1024
158#endif
159
160/* Check that AT_SECURE=0, or that the passed name does not contain
161 directories and is not overly long. Reject empty names
162 unconditionally. */
163static bool
164dso_name_valid_for_suid (const char *p)
165{
166 if (__glibc_unlikely (__libc_enable_secure))
167 {
168 /* Ignore pathnames with directories for AT_SECURE=1
169 programs, and also skip overlong names. */
170 size_t len = strlen (p);
171 if (len >= SECURE_NAME_LIMIT || memchr (p, '/', len) != NULL)
172 return false;
173 }
174 return *p != '\0';
175}
827b7087 176
81b82fb9
FW
177/* LD_AUDIT variable contents. Must be processed before the
178 audit_list below. */
179const char *audit_list_string;
180
181/* Cyclic list of auditing DSOs. audit_list->next is the first
182 element. */
9dcafc55
UD
183static struct audit_list
184{
185 const char *name;
186 struct audit_list *next;
187} *audit_list;
188
81b82fb9
FW
189/* Iterator for audit_list_string followed by audit_list. */
190struct audit_list_iter
191{
192 /* Tail of audit_list_string still needing processing, or NULL. */
193 const char *audit_list_tail;
194
195 /* The list element returned in the previous iteration. NULL before
196 the first element. */
197 struct audit_list *previous;
198
199 /* Scratch buffer for returning a name which is part of
200 audit_list_string. */
201 char fname[SECURE_NAME_LIMIT];
202};
203
204/* Initialize an audit list iterator. */
205static void
206audit_list_iter_init (struct audit_list_iter *iter)
207{
208 iter->audit_list_tail = audit_list_string;
209 iter->previous = NULL;
210}
211
212/* Iterate through both audit_list_string and audit_list. */
213static const char *
214audit_list_iter_next (struct audit_list_iter *iter)
215{
216 if (iter->audit_list_tail != NULL)
217 {
218 /* First iterate over audit_list_string. */
219 while (*iter->audit_list_tail != '\0')
220 {
221 /* Split audit list at colon. */
222 size_t len = strcspn (iter->audit_list_tail, ":");
223 if (len > 0 && len < sizeof (iter->fname))
224 {
225 memcpy (iter->fname, iter->audit_list_tail, len);
226 iter->fname[len] = '\0';
227 }
228 else
229 /* Do not return this name to the caller. */
230 iter->fname[0] = '\0';
231
232 /* Skip over the substring and the following delimiter. */
233 iter->audit_list_tail += len;
234 if (*iter->audit_list_tail == ':')
235 ++iter->audit_list_tail;
236
237 /* If the name is valid, return it. */
238 if (dso_name_valid_for_suid (iter->fname))
239 return iter->fname;
240 /* Otherwise, wrap around and try the next name. */
241 }
242 /* Fall through to the procesing of audit_list. */
243 }
244
245 if (iter->previous == NULL)
246 {
247 if (audit_list == NULL)
248 /* No pre-parsed audit list. */
249 return NULL;
250 /* Start of audit list. The first list element is at
251 audit_list->next (cyclic list). */
252 iter->previous = audit_list->next;
253 return iter->previous->name;
254 }
255 if (iter->previous == audit_list)
256 /* Cyclic list wrap-around. */
257 return NULL;
258 iter->previous = iter->previous->next;
259 return iter->previous->name;
260}
261
ce6e047f 262#ifndef HAVE_INLINED_SYSCALLS
39778c6c
UD
263/* Set nonzero during loading and initialization of executable and
264 libraries, cleared before the executable's entry point runs. This
265 must not be initialized to nonzero, because the unused dynamic
266 linker loaded in for libc.so's "ld.so.1" dep will provide the
267 definition seen by libc.so's initializer; that value must be zero,
268 and will be since that dynamic linker's _dl_start and dl_main will
269 never be called. */
e6caf4e1 270int _dl_starting_up = 0;
9cf27b8d 271rtld_hidden_def (_dl_starting_up)
ce6e047f 272#endif
39778c6c 273
d6b5d570
UD
274/* This is the structure which defines all variables global to ld.so
275 (except those which cannot be added for some reason). */
5688da55
UD
276struct rtld_global _rtld_global =
277 {
30950a5f
RA
278 /* Generally the default presumption without further information is an
279 * executable stack but this is not true for all platforms. */
280 ._dl_stack_flags = DEFAULT_STACK_PERMS,
ffa8d2a0 281#ifdef _LIBC_REENTRANT
22c83193 282 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
5a2a1d75 283 ._dl_load_write_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
ffa8d2a0 284#endif
415ac3df
UD
285 ._dl_nns = 1,
286 ._dl_ns =
287 {
bea9b193 288#ifdef _LIBC_REENTRANT
415ac3df
UD
289 [LM_ID_BASE] = { ._ns_unique_sym_table
290 = { .lock = _RTLD_LOCK_RECURSIVE_INITIALIZER } }
bea9b193 291#endif
415ac3df 292 }
5688da55 293 };
27a754a9
UD
294/* If we would use strong_alias here the compiler would see a
295 non-hidden definition. This would undo the effect of the previous
296 declaration. So spell out was strong_alias does plus add the
297 visibility attribute. */
298extern struct rtld_global _rtld_local
299 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
c0fb8a56 300
afdca0f2
UD
301
302/* This variable is similar to _rtld_local, but all values are
303 read-only after relocation. */
304struct rtld_global_ro _rtld_global_ro attribute_relro =
305 {
c31e278f
UD
306 /* Get architecture specific initializer. */
307#include <dl-procinfo.c>
afdca0f2
UD
308#ifdef NEED_DL_SYSINFO
309 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
310#endif
dd70526e 311 ._dl_debug_fd = STDERR_FILENO,
afdca0f2
UD
312 ._dl_use_load_bias = -2,
313 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
ff08fc59 314#if !HAVE_TUNABLES
afdca0f2 315 ._dl_hwcap_mask = HWCAP_IMPORTANT,
ff08fc59 316#endif
afdca0f2
UD
317 ._dl_lazy = 1,
318 ._dl_fpu_control = _FPU_DEFAULT,
02d46fc4 319 ._dl_pagesize = EXEC_PAGESIZE,
73d65cc3 320 ._dl_inhibit_cache = 0,
154d10bd
UD
321
322 /* Function pointers. */
154d10bd 323 ._dl_debug_printf = _dl_debug_printf,
ab97ee8f 324 ._dl_mcount = _dl_mcount,
021723ab 325 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
9dcafc55 326 ._dl_open = _dl_open,
93025f93 327 ._dl_close = _dl_close,
7c22c7ec
UD
328 ._dl_tls_get_addr_soft = _dl_tls_get_addr_soft,
329#ifdef HAVE_DL_DISCOVER_OSVERSION
330 ._dl_discover_osversion = _dl_discover_osversion
331#endif
afdca0f2
UD
332 };
333/* If we would use strong_alias here the compiler would see a
334 non-hidden definition. This would undo the effect of the previous
335 declaration. So spell out was strong_alias does plus add the
336 visibility attribute. */
337extern struct rtld_global_ro _rtld_local_ro
338 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
339
340
67ddea92 341static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
3a56ea26 342 ElfW(Addr) *user_entry, ElfW(auxv_t) *auxv);
d66e34cd 343
392a6b52 344/* These two variables cannot be moved into .data.rel.ro. */
d6b5d570
UD
345static struct libname_list _dl_rtld_libname;
346static struct libname_list _dl_rtld_libname2;
86d2c878 347
db276fa1 348/* Variable for statistics. */
1e372ded
AZ
349RLTD_TIMING_DECLARE (relocate_time, static);
350RLTD_TIMING_DECLARE (load_time, static, attribute_relro);
351RLTD_TIMING_DECLARE (start_time, static, attribute_relro);
db276fa1 352
2a76f7ef
UD
353/* Additional definitions needed by TLS initialization. */
354#ifdef TLS_INIT_HELPER
355TLS_INIT_HELPER
5e289179
UD
356#endif
357
358/* Helper function for syscall implementation. */
359#ifdef DL_SYSINFO_IMPLEMENTATION
360DL_SYSINFO_IMPLEMENTATION
2a76f7ef
UD
361#endif
362
01d8e36d
UD
363/* Before ld.so is relocated we must not access variables which need
364 relocations. This means variables which are exported. Variables
365 declared as static are fine. If we can mark a variable hidden this
27a754a9 366 is fine, too. The latter is important here. We can avoid setting
01d8e36d
UD
367 up a temporary link map for ld.so if we can mark _rtld_global as
368 hidden. */
11bf311e 369#ifdef PI_STATIC_AND_HIDDEN
01d8e36d
UD
370# define DONT_USE_BOOTSTRAP_MAP 1
371#endif
372
373#ifdef DONT_USE_BOOTSTRAP_MAP
374static ElfW(Addr) _dl_start_final (void *arg);
375#else
4874b009
RM
376struct dl_start_final_info
377{
378 struct link_map l;
1e372ded 379 RTLD_TIMING_VAR (start_time);
4874b009 380};
01d8e36d 381static ElfW(Addr) _dl_start_final (void *arg,
4874b009 382 struct dl_start_final_info *info);
01d8e36d 383#endif
6a1db4ff 384
65da9563
RM
385/* These defined magically in the linker script. */
386extern char _begin[] attribute_hidden;
eec8b6ca 387extern char _etext[] attribute_hidden;
65da9563
RM
388extern char _end[] attribute_hidden;
389
390
b1dbbaa4
RM
391#ifdef RTLD_START
392RTLD_START
393#else
eaad82e0 394# error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
b1dbbaa4
RM
395#endif
396
c2248c44
RM
397/* This is the second half of _dl_start (below). It can be inlined safely
398 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
399 references. When the tools don't permit us to avoid using a GOT entry
400 for _dl_rtld_global (no attribute_hidden support), we must make sure
401 this function is not inlined (see below). */
402
403#ifdef DONT_USE_BOOTSTRAP_MAP
404static inline ElfW(Addr) __attribute__ ((always_inline))
405_dl_start_final (void *arg)
406#else
407static ElfW(Addr) __attribute__ ((noinline))
4874b009 408_dl_start_final (void *arg, struct dl_start_final_info *info)
c2248c44
RM
409#endif
410{
411 ElfW(Addr) start_addr;
c2248c44 412
1e372ded
AZ
413 /* If it hasn't happen yet record the startup time. */
414 rtld_timer_start (&start_time);
415#if !defined DONT_USE_BOOTSTRAP_MAP
416 RTLD_TIMING_SET (start_time, info->start_time);
4874b009 417#endif
c2248c44
RM
418
419 /* Transfer data about ourselves to the permanent link_map structure. */
420#ifndef DONT_USE_BOOTSTRAP_MAP
4874b009
RM
421 GL(dl_rtld_map).l_addr = info->l.l_addr;
422 GL(dl_rtld_map).l_ld = info->l.l_ld;
423 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
c2248c44 424 sizeof GL(dl_rtld_map).l_info);
4874b009 425 GL(dl_rtld_map).l_mach = info->l.l_mach;
82221992 426 GL(dl_rtld_map).l_relocated = 1;
c2248c44
RM
427#endif
428 _dl_setup_hash (&GL(dl_rtld_map));
c0f62c56 429 GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
c2248c44
RM
430 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
431 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
eec8b6ca 432 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
c2248c44 433 /* Copy the TLS related data if necessary. */
11bf311e 434#ifndef DONT_USE_BOOTSTRAP_MAP
3d8c8bff 435# if NO_TLS_OFFSET != 0
299601a1 436 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
c2248c44 437# endif
c2248c44
RM
438#endif
439
ea4f25a7
UD
440 /* Initialize the stack end variable. */
441 __libc_stack_end = __builtin_frame_address (0);
442
c2248c44
RM
443 /* Call the OS-dependent function to set up life so we can do things like
444 file access. It will call `dl_main' (below) to do all the real work
445 of the dynamic linker, and then unwind our frame and run the user
446 entry point on the same stack we entered on. */
ecdeaac0 447 start_addr = _dl_sysdep_start (arg, &dl_main);
c2248c44 448
a1ffb40e 449 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS))
39b04aa3 450 {
1e372ded
AZ
451 RTLD_TIMING_VAR (rtld_total_time);
452 rtld_timer_stop (&rtld_total_time, start_time);
453 print_statistics (RTLD_TIMING_REF(rtld_total_time));
39b04aa3 454 }
c2248c44
RM
455
456 return start_addr;
457}
458
630bf491 459static ElfW(Addr) __attribute_used__
d66e34cd
RM
460_dl_start (void *arg)
461{
01d8e36d
UD
462#ifdef DONT_USE_BOOTSTRAP_MAP
463# define bootstrap_map GL(dl_rtld_map)
464#else
4874b009
RM
465 struct dl_start_final_info info;
466# define bootstrap_map info.l
739d440d 467#endif
d66e34cd 468
b1dbbaa4 469 /* This #define produces dynamic linking inline functions for
2f978feb
UD
470 bootstrap relocation instead of general-purpose relocation.
471 Since ld.so must not have any undefined symbols the result
472 is trivial: always the map of ld.so itself. */
b1dbbaa4 473#define RTLD_BOOTSTRAP
b8818ab5
L
474#define BOOTSTRAP_MAP (&bootstrap_map)
475#define RESOLVE_MAP(sym, version, flags) BOOTSTRAP_MAP
b1dbbaa4
RM
476#include "dynamic-link.h"
477
4874b009 478#ifdef DONT_USE_BOOTSTRAP_MAP
1e372ded 479 rtld_timer_start (&start_time);
4874b009 480#else
1e372ded 481 rtld_timer_start (&info.start_time);
4874b009 482#endif
db276fa1 483
e66d0a4c
UD
484 /* Partly clean the `bootstrap_map' structure up. Don't use
485 `memset' since it might not be built in or inlined and we cannot
486 make function calls at this point. Use '__builtin_memset' if we
01d8e36d
UD
487 know it is available. We do not have to clear the memory if we
488 do not have to use the temporary bootstrap_map. Global variables
489 are initialized to zero by default. */
490#ifndef DONT_USE_BOOTSTRAP_MAP
491# ifdef HAVE_BUILTIN_MEMSET
e66d0a4c 492 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
01d8e36d 493# else
ce460d04 494 for (size_t cnt = 0;
264ec183
UD
495 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
496 ++cnt)
497 bootstrap_map.l_info[cnt] = 0;
01d8e36d 498# endif
e66d0a4c 499#endif
264ec183 500
d66e34cd 501 /* Figure out the run-time load address of the dynamic linker itself. */
86d2c878 502 bootstrap_map.l_addr = elf_machine_load_address ();
d66e34cd 503
47707456
UD
504 /* Read our own dynamic section and fill in the info array. */
505 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
479aa8ec 506 elf_get_dynamic_info (&bootstrap_map, NULL);
d66e34cd 507
11bf311e 508#if NO_TLS_OFFSET != 0
299601a1
UD
509 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
510#endif
511
d66e34cd 512#ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
86d2c878 513 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
d66e34cd
RM
514#endif
515
32e6df36
UD
516 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
517 {
518 /* Relocate ourselves so we can do normal function calls and
519 data access using the global offset table. */
520
3a62d00d 521 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0, 0);
32e6df36 522 }
f85f3563 523 bootstrap_map.l_relocated = 1;
421f82e5 524
ea7eb7e3
UD
525 /* Please note that we don't allow profiling of this object and
526 therefore need not test whether we have to allocate the array
527 for the relocation results (as done in dl-reloc.c). */
421f82e5 528
d66e34cd
RM
529 /* Now life is sane; we can call functions and access global data.
530 Set up to use the operating system facilities, and find out from
531 the operating system's program loader where to find the program
6a1db4ff
UD
532 header table in core. Put the rest of _dl_start into a separate
533 function, that way the compiler cannot put accesses to the GOT
534 before ELF_DYNAMIC_RELOCATE. */
c0282c06 535 {
01d8e36d
UD
536#ifdef DONT_USE_BOOTSTRAP_MAP
537 ElfW(Addr) entry = _dl_start_final (arg);
538#else
4874b009 539 ElfW(Addr) entry = _dl_start_final (arg, &info);
01d8e36d 540#endif
c0282c06
UD
541
542#ifndef ELF_MACHINE_START_ADDRESS
543# define ELF_MACHINE_START_ADDRESS(map, start) (start)
544#endif
545
7cb92a99 546 return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, entry);
c0282c06 547 }
6a1db4ff
UD
548}
549
550
d66e34cd 551
d66e34cd
RM
552/* Now life is peachy; we can do all normal operations.
553 On to the real work. */
554
993b3242
UD
555/* Some helper functions. */
556
557/* Arguments to relocate_doit. */
558struct relocate_args
559{
560 struct link_map *l;
2ca285b0 561 int reloc_mode;
993b3242
UD
562};
563
564struct map_args
565{
566 /* Argument to map_doit. */
acf869f4 567 const char *str;
f04b9a68 568 struct link_map *loader;
f04b9a68 569 int mode;
993b3242 570 /* Return value of map_doit. */
f04b9a68 571 struct link_map *map;
993b3242
UD
572};
573
9dcafc55
UD
574struct dlmopen_args
575{
576 const char *fname;
577 struct link_map *map;
578};
579
580struct lookup_args
581{
582 const char *name;
583 struct link_map *map;
584 void *result;
585};
586
993b3242
UD
587/* Arguments to version_check_doit. */
588struct version_check_args
589{
993b3242 590 int doexit;
145b8413 591 int dotrace;
993b3242
UD
592};
593
594static void
595relocate_doit (void *a)
596{
597 struct relocate_args *args = (struct relocate_args *) a;
598
2ca285b0 599 _dl_relocate_object (args->l, args->l->l_scope, args->reloc_mode, 0);
993b3242
UD
600}
601
602static void
603map_doit (void *a)
604{
be935610 605 struct map_args *args = (struct map_args *) a;
798212a0
PP
606 int type = (args->mode == __RTLD_OPENEXEC) ? lt_executable : lt_library;
607 args->map = _dl_map_object (args->loader, args->str, type, 0,
8e9f92e9 608 args->mode, LM_ID_BASE);
993b3242
UD
609}
610
9dcafc55
UD
611static void
612dlmopen_doit (void *a)
613{
614 struct dlmopen_args *args = (struct dlmopen_args *) a;
8e9f92e9
AS
615 args->map = _dl_open (args->fname,
616 (RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT
617 | __RTLD_SECURE),
4243cbea 618 dl_main, LM_ID_NEWLM, _dl_argc, _dl_argv,
9dcafc55
UD
619 __environ);
620}
621
622static void
623lookup_doit (void *a)
624{
625 struct lookup_args *args = (struct lookup_args *) a;
626 const ElfW(Sym) *ref = NULL;
627 args->result = NULL;
628 lookup_t l = _dl_lookup_symbol_x (args->name, args->map, &ref,
629 args->map->l_local_scope, NULL, 0,
630 DL_LOOKUP_RETURN_NEWEST, NULL);
631 if (ref != NULL)
632 args->result = DL_SYMBOL_ADDRESS (l, ref);
633}
634
993b3242
UD
635static void
636version_check_doit (void *a)
637{
be935610 638 struct version_check_args *args = (struct version_check_args *) a;
c0f62c56
UD
639 if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
640 args->dotrace) && args->doexit)
993b3242
UD
641 /* We cannot start the application. Abort now. */
642 _exit (1);
643}
644
ce37fa88
UD
645
646static inline struct link_map *
647find_needed (const char *name)
648{
c0f62c56
UD
649 struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
650 unsigned int n = scope->r_nlist;
ce37fa88 651
be935610 652 while (n-- > 0)
c0f62c56
UD
653 if (_dl_name_match_p (name, scope->r_list[n]))
654 return scope->r_list[n];
ce37fa88
UD
655
656 /* Should never happen. */
657 return NULL;
658}
659
660static int
661match_version (const char *string, struct link_map *map)
662{
a42195db 663 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
ce37fa88
UD
664 ElfW(Verdef) *def;
665
b0982c4a 666#define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
ce37fa88
UD
667 if (map->l_info[VERDEFTAG] == NULL)
668 /* The file has no symbol versioning. */
669 return 0;
670
671 def = (ElfW(Verdef) *) ((char *) map->l_addr
672 + map->l_info[VERDEFTAG]->d_un.d_ptr);
673 while (1)
674 {
675 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
676
677 /* Compare the version strings. */
678 if (strcmp (string, strtab + aux->vda_name) == 0)
679 /* Bingo! */
680 return 1;
681
682 /* If no more definitions we failed to find what we want. */
683 if (def->vd_next == 0)
684 break;
685
686 /* Next definition. */
687 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
688 }
689
690 return 0;
691}
692
9dcafc55
UD
693static bool tls_init_tp_called;
694
695static void *
696init_tls (void)
697{
698 /* Number of elements in the static TLS block. */
699 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
700
701 /* Do not do this twice. The audit interface might have required
702 the DTV interfaces to be set up early. */
703 if (GL(dl_initial_dtv) != NULL)
704 return NULL;
705
706 /* Allocate the array which contains the information about the
707 dtv slots. We allocate a few entries more than needed to
708 avoid the need for reallocation. */
709 size_t nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
710
711 /* Allocate. */
712 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
713 calloc (sizeof (struct dtv_slotinfo_list)
714 + nelem * sizeof (struct dtv_slotinfo), 1);
715 /* No need to check the return value. If memory allocation failed
716 the program would have been terminated. */
717
718 struct dtv_slotinfo *slotinfo = GL(dl_tls_dtv_slotinfo_list)->slotinfo;
719 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
720 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
721
722 /* Fill in the information from the loaded modules. No namespace
723 but the base one can be filled at this time. */
724 assert (GL(dl_ns)[LM_ID_BASE + 1]._ns_loaded == NULL);
725 int i = 0;
726 for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
727 l = l->l_next)
728 if (l->l_tls_blocksize != 0)
729 {
730 /* This is a module with TLS data. Store the map reference.
731 The generation counter is zero. */
732 slotinfo[i].map = l;
733 /* slotinfo[i].gen = 0; */
734 ++i;
735 }
736 assert (i == GL(dl_tls_max_dtv_idx));
737
738 /* Compute the TLS offsets for the various blocks. */
739 _dl_determine_tlsoffset ();
740
741 /* Construct the static TLS block and the dtv for the initial
742 thread. For some platforms this will include allocating memory
743 for the thread descriptor. The memory for the TLS block will
744 never be freed. It should be allocated accordingly. The dtv
745 array can be changed if dynamic loading requires it. */
746 void *tcbp = _dl_allocate_tls_storage ();
747 if (tcbp == NULL)
748 _dl_fatal_printf ("\
f648728c 749cannot allocate TLS data structures for initial thread\n");
9dcafc55
UD
750
751 /* Store for detection of the special case by __tls_get_addr
752 so it knows not to pass this dtv to the normal realloc. */
753 GL(dl_initial_dtv) = GET_DTV (tcbp);
754
3d8c8bff 755 /* And finally install it for the main thread. */
774f9285 756 const char *lossage = TLS_INIT_TP (tcbp);
a1ffb40e 757 if (__glibc_unlikely (lossage != NULL))
9dcafc55
UD
758 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
759 tls_init_tp_called = true;
760
761 return tcbp;
762}
9dcafc55 763
20fe49b9 764static unsigned int
acf869f4 765do_preload (const char *fname, struct link_map *main_map, const char *where)
20fe49b9
UD
766{
767 const char *objname;
768 const char *err_str = NULL;
769 struct map_args args;
74780cf6 770 bool malloced;
20fe49b9
UD
771
772 args.str = fname;
773 args.loader = main_map;
8e9f92e9 774 args.mode = __RTLD_SECURE;
20fe49b9
UD
775
776 unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
777
74780cf6 778 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
a1ffb40e 779 if (__glibc_unlikely (err_str != NULL))
20fe49b9
UD
780 {
781 _dl_error_printf ("\
4db5b08f
MS
782ERROR: ld.so: object '%s' from %s cannot be preloaded (%s): ignored.\n",
783 fname, where, err_str);
20fe49b9
UD
784 /* No need to call free, this is still before
785 the libc's malloc is used. */
786 }
787 else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
788 /* It is no duplicate. */
789 return 1;
790
791 /* Nothing loaded. */
792 return 0;
793}
794
334fcf2a
UD
795#if defined SHARED && defined _LIBC_REENTRANT \
796 && defined __rtld_lock_default_lock_recursive
20fe49b9
UD
797static void
798rtld_lock_default_lock_recursive (void *lock)
334fcf2a
UD
799{
800 __rtld_lock_default_lock_recursive (lock);
801}
802
20fe49b9
UD
803static void
804rtld_lock_default_unlock_recursive (void *lock)
334fcf2a
UD
805{
806 __rtld_lock_default_unlock_recursive (lock);
807}
808#endif
809
810
4c48ef06
UD
811static void
812security_init (void)
813{
814 /* Set up the stack checker's canary. */
965cb60a 815 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard (_dl_random);
4c48ef06
UD
816#ifdef THREAD_SET_STACK_GUARD
817 THREAD_SET_STACK_GUARD (stack_chk_guard);
818#else
819 __stack_chk_guard = stack_chk_guard;
820#endif
821
822 /* Set up the pointer guard as well, if necessary. */
a014cecd
FW
823 uintptr_t pointer_chk_guard
824 = _dl_setup_pointer_guard (_dl_random, stack_chk_guard);
4c48ef06 825#ifdef THREAD_SET_POINTER_GUARD
a014cecd 826 THREAD_SET_POINTER_GUARD (pointer_chk_guard);
4c48ef06 827#endif
a014cecd 828 __pointer_chk_guard_local = pointer_chk_guard;
965cb60a
UD
829
830 /* We do not need the _dl_random value anymore. The less
831 information we leave behind, the better, so clear the
832 variable. */
833 _dl_random = NULL;
4c48ef06
UD
834}
835
9cee5585 836#include "setup-vdso.h"
4c48ef06 837
392a6b52
UD
838/* The library search path. */
839static const char *library_path attribute_relro;
840/* The list preloaded objects. */
841static const char *preloadlist attribute_relro;
842/* Nonzero if information about versions has to be printed. */
843static int version_info attribute_relro;
8692ebdb
DN
844/* The preload list passed as a command argument. */
845static const char *preloadarg attribute_relro;
a1a9d215 846
6d0ba622
FW
847/* The LD_PRELOAD environment variable gives list of libraries
848 separated by white space or colons that are loaded before the
849 executable's dependencies and prepended to the global scope list.
850 (If the binary is running setuid all elements containing a '/' are
851 ignored since it is insecure.) Return the number of preloads
8692ebdb 852 performed. Ditto for --preload command argument. */
6d0ba622 853unsigned int
8692ebdb
DN
854handle_preload_list (const char *preloadlist, struct link_map *main_map,
855 const char *where)
6d0ba622
FW
856{
857 unsigned int npreloads = 0;
858 const char *p = preloadlist;
859 char fname[SECURE_PATH_LIMIT];
860
861 while (*p != '\0')
862 {
863 /* Split preload list at space/colon. */
864 size_t len = strcspn (p, " :");
865 if (len > 0 && len < sizeof (fname))
866 {
867 memcpy (fname, p, len);
868 fname[len] = '\0';
869 }
870 else
871 fname[0] = '\0';
872
873 /* Skip over the substring and the following delimiter. */
874 p += len;
875 if (*p != '\0')
876 ++p;
877
878 if (dso_name_valid_for_suid (fname))
8692ebdb 879 npreloads += do_preload (fname, main_map, where);
6d0ba622
FW
880 }
881 return npreloads;
882}
883
3b856d09
FW
884/* Called if the audit DSO cannot be used: if it does not have the
885 appropriate interfaces, or it expects a more recent version library
886 version than what the dynamic linker provides. */
887static void
888unload_audit_module (struct link_map *map, int original_tls_idx)
889{
890#ifndef NDEBUG
891 Lmid_t ns = map->l_ns;
892#endif
893 _dl_close (map);
894
895 /* Make sure the namespace has been cleared entirely. */
896 assert (GL(dl_ns)[ns]._ns_loaded == NULL);
897 assert (GL(dl_ns)[ns]._ns_nloaded == 0);
898
899 GL(dl_tls_max_dtv_idx) = original_tls_idx;
900}
901
902/* Called to print an error message if loading of an audit module
903 failed. */
904static void
905report_audit_module_load_error (const char *name, const char *err_str,
906 bool malloced)
907{
908 _dl_error_printf ("\
909ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
910 name, err_str);
911 if (malloced)
912 free ((char *) err_str);
913}
914
915/* Load one audit module. */
916static void
917load_audit_module (const char *name, struct audit_ifaces **last_audit)
918{
919 int original_tls_idx = GL(dl_tls_max_dtv_idx);
920
921 struct dlmopen_args dlmargs;
922 dlmargs.fname = name;
923 dlmargs.map = NULL;
924
925 const char *objname;
926 const char *err_str = NULL;
927 bool malloced;
928 _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit, &dlmargs);
929 if (__glibc_unlikely (err_str != NULL))
930 {
931 report_audit_module_load_error (name, err_str, malloced);
932 return;
933 }
934
935 struct lookup_args largs;
936 largs.name = "la_version";
937 largs.map = dlmargs.map;
938 _dl_catch_error (&objname, &err_str, &malloced, lookup_doit, &largs);
939 if (__glibc_likely (err_str != NULL))
940 {
941 unload_audit_module (dlmargs.map, original_tls_idx);
942 report_audit_module_load_error (name, err_str, malloced);
943 return;
944 }
945
946 unsigned int (*laversion) (unsigned int) = largs.result;
947
948 /* A null symbol indicates that something is very wrong with the
949 loaded object because defined symbols are supposed to have a
950 valid, non-null address. */
951 assert (laversion != NULL);
952
953 unsigned int lav = laversion (LAV_CURRENT);
954 if (lav == 0)
955 {
956 /* Only print an error message if debugging because this can
957 happen deliberately. */
958 if (GLRO(dl_debug_mask) & DL_DEBUG_FILES)
959 _dl_debug_printf ("\
960file=%s [%lu]; audit interface function la_version returned zero; ignored.\n",
961 dlmargs.map->l_name, dlmargs.map->l_ns);
962 unload_audit_module (dlmargs.map, original_tls_idx);
963 return;
964 }
965
966 if (lav > LAV_CURRENT)
967 {
968 _dl_debug_printf ("\
969ERROR: audit interface '%s' requires version %d (maximum supported version %d); ignored.\n",
970 name, lav, LAV_CURRENT);
971 unload_audit_module (dlmargs.map, original_tls_idx);
972 return;
973 }
974
975 enum { naudit_ifaces = 8 };
976 union
977 {
978 struct audit_ifaces ifaces;
979 void (*fptr[naudit_ifaces]) (void);
980 } *newp = malloc (sizeof (*newp));
981 if (newp == NULL)
982 _dl_fatal_printf ("Out of memory while loading audit modules\n");
983
984 /* Names of the auditing interfaces. All in one
985 long string. */
986 static const char audit_iface_names[] =
987 "la_activity\0"
988 "la_objsearch\0"
989 "la_objopen\0"
990 "la_preinit\0"
991#if __ELF_NATIVE_CLASS == 32
992 "la_symbind32\0"
993#elif __ELF_NATIVE_CLASS == 64
994 "la_symbind64\0"
995#else
996# error "__ELF_NATIVE_CLASS must be defined"
997#endif
998#define STRING(s) __STRING (s)
999 "la_" STRING (ARCH_LA_PLTENTER) "\0"
1000 "la_" STRING (ARCH_LA_PLTEXIT) "\0"
1001 "la_objclose\0";
1002 unsigned int cnt = 0;
1003 const char *cp = audit_iface_names;
1004 do
1005 {
1006 largs.name = cp;
1007 _dl_catch_error (&objname, &err_str, &malloced, lookup_doit, &largs);
1008
1009 /* Store the pointer. */
1010 if (err_str == NULL && largs.result != NULL)
1011 {
1012 newp->fptr[cnt] = largs.result;
1013
1014 /* The dynamic linker link map is statically allocated,
1015 initialize the data now. */
1016 GL(dl_rtld_map).l_audit[cnt].cookie = (intptr_t) &GL(dl_rtld_map);
1017 }
1018 else
1019 newp->fptr[cnt] = NULL;
1020 ++cnt;
1021
1022 cp = rawmemchr (cp, '\0') + 1;
1023 }
1024 while (*cp != '\0');
1025 assert (cnt == naudit_ifaces);
1026
1027 /* Now append the new auditing interface to the list. */
1028 newp->ifaces.next = NULL;
1029 if (*last_audit == NULL)
1030 *last_audit = GLRO(dl_audit) = &newp->ifaces;
1031 else
1032 *last_audit = (*last_audit)->next = &newp->ifaces;
1033 ++GLRO(dl_naudit);
1034
1035 /* Mark the DSO as being used for auditing. */
1036 dlmargs.map->l_auditing = 1;
1037}
1038
1039/* Notify the the audit modules that the object MAP has already been
1040 loaded. */
1041static void
1042notify_audit_modules_of_loaded_object (struct link_map *map)
1043{
1044 struct audit_ifaces *afct = GLRO(dl_audit);
1045 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1046 {
1047 if (afct->objopen != NULL)
1048 {
1049 map->l_audit[cnt].bindflags
1050 = afct->objopen (map, LM_ID_BASE, &map->l_audit[cnt].cookie);
1051 map->l_audit_any_plt |= map->l_audit[cnt].bindflags != 0;
1052 }
1053
1054 afct = afct->next;
1055 }
1056}
1057
1058/* Load all audit modules. */
1059static void
1060load_audit_modules (struct link_map *main_map)
1061{
1062 struct audit_ifaces *last_audit = NULL;
1063 struct audit_list_iter al_iter;
1064 audit_list_iter_init (&al_iter);
1065
1066 while (true)
1067 {
1068 const char *name = audit_list_iter_next (&al_iter);
1069 if (name == NULL)
1070 break;
1071 load_audit_module (name, &last_audit);
1072 }
1073
1074 /* Notify audit modules of the initially loaded modules (the main
1075 program and the dynamic linker itself). */
1076 if (GLRO(dl_naudit) > 0)
1077 {
1078 notify_audit_modules_of_loaded_object (main_map);
1079 notify_audit_modules_of_loaded_object (&GL(dl_rtld_map));
1080 }
1081}
1082
d66e34cd 1083static void
266180eb 1084dl_main (const ElfW(Phdr) *phdr,
72f70279 1085 ElfW(Word) phnum,
3a56ea26
AK
1086 ElfW(Addr) *user_entry,
1087 ElfW(auxv_t) *auxv)
d66e34cd 1088{
266180eb 1089 const ElfW(Phdr) *ph;
ea278354 1090 enum mode mode;
c0f62c56 1091 struct link_map *main_map;
14bab8de
UD
1092 size_t file_size;
1093 char *file;
164a7164 1094 bool has_interp = false;
77aba05b 1095 unsigned int i;
164a7164
UD
1096 bool prelinked = false;
1097 bool rtld_is_main = false;
9dcafc55 1098 void *tcbp = NULL;
d66e34cd 1099
adc12574 1100 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
adc12574 1101
334fcf2a
UD
1102#if defined SHARED && defined _LIBC_REENTRANT \
1103 && defined __rtld_lock_default_lock_recursive
1104 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
1105 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
1106#endif
1107
c70ba488
RM
1108 /* The explicit initialization here is cheaper than processing the reloc
1109 in the _rtld_local definition's initializer. */
1110 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
1111
ea278354 1112 /* Process the environment variable which control the behaviour. */
ba9fcb3f 1113 process_envvars (&mode);
3996f34b 1114
ce6e047f 1115#ifndef HAVE_INLINED_SYSCALLS
46ec036d 1116 /* Set up a flag which tells we are just starting. */
9cf27b8d 1117 _dl_starting_up = 1;
ce6e047f 1118#endif
46ec036d 1119
a16956f3 1120 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
0200214b
RM
1121 {
1122 /* Ho ho. We are not the program interpreter! We are the program
1123 itself! This means someone ran ld.so as a command. Well, that
1124 might be convenient to do sometimes. We support it by
1125 interpreting the args like this:
1126
1127 ld.so PROGRAM ARGS...
1128
1129 The first argument is the name of a file containing an ELF
1130 executable we will load and run with the following arguments.
1131 To simplify life here, PROGRAM is searched for using the
1132 normal rules for shared objects, rather than $PATH or anything
1133 like that. We just load it and use its entry point; we don't
1134 pay attention to its PT_INTERP command (we are the interpreter
1135 ourselves). This is an easy way to test a new ld.so before
1136 installing it. */
164a7164 1137 rtld_is_main = true;
421f82e5 1138
ffee1316 1139 /* Note the place where the dynamic linker actually came from. */
e6caf4e1 1140 GL(dl_rtld_map).l_name = rtld_progname;
6a76c115 1141
fd26970f 1142 while (_dl_argc > 1)
4243cbea 1143 if (! strcmp (_dl_argv[1], "--list"))
fd26970f
UD
1144 {
1145 mode = list;
afdca0f2 1146 GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
61965e9b 1147
fd26970f
UD
1148 ++_dl_skip_args;
1149 --_dl_argc;
4243cbea 1150 ++_dl_argv;
fd26970f 1151 }
4243cbea 1152 else if (! strcmp (_dl_argv[1], "--verify"))
fd26970f
UD
1153 {
1154 mode = verify;
6a76c115 1155
73d65cc3
SP
1156 ++_dl_skip_args;
1157 --_dl_argc;
4243cbea 1158 ++_dl_argv;
73d65cc3 1159 }
4243cbea 1160 else if (! strcmp (_dl_argv[1], "--inhibit-cache"))
73d65cc3
SP
1161 {
1162 GLRO(dl_inhibit_cache) = 1;
fd26970f
UD
1163 ++_dl_skip_args;
1164 --_dl_argc;
4243cbea 1165 ++_dl_argv;
fd26970f 1166 }
4243cbea 1167 else if (! strcmp (_dl_argv[1], "--library-path")
e6caf4e1 1168 && _dl_argc > 2)
880f421f 1169 {
4243cbea 1170 library_path = _dl_argv[2];
880f421f 1171
310930c1
UD
1172 _dl_skip_args += 2;
1173 _dl_argc -= 2;
4243cbea 1174 _dl_argv += 2;
310930c1 1175 }
4243cbea 1176 else if (! strcmp (_dl_argv[1], "--inhibit-rpath")
e6caf4e1 1177 && _dl_argc > 2)
310930c1 1178 {
4243cbea 1179 GLRO(dl_inhibit_rpath) = _dl_argv[2];
310930c1 1180
74780cf6
UD
1181 _dl_skip_args += 2;
1182 _dl_argc -= 2;
4243cbea 1183 _dl_argv += 2;
74780cf6 1184 }
4243cbea 1185 else if (! strcmp (_dl_argv[1], "--audit") && _dl_argc > 2)
74780cf6 1186 {
4243cbea 1187 process_dl_audit (_dl_argv[2]);
74780cf6 1188
8692ebdb
DN
1189 _dl_skip_args += 2;
1190 _dl_argc -= 2;
1191 _dl_argv += 2;
1192 }
1193 else if (! strcmp (_dl_argv[1], "--preload") && _dl_argc > 2)
1194 {
1195 preloadarg = _dl_argv[2];
880f421f
UD
1196 _dl_skip_args += 2;
1197 _dl_argc -= 2;
4243cbea 1198 _dl_argv += 2;
880f421f 1199 }
fd26970f
UD
1200 else
1201 break;
d66e34cd 1202
61eb22d3
UD
1203 /* If we have no further argument the program was called incorrectly.
1204 Grant the user some education. */
1205 if (_dl_argc < 2)
35fc382a 1206 _dl_fatal_printf ("\
2bcf29ba 1207Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
61eb22d3
UD
1208You have invoked `ld.so', the helper program for shared library executables.\n\
1209This program usually lives in the file `/lib/ld.so', and special directives\n\
1210in executable files using ELF shared libraries tell the system's program\n\
1211loader to load the helper program from this file. This helper program loads\n\
1212the shared libraries needed by the program executable, prepares the program\n\
1213to run, and runs it. You may invoke this helper program directly from the\n\
1214command line to load and run an ELF executable file; this is like executing\n\
1215that file itself, but always uses this helper program from the file you\n\
1216specified, instead of the helper program file specified in the executable\n\
1217file you run. This is mostly of use for maintainers to test new versions\n\
2bcf29ba
UD
1218of this helper program; chances are you did not intend to run this program.\n\
1219\n\
b0a01055
UD
1220 --list list all dependencies and how they are resolved\n\
1221 --verify verify that given object really is a dynamically linked\n\
3a56ea26 1222 object we can handle\n\
73d65cc3 1223 --inhibit-cache Do not use " LD_SO_CACHE "\n\
b0a01055 1224 --library-path PATH use given PATH instead of content of the environment\n\
3a56ea26 1225 variable LD_LIBRARY_PATH\n\
fcf70d41 1226 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
3a56ea26 1227 in LIST\n\
8692ebdb
DN
1228 --audit LIST use objects named in LIST as auditors\n\
1229 --preload LIST preload objects named in LIST\n");
61eb22d3 1230
0200214b
RM
1231 ++_dl_skip_args;
1232 --_dl_argc;
4243cbea 1233 ++_dl_argv;
91f62ce6 1234
c70ba488
RM
1235 /* The initialization of _dl_stack_flags done below assumes the
1236 executable's PT_GNU_STACK may have been honored by the kernel, and
1237 so a PT_GNU_STACK with PF_X set means the stack started out with
1238 execute permission. However, this is not really true if the
1239 dynamic linker is the executable the kernel loaded. For this
1240 case, we must reinitialize _dl_stack_flags to match the dynamic
1241 linker itself. If the dynamic linker was built with a
1242 PT_GNU_STACK, then the kernel may have loaded us with a
1243 nonexecutable stack that we will have to make executable when we
1244 load the program below unless it has a PT_GNU_STACK indicating
1245 nonexecutable stack is ok. */
1246
1247 for (ph = phdr; ph < &phdr[phnum]; ++ph)
1248 if (ph->p_type == PT_GNU_STACK)
1249 {
1250 GL(dl_stack_flags) = ph->p_flags;
1251 break;
1252 }
1253
9a821cf9 1254 if (__builtin_expect (mode, normal) == verify)
2de99474 1255 {
8e17ea58
UD
1256 const char *objname;
1257 const char *err_str = NULL;
993b3242 1258 struct map_args args;
74780cf6 1259 bool malloced;
2de99474 1260
e6caf4e1 1261 args.str = rtld_progname;
f04b9a68 1262 args.loader = NULL;
f04b9a68 1263 args.mode = __RTLD_OPENEXEC;
74780cf6
UD
1264 (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
1265 &args);
a1ffb40e 1266 if (__glibc_unlikely (err_str != NULL))
e6caf4e1
UD
1267 /* We don't free the returned string, the programs stops
1268 anyway. */
1269 _exit (EXIT_FAILURE);
2de99474
UD
1270 }
1271 else
db276fa1 1272 {
1e372ded
AZ
1273 RTLD_TIMING_VAR (start);
1274 rtld_timer_start (&start);
798212a0 1275 _dl_map_object (NULL, rtld_progname, lt_executable, 0,
c0f62c56 1276 __RTLD_OPENEXEC, LM_ID_BASE);
1e372ded 1277 rtld_timer_stop (&load_time, start);
db276fa1 1278 }
2de99474 1279
c0f62c56
UD
1280 /* Now the map for the main executable is available. */
1281 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1282
f3fd569c
DL
1283 if (__builtin_expect (mode, normal) == normal
1284 && GL(dl_rtld_map).l_info[DT_SONAME] != NULL
01f16ab0
UD
1285 && main_map->l_info[DT_SONAME] != NULL
1286 && strcmp ((const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1287 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val,
1288 (const char *) D_PTR (main_map, l_info[DT_STRTAB])
1289 + main_map->l_info[DT_SONAME]->d_un.d_val) == 0)
1290 _dl_fatal_printf ("loader cannot load itself\n");
1291
c0f62c56
UD
1292 phdr = main_map->l_phdr;
1293 phnum = main_map->l_phnum;
143e2b96
UD
1294 /* We overwrite here a pointer to a malloc()ed string. But since
1295 the malloc() implementation used at this point is the dummy
1296 implementations which has no real free() function it does not
1297 makes sense to free the old string first. */
c0f62c56
UD
1298 main_map->l_name = (char *) "";
1299 *user_entry = main_map->l_entry;
3a56ea26 1300
bc58236c 1301#ifdef HAVE_AUX_VECTOR
3a56ea26
AK
1302 /* Adjust the on-stack auxiliary vector so that it looks like the
1303 binary was executed directly. */
bc58236c 1304 for (ElfW(auxv_t) *av = auxv; av->a_type != AT_NULL; av++)
3a56ea26
AK
1305 switch (av->a_type)
1306 {
1307 case AT_PHDR:
4dd019e3 1308 av->a_un.a_val = (uintptr_t) phdr;
3a56ea26
AK
1309 break;
1310 case AT_PHNUM:
1311 av->a_un.a_val = phnum;
1312 break;
1313 case AT_ENTRY:
1314 av->a_un.a_val = *user_entry;
1315 break;
5c349950
PP
1316 case AT_EXECFN:
1317 av->a_un.a_val = (uintptr_t) _dl_argv[0];
1318 break;
3a56ea26 1319 }
bc58236c 1320#endif
0200214b
RM
1321 }
1322 else
1323 {
1324 /* Create a link_map for the executable itself.
1325 This will be what dlopen on "" returns. */
9fbdeb41
UD
1326 main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1327 __RTLD_OPENEXEC, LM_ID_BASE);
9dcafc55 1328 assert (main_map != NULL);
c0f62c56
UD
1329 main_map->l_phdr = phdr;
1330 main_map->l_phnum = phnum;
1331 main_map->l_entry = *user_entry;
da832465 1332
f0967738
AK
1333 /* Even though the link map is not yet fully initialized we can add
1334 it to the map list since there are no possible users running yet. */
1335 _dl_add_to_namespace_list (main_map, LM_ID_BASE);
fa41c84d 1336 assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
f0967738 1337
61e0617a
UD
1338 /* At this point we are in a bit of trouble. We would have to
1339 fill in the values for l_dev and l_ino. But in general we
1340 do not know where the file is. We also do not handle AT_EXECFD
1341 even if it would be passed up.
1342
1343 We leave the values here defined to 0. This is normally no
1344 problem as the program code itself is normally no shared
1345 object and therefore cannot be loaded dynamically. Nothing
1346 prevent the use of dynamic binaries and in these situations
1347 we might get problems. We might not be able to find out
1348 whether the object is already loaded. But since there is no
1349 easy way out and because the dynamic binary must also not
1350 have an SONAME we ignore this program for now. If it becomes
1351 a problem we can force people using SONAMEs. */
1352
97a51d8a
UD
1353 /* We delay initializing the path structure until we got the dynamic
1354 information for the program. */
0200214b
RM
1355 }
1356
c0f62c56
UD
1357 main_map->l_map_end = 0;
1358 main_map->l_text_end = 0;
052b6a6c 1359 /* Perhaps the executable has no PT_LOAD header entries at all. */
c0f62c56 1360 main_map->l_map_start = ~0;
c0f62c56
UD
1361 /* And it was opened directly. */
1362 ++main_map->l_direct_opencount;
052b6a6c 1363
0200214b 1364 /* Scan the program header table for the dynamic section. */
72f70279 1365 for (ph = phdr; ph < &phdr[phnum]; ++ph)
0200214b
RM
1366 switch (ph->p_type)
1367 {
da832465
UD
1368 case PT_PHDR:
1369 /* Find out the load address. */
c0f62c56 1370 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
da832465 1371 break;
0200214b
RM
1372 case PT_DYNAMIC:
1373 /* This tells us where to find the dynamic section,
1374 which tells us everything we need to do. */
c0f62c56 1375 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
0200214b
RM
1376 break;
1377 case PT_INTERP:
1378 /* This "interpreter segment" was used by the program loader to
1379 find the program interpreter, which is this program itself, the
1380 dynamic linker. We note what name finds us, so that a future
1381 dlopen call or DT_NEEDED entry, for something that wants to link
1382 against the dynamic linker as a shared library, will know that
1383 the shared object is already loaded. */
c0f62c56 1384 _dl_rtld_libname.name = ((const char *) main_map->l_addr
be935610 1385 + ph->p_vaddr);
752a2a50 1386 /* _dl_rtld_libname.next = NULL; Already zero. */
d6b5d570 1387 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
f41c8091
UD
1388
1389 /* Ordinarilly, we would get additional names for the loader from
1390 our DT_SONAME. This can't happen if we were actually linked as
1391 a static executable (detect this case when we have no DYNAMIC).
1392 If so, assume the filename component of the interpreter path to
1393 be our SONAME, and add it to our name list. */
d6b5d570 1394 if (GL(dl_rtld_map).l_ld == NULL)
f41c8091 1395 {
88794e30
UD
1396 const char *p = NULL;
1397 const char *cp = _dl_rtld_libname.name;
1398
1399 /* Find the filename part of the path. */
1400 while (*cp != '\0')
1401 if (*cp++ == '/')
1402 p = cp;
1403
1404 if (p != NULL)
f41c8091 1405 {
88794e30 1406 _dl_rtld_libname2.name = p;
752a2a50 1407 /* _dl_rtld_libname2.next = NULL; Already zero. */
f41c8091
UD
1408 _dl_rtld_libname.next = &_dl_rtld_libname2;
1409 }
1410 }
1411
164a7164 1412 has_interp = true;
0200214b 1413 break;
052b6a6c 1414 case PT_LOAD:
052b6a6c
UD
1415 {
1416 ElfW(Addr) mapstart;
2373b30e
UD
1417 ElfW(Addr) allocend;
1418
1419 /* Remember where the main program starts in memory. */
b92e3780
UD
1420 mapstart = (main_map->l_addr
1421 + (ph->p_vaddr & ~(GLRO(dl_pagesize) - 1)));
c0f62c56
UD
1422 if (main_map->l_map_start > mapstart)
1423 main_map->l_map_start = mapstart;
2373b30e
UD
1424
1425 /* Also where it ends. */
c0f62c56
UD
1426 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1427 if (main_map->l_map_end < allocend)
1428 main_map->l_map_end = allocend;
1429 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1430 main_map->l_text_end = allocend;
052b6a6c
UD
1431 }
1432 break;
9dcafc55 1433
a334319f 1434 case PT_TLS:
aed283dd
UD
1435 if (ph->p_memsz > 0)
1436 {
1437 /* Note that in the case the dynamic linker we duplicate work
1438 here since we read the PT_TLS entry already in
1439 _dl_start_final. But the result is repeatable so do not
1440 check for this special but unimportant case. */
c0f62c56
UD
1441 main_map->l_tls_blocksize = ph->p_memsz;
1442 main_map->l_tls_align = ph->p_align;
99fe3b0e 1443 if (ph->p_align == 0)
c0f62c56 1444 main_map->l_tls_firstbyte_offset = 0;
99fe3b0e 1445 else
c0f62c56
UD
1446 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1447 & (ph->p_align - 1));
1448 main_map->l_tls_initimage_size = ph->p_filesz;
1449 main_map->l_tls_initimage = (void *) ph->p_vaddr;
aed283dd
UD
1450
1451 /* This image gets the ID one. */
c0f62c56 1452 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
aed283dd 1453 }
9dcafc55
UD
1454 break;
1455
ecdeaac0
RM
1456 case PT_GNU_STACK:
1457 GL(dl_stack_flags) = ph->p_flags;
1458 break;
e8ed861d
UD
1459
1460 case PT_GNU_RELRO:
c0f62c56
UD
1461 main_map->l_relro_addr = ph->p_vaddr;
1462 main_map->l_relro_size = ph->p_memsz;
e8ed861d 1463 break;
f753fa7d
L
1464
1465 case PT_NOTE:
1466 if (_rtld_process_pt_note (main_map, ph))
1467 _dl_error_printf ("\
1468ERROR: '%s': cannot process note segment.\n", _dl_argv[0]);
1469 break;
0200214b 1470 }
11bf311e
UD
1471
1472 /* Adjust the address of the TLS initialization image in case
1473 the executable is actually an ET_DYN object. */
1474 if (main_map->l_tls_initimage != NULL)
1475 main_map->l_tls_initimage
1476 = (char *) main_map->l_tls_initimage + main_map->l_addr;
c0f62c56
UD
1477 if (! main_map->l_map_end)
1478 main_map->l_map_end = ~0;
1479 if (! main_map->l_text_end)
1480 main_map->l_text_end = ~0;
d6b5d570 1481 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
c84142e8
UD
1482 {
1483 /* We were invoked directly, so the program might not have a
1484 PT_INTERP. */
d6b5d570 1485 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
f0967738 1486 /* _dl_rtld_libname.next = NULL; Already zero. */
d6b5d570 1487 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
c84142e8 1488 }
ffee1316 1489 else
d6b5d570 1490 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
0200214b 1491
9dcafc55
UD
1492 /* If the current libname is different from the SONAME, add the
1493 latter as well. */
1494 if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1495 && strcmp (GL(dl_rtld_map).l_libname->name,
1496 (const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1497 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1498 {
1499 static struct libname_list newname;
1500 newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1501 + GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1502 newname.next = NULL;
1503 newname.dont_free = 1;
1504
1505 assert (GL(dl_rtld_map).l_libname->next == NULL);
1506 GL(dl_rtld_map).l_libname->next = &newname;
1507 }
1508 /* The ld.so must be relocated since otherwise loading audit modules
1509 will fail since they reuse the very same ld.so. */
1510 assert (GL(dl_rtld_map).l_relocated);
1511
9a51759b
UD
1512 if (! rtld_is_main)
1513 {
1514 /* Extract the contents of the dynamic section for easy access. */
c0f62c56 1515 elf_get_dynamic_info (main_map, NULL);
efec5079 1516 /* Set up our cache of pointers into the hash table. */
c0f62c56 1517 _dl_setup_hash (main_map);
9a51759b 1518 }
0200214b 1519
9a821cf9 1520 if (__builtin_expect (mode, normal) == verify)
e2102c14
UD
1521 {
1522 /* We were called just to verify that this is a dynamic
1523 executable using us as the program interpreter. Exit with an
1524 error if we were not able to load the binary or no interpreter
1525 is specified (i.e., this is no dynamically linked binary. */
c0f62c56 1526 if (main_map->l_ld == NULL)
e2102c14 1527 _exit (1);
e2102c14
UD
1528
1529 /* We allow here some platform specific code. */
1530#ifdef DISTINGUISH_LIB_VERSIONS
1531 DISTINGUISH_LIB_VERSIONS;
1532#endif
eb406346 1533 _exit (has_interp ? 0 : 2);
e2102c14
UD
1534 }
1535
ab1d521d 1536 struct link_map **first_preload = &GL(dl_rtld_map).l_next;
ab1d521d
RM
1537 /* Set up the data structures for the system-supplied DSO early,
1538 so they can influence _dl_init_paths. */
9cee5585 1539 setup_vdso (main_map, &first_preload);
ab1d521d
RM
1540
1541#ifdef DL_SYSDEP_OSCHECK
ceb809dc 1542 DL_SYSDEP_OSCHECK (_dl_fatal_printf);
ab1d521d
RM
1543#endif
1544
1545 /* Initialize the data structures for the search paths for shared
1546 objects. */
1547 _dl_init_paths (library_path);
97a51d8a 1548
9dcafc55 1549 /* Initialize _r_debug. */
29f97654
UD
1550 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1551 LM_ID_BASE);
9dcafc55
UD
1552 r->r_state = RT_CONSISTENT;
1553
0200214b 1554 /* Put the link_map for ourselves on the chain so it can be found by
ceb2d9aa 1555 name. Note that at this point the global chain of link maps contains
d6b5d570
UD
1556 exactly one element, which is pointed to by dl_loaded. */
1557 if (! GL(dl_rtld_map).l_name)
ffee1316
RM
1558 /* If not invoked directly, the dynamic linker shared object file was
1559 found by the PT_INTERP name. */
d6b5d570
UD
1560 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1561 GL(dl_rtld_map).l_type = lt_library;
c0f62c56
UD
1562 main_map->l_next = &GL(dl_rtld_map);
1563 GL(dl_rtld_map).l_prev = main_map;
1564 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
e8ed861d 1565 ++GL(dl_load_adds);
0200214b 1566
97fd3a30
UD
1567 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1568 to not using bias for non-prelinked PIEs and libraries
1569 and using it for executables or prelinked PIEs or libraries. */
afdca0f2 1570 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
c0f62c56 1571 GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
97fd3a30 1572
553eca26 1573 /* Set up the program header information for the dynamic linker
44c4e5d5
RM
1574 itself. It is needed in the dl_iterate_phdr callbacks. */
1575 const ElfW(Ehdr) *rtld_ehdr;
1576
1577 /* Starting from binutils-2.23, the linker will define the magic symbol
1578 __ehdr_start to point to our own ELF header if it is visible in a
1579 segment that also includes the phdrs. If that's not available, we use
1580 the old method that assumes the beginning of the file is part of the
1581 lowest-addressed PT_LOAD segment. */
1582#ifdef HAVE_EHDR_START
1583 extern const ElfW(Ehdr) __ehdr_start __attribute__ ((visibility ("hidden")));
1584 rtld_ehdr = &__ehdr_start;
1585#else
1586 rtld_ehdr = (void *) GL(dl_rtld_map).l_map_start;
1587#endif
1588 assert (rtld_ehdr->e_ehsize == sizeof *rtld_ehdr);
1589 assert (rtld_ehdr->e_phentsize == sizeof (ElfW(Phdr)));
1590
1591 const ElfW(Phdr) *rtld_phdr = (const void *) rtld_ehdr + rtld_ehdr->e_phoff;
1592
e8ed861d 1593 GL(dl_rtld_map).l_phdr = rtld_phdr;
553eca26
UD
1594 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1595
9dcafc55 1596
e8ed861d
UD
1597 /* PT_GNU_RELRO is usually the last phdr. */
1598 size_t cnt = rtld_ehdr->e_phnum;
1599 while (cnt-- > 0)
1600 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1601 {
1602 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1603 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1604 break;
1605 }
1606
9dcafc55
UD
1607 /* Add the dynamic linker to the TLS list if it also uses TLS. */
1608 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1609 /* Assign a module ID. Do this before loading any audit modules. */
1610 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
9dcafc55
UD
1611
1612 /* If we have auditing DSOs to load, do it now. */
81b82fb9
FW
1613 bool need_security_init = true;
1614 if (__glibc_unlikely (audit_list != NULL)
1615 || __glibc_unlikely (audit_list_string != NULL))
9dcafc55 1616 {
3abee0b7
UD
1617 /* Since we start using the auditing DSOs right away we need to
1618 initialize the data structures now. */
1619 tcbp = init_tls ();
1620
4c48ef06
UD
1621 /* Initialize security features. We need to do it this early
1622 since otherwise the constructors of the audit libraries will
1623 use different values (especially the pointer guard) and will
1624 fail later on. */
1625 security_init ();
81b82fb9 1626 need_security_init = false;
4c48ef06 1627
3b856d09 1628 load_audit_modules (main_map);
9dcafc55
UD
1629 }
1630
d0503676
CD
1631 /* Keep track of the currently loaded modules to count how many
1632 non-audit modules which use TLS are loaded. */
1633 size_t count_modids = _dl_count_modids ();
1634
c63d8f80
UD
1635 /* Set up debugging before the debugger is notified for the first time. */
1636#ifdef ELF_MACHINE_DEBUG_SETUP
1637 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1638 ELF_MACHINE_DEBUG_SETUP (main_map, r);
1639 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1640#else
1641 if (main_map->l_info[DT_DEBUG] != NULL)
1642 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1643 with the run-time address of the r_debug structure */
1644 main_map->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1645
1646 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1647 case you run gdb on the dynamic linker directly. */
1648 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1649 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1650#endif
1651
9dcafc55
UD
1652 /* We start adding objects. */
1653 r->r_state = RT_ADD;
1654 _dl_debug_state ();
815e6fa3 1655 LIBC_PROBE (init_start, 2, LM_ID_BASE, r);
9dcafc55
UD
1656
1657 /* Auditing checkpoint: we are ready to signal that the initial map
1658 is being constructed. */
a1ffb40e 1659 if (__glibc_unlikely (GLRO(dl_naudit) > 0))
9dcafc55
UD
1660 {
1661 struct audit_ifaces *afct = GLRO(dl_audit);
1662 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1663 {
1664 if (afct->activity != NULL)
1665 afct->activity (&main_map->l_audit[cnt].cookie, LA_ACT_ADD);
1666
1667 afct = afct->next;
1668 }
1669 }
1670
14bab8de 1671 /* We have two ways to specify objects to preload: via environment
49c091e5 1672 variable and via the file /etc/ld.so.preload. The latter can also
14bab8de 1673 be used when security is enabled. */
ab1d521d 1674 assert (*first_preload == NULL);
20fe49b9
UD
1675 struct link_map **preloads = NULL;
1676 unsigned int npreloads = 0;
14bab8de 1677
a1ffb40e 1678 if (__glibc_unlikely (preloadlist != NULL))
c4029823 1679 {
1e372ded
AZ
1680 RTLD_TIMING_VAR (start);
1681 rtld_timer_start (&start);
8692ebdb 1682 npreloads += handle_preload_list (preloadlist, main_map, "LD_PRELOAD");
1e372ded 1683 rtld_timer_accum (&load_time, start);
8692ebdb
DN
1684 }
1685
1686 if (__glibc_unlikely (preloadarg != NULL))
1687 {
1e372ded
AZ
1688 RTLD_TIMING_VAR (start);
1689 rtld_timer_start (&start);
8692ebdb 1690 npreloads += handle_preload_list (preloadarg, main_map, "--preload");
1e372ded 1691 rtld_timer_accum (&load_time, start);
c4029823
UD
1692 }
1693
761490a1
UD
1694 /* There usually is no ld.so.preload file, it should only be used
1695 for emergencies and testing. So the open call etc should usually
1696 fail. Using access() on a non-existing file is faster than using
1697 open(). So we do this first. If it succeeds we do almost twice
1698 the work but this does not matter, since it is not for production
1699 use. */
1700 static const char preload_file[] = "/etc/ld.so.preload";
a1ffb40e 1701 if (__glibc_unlikely (__access (preload_file, R_OK) == 0))
14bab8de 1702 {
761490a1
UD
1703 /* Read the contents of the file. */
1704 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1705 PROT_READ | PROT_WRITE);
a1ffb40e 1706 if (__glibc_unlikely (file != MAP_FAILED))
14bab8de 1707 {
761490a1
UD
1708 /* Parse the file. It contains names of libraries to be loaded,
1709 separated by white spaces or `:'. It may also contain
1710 comments introduced by `#'. */
1711 char *problem;
1712 char *runp;
1713 size_t rest;
1714
1715 /* Eliminate comments. */
e2102c14 1716 runp = file;
761490a1
UD
1717 rest = file_size;
1718 while (rest > 0)
1719 {
1720 char *comment = memchr (runp, '#', rest);
1721 if (comment == NULL)
1722 break;
1723
1724 rest -= comment - runp;
1725 do
1726 *comment = ' ';
1727 while (--rest > 0 && *++comment != '\n');
1728 }
1729
1730 /* We have one problematic case: if we have a name at the end of
1731 the file without a trailing terminating characters, we cannot
1732 place the \0. Handle the case separately. */
1733 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1734 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1735 {
1736 problem = &file[file_size];
1737 while (problem > file && problem[-1] != ' '
1738 && problem[-1] != '\t'
1739 && problem[-1] != '\n' && problem[-1] != ':')
1740 --problem;
1741
1742 if (problem > file)
1743 problem[-1] = '\0';
1744 }
1745 else
1746 {
1747 problem = NULL;
1748 file[file_size - 1] = '\0';
1749 }
f04b9a68 1750
1e372ded
AZ
1751 RTLD_TIMING_VAR (start);
1752 rtld_timer_start (&start);
f04b9a68 1753
761490a1
UD
1754 if (file != problem)
1755 {
1756 char *p;
1757 runp = file;
1758 while ((p = strsep (&runp, ": \t\n")) != NULL)
1759 if (p[0] != '\0')
20fe49b9 1760 npreloads += do_preload (p, main_map, preload_file);
761490a1
UD
1761 }
1762
1763 if (problem != NULL)
1764 {
1765 char *p = strndupa (problem, file_size - (problem - file));
20fe49b9
UD
1766
1767 npreloads += do_preload (p, main_map, preload_file);
761490a1 1768 }
14bab8de 1769
1e372ded 1770 rtld_timer_accum (&load_time, start);
db276fa1 1771
761490a1
UD
1772 /* We don't need the file anymore. */
1773 __munmap (file, file_size);
1774 }
14bab8de
UD
1775 }
1776
a1ffb40e 1777 if (__glibc_unlikely (*first_preload != NULL))
14bab8de
UD
1778 {
1779 /* Set up PRELOADS with a vector of the preloaded libraries. */
ab1d521d 1780 struct link_map *l = *first_preload;
14bab8de 1781 preloads = __alloca (npreloads * sizeof preloads[0]);
14bab8de
UD
1782 i = 0;
1783 do
1784 {
1785 preloads[i++] = l;
1786 l = l->l_next;
1787 } while (l);
1788 assert (i == npreloads);
1789 }
1790
2064087b
RM
1791 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1792 specified some libraries to load, these are inserted before the actual
1793 dependencies in the executable's searchlist for symbol resolution. */
1e372ded
AZ
1794 {
1795 RTLD_TIMING_VAR (start);
1796 rtld_timer_start (&start);
1797 _dl_map_object_deps (main_map, preloads, npreloads, mode == trace, 0);
1798 rtld_timer_accum (&load_time, start);
1799 }
e3e35cfc 1800
20fe49b9 1801 /* Mark all objects as being in the global scope. */
c0f62c56 1802 for (i = main_map->l_searchlist.r_nlist; i > 0; )
20fe49b9 1803 main_map->l_searchlist.r_list[--i]->l_global = 1;
d66e34cd 1804
f9496a7b 1805 /* Remove _dl_rtld_map from the chain. */
d6b5d570 1806 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
20fe49b9 1807 if (GL(dl_rtld_map).l_next != NULL)
d6b5d570 1808 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
f9496a7b 1809
20fe49b9
UD
1810 for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1811 if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1812 break;
1813
1814 bool rtld_multiple_ref = false;
a1ffb40e 1815 if (__glibc_likely (i < main_map->l_searchlist.r_nlist))
0200214b 1816 {
f9496a7b
RM
1817 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1818 put it back in the list of visible objects. We insert it into the
1819 chain in symbol search order because gdb uses the chain's order as
1820 its symbol search order. */
20fe49b9
UD
1821 rtld_multiple_ref = true;
1822
c0f62c56 1823 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
b2bcd61a 1824 if (__builtin_expect (mode, normal) == normal)
3b3ddb4f 1825 {
c0f62c56
UD
1826 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1827 ? main_map->l_searchlist.r_list[i + 1]
3b3ddb4f 1828 : NULL);
7775448e 1829#ifdef NEED_DL_SYSINFO_DSO
ab1d521d
RM
1830 if (GLRO(dl_sysinfo_map) != NULL
1831 && GL(dl_rtld_map).l_prev->l_next == GLRO(dl_sysinfo_map)
1832 && GL(dl_rtld_map).l_next != GLRO(dl_sysinfo_map))
1833 GL(dl_rtld_map).l_prev = GLRO(dl_sysinfo_map);
3b3ddb4f
UD
1834#endif
1835 }
b2bcd61a
UD
1836 else
1837 /* In trace mode there might be an invisible object (which we
1838 could not find) after the previous one in the search list.
1839 In this case it doesn't matter much where we put the
1840 interpreter object, so we just initialize the list pointer so
1841 that the assertion below holds. */
d6b5d570 1842 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
b2bcd61a 1843
d6b5d570
UD
1844 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1845 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
3fb55878 1846 if (GL(dl_rtld_map).l_next != NULL)
f9496a7b 1847 {
d6b5d570
UD
1848 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1849 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
f9496a7b 1850 }
0200214b 1851 }
d66e34cd 1852
c84142e8
UD
1853 /* Now let us see whether all libraries are available in the
1854 versions we need. */
1855 {
993b3242
UD
1856 struct version_check_args args;
1857 args.doexit = mode == normal;
145b8413 1858 args.dotrace = mode == trace;
993b3242 1859 _dl_receive_error (print_missing_version, version_check_doit, &args);
c84142e8
UD
1860 }
1861
2d148689
RM
1862 /* We do not initialize any of the TLS functionality unless any of the
1863 initial modules uses TLS. This makes dynamic loading of modules with
1864 TLS impossible, but to support it requires either eagerly doing setup
1865 now or lazily doing it later. Doing it now makes us incompatible with
1866 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1867 used. Trying to do it lazily is too hairy to try when there could be
1868 multiple threads (from a non-TLS-using libpthread). */
9dcafc55 1869 bool was_tls_init_tp_called = tls_init_tp_called;
35f1e827 1870 if (tcbp == NULL)
9dcafc55 1871 tcbp = init_tls ();
0ecb606c 1872
81b82fb9 1873 if (__glibc_likely (need_security_init))
4c48ef06
UD
1874 /* Initialize security features. But only if we have not done it
1875 earlier. */
1876 security_init ();
827b7087 1877
9a821cf9 1878 if (__builtin_expect (mode, normal) != normal)
0200214b
RM
1879 {
1880 /* We were run just to list the shared libraries. It is
1881 important that we do this before real relocation, because the
1882 functions we call below for output may no longer work properly
1883 after relocation. */
81f3ac4c
UD
1884 struct link_map *l;
1885
afdca0f2 1886 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
ceb2d9aa 1887 {
c0f62c56 1888 struct r_scope_elem *scope = &main_map->l_searchlist;
ceb2d9aa 1889
81f3ac4c 1890 for (i = 0; i < scope->r_nlist; i++)
32e6df36 1891 {
81f3ac4c
UD
1892 l = scope->r_list [i];
1893 if (l->l_faked)
32e6df36 1894 {
81f3ac4c
UD
1895 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1896 continue;
1897 }
afdca0f2
UD
1898 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1899 GLRO(dl_trace_prelink_map) = l;
81f3ac4c 1900 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
b9375348
SP
1901 DSO_FILENAME (l->l_libname->name),
1902 DSO_FILENAME (l->l_name),
d347a4ab
UD
1903 (int) sizeof l->l_map_start * 2,
1904 (size_t) l->l_map_start,
1905 (int) sizeof l->l_addr * 2,
1906 (size_t) l->l_addr);
11bf311e 1907
81f3ac4c
UD
1908 if (l->l_tls_modid)
1909 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1910 (int) sizeof l->l_tls_offset * 2,
d347a4ab 1911 (size_t) l->l_tls_offset);
81f3ac4c 1912 else
81f3ac4c 1913 _dl_printf ("\n");
32e6df36 1914 }
ceb2d9aa 1915 }
7a11603d
UD
1916 else if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
1917 {
1918 /* Look through the dependencies of the main executable
1919 and determine which of them is not actually
1920 required. */
c0f62c56 1921 struct link_map *l = main_map;
7a11603d
UD
1922
1923 /* Relocate the main executable. */
2ca285b0 1924 struct relocate_args args = { .l = l,
3a62d00d
AS
1925 .reloc_mode = ((GLRO(dl_lazy)
1926 ? RTLD_LAZY : 0)
1927 | __RTLD_NOIFUNC) };
7a11603d
UD
1928 _dl_receive_error (print_unresolved, relocate_doit, &args);
1929
1930 /* This loop depends on the dependencies of the executable to
1931 correspond in number and order to the DT_NEEDED entries. */
c0f62c56 1932 ElfW(Dyn) *dyn = main_map->l_ld;
7a11603d
UD
1933 bool first = true;
1934 while (dyn->d_tag != DT_NULL)
1935 {
1936 if (dyn->d_tag == DT_NEEDED)
1937 {
1938 l = l->l_next;
7775448e 1939#ifdef NEED_DL_SYSINFO_DSO
ff9f1c5f
DM
1940 /* Skip the VDSO since it's not part of the list
1941 of objects we brought in via DT_NEEDED entries. */
1942 if (l == GLRO(dl_sysinfo_map))
1943 l = l->l_next;
1944#endif
7a11603d
UD
1945 if (!l->l_used)
1946 {
1947 if (first)
1948 {
1949 _dl_printf ("Unused direct dependencies:\n");
1950 first = false;
1951 }
1952
1953 _dl_printf ("\t%s\n", l->l_name);
1954 }
1955 }
1956
1957 ++dyn;
1958 }
1959
1960 _exit (first != true);
1961 }
c0f62c56 1962 else if (! main_map->l_info[DT_NEEDED])
81f3ac4c
UD
1963 _dl_printf ("\tstatically linked\n");
1964 else
1965 {
c0f62c56 1966 for (l = main_map->l_next; l; l = l->l_next)
81f3ac4c
UD
1967 if (l->l_faked)
1968 /* The library was not found. */
1969 _dl_printf ("\t%s => not found\n", l->l_libname->name);
75489693 1970 else if (strcmp (l->l_libname->name, l->l_name) == 0)
7a11603d
UD
1971 _dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
1972 (int) sizeof l->l_map_start * 2,
1973 (size_t) l->l_map_start);
81f3ac4c
UD
1974 else
1975 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1976 l->l_name, (int) sizeof l->l_map_start * 2,
d347a4ab 1977 (size_t) l->l_map_start);
81f3ac4c 1978 }
1a3a58fd 1979
9a821cf9 1980 if (__builtin_expect (mode, trace) != trace)
5a47e7f2 1981 for (i = 1; i < (unsigned int) _dl_argc; ++i)
cddcfecf
RM
1982 {
1983 const ElfW(Sym) *ref = NULL;
c0282c06
UD
1984 ElfW(Addr) loadbase;
1985 lookup_t result;
c0282c06 1986
4243cbea 1987 result = _dl_lookup_symbol_x (_dl_argv[i], main_map,
11bf311e
UD
1988 &ref, main_map->l_scope,
1989 NULL, ELF_RTYPE_CLASS_PLT,
021723ab 1990 DL_LOOKUP_ADD_DEPENDENCY, NULL);
c0282c06 1991
10a446dd 1992 loadbase = LOOKUP_VALUE_ADDRESS (result, false);
c0282c06 1993
35fc382a 1994 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
4243cbea 1995 _dl_argv[i],
d347a4ab
UD
1996 (int) sizeof ref->st_value * 2,
1997 (size_t) ref->st_value,
1998 (int) sizeof loadbase * 2, (size_t) loadbase);
cddcfecf 1999 }
ce37fa88 2000 else
fd26970f 2001 {
20fe49b9 2002 /* If LD_WARN is set, warn about undefined symbols. */
afdca0f2 2003 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
ce37fa88
UD
2004 {
2005 /* We have to do symbol dependency testing. */
2006 struct relocate_args args;
48b67d71 2007 unsigned int i;
993b3242 2008
3a62d00d
AS
2009 args.reloc_mode = ((GLRO(dl_lazy) ? RTLD_LAZY : 0)
2010 | __RTLD_NOIFUNC);
fd26970f 2011
48b67d71
AS
2012 i = main_map->l_searchlist.r_nlist;
2013 while (i-- > 0)
ce37fa88 2014 {
48b67d71 2015 struct link_map *l = main_map->l_initfini[i];
d6b5d570 2016 if (l != &GL(dl_rtld_map) && ! l->l_faked)
ce37fa88
UD
2017 {
2018 args.l = l;
2019 _dl_receive_error (print_unresolved, relocate_doit,
2020 &args);
ce37fa88 2021 }
20fe49b9 2022 }
32e6df36 2023
afdca0f2 2024 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
20fe49b9 2025 && rtld_multiple_ref)
e38c954b
UD
2026 {
2027 /* Mark the link map as not yet relocated again. */
2028 GL(dl_rtld_map).l_relocated = 0;
11bf311e 2029 _dl_relocate_object (&GL(dl_rtld_map),
3a62d00d 2030 main_map->l_scope, __RTLD_NOIFUNC, 0);
e38c954b 2031 }
3a56ea26 2032 }
b0982c4a 2033#define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
120b4c49 2034 if (version_info)
fd26970f 2035 {
ce37fa88
UD
2036 /* Print more information. This means here, print information
2037 about the versions needed. */
2038 int first = 1;
c0f62c56 2039 struct link_map *map;
ce37fa88 2040
c0f62c56 2041 for (map = main_map; map != NULL; map = map->l_next)
fd26970f 2042 {
f41c8091 2043 const char *strtab;
ce37fa88 2044 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
f41c8091
UD
2045 ElfW(Verneed) *ent;
2046
2047 if (dyn == NULL)
2048 continue;
2049
a42195db 2050 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
f41c8091 2051 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
ce37fa88 2052
f41c8091 2053 if (first)
ce37fa88 2054 {
35fc382a 2055 _dl_printf ("\n\tVersion information:\n");
f41c8091
UD
2056 first = 0;
2057 }
ce37fa88 2058
b9375348 2059 _dl_printf ("\t%s:\n", DSO_FILENAME (map->l_name));
f41c8091
UD
2060
2061 while (1)
2062 {
2063 ElfW(Vernaux) *aux;
2064 struct link_map *needed;
ce37fa88 2065
f41c8091
UD
2066 needed = find_needed (strtab + ent->vn_file);
2067 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
ce37fa88
UD
2068
2069 while (1)
2070 {
f41c8091
UD
2071 const char *fname = NULL;
2072
f41c8091 2073 if (needed != NULL
ba9fcb3f
UD
2074 && match_version (strtab + aux->vna_name,
2075 needed))
f41c8091
UD
2076 fname = needed->l_name;
2077
35fc382a
UD
2078 _dl_printf ("\t\t%s (%s) %s=> %s\n",
2079 strtab + ent->vn_file,
2080 strtab + aux->vna_name,
2081 aux->vna_flags & VER_FLG_WEAK
2082 ? "[WEAK] " : "",
2083 fname ?: "not found");
ce37fa88 2084
f41c8091
UD
2085 if (aux->vna_next == 0)
2086 /* No more symbols. */
ce37fa88
UD
2087 break;
2088
f41c8091
UD
2089 /* Next symbol. */
2090 aux = (ElfW(Vernaux) *) ((char *) aux
2091 + aux->vna_next);
ce37fa88 2092 }
f41c8091
UD
2093
2094 if (ent->vn_next == 0)
2095 /* No more dependencies. */
2096 break;
2097
2098 /* Next dependency. */
2099 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
ce37fa88 2100 }
fd26970f 2101 }
ce37fa88 2102 }
fd26970f 2103 }
d66e34cd 2104
0200214b
RM
2105 _exit (0);
2106 }
86d2c878 2107
c0f62c56 2108 if (main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]
768027a4
UD
2109 && ! __builtin_expect (GLRO(dl_profile) != NULL, 0)
2110 && ! __builtin_expect (GLRO(dl_dynamic_weak), 0))
32e6df36
UD
2111 {
2112 ElfW(Lib) *liblist, *liblistend;
2113 struct link_map **r_list, **r_listend, *l;
c0f62c56 2114 const char *strtab = (const void *) D_PTR (main_map, l_info[DT_STRTAB]);
32e6df36 2115
c0f62c56 2116 assert (main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
32e6df36 2117 liblist = (ElfW(Lib) *)
c0f62c56 2118 main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
32e6df36 2119 liblistend = (ElfW(Lib) *)
34a5a146
JM
2120 ((char *) liblist
2121 + main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
c0f62c56
UD
2122 r_list = main_map->l_searchlist.r_list;
2123 r_listend = r_list + main_map->l_searchlist.r_nlist;
32e6df36
UD
2124
2125 for (; r_list < r_listend && liblist < liblistend; r_list++)
2126 {
2127 l = *r_list;
2128
c0f62c56 2129 if (l == main_map)
32e6df36
UD
2130 continue;
2131
2132 /* If the library is not mapped where it should, fail. */
2133 if (l->l_addr)
2134 break;
2135
2136 /* Next, check if checksum matches. */
2137 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
2138 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
2139 != liblist->l_checksum)
2140 break;
2141
2142 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
2143 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
2144 != liblist->l_time_stamp)
2145 break;
2146
2147 if (! _dl_name_match_p (strtab + liblist->l_name, l))
2148 break;
2149
2150 ++liblist;
2151 }
2152
2153
2154 if (r_list == r_listend && liblist == liblistend)
164a7164 2155 prelinked = true;
32e6df36 2156
a1ffb40e 2157 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_LIBS))
b85a0f39
UD
2158 _dl_debug_printf ("\nprelink checking: %s\n",
2159 prelinked ? "ok" : "failed");
32e6df36
UD
2160 }
2161
ed20b3d9 2162
c31e278f 2163 /* Now set up the variable which helps the assembler startup code. */
c0f62c56 2164 GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
c31e278f
UD
2165
2166 /* Save the information about the original global scope list since
2167 we need it in the memory handling later. */
c0f62c56 2168 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
c31e278f 2169
e23fe25b 2170 /* Remember the last search directory added at startup, now that
8e1472d2
FW
2171 malloc will no longer be the one from dl-minimal.c. As a side
2172 effect, this marks ld.so as initialized, so that the rtld_active
2173 function returns true from now on. */
e23fe25b
AS
2174 GLRO(dl_init_all_dirs) = GL(dl_all_dirs);
2175
73d7af4f 2176 /* Print scope information. */
a1ffb40e 2177 if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_SCOPES))
73d7af4f
UD
2178 {
2179 _dl_debug_printf ("\nInitial object scopes\n");
2180
2181 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
174baab3 2182 _dl_show_scope (l, 0);
73d7af4f
UD
2183 }
2184
f753fa7d
L
2185 _rtld_main_check (main_map, _dl_argv[0]);
2186
32e6df36
UD
2187 if (prelinked)
2188 {
c0f62c56 2189 if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
32e6df36
UD
2190 {
2191 ElfW(Rela) *conflict, *conflictend;
32e6df36 2192
1e372ded
AZ
2193 RTLD_TIMING_VAR (start);
2194 rtld_timer_start (&start);
2195
c0f62c56 2196 assert (main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
32e6df36 2197 conflict = (ElfW(Rela) *)
c0f62c56 2198 main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
32e6df36 2199 conflictend = (ElfW(Rela) *)
d89ae1d5 2200 ((char *) conflict
c0f62c56
UD
2201 + main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
2202 _dl_resolve_conflicts (main_map, conflict, conflictend);
1e372ded
AZ
2203
2204 rtld_timer_stop (&relocate_time, start);
32e6df36
UD
2205 }
2206
d89ae1d5
RM
2207
2208 /* Mark all the objects so we know they have been already relocated. */
9dcafc55 2209 for (struct link_map *l = main_map; l != NULL; l = l->l_next)
e8648a5a
UD
2210 {
2211 l->l_relocated = 1;
2212 if (l->l_relro_size)
2213 _dl_protect_relro (l);
9dcafc55
UD
2214
2215 /* Add object to slot information data if necessasy. */
2216 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2217 _dl_add_to_slotinfo (l);
e8648a5a 2218 }
32e6df36
UD
2219 }
2220 else
164a7164
UD
2221 {
2222 /* Now we have all the objects loaded. Relocate them all except for
2223 the dynamic linker itself. We do this in reverse order so that copy
2224 relocs of earlier objects overwrite the data written by later
2225 objects. We do not re-relocate the dynamic linker itself in this
2226 loop because that could result in the GOT entries for functions we
2227 call being changed, and that would break us. It is safe to relocate
2228 the dynamic linker out of order because it has no copy relocs (we
2229 know that because it is self-contained). */
2230
afdca0f2 2231 int consider_profiling = GLRO(dl_profile) != NULL;
c0fb8a56 2232
164a7164 2233 /* If we are profiling we also must do lazy reloaction. */
afdca0f2 2234 GLRO(dl_lazy) |= consider_profiling;
c0fb8a56 2235
1e372ded
AZ
2236 RTLD_TIMING_VAR (start);
2237 rtld_timer_start (&start);
2bc17433
AS
2238 unsigned i = main_map->l_searchlist.r_nlist;
2239 while (i-- > 0)
164a7164 2240 {
2bc17433
AS
2241 struct link_map *l = main_map->l_initfini[i];
2242
164a7164
UD
2243 /* While we are at it, help the memory handling a bit. We have to
2244 mark some data structures as allocated with the fake malloc()
2245 implementation in ld.so. */
2246 struct libname_list *lnp = l->l_libname->next;
752a2a50 2247
164a7164
UD
2248 while (__builtin_expect (lnp != NULL, 0))
2249 {
2250 lnp->dont_free = 1;
2251 lnp = lnp->next;
2252 }
0479b305
AS
2253 /* Also allocated with the fake malloc(). */
2254 l->l_free_initfini = 0;
752a2a50 2255
164a7164 2256 if (l != &GL(dl_rtld_map))
2ca285b0 2257 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy) ? RTLD_LAZY : 0,
154d10bd 2258 consider_profiling);
be935610 2259
9dcafc55
UD
2260 /* Add object to slot information data if necessasy. */
2261 if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2262 _dl_add_to_slotinfo (l);
164a7164 2263 }
1e372ded 2264 rtld_timer_stop (&relocate_time, start);
164a7164 2265
164a7164
UD
2266 /* Now enable profiling if needed. Like the previous call,
2267 this has to go here because the calls it makes should use the
2268 rtld versions of the functions (particularly calloc()), but it
2269 needs to have _dl_profile_map set up by the relocator. */
a1ffb40e 2270 if (__glibc_unlikely (GL(dl_profile_map) != NULL))
164a7164 2271 /* We must prepare the profiling. */
53bfdc1c 2272 _dl_start_profile ();
164a7164 2273 }
ac16e905 2274
d0503676
CD
2275 if ((!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2276 || count_modids != _dl_count_modids ())
35f1e827 2277 ++GL(dl_tls_generation);
9dcafc55 2278
35f1e827
UD
2279 /* Now that we have completed relocation, the initializer data
2280 for the TLS blocks has its final values and we can copy them
91ac3a7d
TMQMF
2281 into the main thread's TLS area, which we allocated above.
2282 Note: thread-local variables must only be accessed after completing
2283 the next step. */
35f1e827 2284 _dl_allocate_tls_init (tcbp);
a334319f 2285
3d8c8bff 2286 /* And finally install it for the main thread. */
35f1e827
UD
2287 if (! tls_init_tp_called)
2288 {
774f9285 2289 const char *lossage = TLS_INIT_TP (tcbp);
a1ffb40e 2290 if (__glibc_unlikely (lossage != NULL))
35f1e827
UD
2291 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2292 lossage);
0ecb606c 2293 }
0ecb606c 2294
e23fe25b
AS
2295 /* Make sure no new search directories have been added. */
2296 assert (GLRO(dl_init_all_dirs) == GL(dl_all_dirs));
bc5fb037 2297
cafdfdb6
RM
2298 if (! prelinked && rtld_multiple_ref)
2299 {
2300 /* There was an explicit ref to the dynamic linker as a shared lib.
2301 Re-relocate ourselves with user-controlled symbol definitions.
2302
2303 We must do this after TLS initialization in case after this
2304 re-relocation, we might call a user-supplied function
2305 (e.g. calloc from _dl_relocate_object) that uses TLS data. */
2306
1e372ded
AZ
2307 RTLD_TIMING_VAR (start);
2308 rtld_timer_start (&start);
cafdfdb6 2309
cafdfdb6
RM
2310 /* Mark the link map as not yet relocated again. */
2311 GL(dl_rtld_map).l_relocated = 0;
c0a777e8 2312 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
1e372ded
AZ
2313
2314 rtld_timer_accum (&relocate_time, start);
cafdfdb6
RM
2315 }
2316
bf8523c8
RM
2317 /* Do any necessary cleanups for the startup OS interface code.
2318 We do these now so that no calls are made after rtld re-relocation
2319 which might be resolved to different functions than we expect.
2320 We cannot do this before relocating the other objects because
2321 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2322 _dl_sysdep_start_cleanup ();
2323
9dcafc55
UD
2324#ifdef SHARED
2325 /* Auditing checkpoint: we have added all objects. */
a1ffb40e 2326 if (__glibc_unlikely (GLRO(dl_naudit) > 0))
9dcafc55
UD
2327 {
2328 struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2329 /* Do not call the functions for any auditing object. */
2330 if (head->l_auditing == 0)
2331 {
2332 struct audit_ifaces *afct = GLRO(dl_audit);
2333 for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2334 {
2335 if (afct->activity != NULL)
2336 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
2337
2338 afct = afct->next;
2339 }
2340 }
2341 }
2342#endif
2343
2344 /* Notify the debugger all new objects are now ready to go. We must re-get
2345 the address since by now the variable might be in another object. */
29f97654 2346 r = _dl_debug_initialize (0, LM_ID_BASE);
9dcafc55 2347 r->r_state = RT_CONSISTENT;
154d10bd 2348 _dl_debug_state ();
815e6fa3 2349 LIBC_PROBE (init_complete, 2, LM_ID_BASE, r);
0200214b 2350
f57f8055 2351#if defined USE_LDCONFIG && !defined MAP_COPY
08cac4ac 2352 /* We must munmap() the cache file. */
154d10bd 2353 _dl_unload_cache ();
08cac4ac
UD
2354#endif
2355
d66e34cd
RM
2356 /* Once we return, _dl_sysdep_start will invoke
2357 the DT_INIT functions and then *USER_ENTRY. */
2358}
fd26970f
UD
2359\f
2360/* This is a little helper function for resolving symbols while
2361 tracing the binary. */
2362static void
c84142e8
UD
2363print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2364 const char *errstring)
fd26970f 2365{
3996f34b 2366 if (objname[0] == '\0')
b9375348 2367 objname = RTLD_PROGNAME;
35fc382a 2368 _dl_error_printf ("%s (%s)\n", errstring, objname);
fd26970f 2369}
c84142e8
UD
2370\f
2371/* This is a little helper function for resolving symbols while
2372 tracing the binary. */
2373static void
2374print_missing_version (int errcode __attribute__ ((unused)),
2375 const char *objname, const char *errstring)
2376{
b9375348 2377 _dl_error_printf ("%s: %s: %s\n", RTLD_PROGNAME,
35fc382a 2378 objname, errstring);
c84142e8 2379}
ea278354 2380\f
7dea968e 2381/* Nonzero if any of the debugging options is enabled. */
392a6b52 2382static int any_debug attribute_relro;
7dea968e 2383
b5efde2f
UD
2384/* Process the string given as the parameter which explains which debugging
2385 options are enabled. */
2386static void
14c44e2e 2387process_dl_debug (const char *dl_debug)
b5efde2f 2388{
3e2040c8
UD
2389 /* When adding new entries make sure that the maximal length of a name
2390 is correctly handled in the LD_DEBUG_HELP code below. */
2391 static const struct
2392 {
379d4ec4
UD
2393 unsigned char len;
2394 const char name[10];
3e2040c8
UD
2395 const char helptext[41];
2396 unsigned short int mask;
2397 } debopts[] =
2398 {
379d4ec4
UD
2399#define LEN_AND_STR(str) sizeof (str) - 1, str
2400 { LEN_AND_STR ("libs"), "display library search paths",
3e2040c8 2401 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
379d4ec4 2402 { LEN_AND_STR ("reloc"), "display relocation processing",
3e2040c8 2403 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
379d4ec4 2404 { LEN_AND_STR ("files"), "display progress for input file",
3e2040c8 2405 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
379d4ec4 2406 { LEN_AND_STR ("symbols"), "display symbol table processing",
3e2040c8 2407 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
379d4ec4 2408 { LEN_AND_STR ("bindings"), "display information about symbol binding",
3e2040c8 2409 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
379d4ec4 2410 { LEN_AND_STR ("versions"), "display version dependencies",
3e2040c8 2411 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
73d7af4f
UD
2412 { LEN_AND_STR ("scopes"), "display scope information",
2413 DL_DEBUG_SCOPES },
379d4ec4 2414 { LEN_AND_STR ("all"), "all previous options combined",
3e2040c8 2415 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
73d7af4f
UD
2416 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS
2417 | DL_DEBUG_SCOPES },
379d4ec4 2418 { LEN_AND_STR ("statistics"), "display relocation statistics",
3e2040c8 2419 DL_DEBUG_STATISTICS },
7a11603d
UD
2420 { LEN_AND_STR ("unused"), "determined unused DSOs",
2421 DL_DEBUG_UNUSED },
379d4ec4 2422 { LEN_AND_STR ("help"), "display this help message and exit",
3e2040c8
UD
2423 DL_DEBUG_HELP },
2424 };
2425#define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
3e2040c8 2426
379d4ec4
UD
2427 /* Skip separating white spaces and commas. */
2428 while (*dl_debug != '\0')
b5efde2f 2429 {
379d4ec4 2430 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
b5efde2f 2431 {
3e2040c8 2432 size_t cnt;
379d4ec4 2433 size_t len = 1;
77aba05b 2434
379d4ec4
UD
2435 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2436 && dl_debug[len] != ',' && dl_debug[len] != ':')
2437 ++len;
14c44e2e 2438
3e2040c8 2439 for (cnt = 0; cnt < ndebopts; ++cnt)
379d4ec4
UD
2440 if (debopts[cnt].len == len
2441 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
3e2040c8 2442 {
afdca0f2 2443 GLRO(dl_debug_mask) |= debopts[cnt].mask;
5688da55 2444 any_debug = 1;
3e2040c8
UD
2445 break;
2446 }
77aba05b 2447
3e2040c8
UD
2448 if (cnt == ndebopts)
2449 {
2450 /* Display a warning and skip everything until next
2451 separator. */
2452 char *copy = strndupa (dl_debug, len);
2453 _dl_error_printf ("\
2454warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
379d4ec4
UD
2455 }
2456
2457 dl_debug += len;
2458 continue;
3e2040c8 2459 }
379d4ec4
UD
2460
2461 ++dl_debug;
3e2040c8 2462 }
77aba05b 2463
ff9f1c5f
DM
2464 if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
2465 {
2466 /* In order to get an accurate picture of whether a particular
2467 DT_NEEDED entry is actually used we have to process both
2468 the PLT and non-PLT relocation entries. */
2469 GLRO(dl_lazy) = 0;
2470 }
2471
afdca0f2 2472 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
3e2040c8
UD
2473 {
2474 size_t cnt;
14c44e2e 2475
3e2040c8
UD
2476 _dl_printf ("\
2477Valid options for the LD_DEBUG environment variable are:\n\n");
db276fa1 2478
3e2040c8 2479 for (cnt = 0; cnt < ndebopts; ++cnt)
37d8b778
UD
2480 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2481 " " + debopts[cnt].len - 3,
3e2040c8 2482 debopts[cnt].helptext);
14c44e2e 2483
3e2040c8
UD
2484 _dl_printf ("\n\
2485To direct the debugging output into a file instead of standard output\n\
2486a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2487 _exit (0);
b5efde2f 2488 }
b5efde2f
UD
2489}
2490\f
9dcafc55
UD
2491static void
2492process_dl_audit (char *str)
2493{
2494 /* The parameter is a colon separated list of DSO names. */
2495 char *p;
2496
2497 while ((p = (strsep) (&str, ":")) != NULL)
81b82fb9 2498 if (dso_name_valid_for_suid (p))
9dcafc55
UD
2499 {
2500 /* This is using the local malloc, not the system malloc. The
2501 memory can never be freed. */
2502 struct audit_list *newp = malloc (sizeof (*newp));
2503 newp->name = p;
2504
2505 if (audit_list == NULL)
2506 audit_list = newp->next = newp;
2507 else
2508 {
2509 newp->next = audit_list->next;
2510 audit_list = audit_list->next = newp;
2511 }
2512 }
2513}
2514\f
ea278354
UD
2515/* Process all environments variables the dynamic linker must recognize.
2516 Since all of them start with `LD_' we are a bit smarter while finding
2517 all the entries. */
9360906d 2518extern char **_environ attribute_hidden;
67c94753 2519
d6b5d570 2520
ea278354 2521static void
ba9fcb3f 2522process_envvars (enum mode *modep)
ea278354 2523{
67c94753 2524 char **runp = _environ;
ea278354
UD
2525 char *envline;
2526 enum mode mode = normal;
7dea968e 2527 char *debug_output = NULL;
ea278354
UD
2528
2529 /* This is the default place for profiling data file. */
afdca0f2 2530 GLRO(dl_profile_output)
6bc6bd3b 2531 = &"/var/tmp\0/var/profile"[__libc_enable_secure ? 9 : 0];
ea278354
UD
2532
2533 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2534 {
379d4ec4
UD
2535 size_t len = 0;
2536
2537 while (envline[len] != '\0' && envline[len] != '=')
2538 ++len;
ea278354 2539
75e8d1f5
UD
2540 if (envline[len] != '=')
2541 /* This is a "LD_" variable at the end of the string without
2542 a '=' character. Ignore it since otherwise we will access
2543 invalid memory below. */
67c94753 2544 continue;
75e8d1f5 2545
67c94753 2546 switch (len)
ea278354 2547 {
14c44e2e
UD
2548 case 4:
2549 /* Warning level, verbose or not. */
67c94753 2550 if (memcmp (envline, "WARN", 4) == 0)
afdca0f2 2551 GLRO(dl_verbose) = envline[5] != '\0';
14c44e2e 2552 break;
ea278354 2553
14c44e2e
UD
2554 case 5:
2555 /* Debugging of the dynamic linker? */
67c94753 2556 if (memcmp (envline, "DEBUG", 5) == 0)
9dcafc55
UD
2557 {
2558 process_dl_debug (&envline[6]);
2559 break;
2560 }
2561 if (memcmp (envline, "AUDIT", 5) == 0)
81b82fb9 2562 audit_list_string = &envline[6];
14c44e2e 2563 break;
b5efde2f 2564
14c44e2e
UD
2565 case 7:
2566 /* Print information about versions. */
67c94753 2567 if (memcmp (envline, "VERBOSE", 7) == 0)
14c44e2e 2568 {
67c94753 2569 version_info = envline[8] != '\0';
14c44e2e
UD
2570 break;
2571 }
7dea968e 2572
14c44e2e 2573 /* List of objects to be preloaded. */
67c94753 2574 if (memcmp (envline, "PRELOAD", 7) == 0)
14c44e2e 2575 {
67c94753 2576 preloadlist = &envline[8];
14c44e2e
UD
2577 break;
2578 }
120b4c49 2579
14c44e2e 2580 /* Which shared object shall be profiled. */
c95f3fd4 2581 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
afdca0f2 2582 GLRO(dl_profile) = &envline[8];
14c44e2e 2583 break;
120b4c49 2584
14c44e2e
UD
2585 case 8:
2586 /* Do we bind early? */
67c94753 2587 if (memcmp (envline, "BIND_NOW", 8) == 0)
f53c03c2 2588 {
afdca0f2 2589 GLRO(dl_lazy) = envline[9] == '\0';
f53c03c2
UD
2590 break;
2591 }
67c94753 2592 if (memcmp (envline, "BIND_NOT", 8) == 0)
afdca0f2 2593 GLRO(dl_bind_not) = envline[9] != '\0';
14c44e2e 2594 break;
ea278354 2595
14c44e2e
UD
2596 case 9:
2597 /* Test whether we want to see the content of the auxiliary
2598 array passed up from the kernel. */
6bc6bd3b 2599 if (!__libc_enable_secure
00a12162 2600 && memcmp (envline, "SHOW_AUXV", 9) == 0)
14c44e2e
UD
2601 _dl_show_auxv ();
2602 break;
ea278354 2603
ff08fc59 2604#if !HAVE_TUNABLES
12264bd7 2605 case 10:
3081378b 2606 /* Mask for the important hardware capabilities. */
1c1243b6
SP
2607 if (!__libc_enable_secure
2608 && memcmp (envline, "HWCAP_MASK", 10) == 0)
37b66c0b 2609 GLRO(dl_hwcap_mask) = _dl_strtoul (&envline[11], NULL);
12264bd7 2610 break;
ff08fc59 2611#endif
12264bd7 2612
f787edde
UD
2613 case 11:
2614 /* Path where the binary is found. */
6bc6bd3b 2615 if (!__libc_enable_secure
67c94753 2616 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
afdca0f2 2617 GLRO(dl_origin_path) = &envline[12];
f787edde
UD
2618 break;
2619
14c44e2e 2620 case 12:
dec126b4 2621 /* The library search path. */
f6110a8f
FW
2622 if (!__libc_enable_secure
2623 && memcmp (envline, "LIBRARY_PATH", 12) == 0)
dec126b4 2624 {
67c94753 2625 library_path = &envline[13];
dec126b4
UD
2626 break;
2627 }
2628
14c44e2e 2629 /* Where to place the profiling data file. */
67c94753 2630 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
14c44e2e 2631 {
67c94753 2632 debug_output = &envline[13];
14c44e2e
UD
2633 break;
2634 }
ea278354 2635
6bc6bd3b 2636 if (!__libc_enable_secure
00a12162 2637 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
afdca0f2 2638 GLRO(dl_dynamic_weak) = 1;
14c44e2e 2639 break;
ea278354 2640
97fd3a30
UD
2641 case 13:
2642 /* We might have some extra environment variable with length 13
2643 to handle. */
2644#ifdef EXTRA_LD_ENVVARS_13
2645 EXTRA_LD_ENVVARS_13
2646#endif
6bc6bd3b 2647 if (!__libc_enable_secure
97fd3a30 2648 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
827b7087
UD
2649 {
2650 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2651 break;
2652 }
97fd3a30
UD
2653 break;
2654
14c44e2e
UD
2655 case 14:
2656 /* Where to place the profiling data file. */
6bc6bd3b 2657 if (!__libc_enable_secure
3e2040c8
UD
2658 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2659 && envline[15] != '\0')
afdca0f2 2660 GLRO(dl_profile_output) = &envline[15];
14c44e2e 2661 break;
120b4c49 2662
32e6df36
UD
2663 case 16:
2664 /* The mode of the dynamic linker can be set. */
2665 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2666 {
2667 mode = trace;
afdca0f2
UD
2668 GLRO(dl_verbose) = 1;
2669 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2670 GLRO(dl_trace_prelink) = &envline[17];
32e6df36
UD
2671 }
2672 break;
2673
14c44e2e
UD
2674 case 20:
2675 /* The mode of the dynamic linker can be set. */
67c94753 2676 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
14c44e2e
UD
2677 mode = trace;
2678 break;
e2102c14
UD
2679
2680 /* We might have some extra environment variable to handle. This
2681 is tricky due to the pre-processing of the length of the name
2682 in the switch statement here. The code here assumes that added
2683 environment variables have a different length. */
2684#ifdef EXTRA_LD_ENVVARS
2685 EXTRA_LD_ENVVARS
2686#endif
ea278354
UD
2687 }
2688 }
2689
3e2040c8
UD
2690 /* The caller wants this information. */
2691 *modep = mode;
2692
4bae5567
UD
2693 /* Extra security for SUID binaries. Remove all dangerous environment
2694 variables. */
6bc6bd3b 2695 if (__builtin_expect (__libc_enable_secure, 0))
4bae5567 2696 {
c95f3fd4 2697 static const char unsecure_envvars[] =
4bae5567
UD
2698#ifdef EXTRA_UNSECURE_ENVVARS
2699 EXTRA_UNSECURE_ENVVARS
2700#endif
c95f3fd4
UD
2701 UNSECURE_ENVVARS;
2702 const char *nextp;
2703
2704 nextp = unsecure_envvars;
2705 do
2706 {
2707 unsetenv (nextp);
9710f75d
UD
2708 /* We could use rawmemchr but this need not be fast. */
2709 nextp = (char *) (strchr) (nextp, '\0') + 1;
c95f3fd4
UD
2710 }
2711 while (*nextp != '\0');
74955460
UD
2712
2713 if (__access ("/etc/suid-debug", F_OK) != 0)
3a56ea26 2714 {
67e58f39 2715#if !HAVE_TUNABLES
00a12162 2716 unsetenv ("MALLOC_CHECK_");
67e58f39 2717#endif
f57a3c94 2718 GLRO(dl_debug_mask) = 0;
3a56ea26 2719 }
f57a3c94
RM
2720
2721 if (mode != normal)
2722 _exit (5);
4bae5567 2723 }
7dea968e
UD
2724 /* If we have to run the dynamic linker in debugging mode and the
2725 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2726 messages to this file. */
3e2040c8 2727 else if (any_debug && debug_output != NULL)
7dea968e 2728 {
5f2de337 2729 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
7a2fd787
UD
2730 size_t name_len = strlen (debug_output);
2731 char buf[name_len + 12];
2732 char *startp;
2733
2734 buf[name_len + 11] = '\0';
9710f75d 2735 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
7a2fd787
UD
2736 *--startp = '.';
2737 startp = memcpy (startp - name_len, debug_output, name_len);
2738
329ea513 2739 GLRO(dl_debug_fd) = __open64_nocancel (startp, flags, DEFFILEMODE);
dd70526e 2740 if (GLRO(dl_debug_fd) == -1)
7dea968e 2741 /* We use standard output if opening the file failed. */
dd70526e 2742 GLRO(dl_debug_fd) = STDOUT_FILENO;
7dea968e 2743 }
ea278354 2744}
db276fa1 2745
1e372ded
AZ
2746#if HP_TIMING_INLINE
2747static void
2748print_statistics_item (const char *title, hp_timing_t time,
2749 hp_timing_t total)
2750{
2751 char cycles[HP_TIMING_PRINT_SIZE];
2752 HP_TIMING_PRINT (cycles, sizeof (cycles), time);
2753
2754 char relative[3 * sizeof (hp_timing_t) + 2];
2755 char *cp = _itoa ((1000ULL * time) / total, relative + sizeof (relative),
2756 10, 0);
2757 /* Sets the decimal point. */
2758 char *wp = relative;
2759 switch (relative + sizeof (relative) - cp)
2760 {
2761 case 3:
2762 *wp++ = *cp++;
2763 /* Fall through. */
2764 case 2:
2765 *wp++ = *cp++;
2766 /* Fall through. */
2767 case 1:
2768 *wp++ = '.';
2769 *wp++ = *cp++;
2770 }
2771 *wp = '\0';
2772 _dl_debug_printf ("%s: %s cycles (%s%%)\n", title, cycles, relative);
2773}
2774#endif
db276fa1
UD
2775
2776/* Print the various times we collected. */
2777static void
ee600e3f 2778__attribute ((noinline))
1e372ded 2779print_statistics (const hp_timing_t *rtld_total_timep)
db276fa1 2780{
1e372ded
AZ
2781#if HP_TIMING_INLINE
2782 {
2783 char cycles[HP_TIMING_PRINT_SIZE];
2784 HP_TIMING_PRINT (cycles, sizeof (cycles), *rtld_total_timep);
2785 _dl_debug_printf ("\nruntime linker statistics:\n"
2786 " total startup time in dynamic loader: %s cycles\n",
2787 cycles);
2788 print_statistics_item (" time needed for relocation",
2789 relocate_time, *rtld_total_timep);
2790 }
1531e094 2791#endif
a21a20a3
UD
2792
2793 unsigned long int num_relative_relocations = 0;
22c83193 2794 for (Lmid_t ns = 0; ns < GL(dl_nns); ++ns)
a21a20a3 2795 {
c120d94d
UD
2796 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2797 continue;
2798
c0f62c56 2799 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
a21a20a3 2800
c0f62c56
UD
2801 for (unsigned int i = 0; i < scope->r_nlist; i++)
2802 {
2803 struct link_map *l = scope->r_list [i];
2804
c120d94d 2805 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
c0f62c56
UD
2806 num_relative_relocations
2807 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
c120d94d
UD
2808#ifndef ELF_MACHINE_REL_RELATIVE
2809 /* Relative relocations are processed on these architectures if
2810 library is loaded to different address than p_vaddr or
2811 if not prelinked. */
2812 if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2813 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2814#else
2815 /* On e.g. IA-64 or Alpha, relative relocations are processed
2816 only if library is loaded to different address than p_vaddr. */
2817 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2818#endif
c0f62c56
UD
2819 num_relative_relocations
2820 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2821 }
a21a20a3
UD
2822 }
2823
42af49f8
UD
2824 _dl_debug_printf (" number of relocations: %lu\n"
2825 " number of relocations from cache: %lu\n"
2826 " number of relative relocations: %lu\n",
2827 GL(dl_num_relocations),
2828 GL(dl_num_cache_relocations),
154d10bd 2829 num_relative_relocations);
db276fa1 2830
1e372ded
AZ
2831#if HP_TIMING_INLINE
2832 print_statistics_item (" time needed to load objects",
2833 load_time, *rtld_total_timep);
1531e094 2834#endif
db276fa1 2835}