1
/* Run time dynamic linker.
2
Copyright (C) 1995-2012 Free Software Foundation, Inc.
3
This file is part of the GNU C Library.
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.
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.
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/>. */
19
#include <gnu/option-groups.h>
28
#include <sys/param.h>
33
#include <fpu_control.h>
34
#include <hp-timing.h>
35
#include <bits/libc-lock.h>
36
#include "dynamic-link.h"
37
#include <dl-librecon.h>
38
#include <unsecvars.h>
40
#include <dl-osinfo.h>
41
#include <dl-procinfo.h>
43
#include <stackinfo.h>
47
/* Avoid PLT use for our local calls at startup. */
48
extern __typeof (__mempcpy) __mempcpy attribute_hidden;
50
/* GCC has mental blocks about _exit. */
51
extern __typeof (_exit) exit_internal asm ("_exit") attribute_hidden;
52
#define _exit exit_internal
54
/* Helper function to handle errors while resolving symbols. */
55
static void print_unresolved (int errcode, const char *objname,
56
const char *errsting);
58
/* Helper function to handle errors when a version is missing. */
59
static void print_missing_version (int errcode, const char *objname,
60
const char *errsting);
62
/* Print the various times we collected. */
63
static void print_statistics (hp_timing_t *total_timep);
65
/* Add audit objects. */
66
static void process_dl_audit (char *str);
68
/* This is a list of all the modes the dynamic loader can be in. */
69
enum mode { normal, list, verify, trace };
71
/* Process all environments variables the dynamic linker must recognize.
72
Since all of them start with `LD_' we are a bit smarter while finding
74
static void process_envvars (enum mode *modep);
76
#ifdef DL_ARGV_NOT_RELRO
77
int _dl_argc attribute_hidden;
78
char **_dl_argv = NULL;
79
/* Nonzero if we were run directly. */
80
unsigned int _dl_skip_args attribute_hidden;
82
int _dl_argc attribute_relro attribute_hidden;
83
char **_dl_argv attribute_relro = NULL;
84
unsigned int _dl_skip_args attribute_relro attribute_hidden;
88
#ifndef THREAD_SET_STACK_GUARD
89
/* Only exported for architectures that don't store the stack guard canary
90
in thread local area. */
91
uintptr_t __stack_chk_guard attribute_relro;
94
/* Only exported for architectures that don't store the pointer guard
95
value in thread local area. */
96
uintptr_t __pointer_chk_guard_local
97
attribute_relro attribute_hidden __attribute__ ((nocommon));
98
#ifndef THREAD_SET_POINTER_GUARD
99
strong_alias (__pointer_chk_guard_local, __pointer_chk_guard)
103
/* List of auditing DSOs. */
104
static struct audit_list
107
struct audit_list *next;
110
#ifndef HAVE_INLINED_SYSCALLS
111
/* Set nonzero during loading and initialization of executable and
112
libraries, cleared before the executable's entry point runs. This
113
must not be initialized to nonzero, because the unused dynamic
114
linker loaded in for libc.so's "ld.so.1" dep will provide the
115
definition seen by libc.so's initializer; that value must be zero,
116
and will be since that dynamic linker's _dl_start and dl_main will
118
int _dl_starting_up = 0;
119
INTVARDEF(_dl_starting_up)
122
/* This is the structure which defines all variables global to ld.so
123
(except those which cannot be added for some reason). */
124
struct rtld_global _rtld_global =
126
/* Generally the default presumption without further information is an
127
* executable stack but this is not true for all platforms. */
128
._dl_stack_flags = DEFAULT_STACK_PERMS,
129
#ifdef _LIBC_REENTRANT
130
._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
131
._dl_load_write_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER,
136
[LM_ID_BASE] = { ._ns_unique_sym_table
137
= { .lock = _RTLD_LOCK_RECURSIVE_INITIALIZER } }
140
/* If we would use strong_alias here the compiler would see a
141
non-hidden definition. This would undo the effect of the previous
142
declaration. So spell out was strong_alias does plus add the
143
visibility attribute. */
144
extern struct rtld_global _rtld_local
145
__attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
148
/* This variable is similar to _rtld_local, but all values are
149
read-only after relocation. */
150
struct rtld_global_ro _rtld_global_ro attribute_relro =
152
/* Get architecture specific initializer. */
153
#include <dl-procinfo.c>
154
#ifdef NEED_DL_SYSINFO
155
._dl_sysinfo = DL_SYSINFO_DEFAULT,
158
/* GNU/Hurd needs this because otherwise libpthread's pthread_mutex_lock gets
159
* * overridden by libX11's stubs. */
160
._dl_dynamic_weak = 1,
162
._dl_debug_fd = STDERR_FILENO,
163
._dl_use_load_bias = -2,
164
._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
165
._dl_hwcap_mask = HWCAP_IMPORTANT,
167
._dl_fpu_control = _FPU_DEFAULT,
168
._dl_pointer_guard = 1,
169
._dl_pagesize = EXEC_PAGESIZE,
170
._dl_inhibit_cache = 0,
172
/* Function pointers. */
173
._dl_debug_printf = _dl_debug_printf,
174
._dl_catch_error = _dl_catch_error,
175
._dl_signal_error = _dl_signal_error,
176
._dl_mcount = _dl_mcount_internal,
177
._dl_lookup_symbol_x = _dl_lookup_symbol_x,
178
._dl_check_caller = _dl_check_caller,
179
._dl_open = _dl_open,
180
._dl_close = _dl_close,
181
._dl_tls_get_addr_soft = _dl_tls_get_addr_soft,
182
#ifdef HAVE_DL_DISCOVER_OSVERSION
183
._dl_discover_osversion = _dl_discover_osversion
186
/* If we would use strong_alias here the compiler would see a
187
non-hidden definition. This would undo the effect of the previous
188
declaration. So spell out was strong_alias does plus add the
189
visibility attribute. */
190
extern struct rtld_global_ro _rtld_local_ro
191
__attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
194
static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
195
ElfW(Addr) *user_entry, ElfW(auxv_t) *auxv);
197
/* These two variables cannot be moved into .data.rel.ro. */
198
static struct libname_list _dl_rtld_libname;
199
static struct libname_list _dl_rtld_libname2;
201
/* We expect less than a second for relocation. */
202
#ifdef HP_SMALL_TIMING_AVAIL
203
# undef HP_TIMING_AVAIL
204
# define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
207
/* Variable for statistics. */
208
#ifndef HP_TIMING_NONAVAIL
209
static hp_timing_t relocate_time;
210
static hp_timing_t load_time attribute_relro;
211
static hp_timing_t start_time attribute_relro;
214
/* Additional definitions needed by TLS initialization. */
215
#ifdef TLS_INIT_HELPER
219
/* Helper function for syscall implementation. */
220
#ifdef DL_SYSINFO_IMPLEMENTATION
221
DL_SYSINFO_IMPLEMENTATION
224
/* Before ld.so is relocated we must not access variables which need
225
relocations. This means variables which are exported. Variables
226
declared as static are fine. If we can mark a variable hidden this
227
is fine, too. The latter is important here. We can avoid setting
228
up a temporary link map for ld.so if we can mark _rtld_global as
230
#ifdef PI_STATIC_AND_HIDDEN
231
# define DONT_USE_BOOTSTRAP_MAP 1
234
#ifdef DONT_USE_BOOTSTRAP_MAP
235
static ElfW(Addr) _dl_start_final (void *arg);
237
struct dl_start_final_info
240
#if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
241
hp_timing_t start_time;
244
static ElfW(Addr) _dl_start_final (void *arg,
245
struct dl_start_final_info *info);
248
/* These defined magically in the linker script. */
249
extern char _begin[] attribute_hidden;
250
extern char _etext[] attribute_hidden;
251
extern char _end[] attribute_hidden;
257
# error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
261
# define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
262
+ DT_EXTRANUM + DT_VALTAGIDX (tag))
265
# define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
266
+ DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
269
/* This is the second half of _dl_start (below). It can be inlined safely
270
under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
271
references. When the tools don't permit us to avoid using a GOT entry
272
for _dl_rtld_global (no attribute_hidden support), we must make sure
273
this function is not inlined (see below). */
275
#ifdef DONT_USE_BOOTSTRAP_MAP
276
static inline ElfW(Addr) __attribute__ ((always_inline))
277
_dl_start_final (void *arg)
279
static ElfW(Addr) __attribute__ ((noinline))
280
_dl_start_final (void *arg, struct dl_start_final_info *info)
283
ElfW(Addr) start_addr;
287
/* If it hasn't happen yet record the startup time. */
288
if (! HP_TIMING_INLINE)
289
HP_TIMING_NOW (start_time);
290
#if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
292
start_time = info->start_time;
295
/* Initialize the timing functions. */
296
HP_TIMING_DIFF_INIT ();
299
/* Transfer data about ourselves to the permanent link_map structure. */
300
#ifndef DONT_USE_BOOTSTRAP_MAP
301
GL(dl_rtld_map).l_addr = info->l.l_addr;
302
GL(dl_rtld_map).l_ld = info->l.l_ld;
303
memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
304
sizeof GL(dl_rtld_map).l_info);
305
GL(dl_rtld_map).l_mach = info->l.l_mach;
306
GL(dl_rtld_map).l_relocated = 1;
308
_dl_setup_hash (&GL(dl_rtld_map));
309
GL(dl_rtld_map).l_real = &GL(dl_rtld_map);
310
GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
311
GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
312
GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
313
/* Copy the TLS related data if necessary. */
314
#ifndef DONT_USE_BOOTSTRAP_MAP
316
assert (info->l.l_tls_modid != 0);
317
GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
318
GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
319
GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
320
GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
321
GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
322
GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
323
GL(dl_rtld_map).l_tls_modid = 1;
325
# if NO_TLS_OFFSET != 0
326
GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
333
HP_TIMING_NOW (GL(dl_cpuclock_offset));
336
/* Initialize the stack end variable. */
337
__libc_stack_end = __builtin_frame_address (0);
339
/* Call the OS-dependent function to set up life so we can do things like
340
file access. It will call `dl_main' (below) to do all the real work
341
of the dynamic linker, and then unwind our frame and run the user
342
entry point on the same stack we entered on. */
343
start_addr = _dl_sysdep_start (arg, &dl_main);
345
#ifndef HP_TIMING_NONAVAIL
346
hp_timing_t rtld_total_time;
349
hp_timing_t end_time;
351
/* Get the current time. */
352
HP_TIMING_NOW (end_time);
354
/* Compute the difference. */
355
HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
359
if (__builtin_expect (GLRO_dl_debug_mask & DL_DEBUG_STATISTICS, 0))
361
#ifndef HP_TIMING_NONAVAIL
362
print_statistics (&rtld_total_time);
364
print_statistics (NULL);
371
static ElfW(Addr) __attribute_used__ internal_function
372
_dl_start (void *arg)
374
#ifdef DONT_USE_BOOTSTRAP_MAP
375
# define bootstrap_map GL(dl_rtld_map)
377
struct dl_start_final_info info;
378
# define bootstrap_map info.l
381
/* This #define produces dynamic linking inline functions for
382
bootstrap relocation instead of general-purpose relocation.
383
Since ld.so must not have any undefined symbols the result
384
is trivial: always the map of ld.so itself. */
385
#define RTLD_BOOTSTRAP
386
#define RESOLVE_MAP(sym, version, flags) (&bootstrap_map)
387
#include "dynamic-link.h"
389
if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
390
#ifdef DONT_USE_BOOTSTRAP_MAP
391
HP_TIMING_NOW (start_time);
393
HP_TIMING_NOW (info.start_time);
396
/* Partly clean the `bootstrap_map' structure up. Don't use
397
`memset' since it might not be built in or inlined and we cannot
398
make function calls at this point. Use '__builtin_memset' if we
399
know it is available. We do not have to clear the memory if we
400
do not have to use the temporary bootstrap_map. Global variables
401
are initialized to zero by default. */
402
#if !defined DONT_USE_BOOTSTRAP_MAP
403
# ifdef HAVE_BUILTIN_MEMSET
404
__builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
406
/* Clear the whole bootstrap_map structure */
407
for (char *cnt = (char *)&(bootstrap_map);
408
cnt < ((char *)&(bootstrap_map) + sizeof (bootstrap_map));
412
bootstrap_map.l_tls_modid = 0;
416
/* Figure out the run-time load address of the dynamic linker itself. */
417
bootstrap_map.l_addr = elf_machine_load_address ();
419
/* Read our own dynamic section and fill in the info array. */
420
bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
421
elf_get_dynamic_info (&bootstrap_map, NULL);
423
#if NO_TLS_OFFSET != 0
424
bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
427
/* Get the dynamic linker's own program header. First we need the ELF
428
file header. The `_begin' symbol created by the linker script points
429
to it. When we have something like GOTOFF relocs, we can use a plain
430
reference to find the runtime address. Without that, we have to rely
431
on the `l_addr' value, which is not the value we want when prelinked. */
435
# ifdef DONT_USE_BOOTSTRAP_MAP
436
= (ElfW(Ehdr) *) &_begin;
438
# error This will not work with prelink.
439
= (ElfW(Ehdr) *) bootstrap_map.l_addr;
441
ElfW(Phdr) *phdr = (ElfW(Phdr) *) ((void *) ehdr + ehdr->e_phoff);
442
size_t cnt = ehdr->e_phnum; /* PT_TLS is usually the last phdr. */
444
if (phdr[cnt].p_type == PT_TLS)
447
size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
450
bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
451
bootstrap_map.l_tls_align = phdr[cnt].p_align;
452
if (phdr[cnt].p_align == 0)
453
bootstrap_map.l_tls_firstbyte_offset = 0;
455
bootstrap_map.l_tls_firstbyte_offset = (phdr[cnt].p_vaddr
456
& (phdr[cnt].p_align - 1));
457
assert (bootstrap_map.l_tls_blocksize != 0);
458
bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
459
bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
460
+ phdr[cnt].p_vaddr);
462
/* We can now allocate the initial TLS block. This can happen
463
on the stack. We'll get the final memory later when we
464
know all about the various objects loaded at startup
467
tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
472
tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
473
bootstrap_map.l_tls_align)
474
+ bootstrap_map.l_tls_blocksize
477
/* In case a model with a different layout for the TCB and DTV
478
is defined add another #elif here and in the following #ifs. */
479
# error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
481
/* Align the TLS block. */
482
tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
485
/* Initialize the dtv. [0] is the length, [1] the generation
487
initdtv[0].counter = 1;
488
initdtv[1].counter = 0;
490
/* Initialize the TLS block. */
492
initdtv[2].pointer = tlsblock;
494
bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
495
bootstrap_map.l_tls_align);
496
initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
498
# error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
500
p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
501
bootstrap_map.l_tls_initimage_size);
502
# ifdef HAVE_BUILTIN_MEMSET
503
__builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
504
- bootstrap_map.l_tls_initimage_size));
507
size_t remaining = (bootstrap_map.l_tls_blocksize
508
- bootstrap_map.l_tls_initimage_size);
509
while (remaining-- > 0)
514
/* Install the pointer to the dtv. */
516
/* Initialize the thread pointer. */
518
bootstrap_map.l_tls_offset
519
= roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
521
INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
524
const char *lossage = TLS_INIT_TP ((char *) tlsblock
525
+ bootstrap_map.l_tls_offset, 0);
527
INSTALL_DTV (tlsblock, initdtv);
528
const char *lossage = TLS_INIT_TP (tlsblock, 0);
530
# error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
532
if (__builtin_expect (lossage != NULL, 0))
533
_dl_fatal_printf ("cannot set up thread-local storage: %s\n",
536
/* So far this is module number one. */
537
bootstrap_map.l_tls_modid = 1;
539
/* There can only be one PT_TLS entry. */
542
#endif /* USE___THREAD */
544
#ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
545
ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
548
if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
550
/* Relocate ourselves so we can do normal function calls and
551
data access using the global offset table. */
553
ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0, 0);
555
bootstrap_map.l_relocated = 1;
557
/* Please note that we don't allow profiling of this object and
558
therefore need not test whether we have to allocate the array
559
for the relocation results (as done in dl-reloc.c). */
561
/* Now life is sane; we can call functions and access global data.
562
Set up to use the operating system facilities, and find out from
563
the operating system's program loader where to find the program
564
header table in core. Put the rest of _dl_start into a separate
565
function, that way the compiler cannot put accesses to the GOT
566
before ELF_DYNAMIC_RELOCATE. */
568
#ifdef DONT_USE_BOOTSTRAP_MAP
569
ElfW(Addr) entry = _dl_start_final (arg);
571
ElfW(Addr) entry = _dl_start_final (arg, &info);
574
#ifndef ELF_MACHINE_START_ADDRESS
575
# define ELF_MACHINE_START_ADDRESS(map, start) (start)
578
return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, entry);
584
/* Now life is peachy; we can do all normal operations.
585
On to the real work. */
587
/* Some helper functions. */
589
/* Arguments to relocate_doit. */
598
/* Argument to map_doit. */
600
struct link_map *loader;
602
/* Return value of map_doit. */
603
struct link_map *map;
609
struct link_map *map;
615
struct link_map *map;
619
/* Arguments to version_check_doit. */
620
struct version_check_args
627
relocate_doit (void *a)
629
struct relocate_args *args = (struct relocate_args *) a;
631
_dl_relocate_object (args->l, args->l->l_scope, args->reloc_mode, 0);
637
struct map_args *args = (struct map_args *) a;
638
args->map = _dl_map_object (args->loader, args->str, lt_library, 0,
639
args->mode, LM_ID_BASE);
643
dlmopen_doit (void *a)
645
struct dlmopen_args *args = (struct dlmopen_args *) a;
646
args->map = _dl_open (args->fname,
647
(RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT
649
dl_main, LM_ID_NEWLM, _dl_argc, INTUSE(_dl_argv),
654
lookup_doit (void *a)
656
struct lookup_args *args = (struct lookup_args *) a;
657
const ElfW(Sym) *ref = NULL;
659
lookup_t l = _dl_lookup_symbol_x (args->name, args->map, &ref,
660
args->map->l_local_scope, NULL, 0,
661
DL_LOOKUP_RETURN_NEWEST, NULL);
663
args->result = DL_SYMBOL_ADDRESS (l, ref);
667
version_check_doit (void *a)
669
struct version_check_args *args = (struct version_check_args *) a;
670
if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
671
args->dotrace) && args->doexit)
672
/* We cannot start the application. Abort now. */
677
static inline struct link_map *
678
find_needed (const char *name)
680
struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
681
unsigned int n = scope->r_nlist;
684
if (_dl_name_match_p (name, scope->r_list[n]))
685
return scope->r_list[n];
687
/* Should never happen. */
692
match_version (const char *string, struct link_map *map)
694
const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
697
#define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
698
if (map->l_info[VERDEFTAG] == NULL)
699
/* The file has no symbol versioning. */
702
def = (ElfW(Verdef) *) ((char *) map->l_addr
703
+ map->l_info[VERDEFTAG]->d_un.d_ptr);
706
ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
708
/* Compare the version strings. */
709
if (strcmp (string, strtab + aux->vda_name) == 0)
713
/* If no more definitions we failed to find what we want. */
714
if (def->vd_next == 0)
717
/* Next definition. */
718
def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
724
static bool tls_init_tp_called;
729
/* Number of elements in the static TLS block. */
730
GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
732
/* Do not do this twice. The audit interface might have required
733
the DTV interfaces to be set up early. */
734
if (GL(dl_initial_dtv) != NULL)
737
/* Allocate the array which contains the information about the
738
dtv slots. We allocate a few entries more than needed to
739
avoid the need for reallocation. */
740
size_t nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
743
GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
744
calloc (sizeof (struct dtv_slotinfo_list)
745
+ nelem * sizeof (struct dtv_slotinfo), 1);
746
/* No need to check the return value. If memory allocation failed
747
the program would have been terminated. */
749
struct dtv_slotinfo *slotinfo = GL(dl_tls_dtv_slotinfo_list)->slotinfo;
750
GL(dl_tls_dtv_slotinfo_list)->len = nelem;
751
GL(dl_tls_dtv_slotinfo_list)->next = NULL;
753
/* Fill in the information from the loaded modules. No namespace
754
but the base one can be filled at this time. */
755
assert (GL(dl_ns)[LM_ID_BASE + 1]._ns_loaded == NULL);
757
for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
759
if (l->l_tls_blocksize != 0)
761
/* This is a module with TLS data. Store the map reference.
762
The generation counter is zero. */
764
/* slotinfo[i].gen = 0; */
767
assert (i == GL(dl_tls_max_dtv_idx));
769
/* Compute the TLS offsets for the various blocks. */
770
_dl_determine_tlsoffset ();
772
/* Construct the static TLS block and the dtv for the initial
773
thread. For some platforms this will include allocating memory
774
for the thread descriptor. The memory for the TLS block will
775
never be freed. It should be allocated accordingly. The dtv
776
array can be changed if dynamic loading requires it. */
777
void *tcbp = _dl_allocate_tls_storage ();
780
cannot allocate TLS data structures for initial thread");
782
/* Store for detection of the special case by __tls_get_addr
783
so it knows not to pass this dtv to the normal realloc. */
784
GL(dl_initial_dtv) = GET_DTV (tcbp);
786
/* And finally install it for the main thread. If ld.so itself uses
787
TLS we know the thread pointer was initialized earlier. */
790
= TLS_INIT_TP (tcbp, USE___THREAD);
792
= TLS_INIT_TP (tcbp, 0);
794
if (__builtin_expect (lossage != NULL, 0))
795
_dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
796
tls_init_tp_called = true;
801
#ifdef _LIBC_REENTRANT
802
/* _dl_error_catch_tsd points to this for the single-threaded case.
803
It's reset by the thread library for multithreaded programs. */
804
void ** __attribute__ ((const))
805
_dl_initial_error_catch_tsd (void)
814
do_preload (char *fname, struct link_map *main_map, const char *where)
817
const char *err_str = NULL;
818
struct map_args args;
822
args.loader = main_map;
823
args.mode = __RTLD_SECURE;
825
unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
827
(void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
828
if (__builtin_expect (err_str != NULL, 0))
831
ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
833
/* No need to call free, this is still before
834
the libc's malloc is used. */
836
else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
837
/* It is no duplicate. */
840
/* Nothing loaded. */
844
#if defined SHARED && defined _LIBC_REENTRANT \
845
&& defined __rtld_lock_default_lock_recursive
847
rtld_lock_default_lock_recursive (void *lock)
849
__rtld_lock_default_lock_recursive (lock);
853
rtld_lock_default_unlock_recursive (void *lock)
855
__rtld_lock_default_unlock_recursive (lock);
863
/* Set up the stack checker's canary. */
864
uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard (_dl_random);
865
#ifdef THREAD_SET_STACK_GUARD
866
THREAD_SET_STACK_GUARD (stack_chk_guard);
868
__stack_chk_guard = stack_chk_guard;
871
/* Set up the pointer guard as well, if necessary. */
872
if (GLRO(dl_pointer_guard))
874
uintptr_t pointer_chk_guard = _dl_setup_pointer_guard (_dl_random,
876
#ifdef THREAD_SET_POINTER_GUARD
877
THREAD_SET_POINTER_GUARD (pointer_chk_guard);
879
__pointer_chk_guard_local = pointer_chk_guard;
882
/* We do not need the _dl_random value anymore. The less
883
information we leave behind, the better, so clear the
889
/* The library search path. */
890
static const char *library_path attribute_relro;
891
/* The list preloaded objects. */
892
static const char *preloadlist attribute_relro;
893
/* Nonzero if information about versions has to be printed. */
894
static int version_info attribute_relro;
897
dl_main (const ElfW(Phdr) *phdr,
899
ElfW(Addr) *user_entry,
902
const ElfW(Phdr) *ph;
904
struct link_map *main_map;
907
bool has_interp = false;
909
bool prelinked = false;
910
bool rtld_is_main = false;
911
#ifndef HP_TIMING_NONAVAIL
918
#ifdef _LIBC_REENTRANT
919
/* Explicit initialization since the reloc would just be more work. */
920
GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
923
GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
925
#if defined SHARED && defined _LIBC_REENTRANT \
926
&& defined __rtld_lock_default_lock_recursive
927
GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
928
GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
931
/* The explicit initialization here is cheaper than processing the reloc
932
in the _rtld_local definition's initializer. */
933
GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
935
/* Process the environment variable which control the behaviour. */
936
process_envvars (&mode);
938
#ifndef HAVE_INLINED_SYSCALLS
939
/* Set up a flag which tells we are just starting. */
940
INTUSE(_dl_starting_up) = 1;
943
if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
945
/* Ho ho. We are not the program interpreter! We are the program
946
itself! This means someone ran ld.so as a command. Well, that
947
might be convenient to do sometimes. We support it by
948
interpreting the args like this:
950
ld.so PROGRAM ARGS...
952
The first argument is the name of a file containing an ELF
953
executable we will load and run with the following arguments.
954
To simplify life here, PROGRAM is searched for using the
955
normal rules for shared objects, rather than $PATH or anything
956
like that. We just load it and use its entry point; we don't
957
pay attention to its PT_INTERP command (we are the interpreter
958
ourselves). This is an easy way to test a new ld.so before
962
/* Note the place where the dynamic linker actually came from. */
963
GL(dl_rtld_map).l_name = rtld_progname;
966
if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
969
GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
975
else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
983
else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-cache"))
985
GLRO(dl_inhibit_cache) = 1;
990
else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
993
library_path = INTUSE(_dl_argv)[2];
997
INTUSE(_dl_argv) += 2;
999
else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
1002
GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
1006
INTUSE(_dl_argv) += 2;
1008
else if (! strcmp (INTUSE(_dl_argv)[1], "--audit") && _dl_argc > 2)
1010
process_dl_audit (INTUSE(_dl_argv)[2]);
1014
INTUSE(_dl_argv) += 2;
1019
/* If we have no further argument the program was called incorrectly.
1020
Grant the user some education. */
1022
_dl_fatal_printf ("\
1023
Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
1024
You have invoked `ld.so', the helper program for shared library executables.\n\
1025
This program usually lives in the file `/lib/ld.so', and special directives\n\
1026
in executable files using ELF shared libraries tell the system's program\n\
1027
loader to load the helper program from this file. This helper program loads\n\
1028
the shared libraries needed by the program executable, prepares the program\n\
1029
to run, and runs it. You may invoke this helper program directly from the\n\
1030
command line to load and run an ELF executable file; this is like executing\n\
1031
that file itself, but always uses this helper program from the file you\n\
1032
specified, instead of the helper program file specified in the executable\n\
1033
file you run. This is mostly of use for maintainers to test new versions\n\
1034
of this helper program; chances are you did not intend to run this program.\n\
1036
--list list all dependencies and how they are resolved\n\
1037
--verify verify that given object really is a dynamically linked\n\
1038
object we can handle\n\
1039
--inhibit-cache Do not use " LD_SO_CACHE "\n\
1040
--library-path PATH use given PATH instead of content of the environment\n\
1041
variable LD_LIBRARY_PATH\n\
1042
--inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
1044
--audit LIST use objects named in LIST as auditors\n");
1050
/* The initialization of _dl_stack_flags done below assumes the
1051
executable's PT_GNU_STACK may have been honored by the kernel, and
1052
so a PT_GNU_STACK with PF_X set means the stack started out with
1053
execute permission. However, this is not really true if the
1054
dynamic linker is the executable the kernel loaded. For this
1055
case, we must reinitialize _dl_stack_flags to match the dynamic
1056
linker itself. If the dynamic linker was built with a
1057
PT_GNU_STACK, then the kernel may have loaded us with a
1058
nonexecutable stack that we will have to make executable when we
1059
load the program below unless it has a PT_GNU_STACK indicating
1060
nonexecutable stack is ok. */
1062
for (ph = phdr; ph < &phdr[phnum]; ++ph)
1063
if (ph->p_type == PT_GNU_STACK)
1065
GL(dl_stack_flags) = ph->p_flags;
1069
if (__builtin_expect (mode, normal) == verify)
1071
const char *objname;
1072
const char *err_str = NULL;
1073
struct map_args args;
1076
args.str = rtld_progname;
1078
args.mode = __RTLD_OPENEXEC;
1079
(void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
1081
if (__builtin_expect (err_str != NULL, 0))
1082
/* We don't free the returned string, the programs stops
1084
_exit (EXIT_FAILURE);
1088
HP_TIMING_NOW (start);
1089
_dl_map_object (NULL, rtld_progname, lt_library, 0,
1090
__RTLD_OPENEXEC, LM_ID_BASE);
1091
HP_TIMING_NOW (stop);
1093
HP_TIMING_DIFF (load_time, start, stop);
1096
/* Now the map for the main executable is available. */
1097
main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
1099
if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1100
&& main_map->l_info[DT_SONAME] != NULL
1101
&& strcmp ((const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1102
+ GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val,
1103
(const char *) D_PTR (main_map, l_info[DT_STRTAB])
1104
+ main_map->l_info[DT_SONAME]->d_un.d_val) == 0)
1105
_dl_fatal_printf ("loader cannot load itself\n");
1107
phdr = main_map->l_phdr;
1108
phnum = main_map->l_phnum;
1109
/* We overwrite here a pointer to a malloc()ed string. But since
1110
the malloc() implementation used at this point is the dummy
1111
implementations which has no real free() function it does not
1112
makes sense to free the old string first. */
1113
main_map->l_name = (char *) "";
1114
*user_entry = main_map->l_entry;
1116
#ifdef HAVE_AUX_VECTOR
1117
/* Adjust the on-stack auxiliary vector so that it looks like the
1118
binary was executed directly. */
1119
for (ElfW(auxv_t) *av = auxv; av->a_type != AT_NULL; av++)
1123
av->a_un.a_val = (uintptr_t) phdr;
1126
av->a_un.a_val = phnum;
1129
av->a_un.a_val = *user_entry;
1136
/* Create a link_map for the executable itself.
1137
This will be what dlopen on "" returns. */
1138
main_map = _dl_new_object ((char *) "", "", lt_executable, NULL,
1139
__RTLD_OPENEXEC, LM_ID_BASE);
1140
assert (main_map != NULL);
1141
main_map->l_phdr = phdr;
1142
main_map->l_phnum = phnum;
1143
main_map->l_entry = *user_entry;
1145
/* Even though the link map is not yet fully initialized we can add
1146
it to the map list since there are no possible users running yet. */
1147
_dl_add_to_namespace_list (main_map, LM_ID_BASE);
1148
assert (main_map == GL(dl_ns)[LM_ID_BASE]._ns_loaded);
1150
/* At this point we are in a bit of trouble. We would have to
1151
fill in the values for l_dev and l_ino. But in general we
1152
do not know where the file is. We also do not handle AT_EXECFD
1153
even if it would be passed up.
1155
We leave the values here defined to 0. This is normally no
1156
problem as the program code itself is normally no shared
1157
object and therefore cannot be loaded dynamically. Nothing
1158
prevent the use of dynamic binaries and in these situations
1159
we might get problems. We might not be able to find out
1160
whether the object is already loaded. But since there is no
1161
easy way out and because the dynamic binary must also not
1162
have an SONAME we ignore this program for now. If it becomes
1163
a problem we can force people using SONAMEs. */
1165
/* We delay initializing the path structure until we got the dynamic
1166
information for the program. */
1169
main_map->l_map_end = 0;
1170
main_map->l_text_end = 0;
1171
/* Perhaps the executable has no PT_LOAD header entries at all. */
1172
main_map->l_map_start = ~0;
1173
/* And it was opened directly. */
1174
++main_map->l_direct_opencount;
1176
/* Scan the program header table for the dynamic section. */
1177
for (ph = phdr; ph < &phdr[phnum]; ++ph)
1181
/* Find out the load address. */
1182
main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
1185
/* This tells us where to find the dynamic section,
1186
which tells us everything we need to do. */
1187
main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
1190
/* This "interpreter segment" was used by the program loader to
1191
find the program interpreter, which is this program itself, the
1192
dynamic linker. We note what name finds us, so that a future
1193
dlopen call or DT_NEEDED entry, for something that wants to link
1194
against the dynamic linker as a shared library, will know that
1195
the shared object is already loaded. */
1196
_dl_rtld_libname.name = ((const char *) main_map->l_addr
1198
/* _dl_rtld_libname.next = NULL; Already zero. */
1199
GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1201
/* Ordinarilly, we would get additional names for the loader from
1202
our DT_SONAME. This can't happen if we were actually linked as
1203
a static executable (detect this case when we have no DYNAMIC).
1204
If so, assume the filename component of the interpreter path to
1205
be our SONAME, and add it to our name list. */
1206
if (GL(dl_rtld_map).l_ld == NULL)
1208
const char *p = NULL;
1209
const char *cp = _dl_rtld_libname.name;
1211
/* Find the filename part of the path. */
1218
_dl_rtld_libname2.name = p;
1219
/* _dl_rtld_libname2.next = NULL; Already zero. */
1220
_dl_rtld_libname.next = &_dl_rtld_libname2;
1228
ElfW(Addr) mapstart;
1229
ElfW(Addr) allocend;
1231
/* Remember where the main program starts in memory. */
1232
mapstart = (main_map->l_addr
1233
+ (ph->p_vaddr & ~(GLRO(dl_pagesize) - 1)));
1234
if (main_map->l_map_start > mapstart)
1235
main_map->l_map_start = mapstart;
1237
/* Also where it ends. */
1238
allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
1239
if (main_map->l_map_end < allocend)
1240
main_map->l_map_end = allocend;
1241
if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
1242
main_map->l_text_end = allocend;
1247
if (ph->p_memsz > 0)
1249
/* Note that in the case the dynamic linker we duplicate work
1250
here since we read the PT_TLS entry already in
1251
_dl_start_final. But the result is repeatable so do not
1252
check for this special but unimportant case. */
1253
main_map->l_tls_blocksize = ph->p_memsz;
1254
main_map->l_tls_align = ph->p_align;
1255
if (ph->p_align == 0)
1256
main_map->l_tls_firstbyte_offset = 0;
1258
main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1259
& (ph->p_align - 1));
1260
main_map->l_tls_initimage_size = ph->p_filesz;
1261
main_map->l_tls_initimage = (void *) ph->p_vaddr;
1263
/* This image gets the ID one. */
1264
GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1269
GL(dl_stack_flags) = ph->p_flags;
1273
main_map->l_relro_addr = ph->p_vaddr;
1274
main_map->l_relro_size = ph->p_memsz;
1278
/* Adjust the address of the TLS initialization image in case
1279
the executable is actually an ET_DYN object. */
1280
if (main_map->l_tls_initimage != NULL)
1281
main_map->l_tls_initimage
1282
= (char *) main_map->l_tls_initimage + main_map->l_addr;
1283
if (! main_map->l_map_end)
1284
main_map->l_map_end = ~0;
1285
if (! main_map->l_text_end)
1286
main_map->l_text_end = ~0;
1287
if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1289
/* We were invoked directly, so the program might not have a
1291
_dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1292
/* _dl_rtld_libname.next = NULL; Already zero. */
1293
GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1296
assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1298
/* If the current libname is different from the SONAME, add the
1300
if (GL(dl_rtld_map).l_info[DT_SONAME] != NULL
1301
&& strcmp (GL(dl_rtld_map).l_libname->name,
1302
(const char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1303
+ GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_val) != 0)
1305
static struct libname_list newname;
1306
newname.name = ((char *) D_PTR (&GL(dl_rtld_map), l_info[DT_STRTAB])
1307
+ GL(dl_rtld_map).l_info[DT_SONAME]->d_un.d_ptr);
1308
newname.next = NULL;
1309
newname.dont_free = 1;
1311
assert (GL(dl_rtld_map).l_libname->next == NULL);
1312
GL(dl_rtld_map).l_libname->next = &newname;
1314
/* The ld.so must be relocated since otherwise loading audit modules
1315
will fail since they reuse the very same ld.so. */
1316
assert (GL(dl_rtld_map).l_relocated);
1320
/* Extract the contents of the dynamic section for easy access. */
1321
elf_get_dynamic_info (main_map, NULL);
1322
/* Set up our cache of pointers into the hash table. */
1323
_dl_setup_hash (main_map);
1326
if (__builtin_expect (mode, normal) == verify)
1328
/* We were called just to verify that this is a dynamic
1329
executable using us as the program interpreter. Exit with an
1330
error if we were not able to load the binary or no interpreter
1331
is specified (i.e., this is no dynamically linked binary. */
1332
if (main_map->l_ld == NULL)
1335
/* We allow here some platform specific code. */
1336
#ifdef DISTINGUISH_LIB_VERSIONS
1337
DISTINGUISH_LIB_VERSIONS;
1339
_exit (has_interp ? 0 : 2);
1342
struct link_map **first_preload = &GL(dl_rtld_map).l_next;
1343
#if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1344
/* Set up the data structures for the system-supplied DSO early,
1345
so they can influence _dl_init_paths. */
1346
if (GLRO(dl_sysinfo_dso) != NULL)
1348
/* Do an abridged version of the work _dl_map_object_from_fd would do
1349
to map in the object. It's already mapped and prelinked (and
1350
better be, since it's read-only and so we couldn't relocate it).
1351
We just want our data structures to describe it as if we had just
1352
mapped and relocated it normally. */
1353
struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL,
1355
if (__builtin_expect (l != NULL, 1))
1357
static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
1359
l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1360
+ GLRO(dl_sysinfo_dso)->e_phoff);
1361
l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1362
for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1364
const ElfW(Phdr) *const ph = &l->l_phdr[i];
1365
if (ph->p_type == PT_DYNAMIC)
1367
l->l_ld = (void *) ph->p_vaddr;
1368
l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1370
else if (ph->p_type == PT_LOAD)
1373
l->l_addr = ph->p_vaddr;
1374
if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1375
l->l_map_end = ph->p_vaddr + ph->p_memsz;
1376
if ((ph->p_flags & PF_X)
1377
&& ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1378
l->l_text_end = ph->p_vaddr + ph->p_memsz;
1381
/* There must be no TLS segment. */
1382
assert (ph->p_type != PT_TLS);
1384
l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1385
l->l_addr = l->l_map_start - l->l_addr;
1386
l->l_map_end += l->l_addr;
1387
l->l_text_end += l->l_addr;
1388
l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1389
elf_get_dynamic_info (l, dyn_temp);
1393
/* The vDSO is always used. */
1396
/* Initialize l_local_scope to contain just this map. This allows
1397
the use of dl_lookup_symbol_x to resolve symbols within the vdso.
1398
So we create a single entry list pointing to l_real as its only
1400
l->l_local_scope[0]->r_nlist = 1;
1401
l->l_local_scope[0]->r_list = &l->l_real;
1403
/* Now that we have the info handy, use the DSO image's soname
1404
so this object can be looked up by name. Note that we do not
1405
set l_name here. That field gives the file name of the DSO,
1406
and this DSO is not associated with any file. */
1407
if (l->l_info[DT_SONAME] != NULL)
1409
/* Work around a kernel problem. The kernel cannot handle
1410
addresses in the vsyscall DSO pages in writev() calls. */
1411
const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1412
+ l->l_info[DT_SONAME]->d_un.d_val);
1413
size_t len = strlen (dsoname);
1414
char *copy = malloc (len);
1416
_dl_fatal_printf ("out of memory\n");
1417
l->l_libname->name = memcpy (copy, dsoname, len);
1418
if (GLRO(dl_debug_mask))
1422
/* Add the vDSO to the object list. */
1423
_dl_add_to_namespace_list (l, LM_ID_BASE);
1425
/* Rearrange the list so this DSO appears after rtld_map. */
1426
assert (l->l_next == NULL);
1427
assert (l->l_prev == main_map);
1428
GL(dl_rtld_map).l_next = l;
1429
l->l_prev = &GL(dl_rtld_map);
1430
first_preload = &l->l_next;
1432
/* We have a prelinked DSO preloaded by the system. */
1433
GLRO(dl_sysinfo_map) = l;
1434
# ifdef NEED_DL_SYSINFO
1435
if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1436
GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1442
#ifdef DL_SYSDEP_OSCHECK
1443
DL_SYSDEP_OSCHECK (_dl_fatal_printf);
1446
/* Initialize the data structures for the search paths for shared
1448
_dl_init_paths (library_path);
1450
/* Initialize _r_debug. */
1451
struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
1453
r->r_state = RT_CONSISTENT;
1455
/* Put the link_map for ourselves on the chain so it can be found by
1456
name. Note that at this point the global chain of link maps contains
1457
exactly one element, which is pointed to by dl_loaded. */
1458
if (! GL(dl_rtld_map).l_name)
1459
/* If not invoked directly, the dynamic linker shared object file was
1460
found by the PT_INTERP name. */
1461
GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1462
GL(dl_rtld_map).l_type = lt_library;
1463
main_map->l_next = &GL(dl_rtld_map);
1464
GL(dl_rtld_map).l_prev = main_map;
1465
++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1468
/* If LD_USE_LOAD_BIAS env variable has not been seen, default
1469
to not using bias for non-prelinked PIEs and libraries
1470
and using it for executables or prelinked PIEs or libraries. */
1471
if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1472
GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
1474
/* Set up the program header information for the dynamic linker
1475
itself. It is needed in the dl_iterate_phdr() callbacks. */
1476
ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1477
ElfW(Phdr) *rtld_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1478
+ rtld_ehdr->e_phoff);
1479
GL(dl_rtld_map).l_phdr = rtld_phdr;
1480
GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1483
/* PT_GNU_RELRO is usually the last phdr. */
1484
size_t cnt = rtld_ehdr->e_phnum;
1486
if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1488
GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1489
GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1493
/* Add the dynamic linker to the TLS list if it also uses TLS. */
1494
if (GL(dl_rtld_map).l_tls_blocksize != 0)
1495
/* Assign a module ID. Do this before loading any audit modules. */
1496
GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1498
/* If we have auditing DSOs to load, do it now. */
1499
if (__builtin_expect (audit_list != NULL, 0))
1501
/* Iterate over all entries in the list. The order is important. */
1502
struct audit_ifaces *last_audit = NULL;
1503
struct audit_list *al = audit_list->next;
1505
/* Since we start using the auditing DSOs right away we need to
1506
initialize the data structures now. */
1509
/* Initialize security features. We need to do it this early
1510
since otherwise the constructors of the audit libraries will
1511
use different values (especially the pointer guard) and will
1517
int tls_idx = GL(dl_tls_max_dtv_idx);
1519
/* Now it is time to determine the layout of the static TLS
1520
block and allocate it for the initial thread. Note that we
1521
always allocate the static block, we never defer it even if
1522
no DF_STATIC_TLS bit is set. The reason is that we know
1523
glibc will use the static model. */
1524
struct dlmopen_args dlmargs;
1525
dlmargs.fname = al->name;
1528
const char *objname;
1529
const char *err_str = NULL;
1531
(void) _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit,
1533
if (__builtin_expect (err_str != NULL, 0))
1536
_dl_error_printf ("\
1537
ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
1540
free ((char *) err_str);
1544
struct lookup_args largs;
1545
largs.name = "la_version";
1546
largs.map = dlmargs.map;
1548
/* Check whether the interface version matches. */
1549
(void) _dl_catch_error (&objname, &err_str, &malloced,
1550
lookup_doit, &largs);
1552
unsigned int (*laversion) (unsigned int);
1555
&& (laversion = largs.result) != NULL
1556
&& (lav = laversion (LAV_CURRENT)) > 0
1557
&& lav <= LAV_CURRENT)
1559
/* Allocate structure for the callback function pointers.
1560
This call can never fail. */
1563
struct audit_ifaces ifaces;
1564
#define naudit_ifaces 8
1565
void (*fptr[naudit_ifaces]) (void);
1566
} *newp = malloc (sizeof (*newp));
1568
/* Names of the auditing interfaces. All in one
1570
static const char audit_iface_names[] =
1575
#if __ELF_NATIVE_CLASS == 32
1577
#elif __ELF_NATIVE_CLASS == 64
1580
# error "__ELF_NATIVE_CLASS must be defined"
1582
#define STRING(s) __STRING (s)
1583
"la_" STRING (ARCH_LA_PLTENTER) "\0"
1584
"la_" STRING (ARCH_LA_PLTEXIT) "\0"
1586
unsigned int cnt = 0;
1587
const char *cp = audit_iface_names;
1591
(void) _dl_catch_error (&objname, &err_str, &malloced,
1592
lookup_doit, &largs);
1594
/* Store the pointer. */
1595
if (err_str == NULL && largs.result != NULL)
1597
newp->fptr[cnt] = largs.result;
1599
/* The dynamic linker link map is statically
1600
allocated, initialize the data now. */
1601
GL(dl_rtld_map).l_audit[cnt].cookie
1602
= (intptr_t) &GL(dl_rtld_map);
1605
newp->fptr[cnt] = NULL;
1608
cp = (char *) rawmemchr (cp, '\0') + 1;
1610
while (*cp != '\0');
1611
assert (cnt == naudit_ifaces);
1613
/* Now append the new auditing interface to the list. */
1614
newp->ifaces.next = NULL;
1615
if (last_audit == NULL)
1616
last_audit = GLRO(dl_audit) = &newp->ifaces;
1618
last_audit = last_audit->next = &newp->ifaces;
1621
/* Mark the DSO as being used for auditing. */
1622
dlmargs.map->l_auditing = 1;
1626
/* We cannot use the DSO, it does not have the
1627
appropriate interfaces or it expects something
1630
Lmid_t ns = dlmargs.map->l_ns;
1632
_dl_close (dlmargs.map);
1634
/* Make sure the namespace has been cleared entirely. */
1635
assert (GL(dl_ns)[ns]._ns_loaded == NULL);
1636
assert (GL(dl_ns)[ns]._ns_nloaded == 0);
1638
GL(dl_tls_max_dtv_idx) = tls_idx;
1645
while (al != audit_list->next);
1647
/* If we have any auditing modules, announce that we already
1648
have two objects loaded. */
1649
if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1651
struct link_map *ls[2] = { main_map, &GL(dl_rtld_map) };
1653
for (unsigned int outer = 0; outer < 2; ++outer)
1655
struct audit_ifaces *afct = GLRO(dl_audit);
1656
for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1658
if (afct->objopen != NULL)
1660
ls[outer]->l_audit[cnt].bindflags
1661
= afct->objopen (ls[outer], LM_ID_BASE,
1662
&ls[outer]->l_audit[cnt].cookie);
1664
ls[outer]->l_audit_any_plt
1665
|= ls[outer]->l_audit[cnt].bindflags != 0;
1674
/* Set up debugging before the debugger is notified for the first time. */
1675
#ifdef ELF_MACHINE_DEBUG_SETUP
1676
/* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1677
ELF_MACHINE_DEBUG_SETUP (main_map, r);
1678
ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1680
if (main_map->l_info[DT_DEBUG] != NULL)
1681
/* There is a DT_DEBUG entry in the dynamic section. Fill it in
1682
with the run-time address of the r_debug structure */
1683
main_map->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1685
/* Fill in the pointer in the dynamic linker's own dynamic section, in
1686
case you run gdb on the dynamic linker directly. */
1687
if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1688
GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1691
/* We start adding objects. */
1692
r->r_state = RT_ADD;
1695
/* Auditing checkpoint: we are ready to signal that the initial map
1696
is being constructed. */
1697
if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
1699
struct audit_ifaces *afct = GLRO(dl_audit);
1700
for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
1702
if (afct->activity != NULL)
1703
afct->activity (&main_map->l_audit[cnt].cookie, LA_ACT_ADD);
1709
/* We have two ways to specify objects to preload: via environment
1710
variable and via the file /etc/ld.so.preload. The latter can also
1711
be used when security is enabled. */
1712
assert (*first_preload == NULL);
1713
struct link_map **preloads = NULL;
1714
unsigned int npreloads = 0;
1716
if (__builtin_expect (preloadlist != NULL, 0))
1718
/* The LD_PRELOAD environment variable gives list of libraries
1719
separated by white space or colons that are loaded before the
1720
executable's dependencies and prepended to the global scope
1721
list. If the binary is running setuid all elements
1722
containing a '/' are ignored since it is insecure. */
1723
char *list = strdupa (preloadlist);
1726
HP_TIMING_NOW (start);
1728
/* Prevent optimizing strsep. Speed is not important here. */
1729
while ((p = (strsep) (&list, " :")) != NULL)
1731
&& (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1732
|| strchr (p, '/') == NULL))
1733
npreloads += do_preload (p, main_map, "LD_PRELOAD");
1735
HP_TIMING_NOW (stop);
1736
HP_TIMING_DIFF (diff, start, stop);
1737
HP_TIMING_ACCUM_NT (load_time, diff);
1740
/* There usually is no ld.so.preload file, it should only be used
1741
for emergencies and testing. So the open call etc should usually
1742
fail. Using access() on a non-existing file is faster than using
1743
open(). So we do this first. If it succeeds we do almost twice
1744
the work but this does not matter, since it is not for production
1746
static const char preload_file[] = "/etc/ld.so.preload";
1747
if (__builtin_expect (__access (preload_file, R_OK) == 0, 0))
1749
/* Read the contents of the file. */
1750
file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1751
PROT_READ | PROT_WRITE);
1752
if (__builtin_expect (file != MAP_FAILED, 0))
1754
/* Parse the file. It contains names of libraries to be loaded,
1755
separated by white spaces or `:'. It may also contain
1756
comments introduced by `#'. */
1761
/* Eliminate comments. */
1766
char *comment = memchr (runp, '#', rest);
1767
if (comment == NULL)
1770
rest -= comment - runp;
1773
while (--rest > 0 && *++comment != '\n');
1776
/* We have one problematic case: if we have a name at the end of
1777
the file without a trailing terminating characters, we cannot
1778
place the \0. Handle the case separately. */
1779
if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1780
&& file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1782
problem = &file[file_size];
1783
while (problem > file && problem[-1] != ' '
1784
&& problem[-1] != '\t'
1785
&& problem[-1] != '\n' && problem[-1] != ':')
1794
file[file_size - 1] = '\0';
1797
HP_TIMING_NOW (start);
1799
if (file != problem)
1803
while ((p = strsep (&runp, ": \t\n")) != NULL)
1805
npreloads += do_preload (p, main_map, preload_file);
1808
if (problem != NULL)
1810
char *p = strndupa (problem, file_size - (problem - file));
1812
npreloads += do_preload (p, main_map, preload_file);
1815
HP_TIMING_NOW (stop);
1816
HP_TIMING_DIFF (diff, start, stop);
1817
HP_TIMING_ACCUM_NT (load_time, diff);
1819
/* We don't need the file anymore. */
1820
__munmap (file, file_size);
1824
if (__builtin_expect (*first_preload != NULL, 0))
1826
/* Set up PRELOADS with a vector of the preloaded libraries. */
1827
struct link_map *l = *first_preload;
1828
preloads = __alloca (npreloads * sizeof preloads[0]);
1835
assert (i == npreloads);
1838
/* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1839
specified some libraries to load, these are inserted before the actual
1840
dependencies in the executable's searchlist for symbol resolution. */
1841
HP_TIMING_NOW (start);
1842
_dl_map_object_deps (main_map, preloads, npreloads, mode == trace, 0);
1843
HP_TIMING_NOW (stop);
1844
HP_TIMING_DIFF (diff, start, stop);
1845
HP_TIMING_ACCUM_NT (load_time, diff);
1847
/* Mark all objects as being in the global scope. */
1848
for (i = main_map->l_searchlist.r_nlist; i > 0; )
1849
main_map->l_searchlist.r_list[--i]->l_global = 1;
1851
/* Remove _dl_rtld_map from the chain. */
1852
GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1853
if (GL(dl_rtld_map).l_next != NULL)
1854
GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1856
for (i = 1; i < main_map->l_searchlist.r_nlist; ++i)
1857
if (main_map->l_searchlist.r_list[i] == &GL(dl_rtld_map))
1860
bool rtld_multiple_ref = false;
1861
if (__builtin_expect (i < main_map->l_searchlist.r_nlist, 1))
1863
/* Some DT_NEEDED entry referred to the interpreter object itself, so
1864
put it back in the list of visible objects. We insert it into the
1865
chain in symbol search order because gdb uses the chain's order as
1866
its symbol search order. */
1867
rtld_multiple_ref = true;
1869
GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1870
if (__builtin_expect (mode, normal) == normal)
1872
GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1873
? main_map->l_searchlist.r_list[i + 1]
1875
#if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1876
if (GLRO(dl_sysinfo_map) != NULL
1877
&& GL(dl_rtld_map).l_prev->l_next == GLRO(dl_sysinfo_map)
1878
&& GL(dl_rtld_map).l_next != GLRO(dl_sysinfo_map))
1879
GL(dl_rtld_map).l_prev = GLRO(dl_sysinfo_map);
1883
/* In trace mode there might be an invisible object (which we
1884
could not find) after the previous one in the search list.
1885
In this case it doesn't matter much where we put the
1886
interpreter object, so we just initialize the list pointer so
1887
that the assertion below holds. */
1888
GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1890
assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1891
GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1892
if (GL(dl_rtld_map).l_next != NULL)
1894
assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1895
GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1899
/* Now let us see whether all libraries are available in the
1900
versions we need. */
1902
struct version_check_args args;
1903
args.doexit = mode == normal;
1904
args.dotrace = mode == trace;
1905
_dl_receive_error (print_missing_version, version_check_doit, &args);
1908
/* We do not initialize any of the TLS functionality unless any of the
1909
initial modules uses TLS. This makes dynamic loading of modules with
1910
TLS impossible, but to support it requires either eagerly doing setup
1911
now or lazily doing it later. Doing it now makes us incompatible with
1912
an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1913
used. Trying to do it lazily is too hairy to try when there could be
1914
multiple threads (from a non-TLS-using libpthread). */
1915
bool was_tls_init_tp_called = tls_init_tp_called;
1919
if (__builtin_expect (audit_list == NULL, 1))
1920
/* Initialize security features. But only if we have not done it
1924
if (__builtin_expect (mode, normal) != normal)
1926
/* We were run just to list the shared libraries. It is
1927
important that we do this before real relocation, because the
1928
functions we call below for output may no longer work properly
1929
after relocation. */
1932
if (GLRO_dl_debug_mask & DL_DEBUG_PRELINK)
1934
struct r_scope_elem *scope = &main_map->l_searchlist;
1936
for (i = 0; i < scope->r_nlist; i++)
1938
l = scope->r_list [i];
1941
_dl_printf ("\t%s => not found\n", l->l_libname->name);
1944
if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1945
GLRO(dl_trace_prelink_map) = l;
1946
_dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1947
l->l_libname->name[0] ? l->l_libname->name
1948
: rtld_progname ?: "<main program>",
1949
l->l_name[0] ? l->l_name
1950
: rtld_progname ?: "<main program>",
1951
(int) sizeof l->l_map_start * 2,
1952
(size_t) l->l_map_start,
1953
(int) sizeof l->l_addr * 2,
1954
(size_t) l->l_addr);
1957
_dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1958
(int) sizeof l->l_tls_offset * 2,
1959
(size_t) l->l_tls_offset);
1964
else if (GLRO_dl_debug_mask & DL_DEBUG_UNUSED)
1966
/* Look through the dependencies of the main executable
1967
and determine which of them is not actually
1969
struct link_map *l = main_map;
1971
/* Relocate the main executable. */
1972
struct relocate_args args = { .l = l,
1973
.reloc_mode = ((GLRO(dl_lazy)
1975
| __RTLD_NOIFUNC) };
1976
_dl_receive_error (print_unresolved, relocate_doit, &args);
1978
/* This loop depends on the dependencies of the executable to
1979
correspond in number and order to the DT_NEEDED entries. */
1980
ElfW(Dyn) *dyn = main_map->l_ld;
1982
while (dyn->d_tag != DT_NULL)
1984
if (dyn->d_tag == DT_NEEDED)
1987
#if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1988
/* Skip the VDSO since it's not part of the list
1989
of objects we brought in via DT_NEEDED entries. */
1990
if (l == GLRO(dl_sysinfo_map))
1997
_dl_printf ("Unused direct dependencies:\n");
2001
_dl_printf ("\t%s\n", l->l_name);
2008
_exit (first != true);
2010
else if (! main_map->l_info[DT_NEEDED])
2011
_dl_printf ("\tstatically linked\n");
2014
for (l = main_map->l_next; l; l = l->l_next)
2016
/* The library was not found. */
2017
_dl_printf ("\t%s => not found\n", l->l_libname->name);
2018
else if (strcmp (l->l_libname->name, l->l_name) == 0)
2019
_dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
2020
(int) sizeof l->l_map_start * 2,
2021
(size_t) l->l_map_start);
2023
_dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
2024
l->l_name, (int) sizeof l->l_map_start * 2,
2025
(size_t) l->l_map_start);
2028
if (__builtin_expect (mode, trace) != trace)
2029
for (i = 1; i < (unsigned int) _dl_argc; ++i)
2031
const ElfW(Sym) *ref = NULL;
2032
ElfW(Addr) loadbase;
2035
result = _dl_lookup_symbol_x (INTUSE(_dl_argv)[i], main_map,
2036
&ref, main_map->l_scope,
2037
NULL, ELF_RTYPE_CLASS_PLT,
2038
DL_LOOKUP_ADD_DEPENDENCY, NULL);
2040
loadbase = LOOKUP_VALUE_ADDRESS (result);
2042
_dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
2043
INTUSE(_dl_argv)[i],
2044
(int) sizeof ref->st_value * 2,
2045
(size_t) ref->st_value,
2046
(int) sizeof loadbase * 2, (size_t) loadbase);
2050
/* If LD_WARN is set, warn about undefined symbols. */
2051
if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
2053
/* We have to do symbol dependency testing. */
2054
struct relocate_args args;
2057
args.reloc_mode = ((GLRO(dl_lazy) ? RTLD_LAZY : 0)
2060
i = main_map->l_searchlist.r_nlist;
2063
struct link_map *l = main_map->l_initfini[i];
2064
if (l != &GL(dl_rtld_map) && ! l->l_faked)
2067
_dl_receive_error (print_unresolved, relocate_doit,
2072
if ((GLRO_dl_debug_mask & DL_DEBUG_PRELINK)
2073
&& rtld_multiple_ref)
2075
/* Mark the link map as not yet relocated again. */
2076
GL(dl_rtld_map).l_relocated = 0;
2077
_dl_relocate_object (&GL(dl_rtld_map),
2078
main_map->l_scope, __RTLD_NOIFUNC, 0);
2081
#define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
2084
/* Print more information. This means here, print information
2085
about the versions needed. */
2087
struct link_map *map;
2089
for (map = main_map; map != NULL; map = map->l_next)
2092
ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
2098
strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
2099
ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
2103
_dl_printf ("\n\tVersion information:\n");
2107
_dl_printf ("\t%s:\n",
2108
map->l_name[0] ? map->l_name : rtld_progname);
2113
struct link_map *needed;
2115
needed = find_needed (strtab + ent->vn_file);
2116
aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
2120
const char *fname = NULL;
2123
&& match_version (strtab + aux->vna_name,
2125
fname = needed->l_name;
2127
_dl_printf ("\t\t%s (%s) %s=> %s\n",
2128
strtab + ent->vn_file,
2129
strtab + aux->vna_name,
2130
aux->vna_flags & VER_FLG_WEAK
2132
fname ?: "not found");
2134
if (aux->vna_next == 0)
2135
/* No more symbols. */
2139
aux = (ElfW(Vernaux) *) ((char *) aux
2143
if (ent->vn_next == 0)
2144
/* No more dependencies. */
2147
/* Next dependency. */
2148
ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
2157
if (main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]
2158
&& ! __builtin_expect (GLRO(dl_profile) != NULL, 0)
2159
&& ! __builtin_expect (GLRO(dl_dynamic_weak), 0))
2161
ElfW(Lib) *liblist, *liblistend;
2162
struct link_map **r_list, **r_listend, *l;
2163
const char *strtab = (const void *) D_PTR (main_map, l_info[DT_STRTAB]);
2165
assert (main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
2166
liblist = (ElfW(Lib) *)
2167
main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
2168
liblistend = (ElfW(Lib) *)
2170
main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
2171
r_list = main_map->l_searchlist.r_list;
2172
r_listend = r_list + main_map->l_searchlist.r_nlist;
2174
for (; r_list < r_listend && liblist < liblistend; r_list++)
2181
/* If the library is not mapped where it should, fail. */
2185
/* Next, check if checksum matches. */
2186
if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
2187
|| l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
2188
!= liblist->l_checksum)
2191
if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
2192
|| l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
2193
!= liblist->l_time_stamp)
2196
if (! _dl_name_match_p (strtab + liblist->l_name, l))
2203
if (r_list == r_listend && liblist == liblistend)
2206
if (__builtin_expect (GLRO_dl_debug_mask & DL_DEBUG_LIBS, 0))
2207
_dl_debug_printf ("\nprelink checking: %s\n",
2208
prelinked ? "ok" : "failed");
2212
/* Now set up the variable which helps the assembler startup code. */
2213
GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
2215
/* Save the information about the original global scope list since
2216
we need it in the memory handling later. */
2217
GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
2219
/* Remember the last search directory added at startup, now that
2220
malloc will no longer be the one from dl-minimal.c. */
2221
GLRO(dl_init_all_dirs) = GL(dl_all_dirs);
2223
/* Print scope information. */
2224
if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_SCOPES, 0))
2226
_dl_debug_printf ("\nInitial object scopes\n");
2228
for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2229
_dl_show_scope (l, 0);
2234
if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
2236
ElfW(Rela) *conflict, *conflictend;
2237
#ifndef HP_TIMING_NONAVAIL
2242
HP_TIMING_NOW (start);
2243
assert (main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
2244
conflict = (ElfW(Rela) *)
2245
main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
2246
conflictend = (ElfW(Rela) *)
2248
+ main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
2249
_dl_resolve_conflicts (main_map, conflict, conflictend);
2250
HP_TIMING_NOW (stop);
2251
HP_TIMING_DIFF (relocate_time, start, stop);
2255
/* Mark all the objects so we know they have been already relocated. */
2256
for (struct link_map *l = main_map; l != NULL; l = l->l_next)
2259
if (l->l_relro_size)
2260
_dl_protect_relro (l);
2262
/* Add object to slot information data if necessasy. */
2263
if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2264
_dl_add_to_slotinfo (l);
2269
/* Now we have all the objects loaded. Relocate them all except for
2270
the dynamic linker itself. We do this in reverse order so that copy
2271
relocs of earlier objects overwrite the data written by later
2272
objects. We do not re-relocate the dynamic linker itself in this
2273
loop because that could result in the GOT entries for functions we
2274
call being changed, and that would break us. It is safe to relocate
2275
the dynamic linker out of order because it has no copy relocs (we
2276
know that because it is self-contained). */
2278
int consider_profiling = GLRO(dl_profile) != NULL;
2279
#ifndef HP_TIMING_NONAVAIL
2284
/* If we are profiling we also must do lazy reloaction. */
2285
GLRO(dl_lazy) |= consider_profiling;
2287
HP_TIMING_NOW (start);
2288
unsigned i = main_map->l_searchlist.r_nlist;
2291
struct link_map *l = main_map->l_initfini[i];
2293
/* While we are at it, help the memory handling a bit. We have to
2294
mark some data structures as allocated with the fake malloc()
2295
implementation in ld.so. */
2296
struct libname_list *lnp = l->l_libname->next;
2298
while (__builtin_expect (lnp != NULL, 0))
2303
/* Also allocated with the fake malloc(). */
2304
l->l_free_initfini = 0;
2306
if (l != &GL(dl_rtld_map))
2307
_dl_relocate_object (l, l->l_scope, GLRO(dl_lazy) ? RTLD_LAZY : 0,
2308
consider_profiling);
2310
/* Add object to slot information data if necessasy. */
2311
if (l->l_tls_blocksize != 0 && tls_init_tp_called)
2312
_dl_add_to_slotinfo (l);
2314
HP_TIMING_NOW (stop);
2316
HP_TIMING_DIFF (relocate_time, start, stop);
2318
/* Now enable profiling if needed. Like the previous call,
2319
this has to go here because the calls it makes should use the
2320
rtld versions of the functions (particularly calloc()), but it
2321
needs to have _dl_profile_map set up by the relocator. */
2322
if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
2323
/* We must prepare the profiling. */
2324
_dl_start_profile ();
2327
#ifndef NONTLS_INIT_TP
2328
# define NONTLS_INIT_TP do { } while (0)
2331
if (!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
2332
++GL(dl_tls_generation);
2334
/* Now that we have completed relocation, the initializer data
2335
for the TLS blocks has its final values and we can copy them
2336
into the main thread's TLS area, which we allocated above. */
2337
_dl_allocate_tls_init (tcbp);
2339
/* And finally install it for the main thread. If ld.so itself uses
2340
TLS we know the thread pointer was initialized earlier. */
2341
if (! tls_init_tp_called)
2345
= TLS_INIT_TP (tcbp, USE___THREAD);
2347
= TLS_INIT_TP (tcbp, 0);
2349
if (__builtin_expect (lossage != NULL, 0))
2350
_dl_fatal_printf ("cannot set up thread-local storage: %s\n",
2354
/* Make sure no new search directories have been added. */
2355
assert (GLRO(dl_init_all_dirs) == GL(dl_all_dirs));
2357
if (! prelinked && rtld_multiple_ref)
2359
/* There was an explicit ref to the dynamic linker as a shared lib.
2360
Re-relocate ourselves with user-controlled symbol definitions.
2362
We must do this after TLS initialization in case after this
2363
re-relocation, we might call a user-supplied function
2364
(e.g. calloc from _dl_relocate_object) that uses TLS data. */
2366
#ifndef HP_TIMING_NONAVAIL
2372
HP_TIMING_NOW (start);
2373
/* Mark the link map as not yet relocated again. */
2374
GL(dl_rtld_map).l_relocated = 0;
2375
_dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2376
HP_TIMING_NOW (stop);
2377
HP_TIMING_DIFF (add, start, stop);
2378
HP_TIMING_ACCUM_NT (relocate_time, add);
2381
/* Do any necessary cleanups for the startup OS interface code.
2382
We do these now so that no calls are made after rtld re-relocation
2383
which might be resolved to different functions than we expect.
2384
We cannot do this before relocating the other objects because
2385
_dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2386
_dl_sysdep_start_cleanup ();
2389
/* Auditing checkpoint: we have added all objects. */
2390
if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
2392
struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
2393
/* Do not call the functions for any auditing object. */
2394
if (head->l_auditing == 0)
2396
struct audit_ifaces *afct = GLRO(dl_audit);
2397
for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
2399
if (afct->activity != NULL)
2400
afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
2408
/* Notify the debugger all new objects are now ready to go. We must re-get
2409
the address since by now the variable might be in another object. */
2410
r = _dl_debug_initialize (0, LM_ID_BASE);
2411
r->r_state = RT_CONSISTENT;
2415
/* We must munmap() the cache file. */
2416
_dl_unload_cache ();
2419
/* Once we return, _dl_sysdep_start will invoke
2420
the DT_INIT functions and then *USER_ENTRY. */
2423
/* This is a little helper function for resolving symbols while
2424
tracing the binary. */
2426
print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2427
const char *errstring)
2429
if (objname[0] == '\0')
2430
objname = rtld_progname ?: "<main program>";
2431
_dl_error_printf ("%s (%s)\n", errstring, objname);
2434
/* This is a little helper function for resolving symbols while
2435
tracing the binary. */
2437
print_missing_version (int errcode __attribute__ ((unused)),
2438
const char *objname, const char *errstring)
2440
_dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
2441
objname, errstring);
2444
#if __OPTION_EGLIBC_RTLD_DEBUG
2445
/* Nonzero if any of the debugging options is enabled. */
2446
static int any_debug attribute_relro;
2448
/* Process the string given as the parameter which explains which debugging
2449
options are enabled. */
2451
process_dl_debug (const char *dl_debug)
2453
/* When adding new entries make sure that the maximal length of a name
2454
is correctly handled in the LD_DEBUG_HELP code below. */
2458
const char name[10];
2459
const char helptext[41];
2460
unsigned short int mask;
2463
#define LEN_AND_STR(str) sizeof (str) - 1, str
2464
{ LEN_AND_STR ("libs"), "display library search paths",
2465
DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2466
{ LEN_AND_STR ("reloc"), "display relocation processing",
2467
DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2468
{ LEN_AND_STR ("files"), "display progress for input file",
2469
DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2470
{ LEN_AND_STR ("symbols"), "display symbol table processing",
2471
DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2472
{ LEN_AND_STR ("bindings"), "display information about symbol binding",
2473
DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2474
{ LEN_AND_STR ("versions"), "display version dependencies",
2475
DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2476
{ LEN_AND_STR ("scopes"), "display scope information",
2478
{ LEN_AND_STR ("all"), "all previous options combined",
2479
DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2480
| DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS
2481
| DL_DEBUG_SCOPES },
2482
{ LEN_AND_STR ("statistics"), "display relocation statistics",
2483
DL_DEBUG_STATISTICS },
2484
{ LEN_AND_STR ("unused"), "determined unused DSOs",
2486
{ LEN_AND_STR ("help"), "display this help message and exit",
2489
#define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2491
/* Skip separating white spaces and commas. */
2492
while (*dl_debug != '\0')
2494
if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2499
while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2500
&& dl_debug[len] != ',' && dl_debug[len] != ':')
2503
for (cnt = 0; cnt < ndebopts; ++cnt)
2504
if (debopts[cnt].len == len
2505
&& memcmp (dl_debug, debopts[cnt].name, len) == 0)
2507
GLRO_dl_debug_mask |= debopts[cnt].mask;
2512
if (cnt == ndebopts)
2514
/* Display a warning and skip everything until next
2516
char *copy = strndupa (dl_debug, len);
2517
_dl_error_printf ("\
2518
warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2528
if (GLRO_dl_debug_mask & DL_DEBUG_UNUSED)
2530
/* In order to get an accurate picture of whether a particular
2531
DT_NEEDED entry is actually used we have to process both
2532
the PLT and non-PLT relocation entries. */
2536
if (GLRO_dl_debug_mask & DL_DEBUG_HELP)
2541
Valid options for the LD_DEBUG environment variable are:\n\n");
2543
for (cnt = 0; cnt < ndebopts; ++cnt)
2544
_dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2545
" " + debopts[cnt].len - 3,
2546
debopts[cnt].helptext);
2549
To direct the debugging output into a file instead of standard output\n\
2550
a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2554
#endif /* __OPTION_EGLIBC_RTLD_DEBUG */
2557
process_dl_audit (char *str)
2559
/* The parameter is a colon separated list of DSO names. */
2562
while ((p = (strsep) (&str, ":")) != NULL)
2564
&& (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
2565
|| strchr (p, '/') == NULL))
2567
/* This is using the local malloc, not the system malloc. The
2568
memory can never be freed. */
2569
struct audit_list *newp = malloc (sizeof (*newp));
2572
if (audit_list == NULL)
2573
audit_list = newp->next = newp;
2576
newp->next = audit_list->next;
2577
audit_list = audit_list->next = newp;
2582
/* Process all environments variables the dynamic linker must recognize.
2583
Since all of them start with `LD_' we are a bit smarter while finding
2585
extern char **_environ attribute_hidden;
2589
process_envvars (enum mode *modep)
2591
char **runp = _environ;
2593
enum mode mode = normal;
2594
char *debug_output = NULL;
2596
/* This is the default place for profiling data file. */
2597
GLRO(dl_profile_output)
2598
= &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2600
while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2604
while (envline[len] != '\0' && envline[len] != '=')
2607
if (envline[len] != '=')
2608
/* This is a "LD_" variable at the end of the string without
2609
a '=' character. Ignore it since otherwise we will access
2610
invalid memory below. */
2616
/* Warning level, verbose or not. */
2617
if (memcmp (envline, "WARN", 4) == 0)
2618
GLRO(dl_verbose) = envline[5] != '\0';
2622
#if __OPTION_EGLIBC_RTLD_DEBUG
2623
/* Debugging of the dynamic linker? */
2624
if (memcmp (envline, "DEBUG", 5) == 0)
2626
process_dl_debug (&envline[6]);
2630
if (memcmp (envline, "AUDIT", 5) == 0)
2631
process_dl_audit (&envline[6]);
2635
/* Print information about versions. */
2636
if (memcmp (envline, "VERBOSE", 7) == 0)
2638
version_info = envline[8] != '\0';
2642
/* List of objects to be preloaded. */
2643
if (memcmp (envline, "PRELOAD", 7) == 0)
2645
preloadlist = &envline[8];
2649
/* Which shared object shall be profiled. */
2650
if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2651
GLRO(dl_profile) = &envline[8];
2655
/* Do we bind early? */
2656
if (memcmp (envline, "BIND_NOW", 8) == 0)
2658
GLRO(dl_lazy) = envline[9] == '\0';
2661
if (memcmp (envline, "BIND_NOT", 8) == 0)
2662
GLRO(dl_bind_not) = envline[9] != '\0';
2666
/* Test whether we want to see the content of the auxiliary
2667
array passed up from the kernel. */
2668
if (!INTUSE(__libc_enable_secure)
2669
&& memcmp (envline, "SHOW_AUXV", 9) == 0)
2674
/* Mask for the important hardware capabilities. */
2675
if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2676
GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2681
/* Path where the binary is found. */
2682
if (!INTUSE(__libc_enable_secure)
2683
&& memcmp (envline, "ORIGIN_PATH", 11) == 0)
2684
GLRO(dl_origin_path) = &envline[12];
2688
/* The library search path. */
2689
if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2691
library_path = &envline[13];
2695
/* Where to place the profiling data file. */
2696
if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2698
debug_output = &envline[13];
2702
if (!INTUSE(__libc_enable_secure)
2703
&& memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2704
GLRO(dl_dynamic_weak) = 1;
2708
/* We might have some extra environment variable with length 13
2710
#ifdef EXTRA_LD_ENVVARS_13
2713
if (!INTUSE(__libc_enable_secure)
2714
&& memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2716
GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2720
if (memcmp (envline, "POINTER_GUARD", 13) == 0)
2721
GLRO(dl_pointer_guard) = envline[14] != '0';
2725
/* Where to place the profiling data file. */
2726
if (!INTUSE(__libc_enable_secure)
2727
&& memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2728
&& envline[15] != '\0')
2729
GLRO(dl_profile_output) = &envline[15];
2733
/* The mode of the dynamic linker can be set. */
2734
if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2737
GLRO(dl_verbose) = 1;
2738
#if __OPTION_EGLIBC_RTLD_DEBUG
2739
GLRO_dl_debug_mask |= DL_DEBUG_PRELINK;
2741
GLRO(dl_trace_prelink) = &envline[17];
2746
/* The mode of the dynamic linker can be set. */
2747
if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2751
/* We might have some extra environment variable to handle. This
2752
is tricky due to the pre-processing of the length of the name
2753
in the switch statement here. The code here assumes that added
2754
environment variables have a different length. */
2755
#ifdef EXTRA_LD_ENVVARS
2761
/* The caller wants this information. */
2764
/* Extra security for SUID binaries. Remove all dangerous environment
2766
if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2768
static const char unsecure_envvars[] =
2769
#ifdef EXTRA_UNSECURE_ENVVARS
2770
EXTRA_UNSECURE_ENVVARS
2775
nextp = unsecure_envvars;
2779
/* We could use rawmemchr but this need not be fast. */
2780
nextp = (char *) (strchr) (nextp, '\0') + 1;
2782
while (*nextp != '\0');
2784
if (__access ("/etc/suid-debug", F_OK) != 0)
2786
unsetenv ("MALLOC_CHECK_");
2787
#if __OPTION_EGLIBC_RTLD_DEBUG
2788
GLRO_dl_debug_mask = 0;
2795
#if __OPTION_EGLIBC_RTLD_DEBUG
2796
/* If we have to run the dynamic linker in debugging mode and the
2797
LD_DEBUG_OUTPUT environment variable is given, we write the debug
2798
messages to this file. */
2799
else if (any_debug && debug_output != NULL)
2802
const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2804
const int flags = O_WRONLY | O_APPEND | O_CREAT;
2806
size_t name_len = strlen (debug_output);
2807
char buf[name_len + 12];
2810
buf[name_len + 11] = '\0';
2811
startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2813
startp = memcpy (startp - name_len, debug_output, name_len);
2815
GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2816
if (GLRO(dl_debug_fd) == -1)
2817
/* We use standard output if opening the file failed. */
2818
GLRO(dl_debug_fd) = STDOUT_FILENO;
2820
#endif /* __OPTION_EGLIBC_RTLD_DEBUG */
2824
/* Print the various times we collected. */
2826
__attribute ((noinline))
2827
print_statistics (hp_timing_t *rtld_total_timep)
2829
#ifndef HP_TIMING_NONAVAIL
2834
/* Total time rtld used. */
2835
if (HP_TIMING_AVAIL)
2837
HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2838
_dl_debug_printf ("\nruntime linker statistics:\n"
2839
" total startup time in dynamic loader: %s\n", buf);
2841
/* Print relocation statistics. */
2843
HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2844
cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2845
pbuf + sizeof (pbuf), 10, 0);
2847
switch (pbuf + sizeof (pbuf) - cp)
2858
_dl_debug_printf ("\
2859
time needed for relocation: %s (%s%%)\n", buf, pbuf);
2863
unsigned long int num_relative_relocations = 0;
2864
for (Lmid_t ns = 0; ns < GL(dl_nns); ++ns)
2866
if (GL(dl_ns)[ns]._ns_loaded == NULL)
2869
struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2871
for (unsigned int i = 0; i < scope->r_nlist; i++)
2873
struct link_map *l = scope->r_list [i];
2875
if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2876
num_relative_relocations
2877
+= l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2878
#ifndef ELF_MACHINE_REL_RELATIVE
2879
/* Relative relocations are processed on these architectures if
2880
library is loaded to different address than p_vaddr or
2881
if not prelinked. */
2882
if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2883
&& l->l_info[VERSYMIDX (DT_RELACOUNT)])
2885
/* On e.g. IA-64 or Alpha, relative relocations are processed
2886
only if library is loaded to different address than p_vaddr. */
2887
if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2889
num_relative_relocations
2890
+= l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2894
_dl_debug_printf (" number of relocations: %lu\n"
2895
" number of relocations from cache: %lu\n"
2896
" number of relative relocations: %lu\n",
2897
GL(dl_num_relocations),
2898
GL(dl_num_cache_relocations),
2899
num_relative_relocations);
2901
#ifndef HP_TIMING_NONAVAIL
2902
/* Time spend while loading the object and the dependencies. */
2903
if (HP_TIMING_AVAIL)
2906
HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2907
cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2908
pbuf + sizeof (pbuf), 10, 0);
2910
switch (pbuf + sizeof (pbuf) - cp)
2921
_dl_debug_printf ("\
2922
time needed to load objects: %s (%s%%)\n",