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