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