Update.
[glibc.git] / elf / rtld.c
blob33002f8cef10aacbbf705667e928539e93600061
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) bootstrap_map.l_addr
136 #include "dynamic-link.h"
138 /* Figure out the run-time load address of the dynamic linker itself. */
139 bootstrap_map.l_addr = elf_machine_load_address ();
141 /* Read our own dynamic section and fill in the info array. */
142 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
143 elf_get_dynamic_info (bootstrap_map.l_ld, bootstrap_map.l_info);
145 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
146 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
147 #endif
149 /* Relocate ourselves so we can do normal function calls and
150 data access using the global offset table. */
152 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
153 /* Please note that we don't allow profiling of this object and
154 therefore need not test whether we have to allocate the array
155 for the relocation results (as done in dl-reloc.c). */
157 /* Now life is sane; we can call functions and access global data.
158 Set up to use the operating system facilities, and find out from
159 the operating system's program loader where to find the program
160 header table in core. */
162 /* Transfer data about ourselves to the permanent link_map structure. */
163 _dl_rtld_map.l_addr = bootstrap_map.l_addr;
164 _dl_rtld_map.l_ld = bootstrap_map.l_ld;
165 _dl_rtld_map.l_opencount = 1;
166 memcpy (_dl_rtld_map.l_info, bootstrap_map.l_info,
167 sizeof _dl_rtld_map.l_info);
168 _dl_setup_hash (&_dl_rtld_map);
170 /* Don't bother trying to work out how ld.so is mapped in memory. */
171 _dl_rtld_map.l_map_start = ~0;
172 _dl_rtld_map.l_map_end = ~0;
174 /* Call the OS-dependent function to set up life so we can do things like
175 file access. It will call `dl_main' (below) to do all the real work
176 of the dynamic linker, and then unwind our frame and run the user
177 entry point on the same stack we entered on. */
178 return _dl_sysdep_start (arg, &dl_main);
181 /* Now life is peachy; we can do all normal operations.
182 On to the real work. */
184 void ENTRY_POINT (void);
186 /* Some helper functions. */
188 /* Arguments to relocate_doit. */
189 struct relocate_args
191 struct link_map *l;
192 int lazy;
195 struct map_args
197 /* Argument to map_doit. */
198 char *str;
199 /* Return value of map_doit. */
200 struct link_map *main_map;
203 /* Arguments to version_check_doit. */
204 struct version_check_args
206 int doexit;
209 static void
210 relocate_doit (void *a)
212 struct relocate_args *args = (struct relocate_args *) a;
214 _dl_relocate_object (args->l, args->l->l_scope,
215 args->lazy, 0);
218 static void
219 map_doit (void *a)
221 struct map_args *args = (struct map_args *) a;
222 args->main_map = _dl_map_object (NULL, args->str, 0, lt_library, 0);
225 static void
226 version_check_doit (void *a)
228 struct version_check_args *args = (struct version_check_args *) a;
229 if (_dl_check_all_versions (_dl_loaded, 1) && args->doexit)
230 /* We cannot start the application. Abort now. */
231 _exit (1);
235 static inline struct link_map *
236 find_needed (const char *name)
238 unsigned int n = _dl_loaded->l_searchlist.r_nlist;
240 while (n-- > 0)
241 if (_dl_name_match_p (name, _dl_loaded->l_searchlist.r_list[n]))
242 return _dl_loaded->l_searchlist.r_list[n];
244 /* Should never happen. */
245 return NULL;
248 static int
249 match_version (const char *string, struct link_map *map)
251 const char *strtab = (const char *) (map->l_addr
252 + map->l_info[DT_STRTAB]->d_un.d_ptr);
253 ElfW(Verdef) *def;
255 #define VERDEFTAG (DT_NUM + DT_PROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
256 if (map->l_info[VERDEFTAG] == NULL)
257 /* The file has no symbol versioning. */
258 return 0;
260 def = (ElfW(Verdef) *) ((char *) map->l_addr
261 + map->l_info[VERDEFTAG]->d_un.d_ptr);
262 while (1)
264 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
266 /* Compare the version strings. */
267 if (strcmp (string, strtab + aux->vda_name) == 0)
268 /* Bingo! */
269 return 1;
271 /* If no more definitions we failed to find what we want. */
272 if (def->vd_next == 0)
273 break;
275 /* Next definition. */
276 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
279 return 0;
282 static const char *library_path; /* The library search path. */
283 static const char *preloadlist; /* The list preloaded objects. */
284 static int version_info; /* Nonzero if information about
285 versions has to be printed. */
287 static void
288 dl_main (const ElfW(Phdr) *phdr,
289 ElfW(Half) phent,
290 ElfW(Addr) *user_entry)
292 const ElfW(Phdr) *ph;
293 int lazy;
294 enum mode mode;
295 struct link_map **preloads;
296 unsigned int npreloads;
297 size_t file_size;
298 char *file;
299 int has_interp = 0;
300 unsigned int i;
301 int paths_initialized = 0;
303 /* Process the environment variable which control the behaviour. */
304 process_envvars (&mode, &lazy);
306 /* Set up a flag which tells we are just starting. */
307 _dl_starting_up = 1;
309 if (*user_entry == (ElfW(Addr)) &ENTRY_POINT)
311 /* Ho ho. We are not the program interpreter! We are the program
312 itself! This means someone ran ld.so as a command. Well, that
313 might be convenient to do sometimes. We support it by
314 interpreting the args like this:
316 ld.so PROGRAM ARGS...
318 The first argument is the name of a file containing an ELF
319 executable we will load and run with the following arguments.
320 To simplify life here, PROGRAM is searched for using the
321 normal rules for shared objects, rather than $PATH or anything
322 like that. We just load it and use its entry point; we don't
323 pay attention to its PT_INTERP command (we are the interpreter
324 ourselves). This is an easy way to test a new ld.so before
325 installing it. */
327 /* Note the place where the dynamic linker actually came from. */
328 _dl_rtld_map.l_name = _dl_argv[0];
330 while (_dl_argc > 1)
331 if (! strcmp (_dl_argv[1], "--list"))
333 mode = list;
334 lazy = -1; /* This means do no dependency analysis. */
336 ++_dl_skip_args;
337 --_dl_argc;
338 ++_dl_argv;
340 else if (! strcmp (_dl_argv[1], "--verify"))
342 mode = verify;
344 ++_dl_skip_args;
345 --_dl_argc;
346 ++_dl_argv;
348 else if (! strcmp (_dl_argv[1], "--library-path") && _dl_argc > 2)
350 library_path = _dl_argv[2];
352 _dl_skip_args += 2;
353 _dl_argc -= 2;
354 _dl_argv += 2;
356 else if (! strcmp (_dl_argv[1], "--inhibit-rpath") && _dl_argc > 2)
358 _dl_inhibit_rpath = _dl_argv[2];
360 _dl_skip_args += 2;
361 _dl_argc -= 2;
362 _dl_argv += 2;
364 else
365 break;
367 /* If we have no further argument the program was called incorrectly.
368 Grant the user some education. */
369 if (_dl_argc < 2)
370 _dl_sysdep_fatal ("\
371 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
372 You have invoked `ld.so', the helper program for shared library executables.\n\
373 This program usually lives in the file `/lib/ld.so', and special directives\n\
374 in executable files using ELF shared libraries tell the system's program\n\
375 loader to load the helper program from this file. This helper program loads\n\
376 the shared libraries needed by the program executable, prepares the program\n\
377 to run, and runs it. You may invoke this helper program directly from the\n\
378 command line to load and run an ELF executable file; this is like executing\n\
379 that file itself, but always uses this helper program from the file you\n\
380 specified, instead of the helper program file specified in the executable\n\
381 file you run. This is mostly of use for maintainers to test new versions\n\
382 of this helper program; chances are you did not intend to run this program.\n\
384 --list list all dependencies and how they are resolved\n\
385 --verify verify that given object really is a dynamically linked\n\
386 object we get handle\n\
387 --library-path PATH use given PATH instead of content of the environment\n\
388 variable LD_LIBRARY_PATH\n\
389 --inhibit-rpath LIST ignore RPATH information in object names in LIST\n",
390 NULL);
392 ++_dl_skip_args;
393 --_dl_argc;
394 ++_dl_argv;
396 /* Initialize the data structures for the search paths for shared
397 objects. */
398 _dl_init_paths (library_path);
399 paths_initialized = 1;
401 if (mode == verify)
403 char *err_str = NULL;
404 struct map_args args;
406 args.str = _dl_argv[0];
407 (void) _dl_catch_error (&err_str, map_doit, &args);
408 if (err_str != NULL)
410 free (err_str);
411 _exit (EXIT_FAILURE);
414 else
415 _dl_map_object (NULL, _dl_argv[0], 0, lt_library, 0);
417 phdr = _dl_loaded->l_phdr;
418 phent = _dl_loaded->l_phnum;
419 /* We overwrite here a pointer to a malloc()ed string. But since
420 the malloc() implementation used at this point is the dummy
421 implementations which has no real free() function it does not
422 makes sense to free the old string first. */
423 _dl_loaded->l_name = (char *) "";
424 *user_entry = _dl_loaded->l_entry;
426 else
428 /* Create a link_map for the executable itself.
429 This will be what dlopen on "" returns. */
430 _dl_new_object ((char *) "", "", lt_executable, NULL);
431 if (_dl_loaded == NULL)
432 _dl_sysdep_fatal ("cannot allocate memory for link map\n", NULL);
433 _dl_loaded->l_phdr = phdr;
434 _dl_loaded->l_phnum = phent;
435 _dl_loaded->l_entry = *user_entry;
436 _dl_loaded->l_opencount = 1;
438 /* We delay initializing the path structure until we got the dynamic
439 information for the program. */
442 /* It is not safe to load stuff after the main program. */
443 _dl_loaded->l_map_end = ~0;
444 /* Perhaps the executable has no PT_LOAD header entries at all. */
445 _dl_loaded->l_map_start = ~0;
447 /* Scan the program header table for the dynamic section. */
448 for (ph = phdr; ph < &phdr[phent]; ++ph)
449 switch (ph->p_type)
451 case PT_PHDR:
452 /* Find out the load address. */
453 _dl_loaded->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
454 break;
455 case PT_DYNAMIC:
456 /* This tells us where to find the dynamic section,
457 which tells us everything we need to do. */
458 _dl_loaded->l_ld = (void *) _dl_loaded->l_addr + ph->p_vaddr;
459 break;
460 case PT_INTERP:
461 /* This "interpreter segment" was used by the program loader to
462 find the program interpreter, which is this program itself, the
463 dynamic linker. We note what name finds us, so that a future
464 dlopen call or DT_NEEDED entry, for something that wants to link
465 against the dynamic linker as a shared library, will know that
466 the shared object is already loaded. */
467 _dl_rtld_libname.name = ((const char *) _dl_loaded->l_addr
468 + ph->p_vaddr);
469 _dl_rtld_libname.next = NULL;
470 _dl_rtld_map.l_libname = &_dl_rtld_libname;
472 /* Ordinarilly, we would get additional names for the loader from
473 our DT_SONAME. This can't happen if we were actually linked as
474 a static executable (detect this case when we have no DYNAMIC).
475 If so, assume the filename component of the interpreter path to
476 be our SONAME, and add it to our name list. */
477 if (_dl_rtld_map.l_ld == NULL)
479 char *p = strrchr (_dl_rtld_libname.name, '/');
480 if (p)
482 _dl_rtld_libname2.name = p+1;
483 _dl_rtld_libname2.next = NULL;
484 _dl_rtld_libname.next = &_dl_rtld_libname2;
488 has_interp = 1;
489 break;
490 case PT_LOAD:
491 /* Remember where the main program starts in memory. */
493 ElfW(Addr) mapstart;
494 mapstart = _dl_loaded->l_addr + (ph->p_vaddr & ~(ph->p_align - 1));
495 if (_dl_loaded->l_map_start > mapstart)
496 _dl_loaded->l_map_start = mapstart;
498 break;
500 if (! _dl_rtld_map.l_libname && _dl_rtld_map.l_name)
502 /* We were invoked directly, so the program might not have a
503 PT_INTERP. */
504 _dl_rtld_libname.name = _dl_rtld_map.l_name;
505 _dl_rtld_libname.next = NULL;
506 _dl_rtld_map.l_libname = &_dl_rtld_libname;
508 else
509 assert (_dl_rtld_map.l_libname); /* How else did we get here? */
511 /* Extract the contents of the dynamic section for easy access. */
512 elf_get_dynamic_info (_dl_loaded->l_ld, _dl_loaded->l_info);
513 if (_dl_loaded->l_info[DT_HASH])
514 /* Set up our cache of pointers into the hash table. */
515 _dl_setup_hash (_dl_loaded);
517 if (mode == verify)
519 /* We were called just to verify that this is a dynamic
520 executable using us as the program interpreter. Exit with an
521 error if we were not able to load the binary or no interpreter
522 is specified (i.e., this is no dynamically linked binary. */
523 if (_dl_loaded->l_ld == NULL)
524 _exit (1);
526 /* We allow here some platform specific code. */
527 #ifdef DISTINGUISH_LIB_VERSIONS
528 DISTINGUISH_LIB_VERSIONS;
529 #endif
530 _exit (has_interp ? 0 : 2);
533 if (! paths_initialized)
534 /* Initialize the data structures for the search paths for shared
535 objects. */
536 _dl_init_paths (library_path);
538 /* Put the link_map for ourselves on the chain so it can be found by
539 name. Note that at this point the global chain of link maps contains
540 exactly one element, which is pointed to by _dl_loaded. */
541 if (! _dl_rtld_map.l_name)
542 /* If not invoked directly, the dynamic linker shared object file was
543 found by the PT_INTERP name. */
544 _dl_rtld_map.l_name = (char *) _dl_rtld_map.l_libname->name;
545 _dl_rtld_map.l_type = lt_library;
546 _dl_loaded->l_next = &_dl_rtld_map;
547 _dl_rtld_map.l_prev = _dl_loaded;
549 /* We have two ways to specify objects to preload: via environment
550 variable and via the file /etc/ld.so.preload. The later can also
551 be used when security is enabled. */
552 preloads = NULL;
553 npreloads = 0;
555 if (preloadlist)
557 /* The LD_PRELOAD environment variable gives list of libraries
558 separated by white space or colons that are loaded before the
559 executable's dependencies and prepended to the global scope
560 list. If the binary is running setuid all elements
561 containing a '/' are ignored since it is insecure. */
562 char *list = strdupa (preloadlist);
563 char *p;
564 while ((p = strsep (&list, " :")) != NULL)
565 if (p[0] != '\0'
566 && (! __libc_enable_secure || strchr (p, '/') == NULL))
568 struct link_map *new_map = _dl_map_object (_dl_loaded, p, 1,
569 lt_library, 0);
570 if (new_map->l_opencount == 1)
571 /* It is no duplicate. */
572 ++npreloads;
576 /* Read the contents of the file. */
577 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
578 PROT_READ | PROT_WRITE);
579 if (file)
581 /* Parse the file. It contains names of libraries to be loaded,
582 separated by white spaces or `:'. It may also contain
583 comments introduced by `#'. */
584 char *problem;
585 char *runp;
586 size_t rest;
588 /* Eliminate comments. */
589 runp = file;
590 rest = file_size;
591 while (rest > 0)
593 char *comment = memchr (runp, '#', rest);
594 if (comment == NULL)
595 break;
597 rest -= comment - runp;
599 *comment = ' ';
600 while (--rest > 0 && *++comment != '\n');
603 /* We have one problematic case: if we have a name at the end of
604 the file without a trailing terminating characters, we cannot
605 place the \0. Handle the case separately. */
606 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
607 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
609 problem = &file[file_size];
610 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
611 && problem[-1] != '\n' && problem[-1] != ':')
612 --problem;
614 if (problem > file)
615 problem[-1] = '\0';
617 else
619 problem = NULL;
620 file[file_size - 1] = '\0';
623 if (file != problem)
625 char *p;
626 runp = file;
627 while ((p = strsep (&runp, ": \t\n")) != NULL)
628 if (p[0] != '\0')
630 struct link_map *new_map = _dl_map_object (_dl_loaded, p, 1,
631 lt_library, 0);
632 if (new_map->l_opencount == 1)
633 /* It is no duplicate. */
634 ++npreloads;
638 if (problem != NULL)
640 char *p = strndupa (problem, file_size - (problem - file));
641 struct link_map *new_map = _dl_map_object (_dl_loaded, p, 1,
642 lt_library, 0);
643 if (new_map->l_opencount == 1)
644 /* It is no duplicate. */
645 ++npreloads;
648 /* We don't need the file anymore. */
649 __munmap (file, file_size);
652 if (npreloads != 0)
654 /* Set up PRELOADS with a vector of the preloaded libraries. */
655 struct link_map *l;
656 preloads = __alloca (npreloads * sizeof preloads[0]);
657 l = _dl_rtld_map.l_next; /* End of the chain before preloads. */
658 i = 0;
661 preloads[i++] = l;
662 l = l->l_next;
663 } while (l);
664 assert (i == npreloads);
667 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
668 specified some libraries to load, these are inserted before the actual
669 dependencies in the executable's searchlist for symbol resolution. */
670 _dl_map_object_deps (_dl_loaded, preloads, npreloads, mode == trace);
672 #ifndef MAP_ANON
673 /* We are done mapping things, so close the zero-fill descriptor. */
674 __close (_dl_zerofd);
675 _dl_zerofd = -1;
676 #endif
678 /* Remove _dl_rtld_map from the chain. */
679 _dl_rtld_map.l_prev->l_next = _dl_rtld_map.l_next;
680 if (_dl_rtld_map.l_next)
681 _dl_rtld_map.l_next->l_prev = _dl_rtld_map.l_prev;
683 if (_dl_rtld_map.l_opencount > 1)
685 /* Some DT_NEEDED entry referred to the interpreter object itself, so
686 put it back in the list of visible objects. We insert it into the
687 chain in symbol search order because gdb uses the chain's order as
688 its symbol search order. */
689 i = 1;
690 while (_dl_loaded->l_searchlist.r_list[i] != &_dl_rtld_map)
691 ++i;
692 _dl_rtld_map.l_prev = _dl_loaded->l_searchlist.r_list[i - 1];
693 _dl_rtld_map.l_next = (i + 1 < _dl_loaded->l_searchlist.r_nlist
694 ? _dl_loaded->l_searchlist.r_list[i + 1]
695 : NULL);
696 assert (_dl_rtld_map.l_prev->l_next == _dl_rtld_map.l_next);
697 _dl_rtld_map.l_prev->l_next = &_dl_rtld_map;
698 if (_dl_rtld_map.l_next)
700 assert (_dl_rtld_map.l_next->l_prev == _dl_rtld_map.l_prev);
701 _dl_rtld_map.l_next->l_prev = &_dl_rtld_map;
705 /* Now let us see whether all libraries are available in the
706 versions we need. */
708 struct version_check_args args;
709 args.doexit = mode == normal;
710 _dl_receive_error (print_missing_version, version_check_doit, &args);
713 if (mode != normal)
715 /* We were run just to list the shared libraries. It is
716 important that we do this before real relocation, because the
717 functions we call below for output may no longer work properly
718 after relocation. */
719 if (! _dl_loaded->l_info[DT_NEEDED])
720 _dl_sysdep_message ("\t", "statically linked\n", NULL);
721 else
723 struct link_map *l;
725 for (l = _dl_loaded->l_next; l; l = l->l_next)
726 if (l->l_opencount == 0)
727 /* The library was not found. */
728 _dl_sysdep_message ("\t", l->l_libname->name, " => not found\n",
729 NULL);
730 else
732 char buf[20], *bp;
733 buf[sizeof buf - 1] = '\0';
734 bp = _itoa_word (l->l_addr, &buf[sizeof buf - 1], 16, 0);
735 while ((size_t) (&buf[sizeof buf - 1] - bp)
736 < sizeof l->l_addr * 2)
737 *--bp = '0';
738 _dl_sysdep_message ("\t", l->l_libname->name, " => ",
739 l->l_name, " (0x", bp, ")\n", NULL);
743 if (mode != trace)
744 for (i = 1; i < _dl_argc; ++i)
746 const ElfW(Sym) *ref = NULL;
747 ElfW(Addr) loadbase = _dl_lookup_symbol (_dl_argv[i], &ref,
748 _dl_loaded->l_scope,
749 "argument",
750 ELF_MACHINE_JMP_SLOT);
751 char buf[20], *bp;
752 buf[sizeof buf - 1] = '\0';
753 bp = _itoa_word (ref->st_value, &buf[sizeof buf - 1], 16, 0);
754 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
755 *--bp = '0';
756 _dl_sysdep_message (_dl_argv[i], " found at 0x", bp, NULL);
757 buf[sizeof buf - 1] = '\0';
758 bp = _itoa_word (loadbase, &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 (" in object at 0x", bp, "\n", NULL);
763 else
765 if (lazy >= 0)
767 /* We have to do symbol dependency testing. */
768 struct relocate_args args;
769 struct link_map *l;
771 args.lazy = lazy;
773 l = _dl_loaded;
774 while (l->l_next)
775 l = l->l_next;
778 if (l != &_dl_rtld_map && l->l_opencount > 0)
780 args.l = l;
781 _dl_receive_error (print_unresolved, relocate_doit,
782 &args);
784 l = l->l_prev;
785 } while (l);
788 #define VERNEEDTAG (DT_NUM + DT_PROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
789 if (version_info)
791 /* Print more information. This means here, print information
792 about the versions needed. */
793 int first = 1;
794 struct link_map *map = _dl_loaded;
796 for (map = _dl_loaded; map != NULL; map = map->l_next)
798 const char *strtab;
799 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
800 ElfW(Verneed) *ent;
802 if (dyn == NULL)
803 continue;
805 strtab = (const char *)
806 (map->l_addr + map->l_info[DT_STRTAB]->d_un.d_ptr);
807 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
809 if (first)
811 _dl_sysdep_message ("\n\tVersion information:\n", NULL);
812 first = 0;
815 _dl_sysdep_message ("\t", (map->l_name[0]
816 ? map->l_name : _dl_argv[0]),
817 ":\n", NULL);
819 while (1)
821 ElfW(Vernaux) *aux;
822 struct link_map *needed;
824 needed = find_needed (strtab + ent->vn_file);
825 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
827 while (1)
829 const char *fname = NULL;
831 _dl_sysdep_message ("\t\t",
832 strtab + ent->vn_file,
833 " (", strtab + aux->vna_name,
834 ") ",
835 (aux->vna_flags
836 & VER_FLG_WEAK
837 ? "[WEAK] " : ""),
838 "=> ", NULL);
840 if (needed != NULL
841 && match_version (strtab+aux->vna_name, needed))
842 fname = needed->l_name;
844 _dl_sysdep_message (fname ?: "not found", "\n",
845 NULL);
847 if (aux->vna_next == 0)
848 /* No more symbols. */
849 break;
851 /* Next symbol. */
852 aux = (ElfW(Vernaux) *) ((char *) aux
853 + aux->vna_next);
856 if (ent->vn_next == 0)
857 /* No more dependencies. */
858 break;
860 /* Next dependency. */
861 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
867 _exit (0);
871 /* Now we have all the objects loaded. Relocate them all except for
872 the dynamic linker itself. We do this in reverse order so that copy
873 relocs of earlier objects overwrite the data written by later
874 objects. We do not re-relocate the dynamic linker itself in this
875 loop because that could result in the GOT entries for functions we
876 call being changed, and that would break us. It is safe to relocate
877 the dynamic linker out of order because it has no copy relocs (we
878 know that because it is self-contained). */
880 struct link_map *l;
881 int consider_profiling = _dl_profile != NULL;
883 /* If we are profiling we also must do lazy reloaction. */
884 lazy |= consider_profiling;
886 l = _dl_loaded;
887 while (l->l_next)
888 l = l->l_next;
891 if (l != &_dl_rtld_map)
892 _dl_relocate_object (l, l->l_scope, lazy, consider_profiling);
894 l = l->l_prev;
895 } while (l);
897 /* Do any necessary cleanups for the startup OS interface code.
898 We do these now so that no calls are made after rtld re-relocation
899 which might be resolved to different functions than we expect.
900 We cannot do this before relocating the other objects because
901 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
902 _dl_sysdep_start_cleanup ();
904 if (_dl_rtld_map.l_opencount > 0)
905 /* There was an explicit ref to the dynamic linker as a shared lib.
906 Re-relocate ourselves with user-controlled symbol definitions. */
907 _dl_relocate_object (&_dl_rtld_map, _dl_loaded->l_scope, 0, 0);
910 /* Now set up the variable which helps the assembler startup code. */
911 _dl_main_searchlist = &_dl_loaded->l_searchlist;
912 _dl_global_scope[0] = &_dl_loaded->l_searchlist;
914 /* Safe the information about the original global scope list since
915 we need it in the memory handling later. */
916 _dl_initial_searchlist = *_dl_main_searchlist;
919 /* Initialize _r_debug. */
920 struct r_debug *r = _dl_debug_initialize (_dl_rtld_map.l_addr);
921 struct link_map *l;
923 l = _dl_loaded;
925 #ifdef ELF_MACHINE_DEBUG_SETUP
927 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
929 ELF_MACHINE_DEBUG_SETUP (l, r);
930 ELF_MACHINE_DEBUG_SETUP (&_dl_rtld_map, r);
932 #else
934 if (l->l_info[DT_DEBUG])
935 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
936 with the run-time address of the r_debug structure */
937 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
939 /* Fill in the pointer in the dynamic linker's own dynamic section, in
940 case you run gdb on the dynamic linker directly. */
941 if (_dl_rtld_map.l_info[DT_DEBUG])
942 _dl_rtld_map.l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
944 #endif
946 /* Notify the debugger that all objects are now mapped in. */
947 r->r_state = RT_ADD;
948 _dl_debug_state ();
951 #ifndef MAP_COPY
952 /* We must munmap() the cache file. */
953 _dl_unload_cache ();
954 #endif
956 /* Now enable profiling if needed. */
957 if (_dl_profile_map != NULL)
958 /* We must prepare the profiling. */
959 _dl_start_profile (_dl_profile_map, _dl_profile_output);
961 /* Once we return, _dl_sysdep_start will invoke
962 the DT_INIT functions and then *USER_ENTRY. */
965 /* This is a little helper function for resolving symbols while
966 tracing the binary. */
967 static void
968 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
969 const char *errstring)
971 if (objname[0] == '\0')
972 objname = _dl_argv[0] ?: "<main program>";
973 _dl_sysdep_error (errstring, " (", objname, ")\n", NULL);
976 /* This is a little helper function for resolving symbols while
977 tracing the binary. */
978 static void
979 print_missing_version (int errcode __attribute__ ((unused)),
980 const char *objname, const char *errstring)
982 _dl_sysdep_error (_dl_argv[0] ?: "<program name unknown>", ": ",
983 objname, ": ", errstring, "\n", NULL);
986 /* Nonzero if any of the debugging options is enabled. */
987 static int any_debug;
989 /* Process the string given as the parameter which explains which debugging
990 options are enabled. */
991 static void
992 process_dl_debug (const char *dl_debug)
994 size_t len;
995 #define separators " ,:"
998 len = 0;
999 /* Skip separating white spaces and commas. */
1000 dl_debug += strspn (dl_debug, separators);
1001 if (*dl_debug != '\0')
1003 len = strcspn (dl_debug, separators);
1005 switch (len)
1007 case 3:
1008 /* This option is not documented since it is not generally
1009 useful. */
1010 if (memcmp (dl_debug, "all", 3) == 0)
1012 _dl_debug_libs = 1;
1013 _dl_debug_impcalls = 1;
1014 _dl_debug_reloc = 1;
1015 _dl_debug_files = 1;
1016 _dl_debug_symbols = 1;
1017 _dl_debug_bindings = 1;
1018 _dl_debug_versions = 1;
1019 any_debug = 1;
1020 continue;
1022 break;
1024 case 4:
1025 if (memcmp (dl_debug, "help", 4) == 0)
1027 _dl_sysdep_message ("\
1028 Valid options for the LD_DEBUG environment variable are:\n\
1030 bindings display information about symbol binding\n\
1031 files display processing of files and libraries\n\
1032 help display this help message and exit\n\
1033 libs display library search paths\n\
1034 reloc display relocation processing\n\
1035 symbols display symbol table processing\n\
1036 versions display version dependencies\n\
1038 To direct the debugging output into a file instead of standard output\n\
1039 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n",
1040 NULL);
1041 _exit (0);
1044 if (memcmp (dl_debug, "libs", 4) == 0)
1046 _dl_debug_libs = 1;
1047 _dl_debug_impcalls = 1;
1048 any_debug = 1;
1049 continue;
1051 break;
1053 case 5:
1054 if (memcmp (dl_debug, "reloc", 5) == 0)
1056 _dl_debug_reloc = 1;
1057 _dl_debug_impcalls = 1;
1058 any_debug = 1;
1059 continue;
1062 if (memcmp (dl_debug, "files", 5) == 0)
1064 _dl_debug_files = 1;
1065 _dl_debug_impcalls = 1;
1066 any_debug = 1;
1067 continue;
1069 break;
1071 case 7:
1072 if (memcmp (dl_debug, "symbols", 7) == 0)
1074 _dl_debug_symbols = 1;
1075 _dl_debug_impcalls = 1;
1076 any_debug = 1;
1077 continue;
1079 break;
1081 case 8:
1082 if (memcmp (dl_debug, "bindings", 8) == 0)
1084 _dl_debug_bindings = 1;
1085 _dl_debug_impcalls = 1;
1086 any_debug = 1;
1087 continue;
1090 if (memcmp (dl_debug, "versions", 8) == 0)
1092 _dl_debug_versions = 1;
1093 _dl_debug_impcalls = 1;
1094 any_debug = 1;
1095 continue;
1097 break;
1099 default:
1100 break;
1104 /* Display a warning and skip everything until next separator. */
1105 char *startp = strndupa (dl_debug, len);
1106 _dl_sysdep_error ("warning: debug option `", startp,
1107 "' unknown; try LD_DEBUG=help\n", NULL);
1111 while (*(dl_debug += len) != '\0');
1114 /* Process all environments variables the dynamic linker must recognize.
1115 Since all of them start with `LD_' we are a bit smarter while finding
1116 all the entries. */
1117 static void
1118 process_envvars (enum mode *modep, int *lazyp)
1120 char **runp = NULL;
1121 char *envline;
1122 enum mode mode = normal;
1123 int bind_now = 0;
1124 char *debug_output = NULL;
1126 /* This is the default place for profiling data file. */
1127 _dl_profile_output = "/var/tmp";
1129 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
1131 size_t len = strcspn (envline, "=") - 3;
1133 switch (len)
1135 case 4:
1136 /* Warning level, verbose or not. */
1137 if (memcmp (&envline[3], "WARN", 4) == 0)
1138 _dl_verbose = envline[8] != '\0';
1139 break;
1141 case 5:
1142 /* Debugging of the dynamic linker? */
1143 if (memcmp (&envline[3], "DEBUG", 5) == 0)
1144 process_dl_debug (&envline[9]);
1145 break;
1147 case 7:
1148 /* Print information about versions. */
1149 if (memcmp (&envline[3], "VERBOSE", 7) == 0)
1151 version_info = envline[11] != '\0';
1152 break;
1155 /* List of objects to be preloaded. */
1156 if (memcmp (&envline[3], "PRELOAD", 7) == 0)
1158 preloadlist = &envline[11];
1159 break;
1162 /* Which shared object shall be profiled. */
1163 if (memcmp (&envline[3], "PROFILE", 7) == 0)
1165 _dl_profile = &envline[11];
1166 if (*_dl_profile == '\0')
1167 _dl_profile = NULL;
1169 break;
1171 case 8:
1172 /* Do we bind early? */
1173 if (memcmp (&envline[3], "BIND_NOW", 8) == 0
1174 && (envline[12] == '1' || envline[12] == 'y'
1175 || envline[12] == 'Y'
1176 || ((envline[12] == 'o' || envline[12] == 'O')
1177 && (envline[13] == 'n' || envline[13] == 'N'))))
1178 bind_now = 1;
1179 break;
1181 case 9:
1182 /* Test whether we want to see the content of the auxiliary
1183 array passed up from the kernel. */
1184 if (memcmp (&envline[3], "SHOW_AUXV", 9) == 0)
1185 _dl_show_auxv ();
1186 break;
1188 case 10:
1189 /* Mask for the important hardware capabilities. */
1190 if (memcmp (&envline[3], "HWCAP_MASK", 10) == 0)
1191 _dl_hwcap_mask = strtoul (&envline[14], NULL, 0);
1192 break;
1194 case 11:
1195 /* Path where the binary is found. */
1196 if (!__libc_enable_secure
1197 && memcmp (&envline[3], "ORIGIN_PATH", 11) == 0)
1198 _dl_origin_path = &envline[15];
1199 break;
1201 case 12:
1202 /* Where to place the profiling data file. */
1203 if (memcmp (&envline[3], "DEBUG_OUTPUT", 12) == 0)
1205 debug_output = &envline[16];
1206 break;
1209 /* The library search path. */
1210 if (memcmp (&envline[3], "LIBRARY_PATH", 12) == 0)
1211 library_path = &envline[16];
1212 break;
1214 case 14:
1215 /* Where to place the profiling data file. */
1216 if (!__libc_enable_secure
1217 && memcmp (&envline[3], "PROFILE_OUTPUT", 14) == 0)
1219 _dl_profile_output = &envline[18];
1220 if (*_dl_profile_output == '\0')
1221 _dl_profile_output = "/var/tmp";
1223 break;
1225 case 20:
1226 /* The mode of the dynamic linker can be set. */
1227 if (memcmp (&envline[3], "TRACE_LOADED_OBJECTS", 20) == 0)
1228 mode = trace;
1229 break;
1231 /* We might have some extra environment variable to handle. This
1232 is tricky due to the pre-processing of the length of the name
1233 in the switch statement here. The code here assumes that added
1234 environment variables have a different length. */
1235 #ifdef EXTRA_LD_ENVVARS
1236 EXTRA_LD_ENVVARS
1237 #endif
1241 /* Extra security for SUID binaries. Remove all dangerous environment
1242 variables. */
1243 if (__libc_enable_secure)
1245 static const char *unsecure_envvars[] =
1247 #ifdef EXTRA_UNSECURE_ENVVARS
1248 EXTRA_UNSECURE_ENVVARS
1249 #endif
1251 size_t cnt;
1253 if (preloadlist != NULL)
1254 unsetenv ("LD_PRELOAD");
1255 if (library_path != NULL)
1256 unsetenv ("LD_LIBRARY_PATH");
1258 for (cnt = 0;
1259 cnt < sizeof (unsecure_envvars) / sizeof (unsecure_envvars[0]);
1260 ++cnt)
1261 unsetenv (unsecure_envvars[cnt]);
1264 /* If we have to run the dynamic linker in debugging mode and the
1265 LD_DEBUG_OUTPUT environment variable is given, we write the debug
1266 messages to this file. */
1267 if (any_debug && debug_output != NULL && !__libc_enable_secure)
1269 size_t name_len = strlen (debug_output);
1270 char buf[name_len + 12];
1271 char *startp;
1273 buf[name_len + 11] = '\0';
1274 startp = _itoa_word (__getpid (), &buf[name_len + 11], 10, 0);
1275 *--startp = '.';
1276 startp = memcpy (startp - name_len, debug_output, name_len);
1278 _dl_debug_fd = __open (startp, O_WRONLY | O_APPEND | O_CREAT, 0666);
1279 if (_dl_debug_fd == -1)
1280 /* We use standard output if opening the file failed. */
1281 _dl_debug_fd = STDOUT_FILENO;
1284 /* LAZY is determined by the environment variable LD_WARN and
1285 LD_BIND_NOW if we trace the binary. */
1286 if (mode == trace)
1287 *lazyp = _dl_verbose ? !bind_now : -1;
1288 else
1289 *lazyp = !__libc_enable_secure && !bind_now;
1291 *modep = mode;