~ubuntu-branches/ubuntu/utopic/eglibc/utopic

« back to all changes in this revision

Viewing changes to .pc/ubuntu/local-disable-ld_audit.diff/elf/rtld.c

  • Committer: Package Import Robot
  • Author(s): Adam Conrad
  • Date: 2012-10-26 05:14:58 UTC
  • mfrom: (1.5.1) (4.4.22 experimental)
  • Revision ID: package-import@ubuntu.com-20121026051458-oryotr4i03ob5pab
Tags: 2.16-0ubuntu1
* Merge with unreleased 2.16 in Debian experimental, remaining changes:
  - Drop the Breaks line from libc6, which refers to a Debian transition
  - Remove the libc6 recommends on libc6-i686, which we don't build
  - Enable libc6{,-dev}-armel on armhf and libc6{-dev}-armhf on armel
  - Ship update-locale and validlocale in /usr/sbin in libc-bin
  - Don't build locales or locales-all in Ubuntu, we rely on langpacks
  - Heavily mangle the way we do service restarting on major upgrades
  - Use different MIN_KERNEL_SUPPORTED versions than Debian, due to
    buildd needs.  This should be universally bumped to 3.2.0 once all
    our buildds (including the PPA guests) are running precise kernels
  - Build i386 variants as -march=i686, build amd64 with -O3, and build
    ppc64 variants (both 64-bit and 32-bit) with -O3 -fno-tree-vectorize
  - Re-enable unsubmitted-ldconfig-cache-abi.diff and rebuild the cache
    on upgrades from previous versions that used a different constant
  - debian/patches/any/local-CVE-2012-3406.diff: switch to malloc when
    array grows too large to handle via alloca extension (CVE-2012-3406)
  - Build generic i386/i686 flavour with -mno-tls-direct-seg-refs
* Changes added/dropped with this merge while reducing our delta:
  - Stop building glibc docs from the eglibc source, and instead make
    the glibc-docs stub have a hard dependency on glibc-doc-reference
  - Remove outdated conflicts against ancient versions of ia32-libs
  - Drop the tzdata dependency from libc6, it's in required and minimal
  - Use gcc-4.7/g++-4.7 by default on all our supported architectures
  - Save our historical changelog as changelog.ubuntu in the source
  - Drop nscd's libaudit build-dep for now, as libaudit is in universe
  - Drop the unnecessary Breaks from libc6 to locales and locales-all
  - Ship xen's ld.so.conf.d snippet as /etc/ld.so.conf.d/libc6-xen.conf
* Disable hard failures on the test suite for the first upload to raring

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* Run time dynamic linker.
 
2
   Copyright (C) 1995-2012 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 <gnu/option-groups.h>
 
20
#include <errno.h>
 
21
#include <dlfcn.h>
 
22
#include <fcntl.h>
 
23
#include <stdbool.h>
 
24
#include <stdlib.h>
 
25
#include <string.h>
 
26
#include <unistd.h>
 
27
#include <sys/mman.h>
 
28
#include <sys/param.h>
 
29
#include <sys/stat.h>
 
30
#include <ldsodefs.h>
 
31
#include <_itoa.h>
 
32
#include <entry.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>
 
39
#include <dl-cache.h>
 
40
#include <dl-osinfo.h>
 
41
#include <dl-procinfo.h>
 
42
#include <tls.h>
 
43
#include <stackinfo.h>
 
44
 
 
45
#include <assert.h>
 
46
 
 
47
/* Avoid PLT use for our local calls at startup.  */
 
48
extern __typeof (__mempcpy) __mempcpy attribute_hidden;
 
49
 
 
50
/* GCC has mental blocks about _exit.  */
 
51
extern __typeof (_exit) exit_internal asm ("_exit") attribute_hidden;
 
52
#define _exit exit_internal
 
53
 
 
54
/* Helper function to handle errors while resolving symbols.  */
 
55
static void print_unresolved (int errcode, const char *objname,
 
56
                              const char *errsting);
 
57
 
 
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);
 
61
 
 
62
/* Print the various times we collected.  */
 
63
static void print_statistics (hp_timing_t *total_timep);
 
64
 
 
65
/* Add audit objects.  */
 
66
static void process_dl_audit (char *str);
 
67
 
 
68
/* This is a list of all the modes the dynamic loader can be in.  */
 
69
enum mode { normal, list, verify, trace };
 
70
 
 
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
 
73
   all the entries.  */
 
74
static void process_envvars (enum mode *modep);
 
75
 
 
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;
 
81
#else
 
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;
 
85
#endif
 
86
INTDEF(_dl_argv)
 
87
 
 
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;
 
92
#endif
 
93
 
 
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)
 
100
#endif
 
101
 
 
102
 
 
103
/* List of auditing DSOs.  */
 
104
static struct audit_list
 
105
{
 
106
  const char *name;
 
107
  struct audit_list *next;
 
108
} *audit_list;
 
109
 
 
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
 
117
   never be called.  */
 
118
int _dl_starting_up = 0;
 
119
INTVARDEF(_dl_starting_up)
 
120
#endif
 
121
 
 
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 =
 
125
  {
 
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,
 
132
#endif
 
133
    ._dl_nns = 1,
 
134
    ._dl_ns =
 
135
    {
 
136
      [LM_ID_BASE] = { ._ns_unique_sym_table
 
137
                       = { .lock = _RTLD_LOCK_RECURSIVE_INITIALIZER } }
 
138
    }
 
139
  };
 
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")));
 
146
 
 
147
 
 
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 =
 
151
  {
 
152
    /* Get architecture specific initializer.  */
 
153
#include <dl-procinfo.c>
 
154
#ifdef NEED_DL_SYSINFO
 
155
    ._dl_sysinfo = DL_SYSINFO_DEFAULT,
 
156
#endif
 
157
#ifdef __GNU__
 
158
/* GNU/Hurd needs this because otherwise libpthread's pthread_mutex_lock gets
 
159
 *  * overridden by libX11's stubs.  */
 
160
    ._dl_dynamic_weak = 1,
 
161
#endif
 
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,
 
166
    ._dl_lazy = 1,
 
167
    ._dl_fpu_control = _FPU_DEFAULT,
 
168
    ._dl_pointer_guard = 1,
 
169
    ._dl_pagesize = EXEC_PAGESIZE,
 
170
    ._dl_inhibit_cache = 0,
 
171
 
 
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
 
184
#endif
 
185
  };
 
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")));
 
192
 
 
193
 
 
194
static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
 
195
                     ElfW(Addr) *user_entry, ElfW(auxv_t) *auxv);
 
196
 
 
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;
 
200
 
 
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
 
205
#endif
 
206
 
 
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;
 
212
#endif
 
213
 
 
214
/* Additional definitions needed by TLS initialization.  */
 
215
#ifdef TLS_INIT_HELPER
 
216
TLS_INIT_HELPER
 
217
#endif
 
218
 
 
219
/* Helper function for syscall implementation.  */
 
220
#ifdef DL_SYSINFO_IMPLEMENTATION
 
221
DL_SYSINFO_IMPLEMENTATION
 
222
#endif
 
223
 
 
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
 
229
   hidden.  */
 
230
#ifdef PI_STATIC_AND_HIDDEN
 
231
# define DONT_USE_BOOTSTRAP_MAP 1
 
232
#endif
 
233
 
 
234
#ifdef DONT_USE_BOOTSTRAP_MAP
 
235
static ElfW(Addr) _dl_start_final (void *arg);
 
236
#else
 
237
struct dl_start_final_info
 
238
{
 
239
  struct link_map l;
 
240
#if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
 
241
  hp_timing_t start_time;
 
242
#endif
 
243
};
 
244
static ElfW(Addr) _dl_start_final (void *arg,
 
245
                                   struct dl_start_final_info *info);
 
246
#endif
 
247
 
 
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;
 
252
 
 
253
 
 
254
#ifdef RTLD_START
 
255
RTLD_START
 
256
#else
 
257
# error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
 
258
#endif
 
259
 
 
260
#ifndef VALIDX
 
261
# define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
 
262
                      + DT_EXTRANUM + DT_VALTAGIDX (tag))
 
263
#endif
 
264
#ifndef ADDRIDX
 
265
# define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
 
266
                       + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
 
267
#endif
 
268
 
 
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).  */
 
274
 
 
275
#ifdef DONT_USE_BOOTSTRAP_MAP
 
276
static inline ElfW(Addr) __attribute__ ((always_inline))
 
277
_dl_start_final (void *arg)
 
278
#else
 
279
static ElfW(Addr) __attribute__ ((noinline))
 
280
_dl_start_final (void *arg, struct dl_start_final_info *info)
 
281
#endif
 
282
{
 
283
  ElfW(Addr) start_addr;
 
284
 
 
285
  if (HP_TIMING_AVAIL)
 
286
    {
 
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
 
291
      else
 
292
        start_time = info->start_time;
 
293
#endif
 
294
 
 
295
      /* Initialize the timing functions.  */
 
296
      HP_TIMING_DIFF_INIT ();
 
297
    }
 
298
 
 
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;
 
307
#endif
 
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
 
315
# if USE___THREAD
 
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;
 
324
# else
 
325
#  if NO_TLS_OFFSET != 0
 
326
  GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
 
327
#  endif
 
328
# endif
 
329
 
 
330
#endif
 
331
 
 
332
#if HP_TIMING_AVAIL
 
333
  HP_TIMING_NOW (GL(dl_cpuclock_offset));
 
334
#endif
 
335
 
 
336
  /* Initialize the stack end variable.  */
 
337
  __libc_stack_end = __builtin_frame_address (0);
 
338
 
 
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);
 
344
 
 
345
#ifndef HP_TIMING_NONAVAIL
 
346
  hp_timing_t rtld_total_time;
 
347
  if (HP_TIMING_AVAIL)
 
