update from main archive 961009
[glibc.git] / elf / rtld.c
blob58676924e51baf3854f7f4275628e3d6e0ba4412
1 /* Run time dynamic linker.
2 Copyright (C) 1995, 1996 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
17 not, write to the Free Software Foundation, Inc., 675 Mass Ave,
18 Cambridge, MA 02139, USA. */
20 #include <link.h>
21 #include <stddef.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <sys/mman.h> /* Check if MAP_ANON is defined. */
26 #include "../stdio-common/_itoa.h"
27 #include <assert.h>
28 #include "dynamic-link.h"
31 /* System-specific function to do initial startup for the dynamic linker.
32 After this, file access calls and getenv must work. This is responsible
33 for setting __libc_enable_secure if we need to be secure (e.g. setuid),
34 and for setting _dl_argc and _dl_argv, and then calling _dl_main. */
35 extern ElfW(Addr) _dl_sysdep_start (void **start_argptr,
36 void (*dl_main) (const ElfW(Phdr) *phdr,
37 ElfW(Half) phent,
38 ElfW(Addr) *user_entry));
39 extern void _dl_sysdep_start_cleanup (void);
41 /* System-dependent function to read a file's whole contents
42 in the most convenient manner available. */
43 extern void *_dl_sysdep_read_whole_file (const char *filename,
44 size_t *filesize_ptr,
45 int mmap_prot);
47 int _dl_argc;
48 char **_dl_argv;
49 const char *_dl_rpath;
51 /* Set nonzero during loading and initialization of executable and
52 libraries, cleared before the executable's entry point runs. This
53 must not be initialized to nonzero, because the unused dynamic
54 linker loaded in for libc.so's "ld.so.1" dep will provide the
55 definition seen by libc.so's initializer; that value must be zero,
56 and will be since that dynamic linker's _dl_start and dl_main will
57 never be called. */
58 int _dl_starting_up;
60 static void dl_main (const ElfW(Phdr) *phdr,
61 ElfW(Half) phent,
62 ElfW(Addr) *user_entry);
64 struct link_map _dl_rtld_map;
66 #ifdef RTLD_START
67 RTLD_START
68 #else
69 #error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
70 #endif
72 ElfW(Addr)
73 _dl_start (void *arg)
75 struct link_map bootstrap_map;
77 /* This #define produces dynamic linking inline functions for
78 bootstrap relocation instead of general-purpose relocation. */
79 #define RTLD_BOOTSTRAP
80 #define RESOLVE(sym, flags) bootstrap_map.l_addr
81 #include "dynamic-link.h"
83 /* Figure out the run-time load address of the dynamic linker itself. */
84 bootstrap_map.l_addr = elf_machine_load_address ();
86 /* Read our own dynamic section and fill in the info array.
87 Conveniently, the first element of the GOT contains the
88 offset of _DYNAMIC relative to the run-time load address. */
89 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + *elf_machine_got ();
90 elf_get_dynamic_info (bootstrap_map.l_ld, bootstrap_map.l_info);
92 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
93 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
94 #endif
96 /* Relocate ourselves so we can do normal function calls and
97 data access using the global offset table. */
99 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0);
102 /* Now life is sane; we can call functions and access global data.
103 Set up to use the operating system facilities, and find out from
104 the operating system's program loader where to find the program
105 header table in core. */
108 /* Transfer data about ourselves to the permanent link_map structure. */
109 _dl_rtld_map.l_addr = bootstrap_map.l_addr;
110 _dl_rtld_map.l_ld = bootstrap_map.l_ld;
111 memcpy (_dl_rtld_map.l_info, bootstrap_map.l_info,
112 sizeof _dl_rtld_map.l_info);
113 _dl_setup_hash (&_dl_rtld_map);
115 /* Cache the DT_RPATH stored in ld.so itself; this will be
116 the default search path. */
117 _dl_rpath = (void *) (_dl_rtld_map.l_addr +
118 _dl_rtld_map.l_info[DT_STRTAB]->d_un.d_ptr +
119 _dl_rtld_map.l_info[DT_RPATH]->d_un.d_val);
121 /* Call the OS-dependent function to set up life so we can do things like
122 file access. It will call `dl_main' (below) to do all the real work
123 of the dynamic linker, and then unwind our frame and run the user
124 entry point on the same stack we entered on. */
125 return _dl_sysdep_start (arg, &dl_main);
129 /* Now life is peachy; we can do all normal operations.
130 On to the real work. */
132 void _start (void);
134 unsigned int _dl_skip_args; /* Nonzero if we were run directly. */
136 static void
137 dl_main (const ElfW(Phdr) *phdr,
138 ElfW(Half) phent,
139 ElfW(Addr) *user_entry)
141 const ElfW(Phdr) *ph;
142 struct link_map *l;
143 int lazy;
144 enum { normal, list, verify, trace } mode;
145 struct link_map **preloads;
146 unsigned int npreloads;
147 size_t file_size;
148 char *file;
150 mode = getenv ("LD_TRACE_LOADED_OBJECTS") != NULL ? trace : normal;
152 if (*user_entry == (ElfW(Addr)) &_start)
154 /* Ho ho. We are not the program interpreter! We are the program
155 itself! This means someone ran ld.so as a command. Well, that
156 might be convenient to do sometimes. We support it by
157 interpreting the args like this:
159 ld.so PROGRAM ARGS...
161 The first argument is the name of a file containing an ELF
162 executable we will load and run with the following arguments.
163 To simplify life here, PROGRAM is searched for using the
164 normal rules for shared objects, rather than $PATH or anything
165 like that. We just load it and use its entry point; we don't
166 pay attention to its PT_INTERP command (we are the interpreter
167 ourselves). This is an easy way to test a new ld.so before
168 installing it. */
169 if (_dl_argc < 2)
170 _dl_sysdep_fatal ("\
171 Usage: ld.so [--list|--verify] EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
172 You have invoked `ld.so', the helper program for shared library executables.\n\
173 This program usually lives in the file `/lib/ld.so', and special directives\n\
174 in executable files using ELF shared libraries tell the system's program\n\
175 loader to load the helper program from this file. This helper program loads\n\
176 the shared libraries needed by the program executable, prepares the program\n\
177 to run, and runs it. You may invoke this helper program directly from the\n\
178 command line to load and run an ELF executable file; this is like executing\n\
179 that file itself, but always uses this helper program from the file you\n\
180 specified, instead of the helper program file specified in the executable\n\
181 file you run. This is mostly of use for maintainers to test new versions\n\
182 of this helper program; chances are you did not intend to run this program.\n",
183 NULL);
185 /* Note the place where the dynamic linker actually came from. */
186 _dl_rtld_map.l_name = _dl_argv[0];
188 if (! strcmp (_dl_argv[1], "--list"))
190 mode = list;
192 ++_dl_skip_args;
193 --_dl_argc;
194 ++_dl_argv;
196 else if (! strcmp (_dl_argv[1], "--verify"))
198 mode = verify;
200 ++_dl_skip_args;
201 --_dl_argc;
202 ++_dl_argv;
205 ++_dl_skip_args;
206 --_dl_argc;
207 ++_dl_argv;
209 if (mode == verify)
211 void doit (void)
213 l = _dl_map_object (NULL, _dl_argv[0], lt_library);
215 char *err_str = NULL;
216 const char *obj_name __attribute__ ((unused));
218 (void) _dl_catch_error (&err_str, &obj_name, doit);
219 if (err_str != NULL)
221 free (err_str);
222 _exit (EXIT_FAILURE);
225 else
226 l = _dl_map_object (NULL, _dl_argv[0], lt_library);
228 phdr = l->l_phdr;
229 phent = l->l_phnum;
230 l->l_name = (char *) "";
231 *user_entry = l->l_entry;
233 else
235 /* Create a link_map for the executable itself.
236 This will be what dlopen on "" returns. */
237 l = _dl_new_object ((char *) "", "", lt_executable);
238 l->l_phdr = phdr;
239 l->l_phnum = phent;
240 l->l_entry = *user_entry;
243 if (l != _dl_loaded)
245 /* GDB assumes that the first element on the chain is the
246 link_map for the executable itself, and always skips it.
247 Make sure the first one is indeed that one. */
248 l->l_prev->l_next = l->l_next;
249 if (l->l_next)
250 l->l_next->l_prev = l->l_prev;
251 l->l_prev = NULL;
252 l->l_next = _dl_loaded;
253 _dl_loaded->l_prev = l;
254 _dl_loaded = l;
257 /* Scan the program header table for the dynamic section. */
258 for (ph = phdr; ph < &phdr[phent]; ++ph)
259 switch (ph->p_type)
261 case PT_DYNAMIC:
262 /* This tells us where to find the dynamic section,
263 which tells us everything we need to do. */
264 l->l_ld = (void *) l->l_addr + ph->p_vaddr;
265 break;
266 case PT_INTERP:
267 /* This "interpreter segment" was used by the program loader to
268 find the program interpreter, which is this program itself, the
269 dynamic linker. We note what name finds us, so that a future
270 dlopen call or DT_NEEDED entry, for something that wants to link
271 against the dynamic linker as a shared library, will know that
272 the shared object is already loaded. */
273 _dl_rtld_map.l_libname = (const char *) l->l_addr + ph->p_vaddr;
274 break;
276 if (! _dl_rtld_map.l_libname && _dl_rtld_map.l_name)
277 /* We were invoked directly, so the program might not have a PT_INTERP. */
278 _dl_rtld_map.l_libname = _dl_rtld_map.l_name;
279 else
280 assert (_dl_rtld_map.l_libname); /* How else did we get here? */
282 if (mode == verify)
283 /* We were called just to verify that this is a dynamic executable
284 using us as the program interpreter. */
285 _exit ((strcmp (_dl_rtld_map.l_libname, _dl_rtld_map.l_name) ||
286 l->l_ld == NULL)
287 ? EXIT_FAILURE : EXIT_SUCCESS);
289 /* Extract the contents of the dynamic section for easy access. */
290 elf_get_dynamic_info (l->l_ld, l->l_info);
291 if (l->l_info[DT_HASH])
292 /* Set up our cache of pointers into the hash table. */
293 _dl_setup_hash (l);
295 /* Put the link_map for ourselves on the chain so it can be found by
296 name. */
297 if (! _dl_rtld_map.l_name)
298 /* If not invoked directly, the dynamic linker shared object file was
299 found by the PT_INTERP name. */
300 _dl_rtld_map.l_name = (char *) _dl_rtld_map.l_libname;
301 _dl_rtld_map.l_type = lt_library;
302 while (l->l_next)
303 l = l->l_next;
304 l->l_next = &_dl_rtld_map;
305 _dl_rtld_map.l_prev = l;
307 /* We have two ways to specify objects to preload: via environment
308 variable and via the file /etc/ld.so.preload. The later can also
309 be used when security is enabled. */
310 preloads = NULL;
311 npreloads = 0;
313 if (! __libc_enable_secure)
315 const char *preloadlist = getenv ("LD_PRELOAD");
316 if (preloadlist)
318 /* The LD_PRELOAD environment variable gives a colon-separated
319 list of libraries that are loaded before the executable's
320 dependencies and prepended to the global scope list. */
321 char *list = strdupa (preloadlist);
322 char *p;
323 while ((p = strsep (&list, ":")) != NULL)
325 (void) _dl_map_object (NULL, p, lt_library);
326 ++npreloads;
331 /* Read the contents of the file. */
332 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
333 PROT_READ | PROT_WRITE);
334 if (file)
336 /* Parse the file. It contains names of libraries to be loaded,
337 separated by white spaces or `:'. It may also contain
338 comments introduced by `#'. */
339 char *problem;
340 char *runp;
341 size_t rest;
343 /* Eliminate comments. */
344 runp = file;
345 rest = file_size;
346 while (rest > 0)
348 char *comment = memchr (runp, '#', rest);
349 if (comment == NULL)
350 break;
352 rest -= comment - runp;
354 *comment = ' ';
355 while (--rest > 0 && *++comment != '\n');
358 /* We have one problematic case: if we have a name at the end of
359 the file without a trailing terminating characters, we cannot
360 place the \0. Handle the case separately. */
361 if (file[file_size - 1] != ' ' && file[file_size] != '\t'
362 && file[file_size] != '\n')
364 problem = &file[file_size];
365 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
366 && problem[-1] != '\n')
367 --problem;
369 if (problem > file)
370 problem[-1] = '\0';
372 else
373 problem = NULL;
375 if (file != problem)
377 char *p;
378 runp = file;
379 while ((p = strsep (&runp, ": \t\n")) != NULL)
381 (void) _dl_map_object (NULL, p, lt_library);
382 ++npreloads;
386 if (problem != NULL)
388 char *p = strndupa (problem, file_size - (problem - file));
389 (void) _dl_map_object (NULL, p, lt_library);
392 /* We don't need the file anymore. */
393 __munmap (file, file_size);
396 if (npreloads != 0)
398 /* Set up PRELOADS with a vector of the preloaded libraries. */
399 struct link_map *l;
400 unsigned int i;
401 preloads = __alloca (npreloads * sizeof preloads[0]);
402 l = _dl_rtld_map.l_next; /* End of the chain before preloads. */
403 i = 0;
406 preloads[i++] = l;
407 l = l->l_next;
408 } while (l);
409 assert (i == npreloads);
412 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
413 specified some libraries to load, these are inserted before the actual
414 dependencies in the executable's searchlist for symbol resolution. */
415 _dl_map_object_deps (l, preloads, npreloads);
417 #ifndef MAP_ANON
418 /* We are done mapping things, so close the zero-fill descriptor. */
419 __close (_dl_zerofd);
420 _dl_zerofd = -1;
421 #endif
423 /* Remove _dl_rtld_map from the chain. */
424 _dl_rtld_map.l_prev->l_next = _dl_rtld_map.l_next;
425 if (_dl_rtld_map.l_next)
426 _dl_rtld_map.l_next->l_prev = _dl_rtld_map.l_prev;
428 if (_dl_rtld_map.l_opencount)
430 /* Some DT_NEEDED entry referred to the interpreter object itself, so
431 put it back in the list of visible objects. We insert it into the
432 chain in symbol search order because gdb uses the chain's order as
433 its symbol search order. */
434 unsigned int i = 1;
435 while (l->l_searchlist[i] != &_dl_rtld_map)
436 ++i;
437 _dl_rtld_map.l_prev = l->l_searchlist[i - 1];
438 _dl_rtld_map.l_next = (i + 1 < l->l_nsearchlist ?
439 l->l_searchlist[i + 1] : NULL);
440 assert (_dl_rtld_map.l_prev->l_next == _dl_rtld_map.l_next);
441 _dl_rtld_map.l_prev->l_next = &_dl_rtld_map;
442 if (_dl_rtld_map.l_next)
444 assert (_dl_rtld_map.l_next->l_prev == _dl_rtld_map.l_prev);
445 _dl_rtld_map.l_next->l_prev = &_dl_rtld_map;
449 if (mode != normal)
451 /* We were run just to list the shared libraries. It is
452 important that we do this before real relocation, because the
453 functions we call below for output may no longer work properly
454 after relocation. */
456 int i;
458 if (! _dl_loaded->l_info[DT_NEEDED])
459 _dl_sysdep_message ("\t", "statically linked\n", NULL);
460 else
461 for (l = _dl_loaded->l_next; l; l = l->l_next)
463 char buf[20], *bp;
464 buf[sizeof buf - 1] = '\0';
465 bp = _itoa (l->l_addr, &buf[sizeof buf - 1], 16, 0);
466 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof l->l_addr * 2)
467 *--bp = '0';
468 _dl_sysdep_message ("\t", l->l_libname, " => ", l->l_name,
469 " (0x", bp, ")\n", NULL);
472 if (mode != trace)
473 for (i = 1; i < _dl_argc; ++i)
475 const ElfW(Sym) *ref = NULL;
476 ElfW(Addr) loadbase = _dl_lookup_symbol (_dl_argv[i], &ref,
477 &_dl_default_scope[2],
478 "argument",
479 DL_LOOKUP_NOPLT);
480 char buf[20], *bp;
481 buf[sizeof buf - 1] = '\0';
482 bp = _itoa (ref->st_value, &buf[sizeof buf - 1], 16, 0);
483 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
484 *--bp = '0';
485 _dl_sysdep_message (_dl_argv[i], " found at 0x", bp, NULL);
486 buf[sizeof buf - 1] = '\0';
487 bp = _itoa (loadbase, &buf[sizeof buf - 1], 16, 0);
488 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
489 *--bp = '0';
490 _dl_sysdep_message (" in object at 0x", bp, "\n", NULL);
493 _exit (0);
496 lazy = !__libc_enable_secure && *(getenv ("LD_BIND_NOW") ?: "") == '\0';
499 /* Now we have all the objects loaded. Relocate them all except for
500 the dynamic linker itself. We do this in reverse order so that copy
501 relocs of earlier objects overwrite the data written by later
502 objects. We do not re-relocate the dynamic linker itself in this
503 loop because that could result in the GOT entries for functions we
504 call being changed, and that would break us. It is safe to relocate
505 the dynamic linker out of order because it has no copy relocs (we
506 know that because it is self-contained). */
508 l = _dl_loaded;
509 while (l->l_next)
510 l = l->l_next;
513 if (l != &_dl_rtld_map)
515 _dl_relocate_object (l, _dl_object_relocation_scope (l), lazy);
516 *_dl_global_scope_end = NULL;
518 l = l->l_prev;
519 } while (l);
521 /* Do any necessary cleanups for the startup OS interface code.
522 We do these now so that no calls are made after rtld re-relocation
523 which might be resolved to different functions than we expect.
524 We cannot do this before relocating the other objects because
525 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
526 _dl_sysdep_start_cleanup ();
528 if (_dl_rtld_map.l_opencount > 0)
529 /* There was an explicit ref to the dynamic linker as a shared lib.
530 Re-relocate ourselves with user-controlled symbol definitions. */
531 _dl_relocate_object (&_dl_rtld_map, &_dl_default_scope[2], 0);
535 /* Initialize _r_debug. */
536 struct r_debug *r = _dl_debug_initialize (_dl_rtld_map.l_addr);
538 l = _dl_loaded;
540 #ifdef ELF_MACHINE_DEBUG_SETUP
542 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
544 ELF_MACHINE_DEBUG_SETUP (l, r);
545 ELF_MACHINE_DEBUG_SETUP (&_dl_rtld_map, r);
547 #else
549 if (l->l_info[DT_DEBUG])
550 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
551 with the run-time address of the r_debug structure */
552 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
554 /* Fill in the pointer in the dynamic linker's own dynamic section, in
555 case you run gdb on the dynamic linker directly. */
556 if (_dl_rtld_map.l_info[DT_DEBUG])
557 _dl_rtld_map.l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
559 #endif
561 /* Notify the debugger that all objects are now mapped in. */
562 r->r_state = RT_ADD;
563 _dl_debug_state ();
566 /* We finished the intialization and will start up. */
567 _dl_starting_up = 1;
569 /* Once we return, _dl_sysdep_start will invoke
570 the DT_INIT functions and then *USER_ENTRY. */