Update.
[glibc.git] / elf / rtld.c
blob7216c19aabdf6d987cb46df11243101d912e163c
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 "dynamic-link.h"
29 #include "dl-librecon.h"
31 #include <assert.h>
33 /* System-specific function to do initial startup for the dynamic linker.
34 After this, file access calls and getenv must work. This is responsible
35 for setting __libc_enable_secure if we need to be secure (e.g. setuid),
36 and for setting _dl_argc and _dl_argv, and then calling _dl_main. */
37 extern ElfW(Addr) _dl_sysdep_start (void **start_argptr,
38 void (*dl_main) (const ElfW(Phdr) *phdr,
39 ElfW(Half) phent,
40 ElfW(Addr) *user_entry));
41 extern void _dl_sysdep_start_cleanup (void);
43 /* This function is used to unload the cache file if necessary. */
44 extern void _dl_unload_cache (void);
46 /* System-dependent function to read a file's whole contents
47 in the most convenient manner available. */
48 extern void *_dl_sysdep_read_whole_file (const char *filename,
49 size_t *filesize_ptr,
50 int mmap_prot);
52 /* Helper function to handle errors while resolving symbols. */
53 static void print_unresolved (int errcode, const char *objname,
54 const char *errsting);
56 /* Helper function to handle errors when a version is missing. */
57 static void print_missing_version (int errcode, const char *objname,
58 const char *errsting);
61 /* This is a list of all the modes the dynamic loader can be in. */
62 enum mode { normal, list, verify, trace };
64 /* Process all environments variables the dynamic linker must recognize.
65 Since all of them start with `LD_' we are a bit smarter while finding
66 all the entries. */
67 static void process_envvars (enum mode *modep, int *lazyp);
69 int _dl_argc;
70 char **_dl_argv;
71 unsigned int _dl_skip_args; /* Nonzero if we were run directly. */
72 const char *_dl_rpath;
73 int _dl_verbose;
74 const char *_dl_platform;
75 size_t _dl_platformlen;
76 unsigned long _dl_hwcap;
77 struct r_search_path *_dl_search_paths;
78 const char *_dl_profile;
79 const char *_dl_profile_output;
80 struct link_map *_dl_profile_map;
81 int _dl_debug_libs;
82 int _dl_debug_impcalls;
83 int _dl_debug_bindings;
84 int _dl_debug_symbols;
85 int _dl_debug_versions;
86 int _dl_debug_reloc;
87 int _dl_debug_files;
88 const char *_dl_inhibit_rpath; /* RPATH values which should be
89 ignored. */
90 const char *_dl_origin_path;
92 /* This is a pointer to the map for the main object and through it to
93 all loaded objects. */
94 struct link_map *_dl_loaded;
95 /* Pointer to the l_searchlist element of the link map of the main object. */
96 struct r_scope_elem *_dl_main_searchlist;
97 /* Array which is used when looking up in the global scope. */
98 struct r_scope_elem *_dl_global_scope[2];
100 /* Set nonzero during loading and initialization of executable and
101 libraries, cleared before the executable's entry point runs. This
102 must not be initialized to nonzero, because the unused dynamic
103 linker loaded in for libc.so's "ld.so.1" dep will provide the
104 definition seen by libc.so's initializer; that value must be zero,
105 and will be since that dynamic linker's _dl_start and dl_main will
106 never be called. */
107 int _dl_starting_up;
110 static void dl_main (const ElfW(Phdr) *phdr,
111 ElfW(Half) phent,
112 ElfW(Addr) *user_entry);
114 struct link_map _dl_rtld_map;
115 struct libname_list _dl_rtld_libname;
116 struct libname_list _dl_rtld_libname2;
118 #ifdef RTLD_START
119 RTLD_START
120 #else
121 #error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
122 #endif
124 static ElfW(Addr)
125 _dl_start (void *arg)
127 struct link_map bootstrap_map;
129 /* This #define produces dynamic linking inline functions for
130 bootstrap relocation instead of general-purpose relocation. */
131 #define RTLD_BOOTSTRAP
132 #define RESOLVE(sym, version, flags) bootstrap_map.l_addr
133 #include "dynamic-link.h"
135 /* Figure out the run-time load address of the dynamic linker itself. */
136 bootstrap_map.l_addr = elf_machine_load_address ();
138 /* Read our own dynamic section and fill in the info array. */
139 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
140 elf_get_dynamic_info (bootstrap_map.l_ld, bootstrap_map.l_info);
142 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
143 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
144 #endif
146 /* Relocate ourselves so we can do normal function calls and
147 data access using the global offset table. */
149 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
150 /* Please note that we don't allow profiling of this object and
151 therefore need not test whether we have to allocate the array
152 for the relocation results (as done in dl-reloc.c). */
154 /* Now life is sane; we can call functions and access global data.
155 Set up to use the operating system facilities, and find out from
156 the operating system's program loader where to find the program
157 header table in core. */
159 /* Transfer data about ourselves to the permanent link_map structure. */
160 _dl_rtld_map.l_addr = bootstrap_map.l_addr;
161 _dl_rtld_map.l_ld = bootstrap_map.l_ld;
162 _dl_rtld_map.l_opencount = 1;
163 memcpy (_dl_rtld_map.l_info, bootstrap_map.l_info,
164 sizeof _dl_rtld_map.l_info);
165 _dl_setup_hash (&_dl_rtld_map);
167 /* Cache the DT_RPATH stored in ld.so itself; this will be
168 the default search path. */
169 if (_dl_rtld_map.l_info[DT_STRTAB] && _dl_rtld_map.l_info[DT_RPATH])
171 _dl_rpath = (void *) (_dl_rtld_map.l_addr +
172 _dl_rtld_map.l_info[DT_STRTAB]->d_un.d_ptr +
173 _dl_rtld_map.l_info[DT_RPATH]->d_un.d_val);
176 /* Don't bother trying to work out how ld.so is mapped in memory. */
177 _dl_rtld_map.l_map_start = ~0;
178 _dl_rtld_map.l_map_end = ~0;
180 /* Call the OS-dependent function to set up life so we can do things like
181 file access. It will call `dl_main' (below) to do all the real work
182 of the dynamic linker, and then unwind our frame and run the user
183 entry point on the same stack we entered on. */
184 return _dl_sysdep_start (arg, &dl_main);
187 /* Now life is peachy; we can do all normal operations.
188 On to the real work. */
190 void ENTRY_POINT (void);
192 /* Some helper functions. */
194 /* Arguments to relocate_doit. */
195 struct relocate_args
197 struct link_map *l;
198 int lazy;
201 struct map_args
203 /* Argument to map_doit. */
204 char *str;
205 /* Return value of map_doit. */
206 struct link_map *main_map;
209 /* Arguments to version_check_doit. */
210 struct version_check_args
212 int doexit;
215 static void
216 relocate_doit (void *a)
218 struct relocate_args *args = (struct relocate_args *) a;
220 _dl_relocate_object (args->l, args->l->l_scope,
221 args->lazy, 0);
224 static void
225 map_doit (void *a)
227 struct map_args *args = (struct map_args *) a;
228 args->main_map = _dl_map_object (NULL, args->str, 0, lt_library, 0);
231 static void
232 version_check_doit (void *a)
234 struct version_check_args *args = (struct version_check_args *) a;
235 if (_dl_check_all_versions (_dl_loaded, 1) && args->doexit)
236 /* We cannot start the application. Abort now. */
237 _exit (1);
241 static inline struct link_map *
242 find_needed (const char *name)
244 unsigned int n = _dl_loaded->l_searchlist.r_nlist;
246 while (n-- > 0)
247 if (_dl_name_match_p (name, _dl_loaded->l_searchlist.r_list[n]))
248 return _dl_loaded->l_searchlist.r_list[n];
250 /* Should never happen. */
251 return NULL;
254 static int
255 match_version (const char *string, struct link_map *map)
257 const char *strtab = (const char *) (map->l_addr
258 + map->l_info[DT_STRTAB]->d_un.d_ptr);
259 ElfW(Verdef) *def;
261 #define VERDEFTAG (DT_NUM + DT_PROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
262 if (map->l_info[VERDEFTAG] == NULL)
263 /* The file has no symbol versioning. */
264 return 0;
266 def = (ElfW(Verdef) *) ((char *) map->l_addr
267 + map->l_info[VERDEFTAG]->d_un.d_ptr);
268 while (1)
270 ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
272 /* Compare the version strings. */
273 if (strcmp (string, strtab + aux->vda_name) == 0)
274 /* Bingo! */
275 return 1;
277 /* If no more definitions we failed to find what we want. */
278 if (def->vd_next == 0)
279 break;
281 /* Next definition. */
282 def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
285 return 0;
288 static const char *library_path; /* The library search path. */
289 static const char *preloadlist; /* The list preloaded objects. */
290 static int version_info; /* Nonzero if information about
291 versions has to be printed. */
293 static void
294 dl_main (const ElfW(Phdr) *phdr,
295 ElfW(Half) phent,
296 ElfW(Addr) *user_entry)
298 const ElfW(Phdr) *ph;
299 int lazy;
300 enum mode mode;
301 struct link_map **preloads;
302 unsigned int npreloads;
303 size_t file_size;
304 char *file;
305 int has_interp = 0;
306 unsigned int i;
307 int paths_initialized = 0;
309 /* Process the environment variable which control the behaviour. */
310 process_envvars (&mode, &lazy);
312 /* Set up a flag which tells we are just starting. */
313 _dl_starting_up = 1;
315 if (*user_entry == (ElfW(Addr)) &ENTRY_POINT)
317 /* Ho ho. We are not the program interpreter! We are the program
318 itself! This means someone ran ld.so as a command. Well, that
319 might be convenient to do sometimes. We support it by
320 interpreting the args like this:
322 ld.so PROGRAM ARGS...
324 The first argument is the name of a file containing an ELF
325 executable we will load and run with the following arguments.
326 To simplify life here, PROGRAM is searched for using the
327 normal rules for shared objects, rather than $PATH or anything
328 like that. We just load it and use its entry point; we don't
329 pay attention to its PT_INTERP command (we are the interpreter
330 ourselves). This is an easy way to test a new ld.so before
331 installing it. */
333 /* Note the place where the dynamic linker actually came from. */
334 _dl_rtld_map.l_name = _dl_argv[0];
336 while (_dl_argc > 1)
337 if (! strcmp (_dl_argv[1], "--list"))
339 mode = list;
340 lazy = -1; /* This means do no dependency analysis. */
342 ++_dl_skip_args;
343 --_dl_argc;
344 ++_dl_argv;
346 else if (! strcmp (_dl_argv[1], "--verify"))
348 mode = verify;
350 ++_dl_skip_args;
351 --_dl_argc;
352 ++_dl_argv;
354 else if (! strcmp (_dl_argv[1], "--library-path") && _dl_argc > 2)
356 library_path = _dl_argv[2];
358 _dl_skip_args += 2;
359 _dl_argc -= 2;
360 _dl_argv += 2;
362 else if (! strcmp (_dl_argv[1], "--inhibit-rpath") && _dl_argc > 2)
364 _dl_inhibit_rpath = _dl_argv[2];
366 _dl_skip_args += 2;
367 _dl_argc -= 2;
368 _dl_argv += 2;
370 else
371 break;
373 /* If we have no further argument the program was called incorrectly.
374 Grant the user some education. */
375 if (_dl_argc < 2)
376 _dl_sysdep_fatal ("\
377 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
378 You have invoked `ld.so', the helper program for shared library executables.\n\
379 This program usually lives in the file `/lib/ld.so', and special directives\n\
380 in executable files using ELF shared libraries tell the system's program\n\
381 loader to load the helper program from this file. This helper program loads\n\
382 the shared libraries needed by the program executable, prepares the program\n\
383 to run, and runs it. You may invoke this helper program directly from the\n\
384 command line to load and run an ELF executable file; this is like executing\n\
385 that file itself, but always uses this helper program from the file you\n\
386 specified, instead of the helper program file specified in the executable\n\
387 file you run. This is mostly of use for maintainers to test new versions\n\
388 of this helper program; chances are you did not intend to run this program.\n\
390 --list list all dependencies and how they are resolved\n\
391 --verify verify that given object really is a dynamically linked\n\
392 object we get handle\n\
393 --library-path PATH use given PATH instead of content of the environment\n\
394 variable LD_LIBRARY_PATH\n\
395 --inhibit-rpath LIST ignore RPATH information in object names in LIST\n",
396 NULL);
398 ++_dl_skip_args;
399 --_dl_argc;
400 ++_dl_argv;
402 /* Initialize the data structures for the search paths for shared
403 objects. */
404 _dl_init_paths (library_path);
405 paths_initialized = 1;
407 if (mode == verify)
409 char *err_str = NULL;
410 struct map_args args;
412 args.str = _dl_argv[0];
413 (void) _dl_catch_error (&err_str, map_doit, &args);
414 if (err_str != NULL)
416 free (err_str);
417 _exit (EXIT_FAILURE);
420 else
421 _dl_map_object (NULL, _dl_argv[0], 0, lt_library, 0);
423 phdr = _dl_loaded->l_phdr;
424 phent = _dl_loaded->l_phnum;
425 /* We overwrite here a pointer to a malloc()ed string. But since
426 the malloc() implementation used at this point is the dummy
427 implementations which has no real free() function it does not
428 makes sense to free the old string first. */
429 _dl_loaded->l_name = (char *) "";
430 *user_entry = _dl_loaded->l_entry;
432 else
434 /* Create a link_map for the executable itself.
435 This will be what dlopen on "" returns. */
436 _dl_new_object ((char *) "", "", lt_executable, NULL);
437 if (_dl_loaded == NULL)
438 _dl_sysdep_fatal ("cannot allocate memory for link map\n", NULL);
439 _dl_loaded->l_phdr = phdr;
440 _dl_loaded->l_phnum = phent;
441 _dl_loaded->l_entry = *user_entry;
442 _dl_loaded->l_opencount = 1;
444 /* We delay initializing the path structure until we got the dynamic
445 information for the program. */
448 /* It is not safe to load stuff after the main program. */
449 _dl_loaded->l_map_end = ~0;
450 /* Perhaps the executable has no PT_LOAD header entries at all. */
451 _dl_loaded->l_map_start = ~0;
453 /* Scan the program header table for the dynamic section. */
454 for (ph = phdr; ph < &phdr[phent]; ++ph)
455 switch (ph->p_type)
457 case PT_PHDR:
458 /* Find out the load address. */
459 _dl_loaded->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
460 break;
461 case PT_DYNAMIC:
462 /* This tells us where to find the dynamic section,
463 which tells us everything we need to do. */
464 _dl_loaded->l_ld = (void *) _dl_loaded->l_addr + ph->p_vaddr;
465 break;
466 case PT_INTERP:
467 /* This "interpreter segment" was used by the program loader to
468 find the program interpreter, which is this program itself, the
469 dynamic linker. We note what name finds us, so that a future
470 dlopen call or DT_NEEDED entry, for something that wants to link
471 against the dynamic linker as a shared library, will know that
472 the shared object is already loaded. */
473 _dl_rtld_libname.name = ((const char *) _dl_loaded->l_addr
474 + ph->p_vaddr);
475 _dl_rtld_libname.next = NULL;
476 _dl_rtld_map.l_libname = &_dl_rtld_libname;
478 /* Ordinarilly, we would get additional names for the loader from
479 our DT_SONAME. This can't happen if we were actually linked as
480 a static executable (detect this case when we have no DYNAMIC).
481 If so, assume the filename component of the interpreter path to
482 be our SONAME, and add it to our name list. */
483 if (_dl_rtld_map.l_ld == NULL)
485 char *p = strrchr (_dl_rtld_libname.name, '/');
486 if (p)
488 _dl_rtld_libname2.name = p+1;
489 _dl_rtld_libname2.next = NULL;
490 _dl_rtld_libname.next = &_dl_rtld_libname2;
494 has_interp = 1;
495 break;
496 case PT_LOAD:
497 /* Remember where the main program starts in memory. */
499 ElfW(Addr) mapstart;
500 mapstart = _dl_loaded->l_addr + (ph->p_vaddr & ~(ph->p_align - 1));
501 if (_dl_loaded->l_map_start > mapstart)
502 _dl_loaded->l_map_start = mapstart;
504 break;
506 if (! _dl_rtld_map.l_libname && _dl_rtld_map.l_name)
508 /* We were invoked directly, so the program might not have a
509 PT_INTERP. */
510 _dl_rtld_libname.name = _dl_rtld_map.l_name;
511 _dl_rtld_libname.next = NULL;
512 _dl_rtld_map.l_libname = &_dl_rtld_libname;
514 else
515 assert (_dl_rtld_map.l_libname); /* How else did we get here? */
517 /* Extract the contents of the dynamic section for easy access. */
518 elf_get_dynamic_info (_dl_loaded->l_ld, _dl_loaded->l_info);
519 if (_dl_loaded->l_info[DT_HASH])
520 /* Set up our cache of pointers into the hash table. */
521 _dl_setup_hash (_dl_loaded);
523 if (mode == verify)
525 /* We were called just to verify that this is a dynamic
526 executable using us as the program interpreter. Exit with an
527 error if we were not able to load the binary or no interpreter
528 is specified (i.e., this is no dynamically linked binary. */
529 if (_dl_loaded->l_ld == NULL)
530 _exit (1);
532 /* We allow here some platform specific code. */
533 #ifdef DISTINGUISH_LIB_VERSIONS
534 DISTINGUISH_LIB_VERSIONS;
535 #endif
536 _exit (has_interp ? 0 : 2);
539 if (! paths_initialized)
540 /* Initialize the data structures for the search paths for shared
541 objects. */
542 _dl_init_paths (library_path);
544 /* Put the link_map for ourselves on the chain so it can be found by
545 name. Note that at this point the global chain of link maps contains
546 exactly one element, which is pointed to by _dl_loaded. */
547 if (! _dl_rtld_map.l_name)
548 /* If not invoked directly, the dynamic linker shared object file was
549 found by the PT_INTERP name. */
550 _dl_rtld_map.l_name = (char *) _dl_rtld_map.l_libname->name;
551 _dl_rtld_map.l_type = lt_library;
552 _dl_loaded->l_next = &_dl_rtld_map;
553 _dl_rtld_map.l_prev = _dl_loaded;
555 /* We have two ways to specify objects to preload: via environment
556 variable and via the file /etc/ld.so.preload. The later can also
557 be used when security is enabled. */
558 preloads = NULL;
559 npreloads = 0;
561 if (preloadlist)
563 /* The LD_PRELOAD environment variable gives list of libraries
564 separated by white space or colons that are loaded before the
565 executable's dependencies and prepended to the global scope
566 list. If the binary is running setuid all elements
567 containing a '/' are ignored since it is insecure. */
568 char *list = strdupa (preloadlist);
569 char *p;
570 while ((p = strsep (&list, " :")) != NULL)
571 if (p[0] != '\0'
572 && (! __libc_enable_secure || strchr (p, '/') == NULL))
574 struct link_map *new_map = _dl_map_object (_dl_loaded, p, 1,
575 lt_library, 0);
576 if (new_map->l_opencount == 1)
577 /* It is no duplicate. */
578 ++npreloads;
582 /* Read the contents of the file. */
583 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
584 PROT_READ | PROT_WRITE);
585 if (file)
587 /* Parse the file. It contains names of libraries to be loaded,
588 separated by white spaces or `:'. It may also contain
589 comments introduced by `#'. */
590 char *problem;
591 char *runp;
592 size_t rest;
594 /* Eliminate comments. */
595 runp = file;
596 rest = file_size;
597 while (rest > 0)
599 char *comment = memchr (runp, '#', rest);
600 if (comment == NULL)
601 break;
603 rest -= comment - runp;
605 *comment = ' ';
606 while (--rest > 0 && *++comment != '\n');
609 /* We have one problematic case: if we have a name at the end of
610 the file without a trailing terminating characters, we cannot
611 place the \0. Handle the case separately. */
612 if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
613 && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
615 problem = &file[file_size];
616 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
617 && problem[-1] != '\n' && problem[-1] != ':')
618 --problem;
620 if (problem > file)
621 problem[-1] = '\0';
623 else
625 problem = NULL;
626 file[file_size - 1] = '\0';
629 if (file != problem)
631 char *p;
632 runp = file;
633 while ((p = strsep (&runp, ": \t\n")) != NULL)
634 if (p[0] != '\0')
636 struct link_map *new_map = _dl_map_object (_dl_loaded, p, 1,
637 lt_library, 0);
638 if (new_map->l_opencount == 1)
639 /* It is no duplicate. */
640 ++npreloads;
644 if (problem != NULL)
646 char *p = strndupa (problem, file_size - (problem - file));
647 struct link_map *new_map = _dl_map_object (_dl_loaded, p, 1,
648 lt_library, 0);
649 if (new_map->l_opencount == 1)
650 /* It is no duplicate. */
651 ++npreloads;
654 /* We don't need the file anymore. */
655 __munmap (file, file_size);
658 if (npreloads != 0)
660 /* Set up PRELOADS with a vector of the preloaded libraries. */
661 struct link_map *l;
662 preloads = __alloca (npreloads * sizeof preloads[0]);
663 l = _dl_rtld_map.l_next; /* End of the chain before preloads. */
664 i = 0;
667 preloads[i++] = l;
668 l = l->l_next;
669 } while (l);
670 assert (i == npreloads);
673 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
674 specified some libraries to load, these are inserted before the actual
675 dependencies in the executable's searchlist for symbol resolution. */
676 _dl_map_object_deps (_dl_loaded, preloads, npreloads, mode == trace);
678 #ifndef MAP_ANON
679 /* We are done mapping things, so close the zero-fill descriptor. */
680 __close (_dl_zerofd);
681 _dl_zerofd = -1;
682 #endif
684 /* Remove _dl_rtld_map from the chain. */
685 _dl_rtld_map.l_prev->l_next = _dl_rtld_map.l_next;
686 if (_dl_rtld_map.l_next)
687 _dl_rtld_map.l_next->l_prev = _dl_rtld_map.l_prev;
689 if (_dl_rtld_map.l_opencount > 1)
691 /* Some DT_NEEDED entry referred to the interpreter object itself, so
692 put it back in the list of visible objects. We insert it into the
693 chain in symbol search order because gdb uses the chain's order as
694 its symbol search order. */
695 i = 1;
696 while (_dl_loaded->l_searchlist.r_list[i] != &_dl_rtld_map)
697 ++i;
698 _dl_rtld_map.l_prev = _dl_loaded->l_searchlist.r_list[i - 1];
699 _dl_rtld_map.l_next = (i + 1 < _dl_loaded->l_searchlist.r_nlist
700 ? _dl_loaded->l_searchlist.r_list[i + 1]
701 : NULL);
702 assert (_dl_rtld_map.l_prev->l_next == _dl_rtld_map.l_next);
703 _dl_rtld_map.l_prev->l_next = &_dl_rtld_map;
704 if (_dl_rtld_map.l_next)
706 assert (_dl_rtld_map.l_next->l_prev == _dl_rtld_map.l_prev);
707 _dl_rtld_map.l_next->l_prev = &_dl_rtld_map;
711 /* Now let us see whether all libraries are available in the
712 versions we need. */
714 struct version_check_args args;
715 args.doexit = mode == normal;
716 _dl_receive_error (print_missing_version, version_check_doit, &args);
719 if (mode != normal)
721 /* We were run just to list the shared libraries. It is
722 important that we do this before real relocation, because the
723 functions we call below for output may no longer work properly
724 after relocation. */
725 if (! _dl_loaded->l_info[DT_NEEDED])
726 _dl_sysdep_message ("\t", "statically linked\n", NULL);
727 else
729 struct link_map *l;
731 for (l = _dl_loaded->l_next; l; l = l->l_next)
732 if (l->l_opencount == 0)
733 /* The library was not found. */
734 _dl_sysdep_message ("\t", l->l_libname->name, " => not found\n",
735 NULL);
736 else
738 char buf[20], *bp;
739 buf[sizeof buf - 1] = '\0';
740 bp = _itoa_word (l->l_addr, &buf[sizeof buf - 1], 16, 0);
741 while ((size_t) (&buf[sizeof buf - 1] - bp)
742 < sizeof l->l_addr * 2)
743 *--bp = '0';
744 _dl_sysdep_message ("\t", l->l_libname->name, " => ",
745 l->l_name, " (0x", bp, ")\n", NULL);
749 if (mode != trace)
750 for (i = 1; i < _dl_argc; ++i)
752 const ElfW(Sym) *ref = NULL;
753 ElfW(Addr) loadbase = _dl_lookup_symbol (_dl_argv[i], &ref,
754 _dl_loaded->l_scope,
755 "argument",
756 ELF_MACHINE_JMP_SLOT);
757 char buf[20], *bp;
758 buf[sizeof buf - 1] = '\0';
759 bp = _itoa_word (ref->st_value, &buf[sizeof buf - 1], 16, 0);
760 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
761 *--bp = '0';
762 _dl_sysdep_message (_dl_argv[i], " found at 0x", bp, NULL);
763 buf[sizeof buf - 1] = '\0';
764 bp = _itoa_word (loadbase, &buf[sizeof buf - 1], 16, 0);
765 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
766 *--bp = '0';
767 _dl_sysdep_message (" in object at 0x", bp, "\n", NULL);
769 else
771 if (lazy >= 0)
773 /* We have to do symbol dependency testing. */
774 struct relocate_args args;
775 struct link_map *l;
777 args.lazy = lazy;
779 l = _dl_loaded;
780 while (l->l_next)
781 l = l->l_next;
784 if (l != &_dl_rtld_map && l->l_opencount > 0)
786 args.l = l;
787 _dl_receive_error (print_unresolved, relocate_doit,
788 &args);
790 l = l->l_prev;
791 } while (l);
794 #define VERNEEDTAG (DT_NUM + DT_PROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
795 if (version_info)
797 /* Print more information. This means here, print information
798 about the versions needed. */
799 int first = 1;
800 struct link_map *map = _dl_loaded;
802 for (map = _dl_loaded; map != NULL; map = map->l_next)
804 const char *strtab;
805 ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
806 ElfW(Verneed) *ent;
808 if (dyn == NULL)
809 continue;
811 strtab = (const char *)
812 (map->l_addr + map->l_info[DT_STRTAB]->d_un.d_ptr);
813 ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
815 if (first)
817 _dl_sysdep_message ("\n\tVersion information:\n", NULL);
818 first = 0;
821 _dl_sysdep_message ("\t", (map->l_name[0]
822 ? map->l_name : _dl_argv[0]),
823 ":\n", NULL);
825 while (1)
827 ElfW(Vernaux) *aux;
828 struct link_map *needed;
830 needed = find_needed (strtab + ent->vn_file);
831 aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
833 while (1)
835 const char *fname = NULL;
837 _dl_sysdep_message ("\t\t",
838 strtab + ent->vn_file,
839 " (", strtab + aux->vna_name,
840 ") ",
841 (aux->vna_flags
842 & VER_FLG_WEAK
843 ? "[WEAK] " : ""),
844 "=> ", NULL);
846 if (needed != NULL
847 && match_version (strtab+aux->vna_name, needed))
848 fname = needed->l_name;
850 _dl_sysdep_message (fname ?: "not found", "\n",
851 NULL);
853 if (aux->vna_next == 0)
854 /* No more symbols. */
855 break;
857 /* Next symbol. */
858 aux = (ElfW(Vernaux) *) ((char *) aux
859 + aux->vna_next);
862 if (ent->vn_next == 0)
863 /* No more dependencies. */
864 break;
866 /* Next dependency. */
867 ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
873 _exit (0);
877 /* Now we have all the objects loaded. Relocate them all except for
878 the dynamic linker itself. We do this in reverse order so that copy
879 relocs of earlier objects overwrite the data written by later
880 objects. We do not re-relocate the dynamic linker itself in this
881 loop because that could result in the GOT entries for functions we
882 call being changed, and that would break us. It is safe to relocate
883 the dynamic linker out of order because it has no copy relocs (we
884 know that because it is self-contained). */
886 struct link_map *l;
887 int consider_profiling = _dl_profile != NULL;
889 /* If we are profiling we also must do lazy reloaction. */
890 lazy |= consider_profiling;
892 l = _dl_loaded;
893 while (l->l_next)
894 l = l->l_next;
897 if (l != &_dl_rtld_map)
898 _dl_relocate_object (l, l->l_scope, lazy, consider_profiling);
900 l = l->l_prev;
901 } while (l);
903 /* Do any necessary cleanups for the startup OS interface code.
904 We do these now so that no calls are made after rtld re-relocation
905 which might be resolved to different functions than we expect.
906 We cannot do this before relocating the other objects because
907 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
908 _dl_sysdep_start_cleanup ();
910 if (_dl_rtld_map.l_opencount > 0)
911 /* There was an explicit ref to the dynamic linker as a shared lib.
912 Re-relocate ourselves with user-controlled symbol definitions. */
913 _dl_relocate_object (&_dl_rtld_map, _dl_loaded->l_scope, 0, 0);
916 /* Now set up the variable which helps the assembler startup code. */
917 _dl_main_searchlist = &_dl_loaded->l_searchlist;
918 _dl_global_scope[0] = &_dl_loaded->l_searchlist;
921 /* Initialize _r_debug. */
922 struct r_debug *r = _dl_debug_initialize (_dl_rtld_map.l_addr);
923 struct link_map *l;
925 l = _dl_loaded;
927 #ifdef ELF_MACHINE_DEBUG_SETUP
929 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
931 ELF_MACHINE_DEBUG_SETUP (l, r);
932 ELF_MACHINE_DEBUG_SETUP (&_dl_rtld_map, r);
934 #else
936 if (l->l_info[DT_DEBUG])
937 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
938 with the run-time address of the r_debug structure */
939 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
941 /* Fill in the pointer in the dynamic linker's own dynamic section, in
942 case you run gdb on the dynamic linker directly. */
943 if (_dl_rtld_map.l_info[DT_DEBUG])
944 _dl_rtld_map.l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
946 #endif
948 /* Notify the debugger that all objects are now mapped in. */
949 r->r_state = RT_ADD;
950 _dl_debug_state ();
953 #ifndef MAP_COPY
954 /* We must munmap() the cache file. */
955 _dl_unload_cache ();
956 #endif
958 /* Now enable profiling if needed. */
959 if (_dl_profile_map != NULL)
960 /* We must prepare the profiling. */
961 _dl_start_profile (_dl_profile_map, _dl_profile_output);
963 /* Once we return, _dl_sysdep_start will invoke
964 the DT_INIT functions and then *USER_ENTRY. */
967 /* This is a little helper function for resolving symbols while
968 tracing the binary. */
969 static void
970 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
971 const char *errstring)
973 if (objname[0] == '\0')
974 objname = _dl_argv[0] ?: "<main program>";
975 _dl_sysdep_error (errstring, " (", objname, ")\n", NULL);
978 /* This is a little helper function for resolving symbols while
979 tracing the binary. */
980 static void
981 print_missing_version (int errcode __attribute__ ((unused)),
982 const char *objname, const char *errstring)
984 _dl_sysdep_error (_dl_argv[0] ?: "<program name unknown>", ": ",
985 objname, ": ", errstring, "\n", NULL);
988 /* Nonzero if any of the debugging options is enabled. */
989 static int any_debug;
991 /* Process the string given as the parameter which explains which debugging
992 options are enabled. */
993 static void
994 process_dl_debug (const char *dl_debug)
996 size_t len;
997 #define separators " ,:"
1000 len = 0;
1001 /* Skip separating white spaces and commas. */
1002 dl_debug += strspn (dl_debug, separators);
1003 if (*dl_debug != '\0')
1005 len = strcspn (dl_debug, separators);
1007 switch (len)
1009 case 3:
1010 /* This option is not documented since it is not generally
1011 useful. */
1012 if (memcmp (dl_debug, "all", 3) == 0)
1014 _dl_debug_libs = 1;
1015 _dl_debug_impcalls = 1;
1016 _dl_debug_reloc = 1;
1017 _dl_debug_files = 1;
1018 _dl_debug_symbols = 1;
1019 _dl_debug_bindings = 1;
1020 _dl_debug_versions = 1;
1021 any_debug = 1;
1022 continue;
1024 break;
1026 case 4:
1027 if (memcmp (dl_debug, "help", 4) == 0)
1029 _dl_sysdep_message ("\
1030 Valid options for the LD_DEBUG environment variable are:\n\
1032 bindings display information about symbol binding\n\
1033 files display processing of files and libraries\n\
1034 help display this help message and exit\n\
1035 libs display library search paths\n\
1036 reloc display relocation processing\n\
1037 symbols display symbol table processing\n\
1038 versions display version dependencies\n\
1040 To direct the debugging output into a file instead of standard output\n\
1041 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n",
1042 NULL);
1043 _exit (0);
1046 if (memcmp (dl_debug, "libs", 4) == 0)
1048 _dl_debug_libs = 1;
1049 _dl_debug_impcalls = 1;
1050 any_debug = 1;
1051 continue;
1053 break;
1055 case 5:
1056 if (memcmp (dl_debug, "reloc", 5) == 0)
1058 _dl_debug_reloc = 1;
1059 _dl_debug_impcalls = 1;
1060 any_debug = 1;
1061 continue;
1064 if (memcmp (dl_debug, "files", 5) == 0)
1066 _dl_debug_files = 1;
1067 _dl_debug_impcalls = 1;
1068 any_debug = 1;
1069 continue;
1071 break;
1073 case 7:
1074 if (memcmp (dl_debug, "symbols", 7) == 0)
1076 _dl_debug_symbols = 1;
1077 _dl_debug_impcalls = 1;
1078 any_debug = 1;
1079 continue;
1081 break;
1083 case 8:
1084 if (memcmp (dl_debug, "bindings", 8) == 0)
1086 _dl_debug_bindings = 1;
1087 _dl_debug_impcalls = 1;
1088 any_debug = 1;
1089 continue;
1092 if (memcmp (dl_debug, "versions", 8) == 0)
1094 _dl_debug_versions = 1;
1095 _dl_debug_impcalls = 1;
1096 any_debug = 1;
1097 continue;
1099 break;
1101 default:
1102 break;
1106 /* Display a warning and skip everything until next separator. */
1107 char *startp = strndupa (dl_debug, len);
1108 _dl_sysdep_error ("warning: debug option `", startp,
1109 "' unknown; try LD_DEBUG=help\n", NULL);
1113 while (*(dl_debug += len) != '\0');
1116 /* Process all environments variables the dynamic linker must recognize.
1117 Since all of them start with `LD_' we are a bit smarter while finding
1118 all the entries. */
1119 static void
1120 process_envvars (enum mode *modep, int *lazyp)
1122 char **runp = NULL;
1123 char *envline;
1124 enum mode mode = normal;
1125 int bind_now = 0;
1126 char *debug_output = NULL;
1128 /* This is the default place for profiling data file. */
1129 _dl_profile_output = "/var/tmp";
1131 while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
1133 size_t len = strcspn (envline, "=") - 3;
1135 switch (len)
1137 case 4:
1138 /* Warning level, verbose or not. */
1139 if (memcmp (&envline[3], "WARN", 4) == 0)
1140 _dl_verbose = envline[8] != '\0';
1141 break;
1143 case 5:
1144 /* Debugging of the dynamic linker? */
1145 if (memcmp (&envline[3], "DEBUG", 5) == 0)
1146 process_dl_debug (&envline[9]);
1147 break;
1149 case 7:
1150 /* Print information about versions. */
1151 if (memcmp (&envline[3], "VERBOSE", 7) == 0)
1153 version_info = envline[11] != '\0';
1154 break;
1157 /* List of objects to be preloaded. */
1158 if (memcmp (&envline[3], "PRELOAD", 7) == 0)
1160 preloadlist = &envline[11];
1161 break;
1164 /* Which shared object shall be profiled. */
1165 if (memcmp (&envline[3], "PROFILE", 7) == 0)
1167 _dl_profile = &envline[11];
1168 if (*_dl_profile == '\0')
1169 _dl_profile = NULL;
1171 break;
1173 case 8:
1174 /* Do we bind early? */
1175 if (memcmp (&envline[3], "BIND_NOW", 8) == 0
1176 && (envline[12] == '1' || envline[12] == 'y'
1177 || envline[12] == 'Y'
1178 || ((envline[12] == 'o' || envline[12] == 'O')
1179 && (envline[13] == 'n' || envline[13] == 'N'))))
1180 bind_now = 1;
1181 break;
1183 case 9:
1184 /* Test whether we want to see the content of the auxiliary
1185 array passed up from the kernel. */
1186 if (memcmp (&envline[3], "SHOW_AUXV", 9) == 0)
1187 _dl_show_auxv ();
1188 break;
1190 case 10:
1191 /* Mask for the important hardware capabilities. */
1192 if (memcmp (&envline[3], "HWCAP_MASK", 10) == 0)
1193 _dl_hwcap_mask = strtoul (&envline[14], NULL, 0);
1194 break;
1196 case 11:
1197 /* Path where the binary is found. */
1198 if (!__libc_enable_secure
1199 && memcmp (&envline[3], "ORIGIN_PATH", 11) == 0)
1200 _dl_origin_path = &envline[15];
1201 break;
1203 case 12:
1204 /* Where to place the profiling data file. */
1205 if (memcmp (&envline[3], "DEBUG_OUTPUT", 12) == 0)
1207 debug_output = &envline[16];
1208 break;
1211 /* The library search path. */
1212 if (memcmp (&envline[3], "LIBRARY_PATH", 12) == 0)
1213 library_path = &envline[16];
1214 break;
1216 case 14:
1217 /* Where to place the profiling data file. */
1218 if (!__libc_enable_secure
1219 && memcmp (&envline[3], "PROFILE_OUTPUT", 14) == 0)
1221 _dl_profile_output = &envline[18];
1222 if (*_dl_profile_output == '\0')
1223 _dl_profile_output = "/var/tmp";
1225 break;
1227 case 20:
1228 /* The mode of the dynamic linker can be set. */
1229 if (memcmp (&envline[3], "TRACE_LOADED_OBJECTS", 20) == 0)
1230 mode = trace;
1231 break;
1233 /* We might have some extra environment variable to handle. This
1234 is tricky due to the pre-processing of the length of the name
1235 in the switch statement here. The code here assumes that added
1236 environment variables have a different length. */
1237 #ifdef EXTRA_LD_ENVVARS
1238 EXTRA_LD_ENVVARS
1239 #endif
1243 /* Extra security for SUID binaries. Remove all dangerous environment
1244 variables. */
1245 if (__libc_enable_secure)
1247 static const char *unsecure_envvars[] =
1249 #ifdef EXTRA_UNSECURE_ENVVARS
1250 EXTRA_UNSECURE_ENVVARS
1251 #endif
1253 size_t cnt;
1255 if (preloadlist != NULL)
1256 unsetenv ("LD_PRELOAD");
1257 if (library_path != NULL)
1258 unsetenv ("LD_LIBRARY_PATH");
1260 for (cnt = 0;
1261 cnt < sizeof (unsecure_envvars) / sizeof (unsecure_envvars[0]);
1262 ++cnt)
1263 unsetenv (unsecure_envvars[cnt]);
1266 /* If we have to run the dynamic linker in debugging mode and the
1267 LD_DEBUG_OUTPUT environment variable is given, we write the debug
1268 messages to this file. */
1269 if (any_debug && debug_output != NULL && !__libc_enable_secure)
1271 size_t name_len = strlen (debug_output);
1272 char buf[name_len + 12];
1273 char *startp;
1275 buf[name_len + 11] = '\0';
1276 startp = _itoa_word (__getpid (), &buf[name_len + 11], 10, 0);
1277 *--startp = '.';
1278 startp = memcpy (startp - name_len, debug_output, name_len);
1280 _dl_debug_fd = __open (startp, O_WRONLY | O_APPEND | O_CREAT, 0666);
1281 if (_dl_debug_fd == -1)
1282 /* We use standard output if opening the file failed. */
1283 _dl_debug_fd = STDOUT_FILENO;
1286 /* LAZY is determined by the environment variable LD_WARN and
1287 LD_BIND_NOW if we trace the binary. */
1288 if (mode == trace)
1289 *lazyp = _dl_verbose ? !bind_now : -1;
1290 else
1291 *lazyp = !__libc_enable_secure && !bind_now;
1293 *modep = mode;