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