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