Update.
[glibc.git] / elf / rtld.c
blob8a144730ca96f467ee37d8d1353deae4682b9135
1 /* Run time dynamic linker.
2 Copyright (C) 1995-1999, 2000, 2001, 2002 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>
41 #include <assert.h>
43 /* Helper function to handle errors while resolving symbols. */
44 static void print_unresolved (int errcode, const char *objname,
45 const char *errsting);
47 /* Helper function to handle errors when a version is missing. */
48 static void print_missing_version (int errcode, const char *objname,
49 const char *errsting);
51 /* Print the various times we collected. */
52 static void print_statistics (void);
54 /* This is a list of all the modes the dynamic loader can be in. */
55 enum mode { normal, list, verify, trace };
57 /* Process all environments variables the dynamic linker must recognize.
58 Since all of them start with `LD_' we are a bit smarter while finding
59 all the entries. */
60 static void process_envvars (enum mode *modep);
62 int _dl_argc attribute_hidden;
63 char **_dl_argv = NULL;
64 INTDEF(_dl_argv)
66 /* Nonzero if we were run directly. */
67 unsigned int _dl_skip_args attribute_hidden;
69 /* Set nonzero during loading and initialization of executable and
70 libraries, cleared before the executable's entry point runs. This
71 must not be initialized to nonzero, because the unused dynamic
72 linker loaded in for libc.so's "ld.so.1" dep will provide the
73 definition seen by libc.so's initializer; that value must be zero,
74 and will be since that dynamic linker's _dl_start and dl_main will
75 never be called. */
76 int _dl_starting_up = 0;
77 INTVARDEF(_dl_starting_up)
79 /* This is the structure which defines all variables global to ld.so
80 (except those which cannot be added for some reason). */
81 struct rtld_global _rtld_global =
83 /* Get architecture specific initializer. */
84 #include <dl-procinfo.c>
85 ._dl_debug_fd = STDERR_FILENO,
86 #if 1
87 /* XXX I know about at least one case where we depend on the old
88 weak behavior (it has to do with librt). Until we get DSO
89 groups implemented we have to make this the default.
90 Bummer. --drepper */
91 ._dl_dynamic_weak = 1,
92 #endif
93 ._dl_lazy = 1,
94 ._dl_fpu_control = _FPU_DEFAULT,
95 ._dl_correct_cache_id = _DL_CACHE_DEFAULT_ID,
96 ._dl_hwcap_mask = HWCAP_IMPORTANT,
97 ._dl_load_lock = _LIBC_LOCK_RECURSIVE_INITIALIZER
99 strong_alias (_rtld_global, _rtld_local);
101 static void dl_main (const ElfW(Phdr) *phdr, ElfW(Word) phnum,
102 ElfW(Addr) *user_entry);
104 static struct libname_list _dl_rtld_libname;
105 static struct libname_list _dl_rtld_libname2;
107 /* We expect less than a second for relocation. */
108 #ifdef HP_SMALL_TIMING_AVAIL
109 # undef HP_TIMING_AVAIL
110 # define HP_TIMING_AVAIL HP_SMALL_TIMING_AVAIL
111 #endif
113 /* Variable for statistics. */
114 #ifndef HP_TIMING_NONAVAIL
115 static hp_timing_t rtld_total_time;
116 static hp_timing_t relocate_time;
117 static hp_timing_t load_time;
118 #endif
120 static ElfW(Addr) _dl_start_final (void *arg, struct link_map *bootstrap_map_p,
121 hp_timing_t start_time);
123 #ifdef RTLD_START
124 RTLD_START
125 #else
126 # error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
127 #endif
129 static ElfW(Addr) __attribute_used__ internal_function
130 _dl_start (void *arg)
132 struct link_map bootstrap_map;
133 hp_timing_t start_time;
134 #if !defined HAVE_BUILTIN_MEMSET || defined USE_TLS
135 size_t cnt;
136 #endif
137 #ifdef USE_TLS
138 ElfW(Ehdr) *ehdr;
139 ElfW(Phdr) *phdr;
140 dtv_t initdtv[3];
141 #endif
143 /* This #define produces dynamic linking inline functions for
144 bootstrap relocation instead of general-purpose relocation. */
145 #define RTLD_BOOTSTRAP
146 #define RESOLVE_MAP(sym, version, flags) \
147 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : &bootstrap_map)
148 #define RESOLVE(sym, version, flags) \
149 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : bootstrap_map.l_addr)
150 #include "dynamic-link.h"
152 if (HP_TIMING_INLINE && HP_TIMING_AVAIL)
153 HP_TIMING_NOW (start_time);
155 /* Partly clean the `bootstrap_map' structure up. Don't use
156 `memset' since it might not be built in or inlined and we cannot
157 make function calls at this point. Use '__builtin_memset' if we
158 know it is available. */
159 #ifdef HAVE_BUILTIN_MEMSET
160 __builtin_memset (bootstrap_map.l_info, '\0', sizeof (bootstrap_map.l_info));
161 #else
162 for (cnt = 0;
163 cnt < sizeof (bootstrap_map.l_info) / sizeof (bootstrap_map.l_info[0]);
164 ++cnt)
165 bootstrap_map.l_info[cnt] = 0;
166 #endif
168 /* Figure out the run-time load address of the dynamic linker itself. */
169 bootstrap_map.l_addr = elf_machine_load_address ();
171 /* Read our own dynamic section and fill in the info array. */
172 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
173 elf_get_dynamic_info (&bootstrap_map);
175 #if USE_TLS
176 # ifndef HAVE___THREAD
177 /* Signal that we have not found TLS data so far. */
178 bootstrap_map.l_tls_modid = 0;
179 # endif
181 /* Get the dynamic linkers program header. */
182 ehdr = (ElfW(Ehdr) *) bootstrap_map.l_addr;
183 phdr = (ElfW(Phdr) *) (bootstrap_map.l_addr + ehdr->e_phoff);
184 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt)
185 if (phdr[cnt].p_type == PT_TLS)
187 void *tlsblock;
188 size_t max_align = MAX (TLS_INIT_TCB_ALIGN, phdr[cnt].p_align);
189 char *p;
191 bootstrap_map.l_tls_blocksize = phdr[cnt].p_memsz;
192 bootstrap_map.l_tls_align = phdr[cnt].p_align;
193 assert (bootstrap_map.l_tls_blocksize != 0);
194 bootstrap_map.l_tls_initimage_size = phdr[cnt].p_filesz;
195 bootstrap_map.l_tls_initimage = (void *) (bootstrap_map.l_addr
196 + phdr[cnt].p_vaddr);
198 /* We can now allocate the initial TLS block. This can happen
199 on the stack. We'll get the final memory later when we
200 know all about the various objects loaded at startup
201 time. */
202 # if TLS_TCB_AT_TP
203 tlsblock = alloca (roundup (bootstrap_map.l_tls_blocksize,
204 TLS_INIT_TCB_ALIGN)
205 + TLS_INIT_TCB_SIZE
206 + max_align);
207 # elif TLS_DTV_AT_TP
208 tlsblock = alloca (roundup (TLS_INIT_TCB_SIZE,
209 bootstrap_map.l_tls_align)
210 + bootstrap_map.l_tls_blocksize
211 + max_align);
212 # else
213 /* In case a model with a different layout for the TCB and DTV
214 is defined add another #elif here and in the following #ifs. */
215 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
216 # endif
217 /* Align the TLS block. */
218 tlsblock = (void *) (((uintptr_t) tlsblock + max_align - 1)
219 & ~(max_align - 1));
221 /* Initialize the dtv. [0] is the length, [1] the generation
222 counter. */
223 initdtv[0].counter = 1;
224 initdtv[1].counter = 0;
226 /* Initialize the TLS block. */
227 # if TLS_TCB_AT_TP
228 initdtv[2].pointer = tlsblock;
229 # elif TLS_DTV_AT_TP
230 bootstrap_map.l_tls_offset = roundup (TLS_INIT_TCB_SIZE,
231 bootstrap_map.l_tls_align);
232 initdtv[2].pointer = (char *) tlsblock + bootstrap_map.l_tls_offset;
233 # else
234 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
235 # endif
236 p = __mempcpy (initdtv[2].pointer, bootstrap_map.l_tls_initimage,
237 bootstrap_map.l_tls_initimage_size);
238 # ifdef HAVE_BUILTIN_MEMSET
239 __builtin_memset (p, '\0', (bootstrap_map.l_tls_blocksize
240 - bootstrap_map.l_tls_initimage_size));
241 # else
243 size_t remaining = (bootstrap_map.l_tls_blocksize
244 - bootstrap_map.l_tls_initimage_size);
245 while (remaining-- > 0)
246 *p++ = '\0';
248 #endif
250 /* Install the pointer to the dtv. */
252 /* Initialize the thread pointer. */
253 # if TLS_TCB_AT_TP
254 bootstrap_map.l_tls_offset
255 = roundup (bootstrap_map.l_tls_blocksize, TLS_INIT_TCB_ALIGN);
257 INSTALL_DTV ((char *) tlsblock + bootstrap_map.l_tls_offset,
258 initdtv);
260 TLS_INIT_TP ((char *) tlsblock + bootstrap_map.l_tls_offset);
261 # elif TLS_DTV_AT_TP
262 INSTALL_DTV (tlsblock, initdtv);
263 TLS_INIT_TP (tlsblock);
264 # else
265 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
266 # endif
268 /* So far this is module number one. */
269 bootstrap_map.l_tls_modid = 1;
271 /* There can only be one PT_TLS entry. */
272 break;
274 #endif /* use TLS */
276 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
277 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
278 #endif
280 if (bootstrap_map.l_addr || ! bootstrap_map.l_info[VALIDX(DT_GNU_PRELINKED)])
282 /* Relocate ourselves so we can do normal function calls and
283 data access using the global offset table. */
285 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
288 /* Please note that we don't allow profiling of this object and
289 therefore need not test whether we have to allocate the array
290 for the relocation results (as done in dl-reloc.c). */
292 /* Now life is sane; we can call functions and access global data.
293 Set up to use the operating system facilities, and find out from
294 the operating system's program loader where to find the program
295 header table in core. Put the rest of _dl_start into a separate
296 function, that way the compiler cannot put accesses to the GOT
297 before ELF_DYNAMIC_RELOCATE. */
299 ElfW(Addr) entry = _dl_start_final (arg, &bootstrap_map, start_time);
301 #ifndef ELF_MACHINE_START_ADDRESS
302 # define ELF_MACHINE_START_ADDRESS(map, start) (start)
303 #endif
305 return ELF_MACHINE_START_ADDRESS (GL(dl_loaded), entry);
310 #ifndef VALIDX
311 # define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
312 + DT_EXTRANUM + DT_VALTAGIDX (tag))
313 #endif
314 #ifndef ADDRIDX
315 # define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
316 + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
317 #endif
319 static ElfW(Addr)
320 _dl_start_final (void *arg, struct link_map *bootstrap_map_p,
321 hp_timing_t start_time)
323 /* The use of `alloca' here looks ridiculous but it helps. The goal
324 is to avoid the function from being inlined. There is no official
325 way to do this so we use this trick. gcc never inlines functions
326 which use `alloca'. */
327 ElfW(Addr) *start_addr = alloca (sizeof (ElfW(Addr)));
328 extern char _begin[] attribute_hidden;
329 extern char _end[] attribute_hidden;
331 if (HP_TIMING_AVAIL)
333 /* If it hasn't happen yet record the startup time. */
334 if (! HP_TIMING_INLINE)
335 HP_TIMING_NOW (start_time);
337 /* Initialize the timing functions. */
338 HP_TIMING_DIFF_INIT ();
341 /* Transfer data about ourselves to the permanent link_map structure. */
342 GL(dl_rtld_map).l_addr = bootstrap_map_p->l_addr;
343 GL(dl_rtld_map).l_ld = bootstrap_map_p->l_ld;
344 GL(dl_rtld_map).l_opencount = 1;
345 memcpy (GL(dl_rtld_map).l_info, bootstrap_map_p->l_info,
346 sizeof GL(dl_rtld_map).l_info);
347 _dl_setup_hash (&GL(dl_rtld_map));
348 GL(dl_rtld_map).l_mach = bootstrap_map_p->l_mach;
349 GL(dl_rtld_map).l_map_start = (ElfW(Addr)) _begin;
350 GL(dl_rtld_map).l_map_end = (ElfW(Addr)) _end;
351 /* Copy the TLS related data if necessary. */
352 #if USE_TLS
353 # ifdef HAVE___THREAD
354 assert (bootstrap_map_p->l_tls_modid != 0);
355 # else
356 if (bootstrap_map_p->l_tls_modid != 0)
357 # endif
359 GL(dl_rtld_map).l_tls_blocksize = bootstrap_map_p->l_tls_blocksize;
360 GL(dl_rtld_map).l_tls_align = bootstrap_map_p->l_tls_align;
361 GL(dl_rtld_map).l_tls_initimage_size
362 = bootstrap_map_p->l_tls_initimage_size;
363 GL(dl_rtld_map).l_tls_initimage = bootstrap_map_p->l_tls_initimage;
364 GL(dl_rtld_map).l_tls_offset = bootstrap_map_p->l_tls_offset;
365 GL(dl_rtld_map).l_tls_modid = 1;
367 #endif
369 #if HP_TIMING_AVAIL
370 HP_TIMING_NOW (GL(dl_cpuclock_offset));
371 #endif
373 /* Call the OS-dependent function to set up life so we can do things like
374 file access. It will call `dl_main' (below) to do all the real work
375 of the dynamic linker, and then unwind our frame and run the user
376 entry point on the same stack we entered on. */
377 *start_addr = _dl_sysdep_start (arg, &dl_main);
379 #ifndef HP_TIMING_NONAVAIL
380 if (HP_TIMING_AVAIL)
382 hp_timing_t end_time;
384 /* Get the current time. */
385 HP_TIMING_NOW (end_time);
387 /* Compute the difference. */
388 HP_TIMING_DIFF (rtld_total_time, start_time, end_time);
390 #endif
392 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_STATISTICS, 0))
393 print_statistics ();
395 return *start_addr;
398 /* Now life is peachy; we can do all normal operations.
399 On to the real work. */
401 /* Some helper functions. */
403 /* Arguments to relocate_doit. */
404 struct relocate_args
406 struct link_map *l;
407 int lazy;
410 struct map_args
412 /* Argument to map_doit. */
413 char *str;
414 /* Return value of map_doit. */
415 struct link_map *main_map;
418 /* Arguments to version_check_doit. */
419 struct version_check_args
421 int doexit;
422 int dotrace;
425 static void
426 relocate_doit (void *a)
428 struct relocate_args *args = (struct relocate_args *) a;
430 INTUSE(_dl_relocate_object) (args->l, args->l->l_scope, args->lazy, 0);
433 static void
434 map_doit (void *a)
436 struct map_args *args = (struct map_args *) a;
437 args->main_map = INTUSE(_dl_map_object) (NULL, args->str, 0, lt_library, 0, 0);
440 static void
441 version_check_doit (void *a)
443 struct version_check_args *args = (struct version_check_args *) a;
444 if (_dl_check_all_versions (GL(dl_loaded), 1, args->dotrace) && args->doexit)
445 /* We cannot start the application. Abort now. */
446 _exit (1);
450 static inline struct link_map *
451 find_needed (const char *name)
453 unsigned int n = GL(dl_loaded)->l_searchlist.r_nlist;
455 while (n-- > 0)
456 if (_dl_name_match_p (name, GL(dl_loaded)->l_searchlist.r_list[n]))
457 return GL(dl_loaded)->l_searchlist.r_list[n];
459 /* Should never happen. */
460 return NULL;
463 static int
464 match_version (const char *string, struct link_map *map)
466 const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
467 ElfW(Verdef) *def;
469 #define VERDEFTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
470 if (map->l_info[VERDEFTAG] == NULL)
471 /* The file has no symbol versioning. */
472 return 0;
474 def = (ElfW(Verdef) *) ((char *) map->l_addr
475 + map->l_info[VERDEFTAG]->d_un.d_ptr);
476 while (1)
478 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
480 /* Compare the version strings. */
481 if (strcmp (string, strtab + aux->vda_name) == 0)
482 /* Bingo! */
483 return 1;
485 /* If no more definitions we failed to find what we want. */
486 if (def->vd_next == 0)
487 break;
489 /* Next definition. */
490 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
493 return 0;
496 static const char *library_path; /* The library search path. */
497 static const char *preloadlist; /* The list preloaded objects. */
498 static int version_info; /* Nonzero if information about
499 versions has to be printed. */
501 static void
502 dl_main (const ElfW(Phdr) *phdr,
503 ElfW(Word) phnum,
504 ElfW(Addr) *user_entry)
506 const ElfW(Phdr) *ph;
507 enum mode mode;
508 struct link_map **preloads;
509 unsigned int npreloads;
510 size_t file_size;
511 char *file;
512 bool has_interp = false;
513 unsigned int i;
514 bool prelinked = false;
515 bool rtld_is_main = false;
516 #ifndef HP_TIMING_NONAVAIL
517 hp_timing_t start;
518 hp_timing_t stop;
519 hp_timing_t diff;
520 #endif
521 #ifdef USE_TLS
522 void *tcbp;
523 #endif
525 /* Process the environment variable which control the behaviour. */
526 process_envvars (&mode);
528 /* Set up a flag which tells we are just starting. */
529 INTUSE(_dl_starting_up) = 1;
531 if (*user_entry == (ElfW(Addr)) ENTRY_POINT)
533 /* Ho ho. We are not the program interpreter! We are the program
534 itself! This means someone ran ld.so as a command. Well, that
535 might be convenient to do sometimes. We support it by
536 interpreting the args like this:
538 ld.so PROGRAM ARGS...
540 The first argument is the name of a file containing an ELF
541 executable we will load and run with the following arguments.
542 To simplify life here, PROGRAM is searched for using the
543 normal rules for shared objects, rather than $PATH or anything
544 like that. We just load it and use its entry point; we don't
545 pay attention to its PT_INTERP command (we are the interpreter
546 ourselves). This is an easy way to test a new ld.so before
547 installing it. */
548 rtld_is_main = true;
550 /* Note the place where the dynamic linker actually came from. */
551 GL(dl_rtld_map).l_name = rtld_progname;
553 while (_dl_argc > 1)
554 if (! strcmp (INTUSE(_dl_argv)[1], "--list"))
556 mode = list;
557 GL(dl_lazy) = -1; /* This means do no dependency analysis. */
559 ++_dl_skip_args;
560 --_dl_argc;
561 ++INTUSE(_dl_argv);
563 else if (! strcmp (INTUSE(_dl_argv)[1], "--verify"))
565 mode = verify;
567 ++_dl_skip_args;
568 --_dl_argc;
569 ++INTUSE(_dl_argv);
571 else if (! strcmp (INTUSE(_dl_argv)[1], "--library-path")
572 && _dl_argc > 2)
574 library_path = INTUSE(_dl_argv)[2];
576 _dl_skip_args += 2;
577 _dl_argc -= 2;
578 INTUSE(_dl_argv) += 2;
580 else if (! strcmp (INTUSE(_dl_argv)[1], "--inhibit-rpath")
581 && _dl_argc > 2)
583 GL(dl_inhibit_rpath) = INTUSE(_dl_argv)[2];
585 _dl_skip_args += 2;
586 _dl_argc -= 2;
587 INTUSE(_dl_argv) += 2;
589 else
590 break;
592 /* If we have no further argument the program was called incorrectly.
593 Grant the user some education. */
594 if (_dl_argc < 2)
595 _dl_fatal_printf ("\
596 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
597 You have invoked `ld.so', the helper program for shared library executables.\n\
598 This program usually lives in the file `/lib/ld.so', and special directives\n\
599 in executable files using ELF shared libraries tell the system's program\n\
600 loader to load the helper program from this file. This helper program loads\n\
601 the shared libraries needed by the program executable, prepares the program\n\
602 to run, and runs it. You may invoke this helper program directly from the\n\
603 command line to load and run an ELF executable file; this is like executing\n\
604 that file itself, but always uses this helper program from the file you\n\
605 specified, instead of the helper program file specified in the executable\n\
606 file you run. This is mostly of use for maintainers to test new versions\n\
607 of this helper program; chances are you did not intend to run this program.\n\
609 --list list all dependencies and how they are resolved\n\
610 --verify verify that given object really is a dynamically linked\n\
611 object we can handle\n\
612 --library-path PATH use given PATH instead of content of the environment\n\
613 variable LD_LIBRARY_PATH\n\
614 --inhibit-rpath LIST ignore RUNPATH and RPATH information in object names\n\
615 in LIST\n");
617 ++_dl_skip_args;
618 --_dl_argc;
619 ++INTUSE(_dl_argv);
621 /* Initialize the data structures for the search paths for shared
622 objects. */
623 _dl_init_paths (library_path);
625 if (__builtin_expect (mode, normal) == verify)
627 const char *objname;
628 const char *err_str = NULL;
629 struct map_args args;
631 args.str = rtld_progname;
632 (void) INTUSE(_dl_catch_error) (&objname, &err_str, map_doit, &args);
633 if (__builtin_expect (err_str != NULL, 0))
634 /* We don't free the returned string, the programs stops
635 anyway. */
636 _exit (EXIT_FAILURE);
638 else
640 HP_TIMING_NOW (start);
641 INTUSE(_dl_map_object) (NULL, rtld_progname, 0, lt_library, 0, 0);
642 HP_TIMING_NOW (stop);
644 HP_TIMING_DIFF (load_time, start, stop);
647 phdr = GL(dl_loaded)->l_phdr;
648 phnum = GL(dl_loaded)->l_phnum;
649 /* We overwrite here a pointer to a malloc()ed string. But since
650 the malloc() implementation used at this point is the dummy
651 implementations which has no real free() function it does not
652 makes sense to free the old string first. */
653 GL(dl_loaded)->l_name = (char *) "";
654 *user_entry = GL(dl_loaded)->l_entry;
656 else
658 /* Create a link_map for the executable itself.
659 This will be what dlopen on "" returns. */
660 _dl_new_object ((char *) "", "", lt_executable, NULL);
661 if (GL(dl_loaded) == NULL)
662 _dl_fatal_printf ("cannot allocate memory for link map\n");
663 GL(dl_loaded)->l_phdr = phdr;
664 GL(dl_loaded)->l_phnum = phnum;
665 GL(dl_loaded)->l_entry = *user_entry;
667 /* At this point we are in a bit of trouble. We would have to
668 fill in the values for l_dev and l_ino. But in general we
669 do not know where the file is. We also do not handle AT_EXECFD
670 even if it would be passed up.
672 We leave the values here defined to 0. This is normally no
673 problem as the program code itself is normally no shared
674 object and therefore cannot be loaded dynamically. Nothing
675 prevent the use of dynamic binaries and in these situations
676 we might get problems. We might not be able to find out
677 whether the object is already loaded. But since there is no
678 easy way out and because the dynamic binary must also not
679 have an SONAME we ignore this program for now. If it becomes
680 a problem we can force people using SONAMEs. */
682 /* We delay initializing the path structure until we got the dynamic
683 information for the program. */
686 GL(dl_loaded)->l_map_end = 0;
687 /* Perhaps the executable has no PT_LOAD header entries at all. */
688 GL(dl_loaded)->l_map_start = ~0;
689 /* We opened the file, account for it. */
690 ++GL(dl_loaded)->l_opencount;
692 /* Scan the program header table for the dynamic section. */
693 for (ph = phdr; ph < &phdr[phnum]; ++ph)
694 switch (ph->p_type)
696 case PT_PHDR:
697 /* Find out the load address. */
698 GL(dl_loaded)->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
699 break;
700 case PT_DYNAMIC:
701 /* This tells us where to find the dynamic section,
702 which tells us everything we need to do. */
703 GL(dl_loaded)->l_ld = (void *) GL(dl_loaded)->l_addr + ph->p_vaddr;
704 break;
705 case PT_INTERP:
706 /* This "interpreter segment" was used by the program loader to
707 find the program interpreter, which is this program itself, the
708 dynamic linker. We note what name finds us, so that a future
709 dlopen call or DT_NEEDED entry, for something that wants to link
710 against the dynamic linker as a shared library, will know that
711 the shared object is already loaded. */
712 _dl_rtld_libname.name = ((const char *) GL(dl_loaded)->l_addr
713 + ph->p_vaddr);
714 /* _dl_rtld_libname.next = NULL; Already zero. */
715 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
717 /* Ordinarilly, we would get additional names for the loader from
718 our DT_SONAME. This can't happen if we were actually linked as
719 a static executable (detect this case when we have no DYNAMIC).
720 If so, assume the filename component of the interpreter path to
721 be our SONAME, and add it to our name list. */
722 if (GL(dl_rtld_map).l_ld == NULL)
724 const char *p = NULL;
725 const char *cp = _dl_rtld_libname.name;
727 /* Find the filename part of the path. */
728 while (*cp != '\0')
729 if (*cp++ == '/')
730 p = cp;
732 if (p != NULL)
734 _dl_rtld_libname2.name = p;
735 /* _dl_rtld_libname2.next = NULL; Already zero. */
736 _dl_rtld_libname.next = &_dl_rtld_libname2;
740 has_interp = true;
741 break;
742 case PT_LOAD:
744 ElfW(Addr) mapstart;
745 ElfW(Addr) allocend;
747 /* Remember where the main program starts in memory. */
748 mapstart = (GL(dl_loaded)->l_addr
749 + (ph->p_vaddr & ~(ph->p_align - 1)));
750 if (GL(dl_loaded)->l_map_start > mapstart)
751 GL(dl_loaded)->l_map_start = mapstart;
753 /* Also where it ends. */
754 allocend = GL(dl_loaded)->l_addr + ph->p_vaddr + ph->p_memsz;
755 if (GL(dl_loaded)->l_map_end < allocend)
756 GL(dl_loaded)->l_map_end = allocend;
758 break;
759 #ifdef USE_TLS
760 case PT_TLS:
761 if (ph->p_memsz > 0)
763 /* Note that in the case the dynamic linker we duplicate work
764 here since we read the PT_TLS entry already in
765 _dl_start_final. But the result is repeatable so do not
766 check for this special but unimportant case. */
767 GL(dl_loaded)->l_tls_blocksize = ph->p_memsz;
768 GL(dl_loaded)->l_tls_align = ph->p_align;
769 GL(dl_loaded)->l_tls_initimage_size = ph->p_filesz;
770 GL(dl_loaded)->l_tls_initimage = (void *) ph->p_vaddr;
772 /* This image gets the ID one. */
773 GL(dl_tls_max_dtv_idx) = GL(dl_loaded)->l_tls_modid = 1;
775 break;
776 #endif
778 if (! GL(dl_loaded)->l_map_end)
779 GL(dl_loaded)->l_map_end = ~0;
780 if (! GL(dl_rtld_map).l_libname && GL(dl_rtld_map).l_name)
782 /* We were invoked directly, so the program might not have a
783 PT_INTERP. */
784 _dl_rtld_libname.name = GL(dl_rtld_map).l_name;
785 /* _dl_rtld_libname.next = NULL; Already zero. */
786 GL(dl_rtld_map).l_libname = &_dl_rtld_libname;
788 else
789 assert (GL(dl_rtld_map).l_libname); /* How else did we get here? */
791 if (! rtld_is_main)
793 /* Extract the contents of the dynamic section for easy access. */
794 elf_get_dynamic_info (GL(dl_loaded));
795 if (GL(dl_loaded)->l_info[DT_HASH])
796 /* Set up our cache of pointers into the hash table. */
797 _dl_setup_hash (GL(dl_loaded));
800 if (__builtin_expect (mode, normal) == verify)
802 /* We were called just to verify that this is a dynamic
803 executable using us as the program interpreter. Exit with an
804 error if we were not able to load the binary or no interpreter
805 is specified (i.e., this is no dynamically linked binary. */
806 if (GL(dl_loaded)->l_ld == NULL)
807 _exit (1);
809 /* We allow here some platform specific code. */
810 #ifdef DISTINGUISH_LIB_VERSIONS
811 DISTINGUISH_LIB_VERSIONS;
812 #endif
813 _exit (has_interp ? 0 : 2);
816 if (! rtld_is_main)
817 /* Initialize the data structures for the search paths for shared
818 objects. */
819 _dl_init_paths (library_path);
821 /* Put the link_map for ourselves on the chain so it can be found by
822 name. Note that at this point the global chain of link maps contains
823 exactly one element, which is pointed to by dl_loaded. */
824 if (! GL(dl_rtld_map).l_name)
825 /* If not invoked directly, the dynamic linker shared object file was
826 found by the PT_INTERP name. */
827 GL(dl_rtld_map).l_name = (char *) GL(dl_rtld_map).l_libname->name;
828 GL(dl_rtld_map).l_type = lt_library;
829 GL(dl_loaded)->l_next = &GL(dl_rtld_map);
830 GL(dl_rtld_map).l_prev = GL(dl_loaded);
831 ++GL(dl_nloaded);
833 /* We have two ways to specify objects to preload: via environment
834 variable and via the file /etc/ld.so.preload. The latter can also
835 be used when security is enabled. */
836 preloads = NULL;
837 npreloads = 0;
839 if (__builtin_expect (preloadlist != NULL, 0))
841 /* The LD_PRELOAD environment variable gives list of libraries
842 separated by white space or colons that are loaded before the
843 executable's dependencies and prepended to the global scope
844 list. If the binary is running setuid all elements
845 containing a '/' are ignored since it is insecure. */
846 char *list = strdupa (preloadlist);
847 char *p;
849 HP_TIMING_NOW (start);
851 /* Prevent optimizing strsep. Speed is not important here. */
852 while ((p = (strsep) (&list, " :")) != NULL)
853 if (p[0] != '\0'
854 && (__builtin_expect (! INTUSE(__libc_enable_secure), 1)
855 || strchr (p, '/') == NULL))
857 struct link_map *new_map = INTUSE(_dl_map_object) (GL(dl_loaded),
858 p, 1,
859 lt_library,
860 0, 0);
861 if (++new_map->l_opencount == 1)
862 /* It is no duplicate. */
863 ++npreloads;
866 HP_TIMING_NOW (stop);
867 HP_TIMING_DIFF (diff, start, stop);
868 HP_TIMING_ACCUM_NT (load_time, diff);
871 /* Read the contents of the file. */
872 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
873 PROT_READ | PROT_WRITE);
874 if (__builtin_expect (file != MAP_FAILED, 0))
876 /* Parse the file. It contains names of libraries to be loaded,
877 separated by white spaces or `:'. It may also contain
878 comments introduced by `#'. */
879 char *problem;
880 char *runp;
881 size_t rest;
883 /* Eliminate comments. */
884 runp = file;
885 rest = file_size;
886 while (rest > 0)
888 char *comment = memchr (runp, '#', rest);
889 if (comment == NULL)
890 break;
892 rest -= comment - runp;
894 *comment = ' ';
895 while (--rest > 0 && *++comment != '\n');
898 /* We have one problematic case: if we have a name at the end of
899 the file without a trailing terminating characters, we cannot
900 place the \0. Handle the case separately. */
901 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
902 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
904 problem = &file[file_size];
905 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
906 && problem[-1] != '\n' && problem[-1] != ':')
907 --problem;
909 if (problem > file)
910 problem[-1] = '\0';
912 else
914 problem = NULL;
915 file[file_size - 1] = '\0';
918 HP_TIMING_NOW (start);
920 if (file != problem)
922 char *p;
923 runp = file;
924 while ((p = strsep (&runp, ": \t\n")) != NULL)
925 if (p[0] != '\0')
927 struct link_map *new_map = INTUSE(_dl_map_object) (GL(dl_loaded),
928 p, 1,
929 lt_library,
930 0, 0);
931 if (++new_map->l_opencount == 1)
932 /* It is no duplicate. */
933 ++npreloads;
937 if (problem != NULL)
939 char *p = strndupa (problem, file_size - (problem - file));
940 struct link_map *new_map = INTUSE(_dl_map_object) (GL(dl_loaded), p,
941 1, lt_library,
942 0, 0);
943 if (++new_map->l_opencount == 1)
944 /* It is no duplicate. */
945 ++npreloads;
948 HP_TIMING_NOW (stop);
949 HP_TIMING_DIFF (diff, start, stop);
950 HP_TIMING_ACCUM_NT (load_time, diff);
952 /* We don't need the file anymore. */
953 __munmap (file, file_size);
956 if (__builtin_expect (npreloads, 0) != 0)
958 /* Set up PRELOADS with a vector of the preloaded libraries. */
959 struct link_map *l;
960 preloads = __alloca (npreloads * sizeof preloads[0]);
961 l = GL(dl_rtld_map).l_next; /* End of the chain before preloads. */
962 i = 0;
965 preloads[i++] = l;
966 l = l->l_next;
967 } while (l);
968 assert (i == npreloads);
971 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
972 specified some libraries to load, these are inserted before the actual
973 dependencies in the executable's searchlist for symbol resolution. */
974 HP_TIMING_NOW (start);
975 INTUSE(_dl_map_object_deps) (GL(dl_loaded), preloads, npreloads,
976 mode == trace, 0);
977 HP_TIMING_NOW (stop);
978 HP_TIMING_DIFF (diff, start, stop);
979 HP_TIMING_ACCUM_NT (load_time, diff);
981 /* Mark all objects as being in the global scope and set the open
982 counter. */
983 for (i = GL(dl_loaded)->l_searchlist.r_nlist; i > 0; )
985 --i;
986 GL(dl_loaded)->l_searchlist.r_list[i]->l_global = 1;
987 ++GL(dl_loaded)->l_searchlist.r_list[i]->l_opencount;
990 #ifndef MAP_ANON
991 /* We are done mapping things, so close the zero-fill descriptor. */
992 __close (_dl_zerofd);
993 _dl_zerofd = -1;
994 #endif
996 /* Remove _dl_rtld_map from the chain. */
997 GL(dl_rtld_map).l_prev->l_next = GL(dl_rtld_map).l_next;
998 if (GL(dl_rtld_map).l_next)
999 GL(dl_rtld_map).l_next->l_prev = GL(dl_rtld_map).l_prev;
1001 if (__builtin_expect (GL(dl_rtld_map).l_opencount > 1, 1))
1003 /* Some DT_NEEDED entry referred to the interpreter object itself, so
1004 put it back in the list of visible objects. We insert it into the
1005 chain in symbol search order because gdb uses the chain's order as
1006 its symbol search order. */
1007 i = 1;
1008 while (GL(dl_loaded)->l_searchlist.r_list[i] != &GL(dl_rtld_map))
1009 ++i;
1010 GL(dl_rtld_map).l_prev = GL(dl_loaded)->l_searchlist.r_list[i - 1];
1011 if (__builtin_expect (mode, normal) == normal)
1012 GL(dl_rtld_map).l_next = (i + 1 < GL(dl_loaded)->l_searchlist.r_nlist
1013 ? GL(dl_loaded)->l_searchlist.r_list[i + 1]
1014 : NULL);
1015 else
1016 /* In trace mode there might be an invisible object (which we
1017 could not find) after the previous one in the search list.
1018 In this case it doesn't matter much where we put the
1019 interpreter object, so we just initialize the list pointer so
1020 that the assertion below holds. */
1021 GL(dl_rtld_map).l_next = GL(dl_rtld_map).l_prev->l_next;
1023 assert (GL(dl_rtld_map).l_prev->l_next == GL(dl_rtld_map).l_next);
1024 GL(dl_rtld_map).l_prev->l_next = &GL(dl_rtld_map);
1025 if (GL(dl_rtld_map).l_next != NULL)
1027 assert (GL(dl_rtld_map).l_next->l_prev == GL(dl_rtld_map).l_prev);
1028 GL(dl_rtld_map).l_next->l_prev = &GL(dl_rtld_map);
1032 /* Now let us see whether all libraries are available in the
1033 versions we need. */
1035 struct version_check_args args;
1036 args.doexit = mode == normal;
1037 args.dotrace = mode == trace;
1038 _dl_receive_error (print_missing_version, version_check_doit, &args);
1041 #ifdef USE_TLS
1042 /* Now it is time to determine the layout of the static TLS block
1043 and allocate it for the initial thread. Note that we always
1044 allocate the static block, we never defer it even if no
1045 DF_STATIC_TLS bit is set. The reason is that we know glibc will
1046 use the static model. First add the dynamic linker to the list
1047 if it also uses TLS. */
1048 if (GL(dl_rtld_map).l_tls_blocksize != 0)
1049 /* Assign a module ID. */
1050 GL(dl_rtld_map).l_tls_modid = _dl_next_tls_modid ();
1052 # ifndef SHARED
1053 /* If dynamic loading of modules with TLS is impossible we do not
1054 have to initialize any of the TLS functionality unless any of the
1055 initial modules uses TLS. */
1056 if (GL(dl_tls_max_dtv_idx) > 0)
1057 # endif
1059 struct link_map *l;
1060 size_t nelem;
1061 struct dtv_slotinfo *slotinfo;
1063 /* Number of elements in the static TLS block. */
1064 GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx);
1066 /* Allocate the array which contains the information about the
1067 dtv slots. We allocate a few entries more than needed to
1068 avoid the need for reallocation. */
1069 nelem = GL(dl_tls_max_dtv_idx) + 1 + TLS_SLOTINFO_SURPLUS;
1071 /* Allocate. */
1072 GL(dl_tls_dtv_slotinfo_list) = (struct dtv_slotinfo_list *)
1073 malloc (sizeof (struct dtv_slotinfo_list)
1074 + nelem * sizeof (struct dtv_slotinfo));
1075 /* No need to check the return value. If memory allocation failed
1076 the program would have been terminated. */
1078 slotinfo = memset (GL(dl_tls_dtv_slotinfo_list)->slotinfo, '\0',
1079 nelem * sizeof (struct dtv_slotinfo));
1080 GL(dl_tls_dtv_slotinfo_list)->len = nelem;
1081 GL(dl_tls_dtv_slotinfo_list)->next = NULL;
1083 /* Fill in the information from the loaded modules. */
1084 for (l = GL(dl_loaded), i = 0; l != NULL; l = l->l_next)
1085 if (l->l_tls_blocksize != 0)
1086 /* This is a module with TLS data. Store the map reference.
1087 The generation counter is zero. */
1088 slotinfo[++i].map = l;
1089 assert (i == GL(dl_tls_max_dtv_idx));
1091 /* Compute the TLS offsets for the various blocks. We call this
1092 function even if none of the modules available at startup time
1093 uses TLS to initialize some variables. */
1094 _dl_determine_tlsoffset ();
1096 /* Construct the static TLS block and the dtv for the initial
1097 thread. For some platforms this will include allocating memory
1098 for the thread descriptor. The memory for the TLS block will
1099 never be freed. It should be allocated accordingly. The dtv
1100 array can be changed if dynamic loading requires it. */
1101 tcbp = _dl_allocate_tls_storage ();
1102 if (tcbp == NULL)
1103 _dl_fatal_printf ("\
1104 cannot allocate TLS data structures for initial thread");
1106 /* Store for detection of the special case by __tls_get_addr
1107 so it knows not to pass this dtv to the normal realloc. */
1108 GL(dl_initial_dtv) = GET_DTV (tcbp);
1110 #endif
1112 if (__builtin_expect (mode, normal) != normal)
1114 /* We were run just to list the shared libraries. It is
1115 important that we do this before real relocation, because the
1116 functions we call below for output may no longer work properly
1117 after relocation. */
1118 if (! GL(dl_loaded)->l_info[DT_NEEDED])
1119 _dl_printf ("\tstatically linked\n");
1120 else
1122 struct link_map *l;
1124 if (GL(dl_debug_mask) & DL_DEBUG_PRELINK)
1126 struct r_scope_elem *scope = &GL(dl_loaded)->l_searchlist;
1128 for (i = 0; i < scope->r_nlist; i++)
1130 l = scope->r_list [i];
1131 if (l->l_faked)
1133 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1134 continue;
1136 if (_dl_name_match_p (GL(dl_trace_prelink), l))
1137 GL(dl_trace_prelink_map) = l;
1138 _dl_printf ("\t%s => %s (0x%0*Zx, 0x%0*Zx)",
1139 l->l_libname->name[0] ? l->l_libname->name
1140 : rtld_progname ?: "<main program>",
1141 l->l_name[0] ? l->l_name
1142 : rtld_progname ?: "<main program>",
1143 (int) sizeof l->l_map_start * 2,
1144 l->l_map_start,
1145 (int) sizeof l->l_addr * 2,
1146 l->l_addr);
1147 #ifdef USE_TLS
1148 if (l->l_tls_modid)
1149 _dl_printf (" TLS(0x%Zx, 0x%0*Zx)\n", l->l_tls_modid,
1150 (int) sizeof l->l_tls_offset * 2,
1151 l->l_tls_offset);
1152 else
1153 #endif
1154 _dl_printf ("\n");
1157 else
1159 for (l = GL(dl_loaded)->l_next; l; l = l->l_next)
1160 if (l->l_faked)
1161 /* The library was not found. */
1162 _dl_printf ("\t%s => not found\n", l->l_libname->name);
1163 else
1164 _dl_printf ("\t%s => %s (0x%0*Zx)\n", l->l_libname->name,
1165 l->l_name, (int) sizeof l->l_map_start * 2,
1166 l->l_map_start);
1170 if (__builtin_expect (mode, trace) != trace)
1171 for (i = 1; i < _dl_argc; ++i)
1173 const ElfW(Sym) *ref = NULL;
1174 ElfW(Addr) loadbase;
1175 lookup_t result;
1177 result = INTUSE(_dl_lookup_symbol) (INTUSE(_dl_argv)[i],
1178 GL(dl_loaded),
1179 &ref, GL(dl_loaded)->l_scope,
1180 ELF_RTYPE_CLASS_PLT, 1);
1182 loadbase = LOOKUP_VALUE_ADDRESS (result);
1184 _dl_printf ("%s found at 0x%0*Zd in object at 0x%0*Zd\n",
1185 INTUSE(_dl_argv)[i],
1186 (int) sizeof ref->st_value * 2, ref->st_value,
1187 (int) sizeof loadbase * 2, loadbase);
1189 else
1191 /* If LD_WARN is set warn about undefined symbols. */
1192 if (GL(dl_lazy) >= 0 && GL(dl_verbose))
1194 /* We have to do symbol dependency testing. */
1195 struct relocate_args args;
1196 struct link_map *l;
1198 args.lazy = GL(dl_lazy);
1200 l = GL(dl_loaded);
1201 while (l->l_next)
1202 l = l->l_next;
1205 if (l != &GL(dl_rtld_map) && ! l->l_faked)
1207 args.l = l;
1208 _dl_receive_error (print_unresolved, relocate_doit,
1209 &args);
1211 l = l->l_prev;
1212 } while (l);
1214 if ((GL(dl_debug_mask) & DL_DEBUG_PRELINK)
1215 && GL(dl_rtld_map).l_opencount > 1)
1216 INTUSE(_dl_relocate_object) (&GL(dl_rtld_map),
1217 GL(dl_loaded)->l_scope, 0, 0);
1220 #define VERNEEDTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
1221 if (version_info)
1223 /* Print more information. This means here, print information
1224 about the versions needed. */
1225 int first = 1;
1226 struct link_map *map = GL(dl_loaded);
1228 for (map = GL(dl_loaded); map != NULL; map = map->l_next)
1230 const char *strtab;
1231 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
1232 ElfW(Verneed) *ent;
1234 if (dyn == NULL)
1235 continue;
1237 strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
1238 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
1240 if (first)
1242 _dl_printf ("\n\tVersion information:\n");
1243 first = 0;
1246 _dl_printf ("\t%s:\n",
1247 map->l_name[0] ? map->l_name : rtld_progname);
1249 while (1)
1251 ElfW(Vernaux) *aux;
1252 struct link_map *needed;
1254 needed = find_needed (strtab + ent->vn_file);
1255 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
1257 while (1)
1259 const char *fname = NULL;
1261 if (needed != NULL
1262 && match_version (strtab + aux->vna_name,
1263 needed))
1264 fname = needed->l_name;
1266 _dl_printf ("\t\t%s (%s) %s=> %s\n",
1267 strtab + ent->vn_file,
1268 strtab + aux->vna_name,
1269 aux->vna_flags & VER_FLG_WEAK
1270 ? "[WEAK] " : "",
1271 fname ?: "not found");
1273 if (aux->vna_next == 0)
1274 /* No more symbols. */
1275 break;
1277 /* Next symbol. */
1278 aux = (ElfW(Vernaux) *) ((char *) aux
1279 + aux->vna_next);
1282 if (ent->vn_next == 0)
1283 /* No more dependencies. */
1284 break;
1286 /* Next dependency. */
1287 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
1293 _exit (0);
1296 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]
1297 && ! __builtin_expect (GL(dl_profile) != NULL, 0))
1299 ElfW(Lib) *liblist, *liblistend;
1300 struct link_map **r_list, **r_listend, *l;
1301 const char *strtab = (const void *) D_PTR (GL(dl_loaded),
1302 l_info[DT_STRTAB]);
1304 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)] != NULL);
1305 liblist = (ElfW(Lib) *)
1306 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_LIBLIST)]->d_un.d_ptr;
1307 liblistend = (ElfW(Lib) *)
1308 ((char *) liblist
1309 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_LIBLISTSZ)]->d_un.d_val);
1310 r_list = GL(dl_loaded)->l_searchlist.r_list;
1311 r_listend = r_list + GL(dl_loaded)->l_searchlist.r_nlist;
1313 for (; r_list < r_listend && liblist < liblistend; r_list++)
1315 l = *r_list;
1317 if (l == GL(dl_loaded))
1318 continue;
1320 /* If the library is not mapped where it should, fail. */
1321 if (l->l_addr)
1322 break;
1324 /* Next, check if checksum matches. */
1325 if (l->l_info [VALIDX(DT_CHECKSUM)] == NULL
1326 || l->l_info [VALIDX(DT_CHECKSUM)]->d_un.d_val
1327 != liblist->l_checksum)
1328 break;
1330 if (l->l_info [VALIDX(DT_GNU_PRELINKED)] == NULL
1331 || l->l_info [VALIDX(DT_GNU_PRELINKED)]->d_un.d_val
1332 != liblist->l_time_stamp)
1333 break;
1335 if (! _dl_name_match_p (strtab + liblist->l_name, l))
1336 break;
1338 ++liblist;
1342 if (r_list == r_listend && liblist == liblistend)
1343 prelinked = true;
1345 if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_LIBS, 0))
1346 _dl_printf ("\nprelink checking: %s\n", prelinked ? "ok" : "failed");
1349 if (prelinked)
1351 if (GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)] != NULL)
1353 ElfW(Rela) *conflict, *conflictend;
1354 #ifndef HP_TIMING_NONAVAIL
1355 hp_timing_t start;
1356 hp_timing_t stop;
1357 #endif
1359 HP_TIMING_NOW (start);
1360 assert (GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)] != NULL);
1361 conflict = (ElfW(Rela) *)
1362 GL(dl_loaded)->l_info [ADDRIDX (DT_GNU_CONFLICT)]->d_un.d_ptr;
1363 conflictend = (ElfW(Rela) *)
1364 ((char *) conflict
1365 + GL(dl_loaded)->l_info [VALIDX (DT_GNU_CONFLICTSZ)]->d_un.d_val);
1366 _dl_resolve_conflicts (GL(dl_loaded), conflict, conflictend);
1367 HP_TIMING_NOW (stop);
1368 HP_TIMING_DIFF (relocate_time, start, stop);
1371 _dl_sysdep_start_cleanup ();
1373 else
1375 /* Now we have all the objects loaded. Relocate them all except for
1376 the dynamic linker itself. We do this in reverse order so that copy
1377 relocs of earlier objects overwrite the data written by later
1378 objects. We do not re-relocate the dynamic linker itself in this
1379 loop because that could result in the GOT entries for functions we
1380 call being changed, and that would break us. It is safe to relocate
1381 the dynamic linker out of order because it has no copy relocs (we
1382 know that because it is self-contained). */
1384 struct link_map *l;
1385 int consider_profiling = GL(dl_profile) != NULL;
1386 #ifndef HP_TIMING_NONAVAIL
1387 hp_timing_t start;
1388 hp_timing_t stop;
1389 hp_timing_t add;
1390 #endif
1392 /* If we are profiling we also must do lazy reloaction. */
1393 GL(dl_lazy) |= consider_profiling;
1395 l = GL(dl_loaded);
1396 while (l->l_next)
1397 l = l->l_next;
1399 HP_TIMING_NOW (start);
1402 /* While we are at it, help the memory handling a bit. We have to
1403 mark some data structures as allocated with the fake malloc()
1404 implementation in ld.so. */
1405 struct libname_list *lnp = l->l_libname->next;
1407 while (__builtin_expect (lnp != NULL, 0))
1409 lnp->dont_free = 1;
1410 lnp = lnp->next;
1413 if (l != &GL(dl_rtld_map))
1414 INTUSE(_dl_relocate_object) (l, l->l_scope, GL(dl_lazy),
1415 consider_profiling);
1417 l = l->l_prev;
1419 while (l);
1420 HP_TIMING_NOW (stop);
1422 HP_TIMING_DIFF (relocate_time, start, stop);
1424 /* Do any necessary cleanups for the startup OS interface code.
1425 We do these now so that no calls are made after rtld re-relocation
1426 which might be resolved to different functions than we expect.
1427 We cannot do this before relocating the other objects because
1428 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
1429 _dl_sysdep_start_cleanup ();
1431 /* Now enable profiling if needed. Like the previous call,
1432 this has to go here because the calls it makes should use the
1433 rtld versions of the functions (particularly calloc()), but it
1434 needs to have _dl_profile_map set up by the relocator. */
1435 if (__builtin_expect (GL(dl_profile_map) != NULL, 0))
1436 /* We must prepare the profiling. */
1437 INTUSE(_dl_start_profile) (GL(dl_profile_map), GL(dl_profile_output));
1439 if (GL(dl_rtld_map).l_opencount > 1)
1441 /* There was an explicit ref to the dynamic linker as a shared lib.
1442 Re-relocate ourselves with user-controlled symbol definitions. */
1443 HP_TIMING_NOW (start);
1444 INTUSE(_dl_relocate_object) (&GL(dl_rtld_map), GL(dl_loaded)->l_scope,
1445 0, 0);
1446 HP_TIMING_NOW (stop);
1447 HP_TIMING_DIFF (add, start, stop);
1448 HP_TIMING_ACCUM_NT (relocate_time, add);
1452 /* Now set up the variable which helps the assembler startup code. */
1453 GL(dl_main_searchlist) = &GL(dl_loaded)->l_searchlist;
1454 GL(dl_global_scope)[0] = &GL(dl_loaded)->l_searchlist;
1456 /* Save the information about the original global scope list since
1457 we need it in the memory handling later. */
1458 GL(dl_initial_searchlist) = *GL(dl_main_searchlist);
1460 #ifdef USE_TLS
1461 # ifndef SHARED
1462 if (GL(dl_tls_max_dtv_idx) > 0)
1463 # endif
1465 /* Now that we have completed relocation, the initializer data
1466 for the TLS blocks has its final values and we can copy them
1467 into the main thread's TLS area, which we allocated above. */
1468 _dl_allocate_tls_init (tcbp);
1470 /* And finally install it for the main thread. */
1471 TLS_INIT_TP (tcbp);
1473 #endif
1476 /* Initialize _r_debug. */
1477 struct r_debug *r = _dl_debug_initialize (GL(dl_rtld_map).l_addr);
1478 struct link_map *l;
1480 l = GL(dl_loaded);
1482 #ifdef ELF_MACHINE_DEBUG_SETUP
1484 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
1486 ELF_MACHINE_DEBUG_SETUP (l, r);
1487 ELF_MACHINE_DEBUG_SETUP (&GL(dl_rtld_map), r);
1489 #else
1491 if (l->l_info[DT_DEBUG] != NULL)
1492 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
1493 with the run-time address of the r_debug structure */
1494 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1496 /* Fill in the pointer in the dynamic linker's own dynamic section, in
1497 case you run gdb on the dynamic linker directly. */
1498 if (GL(dl_rtld_map).l_info[DT_DEBUG] != NULL)
1499 GL(dl_rtld_map).l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
1501 #endif
1503 /* Notify the debugger that all objects are now mapped in. */
1504 r->r_state = RT_ADD;
1505 INTUSE(_dl_debug_state) ();
1508 #ifndef MAP_COPY
1509 /* We must munmap() the cache file. */
1510 INTUSE(_dl_unload_cache) ();
1511 #endif
1513 /* Once we return, _dl_sysdep_start will invoke
1514 the DT_INIT functions and then *USER_ENTRY. */
1517 /* This is a little helper function for resolving symbols while
1518 tracing the binary. */
1519 static void
1520 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
1521 const char *errstring)
1523 if (objname[0] == '\0')
1524 objname = rtld_progname ?: "<main program>";
1525 _dl_error_printf ("%s (%s)\n", errstring, objname);
1528 /* This is a little helper function for resolving symbols while
1529 tracing the binary. */
1530 static void
1531 print_missing_version (int errcode __attribute__ ((unused)),
1532 const char *objname, const char *errstring)
1534 _dl_error_printf ("%s: %s: %s\n", rtld_progname ?: "<program name unknown>",
1535 objname, errstring);
1538 /* Nonzero if any of the debugging options is enabled. */
1539 static int any_debug;
1541 /* Process the string given as the parameter which explains which debugging
1542 options are enabled. */
1543 static void
1544 process_dl_debug (const char *dl_debug)
1546 /* When adding new entries make sure that the maximal length of a name
1547 is correctly handled in the LD_DEBUG_HELP code below. */
1548 static const struct
1550 unsigned char len;
1551 const char name[10];
1552 const char helptext[41];
1553 unsigned short int mask;
1554 } debopts[] =
1556 #define LEN_AND_STR(str) sizeof (str) - 1, str
1557 { LEN_AND_STR ("libs"), "display library search paths",
1558 DL_DEBUG_LIBS | DL_DEBUG_IMPCALLS },
1559 { LEN_AND_STR ("reloc"), "display relocation processing",
1560 DL_DEBUG_RELOC | DL_DEBUG_IMPCALLS },
1561 { LEN_AND_STR ("files"), "display progress for input file",
1562 DL_DEBUG_FILES | DL_DEBUG_IMPCALLS },
1563 { LEN_AND_STR ("symbols"), "display symbol table processing",
1564 DL_DEBUG_SYMBOLS | DL_DEBUG_IMPCALLS },
1565 { LEN_AND_STR ("bindings"), "display information about symbol binding",
1566 DL_DEBUG_BINDINGS | DL_DEBUG_IMPCALLS },
1567 { LEN_AND_STR ("versions"), "display version dependencies",
1568 DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1569 { LEN_AND_STR ("all"), "all previous options combined",
1570 DL_DEBUG_LIBS | DL_DEBUG_RELOC | DL_DEBUG_FILES | DL_DEBUG_SYMBOLS
1571 | DL_DEBUG_BINDINGS | DL_DEBUG_VERSIONS | DL_DEBUG_IMPCALLS },
1572 { LEN_AND_STR ("statistics"), "display relocation statistics",
1573 DL_DEBUG_STATISTICS },
1574 { LEN_AND_STR ("help"), "display this help message and exit",
1575 DL_DEBUG_HELP },
1577 #define ndebopts (sizeof (debopts) / sizeof (debopts[0]))
1579 /* Skip separating white spaces and commas. */
1580 while (*dl_debug != '\0')
1582 if (*dl_debug != ' ' && *dl_debug != ',' && *dl_debug != ':')
1584 size_t cnt;
1585 size_t len = 1;
1587 while (dl_debug[len] != '\0' && dl_debug[len] != ' '
1588 && dl_debug[len] != ',' && dl_debug[len] != ':')
1589 ++len;
1591 for (cnt = 0; cnt < ndebopts; ++cnt)
1592 if (debopts[cnt].len == len
1593 && memcmp (dl_debug, debopts[cnt].name, len) == 0)
1595 GL(dl_debug_mask) |= debopts[cnt].mask;
1596 any_debug = 1;
1597 break;
1600 if (cnt == ndebopts)
1602 /* Display a warning and skip everything until next
1603 separator. */
1604 char *copy = strndupa (dl_debug, len);
1605 _dl_error_printf ("\
1606 warning: debug option `%s' unknown; try LD_DEBUG=help\n", copy);
1609 dl_debug += len;
1610 continue;
1613 ++dl_debug;
1616 if (GL(dl_debug_mask) & DL_DEBUG_HELP)
1618 size_t cnt;
1620 _dl_printf ("\
1621 Valid options for the LD_DEBUG environment variable are:\n\n");
1623 for (cnt = 0; cnt < ndebopts; ++cnt)
1624 _dl_printf (" %.*s%s%s\n", debopts[cnt].len, debopts[cnt].name,
1625 " " + debopts[cnt].len - 3,
1626 debopts[cnt].helptext);
1628 _dl_printf ("\n\
1629 To direct the debugging output into a file instead of standard output\n\
1630 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n");
1631 _exit (0);
1635 /* Process all environments variables the dynamic linker must recognize.
1636 Since all of them start with `LD_' we are a bit smarter while finding
1637 all the entries. */
1638 extern char **_environ attribute_hidden;
1641 static void
1642 process_envvars (enum mode *modep)
1644 char **runp = _environ;
1645 char *envline;
1646 enum mode mode = normal;
1647 char *debug_output = NULL;
1649 /* This is the default place for profiling data file. */
1650 GL(dl_profile_output)
1651 = &"/var/tmp\0/var/profile"[INTUSE(__libc_enable_secure) ? 9 : 0];
1653 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
1655 size_t len = 0;
1657 while (envline[len] != '\0' && envline[len] != '=')
1658 ++len;
1660 if (envline[len] != '=')
1661 /* This is a "LD_" variable at the end of the string without
1662 a '=' character. Ignore it since otherwise we will access
1663 invalid memory below. */
1664 continue;
1666 switch (len)
1668 case 4:
1669 /* Warning level, verbose or not. */
1670 if (memcmp (envline, "WARN", 4) == 0)
1671 GL(dl_verbose) = envline[5] != '\0';
1672 break;
1674 case 5:
1675 /* Debugging of the dynamic linker? */
1676 if (memcmp (envline, "DEBUG", 5) == 0)
1677 process_dl_debug (&envline[6]);
1678 break;
1680 case 7:
1681 /* Print information about versions. */
1682 if (memcmp (envline, "VERBOSE", 7) == 0)
1684 version_info = envline[8] != '\0';
1685 break;
1688 /* List of objects to be preloaded. */
1689 if (memcmp (envline, "PRELOAD", 7) == 0)
1691 preloadlist = &envline[8];
1692 break;
1695 /* Which shared object shall be profiled. */
1696 if (memcmp (envline, "PROFILE", 7) == 0 && envline[8] != '\0')
1697 GL(dl_profile) = &envline[8];
1698 break;
1700 case 8:
1701 /* Do we bind early? */
1702 if (memcmp (envline, "BIND_NOW", 8) == 0)
1704 GL(dl_lazy) = envline[9] == '\0';
1705 break;
1707 if (memcmp (envline, "BIND_NOT", 8) == 0)
1708 GL(dl_bind_not) = envline[9] != '\0';
1709 break;
1711 case 9:
1712 /* Test whether we want to see the content of the auxiliary
1713 array passed up from the kernel. */
1714 if (memcmp (envline, "SHOW_AUXV", 9) == 0)
1715 _dl_show_auxv ();
1716 break;
1718 case 10:
1719 /* Mask for the important hardware capabilities. */
1720 if (memcmp (envline, "HWCAP_MASK", 10) == 0)
1721 GL(dl_hwcap_mask) = __strtoul_internal (&envline[11], NULL, 0, 0);
1722 break;
1724 case 11:
1725 /* Path where the binary is found. */
1726 if (!INTUSE(__libc_enable_secure)
1727 && memcmp (envline, "ORIGIN_PATH", 11) == 0)
1728 GL(dl_origin_path) = &envline[12];
1729 break;
1731 case 12:
1732 /* The library search path. */
1733 if (memcmp (envline, "LIBRARY_PATH", 12) == 0)
1735 library_path = &envline[13];
1736 break;
1739 /* Where to place the profiling data file. */
1740 if (memcmp (envline, "DEBUG_OUTPUT", 12) == 0)
1742 debug_output = &envline[13];
1743 break;
1746 if (memcmp (envline, "DYNAMIC_WEAK", 12) == 0)
1747 GL(dl_dynamic_weak) = 1;
1748 break;
1750 case 14:
1751 /* Where to place the profiling data file. */
1752 if (!INTUSE(__libc_enable_secure)
1753 && memcmp (envline, "PROFILE_OUTPUT", 14) == 0
1754 && envline[15] != '\0')
1755 GL(dl_profile_output) = &envline[15];
1756 break;
1758 case 16:
1759 /* The mode of the dynamic linker can be set. */
1760 if (memcmp (envline, "TRACE_PRELINKING", 16) == 0)
1762 mode = trace;
1763 GL(dl_verbose) = 1;
1764 GL(dl_debug_mask) |= DL_DEBUG_PRELINK;
1765 GL(dl_trace_prelink) = &envline[17];
1767 break;
1769 case 20:
1770 /* The mode of the dynamic linker can be set. */
1771 if (memcmp (envline, "TRACE_LOADED_OBJECTS", 20) == 0)
1772 mode = trace;
1773 break;
1775 /* We might have some extra environment variable to handle. This
1776 is tricky due to the pre-processing of the length of the name
1777 in the switch statement here. The code here assumes that added
1778 environment variables have a different length. */
1779 #ifdef EXTRA_LD_ENVVARS
1780 EXTRA_LD_ENVVARS
1781 #endif
1785 /* The caller wants this information. */
1786 *modep = mode;
1788 /* Extra security for SUID binaries. Remove all dangerous environment
1789 variables. */
1790 if (__builtin_expect (INTUSE(__libc_enable_secure), 0))
1792 static const char unsecure_envvars[] =
1793 #ifdef EXTRA_UNSECURE_ENVVARS
1794 EXTRA_UNSECURE_ENVVARS
1795 #endif
1796 UNSECURE_ENVVARS;
1797 const char *nextp;
1799 nextp = unsecure_envvars;
1802 unsetenv (nextp);
1803 /* We could use rawmemchr but this need not be fast. */
1804 nextp = (char *) (strchr) (nextp, '\0') + 1;
1806 while (*nextp != '\0');
1808 if (__access ("/etc/suid-debug", F_OK) != 0)
1809 unsetenv ("MALLOC_CHECK_");
1811 /* If we have to run the dynamic linker in debugging mode and the
1812 LD_DEBUG_OUTPUT environment variable is given, we write the debug
1813 messages to this file. */
1814 else if (any_debug && debug_output != NULL)
1816 #ifdef O_NOFOLLOW
1817 const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW;
1818 #else
1819 const int flags = O_WRONLY | O_APPEND | O_CREAT;
1820 #endif
1821 size_t name_len = strlen (debug_output);
1822 char buf[name_len + 12];
1823 char *startp;
1825 buf[name_len + 11] = '\0';
1826 startp = _itoa (__getpid (), &buf[name_len + 11], 10, 0);
1827 *--startp = '.';
1828 startp = memcpy (startp - name_len, debug_output, name_len);
1830 GL(dl_debug_fd) = __open (startp, flags, DEFFILEMODE);
1831 if (GL(dl_debug_fd) == -1)
1832 /* We use standard output if opening the file failed. */
1833 GL(dl_debug_fd) = STDOUT_FILENO;
1838 /* Print the various times we collected. */
1839 static void
1840 print_statistics (void)
1842 #ifndef HP_TIMING_NONAVAIL
1843 char buf[200];
1844 char *cp;
1845 char *wp;
1847 /* Total time rtld used. */
1848 if (HP_TIMING_AVAIL)
1850 HP_TIMING_PRINT (buf, sizeof (buf), rtld_total_time);
1851 INTUSE(_dl_debug_printf) ("\nruntime linker statistics:\n"
1852 " total startup time in dynamic loader: %s\n",
1853 buf);
1856 /* Print relocation statistics. */
1857 if (HP_TIMING_AVAIL)
1859 char pbuf[30];
1860 HP_TIMING_PRINT (buf, sizeof (buf), relocate_time);
1861 cp = _itoa ((1000ULL * relocate_time) / rtld_total_time,
1862 pbuf + sizeof (pbuf), 10, 0);
1863 wp = pbuf;
1864 switch (pbuf + sizeof (pbuf) - cp)
1866 case 3:
1867 *wp++ = *cp++;
1868 case 2:
1869 *wp++ = *cp++;
1870 case 1:
1871 *wp++ = '.';
1872 *wp++ = *cp++;
1874 *wp = '\0';
1875 INTUSE(_dl_debug_printf) ("\
1876 time needed for relocation: %s (%s%%)\n",
1877 buf, pbuf);
1879 #endif
1880 INTUSE(_dl_debug_printf) (" number of relocations: %lu\n",
1881 GL(dl_num_relocations));
1882 INTUSE(_dl_debug_printf) (" number of relocations from cache: %lu\n",
1883 GL(dl_num_cache_relocations));
1885 #ifndef HP_TIMING_NONAVAIL
1886 /* Time spend while loading the object and the dependencies. */
1887 if (HP_TIMING_AVAIL)
1889 char pbuf[30];
1890 HP_TIMING_PRINT (buf, sizeof (buf), load_time);
1891 cp = _itoa ((1000ULL * load_time) / rtld_total_time,
1892 pbuf + sizeof (pbuf), 10, 0);
1893 wp = pbuf;
1894 switch (pbuf + sizeof (pbuf) - cp)
1896 case 3:
1897 *wp++ = *cp++;
1898 case 2:
1899 *wp++ = *cp++;
1900 case 1:
1901 *wp++ = '.';
1902 *wp++ = *cp++;
1904 *wp = '\0';
1905 INTUSE(_dl_debug_printf) ("\
1906 time needed to load objects: %s (%s%%)\n",
1907 buf, pbuf);
1909 #endif