Update.
[platform/upstream/glibc.git] / elf / rtld.c
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.
4
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.
9
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.
14
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.  */
19
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"
30
31 #include <assert.h>
32
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);
42
43 /* System-dependent function to read a file's whole contents
44    in the most convenient manner available.  */
45 extern void *_dl_sysdep_read_whole_file (const char *filename,
46                                          size_t *filesize_ptr,
47                                          int mmap_prot);
48
49 /* Helper function to handle errors while resolving symbols.  */
50 static void print_unresolved (int errcode, const char *objname,
51                               const char *errsting);
52
53 /* Helper function to handle errors when a version is missing.  */
54 static void print_missing_version (int errcode, const char *objname,
55                                    const char *errsting);
56
57
58 /* This is a list of all the modes the dynamic loader can be in.  */
59 enum mode { normal, list, verify, trace };
60
61 /* Process all environments variables the dynamic linker must recognize.
62    Since all of them start with `LD_' we are a bit smarter while finding
63    all the entries.  */
64 static void process_envvars (enum mode *modep, int *lazyp);
65
66 int _dl_argc;
67 char **_dl_argv;
68 const char *_dl_rpath;
69 int _dl_verbose;
70 const char *_dl_platform;
71 size_t _dl_platformlen;
72 unsigned long _dl_hwcap;
73 struct r_search_path *_dl_search_paths;
74 const char *_dl_profile;
75 const char *_dl_profile_output;
76 int _dl_debug_libs;
77 int _dl_debug_impcalls;
78 int _dl_debug_bindings;
79 int _dl_debug_symbols;
80 int _dl_debug_versions;
81 int _dl_debug_reloc;
82 int _dl_debug_files;
83 const char *_dl_inhibit_rpath;          /* RPATH values which should be
84                                            ignored.  */
85
86 /* Set nonzero during loading and initialization of executable and
87    libraries, cleared before the executable's entry point runs.  This
88    must not be initialized to nonzero, because the unused dynamic
89    linker loaded in for libc.so's "ld.so.1" dep will provide the
90    definition seen by libc.so's initializer; that value must be zero,
91    and will be since that dynamic linker's _dl_start and dl_main will
92    never be called.  */
93 int _dl_starting_up;
94
95
96 static void dl_main (const ElfW(Phdr) *phdr,
97                      ElfW(Half) phent,
98                      ElfW(Addr) *user_entry);
99
100 struct link_map _dl_rtld_map;
101 struct libname_list _dl_rtld_libname;
102 struct libname_list _dl_rtld_libname2;
103
104 #ifdef RTLD_START
105 RTLD_START
106 #else
107 #error "sysdeps/MACHINE/dl-machine.h fails to define RTLD_START"
108 #endif
109
110 static ElfW(Addr)
111 _dl_start (void *arg)
112 {
113   struct link_map bootstrap_map;
114
115   /* This #define produces dynamic linking inline functions for
116      bootstrap relocation instead of general-purpose relocation.  */
117 #define RTLD_BOOTSTRAP
118 #define RESOLVE(sym, version, flags) bootstrap_map.l_addr
119 #include "dynamic-link.h"
120
121   /* Figure out the run-time load address of the dynamic linker itself.  */
122   bootstrap_map.l_addr = elf_machine_load_address ();
123
124   /* Read our own dynamic section and fill in the info array.  */
125   bootstrap_map.l_ld = (void *) bootstrap_map.l_addr + elf_machine_dynamic ();
126   elf_get_dynamic_info (bootstrap_map.l_ld, bootstrap_map.l_info);
127
128 #ifdef ELF_MACHINE_BEFORE_RTLD_RELOC
129   ELF_MACHINE_BEFORE_RTLD_RELOC (bootstrap_map.l_info);
130 #endif
131
132   /* Relocate ourselves so we can do normal function calls and
133      data access using the global offset table.  */
134
135   ELF_DYNAMIC_RELOCATE (&bootstrap_map, 0, 0);
136   /* Please note that we don't allow profiling of this object and
137      therefore need not test whether we have to allocate the array
138      for the relocation results (as done in dl-reloc.c).  */
139
140   /* Now life is sane; we can call functions and access global data.
141      Set up to use the operating system facilities, and find out from
142      the operating system's program loader where to find the program
143      header table in core.  */
144
145   /* Transfer data about ourselves to the permanent link_map structure.  */
146   _dl_rtld_map.l_addr = bootstrap_map.l_addr;
147   _dl_rtld_map.l_ld = bootstrap_map.l_ld;
148   _dl_rtld_map.l_opencount = 1;
149   memcpy (_dl_rtld_map.l_info, bootstrap_map.l_info,
150           sizeof _dl_rtld_map.l_info);
151   _dl_setup_hash (&_dl_rtld_map);
152
153   /* Cache the DT_RPATH stored in ld.so itself; this will be
154      the default search path.  */
155   if (_dl_rtld_map.l_info[DT_STRTAB] && _dl_rtld_map.l_info[DT_RPATH])
156     {
157       _dl_rpath = (void *) (_dl_rtld_map.l_addr +
158                             _dl_rtld_map.l_info[DT_STRTAB]->d_un.d_ptr +
159                             _dl_rtld_map.l_info[DT_RPATH]->d_un.d_val);
160     }
161
162   /* Call the OS-dependent function to set up life so we can do things like
163      file access.  It will call `dl_main' (below) to do all the real work
164      of the dynamic linker, and then unwind our frame and run the user
165      entry point on the same stack we entered on.  */
166   return _dl_sysdep_start (arg, &dl_main);
167 }
168
169 /* Now life is peachy; we can do all normal operations.
170    On to the real work.  */
171
172 void ENTRY_POINT (void);
173
174 /* Some helper functions.  */
175
176 /* Arguments to relocate_doit.  */
177 struct relocate_args
178 {
179   struct link_map *l;
180   int lazy;
181 };
182
183 struct map_args
184 {
185   /* Argument to map_doit.  */
186   char *str;
187   /* Return value of map_doit.  */
188   struct link_map *main_map;
189 };
190
191 /* Arguments to version_check_doit.  */
192 struct version_check_args
193 {
194   struct link_map *main_map;
195   int doexit;
196 };
197
198 static void
199 relocate_doit (void *a)
200 {
201   struct relocate_args *args = (struct relocate_args *) a;
202
203   _dl_relocate_object (args->l, _dl_object_relocation_scope (args->l),
204                        args->lazy, 0);
205 }
206
207 static void
208 map_doit (void *a)
209 {
210   struct map_args *args = (struct map_args *)a;
211   args->main_map = _dl_map_object (NULL, args->str, 0, lt_library, 0);
212 }
213
214 static void
215 version_check_doit (void *a)
216 {
217   struct version_check_args *args = (struct version_check_args *)a;
218   if (_dl_check_all_versions (args->main_map, 1) && args->doexit)
219     /* We cannot start the application.  Abort now.  */
220     _exit (1);
221 }
222
223
224 static inline struct link_map *
225 find_needed (const char *name)
226 {
227   unsigned int n;
228
229   for (n = 0; n < _dl_loaded->l_nsearchlist; ++n)
230     if (_dl_name_match_p (name, _dl_loaded->l_searchlist[n]))
231       return _dl_loaded->l_searchlist[n];
232
233   /* Should never happen.  */
234   return NULL;
235 }
236
237 static int
238 match_version (const char *string, struct link_map *map)
239 {
240   const char *strtab = (const char *) (map->l_addr
241                                        + map->l_info[DT_STRTAB]->d_un.d_ptr);
242   ElfW(Verdef) *def;
243
244 #define VERDEFTAG (DT_NUM + DT_PROCNUM + DT_VERSIONTAGIDX (DT_VERDEF))
245   if (map->l_info[VERDEFTAG] == NULL)
246     /* The file has no symbol versioning.  */
247     return 0;
248
249   def = (ElfW(Verdef) *) ((char *) map->l_addr
250                           + map->l_info[VERDEFTAG]->d_un.d_ptr);
251   while (1)
252     {
253       ElfW(Verdaux) *aux = (ElfW(Verdaux) *) ((char *) def + def->vd_aux);
254
255       /* Compare the version strings.  */
256       if (strcmp (string, strtab + aux->vda_name) == 0)
257         /* Bingo!  */
258         return 1;
259
260       /* If no more definitions we failed to find what we want.  */
261       if (def->vd_next == 0)
262         break;
263
264       /* Next definition.  */
265       def = (ElfW(Verdef) *) ((char *) def + def->vd_next);
266     }
267
268   return 0;
269 }
270
271 static unsigned int _dl_skip_args;      /* Nonzero if we were run directly.  */
272 static const char *library_path;        /* The library search path.  */
273 static const char *preloadlist;         /* The list preloaded objects.  */
274 static int version_info;                /* Nonzero if information about
275                                            versions has to be printed.  */
276
277 static void
278 dl_main (const ElfW(Phdr) *phdr,
279          ElfW(Half) phent,
280          ElfW(Addr) *user_entry)
281 {
282   const ElfW(Phdr) *ph;
283   struct link_map *main_map;
284   int lazy;
285   enum mode mode;
286   struct link_map **preloads;
287   unsigned int npreloads;
288   size_t file_size;
289   char *file;
290   int has_interp = 0;
291   unsigned int i;
292   int paths_initialized = 0;
293
294   /* Process the environment variable which control the behaviour.  */
295   process_envvars (&mode, &lazy);
296
297   /* Set up a flag which tells we are just starting.  */
298   _dl_starting_up = 1;
299
300   if (*user_entry == (ElfW(Addr)) &ENTRY_POINT)
301     {
302       /* Ho ho.  We are not the program interpreter!  We are the program
303          itself!  This means someone ran ld.so as a command.  Well, that
304          might be convenient to do sometimes.  We support it by
305          interpreting the args like this:
306
307          ld.so PROGRAM ARGS...
308
309          The first argument is the name of a file containing an ELF
310          executable we will load and run with the following arguments.
311          To simplify life here, PROGRAM is searched for using the
312          normal rules for shared objects, rather than $PATH or anything
313          like that.  We just load it and use its entry point; we don't
314          pay attention to its PT_INTERP command (we are the interpreter
315          ourselves).  This is an easy way to test a new ld.so before
316          installing it.  */
317
318       /* Note the place where the dynamic linker actually came from.  */
319       _dl_rtld_map.l_name = _dl_argv[0];
320
321       while (_dl_argc > 1)
322         if (! strcmp (_dl_argv[1], "--list"))
323           {
324             mode = list;
325             lazy = -1;  /* This means do no dependency analysis.  */
326
327             ++_dl_skip_args;
328             --_dl_argc;
329             ++_dl_argv;
330           }
331         else if (! strcmp (_dl_argv[1], "--verify"))
332           {
333             mode = verify;
334
335             ++_dl_skip_args;
336             --_dl_argc;
337             ++_dl_argv;
338           }
339         else if (! strcmp (_dl_argv[1], "--library-path") && _dl_argc > 2)
340           {
341             library_path = _dl_argv[2];
342
343             _dl_skip_args += 2;
344             _dl_argc -= 2;
345             _dl_argv += 2;
346           }
347         else if (! strcmp (_dl_argv[1], "--inhibit-rpath") && _dl_argc > 2)
348           {
349             _dl_inhibit_rpath = _dl_argv[2];
350
351             _dl_skip_args += 2;
352             _dl_argc -= 2;
353             _dl_argv += 2;
354           }
355         else
356           break;
357
358       /* If we have no further argument the program was called incorrectly.
359          Grant the user some education.  */
360       if (_dl_argc < 2)
361         _dl_sysdep_fatal ("\
362 Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n\
363 You have invoked `ld.so', the helper program for shared library executables.\n\
364 This program usually lives in the file `/lib/ld.so', and special directives\n\
365 in executable files using ELF shared libraries tell the system's program\n\
366 loader to load the helper program from this file.  This helper program loads\n\
367 the shared libraries needed by the program executable, prepares the program\n\
368 to run, and runs it.  You may invoke this helper program directly from the\n\
369 command line to load and run an ELF executable file; this is like executing\n\
370 that file itself, but always uses this helper program from the file you\n\
371 specified, instead of the helper program file specified in the executable\n\
372 file you run.  This is mostly of use for maintainers to test new versions\n\
373 of this helper program; chances are you did not intend to run this program.\n\
374 \n\
375   --list                list all dependencies and how they are resolved\n\
376   --verify              verify that given object really is a dynamically linked\n\
377                         object we get handle\n\
378   --library-path PATH   use given PATH instead of content of the environment\n\
379                         variable LD_LIBRARY_PATH\n\
380   --inhibit-rpath LIST  ignore RPATH information in object names in LIST\n",
381                           NULL);
382
383       ++_dl_skip_args;
384       --_dl_argc;
385       ++_dl_argv;
386
387       /* Initialize the data structures for the search paths for shared
388          objects.  */
389       _dl_init_paths (library_path);
390       paths_initialized = 1;
391
392       if (mode == verify)
393         {
394           char *err_str = NULL;
395           struct map_args args;
396
397           args.str = _dl_argv[0];
398           (void) _dl_catch_error (&err_str, map_doit, &args);
399           main_map = args.main_map;
400           if (err_str != NULL)
401             {
402               free (err_str);
403               _exit (EXIT_FAILURE);
404             }
405         }
406       else
407         main_map = _dl_map_object (NULL, _dl_argv[0], 0, lt_library, 0);
408
409       phdr = main_map->l_phdr;
410       phent = main_map->l_phnum;
411       main_map->l_name = (char *) "";
412       *user_entry = main_map->l_entry;
413     }
414   else
415     {
416       /* Create a link_map for the executable itself.
417          This will be what dlopen on "" returns.  */
418       main_map = _dl_new_object ((char *) "", "", lt_executable);
419       if (main_map == NULL)
420         _dl_sysdep_fatal ("cannot allocate memory for link map\n", NULL);
421       main_map->l_phdr = phdr;
422       main_map->l_phnum = phent;
423       main_map->l_entry = *user_entry;
424       main_map->l_opencount = 1;
425
426       /* We delay initializing the path structure until we got the dynamic
427          information for the program.  */
428     }
429
430   /* Scan the program header table for the dynamic section.  */
431   for (ph = phdr; ph < &phdr[phent]; ++ph)
432     switch (ph->p_type)
433       {
434       case PT_PHDR:
435         /* Find out the load address.  */
436         main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;
437         break;
438       case PT_DYNAMIC:
439         /* This tells us where to find the dynamic section,
440            which tells us everything we need to do.  */
441         main_map->l_ld = (void *) main_map->l_addr + ph->p_vaddr;
442         break;
443       case PT_INTERP:
444         /* This "interpreter segment" was used by the program loader to
445            find the program interpreter, which is this program itself, the
446            dynamic linker.  We note what name finds us, so that a future
447            dlopen call or DT_NEEDED entry, for something that wants to link
448            against the dynamic linker as a shared library, will know that
449            the shared object is already loaded.  */
450         _dl_rtld_libname.name = (const char *) main_map->l_addr + ph->p_vaddr;
451         _dl_rtld_libname.next = NULL;
452         _dl_rtld_map.l_libname = &_dl_rtld_libname;
453
454         /* Ordinarilly, we would get additional names for the loader from
455            our DT_SONAME.  This can't happen if we were actually linked as
456            a static executable (detect this case when we have no DYNAMIC).
457            If so, assume the filename component of the interpreter path to
458            be our SONAME, and add it to our name list.  */
459         if (_dl_rtld_map.l_ld == NULL)
460           {
461             char *p = strrchr (_dl_rtld_libname.name, '/');
462             if (p)
463               {
464                 _dl_rtld_libname2.name = p+1;
465                 _dl_rtld_libname2.next = NULL;
466                 _dl_rtld_libname.next = &_dl_rtld_libname2;
467               }
468           }
469
470         has_interp = 1;
471         break;
472       }
473   if (! _dl_rtld_map.l_libname && _dl_rtld_map.l_name)
474     {
475       /* We were invoked directly, so the program might not have a
476          PT_INTERP.  */
477       _dl_rtld_libname.name = _dl_rtld_map.l_name;
478       _dl_rtld_libname.next = NULL;
479       _dl_rtld_map.l_libname =  &_dl_rtld_libname;
480     }
481   else
482     assert (_dl_rtld_map.l_libname); /* How else did we get here?  */
483
484   /* Extract the contents of the dynamic section for easy access.  */
485   elf_get_dynamic_info (main_map->l_ld, main_map->l_info);
486   if (main_map->l_info[DT_HASH])
487     /* Set up our cache of pointers into the hash table.  */
488     _dl_setup_hash (main_map);
489
490   if (mode == verify)
491     {
492       /* We were called just to verify that this is a dynamic
493          executable using us as the program interpreter.  Exit with an
494          error if we were not able to load the binary or no interpreter
495          is specified (i.e., this is no dynamically linked binary.  */
496       if (main_map->l_ld == NULL)
497         _exit (1);
498
499       /* We allow here some platform specific code.  */
500 #ifdef DISTINGUISH_LIB_VERSIONS
501       DISTINGUISH_LIB_VERSIONS;
502 #endif
503       _exit (has_interp ? 0 : 2);
504     }
505
506   if (! paths_initialized)
507     /* Initialize the data structures for the search paths for shared
508        objects.  */
509     _dl_init_paths (library_path);
510
511   /* Put the link_map for ourselves on the chain so it can be found by
512      name.  Note that at this point the global chain of link maps contains
513      exactly one element, which is pointed to by main_map.  */
514   if (! _dl_rtld_map.l_name)
515     /* If not invoked directly, the dynamic linker shared object file was
516        found by the PT_INTERP name.  */
517     _dl_rtld_map.l_name = (char *) _dl_rtld_map.l_libname->name;
518   _dl_rtld_map.l_type = lt_library;
519   main_map->l_next = &_dl_rtld_map;
520   _dl_rtld_map.l_prev = main_map;
521
522   /* We have two ways to specify objects to preload: via environment
523      variable and via the file /etc/ld.so.preload.  The later can also
524      be used when security is enabled.  */
525   preloads = NULL;
526   npreloads = 0;
527
528   if (preloadlist)
529     {
530       /* The LD_PRELOAD environment variable gives list of libraries
531          separated by white space or colons that are loaded before the
532          executable's dependencies and prepended to the global scope
533          list.  If the binary is running setuid all elements
534          containing a '/' are ignored since it is insecure.  */
535       char *list = strdupa (preloadlist);
536       char *p;
537       while ((p = strsep (&list, " :")) != NULL)
538         if (p[0] != '\0'
539             && (! __libc_enable_secure || strchr (p, '/') == NULL))
540           {
541             struct link_map *new_map = _dl_map_object (main_map, p, 1,
542                                                        lt_library, 0);
543             if (new_map->l_opencount == 1)
544               /* It is no duplicate.  */
545               ++npreloads;
546           }
547     }
548
549   /* Read the contents of the file.  */
550   file = _dl_sysdep_read_whole_file ("/etc/ld.so.preload", &file_size,
551                                      PROT_READ | PROT_WRITE);
552   if (file)
553     {
554       /* Parse the file.  It contains names of libraries to be loaded,
555          separated by white spaces or `:'.  It may also contain
556          comments introduced by `#'.  */
557       char *problem;
558       char *runp;
559       size_t rest;
560
561       /* Eliminate comments.  */
562       runp = file;
563       rest = file_size;
564       while (rest > 0)
565         {
566           char *comment = memchr (runp, '#', rest);
567           if (comment == NULL)
568             break;
569
570           rest -= comment - runp;
571           do
572             *comment = ' ';
573           while (--rest > 0 && *++comment != '\n');
574         }
575
576       /* We have one problematic case: if we have a name at the end of
577          the file without a trailing terminating characters, we cannot
578          place the \0.  Handle the case separately.  */
579       if (file[file_size - 1] != ' ' && file[file_size - 1] != '\t'
580           && file[file_size - 1] != '\n' && file[file_size - 1] != ':')
581         {
582           problem = &file[file_size];
583           while (problem > file && problem[-1] != ' ' && problem[-1] != '\t'
584                  && problem[-1] != '\n' && problem[-1] != ':')
585             --problem;
586
587           if (problem > file)
588             problem[-1] = '\0';
589         }
590       else
591         {
592           problem = NULL;
593           file[file_size - 1] = '\0';
594         }
595
596       if (file != problem)
597         {
598           char *p;
599           runp = file;
600           while ((p = strsep (&runp, ": \t\n")) != NULL)
601             if (p[0] != '\0')
602               {
603                 struct link_map *new_map = _dl_map_object (main_map, p, 1,
604                                                            lt_library, 0);
605                 if (new_map->l_opencount == 1)
606                   /* It is no duplicate.  */
607                   ++npreloads;
608               }
609         }
610
611       if (problem != NULL)
612         {
613           char *p = strndupa (problem, file_size - (problem - file));
614           struct link_map *new_map = _dl_map_object (main_map, p, 1,
615                                                      lt_library, 0);
616           if (new_map->l_opencount == 1)
617             /* It is no duplicate.  */
618             ++npreloads;
619         }
620
621       /* We don't need the file anymore.  */
622       __munmap (file, file_size);
623     }
624
625   if (npreloads != 0)
626     {
627       /* Set up PRELOADS with a vector of the preloaded libraries.  */
628       struct link_map *l;
629       preloads = __alloca (npreloads * sizeof preloads[0]);
630       l = _dl_rtld_map.l_next; /* End of the chain before preloads.  */
631       i = 0;
632       do
633         {
634           preloads[i++] = l;
635           l = l->l_next;
636         } while (l);
637       assert (i == npreloads);
638     }
639
640   /* Load all the libraries specified by DT_NEEDED entries.  If LD_PRELOAD
641      specified some libraries to load, these are inserted before the actual
642      dependencies in the executable's searchlist for symbol resolution.  */
643   _dl_map_object_deps (main_map, preloads, npreloads, mode == trace);
644
645 #ifndef MAP_ANON
646   /* We are done mapping things, so close the zero-fill descriptor.  */
647   __close (_dl_zerofd);
648   _dl_zerofd = -1;
649 #endif
650
651   /* Remove _dl_rtld_map from the chain.  */
652   _dl_rtld_map.l_prev->l_next = _dl_rtld_map.l_next;
653   if (_dl_rtld_map.l_next)
654     _dl_rtld_map.l_next->l_prev = _dl_rtld_map.l_prev;
655
656   if (_dl_rtld_map.l_opencount > 1)
657     {
658       /* Some DT_NEEDED entry referred to the interpreter object itself, so
659          put it back in the list of visible objects.  We insert it into the
660          chain in symbol search order because gdb uses the chain's order as
661          its symbol search order.  */
662       i = 1;
663       while (main_map->l_searchlist[i] != &_dl_rtld_map)
664         ++i;
665       _dl_rtld_map.l_prev = main_map->l_searchlist[i - 1];
666       _dl_rtld_map.l_next = (i + 1 < main_map->l_nsearchlist ?
667                              main_map->l_searchlist[i + 1] : NULL);
668       assert (_dl_rtld_map.l_prev->l_next == _dl_rtld_map.l_next);
669       _dl_rtld_map.l_prev->l_next = &_dl_rtld_map;
670       if (_dl_rtld_map.l_next)
671         {
672           assert (_dl_rtld_map.l_next->l_prev == _dl_rtld_map.l_prev);
673           _dl_rtld_map.l_next->l_prev = &_dl_rtld_map;
674         }
675     }
676
677   /* Now let us see whether all libraries are available in the
678      versions we need.  */
679   {
680     struct version_check_args args;
681     args.doexit = mode == normal;
682     args.main_map = main_map;
683     _dl_receive_error (print_missing_version, version_check_doit, &args);
684   }
685
686   if (mode != normal)
687     {
688       /* We were run just to list the shared libraries.  It is
689          important that we do this before real relocation, because the
690          functions we call below for output may no longer work properly
691          after relocation.  */
692       if (! _dl_loaded->l_info[DT_NEEDED])
693         _dl_sysdep_message ("\t", "statically linked\n", NULL);
694       else
695         {
696           struct link_map *l;
697
698           for (l = _dl_loaded->l_next; l; l = l->l_next)
699             if (l->l_opencount == 0)
700               /* The library was not found.  */
701               _dl_sysdep_message ("\t", l->l_libname->name, " => not found\n",
702                                   NULL);
703             else
704               {
705                 char buf[20], *bp;
706                 buf[sizeof buf - 1] = '\0';
707                 bp = _itoa_word (l->l_addr, &buf[sizeof buf - 1], 16, 0);
708                 while ((size_t) (&buf[sizeof buf - 1] - bp)
709                        < sizeof l->l_addr * 2)
710                   *--bp = '0';
711                 _dl_sysdep_message ("\t", l->l_libname->name, " => ",
712                                     l->l_name, " (0x", bp, ")\n", NULL);
713               }
714         }
715
716       if (mode != trace)
717         for (i = 1; i < _dl_argc; ++i)
718           {
719             const ElfW(Sym) *ref = NULL;
720             ElfW(Addr) loadbase = _dl_lookup_symbol (_dl_argv[i], &ref,
721                                                      &_dl_default_scope[2],
722                                                      "argument",
723                                                      ELF_MACHINE_JMP_SLOT);
724             char buf[20], *bp;
725             buf[sizeof buf - 1] = '\0';
726             bp = _itoa_word (ref->st_value, &buf[sizeof buf - 1], 16, 0);
727             while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
728               *--bp = '0';
729             _dl_sysdep_message (_dl_argv[i], " found at 0x", bp, NULL);
730             buf[sizeof buf - 1] = '\0';
731             bp = _itoa_word (loadbase, &buf[sizeof buf - 1], 16, 0);
732             while ((size_t) (&buf[sizeof buf - 1] - bp) < sizeof loadbase * 2)
733               *--bp = '0';
734             _dl_sysdep_message (" in object at 0x", bp, "\n", NULL);
735           }
736       else
737         {
738           if (lazy >= 0)
739             {
740               /* We have to do symbol dependency testing.  */
741               struct relocate_args args;
742               struct link_map *l;
743
744               args.lazy = lazy;
745
746               l = _dl_loaded;
747               while (l->l_next)
748                 l = l->l_next;
749               do
750                 {
751                   if (l != &_dl_rtld_map && l->l_opencount > 0)
752                     {
753                       args.l = l;
754                       _dl_receive_error (print_unresolved, relocate_doit,
755                                          &args);
756                       *_dl_global_scope_end = NULL;
757                     }
758                   l = l->l_prev;
759                 } while (l);
760             }
761
762 #define VERNEEDTAG (DT_NUM + DT_PROCNUM + DT_VERSIONTAGIDX (DT_VERNEED))
763           if (version_info)
764             {
765               /* Print more information.  This means here, print information
766                  about the versions needed.  */
767               int first = 1;
768               struct link_map *map = _dl_loaded;
769
770               for (map = _dl_loaded; map != NULL; map = map->l_next)
771                 {
772                   const char *strtab;
773                   ElfW(Dyn) *dyn = map->l_info[VERNEEDTAG];
774                   ElfW(Verneed) *ent;
775
776                   if (dyn == NULL)
777                     continue;
778
779                   strtab = (const char *)
780                     (map->l_addr + map->l_info[DT_STRTAB]->d_un.d_ptr);
781                   ent = (ElfW(Verneed) *) (map->l_addr + dyn->d_un.d_ptr);
782
783                   if (first)
784                     {
785                       _dl_sysdep_message ("\n\tVersion information:\n", NULL);
786                       first = 0;
787                     }
788
789                   _dl_sysdep_message ("\t", (map->l_name[0]
790                                              ? map->l_name : _dl_argv[0]),
791                                       ":\n", NULL);
792
793                   while (1)
794                     {
795                       ElfW(Vernaux) *aux;
796                       struct link_map *needed;
797
798                       needed = find_needed (strtab + ent->vn_file);
799                       aux = (ElfW(Vernaux) *) ((char *) ent + ent->vn_aux);
800
801                       while (1)
802                         {
803                           const char *fname = NULL;
804
805                           _dl_sysdep_message ("\t\t",
806                                               strtab + ent->vn_file,
807                                               " (", strtab + aux->vna_name,
808                                               ") ",
809                                               (aux->vna_flags
810                                                & VER_FLG_WEAK
811                                                ? "[WEAK] " : ""),
812                                               "=> ", NULL);
813
814                           if (needed != NULL
815                               && match_version (strtab+aux->vna_name, needed))
816                             fname = needed->l_name;
817
818                           _dl_sysdep_message (fname ?: "not found", "\n",
819                                               NULL);
820
821                           if (aux->vna_next == 0)
822                             /* No more symbols.  */
823                             break;
824
825                           /* Next symbol.  */
826                           aux = (ElfW(Vernaux) *) ((char *) aux
827                                                    + aux->vna_next);
828                         }
829
830                       if (ent->vn_next == 0)
831                         /* No more dependencies.  */
832                         break;
833
834                       /* Next dependency.  */
835                       ent = (ElfW(Verneed) *) ((char *) ent + ent->vn_next);
836                     }
837                 }
838             }
839         }
840
841       _exit (0);
842     }
843
844   {
845     /* Now we have all the objects loaded.  Relocate them all except for
846        the dynamic linker itself.  We do this in reverse order so that copy
847        relocs of earlier objects overwrite the data written by later
848        objects.  We do not re-relocate the dynamic linker itself in this
849        loop because that could result in the GOT entries for functions we
850        call being changed, and that would break us.  It is safe to relocate
851        the dynamic linker out of order because it has no copy relocs (we
852        know that because it is self-contained).  */
853
854     struct link_map *l;
855     int consider_profiling = _dl_profile != NULL;
856
857     /* If we are profiling we also must do lazy reloaction.  */
858     lazy |= consider_profiling;
859
860     l = _dl_loaded;
861     while (l->l_next)
862       l = l->l_next;
863     do
864       {
865         if (l != &_dl_rtld_map)
866           {
867             _dl_relocate_object (l, _dl_object_relocation_scope (l), lazy,
868                                  consider_profiling);
869             *_dl_global_scope_end = NULL;
870           }
871         l = l->l_prev;
872       } while (l);
873
874     /* Do any necessary cleanups for the startup OS interface code.
875        We do these now so that no calls are made after rtld re-relocation
876        which might be resolved to different functions than we expect.
877        We cannot do this before relocating the other objects because
878        _dl_relocate_object might need to call `mprotect' for DT_TEXTREL.  */
879     _dl_sysdep_start_cleanup ();
880
881     if (_dl_rtld_map.l_opencount > 0)
882       /* There was an explicit ref to the dynamic linker as a shared lib.
883          Re-relocate ourselves with user-controlled symbol definitions.  */
884       _dl_relocate_object (&_dl_rtld_map, &_dl_default_scope[2], 0, 0);
885   }
886
887   {
888     /* Initialize _r_debug.  */
889     struct r_debug *r = _dl_debug_initialize (_dl_rtld_map.l_addr);
890     struct link_map *l;
891
892     l = _dl_loaded;
893
894 #ifdef ELF_MACHINE_DEBUG_SETUP
895
896     /* Some machines (e.g. MIPS) don't use DT_DEBUG in this way.  */
897
898     ELF_MACHINE_DEBUG_SETUP (l, r);
899     ELF_MACHINE_DEBUG_SETUP (&_dl_rtld_map, r);
900
901 #else
902
903     if (l->l_info[DT_DEBUG])
904       /* There is a DT_DEBUG entry in the dynamic section.  Fill it in
905          with the run-time address of the r_debug structure  */
906       l->l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
907
908     /* Fill in the pointer in the dynamic linker's own dynamic section, in
909        case you run gdb on the dynamic linker directly.  */
910     if (_dl_rtld_map.l_info[DT_DEBUG])
911       _dl_rtld_map.l_info[DT_DEBUG]->d_un.d_ptr = (ElfW(Addr)) r;
912
913 #endif
914
915     /* Notify the debugger that all objects are now mapped in.  */
916     r->r_state = RT_ADD;
917     _dl_debug_state ();
918   }
919
920   /* Now enable profiling if needed.  */
921   if (_dl_profile_map != NULL)
922     /* We must prepare the profiling.  */
923     _dl_start_profile (_dl_profile_map, _dl_profile_output);
924
925   /* Once we return, _dl_sysdep_start will invoke
926      the DT_INIT functions and then *USER_ENTRY.  */
927 }
928 \f
929 /* This is a little helper function for resolving symbols while
930    tracing the binary.  */
931 static void
932 print_unresolved (int errcode __attribute__ ((unused)), const char *objname,
933                   const char *errstring)
934 {
935   if (objname[0] == '\0')
936     objname = _dl_argv[0] ?: "<main program>";
937   _dl_sysdep_error (errstring, "        (", objname, ")\n", NULL);
938 }
939 \f
940 /* This is a little helper function for resolving symbols while
941    tracing the binary.  */
942 static void
943 print_missing_version (int errcode __attribute__ ((unused)),
944                        const char *objname, const char *errstring)
945 {
946   _dl_sysdep_error (_dl_argv[0] ?: "<program name unknown>", ": ",
947                     objname, ": ", errstring, "\n", NULL);
948 }
949 \f
950 /* Nonzero if any of the debugging options is enabled.  */
951 static int any_debug;
952
953 /* Process the string given as the parameter which explains which debugging
954    options are enabled.  */
955 static void
956 process_dl_debug (const char *dl_debug)
957 {
958   size_t len;
959 #define separators " ,:"
960   do
961     {
962       len = 0;
963       /* Skip separating white spaces and commas.  */
964       dl_debug += strspn (dl_debug, separators);
965       if (*dl_debug != '\0')
966         {
967           len = strcspn (dl_debug, separators);
968
969           switch (len)
970             {
971             case 4:
972               if (memcmp (dl_debug, "help", 4) == 0)
973                 {
974                   _dl_sysdep_message ("\
975 Valid options for the LD_DEBUG environment variable are:\n\
976 \n\
977   bindings  display information about symbol binding\n\
978   files     display processing of files and libraries\n\
979   help      display this help message and exit\n\
980   libs      display library search paths\n\
981   reloc     display relocation processing\n\
982   symbols   display symbol table processing\n\
983   versions  display version dependencies\n\
984 \n\
985 To direct the debugging output into a file instead of standard output\n\
986 a filename can be specified using the LD_DEBUG_OUTPUT environment variable.\n",
987                                   NULL);
988                   _exit (0);
989                 }
990
991               if (memcmp (dl_debug, "libs", 4) == 0)
992                 {
993                   _dl_debug_libs = 1;
994                   _dl_debug_impcalls = 1;
995                   any_debug = 1;
996                   continue;
997                 }
998               break;
999
1000             case 5:
1001               if (memcmp (dl_debug, "reloc", 5) == 0)
1002                 {
1003                   _dl_debug_reloc = 1;
1004                   _dl_debug_impcalls = 1;
1005                   any_debug = 1;
1006                   continue;
1007                 }
1008
1009               if (memcmp (dl_debug, "files", 5) == 0)
1010                 {
1011                   _dl_debug_files = 1;
1012                   _dl_debug_impcalls = 1;
1013                   any_debug = 1;
1014                   continue;
1015                 }
1016               break;
1017
1018             case 7:
1019               if (memcmp (dl_debug, "symbols", 7) == 0)
1020                 {
1021                   _dl_debug_symbols = 1;
1022                   _dl_debug_impcalls = 1;
1023                   any_debug = 1;
1024                   continue;
1025                 }
1026               break;
1027
1028             case 8:
1029               if (memcmp (dl_debug, "bindings", 8) == 0)
1030                 {
1031                   _dl_debug_bindings = 1;
1032                   _dl_debug_impcalls = 1;
1033                   any_debug = 1;
1034                   continue;
1035                 }
1036
1037               if (memcmp (dl_debug, "versions", 8) == 0)
1038                 {
1039                   _dl_debug_versions = 1;
1040                   _dl_debug_impcalls = 1;
1041                   any_debug = 1;
1042                   continue;
1043                 }
1044               break;
1045
1046             default:
1047               break;
1048             }
1049
1050           {
1051             /* Display a warning and skip everything until next separator.  */
1052             char *startp = strndupa (dl_debug, len);
1053             _dl_sysdep_error ("warning: debug option `", startp,
1054                               "' unknown; try LD_DEBUG=help\n", NULL);
1055           }
1056         }
1057     }
1058   while (*(dl_debug += len) != '\0');
1059 }
1060 \f
1061 /* Process all environments variables the dynamic linker must recognize.
1062    Since all of them start with `LD_' we are a bit smarter while finding
1063    all the entries.  */
1064 static void
1065 process_envvars (enum mode *modep, int *lazyp)
1066 {
1067   char **runp = NULL;
1068   char *envline;
1069   enum mode mode = normal;
1070   int bind_now = 0;
1071   char *debug_output = NULL;
1072
1073   /* This is the default place for profiling data file.  */
1074   _dl_profile_output = "/var/tmp";
1075
1076   while ((envline = _dl_next_ld_env_entry (&runp)) != NULL)
1077     {
1078       size_t len = strcspn (envline, "=") - 3;
1079
1080       switch (len)
1081         {
1082         case 4:
1083           /* Warning level, verbose or not.  */
1084           if (memcmp (&envline[3], "WARN", 4) == 0)
1085             _dl_verbose = envline[8] != '\0';
1086           break;
1087
1088         case 5:
1089           /* Debugging of the dynamic linker?  */
1090           if (memcmp (&envline[3], "DEBUG", 5) == 0)
1091             process_dl_debug (&envline[9]);
1092           break;
1093
1094         case 7:
1095           /* Print information about versions.  */
1096           if (memcmp (&envline[3], "VERBOSE", 7) == 0)
1097             {
1098               version_info = envline[11] != '\0';
1099               break;
1100             }
1101
1102           /* List of objects to be preloaded.  */
1103           if (memcmp (&envline[3], "PRELOAD", 7) == 0)
1104             {
1105               preloadlist = &envline[11];
1106               break;
1107             }
1108
1109           /* Which shared object shall be profiled.  */
1110           if (memcmp (&envline[3], "PROFILE", 7) == 0)
1111             {
1112               _dl_profile = &envline[11];
1113               if (*_dl_profile == '\0')
1114                 _dl_profile = NULL;
1115             }
1116           break;
1117
1118         case 8:
1119           /* Do we bind early?  */
1120           if (memcmp (&envline[3], "BIND_NOW", 8) == 0)
1121             bind_now = 1;
1122           break;
1123
1124         case 9:
1125           /* Test whether we want to see the content of the auxiliary
1126              array passed up from the kernel.  */
1127           if (memcmp (&envline[3], "SHOW_AUXV", 9) == 0)
1128             _dl_show_auxv ();
1129           break;
1130
1131         case 10:
1132           /* Mask for the important hardware capabilities.  */
1133           if (memcmp (&envline[3], "HWCAP_MASK", 10) == 0)
1134             _dl_hwcap_mask = strtoul (&envline[14], NULL, 0);
1135           break;
1136
1137         case 12:
1138           /* Where to place the profiling data file.  */
1139           if (memcmp (&envline[3], "DEBUG_OUTPUT", 12) == 0)
1140             {
1141               debug_output = &envline[16];
1142               break;
1143             }
1144
1145           /* The library search path.  */
1146           if (memcmp (&envline[3], "LIBRARY_PATH", 12) == 0)
1147             library_path = &envline[16];
1148           break;
1149
1150         case 14:
1151           /* Where to place the profiling data file.  */
1152           if (!__libc_enable_secure
1153               && memcmp (&envline[3], "PROFILE_OUTPUT", 14) == 0)
1154             {
1155               _dl_profile_output = &envline[18];
1156               if (*_dl_profile_output == '\0')
1157                 _dl_profile_output = "/var/tmp";
1158             }
1159           break;
1160
1161         case 20:
1162           /* The mode of the dynamic linker can be set.  */
1163           if (memcmp (&envline[3], "TRACE_LOADED_OBJECTS", 20) == 0)
1164             mode = trace;
1165           break;
1166
1167           /* We might have some extra environment variable to handle.  This
1168              is tricky due to the pre-processing of the length of the name
1169              in the switch statement here.  The code here assumes that added
1170              environment variables have a different length.  */
1171 #ifdef EXTRA_LD_ENVVARS
1172           EXTRA_LD_ENVVARS
1173 #endif
1174         }
1175     }
1176
1177   /* If we have to run the dynamic linker in debugging mode and the
1178      LD_DEBUG_OUTPUT environment variable is given, we write the debug
1179      messages to this file.  */
1180   if (any_debug && debug_output != NULL && !__libc_enable_secure)
1181     {
1182       _dl_debug_fd = __open (debug_output, O_WRONLY | O_APPEND | O_CREAT,
1183                              0666);
1184       if (_dl_debug_fd == -1)
1185         /* We use standard output if opening the file failed.  */
1186         _dl_debug_fd = STDOUT_FILENO;
1187     }
1188
1189   /* LAZY is determined by the environment variable LD_WARN and
1190      LD_BIND_NOW if we trace the binary.  */
1191   if (mode == trace)
1192     *lazyp = _dl_verbose ? !bind_now : -1;
1193   else
1194     *lazyp = !__libc_enable_secure && !bind_now;
1195
1196   *modep = mode;
1197 }