348
    {
 
349
      hp_timing_t end_time;
 
350
 
 
351
      /* Get the current time.  */
 
352
      HP_TIMING_NOW (end_time);
 
353
 
 
354
      /* Compute the difference.  */
 
355
      HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
 
356
    }
 
357
#endif
 
358
 
 
359
  if (__builtin_expect (GLRO_dl_debug_mask & DL_DEBUG_STATISTICS, 0))
 
360
    {
 
361
#ifndef HP_TIMING_NONAVAIL
 
362
      print_statistics (&rtld_total_time);
 
363
#else
 
364
      print_statistics (NULL);
 
365
#endif
 
366
    }
 
367
 
 
368
  return start_addr;
 
369
}
 
370
 
 
371
static ElfW(Addr) __attribute_used__ internal_function
 
372
_dl_start (void *arg)
 
373
{
 
374
#ifdef DONT_USE_BOOTSTRAP_MAP
 
375
# define bootstrap_map GL(dl_rtld_map)
 
376
#else
 
377
  struct dl_start_final_info info;
 
378
# define bootstrap_map info.l
 
379
#endif
 
380
 
 
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"
 
388
 
 
389
  if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
 
390
#ifdef DONT_USE_BOOTSTRAP_MAP
 
391
    HP_TIMING_NOW (start_time);
 
392
#else
 
393
    HP_TIMING_NOW (info.start_time);
 
394
#endif
 
395
 
 
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));
 
405
# else
 
406
  /* Clear the whole bootstrap_map structure */
 
407
  for (char *cnt = (char *)&(bootstrap_map);
 
408
       cnt < ((char *)&(bootstrap_map) + sizeof (bootstrap_map));
 
409
       *cnt++ = '\0');
 
410
# endif
 
411
# if USE___THREAD
 
412
  bootstrap_map.l_tls_modid = 0;
 
413
# endif
 
414
#endif
 
415
 
 
416
  /* Figure out the run-time load address of the dynamic linker itself.  */
 
417
  bootstrap_map.l_addr = elf_machine_load_address ();
 
418
 
 
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);
 
422
 
 
423
#if NO_TLS_OFFSET != 0
 
424
  bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
 
425
#endif
 
426
 
 
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.  */
 
432
#if USE___THREAD
 
433
  dtv_t initdtv[3];
 
434
  ElfW(Ehdr) *ehdr
 
435
# ifdef DONT_USE_BOOTSTRAP_MAP
 
436
    = (ElfW(Ehdr) *) &_begin;
 
437
# else
 
438
#  error This will not work with prelink.
 
439
    = (ElfW(Ehdr) *) bootstrap_map.l_addr;
 
440
# endif
 
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.  */
 
443
  while (cnt-- > 0)
 
444
    if (phdr[cnt].p_type == PT_TLS)
 
445
      {
 
446
        void *tlsblock;
 
447
        size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
 
448
        char *p;
 
449
 
 
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;
 
454
        else
 
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);
 
461
 
 
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
 
465
           time.  */
 
466
# if TLS_TCB_AT_TP
 
467
        tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
 
468
                                    TLS_INIT_TCB_ALIGN)
 
469
                           + TLS_INIT_TCB_SIZE
 
470
                           + max_align);
 
471
# elif TLS_DTV_AT_TP
 
472
        tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
 
473
                                    bootstrap_map.l_tls_align)
 
474
                           + bootstrap_map.l_tls_blocksize
 
475
                           + max_align);
 
476
# else
 
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"
 
480
# endif
 
481
        /* Align the TLS block.  */
 
482
        tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
 
483
                             & ~(max_align - 1));
 
484
 
 
485
        /* Initialize the dtv.  [0] is the length, [1] the generation
 
486
           counter.  */
 
487
        initdtv[0].counter = 1;
 
488
        initdtv[1].counter = 0;
 
489
 
 
490
        /* Initialize the TLS block.  */
 
491
# if TLS_TCB_AT_TP
 
492
        initdtv[2].pointer = tlsblock;
 
493
# elif TLS_DTV_AT_TP
 
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;
 
497
# else
 
498
#  error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
 
499
# endif
 
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));
 
505
# else
 
506
        {
 
507
          size_t remaining = (bootstrap_map.l_tls_blocksize
 
508
                              - bootstrap_map.l_tls_initimage_size);
 
509
          while (remaining-- > 0)
 
510
            *p++ = '\0';
 
511
        }
 
512
# endif
 
513
 
 
514
        /* Install the pointer to the dtv.  */
 
515
 
 
516
        /* Initialize the thread pointer.  */
 
517
# if TLS_TCB_AT_TP
 
518
        bootstrap_map.l_tls_offset
 
519
          = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
 
520
 
 
521
        INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
 
522
                     initdtv);
 
523
 
 
524
        const char *lossage = TLS_INIT_TP ((char *) tlsblock
 
525
                                           + bootstrap_map.l_tls_offset, 0);
 
526
# elif TLS_DTV_AT_TP
 
527
        INSTALL_DTV (tlsblock, initdtv);
 
528
        const char *lossage = TLS_INIT_TP (tlsblock, 0);
 
529
# else
 
530
#  error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
 
531
# endif
 
532
        if (__builtin_expect (lossage != NULL, 0))
 
533
          _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
 
534
                            lossage);
 
535
 
 
536
        /* So far this is module number one.  */
 
537
        bootstrap_map.l_tls_modid = 1;
 
538
 
 
539
        /* There can only be one PT_TLS entry.  */
 
540
        break;
 
541
      }
 
542
#endif  /* USE___THREAD */
 
543
 
 
544
#ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
 
545
  ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
 
546
#endif
 
547
 
 
548
  if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
 
549
    {
 
550
      /* Relocate ourselves so we can do normal function calls and
 
551
         data access using the global offset table.  */
 
552
 
 
553
      ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0, 0);
 
554
    }
 
555
  bootstrap_map.l_relocated = 1;
 
556
 
 
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).  */
 
560
 
 
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.  */
 
567
  {
 
568
#ifdef DONT_USE_BOOTSTRAP_MAP
 
569
    ElfW(Addr) entry = _dl_start_final (arg);
 
570
#else
 
571
    ElfW(Addr) entry = _dl_start_final (arg, &info);
 
572
#endif
 
573
 
 
574
#ifndef ELF_MACHINE_START_ADDRESS
 
575
# define ELF_MACHINE_START_ADDRESS(map, start) (start)
 
576
#endif
 
577
 
 
578
    return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, entry);
 
579
  }
 
580
}
 
581
 
 
582
 
 
583
 
 
584
/* Now life is peachy; we can do all normal operations.
 
585
   On to the real work.  */
 
586
 
 
587
/* Some helper functions.  */
 
588
 
 
589
/* Arguments to relocate_doit.  */
 
590
struct relocate_args
 
591
{
 
592
  struct link_map *l;
 
593
  int reloc_mode;
 
594
};
 
595
 
 
596
struct map_args
 
597
{
 
598
  /* Argument to map_doit.  */
 
599
  char *str;
 
600
  struct link_map *loader;
 
601
  int mode;
 
602
  /* Return value of map_doit.  */
 
603
  struct link_map *map;
 
604
};
 
605
 
 
606
struct dlmopen_args
 
607
{
 
608
  const char *fname;
 
609
  struct link_map *map;
 
610
};
 
611
 
 
612
struct lookup_args
 
613
{
 
614
  const char *name;
 
615
  struct link_map *map;
 
616
  void *result;
 
617
};
 
618
 
 
619
/* Arguments to version_check_doit.  */
 
620
struct version_check_args
 
621
{
 
622
  int doexit;
 
623
  int dotrace;
 
624
};
 
625
 
 
626
static void
 
627
relocate_doit (void *a)
 
628
{
 
629
  struct relocate_args *args = (struct relocate_args *) a;
 
630
 
 
631
  _dl_relocate_object (args->l, args->l->l_scope, args->reloc_mode, 0);
 
632
}
 
633
 
 
634
static void
 
635
map_doit (void *a)
 
636
{
 
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);
 
640
}
 
641
 
 
642
static void
 
643
dlmopen_doit (void *a)
 
644
{
 
645
  struct dlmopen_args *args = (struct dlmopen_args *) a;
 
646
  args->map = _dl_open (args->fname,
 
647
                        (RTLD_LAZY | __RTLD_DLOPEN | __RTLD_AUDIT
 
648
                         | __RTLD_SECURE),
 
649
                        dl_main, LM_ID_NEWLM, _dl_argc, INTUSE(_dl_argv),
 
650
                        __environ);
 
651
}
 
652
 
 
653
static void
 
654
lookup_doit (void *a)
 
655
{
 
656
  struct lookup_args *args = (struct lookup_args *) a;
 
657
  const ElfW(Sym) *ref = NULL;
 
658
  args->result = 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);
 
662
  if (ref != NULL)
 
663
    args->result = DL_SYMBOL_ADDRESS (l, ref);
 
664
}
 
665
 
 
666
static void
 
667
version_check_doit (void *a)
 
668
{
 
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.  */
 
673
    _exit (1);
 
674
}
 
675
 
 
676
 
 
677
static inline struct link_map *
 
678
find_needed (const char *name)
 
679
{
 
680
  struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
 
681
  unsigned int n = scope->r_nlist;
 
682
 
 
683
  while (n-- > 0)
 
684
    if (_dl_name_match_p (name, scope->r_list[n]))
 
685
      return scope->r_list[n];
 
686
 
 
687
  /* Should never happen.  */
 
688
  return NULL;
 
689
}
 
690
 
 
691
static int
 
692
match_version (const char *string, struct link_map *map)
 
