Updated to fedora-glibc-20041207T1331
[glibc.git] / elf / rtld.c
blob45c65af9047b6a29db95534bc042f4dee008da06
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_real = &GL(dl_rtld_map);
273 GL(dl_rtld_map).l_opencount = 1;
274 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
275 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
276 GL(dl_rtld_map).l_text_end = (ElfW(Addr)) _etext;
277 /* Copy the TLS related data if necessary. */
278 #if USE_TLS && !defined DONT_USE_BOOTSTRAP_MAP
279 # if USE___THREAD
280 assert (info->l.l_tls_modid != 0);
281 GL(dl_rtld_map).l_tls_blocksize = info->l.l_tls_blocksize;
282 GL(dl_rtld_map).l_tls_align = info->l.l_tls_align;
283 GL(dl_rtld_map).l_tls_firstbyte_offset = info->l.l_tls_firstbyte_offset;
284 GL(dl_rtld_map).l_tls_initimage_size = info->l.l_tls_initimage_size;
285 GL(dl_rtld_map).l_tls_initimage = info->l.l_tls_initimage;
286 GL(dl_rtld_map).l_tls_offset = info->l.l_tls_offset;
287 GL(dl_rtld_map).l_tls_modid = 1;
288 # else
289 assert (info->l.l_tls_modid == 0);
290 # if NO_TLS_OFFSET != 0
291 GL(dl_rtld_map).l_tls_offset = NO_TLS_OFFSET;
292 # endif
293 # endif
295 #endif
297 #if HP_TIMING_AVAIL
298 HP_TIMING_NOW (GL(dl_cpuclock_offset));
299 #endif
301 /* Initialize the stack end variable. */
302 __libc_stack_end = __builtin_frame_address (0);
304 /* Call the OS-dependent function to set up life so we can do things like
305 file access. It will call `dl_main' (below) to do all the real work
306 of the dynamic linker, and then unwind our frame and run the user
307 entry point on the same stack we entered on. */
308 start_addr = _dl_sysdep_start (arg, &dl_main);
310 #ifndef HP_TIMING_NONAVAIL
311 hp_timing_t rtld_total_time;
312 if (HP_TIMING_AVAIL)
314 hp_timing_t end_time;
316 /* Get the current time. */
317 HP_TIMING_NOW (end_time);
319 /* Compute the difference. */
320 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
322 #endif
324 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
326 #ifndef HP_TIMING_NONAVAIL
327 print_statistics (&rtld_total_time);
328 #else
329 print_statistics (NULL);
330 #endif
333 return start_addr;
336 static ElfW(Addr) __attribute_used__ internal_function
337 _dl_start (void *arg)
339 #ifdef DONT_USE_BOOTSTRAP_MAP
340 # define bootstrap_map GL(dl_rtld_map)
341 #else
342 struct dl_start_final_info info;
343 # define bootstrap_map info.l
344 #endif
346 /* This #define produces dynamic linking inline functions for
347 bootstrap relocation instead of general-purpose relocation. */
348 #define RTLD_BOOTSTRAP
349 #define RESOLVE_MAP(sym, version, flags) \
350 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : &bootstrap_map)
351 #define RESOLVE(sym, version, flags) \
352 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : bootstrap_map.l_addr)
353 #include "dynamic-link.h"
355 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
356 #ifdef DONT_USE_BOOTSTRAP_MAP
357 HP_TIMING_NOW (start_time);
358 #else
359 HP_TIMING_NOW (info.start_time);
360 #endif
362 /* Partly clean the `bootstrap_map' structure up. Don't use
363 `memset' since it might not be built in or inlined and we cannot
364 make function calls at this point. Use '__builtin_memset' if we
365 know it is available. We do not have to clear the memory if we
366 do not have to use the temporary bootstrap_map. Global variables
367 are initialized to zero by default. */
368 #ifndef DONT_USE_BOOTSTRAP_MAP
369 # ifdef HAVE_BUILTIN_MEMSET
370 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
371 # else
372 for (size_t cnt = 0;
373 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
374 ++cnt)
375 bootstrap_map.l_info[cnt] = 0;
376 # endif
377 #endif
379 /* Figure out the run-time load address of the dynamic linker itself. */
380 bootstrap_map.l_addr = elf_machine_load_address ();
382 /* Read our own dynamic section and fill in the info array. */
383 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
384 elf_get_dynamic_info (&bootstrap_map, NULL);
386 #if defined USE_TLS && NO_TLS_OFFSET != 0
387 bootstrap_map.l_tls_offset = NO_TLS_OFFSET;
388 #endif
390 /* Get the dynamic linker's own program header. First we need the ELF
391 file header. The `_begin' symbol created by the linker script points
392 to it. When we have something like GOTOFF relocs, we can use a plain
393 reference to find the runtime address. Without that, we have to rely
394 on the `l_addr' value, which is not the value we want when prelinked. */
395 #if USE___THREAD
396 dtv_t initdtv[3];
397 ElfW(Ehdr) *ehdr
398 # ifdef DONT_USE_BOOTSTRAP_MAP
399 = (ElfW(Ehdr) *) &_begin;
400 # else
401 # error This will not work with prelink.
402 = (ElfW(Ehdr) *) bootstrap_map.l_addr;
403 # endif
404 ElfW(Phdr) *phdr = (ElfW(Phdr) *) ((void *) ehdr + ehdr->e_phoff);
405 size_t cnt = ehdr->e_phnum; /* PT_TLS is usually the last phdr. */
406 while (cnt-- > 0)
407 if (phdr[cnt].p_type == PT_TLS)
409 void *tlsblock;
410 size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
411 char *p;
413 bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
414 bootstrap_map.l_tls_align = phdr[cnt].p_align;
415 if (phdr[cnt].p_align == 0)
416 bootstrap_map.l_tls_firstbyte_offset = 0;
417 else
418 bootstrap_map.l_tls_firstbyte_offset = (phdr[cnt].p_vaddr
419 & (phdr[cnt].p_align - 1));
420 assert (bootstrap_map.l_tls_blocksize != 0);
421 bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
422 bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
423 + phdr[cnt].p_vaddr);
425 /* We can now allocate the initial TLS block. This can happen
426 on the stack. We'll get the final memory later when we
427 know all about the various objects loaded at startup
428 time. */
429 # if TLS_TCB_AT_TP
430 tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
431 TLS_INIT_TCB_ALIGN)
432 + TLS_INIT_TCB_SIZE
433 + max_align);
434 # elif TLS_DTV_AT_TP
435 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
436 bootstrap_map.l_tls_align)
437 + bootstrap_map.l_tls_blocksize
438 + max_align);
439 # else
440 /* In case a model with a different layout for the TCB and DTV
441 is defined add another #elif here and in the following #ifs. */
442 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
443 # endif
444 /* Align the TLS block. */
445 tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
446 & ~(max_align - 1));
448 /* Initialize the dtv. [0] is the length, [1] the generation
449 counter. */
450 initdtv[0].counter = 1;
451 initdtv[1].counter = 0;
453 /* Initialize the TLS block. */
454 # if TLS_TCB_AT_TP
455 initdtv[2].pointer = tlsblock;
456 # elif TLS_DTV_AT_TP
457 bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
458 bootstrap_map.l_tls_align);
459 initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
460 # else
461 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
462 # endif
463 p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
464 bootstrap_map.l_tls_initimage_size);
465 # ifdef HAVE_BUILTIN_MEMSET
466 __builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
467 - bootstrap_map.l_tls_initimage_size));
468 # else
470 size_t remaining = (bootstrap_map.l_tls_blocksize
471 - bootstrap_map.l_tls_initimage_size);
472 while (remaining-- > 0)
473 *p++ = '\0';
475 #endif
477 /* Install the pointer to the dtv. */
479 /* Initialize the thread pointer. */
480 # if TLS_TCB_AT_TP
481 bootstrap_map.l_tls_offset
482 = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
484 INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
485 initdtv);
487 const char *lossage = TLS_INIT_TP ((char *) tlsblock
488 + bootstrap_map.l_tls_offset, 0);
489 # elif TLS_DTV_AT_TP
490 INSTALL_DTV (tlsblock, initdtv);
491 const char *lossage = TLS_INIT_TP (tlsblock, 0);
492 # else
493 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
494 # endif
495 if (__builtin_expect (lossage != NULL, 0))
496 _dl_fatal_printf ("cannot set up thread-local storage: %s\n",
497 lossage);
499 /* So far this is module number one. */
500 bootstrap_map.l_tls_modid = 1;
502 /* There can only be one PT_TLS entry. */
503 break;
505 #endif /* USE___THREAD */
507 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
508 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
509 #endif
511 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
513 /* Relocate ourselves so we can do normal function calls and
514 data access using the global offset table. */
516 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
519 /* Please note that we don't allow profiling of this object and
520 therefore need not test whether we have to allocate the array
521 for the relocation results (as done in dl-reloc.c). */
523 /* Now life is sane; we can call functions and access global data.
524 Set up to use the operating system facilities, and find out from
525 the operating system's program loader where to find the program
526 header table in core. Put the rest of _dl_start into a separate
527 function, that way the compiler cannot put accesses to the GOT
528 before ELF_DYNAMIC_RELOCATE. */
530 #ifdef DONT_USE_BOOTSTRAP_MAP
531 ElfW(Addr) entry = _dl_start_final (arg);
532 #else
533 ElfW(Addr) entry = _dl_start_final (arg, &info);
534 #endif
536 #ifndef ELF_MACHINE_START_ADDRESS
537 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
538 #endif
540 return ELF_MACHINE_START_ADDRESS (GL(dl_ns)[LM_ID_BASE]._ns_loaded, entry);
546 /* Now life is peachy; we can do all normal operations.
547 On to the real work. */
549 /* Some helper functions. */
551 /* Arguments to relocate_doit. */
552 struct relocate_args
554 struct link_map *l;
555 int lazy;
558 struct map_args
560 /* Argument to map_doit. */
561 char *str;
562 struct link_map *loader;
563 int is_preloaded;
564 int mode;
565 /* Return value of map_doit. */
566 struct link_map *map;
569 /* Arguments to version_check_doit. */
570 struct version_check_args
572 int doexit;
573 int dotrace;
576 static void
577 relocate_doit (void *a)
579 struct relocate_args *args = (struct relocate_args *) a;
581 _dl_relocate_object (args->l, args->l->l_scope, args->lazy, 0);
584 static void
585 map_doit (void *a)
587 struct map_args *args = (struct map_args *) a;
588 args->map = _dl_map_object (args->loader, args->str,
589 args->is_preloaded, lt_library, 0, args->mode,
590 LM_ID_BASE);
593 static void
594 version_check_doit (void *a)
596 struct version_check_args *args = (struct version_check_args *) a;
597 if (_dl_check_all_versions (GL(dl_ns)[LM_ID_BASE]._ns_loaded, 1,
598 args->dotrace) && args->doexit)
599 /* We cannot start the application. Abort now. */
600 _exit (1);
604 static inline struct link_map *
605 find_needed (const char *name)
607 struct r_scope_elem *scope = &GL(dl_ns)[LM_ID_BASE]._ns_loaded->l_searchlist;
608 unsigned int n = scope->r_nlist;
610 while (n-- > 0)
611 if (_dl_name_match_p (name, scope->r_list[n]))
612 return scope->r_list[n];
614 /* Should never happen. */
615 return NULL;
618 static int
619 match_version (const char *string, struct link_map *map)
621 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
622 ElfW(Verdef) *def;
624 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
625 if (map->l_info[VERDEFTAG] == NULL)
626 /* The file has no symbol versioning. */
627 return 0;
629 def = (ElfW(Verdef) *) ((char *) map->l_addr
630 + map->l_info[VERDEFTAG]->d_un.d_ptr);
631 while (1)
633 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
635 /* Compare the version strings. */
636 if (strcmp (string, strtab + aux->vda_name) == 0)
637 /* Bingo! */
638 return 1;
640 /* If no more definitions we failed to find what we want. */
641 if (def->vd_next == 0)
642 break;
644 /* Next definition. */
645 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
648 return 0;
651 #ifdef _LIBC_REENTRANT
652 /* _dl_error_catch_tsd points to this for the single-threaded case.
653 It's reset by the thread library for multithreaded programs. */
654 void ** __attribute__ ((const))
655 _dl_initial_error_catch_tsd (void)
657 static void *data;
658 return &data;
660 #endif
662 #if defined SHARED && defined _LIBC_REENTRANT \
663 && defined __rtld_lock_default_lock_recursive
664 static void rtld_lock_default_lock_recursive (void *lock)
666 __rtld_lock_default_lock_recursive (lock);
669 static void rtld_lock_default_unlock_recursive (void *lock)
671 __rtld_lock_default_unlock_recursive (lock);
673 #endif
676 /* The library search path. */
677 static const char *library_path attribute_relro;
678 /* The list preloaded objects. */
679 static const char *preloadlist attribute_relro;
680 /* Nonzero if information about versions has to be printed. */
681 static int version_info attribute_relro;
683 static void
684 dl_main (const ElfW(Phdr) *phdr,
685 ElfW(Word) phnum,
686 ElfW(Addr) *user_entry)
688 const ElfW(Phdr) *ph;
689 enum mode mode;
690 struct link_map **preloads;
691 unsigned int npreloads;
692 struct link_map *main_map;
693 size_t file_size;
694 char *file;
695 bool has_interp = false;
696 unsigned int i;
697 bool prelinked = false;
698 bool rtld_is_main = false;
699 #ifndef HP_TIMING_NONAVAIL
700 hp_timing_t start;
701 hp_timing_t stop;
702 hp_timing_t diff;
703 #endif
704 #ifdef USE_TLS
705 void *tcbp;
706 #endif
708 #ifdef _LIBC_REENTRANT
709 /* Explicit initialization since the reloc would just be more work. */
710 GL(dl_error_catch_tsd) = &_dl_initial_error_catch_tsd;
711 #endif
713 #ifdef USE_TLS
714 GL(dl_init_static_tls) = &_dl_nothread_init_static_tls;
715 #endif
717 #if defined SHARED && defined _LIBC_REENTRANT \
718 && defined __rtld_lock_default_lock_recursive
719 GL(dl_rtld_lock_recursive) = rtld_lock_default_lock_recursive;
720 GL(dl_rtld_unlock_recursive) = rtld_lock_default_unlock_recursive;
721 #endif
723 /* The explicit initialization here is cheaper than processing the reloc
724 in the _rtld_local definition's initializer. */
725 GL(dl_make_stack_executable_hook) = &_dl_make_stack_executable;
727 /* Process the environment variable which control the behaviour. */
728 process_envvars (&mode);
730 #ifndef HAVE_INLINED_SYSCALLS
731 /* Set up a flag which tells we are just starting. */
732 INTUSE(_dl_starting_up) = 1;
733 #endif
735 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
737 /* Ho ho. We are not the program interpreter! We are the program
738 itself! This means someone ran ld.so as a command. Well, that
739 might be convenient to do sometimes. We support it by
740 interpreting the args like this:
742 ld.so PROGRAM ARGS...
744 The first argument is the name of a file containing an ELF
745 executable we will load and run with the following arguments.
746 To simplify life here, PROGRAM is searched for using the
747 normal rules for shared objects, rather than $PATH or anything
748 like that. We just load it and use its entry point; we don't
749 pay attention to its PT_INTERP command (we are the interpreter
750 ourselves). This is an easy way to test a new ld.so before
751 installing it. */
752 rtld_is_main = true;
754 /* Note the place where the dynamic linker actually came from. */
755 GL(dl_rtld_map).l_name = rtld_progname;
757 while (_dl_argc > 1)
758 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
760 mode = list;
761 GLRO(dl_lazy) = -1; /* This means do no dependency analysis. */
763 ++_dl_skip_args;
764 --_dl_argc;
765 ++INTUSE(_dl_argv);
767 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
769 mode = verify;
771 ++_dl_skip_args;
772 --_dl_argc;
773 ++INTUSE(_dl_argv);
775 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
776 && _dl_argc > 2)
778 library_path = INTUSE(_dl_argv)[2];
780 _dl_skip_args += 2;
781 _dl_argc -= 2;
782 INTUSE(_dl_argv) += 2;
784 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
785 && _dl_argc > 2)
787 GLRO(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
789 _dl_skip_args += 2;
790 _dl_argc -= 2;
791 INTUSE(_dl_argv) += 2;
793 else
794 break;
796 /* If we have no further argument the program was called incorrectly.
797 Grant the user some education. */
798 if (_dl_argc < 2)
799 _dl_fatal_printf ("\
800 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
801 You have invoked `ld.so', the helper program for shared library executables.\n\
802 This program usually lives in the file `/lib/ld.so', and special directives\n\
803 in executable files using ELF shared libraries tell the system's program\n\
804 loader to load the helper program from this file. This helper program loads\n\
805 the shared libraries needed by the program executable, prepares the program\n\
806 to run, and runs it. You may invoke this helper program directly from the\n\
807 command line to load and run an ELF executable file; this is like executing\n\
808 that file itself, but always uses this helper program from the file you\n\
809 specified, instead of the helper program file specified in the executable\n\
810 file you run. This is mostly of use for maintainers to test new versions\n\
811 of this helper program; chances are you did not intend to run this program.\n\
813 --list list all dependencies and how they are resolved\n\
814 --verify verify that given object really is a dynamically linked\n\
815 object we can handle\n\
816 --library-path PATH use given PATH instead of content of the environment\n\
817 variable LD_LIBRARY_PATH\n\
818 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
819 in LIST\n");
821 ++_dl_skip_args;
822 --_dl_argc;
823 ++INTUSE(_dl_argv);
825 /* Initialize the data structures for the search paths for shared
826 objects. */
827 _dl_init_paths (library_path);
829 /* The initialization of _dl_stack_flags done below assumes the
830 executable's PT_GNU_STACK may have been honored by the kernel, and
831 so a PT_GNU_STACK with PF_X set means the stack started out with
832 execute permission. However, this is not really true if the
833 dynamic linker is the executable the kernel loaded. For this
834 case, we must reinitialize _dl_stack_flags to match the dynamic
835 linker itself. If the dynamic linker was built with a
836 PT_GNU_STACK, then the kernel may have loaded us with a
837 nonexecutable stack that we will have to make executable when we
838 load the program below unless it has a PT_GNU_STACK indicating
839 nonexecutable stack is ok. */
841 for (ph = phdr; ph < &phdr[phnum]; ++ph)
842 if (ph->p_type == PT_GNU_STACK)
844 GL(dl_stack_flags) = ph->p_flags;
845 break;
848 if (__builtin_expect (mode, normal) == verify)
850 const char *objname;
851 const char *err_str = NULL;
852 struct map_args args;
854 args.str = rtld_progname;
855 args.loader = NULL;
856 args.is_preloaded = 0;
857 args.mode = __RTLD_OPENEXEC;
858 (void) _dl_catch_error (&objname, &err_str, map_doit, &args);
859 if (__builtin_expect (err_str != NULL, 0))
860 /* We don't free the returned string, the programs stops
861 anyway. */
862 _exit (EXIT_FAILURE);
864 else
866 HP_TIMING_NOW (start);
867 _dl_map_object (NULL, rtld_progname, 0, lt_library, 0,
868 __RTLD_OPENEXEC, LM_ID_BASE);
869 HP_TIMING_NOW (stop);
871 HP_TIMING_DIFF (load_time, start, stop);
874 /* Now the map for the main executable is available. */
875 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
877 phdr = main_map->l_phdr;
878 phnum = main_map->l_phnum;
879 /* We overwrite here a pointer to a malloc()ed string. But since
880 the malloc() implementation used at this point is the dummy
881 implementations which has no real free() function it does not
882 makes sense to free the old string first. */
883 main_map->l_name = (char *) "";
884 *user_entry = main_map->l_entry;
886 else
888 /* Create a link_map for the executable itself.
889 This will be what dlopen on "" returns. */
890 _dl_new_object ((char *) "", "", lt_executable, NULL, 0, LM_ID_BASE);
891 main_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
892 if (main_map == NULL)
893 _dl_fatal_printf ("cannot allocate memory for link map\n");
894 main_map->l_phdr = phdr;
895 main_map->l_phnum = phnum;
896 main_map->l_entry = *user_entry;
898 /* At this point we are in a bit of trouble. We would have to
899 fill in the values for l_dev and l_ino. But in general we
900 do not know where the file is. We also do not handle AT_EXECFD
901 even if it would be passed up.
903 We leave the values here defined to 0. This is normally no
904 problem as the program code itself is normally no shared
905 object and therefore cannot be loaded dynamically. Nothing
906 prevent the use of dynamic binaries and in these situations
907 we might get problems. We might not be able to find out
908 whether the object is already loaded. But since there is no
909 easy way out and because the dynamic binary must also not
910 have an SONAME we ignore this program for now. If it becomes
911 a problem we can force people using SONAMEs. */
913 /* We delay initializing the path structure until we got the dynamic
914 information for the program. */
917 main_map->l_map_end = 0;
918 main_map->l_text_end = 0;
919 /* Perhaps the executable has no PT_LOAD header entries at all. */
920 main_map->l_map_start = ~0;
921 /* We opened the file, account for it. */
922 ++main_map->l_opencount;
923 /* And it was opened directly. */
924 ++main_map->l_direct_opencount;
926 /* Scan the program header table for the dynamic section. */
927 for (ph = phdr; ph < &phdr[phnum]; ++ph)
928 switch (ph->p_type)
930 case PT_PHDR:
931 /* Find out the load address. */
932 main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
933 break;
934 case PT_DYNAMIC:
935 /* This tells us where to find the dynamic section,
936 which tells us everything we need to do. */
937 main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
938 break;
939 case PT_INTERP:
940 /* This "interpreter segment" was used by the program loader to
941 find the program interpreter, which is this program itself, the
942 dynamic linker. We note what name finds us, so that a future
943 dlopen call or DT_NEEDED entry, for something that wants to link
944 against the dynamic linker as a shared library, will know that
945 the shared object is already loaded. */
946 _dl_rtld_libname.name = ((const char *) main_map->l_addr
947 + ph->p_vaddr);
948 /* _dl_rtld_libname.next = NULL; Already zero. */
949 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
951 /* Ordinarilly, we would get additional names for the loader from
952 our DT_SONAME. This can't happen if we were actually linked as
953 a static executable (detect this case when we have no DYNAMIC).
954 If so, assume the filename component of the interpreter path to
955 be our SONAME, and add it to our name list. */
956 if (GL(dl_rtld_map).l_ld == NULL)
958 const char *p = NULL;
959 const char *cp = _dl_rtld_libname.name;
961 /* Find the filename part of the path. */
962 while (*cp != '\0')
963 if (*cp++ == '/')
964 p = cp;
966 if (p != NULL)
968 _dl_rtld_libname2.name = p;
969 /* _dl_rtld_libname2.next = NULL; Already zero. */
970 _dl_rtld_libname.next = &_dl_rtld_libname2;
974 has_interp = true;
975 break;
976 case PT_LOAD:
978 ElfW(Addr) mapstart;
979 ElfW(Addr) allocend;
981 /* Remember where the main program starts in memory. */
982 mapstart = (main_map->l_addr + (ph->p_vaddr & ~(ph->p_align - 1)));
983 if (main_map->l_map_start > mapstart)
984 main_map->l_map_start = mapstart;
986 /* Also where it ends. */
987 allocend = main_map->l_addr + ph->p_vaddr + ph->p_memsz;
988 if (main_map->l_map_end < allocend)
989 main_map->l_map_end = allocend;
990 if ((ph->p_flags & PF_X) && allocend > main_map->l_text_end)
991 main_map->l_text_end = allocend;
993 break;
994 #ifdef USE_TLS
995 case PT_TLS:
996 if (ph->p_memsz > 0)
998 /* Note that in the case the dynamic linker we duplicate work
999 here since we read the PT_TLS entry already in
1000 _dl_start_final. But the result is repeatable so do not
1001 check for this special but unimportant case. */
1002 main_map->l_tls_blocksize = ph->p_memsz;
1003 main_map->l_tls_align = ph->p_align;
1004 if (ph->p_align == 0)
1005 main_map->l_tls_firstbyte_offset = 0;
1006 else
1007 main_map->l_tls_firstbyte_offset = (ph->p_vaddr
1008 & (ph->p_align - 1));
1009 main_map->l_tls_initimage_size = ph->p_filesz;
1010 main_map->l_tls_initimage = (void *) ph->p_vaddr;
1012 /* This image gets the ID one. */
1013 GL(dl_tls_max_dtv_idx) = main_map->l_tls_modid = 1;
1015 break;
1016 #endif
1017 case PT_GNU_STACK:
1018 GL(dl_stack_flags) = ph->p_flags;
1019 break;
1021 case PT_GNU_RELRO:
1022 main_map->l_relro_addr = ph->p_vaddr;
1023 main_map->l_relro_size = ph->p_memsz;
1024 break;
1026 #ifdef USE_TLS
1027 /* Adjust the address of the TLS initialization image in case
1028 the executable is actually an ET_DYN object. */
1029 if (main_map->l_tls_initimage != NULL)
1030 main_map->l_tls_initimage
1031 = (char *) main_map->l_tls_initimage + main_map->l_addr;
1032 #endif
1033 if (! main_map->l_map_end)
1034 main_map->l_map_end = ~0;
1035 if (! main_map->l_text_end)
1036 main_map->l_text_end = ~0;
1037 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
1039 /* We were invoked directly, so the program might not have a
1040 PT_INTERP. */
1041 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
1042 /* _dl_rtld_libname.next = NULL; Already zero. */
1043 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
1045 else
1046 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
1048 if (! rtld_is_main)
1050 /* Extract the contents of the dynamic section for easy access. */
1051 elf_get_dynamic_info (main_map, NULL);
1052 /* Set up our cache of pointers into the hash table. */
1053 _dl_setup_hash (main_map);
1056 if (__builtin_expect (mode, normal) == verify)
1058 /* We were called just to verify that this is a dynamic
1059 executable using us as the program interpreter. Exit with an
1060 error if we were not able to load the binary or no interpreter
1061 is specified (i.e., this is no dynamically linked binary. */
1062 if (main_map->l_ld == NULL)
1063 _exit (1);
1065 /* We allow here some platform specific code. */
1066 #ifdef DISTINGUISH_LIB_VERSIONS
1067 DISTINGUISH_LIB_VERSIONS;
1068 #endif
1069 _exit (has_interp ? 0 : 2);
1072 if (! rtld_is_main)
1073 /* Initialize the data structures for the search paths for shared
1074 objects. */
1075 _dl_init_paths (library_path);
1077 /* Put the link_map for ourselves on the chain so it can be found by
1078 name. Note that at this point the global chain of link maps contains
1079 exactly one element, which is pointed to by dl_loaded. */
1080 if (! GL(dl_rtld_map).l_name)
1081 /* If not invoked directly, the dynamic linker shared object file was
1082 found by the PT_INTERP name. */
1083 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
1084 GL(dl_rtld_map).l_type = lt_library;
1085 main_map->l_next = &GL(dl_rtld_map);
1086 GL(dl_rtld_map).l_prev = main_map;
1087 ++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
1088 ++GL(dl_load_adds);
1090 #if defined(__i386__)
1091 /* Force non-TLS libraries for glibc 2.0 binaries
1092 or if a buggy binary references non-TLS errno or h_errno. */
1093 if (__builtin_expect (main_map->l_info[DT_NUM + DT_THISPROCNUM
1094 + DT_VERSIONTAGIDX (DT_VERNEED)]
1095 == NULL, 0)
1096 && main_map->l_info[DT_DEBUG])
1097 GLRO(dl_osversion) = 0x20205;
1098 else if ((__builtin_expect (mode, normal) != normal
1099 || main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)] == NULL)
1100 /* Only binaries have DT_DEBUG dynamic tags... */
1101 && main_map->l_info[DT_DEBUG])
1103 /* Workaround for buggy binaries. This doesn't handle buggy
1104 libraries. */
1105 bool buggy = false;
1106 const ElfW(Sym) *symtab = (const void *) D_PTR (main_map,
1107 l_info[DT_SYMTAB]);
1108 const char *strtab = (const void *) D_PTR (main_map,
1109 l_info[DT_STRTAB]);
1110 Elf_Symndx symidx;
1111 for (symidx = main_map->l_buckets[0x6c994f % main_map->l_nbuckets];
1112 symidx != STN_UNDEF;
1113 symidx = main_map->l_chain[symidx])
1115 if (__builtin_expect (strcmp (strtab + symtab[symidx].st_name,
1116 "errno") == 0, 0)
1117 && ELFW(ST_TYPE) (symtab[symidx].st_info) != STT_TLS)
1118 buggy = true;
1120 for (symidx = main_map->l_buckets[0xe5c992f % main_map->l_nbuckets];
1121 symidx != STN_UNDEF;
1122 symidx = main_map->l_chain[symidx])
1124 if (__builtin_expect (strcmp (strtab + symtab[symidx].st_name,
1125 "h_errno") == 0, 0)
1126 && ELFW(ST_TYPE) (symtab[symidx].st_info) != STT_TLS)
1127 buggy = true;
1129 if (__builtin_expect (buggy, false) && GLRO(dl_osversion) > 0x20401)
1131 GLRO(dl_osversion) = 0x20401;
1132 _dl_error_printf ("Incorrectly built binary which accesses errno or h_errno directly. Needs to be fixed.\n");
1135 #endif
1137 /* If LD_USE_LOAD_BIAS env variable has not been seen, default
1138 to not using bias for non-prelinked PIEs and libraries
1139 and using it for executables or prelinked PIEs or libraries. */
1140 if (GLRO(dl_use_load_bias) == (ElfW(Addr)) -2)
1141 GLRO(dl_use_load_bias) = main_map->l_addr == 0 ? -1 : 0;
1143 /* Set up the program header information for the dynamic linker
1144 itself. It is needed in the dl_iterate_phdr() callbacks. */
1145 ElfW(Ehdr) *rtld_ehdr = (ElfW(Ehdr) *) GL(dl_rtld_map).l_map_start;
1146 ElfW(Phdr) *rtld_phdr = (ElfW(Phdr) *) (GL(dl_rtld_map).l_map_start
1147 + rtld_ehdr->e_phoff);
1148 GL(dl_rtld_map).l_phdr = rtld_phdr;
1149 GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
1151 /* PT_GNU_RELRO is usually the last phdr. */
1152 size_t cnt = rtld_ehdr->e_phnum;
1153 while (cnt-- > 0)
1154 if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
1156 GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
1157 GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
1158 break;
1161 /* We have two ways to specify objects to preload: via environment
1162 variable and via the file /etc/ld.so.preload. The latter can also
1163 be used when security is enabled. */
1164 preloads = NULL;
1165 npreloads = 0;
1167 if (__builtin_expect (preloadlist != NULL, 0))
1169 /* The LD_PRELOAD environment variable gives list of libraries
1170 separated by white space or colons that are loaded before the
1171 executable's dependencies and prepended to the global scope
1172 list. If the binary is running setuid all elements
1173 containing a '/' are ignored since it is insecure. */
1174 char *list = strdupa (preloadlist);
1175 char *p;
1177 HP_TIMING_NOW (start);
1179 /* Prevent optimizing strsep. Speed is not important here. */
1180 while ((p = (strsep) (&list, " :")) != NULL)
1181 if (p[0] != '\0'
1182 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
1183 || strchr (p, '/') == NULL))
1185 struct link_map *new_map = _dl_map_object (main_map, p, 1,
1186 lt_library, 0, 0,
1187 LM_ID_BASE);
1188 if (++new_map->l_opencount == 1)
1189 /* It is no duplicate. */
1190 ++npreloads;
1193 HP_TIMING_NOW (stop);
1194 HP_TIMING_DIFF (diff, start, stop);
1195 HP_TIMING_ACCUM_NT (load_time, diff);
1198 /* There usually is no ld.so.preload file, it should only be used
1199 for emergencies and testing. So the open call etc should usually
1200 fail. Using access() on a non-existing file is faster than using
1201 open(). So we do this first. If it succeeds we do almost twice
1202 the work but this does not matter, since it is not for production
1203 use. */
1204 static const char preload_file[] = "/etc/ld.so.preload";
1205 if (__builtin_expect (__access (preload_file, R_OK) == 0, 0))
1207 /* Read the contents of the file. */
1208 file = _dl_sysdep_read_whole_file (preload_file, &file_size,
1209 PROT_READ | PROT_WRITE);
1210 if (__builtin_expect (file != MAP_FAILED, 0))
1212 /* Parse the file. It contains names of libraries to be loaded,
1213 separated by white spaces or `:'. It may also contain
1214 comments introduced by `#'. */
1215 char *problem;
1216 char *runp;
1217 size_t rest;
1219 /* Eliminate comments. */
1220 runp = file;
1221 rest = file_size;
1222 while (rest > 0)
1224 char *comment = memchr (runp, '#', rest);
1225 if (comment == NULL)
1226 break;
1228 rest -= comment - runp;
1230 *comment = ' ';
1231 while (--rest > 0 && *++comment != '\n');
1234 /* We have one problematic case: if we have a name at the end of
1235 the file without a trailing terminating characters, we cannot
1236 place the \0. Handle the case separately. */
1237 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
1238 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
1240 problem = &file[file_size];
1241 while (problem > file && problem[-1] != ' '
1242 && problem[-1] != '\t'
1243 && problem[-1] != '\n' && problem[-1] != ':')
1244 --problem;
1246 if (problem > file)
1247 problem[-1] = '\0';
1249 else
1251 problem = NULL;
1252 file[file_size - 1] = '\0';
1255 HP_TIMING_NOW (start);
1257 if (file != problem)
1259 char *p;
1260 runp = file;
1261 while ((p = strsep (&runp, ": \t\n")) != NULL)
1262 if (p[0] != '\0')
1264 const char *objname;
1265 const char *err_str = NULL;
1266 struct map_args args;
1268 args.str = p;
1269 args.loader = main_map;
1270 args.is_preloaded = 1;
1271 args.mode = 0;
1273 (void) _dl_catch_error (&objname, &err_str, map_doit,
1274 &args);
1275 if (__builtin_expect (err_str != NULL, 0))
1277 _dl_error_printf ("\
1278 ERROR: ld.so: object '%s' from %s cannot be preloaded: ignored.\n",
1279 p, preload_file);
1280 /* No need to call free, this is still before
1281 the libc's malloc is used. */
1283 else if (++args.map->l_opencount == 1)
1284 /* It is no duplicate. */
1285 ++npreloads;
1289 if (problem != NULL)
1291 char *p = strndupa (problem, file_size - (problem - file));
1292 struct link_map *new_map = _dl_map_object (main_map, p, 1,
1293 lt_library, 0, 0,
1294 LM_ID_BASE);
1295 if (++new_map->l_opencount == 1)
1296 /* It is no duplicate. */
1297 ++npreloads;
1300 HP_TIMING_NOW (stop);
1301 HP_TIMING_DIFF (diff, start, stop);
1302 HP_TIMING_ACCUM_NT (load_time, diff);
1304 /* We don't need the file anymore. */
1305 __munmap (file, file_size);
1310 #if defined(__i386__) || defined(__alpha__) || (defined(__sparc__) && !defined(__arch64__))
1312 * Modifications by Red Hat Software
1314 * Deal with the broken binaries from the non-versioned ages of glibc.
1315 * If a binary does not have version information enabled, we assume that
1316 * it is a glibc 2.0 binary and we load a compatibility library to try to
1317 * overcome binary incompatibilities.
1318 * Blame: gafton@redhat.com
1320 #define LIB_NOVERSION "/lib/libNoVersion.so.1"
1322 if (__builtin_expect (main_map->l_info[DT_NUM + DT_THISPROCNUM
1323 + DT_VERSIONTAGIDX (DT_VERNEED)]
1324 == NULL, 0)
1325 && (main_map->l_info[DT_DEBUG]
1326 || !(GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)))
1328 struct stat test_st;
1329 int test_fd;
1330 int can_load;
1332 HP_TIMING_NOW (start);
1334 /* _dl_sysdep_message("Loading compatibility library... ", NULL); */
1336 can_load = 1;
1337 test_fd = __open (LIB_NOVERSION, O_RDONLY);
1338 if (test_fd < 0) {
1339 can_load = 0;
1340 /* _dl_sysdep_message(" Can't find " LIB_NOVERSION "\n", NULL); */
1341 } else {
1342 if (__fxstat (_STAT_VER, test_fd, &test_st) < 0 || test_st.st_size == 0) {
1343 can_load = 0;
1344 /* _dl_sysdep_message(" Can't stat " LIB_NOVERSION "\n", NULL); */
1348 if (test_fd >= 0) /* open did no fail.. */
1349 __close(test_fd); /* avoid fd leaks */
1351 if (can_load != 0) {
1352 struct link_map *new_map;
1353 new_map = _dl_map_object (main_map, LIB_NOVERSION,
1354 1, lt_library, 0, 0, LM_ID_BASE);
1355 if (++new_map->l_opencount == 1) {
1356 /* It is no duplicate. */
1357 ++npreloads;
1358 /* _dl_sysdep_message(" DONE\n", NULL); */
1359 } else {
1360 /* _dl_sysdep_message(" FAILED\n", NULL); */
1364 HP_TIMING_NOW (stop);
1365 HP_TIMING_DIFF (diff, start, stop);
1366 HP_TIMING_ACCUM_NT (load_time, diff);
1368 #endif
1370 if (__builtin_expect (npreloads, 0) != 0)
1372 /* Set up PRELOADS with a vector of the preloaded libraries. */
1373 struct link_map *l;
1374 preloads = __alloca (npreloads * sizeof preloads[0]);
1375 l = GL(dl_rtld_map).l_next; /* End of the chain before preloads. */
1376 i = 0;
1379 preloads[i++] = l;
1380 l = l->l_next;
1381 } while (l);
1382 assert (i == npreloads);
1385 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1386 struct link_map *sysinfo_map = NULL;
1387 if (GLRO(dl_sysinfo_dso) != NULL)
1389 /* Do an abridged version of the work _dl_map_object_from_fd would do
1390 to map in the object. It's already mapped and prelinked (and
1391 better be, since it's read-only and so we couldn't relocate it).
1392 We just want our data structures to describe it as if we had just
1393 mapped and relocated it normally. */
1394 struct link_map *l = _dl_new_object ((char *) "", "", lt_library, NULL,
1395 0, LM_ID_BASE);
1396 if (__builtin_expect (l != NULL, 1))
1398 static ElfW(Dyn) dyn_temp[DL_RO_DYN_TEMP_CNT] attribute_relro;
1400 l->l_phdr = ((const void *) GLRO(dl_sysinfo_dso)
1401 + GLRO(dl_sysinfo_dso)->e_phoff);
1402 l->l_phnum = GLRO(dl_sysinfo_dso)->e_phnum;
1403 for (uint_fast16_t i = 0; i < l->l_phnum; ++i)
1405 const ElfW(Phdr) *const ph = &l->l_phdr[i];
1406 if (ph->p_type == PT_DYNAMIC)
1408 l->l_ld = (void *) ph->p_vaddr;
1409 l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn));
1411 else if (ph->p_type == PT_LOAD)
1413 if (! l->l_addr)
1414 l->l_addr = ph->p_vaddr;
1415 else if (ph->p_vaddr + ph->p_memsz >= l->l_map_end)
1416 l->l_map_end = ph->p_vaddr + ph->p_memsz;
1417 else if ((ph->p_flags & PF_X)
1418 && ph->p_vaddr + ph->p_memsz >= l->l_text_end)
1419 l->l_text_end = ph->p_vaddr + ph->p_memsz;
1422 l->l_map_start = (ElfW(Addr)) GLRO(dl_sysinfo_dso);
1423 l->l_addr = l->l_map_start - l->l_addr;
1424 l->l_map_end += l->l_addr;
1425 l->l_text_end += l->l_addr;
1426 l->l_ld = (void *) ((ElfW(Addr)) l->l_ld + l->l_addr);
1427 elf_get_dynamic_info (l, dyn_temp);
1428 _dl_setup_hash (l);
1429 l->l_relocated = 1;
1431 /* Now that we have the info handy, use the DSO image's soname
1432 so this object can be looked up by name. Note that we do not
1433 set l_name here. That field gives the file name of the DSO,
1434 and this DSO is not associated with any file. */
1435 if (l->l_info[DT_SONAME] != NULL)
1437 /* Work around a kernel problem. The kernel cannot handle
1438 addresses in the vsyscall DSO pages in writev() calls. */
1439 const char *dsoname = ((char *) D_PTR (l, l_info[DT_STRTAB])
1440 + l->l_info[DT_SONAME]->d_un.d_val);
1441 size_t len = strlen (dsoname);
1442 char *copy = malloc (len);
1443 if (copy == NULL)
1444 _dl_fatal_printf ("out of memory\n");
1445 l->l_libname->name = memcpy (copy, dsoname, len);
1448 /* We have a prelinked DSO preloaded by the system. */
1449 sysinfo_map = l;
1450 # ifdef NEED_DL_SYSINFO
1451 if (GLRO(dl_sysinfo) == DL_SYSINFO_DEFAULT)
1452 GLRO(dl_sysinfo) = GLRO(dl_sysinfo_dso)->e_entry + l->l_addr;
1453 # endif
1456 #endif
1458 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
1459 specified some libraries to load, these are inserted before the actual
1460 dependencies in the executable's searchlist for symbol resolution. */
1461 HP_TIMING_NOW (start);
1462 _dl_map_object_deps (main_map, preloads, npreloads, mode == trace, 0);
1463 HP_TIMING_NOW (stop);
1464 HP_TIMING_DIFF (diff, start, stop);
1465 HP_TIMING_ACCUM_NT (load_time, diff);
1467 /* Mark all objects as being in the global scope and set the open
1468 counter. */
1469 for (i = main_map->l_searchlist.r_nlist; i > 0; )
1471 --i;
1472 main_map->l_searchlist.r_list[i]->l_global = 1;
1473 ++main_map->l_searchlist.r_list[i]->l_opencount;
1476 #ifndef MAP_ANON
1477 /* We are done mapping things, so close the zero-fill descriptor. */
1478 __close (_dl_zerofd);
1479 _dl_zerofd = -1;
1480 #endif
1482 /* Remove _dl_rtld_map from the chain. */
1483 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
1484 if (GL(dl_rtld_map).l_next)
1485 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1487 if (__builtin_expect (GL(dl_rtld_map).l_opencount > 1, 1))
1489 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1490 put it back in the list of visible objects. We insert it into the
1491 chain in symbol search order because gdb uses the chain's order as
1492 its symbol search order. */
1493 i = 1;
1494 while (main_map->l_searchlist.r_list[i] != &GL(dl_rtld_map))
1495 ++i;
1496 GL(dl_rtld_map).l_prev = main_map->l_searchlist.r_list[i - 1];
1497 if (__builtin_expect (mode, normal) == normal)
1499 GL(dl_rtld_map).l_next = (i + 1 < main_map->l_searchlist.r_nlist
1500 ? main_map->l_searchlist.r_list[i + 1]
1501 : NULL);
1502 #if defined NEED_DL_SYSINFO || defined NEED_DL_SYSINFO_DSO
1503 if (sysinfo_map != NULL
1504 && GL(dl_rtld_map).l_prev->l_next == sysinfo_map
1505 && GL(dl_rtld_map).l_next != sysinfo_map)
1506 GL(dl_rtld_map).l_prev = sysinfo_map;
1507 #endif
1509 else
1510 /* In trace mode there might be an invisible object (which we
1511 could not find) after the previous one in the search list.
1512 In this case it doesn't matter much where we put the
1513 interpreter object, so we just initialize the list pointer so
1514 that the assertion below holds. */
1515 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1517 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1518 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1519 if (GL(dl_rtld_map).l_next != NULL)
1521 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1522 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1526 /* Now let us see whether all libraries are available in the
1527 versions we need. */
1529 struct version_check_args args;
1530 args.doexit = mode == normal;
1531 args.dotrace = mode == trace;
1532 _dl_receive_error (print_missing_version, version_check_doit, &args);
1535 #ifdef USE_TLS
1536 /* Now it is time to determine the layout of the static TLS block
1537 and allocate it for the initial thread. Note that we always
1538 allocate the static block, we never defer it even if no
1539 DF_STATIC_TLS bit is set. The reason is that we know glibc will
1540 use the static model. First add the dynamic linker to the list
1541 if it also uses TLS. */
1542 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1543 /* Assign a module ID. */
1544 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1546 # ifndef TLS_INIT_TP_EXPENSIVE
1547 # define TLS_INIT_TP_EXPENSIVE 0
1548 # endif
1550 /* We do not initialize any of the TLS functionality unless any of the
1551 initial modules uses TLS. This makes dynamic loading of modules with
1552 TLS impossible, but to support it requires either eagerly doing setup
1553 now or lazily doing it later. Doing it now makes us incompatible with
1554 an old kernel that can't perform TLS_INIT_TP, even if no TLS is ever
1555 used. Trying to do it lazily is too hairy to try when there could be
1556 multiple threads (from a non-TLS-using libpthread). */
1557 if (!TLS_INIT_TP_EXPENSIVE || GL(dl_tls_max_dtv_idx) > 0)
1559 struct link_map *l;
1560 size_t nelem;
1561 struct dtv_slotinfo *slotinfo;
1563 /* Number of elements in the static TLS block. */
1564 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
1566 /* Allocate the array which contains the information about the
1567 dtv slots. We allocate a few entries more than needed to
1568 avoid the need for reallocation. */
1569 nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
1571 /* Allocate. */
1572 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
1573 malloc (sizeof (struct dtv_slotinfo_list)
1574 + nelem * sizeof (struct dtv_slotinfo));
1575 /* No need to check the return value. If memory allocation failed
1576 the program would have been terminated. */
1578 slotinfo = memset (GL(dl_tls_dtv_slotinfo_list)->slotinfo, '\0',
1579 nelem * sizeof (struct dtv_slotinfo));
1580 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
1581 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
1583 /* Fill in the information from the loaded modules. */
1584 for (l = main_map, i = 0; l != NULL; l = l->l_next)
1585 if (l->l_tls_blocksize != 0)
1586 /* This is a module with TLS data. Store the map reference.
1587 The generation counter is zero. */
1588 slotinfo[++i].map = l;
1589 assert (i == GL(dl_tls_max_dtv_idx));
1591 /* Compute the TLS offsets for the various blocks. */
1592 _dl_determine_tlsoffset ();
1594 /* Construct the static TLS block and the dtv for the initial
1595 thread. For some platforms this will include allocating memory
1596 for the thread descriptor. The memory for the TLS block will
1597 never be freed. It should be allocated accordingly. The dtv
1598 array can be changed if dynamic loading requires it. */
1599 tcbp = _dl_allocate_tls_storage ();
1600 if (tcbp == NULL)
1601 _dl_fatal_printf ("\
1602 cannot allocate TLS data structures for initial thread");
1604 /* Store for detection of the special case by __tls_get_addr
1605 so it knows not to pass this dtv to the normal realloc. */
1606 GL(dl_initial_dtv) = GET_DTV (tcbp);
1608 #endif
1610 if (__builtin_expect (mode, normal) != normal)
1612 /* We were run just to list the shared libraries. It is
1613 important that we do this before real relocation, because the
1614 functions we call below for output may no longer work properly
1615 after relocation. */
1616 struct link_map *l;
1618 if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1620 struct r_scope_elem *scope = &main_map->l_searchlist;
1622 for (i = 0; i < scope->r_nlist; i++)
1624 l = scope->r_list [i];
1625 if (l->l_faked)
1627 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1628 continue;
1630 if (_dl_name_match_p (GLRO(dl_trace_prelink), l))
1631 GLRO(dl_trace_prelink_map) = l;
1632 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1633 l->l_libname->name[0] ? l->l_libname->name
1634 : rtld_progname ?: "<main program>",
1635 l->l_name[0] ? l->l_name
1636 : rtld_progname ?: "<main program>",
1637 (int) sizeof l->l_map_start * 2,
1638 (size_t) l->l_map_start,
1639 (int) sizeof l->l_addr * 2,
1640 (size_t) l->l_addr);
1641 #ifdef USE_TLS
1642 if (l->l_tls_modid)
1643 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1644 (int) sizeof l->l_tls_offset * 2,
1645 (size_t) l->l_tls_offset);
1646 else
1647 #endif
1648 _dl_printf ("\n");
1651 else if (GLRO(dl_debug_mask) & DL_DEBUG_UNUSED)
1653 /* Look through the dependencies of the main executable
1654 and determine which of them is not actually
1655 required. */
1656 struct link_map *l = main_map;
1658 /* Relocate the main executable. */
1659 struct relocate_args args = { .l = l, .lazy = GLRO(dl_lazy) };
1660 _dl_receive_error (print_unresolved, relocate_doit, &args);
1662 /* This loop depends on the dependencies of the executable to
1663 correspond in number and order to the DT_NEEDED entries. */
1664 ElfW(Dyn) *dyn = main_map->l_ld;
1665 bool first = true;
1666 while (dyn->d_tag != DT_NULL)
1668 if (dyn->d_tag == DT_NEEDED)
1670 l = l->l_next;
1672 if (!l->l_used)
1674 if (first)
1676 _dl_printf ("Unused direct dependencies:\n");
1677 first = false;
1680 _dl_printf ("\t%s\n", l->l_name);
1684 ++dyn;
1687 _exit (first != true);
1689 else if (! main_map->l_info[DT_NEEDED])
1690 _dl_printf ("\tstatically linked\n");
1691 else
1693 for (l = main_map->l_next; l; l = l->l_next)
1694 if (l->l_faked)
1695 /* The library was not found. */
1696 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1697 else if (strcmp (l->l_libname->name, l->l_name) == 0)
1698 _dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
1699 (int) sizeof l->l_map_start * 2,
1700 (size_t) l->l_map_start);
1701 else
1702 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1703 l->l_name, (int) sizeof l->l_map_start * 2,
1704 (size_t) l->l_map_start);
1707 if (__builtin_expect (mode, trace) != trace)
1708 for (i = 1; i < (unsigned int) _dl_argc; ++i)
1710 const ElfW(Sym) *ref = NULL;
1711 ElfW(Addr) loadbase;
1712 lookup_t result;
1714 result = _dl_lookup_symbol_x (INTUSE(_dl_argv)[i], main_map,
1715 &ref, main_map->l_scope, NULL,
1716 ELF_RTYPE_CLASS_PLT,
1717 DL_LOOKUP_ADD_DEPENDENCY, NULL);
1719 loadbase = LOOKUP_VALUE_ADDRESS (result);
1721 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
1722 INTUSE(_dl_argv)[i],
1723 (int) sizeof ref->st_value * 2,
1724 (size_t) ref->st_value,
1725 (int) sizeof loadbase * 2, (size_t) loadbase);
1727 else
1729 /* If LD_WARN is set warn about undefined symbols. */
1730 if (GLRO(dl_lazy) >= 0 && GLRO(dl_verbose))
1732 /* We have to do symbol dependency testing. */
1733 struct relocate_args args;
1734 struct link_map *l;
1736 args.lazy = GLRO(dl_lazy);
1738 l = main_map;
1739 while (l->l_next)
1740 l = l->l_next;
1743 if (l != &GL(dl_rtld_map) && ! l->l_faked)
1745 args.l = l;
1746 _dl_receive_error (print_unresolved, relocate_doit,
1747 &args);
1749 l = l->l_prev;
1750 } while (l);
1752 if ((GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
1753 && GL(dl_rtld_map).l_opencount > 1)
1754 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope,
1755 0, 0);
1758 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
1759 if (version_info)
1761 /* Print more information. This means here, print information
1762 about the versions needed. */
1763 int first = 1;
1764 struct link_map *map;
1766 for (map = main_map; map != NULL; map = map->l_next)
1768 const char *strtab;
1769 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
1770 ElfW(Verneed) *ent;
1772 if (dyn == NULL)
1773 continue;
1775 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
1776 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
1778 if (first)
1780 _dl_printf ("\n\tVersion information:\n");
1781 first = 0;
1784 _dl_printf ("\t%s:\n",
1785 map->l_name[0] ? map->l_name : rtld_progname);
1787 while (1)
1789 ElfW(Vernaux) *aux;
1790 struct link_map *needed;
1792 needed = find_needed (strtab + ent->vn_file);
1793 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
1795 while (1)
1797 const char *fname = NULL;
1799 if (needed != NULL
1800 && match_version (strtab + aux->vna_name,
1801 needed))
1802 fname = needed->l_name;
1804 _dl_printf ("\t\t%s (%s) %s=> %s\n",
1805 strtab + ent->vn_file,
1806 strtab + aux->vna_name,
1807 aux->vna_flags & VER_FLG_WEAK
1808 ? "[WEAK] " : "",
1809 fname ?: "not found");
1811 if (aux->vna_next == 0)
1812 /* No more symbols. */
1813 break;
1815 /* Next symbol. */
1816 aux = (ElfW(Vernaux) *) ((char *) aux
1817 + aux->vna_next);
1820 if (ent->vn_next == 0)
1821 /* No more dependencies. */
1822 break;
1824 /* Next dependency. */
1825 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
1831 _exit (0);
1834 if (main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]
1835 && ! __builtin_expect (GLRO(dl_profile) != NULL, 0))
1837 ElfW(Lib) *liblist, *liblistend;
1838 struct link_map **r_list, **r_listend, *l;
1839 const char *strtab = (const void *) D_PTR (main_map, l_info[DT_STRTAB]);
1841 assert (main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
1842 liblist = (ElfW(Lib) *)
1843 main_map->l_info[ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
1844 liblistend = (ElfW(Lib) *)
1845 ((char *) liblist +
1846 main_map->l_info[VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
1847 r_list = main_map->l_searchlist.r_list;
1848 r_listend = r_list + main_map->l_searchlist.r_nlist;
1850 for (; r_list < r_listend && liblist < liblistend; r_list++)
1852 l = *r_list;
1854 if (l == main_map)
1855 continue;
1857 /* If the library is not mapped where it should, fail. */
1858 if (l->l_addr)
1859 break;
1861 /* Next, check if checksum matches. */
1862 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
1863 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
1864 != liblist->l_checksum)
1865 break;
1867 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
1868 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
1869 != liblist->l_time_stamp)
1870 break;
1872 if (! _dl_name_match_p (strtab + liblist->l_name, l))
1873 break;
1875 ++liblist;
1879 if (r_list == r_listend && liblist == liblistend)
1880 prelinked = true;
1882 if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1883 _dl_debug_printf ("\nprelink checking: %s\n",
1884 prelinked ? "ok" : "failed");
1888 /* Initialize _r_debug. */
1889 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr);
1891 struct link_map *l = main_map;
1893 #ifdef ELF_MACHINE_DEBUG_SETUP
1895 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1897 ELF_MACHINE_DEBUG_SETUP (l, r);
1898 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1900 #else
1902 if (l->l_info[DT_DEBUG] != NULL)
1903 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1904 with the run-time address of the r_debug structure */
1905 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1907 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1908 case you run gdb on the dynamic linker directly. */
1909 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1910 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1911 #endif
1914 /* Now set up the variable which helps the assembler startup code. */
1915 GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist = &main_map->l_searchlist;
1916 GL(dl_ns)[LM_ID_BASE]._ns_global_scope[0] = &main_map->l_searchlist;
1918 /* Save the information about the original global scope list since
1919 we need it in the memory handling later. */
1920 GLRO(dl_initial_searchlist) = *GL(dl_ns)[LM_ID_BASE]._ns_main_searchlist;
1922 if (prelinked)
1924 struct link_map *l;
1926 if (main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
1928 ElfW(Rela) *conflict, *conflictend;
1929 #ifndef HP_TIMING_NONAVAIL
1930 hp_timing_t start;
1931 hp_timing_t stop;
1932 #endif
1934 HP_TIMING_NOW (start);
1935 assert (main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
1936 conflict = (ElfW(Rela) *)
1937 main_map->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
1938 conflictend = (ElfW(Rela) *)
1939 ((char *) conflict
1940 + main_map->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
1941 _dl_resolve_conflicts (main_map, conflict, conflictend);
1942 HP_TIMING_NOW (stop);
1943 HP_TIMING_DIFF (relocate_time, start, stop);
1947 /* Mark all the objects so we know they have been already relocated. */
1948 for (l = main_map; l != NULL; l = l->l_next)
1950 l->l_relocated = 1;
1951 if (l->l_relro_size)
1952 _dl_protect_relro (l);
1955 _dl_sysdep_start_cleanup ();
1957 else
1959 /* Now we have all the objects loaded. Relocate them all except for
1960 the dynamic linker itself. We do this in reverse order so that copy
1961 relocs of earlier objects overwrite the data written by later
1962 objects. We do not re-relocate the dynamic linker itself in this
1963 loop because that could result in the GOT entries for functions we
1964 call being changed, and that would break us. It is safe to relocate
1965 the dynamic linker out of order because it has no copy relocs (we
1966 know that because it is self-contained). */
1968 struct link_map *l;
1969 int consider_profiling = GLRO(dl_profile) != NULL;
1970 #ifndef HP_TIMING_NONAVAIL
1971 hp_timing_t start;
1972 hp_timing_t stop;
1973 hp_timing_t add;
1974 #endif
1976 /* If we are profiling we also must do lazy reloaction. */
1977 GLRO(dl_lazy) |= consider_profiling;
1979 l = main_map;
1980 while (l->l_next)
1981 l = l->l_next;
1983 HP_TIMING_NOW (start);
1986 /* While we are at it, help the memory handling a bit. We have to
1987 mark some data structures as allocated with the fake malloc()
1988 implementation in ld.so. */
1989 struct libname_list *lnp = l->l_libname->next;
1991 while (__builtin_expect (lnp != NULL, 0))
1993 lnp->dont_free = 1;
1994 lnp = lnp->next;
1997 if (l != &GL(dl_rtld_map))
1998 _dl_relocate_object (l, l->l_scope, GLRO(dl_lazy),
1999 consider_profiling);
2001 l = l->l_prev;
2003 while (l);
2004 HP_TIMING_NOW (stop);
2006 HP_TIMING_DIFF (relocate_time, start, stop);
2008 /* Do any necessary cleanups for the startup OS interface code.
2009 We do these now so that no calls are made after rtld re-relocation
2010 which might be resolved to different functions than we expect.
2011 We cannot do this before relocating the other objects because
2012 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
2013 _dl_sysdep_start_cleanup ();
2015 /* Now enable profiling if needed. Like the previous call,
2016 this has to go here because the calls it makes should use the
2017 rtld versions of the functions (particularly calloc()), but it
2018 needs to have _dl_profile_map set up by the relocator. */
2019 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
2020 /* We must prepare the profiling. */
2021 _dl_start_profile ();
2023 if (GL(dl_rtld_map).l_opencount > 1)
2025 /* There was an explicit ref to the dynamic linker as a shared lib.
2026 Re-relocate ourselves with user-controlled symbol definitions. */
2027 HP_TIMING_NOW (start);
2028 _dl_relocate_object (&GL(dl_rtld_map), main_map->l_scope, 0, 0);
2029 HP_TIMING_NOW (stop);
2030 HP_TIMING_DIFF (add, start, stop);
2031 HP_TIMING_ACCUM_NT (relocate_time, add);
2035 #ifndef NONTLS_INIT_TP
2036 # define NONTLS_INIT_TP do { } while (0)
2037 #endif
2039 #ifdef USE_TLS
2040 if (GL(dl_tls_max_dtv_idx) > 0 || USE___THREAD || !TLS_INIT_TP_EXPENSIVE)
2042 /* Now that we have completed relocation, the initializer data
2043 for the TLS blocks has its final values and we can copy them
2044 into the main thread's TLS area, which we allocated above. */
2045 _dl_allocate_tls_init (tcbp);
2047 /* And finally install it for the main thread. If ld.so itself uses
2048 TLS we know the thread pointer was initialized earlier. */
2049 const char *lossage = TLS_INIT_TP (tcbp, USE___THREAD);
2050 if (__builtin_expect (lossage != NULL, 0))
2051 _dl_fatal_printf ("cannot set up thread-local storage: %s\n", lossage);
2053 else
2054 #endif
2055 NONTLS_INIT_TP;
2057 /* Notify the debugger that all objects are now mapped in. */
2058 r->r_state = RT_ADD;
2059 _dl_debug_state ();
2061 #ifndef MAP_COPY
2062 /* We must munmap() the cache file. */
2063 _dl_unload_cache ();
2064 #endif
2066 /* Once we return, _dl_sysdep_start will invoke
2067 the DT_INIT functions and then *USER_ENTRY. */
2070 /* This is a little helper function for resolving symbols while
2071 tracing the binary. */
2072 static void
2073 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
2074 const char *errstring)
2076 if (objname[0] == '\0')
2077 objname = rtld_progname ?: "<main program>";
2078 _dl_error_printf ("%s (%s)\n", errstring, objname);
2081 /* This is a little helper function for resolving symbols while
2082 tracing the binary. */
2083 static void
2084 print_missing_version (int errcode __attribute__ ((unused)),
2085 const char *objname, const char *errstring)
2087 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
2088 objname, errstring);
2091 /* Nonzero if any of the debugging options is enabled. */
2092 static int any_debug attribute_relro;
2094 /* Process the string given as the parameter which explains which debugging
2095 options are enabled. */
2096 static void
2097 process_dl_debug (const char *dl_debug)
2099 /* When adding new entries make sure that the maximal length of a name
2100 is correctly handled in the LD_DEBUG_HELP code below. */
2101 static const struct
2103 unsigned char len;
2104 const char name[10];
2105 const char helptext[41];
2106 unsigned short int mask;
2107 } debopts[] =
2109 #define LEN_AND_STR(str) sizeof (str) - 1, str
2110 { LEN_AND_STR ("libs"), "display library search paths",
2111 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
2112 { LEN_AND_STR ("reloc"), "display relocation processing",
2113 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
2114 { LEN_AND_STR ("files"), "display progress for input file",
2115 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
2116 { LEN_AND_STR ("symbols"), "display symbol table processing",
2117 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
2118 { LEN_AND_STR ("bindings"), "display information about symbol binding",
2119 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
2120 { LEN_AND_STR ("versions"), "display version dependencies",
2121 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2122 { LEN_AND_STR ("all"), "all previous options combined",
2123 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
2124 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
2125 { LEN_AND_STR ("statistics"), "display relocation statistics",
2126 DL_DEBUG_STATISTICS },
2127 { LEN_AND_STR ("unused"), "determined unused DSOs",
2128 DL_DEBUG_UNUSED },
2129 { LEN_AND_STR ("help"), "display this help message and exit",
2130 DL_DEBUG_HELP },
2132 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
2134 /* Skip separating white spaces and commas. */
2135 while (*dl_debug != '\0')
2137 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
2139 size_t cnt;
2140 size_t len = 1;
2142 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
2143 && dl_debug[len] != ',' && dl_debug[len] != ':')
2144 ++len;
2146 for (cnt = 0; cnt < ndebopts; ++cnt)
2147 if (debopts[cnt].len == len
2148 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
2150 GLRO(dl_debug_mask) |= debopts[cnt].mask;
2151 any_debug = 1;
2152 break;
2155 if (cnt == ndebopts)
2157 /* Display a warning and skip everything until next
2158 separator. */
2159 char *copy = strndupa (dl_debug, len);
2160 _dl_error_printf ("\
2161 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
2164 dl_debug += len;
2165 continue;
2168 ++dl_debug;
2171 if (GLRO(dl_debug_mask) & DL_DEBUG_HELP)
2173 size_t cnt;
2175 _dl_printf ("\
2176 Valid options for the LD_DEBUG environment variable are:\n\n");
2178 for (cnt = 0; cnt < ndebopts; ++cnt)
2179 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
2180 " " + debopts[cnt].len - 3,
2181 debopts[cnt].helptext);
2183 _dl_printf ("\n\
2184 To direct the debugging output into a file instead of standard output\n\
2185 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
2186 _exit (0);
2190 /* Process all environments variables the dynamic linker must recognize.
2191 Since all of them start with `LD_' we are a bit smarter while finding
2192 all the entries. */
2193 extern char **_environ attribute_hidden;
2196 static void
2197 process_envvars (enum mode *modep)
2199 char **runp = _environ;
2200 char *envline;
2201 enum mode mode = normal;
2202 char *debug_output = NULL;
2204 /* This is the default place for profiling data file. */
2205 GLRO(dl_profile_output)
2206 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
2208 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
2210 size_t len = 0;
2212 while (envline[len] != '\0' && envline[len] != '=')
2213 ++len;
2215 if (envline[len] != '=')
2216 /* This is a "LD_" variable at the end of the string without
2217 a '=' character. Ignore it since otherwise we will access
2218 invalid memory below. */
2219 continue;
2221 switch (len)
2223 case 4:
2224 /* Warning level, verbose or not. */
2225 if (memcmp (envline, "WARN", 4) == 0)
2226 GLRO(dl_verbose) = envline[5] != '\0';
2227 break;
2229 case 5:
2230 /* Debugging of the dynamic linker? */
2231 if (memcmp (envline, "DEBUG", 5) == 0)
2232 process_dl_debug (&envline[6]);
2233 break;
2235 case 7:
2236 /* Print information about versions. */
2237 if (memcmp (envline, "VERBOSE", 7) == 0)
2239 version_info = envline[8] != '\0';
2240 break;
2243 /* List of objects to be preloaded. */
2244 if (memcmp (envline, "PRELOAD", 7) == 0)
2246 preloadlist = &envline[8];
2247 break;
2250 /* Which shared object shall be profiled. */
2251 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
2252 GLRO(dl_profile) = &envline[8];
2253 break;
2255 case 8:
2256 /* Do we bind early? */
2257 if (memcmp (envline, "BIND_NOW", 8) == 0)
2259 GLRO(dl_lazy) = envline[9] == '\0';
2260 break;
2262 if (memcmp (envline, "BIND_NOT", 8) == 0)
2263 GLRO(dl_bind_not) = envline[9] != '\0';
2264 break;
2266 case 9:
2267 /* Test whether we want to see the content of the auxiliary
2268 array passed up from the kernel. */
2269 if (!INTUSE(__libc_enable_secure)
2270 && memcmp (envline, "SHOW_AUXV", 9) == 0)
2271 _dl_show_auxv ();
2272 break;
2274 case 10:
2275 /* Mask for the important hardware capabilities. */
2276 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
2277 GLRO(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL,
2278 0, 0);
2279 break;
2281 case 11:
2282 /* Path where the binary is found. */
2283 if (!INTUSE(__libc_enable_secure)
2284 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
2285 GLRO(dl_origin_path) = &envline[12];
2286 break;
2288 case 12:
2289 /* The library search path. */
2290 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
2292 library_path = &envline[13];
2293 break;
2296 /* Where to place the profiling data file. */
2297 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
2299 debug_output = &envline[13];
2300 break;
2303 if (!INTUSE(__libc_enable_secure)
2304 && memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
2305 GLRO(dl_dynamic_weak) = 1;
2306 break;
2308 case 13:
2309 /* We might have some extra environment variable with length 13
2310 to handle. */
2311 #ifdef EXTRA_LD_ENVVARS_13
2312 EXTRA_LD_ENVVARS_13
2313 #endif
2314 if (!INTUSE(__libc_enable_secure)
2315 && memcmp (envline, "USE_LOAD_BIAS", 13) == 0)
2316 GLRO(dl_use_load_bias) = envline[14] == '1' ? -1 : 0;
2317 break;
2319 case 14:
2320 /* Where to place the profiling data file. */
2321 if (!INTUSE(__libc_enable_secure)
2322 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
2323 && envline[15] != '\0')
2324 GLRO(dl_profile_output) = &envline[15];
2325 break;
2327 case 16:
2328 /* The mode of the dynamic linker can be set. */
2329 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
2331 mode = trace;
2332 GLRO(dl_verbose) = 1;
2333 GLRO(dl_debug_mask) |= DL_DEBUG_PRELINK;
2334 GLRO(dl_trace_prelink) = &envline[17];
2336 break;
2338 case 20:
2339 /* The mode of the dynamic linker can be set. */
2340 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
2341 mode = trace;
2342 break;
2344 /* We might have some extra environment variable to handle. This
2345 is tricky due to the pre-processing of the length of the name
2346 in the switch statement here. The code here assumes that added
2347 environment variables have a different length. */
2348 #ifdef EXTRA_LD_ENVVARS
2349 EXTRA_LD_ENVVARS
2350 #endif
2354 /* The caller wants this information. */
2355 *modep = mode;
2357 /* Extra security for SUID binaries. Remove all dangerous environment
2358 variables. */
2359 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
2361 static const char unsecure_envvars[] =
2362 #ifdef EXTRA_UNSECURE_ENVVARS
2363 EXTRA_UNSECURE_ENVVARS
2364 #endif
2365 UNSECURE_ENVVARS;
2366 const char *nextp;
2368 nextp = unsecure_envvars;
2371 unsetenv (nextp);
2372 /* We could use rawmemchr but this need not be fast. */
2373 nextp = (char *) (strchr) (nextp, '\0') + 1;
2375 while (*nextp != '\0');
2377 if (__access ("/etc/suid-debug", F_OK) != 0)
2379 unsetenv ("MALLOC_CHECK_");
2380 if (mode == normal)
2381 GLRO(dl_debug_mask) = 0;
2384 /* If we have to run the dynamic linker in debugging mode and the
2385 LD_DEBUG_OUTPUT environment variable is given, we write the debug
2386 messages to this file. */
2387 else if (any_debug && debug_output != NULL)
2389 #ifdef O_NOFOLLOW
2390 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
2391 #else
2392 const int flags = O_WRONLY | O_APPEND | O_CREAT;
2393 #endif
2394 size_t name_len = strlen (debug_output);
2395 char buf[name_len + 12];
2396 char *startp;
2398 buf[name_len + 11] = '\0';
2399 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
2400 *--startp = '.';
2401 startp = memcpy (startp - name_len, debug_output, name_len);
2403 GLRO(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
2404 if (GLRO(dl_debug_fd) == -1)
2405 /* We use standard output if opening the file failed. */
2406 GLRO(dl_debug_fd) = STDOUT_FILENO;
2411 /* Print the various times we collected. */
2412 static void
2413 __attribute ((noinline))
2414 print_statistics (hp_timing_t *rtld_total_timep)
2416 #ifndef HP_TIMING_NONAVAIL
2417 char buf[200];
2418 char *cp;
2419 char *wp;
2421 /* Total time rtld used. */
2422 if (HP_TIMING_AVAIL)
2424 HP_TIMING_PRINT (buf, sizeof (buf), *rtld_total_timep);
2425 _dl_debug_printf ("\nruntime linker statistics:\n"
2426 " total startup time in dynamic loader: %s\n", buf);
2428 /* Print relocation statistics. */
2429 char pbuf[30];
2430 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
2431 cp = _itoa ((1000ULL * relocate_time) / *rtld_total_timep,
2432 pbuf + sizeof (pbuf), 10, 0);
2433 wp = pbuf;
2434 switch (pbuf + sizeof (pbuf) - cp)
2436 case 3:
2437 *wp++ = *cp++;
2438 case 2:
2439 *wp++ = *cp++;
2440 case 1:
2441 *wp++ = '.';
2442 *wp++ = *cp++;
2444 *wp = '\0';
2445 _dl_debug_printf ("\
2446 time needed for relocation: %s (%s%%)\n", buf, pbuf);
2448 #endif
2450 unsigned long int num_relative_relocations = 0;
2451 for (Lmid_t ns = 0; ns < DL_NNS; ++ns)
2453 if (GL(dl_ns)[ns]._ns_loaded == NULL)
2454 continue;
2456 struct r_scope_elem *scope = &GL(dl_ns)[ns]._ns_loaded->l_searchlist;
2458 for (unsigned int i = 0; i < scope->r_nlist; i++)
2460 struct link_map *l = scope->r_list [i];
2462 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELCOUNT)])
2463 num_relative_relocations
2464 += l->l_info[VERSYMIDX (DT_RELCOUNT)]->d_un.d_val;
2465 #ifndef ELF_MACHINE_REL_RELATIVE
2466 /* Relative relocations are processed on these architectures if
2467 library is loaded to different address than p_vaddr or
2468 if not prelinked. */
2469 if ((l->l_addr != 0 || !l->l_info[VALIDX(DT_GNU_PRELINKED)])
2470 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2471 #else
2472 /* On e.g. IA-64 or Alpha, relative relocations are processed
2473 only if library is loaded to different address than p_vaddr. */
2474 if (l->l_addr != 0 && l->l_info[VERSYMIDX (DT_RELACOUNT)])
2475 #endif
2476 num_relative_relocations
2477 += l->l_info[VERSYMIDX (DT_RELACOUNT)]->d_un.d_val;
2481 _dl_debug_printf (" number of relocations: %lu\n"
2482 " number of relocations from cache: %lu\n"
2483 " number of relative relocations: %lu\n",
2484 GL(dl_num_relocations),
2485 GL(dl_num_cache_relocations),
2486 num_relative_relocations);
2488 #ifndef HP_TIMING_NONAVAIL
2489 /* Time spend while loading the object and the dependencies. */
2490 if (HP_TIMING_AVAIL)
2492 char pbuf[30];
2493 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
2494 cp = _itoa ((1000ULL * load_time) / *rtld_total_timep,
2495 pbuf + sizeof (pbuf), 10, 0);
2496 wp = pbuf;
2497 switch (pbuf + sizeof (pbuf) - cp)
2499 case 3:
2500 *wp++ = *cp++;
2501 case 2:
2502 *wp++ = *cp++;
2503 case 1:
2504 *wp++ = '.';
2505 *wp++ = *cp++;
2507 *wp = '\0';
2508 _dl_debug_printf ("\
2509 time needed to load objects: %s (%s%%)\n",
2510 buf, pbuf);
2512 #endif