Update.
[glibc.git] / elf / rtld.c
blob38c7b051b183a4eaa5f7705a16c597e364fece26
1 /* Run time dynamic linker.
2 Copyright (C) 1995, 1996, 1997, 1998 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 Library General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 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 Library General Public License for more details.
15 You should have received a copy of the GNU Library General Public
16 License along with the GNU C Library; see the file COPYING.LIB. If not,
17 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
20 #include <fcntl.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <sys/mman.h> /* Check if MAP_ANON is defined. */
25 #include <elf/ldsodefs.h>
26 #include <stdio-common/_itoa.h>
27 #include <entry.h>
28 #include <fpu_control.h>
29 #include "dynamic-link.h"
30 #include "dl-librecon.h"
32 #include <assert.h>
34 /* System-specific function to do initial startup for the dynamic linker.
35 After this, file access calls and getenv must work. This is responsible
36 for setting __libc_enable_secure if we need to be secure (e.g. setuid),
37 and for setting _dl_argc and _dl_argv, and then calling _dl_main. */
38 extern ElfW(Addr) _dl_sysdep_start (void **start_argptr,
39 void (*dl_main) (const ElfW(Phdr) *phdr,
40 ElfW(Half) phent,
41 ElfW(Addr) *user_entry));
42 extern void _dl_sysdep_start_cleanup (void);
44 /* This function is used to unload the cache file if necessary. */
45 extern void _dl_unload_cache (void);
47 /* System-dependent function to read a file's whole contents
48 in the most convenient manner available. */
49 extern void *_dl_sysdep_read_whole_file (const char *filename,
50 size_t *filesize_ptr,
51 int mmap_prot);
53 /* Helper function to handle errors while resolving symbols. */
54 static void print_unresolved (int errcode, const char *objname,
55 const char *errsting);
57 /* Helper function to handle errors when a version is missing. */
58 static void print_missing_version (int errcode, const char *objname,
59 const char *errsting);
62 /* This is a list of all the modes the dynamic loader can be in. */
63 enum mode { normal, list, verify, trace };
65 /* Process all environments variables the dynamic linker must recognize.
66 Since all of them start with `LD_' we are a bit smarter while finding
67 all the entries. */
68 static void process_envvars (enum mode *modep, int *lazyp);
70 int _dl_argc;
71 char **_dl_argv;
72 unsigned int _dl_skip_args; /* Nonzero if we were run directly. */
73 int _dl_verbose;
74 const char *_dl_platform;
75 size_t _dl_platformlen;
76 unsigned long _dl_hwcap;
77 fpu_control_t _dl_fpu_control = _FPU_DEFAULT;
78 struct r_search_path *_dl_search_paths;
79 const char *_dl_profile;
80 const char *_dl_profile_output;
81 struct link_map *_dl_profile_map;
82 int _dl_debug_libs;
83 int _dl_debug_impcalls;
84 int _dl_debug_bindings;
85 int _dl_debug_symbols;
86 int _dl_debug_versions;
87 int _dl_debug_reloc;
88 int _dl_debug_files;
89 const char *_dl_inhibit_rpath; /* RPATH values which should be
90 ignored. */
91 const char *_dl_origin_path;
93 /* This is a pointer to the map for the main object and through it to
94 all loaded objects. */
95 struct link_map *_dl_loaded;
96 /* Pointer to the l_searchlist element of the link map of the main object. */
97 struct r_scope_elem *_dl_main_searchlist;
98 /* Copy of the content of `_dl_main_searchlist'. */
99 struct r_scope_elem _dl_initial_searchlist;
100 /* Array which is used when looking up in the global scope. */
101 struct r_scope_elem *_dl_global_scope[2];
103 /* Set nonzero during loading and initialization of executable and
104 libraries, cleared before the executable's entry point runs. This
105 must not be initialized to nonzero, because the unused dynamic
106 linker loaded in for libc.so's "ld.so.1" dep will provide the
107 definition seen by libc.so's initializer; that value must be zero,
108 and will be since that dynamic linker's _dl_start and dl_main will
109 never be called. */
110 int _dl_starting_up;
113 static void dl_main (const ElfW(Phdr) *phdr,
114 ElfW(Half) phent,
115 ElfW(Addr) *user_entry);
117 struct link_map _dl_rtld_map;
118 struct libname_list _dl_rtld_libname;
119 struct libname_list _dl_rtld_libname2;
121 #ifdef RTLD_START
122 RTLD_START
123 #else
124 #error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
125 #endif
127 static ElfW(Addr)
128 _dl_start (void *arg)
130 struct link_map bootstrap_map;
132 /* This #define produces dynamic linking inline functions for
133 bootstrap relocation instead of general-purpose relocation. */
134 #define RTLD_BOOTSTRAP
135 #define RESOLVE(sym, version, flags) \
136 ((*(sym))->st_shndx == SHN_UNDEF ? 0 : bootstrap_map.l_addr)
137 #include "dynamic-link.h"
139 /* Figure out the run-time load address of the dynamic linker itself. */
140 bootstrap_map.l_addr = elf_machine_load_address ();
142 /* Read our own dynamic section and fill in the info array. */
143 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
144 elf_get_dynamic_info (bootstrap_map.l_ld, bootstrap_map.l_info);
146 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
147 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
148 #endif
150 /* Relocate ourselves so we can do normal function calls and
151 data access using the global offset table. */
153 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
154 /* Please note that we don't allow profiling of this object and
155 therefore need not test whether we have to allocate the array
156 for the relocation results (as done in dl-reloc.c). */
158 /* Now life is sane; we can call functions and access global data.
159 Set up to use the operating system facilities, and find out from
160 the operating system's program loader where to find the program
161 header table in core. */
163 /* Transfer data about ourselves to the permanent link_map structure. */
164 _dl_rtld_map.l_addr = bootstrap_map.l_addr;
165 _dl_rtld_map.l_ld = bootstrap_map.l_ld;
166 _dl_rtld_map.l_opencount = 1;
167 memcpy (_dl_rtld_map.l_info, bootstrap_map.l_info,
168 sizeof _dl_rtld_map.l_info);
169 _dl_setup_hash (&_dl_rtld_map);
171 /* Don't bother trying to work out how ld.so is mapped in memory. */
172 _dl_rtld_map.l_map_start = ~0;
173 _dl_rtld_map.l_map_end = ~0;
175 /* Call the OS-dependent function to set up life so we can do things like
176 file access. It will call `dl_main' (below) to do all the real work
177 of the dynamic linker, and then unwind our frame and run the user
178 entry point on the same stack we entered on. */
179 return _dl_sysdep_start (arg, &dl_main);
182 /* Now life is peachy; we can do all normal operations.
183 On to the real work. */
185 void ENTRY_POINT (void);
187 /* Some helper functions. */
189 /* Arguments to relocate_doit. */
190 struct relocate_args
192 struct link_map *l;
193 int lazy;
196 struct map_args
198 /* Argument to map_doit. */
199 char *str;
200 /* Return value of map_doit. */
201 struct link_map *main_map;
204 /* Arguments to version_check_doit. */
205 struct version_check_args
207 int doexit;
210 static void
211 relocate_doit (void *a)
213 struct relocate_args *args = (struct relocate_args *) a;
215 _dl_relocate_object (args->l, args->l->l_scope,
216 args->lazy, 0);
219 static void
220 map_doit (void *a)
222 struct map_args *args = (struct map_args *) a;
223 args->main_map = _dl_map_object (NULL, args->str, 0, lt_library, 0);
226 static void
227 version_check_doit (void *a)
229 struct version_check_args *args = (struct version_check_args *) a;
230 if (_dl_check_all_versions (_dl_loaded, 1) && args->doexit)
231 /* We cannot start the application. Abort now. */
232 _exit (1);
236 static inline struct link_map *
237 find_needed (const char *name)
239 unsigned int n = _dl_loaded->l_searchlist.r_nlist;
241 while (n-- > 0)
242 if (_dl_name_match_p (name, _dl_loaded->l_searchlist.r_list[n]))
243 return _dl_loaded->l_searchlist.r_list[n];
245 /* Should never happen. */
246 return NULL;
249 static int
250 match_version (const char *string, struct link_map *map)
252 const char *strtab = (const char *) (map->l_addr
253 + map->l_info[DT_STRTAB]->d_un.d_ptr);
254 ElfW(Verdef) *def;
256 #define VERDEFTAG (DT_NUM + DT_PROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
257 if (map->l_info[VERDEFTAG] == NULL)
258 /* The file has no symbol versioning. */
259 return 0;
261 def = (ElfW(Verdef) *) ((char *) map->l_addr
262 + map->l_info[VERDEFTAG]->d_un.d_ptr);
263 while (1)
265 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
267 /* Compare the version strings. */
268 if (strcmp (string, strtab + aux->vda_name) == 0)
269 /* Bingo! */
270 return 1;
272 /* If no more definitions we failed to find what we want. */
273 if (def->vd_next == 0)
274 break;
276 /* Next definition. */
277 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
280 return 0;
283 static const char *library_path; /* The library search path. */
284 static const char *preloadlist; /* The list preloaded objects. */
285 static int version_info; /* Nonzero if information about
286 versions has to be printed. */
288 static void
289 dl_main (const ElfW(Phdr) *phdr,
290 ElfW(Half) phent,
291 ElfW(Addr) *user_entry)
293 const ElfW(Phdr) *ph;
294 int lazy;
295 enum mode mode;
296 struct link_map **preloads;
297 unsigned int npreloads;
298 size_t file_size;
299 char *file;
300 int has_interp = 0;
301 unsigned int i;
302 int paths_initialized = 0;
304 /* Process the environment variable which control the behaviour. */
305 process_envvars (&mode, &lazy);
307 /* Set up a flag which tells we are just starting. */
308 _dl_starting_up = 1;
310 if (*user_entry == (ElfW(Addr)) &ENTRY_POINT)
312 /* Ho ho. We are not the program interpreter! We are the program
313 itself! This means someone ran ld.so as a command. Well, that
314 might be convenient to do sometimes. We support it by
315 interpreting the args like this:
317 ld.so PROGRAM ARGS...
319 The first argument is the name of a file containing an ELF
320 executable we will load and run with the following arguments.
321 To simplify life here, PROGRAM is searched for using the
322 normal rules for shared objects, rather than $PATH or anything
323 like that. We just load it and use its entry point; we don't
324 pay attention to its PT_INTERP command (we are the interpreter
325 ourselves). This is an easy way to test a new ld.so before
326 installing it. */
328 /* Note the place where the dynamic linker actually came from. */
329 _dl_rtld_map.l_name = _dl_argv[0];
331 while (_dl_argc > 1)
332 if (! strcmp (_dl_argv[1], "--list"))
334 mode = list;
335 lazy = -1; /* This means do no dependency analysis. */
337 ++_dl_skip_args;
338 --_dl_argc;
339 ++_dl_argv;
341 else if (! strcmp (_dl_argv[1], "--verify"))
343 mode = verify;
345 ++_dl_skip_args;
346 --_dl_argc;
347 ++_dl_argv;
349 else if (! strcmp (_dl_argv[1], "--library-path") && _dl_argc > 2)
351 library_path = _dl_argv[2];
353 _dl_skip_args += 2;
354 _dl_argc -= 2;
355 _dl_argv += 2;
357 else if (! strcmp (_dl_argv[1], "--inhibit-rpath") && _dl_argc > 2)
359 _dl_inhibit_rpath = _dl_argv[2];
361 _dl_skip_args += 2;
362 _dl_argc -= 2;
363 _dl_argv += 2;
365 else
366 break;
368 /* If we have no further argument the program was called incorrectly.
369 Grant the user some education. */
370 if (_dl_argc < 2)
371 _dl_sysdep_fatal ("\
372 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
373 You have invoked `ld.so', the helper program for shared library executables.\n\
374 This program usually lives in the file `/lib/ld.so', and special directives\n\
375 in executable files using ELF shared libraries tell the system's program\n\
376 loader to load the helper program from this file. This helper program loads\n\
377 the shared libraries needed by the program executable, prepares the program\n\
378 to run, and runs it. You may invoke this helper program directly from the\n\
379 command line to load and run an ELF executable file; this is like executing\n\
380 that file itself, but always uses this helper program from the file you\n\
381 specified, instead of the helper program file specified in the executable\n\
382 file you run. This is mostly of use for maintainers to test new versions\n\
383 of this helper program; chances are you did not intend to run this program.\n\
385 --list list all dependencies and how they are resolved\n\
386 --verify verify that given object really is a dynamically linked\n\
387 object we get handle\n\
388 --library-path PATH use given PATH instead of content of the environment\n\
389 variable LD_LIBRARY_PATH\n\
390 --inhibit-rpath LIST ignore RPATH information in object names in LIST\n",
391 NULL);
393 ++_dl_skip_args;
394 --_dl_argc;
395 ++_dl_argv;
397 /* Initialize the data structures for the search paths for shared
398 objects. */
399 _dl_init_paths (library_path);
400 paths_initialized = 1;
402 if (__builtin_expect (mode, normal) == verify)
404 char *err_str = NULL;
405 struct map_args args;
407 args.str = _dl_argv[0];
408 (void) _dl_catch_error (&err_str, map_doit, &args);
409 if (err_str != NULL)
411 free (err_str);
412 _exit (EXIT_FAILURE);
415 else
416 _dl_map_object (NULL, _dl_argv[0], 0, lt_library, 0);
418 phdr = _dl_loaded->l_phdr;
419 phent = _dl_loaded->l_phnum;
420 /* We overwrite here a pointer to a malloc()ed string. But since
421 the malloc() implementation used at this point is the dummy
422 implementations which has no real free() function it does not
423 makes sense to free the old string first. */
424 _dl_loaded->l_name = (char *) "";
425 *user_entry = _dl_loaded->l_entry;
427 else
429 /* Create a link_map for the executable itself.
430 This will be what dlopen on "" returns. */
431 _dl_new_object ((char *) "", "", lt_executable, NULL);
432 if (_dl_loaded == NULL)
433 _dl_sysdep_fatal ("cannot allocate memory for link map\n", NULL);
434 _dl_loaded->l_phdr = phdr;
435 _dl_loaded->l_phnum = phent;
436 _dl_loaded->l_entry = *user_entry;
437 _dl_loaded->l_opencount = 1;
439 /* We delay initializing the path structure until we got the dynamic
440 information for the program. */
443 /* It is not safe to load stuff after the main program. */
444 _dl_loaded->l_map_end = ~0;
445 /* Perhaps the executable has no PT_LOAD header entries at all. */
446 _dl_loaded->l_map_start = ~0;
448 /* Scan the program header table for the dynamic section. */
449 for (ph = phdr; ph < &phdr[phent]; ++ph)
450 switch (ph->p_type)
452 case PT_PHDR:
453 /* Find out the load address. */
454 _dl_loaded->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
455 break;
456 case PT_DYNAMIC:
457 /* This tells us where to find the dynamic section,
458 which tells us everything we need to do. */
459 _dl_loaded->l_ld = (void *) _dl_loaded->l_addr + ph->p_vaddr;
460 break;
461 case PT_INTERP:
462 /* This "interpreter segment" was used by the program loader to
463 find the program interpreter, which is this program itself, the
464 dynamic linker. We note what name finds us, so that a future
465 dlopen call or DT_NEEDED entry, for something that wants to link
466 against the dynamic linker as a shared library, will know that
467 the shared object is already loaded. */
468 _dl_rtld_libname.name = ((const char *) _dl_loaded->l_addr
469 + ph->p_vaddr);
470 _dl_rtld_libname.next = NULL;
471 _dl_rtld_map.l_libname = &_dl_rtld_libname;
473 /* Ordinarilly, we would get additional names for the loader from
474 our DT_SONAME. This can't happen if we were actually linked as
475 a static executable (detect this case when we have no DYNAMIC).
476 If so, assume the filename component of the interpreter path to
477 be our SONAME, and add it to our name list. */
478 if (_dl_rtld_map.l_ld == NULL)
480 char *p = strrchr (_dl_rtld_libname.name, '/');
481 if (p)
483 _dl_rtld_libname2.name = p+1;
484 _dl_rtld_libname2.next = NULL;
485 _dl_rtld_libname.next = &_dl_rtld_libname2;
489 has_interp = 1;
490 break;
491 case PT_LOAD:
492 /* Remember where the main program starts in memory. */
494 ElfW(Addr) mapstart;
495 mapstart = _dl_loaded->l_addr + (ph->p_vaddr & ~(ph->p_align - 1));
496 if (_dl_loaded->l_map_start > mapstart)
497 _dl_loaded->l_map_start = mapstart;
499 break;
501 if (! _dl_rtld_map.l_libname && _dl_rtld_map.l_name)
503 /* We were invoked directly, so the program might not have a
504 PT_INTERP. */
505 _dl_rtld_libname.name = _dl_rtld_map.l_name;
506 _dl_rtld_libname.next = NULL;
507 _dl_rtld_map.l_libname = &_dl_rtld_libname;
509 else
510 assert (_dl_rtld_map.l_libname); /* How else did we get here? */
512 /* Extract the contents of the dynamic section for easy access. */
513 elf_get_dynamic_info (_dl_loaded->l_ld, _dl_loaded->l_info);
514 if (_dl_loaded->l_info[DT_HASH])
515 /* Set up our cache of pointers into the hash table. */
516 _dl_setup_hash (_dl_loaded);
518 if (__builtin_expect (mode, normal) == verify)
520 /* We were called just to verify that this is a dynamic
521 executable using us as the program interpreter. Exit with an
522 error if we were not able to load the binary or no interpreter
523 is specified (i.e., this is no dynamically linked binary. */
524 if (_dl_loaded->l_ld == NULL)
525 _exit (1);
527 /* We allow here some platform specific code. */
528 #ifdef DISTINGUISH_LIB_VERSIONS
529 DISTINGUISH_LIB_VERSIONS;
530 #endif
531 _exit (has_interp ? 0 : 2);
534 if (! paths_initialized)
535 /* Initialize the data structures for the search paths for shared
536 objects. */
537 _dl_init_paths (library_path);
539 /* Put the link_map for ourselves on the chain so it can be found by
540 name. Note that at this point the global chain of link maps contains
541 exactly one element, which is pointed to by _dl_loaded. */
542 if (! _dl_rtld_map.l_name)
543 /* If not invoked directly, the dynamic linker shared object file was
544 found by the PT_INTERP name. */
545 _dl_rtld_map.l_name = (char *) _dl_rtld_map.l_libname->name;
546 _dl_rtld_map.l_type = lt_library;
547 _dl_loaded->l_next = &_dl_rtld_map;
548 _dl_rtld_map.l_prev = _dl_loaded;
550 /* We have two ways to specify objects to preload: via environment
551 variable and via the file /etc/ld.so.preload. The later can also
552 be used when security is enabled. */
553 preloads = NULL;
554 npreloads = 0;
556 if (preloadlist)
558 /* The LD_PRELOAD environment variable gives list of libraries
559 separated by white space or colons that are loaded before the
560 executable's dependencies and prepended to the global scope
561 list. If the binary is running setuid all elements
562 containing a '/' are ignored since it is insecure. */
563 char *list = strdupa (preloadlist);
564 char *p;
565 while ((p = strsep (&list, " :")) != NULL)
566 if (p[0] != '\0'
567 && (! __libc_enable_secure || strchr (p, '/') == NULL))
569 struct link_map *new_map = _dl_map_object (_dl_loaded, p, 1,
570 lt_library, 0);
571 if (new_map->l_opencount == 1)
572 /* It is no duplicate. */
573 ++npreloads;
577 /* Read the contents of the file. */
578 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
579 PROT_READ | PROT_WRITE);
580 if (file)
582 /* Parse the file. It contains names of libraries to be loaded,
583 separated by white spaces or `:'. It may also contain
584 comments introduced by `#'. */
585 char *problem;
586 char *runp;
587 size_t rest;
589 /* Eliminate comments. */
590 runp = file;
591 rest = file_size;
592 while (rest > 0)
594 char *comment = memchr (runp, '#', rest);
595 if (comment == NULL)
596 break;
598 rest -= comment - runp;
600 *comment = ' ';
601 while (--rest > 0 && *++comment != '\n');
604 /* We have one problematic case: if we have a name at the end of
605 the file without a trailing terminating characters, we cannot
606 place the \0. Handle the case separately. */
607 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
608 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
610 problem = &file[file_size];
611 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
612 && problem[-1] != '\n' && problem[-1] != ':')
613 --problem;
615 if (problem > file)
616 problem[-1] = '\0';
618 else
620 problem = NULL;
621 file[file_size - 1] = '\0';
624 if (file != problem)
626 char *p;
627 runp = file;
628 while ((p = strsep (&runp, ": \t\n")) != NULL)
629 if (p[0] != '\0')
631 struct link_map *new_map = _dl_map_object (_dl_loaded, p, 1,
632 lt_library, 0);
633 if (new_map->l_opencount == 1)
634 /* It is no duplicate. */
635 ++npreloads;
639 if (problem != NULL)
641 char *p = strndupa (problem, file_size - (problem - file));
642 struct link_map *new_map = _dl_map_object (_dl_loaded, p, 1,
643 lt_library, 0);
644 if (new_map->l_opencount == 1)
645 /* It is no duplicate. */
646 ++npreloads;
649 /* We don't need the file anymore. */
650 __munmap (file, file_size);
653 if (npreloads != 0)
655 /* Set up PRELOADS with a vector of the preloaded libraries. */
656 struct link_map *l;
657 preloads = __alloca (npreloads * sizeof preloads[0]);
658 l = _dl_rtld_map.l_next; /* End of the chain before preloads. */
659 i = 0;
662 preloads[i++] = l;
663 l = l->l_next;
664 } while (l);
665 assert (i == npreloads);
668 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
669 specified some libraries to load, these are inserted before the actual
670 dependencies in the executable's searchlist for symbol resolution. */
671 _dl_map_object_deps (_dl_loaded, preloads, npreloads, mode == trace, 0);
673 /* Mark all objects as being in the global scope. */
674 for (i = _dl_loaded->l_searchlist.r_nlist; i > 0; )
675 _dl_loaded->l_searchlist.r_list[--i]->l_global = 1;
677 #ifndef MAP_ANON
678 /* We are done mapping things, so close the zero-fill descriptor. */
679 __close (_dl_zerofd);
680 _dl_zerofd = -1;
681 #endif
683 /* Remove _dl_rtld_map from the chain. */
684 _dl_rtld_map.l_prev->l_next = _dl_rtld_map.l_next;
685 if (_dl_rtld_map.l_next)
686 _dl_rtld_map.l_next->l_prev = _dl_rtld_map.l_prev;
688 if (__builtin_expect (_dl_rtld_map.l_opencount, 2) > 1)
690 /* Some DT_NEEDED entry referred to the interpreter object itself, so
691 put it back in the list of visible objects. We insert it into the
692 chain in symbol search order because gdb uses the chain's order as
693 its symbol search order. */
694 i = 1;
695 while (_dl_loaded->l_searchlist.r_list[i] != &_dl_rtld_map)
696 ++i;
697 _dl_rtld_map.l_prev = _dl_loaded->l_searchlist.r_list[i - 1];
698 _dl_rtld_map.l_next = (i + 1 < _dl_loaded->l_searchlist.r_nlist
699 ? _dl_loaded->l_searchlist.r_list[i + 1]
700 : NULL);
701 assert (_dl_rtld_map.l_prev->l_next == _dl_rtld_map.l_next);
702 _dl_rtld_map.l_prev->l_next = &_dl_rtld_map;
703 if (_dl_rtld_map.l_next)
705 assert (_dl_rtld_map.l_next->l_prev == _dl_rtld_map.l_prev);
706 _dl_rtld_map.l_next->l_prev = &_dl_rtld_map;
710 /* Now let us see whether all libraries are available in the
711 versions we need. */
713 struct version_check_args args;
714 args.doexit = mode == normal;
715 _dl_receive_error (print_missing_version, version_check_doit, &args);
718 if (__builtin_expect (mode, normal) != normal)
720 /* We were run just to list the shared libraries. It is
721 important that we do this before real relocation, because the
722 functions we call below for output may no longer work properly
723 after relocation. */
724 if (! _dl_loaded->l_info[DT_NEEDED])
725 _dl_sysdep_message ("\t", "statically linked\n", NULL);
726 else
728 struct link_map *l;
730 for (l = _dl_loaded->l_next; l; l = l->l_next)
731 if (l->l_opencount == 0)
732 /* The library was not found. */
733 _dl_sysdep_message ("\t", l->l_libname->name, " => not found\n",
734 NULL);
735 else
737 char buf[20], *bp;
738 buf[sizeof buf - 1] = '\0';
739 bp = _itoa_word (l->l_addr, &buf[sizeof buf - 1], 16, 0);
740 while ((size_t) (&buf[sizeof buf - 1] - bp)
741 < sizeof l->l_addr * 2)
742 *--bp = '0';
743 _dl_sysdep_message ("\t", l->l_libname->name, " => ",
744 l->l_name, " (0x", bp, ")\n", NULL);
748 if (__builtin_expect (mode, trace) != trace)
749 for (i = 1; i < _dl_argc; ++i)
751 const ElfW(Sym) *ref = NULL;
752 ElfW(Addr) loadbase = _dl_lookup_symbol (_dl_argv[i], &ref,
753 _dl_loaded->l_scope,
754 "argument",
755 ELF_MACHINE_JMP_SLOT);
756 char buf[20], *bp;
757 buf[sizeof buf - 1] = '\0';
758 bp = _itoa_word (ref->st_value, &buf[sizeof buf - 1], 16, 0);
759 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
760 *--bp = '0';
761 _dl_sysdep_message (_dl_argv[i], " found at 0x", bp, NULL);
762 buf[sizeof buf - 1] = '\0';
763 bp = _itoa_word (loadbase, &buf[sizeof buf - 1], 16, 0);
764 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
765 *--bp = '0';
766 _dl_sysdep_message (" in object at 0x", bp, "\n", NULL);
768 else
770 if (lazy >= 0)
772 /* We have to do symbol dependency testing. */
773 struct relocate_args args;
774 struct link_map *l;
776 args.lazy = lazy;
778 l = _dl_loaded;
779 while (l->l_next)
780 l = l->l_next;
783 if (l != &_dl_rtld_map && l->l_opencount > 0)
785 args.l = l;
786 _dl_receive_error (print_unresolved, relocate_doit,
787 &args);
789 l = l->l_prev;
790 } while (l);
793 #define VERNEEDTAG (DT_NUM + DT_PROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
794 if (version_info)
796 /* Print more information. This means here, print information
797 about the versions needed. */
798 int first = 1;
799 struct link_map *map = _dl_loaded;
801 for (map = _dl_loaded; map != NULL; map = map->l_next)
803 const char *strtab;
804 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
805 ElfW(Verneed) *ent;
807 if (dyn == NULL)
808 continue;
810 strtab = (const char *)
811 (map->l_addr + map->l_info[DT_STRTAB]->d_un.d_ptr);
812 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
814 if (first)
816 _dl_sysdep_message ("\n\tVersion information:\n", NULL);
817 first = 0;
820 _dl_sysdep_message ("\t", (map->l_name[0]
821 ? map->l_name : _dl_argv[0]),
822 ":\n", NULL);
824 while (1)
826 ElfW(Vernaux) *aux;
827 struct link_map *needed;
829 needed = find_needed (strtab + ent->vn_file);
830 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
832 while (1)
834 const char *fname = NULL;
836 _dl_sysdep_message ("\t\t",
837 strtab + ent->vn_file,
838 " (", strtab + aux->vna_name,
839 ") ",
840 (aux->vna_flags
841 & VER_FLG_WEAK
842 ? "[WEAK] " : ""),
843 "=> ", NULL);
845 if (needed != NULL
846 && match_version (strtab+aux->vna_name, needed))
847 fname = needed->l_name;
849 _dl_sysdep_message (fname ?: "not found", "\n",
850 NULL);
852 if (aux->vna_next == 0)
853 /* No more symbols. */
854 break;
856 /* Next symbol. */
857 aux = (ElfW(Vernaux) *) ((char *) aux
858 + aux->vna_next);
861 if (ent->vn_next == 0)
862 /* No more dependencies. */
863 break;
865 /* Next dependency. */
866 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
872 _exit (0);
876 /* Now we have all the objects loaded. Relocate them all except for
877 the dynamic linker itself. We do this in reverse order so that copy
878 relocs of earlier objects overwrite the data written by later
879 objects. We do not re-relocate the dynamic linker itself in this
880 loop because that could result in the GOT entries for functions we
881 call being changed, and that would break us. It is safe to relocate
882 the dynamic linker out of order because it has no copy relocs (we
883 know that because it is self-contained). */
885 struct link_map *l;
886 int consider_profiling = _dl_profile != NULL;
888 /* If we are profiling we also must do lazy reloaction. */
889 lazy |= consider_profiling;
891 l = _dl_loaded;
892 while (l->l_next)
893 l = l->l_next;
896 if (l != &_dl_rtld_map)
897 _dl_relocate_object (l, l->l_scope, lazy, consider_profiling);
899 l = l->l_prev;
900 } while (l);
902 /* Do any necessary cleanups for the startup OS interface code.
903 We do these now so that no calls are made after rtld re-relocation
904 which might be resolved to different functions than we expect.
905 We cannot do this before relocating the other objects because
906 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
907 _dl_sysdep_start_cleanup ();
909 if (_dl_rtld_map.l_opencount > 0)
910 /* There was an explicit ref to the dynamic linker as a shared lib.
911 Re-relocate ourselves with user-controlled symbol definitions. */
912 _dl_relocate_object (&_dl_rtld_map, _dl_loaded->l_scope, 0, 0);
915 /* Now set up the variable which helps the assembler startup code. */
916 _dl_main_searchlist = &_dl_loaded->l_searchlist;
917 _dl_global_scope[0] = &_dl_loaded->l_searchlist;
919 /* Safe the information about the original global scope list since
920 we need it in the memory handling later. */
921 _dl_initial_searchlist = *_dl_main_searchlist;
924 /* Initialize _r_debug. */
925 struct r_debug *r = _dl_debug_initialize (_dl_rtld_map.l_addr);
926 struct link_map *l;
928 l = _dl_loaded;
930 #ifdef ELF_MACHINE_DEBUG_SETUP
932 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
934 ELF_MACHINE_DEBUG_SETUP (l, r);
935 ELF_MACHINE_DEBUG_SETUP (&_dl_rtld_map, r);
937 #else
939 if (l->l_info[DT_DEBUG])
940 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
941 with the run-time address of the r_debug structure */
942 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
944 /* Fill in the pointer in the dynamic linker's own dynamic section, in
945 case you run gdb on the dynamic linker directly. */
946 if (_dl_rtld_map.l_info[DT_DEBUG])
947 _dl_rtld_map.l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
949 #endif
951 /* Notify the debugger that all objects are now mapped in. */
952 r->r_state = RT_ADD;
953 _dl_debug_state ();
956 #ifndef MAP_COPY
957 /* We must munmap() the cache file. */
958 _dl_unload_cache ();
959 #endif
961 /* Now enable profiling if needed. */
962 if (_dl_profile_map != NULL)
963 /* We must prepare the profiling. */
964 _dl_start_profile (_dl_profile_map, _dl_profile_output);
966 /* Once we return, _dl_sysdep_start will invoke
967 the DT_INIT functions and then *USER_ENTRY. */
970 /* This is a little helper function for resolving symbols while
971 tracing the binary. */
972 static void
973 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
974 const char *errstring)
976 if (objname[0] == '\0')
977 objname = _dl_argv[0] ?: "<main program>";
978 _dl_sysdep_error (errstring, " (", objname, ")\n", NULL);
981 /* This is a little helper function for resolving symbols while
982 tracing the binary. */
983 static void
984 print_missing_version (int errcode __attribute__ ((unused)),
985 const char *objname, const char *errstring)
987 _dl_sysdep_error (_dl_argv[0] ?: "<program name unknown>", ": ",
988 objname, ": ", errstring, "\n", NULL);
991 /* Nonzero if any of the debugging options is enabled. */
992 static int any_debug;
994 /* Process the string given as the parameter which explains which debugging
995 options are enabled. */
996 static void
997 process_dl_debug (const char *dl_debug)
999 size_t len;
1000 #define separators " ,:"
1003 len = 0;
1004 /* Skip separating white spaces and commas. */
1005 dl_debug += strspn (dl_debug, separators);
1006 if (*dl_debug != '\0')
1008 len = strcspn (dl_debug, separators);
1010 switch (len)
1012 case 3:
1013 /* This option is not documented since it is not generally
1014 useful. */
1015 if (memcmp (dl_debug, "all", 3) == 0)
1017 _dl_debug_libs = 1;
1018 _dl_debug_impcalls = 1;
1019 _dl_debug_reloc = 1;
1020 _dl_debug_files = 1;
1021 _dl_debug_symbols = 1;
1022 _dl_debug_bindings = 1;
1023 _dl_debug_versions = 1;
1024 any_debug = 1;
1025 continue;
1027 break;
1029 case 4:
1030 if (memcmp (dl_debug, "help", 4) == 0)
1032 _dl_sysdep_message ("\
1033 Valid options for the LD_DEBUG environment variable are:\n\
1035 bindings display information about symbol binding\n\
1036 files display processing of files and libraries\n\
1037 help display this help message and exit\n\
1038 libs display library search paths\n\
1039 reloc display relocation processing\n\
1040 symbols display symbol table processing\n\
1041 versions display version dependencies\n\
1043 To direct the debugging output into a file instead of standard output\n\
1044 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n",
1045 NULL);
1046 _exit (0);
1049 if (memcmp (dl_debug, "libs", 4) == 0)
1051 _dl_debug_libs = 1;
1052 _dl_debug_impcalls = 1;
1053 any_debug = 1;
1054 continue;
1056 break;
1058 case 5:
1059 if (memcmp (dl_debug, "reloc", 5) == 0)
1061 _dl_debug_reloc = 1;
1062 _dl_debug_impcalls = 1;
1063 any_debug = 1;
1064 continue;
1067 if (memcmp (dl_debug, "files", 5) == 0)
1069 _dl_debug_files = 1;
1070 _dl_debug_impcalls = 1;
1071 any_debug = 1;
1072 continue;
1074 break;
1076 case 7:
1077 if (memcmp (dl_debug, "symbols", 7) == 0)
1079 _dl_debug_symbols = 1;
1080 _dl_debug_impcalls = 1;
1081 any_debug = 1;
1082 continue;
1084 break;
1086 case 8:
1087 if (memcmp (dl_debug, "bindings", 8) == 0)
1089 _dl_debug_bindings = 1;
1090 _dl_debug_impcalls = 1;
1091 any_debug = 1;
1092 continue;
1095 if (memcmp (dl_debug, "versions", 8) == 0)
1097 _dl_debug_versions = 1;
1098 _dl_debug_impcalls = 1;
1099 any_debug = 1;
1100 continue;
1102 break;
1104 default:
1105 break;
1109 /* Display a warning and skip everything until next separator. */
1110 char *startp = strndupa (dl_debug, len);
1111 _dl_sysdep_error ("warning: debug option `", startp,
1112 "' unknown; try LD_DEBUG=help\n", NULL);
1116 while (*(dl_debug += len) != '\0');
1119 /* Process all environments variables the dynamic linker must recognize.
1120 Since all of them start with `LD_' we are a bit smarter while finding
1121 all the entries. */
1122 static void
1123 process_envvars (enum mode *modep, int *lazyp)
1125 char **runp = NULL;
1126 char *envline;
1127 enum mode mode = normal;
1128 int bind_now = 0;
1129 char *debug_output = NULL;
1131 /* This is the default place for profiling data file. */
1132 _dl_profile_output = "/var/tmp";
1134 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
1136 size_t len = strcspn (envline, "=") - 3;
1138 switch (len)
1140 case 4:
1141 /* Warning level, verbose or not. */
1142 if (memcmp (&envline[3], "WARN", 4) == 0)
1143 _dl_verbose = envline[8] != '\0';
1144 break;
1146 case 5:
1147 /* Debugging of the dynamic linker? */
1148 if (memcmp (&envline[3], "DEBUG", 5) == 0)
1149 process_dl_debug (&envline[9]);
1150 break;
1152 case 7:
1153 /* Print information about versions. */
1154 if (memcmp (&envline[3], "VERBOSE", 7) == 0)
1156 version_info = envline[11] != '\0';
1157 break;
1160 /* List of objects to be preloaded. */
1161 if (memcmp (&envline[3], "PRELOAD", 7) == 0)
1163 preloadlist = &envline[11];
1164 break;
1167 /* Which shared object shall be profiled. */
1168 if (memcmp (&envline[3], "PROFILE", 7) == 0)
1170 _dl_profile = &envline[11];
1171 if (*_dl_profile == '\0')
1172 _dl_profile = NULL;
1174 break;
1176 case 8:
1177 /* Do we bind early? */
1178 if (memcmp (&envline[3], "BIND_NOW", 8) == 0)
1179 bind_now = envline[12] != '\0';
1180 break;
1182 case 9:
1183 /* Test whether we want to see the content of the auxiliary
1184 array passed up from the kernel. */
1185 if (memcmp (&envline[3], "SHOW_AUXV", 9) == 0)
1186 _dl_show_auxv ();
1187 break;
1189 case 10:
1190 /* Mask for the important hardware capabilities. */
1191 if (memcmp (&envline[3], "HWCAP_MASK", 10) == 0)
1192 _dl_hwcap_mask = strtoul (&envline[14], NULL, 0);
1193 break;
1195 case 11:
1196 /* Path where the binary is found. */
1197 if (!__libc_enable_secure
1198 && memcmp (&envline[3], "ORIGIN_PATH", 11) == 0)
1199 _dl_origin_path = &envline[15];
1200 break;
1202 case 12:
1203 /* Where to place the profiling data file. */
1204 if (memcmp (&envline[3], "DEBUG_OUTPUT", 12) == 0)
1206 debug_output = &envline[16];
1207 break;
1210 /* The library search path. */
1211 if (memcmp (&envline[3], "LIBRARY_PATH", 12) == 0)
1212 library_path = &envline[16];
1213 break;
1215 case 14:
1216 /* Where to place the profiling data file. */
1217 if (!__libc_enable_secure
1218 && memcmp (&envline[3], "PROFILE_OUTPUT", 14) == 0)
1220 _dl_profile_output = &envline[18];
1221 if (*_dl_profile_output == '\0')
1222 _dl_profile_output = "/var/tmp";
1224 break;
1226 case 20:
1227 /* The mode of the dynamic linker can be set. */
1228 if (memcmp (&envline[3], "TRACE_LOADED_OBJECTS", 20) == 0)
1229 mode = trace;
1230 break;
1232 /* We might have some extra environment variable to handle. This
1233 is tricky due to the pre-processing of the length of the name
1234 in the switch statement here. The code here assumes that added
1235 environment variables have a different length. */
1236 #ifdef EXTRA_LD_ENVVARS
1237 EXTRA_LD_ENVVARS
1238 #endif
1242 /* Extra security for SUID binaries. Remove all dangerous environment
1243 variables. */
1244 if (__libc_enable_secure)
1246 static const char *unsecure_envvars[] =
1248 #ifdef EXTRA_UNSECURE_ENVVARS
1249 EXTRA_UNSECURE_ENVVARS
1250 #endif
1252 size_t cnt;
1254 if (preloadlist != NULL)
1255 unsetenv ("LD_PRELOAD");
1256 if (library_path != NULL)
1257 unsetenv ("LD_LIBRARY_PATH");
1259 for (cnt = 0;
1260 cnt < sizeof (unsecure_envvars) / sizeof (unsecure_envvars[0]);
1261 ++cnt)
1262 unsetenv (unsecure_envvars[cnt]);
1265 /* If we have to run the dynamic linker in debugging mode and the
1266 LD_DEBUG_OUTPUT environment variable is given, we write the debug
1267 messages to this file. */
1268 if (any_debug && debug_output != NULL && !__libc_enable_secure)
1270 size_t name_len = strlen (debug_output);
1271 char buf[name_len + 12];
1272 char *startp;
1274 buf[name_len + 11] = '\0';
1275 startp = _itoa_word (__getpid (), &buf[name_len + 11], 10, 0);
1276 *--startp = '.';
1277 startp = memcpy (startp - name_len, debug_output, name_len);
1279 _dl_debug_fd = __open (startp, O_WRONLY | O_APPEND | O_CREAT, 0666);
1280 if (_dl_debug_fd == -1)
1281 /* We use standard output if opening the file failed. */
1282 _dl_debug_fd = STDOUT_FILENO;
1285 /* LAZY is determined by the environment variable LD_WARN and
1286 LD_BIND_NOW if we trace the binary. */
1287 if (__builtin_expect (mode, normal) == trace)
1288 *lazyp = _dl_verbose ? !bind_now : -1;
1289 else
1290 *lazyp = !__libc_enable_secure && !bind_now;
1292 *modep = mode;