693
{
 
694
  const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
 
695
  ElfW(Verdef) *def;
 
696
 
 
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.  */
 
700
    return 0;
 
701
 
 
702
  def = (ElfW(Verdef) *) ((char *) map->l_addr
 
703
                          + map->l_info[VERDEFTAG]->d_un.d_ptr);
 
704
  while (1)
 
705
    {
 
706
      ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
 
707
 
 
708
      /* Compare the version strings.  */
 
709
      if (strcmp (string, strtab + aux->vda_name) == 0)
 
710
        /* Bingo!  */
 
711
        return 1;
 
712
 
 
713
      /* If no more definitions we failed to find what we want.  */
 
714
      if (def->vd_next == 0)
 
715
        break;
 
716
 
 
717
      /* Next definition.  */
 
718
      def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
 
719
    }
 
720
 
 
721
  return 0;
 
722
}
 
723
 
 
724
static bool tls_init_tp_called;
 
725
 
 
726
static void *
 
727
init_tls (void)
 
728
{
 
729
  /* Number of elements in the static TLS block.  */
 
730
  GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
 
731
 
 
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)
 
735
    return NULL;
 
736
 
 
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;
 
741
 
 
742
  /* Allocate.  */
 
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.  */
 
748
 
 
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;
 
752
 
 
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);
 
756
  int i = 0;
 
757
  for (struct link_map *l = GL(dl_ns)[LM_ID_BASE]._ns_loaded; l != NULL;
 
758
       l = l->l_next)
 
759
    if (l->l_tls_blocksize != 0)
 
760
      {
 
761
        /* This is a module with TLS data.  Store the map reference.
 
762
           The generation counter is zero.  */
 
763
        slotinfo[i].map = l;
 
764
        /* slotinfo[i].gen = 0; */
 
765
        ++i;
 
766
      }
 
767
  assert (i == GL(dl_tls_max_dtv_idx));
 
768
 
 
769
  /* Compute the TLS offsets for the various blocks.  */
 
770
  _dl_determine_tlsoffset ();
 
771
 
 
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 ();
 
778
  if (tcbp == NULL)
 
779
    _dl_fatal_printf ("\
 
780
cannot allocate TLS data structures for initial thread");
 
781
 
 
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);
 
785
 
 
786
  /* And finally install it for the main thread.  If ld.so itself uses
 
787
     TLS we know the thread pointer was initialized earlier.  */
 
788
  const char *lossage
 
789
#ifdef USE___THREAD
 
790
    = TLS_INIT_TP (tcbp, USE___THREAD);
 
791
#else
 
792
    = TLS_INIT_TP (tcbp, 0);
 
793
#endif
 
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;
 
797
 
 
798
  return tcbp;
 
799
}
 
800
 
 
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)
 
806
{
 
807
  static void *data;
 
808
  return &data;
 
809
}
 
810
#endif
 
811
 
 
812
 
 
813
static unsigned int
 
814
do_preload (char *fname, struct link_map *main_map, const char *where)
 
815
{
 
816
  const char *objname;
 
817
  const char *err_str = NULL;
 
818
  struct map_args args;
 
819
  bool malloced;
 
820
 
 
821
  args.str = fname;
 
822
  args.loader = main_map;
 
823
  args.mode = __RTLD_SECURE;
 
824
 
 
825
  unsigned int old_nloaded = GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
 
826
 
 
827
  (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit, &args);
 
828
  if (__builtin_expect (err_str != NULL, 0))
 
829
    {
 
830
      _dl_error_printf ("\
 
831
ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
 
832
                        fname, where);
 
833
      /* No need to call free, this is still before
 
834
         the libc's malloc is used.  */
 
835
    }
 
836
  else if (GL(dl_ns)[LM_ID_BASE]._ns_nloaded != old_nloaded)
 
837
    /* It is no duplicate.  */
 
838
    return 1;
 
839
 
 
840
  /* Nothing loaded.  */
 
841
  return 0;
 
842
}
 
843
 
 
844
#if defined SHARED && defined _LIBC_REENTRANT \
 
845
    && defined __rtld_lock_default_lock_recursive
 
846
static void
 
847
rtld_lock_default_lock_recursive (void *lock)
 
848
{
 
849
  __rtld_lock_default_lock_recursive (lock);
 
850
}
 
851
 
 
852
static void
 
853
rtld_lock_default_unlock_recursive (void *lock)
 
854
{
 
855
  __rtld_lock_default_unlock_recursive (lock);
 
856
}
 
857
#endif
 
858
 
 
859
 
 
860
static void
 
861
security_init (void)
 
862
{
 
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);
 
867
#else
 
868
  __stack_chk_guard = stack_chk_guard;
 
869
#endif
 
870
 
 
871
  /* Set up the pointer guard as well, if necessary.  */
 
872
  if (GLRO(dl_pointer_guard))
 
873
    {
 
874
      uintptr_t pointer_chk_guard = _dl_setup_pointer_guard (_dl_random,
 
875
                                                             stack_chk_guard);
 
876
#ifdef THREAD_SET_POINTER_GUARD
 
877
      THREAD_SET_POINTER_GUARD (pointer_chk_guard);
 
878
#endif
 
879
      __pointer_chk_guard_local = pointer_chk_guard;
 
880
    }
 
881
 
 
882
  /* We do not need the _dl_random value anymore.  The less
 
883
     information we leave behind, the better, so clear the
 
884
     variable.  */
 
885
  _dl_random = NULL;
 
886
}
 
887
 
 
888
 
 
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;
 
895
 
 
896
static void
 
897
dl_main (const ElfW(Phdr) *phdr,
 
898
         ElfW(Word) phnum,
 
899
         ElfW(Addr) *user_entry,
 
900
         ElfW(auxv_t) *auxv)
 
901
{
 
902
  const ElfW(Phdr) *ph;
 
903
  enum mode mode;
 
904
  struct link_map *main_map;
 
905
  size_t file_size;
 
906
  char *file;
 
907
  bool has_interp = false;
 
908
  unsigned int i;
 
909
  bool prelinked = false;
 
910
  bool rtld_is_main = false;
 
911
#ifndef HP_TIMING_NONAVAIL
 
912
  hp_timing_t start;
 
913
  hp_timing_t stop;
 
914
  hp_timing_t diff;
 
915
#endif
 
916
  void *tcbp = NULL;
 
917
 
 
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;
 
921
#endif
 
922
 
 
923
  GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
 
924
 
 
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;
 
929
#endif
 
930
 
 
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;
 
934
 
 
935
  /* Process the environment variable which control the behaviour.  */
 
936
  process_envvars (&mode);
 
937
 
 
938
#ifndef HAVE_INLINED_SYSCALLS
 
939
  /* Set up a flag which tells we are just starting.  */
 
940
  INTUSE(_dl_starting_up) = 1;
 
941
#endif
 
942
 
 
943
  if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
 
944
    {
 
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:
 
949
 
 
950
         ld.so PROGRAM ARGS...
 
951
 
 
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
 
959
         installing it.  */
 
960
      rtld_is_main = true;
 
961
 
 
962
      /* Note the place where the dynamic linker actually came from.  */
 
963
      GL(dl_rtld_map).l_name = rtld_progname;
 
964
 
 
965
      while (_dl_argc > 1)
 
966
        if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
 
967
          {
 
968
            mode = list;
 
969
            GLRO(dl_lazy) = -1; /* This means do no dependency analysis.  */
 
970
 
 
971
            ++_dl_skip_args;
 
972
            --_dl_argc;
 
973
            ++INTUSE(_dl_argv);
 
974
          }
 
975
        else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
 
976
          {
 
977
            mode = verify;
 
978
 
 
979
            ++_dl_skip_args;
 
980
            --_dl_argc;
 
981
            ++INTUSE(_dl_argv);
 
982
          }
 
983
        else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-cache"))
 
984
          {
 
985
            GLRO(dl_inhibit_cache) = 1;
 
986
            ++_dl_skip_args;
 
987
            --_dl_argc;
 
988
            ++INTUSE(_dl_argv);
 
989
          }
 
990
        else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
 
991
                 && _dl_argc > 2)
 
992
          {
 
993
            library_path = INTUSE(_dl_argv)[2];
 
994
 
 
995
            _dl_skip_args += 2;
 
996
            _dl_argc -= 2;
 
997
            INTUSE(_dl_argv) += 2;
 
998
          }
 
999
        else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
 
1000
                 && _dl_argc > 2)
 
1001
          {
 
1002
            GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
 
1003
 
 
1004
            _dl_skip_args += 2;
 
1005
            _dl_argc -= 2;
 
1006
            INTUSE(_dl_argv) += 2;
 
1007
          }
 
1008
        else if (! strcmp (INTUSE(_dl_argv)[1], "--audit") && _dl_argc > 2)
 
1009
          {
 
1010
            process_dl_audit (INTUSE(_dl_argv)[2]);
 
1011
 
 
1012
            _dl_skip_args += 2;
 
1013
            _dl_argc -= 2;
 
1014
            INTUSE(_dl_argv) += 2;
 
1015
          }
 
1016
        else
 
1017
          break;
 
1018
 
 
1019
      /* If we have no further argument the program was called incorrectly.
 
1020
         Grant the user some education.  */
 
1021
      if (_dl_argc < 2)
 
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\
 
1035
\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\
 
1043
                        in LIST\n\
 
1044
  --audit LIST          use objects named in LIST as auditors\n");
 
1045
 
 
1046
      ++_dl_skip_args;
 
1047
      --_dl_argc;
 
1048
      ++INTUSE(_dl_argv);
 
1049
 
 
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.  */
 
1061
 
 
1062
      for (ph = phdr; ph < &phdr[phnum]; ++ph)
 
1063
        if (ph->p_type == PT_GNU_STACK)
 
1064
          {
 
1065
            GL(dl_stack_flags) = ph->p_flags;
 
1066
            break;
 
1067
          }
 
1068
 
 
1069
      if (__builtin_expect (mode, normal) == verify)
 
