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