Update.
[glibc.git] / elf / rtld.c
blob4d67176d0329abf7f3acab73366ded0f02c0f8ac
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 /* Array which is used when looking up in the global scope. */
99 struct r_scope_elem *_dl_global_scope[2];
101 /* Set nonzero during loading and initialization of executable and
102 libraries, cleared before the executable's entry point runs. This
103 must not be initialized to nonzero, because the unused dynamic
104 linker loaded in for libc.so's "ld.so.1" dep will provide the
105 definition seen by libc.so's initializer; that value must be zero,
106 and will be since that dynamic linker's _dl_start and dl_main will
107 never be called. */
108 int _dl_starting_up;
111 static void dl_main (const ElfW(Phdr) *phdr,
112 ElfW(Half) phent,
113 ElfW(Addr) *user_entry);
115 struct link_map _dl_rtld_map;
116 struct libname_list _dl_rtld_libname;
117 struct libname_list _dl_rtld_libname2;
119 #ifdef RTLD_START
120 RTLD_START
121 #else
122 #error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
123 #endif
125 static ElfW(Addr)
126 _dl_start (void *arg)
128 struct link_map bootstrap_map;
130 /* This #define produces dynamic linking inline functions for
131 bootstrap relocation instead of general-purpose relocation. */
132 #define RTLD_BOOTSTRAP
133 #define RESOLVE(sym, version, flags) bootstrap_map.l_addr
134 #include "dynamic-link.h"
136 /* Figure out the run-time load address of the dynamic linker itself. */
137 bootstrap_map.l_addr = elf_machine_load_address ();
139 /* Read our own dynamic section and fill in the info array. */
140 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
141 elf_get_dynamic_info (bootstrap_map.l_ld, bootstrap_map.l_info);
143 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
144 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
145 #endif
147 /* Relocate ourselves so we can do normal function calls and
148 data access using the global offset table. */
150 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
151 /* Please note that we don't allow profiling of this object and
152 therefore need not test whether we have to allocate the array
153 for the relocation results (as done in dl-reloc.c). */
155 /* Now life is sane; we can call functions and access global data.
156 Set up to use the operating system facilities, and find out from
157 the operating system's program loader where to find the program
158 header table in core. */
160 /* Transfer data about ourselves to the permanent link_map structure. */
161 _dl_rtld_map.l_addr = bootstrap_map.l_addr;
162 _dl_rtld_map.l_ld = bootstrap_map.l_ld;
163 _dl_rtld_map.l_opencount = 1;
164 memcpy (_dl_rtld_map.l_info, bootstrap_map.l_info,
165 sizeof _dl_rtld_map.l_info);
166 _dl_setup_hash (&_dl_rtld_map);
168 /* Don't bother trying to work out how ld.so is mapped in memory. */
169 _dl_rtld_map.l_map_start = ~0;
170 _dl_rtld_map.l_map_end = ~0;
172 /* Call the OS-dependent function to set up life so we can do things like
173 file access. It will call `dl_main' (below) to do all the real work
174 of the dynamic linker, and then unwind our frame and run the user
175 entry point on the same stack we entered on. */
176 return _dl_sysdep_start (arg, &dl_main);
179 /* Now life is peachy; we can do all normal operations.
180 On to the real work. */
182 void ENTRY_POINT (void);
184 /* Some helper functions. */
186 /* Arguments to relocate_doit. */
187 struct relocate_args
189 struct link_map *l;
190 int lazy;
193 struct map_args
195 /* Argument to map_doit. */
196 char *str;
197 /* Return value of map_doit. */
198 struct link_map *main_map;
201 /* Arguments to version_check_doit. */
202 struct version_check_args
204 int doexit;
207 static void
208 relocate_doit (void *a)
210 struct relocate_args *args = (struct relocate_args *) a;
212 _dl_relocate_object (args->l, args->l->l_scope,
213 args->lazy, 0);
216 static void
217 map_doit (void *a)
219 struct map_args *args = (struct map_args *) a;
220 args->main_map = _dl_map_object (NULL, args->str, 0, lt_library, 0);
223 static void
224 version_check_doit (void *a)
226 struct version_check_args *args = (struct version_check_args *) a;
227 if (_dl_check_all_versions (_dl_loaded, 1) && args->doexit)
228 /* We cannot start the application. Abort now. */
229 _exit (1);
233 static inline struct link_map *
234 find_needed (const char *name)
236 unsigned int n = _dl_loaded->l_searchlist.r_nlist;
238 while (n-- > 0)
239 if (_dl_name_match_p (name, _dl_loaded->l_searchlist.r_list[n]))
240 return _dl_loaded->l_searchlist.r_list[n];
242 /* Should never happen. */
243 return NULL;
246 static int
247 match_version (const char *string, struct link_map *map)
249 const char *strtab = (const char *) (map->l_addr
250 + map->l_info[DT_STRTAB]->d_un.d_ptr);
251 ElfW(Verdef) *def;
253 #define VERDEFTAG (DT_NUM + DT_PROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
254 if (map->l_info[VERDEFTAG] == NULL)
255 /* The file has no symbol versioning. */
256 return 0;
258 def = (ElfW(Verdef) *) ((char *) map->l_addr
259 + map->l_info[VERDEFTAG]->d_un.d_ptr);
260 while (1)
262 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
264 /* Compare the version strings. */
265 if (strcmp (string, strtab + aux->vda_name) == 0)
266 /* Bingo! */
267 return 1;
269 /* If no more definitions we failed to find what we want. */
270 if (def->vd_next == 0)
271 break;
273 /* Next definition. */
274 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
277 return 0;
280 static const char *library_path; /* The library search path. */
281 static const char *preloadlist; /* The list preloaded objects. */
282 static int version_info; /* Nonzero if information about
283 versions has to be printed. */
285 static void
286 dl_main (const ElfW(Phdr) *phdr,
287 ElfW(Half) phent,
288 ElfW(Addr) *user_entry)
290 const ElfW(Phdr) *ph;
291 int lazy;
292 enum mode mode;
293 struct link_map **preloads;
294 unsigned int npreloads;
295 size_t file_size;
296 char *file;
297 int has_interp = 0;
298 unsigned int i;
299 int paths_initialized = 0;
301 /* Process the environment variable which control the behaviour. */
302 process_envvars (&mode, &lazy);
304 /* Set up a flag which tells we are just starting. */
305 _dl_starting_up = 1;
307 if (*user_entry == (ElfW(Addr)) &ENTRY_POINT)
309 /* Ho ho. We are not the program interpreter! We are the program
310 itself! This means someone ran ld.so as a command. Well, that
311 might be convenient to do sometimes. We support it by
312 interpreting the args like this:
314 ld.so PROGRAM ARGS...
316 The first argument is the name of a file containing an ELF
317 executable we will load and run with the following arguments.
318 To simplify life here, PROGRAM is searched for using the
319 normal rules for shared objects, rather than $PATH or anything
320 like that. We just load it and use its entry point; we don't
321 pay attention to its PT_INTERP command (we are the interpreter
322 ourselves). This is an easy way to test a new ld.so before
323 installing it. */
325 /* Note the place where the dynamic linker actually came from. */
326 _dl_rtld_map.l_name = _dl_argv[0];
328 while (_dl_argc > 1)
329 if (! strcmp (_dl_argv[1], "--list"))
331 mode = list;
332 lazy = -1; /* This means do no dependency analysis. */
334 ++_dl_skip_args;
335 --_dl_argc;
336 ++_dl_argv;
338 else if (! strcmp (_dl_argv[1], "--verify"))
340 mode = verify;
342 ++_dl_skip_args;
343 --_dl_argc;
344 ++_dl_argv;
346 else if (! strcmp (_dl_argv[1], "--library-path") && _dl_argc > 2)
348 library_path = _dl_argv[2];
350 _dl_skip_args += 2;
351 _dl_argc -= 2;
352 _dl_argv += 2;
354 else if (! strcmp (_dl_argv[1], "--inhibit-rpath") && _dl_argc > 2)
356 _dl_inhibit_rpath = _dl_argv[2];
358 _dl_skip_args += 2;
359 _dl_argc -= 2;
360 _dl_argv += 2;
362 else
363 break;
365 /* If we have no further argument the program was called incorrectly.
366 Grant the user some education. */
367 if (_dl_argc < 2)
368 _dl_sysdep_fatal ("\
369 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
370 You have invoked `ld.so', the helper program for shared library executables.\n\
371 This program usually lives in the file `/lib/ld.so', and special directives\n\
372 in executable files using ELF shared libraries tell the system's program\n\
373 loader to load the helper program from this file. This helper program loads\n\
374 the shared libraries needed by the program executable, prepares the program\n\
375 to run, and runs it. You may invoke this helper program directly from the\n\
376 command line to load and run an ELF executable file; this is like executing\n\
377 that file itself, but always uses this helper program from the file you\n\
378 specified, instead of the helper program file specified in the executable\n\
379 file you run. This is mostly of use for maintainers to test new versions\n\
380 of this helper program; chances are you did not intend to run this program.\n\
382 --list list all dependencies and how they are resolved\n\
383 --verify verify that given object really is a dynamically linked\n\
384 object we get handle\n\
385 --library-path PATH use given PATH instead of content of the environment\n\
386 variable LD_LIBRARY_PATH\n\
387 --inhibit-rpath LIST ignore RPATH information in object names in LIST\n",
388 NULL);
390 ++_dl_skip_args;
391 --_dl_argc;
392 ++_dl_argv;
394 /* Initialize the data structures for the search paths for shared
395 objects. */
396 _dl_init_paths (library_path);
397 paths_initialized = 1;
399 if (mode == verify)
401 char *err_str = NULL;
402 struct map_args args;
404 args.str = _dl_argv[0];
405 (void) _dl_catch_error (&err_str, map_doit, &args);
406 if (err_str != NULL)
408 free (err_str);
409 _exit (EXIT_FAILURE);
412 else
413 _dl_map_object (NULL, _dl_argv[0], 0, lt_library, 0);
415 phdr = _dl_loaded->l_phdr;
416 phent = _dl_loaded->l_phnum;
417 /* We overwrite here a pointer to a malloc()ed string. But since
418 the malloc() implementation used at this point is the dummy
419 implementations which has no real free() function it does not
420 makes sense to free the old string first. */
421 _dl_loaded->l_name = (char *) "";
422 *user_entry = _dl_loaded->l_entry;
424 else
426 /* Create a link_map for the executable itself.
427 This will be what dlopen on "" returns. */
428 _dl_new_object ((char *) "", "", lt_executable, NULL);
429 if (_dl_loaded == NULL)
430 _dl_sysdep_fatal ("cannot allocate memory for link map\n", NULL);
431 _dl_loaded->l_phdr = phdr;
432 _dl_loaded->l_phnum = phent;
433 _dl_loaded->l_entry = *user_entry;
434 _dl_loaded->l_opencount = 1;
436 /* We delay initializing the path structure until we got the dynamic
437 information for the program. */
440 /* It is not safe to load stuff after the main program. */
441 _dl_loaded->l_map_end = ~0;
442 /* Perhaps the executable has no PT_LOAD header entries at all. */
443 _dl_loaded->l_map_start = ~0;
445 /* Scan the program header table for the dynamic section. */
446 for (ph = phdr; ph < &phdr[phent]; ++ph)
447 switch (ph->p_type)
449 case PT_PHDR:
450 /* Find out the load address. */
451 _dl_loaded->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
452 break;
453 case PT_DYNAMIC:
454 /* This tells us where to find the dynamic section,
455 which tells us everything we need to do. */
456 _dl_loaded->l_ld = (void *) _dl_loaded->l_addr + ph->p_vaddr;
457 break;
458 case PT_INTERP:
459 /* This "interpreter segment" was used by the program loader to
460 find the program interpreter, which is this program itself, the
461 dynamic linker. We note what name finds us, so that a future
462 dlopen call or DT_NEEDED entry, for something that wants to link
463 against the dynamic linker as a shared library, will know that
464 the shared object is already loaded. */
465 _dl_rtld_libname.name = ((const char *) _dl_loaded->l_addr
466 + ph->p_vaddr);
467 _dl_rtld_libname.next = NULL;
468 _dl_rtld_map.l_libname = &_dl_rtld_libname;
470 /* Ordinarilly, we would get additional names for the loader from
471 our DT_SONAME. This can't happen if we were actually linked as
472 a static executable (detect this case when we have no DYNAMIC).
473 If so, assume the filename component of the interpreter path to
474 be our SONAME, and add it to our name list. */
475 if (_dl_rtld_map.l_ld == NULL)
477 char *p = strrchr (_dl_rtld_libname.name, '/');
478 if (p)
480 _dl_rtld_libname2.name = p+1;
481 _dl_rtld_libname2.next = NULL;
482 _dl_rtld_libname.next = &_dl_rtld_libname2;
486 has_interp = 1;
487 break;
488 case PT_LOAD:
489 /* Remember where the main program starts in memory. */
491 ElfW(Addr) mapstart;
492 mapstart = _dl_loaded->l_addr + (ph->p_vaddr & ~(ph->p_align - 1));
493 if (_dl_loaded->l_map_start > mapstart)
494 _dl_loaded->l_map_start = mapstart;
496 break;
498 if (! _dl_rtld_map.l_libname && _dl_rtld_map.l_name)
500 /* We were invoked directly, so the program might not have a
501 PT_INTERP. */
502 _dl_rtld_libname.name = _dl_rtld_map.l_name;
503 _dl_rtld_libname.next = NULL;
504 _dl_rtld_map.l_libname = &_dl_rtld_libname;
506 else
507 assert (_dl_rtld_map.l_libname); /* How else did we get here? */
509 /* Extract the contents of the dynamic section for easy access. */
510 elf_get_dynamic_info (_dl_loaded->l_ld, _dl_loaded->l_info);
511 if (_dl_loaded->l_info[DT_HASH])
512 /* Set up our cache of pointers into the hash table. */
513 _dl_setup_hash (_dl_loaded);
515 if (mode == verify)
517 /* We were called just to verify that this is a dynamic
518 executable using us as the program interpreter. Exit with an
519 error if we were not able to load the binary or no interpreter
520 is specified (i.e., this is no dynamically linked binary. */
521 if (_dl_loaded->l_ld == NULL)
522 _exit (1);
524 /* We allow here some platform specific code. */
525 #ifdef DISTINGUISH_LIB_VERSIONS
526 DISTINGUISH_LIB_VERSIONS;
527 #endif
528 _exit (has_interp ? 0 : 2);
531 if (! paths_initialized)
532 /* Initialize the data structures for the search paths for shared
533 objects. */
534 _dl_init_paths (library_path);
536 /* Put the link_map for ourselves on the chain so it can be found by
537 name. Note that at this point the global chain of link maps contains
538 exactly one element, which is pointed to by _dl_loaded. */
539 if (! _dl_rtld_map.l_name)
540 /* If not invoked directly, the dynamic linker shared object file was
541 found by the PT_INTERP name. */
542 _dl_rtld_map.l_name = (char *) _dl_rtld_map.l_libname->name;
543 _dl_rtld_map.l_type = lt_library;
544 _dl_loaded->l_next = &_dl_rtld_map;
545 _dl_rtld_map.l_prev = _dl_loaded;
547 /* We have two ways to specify objects to preload: via environment
548 variable and via the file /etc/ld.so.preload. The later can also
549 be used when security is enabled. */
550 preloads = NULL;
551 npreloads = 0;
553 if (preloadlist)
555 /* The LD_PRELOAD environment variable gives list of libraries
556 separated by white space or colons that are loaded before the
557 executable's dependencies and prepended to the global scope
558 list. If the binary is running setuid all elements
559 containing a '/' are ignored since it is insecure. */
560 char *list = strdupa (preloadlist);
561 char *p;
562 while ((p = strsep (&list, " :")) != NULL)
563 if (p[0] != '\0'
564 && (! __libc_enable_secure || strchr (p, '/') == NULL))
566 struct link_map *new_map = _dl_map_object (_dl_loaded, p, 1,
567 lt_library, 0);
568 if (new_map->l_opencount == 1)
569 /* It is no duplicate. */
570 ++npreloads;
574 /* Read the contents of the file. */
575 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
576 PROT_READ | PROT_WRITE);
577 if (file)
579 /* Parse the file. It contains names of libraries to be loaded,
580 separated by white spaces or `:'. It may also contain
581 comments introduced by `#'. */
582 char *problem;
583 char *runp;
584 size_t rest;
586 /* Eliminate comments. */
587 runp = file;
588 rest = file_size;
589 while (rest > 0)
591 char *comment = memchr (runp, '#', rest);
592 if (comment == NULL)
593 break;
595 rest -= comment - runp;
597 *comment = ' ';
598 while (--rest > 0 && *++comment != '\n');
601 /* We have one problematic case: if we have a name at the end of
602 the file without a trailing terminating characters, we cannot
603 place the \0. Handle the case separately. */
604 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
605 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
607 problem = &file[file_size];
608 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
609 && problem[-1] != '\n' && problem[-1] != ':')
610 --problem;
612 if (problem > file)
613 problem[-1] = '\0';
615 else
617 problem = NULL;
618 file[file_size - 1] = '\0';
621 if (file != problem)
623 char *p;
624 runp = file;
625 while ((p = strsep (&runp, ": \t\n")) != NULL)
626 if (p[0] != '\0')
628 struct link_map *new_map = _dl_map_object (_dl_loaded, p, 1,
629 lt_library, 0);
630 if (new_map->l_opencount == 1)
631 /* It is no duplicate. */
632 ++npreloads;
636 if (problem != NULL)
638 char *p = strndupa (problem, file_size - (problem - file));
639 struct link_map *new_map = _dl_map_object (_dl_loaded, p, 1,
640 lt_library, 0);
641 if (new_map->l_opencount == 1)
642 /* It is no duplicate. */
643 ++npreloads;
646 /* We don't need the file anymore. */
647 __munmap (file, file_size);
650 if (npreloads != 0)
652 /* Set up PRELOADS with a vector of the preloaded libraries. */
653 struct link_map *l;
654 preloads = __alloca (npreloads * sizeof preloads[0]);
655 l = _dl_rtld_map.l_next; /* End of the chain before preloads. */
656 i = 0;
659 preloads[i++] = l;
660 l = l->l_next;
661 } while (l);
662 assert (i == npreloads);
665 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
666 specified some libraries to load, these are inserted before the actual
667 dependencies in the executable's searchlist for symbol resolution. */
668 _dl_map_object_deps (_dl_loaded, preloads, npreloads, mode == trace);
670 #ifndef MAP_ANON
671 /* We are done mapping things, so close the zero-fill descriptor. */
672 __close (_dl_zerofd);
673 _dl_zerofd = -1;
674 #endif
676 /* Remove _dl_rtld_map from the chain. */
677 _dl_rtld_map.l_prev->l_next = _dl_rtld_map.l_next;
678 if (_dl_rtld_map.l_next)
679 _dl_rtld_map.l_next->l_prev = _dl_rtld_map.l_prev;
681 if (_dl_rtld_map.l_opencount > 1)
683 /* Some DT_NEEDED entry referred to the interpreter object itself, so
684 put it back in the list of visible objects. We insert it into the
685 chain in symbol search order because gdb uses the chain's order as
686 its symbol search order. */
687 i = 1;
688 while (_dl_loaded->l_searchlist.r_list[i] != &_dl_rtld_map)
689 ++i;
690 _dl_rtld_map.l_prev = _dl_loaded->l_searchlist.r_list[i - 1];
691 _dl_rtld_map.l_next = (i + 1 < _dl_loaded->l_searchlist.r_nlist
692 ? _dl_loaded->l_searchlist.r_list[i + 1]
693 : NULL);
694 assert (_dl_rtld_map.l_prev->l_next == _dl_rtld_map.l_next);
695 _dl_rtld_map.l_prev->l_next = &_dl_rtld_map;
696 if (_dl_rtld_map.l_next)
698 assert (_dl_rtld_map.l_next->l_prev == _dl_rtld_map.l_prev);
699 _dl_rtld_map.l_next->l_prev = &_dl_rtld_map;
703 /* Now let us see whether all libraries are available in the
704 versions we need. */
706 struct version_check_args args;
707 args.doexit = mode == normal;
708 _dl_receive_error (print_missing_version, version_check_doit, &args);
711 if (mode != normal)
713 /* We were run just to list the shared libraries. It is
714 important that we do this before real relocation, because the
715 functions we call below for output may no longer work properly
716 after relocation. */
717 if (! _dl_loaded->l_info[DT_NEEDED])
718 _dl_sysdep_message ("\t", "statically linked\n", NULL);
719 else
721 struct link_map *l;
723 for (l = _dl_loaded->l_next; l; l = l->l_next)
724 if (l->l_opencount == 0)
725 /* The library was not found. */
726 _dl_sysdep_message ("\t", l->l_libname->name, " => not found\n",
727 NULL);
728 else
730 char buf[20], *bp;
731 buf[sizeof buf - 1] = '\0';
732 bp = _itoa_word (l->l_addr, &buf[sizeof buf - 1], 16, 0);
733 while ((size_t) (&buf[sizeof buf - 1] - bp)
734 < sizeof l->l_addr * 2)
735 *--bp = '0';
736 _dl_sysdep_message ("\t", l->l_libname->name, " => ",
737 l->l_name, " (0x", bp, ")\n", NULL);
741 if (mode != trace)
742 for (i = 1; i < _dl_argc; ++i)
744 const ElfW(Sym) *ref = NULL;
745 ElfW(Addr) loadbase = _dl_lookup_symbol (_dl_argv[i], &ref,
746 _dl_loaded->l_scope,
747 "argument",
748 ELF_MACHINE_JMP_SLOT);
749 char buf[20], *bp;
750 buf[sizeof buf - 1] = '\0';
751 bp = _itoa_word (ref->st_value, &buf[sizeof buf - 1], 16, 0);
752 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
753 *--bp = '0';
754 _dl_sysdep_message (_dl_argv[i], " found at 0x", bp, NULL);
755 buf[sizeof buf - 1] = '\0';
756 bp = _itoa_word (loadbase, &buf[sizeof buf - 1], 16, 0);
757 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
758 *--bp = '0';
759 _dl_sysdep_message (" in object at 0x", bp, "\n", NULL);
761 else
763 if (lazy >= 0)
765 /* We have to do symbol dependency testing. */
766 struct relocate_args args;
767 struct link_map *l;
769 args.lazy = lazy;
771 l = _dl_loaded;
772 while (l->l_next)
773 l = l->l_next;
776 if (l != &_dl_rtld_map && l->l_opencount > 0)
778 args.l = l;
779 _dl_receive_error (print_unresolved, relocate_doit,
780 &args);
782 l = l->l_prev;
783 } while (l);
786 #define VERNEEDTAG (DT_NUM + DT_PROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
787 if (version_info)
789 /* Print more information. This means here, print information
790 about the versions needed. */
791 int first = 1;
792 struct link_map *map = _dl_loaded;
794 for (map = _dl_loaded; map != NULL; map = map->l_next)
796 const char *strtab;
797 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
798 ElfW(Verneed) *ent;
800 if (dyn == NULL)
801 continue;
803 strtab = (const char *)
804 (map->l_addr + map->l_info[DT_STRTAB]->d_un.d_ptr);
805 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
807 if (first)
809 _dl_sysdep_message ("\n\tVersion information:\n", NULL);
810 first = 0;
813 _dl_sysdep_message ("\t", (map->l_name[0]
814 ? map->l_name : _dl_argv[0]),
815 ":\n", NULL);
817 while (1)
819 ElfW(Vernaux) *aux;
820 struct link_map *needed;
822 needed = find_needed (strtab + ent->vn_file);
823 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
825 while (1)
827 const char *fname = NULL;
829 _dl_sysdep_message ("\t\t",
830 strtab + ent->vn_file,
831 " (", strtab + aux->vna_name,
832 ") ",
833 (aux->vna_flags
834 & VER_FLG_WEAK
835 ? "[WEAK] " : ""),
836 "=> ", NULL);
838 if (needed != NULL
839 && match_version (strtab+aux->vna_name, needed))
840 fname = needed->l_name;
842 _dl_sysdep_message (fname ?: "not found", "\n",
843 NULL);
845 if (aux->vna_next == 0)
846 /* No more symbols. */
847 break;
849 /* Next symbol. */
850 aux = (ElfW(Vernaux) *) ((char *) aux
851 + aux->vna_next);
854 if (ent->vn_next == 0)
855 /* No more dependencies. */
856 break;
858 /* Next dependency. */
859 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
865 _exit (0);
869 /* Now we have all the objects loaded. Relocate them all except for
870 the dynamic linker itself. We do this in reverse order so that copy
871 relocs of earlier objects overwrite the data written by later
872 objects. We do not re-relocate the dynamic linker itself in this
873 loop because that could result in the GOT entries for functions we
874 call being changed, and that would break us. It is safe to relocate
875 the dynamic linker out of order because it has no copy relocs (we
876 know that because it is self-contained). */
878 struct link_map *l;
879 int consider_profiling = _dl_profile != NULL;
881 /* If we are profiling we also must do lazy reloaction. */
882 lazy |= consider_profiling;
884 l = _dl_loaded;
885 while (l->l_next)
886 l = l->l_next;
889 if (l != &_dl_rtld_map)
890 _dl_relocate_object (l, l->l_scope, lazy, consider_profiling);
892 l = l->l_prev;
893 } while (l);
895 /* Do any necessary cleanups for the startup OS interface code.
896 We do these now so that no calls are made after rtld re-relocation
897 which might be resolved to different functions than we expect.
898 We cannot do this before relocating the other objects because
899 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
900 _dl_sysdep_start_cleanup ();
902 if (_dl_rtld_map.l_opencount > 0)
903 /* There was an explicit ref to the dynamic linker as a shared lib.
904 Re-relocate ourselves with user-controlled symbol definitions. */
905 _dl_relocate_object (&_dl_rtld_map, _dl_loaded->l_scope, 0, 0);
908 /* Now set up the variable which helps the assembler startup code. */
909 _dl_main_searchlist = &_dl_loaded->l_searchlist;
910 _dl_global_scope[0] = &_dl_loaded->l_searchlist;
913 /* Initialize _r_debug. */
914 struct r_debug *r = _dl_debug_initialize (_dl_rtld_map.l_addr);
915 struct link_map *l;
917 l = _dl_loaded;
919 #ifdef ELF_MACHINE_DEBUG_SETUP
921 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
923 ELF_MACHINE_DEBUG_SETUP (l, r);
924 ELF_MACHINE_DEBUG_SETUP (&_dl_rtld_map, r);
926 #else
928 if (l->l_info[DT_DEBUG])
929 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
930 with the run-time address of the r_debug structure */
931 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
933 /* Fill in the pointer in the dynamic linker's own dynamic section, in
934 case you run gdb on the dynamic linker directly. */
935 if (_dl_rtld_map.l_info[DT_DEBUG])
936 _dl_rtld_map.l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
938 #endif
940 /* Notify the debugger that all objects are now mapped in. */
941 r->r_state = RT_ADD;
942 _dl_debug_state ();
945 #ifndef MAP_COPY
946 /* We must munmap() the cache file. */
947 _dl_unload_cache ();
948 #endif
950 /* Now enable profiling if needed. */
951 if (_dl_profile_map != NULL)
952 /* We must prepare the profiling. */
953 _dl_start_profile (_dl_profile_map, _dl_profile_output);
955 /* Once we return, _dl_sysdep_start will invoke
956 the DT_INIT functions and then *USER_ENTRY. */
959 /* This is a little helper function for resolving symbols while
960 tracing the binary. */
961 static void
962 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
963 const char *errstring)
965 if (objname[0] == '\0')
966 objname = _dl_argv[0] ?: "<main program>";
967 _dl_sysdep_error (errstring, " (", objname, ")\n", NULL);
970 /* This is a little helper function for resolving symbols while
971 tracing the binary. */
972 static void
973 print_missing_version (int errcode __attribute__ ((unused)),
974 const char *objname, const char *errstring)
976 _dl_sysdep_error (_dl_argv[0] ?: "<program name unknown>", ": ",
977 objname, ": ", errstring, "\n", NULL);
980 /* Nonzero if any of the debugging options is enabled. */
981 static int any_debug;
983 /* Process the string given as the parameter which explains which debugging
984 options are enabled. */
985 static void
986 process_dl_debug (const char *dl_debug)
988 size_t len;
989 #define separators " ,:"
992 len = 0;
993 /* Skip separating white spaces and commas. */
994 dl_debug += strspn (dl_debug, separators);
995 if (*dl_debug != '\0')
997 len = strcspn (dl_debug, separators);
999 switch (len)
1001 case 3:
1002 /* This option is not documented since it is not generally
1003 useful. */
1004 if (memcmp (dl_debug, "all", 3) == 0)
1006 _dl_debug_libs = 1;
1007 _dl_debug_impcalls = 1;
1008 _dl_debug_reloc = 1;
1009 _dl_debug_files = 1;
1010 _dl_debug_symbols = 1;
1011 _dl_debug_bindings = 1;
1012 _dl_debug_versions = 1;
1013 any_debug = 1;
1014 continue;
1016 break;
1018 case 4:
1019 if (memcmp (dl_debug, "help", 4) == 0)
1021 _dl_sysdep_message ("\
1022 Valid options for the LD_DEBUG environment variable are:\n\
1024 bindings display information about symbol binding\n\
1025 files display processing of files and libraries\n\
1026 help display this help message and exit\n\
1027 libs display library search paths\n\
1028 reloc display relocation processing\n\
1029 symbols display symbol table processing\n\
1030 versions display version dependencies\n\
1032 To direct the debugging output into a file instead of standard output\n\
1033 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n",
1034 NULL);
1035 _exit (0);
1038 if (memcmp (dl_debug, "libs", 4) == 0)
1040 _dl_debug_libs = 1;
1041 _dl_debug_impcalls = 1;
1042 any_debug = 1;
1043 continue;
1045 break;
1047 case 5:
1048 if (memcmp (dl_debug, "reloc", 5) == 0)
1050 _dl_debug_reloc = 1;
1051 _dl_debug_impcalls = 1;
1052 any_debug = 1;
1053 continue;
1056 if (memcmp (dl_debug, "files", 5) == 0)
1058 _dl_debug_files = 1;
1059 _dl_debug_impcalls = 1;
1060 any_debug = 1;
1061 continue;
1063 break;
1065 case 7:
1066 if (memcmp (dl_debug, "symbols", 7) == 0)
1068 _dl_debug_symbols = 1;
1069 _dl_debug_impcalls = 1;
1070 any_debug = 1;
1071 continue;
1073 break;
1075 case 8:
1076 if (memcmp (dl_debug, "bindings", 8) == 0)
1078 _dl_debug_bindings = 1;
1079 _dl_debug_impcalls = 1;
1080 any_debug = 1;
1081 continue;
1084 if (memcmp (dl_debug, "versions", 8) == 0)
1086 _dl_debug_versions = 1;
1087 _dl_debug_impcalls = 1;
1088 any_debug = 1;
1089 continue;
1091 break;
1093 default:
1094 break;
1098 /* Display a warning and skip everything until next separator. */
1099 char *startp = strndupa (dl_debug, len);
1100 _dl_sysdep_error ("warning: debug option `", startp,
1101 "' unknown; try LD_DEBUG=help\n", NULL);
1105 while (*(dl_debug += len) != '\0');
1108 /* Process all environments variables the dynamic linker must recognize.
1109 Since all of them start with `LD_' we are a bit smarter while finding
1110 all the entries. */
1111 static void
1112 process_envvars (enum mode *modep, int *lazyp)
1114 char **runp = NULL;
1115 char *envline;
1116 enum mode mode = normal;
1117 int bind_now = 0;
1118 char *debug_output = NULL;
1120 /* This is the default place for profiling data file. */
1121 _dl_profile_output = "/var/tmp";
1123 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
1125 size_t len = strcspn (envline, "=") - 3;
1127 switch (len)
1129 case 4:
1130 /* Warning level, verbose or not. */
1131 if (memcmp (&envline[3], "WARN", 4) == 0)
1132 _dl_verbose = envline[8] != '\0';
1133 break;
1135 case 5:
1136 /* Debugging of the dynamic linker? */
1137 if (memcmp (&envline[3], "DEBUG", 5) == 0)
1138 process_dl_debug (&envline[9]);
1139 break;
1141 case 7:
1142 /* Print information about versions. */
1143 if (memcmp (&envline[3], "VERBOSE", 7) == 0)
1145 version_info = envline[11] != '\0';
1146 break;
1149 /* List of objects to be preloaded. */
1150 if (memcmp (&envline[3], "PRELOAD", 7) == 0)
1152 preloadlist = &envline[11];
1153 break;
1156 /* Which shared object shall be profiled. */
1157 if (memcmp (&envline[3], "PROFILE", 7) == 0)
1159 _dl_profile = &envline[11];
1160 if (*_dl_profile == '\0')
1161 _dl_profile = NULL;
1163 break;
1165 case 8:
1166 /* Do we bind early? */
1167 if (memcmp (&envline[3], "BIND_NOW", 8) == 0
1168 && (envline[12] == '1' || envline[12] == 'y'
1169 || envline[12] == 'Y'
1170 || ((envline[12] == 'o' || envline[12] == 'O')
1171 && (envline[13] == 'n' || envline[13] == 'N'))))
1172 bind_now = 1;
1173 break;
1175 case 9:
1176 /* Test whether we want to see the content of the auxiliary
1177 array passed up from the kernel. */
1178 if (memcmp (&envline[3], "SHOW_AUXV", 9) == 0)
1179 _dl_show_auxv ();
1180 break;
1182 case 10:
1183 /* Mask for the important hardware capabilities. */
1184 if (memcmp (&envline[3], "HWCAP_MASK", 10) == 0)
1185 _dl_hwcap_mask = strtoul (&envline[14], NULL, 0);
1186 break;
1188 case 11:
1189 /* Path where the binary is found. */
1190 if (!__libc_enable_secure
1191 && memcmp (&envline[3], "ORIGIN_PATH", 11) == 0)
1192 _dl_origin_path = &envline[15];
1193 break;
1195 case 12:
1196 /* Where to place the profiling data file. */
1197 if (memcmp (&envline[3], "DEBUG_OUTPUT", 12) == 0)
1199 debug_output = &envline[16];
1200 break;
1203 /* The library search path. */
1204 if (memcmp (&envline[3], "LIBRARY_PATH", 12) == 0)
1205 library_path = &envline[16];
1206 break;
1208 case 14:
1209 /* Where to place the profiling data file. */
1210 if (!__libc_enable_secure
1211 && memcmp (&envline[3], "PROFILE_OUTPUT", 14) == 0)
1213 _dl_profile_output = &envline[18];
1214 if (*_dl_profile_output == '\0')
1215 _dl_profile_output = "/var/tmp";
1217 break;
1219 case 20:
1220 /* The mode of the dynamic linker can be set. */
1221 if (memcmp (&envline[3], "TRACE_LOADED_OBJECTS", 20) == 0)
1222 mode = trace;
1223 break;
1225 /* We might have some extra environment variable to handle. This
1226 is tricky due to the pre-processing of the length of the name
1227 in the switch statement here. The code here assumes that added
1228 environment variables have a different length. */
1229 #ifdef EXTRA_LD_ENVVARS
1230 EXTRA_LD_ENVVARS
1231 #endif
1235 /* Extra security for SUID binaries. Remove all dangerous environment
1236 variables. */
1237 if (__libc_enable_secure)
1239 static const char *unsecure_envvars[] =
1241 #ifdef EXTRA_UNSECURE_ENVVARS
1242 EXTRA_UNSECURE_ENVVARS
1243 #endif
1245 size_t cnt;
1247 if (preloadlist != NULL)
1248 unsetenv ("LD_PRELOAD");
1249 if (library_path != NULL)
1250 unsetenv ("LD_LIBRARY_PATH");
1252 for (cnt = 0;
1253 cnt < sizeof (unsecure_envvars) / sizeof (unsecure_envvars[0]);
1254 ++cnt)
1255 unsetenv (unsecure_envvars[cnt]);
1258 /* If we have to run the dynamic linker in debugging mode and the
1259 LD_DEBUG_OUTPUT environment variable is given, we write the debug
1260 messages to this file. */
1261 if (any_debug && debug_output != NULL && !__libc_enable_secure)
1263 size_t name_len = strlen (debug_output);
1264 char buf[name_len + 12];
1265 char *startp;
1267 buf[name_len + 11] = '\0';
1268 startp = _itoa_word (__getpid (), &buf[name_len + 11], 10, 0);
1269 *--startp = '.';
1270 startp = memcpy (startp - name_len, debug_output, name_len);
1272 _dl_debug_fd = __open (startp, O_WRONLY | O_APPEND | O_CREAT, 0666);
1273 if (_dl_debug_fd == -1)
1274 /* We use standard output if opening the file failed. */
1275 _dl_debug_fd = STDOUT_FILENO;
1278 /* LAZY is determined by the environment variable LD_WARN and
1279 LD_BIND_NOW if we trace the binary. */
1280 if (mode == trace)
1281 *lazyp = _dl_verbose ? !bind_now : -1;
1282 else
1283 *lazyp = !__libc_enable_secure && !bind_now;
1285 *modep = mode;