1070
        {
 
1071
          const char *objname;
 
1072
          const char *err_str = NULL;
 
1073
          struct map_args args;
 
1074
          bool malloced;
 
1075
 
 
1076
          args.str = rtld_progname;
 
1077
          args.loader = NULL;
 
1078
          args.mode = __RTLD_OPENEXEC;
 
1079
          (void) _dl_catch_error (&objname, &err_str, &malloced, map_doit,
 
1080
                                  &args);
 
1081
          if (__builtin_expect (err_str != NULL, 0))
 
1082
            /* We don't free the returned string, the programs stops
 
1083
               anyway.  */
 
1084
            _exit (EXIT_FAILURE);
 
1085
        }
 
1086
      else
 
1087
        {
 
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);
 
1092
 
 
1093
          HP_TIMING_DIFF (load_time, start, stop);
 
1094
        }
 
1095
 
 
1096
      /* Now the map for the main executable is available.  */
 
1097
      main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
 
1098
 
 
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");
 
1106
 
 
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;
 
1115
 
 
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++)
 
1120
        switch (av->a_type)
 
1121
          {
 
1122
          case AT_PHDR:
 
1123
            av->a_un.a_val = (uintptr_t) phdr;
 
1124
            break;
 
1125
          case AT_PHNUM:
 
1126
            av->a_un.a_val = phnum;
 
1127
            break;
 
1128
          case AT_ENTRY:
 
1129
            av->a_un.a_val = *user_entry;
 
1130
            break;
 
1131
          }
 
1132
#endif
 
1133
    }
 
1134
  else
 
1135
    {
 
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;
 
1144
 
 
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);
 
1149
 
 
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.
 
1154
 
 
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.  */
 
1164
 
 
1165
      /* We delay initializing the path structure until we got the dynamic
 
1166
         information for the program.  */
 
1167
    }
 
1168
 
 
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;
 
1175
 
 
1176
  /* Scan the program header table for the dynamic section.  */
 
1177
  for (ph = phdr; ph < &phdr[phnum]; ++ph)
 
1178
    switch (ph->p_type)
 
1179
      {
 
1180
      case PT_PHDR:
 
1181
        /* Find out the load address.  */
 
1182
        main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
 
1183
        break;
 
1184
      case PT_DYNAMIC:
 
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;
 
1188
        break;
 
1189
      case PT_INTERP:
 
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
 
1197
                                 + ph->p_vaddr);
 
1198
        /* _dl_rtld_libname.next = NULL;        Already zero.  */
 
1199
        GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
 
1200
 
 
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)
 
1207
          {
 
1208
            const char *p = NULL;
 
1209
            const char *cp = _dl_rtld_libname.name;
 
1210
 
 
1211
            /* Find the filename part of the path.  */
 
1212
            while (*cp != '\0')
 
1213
              if (*cp++ == '/')
 
1214
                p = cp;
 
1215
 
 
1216
            if (p != NULL)
 
1217
              {
 
1218
                _dl_rtld_libname2.name = p;
 
1219
                /* _dl_rtld_libname2.next = NULL;  Already zero.  */
 
1220
                _dl_rtld_libname.next = &_dl_rtld_libname2;
 
1221
              }
 
1222
          }
 
1223
 
 
1224
        has_interp = true;
 
1225
        break;
 
1226
      case PT_LOAD:
 
1227
        {
 
1228
          ElfW(Addr) mapstart;
 
1229
          ElfW(Addr) allocend;
 
1230
 
 
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;
 
1236
 
 
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;
 
1243
        }
 
1244
        break;
 
1245
 
 
1246
      case PT_TLS:
 
1247
        if (ph->p_memsz > 0)
 
1248
          {
 
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;
 
1257
            else
 
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;
 
1262
 
 
1263
            /* This image gets the ID one.  */
 
1264
            GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
 
1265
          }
 
1266
        break;
 
1267
 
 
1268
      case PT_GNU_STACK:
 
1269
        GL(dl_stack_flags) = ph->p_flags;
 
1270
        break;
 
1271
 
 
1272
      case PT_GNU_RELRO:
 
1273
        main_map->l_relro_addr = ph->p_vaddr;
 
1274
        main_map->l_relro_size = ph->p_memsz;
 
1275
        break;
 
1276
      }
 
1277
 
 
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)
 
1288
    {
 
1289
      /* We were invoked directly, so the program might not have a
 
1290
         PT_INTERP.  */
 
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;
 
1294
    }
 
1295
  else
 
1296
    assert (GL(dl_rtld_map).l_libname); /* How else did we get here?  */
 
1297
 
 
1298
  /* If the current libname is different from the SONAME, add the
 
1299
     latter as well.  */
 
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)
 
1304
    {
 
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;
 
1310
 
 
1311
      assert (GL(dl_rtld_map).l_libname->next == NULL);
 
1312
      GL(dl_rtld_map).l_libname->next = &newname;
 
1313
    }
 
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);
 
1317
 
 
1318
  if (! rtld_is_main)
 
1319
    {
 
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);
 
1324
    }
 
1325
 
 
1326
  if (__builtin_expect (mode, normal) == verify)
 
1327
    {
 
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)
 
1333
        _exit (1);
 
1334
 
 
1335
      /* We allow here some platform specific code.  */
 
1336
#ifdef DISTINGUISH_LIB_VERSIONS
 
1337
      DISTINGUISH_LIB_VERSIONS;
 
1338
#endif
 
1339
      _exit (has_interp ? 0 : 2);
 
1340
    }
 
1341
 
 
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)
 
1347
    {
 
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,
 
1354
                                           0, LM_ID_BASE);
 
1355
      if (__builtin_expect (l != NULL, 1))
 
1356
        {
 
1357
          static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
 
1358
 
 
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)
 
1363
            {
 
1364
              const ElfW(Phdr) *const ph = &l->l_phdr[i];
 
1365
              if (ph->p_type == PT_DYNAMIC)
 
1366
                {
 
1367
                  l->l_ld = (void *) ph->p_vaddr;
 
1368
                  l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
 
1369
                }
 
1370
              else if (ph->p_type == PT_LOAD)
 
1371
                {
 
1372
                  if (! l->l_addr)
 
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;
 
1379
                }
 
1380
              else
 
1381
                /* There must be no TLS segment.  */
 
1382
                assert (ph->p_type != PT_TLS);
 
1383
            }
 
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);
 
1390
          _dl_setup_hash (l);
 
1391
          l->l_relocated = 1;
 
1392
 
 
1393
          /* The vDSO is always used.  */
 
1394
          l->l_used = 1;
 
1395
 
 
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
 
1399
             element */
 
1400
          l->l_local_scope[0]->r_nlist = 1;
 
1401
          l->l_local_scope[0]->r_list = &l->l_real;
 
1402
 
 
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)
 
1408
            {
 
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);
 
1415
              if (copy == NULL)
 
1416
                _dl_fatal_printf ("out of memory\n");
 
1417
              l->l_libname->name = memcpy (copy, dsoname, len);
 
1418
              if (GLRO(dl_debug_mask))
 
1419
                l->l_name = copy;
 
1420
            }
 
1421
 
 
1422
          /* Add the vDSO to the object list.  */
 
1423
          _dl_add_to_namespace_list (l, LM_ID_BASE);
 
1424
 
 
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;
 
1431
 
 
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;
 
1437
# endif
 
1438
        }
 
1439
    }
 
1440
#endif
 
1441
 
 
1442
#ifdef DL_SYSDEP_OSCHECK
 
1443
  DL_SYSDEP_OSCHECK (_dl_fatal_printf);
 
1444
#endif
 
1445
 
 
1446
  /* Initialize the data structures for the search paths for shared
 
1447
     objects.  */
 
1448
  _dl_init_paths (library_path);
 
1449
 
 
1450
  /* Initialize _r_debug.  */
 
1451
  struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr,
 
1452
                                            LM_ID_BASE);
 
1453
  r->r_state = RT_CONSISTENT;
 
1454
 
 
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;
 
1466
  ++GL(dl_load_adds);
 
1467
 
 
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;
 
1473
 
 
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;
 
1481
 
 
1482
 
 
1483
  /* PT_GNU_RELRO is usually the last phdr.  */
 
1484
  size_t cnt = rtld_ehdr->e_phnum;
 
1485
  while (cnt-- > 0)
 
1486
    if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
 
1487
      {
 
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;
 
1490
        break;
 
1491
      }
 
1492
 
 
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 ();
 
1497
 
 
1498
  /* If we have auditing DSOs to load, do it now.  */
 
1499
  if (__builtin_expect (audit_list != NULL, 0))
 
