Call _dl_map_object with new argument.
[glibc.git] / elf / rtld.c
blobc7bac88f02416c9cc008e32ba1c604f129ec5f94
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 <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 /* Helper function to handle errors while resolving symbols. */
48 static void print_unresolved (const char *errstring, const char *objname);
51 int _dl_argc;
52 char **_dl_argv;
53 const char *_dl_rpath;
55 /* Set nonzero during loading and initialization of executable and
56 libraries, cleared before the executable's entry point runs. This
57 must not be initialized to nonzero, because the unused dynamic
58 linker loaded in for libc.so's "ld.so.1" dep will provide the
59 definition seen by libc.so's initializer; that value must be zero,
60 and will be since that dynamic linker's _dl_start and dl_main will
61 never be called. */
62 int _dl_starting_up;
64 static void dl_main (const ElfW(Phdr) *phdr,
65 ElfW(Half) phent,
66 ElfW(Addr) *user_entry);
68 struct link_map _dl_rtld_map;
70 #ifdef RTLD_START
71 RTLD_START
72 #else
73 #error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
74 #endif
76 ElfW(Addr)
77 _dl_start (void *arg)
79 struct link_map bootstrap_map;
81 /* This #define produces dynamic linking inline functions for
82 bootstrap relocation instead of general-purpose relocation. */
83 #define RTLD_BOOTSTRAP
84 #define RESOLVE(sym, flags) bootstrap_map.l_addr
85 #include "dynamic-link.h"
87 /* Figure out the run-time load address of the dynamic linker itself. */
88 bootstrap_map.l_addr = elf_machine_load_address ();
90 /* Read our own dynamic section and fill in the info array. */
91 bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
92 elf_get_dynamic_info (bootstrap_map.l_ld, bootstrap_map.l_info);
94 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
95 ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
96 #endif
98 /* Relocate ourselves so we can do normal function calls and
99 data access using the global offset table. */
101 ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0);
104 /* Now life is sane; we can call functions and access global data.
105 Set up to use the operating system facilities, and find out from
106 the operating system's program loader where to find the program
107 header table in core. */
110 /* Transfer data about ourselves to the permanent link_map structure. */
111 _dl_rtld_map.l_addr = bootstrap_map.l_addr;
112 _dl_rtld_map.l_ld = bootstrap_map.l_ld;
113 memcpy (_dl_rtld_map.l_info, bootstrap_map.l_info,
114 sizeof _dl_rtld_map.l_info);
115 _dl_setup_hash (&_dl_rtld_map);
117 /* Cache the DT_RPATH stored in ld.so itself; this will be
118 the default search path. */
119 _dl_rpath = (void *) (_dl_rtld_map.l_addr +
120 _dl_rtld_map.l_info[DT_STRTAB]->d_un.d_ptr +
121 _dl_rtld_map.l_info[DT_RPATH]->d_un.d_val);
123 /* Call the OS-dependent function to set up life so we can do things like
124 file access. It will call `dl_main' (below) to do all the real work
125 of the dynamic linker, and then unwind our frame and run the user
126 entry point on the same stack we entered on. */
127 return _dl_sysdep_start (arg, &dl_main);
131 /* Now life is peachy; we can do all normal operations.
132 On to the real work. */
134 void _start (void);
136 unsigned int _dl_skip_args; /* Nonzero if we were run directly. */
138 static void
139 dl_main (const ElfW(Phdr) *phdr,
140 ElfW(Half) phent,
141 ElfW(Addr) *user_entry)
143 const ElfW(Phdr) *ph;
144 struct link_map *l;
145 int lazy;
146 enum { normal, list, verify, trace } mode;
147 struct link_map **preloads;
148 unsigned int npreloads;
149 const char *preloadlist;
150 size_t file_size;
151 char *file;
153 mode = getenv ("LD_TRACE_LOADED_OBJECTS") != NULL ? trace : normal;
155 /* LAZY is determined by the parameters --datadeps and --function-deps
156 if we trace the binary. */
157 if (mode == trace)
158 lazy = -1;
159 else
160 lazy = !__libc_enable_secure && *(getenv ("LD_BIND_NOW") ?: "") == '\0';
162 /* Set up a flag which tells we are just starting. */
163 _dl_starting_up = 1;
165 if (*user_entry == (ElfW(Addr)) &_start)
167 /* Ho ho. We are not the program interpreter! We are the program
168 itself! This means someone ran ld.so as a command. Well, that
169 might be convenient to do sometimes. We support it by
170 interpreting the args like this:
172 ld.so PROGRAM ARGS...
174 The first argument is the name of a file containing an ELF
175 executable we will load and run with the following arguments.
176 To simplify life here, PROGRAM is searched for using the
177 normal rules for shared objects, rather than $PATH or anything
178 like that. We just load it and use its entry point; we don't
179 pay attention to its PT_INTERP command (we are the interpreter
180 ourselves). This is an easy way to test a new ld.so before
181 installing it. */
182 if (_dl_argc < 2)
183 _dl_sysdep_fatal ("\
184 Usage: ld.so [--list|--verify] EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
185 You have invoked `ld.so', the helper program for shared library executables.\n\
186 This program usually lives in the file `/lib/ld.so', and special directives\n\
187 in executable files using ELF shared libraries tell the system's program\n\
188 loader to load the helper program from this file. This helper program loads\n\
189 the shared libraries needed by the program executable, prepares the program\n\
190 to run, and runs it. You may invoke this helper program directly from the\n\
191 command line to load and run an ELF executable file; this is like executing\n\
192 that file itself, but always uses this helper program from the file you\n\
193 specified, instead of the helper program file specified in the executable\n\
194 file you run. This is mostly of use for maintainers to test new versions\n\
195 of this helper program; chances are you did not intend to run this program.\n",
196 NULL);
198 /* Note the place where the dynamic linker actually came from. */
199 _dl_rtld_map.l_name = _dl_argv[0];
201 while (_dl_argc > 1)
202 if (! strcmp (_dl_argv[1], "--list"))
204 mode = list;
205 lazy = -1; /* This means do no dependency analysis. */
207 ++_dl_skip_args;
208 --_dl_argc;
209 ++_dl_argv;
211 else if (! strcmp (_dl_argv[1], "--verify"))
213 mode = verify;
215 ++_dl_skip_args;
216 --_dl_argc;
217 ++_dl_argv;
219 else if (! strcmp (_dl_argv[1], "--data-relocs"))
221 mode = trace;
222 lazy = 1; /* This means do only data relocation analysis. */
224 ++_dl_skip_args;
225 --_dl_argc;
226 ++_dl_argv;
228 else if (! strcmp (_dl_argv[1], "--function-relocs"))
230 mode = trace;
231 lazy = 0; /* This means do also function relocation analysis. */
233 ++_dl_skip_args;
234 --_dl_argc;
235 ++_dl_argv;
237 else
238 break;
240 ++_dl_skip_args;
241 --_dl_argc;
242 ++_dl_argv;
244 if (mode == verify)
246 void doit (void)
248 l = _dl_map_object (NULL, _dl_argv[0], 0, lt_library, 0);
250 char *err_str = NULL;
251 const char *obj_name __attribute__ ((unused));
253 (void) _dl_catch_error (&err_str, &obj_name, doit);
254 if (err_str != NULL)
256 free (err_str);
257 _exit (EXIT_FAILURE);
260 else
261 l = _dl_map_object (NULL, _dl_argv[0], 0, lt_library, 0);
263 phdr = l->l_phdr;
264 phent = l->l_phnum;
265 l->l_name = (char *) "";
266 *user_entry = l->l_entry;
268 else
270 /* Create a link_map for the executable itself.
271 This will be what dlopen on "" returns. */
272 l = _dl_new_object ((char *) "", "", lt_executable);
273 if (l == NULL)
274 _dl_sysdep_fatal ("cannot allocate memory for link map", NULL);
275 l->l_phdr = phdr;
276 l->l_phnum = phent;
277 l->l_entry = *user_entry;
280 if (l != _dl_loaded)
282 /* GDB assumes that the first element on the chain is the
283 link_map for the executable itself, and always skips it.
284 Make sure the first one is indeed that one. */
285 l->l_prev->l_next = l->l_next;
286 if (l->l_next)
287 l->l_next->l_prev = l->l_prev;
288 l->l_prev = NULL;
289 l->l_next = _dl_loaded;
290 _dl_loaded->l_prev = l;
291 _dl_loaded = l;
294 /* Scan the program header table for the dynamic section. */
295 for (ph = phdr; ph < &phdr[phent]; ++ph)
296 switch (ph->p_type)
298 case PT_DYNAMIC:
299 /* This tells us where to find the dynamic section,
300 which tells us everything we need to do. */
301 l->l_ld = (void *) l->l_addr + ph->p_vaddr;
302 break;
303 case PT_INTERP:
304 /* This "interpreter segment" was used by the program loader to
305 find the program interpreter, which is this program itself, the
306 dynamic linker. We note what name finds us, so that a future
307 dlopen call or DT_NEEDED entry, for something that wants to link
308 against the dynamic linker as a shared library, will know that
309 the shared object is already loaded. */
310 _dl_rtld_map.l_libname = (const char *) l->l_addr + ph->p_vaddr;
311 break;
313 if (! _dl_rtld_map.l_libname && _dl_rtld_map.l_name)
314 /* We were invoked directly, so the program might not have a PT_INTERP. */
315 _dl_rtld_map.l_libname = _dl_rtld_map.l_name;
316 else
317 assert (_dl_rtld_map.l_libname); /* How else did we get here? */
319 if (mode == verify)
320 /* We were called just to verify that this is a dynamic executable
321 using us as the program interpreter. */
322 _exit (l->l_ld == NULL ? EXIT_FAILURE : EXIT_SUCCESS);
324 /* Extract the contents of the dynamic section for easy access. */
325 elf_get_dynamic_info (l->l_ld, l->l_info);
326 if (l->l_info[DT_HASH])
327 /* Set up our cache of pointers into the hash table. */
328 _dl_setup_hash (l);
330 /* Put the link_map for ourselves on the chain so it can be found by
331 name. */
332 if (! _dl_rtld_map.l_name)
333 /* If not invoked directly, the dynamic linker shared object file was
334 found by the PT_INTERP name. */
335 _dl_rtld_map.l_name = (char *) _dl_rtld_map.l_libname;
336 _dl_rtld_map.l_type = lt_library;
337 while (l->l_next)
338 l = l->l_next;
339 l->l_next = &_dl_rtld_map;
340 _dl_rtld_map.l_prev = l;
342 /* We have two ways to specify objects to preload: via environment
343 variable and via the file /etc/ld.so.preload. The later can also
344 be used when security is enabled. */
345 preloads = NULL;
346 npreloads = 0;
348 preloadlist = getenv ("LD_PRELOAD");
349 if (preloadlist)
351 /* The LD_PRELOAD environment variable gives list of libraries
352 separated by white space or colons that are loaded before the
353 executable's dependencies and prepended to the global scope
354 list. If the binary is running setuid all elements
355 containing a '/' are ignored since it is insecure. */
356 char *list = strdupa (preloadlist);
357 char *p;
358 while ((p = strsep (&list, " :")) != NULL)
359 if (! __libc_enable_secure || strchr (p, '/') == NULL)
361 struct link_map *new_map = _dl_map_object (NULL, p, 1, lt_library,
363 if (new_map->l_opencount == 1)
364 /* It is no duplicate. */
365 ++npreloads;
369 /* Read the contents of the file. */
370 file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
371 PROT_READ | PROT_WRITE);
372 if (file)
374 /* Parse the file. It contains names of libraries to be loaded,
375 separated by white spaces or `:'. It may also contain
376 comments introduced by `#'. */
377 char *problem;
378 char *runp;
379 size_t rest;
381 /* Eliminate comments. */
382 runp = file;
383 rest = file_size;
384 while (rest > 0)
386 char *comment = memchr (runp, '#', rest);
387 if (comment == NULL)
388 break;
390 rest -= comment - runp;
392 *comment = ' ';
393 while (--rest > 0 && *++comment != '\n');
396 /* We have one problematic case: if we have a name at the end of
397 the file without a trailing terminating characters, we cannot
398 place the \0. Handle the case separately. */
399 if (file_size > 0 && file[file_size - 1] != ' '
400 && file[file_size - 1] != '\t' && file[file_size - 1] != '\n'
401 && file[file_size - 1] != ':')
403 problem = &file[file_size];
404 while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
405 && problem[-1] != '\n' && problem[-1] != ':')
406 --problem;
408 if (problem > file)
409 problem[-1] = '\0';
411 else
413 problem = NULL;
414 if (file_size > 0)
415 file[file_size - 1] = '\0';
418 if (file_size > 0 && file != problem)
420 char *p;
421 runp = file + strspn (file, ": \t\n");
422 while ((p = strsep (&runp, ": \t\n")) != NULL)
424 struct link_map *new_map = _dl_map_object (NULL, p, 1,
425 lt_library, 0);
426 if (new_map->l_opencount == 1)
427 /* It is no duplicate. */
428 ++npreloads;
430 if (runp != NULL)
431 runp += strspn (runp, ": \t\n");
435 if (problem != NULL)
437 char *p = strndupa (problem, file_size - (problem - file));
438 struct link_map *new_map = _dl_map_object (NULL, p, 1,
439 lt_library, 0);
440 if (new_map->l_opencount == 1)
441 /* It is no duplicate. */
442 ++npreloads;
445 /* We don't need the file anymore. */
446 __munmap (file, file_size);
449 if (npreloads != 0)
451 /* Set up PRELOADS with a vector of the preloaded libraries. */
452 struct link_map *l;
453 unsigned int i;
454 preloads = __alloca (npreloads * sizeof preloads[0]);
455 l = _dl_rtld_map.l_next; /* End of the chain before preloads. */
456 i = 0;
459 preloads[i++] = l;
460 l = l->l_next;
461 } while (l);
462 assert (i == npreloads);
465 /* Load all the libraries specified by DT_NEEDED entries. If LD_PRELOAD
466 specified some libraries to load, these are inserted before the actual
467 dependencies in the executable's searchlist for symbol resolution. */
468 _dl_map_object_deps (l, preloads, npreloads, mode == trace);
470 #ifndef MAP_ANON
471 /* We are done mapping things, so close the zero-fill descriptor. */
472 __close (_dl_zerofd);
473 _dl_zerofd = -1;
474 #endif
476 /* Remove _dl_rtld_map from the chain. */
477 _dl_rtld_map.l_prev->l_next = _dl_rtld_map.l_next;
478 if (_dl_rtld_map.l_next)
479 _dl_rtld_map.l_next->l_prev = _dl_rtld_map.l_prev;
481 if (_dl_rtld_map.l_opencount)
483 /* Some DT_NEEDED entry referred to the interpreter object itself, so
484 put it back in the list of visible objects. We insert it into the
485 chain in symbol search order because gdb uses the chain's order as
486 its symbol search order. */
487 unsigned int i = 1;
488 while (l->l_searchlist[i] != &_dl_rtld_map)
489 ++i;
490 _dl_rtld_map.l_prev = l->l_searchlist[i - 1];
491 _dl_rtld_map.l_next = (i + 1 < l->l_nsearchlist ?
492 l->l_searchlist[i + 1] : NULL);
493 assert (_dl_rtld_map.l_prev->l_next == _dl_rtld_map.l_next);
494 _dl_rtld_map.l_prev->l_next = &_dl_rtld_map;
495 if (_dl_rtld_map.l_next)
497 assert (_dl_rtld_map.l_next->l_prev == _dl_rtld_map.l_prev);
498 _dl_rtld_map.l_next->l_prev = &_dl_rtld_map;
502 if (mode != normal)
504 /* We were run just to list the shared libraries. It is
505 important that we do this before real relocation, because the
506 functions we call below for output may no longer work properly
507 after relocation. */
509 int i;
511 if (! _dl_loaded->l_info[DT_NEEDED])
512 _dl_sysdep_message ("\t", "statically linked\n", NULL);
513 else
514 for (l = _dl_loaded->l_next; l; l = l->l_next)
515 if (l->l_opencount == 0)
516 /* The library was not found. */
517 _dl_sysdep_message ("\t", l->l_libname, " => not found\n", NULL);
518 else
520 char buf[20], *bp;
521 buf[sizeof buf - 1] = '\0';
522 bp = _itoa (l->l_addr, &buf[sizeof buf - 1], 16, 0);
523 while ((size_t) (&buf[sizeof buf - 1] - bp)
524 < sizeof l->l_addr * 2)
525 *--bp = '0';
526 _dl_sysdep_message ("\t", l->l_libname, " => ", l->l_name,
527 " (0x", bp, ")\n", NULL);
530 if (mode != trace)
531 for (i = 1; i < _dl_argc; ++i)
533 const ElfW(Sym) *ref = NULL;
534 ElfW(Addr) loadbase = _dl_lookup_symbol (_dl_argv[i], &ref,
535 &_dl_default_scope[2],
536 "argument",
537 DL_LOOKUP_NOPLT);
538 char buf[20], *bp;
539 buf[sizeof buf - 1] = '\0';
540 bp = _itoa (ref->st_value, &buf[sizeof buf - 1], 16, 0);
541 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
542 *--bp = '0';
543 _dl_sysdep_message (_dl_argv[i], " found at 0x", bp, NULL);
544 buf[sizeof buf - 1] = '\0';
545 bp = _itoa (loadbase, &buf[sizeof buf - 1], 16, 0);
546 while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
547 *--bp = '0';
548 _dl_sysdep_message (" in object at 0x", bp, "\n", NULL);
550 else if (lazy >= 0)
552 /* We have to do symbol dependency testing. */
553 void doit (void)
555 _dl_relocate_object (l, _dl_object_relocation_scope (l), lazy);
558 l = _dl_loaded;
559 while (l->l_next)
560 l = l->l_next;
563 if (l != &_dl_rtld_map && l->l_opencount > 0)
565 _dl_receive_error (print_unresolved, doit);
566 *_dl_global_scope_end = NULL;
568 l = l->l_prev;
569 } while (l);
572 _exit (0);
576 /* Now we have all the objects loaded. Relocate them all except for
577 the dynamic linker itself. We do this in reverse order so that copy
578 relocs of earlier objects overwrite the data written by later
579 objects. We do not re-relocate the dynamic linker itself in this
580 loop because that could result in the GOT entries for functions we
581 call being changed, and that would break us. It is safe to relocate
582 the dynamic linker out of order because it has no copy relocs (we
583 know that because it is self-contained). */
585 l = _dl_loaded;
586 while (l->l_next)
587 l = l->l_next;
590 if (l != &_dl_rtld_map)
592 _dl_relocate_object (l, _dl_object_relocation_scope (l), lazy);
593 *_dl_global_scope_end = NULL;
595 l = l->l_prev;
596 } while (l);
598 /* Do any necessary cleanups for the startup OS interface code.
599 We do these now so that no calls are made after rtld re-relocation
600 which might be resolved to different functions than we expect.
601 We cannot do this before relocating the other objects because
602 _dl_relocate_object might need to call `mprotect' for DT_TEXTREL. */
603 _dl_sysdep_start_cleanup ();
605 if (_dl_rtld_map.l_opencount > 0)
606 /* There was an explicit ref to the dynamic linker as a shared lib.
607 Re-relocate ourselves with user-controlled symbol definitions. */
608 _dl_relocate_object (&_dl_rtld_map, &_dl_default_scope[2], 0);
612 /* Initialize _r_debug. */
613 struct r_debug *r = _dl_debug_initialize (_dl_rtld_map.l_addr);
615 l = _dl_loaded;
617 #ifdef ELF_MACHINE_DEBUG_SETUP
619 /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way. */
621 ELF_MACHINE_DEBUG_SETUP (l, r);
622 ELF_MACHINE_DEBUG_SETUP (&_dl_rtld_map, r);
624 #else
626 if (l->l_info[DT_DEBUG])
627 /* There is a DT_DEBUG entry in the dynamic section. Fill it in
628 with the run-time address of the r_debug structure */
629 l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
631 /* Fill in the pointer in the dynamic linker's own dynamic section, in
632 case you run gdb on the dynamic linker directly. */
633 if (_dl_rtld_map.l_info[DT_DEBUG])
634 _dl_rtld_map.l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
636 #endif
638 /* Notify the debugger that all objects are now mapped in. */
639 r->r_state = RT_ADD;
640 _dl_debug_state ();
643 /* Once we return, _dl_sysdep_start will invoke
644 the DT_INIT functions and then *USER_ENTRY. */
647 /* This is a little helper function for resolving symbols while
648 tracing the binary. */
649 static void
650 print_unresolved (const char *errstring, const char *objname)
652 _dl_sysdep_error (errstring, " (", objname, ")\n", NULL);