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