1500
    {
 
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;
 
1504
 
 
1505
      /* Since we start using the auditing DSOs right away we need to
 
1506
         initialize the data structures now.  */
 
1507
      tcbp = init_tls ();
 
1508
 
 
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
 
1512
         fail later on.  */
 
1513
      security_init ();
 
1514
 
 
1515
      do
 
1516
        {
 
1517
          int tls_idx = GL(dl_tls_max_dtv_idx);
 
1518
 
 
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;
 
1526
          dlmargs.map = NULL;
 
1527
 
 
1528
          const char *objname;
 
1529
          const char *err_str = NULL;
 
1530
          bool malloced;
 
1531
          (void) _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit,
 
1532
                                  &dlmargs);
 
1533
          if (__builtin_expect (err_str != NULL, 0))
 
1534
            {
 
1535
            not_loaded:
 
1536
              _dl_error_printf ("\
 
1537
ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
 
1538
                                al->name, err_str);
 
1539
              if (malloced)
 
1540
                free ((char *) err_str);
 
1541
            }
 
1542
          else
 
1543
            {
 
1544
              struct lookup_args largs;
 
1545
              largs.name = "la_version";
 
1546
              largs.map = dlmargs.map;
 
1547
 
 
1548
              /* Check whether the interface version matches.  */
 
1549
              (void) _dl_catch_error (&objname, &err_str, &malloced,
 
1550
                                      lookup_doit, &largs);
 
1551
 
 
1552
              unsigned int (*laversion) (unsigned int);
 
1553
              unsigned int lav;
 
1554
              if  (err_str == NULL
 
1555
                   && (laversion = largs.result) != NULL
 
1556
                   && (lav = laversion (LAV_CURRENT)) > 0
 
1557
                   && lav <= LAV_CURRENT)
 
1558
                {
 
1559
                  /* Allocate structure for the callback function pointers.
 
1560
                     This call can never fail.  */
 
1561
                  union
 
1562
                  {
 
1563
                    struct audit_ifaces ifaces;
 
1564
#define naudit_ifaces 8
 
1565
                    void (*fptr[naudit_ifaces]) (void);
 
1566
                  } *newp = malloc (sizeof (*newp));
 
1567
 
 
1568
                  /* Names of the auditing interfaces.  All in one
 
1569
                     long string.  */
 
1570
                  static const char audit_iface_names[] =
 
1571
                    "la_activity\0"
 
1572
                    "la_objsearch\0"
 
1573
                    "la_objopen\0"
 
1574
                    "la_preinit\0"
 
1575
#if __ELF_NATIVE_CLASS == 32
 
1576
                    "la_symbind32\0"
 
1577
#elif __ELF_NATIVE_CLASS == 64
 
1578
                    "la_symbind64\0"
 
1579
#else
 
1580
# error "__ELF_NATIVE_CLASS must be defined"
 
1581
#endif
 
1582
#define STRING(s) __STRING (s)
 
1583
                    "la_" STRING (ARCH_LA_PLTENTER) "\0"
 
1584
                    "la_" STRING (ARCH_LA_PLTEXIT) "\0"
 
1585
                    "la_objclose\0";
 
1586
                  unsigned int cnt = 0;
 
1587
                  const char *cp = audit_iface_names;
 
1588
                  do
 
1589
                    {
 
1590
                      largs.name = cp;
 
1591
                      (void) _dl_catch_error (&objname, &err_str, &malloced,
 
1592
                                              lookup_doit, &largs);
 
1593
 
 
1594
                      /* Store the pointer.  */
 
1595
                      if (err_str == NULL && largs.result != NULL)
 
1596
                        {
 
1597
                          newp->fptr[cnt] = largs.result;
 
1598
 
 
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);
 
1603
                        }
 
1604
                      else
 
1605
                        newp->fptr[cnt] = NULL;
 
1606
                      ++cnt;
 
1607
 
 
1608
                      cp = (char *) rawmemchr (cp, '\0') + 1;
 
1609
                    }
 
1610
                  while (*cp != '\0');
 
1611
                  assert (cnt == naudit_ifaces);
 
1612
 
 
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;
 
1617
                  else
 
1618
                    last_audit = last_audit->next = &newp->ifaces;
 
1619
                  ++GLRO(dl_naudit);
 
1620
 
 
1621
                  /* Mark the DSO as being used for auditing.  */
 
1622
                  dlmargs.map->l_auditing = 1;
 
1623
                }
 
1624
              else
 
1625
                {
 
1626
                  /* We cannot use the DSO, it does not have the
 
1627
                     appropriate interfaces or it expects something
 
1628
                     more recent.  */
 
1629
#ifndef NDEBUG
 
1630
                  Lmid_t ns = dlmargs.map->l_ns;
 
1631
#endif
 
1632
                  _dl_close (dlmargs.map);
 
1633
 
 
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);
 
1637
 
 
1638
                  GL(dl_tls_max_dtv_idx) = tls_idx;
 
1639
                  goto not_loaded;
 
1640
                }
 
1641
            }
 
1642
 
 
1643
          al = al->next;
 
1644
        }
 
1645
      while (al != audit_list->next);
 
1646
 
 
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))
 
1650
        {
 
1651
          struct link_map *ls[2] = { main_map, &GL(dl_rtld_map) };
 
1652
 
 
1653
          for (unsigned int outer = 0; outer < 2; ++outer)
 
1654
            {
 
1655
              struct audit_ifaces *afct = GLRO(dl_audit);
 
1656
              for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
 
1657
                {
 
1658
                  if (afct->objopen != NULL)
 
1659
                    {
 
1660
                      ls[outer]->l_audit[cnt].bindflags
 
1661
                        = afct->objopen (ls[outer], LM_ID_BASE,
 
1662
                                         &ls[outer]->l_audit[cnt].cookie);
 
1663
 
 
1664
                      ls[outer]->l_audit_any_plt
 
1665
                        |= ls[outer]->l_audit[cnt].bindflags != 0;
 
1666
                    }
 
1667
 
 
1668
                  afct = afct->next;
 
1669
                }
 
1670
            }
 
1671
        }
 
1672
    }
 
1673
 
 
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);
 
1679
#else
 
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;
 
1684
 
 
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;
 
1689
#endif
 
1690
 
 
1691
  /* We start adding objects.  */
 
1692
  r->r_state = RT_ADD;
 
1693
  _dl_debug_state ();
 
1694
 
 
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))
 
1698
    {
 
1699
      struct audit_ifaces *afct = GLRO(dl_audit);
 
1700
      for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
 
1701
        {
 
1702
          if (afct->activity != NULL)
 
1703
            afct->activity (&main_map->l_audit[cnt].cookie, LA_ACT_ADD);
 
1704
 
 
1705
          afct = afct->next;
 
1706
        }
 
1707
    }
 
1708
 
 
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;
 
1715
 
 
1716
  if (__builtin_expect (preloadlist != NULL, 0))
 
1717
    {
 
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);
 
1724
      char *p;
 
1725
 
 
1726
      HP_TIMING_NOW (start);
 
1727
 
 
1728
      /* Prevent optimizing strsep.  Speed is not important here.  */
 
1729
      while ((p = (strsep) (&list, " :")) != NULL)
 
1730
        if (p[0] != '\0'
 
1731
            && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
 
1732
                || strchr (p, '/') == NULL))
 
1733
          npreloads += do_preload (p, main_map, "LD_PRELOAD");
 
1734
 
 
1735
      HP_TIMING_NOW (stop);
 
1736
      HP_TIMING_DIFF (diff, start, stop);
 
1737
      HP_TIMING_ACCUM_NT (load_time, diff);
 
1738
    }
 
1739
 
 
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
 
1745
     use.  */
 
1746
  static const char preload_file[] = "/etc/ld.so.preload";
 
1747
  if (__builtin_expect (__access (preload_file, R_OK) == 0, 0))
 
1748
    {
 
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))
 
