Update.
[glibc.git] / elf / rtld.c
bloba65e9c4c7ce2fa3d06f77e7955da86c200f1fe6b
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 #ifndef HAVE_INLINED_SYSCALLS
83 /* Set nonzero during loading and initialization of executable and
84 libraries, cleared before the executable's entry point runs. This
85 must not be initialized to nonzero, because the unused dynamic
86 linker loaded in for libc.so's "ld.so.1" dep will provide the
87 definition seen by libc.so's initializer; that value must be zero,
88 and will be since that dynamic linker's _dl_start and dl_main will
89 never be called. */
90 int _dl_starting_up = 0;
91 INTVARDEF(_dl_starting_up)
92 #endif
94 /* This is the structure which defines all variables global to ld.so
95 (except those which cannot be added for some reason). */
96 struct rtld_global _rtld_global =
98 /* Default presumption without further information is executable stack. */
99 ._dl_stack_flags = PF_R|PF_W|PF_X,
100 #ifdef _LIBC_REENTRANT
101 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER
102 #endif
104 /* If we would use strong_alias here the compiler would see a
105 non-hidden definition. This would undo the effect of the previous
106 declaration. So spell out was strong_alias does plus add the
107 visibility attribute. */
108 extern struct rtld_global _rtld_local
109 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
112 /* This variable is similar to _rtld_local, but all values are
113 read-only after relocation. */
114 struct rtld_global_ro _rtld_global_ro attribute_relro =
116 /* Get architecture specific initializer. */
117 #include <dl-procinfo.c>
118 #ifdef NEED_DL_SYSINFO
119 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
120 #endif
121 ._dl_debug_fd = STDERR_FILENO,
122 ._dl_use_load_bias = -2,
123 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
124 ._dl_hwcap_mask = HWCAP_IMPORTANT,
125 ._dl_lazy = 1,
126 ._dl_fpu_control = _FPU_DEFAULT,
128 /* Function pointers. */
129 ._dl_get_origin = _dl_get_origin,
130 ._dl_dst_count = _dl_dst_count,
131 ._dl_dst_substitute = _dl_dst_substitute,
132 ._dl_map_object = _dl_map_object,
133 ._dl_map_object_deps = _dl_map_object_deps,
134 ._dl_relocate_object = _dl_relocate_object,
135 ._dl_check_map_versions = _dl_check_map_versions,
136 ._dl_init = _dl_init,
137 ._dl_debug_state = _dl_debug_state,
138 #ifndef MAP_COPY
139 ._dl_unload_cache = _dl_unload_cache,
140 #endif
141 ._dl_debug_printf = _dl_debug_printf,
142 ._dl_catch_error = _dl_catch_error,
143 ._dl_signal_error = _dl_signal_error,
144 ._dl_start_profile = _dl_start_profile,
145 ._dl_mcount = _dl_mcount_internal,
146 ._dl_lookup_symbol_x = _dl_lookup_symbol_x,
147 ._dl_check_caller = _dl_check_caller
149 /* If we would use strong_alias here the compiler would see a
150 non-hidden definition. This would undo the effect of the previous
151 declaration. So spell out was strong_alias does plus add the
152 visibility attribute. */
153 extern struct rtld_global_ro _rtld_local_ro
154 __attribute__ ((alias ("_rtld_global_ro"), visibility ("hidden")));
157 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
158 ElfW(Addr) *user_entry);
160 /* These two variables cannot be moved into .data.rel.ro. */
161 static struct libname_list _dl_rtld_libname;
162 static struct libname_list _dl_rtld_libname2;
164 /* We expect less than a second for relocation. */
165 #ifdef HP_SMALL_TIMING_AVAIL
166 # undef HP_TIMING_AVAIL
167 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
168 #endif
170 /* Variable for statistics. */
171 #ifndef HP_TIMING_NONAVAIL
172 static hp_timing_t relocate_time;
173 static hp_timing_t load_time attribute_relro;
174 static hp_timing_t start_time attribute_relro;
175 #endif
177 /* Additional definitions needed by TLS initialization. */
178 #ifdef TLS_INIT_HELPER
179 TLS_INIT_HELPER
180 #endif
182 /* Helper function for syscall implementation. */
183 #ifdef DL_SYSINFO_IMPLEMENTATION
184 DL_SYSINFO_IMPLEMENTATION
185 #endif
187 /* Before ld.so is relocated we must not access variables which need
188 relocations. This means variables which are exported. Variables
189 declared as static are fine. If we can mark a variable hidden this
190 is fine, too. The latter is important here. We can avoid setting
191 up a temporary link map for ld.so if we can mark _rtld_global as
192 hidden. */
193 #if defined PI_STATIC_AND_HIDDEN && defined HAVE_HIDDEN \
194 && defined HAVE_VISIBILITY_ATTRIBUTE
195 # define DONT_USE_BOOTSTRAP_MAP 1
196 #endif
198 #ifdef DONT_USE_BOOTSTRAP_MAP
199 static ElfW(Addr) _dl_start_final (void *arg);
200 #else
201 struct dl_start_final_info
203 struct link_map l;
204 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
205 hp_timing_t start_time;
206 #endif
208 static ElfW(Addr) _dl_start_final (void *arg,
209 struct dl_start_final_info *info);
210 #endif
212 /* These defined magically in the linker script. */
213 extern char _begin[] attribute_hidden;
214 extern char _etext[] attribute_hidden;
215 extern char _end[] attribute_hidden;
218 #ifdef RTLD_START
219 RTLD_START
220 #else
221 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
222 #endif
224 #ifndef VALIDX
225 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
226 + DT_EXTRANUM + DT_VALTAGIDX (tag))
227 #endif
228 #ifndef ADDRIDX
229 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
230 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
231 #endif
233 /* This is the second half of _dl_start (below). It can be inlined safely
234 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
235 references. When the tools don't permit us to avoid using a GOT entry
236 for _dl_rtld_global (no attribute_hidden support), we must make sure
237 this function is not inlined (see below). */
239 #ifdef DONT_USE_BOOTSTRAP_MAP
240 static inline ElfW(Addr) __attribute__ ((always_inline))
241 _dl_start_final (void *arg)
242 #else
243 static ElfW(Addr) __attribute__ ((noinline))
244 _dl_start_final (void *arg, struct dl_start_final_info *info)
245 #endif
247 ElfW(Addr) start_addr;
249 if (HP_TIMING_AVAIL)
251 /* If it hasn't happen yet record the startup time. */
252 if (! HP_TIMING_INLINE)
253 HP_TIMING_NOW (start_time);
254 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
255 else
256 start_time = info->start_time;
257 #endif
259 /* Initialize the timing functions. */
260 HP_TIMING_DIFF_INIT ();
263 /* Transfer data about ourselves to the permanent link_map structure. */
264 #ifndef DONT_USE_BOOTSTRAP_MAP
265 GL(dl_rtld_map).l_addr = info->l.l_addr;
266 GL(dl_rtld_map).l_ld = info->l.l_ld;
267 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
268 sizeof GL(dl_rtld_map).l_info);
269 GL(dl_rtld_map).l_mach = info->l.l_mach;
270 #endif
271 _dl_setup_hash (&GL(dl_rtld_map));
272 GL(dl_rtld_map).l_opencount = 1;
273 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
274 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
275 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
276 /* Copy the TLS related data if necessary. */
277 #if USE_TLS && !defined DONT_USE_BOOTSTRAP_MAP
278 # if USE___THREAD
279 assert (info->l.l_tls_modid != 0);
280 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
281 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
282 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
283 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
284 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
285 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
286 GL(dl_rtld_map).l_tls_modid = 1;
287 # else
288 assert (info->l.l_tls_modid == 0);
289 # if NO_TLS_OFFSET != 0
290 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
291 # endif
292 # endif
294 #endif
296 #if HP_TIMING_AVAIL
297 HP_TIMING_NOW (GL(dl_cpuclock_offset));
298 #endif
300 /* Initialize the stack end variable. */
301 __libc_stack_end = __builtin_frame_address (0);
303 /* Call the OS-dependent function to set up life so we can do things like
304 file access. It will call `dl_main' (below) to do all the real work
305 of the dynamic linker, and then unwind our frame and run the user
306 entry point on the same stack we entered on. */
307 start_addr = _dl_sysdep_start (arg, &dl_main);
309 #ifndef HP_TIMING_NONAVAIL
310 hp_timing_t rtld_total_time;
311 if (HP_TIMING_AVAIL)
313 hp_timing_t end_time;
315 /* Get the current time. */
316 HP_TIMING_NOW (end_time);
318 /* Compute the difference. */
319 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
321 #endif
323 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
325 #ifndef HP_TIMING_NONAVAIL
326 print_statistics (&rtld_total_time);
327 #else
328 print_statistics (NULL);
329 #endif
332 return start_addr;
335 static ElfW(Addr) __attribute_used__ internal_function
336 _dl_start (void *arg)
338 #ifdef DONT_USE_BOOTSTRAP_MAP
339 # define bootstrap_map GL(dl_rtld_map)
340 #else
341 struct dl_start_final_info info;
342 # define bootstrap_map info.l
343 #endif
345 /* This #define produces dynamic linking inline functions for
346 bootstrap relocation instead of general-purpose relocation. */
347 #define RTLD_BOOTSTRAP
348 #define RESOLVE_MAP(sym, version, flags) \
349 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : &bootstrap_map)
350 #define RESOLVE(sym, version, flags) \
351 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : bootstrap_map.l_addr)
352 #include "dynamic-link.h"
354 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
355 #ifdef DONT_USE_BOOTSTRAP_MAP
356 HP_TIMING_NOW (start_time);
357 #else
358 HP_TIMING_NOW (info.start_time);
359 #endif
361 /* Partly clean the `bootstrap_map' structure up. Don't use
362 `memset' since it might not be built in or inlined and we cannot
363 make function calls at this point. Use '__builtin_memset' if we
364 know it is available. We do not have to clear the memory if we
365 do not have to use the temporary bootstrap_map. Global variables
366 are initialized to zero by default. */
367 #ifndef DONT_USE_BOOTSTRAP_MAP
368 # ifdef HAVE_BUILTIN_MEMSET
369 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
370 # else
371 for (size_t cnt = 0;
372 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
373 ++cnt)
374 bootstrap_map.l_info[cnt] = 0;
375 # endif
376 #endif
378 /* Figure out the run-time load address of the dynamic linker itself. */
379 bootstrap_map.l_addr = elf_machine_load_address ();
381 /* Read our own dynamic section and fill in the info array. */
382 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
383 elf_get_dynamic_info (&bootstrap_map, NULL);
385 #if defined USE_TLS && NO_TLS_OFFSET != 0
386 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
387 #endif
389 /* Get the dynamic linker's own program header. First we need the ELF
390 file header. The `_begin' symbol created by the linker script points
391 to it. When we have something like GOTOFF relocs, we can use a plain
392 reference to find the runtime address. Without that, we have to rely
393 on the `l_addr' value, which is not the value we want when prelinked. */
394 #if USE___THREAD
395 dtv_t initdtv[3];
396 ElfW(Ehdr) *ehdr
397 # ifdef DONT_USE_BOOTSTRAP_MAP
398 = (ElfW(Ehdr) *) &_begin;
399 # else
400 # error This will not work with prelink.
401 = (ElfW(Ehdr) *) bootstrap_map.l_addr;
402 # endif
403 ElfW(Phdr) *phdr = (ElfW(Phdr) *) ((void *) ehdr + ehdr->e_phoff);
404 size_t cnt = ehdr->e_phnum; /* PT_TLS is usually the last phdr. */
405 while (cnt-- > 0)
406 if (phdr[cnt].p_type == PT_TLS)
408 void *tlsblock;
409 size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
410 char *p;
412 bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
413 bootstrap_map.l_tls_align = phdr[cnt].p_align;
414 if (phdr[cnt].p_align == 0)
415 bootstrap_map.l_tls_firstbyte_offset = 0;
416 else
417 bootstrap_map.l_tls_firstbyte_offset = (phdr[cnt].p_vaddr
418 & (phdr[cnt].p_align - 1));
419 assert (bootstrap_map.l_tls_blocksize != 0);
420 bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
421 bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
422 + phdr[cnt].p_vaddr);
424 /* We can now allocate the initial TLS block. This can happen
425 on the stack. We'll get the final memory later when we
426 know all about the various objects loaded at startup
427 time. */
428 # if TLS_TCB_AT_TP
429 tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
430 TLS_INIT_TCB_ALIGN)
431 + TLS_INIT_TCB_SIZE
432 + max_align);
433 # elif TLS_DTV_AT_TP
434 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
435 bootstrap_map.l_tls_align)
436 + bootstrap_map.l_tls_blocksize
437 + max_align);
438 # else
439 /* In case a model with a different layout for the TCB and DTV
440 is defined add another #elif here and in the following #ifs. */
441 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
442 # endif
443 /* Align the TLS block. */
444 tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
445 & ~(max_align - 1));
447 /* Initialize the dtv. [0] is the length, [1] the generation
448 counter. */
449 initdtv[0].counter = 1;
450 initdtv[1].counter = 0;
452 /* Initialize the TLS block. */
453 # if TLS_TCB_AT_TP
454 initdtv[2].pointer = tlsblock;
455 # elif TLS_DTV_AT_TP
456 bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
457 bootstrap_map.l_tls_align);
458 initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
459 # else
460 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
461 # endif
462 p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
463 bootstrap_map.l_tls_initimage_size);
464 # ifdef HAVE_BUILTIN_MEMSET
465 __builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
466 - bootstrap_map.l_tls_initimage_size));
467 # else
469 size_t remaining = (bootstrap_map.l_tls_blocksize
470 - bootstrap_map.l_tls_initimage_size);
471 while (remaining-- > 0)
472 *p++ = '\0';
474 #endif
476 /* Install the pointer to the dtv. */
478 /* Initialize the thread pointer. */
479 # if TLS_TCB_AT_TP
480 bootstrap_map.l_tls_offset
481 = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
483 INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
484 initdtv);
486 const char *lossage = TLS_INIT_TP ((char *) tlsblock
487 + bootstrap_map.l_tls_offset, 0);
488 # elif TLS_DTV_AT_TP
489 INSTALL_DTV (tlsblock, initdtv);
490 const char *lossage = TLS_INIT_TP (tlsblock, 0);
491 # else
492 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
493 # endif
494 if (__builtin_expect (lossage != NULL, 0))
495 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
496 lossage);
498 /* So far this is module number one. */
499 bootstrap_map.l_tls_modid = 1;
501 /* There can only be one PT_TLS entry. */
502 break;
504 #endif /* USE___THREAD */
506 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
507 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
508 #endif
510 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
512 /* Relocate ourselves so we can do normal function calls and
513 data access using the global offset table. */
515 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
518 /* Please note that we don't allow profiling of this object and
519 therefore need not test whether we have to allocate the array
520 for the relocation results (as done in dl-reloc.c). */
522 /* Now life is sane; we can call functions and access global data.
523 Set up to use the operating system facilities, and find out from
524 the operating system's program loader where to find the program
525 header table in core. Put the rest of _dl_start into a separate
526 function, that way the compiler cannot put accesses to the GOT
527 before ELF_DYNAMIC_RELOCATE. */
529 #ifdef DONT_USE_BOOTSTRAP_MAP
530 ElfW(Addr) entry = _dl_start_final (arg);
531 #else
532 ElfW(Addr) entry = _dl_start_final (arg, &info);
533 #endif
535 #ifndef ELF_MACHINE_START_ADDRESS
536 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
537 #endif
539 return ELF_MACHINE_START_ADDRESS (GL(dl_loaded), entry);
545 /* Now life is peachy; we can do all normal operations.
546 On to the real work. */
548 /* Some helper functions. */
550 /* Arguments to relocate_doit. */
551 struct relocate_args
553 struct link_map *l;
554 int lazy;
557 struct map_args
559 /* Argument to map_doit. */
560 char *str;
561 struct link_map *loader;
562 int is_preloaded;
563 int mode;
564 /* Return value of map_doit. */
565 struct link_map *map;
568 /* Arguments to version_check_doit. */
569 struct version_check_args
571 int doexit;
572 int dotrace;
575 static void
576 relocate_doit (void *a)
578 struct relocate_args *args = (struct relocate_args *) a;
580 _dl_relocate_object (args->l, args->l->l_scope, args->lazy, 0);
583 static void
584 map_doit (void *a)
586 struct map_args *args = (struct map_args *) a;
587 args->map = _dl_map_object (args->loader, args->str,
588 args->is_preloaded, lt_library, 0, args->mode);
591 static void
592 version_check_doit (void *a)
594 struct version_check_args *args = (struct version_check_args *) a;
595 if (_dl_check_all_versions (GL(dl_loaded), 1, args->dotrace) && args->doexit)
596 /* We cannot start the application. Abort now. */
597 _exit (1);
601 static inline struct link_map *
602 find_needed (const char *name)
604 unsigned int n = GL(dl_loaded)->l_searchlist.r_nlist;
606 while (n-- > 0)
607 if (_dl_name_match_p (name, GL(dl_loaded)->l_searchlist.r_list[n]))
608 return GL(dl_loaded)->l_searchlist.r_list[n];
610 /* Should never happen. */
611 return NULL;
614 static int
615 match_version (const char *string, struct link_map *map)
617 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
618 ElfW(Verdef) *def;
620 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
621 if (map->l_info[VERDEFTAG] == NULL)
622 /* The file has no symbol versioning. */
623 return 0;
625 def = (ElfW(Verdef) *) ((char *) map->l_addr
626 + map->l_info[VERDEFTAG]->d_un.d_ptr);
627 while (1)
629 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
631 /* Compare the version strings. */
632 if (strcmp (string, strtab + aux->vda_name) == 0)
633 /* Bingo! */
634 return 1;
636 /* If no more definitions we failed to find what we want. */
637 if (def->vd_next == 0)
638 break;
640 /* Next definition. */
641 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
644 return 0;
647 #ifdef _LIBC_REENTRANT
648 /* _dl_error_catch_tsd points to this for the single-threaded case.
649 It's reset by the thread library for multithreaded programs. */
650 void ** __attribute__ ((const))
651 _dl_initial_error_catch_tsd (void)
653 static void *data;
654 return &data;
656 #endif
658 #if defined SHARED && defined _LIBC_REENTRANT \
659 && defined __rtld_lock_default_lock_recursive
660 static void rtld_lock_default_lock_recursive (void *lock)
662 __rtld_lock_default_lock_recursive (lock);
665 static void rtld_lock_default_unlock_recursive (void *lock)
667 __rtld_lock_default_unlock_recursive (lock);
669 #endif
672 /* The library search path. */
673 static const char *library_path attribute_relro;
674 /* The list preloaded objects. */
675 static const char *preloadlist attribute_relro;
676 /* Nonzero if information about versions has to be printed. */
677 static int version_info attribute_relro;
679 static void
680 dl_main (const ElfW(Phdr) *phdr,
681 ElfW(Word) phnum,
682 ElfW(Addr) *user_entry)
684 const ElfW(Phdr) *ph;
685 enum mode mode;
686 struct link_map **preloads;
687 unsigned int npreloads;
688 size_t file_size;
689 char *file;
690 bool has_interp = false;
691 unsigned int i;
692 bool prelinked = false;
693 bool rtld_is_main = false;
694 #ifndef HP_TIMING_NONAVAIL
695 hp_timing_t start;
696 hp_timing_t stop;
697 hp_timing_t diff;
698 #endif
699 #ifdef USE_TLS
700 void *tcbp;
701 #endif
703 #ifdef _LIBC_REENTRANT
704 /* Explicit initialization since the reloc would just be more work. */
705 GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
706 #endif
708 #ifdef USE_TLS
709 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
710 #endif
712 #if defined SHARED && defined _LIBC_REENTRANT \
713 && defined __rtld_lock_default_lock_recursive
714 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
715 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
716 #endif
718 /* The explicit initialization here is cheaper than processing the reloc
719 in the _rtld_local definition's initializer. */
720 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
722 /* Process the environment variable which control the behaviour. */
723 process_envvars (&mode);
725 #ifndef HAVE_INLINED_SYSCALLS
726 /* Set up a flag which tells we are just starting. */
727 INTUSE(_dl_starting_up) = 1;
728 #endif
730 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
732 /* Ho ho. We are not the program interpreter! We are the program
733 itself! This means someone ran ld.so as a command. Well, that
734 might be convenient to do sometimes. We support it by
735 interpreting the args like this:
737 ld.so PROGRAM ARGS...
739 The first argument is the name of a file containing an ELF
740 executable we will load and run with the following arguments.
741 To simplify life here, PROGRAM is searched for using the
742 normal rules for shared objects, rather than $PATH or anything
743 like that. We just load it and use its entry point; we don't
744 pay attention to its PT_INTERP command (we are the interpreter
745 ourselves). This is an easy way to test a new ld.so before
746 installing it. */
747 rtld_is_main = true;
749 /* Note the place where the dynamic linker actually came from. */
750 GL(dl_rtld_map).l_name = rtld_progname;
752 while (_dl_argc > 1)
753 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
755 mode = list;
756 GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
758 ++_dl_skip_args;
759 --_dl_argc;
760 ++INTUSE(_dl_argv);
762 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
764 mode = verify;
766 ++_dl_skip_args;
767 --_dl_argc;
768 ++INTUSE(_dl_argv);
770 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
771 && _dl_argc > 2)
773 library_path = INTUSE(_dl_argv)[2];
775 _dl_skip_args += 2;
776 _dl_argc -= 2;
777 INTUSE(_dl_argv) += 2;
779 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
780 && _dl_argc > 2)
782 GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
784 _dl_skip_args += 2;
785 _dl_argc -= 2;
786 INTUSE(_dl_argv) += 2;
788 else
789 break;
791 /* If we have no further argument the program was called incorrectly.
792 Grant the user some education. */
793 if (_dl_argc < 2)
794 _dl_fatal_printf ("\
795 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
796 You have invoked `ld.so', the helper program for shared library executables.\n\
797 This program usually lives in the file `/lib/ld.so', and special directives\n\
798 in executable files using ELF shared libraries tell the system's program\n\
799 loader to load the helper program from this file. This helper program loads\n\
800 the shared libraries needed by the program executable, prepares the program\n\
801 to run, and runs it. You may invoke this helper program directly from the\n\
802 command line to load and run an ELF executable file; this is like executing\n\
803 that file itself, but always uses this helper program from the file you\n\
804 specified, instead of the helper program file specified in the executable\n\
805 file you run. This is mostly of use for maintainers to test new versions\n\
806 of this helper program; chances are you did not intend to run this program.\n\
808 --list list all dependencies and how they are resolved\n\
809 --verify verify that given object really is a dynamically linked\n\
810 object we can handle\n\
811 --library-path PATH use given PATH instead of content of the environment\n\
812 variable LD_LIBRARY_PATH\n\
813 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
814 in LIST\n");
816 ++_dl_skip_args;
817 --_dl_argc;
818 ++INTUSE(_dl_argv);
820 /* Initialize the data structures for the search paths for shared
821 objects. */
822 _dl_init_paths (library_path);
824 /* The initialization of _dl_stack_flags done below assumes the
825 executable's PT_GNU_STACK may have been honored by the kernel, and
826 so a PT_GNU_STACK with PF_X set means the stack started out with
827 execute permission. However, this is not really true if the
828 dynamic linker is the executable the kernel loaded. For this
829 case, we must reinitialize _dl_stack_flags to match the dynamic
830 linker itself. If the dynamic linker was built with a
831 PT_GNU_STACK, then the kernel may have loaded us with a
832 nonexecutable stack that we will have to make executable when we
833 load the program below unless it has a PT_GNU_STACK indicating
834 nonexecutable stack is ok. */
836 for (ph = phdr; ph < &phdr[phnum]; ++ph)
837 if (ph->p_type == PT_GNU_STACK)
839 GL(dl_stack_flags) = ph->p_flags;
840 break;
843 if (__builtin_expect (mode, normal) == verify)
845 const char *objname;
846 const char *err_str = NULL;
847 struct map_args args;
849 args.str = rtld_progname;
850 args.loader = NULL;
851 args.is_preloaded = 0;
852 args.mode = __RTLD_OPENEXEC;
853 (void) _dl_catch_error (&objname, &err_str, map_doit, &args);
854 if (__builtin_expect (err_str != NULL, 0))
855 /* We don't free the returned string, the programs stops
856 anyway. */
857 _exit (EXIT_FAILURE);
859 else
861 HP_TIMING_NOW (start);
862 _dl_map_object (NULL, rtld_progname, 0, lt_library, 0,
863 __RTLD_OPENEXEC);
864 HP_TIMING_NOW (stop);
866 HP_TIMING_DIFF (load_time, start, stop);
869 phdr = GL(dl_loaded)->l_phdr;
870 phnum = GL(dl_loaded)->l_phnum;
871 /* We overwrite here a pointer to a malloc()ed string. But since
872 the malloc() implementation used at this point is the dummy
873 implementations which has no real free() function it does not
874 makes sense to free the old string first. */
875 GL(dl_loaded)->l_name = (char *) "";
876 *user_entry = GL(dl_loaded)->l_entry;
878 else
880 /* Create a link_map for the executable itself.
881 This will be what dlopen on "" returns. */
882 _dl_new_object ((char *) "", "", lt_executable, NULL);
883 if (GL(dl_loaded) == NULL)
884 _dl_fatal_printf ("cannot allocate memory for link map\n");
885 GL(dl_loaded)->l_phdr = phdr;
886 GL(dl_loaded)->l_phnum = phnum;
887 GL(dl_loaded)->l_entry = *user_entry;
889 /* At this point we are in a bit of trouble. We would have to
890 fill in the values for l_dev and l_ino. But in general we
891 do not know where the file is. We also do not handle AT_EXECFD
892 even if it would be passed up.
894 We leave the values here defined to 0. This is normally no
895 problem as the program code itself is normally no shared
896 object and therefore cannot be loaded dynamically. Nothing
897 prevent the use of dynamic binaries and in these situations
898 we might get problems. We might not be able to find out
899 whether the object is already loaded. But since there is no
900 easy way out and because the dynamic binary must also not
901 have an SONAME we ignore this program for now. If it becomes
902 a problem we can force people using SONAMEs. */
904 /* We delay initializing the path structure until we got the dynamic
905 information for the program. */
908 GL(dl_loaded)->l_map_end = 0;
909 GL(dl_loaded)->l_text_end = 0;
910 /* Perhaps the executable has no PT_LOAD header entries at all. */
911 GL(dl_loaded)->l_map_start = ~0;
912 /* We opened the file, account for it. */
913 ++GL(dl_loaded)->l_opencount;
915 /* Scan the program header table for the dynamic section. */
916 for (ph = phdr; ph < &phdr[phnum]; ++ph)
917 switch (ph->p_type)
919 case PT_PHDR:
920 /* Find out the load address. */
921 GL(dl_loaded)->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
922 break;
923 case PT_DYNAMIC:
924 /* This tells us where to find the dynamic section,
925 which tells us everything we need to do. */
926 GL(dl_loaded)->l_ld = (void *) GL(dl_loaded)->l_addr + ph->p_vaddr;
927 break;
928 case PT_INTERP:
929 /* This "interpreter segment" was used by the program loader to
930 find the program interpreter, which is this program itself, the
931 dynamic linker. We note what name finds us, so that a future
932 dlopen call or DT_NEEDED entry, for something that wants to link
933 against the dynamic linker as a shared library, will know that
934 the shared object is already loaded. */
935 _dl_rtld_libname.name = ((const char *) GL(dl_loaded)->l_addr
936 + ph->p_vaddr);
937 /* _dl_rtld_libname.next = NULL; Already zero. */
938 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
940 /* Ordinarilly, we would get additional names for the loader from
941 our DT_SONAME. This can't happen if we were actually linked as
942 a static executable (detect this case when we have no DYNAMIC).
943 If so, assume the filename component of the interpreter path to
944 be our SONAME, and add it to our name list. */
945 if (GL(dl_rtld_map).l_ld == NULL)
947 const char *p = NULL;
948 const char *cp = _dl_rtld_libname.name;
950 /* Find the filename part of the path. */
951 while (*cp != '\0')
952 if (*cp++ == '/')
953 p = cp;
955 if (p != NULL)
957 _dl_rtld_libname2.name = p;
958 /* _dl_rtld_libname2.next = NULL; Already zero. */
959 _dl_rtld_libname.next = &_dl_rtld_libname2;
963 has_interp = true;
964 break;
965 case PT_LOAD:
967 ElfW(Addr) mapstart;
968 ElfW(Addr) allocend;
970 /* Remember where the main program starts in memory. */
971 mapstart = (GL(dl_loaded)->l_addr
972 + (ph->p_vaddr & ~(ph->p_align - 1)));
973 if (GL(dl_loaded)->l_map_start > mapstart)
974 GL(dl_loaded)->l_map_start = mapstart;
976 /* Also where it ends. */
977 allocend = GL(dl_loaded)->l_addr + ph->p_vaddr + ph->p_memsz;
978 if (GL(dl_loaded)->l_map_end < allocend)
979 GL(dl_loaded)->l_map_end = allocend;
980 if ((ph->p_flags & PF_X) && allocend > GL(dl_loaded)->l_text_end)
981 GL(dl_loaded)->l_text_end = allocend;
983 break;
984 #ifdef USE_TLS
985 case PT_TLS:
986 if (ph->p_memsz > 0)
988 /* Note that in the case the dynamic linker we duplicate work
989 here since we read the PT_TLS entry already in
990 _dl_start_final. But the result is repeatable so do not
991 check for this special but unimportant case. */
992 GL(dl_loaded)->l_tls_blocksize = ph->p_memsz;
993 GL(dl_loaded)->l_tls_align = ph->p_align;
994 if (ph->p_align == 0)
995 GL(dl_loaded)->l_tls_firstbyte_offset = 0;
996 else
997 GL(dl_loaded)->l_tls_firstbyte_offset = (ph->p_vaddr
998 & (ph->p_align - 1));
999 GL(dl_loaded)->l_tls_initimage_size = ph->p_filesz;
1000 GL(dl_loaded)->l_tls_initimage = (void *) ph->p_vaddr;
1002 /* This image gets the ID one. */
1003 GL(dl_tls_max_dtv_idx) = GL(dl_loaded)->l_tls_modid = 1;
1005 break;
1006 #endif
1007 case PT_GNU_STACK:
1008 GL(dl_stack_flags) = ph->p_flags;
1009 break;
1011 case PT_GNU_RELRO:
1012 GL(dl_loaded)->l_relro_addr = ph->p_vaddr;
1013 GL(dl_loaded)->l_relro_size = ph->p_memsz;
1014 break;
1016 #ifdef USE_TLS
1017 /* Adjust the address of the TLS initialization image in case
1018 the executable is actually an ET_DYN object. */
1019 if (GL(dl_loaded)->l_tls_initimage != NULL)
1020 GL(dl_loaded)->l_tls_initimage
1021 = (char *) GL(dl_loaded)->l_tls_initimage + GL(dl_loaded)->l_addr;
1022 #endif
1023 if (! GL(dl_loaded)->l_map_end)
1024 GL(dl_loaded)->l_map_end = ~0;
1025 if (! GL(dl_loaded)->l_text_end)
1026 GL(dl_loaded)->l_text_end = ~0;
1027 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1029 /* We were invoked directly, so the program might not have a
1030 PT_INTERP. */
1031 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1032 /* _dl_rtld_libname.next = NULL; Already zero. */
1033 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1035 else
1036 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1038 if (! rtld_is_main)
1040 /* Extract the contents of the dynamic section for easy access. */
1041 elf_get_dynamic_info (GL(dl_loaded), NULL);
1042 if (GL(dl_loaded)->l_info[DT_HASH])
1043 /* Set up our cache of pointers into the hash table. */
1044 _dl_setup_hash (GL(dl_loaded));
1047 if (__builtin_expect (mode, normal) == verify)
1049 /* We were called just to verify that this is a dynamic
1050 executable using us as the program interpreter. Exit with an
1051 error if we were not able to load the binary or no interpreter
1052 is specified (i.e., this is no dynamically linked binary. */
1053 if (GL(dl_loaded)->l_ld == NULL)
1054 _exit (1);
1056 /* We allow here some platform specific code. */
1057 #ifdef DISTINGUISH_LIB_VERSIONS
1058 DISTINGUISH_LIB_VERSIONS;
1059 #endif
1060 _exit (has_interp ? 0 : 2);
1063 if (! rtld_is_main)
1064 /* Initialize the data structures for the search paths for shared
1065 objects. */
1066 _dl_init_paths (library_path);
1068 /* Put the link_map for ourselves on the chain so it can be found by
1069 name. Note that at this point the global chain of link maps contains
1070 exactly one element, which is pointed to by dl_loaded. */
1071 if (! GL(dl_rtld_map).l_name)
1072 /* If not invoked directly, the dynamic linker shared object file was
1073 found by the PT_INTERP name. */
1074 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1075 GL(dl_rtld_map).l_type = lt_library;
1076 GL(dl_loaded)->l_next = &GL(dl_rtld_map);
1077 GL(dl_rtld_map).l_prev = GL(dl_loaded);
1078 ++GL(dl_nloaded);
1079 ++GL(dl_load_adds);
1081 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1082 to not using bias for non-prelinked PIEs and libraries
1083 and using it for executables or prelinked PIEs or libraries. */
1084 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1085 GLRO(dl_use_load_bias) = (GL(dl_loaded)->l_addr == 0) ? -1 : 0;
1087 /* Set up the program header information for the dynamic linker
1088 itself. It is needed in the dl_iterate_phdr() callbacks. */
1089 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1090 ElfW(Phdr) *rtld_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1091 + rtld_ehdr->e_phoff);
1092 GL(dl_rtld_map).l_phdr = rtld_phdr;
1093 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1095 /* PT_GNU_RELRO is usually the last phdr. */
1096 size_t cnt = rtld_ehdr->e_phnum;
1097 while (cnt-- > 0)
1098 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1100 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1101 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1102 break;
1105 /* We have two ways to specify objects to preload: via environment
1106 variable and via the file /etc/ld.so.preload. The latter can also
1107 be used when security is enabled. */
1108 preloads = NULL;
1109 npreloads = 0;
1111 if (__builtin_expect (preloadlist != NULL, 0))
1113 /* The LD_PRELOAD environment variable gives list of libraries
1114 separated by white space or colons that are loaded before the
1115 executable's dependencies and prepended to the global scope
1116 list. If the binary is running setuid all elements
1117 containing a '/' are ignored since it is insecure. */
1118 char *list = strdupa (preloadlist);
1119 char *p;
1121 HP_TIMING_NOW (start);
1123 /* Prevent optimizing strsep. Speed is not important here. */
1124 while ((p = (strsep) (&list, " :")) != NULL)
1125 if (p[0] != '\0'
1126 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1127 || strchr (p, '/') == NULL))
1129 struct link_map *new_map = _dl_map_object (GL(dl_loaded), p, 1,
1130 lt_library, 0, 0);
1131 if (++new_map->l_opencount == 1)
1132 /* It is no duplicate. */
1133 ++npreloads;
1136 HP_TIMING_NOW (stop);
1137 HP_TIMING_DIFF (diff, start, stop);
1138 HP_TIMING_ACCUM_NT (load_time, diff);
1141 /* Read the contents of the file. */
1142 const char preload_file[] = "/etc/ld.so.preload";
1143 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1144 PROT_READ | PROT_WRITE);
1145 if (__builtin_expect (file != MAP_FAILED, 0))
1147 /* Parse the file. It contains names of libraries to be loaded,
1148 separated by white spaces or `:'. It may also contain
1149 comments introduced by `#'. */
1150 char *problem;
1151 char *runp;
1152 size_t rest;
1154 /* Eliminate comments. */
1155 runp = file;
1156 rest = file_size;
1157 while (rest > 0)
1159 char *comment = memchr (runp, '#', rest);
1160 if (comment == NULL)
1161 break;
1163 rest -= comment - runp;
1165 *comment = ' ';
1166 while (--rest > 0 && *++comment != '\n');
1169 /* We have one problematic case: if we have a name at the end of
1170 the file without a trailing terminating characters, we cannot
1171 place the \0. Handle the case separately. */
1172 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1173 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1175 problem = &file[file_size];
1176 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
1177 && problem[-1] != '\n' && problem[-1] != ':')
1178 --problem;
1180 if (problem > file)
1181 problem[-1] = '\0';
1183 else
1185 problem = NULL;
1186 file[file_size - 1] = '\0';
1189 HP_TIMING_NOW (start);
1191 if (file != problem)
1193 char *p;
1194 runp = file;
1195 while ((p = strsep (&runp, ": \t\n")) != NULL)
1196 if (p[0] != '\0')
1198 const char *objname;
1199 const char *err_str = NULL;
1200 struct map_args args;
1202 args.str = p;
1203 args.loader = GL(dl_loaded);
1204 args.is_preloaded = 1;
1205 args.mode = 0;
1207 (void) _dl_catch_error (&objname, &err_str, map_doit, &args);
1208 if (__builtin_expect (err_str != NULL, 0))
1210 _dl_error_printf ("\
1211 ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
1212 p, preload_file);
1213 /* No need to call free, this is still before the libc's
1214 malloc is used. */
1216 else if (++args.map->l_opencount == 1)
1217 /* It is no duplicate. */
1218 ++npreloads;
1222 if (problem != NULL)
1224 char *p = strndupa (problem, file_size - (problem - file));
1225 struct link_map *new_map = _dl_map_object (GL(dl_loaded), p, 1,
1226 lt_library, 0, 0);
1227 if (++new_map->l_opencount == 1)
1228 /* It is no duplicate. */
1229 ++npreloads;
1232 HP_TIMING_NOW (stop);
1233 HP_TIMING_DIFF (diff, start, stop);
1234 HP_TIMING_ACCUM_NT (load_time, diff);
1236 /* We don't need the file anymore. */
1237 __munmap (file, file_size);
1240 if (__builtin_expect (npreloads, 0) != 0)
1242 /* Set up PRELOADS with a vector of the preloaded libraries. */
1243 struct link_map *l;
1244 preloads = __alloca (npreloads * sizeof preloads[0]);
1245 l = GL(dl_rtld_map).l_next; /* End of the chain before preloads. */
1246 i = 0;
1249 preloads[i++] = l;
1250 l = l->l_next;
1251 } while (l);
1252 assert (i == npreloads);
1255 #ifdef NEED_DL_SYSINFO
1256 struct link_map *sysinfo_map = NULL;
1257 if (GLRO(dl_sysinfo_dso) != NULL)
1259 /* Do an abridged version of the work _dl_map_object_from_fd would do
1260 to map in the object. It's already mapped and prelinked (and
1261 better be, since it's read-only and so we couldn't relocate it).
1262 We just want our data structures to describe it as if we had just
1263 mapped and relocated it normally. */
1264 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL);
1265 if (__builtin_expect (l != NULL, 1))
1267 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
1269 l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1270 + GLRO(dl_sysinfo_dso)->e_phoff);
1271 l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1272 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1274 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1275 if (ph->p_type == PT_DYNAMIC)
1277 l->l_ld = (void *) ph->p_vaddr;
1278 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1280 else if (ph->p_type == PT_LOAD)
1282 if (! l->l_addr)
1283 l->l_addr = ph->p_vaddr;
1284 else if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1285 l->l_map_end = ph->p_vaddr + ph->p_memsz;
1286 else if ((ph->p_flags & PF_X)
1287 && ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1288 l->l_text_end = ph->p_vaddr + ph->p_memsz;
1291 l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1292 l->l_addr = l->l_map_start - l->l_addr;
1293 l->l_map_end += l->l_addr;
1294 l->l_text_end += l->l_addr;
1295 l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1296 elf_get_dynamic_info (l, dyn_temp);
1297 _dl_setup_hash (l);
1298 l->l_relocated = 1;
1300 /* Now that we have the info handy, use the DSO image's soname
1301 so this object can be looked up by name. Note that we do not
1302 set l_name here. That field gives the file name of the DSO,
1303 and this DSO is not associated with any file. */
1304 if (l->l_info[DT_SONAME] != NULL)
1306 /* Work around a kernel problem. The kernel cannot handle
1307 addresses in the vsyscall DSO pages in writev() calls. */
1308 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1309 + l->l_info[DT_SONAME]->d_un.d_val);
1310 size_t len = strlen (dsoname);
1311 char *copy = malloc (len);
1312 if (copy == NULL)
1313 _dl_fatal_printf ("out of memory\n");
1314 l->l_libname->name = memcpy (copy, dsoname, len);
1317 /* We have a prelinked DSO preloaded by the system. */
1318 if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1319 GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1320 sysinfo_map = l;
1323 #endif
1325 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1326 specified some libraries to load, these are inserted before the actual
1327 dependencies in the executable's searchlist for symbol resolution. */
1328 HP_TIMING_NOW (start);
1329 _dl_map_object_deps (GL(dl_loaded), preloads, npreloads, mode == trace, 0);
1330 HP_TIMING_NOW (stop);
1331 HP_TIMING_DIFF (diff, start, stop);
1332 HP_TIMING_ACCUM_NT (load_time, diff);
1334 /* Mark all objects as being in the global scope and set the open
1335 counter. */
1336 for (i = GL(dl_loaded)->l_searchlist.r_nlist; i > 0; )
1338 --i;
1339 GL(dl_loaded)->l_searchlist.r_list[i]->l_global = 1;
1340 ++GL(dl_loaded)->l_searchlist.r_list[i]->l_opencount;
1343 #ifndef MAP_ANON
1344 /* We are done mapping things, so close the zero-fill descriptor. */
1345 __close (_dl_zerofd);
1346 _dl_zerofd = -1;
1347 #endif
1349 /* Remove _dl_rtld_map from the chain. */
1350 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1351 if (GL(dl_rtld_map).l_next)
1352 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1354 if (__builtin_expect (GL(dl_rtld_map).l_opencount > 1, 1))
1356 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1357 put it back in the list of visible objects. We insert it into the
1358 chain in symbol search order because gdb uses the chain's order as
1359 its symbol search order. */
1360 i = 1;
1361 while (GL(dl_loaded)->l_searchlist.r_list[i] != &GL(dl_rtld_map))
1362 ++i;
1363 GL(dl_rtld_map).l_prev = GL(dl_loaded)->l_searchlist.r_list[i - 1];
1364 if (__builtin_expect (mode, normal) == normal)
1366 GL(dl_rtld_map).l_next = (i + 1 < GL(dl_loaded)->l_searchlist.r_nlist
1367 ? GL(dl_loaded)->l_searchlist.r_list[i + 1]
1368 : NULL);
1369 #ifdef NEED_DL_SYSINFO
1370 if (sysinfo_map != NULL
1371 && GL(dl_rtld_map).l_prev->l_next == sysinfo_map
1372 && GL(dl_rtld_map).l_next != sysinfo_map)
1373 GL(dl_rtld_map).l_prev = sysinfo_map;
1374 #endif
1376 else
1377 /* In trace mode there might be an invisible object (which we
1378 could not find) after the previous one in the search list.
1379 In this case it doesn't matter much where we put the
1380 interpreter object, so we just initialize the list pointer so
1381 that the assertion below holds. */
1382 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1384 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1385 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1386 if (GL(dl_rtld_map).l_next != NULL)
1388 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1389 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1393 /* Now let us see whether all libraries are available in the
1394 versions we need. */
1396 struct version_check_args args;
1397 args.doexit = mode == normal;
1398 args.dotrace = mode == trace;
1399 _dl_receive_error (print_missing_version, version_check_doit, &args);
1402 #ifdef USE_TLS
1403 /* Now it is time to determine the layout of the static TLS block
1404 and allocate it for the initial thread. Note that we always
1405 allocate the static block, we never defer it even if no
1406 DF_STATIC_TLS bit is set. The reason is that we know glibc will
1407 use the static model. First add the dynamic linker to the list
1408 if it also uses TLS. */
1409 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1410 /* Assign a module ID. */
1411 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1413 # ifndef TLS_INIT_TP_EXPENSIVE
1414 # define TLS_INIT_TP_EXPENSIVE 0
1415 # endif
1417 /* We do not initialize any of the TLS functionality unless any of the
1418 initial modules uses TLS. This makes dynamic loading of modules with
1419 TLS impossible, but to support it requires either eagerly doing setup
1420 now or lazily doing it later. Doing it now makes us incompatible with
1421 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1422 used. Trying to do it lazily is too hairy to try when there could be
1423 multiple threads (from a non-TLS-using libpthread). */
1424 if (!TLS_INIT_TP_EXPENSIVE || GL(dl_tls_max_dtv_idx) > 0)
1426 struct link_map *l;
1427 size_t nelem;
1428 struct dtv_slotinfo *slotinfo;
1430 /* Number of elements in the static TLS block. */
1431 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
1433 /* Allocate the array which contains the information about the
1434 dtv slots. We allocate a few entries more than needed to
1435 avoid the need for reallocation. */
1436 nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
1438 /* Allocate. */
1439 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
1440 malloc (sizeof (struct dtv_slotinfo_list)
1441 + nelem * sizeof (struct dtv_slotinfo));
1442 /* No need to check the return value. If memory allocation failed
1443 the program would have been terminated. */
1445 slotinfo = memset (GL(dl_tls_dtv_slotinfo_list)->slotinfo, '\0',
1446 nelem * sizeof (struct dtv_slotinfo));
1447 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
1448 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
1450 /* Fill in the information from the loaded modules. */
1451 for (l = GL(dl_loaded), i = 0; l != NULL; l = l->l_next)
1452 if (l->l_tls_blocksize != 0)
1453 /* This is a module with TLS data. Store the map reference.
1454 The generation counter is zero. */
1455 slotinfo[++i].map = l;
1456 assert (i == GL(dl_tls_max_dtv_idx));
1458 /* Compute the TLS offsets for the various blocks. */
1459 _dl_determine_tlsoffset ();
1461 /* Construct the static TLS block and the dtv for the initial
1462 thread. For some platforms this will include allocating memory
1463 for the thread descriptor. The memory for the TLS block will
1464 never be freed. It should be allocated accordingly. The dtv
1465 array can be changed if dynamic loading requires it. */
1466 tcbp = _dl_allocate_tls_storage ();
1467 if (tcbp == NULL)
1468 _dl_fatal_printf ("\
1469 cannot allocate TLS data structures for initial thread");
1471 /* Store for detection of the special case by __tls_get_addr
1472 so it knows not to pass this dtv to the normal realloc. */
1473 GL(dl_initial_dtv) = GET_DTV (tcbp);
1475 #endif
1477 if (__builtin_expect (mode, normal) != normal)
1479 /* We were run just to list the shared libraries. It is
1480 important that we do this before real relocation, because the
1481 functions we call below for output may no longer work properly
1482 after relocation. */
1483 struct link_map *l;
1485 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1487 struct r_scope_elem *scope = &GL(dl_loaded)->l_searchlist;
1489 for (i = 0; i < scope->r_nlist; i++)
1491 l = scope->r_list [i];
1492 if (l->l_faked)
1494 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1495 continue;
1497 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1498 GLRO(dl_trace_prelink_map) = l;
1499 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1500 l->l_libname->name[0] ? l->l_libname->name
1501 : rtld_progname ?: "<main program>",
1502 l->l_name[0] ? l->l_name
1503 : rtld_progname ?: "<main program>",
1504 (int) sizeof l->l_map_start * 2,
1505 (size_t) l->l_map_start,
1506 (int) sizeof l->l_addr * 2,
1507 (size_t) l->l_addr);
1508 #ifdef USE_TLS
1509 if (l->l_tls_modid)
1510 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1511 (int) sizeof l->l_tls_offset * 2,
1512 (size_t) l->l_tls_offset);
1513 else
1514 #endif
1515 _dl_printf ("\n");
1518 else if (! GL(dl_loaded)->l_info[DT_NEEDED])
1519 _dl_printf ("\tstatically linked\n");
1520 else
1522 for (l = GL(dl_loaded)->l_next; l; l = l->l_next)
1523 if (l->l_faked)
1524 /* The library was not found. */
1525 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1526 else
1527 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1528 l->l_name, (int) sizeof l->l_map_start * 2,
1529 (size_t) l->l_map_start);
1532 if (__builtin_expect (mode, trace) != trace)
1533 for (i = 1; i < (unsigned int) _dl_argc; ++i)
1535 const ElfW(Sym) *ref = NULL;
1536 ElfW(Addr) loadbase;
1537 lookup_t result;
1539 result = _dl_lookup_symbol_x (INTUSE(_dl_argv)[i], GL(dl_loaded),
1540 &ref, GL(dl_loaded)->l_scope, NULL,
1541 ELF_RTYPE_CLASS_PLT,
1542 DL_LOOKUP_ADD_DEPENDENCY, NULL);
1544 loadbase = LOOKUP_VALUE_ADDRESS (result);
1546 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
1547 INTUSE(_dl_argv)[i],
1548 (int) sizeof ref->st_value * 2,
1549 (size_t) ref->st_value,
1550 (int) sizeof loadbase * 2, (size_t) loadbase);
1552 else
1554 /* If LD_WARN is set warn about undefined symbols. */
1555 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
1557 /* We have to do symbol dependency testing. */
1558 struct relocate_args args;
1559 struct link_map *l;
1561 args.lazy = GLRO(dl_lazy);
1563 l = GL(dl_loaded);
1564 while (l->l_next)
1565 l = l->l_next;
1568 if (l != &GL(dl_rtld_map) && ! l->l_faked)
1570 args.l = l;
1571 _dl_receive_error (print_unresolved, relocate_doit,
1572 &args);
1574 l = l->l_prev;
1575 } while (l);
1577 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1578 && GL(dl_rtld_map).l_opencount > 1)
1579 _dl_relocate_object (&GL(dl_rtld_map), GL(dl_loaded)->l_scope,
1580 0, 0);
1583 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
1584 if (version_info)
1586 /* Print more information. This means here, print information
1587 about the versions needed. */
1588 int first = 1;
1589 struct link_map *map = GL(dl_loaded);
1591 for (map = GL(dl_loaded); map != NULL; map = map->l_next)
1593 const char *strtab;
1594 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
1595 ElfW(Verneed) *ent;
1597 if (dyn == NULL)
1598 continue;
1600 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
1601 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
1603 if (first)
1605 _dl_printf ("\n\tVersion information:\n");
1606 first = 0;
1609 _dl_printf ("\t%s:\n",
1610 map->l_name[0] ? map->l_name : rtld_progname);
1612 while (1)
1614 ElfW(Vernaux) *aux;
1615 struct link_map *needed;
1617 needed = find_needed (strtab + ent->vn_file);
1618 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
1620 while (1)
1622 const char *fname = NULL;
1624 if (needed != NULL
1625 && match_version (strtab + aux->vna_name,
1626 needed))
1627 fname = needed->l_name;
1629 _dl_printf ("\t\t%s (%s) %s=> %s\n",
1630 strtab + ent->vn_file,
1631 strtab + aux->vna_name,
1632 aux->vna_flags & VER_FLG_WEAK
1633 ? "[WEAK] " : "",
1634 fname ?: "not found");
1636 if (aux->vna_next == 0)
1637 /* No more symbols. */
1638 break;
1640 /* Next symbol. */
1641 aux = (ElfW(Vernaux) *) ((char *) aux
1642 + aux->vna_next);
1645 if (ent->vn_next == 0)
1646 /* No more dependencies. */
1647 break;
1649 /* Next dependency. */
1650 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
1656 _exit (0);
1659 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]
1660 && ! __builtin_expect (GLRO(dl_profile) != NULL, 0))
1662 ElfW(Lib) *liblist, *liblistend;
1663 struct link_map **r_list, **r_listend, *l;
1664 const char *strtab = (const void *) D_PTR (GL(dl_loaded),
1665 l_info[DT_STRTAB]);
1667 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
1668 liblist = (ElfW(Lib) *)
1669 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
1670 liblistend = (ElfW(Lib) *)
1671 ((char *) liblist
1672 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
1673 r_list = GL(dl_loaded)->l_searchlist.r_list;
1674 r_listend = r_list + GL(dl_loaded)->l_searchlist.r_nlist;
1676 for (; r_list < r_listend && liblist < liblistend; r_list++)
1678 l = *r_list;
1680 if (l == GL(dl_loaded))
1681 continue;
1683 /* If the library is not mapped where it should, fail. */
1684 if (l->l_addr)
1685 break;
1687 /* Next, check if checksum matches. */
1688 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
1689 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
1690 != liblist->l_checksum)
1691 break;
1693 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
1694 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
1695 != liblist->l_time_stamp)
1696 break;
1698 if (! _dl_name_match_p (strtab + liblist->l_name, l))
1699 break;
1701 ++liblist;
1705 if (r_list == r_listend && liblist == liblistend)
1706 prelinked = true;
1708 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1709 _dl_printf ("\nprelink checking: %s\n", prelinked ? "ok" : "failed");
1713 /* Initialize _r_debug. */
1714 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr);
1716 struct link_map *l;
1718 l = GL(dl_loaded);
1720 #ifdef ELF_MACHINE_DEBUG_SETUP
1722 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1724 ELF_MACHINE_DEBUG_SETUP (l, r);
1725 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1727 #else
1729 if (l->l_info[DT_DEBUG] != NULL)
1730 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1731 with the run-time address of the r_debug structure */
1732 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1734 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1735 case you run gdb on the dynamic linker directly. */
1736 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1737 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1738 #endif
1741 /* Now set up the variable which helps the assembler startup code. */
1742 GL(dl_main_searchlist) = &GL(dl_loaded)->l_searchlist;
1743 GL(dl_global_scope)[0] = &GL(dl_loaded)->l_searchlist;
1745 /* Save the information about the original global scope list since
1746 we need it in the memory handling later. */
1747 GLRO(dl_initial_searchlist) = *GL(dl_main_searchlist);
1749 if (prelinked)
1751 struct link_map *l;
1753 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
1755 ElfW(Rela) *conflict, *conflictend;
1756 #ifndef HP_TIMING_NONAVAIL
1757 hp_timing_t start;
1758 hp_timing_t stop;
1759 #endif
1761 HP_TIMING_NOW (start);
1762 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
1763 conflict = (ElfW(Rela) *)
1764 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
1765 conflictend = (ElfW(Rela) *)
1766 ((char *) conflict
1767 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
1768 _dl_resolve_conflicts (GL(dl_loaded), conflict, conflictend);
1769 HP_TIMING_NOW (stop);
1770 HP_TIMING_DIFF (relocate_time, start, stop);
1774 /* Mark all the objects so we know they have been already relocated. */
1775 for (l = GL(dl_loaded); l != NULL; l = l->l_next)
1777 l->l_relocated = 1;
1778 if (l->l_relro_size)
1779 _dl_protect_relro (l);
1782 _dl_sysdep_start_cleanup ();
1784 else
1786 /* Now we have all the objects loaded. Relocate them all except for
1787 the dynamic linker itself. We do this in reverse order so that copy
1788 relocs of earlier objects overwrite the data written by later
1789 objects. We do not re-relocate the dynamic linker itself in this
1790 loop because that could result in the GOT entries for functions we
1791 call being changed, and that would break us. It is safe to relocate
1792 the dynamic linker out of order because it has no copy relocs (we
1793 know that because it is self-contained). */
1795 struct link_map *l;
1796 int consider_profiling = GLRO(dl_profile) != NULL;
1797 #ifndef HP_TIMING_NONAVAIL
1798 hp_timing_t start;
1799 hp_timing_t stop;
1800 hp_timing_t add;
1801 #endif
1803 /* If we are profiling we also must do lazy reloaction. */
1804 GLRO(dl_lazy) |= consider_profiling;
1806 l = GL(dl_loaded);
1807 while (l->l_next)
1808 l = l->l_next;
1810 HP_TIMING_NOW (start);
1813 /* While we are at it, help the memory handling a bit. We have to
1814 mark some data structures as allocated with the fake malloc()
1815 implementation in ld.so. */
1816 struct libname_list *lnp = l->l_libname->next;
1818 while (__builtin_expect (lnp != NULL, 0))
1820 lnp->dont_free = 1;
1821 lnp = lnp->next;
1824 if (l != &GL(dl_rtld_map))
1825 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy),
1826 consider_profiling);
1828 l = l->l_prev;
1830 while (l);
1831 HP_TIMING_NOW (stop);
1833 HP_TIMING_DIFF (relocate_time, start, stop);
1835 /* Do any necessary cleanups for the startup OS interface code.
1836 We do these now so that no calls are made after rtld re-relocation
1837 which might be resolved to different functions than we expect.
1838 We cannot do this before relocating the other objects because
1839 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
1840 _dl_sysdep_start_cleanup ();
1842 /* Now enable profiling if needed. Like the previous call,
1843 this has to go here because the calls it makes should use the
1844 rtld versions of the functions (particularly calloc()), but it
1845 needs to have _dl_profile_map set up by the relocator. */
1846 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
1847 /* We must prepare the profiling. */
1848 _dl_start_profile ();
1850 if (GL(dl_rtld_map).l_opencount > 1)
1852 /* There was an explicit ref to the dynamic linker as a shared lib.
1853 Re-relocate ourselves with user-controlled symbol definitions. */
1854 HP_TIMING_NOW (start);
1855 _dl_relocate_object (&GL(dl_rtld_map), GL(dl_loaded)->l_scope, 0, 0);
1856 HP_TIMING_NOW (stop);
1857 HP_TIMING_DIFF (add, start, stop);
1858 HP_TIMING_ACCUM_NT (relocate_time, add);
1862 #ifndef NONTLS_INIT_TP
1863 # define NONTLS_INIT_TP do { } while (0)
1864 #endif
1866 #ifdef USE_TLS
1867 if (GL(dl_tls_max_dtv_idx) > 0 || USE___THREAD || !TLS_INIT_TP_EXPENSIVE)
1869 /* Now that we have completed relocation, the initializer data
1870 for the TLS blocks has its final values and we can copy them
1871 into the main thread's TLS area, which we allocated above. */
1872 _dl_allocate_tls_init (tcbp);
1874 /* And finally install it for the main thread. If ld.so itself uses
1875 TLS we know the thread pointer was initialized earlier. */
1876 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
1877 if (__builtin_expect (lossage != NULL, 0))
1878 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
1880 else
1881 #endif
1882 NONTLS_INIT_TP;
1884 /* Notify the debugger that all objects are now mapped in. */
1885 r->r_state = RT_ADD;
1886 _dl_debug_state ();
1888 #ifndef MAP_COPY
1889 /* We must munmap() the cache file. */
1890 _dl_unload_cache ();
1891 #endif
1893 /* Once we return, _dl_sysdep_start will invoke
1894 the DT_INIT functions and then *USER_ENTRY. */
1897 /* This is a little helper function for resolving symbols while
1898 tracing the binary. */
1899 static void
1900 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
1901 const char *errstring)
1903 if (objname[0] == '\0')
1904 objname = rtld_progname ?: "<main program>";
1905 _dl_error_printf ("%s (%s)\n", errstring, objname);
1908 /* This is a little helper function for resolving symbols while
1909 tracing the binary. */
1910 static void
1911 print_missing_version (int errcode __attribute__ ((unused)),
1912 const char *objname, const char *errstring)
1914 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
1915 objname, errstring);
1918 /* Nonzero if any of the debugging options is enabled. */
1919 static int any_debug attribute_relro;
1921 /* Process the string given as the parameter which explains which debugging
1922 options are enabled. */
1923 static void
1924 process_dl_debug (const char *dl_debug)
1926 /* When adding new entries make sure that the maximal length of a name
1927 is correctly handled in the LD_DEBUG_HELP code below. */
1928 static const struct
1930 unsigned char len;
1931 const char name[10];
1932 const char helptext[41];
1933 unsigned short int mask;
1934 } debopts[] =
1936 #define LEN_AND_STR(str) sizeof (str) - 1, str
1937 { LEN_AND_STR ("libs"), "display library search paths",
1938 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
1939 { LEN_AND_STR ("reloc"), "display relocation processing",
1940 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
1941 { LEN_AND_STR ("files"), "display progress for input file",
1942 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
1943 { LEN_AND_STR ("symbols"), "display symbol table processing",
1944 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
1945 { LEN_AND_STR ("bindings"), "display information about symbol binding",
1946 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
1947 { LEN_AND_STR ("versions"), "display version dependencies",
1948 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1949 { LEN_AND_STR ("all"), "all previous options combined",
1950 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
1951 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1952 { LEN_AND_STR ("statistics"), "display relocation statistics",
1953 DL_DEBUG_STATISTICS },
1954 { LEN_AND_STR ("help"), "display this help message and exit",
1955 DL_DEBUG_HELP },
1957 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
1959 /* Skip separating white spaces and commas. */
1960 while (*dl_debug != '\0')
1962 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
1964 size_t cnt;
1965 size_t len = 1;
1967 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
1968 && dl_debug[len] != ',' && dl_debug[len] != ':')
1969 ++len;
1971 for (cnt = 0; cnt < ndebopts; ++cnt)
1972 if (debopts[cnt].len == len
1973 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
1975 GLRO(dl_debug_mask) |= debopts[cnt].mask;
1976 any_debug = 1;
1977 break;
1980 if (cnt == ndebopts)
1982 /* Display a warning and skip everything until next
1983 separator. */
1984 char *copy = strndupa (dl_debug, len);
1985 _dl_error_printf ("\
1986 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
1989 dl_debug += len;
1990 continue;
1993 ++dl_debug;
1996 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
1998 size_t cnt;
2000 _dl_printf ("\
2001 Valid options for the LD_DEBUG environment variable are:\n\n");
2003 for (cnt = 0; cnt < ndebopts; ++cnt)
2004 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2005 " " + debopts[cnt].len - 3,
2006 debopts[cnt].helptext);
2008 _dl_printf ("\n\
2009 To direct the debugging output into a file instead of standard output\n\
2010 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2011 _exit (0);
2015 /* Process all environments variables the dynamic linker must recognize.
2016 Since all of them start with `LD_' we are a bit smarter while finding
2017 all the entries. */
2018 extern char **_environ attribute_hidden;
2021 static void
2022 process_envvars (enum mode *modep)
2024 char **runp = _environ;
2025 char *envline;
2026 enum mode mode = normal;
2027 char *debug_output = NULL;
2029 /* This is the default place for profiling data file. */
2030 GLRO(dl_profile_output)
2031 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2033 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2035 size_t len = 0;
2037 while (envline[len] != '\0' && envline[len] != '=')
2038 ++len;
2040 if (envline[len] != '=')
2041 /* This is a "LD_" variable at the end of the string without
2042 a '=' character. Ignore it since otherwise we will access
2043 invalid memory below. */
2044 continue;
2046 switch (len)
2048 case 4:
2049 /* Warning level, verbose or not. */
2050 if (memcmp (envline, "WARN", 4) == 0)
2051 GLRO(dl_verbose) = envline[5] != '\0';
2052 break;
2054 case 5:
2055 /* Debugging of the dynamic linker? */
2056 if (memcmp (envline, "DEBUG", 5) == 0)
2057 process_dl_debug (&envline[6]);
2058 break;
2060 case 7:
2061 /* Print information about versions. */
2062 if (memcmp (envline, "VERBOSE", 7) == 0)
2064 version_info = envline[8] != '\0';
2065 break;
2068 /* List of objects to be preloaded. */
2069 if (memcmp (envline, "PRELOAD", 7) == 0)
2071 preloadlist = &envline[8];
2072 break;
2075 /* Which shared object shall be profiled. */
2076 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2077 GLRO(dl_profile) = &envline[8];
2078 break;
2080 case 8:
2081 /* Do we bind early? */
2082 if (memcmp (envline, "BIND_NOW", 8) == 0)
2084 GLRO(dl_lazy) = envline[9] == '\0';
2085 break;
2087 if (memcmp (envline, "BIND_NOT", 8) == 0)
2088 GLRO(dl_bind_not) = envline[9] != '\0';
2089 break;
2091 case 9:
2092 /* Test whether we want to see the content of the auxiliary
2093 array passed up from the kernel. */
2094 if (memcmp (envline, "SHOW_AUXV", 9) == 0)
2095 _dl_show_auxv ();
2096 break;
2098 case 10:
2099 /* Mask for the important hardware capabilities. */
2100 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2101 GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2102 0, 0);
2103 break;
2105 case 11:
2106 /* Path where the binary is found. */
2107 if (!INTUSE(__libc_enable_secure)
2108 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2109 GLRO(dl_origin_path) = &envline[12];
2110 break;
2112 case 12:
2113 /* The library search path. */
2114 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2116 library_path = &envline[13];
2117 break;
2120 /* Where to place the profiling data file. */
2121 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2123 debug_output = &envline[13];
2124 break;
2127 if (memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2128 GLRO(dl_dynamic_weak) = 1;
2129 break;
2131 case 13:
2132 /* We might have some extra environment variable with length 13
2133 to handle. */
2134 #ifdef EXTRA_LD_ENVVARS_13
2135 EXTRA_LD_ENVVARS_13
2136 #endif
2137 if (!INTUSE(__libc_enable_secure)
2138 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2139 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2140 break;
2142 case 14:
2143 /* Where to place the profiling data file. */
2144 if (!INTUSE(__libc_enable_secure)
2145 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2146 && envline[15] != '\0')
2147 GLRO(dl_profile_output) = &envline[15];
2148 break;
2150 case 16:
2151 /* The mode of the dynamic linker can be set. */
2152 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2154 mode = trace;
2155 GLRO(dl_verbose) = 1;
2156 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2157 GLRO(dl_trace_prelink) = &envline[17];
2159 break;
2161 case 20:
2162 /* The mode of the dynamic linker can be set. */
2163 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2164 mode = trace;
2165 break;
2167 /* We might have some extra environment variable to handle. This
2168 is tricky due to the pre-processing of the length of the name
2169 in the switch statement here. The code here assumes that added
2170 environment variables have a different length. */
2171 #ifdef EXTRA_LD_ENVVARS
2172 EXTRA_LD_ENVVARS
2173 #endif
2177 /* The caller wants this information. */
2178 *modep = mode;
2180 /* Extra security for SUID binaries. Remove all dangerous environment
2181 variables. */
2182 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2184 static const char unsecure_envvars[] =
2185 #ifdef EXTRA_UNSECURE_ENVVARS
2186 EXTRA_UNSECURE_ENVVARS
2187 #endif
2188 UNSECURE_ENVVARS;
2189 const char *nextp;
2191 nextp = unsecure_envvars;
2194 unsetenv (nextp);
2195 /* We could use rawmemchr but this need not be fast. */
2196 nextp = (char *) (strchr) (nextp, '\0') + 1;
2198 while (*nextp != '\0');
2200 if (__access ("/etc/suid-debug", F_OK) != 0)
2201 unsetenv ("MALLOC_CHECK_");
2203 /* If we have to run the dynamic linker in debugging mode and the
2204 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2205 messages to this file. */
2206 else if (any_debug && debug_output != NULL)
2208 #ifdef O_NOFOLLOW
2209 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2210 #else
2211 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2212 #endif
2213 size_t name_len = strlen (debug_output);
2214 char buf[name_len + 12];
2215 char *startp;
2217 buf[name_len + 11] = '\0';
2218 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2219 *--startp = '.';
2220 startp = memcpy (startp - name_len, debug_output, name_len);
2222 GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2223 if (GLRO(dl_debug_fd) == -1)
2224 /* We use standard output if opening the file failed. */
2225 GLRO(dl_debug_fd) = STDOUT_FILENO;
2230 /* Print the various times we collected. */
2231 static void
2232 __attribute ((noinline))
2233 print_statistics (hp_timing_t *rtld_total_timep)
2235 #ifndef HP_TIMING_NONAVAIL
2236 char buf[200];
2237 char *cp;
2238 char *wp;
2240 /* Total time rtld used. */
2241 if (HP_TIMING_AVAIL)
2243 HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2244 _dl_debug_printf ("\nruntime linker statistics:\n"
2245 " total startup time in dynamic loader: %s\n", buf);
2247 /* Print relocation statistics. */
2248 char pbuf[30];
2249 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2250 cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2251 pbuf + sizeof (pbuf), 10, 0);
2252 wp = pbuf;
2253 switch (pbuf + sizeof (pbuf) - cp)
2255 case 3:
2256 *wp++ = *cp++;
2257 case 2:
2258 *wp++ = *cp++;
2259 case 1:
2260 *wp++ = '.';
2261 *wp++ = *cp++;
2263 *wp = '\0';
2264 _dl_debug_printf ("\
2265 time needed for relocation: %s (%s%%)\n", buf, pbuf);
2267 #endif
2269 unsigned long int num_relative_relocations = 0;
2270 struct r_scope_elem *scope = &GL(dl_loaded)->l_searchlist;
2271 unsigned int i;
2273 for (i = 0; i < scope->r_nlist; i++)
2275 struct link_map *l = scope->r_list [i];
2277 if (!l->l_addr)
2278 continue;
2280 if (l->l_info[VERSYMIDX (DT_RELCOUNT)])
2281 num_relative_relocations += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2282 if (l->l_info[VERSYMIDX (DT_RELACOUNT)])
2283 num_relative_relocations += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2286 _dl_debug_printf (" number of relocations: %lu\n"
2287 " number of relocations from cache: %lu\n"
2288 " number of relative relocations: %lu\n",
2289 GL(dl_num_relocations),
2290 GL(dl_num_cache_relocations),
2291 num_relative_relocations);
2293 #ifndef HP_TIMING_NONAVAIL
2294 /* Time spend while loading the object and the dependencies. */
2295 if (HP_TIMING_AVAIL)
2297 char pbuf[30];
2298 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2299 cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2300 pbuf + sizeof (pbuf), 10, 0);
2301 wp = pbuf;
2302 switch (pbuf + sizeof (pbuf) - cp)
2304 case 3:
2305 *wp++ = *cp++;
2306 case 2:
2307 *wp++ = *cp++;
2308 case 1:
2309 *wp++ = '.';
2310 *wp++ = *cp++;
2312 *wp = '\0';
2313 _dl_debug_printf ("\
2314 time needed to load objects: %s (%s%%)\n",
2315 buf, pbuf);
2317 #endif