2004-07-01 Roland McGrath <roland@redhat.com>
[glibc.git] / elf / rtld.c
blob31521c64844264f90a63c1fa86088de84200d4a4
1 /* Run time dynamic linker.
2 Copyright (C) 1995-2002, 2003, 2004 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18 02111-1307 USA. */
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-procinfo.h>
41 #include <tls.h>
43 #include <assert.h>
45 /* Avoid PLT use for our local calls at startup. */
46 extern __typeof (__mempcpy) __mempcpy attribute_hidden;
48 /* GCC has mental blocks about _exit. */
49 extern __typeof (_exit) exit_internal asm ("_exit") attribute_hidden;
50 #define _exit exit_internal
52 /* Helper function to handle errors while resolving symbols. */
53 static void print_unresolved (int errcode, const char *objname,
54 const char *errsting);
56 /* Helper function to handle errors when a version is missing. */
57 static void print_missing_version (int errcode, const char *objname,
58 const char *errsting);
60 /* Print the various times we collected. */
61 static void print_statistics (hp_timing_t *total_timep);
63 /* This is a list of all the modes the dynamic loader can be in. */
64 enum mode { normal, list, verify, trace };
66 /* Process all environments variables the dynamic linker must recognize.
67 Since all of them start with `LD_' we are a bit smarter while finding
68 all the entries. */
69 static void process_envvars (enum mode *modep);
71 int _dl_argc attribute_relro attribute_hidden;
72 #ifdef DL_ARGV_NOT_RELRO
73 char **_dl_argv = NULL;
74 #else
75 char **_dl_argv attribute_relro = NULL;
76 #endif
77 INTDEF(_dl_argv)
79 /* Nonzero if we were run directly. */
80 unsigned int _dl_skip_args attribute_relro attribute_hidden;
82 /* Set nonzero during loading and initialization of executable and
83 libraries, cleared before the executable's entry point runs. This
84 must not be initialized to nonzero, because the unused dynamic
85 linker loaded in for libc.so's "ld.so.1" dep will provide the
86 definition seen by libc.so's initializer; that value must be zero,
87 and will be since that dynamic linker's _dl_start and dl_main will
88 never be called. */
89 int _dl_starting_up = 0;
90 INTVARDEF(_dl_starting_up)
92 /* This is the structure which defines all variables global to ld.so
93 (except those which cannot be added for some reason). */
94 struct rtld_global _rtld_global =
96 /* Default presumption without further information is executable stack. */
97 ._dl_stack_flags = PF_R|PF_W|PF_X,
98 #ifdef _LIBC_REENTRANT
99 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER
100 #endif
102 /* If we would use strong_alias here the compiler would see a
103 non-hidden definition. This would undo the effect of the previous
104 declaration. So spell out was strong_alias does plus add the
105 visibility attribute. */
106 extern struct rtld_global _rtld_local
107 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
110 /* This variable is similar to _rtld_local, but all values are
111 read-only after relocation. */
112 struct rtld_global_ro _rtld_global_ro attribute_relro =
114 /* Get architecture specific initializer. */
115 #include <dl-procinfo.c>
116 #ifdef NEED_DL_SYSINFO
117 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
118 #endif
119 ._dl_debug_fd = STDERR_FILENO,
120 ._dl_use_load_bias = -2,
121 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
122 ._dl_hwcap_mask = HWCAP_IMPORTANT,
123 ._dl_lazy = 1,
124 ._dl_fpu_control = _FPU_DEFAULT,
126 /* Function pointers. */
127 ._dl_get_origin = _dl_get_origin,
128 ._dl_dst_count = _dl_dst_count,
129 ._dl_dst_substitute = _dl_dst_substitute,
130 ._dl_map_object = _dl_map_object,
131 ._dl_map_object_deps = _dl_map_object_deps,
132 ._dl_relocate_object = _dl_relocate_object,
133 ._dl_check_map_versions = _dl_check_map_versions,
134 ._dl_init = _dl_init,
135 ._dl_debug_state = _dl_debug_state,
136 #ifndef MAP_COPY
137 ._dl_unload_cache = _dl_unload_cache,
138 #endif
139 ._dl_debug_printf = _dl_debug_printf,
140 ._dl_catch_error = _dl_catch_error,
141 ._dl_signal_error = _dl_signal_error,
142 ._dl_start_profile = _dl_start_profile,
143 ._dl_mcount = _dl_mcount_internal,
144 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
145 ._dl_check_caller = _dl_check_caller
147 /* If we would use strong_alias here the compiler would see a
148 non-hidden definition. This would undo the effect of the previous
149 declaration. So spell out was strong_alias does plus add the
150 visibility attribute. */
151 extern struct rtld_global_ro _rtld_local_ro
152 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
155 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
156 ElfW(Addr) *user_entry);
158 /* These two variables cannot be moved into .data.rel.ro. */
159 static struct libname_list _dl_rtld_libname;
160 static struct libname_list _dl_rtld_libname2;
162 /* We expect less than a second for relocation. */
163 #ifdef HP_SMALL_TIMING_AVAIL
164 # undef HP_TIMING_AVAIL
165 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
166 #endif
168 /* Variable for statistics. */
169 #ifndef HP_TIMING_NONAVAIL
170 static hp_timing_t relocate_time;
171 static hp_timing_t load_time attribute_relro;
172 static hp_timing_t start_time attribute_relro;
173 #endif
175 /* Additional definitions needed by TLS initialization. */
176 #ifdef TLS_INIT_HELPER
177 TLS_INIT_HELPER
178 #endif
180 /* Helper function for syscall implementation. */
181 #ifdef DL_SYSINFO_IMPLEMENTATION
182 DL_SYSINFO_IMPLEMENTATION
183 #endif
185 /* Before ld.so is relocated we must not access variables which need
186 relocations. This means variables which are exported. Variables
187 declared as static are fine. If we can mark a variable hidden this
188 is fine, too. The latter is important here. We can avoid setting
189 up a temporary link map for ld.so if we can mark _rtld_global as
190 hidden. */
191 #if defined PI_STATIC_AND_HIDDEN && defined HAVE_HIDDEN \
192 && defined HAVE_VISIBILITY_ATTRIBUTE
193 # define DONT_USE_BOOTSTRAP_MAP 1
194 #endif
196 #ifdef DONT_USE_BOOTSTRAP_MAP
197 static ElfW(Addr) _dl_start_final (void *arg);
198 #else
199 struct dl_start_final_info
201 struct link_map l;
202 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
203 hp_timing_t start_time;
204 #endif
206 static ElfW(Addr) _dl_start_final (void *arg,
207 struct dl_start_final_info *info);
208 #endif
210 /* These defined magically in the linker script. */
211 extern char _begin[] attribute_hidden;
212 extern char _etext[] attribute_hidden;
213 extern char _end[] attribute_hidden;
216 #ifdef RTLD_START
217 RTLD_START
218 #else
219 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
220 #endif
222 #ifndef VALIDX
223 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
224 + DT_EXTRANUM + DT_VALTAGIDX (tag))
225 #endif
226 #ifndef ADDRIDX
227 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
228 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
229 #endif
231 /* This is the second half of _dl_start (below). It can be inlined safely
232 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
233 references. When the tools don't permit us to avoid using a GOT entry
234 for _dl_rtld_global (no attribute_hidden support), we must make sure
235 this function is not inlined (see below). */
237 #ifdef DONT_USE_BOOTSTRAP_MAP
238 static inline ElfW(Addr) __attribute__ ((always_inline))
239 _dl_start_final (void *arg)
240 #else
241 static ElfW(Addr) __attribute__ ((noinline))
242 _dl_start_final (void *arg, struct dl_start_final_info *info)
243 #endif
245 ElfW(Addr) start_addr;
247 if (HP_TIMING_AVAIL)
249 /* If it hasn't happen yet record the startup time. */
250 if (! HP_TIMING_INLINE)
251 HP_TIMING_NOW (start_time);
252 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
253 else
254 start_time = info->start_time;
255 #endif
257 /* Initialize the timing functions. */
258 HP_TIMING_DIFF_INIT ();
261 /* Transfer data about ourselves to the permanent link_map structure. */
262 #ifndef DONT_USE_BOOTSTRAP_MAP
263 GL(dl_rtld_map).l_addr = info->l.l_addr;
264 GL(dl_rtld_map).l_ld = info->l.l_ld;
265 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
266 sizeof GL(dl_rtld_map).l_info);
267 GL(dl_rtld_map).l_mach = info->l.l_mach;
268 #endif
269 _dl_setup_hash (&GL(dl_rtld_map));
270 GL(dl_rtld_map).l_opencount = 1;
271 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
272 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
273 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
274 /* Copy the TLS related data if necessary. */
275 #if USE_TLS && !defined DONT_USE_BOOTSTRAP_MAP
276 # if USE___THREAD
277 assert (info->l.l_tls_modid != 0);
278 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
279 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
280 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
281 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
282 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
283 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
284 GL(dl_rtld_map).l_tls_modid = 1;
285 # else
286 assert (info->l.l_tls_modid == 0);
287 # if NO_TLS_OFFSET != 0
288 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
289 # endif
290 # endif
292 #endif
294 #if HP_TIMING_AVAIL
295 HP_TIMING_NOW (GL(dl_cpuclock_offset));
296 #endif
298 /* Initialize the stack end variable. */
299 __libc_stack_end = __builtin_frame_address (0);
301 /* Call the OS-dependent function to set up life so we can do things like
302 file access. It will call `dl_main' (below) to do all the real work
303 of the dynamic linker, and then unwind our frame and run the user
304 entry point on the same stack we entered on. */
305 start_addr = _dl_sysdep_start (arg, &dl_main);
307 #ifndef HP_TIMING_NONAVAIL
308 hp_timing_t rtld_total_time;
309 if (HP_TIMING_AVAIL)
311 hp_timing_t end_time;
313 /* Get the current time. */
314 HP_TIMING_NOW (end_time);
316 /* Compute the difference. */
317 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
319 #endif
321 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
323 #ifndef HP_TIMING_NONAVAIL
324 print_statistics (&rtld_total_time);
325 #else
326 print_statistics (NULL);
327 #endif
330 return start_addr;
333 static ElfW(Addr) __attribute_used__ internal_function
334 _dl_start (void *arg)
336 #ifdef DONT_USE_BOOTSTRAP_MAP
337 # define bootstrap_map GL(dl_rtld_map)
338 #else
339 struct dl_start_final_info info;
340 # define bootstrap_map info.l
341 #endif
343 /* This #define produces dynamic linking inline functions for
344 bootstrap relocation instead of general-purpose relocation. */
345 #define RTLD_BOOTSTRAP
346 #define RESOLVE_MAP(sym, version, flags) \
347 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : &bootstrap_map)
348 #define RESOLVE(sym, version, flags) \
349 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : bootstrap_map.l_addr)
350 #include "dynamic-link.h"
352 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
353 #ifdef DONT_USE_BOOTSTRAP_MAP
354 HP_TIMING_NOW (start_time);
355 #else
356 HP_TIMING_NOW (info.start_time);
357 #endif
359 /* Partly clean the `bootstrap_map' structure up. Don't use
360 `memset' since it might not be built in or inlined and we cannot
361 make function calls at this point. Use '__builtin_memset' if we
362 know it is available. We do not have to clear the memory if we
363 do not have to use the temporary bootstrap_map. Global variables
364 are initialized to zero by default. */
365 #ifndef DONT_USE_BOOTSTRAP_MAP
366 # ifdef HAVE_BUILTIN_MEMSET
367 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
368 # else
369 for (size_t cnt = 0;
370 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
371 ++cnt)
372 bootstrap_map.l_info[cnt] = 0;
373 # endif
374 #endif
376 /* Figure out the run-time load address of the dynamic linker itself. */
377 bootstrap_map.l_addr = elf_machine_load_address ();
379 /* Read our own dynamic section and fill in the info array. */
380 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
381 elf_get_dynamic_info (&bootstrap_map, NULL);
383 #if defined USE_TLS && NO_TLS_OFFSET != 0
384 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
385 #endif
387 /* Get the dynamic linker's own program header. First we need the ELF
388 file header. The `_begin' symbol created by the linker script points
389 to it. When we have something like GOTOFF relocs, we can use a plain
390 reference to find the runtime address. Without that, we have to rely
391 on the `l_addr' value, which is not the value we want when prelinked. */
392 #if USE___THREAD
393 dtv_t initdtv[3];
394 ElfW(Ehdr) *ehdr
395 # ifdef DONT_USE_BOOTSTRAP_MAP
396 = (ElfW(Ehdr) *) &_begin;
397 # else
398 # error This will not work with prelink.
399 = (ElfW(Ehdr) *) bootstrap_map.l_addr;
400 # endif
401 ElfW(Phdr) *phdr = (ElfW(Phdr) *) ((void *) ehdr + ehdr->e_phoff);
402 size_t cnt = ehdr->e_phnum; /* PT_TLS is usually the last phdr. */
403 while (cnt-- > 0)
404 if (phdr[cnt].p_type == PT_TLS)
406 void *tlsblock;
407 size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
408 char *p;
410 bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
411 bootstrap_map.l_tls_align = phdr[cnt].p_align;
412 if (phdr[cnt].p_align == 0)
413 bootstrap_map.l_tls_firstbyte_offset = 0;
414 else
415 bootstrap_map.l_tls_firstbyte_offset = (phdr[cnt].p_vaddr
416 & (phdr[cnt].p_align - 1));
417 assert (bootstrap_map.l_tls_blocksize != 0);
418 bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
419 bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
420 + phdr[cnt].p_vaddr);
422 /* We can now allocate the initial TLS block. This can happen
423 on the stack. We'll get the final memory later when we
424 know all about the various objects loaded at startup
425 time. */
426 # if TLS_TCB_AT_TP
427 tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
428 TLS_INIT_TCB_ALIGN)
429 + TLS_INIT_TCB_SIZE
430 + max_align);
431 # elif TLS_DTV_AT_TP
432 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
433 bootstrap_map.l_tls_align)
434 + bootstrap_map.l_tls_blocksize
435 + max_align);
436 # else
437 /* In case a model with a different layout for the TCB and DTV
438 is defined add another #elif here and in the following #ifs. */
439 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
440 # endif
441 /* Align the TLS block. */
442 tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
443 & ~(max_align - 1));
445 /* Initialize the dtv. [0] is the length, [1] the generation
446 counter. */
447 initdtv[0].counter = 1;
448 initdtv[1].counter = 0;
450 /* Initialize the TLS block. */
451 # if TLS_TCB_AT_TP
452 initdtv[2].pointer = tlsblock;
453 # elif TLS_DTV_AT_TP
454 bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
455 bootstrap_map.l_tls_align);
456 initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
457 # else
458 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
459 # endif
460 p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
461 bootstrap_map.l_tls_initimage_size);
462 # ifdef HAVE_BUILTIN_MEMSET
463 __builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
464 - bootstrap_map.l_tls_initimage_size));
465 # else
467 size_t remaining = (bootstrap_map.l_tls_blocksize
468 - bootstrap_map.l_tls_initimage_size);
469 while (remaining-- > 0)
470 *p++ = '\0';
472 #endif
474 /* Install the pointer to the dtv. */
476 /* Initialize the thread pointer. */
477 # if TLS_TCB_AT_TP
478 bootstrap_map.l_tls_offset
479 = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
481 INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
482 initdtv);
484 const char *lossage = TLS_INIT_TP ((char *) tlsblock
485 + bootstrap_map.l_tls_offset, 0);
486 # elif TLS_DTV_AT_TP
487 INSTALL_DTV (tlsblock, initdtv);
488 const char *lossage = TLS_INIT_TP (tlsblock, 0);
489 # else
490 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
491 # endif
492 if (__builtin_expect (lossage != NULL, 0))
493 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
494 lossage);
496 /* So far this is module number one. */
497 bootstrap_map.l_tls_modid = 1;
499 /* There can only be one PT_TLS entry. */
500 break;
502 #endif /* USE___THREAD */
504 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
505 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
506 #endif
508 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
510 /* Relocate ourselves so we can do normal function calls and
511 data access using the global offset table. */
513 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
516 /* Please note that we don't allow profiling of this object and
517 therefore need not test whether we have to allocate the array
518 for the relocation results (as done in dl-reloc.c). */
520 /* Now life is sane; we can call functions and access global data.
521 Set up to use the operating system facilities, and find out from
522 the operating system's program loader where to find the program
523 header table in core. Put the rest of _dl_start into a separate
524 function, that way the compiler cannot put accesses to the GOT
525 before ELF_DYNAMIC_RELOCATE. */
527 #ifdef DONT_USE_BOOTSTRAP_MAP
528 ElfW(Addr) entry = _dl_start_final (arg);
529 #else
530 ElfW(Addr) entry = _dl_start_final (arg, &info);
531 #endif
533 #ifndef ELF_MACHINE_START_ADDRESS
534 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
535 #endif
537 return ELF_MACHINE_START_ADDRESS (GL(dl_loaded), entry);
543 /* Now life is peachy; we can do all normal operations.
544 On to the real work. */
546 /* Some helper functions. */
548 /* Arguments to relocate_doit. */
549 struct relocate_args
551 struct link_map *l;
552 int lazy;
555 struct map_args
557 /* Argument to map_doit. */
558 char *str;
559 struct link_map *loader;
560 int is_preloaded;
561 int mode;
562 /* Return value of map_doit. */
563 struct link_map *map;
566 /* Arguments to version_check_doit. */
567 struct version_check_args
569 int doexit;
570 int dotrace;
573 static void
574 relocate_doit (void *a)
576 struct relocate_args *args = (struct relocate_args *) a;
578 _dl_relocate_object (args->l, args->l->l_scope, args->lazy, 0);
581 static void
582 map_doit (void *a)
584 struct map_args *args = (struct map_args *) a;
585 args->map = _dl_map_object (args->loader, args->str,
586 args->is_preloaded, lt_library, 0, args->mode);
589 static void
590 version_check_doit (void *a)
592 struct version_check_args *args = (struct version_check_args *) a;
593 if (_dl_check_all_versions (GL(dl_loaded), 1, args->dotrace) && args->doexit)
594 /* We cannot start the application. Abort now. */
595 _exit (1);
599 static inline struct link_map *
600 find_needed (const char *name)
602 unsigned int n = GL(dl_loaded)->l_searchlist.r_nlist;
604 while (n-- > 0)
605 if (_dl_name_match_p (name, GL(dl_loaded)->l_searchlist.r_list[n]))
606 return GL(dl_loaded)->l_searchlist.r_list[n];
608 /* Should never happen. */
609 return NULL;
612 static int
613 match_version (const char *string, struct link_map *map)
615 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
616 ElfW(Verdef) *def;
618 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
619 if (map->l_info[VERDEFTAG] == NULL)
620 /* The file has no symbol versioning. */
621 return 0;
623 def = (ElfW(Verdef) *) ((char *) map->l_addr
624 + map->l_info[VERDEFTAG]->d_un.d_ptr);
625 while (1)
627 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
629 /* Compare the version strings. */
630 if (strcmp (string, strtab + aux->vda_name) == 0)
631 /* Bingo! */
632 return 1;
634 /* If no more definitions we failed to find what we want. */
635 if (def->vd_next == 0)
636 break;
638 /* Next definition. */
639 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
642 return 0;
645 #ifdef _LIBC_REENTRANT
646 /* _dl_error_catch_tsd points to this for the single-threaded case.
647 It's reset by the thread library for multithreaded programs. */
648 void ** __attribute__ ((const))
649 _dl_initial_error_catch_tsd (void)
651 static void *data;
652 return &data;
654 #endif
656 #if defined SHARED && defined _LIBC_REENTRANT \
657 && defined __rtld_lock_default_lock_recursive
658 static void rtld_lock_default_lock_recursive (void *lock)
660 __rtld_lock_default_lock_recursive (lock);
663 static void rtld_lock_default_unlock_recursive (void *lock)
665 __rtld_lock_default_unlock_recursive (lock);
667 #endif
670 /* The library search path. */
671 static const char *library_path attribute_relro;
672 /* The list preloaded objects. */
673 static const char *preloadlist attribute_relro;
674 /* Nonzero if information about versions has to be printed. */
675 static int version_info attribute_relro;
677 static void
678 dl_main (const ElfW(Phdr) *phdr,
679 ElfW(Word) phnum,
680 ElfW(Addr) *user_entry)
682 const ElfW(Phdr) *ph;
683 enum mode mode;
684 struct link_map **preloads;
685 unsigned int npreloads;
686 size_t file_size;
687 char *file;
688 bool has_interp = false;
689 unsigned int i;
690 bool prelinked = false;
691 bool rtld_is_main = false;
692 #ifndef HP_TIMING_NONAVAIL
693 hp_timing_t start;
694 hp_timing_t stop;
695 hp_timing_t diff;
696 #endif
697 #ifdef USE_TLS
698 void *tcbp;
699 #endif
701 #ifdef _LIBC_REENTRANT
702 /* Explicit initialization since the reloc would just be more work. */
703 GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
704 #endif
706 #ifdef USE_TLS
707 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
708 #endif
710 #if defined SHARED && defined _LIBC_REENTRANT \
711 && defined __rtld_lock_default_lock_recursive
712 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
713 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
714 #endif
716 /* The explicit initialization here is cheaper than processing the reloc
717 in the _rtld_local definition's initializer. */
718 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
720 /* Process the environment variable which control the behaviour. */
721 process_envvars (&mode);
723 /* Set up a flag which tells we are just starting. */
724 INTUSE(_dl_starting_up) = 1;
726 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
728 /* Ho ho. We are not the program interpreter! We are the program
729 itself! This means someone ran ld.so as a command. Well, that
730 might be convenient to do sometimes. We support it by
731 interpreting the args like this:
733 ld.so PROGRAM ARGS...
735 The first argument is the name of a file containing an ELF
736 executable we will load and run with the following arguments.
737 To simplify life here, PROGRAM is searched for using the
738 normal rules for shared objects, rather than $PATH or anything
739 like that. We just load it and use its entry point; we don't
740 pay attention to its PT_INTERP command (we are the interpreter
741 ourselves). This is an easy way to test a new ld.so before
742 installing it. */
743 rtld_is_main = true;
745 /* Note the place where the dynamic linker actually came from. */
746 GL(dl_rtld_map).l_name = rtld_progname;
748 while (_dl_argc > 1)
749 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
751 mode = list;
752 GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
754 ++_dl_skip_args;
755 --_dl_argc;
756 ++INTUSE(_dl_argv);
758 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
760 mode = verify;
762 ++_dl_skip_args;
763 --_dl_argc;
764 ++INTUSE(_dl_argv);
766 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
767 && _dl_argc > 2)
769 library_path = INTUSE(_dl_argv)[2];
771 _dl_skip_args += 2;
772 _dl_argc -= 2;
773 INTUSE(_dl_argv) += 2;
775 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
776 && _dl_argc > 2)
778 GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
780 _dl_skip_args += 2;
781 _dl_argc -= 2;
782 INTUSE(_dl_argv) += 2;
784 else
785 break;
787 /* If we have no further argument the program was called incorrectly.
788 Grant the user some education. */
789 if (_dl_argc < 2)
790 _dl_fatal_printf ("\
791 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
792 You have invoked `ld.so', the helper program for shared library executables.\n\
793 This program usually lives in the file `/lib/ld.so', and special directives\n\
794 in executable files using ELF shared libraries tell the system's program\n\
795 loader to load the helper program from this file. This helper program loads\n\
796 the shared libraries needed by the program executable, prepares the program\n\
797 to run, and runs it. You may invoke this helper program directly from the\n\
798 command line to load and run an ELF executable file; this is like executing\n\
799 that file itself, but always uses this helper program from the file you\n\
800 specified, instead of the helper program file specified in the executable\n\
801 file you run. This is mostly of use for maintainers to test new versions\n\
802 of this helper program; chances are you did not intend to run this program.\n\
804 --list list all dependencies and how they are resolved\n\
805 --verify verify that given object really is a dynamically linked\n\
806 object we can handle\n\
807 --library-path PATH use given PATH instead of content of the environment\n\
808 variable LD_LIBRARY_PATH\n\
809 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
810 in LIST\n");
812 ++_dl_skip_args;
813 --_dl_argc;
814 ++INTUSE(_dl_argv);
816 /* Initialize the data structures for the search paths for shared
817 objects. */
818 _dl_init_paths (library_path);
820 /* The initialization of _dl_stack_flags done below assumes the
821 executable's PT_GNU_STACK may have been honored by the kernel, and
822 so a PT_GNU_STACK with PF_X set means the stack started out with
823 execute permission. However, this is not really true if the
824 dynamic linker is the executable the kernel loaded. For this
825 case, we must reinitialize _dl_stack_flags to match the dynamic
826 linker itself. If the dynamic linker was built with a
827 PT_GNU_STACK, then the kernel may have loaded us with a
828 nonexecutable stack that we will have to make executable when we
829 load the program below unless it has a PT_GNU_STACK indicating
830 nonexecutable stack is ok. */
832 for (ph = phdr; ph < &phdr[phnum]; ++ph)
833 if (ph->p_type == PT_GNU_STACK)
835 GL(dl_stack_flags) = ph->p_flags;
836 break;
839 if (__builtin_expect (mode, normal) == verify)
841 const char *objname;
842 const char *err_str = NULL;
843 struct map_args args;
845 args.str = rtld_progname;
846 args.loader = NULL;
847 args.is_preloaded = 0;
848 args.mode = __RTLD_OPENEXEC;
849 (void) _dl_catch_error (&objname, &err_str, map_doit, &args);
850 if (__builtin_expect (err_str != NULL, 0))
851 /* We don't free the returned string, the programs stops
852 anyway. */
853 _exit (EXIT_FAILURE);
855 else
857 HP_TIMING_NOW (start);
858 _dl_map_object (NULL, rtld_progname, 0, lt_library, 0,
859 __RTLD_OPENEXEC);
860 HP_TIMING_NOW (stop);
862 HP_TIMING_DIFF (load_time, start, stop);
865 phdr = GL(dl_loaded)->l_phdr;
866 phnum = GL(dl_loaded)->l_phnum;
867 /* We overwrite here a pointer to a malloc()ed string. But since
868 the malloc() implementation used at this point is the dummy
869 implementations which has no real free() function it does not
870 makes sense to free the old string first. */
871 GL(dl_loaded)->l_name = (char *) "";
872 *user_entry = GL(dl_loaded)->l_entry;
874 else
876 /* Create a link_map for the executable itself.
877 This will be what dlopen on "" returns. */
878 _dl_new_object ((char *) "", "", lt_executable, NULL);
879 if (GL(dl_loaded) == NULL)
880 _dl_fatal_printf ("cannot allocate memory for link map\n");
881 GL(dl_loaded)->l_phdr = phdr;
882 GL(dl_loaded)->l_phnum = phnum;
883 GL(dl_loaded)->l_entry = *user_entry;
885 /* At this point we are in a bit of trouble. We would have to
886 fill in the values for l_dev and l_ino. But in general we
887 do not know where the file is. We also do not handle AT_EXECFD
888 even if it would be passed up.
890 We leave the values here defined to 0. This is normally no
891 problem as the program code itself is normally no shared
892 object and therefore cannot be loaded dynamically. Nothing
893 prevent the use of dynamic binaries and in these situations
894 we might get problems. We might not be able to find out
895 whether the object is already loaded. But since there is no
896 easy way out and because the dynamic binary must also not
897 have an SONAME we ignore this program for now. If it becomes
898 a problem we can force people using SONAMEs. */
900 /* We delay initializing the path structure until we got the dynamic
901 information for the program. */
904 GL(dl_loaded)->l_map_end = 0;
905 GL(dl_loaded)->l_text_end = 0;
906 /* Perhaps the executable has no PT_LOAD header entries at all. */
907 GL(dl_loaded)->l_map_start = ~0;
908 /* We opened the file, account for it. */
909 ++GL(dl_loaded)->l_opencount;
911 /* Scan the program header table for the dynamic section. */
912 for (ph = phdr; ph < &phdr[phnum]; ++ph)
913 switch (ph->p_type)
915 case PT_PHDR:
916 /* Find out the load address. */
917 GL(dl_loaded)->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
918 break;
919 case PT_DYNAMIC:
920 /* This tells us where to find the dynamic section,
921 which tells us everything we need to do. */
922 GL(dl_loaded)->l_ld = (void *) GL(dl_loaded)->l_addr + ph->p_vaddr;
923 break;
924 case PT_INTERP:
925 /* This "interpreter segment" was used by the program loader to
926 find the program interpreter, which is this program itself, the
927 dynamic linker. We note what name finds us, so that a future
928 dlopen call or DT_NEEDED entry, for something that wants to link
929 against the dynamic linker as a shared library, will know that
930 the shared object is already loaded. */
931 _dl_rtld_libname.name = ((const char *) GL(dl_loaded)->l_addr
932 + ph->p_vaddr);
933 /* _dl_rtld_libname.next = NULL; Already zero. */
934 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
936 /* Ordinarilly, we would get additional names for the loader from
937 our DT_SONAME. This can't happen if we were actually linked as
938 a static executable (detect this case when we have no DYNAMIC).
939 If so, assume the filename component of the interpreter path to
940 be our SONAME, and add it to our name list. */
941 if (GL(dl_rtld_map).l_ld == NULL)
943 const char *p = NULL;
944 const char *cp = _dl_rtld_libname.name;
946 /* Find the filename part of the path. */
947 while (*cp != '\0')
948 if (*cp++ == '/')
949 p = cp;
951 if (p != NULL)
953 _dl_rtld_libname2.name = p;
954 /* _dl_rtld_libname2.next = NULL; Already zero. */
955 _dl_rtld_libname.next = &_dl_rtld_libname2;
959 has_interp = true;
960 break;
961 case PT_LOAD:
963 ElfW(Addr) mapstart;
964 ElfW(Addr) allocend;
966 /* Remember where the main program starts in memory. */
967 mapstart = (GL(dl_loaded)->l_addr
968 + (ph->p_vaddr & ~(ph->p_align - 1)));
969 if (GL(dl_loaded)->l_map_start > mapstart)
970 GL(dl_loaded)->l_map_start = mapstart;
972 /* Also where it ends. */
973 allocend = GL(dl_loaded)->l_addr + ph->p_vaddr + ph->p_memsz;
974 if (GL(dl_loaded)->l_map_end < allocend)
975 GL(dl_loaded)->l_map_end = allocend;
976 if ((ph->p_flags & PF_X) && allocend > GL(dl_loaded)->l_text_end)
977 GL(dl_loaded)->l_text_end = allocend;
979 break;
980 #ifdef USE_TLS
981 case PT_TLS:
982 if (ph->p_memsz > 0)
984 /* Note that in the case the dynamic linker we duplicate work
985 here since we read the PT_TLS entry already in
986 _dl_start_final. But the result is repeatable so do not
987 check for this special but unimportant case. */
988 GL(dl_loaded)->l_tls_blocksize = ph->p_memsz;
989 GL(dl_loaded)->l_tls_align = ph->p_align;
990 if (ph->p_align == 0)
991 GL(dl_loaded)->l_tls_firstbyte_offset = 0;
992 else
993 GL(dl_loaded)->l_tls_firstbyte_offset = (ph->p_vaddr
994 & (ph->p_align - 1));
995 GL(dl_loaded)->l_tls_initimage_size = ph->p_filesz;
996 GL(dl_loaded)->l_tls_initimage = (void *) ph->p_vaddr;
998 /* This image gets the ID one. */
999 GL(dl_tls_max_dtv_idx) = GL(dl_loaded)->l_tls_modid = 1;
1001 break;
1002 #endif
1003 case PT_GNU_STACK:
1004 GL(dl_stack_flags) = ph->p_flags;
1005 break;
1007 case PT_GNU_RELRO:
1008 GL(dl_loaded)->l_relro_addr = ph->p_vaddr;
1009 GL(dl_loaded)->l_relro_size = ph->p_memsz;
1010 break;
1012 #ifdef USE_TLS
1013 /* Adjust the address of the TLS initialization image in case
1014 the executable is actually an ET_DYN object. */
1015 if (GL(dl_loaded)->l_tls_initimage != NULL)
1016 GL(dl_loaded)->l_tls_initimage
1017 = (char *) GL(dl_loaded)->l_tls_initimage + GL(dl_loaded)->l_addr;
1018 #endif
1019 if (! GL(dl_loaded)->l_map_end)
1020 GL(dl_loaded)->l_map_end = ~0;
1021 if (! GL(dl_loaded)->l_text_end)
1022 GL(dl_loaded)->l_text_end = ~0;
1023 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1025 /* We were invoked directly, so the program might not have a
1026 PT_INTERP. */
1027 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1028 /* _dl_rtld_libname.next = NULL; Already zero. */
1029 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1031 else
1032 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1034 if (! rtld_is_main)
1036 /* Extract the contents of the dynamic section for easy access. */
1037 elf_get_dynamic_info (GL(dl_loaded), NULL);
1038 if (GL(dl_loaded)->l_info[DT_HASH])
1039 /* Set up our cache of pointers into the hash table. */
1040 _dl_setup_hash (GL(dl_loaded));
1043 if (__builtin_expect (mode, normal) == verify)
1045 /* We were called just to verify that this is a dynamic
1046 executable using us as the program interpreter. Exit with an
1047 error if we were not able to load the binary or no interpreter
1048 is specified (i.e., this is no dynamically linked binary. */
1049 if (GL(dl_loaded)->l_ld == NULL)
1050 _exit (1);
1052 /* We allow here some platform specific code. */
1053 #ifdef DISTINGUISH_LIB_VERSIONS
1054 DISTINGUISH_LIB_VERSIONS;
1055 #endif
1056 _exit (has_interp ? 0 : 2);
1059 if (! rtld_is_main)
1060 /* Initialize the data structures for the search paths for shared
1061 objects. */
1062 _dl_init_paths (library_path);
1064 /* Put the link_map for ourselves on the chain so it can be found by
1065 name. Note that at this point the global chain of link maps contains
1066 exactly one element, which is pointed to by dl_loaded. */
1067 if (! GL(dl_rtld_map).l_name)
1068 /* If not invoked directly, the dynamic linker shared object file was
1069 found by the PT_INTERP name. */
1070 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1071 GL(dl_rtld_map).l_type = lt_library;
1072 GL(dl_loaded)->l_next = &GL(dl_rtld_map);
1073 GL(dl_rtld_map).l_prev = GL(dl_loaded);
1074 ++GL(dl_nloaded);
1075 ++GL(dl_load_adds);
1077 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1078 to not using bias for non-prelinked PIEs and libraries
1079 and using it for executables or prelinked PIEs or libraries. */
1080 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1081 GLRO(dl_use_load_bias) = (GL(dl_loaded)->l_addr == 0) ? -1 : 0;
1083 /* Set up the program header information for the dynamic linker
1084 itself. It is needed in the dl_iterate_phdr() callbacks. */
1085 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1086 ElfW(Phdr) *rtld_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1087 + rtld_ehdr->e_phoff);
1088 GL(dl_rtld_map).l_phdr = rtld_phdr;
1089 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1091 /* PT_GNU_RELRO is usually the last phdr. */
1092 size_t cnt = rtld_ehdr->e_phnum;
1093 while (cnt-- > 0)
1094 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1096 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1097 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1098 break;
1101 /* We have two ways to specify objects to preload: via environment
1102 variable and via the file /etc/ld.so.preload. The latter can also
1103 be used when security is enabled. */
1104 preloads = NULL;
1105 npreloads = 0;
1107 if (__builtin_expect (preloadlist != NULL, 0))
1109 /* The LD_PRELOAD environment variable gives list of libraries
1110 separated by white space or colons that are loaded before the
1111 executable's dependencies and prepended to the global scope
1112 list. If the binary is running setuid all elements
1113 containing a '/' are ignored since it is insecure. */
1114 char *list = strdupa (preloadlist);
1115 char *p;
1117 HP_TIMING_NOW (start);
1119 /* Prevent optimizing strsep. Speed is not important here. */
1120 while ((p = (strsep) (&list, " :")) != NULL)
1121 if (p[0] != '\0'
1122 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1123 || strchr (p, '/') == NULL))
1125 struct link_map *new_map = _dl_map_object (GL(dl_loaded), p, 1,
1126 lt_library, 0, 0);
1127 if (++new_map->l_opencount == 1)
1128 /* It is no duplicate. */
1129 ++npreloads;
1132 HP_TIMING_NOW (stop);
1133 HP_TIMING_DIFF (diff, start, stop);
1134 HP_TIMING_ACCUM_NT (load_time, diff);
1137 /* Read the contents of the file. */
1138 const char preload_file[] = "/etc/ld.so.preload";
1139 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1140 PROT_READ | PROT_WRITE);
1141 if (__builtin_expect (file != MAP_FAILED, 0))
1143 /* Parse the file. It contains names of libraries to be loaded,
1144 separated by white spaces or `:'. It may also contain
1145 comments introduced by `#'. */
1146 char *problem;
1147 char *runp;
1148 size_t rest;
1150 /* Eliminate comments. */
1151 runp = file;
1152 rest = file_size;
1153 while (rest > 0)
1155 char *comment = memchr (runp, '#', rest);
1156 if (comment == NULL)
1157 break;
1159 rest -= comment - runp;
1161 *comment = ' ';
1162 while (--rest > 0 && *++comment != '\n');
1165 /* We have one problematic case: if we have a name at the end of
1166 the file without a trailing terminating characters, we cannot
1167 place the \0. Handle the case separately. */
1168 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1169 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1171 problem = &file[file_size];
1172 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
1173 && problem[-1] != '\n' && problem[-1] != ':')
1174 --problem;
1176 if (problem > file)
1177 problem[-1] = '\0';
1179 else
1181 problem = NULL;
1182 file[file_size - 1] = '\0';
1185 HP_TIMING_NOW (start);
1187 if (file != problem)
1189 char *p;
1190 runp = file;
1191 while ((p = strsep (&runp, ": \t\n")) != NULL)
1192 if (p[0] != '\0')
1194 const char *objname;
1195 const char *err_str = NULL;
1196 struct map_args args;
1198 args.str = p;
1199 args.loader = GL(dl_loaded);
1200 args.is_preloaded = 1;
1201 args.mode = 0;
1203 (void) _dl_catch_error (&objname, &err_str, map_doit, &args);
1204 if (__builtin_expect (err_str != NULL, 0))
1206 _dl_error_printf ("\
1207 ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
1208 p, preload_file);
1209 /* No need to call free, this is still before the libc's
1210 malloc is used. */
1212 else if (++args.map->l_opencount == 1)
1213 /* It is no duplicate. */
1214 ++npreloads;
1218 if (problem != NULL)
1220 char *p = strndupa (problem, file_size - (problem - file));
1221 struct link_map *new_map = _dl_map_object (GL(dl_loaded), p, 1,
1222 lt_library, 0, 0);
1223 if (++new_map->l_opencount == 1)
1224 /* It is no duplicate. */
1225 ++npreloads;
1228 HP_TIMING_NOW (stop);
1229 HP_TIMING_DIFF (diff, start, stop);
1230 HP_TIMING_ACCUM_NT (load_time, diff);
1232 /* We don't need the file anymore. */
1233 __munmap (file, file_size);
1236 if (__builtin_expect (npreloads, 0) != 0)
1238 /* Set up PRELOADS with a vector of the preloaded libraries. */
1239 struct link_map *l;
1240 preloads = __alloca (npreloads * sizeof preloads[0]);
1241 l = GL(dl_rtld_map).l_next; /* End of the chain before preloads. */
1242 i = 0;
1245 preloads[i++] = l;
1246 l = l->l_next;
1247 } while (l);
1248 assert (i == npreloads);
1251 #ifdef NEED_DL_SYSINFO
1252 struct link_map *sysinfo_map = NULL;
1253 if (GLRO(dl_sysinfo_dso) != NULL)
1255 /* Do an abridged version of the work _dl_map_object_from_fd would do
1256 to map in the object. It's already mapped and prelinked (and
1257 better be, since it's read-only and so we couldn't relocate it).
1258 We just want our data structures to describe it as if we had just
1259 mapped and relocated it normally. */
1260 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL);
1261 if (__builtin_expect (l != NULL, 1))
1263 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT];
1265 l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1266 + GLRO(dl_sysinfo_dso)->e_phoff);
1267 l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1268 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1270 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1271 if (ph->p_type == PT_DYNAMIC)
1273 l->l_ld = (void *) ph->p_vaddr;
1274 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1276 else if (ph->p_type == PT_LOAD)
1278 if (! l->l_addr)
1279 l->l_addr = ph->p_vaddr;
1280 else if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1281 l->l_map_end = ph->p_vaddr + ph->p_memsz;
1282 else if ((ph->p_flags & PF_X)
1283 && ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1284 l->l_text_end = ph->p_vaddr + ph->p_memsz;
1287 l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1288 l->l_addr = l->l_map_start - l->l_addr;
1289 l->l_map_end += l->l_addr;
1290 l->l_text_end += l->l_addr;
1291 l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1292 elf_get_dynamic_info (l, dyn_temp);
1293 _dl_setup_hash (l);
1294 l->l_relocated = 1;
1296 /* Now that we have the info handy, use the DSO image's soname
1297 so this object can be looked up by name. Note that we do not
1298 set l_name here. That field gives the file name of the DSO,
1299 and this DSO is not associated with any file. */
1300 if (l->l_info[DT_SONAME] != NULL)
1302 /* Work around a kernel problem. The kernel cannot handle
1303 addresses in the vsyscall DSO pages in writev() calls. */
1304 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1305 + l->l_info[DT_SONAME]->d_un.d_val);
1306 size_t len = strlen (dsoname);
1307 char *copy = malloc (len);
1308 if (copy == NULL)
1309 _dl_fatal_printf ("out of memory\n");
1310 l->l_libname->name = memcpy (copy, dsoname, len);
1313 /* We have a prelinked DSO preloaded by the system. */
1314 if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1315 GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1316 sysinfo_map = l;
1319 #endif
1321 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1322 specified some libraries to load, these are inserted before the actual
1323 dependencies in the executable's searchlist for symbol resolution. */
1324 HP_TIMING_NOW (start);
1325 _dl_map_object_deps (GL(dl_loaded), preloads, npreloads, mode == trace, 0);
1326 HP_TIMING_NOW (stop);
1327 HP_TIMING_DIFF (diff, start, stop);
1328 HP_TIMING_ACCUM_NT (load_time, diff);
1330 /* Mark all objects as being in the global scope and set the open
1331 counter. */
1332 for (i = GL(dl_loaded)->l_searchlist.r_nlist; i > 0; )
1334 --i;
1335 GL(dl_loaded)->l_searchlist.r_list[i]->l_global = 1;
1336 ++GL(dl_loaded)->l_searchlist.r_list[i]->l_opencount;
1339 #ifndef MAP_ANON
1340 /* We are done mapping things, so close the zero-fill descriptor. */
1341 __close (_dl_zerofd);
1342 _dl_zerofd = -1;
1343 #endif
1345 /* Remove _dl_rtld_map from the chain. */
1346 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1347 if (GL(dl_rtld_map).l_next)
1348 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1350 if (__builtin_expect (GL(dl_rtld_map).l_opencount > 1, 1))
1352 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1353 put it back in the list of visible objects. We insert it into the
1354 chain in symbol search order because gdb uses the chain's order as
1355 its symbol search order. */
1356 i = 1;
1357 while (GL(dl_loaded)->l_searchlist.r_list[i] != &GL(dl_rtld_map))
1358 ++i;
1359 GL(dl_rtld_map).l_prev = GL(dl_loaded)->l_searchlist.r_list[i - 1];
1360 if (__builtin_expect (mode, normal) == normal)
1362 GL(dl_rtld_map).l_next = (i + 1 < GL(dl_loaded)->l_searchlist.r_nlist
1363 ? GL(dl_loaded)->l_searchlist.r_list[i + 1]
1364 : NULL);
1365 #ifdef NEED_DL_SYSINFO
1366 if (sysinfo_map != NULL
1367 && GL(dl_rtld_map).l_prev->l_next == sysinfo_map
1368 && GL(dl_rtld_map).l_next != sysinfo_map)
1369 GL(dl_rtld_map).l_prev = sysinfo_map;
1370 #endif
1372 else
1373 /* In trace mode there might be an invisible object (which we
1374 could not find) after the previous one in the search list.
1375 In this case it doesn't matter much where we put the
1376 interpreter object, so we just initialize the list pointer so
1377 that the assertion below holds. */
1378 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1380 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1381 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1382 if (GL(dl_rtld_map).l_next != NULL)
1384 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1385 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1389 /* Now let us see whether all libraries are available in the
1390 versions we need. */
1392 struct version_check_args args;
1393 args.doexit = mode == normal;
1394 args.dotrace = mode == trace;
1395 _dl_receive_error (print_missing_version, version_check_doit, &args);
1398 #ifdef USE_TLS
1399 /* Now it is time to determine the layout of the static TLS block
1400 and allocate it for the initial thread. Note that we always
1401 allocate the static block, we never defer it even if no
1402 DF_STATIC_TLS bit is set. The reason is that we know glibc will
1403 use the static model. First add the dynamic linker to the list
1404 if it also uses TLS. */
1405 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1406 /* Assign a module ID. */
1407 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1409 # ifndef TLS_INIT_TP_EXPENSIVE
1410 # define TLS_INIT_TP_EXPENSIVE 0
1411 # endif
1413 /* We do not initialize any of the TLS functionality unless any of the
1414 initial modules uses TLS. This makes dynamic loading of modules with
1415 TLS impossible, but to support it requires either eagerly doing setup
1416 now or lazily doing it later. Doing it now makes us incompatible with
1417 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1418 used. Trying to do it lazily is too hairy to try when there could be
1419 multiple threads (from a non-TLS-using libpthread). */
1420 if (!TLS_INIT_TP_EXPENSIVE || GL(dl_tls_max_dtv_idx) > 0)
1422 struct link_map *l;
1423 size_t nelem;
1424 struct dtv_slotinfo *slotinfo;
1426 /* Number of elements in the static TLS block. */
1427 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
1429 /* Allocate the array which contains the information about the
1430 dtv slots. We allocate a few entries more than needed to
1431 avoid the need for reallocation. */
1432 nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
1434 /* Allocate. */
1435 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
1436 malloc (sizeof (struct dtv_slotinfo_list)
1437 + nelem * sizeof (struct dtv_slotinfo));
1438 /* No need to check the return value. If memory allocation failed
1439 the program would have been terminated. */
1441 slotinfo = memset (GL(dl_tls_dtv_slotinfo_list)->slotinfo, '\0',
1442 nelem * sizeof (struct dtv_slotinfo));
1443 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
1444 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
1446 /* Fill in the information from the loaded modules. */
1447 for (l = GL(dl_loaded), i = 0; l != NULL; l = l->l_next)
1448 if (l->l_tls_blocksize != 0)
1449 /* This is a module with TLS data. Store the map reference.
1450 The generation counter is zero. */
1451 slotinfo[++i].map = l;
1452 assert (i == GL(dl_tls_max_dtv_idx));
1454 /* Compute the TLS offsets for the various blocks. */
1455 _dl_determine_tlsoffset ();
1457 /* Construct the static TLS block and the dtv for the initial
1458 thread. For some platforms this will include allocating memory
1459 for the thread descriptor. The memory for the TLS block will
1460 never be freed. It should be allocated accordingly. The dtv
1461 array can be changed if dynamic loading requires it. */
1462 tcbp = _dl_allocate_tls_storage ();
1463 if (tcbp == NULL)
1464 _dl_fatal_printf ("\
1465 cannot allocate TLS data structures for initial thread");
1467 /* Store for detection of the special case by __tls_get_addr
1468 so it knows not to pass this dtv to the normal realloc. */
1469 GL(dl_initial_dtv) = GET_DTV (tcbp);
1471 #endif
1473 if (__builtin_expect (mode, normal) != normal)
1475 /* We were run just to list the shared libraries. It is
1476 important that we do this before real relocation, because the
1477 functions we call below for output may no longer work properly
1478 after relocation. */
1479 struct link_map *l;
1481 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1483 struct r_scope_elem *scope = &GL(dl_loaded)->l_searchlist;
1485 for (i = 0; i < scope->r_nlist; i++)
1487 l = scope->r_list [i];
1488 if (l->l_faked)
1490 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1491 continue;
1493 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1494 GLRO(dl_trace_prelink_map) = l;
1495 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1496 l->l_libname->name[0] ? l->l_libname->name
1497 : rtld_progname ?: "<main program>",
1498 l->l_name[0] ? l->l_name
1499 : rtld_progname ?: "<main program>",
1500 (int) sizeof l->l_map_start * 2,
1501 (size_t) l->l_map_start,
1502 (int) sizeof l->l_addr * 2,
1503 (size_t) l->l_addr);
1504 #ifdef USE_TLS
1505 if (l->l_tls_modid)
1506 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1507 (int) sizeof l->l_tls_offset * 2,
1508 (size_t) l->l_tls_offset);
1509 else
1510 #endif
1511 _dl_printf ("\n");
1514 else if (! GL(dl_loaded)->l_info[DT_NEEDED])
1515 _dl_printf ("\tstatically linked\n");
1516 else
1518 for (l = GL(dl_loaded)->l_next; l; l = l->l_next)
1519 if (l->l_faked)
1520 /* The library was not found. */
1521 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1522 else
1523 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1524 l->l_name, (int) sizeof l->l_map_start * 2,
1525 (size_t) l->l_map_start);
1528 if (__builtin_expect (mode, trace) != trace)
1529 for (i = 1; i < (unsigned int) _dl_argc; ++i)
1531 const ElfW(Sym) *ref = NULL;
1532 ElfW(Addr) loadbase;
1533 lookup_t result;
1535 result = _dl_lookup_symbol_x (INTUSE(_dl_argv)[i], GL(dl_loaded),
1536 &ref, GL(dl_loaded)->l_scope, NULL,
1537 ELF_RTYPE_CLASS_PLT,
1538 DL_LOOKUP_ADD_DEPENDENCY, NULL);
1540 loadbase = LOOKUP_VALUE_ADDRESS (result);
1542 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
1543 INTUSE(_dl_argv)[i],
1544 (int) sizeof ref->st_value * 2,
1545 (size_t) ref->st_value,
1546 (int) sizeof loadbase * 2, (size_t) loadbase);
1548 else
1550 /* If LD_WARN is set warn about undefined symbols. */
1551 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
1553 /* We have to do symbol dependency testing. */
1554 struct relocate_args args;
1555 struct link_map *l;
1557 args.lazy = GLRO(dl_lazy);
1559 l = GL(dl_loaded);
1560 while (l->l_next)
1561 l = l->l_next;
1564 if (l != &GL(dl_rtld_map) && ! l->l_faked)
1566 args.l = l;
1567 _dl_receive_error (print_unresolved, relocate_doit,
1568 &args);
1570 l = l->l_prev;
1571 } while (l);
1573 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1574 && GL(dl_rtld_map).l_opencount > 1)
1575 _dl_relocate_object (&GL(dl_rtld_map), GL(dl_loaded)->l_scope,
1576 0, 0);
1579 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
1580 if (version_info)
1582 /* Print more information. This means here, print information
1583 about the versions needed. */
1584 int first = 1;
1585 struct link_map *map = GL(dl_loaded);
1587 for (map = GL(dl_loaded); map != NULL; map = map->l_next)
1589 const char *strtab;
1590 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
1591 ElfW(Verneed) *ent;
1593 if (dyn == NULL)
1594 continue;
1596 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
1597 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
1599 if (first)
1601 _dl_printf ("\n\tVersion information:\n");
1602 first = 0;
1605 _dl_printf ("\t%s:\n",
1606 map->l_name[0] ? map->l_name : rtld_progname);
1608 while (1)
1610 ElfW(Vernaux) *aux;
1611 struct link_map *needed;
1613 needed = find_needed (strtab + ent->vn_file);
1614 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
1616 while (1)
1618 const char *fname = NULL;
1620 if (needed != NULL
1621 && match_version (strtab + aux->vna_name,
1622 needed))
1623 fname = needed->l_name;
1625 _dl_printf ("\t\t%s (%s) %s=> %s\n",
1626 strtab + ent->vn_file,
1627 strtab + aux->vna_name,
1628 aux->vna_flags & VER_FLG_WEAK
1629 ? "[WEAK] " : "",
1630 fname ?: "not found");
1632 if (aux->vna_next == 0)
1633 /* No more symbols. */
1634 break;
1636 /* Next symbol. */
1637 aux = (ElfW(Vernaux) *) ((char *) aux
1638 + aux->vna_next);
1641 if (ent->vn_next == 0)
1642 /* No more dependencies. */
1643 break;
1645 /* Next dependency. */
1646 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
1652 _exit (0);
1655 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]
1656 && ! __builtin_expect (GLRO(dl_profile) != NULL, 0))
1658 ElfW(Lib) *liblist, *liblistend;
1659 struct link_map **r_list, **r_listend, *l;
1660 const char *strtab = (const void *) D_PTR (GL(dl_loaded),
1661 l_info[DT_STRTAB]);
1663 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
1664 liblist = (ElfW(Lib) *)
1665 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
1666 liblistend = (ElfW(Lib) *)
1667 ((char *) liblist
1668 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
1669 r_list = GL(dl_loaded)->l_searchlist.r_list;
1670 r_listend = r_list + GL(dl_loaded)->l_searchlist.r_nlist;
1672 for (; r_list < r_listend && liblist < liblistend; r_list++)
1674 l = *r_list;
1676 if (l == GL(dl_loaded))
1677 continue;
1679 /* If the library is not mapped where it should, fail. */
1680 if (l->l_addr)
1681 break;
1683 /* Next, check if checksum matches. */
1684 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
1685 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
1686 != liblist->l_checksum)
1687 break;
1689 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
1690 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
1691 != liblist->l_time_stamp)
1692 break;
1694 if (! _dl_name_match_p (strtab + liblist->l_name, l))
1695 break;
1697 ++liblist;
1701 if (r_list == r_listend && liblist == liblistend)
1702 prelinked = true;
1704 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1705 _dl_printf ("\nprelink checking: %s\n", prelinked ? "ok" : "failed");
1709 /* Initialize _r_debug. */
1710 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr);
1712 struct link_map *l;
1714 l = GL(dl_loaded);
1716 #ifdef ELF_MACHINE_DEBUG_SETUP
1718 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1720 ELF_MACHINE_DEBUG_SETUP (l, r);
1721 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1723 #else
1725 if (l->l_info[DT_DEBUG] != NULL)
1726 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1727 with the run-time address of the r_debug structure */
1728 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1730 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1731 case you run gdb on the dynamic linker directly. */
1732 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1733 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1734 #endif
1737 /* Now set up the variable which helps the assembler startup code. */
1738 GL(dl_main_searchlist) = &GL(dl_loaded)->l_searchlist;
1739 GL(dl_global_scope)[0] = &GL(dl_loaded)->l_searchlist;
1741 /* Save the information about the original global scope list since
1742 we need it in the memory handling later. */
1743 GLRO(dl_initial_searchlist) = *GL(dl_main_searchlist);
1745 if (prelinked)
1747 struct link_map *l;
1749 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
1751 ElfW(Rela) *conflict, *conflictend;
1752 #ifndef HP_TIMING_NONAVAIL
1753 hp_timing_t start;
1754 hp_timing_t stop;
1755 #endif
1757 HP_TIMING_NOW (start);
1758 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
1759 conflict = (ElfW(Rela) *)
1760 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
1761 conflictend = (ElfW(Rela) *)
1762 ((char *) conflict
1763 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
1764 _dl_resolve_conflicts (GL(dl_loaded), conflict, conflictend);
1765 HP_TIMING_NOW (stop);
1766 HP_TIMING_DIFF (relocate_time, start, stop);
1770 /* Mark all the objects so we know they have been already relocated. */
1771 for (l = GL(dl_loaded); l != NULL; l = l->l_next)
1773 l->l_relocated = 1;
1774 if (l->l_relro_size)
1775 _dl_protect_relro (l);
1778 _dl_sysdep_start_cleanup ();
1780 else
1782 /* Now we have all the objects loaded. Relocate them all except for
1783 the dynamic linker itself. We do this in reverse order so that copy
1784 relocs of earlier objects overwrite the data written by later
1785 objects. We do not re-relocate the dynamic linker itself in this
1786 loop because that could result in the GOT entries for functions we
1787 call being changed, and that would break us. It is safe to relocate
1788 the dynamic linker out of order because it has no copy relocs (we
1789 know that because it is self-contained). */
1791 struct link_map *l;
1792 int consider_profiling = GLRO(dl_profile) != NULL;
1793 #ifndef HP_TIMING_NONAVAIL
1794 hp_timing_t start;
1795 hp_timing_t stop;
1796 hp_timing_t add;
1797 #endif
1799 /* If we are profiling we also must do lazy reloaction. */
1800 GLRO(dl_lazy) |= consider_profiling;
1802 l = GL(dl_loaded);
1803 while (l->l_next)
1804 l = l->l_next;
1806 HP_TIMING_NOW (start);
1809 /* While we are at it, help the memory handling a bit. We have to
1810 mark some data structures as allocated with the fake malloc()
1811 implementation in ld.so. */
1812 struct libname_list *lnp = l->l_libname->next;
1814 while (__builtin_expect (lnp != NULL, 0))
1816 lnp->dont_free = 1;
1817 lnp = lnp->next;
1820 if (l != &GL(dl_rtld_map))
1821 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy),
1822 consider_profiling);
1824 l = l->l_prev;
1826 while (l);
1827 HP_TIMING_NOW (stop);
1829 HP_TIMING_DIFF (relocate_time, start, stop);
1831 /* Do any necessary cleanups for the startup OS interface code.
1832 We do these now so that no calls are made after rtld re-relocation
1833 which might be resolved to different functions than we expect.
1834 We cannot do this before relocating the other objects because
1835 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
1836 _dl_sysdep_start_cleanup ();
1838 /* Now enable profiling if needed. Like the previous call,
1839 this has to go here because the calls it makes should use the
1840 rtld versions of the functions (particularly calloc()), but it
1841 needs to have _dl_profile_map set up by the relocator. */
1842 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
1843 /* We must prepare the profiling. */
1844 _dl_start_profile ();
1846 if (GL(dl_rtld_map).l_opencount > 1)
1848 /* There was an explicit ref to the dynamic linker as a shared lib.
1849 Re-relocate ourselves with user-controlled symbol definitions. */
1850 HP_TIMING_NOW (start);
1851 _dl_relocate_object (&GL(dl_rtld_map), GL(dl_loaded)->l_scope, 0, 0);
1852 HP_TIMING_NOW (stop);
1853 HP_TIMING_DIFF (add, start, stop);
1854 HP_TIMING_ACCUM_NT (relocate_time, add);
1858 #ifndef NONTLS_INIT_TP
1859 # define NONTLS_INIT_TP do { } while (0)
1860 #endif
1862 #ifdef USE_TLS
1863 if (GL(dl_tls_max_dtv_idx) > 0 || USE___THREAD || !TLS_INIT_TP_EXPENSIVE)
1865 /* Now that we have completed relocation, the initializer data
1866 for the TLS blocks has its final values and we can copy them
1867 into the main thread's TLS area, which we allocated above. */
1868 _dl_allocate_tls_init (tcbp);
1870 /* And finally install it for the main thread. If ld.so itself uses
1871 TLS we know the thread pointer was initialized earlier. */
1872 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
1873 if (__builtin_expect (lossage != NULL, 0))
1874 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
1876 else
1877 #endif
1878 NONTLS_INIT_TP;
1880 /* Notify the debugger that all objects are now mapped in. */
1881 r->r_state = RT_ADD;
1882 _dl_debug_state ();
1884 #ifndef MAP_COPY
1885 /* We must munmap() the cache file. */
1886 _dl_unload_cache ();
1887 #endif
1889 /* Once we return, _dl_sysdep_start will invoke
1890 the DT_INIT functions and then *USER_ENTRY. */
1893 /* This is a little helper function for resolving symbols while
1894 tracing the binary. */
1895 static void
1896 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
1897 const char *errstring)
1899 if (objname[0] == '\0')
1900 objname = rtld_progname ?: "<main program>";
1901 _dl_error_printf ("%s (%s)\n", errstring, objname);
1904 /* This is a little helper function for resolving symbols while
1905 tracing the binary. */
1906 static void
1907 print_missing_version (int errcode __attribute__ ((unused)),
1908 const char *objname, const char *errstring)
1910 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
1911 objname, errstring);
1914 /* Nonzero if any of the debugging options is enabled. */
1915 static int any_debug attribute_relro;
1917 /* Process the string given as the parameter which explains which debugging
1918 options are enabled. */
1919 static void
1920 process_dl_debug (const char *dl_debug)
1922 /* When adding new entries make sure that the maximal length of a name
1923 is correctly handled in the LD_DEBUG_HELP code below. */
1924 static const struct
1926 unsigned char len;
1927 const char name[10];
1928 const char helptext[41];
1929 unsigned short int mask;
1930 } debopts[] =
1932 #define LEN_AND_STR(str) sizeof (str) - 1, str
1933 { LEN_AND_STR ("libs"), "display library search paths",
1934 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
1935 { LEN_AND_STR ("reloc"), "display relocation processing",
1936 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
1937 { LEN_AND_STR ("files"), "display progress for input file",
1938 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
1939 { LEN_AND_STR ("symbols"), "display symbol table processing",
1940 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
1941 { LEN_AND_STR ("bindings"), "display information about symbol binding",
1942 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
1943 { LEN_AND_STR ("versions"), "display version dependencies",
1944 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1945 { LEN_AND_STR ("all"), "all previous options combined",
1946 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
1947 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1948 { LEN_AND_STR ("statistics"), "display relocation statistics",
1949 DL_DEBUG_STATISTICS },
1950 { LEN_AND_STR ("help"), "display this help message and exit",
1951 DL_DEBUG_HELP },
1953 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
1955 /* Skip separating white spaces and commas. */
1956 while (*dl_debug != '\0')
1958 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
1960 size_t cnt;
1961 size_t len = 1;
1963 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
1964 && dl_debug[len] != ',' && dl_debug[len] != ':')
1965 ++len;
1967 for (cnt = 0; cnt < ndebopts; ++cnt)
1968 if (debopts[cnt].len == len
1969 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
1971 GLRO(dl_debug_mask) |= debopts[cnt].mask;
1972 any_debug = 1;
1973 break;
1976 if (cnt == ndebopts)
1978 /* Display a warning and skip everything until next
1979 separator. */
1980 char *copy = strndupa (dl_debug, len);
1981 _dl_error_printf ("\
1982 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
1985 dl_debug += len;
1986 continue;
1989 ++dl_debug;
1992 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
1994 size_t cnt;
1996 _dl_printf ("\
1997 Valid options for the LD_DEBUG environment variable are:\n\n");
1999 for (cnt = 0; cnt < ndebopts; ++cnt)
2000 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2001 " " + debopts[cnt].len - 3,
2002 debopts[cnt].helptext);
2004 _dl_printf ("\n\
2005 To direct the debugging output into a file instead of standard output\n\
2006 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2007 _exit (0);
2011 /* Process all environments variables the dynamic linker must recognize.
2012 Since all of them start with `LD_' we are a bit smarter while finding
2013 all the entries. */
2014 extern char **_environ attribute_hidden;
2017 static void
2018 process_envvars (enum mode *modep)
2020 char **runp = _environ;
2021 char *envline;
2022 enum mode mode = normal;
2023 char *debug_output = NULL;
2025 /* This is the default place for profiling data file. */
2026 GLRO(dl_profile_output)
2027 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2029 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2031 size_t len = 0;
2033 while (envline[len] != '\0' && envline[len] != '=')
2034 ++len;
2036 if (envline[len] != '=')
2037 /* This is a "LD_" variable at the end of the string without
2038 a '=' character. Ignore it since otherwise we will access
2039 invalid memory below. */
2040 continue;
2042 switch (len)
2044 case 4:
2045 /* Warning level, verbose or not. */
2046 if (memcmp (envline, "WARN", 4) == 0)
2047 GLRO(dl_verbose) = envline[5] != '\0';
2048 break;
2050 case 5:
2051 /* Debugging of the dynamic linker? */
2052 if (memcmp (envline, "DEBUG", 5) == 0)
2053 process_dl_debug (&envline[6]);
2054 break;
2056 case 7:
2057 /* Print information about versions. */
2058 if (memcmp (envline, "VERBOSE", 7) == 0)
2060 version_info = envline[8] != '\0';
2061 break;
2064 /* List of objects to be preloaded. */
2065 if (memcmp (envline, "PRELOAD", 7) == 0)
2067 preloadlist = &envline[8];
2068 break;
2071 /* Which shared object shall be profiled. */
2072 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2073 GLRO(dl_profile) = &envline[8];
2074 break;
2076 case 8:
2077 /* Do we bind early? */
2078 if (memcmp (envline, "BIND_NOW", 8) == 0)
2080 GLRO(dl_lazy) = envline[9] == '\0';
2081 break;
2083 if (memcmp (envline, "BIND_NOT", 8) == 0)
2084 GLRO(dl_bind_not) = envline[9] != '\0';
2085 break;
2087 case 9:
2088 /* Test whether we want to see the content of the auxiliary
2089 array passed up from the kernel. */
2090 if (memcmp (envline, "SHOW_AUXV", 9) == 0)
2091 _dl_show_auxv ();
2092 break;
2094 case 10:
2095 /* Mask for the important hardware capabilities. */
2096 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2097 GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2098 0, 0);
2099 break;
2101 case 11:
2102 /* Path where the binary is found. */
2103 if (!INTUSE(__libc_enable_secure)
2104 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2105 GLRO(dl_origin_path) = &envline[12];
2106 break;
2108 case 12:
2109 /* The library search path. */
2110 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2112 library_path = &envline[13];
2113 break;
2116 /* Where to place the profiling data file. */
2117 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2119 debug_output = &envline[13];
2120 break;
2123 if (memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2124 GLRO(dl_dynamic_weak) = 1;
2125 break;
2127 case 13:
2128 /* We might have some extra environment variable with length 13
2129 to handle. */
2130 #ifdef EXTRA_LD_ENVVARS_13
2131 EXTRA_LD_ENVVARS_13
2132 #endif
2133 if (!INTUSE(__libc_enable_secure)
2134 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2135 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2136 break;
2138 case 14:
2139 /* Where to place the profiling data file. */
2140 if (!INTUSE(__libc_enable_secure)
2141 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2142 && envline[15] != '\0')
2143 GLRO(dl_profile_output) = &envline[15];
2144 break;
2146 case 16:
2147 /* The mode of the dynamic linker can be set. */
2148 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2150 mode = trace;
2151 GLRO(dl_verbose) = 1;
2152 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2153 GLRO(dl_trace_prelink) = &envline[17];
2155 break;
2157 case 20:
2158 /* The mode of the dynamic linker can be set. */
2159 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2160 mode = trace;
2161 break;
2163 /* We might have some extra environment variable to handle. This
2164 is tricky due to the pre-processing of the length of the name
2165 in the switch statement here. The code here assumes that added
2166 environment variables have a different length. */
2167 #ifdef EXTRA_LD_ENVVARS
2168 EXTRA_LD_ENVVARS
2169 #endif
2173 /* The caller wants this information. */
2174 *modep = mode;
2176 /* Extra security for SUID binaries. Remove all dangerous environment
2177 variables. */
2178 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2180 static const char unsecure_envvars[] =
2181 #ifdef EXTRA_UNSECURE_ENVVARS
2182 EXTRA_UNSECURE_ENVVARS
2183 #endif
2184 UNSECURE_ENVVARS;
2185 const char *nextp;
2187 nextp = unsecure_envvars;
2190 unsetenv (nextp);
2191 /* We could use rawmemchr but this need not be fast. */
2192 nextp = (char *) (strchr) (nextp, '\0') + 1;
2194 while (*nextp != '\0');
2196 if (__access ("/etc/suid-debug", F_OK) != 0)
2197 unsetenv ("MALLOC_CHECK_");
2199 /* If we have to run the dynamic linker in debugging mode and the
2200 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2201 messages to this file. */
2202 else if (any_debug && debug_output != NULL)
2204 #ifdef O_NOFOLLOW
2205 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2206 #else
2207 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2208 #endif
2209 size_t name_len = strlen (debug_output);
2210 char buf[name_len + 12];
2211 char *startp;
2213 buf[name_len + 11] = '\0';
2214 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2215 *--startp = '.';
2216 startp = memcpy (startp - name_len, debug_output, name_len);
2218 GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2219 if (GLRO(dl_debug_fd) == -1)
2220 /* We use standard output if opening the file failed. */
2221 GLRO(dl_debug_fd) = STDOUT_FILENO;
2226 /* Print the various times we collected. */
2227 static void
2228 print_statistics (hp_timing_t *rtld_total_timep)
2230 #ifndef HP_TIMING_NONAVAIL
2231 char buf[200];
2232 char *cp;
2233 char *wp;
2235 /* Total time rtld used. */
2236 if (HP_TIMING_AVAIL)
2238 HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2239 _dl_debug_printf ("\nruntime linker statistics:\n"
2240 " total startup time in dynamic loader: %s\n", buf);
2242 /* Print relocation statistics. */
2243 char pbuf[30];
2244 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2245 cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2246 pbuf + sizeof (pbuf), 10, 0);
2247 wp = pbuf;
2248 switch (pbuf + sizeof (pbuf) - cp)
2250 case 3:
2251 *wp++ = *cp++;
2252 case 2:
2253 *wp++ = *cp++;
2254 case 1:
2255 *wp++ = '.';
2256 *wp++ = *cp++;
2258 *wp = '\0';
2259 _dl_debug_printf ("\
2260 time needed for relocation: %s (%s%%)\n", buf, pbuf);
2262 #endif
2264 unsigned long int num_relative_relocations = 0;
2265 struct r_scope_elem *scope = &GL(dl_loaded)->l_searchlist;
2266 unsigned int i;
2268 for (i = 0; i < scope->r_nlist; i++)
2270 struct link_map *l = scope->r_list [i];
2272 if (!l->l_addr)
2273 continue;
2275 if (l->l_info[VERSYMIDX (DT_RELCOUNT)])
2276 num_relative_relocations += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2277 if (l->l_info[VERSYMIDX (DT_RELACOUNT)])
2278 num_relative_relocations += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2281 _dl_debug_printf (" number of relocations: %lu\n"
2282 " number of relocations from cache: %lu\n"
2283 " number of relative relocations: %lu\n",
2284 GL(dl_num_relocations),
2285 GL(dl_num_cache_relocations),
2286 num_relative_relocations);
2288 #ifndef HP_TIMING_NONAVAIL
2289 /* Time spend while loading the object and the dependencies. */
2290 if (HP_TIMING_AVAIL)
2292 char pbuf[30];
2293 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2294 cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2295 pbuf + sizeof (pbuf), 10, 0);
2296 wp = pbuf;
2297 switch (pbuf + sizeof (pbuf) - cp)
2299 case 3:
2300 *wp++ = *cp++;
2301 case 2:
2302 *wp++ = *cp++;
2303 case 1:
2304 *wp++ = '.';
2305 *wp++ = *cp++;
2307 *wp = '\0';
2308 _dl_debug_printf ("\
2309 time needed to load objects: %s (%s%%)\n",
2310 buf, pbuf);
2312 #endif