1753
        {
 
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 `#'.  */
 
1757
          char *problem;
 
1758
          char *runp;
 
1759
          size_t rest;
 
1760
 
 
1761
          /* Eliminate comments.  */
 
1762
          runp = file;
 
1763
          rest = file_size;
 
1764
          while (rest > 0)
 
1765
            {
 
1766
              char *comment = memchr (runp, '#', rest);
 
1767
              if (comment == NULL)
 
1768
                break;
 
1769
 
 
1770
              rest -= comment - runp;
 
1771
              do
 
1772
                *comment = ' ';
 
1773
              while (--rest > 0 && *++comment != '\n');
 
1774
            }
 
1775
 
 
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] != ':')
 
1781
            {
 
1782
              problem = &file[file_size];
 
1783
              while (problem > file && problem[-1] != ' '
 
1784
                     && problem[-1] != '\t'
 
1785
                     && problem[-1] != '\n' && problem[-1] != ':')
 
1786
                --problem;
 
1787
 
 
1788
              if (problem > file)
 
1789
                problem[-1] = '\0';
 
1790
            }
 
1791
          else
 
1792
            {
 
1793
              problem = NULL;
 
1794
              file[file_size - 1] = '\0';
 
1795
            }
 
1796
 
 
1797
          HP_TIMING_NOW (start);
 
1798
 
 
1799
          if (file != problem)
 
1800
            {
 
1801
              char *p;
 
1802
              runp = file;
 
1803
              while ((p = strsep (&runp, ": \t\n")) != NULL)
 
1804
                if (p[0] != '\0')
 
1805
                  npreloads += do_preload (p, main_map, preload_file);
 
1806
            }
 
1807
 
 
1808
          if (problem != NULL)
 
1809
            {
 
1810
              char *p = strndupa (problem, file_size - (problem - file));
 
1811
 
 
1812
              npreloads += do_preload (p, main_map, preload_file);
 
1813
            }
 
1814
 
 
1815
          HP_TIMING_NOW (stop);
 
1816
          HP_TIMING_DIFF (diff, start, stop);
 
1817
          HP_TIMING_ACCUM_NT (load_time, diff);
 
1818
 
 
1819
          /* We don't need the file anymore.  */
 
1820
          __munmap (file, file_size);
 
1821
        }
 
1822
    }
 
1823
 
 
1824
  if (__builtin_expect (*first_preload != NULL, 0))
 
1825
    {
 
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]);
 
1829
      i = 0;
 
1830
      do
 
1831
        {
 
1832
          preloads[i++] = l;
 
1833
          l = l->l_next;
 
1834
        } while (l);
 
1835
      assert (i == npreloads);
 
1836
    }
 
1837
 
 
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);
 
1846
 
 
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;
 
1850
 
 
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;
 
1855
 
 
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))
 
1858
      break;
 
1859
 
 
1860
  bool rtld_multiple_ref = false;
 
1861
  if (__builtin_expect (i < main_map->l_searchlist.r_nlist, 1))
 
1862
    {
 
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;
 
1868
 
 
1869
      GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
 
1870
      if (__builtin_expect (mode, normal) == normal)
 
1871
        {
 
1872
          GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
 
1873
                                    ? main_map->l_searchlist.r_list[i + 1]
 
1874
                                    : NULL);
 
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);
 
1880
#endif
 
1881
        }
 
1882
      else
 
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;
 
1889
 
 
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)
 
1893
        {
 
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);
 
1896
        }
 
1897
    }
 
1898
 
 
1899
  /* Now let us see whether all libraries are available in the
 
1900
     versions we need.  */
 
1901
  {
 
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);
 
1906
  }
 
1907
 
 
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;
 
1916
  if (tcbp == NULL)
 
1917
    tcbp = init_tls ();
 
1918
 
 
1919
  if (__builtin_expect (audit_list == NULL, 1))
 
1920
    /* Initialize security features.  But only if we have not done it
 
1921
       earlier.  */
 
1922
    security_init ();
 
1923
 
 
1924
  if (__builtin_expect (mode, normal) != normal)
 
1925
    {
 
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.  */
 
1930
      struct link_map *l;
 
1931
 
 
1932
      if (GLRO_dl_debug_mask & DL_DEBUG_PRELINK)
 
1933
        {
 
1934
          struct r_scope_elem *scope = &main_map->l_searchlist;
 
1935
 
 
1936
          for (i = 0; i < scope->r_nlist; i++)
 
1937
            {
 
1938
              l = scope->r_list [i];
 
1939
              if (l->l_faked)
 
1940
                {
 
1941
                  _dl_printf ("\t%s => not found\n", l->l_libname->name);
 
1942
                  continue;
 
1943
                }
 
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);
 
1955
 
 
1956
              if (l->l_tls_modid)
 
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);
 
1960
              else
 
1961
                _dl_printf ("\n");
 
1962
            }
 
1963
        }
 
1964
      else if (GLRO_dl_debug_mask & DL_DEBUG_UNUSED)
 
1965
        {
 
1966
          /* Look through the dependencies of the main executable
 
1967
             and determine which of them is not actually
 
1968
             required.  */
 
1969
          struct link_map *l = main_map;
 
1970
 
 
1971
          /* Relocate the main executable.  */
 
1972
          struct relocate_args args = { .l = l,
 
1973
                                        .reloc_mode = ((GLRO(dl_lazy)
 
1974
                                                       ? RTLD_LAZY : 0)
 
1975
                                                       | __RTLD_NOIFUNC) };
 
1976
          _dl_receive_error (print_unresolved, relocate_doit, &args);
 
1977
 
 
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;
 
1981
          bool first = true;
 
1982
          while (dyn->d_tag != DT_NULL)
 
1983
            {
 
1984
              if (dyn->d_tag == DT_NEEDED)
 
1985
                {
 
1986
                  l = l->l_next;
 
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))
 
1991
                    l = l->l_next;
 
1992
#endif
 
1993
                  if (!l->l_used)
 
1994
                    {
 
1995
                      if (first)
 
1996
                        {
 
1997
                          _dl_printf ("Unused direct dependencies:\n");
 
1998
                          first = false;
 
1999
                        }
 
2000
 
 
2001
                      _dl_printf ("\t%s\n", l->l_name);
 
2002
                    }
 
2003
                }
 
2004
 
 
2005
              ++dyn;
 
2006
            }
 
2007
 
 
2008
          _exit (first != true);
 
2009
        }
 
2010
      else if (! main_map->l_info[DT_NEEDED])
 
2011
        _dl_printf ("\tstatically linked\n");
 
2012
      else
 
2013
        {
 
2014
          for (l = main_map->l_next; l; l = l->l_next)
 
2015
            if (l->l_faked)
 
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);
 
2022
            else
 
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);
 
2026
        }
 
2027
 
 
2028
      if (__builtin_expect (mode, trace) != trace)
 
2029
        for (i = 1; i < (unsigned int) _dl_argc; ++i)
 
2030
          {
 
2031
            const ElfW(Sym) *ref = NULL;
 
2032
            ElfW(Addr) loadbase;
 
2033
            lookup_t result;
 
2034
 
 
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);
 
2039
 
 
2040
            loadbase = LOOKUP_VALUE_ADDRESS (result);
 
2041
 
 
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);
 
2047
          }
 
2048
      else
 
2049
        {
 
2050
          /* If LD_WARN is set, warn about undefined symbols.  */
 
2051
          if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
 
2052
            {
 
2053
              /* We have to do symbol dependency testing.  */
 
2054
              struct relocate_args args;
 
2055
              unsigned int i;
 
2056
 
 
2057
              args.reloc_mode = ((GLRO(dl_lazy) ? RTLD_LAZY : 0)
 
2058
                                 | __RTLD_NOIFUNC);
 
2059
 
 
2060
              i = main_map->l_searchlist.r_nlist;
 
2061
              while (i-- > 0)
 
2062
                {
 
2063
                  struct link_map *l = main_map->l_initfini[i];
 
2064
                  if (l != &GL(dl_rtld_map) && ! l->l_faked)
 
2065
                    {
 
2066
                      args.l = l;
 
2067
                      _dl_receive_error (print_unresolved, relocate_doit,
 
2068
                                         &args);
 
2069
                    }
 
2070
                }
 
2071
 
 
2072
              if ((GLRO_dl_debug_mask & DL_DEBUG_PRELINK)
 
2073
                  && rtld_multiple_ref)
 
2074
                {
 
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);
 
2079
                }
 
2080
            }
 
2081
#define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
 
2082
          if (version_info)
 
2083
            {
 
2084
              /* Print more information.  This means here, print information
 
2085
                 about the versions needed.  */
 
2086
              int first = 1;
 
2087
              struct link_map *map;
 
2088
 
 
2089
              for (map = main_map; map != NULL; map = map->l_next)
 
2090
                {
 
2091
                  const char *strtab;
 
2092
                  ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
 
2093
                  ElfW(Verneed) *ent;
 
2094
 
 
2095
                  if (dyn == NULL)
 
2096
                    continue;
 
2097
 
 
2098
                  strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
 
2099
                  ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
 
2100
 
 
2101
                  if (first)
 
2102
                    {
 
2103
                      _dl_printf ("\n\tVersion information:\n");
 
2104
                      first = 0;
 
2105
                    }
 
2106
 
 
2107
                  _dl_printf ("\t%s:\n",
 
2108
                              map->l_name[0] ? map->l_name : rtld_progname);
 
2109
 
 
2110
                  while (1)
 
2111
                    {
 
2112
                      ElfW(Vernaux) *aux;
 
2113
                      struct link_map *needed;
 
2114
 
 
2115
                      needed = find_needed (strtab + ent->vn_file);
 
2116
                      aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
 
2117
 
 
2118
                      while (1)
 
2119
                        {
 
2120
                          const char *fname = NULL;
 
2121
 
 
2122
                          if (needed != NULL
 
2123
                              && match_version (strtab + aux->vna_name,
 
2124
                                                needed))
 
2125
                            fname = needed->l_name;
 
2126
 
 
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
 
2131
                                      ? "[WEAK] " : "",
 
2132
                                      fname ?: "not found");
 
2133
 
 
2134
                          if (aux->vna_next == 0)
 
2135
                            /* No more symbols.  */
 
2136
                            break;
 
2137
 
 
2138
                          /* Next symbol.  */
 
2139
                          aux = (ElfW(Vernaux) *) ((char *) aux
 
2140
                                                   + aux->vna_next);
 
2141
                        }
 
2142
 
 
2143
                      if (ent->vn_next == 0)
 
2144
                        /* No more dependencies.  */
 
2145
                        break;
 
2146
 
 
2147
                      /* Next dependency.  */
 
2148
                      ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
 
2149
                    }
 
2150
                }
 
2151
            }
 
2152
        }
 
2153
 
 
2154
      _exit (0);
 
2155
    }
 
2156
 
 
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))
 
2160
    {
 
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]);
 
2164
 
 
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) *)
 
2169
                   ((char *) liblist +
 
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;
 
2173
 
 
2174
      for (; r_list < r_listend && liblist < liblistend; r_list++)
 
2175
        {
 
2176
          l = *r_list;
 
2177
 
 
2178
          if (l == main_map)
 
2179
            continue;
 
2180
 
 
2181
          /* If the library is not mapped where it should, fail.  */
 
2182
          if (l->l_addr)
 
2183
            break;
 
2184
 
 
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)
 
2189
            break;
 
2190
 
 
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)
 
2194
            break;
 
2195
 
 
2196
          if (! _dl_name_match_p (strtab + liblist->l_name, l))
 
2197
            break;
 
2198
 
 
2199
          ++liblist;
 
2200
        }
 
2201
 
 
2202
 
 
2203
      if (r_list == r_listend && liblist == liblistend)
 
2204
        prelinked = true;
 
2205
 
 
2206
      if (__builtin_expect (GLRO_dl_debug_mask & DL_DEBUG_LIBS, 0))
 
2207
        _dl_debug_printf ("\nprelink checking: %s\n",
 
2208
                          prelinked ? "ok" : "failed");
 
2209
    }
 
2210
 
 
2211
 
 
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;
 
2214
 
 
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;
 
2218
 
 
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);
 
2222
 
 
2223
  /* Print scope information.  */
 
2224
  if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_SCOPES, 0))
 
2225
    {
 
2226
      _dl_debug_printf ("\nInitial object scopes\n");
 
2227
 
 
2228
      for (struct link_map *l = main_map; l != NULL; l = l->l_next)
 
2229
        _dl_show_scope (l, 0);
 
2230
    }
 
2231
 
 
2232
  if (prelinked)
 
2233
    {
 
2234
      if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
 
2235
        {
 
2236
          ElfW(Rela) *conflict, *conflictend;
 
2237
#ifndef HP_TIMING_NONAVAIL
 
2238
          hp_timing_t start;
 
2239
          hp_timing_t stop;
 
2240
#endif
 
2241
 
 
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) *)
 
2247
            ((char *) conflict
 
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);
 
2252
        }
 
2253
 
 
2254
 
 
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)
 
2257
        {
 
2258
          l->l_relocated = 1;
 
2259
          if (l->l_relro_size)
 
2260
            _dl_protect_relro (l);
 
2261
 
 
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);
 
2265
        }
 
2266
    }
 
2267
  else
 
2268
    {
 
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).  */
 
2277
 
 
2278
      int consider_profiling = GLRO(dl_profile) != NULL;
 
2279
#ifndef HP_TIMING_NONAVAIL
 
2280
      hp_timing_t start;
 
2281
      hp_timing_t stop;
 
2282
#endif
 
2283
 
 
2284
      /* If we are profiling we also must do lazy reloaction.  */
 
2285
      GLRO(dl_lazy) |= consider_profiling;
 
2286
 
 
2287
      HP_TIMING_NOW (start);
 
2288
      unsigned i = main_map->l_searchlist.r_nlist;
 
2289
      while (i-- > 0)
 
2290
        {
 
2291
          struct link_map *l = main_map->l_initfini[i];
 
2292
 
 
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;
 
2297
 
 
2298
          while (__builtin_expect (lnp != NULL, 0))
 
2299
            {
 
2300
              lnp->dont_free = 1;
 
2301
              lnp = lnp->next;
 
2302
            }
 
2303
          /* Also allocated with the fake malloc().  */
 
2304
          l->l_free_initfini = 0;
 
2305
 
 
2306
          if (l != &GL(dl_rtld_map))
 
2307
            _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy) ? RTLD_LAZY : 0,
 
2308
                                 consider_profiling);
 
2309
 
 
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);
 
2313
        }
 
2314
      HP_TIMING_NOW (stop);
 
2315
 
 
2316
      HP_TIMING_DIFF (relocate_time, start, stop);
 
2317
 
 
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 ();
 
2325
    }
 
2326
 
 
2327
#ifndef NONTLS_INIT_TP
 
2328
# define NONTLS_INIT_TP do { } while (0)
 
2329
#endif
 
2330
 
 
2331
  if (!was_tls_init_tp_called && GL(dl_tls_max_dtv_idx) > 0)
 
2332
    ++GL(dl_tls_generation);
 
2333
 
 
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);
 
2338
 
 
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)
 
2342
    {
 
2343
      const char *lossage
 
2344
#ifdef USE___THREAD
 
2345
        = TLS_INIT_TP (tcbp, USE___THREAD);
 
2346
#else
 
2347
        = TLS_INIT_TP (tcbp, 0);
 
2348
#endif
 
2349
      if (__builtin_expect (lossage != NULL, 0))
 
2350
        _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
 
2351
                          lossage);
 
2352
    }
 
2353
 
 
2354
  /* Make sure no new search directories have been added.  */
 
2355
  assert (GLRO(dl_init_all_dirs) == GL(dl_all_dirs));
 
2356
 
 
2357
  if (! prelinked && rtld_multiple_ref)
 
2358
    {
 
2359
      /* There was an explicit ref to the dynamic linker as a shared lib.
 
2360
         Re-relocate ourselves with user-controlled symbol definitions.
 
2361
 
 
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.  */
 
2365
 
 
2366
#ifndef HP_TIMING_NONAVAIL
 
2367
      hp_timing_t start;
 
2368
      hp_timing_t stop;
 
2369
      hp_timing_t add;
 
2370
#endif
 
2371
 
 
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);
 
2379
    }
 
2380
 
 
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 ();
 
2387
 
 
2388
#ifdef SHARED
 
2389
  /* Auditing checkpoint: we have added all objects.  */
 
2390
  if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
 
2391
    {
 
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)
 
2395
        {
 
2396
          struct audit_ifaces *afct = GLRO(dl_audit);
 
2397
          for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
 
2398
            {
 
2399
              if (afct->activity != NULL)
 
2400
                afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
 
2401
 
 
2402
              afct = afct->next;
 
2403
            }
 
2404
        }
 
2405
    }
 
2406
#endif
 
2407
 
 
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;
 
2412
  _dl_debug_state ();
 
2413
 
 
2414
#ifndef MAP_COPY
 
2415
  /* We must munmap() the cache file.  */
 
2416
  _dl_unload_cache ();
 
2417
#endif
 
2418
 
 
2419
  /* Once we return, _dl_sysdep_start will invoke
 
2420
     the DT_INIT functions and then *USER_ENTRY.  */
 
2421
}
 
2422
 
 
2423
/* This is a little helper function for resolving symbols while
 
2424
   tracing the binary.  */
 
2425
static void
 
2426
print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
 
2427
                  const char *errstring)
 
2428
{
 
2429
  if (objname[0] == '\0')
 
2430
    objname = rtld_progname ?: "<main program>";
 
2431
  _dl_error_printf ("%s (%s)\n", errstring, objname);
 
2432
}
 
2433
 
 
2434
/* This is a little helper function for resolving symbols while
 
2435
   tracing the binary.  */
 
2436
static void
 
2437
print_missing_version (int errcode __attribute__ ((unused)),
 
2438
                       const char *objname, const char *errstring)
 
2439
{
 
2440
  _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
 
2441
                    objname, errstring);
 
2442
}
 
2443
 
 
2444
#if __OPTION_EGLIBC_RTLD_DEBUG
 
2445
/* Nonzero if any of the debugging options is enabled.  */
 
2446
static int any_debug attribute_relro;
 
2447
 
 
2448
/* Process the string given as the parameter which explains which debugging
 
2449
   options are enabled.  */
 
2450
static void
 
2451
process_dl_debug (const char *dl_debug)
 
2452
{
 
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.  */
 
2455
  static const struct
 
2456
  {
 
2457
    unsigned char len;
 
2458
    const char name[10];
 
2459
    const char helptext[41];
 
2460
    unsigned short int mask;
 
2461
  } debopts[] =
 
2462
    {
 
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",
 
2477
        DL_DEBUG_SCOPES },
 
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",
 
2485
        DL_DEBUG_UNUSED },
 
2486
      { LEN_AND_STR ("help"), "display this help message and exit",
 
2487
        DL_DEBUG_HELP },
 
2488
    };
 
2489
#define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
 
2490
 
 
2491
  /* Skip separating white spaces and commas.  */
 
2492
  while (*dl_debug != '\0')
 
2493
    {
 
2494
      if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
 
2495
        {
 
2496
          size_t cnt;
 
2497
          size_t len = 1;
 
2498
 
 
2499
          while (dl_debug[len] != '\0' && dl_debug[len] != ' '
 
2500
                 && dl_debug[len] != ',' && dl_debug[len] != ':')
 
2501
            ++len;
 
2502
 
 
2503
          for (cnt = 0; cnt < ndebopts; ++cnt)
 
2504
            if (debopts[cnt].len == len
 
2505
                && memcmp (dl_debug, debopts[cnt].name, len) == 0)
 
2506
              {
 
2507
                GLRO_dl_debug_mask |= debopts[cnt].mask;
 
2508
                any_debug = 1;
 
2509
                break;
 
2510
              }
 
2511
 
 
2512
          if (cnt == ndebopts)
 
2513
            {
 
2514
              /* Display a warning and skip everything until next
 
2515
                 separator.  */
 
2516
              char *copy = strndupa (dl_debug, len);
 
2517
              _dl_error_printf ("\
 
2518
warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
 
2519
            }
 
2520
 
 
2521
          dl_debug += len;
 
2522
          continue;
 
2523
        }
 
2524
 
 
2525
      ++dl_debug;
 
2526
    }
 
2527
 
 
2528
  if (GLRO_dl_debug_mask & DL_DEBUG_UNUSED)
 
2529
    {
 
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.  */
 
2533
      GLRO(dl_lazy) = 0;
 
2534
    }
 
2535
 
 
2536
  if (GLRO_dl_debug_mask & DL_DEBUG_HELP)
 
2537
    {
 
2538
      size_t cnt;
 
2539
 
 
2540
      _dl_printf ("\
 
2541
Valid options for the LD_DEBUG environment variable are:\n\n");
 
2542
 
 
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);
 
2547
 
 
2548
      _dl_printf ("\n\
 
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");
 
2551
      _exit (0);
 
2552
    }
 
2553
}
 
2554
#endif /* __OPTION_EGLIBC_RTLD_DEBUG */
 
2555
 
 
2556
static void
 
2557
process_dl_audit (char *str)
 
2558
{
 
2559
  /* The parameter is a colon separated list of DSO names.  */
 
2560
  char *p;
 
2561
 
 
2562
  while ((p = (strsep) (&str, ":")) != NULL)
 
2563
    if (p[0] != '\0'
 
2564
        && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
 
2565
            || strchr (p, '/') == NULL))
 
2566
      {
 
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));
 
2570
        newp->name = p;
 
2571
 
 
2572
        if (audit_list == NULL)
 
2573
          audit_list = newp->next = newp;
 
2574
        else
 
2575
          {
 
2576
            newp->next = audit_list->next;
 
2577
            audit_list = audit_list->next = newp;
 
2578
          }
 
2579
      }
 
2580
}
 
2581
 
 
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
 
2584
   all the entries.  */
 
2585
extern char **_environ attribute_hidden;
 
2586
 
 
2587
 
 
2588
static void
 
2589
process_envvars (enum mode *modep)
 
2590
{
 
2591
  char **runp = _environ;
 
2592
  char *envline;
 
2593
  enum mode mode = normal;
 
2594
  char *debug_output = NULL;
 
2595
 
 
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];
 
2599
 
 
2600
  while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
 
2601
    {
 
2602
      size_t len = 0;
 
2603
 
 
2604
      while (envline[len] != '\0' && envline[len] != '=')
 
2605
        ++len;
 
2606
 
 
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.  */
 
2611
        continue;
 
2612
 
 
2613
      switch (len)
 
2614
        {
 
2615
        case 4:
 
2616
          /* Warning level, verbose or not.  */
 
2617
          if (memcmp (envline, "WARN", 4) == 0)
 
2618
            GLRO(dl_verbose) = envline[5] != '\0';
 
2619
          break;
 
2620
 
 
2621
        case 5:
 
2622
#if __OPTION_EGLIBC_RTLD_DEBUG
 
2623
          /* Debugging of the dynamic linker?  */
 
2624
          if (memcmp (envline, "DEBUG", 5) == 0)
 
2625
            {
 
2626
              process_dl_debug (&envline[6]);
 
2627
              break;
 
2628
            }
 
2629
#endif
 
2630
          if (memcmp (envline, "AUDIT", 5) == 0)
 
2631
            process_dl_audit (&envline[6]);
 
2632
          break;
 
2633
 
 
2634
        case 7:
 
2635
          /* Print information about versions.  */
 
2636
          if (memcmp (envline, "VERBOSE", 7) == 0)
 
2637
            {
 
2638
              version_info = envline[8] != '\0';
 
2639
              break;
 
2640
            }
 
2641
 
 
2642
          /* List of objects to be preloaded.  */
 
2643
          if (memcmp (envline, "PRELOAD", 7) == 0)
 
2644
            {
 
2645
              preloadlist = &envline[8];
 
2646
              break;
 
2647
            }
 
2648
 
 
2649
          /* Which shared object shall be profiled.  */
 
2650
          if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
 
2651
            GLRO(dl_profile) = &envline[8];
 
2652
          break;
 
2653
 
 
2654
        case 8:
 
2655
          /* Do we bind early?  */
 
2656
          if (memcmp (envline, "BIND_NOW", 8) == 0)
 
2657
            {
 
2658
              GLRO(dl_lazy) = envline[9] == '\0';
 
2659
              break;
 
2660
            }
 
2661
          if (memcmp (envline, "BIND_NOT", 8) == 0)
 
2662
            GLRO(dl_bind_not) = envline[9] != '\0';
 
2663
          break;
 
2664
 
 
2665
        case 9:
 
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)
 
2670
            _dl_show_auxv ();
 
2671
          break;
 
2672
 
 
2673
        case 10:
 
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,
 
2677
                                                      0, 0);
 
2678
          break;
 
2679
 
 
2680
        case 11:
 
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];
 
2685
          break;
 
2686
 
 
2687
        case 12:
 
2688
          /* The library search path.  */
 
2689
          if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
 
2690
            {
 
2691
              library_path = &envline[13];
 
2692
              break;
 
2693
            }
 
2694
 
 
2695
          /* Where to place the profiling data file.  */
 
2696
          if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
 
2697
            {
 
2698
              debug_output = &envline[13];
 
2699
              break;
 
2700
            }
 
2701
 
 
2702
          if (!INTUSE(__libc_enable_secure)
 
2703
              && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
 
2704
            GLRO(dl_dynamic_weak) = 1;
 
2705
          break;
 
2706
 
 
2707
        case 13:
 
2708
          /* We might have some extra environment variable with length 13
 
2709
             to handle.  */
 
2710
#ifdef EXTRA_LD_ENVVARS_13
 
2711
          EXTRA_LD_ENVVARS_13
 
2712
#endif
 
2713
          if (!INTUSE(__libc_enable_secure)
 
2714
              && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
 
2715
            {
 
2716
              GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
 
2717
              break;
 
2718
            }
 
2719
 
 
2720
          if (memcmp (envline, "POINTER_GUARD", 13) == 0)
 
2721
            GLRO(dl_pointer_guard) = envline[14] != '0';
 
2722
          break;
 
2723
 
 
2724
        case 14:
 
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];
 
2730
          break;
 
2731
 
 
2732
        case 16:
 
2733
          /* The mode of the dynamic linker can be set.  */
 
2734
          if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
 
2735
            {
 
2736
              mode = trace;
 
2737
              GLRO(dl_verbose) = 1;
 
2738
#if __OPTION_EGLIBC_RTLD_DEBUG
 
2739
              GLRO_dl_debug_mask |= DL_DEBUG_PRELINK;
 
2740
#endif
 
2741
              GLRO(dl_trace_prelink) = &envline[17];
 
2742
            }
 
2743
          break;
 
2744
 
 
2745
        case 20:
 
2746
          /* The mode of the dynamic linker can be set.  */
 
2747
          if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
 
2748
            mode = trace;
 
2749
          break;
 
2750
 
 
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
 
2756
          EXTRA_LD_ENVVARS
 
2757
#endif
 
2758
        }
 
2759
    }
 
2760
 
 
2761
  /* The caller wants this information.  */
 
2762
  *modep = mode;
 
2763
 
 
2764
  /* Extra security for SUID binaries.  Remove all dangerous environment
 
2765
     variables.  */
 
2766
  if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
 
2767
    {
 
2768
      static const char unsecure_envvars[] =
 
2769
#ifdef EXTRA_UNSECURE_ENVVARS
 
2770
        EXTRA_UNSECURE_ENVVARS
 
2771
#endif
 
2772
        UNSECURE_ENVVARS;
 
2773
      const char *nextp;
 
2774
 
 
2775
      nextp = unsecure_envvars;
 
2776
      do
 
2777
        {
 
2778
          unsetenv (nextp);
 
2779
          /* We could use rawmemchr but this need not be fast.  */
 
2780
          nextp = (char *) (strchr) (nextp, '\0') + 1;
 
2781
        }
 
2782
      while (*nextp != '\0');
 
2783
 
 
2784
      if (__access ("/etc/suid-debug", F_OK) != 0)
 
2785
        {
 
2786
          unsetenv ("MALLOC_CHECK_");
 
2787
#if __OPTION_EGLIBC_RTLD_DEBUG
 
2788
          GLRO_dl_debug_mask = 0;
 
2789
#endif
 
2790
        }
 
2791
 
 
2792
      if (mode != normal)
 
2793
        _exit (5);
 
2794
    }
 
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)
 
2800
    {
 
2801
#ifdef O_NOFOLLOW
 
2802
      const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
 
2803
#else
 
2804
      const int flags = O_WRONLY | O_APPEND | O_CREAT;
 
2805
#endif
 
2806
      size_t name_len = strlen (debug_output);
 
2807
      char buf[name_len + 12];
 
2808
      char *startp;
 
2809
 
 
2810
      buf[name_len + 11] = '\0';
 
2811
      startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
 
2812
      *--startp = '.';
 
2813
      startp = memcpy (startp - name_len, debug_output, name_len);
 
2814
 
 
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;
 
2819
    }
 
2820
#endif /* __OPTION_EGLIBC_RTLD_DEBUG */
 
2821
}
 
2822
 
 
2823
 
 
2824
/* Print the various times we collected.  */
 
2825
static void
 
2826
__attribute ((noinline))
 
2827
print_statistics (hp_timing_t *rtld_total_timep)
 
2828
{
 
2829
#ifndef HP_TIMING_NONAVAIL
 
2830
  char buf[200];
 
2831
  char *cp;
 
2832
  char *wp;
 
2833
 
 
2834
  /* Total time rtld used.  */
 
2835
  if (HP_TIMING_AVAIL)
 
2836
    {
 
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);
 
2840
 
 
2841
      /* Print relocation statistics.  */
 
2842
      char pbuf[30];
 
2843
      HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
 
2844
      cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
 
2845
                  pbuf + sizeof (pbuf), 10, 0);
 
2846
      wp = pbuf;
 
2847
      switch (pbuf + sizeof (pbuf) - cp)
 
2848
        {
 
2849
        case 3:
 
2850
          *wp++ = *cp++;
 
2851
        case 2:
 
2852
          *wp++ = *cp++;
 
2853
        case 1:
 
2854
          *wp++ = '.';
 
2855
          *wp++ = *cp++;
 
2856
        }
 
2857
      *wp = '\0';
 
2858
      _dl_debug_printf ("\
 
2859
            time needed for relocation: %s (%s%%)\n", buf, pbuf);
 
2860
    }
 
2861
#endif
 
2862
 
 
2863
  unsigned long int num_relative_relocations = 0;
 
2864
  for (Lmid_t ns = 0; ns < GL(dl_nns); ++ns)
 
2865
    {
 
2866
      if (GL(dl_ns)[ns]._ns_loaded == NULL)
 
2867
        continue;
 
2868
 
 
2869
      struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
 
2870
 
 
2871
      for (unsigned int i = 0; i < scope->r_nlist; i++)
 
2872
        {
 
2873
          struct link_map *l = scope->r_list [i];
 
2874
 
 
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)])
 
2884
#else
 
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)])
 
2888
#endif
 
2889
            num_relative_relocations
 
2890
              += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
 
2891
        }
 
2892
    }
 
2893
 
 
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);
 
2900
 
 
2901
#ifndef HP_TIMING_NONAVAIL
 
2902
  /* Time spend while loading the object and the dependencies.  */
 
2903
  if (HP_TIMING_AVAIL)
 
2904
    {
 
2905
      char pbuf[30];
 
2906
      HP_TIMING_PRINT (buf, sizeof (buf), load_time);
 
2907
      cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
 
2908
                  pbuf + sizeof (pbuf), 10, 0);
 
2909
      wp = pbuf;
 
2910
      switch (pbuf + sizeof (pbuf) - cp)
 
2911
        {
 
2912
        case 3:
 
2913
          *wp++ = *cp++;
 
2914
        case 2:
 
2915
          *wp++ = *cp++;
 
2916
        case 1:
 
2917
          *wp++ = '.';
 
2918
          *wp++ = *cp++;
 
2919
        }
 
2920
      *wp = '\0';
 
2921
      _dl_debug_printf ("\
 
2922
           time needed to load objects: %s (%s%%)\n",
 
2923
                                buf, pbuf);
 
2924
    }
 
2925
#endif
 
2926
}