* sysdeps/alpha/bits/atomic.h (__arch_compare_and_exchange_xxx_8_int): ...
[glibc.git] / elf / rtld.c
blob4273a6fb0712bfcdd0ec19a884b0f8f524b24e9c
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 <fcntl.h>
22 #include <stdbool.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <sys/mman.h> /* Check if MAP_ANON is defined. */
27 #include <sys/param.h>
28 #include <sys/stat.h>
29 #include <ldsodefs.h>
30 #include <stdio-common/_itoa.h>
31 #include <entry.h>
32 #include <fpu_control.h>
33 #include <hp-timing.h>
34 #include <bits/libc-lock.h>
35 #include "dynamic-link.h"
36 #include "dl-librecon.h"
37 #include <unsecvars.h>
38 #include <dl-cache.h>
39 #include <dl-procinfo.h>
40 #include <tls.h>
42 #include <assert.h>
44 /* Avoid PLT use for our local calls at startup. */
45 extern __typeof (__mempcpy) __mempcpy attribute_hidden;
47 /* GCC has mental blocks about _exit. */
48 extern __typeof (_exit) exit_internal asm ("_exit") attribute_hidden;
49 #define _exit exit_internal
51 /* Helper function to handle errors while resolving symbols. */
52 static void print_unresolved (int errcode, const char *objname,
53 const char *errsting);
55 /* Helper function to handle errors when a version is missing. */
56 static void print_missing_version (int errcode, const char *objname,
57 const char *errsting);
59 /* Print the various times we collected. */
60 static void print_statistics (void);
62 /* This is a list of all the modes the dynamic loader can be in. */
63 enum mode { normal, list, verify, trace };
65 /* Process all environments variables the dynamic linker must recognize.
66 Since all of them start with `LD_' we are a bit smarter while finding
67 all the entries. */
68 static void process_envvars (enum mode *modep);
70 int _dl_argc attribute_hidden;
71 char **_dl_argv = NULL;
72 INTDEF(_dl_argv)
74 /* Nonzero if we were run directly. */
75 unsigned int _dl_skip_args attribute_hidden;
77 /* Set nonzero during loading and initialization of executable and
78 libraries, cleared before the executable's entry point runs. This
79 must not be initialized to nonzero, because the unused dynamic
80 linker loaded in for libc.so's "ld.so.1" dep will provide the
81 definition seen by libc.so's initializer; that value must be zero,
82 and will be since that dynamic linker's _dl_start and dl_main will
83 never be called. */
84 int _dl_starting_up = 0;
85 INTVARDEF(_dl_starting_up)
87 /* This is the structure which defines all variables global to ld.so
88 (except those which cannot be added for some reason). */
89 struct rtld_global _rtld_global =
91 /* Get architecture specific initializer. */
92 #include <dl-procinfo.c>
93 ._dl_debug_fd = STDERR_FILENO,
94 #ifdef NEED_DL_SYSINFO
95 ._dl_sysinfo = DL_SYSINFO_DEFAULT,
96 #endif
97 ._dl_lazy = 1,
98 ._dl_use_load_bias = -2,
99 ._dl_fpu_control = _FPU_DEFAULT,
100 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
101 ._dl_hwcap_mask = HWCAP_IMPORTANT,
102 /* Default presumption without further information is executable stack. */
103 ._dl_stack_flags = PF_R|PF_W|PF_X,
104 #ifdef _LIBC_REENTRANT
105 ._dl_load_lock = _RTLD_LOCK_RECURSIVE_INITIALIZER
106 #endif
108 /* If we would use strong_alias here the compiler would see a
109 non-hidden definition. This would undo the effect of the previous
110 declaration. So spell out was strong_alias does plus add the
111 visibility attribute. */
112 extern struct rtld_global _rtld_local
113 __attribute__ ((alias ("_rtld_global"), visibility ("hidden")));
115 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
116 ElfW(Addr) *user_entry);
118 static struct libname_list _dl_rtld_libname;
119 static struct libname_list _dl_rtld_libname2;
121 /* We expect less than a second for relocation. */
122 #ifdef HP_SMALL_TIMING_AVAIL
123 # undef HP_TIMING_AVAIL
124 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
125 #endif
127 /* Variable for statistics. */
128 #ifndef HP_TIMING_NONAVAIL
129 static hp_timing_t rtld_total_time;
130 static hp_timing_t relocate_time;
131 static hp_timing_t load_time;
132 static hp_timing_t start_time;
133 #endif
135 /* Additional definitions needed by TLS initialization. */
136 #ifdef TLS_INIT_HELPER
137 TLS_INIT_HELPER
138 #endif
140 /* Helper function for syscall implementation. */
141 #ifdef DL_SYSINFO_IMPLEMENTATION
142 DL_SYSINFO_IMPLEMENTATION
143 #endif
145 /* Before ld.so is relocated we must not access variables which need
146 relocations. This means variables which are exported. Variables
147 declared as static are fine. If we can mark a variable hidden this
148 is fine, too. The latter is important here. We can avoid setting
149 up a temporary link map for ld.so if we can mark _rtld_global as
150 hidden. */
151 #if defined PI_STATIC_AND_HIDDEN && defined HAVE_HIDDEN \
152 && defined HAVE_VISIBILITY_ATTRIBUTE
153 # define DONT_USE_BOOTSTRAP_MAP 1
154 #endif
156 #ifdef DONT_USE_BOOTSTRAP_MAP
157 static ElfW(Addr) _dl_start_final (void *arg);
158 #else
159 struct dl_start_final_info
161 struct link_map l;
162 #if !defined HP_TIMING_NONAVAIL && HP_TIMING_INLINE
163 hp_timing_t start_time;
164 #endif
166 static ElfW(Addr) _dl_start_final (void *arg,
167 struct dl_start_final_info *info);
168 #endif
170 /* These defined magically in the linker script. */
171 extern char _begin[] attribute_hidden;
172 extern char _end[] attribute_hidden;
175 #ifdef RTLD_START
176 RTLD_START
177 #else
178 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
179 #endif
181 #ifndef VALIDX
182 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
183 + DT_EXTRANUM + DT_VALTAGIDX (tag))
184 #endif
185 #ifndef ADDRIDX
186 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
187 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
188 #endif
190 /* This is the second half of _dl_start (below). It can be inlined safely
191 under DONT_USE_BOOTSTRAP_MAP, where it is careful not to make any GOT
192 references. When the tools don't permit us to avoid using a GOT entry
193 for _dl_rtld_global (no attribute_hidden support), we must make sure
194 this function is not inlined (see below). */
196 #ifdef DONT_USE_BOOTSTRAP_MAP
197 static inline ElfW(Addr) __attribute__ ((always_inline))
198 _dl_start_final (void *arg)
199 #else
200 static ElfW(Addr) __attribute__ ((noinline))
201 _dl_start_final (void *arg, struct dl_start_final_info *info)
202 #endif
204 ElfW(Addr) start_addr;
206 if (HP_TIMING_AVAIL)
208 /* If it hasn't happen yet record the startup time. */
209 if (! HP_TIMING_INLINE)
210 HP_TIMING_NOW (start_time);
211 #if !defined DONT_USE_BOOTSTRAP_MAP && !defined HP_TIMING_NONAVAIL
212 else
213 start_time = info->start_time;
214 #endif
216 /* Initialize the timing functions. */
217 HP_TIMING_DIFF_INIT ();
220 /* Transfer data about ourselves to the permanent link_map structure. */
221 #ifndef DONT_USE_BOOTSTRAP_MAP
222 GL(dl_rtld_map).l_addr = info->l.l_addr;
223 GL(dl_rtld_map).l_ld = info->l.l_ld;
224 memcpy (GL(dl_rtld_map).l_info, info->l.l_info,
225 sizeof GL(dl_rtld_map).l_info);
226 GL(dl_rtld_map).l_mach = info->l.l_mach;
227 #endif
228 _dl_setup_hash (&GL(dl_rtld_map));
229 GL(dl_rtld_map).l_opencount = 1;
230 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
231 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
232 /* Copy the TLS related data if necessary. */
233 #if USE_TLS && !defined DONT_USE_BOOTSTRAP_MAP
234 # if USE___THREAD
235 assert (info->l.l_tls_modid != 0);
236 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
237 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
238 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
239 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
240 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
241 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
242 GL(dl_rtld_map).l_tls_modid = 1;
243 # else
244 assert (info->l.l_tls_modid == 0);
245 # if NO_TLS_OFFSET != 0
246 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
247 # endif
248 # endif
250 #endif
252 #if HP_TIMING_AVAIL
253 HP_TIMING_NOW (GL(dl_cpuclock_offset));
254 #endif
256 /* Call the OS-dependent function to set up life so we can do things like
257 file access. It will call `dl_main' (below) to do all the real work
258 of the dynamic linker, and then unwind our frame and run the user
259 entry point on the same stack we entered on. */
260 start_addr = _dl_sysdep_start (arg, &dl_main);
262 #ifndef HP_TIMING_NONAVAIL
263 if (HP_TIMING_AVAIL)
265 hp_timing_t end_time;
267 /* Get the current time. */
268 HP_TIMING_NOW (end_time);
270 /* Compute the difference. */
271 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
273 #endif
275 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
276 print_statistics ();
278 return start_addr;
281 static ElfW(Addr) __attribute_used__ internal_function
282 _dl_start (void *arg)
284 #ifdef DONT_USE_BOOTSTRAP_MAP
285 # define bootstrap_map GL(dl_rtld_map)
286 #else
287 struct dl_start_final_info info;
288 # define bootstrap_map info.l
289 #endif
291 /* This #define produces dynamic linking inline functions for
292 bootstrap relocation instead of general-purpose relocation. */
293 #define RTLD_BOOTSTRAP
294 #define RESOLVE_MAP(sym, version, flags) \
295 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : &bootstrap_map)
296 #define RESOLVE(sym, version, flags) \
297 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : bootstrap_map.l_addr)
298 #include "dynamic-link.h"
300 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
301 #ifdef DONT_USE_BOOTSTRAP_MAP
302 HP_TIMING_NOW (start_time);
303 #else
304 HP_TIMING_NOW (info.start_time);
305 #endif
307 /* Partly clean the `bootstrap_map' structure up. Don't use
308 `memset' since it might not be built in or inlined and we cannot
309 make function calls at this point. Use '__builtin_memset' if we
310 know it is available. We do not have to clear the memory if we
311 do not have to use the temporary bootstrap_map. Global variables
312 are initialized to zero by default. */
313 #ifndef DONT_USE_BOOTSTRAP_MAP
314 # ifdef HAVE_BUILTIN_MEMSET
315 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
316 # else
317 for (size_t cnt = 0;
318 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
319 ++cnt)
320 bootstrap_map.l_info[cnt] = 0;
321 # endif
322 #endif
324 /* Figure out the run-time load address of the dynamic linker itself. */
325 bootstrap_map.l_addr = elf_machine_load_address ();
327 /* Read our own dynamic section and fill in the info array. */
328 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
329 elf_get_dynamic_info (&bootstrap_map, NULL);
331 #if defined USE_TLS && NO_TLS_OFFSET != 0
332 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
333 #endif
335 /* Get the dynamic linker's own program header. First we need the ELF
336 file header. The `_begin' symbol created by the linker script points
337 to it. When we have something like GOTOFF relocs, we can use a plain
338 reference to find the runtime address. Without that, we have to rely
339 on the `l_addr' value, which is not the value we want when prelinked. */
340 #if USE___THREAD
341 dtv_t initdtv[3];
342 #endif /* USE___THREAD */
343 ElfW(Ehdr) *ehdr
344 # ifdef DONT_USE_BOOTSTRAP_MAP
345 = (ElfW(Ehdr) *) &_begin;
346 # else
347 = (ElfW(Ehdr) *) bootstrap_map.l_addr;
348 # endif
349 ElfW(Phdr) *phdr = (ElfW(Phdr) *) ((void *) ehdr + ehdr->e_phoff);
350 size_t cnt = ehdr->e_phnum; /* PT_TLS is usually the last phdr. */
351 while (cnt-- > 0)
352 #if USE___THREAD
353 if (phdr[cnt].p_type == PT_TLS)
355 void *tlsblock;
356 size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
357 char *p;
359 bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
360 bootstrap_map.l_tls_align = phdr[cnt].p_align;
361 if (phdr[cnt].p_align == 0)
362 bootstrap_map.l_tls_firstbyte_offset = 0;
363 else
364 bootstrap_map.l_tls_firstbyte_offset = (phdr[cnt].p_vaddr
365 & (phdr[cnt].p_align - 1));
366 assert (bootstrap_map.l_tls_blocksize != 0);
367 bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
368 bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
369 + phdr[cnt].p_vaddr);
371 /* We can now allocate the initial TLS block. This can happen
372 on the stack. We'll get the final memory later when we
373 know all about the various objects loaded at startup
374 time. */
375 # if TLS_TCB_AT_TP
376 tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
377 TLS_INIT_TCB_ALIGN)
378 + TLS_INIT_TCB_SIZE
379 + max_align);
380 # elif TLS_DTV_AT_TP
381 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
382 bootstrap_map.l_tls_align)
383 + bootstrap_map.l_tls_blocksize
384 + max_align);
385 # else
386 /* In case a model with a different layout for the TCB and DTV
387 is defined add another #elif here and in the following #ifs. */
388 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
389 # endif
390 /* Align the TLS block. */
391 tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
392 & ~(max_align - 1));
394 /* Initialize the dtv. [0] is the length, [1] the generation
395 counter. */
396 initdtv[0].counter = 1;
397 initdtv[1].counter = 0;
399 /* Initialize the TLS block. */
400 # if TLS_TCB_AT_TP
401 initdtv[2].pointer = tlsblock;
402 # elif TLS_DTV_AT_TP
403 bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
404 bootstrap_map.l_tls_align);
405 initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
406 # else
407 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
408 # endif
409 p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
410 bootstrap_map.l_tls_initimage_size);
411 # ifdef HAVE_BUILTIN_MEMSET
412 __builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
413 - bootstrap_map.l_tls_initimage_size));
414 # else
416 size_t remaining = (bootstrap_map.l_tls_blocksize
417 - bootstrap_map.l_tls_initimage_size);
418 while (remaining-- > 0)
419 *p++ = '\0';
421 #endif
423 /* Install the pointer to the dtv. */
425 /* Initialize the thread pointer. */
426 # if TLS_TCB_AT_TP
427 bootstrap_map.l_tls_offset
428 = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
430 INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
431 initdtv);
433 const char *lossage = TLS_INIT_TP ((char *) tlsblock
434 + bootstrap_map.l_tls_offset, 0);
435 # elif TLS_DTV_AT_TP
436 INSTALL_DTV (tlsblock, initdtv);
437 const char *lossage = TLS_INIT_TP (tlsblock, 0);
438 # else
439 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
440 # endif
441 if (__builtin_expect (lossage != NULL, 0))
442 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
443 lossage);
445 /* So far this is module number one. */
446 bootstrap_map.l_tls_modid = 1;
448 else
449 #endif /* USE___THREAD */
450 if (phdr[cnt].p_type == PT_GNU_RELRO)
452 bootstrap_map.l_relro_addr = phdr[cnt].p_vaddr;
453 bootstrap_map.l_relro_size = phdr[cnt].p_memsz;
456 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
457 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
458 #endif
460 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
462 /* Relocate ourselves so we can do normal function calls and
463 data access using the global offset table. */
465 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
468 /* Please note that we don't allow profiling of this object and
469 therefore need not test whether we have to allocate the array
470 for the relocation results (as done in dl-reloc.c). */
472 /* Now life is sane; we can call functions and access global data.
473 Set up to use the operating system facilities, and find out from
474 the operating system's program loader where to find the program
475 header table in core. Put the rest of _dl_start into a separate
476 function, that way the compiler cannot put accesses to the GOT
477 before ELF_DYNAMIC_RELOCATE. */
479 #ifdef DONT_USE_BOOTSTRAP_MAP
480 ElfW(Addr) entry = _dl_start_final (arg);
481 #else
482 ElfW(Addr) entry = _dl_start_final (arg, &info);
483 #endif
485 #ifndef ELF_MACHINE_START_ADDRESS
486 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
487 #endif
489 return ELF_MACHINE_START_ADDRESS (GL(dl_loaded), entry);
495 /* Now life is peachy; we can do all normal operations.
496 On to the real work. */
498 /* Some helper functions. */
500 /* Arguments to relocate_doit. */
501 struct relocate_args
503 struct link_map *l;
504 int lazy;
507 struct map_args
509 /* Argument to map_doit. */
510 char *str;
511 /* Return value of map_doit. */
512 struct link_map *main_map;
515 /* Arguments to version_check_doit. */
516 struct version_check_args
518 int doexit;
519 int dotrace;
522 static void
523 relocate_doit (void *a)
525 struct relocate_args *args = (struct relocate_args *) a;
527 INTUSE(_dl_relocate_object) (args->l, args->l->l_scope, args->lazy, 0);
530 static void
531 map_doit (void *a)
533 struct map_args *args = (struct map_args *) a;
534 args->main_map = INTUSE(_dl_map_object) (NULL, args->str, 0, lt_library, 0,
535 __RTLD_OPENEXEC);
538 static void
539 version_check_doit (void *a)
541 struct version_check_args *args = (struct version_check_args *) a;
542 if (_dl_check_all_versions (GL(dl_loaded), 1, args->dotrace) && args->doexit)
543 /* We cannot start the application. Abort now. */
544 _exit (1);
548 static inline struct link_map *
549 find_needed (const char *name)
551 unsigned int n = GL(dl_loaded)->l_searchlist.r_nlist;
553 while (n-- > 0)
554 if (_dl_name_match_p (name, GL(dl_loaded)->l_searchlist.r_list[n]))
555 return GL(dl_loaded)->l_searchlist.r_list[n];
557 /* Should never happen. */
558 return NULL;
561 static int
562 match_version (const char *string, struct link_map *map)
564 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
565 ElfW(Verdef) *def;
567 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
568 if (map->l_info[VERDEFTAG] == NULL)
569 /* The file has no symbol versioning. */
570 return 0;
572 def = (ElfW(Verdef) *) ((char *) map->l_addr
573 + map->l_info[VERDEFTAG]->d_un.d_ptr);
574 while (1)
576 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
578 /* Compare the version strings. */
579 if (strcmp (string, strtab + aux->vda_name) == 0)
580 /* Bingo! */
581 return 1;
583 /* If no more definitions we failed to find what we want. */
584 if (def->vd_next == 0)
585 break;
587 /* Next definition. */
588 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
591 return 0;
594 #ifdef _LIBC_REENTRANT
595 /* _dl_error_catch_tsd points to this for the single-threaded case.
596 It's reset by the thread library for multithreaded programs. */
597 void ** __attribute__ ((const))
598 _dl_initial_error_catch_tsd (void)
600 static void *data;
601 return &data;
603 #endif
605 #if defined SHARED && defined _LIBC_REENTRANT \
606 && defined __rtld_lock_default_lock_recursive
607 static void rtld_lock_default_lock_recursive (void *lock)
609 __rtld_lock_default_lock_recursive (lock);
612 static void rtld_lock_default_unlock_recursive (void *lock)
614 __rtld_lock_default_unlock_recursive (lock);
616 #endif
619 static const char *library_path; /* The library search path. */
620 static const char *preloadlist; /* The list preloaded objects. */
621 static int version_info; /* Nonzero if information about
622 versions has to be printed. */
624 static void
625 dl_main (const ElfW(Phdr) *phdr,
626 ElfW(Word) phnum,
627 ElfW(Addr) *user_entry)
629 const ElfW(Phdr) *ph;
630 enum mode mode;
631 struct link_map **preloads;
632 unsigned int npreloads;
633 size_t file_size;
634 char *file;
635 bool has_interp = false;
636 unsigned int i;
637 bool prelinked = false;
638 bool rtld_is_main = false;
639 #ifndef HP_TIMING_NONAVAIL
640 hp_timing_t start;
641 hp_timing_t stop;
642 hp_timing_t diff;
643 #endif
644 #ifdef USE_TLS
645 void *tcbp;
646 #endif
648 #ifdef _LIBC_REENTRANT
649 /* Explicit initialization since the reloc would just be more work. */
650 GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
651 #endif
653 #ifdef USE_TLS
654 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
655 #endif
657 #if defined SHARED && defined _LIBC_REENTRANT \
658 && defined __rtld_lock_default_lock_recursive
659 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
660 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
661 #endif
663 /* The explicit initialization here is cheaper than processing the reloc
664 in the _rtld_local definition's initializer. */
665 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
667 /* Process the environment variable which control the behaviour. */
668 process_envvars (&mode);
670 /* Set up a flag which tells we are just starting. */
671 INTUSE(_dl_starting_up) = 1;
673 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
675 /* Ho ho. We are not the program interpreter! We are the program
676 itself! This means someone ran ld.so as a command. Well, that
677 might be convenient to do sometimes. We support it by
678 interpreting the args like this:
680 ld.so PROGRAM ARGS...
682 The first argument is the name of a file containing an ELF
683 executable we will load and run with the following arguments.
684 To simplify life here, PROGRAM is searched for using the
685 normal rules for shared objects, rather than $PATH or anything
686 like that. We just load it and use its entry point; we don't
687 pay attention to its PT_INTERP command (we are the interpreter
688 ourselves). This is an easy way to test a new ld.so before
689 installing it. */
690 rtld_is_main = true;
692 /* Note the place where the dynamic linker actually came from. */
693 GL(dl_rtld_map).l_name = rtld_progname;
695 while (_dl_argc > 1)
696 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
698 mode = list;
699 GL(dl_lazy) = -1; /* This means do no dependency analysis. */
701 ++_dl_skip_args;
702 --_dl_argc;
703 ++INTUSE(_dl_argv);
705 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
707 mode = verify;
709 ++_dl_skip_args;
710 --_dl_argc;
711 ++INTUSE(_dl_argv);
713 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
714 && _dl_argc > 2)
716 library_path = INTUSE(_dl_argv)[2];
718 _dl_skip_args += 2;
719 _dl_argc -= 2;
720 INTUSE(_dl_argv) += 2;
722 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
723 && _dl_argc > 2)
725 GL(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
727 _dl_skip_args += 2;
728 _dl_argc -= 2;
729 INTUSE(_dl_argv) += 2;
731 else
732 break;
734 /* If we have no further argument the program was called incorrectly.
735 Grant the user some education. */
736 if (_dl_argc < 2)
737 _dl_fatal_printf ("\
738 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
739 You have invoked `ld.so', the helper program for shared library executables.\n\
740 This program usually lives in the file `/lib/ld.so', and special directives\n\
741 in executable files using ELF shared libraries tell the system's program\n\
742 loader to load the helper program from this file. This helper program loads\n\
743 the shared libraries needed by the program executable, prepares the program\n\
744 to run, and runs it. You may invoke this helper program directly from the\n\
745 command line to load and run an ELF executable file; this is like executing\n\
746 that file itself, but always uses this helper program from the file you\n\
747 specified, instead of the helper program file specified in the executable\n\
748 file you run. This is mostly of use for maintainers to test new versions\n\
749 of this helper program; chances are you did not intend to run this program.\n\
751 --list list all dependencies and how they are resolved\n\
752 --verify verify that given object really is a dynamically linked\n\
753 object we can handle\n\
754 --library-path PATH use given PATH instead of content of the environment\n\
755 variable LD_LIBRARY_PATH\n\
756 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
757 in LIST\n");
759 ++_dl_skip_args;
760 --_dl_argc;
761 ++INTUSE(_dl_argv);
763 /* Initialize the data structures for the search paths for shared
764 objects. */
765 _dl_init_paths (library_path);
767 /* The initialization of _dl_stack_flags done below assumes the
768 executable's PT_GNU_STACK may have been honored by the kernel, and
769 so a PT_GNU_STACK with PF_X set means the stack started out with
770 execute permission. However, this is not really true if the
771 dynamic linker is the executable the kernel loaded. For this
772 case, we must reinitialize _dl_stack_flags to match the dynamic
773 linker itself. If the dynamic linker was built with a
774 PT_GNU_STACK, then the kernel may have loaded us with a
775 nonexecutable stack that we will have to make executable when we
776 load the program below unless it has a PT_GNU_STACK indicating
777 nonexecutable stack is ok. */
779 for (ph = phdr; ph < &phdr[phnum]; ++ph)
780 if (ph->p_type == PT_GNU_STACK)
782 GL(dl_stack_flags) = ph->p_flags;
783 break;
785 else if (ph->p_type == PT_GNU_RELRO)
787 GL(dl_loaded)->l_relro_addr = ph->p_vaddr;
788 GL(dl_loaded)->l_relro_size = ph->p_memsz;
791 if (__builtin_expect (mode, normal) == verify)
793 const char *objname;
794 const char *err_str = NULL;
795 struct map_args args;
797 args.str = rtld_progname;
798 (void) INTUSE(_dl_catch_error) (&objname, &err_str, map_doit, &args);
799 if (__builtin_expect (err_str != NULL, 0))
800 /* We don't free the returned string, the programs stops
801 anyway. */
802 _exit (EXIT_FAILURE);
804 else
806 HP_TIMING_NOW (start);
807 INTUSE(_dl_map_object) (NULL, rtld_progname, 0, lt_library, 0,
808 __RTLD_OPENEXEC);
809 HP_TIMING_NOW (stop);
811 HP_TIMING_DIFF (load_time, start, stop);
814 phdr = GL(dl_loaded)->l_phdr;
815 phnum = GL(dl_loaded)->l_phnum;
816 /* We overwrite here a pointer to a malloc()ed string. But since
817 the malloc() implementation used at this point is the dummy
818 implementations which has no real free() function it does not
819 makes sense to free the old string first. */
820 GL(dl_loaded)->l_name = (char *) "";
821 *user_entry = GL(dl_loaded)->l_entry;
823 else
825 /* Create a link_map for the executable itself.
826 This will be what dlopen on "" returns. */
827 _dl_new_object ((char *) "", "", lt_executable, NULL);
828 if (GL(dl_loaded) == NULL)
829 _dl_fatal_printf ("cannot allocate memory for link map\n");
830 GL(dl_loaded)->l_phdr = phdr;
831 GL(dl_loaded)->l_phnum = phnum;
832 GL(dl_loaded)->l_entry = *user_entry;
834 /* At this point we are in a bit of trouble. We would have to
835 fill in the values for l_dev and l_ino. But in general we
836 do not know where the file is. We also do not handle AT_EXECFD
837 even if it would be passed up.
839 We leave the values here defined to 0. This is normally no
840 problem as the program code itself is normally no shared
841 object and therefore cannot be loaded dynamically. Nothing
842 prevent the use of dynamic binaries and in these situations
843 we might get problems. We might not be able to find out
844 whether the object is already loaded. But since there is no
845 easy way out and because the dynamic binary must also not
846 have an SONAME we ignore this program for now. If it becomes
847 a problem we can force people using SONAMEs. */
849 /* We delay initializing the path structure until we got the dynamic
850 information for the program. */
853 GL(dl_loaded)->l_map_end = 0;
854 /* Perhaps the executable has no PT_LOAD header entries at all. */
855 GL(dl_loaded)->l_map_start = ~0;
856 /* We opened the file, account for it. */
857 ++GL(dl_loaded)->l_opencount;
859 /* Scan the program header table for the dynamic section. */
860 for (ph = phdr; ph < &phdr[phnum]; ++ph)
861 switch (ph->p_type)
863 case PT_PHDR:
864 /* Find out the load address. */
865 GL(dl_loaded)->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
866 break;
867 case PT_DYNAMIC:
868 /* This tells us where to find the dynamic section,
869 which tells us everything we need to do. */
870 GL(dl_loaded)->l_ld = (void *) GL(dl_loaded)->l_addr + ph->p_vaddr;
871 break;
872 case PT_INTERP:
873 /* This "interpreter segment" was used by the program loader to
874 find the program interpreter, which is this program itself, the
875 dynamic linker. We note what name finds us, so that a future
876 dlopen call or DT_NEEDED entry, for something that wants to link
877 against the dynamic linker as a shared library, will know that
878 the shared object is already loaded. */
879 _dl_rtld_libname.name = ((const char *) GL(dl_loaded)->l_addr
880 + ph->p_vaddr);
881 /* _dl_rtld_libname.next = NULL; Already zero. */
882 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
884 /* Ordinarilly, we would get additional names for the loader from
885 our DT_SONAME. This can't happen if we were actually linked as
886 a static executable (detect this case when we have no DYNAMIC).
887 If so, assume the filename component of the interpreter path to
888 be our SONAME, and add it to our name list. */
889 if (GL(dl_rtld_map).l_ld == NULL)
891 const char *p = NULL;
892 const char *cp = _dl_rtld_libname.name;
894 /* Find the filename part of the path. */
895 while (*cp != '\0')
896 if (*cp++ == '/')
897 p = cp;
899 if (p != NULL)
901 _dl_rtld_libname2.name = p;
902 /* _dl_rtld_libname2.next = NULL; Already zero. */
903 _dl_rtld_libname.next = &_dl_rtld_libname2;
907 has_interp = true;
908 break;
909 case PT_LOAD:
911 ElfW(Addr) mapstart;
912 ElfW(Addr) allocend;
914 /* Remember where the main program starts in memory. */
915 mapstart = (GL(dl_loaded)->l_addr
916 + (ph->p_vaddr & ~(ph->p_align - 1)));
917 if (GL(dl_loaded)->l_map_start > mapstart)
918 GL(dl_loaded)->l_map_start = mapstart;
920 /* Also where it ends. */
921 allocend = GL(dl_loaded)->l_addr + ph->p_vaddr + ph->p_memsz;
922 if (GL(dl_loaded)->l_map_end < allocend)
923 GL(dl_loaded)->l_map_end = allocend;
925 break;
926 #ifdef USE_TLS
927 case PT_TLS:
928 if (ph->p_memsz > 0)
930 /* Note that in the case the dynamic linker we duplicate work
931 here since we read the PT_TLS entry already in
932 _dl_start_final. But the result is repeatable so do not
933 check for this special but unimportant case. */
934 GL(dl_loaded)->l_tls_blocksize = ph->p_memsz;
935 GL(dl_loaded)->l_tls_align = ph->p_align;
936 if (ph->p_align == 0)
937 GL(dl_loaded)->l_tls_firstbyte_offset = 0;
938 else
939 GL(dl_loaded)->l_tls_firstbyte_offset = (ph->p_vaddr
940 & (ph->p_align - 1));
941 GL(dl_loaded)->l_tls_initimage_size = ph->p_filesz;
942 GL(dl_loaded)->l_tls_initimage = (void *) ph->p_vaddr;
944 /* This image gets the ID one. */
945 GL(dl_tls_max_dtv_idx) = GL(dl_loaded)->l_tls_modid = 1;
947 break;
948 #endif
949 case PT_GNU_STACK:
950 GL(dl_stack_flags) = ph->p_flags;
951 break;
953 #ifdef USE_TLS
954 /* Adjust the address of the TLS initialization image in case
955 the executable is actually an ET_DYN object. */
956 if (GL(dl_loaded)->l_tls_initimage != NULL)
957 GL(dl_loaded)->l_tls_initimage
958 = (char *) GL(dl_loaded)->l_tls_initimage + GL(dl_loaded)->l_addr;
959 #endif
960 if (! GL(dl_loaded)->l_map_end)
961 GL(dl_loaded)->l_map_end = ~0;
962 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
964 /* We were invoked directly, so the program might not have a
965 PT_INTERP. */
966 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
967 /* _dl_rtld_libname.next = NULL; Already zero. */
968 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
970 else
971 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
973 if (! rtld_is_main)
975 /* Extract the contents of the dynamic section for easy access. */
976 elf_get_dynamic_info (GL(dl_loaded), NULL);
977 if (GL(dl_loaded)->l_info[DT_HASH])
978 /* Set up our cache of pointers into the hash table. */
979 _dl_setup_hash (GL(dl_loaded));
982 if (__builtin_expect (mode, normal) == verify)
984 /* We were called just to verify that this is a dynamic
985 executable using us as the program interpreter. Exit with an
986 error if we were not able to load the binary or no interpreter
987 is specified (i.e., this is no dynamically linked binary. */
988 if (GL(dl_loaded)->l_ld == NULL)
989 _exit (1);
991 /* We allow here some platform specific code. */
992 #ifdef DISTINGUISH_LIB_VERSIONS
993 DISTINGUISH_LIB_VERSIONS;
994 #endif
995 _exit (has_interp ? 0 : 2);
998 if (! rtld_is_main)
999 /* Initialize the data structures for the search paths for shared
1000 objects. */
1001 _dl_init_paths (library_path);
1003 /* Put the link_map for ourselves on the chain so it can be found by
1004 name. Note that at this point the global chain of link maps contains
1005 exactly one element, which is pointed to by dl_loaded. */
1006 if (! GL(dl_rtld_map).l_name)
1007 /* If not invoked directly, the dynamic linker shared object file was
1008 found by the PT_INTERP name. */
1009 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1010 GL(dl_rtld_map).l_type = lt_library;
1011 GL(dl_loaded)->l_next = &GL(dl_rtld_map);
1012 GL(dl_rtld_map).l_prev = GL(dl_loaded);
1013 ++GL(dl_nloaded);
1015 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1016 to not using bias for non-prelinked PIEs and libraries
1017 and using it for executables or prelinked PIEs or libraries. */
1018 if (GL(dl_use_load_bias) == (ElfW(Addr)) -2)
1019 GL(dl_use_load_bias) = (GL(dl_loaded)->l_addr == 0) ? -1 : 0;
1021 /* Set up the program header information for the dynamic linker
1022 itself. It is needed in the dl_iterate_phdr() callbacks. */
1023 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1024 GL(dl_rtld_map).l_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1025 + rtld_ehdr->e_phoff);
1026 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1028 /* We have two ways to specify objects to preload: via environment
1029 variable and via the file /etc/ld.so.preload. The latter can also
1030 be used when security is enabled. */
1031 preloads = NULL;
1032 npreloads = 0;
1034 if (__builtin_expect (preloadlist != NULL, 0))
1036 /* The LD_PRELOAD environment variable gives list of libraries
1037 separated by white space or colons that are loaded before the
1038 executable's dependencies and prepended to the global scope
1039 list. If the binary is running setuid all elements
1040 containing a '/' are ignored since it is insecure. */
1041 char *list = strdupa (preloadlist);
1042 char *p;
1044 HP_TIMING_NOW (start);
1046 /* Prevent optimizing strsep. Speed is not important here. */
1047 while ((p = (strsep) (&list, " :")) != NULL)
1048 if (p[0] != '\0'
1049 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1050 || strchr (p, '/') == NULL))
1052 struct link_map *new_map = INTUSE(_dl_map_object) (GL(dl_loaded),
1053 p, 1,
1054 lt_library,
1055 0, 0);
1056 if (++new_map->l_opencount == 1)
1057 /* It is no duplicate. */
1058 ++npreloads;
1061 HP_TIMING_NOW (stop);
1062 HP_TIMING_DIFF (diff, start, stop);
1063 HP_TIMING_ACCUM_NT (load_time, diff);
1066 /* Read the contents of the file. */
1067 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
1068 PROT_READ | PROT_WRITE);
1069 if (__builtin_expect (file != MAP_FAILED, 0))
1071 /* Parse the file. It contains names of libraries to be loaded,
1072 separated by white spaces or `:'. It may also contain
1073 comments introduced by `#'. */
1074 char *problem;
1075 char *runp;
1076 size_t rest;
1078 /* Eliminate comments. */
1079 runp = file;
1080 rest = file_size;
1081 while (rest > 0)
1083 char *comment = memchr (runp, '#', rest);
1084 if (comment == NULL)
1085 break;
1087 rest -= comment - runp;
1089 *comment = ' ';
1090 while (--rest > 0 && *++comment != '\n');
1093 /* We have one problematic case: if we have a name at the end of
1094 the file without a trailing terminating characters, we cannot
1095 place the \0. Handle the case separately. */
1096 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1097 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1099 problem = &file[file_size];
1100 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
1101 && problem[-1] != '\n' && problem[-1] != ':')
1102 --problem;
1104 if (problem > file)
1105 problem[-1] = '\0';
1107 else
1109 problem = NULL;
1110 file[file_size - 1] = '\0';
1113 HP_TIMING_NOW (start);
1115 if (file != problem)
1117 char *p;
1118 runp = file;
1119 while ((p = strsep (&runp, ": \t\n")) != NULL)
1120 if (p[0] != '\0')
1122 struct link_map *new_map = INTUSE(_dl_map_object) (GL(dl_loaded),
1123 p, 1,
1124 lt_library,
1125 0, 0);
1126 if (++new_map->l_opencount == 1)
1127 /* It is no duplicate. */
1128 ++npreloads;
1132 if (problem != NULL)
1134 char *p = strndupa (problem, file_size - (problem - file));
1135 struct link_map *new_map = INTUSE(_dl_map_object) (GL(dl_loaded), p,
1136 1, lt_library,
1137 0, 0);
1138 if (++new_map->l_opencount == 1)
1139 /* It is no duplicate. */
1140 ++npreloads;
1143 HP_TIMING_NOW (stop);
1144 HP_TIMING_DIFF (diff, start, stop);
1145 HP_TIMING_ACCUM_NT (load_time, diff);
1147 /* We don't need the file anymore. */
1148 __munmap (file, file_size);
1151 if (__builtin_expect (npreloads, 0) != 0)
1153 /* Set up PRELOADS with a vector of the preloaded libraries. */
1154 struct link_map *l;
1155 preloads = __alloca (npreloads * sizeof preloads[0]);
1156 l = GL(dl_rtld_map).l_next; /* End of the chain before preloads. */
1157 i = 0;
1160 preloads[i++] = l;
1161 l = l->l_next;
1162 } while (l);
1163 assert (i == npreloads);
1166 #ifdef NEED_DL_SYSINFO
1167 if (GL(dl_sysinfo_dso) != NULL)
1169 /* We have a prelinked DSO preloaded by the system. */
1170 GL(dl_sysinfo) = GL(dl_sysinfo_dso)->e_entry;
1172 /* Do an abridged version of the work _dl_map_object_from_fd would do
1173 to map in the object. It's already mapped and prelinked (and
1174 better be, since it's read-only and so we couldn't relocate it).
1175 We just want our data structures to describe it as if we had just
1176 mapped and relocated it normally. */
1177 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL);
1178 if (__builtin_expect (l != NULL, 1))
1180 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT];
1181 #ifndef NDEBUG
1182 uint_fast16_t pt_load_num = 0;
1183 #endif
1185 l->l_phdr = ((const void *) GL(dl_sysinfo_dso)
1186 + GL(dl_sysinfo_dso)->e_phoff);
1187 l->l_phnum = GL(dl_sysinfo_dso)->e_phnum;
1188 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1190 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1191 if (ph->p_type == PT_DYNAMIC)
1193 l->l_ld = (void *) ph->p_vaddr;
1194 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1195 break;
1197 #ifndef NDEBUG
1198 if (ph->p_type == PT_LOAD)
1200 assert (pt_load_num
1201 || (void *) ph->p_vaddr == GL(dl_sysinfo_dso));
1202 pt_load_num++;
1204 #endif
1206 elf_get_dynamic_info (l, dyn_temp);
1207 _dl_setup_hash (l);
1208 l->l_relocated = 1;
1209 l->l_map_start = (ElfW(Addr)) GL(dl_sysinfo_dso);
1211 /* Now that we have the info handy, use the DSO image's soname
1212 so this object can be looked up by name. Note that we do not
1213 set l_name here. That field gives the file name of the DSO,
1214 and this DSO is not associated with any file. */
1215 if (l->l_info[DT_SONAME] != NULL)
1217 /* Work around a kernel problem. The kernel cannot handle
1218 addresses in the vsyscall DSO pages in writev() calls. */
1219 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1220 + l->l_info[DT_SONAME]->d_un.d_val);
1221 size_t len = strlen (dsoname);
1222 char *copy = malloc (len);
1223 if (copy == NULL)
1224 _dl_fatal_printf ("out of memory\n");
1225 l->l_libname->name = memcpy (copy, dsoname, len);
1229 #endif
1231 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1232 specified some libraries to load, these are inserted before the actual
1233 dependencies in the executable's searchlist for symbol resolution. */
1234 HP_TIMING_NOW (start);
1235 INTUSE(_dl_map_object_deps) (GL(dl_loaded), preloads, npreloads,
1236 mode == trace, 0);
1237 HP_TIMING_NOW (stop);
1238 HP_TIMING_DIFF (diff, start, stop);
1239 HP_TIMING_ACCUM_NT (load_time, diff);
1241 /* Mark all objects as being in the global scope and set the open
1242 counter. */
1243 for (i = GL(dl_loaded)->l_searchlist.r_nlist; i > 0; )
1245 --i;
1246 GL(dl_loaded)->l_searchlist.r_list[i]->l_global = 1;
1247 ++GL(dl_loaded)->l_searchlist.r_list[i]->l_opencount;
1250 #ifndef MAP_ANON
1251 /* We are done mapping things, so close the zero-fill descriptor. */
1252 __close (_dl_zerofd);
1253 _dl_zerofd = -1;
1254 #endif
1256 /* Remove _dl_rtld_map from the chain. */
1257 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1258 if (GL(dl_rtld_map).l_next)
1259 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1261 if (__builtin_expect (GL(dl_rtld_map).l_opencount > 1, 1))
1263 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1264 put it back in the list of visible objects. We insert it into the
1265 chain in symbol search order because gdb uses the chain's order as
1266 its symbol search order. */
1267 i = 1;
1268 while (GL(dl_loaded)->l_searchlist.r_list[i] != &GL(dl_rtld_map))
1269 ++i;
1270 GL(dl_rtld_map).l_prev = GL(dl_loaded)->l_searchlist.r_list[i - 1];
1271 if (__builtin_expect (mode, normal) == normal)
1272 GL(dl_rtld_map).l_next = (i + 1 < GL(dl_loaded)->l_searchlist.r_nlist
1273 ? GL(dl_loaded)->l_searchlist.r_list[i + 1]
1274 : NULL);
1275 else
1276 /* In trace mode there might be an invisible object (which we
1277 could not find) after the previous one in the search list.
1278 In this case it doesn't matter much where we put the
1279 interpreter object, so we just initialize the list pointer so
1280 that the assertion below holds. */
1281 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1283 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1284 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1285 if (GL(dl_rtld_map).l_next != NULL)
1287 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1288 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1292 /* Now let us see whether all libraries are available in the
1293 versions we need. */
1295 struct version_check_args args;
1296 args.doexit = mode == normal;
1297 args.dotrace = mode == trace;
1298 _dl_receive_error (print_missing_version, version_check_doit, &args);
1301 #ifdef USE_TLS
1302 /* Now it is time to determine the layout of the static TLS block
1303 and allocate it for the initial thread. Note that we always
1304 allocate the static block, we never defer it even if no
1305 DF_STATIC_TLS bit is set. The reason is that we know glibc will
1306 use the static model. First add the dynamic linker to the list
1307 if it also uses TLS. */
1308 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1309 /* Assign a module ID. */
1310 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1312 # ifndef TLS_INIT_TP_EXPENSIVE
1313 # define TLS_INIT_TP_EXPENSIVE 0
1314 # endif
1316 /* We do not initialize any of the TLS functionality unless any of the
1317 initial modules uses TLS. This makes dynamic loading of modules with
1318 TLS impossible, but to support it requires either eagerly doing setup
1319 now or lazily doing it later. Doing it now makes us incompatible with
1320 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1321 used. Trying to do it lazily is too hairy to try when there could be
1322 multiple threads (from a non-TLS-using libpthread). */
1323 if (!TLS_INIT_TP_EXPENSIVE || GL(dl_tls_max_dtv_idx) > 0)
1325 struct link_map *l;
1326 size_t nelem;
1327 struct dtv_slotinfo *slotinfo;
1329 /* Number of elements in the static TLS block. */
1330 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
1332 /* Allocate the array which contains the information about the
1333 dtv slots. We allocate a few entries more than needed to
1334 avoid the need for reallocation. */
1335 nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
1337 /* Allocate. */
1338 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
1339 malloc (sizeof (struct dtv_slotinfo_list)
1340 + nelem * sizeof (struct dtv_slotinfo));
1341 /* No need to check the return value. If memory allocation failed
1342 the program would have been terminated. */
1344 slotinfo = memset (GL(dl_tls_dtv_slotinfo_list)->slotinfo, '\0',
1345 nelem * sizeof (struct dtv_slotinfo));
1346 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
1347 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
1349 /* Fill in the information from the loaded modules. */
1350 for (l = GL(dl_loaded), i = 0; l != NULL; l = l->l_next)
1351 if (l->l_tls_blocksize != 0)
1352 /* This is a module with TLS data. Store the map reference.
1353 The generation counter is zero. */
1354 slotinfo[++i].map = l;
1355 assert (i == GL(dl_tls_max_dtv_idx));
1357 /* Compute the TLS offsets for the various blocks. */
1358 _dl_determine_tlsoffset ();
1360 /* Construct the static TLS block and the dtv for the initial
1361 thread. For some platforms this will include allocating memory
1362 for the thread descriptor. The memory for the TLS block will
1363 never be freed. It should be allocated accordingly. The dtv
1364 array can be changed if dynamic loading requires it. */
1365 tcbp = _dl_allocate_tls_storage ();
1366 if (tcbp == NULL)
1367 _dl_fatal_printf ("\
1368 cannot allocate TLS data structures for initial thread");
1370 /* Store for detection of the special case by __tls_get_addr
1371 so it knows not to pass this dtv to the normal realloc. */
1372 GL(dl_initial_dtv) = GET_DTV (tcbp);
1374 #endif
1376 if (__builtin_expect (mode, normal) != normal)
1378 /* We were run just to list the shared libraries. It is
1379 important that we do this before real relocation, because the
1380 functions we call below for output may no longer work properly
1381 after relocation. */
1382 struct link_map *l;
1384 if (GL(dl_debug_mask) & DL_DEBUG_PRELINK)
1386 struct r_scope_elem *scope = &GL(dl_loaded)->l_searchlist;
1388 for (i = 0; i < scope->r_nlist; i++)
1390 l = scope->r_list [i];
1391 if (l->l_faked)
1393 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1394 continue;
1396 if (_dl_name_match_p (GL(dl_trace_prelink), l))
1397 GL(dl_trace_prelink_map) = l;
1398 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1399 l->l_libname->name[0] ? l->l_libname->name
1400 : rtld_progname ?: "<main program>",
1401 l->l_name[0] ? l->l_name
1402 : rtld_progname ?: "<main program>",
1403 (int) sizeof l->l_map_start * 2,
1404 (size_t) l->l_map_start,
1405 (int) sizeof l->l_addr * 2,
1406 (size_t) l->l_addr);
1407 #ifdef USE_TLS
1408 if (l->l_tls_modid)
1409 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1410 (int) sizeof l->l_tls_offset * 2,
1411 (size_t) l->l_tls_offset);
1412 else
1413 #endif
1414 _dl_printf ("\n");
1417 else if (! GL(dl_loaded)->l_info[DT_NEEDED])
1418 _dl_printf ("\tstatically linked\n");
1419 else
1421 for (l = GL(dl_loaded)->l_next; l; l = l->l_next)
1422 if (l->l_faked)
1423 /* The library was not found. */
1424 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1425 else
1426 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1427 l->l_name, (int) sizeof l->l_map_start * 2,
1428 (size_t) l->l_map_start);
1431 if (__builtin_expect (mode, trace) != trace)
1432 for (i = 1; i < (unsigned int) _dl_argc; ++i)
1434 const ElfW(Sym) *ref = NULL;
1435 ElfW(Addr) loadbase;
1436 lookup_t result;
1438 result = INTUSE(_dl_lookup_symbol) (INTUSE(_dl_argv)[i],
1439 GL(dl_loaded),
1440 &ref, GL(dl_loaded)->l_scope,
1441 ELF_RTYPE_CLASS_PLT, 1);
1443 loadbase = LOOKUP_VALUE_ADDRESS (result);
1445 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
1446 INTUSE(_dl_argv)[i],
1447 (int) sizeof ref->st_value * 2,
1448 (size_t) ref->st_value,
1449 (int) sizeof loadbase * 2, (size_t) loadbase);
1451 else
1453 /* If LD_WARN is set warn about undefined symbols. */
1454 if (GL(dl_lazy) >= 0 && GL(dl_verbose))
1456 /* We have to do symbol dependency testing. */
1457 struct relocate_args args;
1458 struct link_map *l;
1460 args.lazy = GL(dl_lazy);
1462 l = GL(dl_loaded);
1463 while (l->l_next)
1464 l = l->l_next;
1467 if (l != &GL(dl_rtld_map) && ! l->l_faked)
1469 args.l = l;
1470 _dl_receive_error (print_unresolved, relocate_doit,
1471 &args);
1473 l = l->l_prev;
1474 } while (l);
1476 if ((GL(dl_debug_mask) & DL_DEBUG_PRELINK)
1477 && GL(dl_rtld_map).l_opencount > 1)
1478 INTUSE(_dl_relocate_object) (&GL(dl_rtld_map),
1479 GL(dl_loaded)->l_scope, 0, 0);
1482 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
1483 if (version_info)
1485 /* Print more information. This means here, print information
1486 about the versions needed. */
1487 int first = 1;
1488 struct link_map *map = GL(dl_loaded);
1490 for (map = GL(dl_loaded); map != NULL; map = map->l_next)
1492 const char *strtab;
1493 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
1494 ElfW(Verneed) *ent;
1496 if (dyn == NULL)
1497 continue;
1499 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
1500 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
1502 if (first)
1504 _dl_printf ("\n\tVersion information:\n");
1505 first = 0;
1508 _dl_printf ("\t%s:\n",
1509 map->l_name[0] ? map->l_name : rtld_progname);
1511 while (1)
1513 ElfW(Vernaux) *aux;
1514 struct link_map *needed;
1516 needed = find_needed (strtab + ent->vn_file);
1517 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
1519 while (1)
1521 const char *fname = NULL;
1523 if (needed != NULL
1524 && match_version (strtab + aux->vna_name,
1525 needed))
1526 fname = needed->l_name;
1528 _dl_printf ("\t\t%s (%s) %s=> %s\n",
1529 strtab + ent->vn_file,
1530 strtab + aux->vna_name,
1531 aux->vna_flags & VER_FLG_WEAK
1532 ? "[WEAK] " : "",
1533 fname ?: "not found");
1535 if (aux->vna_next == 0)
1536 /* No more symbols. */
1537 break;
1539 /* Next symbol. */
1540 aux = (ElfW(Vernaux) *) ((char *) aux
1541 + aux->vna_next);
1544 if (ent->vn_next == 0)
1545 /* No more dependencies. */
1546 break;
1548 /* Next dependency. */
1549 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
1555 _exit (0);
1558 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]
1559 && ! __builtin_expect (GL(dl_profile) != NULL, 0))
1561 ElfW(Lib) *liblist, *liblistend;
1562 struct link_map **r_list, **r_listend, *l;
1563 const char *strtab = (const void *) D_PTR (GL(dl_loaded),
1564 l_info[DT_STRTAB]);
1566 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
1567 liblist = (ElfW(Lib) *)
1568 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
1569 liblistend = (ElfW(Lib) *)
1570 ((char *) liblist
1571 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
1572 r_list = GL(dl_loaded)->l_searchlist.r_list;
1573 r_listend = r_list + GL(dl_loaded)->l_searchlist.r_nlist;
1575 for (; r_list < r_listend && liblist < liblistend; r_list++)
1577 l = *r_list;
1579 if (l == GL(dl_loaded))
1580 continue;
1582 /* If the library is not mapped where it should, fail. */
1583 if (l->l_addr)
1584 break;
1586 /* Next, check if checksum matches. */
1587 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
1588 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
1589 != liblist->l_checksum)
1590 break;
1592 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
1593 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
1594 != liblist->l_time_stamp)
1595 break;
1597 if (! _dl_name_match_p (strtab + liblist->l_name, l))
1598 break;
1600 ++liblist;
1604 if (r_list == r_listend && liblist == liblistend)
1605 prelinked = true;
1607 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1608 _dl_printf ("\nprelink checking: %s\n", prelinked ? "ok" : "failed");
1612 /* Initialize _r_debug. */
1613 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr);
1615 struct link_map *l;
1617 l = GL(dl_loaded);
1619 #ifdef ELF_MACHINE_DEBUG_SETUP
1621 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1623 ELF_MACHINE_DEBUG_SETUP (l, r);
1624 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1626 #else
1628 if (l->l_info[DT_DEBUG] != NULL)
1629 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1630 with the run-time address of the r_debug structure */
1631 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1633 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1634 case you run gdb on the dynamic linker directly. */
1635 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1636 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1637 #endif
1640 if (prelinked)
1642 struct link_map *l;
1644 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
1646 ElfW(Rela) *conflict, *conflictend;
1647 #ifndef HP_TIMING_NONAVAIL
1648 hp_timing_t start;
1649 hp_timing_t stop;
1650 #endif
1652 HP_TIMING_NOW (start);
1653 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
1654 conflict = (ElfW(Rela) *)
1655 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
1656 conflictend = (ElfW(Rela) *)
1657 ((char *) conflict
1658 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
1659 _dl_resolve_conflicts (GL(dl_loaded), conflict, conflictend);
1660 HP_TIMING_NOW (stop);
1661 HP_TIMING_DIFF (relocate_time, start, stop);
1665 /* Mark all the objects so we know they have been already relocated. */
1666 for (l = GL(dl_loaded); l != NULL; l = l->l_next)
1667 l->l_relocated = 1;
1669 _dl_sysdep_start_cleanup ();
1671 else
1673 /* Now we have all the objects loaded. Relocate them all except for
1674 the dynamic linker itself. We do this in reverse order so that copy
1675 relocs of earlier objects overwrite the data written by later
1676 objects. We do not re-relocate the dynamic linker itself in this
1677 loop because that could result in the GOT entries for functions we
1678 call being changed, and that would break us. It is safe to relocate
1679 the dynamic linker out of order because it has no copy relocs (we
1680 know that because it is self-contained). */
1682 struct link_map *l;
1683 int consider_profiling = GL(dl_profile) != NULL;
1684 #ifndef HP_TIMING_NONAVAIL
1685 hp_timing_t start;
1686 hp_timing_t stop;
1687 hp_timing_t add;
1688 #endif
1690 /* If we are profiling we also must do lazy reloaction. */
1691 GL(dl_lazy) |= consider_profiling;
1693 l = GL(dl_loaded);
1694 while (l->l_next)
1695 l = l->l_next;
1697 HP_TIMING_NOW (start);
1700 /* While we are at it, help the memory handling a bit. We have to
1701 mark some data structures as allocated with the fake malloc()
1702 implementation in ld.so. */
1703 struct libname_list *lnp = l->l_libname->next;
1705 while (__builtin_expect (lnp != NULL, 0))
1707 lnp->dont_free = 1;
1708 lnp = lnp->next;
1711 if (l != &GL(dl_rtld_map))
1712 INTUSE(_dl_relocate_object) (l, l->l_scope, GL(dl_lazy),
1713 consider_profiling);
1715 l = l->l_prev;
1717 while (l);
1718 HP_TIMING_NOW (stop);
1720 HP_TIMING_DIFF (relocate_time, start, stop);
1722 /* Do any necessary cleanups for the startup OS interface code.
1723 We do these now so that no calls are made after rtld re-relocation
1724 which might be resolved to different functions than we expect.
1725 We cannot do this before relocating the other objects because
1726 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
1727 _dl_sysdep_start_cleanup ();
1729 /* Now enable profiling if needed. Like the previous call,
1730 this has to go here because the calls it makes should use the
1731 rtld versions of the functions (particularly calloc()), but it
1732 needs to have _dl_profile_map set up by the relocator. */
1733 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
1734 /* We must prepare the profiling. */
1735 INTUSE(_dl_start_profile) (GL(dl_profile_map), GL(dl_profile_output));
1737 if (GL(dl_rtld_map).l_opencount > 1)
1739 /* There was an explicit ref to the dynamic linker as a shared lib.
1740 Re-relocate ourselves with user-controlled symbol definitions. */
1741 HP_TIMING_NOW (start);
1742 INTUSE(_dl_relocate_object) (&GL(dl_rtld_map), GL(dl_loaded)->l_scope,
1743 0, 0);
1744 HP_TIMING_NOW (stop);
1745 HP_TIMING_DIFF (add, start, stop);
1746 HP_TIMING_ACCUM_NT (relocate_time, add);
1750 /* Now set up the variable which helps the assembler startup code. */
1751 GL(dl_main_searchlist) = &GL(dl_loaded)->l_searchlist;
1752 GL(dl_global_scope)[0] = &GL(dl_loaded)->l_searchlist;
1754 /* Save the information about the original global scope list since
1755 we need it in the memory handling later. */
1756 GL(dl_initial_searchlist) = *GL(dl_main_searchlist);
1758 #ifndef NONTLS_INIT_TP
1759 # define NONTLS_INIT_TP do { } while (0)
1760 #endif
1762 #ifdef USE_TLS
1763 if (GL(dl_tls_max_dtv_idx) > 0 || USE___THREAD || !TLS_INIT_TP_EXPENSIVE)
1765 /* Now that we have completed relocation, the initializer data
1766 for the TLS blocks has its final values and we can copy them
1767 into the main thread's TLS area, which we allocated above. */
1768 _dl_allocate_tls_init (tcbp);
1770 /* And finally install it for the main thread. If ld.so itself uses
1771 TLS we know the thread pointer was initialized earlier. */
1772 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
1773 if (__builtin_expect (lossage != NULL, 0))
1774 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
1776 else
1777 #endif
1778 NONTLS_INIT_TP;
1780 /* Notify the debugger that all objects are now mapped in. */
1781 r->r_state = RT_ADD;
1782 INTUSE(_dl_debug_state) ();
1784 #ifndef MAP_COPY
1785 /* We must munmap() the cache file. */
1786 INTUSE(_dl_unload_cache) ();
1787 #endif
1789 /* Once we return, _dl_sysdep_start will invoke
1790 the DT_INIT functions and then *USER_ENTRY. */
1793 /* This is a little helper function for resolving symbols while
1794 tracing the binary. */
1795 static void
1796 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
1797 const char *errstring)
1799 if (objname[0] == '\0')
1800 objname = rtld_progname ?: "<main program>";
1801 _dl_error_printf ("%s (%s)\n", errstring, objname);
1804 /* This is a little helper function for resolving symbols while
1805 tracing the binary. */
1806 static void
1807 print_missing_version (int errcode __attribute__ ((unused)),
1808 const char *objname, const char *errstring)
1810 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
1811 objname, errstring);
1814 /* Nonzero if any of the debugging options is enabled. */
1815 static int any_debug;
1817 /* Process the string given as the parameter which explains which debugging
1818 options are enabled. */
1819 static void
1820 process_dl_debug (const char *dl_debug)
1822 /* When adding new entries make sure that the maximal length of a name
1823 is correctly handled in the LD_DEBUG_HELP code below. */
1824 static const struct
1826 unsigned char len;
1827 const char name[10];
1828 const char helptext[41];
1829 unsigned short int mask;
1830 } debopts[] =
1832 #define LEN_AND_STR(str) sizeof (str) - 1, str
1833 { LEN_AND_STR ("libs"), "display library search paths",
1834 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
1835 { LEN_AND_STR ("reloc"), "display relocation processing",
1836 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
1837 { LEN_AND_STR ("files"), "display progress for input file",
1838 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
1839 { LEN_AND_STR ("symbols"), "display symbol table processing",
1840 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
1841 { LEN_AND_STR ("bindings"), "display information about symbol binding",
1842 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
1843 { LEN_AND_STR ("versions"), "display version dependencies",
1844 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1845 { LEN_AND_STR ("all"), "all previous options combined",
1846 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
1847 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1848 { LEN_AND_STR ("statistics"), "display relocation statistics",
1849 DL_DEBUG_STATISTICS },
1850 { LEN_AND_STR ("help"), "display this help message and exit",
1851 DL_DEBUG_HELP },
1853 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
1855 /* Skip separating white spaces and commas. */
1856 while (*dl_debug != '\0')
1858 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
1860 size_t cnt;
1861 size_t len = 1;
1863 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
1864 && dl_debug[len] != ',' && dl_debug[len] != ':')
1865 ++len;
1867 for (cnt = 0; cnt < ndebopts; ++cnt)
1868 if (debopts[cnt].len == len
1869 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
1871 GL(dl_debug_mask) |= debopts[cnt].mask;
1872 any_debug = 1;
1873 break;
1876 if (cnt == ndebopts)
1878 /* Display a warning and skip everything until next
1879 separator. */
1880 char *copy = strndupa (dl_debug, len);
1881 _dl_error_printf ("\
1882 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
1885 dl_debug += len;
1886 continue;
1889 ++dl_debug;
1892 if (GL(dl_debug_mask) & DL_DEBUG_HELP)
1894 size_t cnt;
1896 _dl_printf ("\
1897 Valid options for the LD_DEBUG environment variable are:\n\n");
1899 for (cnt = 0; cnt < ndebopts; ++cnt)
1900 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
1901 " " + debopts[cnt].len - 3,
1902 debopts[cnt].helptext);
1904 _dl_printf ("\n\
1905 To direct the debugging output into a file instead of standard output\n\
1906 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
1907 _exit (0);
1911 /* Process all environments variables the dynamic linker must recognize.
1912 Since all of them start with `LD_' we are a bit smarter while finding
1913 all the entries. */
1914 extern char **_environ attribute_hidden;
1917 static void
1918 process_envvars (enum mode *modep)
1920 char **runp = _environ;
1921 char *envline;
1922 enum mode mode = normal;
1923 char *debug_output = NULL;
1925 /* This is the default place for profiling data file. */
1926 GL(dl_profile_output)
1927 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
1929 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
1931 size_t len = 0;
1933 while (envline[len] != '\0' && envline[len] != '=')
1934 ++len;
1936 if (envline[len] != '=')
1937 /* This is a "LD_" variable at the end of the string without
1938 a '=' character. Ignore it since otherwise we will access
1939 invalid memory below. */
1940 continue;
1942 switch (len)
1944 case 4:
1945 /* Warning level, verbose or not. */
1946 if (memcmp (envline, "WARN", 4) == 0)
1947 GL(dl_verbose) = envline[5] != '\0';
1948 break;
1950 case 5:
1951 /* Debugging of the dynamic linker? */
1952 if (memcmp (envline, "DEBUG", 5) == 0)
1953 process_dl_debug (&envline[6]);
1954 break;
1956 case 7:
1957 /* Print information about versions. */
1958 if (memcmp (envline, "VERBOSE", 7) == 0)
1960 version_info = envline[8] != '\0';
1961 break;
1964 /* List of objects to be preloaded. */
1965 if (memcmp (envline, "PRELOAD", 7) == 0)
1967 preloadlist = &envline[8];
1968 break;
1971 /* Which shared object shall be profiled. */
1972 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
1973 GL(dl_profile) = &envline[8];
1974 break;
1976 case 8:
1977 /* Do we bind early? */
1978 if (memcmp (envline, "BIND_NOW", 8) == 0)
1980 GL(dl_lazy) = envline[9] == '\0';
1981 break;
1983 if (memcmp (envline, "BIND_NOT", 8) == 0)
1984 GL(dl_bind_not) = envline[9] != '\0';
1985 break;
1987 case 9:
1988 /* Test whether we want to see the content of the auxiliary
1989 array passed up from the kernel. */
1990 if (memcmp (envline, "SHOW_AUXV", 9) == 0)
1991 _dl_show_auxv ();
1992 break;
1994 case 10:
1995 /* Mask for the important hardware capabilities. */
1996 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
1997 GL(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL, 0, 0);
1998 break;
2000 case 11:
2001 /* Path where the binary is found. */
2002 if (!INTUSE(__libc_enable_secure)
2003 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2004 GL(dl_origin_path) = &envline[12];
2005 break;
2007 case 12:
2008 /* The library search path. */
2009 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2011 library_path = &envline[13];
2012 break;
2015 /* Where to place the profiling data file. */
2016 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2018 debug_output = &envline[13];
2019 break;
2022 if (memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2023 GL(dl_dynamic_weak) = 1;
2024 break;
2026 case 13:
2027 /* We might have some extra environment variable with length 13
2028 to handle. */
2029 #ifdef EXTRA_LD_ENVVARS_13
2030 EXTRA_LD_ENVVARS_13
2031 #endif
2032 if (!INTUSE(__libc_enable_secure)
2033 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2034 GL(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2035 break;
2037 case 14:
2038 /* Where to place the profiling data file. */
2039 if (!INTUSE(__libc_enable_secure)
2040 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2041 && envline[15] != '\0')
2042 GL(dl_profile_output) = &envline[15];
2043 break;
2045 case 16:
2046 /* The mode of the dynamic linker can be set. */
2047 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2049 mode = trace;
2050 GL(dl_verbose) = 1;
2051 GL(dl_debug_mask) |= DL_DEBUG_PRELINK;
2052 GL(dl_trace_prelink) = &envline[17];
2054 break;
2056 case 20:
2057 /* The mode of the dynamic linker can be set. */
2058 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2059 mode = trace;
2060 break;
2062 /* We might have some extra environment variable to handle. This
2063 is tricky due to the pre-processing of the length of the name
2064 in the switch statement here. The code here assumes that added
2065 environment variables have a different length. */
2066 #ifdef EXTRA_LD_ENVVARS
2067 EXTRA_LD_ENVVARS
2068 #endif
2072 /* The caller wants this information. */
2073 *modep = mode;
2075 /* Extra security for SUID binaries. Remove all dangerous environment
2076 variables. */
2077 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2079 static const char unsecure_envvars[] =
2080 #ifdef EXTRA_UNSECURE_ENVVARS
2081 EXTRA_UNSECURE_ENVVARS
2082 #endif
2083 UNSECURE_ENVVARS;
2084 const char *nextp;
2086 nextp = unsecure_envvars;
2089 unsetenv (nextp);
2090 /* We could use rawmemchr but this need not be fast. */
2091 nextp = (char *) (strchr) (nextp, '\0') + 1;
2093 while (*nextp != '\0');
2095 if (__access ("/etc/suid-debug", F_OK) != 0)
2096 unsetenv ("MALLOC_CHECK_");
2098 /* If we have to run the dynamic linker in debugging mode and the
2099 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2100 messages to this file. */
2101 else if (any_debug && debug_output != NULL)
2103 #ifdef O_NOFOLLOW
2104 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2105 #else
2106 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2107 #endif
2108 size_t name_len = strlen (debug_output);
2109 char buf[name_len + 12];
2110 char *startp;
2112 buf[name_len + 11] = '\0';
2113 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2114 *--startp = '.';
2115 startp = memcpy (startp - name_len, debug_output, name_len);
2117 GL(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2118 if (GL(dl_debug_fd) == -1)
2119 /* We use standard output if opening the file failed. */
2120 GL(dl_debug_fd) = STDOUT_FILENO;
2125 /* Print the various times we collected. */
2126 static void
2127 print_statistics (void)
2129 #ifndef HP_TIMING_NONAVAIL
2130 char buf[200];
2131 char *cp;
2132 char *wp;
2134 /* Total time rtld used. */
2135 if (HP_TIMING_AVAIL)
2137 HP_TIMING_PRINT (buf, sizeof (buf), rtld_total_time);
2138 INTUSE(_dl_debug_printf) ("\nruntime linker statistics:\n"
2139 " total startup time in dynamic loader: %s\n",
2140 buf);
2143 /* Print relocation statistics. */
2144 if (HP_TIMING_AVAIL)
2146 char pbuf[30];
2147 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2148 cp = _itoa ((1000ULL * relocate_time) / rtld_total_time,
2149 pbuf + sizeof (pbuf), 10, 0);
2150 wp = pbuf;
2151 switch (pbuf + sizeof (pbuf) - cp)
2153 case 3:
2154 *wp++ = *cp++;
2155 case 2:
2156 *wp++ = *cp++;
2157 case 1:
2158 *wp++ = '.';
2159 *wp++ = *cp++;
2161 *wp = '\0';
2162 INTUSE(_dl_debug_printf) ("\
2163 time needed for relocation: %s (%s%%)\n",
2164 buf, pbuf);
2166 #endif
2168 unsigned long int num_relative_relocations = 0;
2169 struct r_scope_elem *scope = &GL(dl_loaded)->l_searchlist;
2170 unsigned int i;
2172 for (i = 0; i < scope->r_nlist; i++)
2174 struct link_map *l = scope->r_list [i];
2176 if (!l->l_addr)
2177 continue;
2179 if (l->l_info[VERSYMIDX (DT_RELCOUNT)])
2180 num_relative_relocations += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2181 if (l->l_info[VERSYMIDX (DT_RELACOUNT)])
2182 num_relative_relocations += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2185 INTUSE(_dl_debug_printf) (" number of relocations: %lu\n",
2186 GL(dl_num_relocations));
2187 INTUSE(_dl_debug_printf) (" number of relocations from cache: %lu\n",
2188 GL(dl_num_cache_relocations));
2189 INTUSE(_dl_debug_printf) (" number of relative relocations: %lu\n",
2190 num_relative_relocations);
2192 #ifndef HP_TIMING_NONAVAIL
2193 /* Time spend while loading the object and the dependencies. */
2194 if (HP_TIMING_AVAIL)
2196 char pbuf[30];
2197 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2198 cp = _itoa ((1000ULL * load_time) / rtld_total_time,
2199 pbuf + sizeof (pbuf), 10, 0);
2200 wp = pbuf;
2201 switch (pbuf + sizeof (pbuf) - cp)
2203 case 3:
2204 *wp++ = *cp++;
2205 case 2:
2206 *wp++ = *cp++;
2207 case 1:
2208 *wp++ = '.';
2209 *wp++ = *cp++;
2211 *wp = '\0';
2212 INTUSE(_dl_debug_printf) ("\
2213 time needed to load objects: %s (%s%%)\n",
2214 buf, pbuf);
2216 #endif